text
stringlengths
2
1.05M
// show current dir on load window.addEventListener('load', function () { document.querySelector('.current-dir').style.visibility = 'visible'; }); // known extensions var fileexts = [ 'png', 'jpg', 'gif', 'mp4', 'mp3', 'psd', 'xls', 'ai', 'eps', 'json', 'js', 'php', 'html', 'css', 'docx', 'pdf', 'zip', 'xml', 'svg', 'pptx', 'exe', 'txt', 'avi' ]; // app var app = new Vue({ el: '#app', data: { path : './', barpath : './', homedir : './', pos : 'Partage', api : '', dirs : [], dirs_ : [], stack : { prev: [], next: [] }, settings: { searchbar : { shown: false, value: '' }, tinysidebar : { shown: false }, dropzone : { shown: false }, clipboard : { todo: null, tomove: [], frompath: '' }, watching : { state: false, intval: null } }, jprompt : new JDialog(), jalert : new JDialog(), JAudio : new JAudio(), JAPlayer: null }, created: function () { }, mounted: function () { var self = this; // load home path && path dirs this.loadConifgs(function (configs) { // update home dir self.path = configs.homedir; self.homedir = configs.homedir; self.api = configs.ip_port; // load path dirs self.loadPath( self.path ); // mount stoneUpload seHelp.stoneUpload.init({ dropzone: document.querySelector('.current-dir'), droplist: document.querySelector('.dropzone .body .wrapper'), server : self.api + '/upload', dataType: 'json', auto : true, maxConcurrent: 3, ondroped: function () { // open dropzone self.toggleDropzone(true); }, onbeforesend: function(fd, file) { fd.append('path', self.path); fd.append('index', file.index); return fd; }, onfilecomplete: function (e, file, response) { // if upload & copy ok, update visual dir if ( response.moved ) { self.loadPath(false, false, true); return true; } // when copy failed on server seHelp.stoneUpload.updateStates(response.index, { doing: 'failed', message: response.cause }); return false; } }); // load start watcher // self.watchFolder(); // initialize JAudio player self.initJAudioPlayer(); }); }, methods: { /** * @method loadConifgs * Load a path content */ loadConifgs: function (handle) { var self = this; // loader seHelp.loader.show("Patientez un instant ..."); // query $.ajax({ url : 'share.config.json', method : 'get', dataType: 'json' }) .done(function (response) { handle( response ); }) .fail(function (err) { self.jalert.show({ title: 'Erreur', message: 'Une erreur est survenue.' }); }) .always(function () { seHelp.loader.hide(); }); }, /** * @method loadPath * Load a path content */ loadPath: function (_path, goingback, refreshing, isfile) { var self = this; var oldpath = this.path; // stop watcher for a while this.settings.watching.state = true; // if is file, open the file if possible if ( isfile ) { var nameparts = _path.split('.'); var checkon = ['mp4', 'mp3', 'ogg', 'webm'].indexOf( nameparts[ nameparts.length-1 ].toLowerCase() ) != -1; var link = this.api + '/defaults/download/?'+ (checkon ? 's':'t') +'=' + encodeURIComponent(this.path + '/' + _path); switch ( nameparts[ nameparts.length-1 ].toLowerCase() ) { case 'mp4': jVideo.play( link ); break; case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp': view.show(link); break; case 'pdf': case 'txt': pdfobject.open(link); break; case 'mp3': case 'ogg': case 'aac': this.JAudio.play({ name: _path, source: link }); break; } return; } // if os for refreshing if ( refreshing ) { _path = this.path; } // if not else { // update showing path // from stack if ( /\//.test(_path) ) { this.path = _path; } // form click else { this.stack.next = []; this.path = this.path + (this.path == './' ? '' : '/') + (_path || ''); } } // show loadeer seHelp.loader.show("Patientez un instant ..."); // query $.ajax({ url : self.api + '/get-path-files', method : 'post', data : { path: self.path }, dataType: 'json' }) .done(function (response) { // on server refused if (response.error) { // show alert self.jalert.show({ title: 'Erreur', message: response.message, okBtnText: 'OK' }); // set old path as default self.path = oldpath; return; } // update dirs self.dirs = response.message.dirs; self.filterFile(); // update path if ( !refreshing ) { // add page leaving path to stack self.stack[ goingback ? 'next' : 'prev' ].push(oldpath); } // update top label var _path_ = _path.split('/'); !_path_[ _path_.length-1 ].trim().length ? _path_.pop() : ''; _path_.forEach(function (item) { self.pos = item; }); self.pos = ['.', ''].indexOf(self.pos.trim()) != -1 ? 'Partage' : self.pos; // bar path self.barpath = self.path; }) .fail(function (err) { // restore leaving path as current self.path = oldpath; }) .always(function () { // release watching state self.settings.watching.state = false; // hide loader seHelp.loader.hide(); }); }, /** * @method create * --- */ create: function (what, label) { var self = this; this.jprompt.show({ title: 'Nouveau ' + label, message: 'Créer un nouveau ' + label + ' dans ce repertoire', cancelBtnText: 'ANNULER', okBtnText: 'CREER', inputs: [{ type: 'text', placeholder: 'Nom du ' + label, name: 'name' }] }) .onConfirm(function (vals) { if ( !vals.name.length ) { self.jalert.show({ title: 'Erreur', message: 'Vous devez specifier un nom pour le ' + label + ' que vous desirez créer', okBtnText: 'OK' }); return; } // display loader seHelp.loader.show('Patientez un instant'); // do query $.ajax({ url : self.api + '/create', method : 'post', data : { path: self.path, name: vals.name, type: what }, dataType: 'json' }) .done(function (response) { if ( ! response.moved ) { self.jalert.show({ title: "Erreur", message: "impossible de créer le " + what + " dans ce repertoire." }); return; } // upate dirs list self.dirs = response.dirs; // filter self.filterFile(); // hide loader seHelp.loader.hide(); }); }); }, /** * @method delete * --- */ deleteFile: function (file) { var self = this; var type = file.isfile ? 'fichier' : 'dossier'; this.jprompt.show({ title: 'Attention', message: 'Vous allez supprimer le fichier <b>'+ file.filename +'</b>', inputs: [], cancelBtnText: 'ANNULER', okBtnText: 'SUPPRIMER' }) .onConfirm(function (vals) { // display loader seHelp.loader.show('Patientez un instant'); // do query $.ajax({ url : self.api + '/delete', method : 'post', data : { path: self.path, name: file.filename }, dataType: 'json' }) .done(function (response) { if ( ! response.removed ) { self.jalert.show({ title: "Erreur", message: "impossible de supprimer ce "+ type +"." }); return; } // upate dirs list self.dirs = response.dirs; // hide search bar self.settings.searchbar.shown = false; document.querySelector('#se_searchbar').value = ''; // filter self.filterFile(); // hide loader seHelp.loader.hide(); }) .always(function () { // hide loader seHelp.loader.hide(); }); }); }, /** * @method renameFile * --- */ renameFile: function (file) { var self = this; var type = file.isfile ? 'fichier' : 'dossier'; this.jprompt.show({ title: 'Renommer le ' + type, message: '', cancelBtnText: 'ANNULER', okBtnText: 'MODIFIER', inputs: [{ type: 'text', placeholder: 'Nouveau nom du ' + type, value: file.filename, name: 'name' }] }) .onConfirm(function (vals) { // do nothing if old name == new name if ( file.filename == vals.name ) { return; } // loader seHelp.loader.show('Patientez un instant'); // do query $.ajax({ url : self.api + '/rename', method : 'post', data : { path: self.path, old : file.filename, name: vals.name }, dataType: 'json' }) .done(function (response) { if ( ! response.renamed ) { self.jalert.show({ title: "Erreur", message: "impossible de renommer ce "+ type +"." }); return; } // upate dirs list self.dirs = response.dirs; // filter self.filterFile(); }) .always(function () { // hide loader seHelp.loader.hide(); }); }); }, /** * @method downloadFile * --- */ downloadFile: function (file) { // alert( file.webroute ); var a = document.createElement('a'); a.href = this.api + '/defaults/download/?l=' + encodeURIComponent(this.path + '/' + file.filename); a.setAttribute('download', file.filename); document.body.appendChild(a); a.click(); a.parentNode.removeChild(a); }, /** * @method getDownableLink * --- */ getDownableLink: function (file, type) { return this.api + '/defaults/download/?'+ (type || 't') +'=' + encodeURIComponent(this.path + '/' + file.filename); }, /** * @method addClipBoard * --- */ addClipBoard: function (files, todo) { var self = this; this.settings.clipboard = { todo: todo, tomove: files, frompath: self.path } }, /** * @method addClipBoard * --- */ pasteFiles: function (destination) { var self = this; // the loader seHelp.loader.show("Patientez un instant ..."); // do query $.ajax({ url : self.api + '/moveorcopy', method : 'post', data : { path: self.path, dest: self.path +'/'+ (destination || ''), from: self.settings.clipboard.frompath, todo: self.settings.clipboard.todo, list: self.settings.clipboard.tomove }, dataType: 'json' }) .done(function (response) { if ( ! response.moveorcopy ) { self.jalert.show({ title: "Erreur", message: "L'operation a échoué !" }); return; } // reinitialize clipboard self.settings.clipboard = { frompath: '', todo : '', tomove : [] }; // upate dirs list self.dirs = response.dirs; // filter self.filterFile(); }) .always(function () { // hide loader seHelp.loader.hide(); }); }, /** * @method watchFolder * --- */ watchFolder: function (destroywatcher) { var self = this; if ( destroywatcher ) { clearInterval( this.settings.watching.intval ); this.settings.watching.state = false; } this.settings.watching.invtal = setInterval(function () { if ( !self.settings.watching.state ) { self.settings.watching.state = true; $.ajax({ url: self.api + '/defaults/watch/?w=' + encodeURIComponent(self.path), type: 'get', dataType: 'text' }) .done(function (response) { console.log(response); }) .fail(function (err) { }) .always(function () { self.settings.watching.state = false; }); } }, 3000); }, /** * @method moveBack * Go to previous folder in stack */ moveBack: function () { // can we move if ( ! this.stack.prev.length ) return; var _prev = this.stack.prev[ this.stack.prev.length - 1 ]; // pop the prevs stack this.stack.prev.pop(); // load path this.loadPath( _prev, true ); }, /** * @method moveForward * Go to next folder in stack */ moveForward: function () { // can we move if ( ! this.stack.next.length ) return; var _next = this.stack.next[ this.stack.next.length - 1 ]; // pop the nexts stack this.stack.next.pop(); // load path this.loadPath( _next ); }, /** * @method moveTop * Go to parent folder */ moveTop: function () { // set top memory var _top = this.path.split('/'); _top.pop(); if ( _top.length ) { // add end slash if length is 1 var endslash = _top.length == 1 ? '/' : ''; var finalpath = _top.join('/') + endslash; // if final path correspond to actual path, do nothing if ( finalpath == this.path ) return; // empty prev stack this.stack.next = []; // load path this.loadPath( _top.join('/') + endslash ); } }, /** * @method goHome * Go to home dir */ goHome: function () { // reinitialize path this.path = this.homedir; // load home path this.loadPath( this.path ); }, /** * @method doRefresh * --- */ doRefresh: function () { this.loadPath( '', false, true ); }, /** * @method handleFileContextMenu * --- */ handleFileContextMenu: function (e, file) { e.preventDefault(); var el = e.target.nodeName == 'LI' ? e.target : e.target.parentNode; el = el.nodeName == 'LI' ? el : el.parentNode; el.querySelector('.dropdown-toggle').click(); }, /** * @method triggerSearchBar * --- */ triggerSearchBar: function (e) { // when press ENTER key if ( e.which == 13 ) { this.loadPath( this.barpath ); } }, /** * @method toggleSearchBar * --- */ toggleSearchBar: function () { this.settings.searchbar.shown = !this.settings.searchbar.shown; if ( this.settings.searchbar.shown ) { document.querySelector('#se_searchbar').focus(); } else { document.querySelector('#se_searchbar').value = ""; this.filterFile(); } }, /** * @method toggleDropzone * --- */ toggleDropzone: function (bool) { this.settings.dropzone.shown = bool ? bool : !this.settings.dropzone.shown; if ( this.settings.searchbar.shown ) { } else { } }, /** * @method toggleTinySidebar * --- */ toggleTinySidebar: function () { this.settings.tinysidebar.shown = !this.settings.tinysidebar.shown; }, /** * @method filterFile * --- */ filterFile: function (e) { var self = this; var allowed = []; var keyword = e ? e.target.value : ''; // close search field if escape pressed if ( e && e.which == 27 ) { this.toggleSearchBar(); return; } this.dirs_ = this.dirs.filter(function (item) { return (new RegExp(keyword, "i")).test(item.filename); }); }, /** * @method renderFileIcon * --- */ renderFileIcon: function (file) { var nameparts = file.filename.split('.'); var extension = nameparts[ nameparts.length-1 ]; var torender = ''; var fileexts = window.fileexts; // when folder if ( !file.isfile ) { torender = 'folder'; } else { torender = fileexts.indexOf(extension) != -1 ? extension : 'file'; } return torender + '.png'; }, /** * @method showFileNamePart * --- */ showFileNamePart: function (file) { var parts = file.filename.split('.'); var exts = file.isfile && parts.length>1 && parts[0].trim().length ? parts[ parts.length-1 ] : ''; var name = parts; name.pop(); name = window.fileexts.indexOf( exts ) != -1 && file.isfile ? name.join('.') : file.filename; return { ext: exts, name: name }; }, /** * @method isPreviewable * --- */ isPreviewable: function (file) { return ['jpg', 'png', 'gif', 'jpeg', 'bmp'].indexOf( this.showFileNamePart(file).ext.toLowerCase() ) != -1; }, /** * @method getFileExt * --- */ getFileExt: function (file) { var parts = file.filename.split('.'); var exts = parts[ parts.length-1 ]; var name = parts; name.pop(); return window.fileexts.indexOf( exts ) != -1 && file.isfile ? name.join('.') : file.filename; }, initJAudioPlayer: function () { this.JAPlayer = new JAudioPlayer( this.JAudio ); new SimpleBar( document.querySelector('.jAudio .playlist .wrapper') ); }, toggleAudioPlay: function () { this.JAPlayer.toggle(); } } });
var classSimTK_1_1MobilizedBody_1_1Screw = [ [ "Screw", "classSimTK_1_1MobilizedBody_1_1Screw.html#ac0962bd5a26af9a140ddc9ef27f8eab9", null ], [ "Screw", "classSimTK_1_1MobilizedBody_1_1Screw.html#ab78258fc13ef7e532427717c9779cf76", null ], [ "Screw", "classSimTK_1_1MobilizedBody_1_1Screw.html#aeb8b0b2d6983c70dae188ab57643b4c5", null ], [ "addBodyDecoration", "classSimTK_1_1MobilizedBody_1_1Screw.html#a36416746f9b8e899c29858cfda05fbbc", null ], [ "addOutboardDecoration", "classSimTK_1_1MobilizedBody_1_1Screw.html#a2fa3275b696a763ab280e7330c6182dd", null ], [ "addInboardDecoration", "classSimTK_1_1MobilizedBody_1_1Screw.html#a426a2eb883ecc8c86a4ee101e1a60e7e", null ], [ "setDefaultInboardFrame", "classSimTK_1_1MobilizedBody_1_1Screw.html#aeb068a3d407dc0126560314332f1a2f2", null ], [ "setDefaultOutboardFrame", "classSimTK_1_1MobilizedBody_1_1Screw.html#abacfc0c852666f1082b3321e60092f86", null ], [ "setDefaultPitch", "classSimTK_1_1MobilizedBody_1_1Screw.html#aa8fec5d77d368a1991e742012cbc7592", null ], [ "getDefaultPitch", "classSimTK_1_1MobilizedBody_1_1Screw.html#a06f0450496db9909150d708633d8add4", null ], [ "setDefaultQ", "classSimTK_1_1MobilizedBody_1_1Screw.html#a6e4146176f0544f83ef8fb012a62e9c9", null ], [ "getDefaultQ", "classSimTK_1_1MobilizedBody_1_1Screw.html#a292455d2fef5bd65812632114165c82d", null ], [ "getQ", "classSimTK_1_1MobilizedBody_1_1Screw.html#a0138602fda2540492d8b7e9ca486795f", null ], [ "getQDot", "classSimTK_1_1MobilizedBody_1_1Screw.html#a006c24ada4dfee35901bdb9a50837a83", null ], [ "getQDotDot", "classSimTK_1_1MobilizedBody_1_1Screw.html#a64dedaab0ab06aec954abedb5704eca3", null ], [ "getU", "classSimTK_1_1MobilizedBody_1_1Screw.html#a73176ae493666747366e91341c975922", null ], [ "getUDot", "classSimTK_1_1MobilizedBody_1_1Screw.html#aaa7eabaeabeeb5dabdc72c61f49d86d4", null ], [ "setQ", "classSimTK_1_1MobilizedBody_1_1Screw.html#af5ed4bad53e3e14008e1953d9e538a42", null ], [ "setU", "classSimTK_1_1MobilizedBody_1_1Screw.html#a0d786cd030e7030c429b8aec8b141d1b", null ], [ "getMyPartQ", "classSimTK_1_1MobilizedBody_1_1Screw.html#a0a7c29696dae14e4a9d3b2fe3873686e", null ], [ "getMyPartU", "classSimTK_1_1MobilizedBody_1_1Screw.html#a7a04ee5b1e9368884650a185904dc004", null ], [ "updMyPartQ", "classSimTK_1_1MobilizedBody_1_1Screw.html#aed693fea5aa0de252db1efcde673fb16", null ], [ "updMyPartU", "classSimTK_1_1MobilizedBody_1_1Screw.html#a270e66a8692625eb1263e5ad0201f565", null ] ];
// This file was procedurally generated from the following sources: // - src/class-elements/eval-contains-superproperty-1.case // - src/class-elements/initializer-eval-super-property/cls-decl-fields-eval.template /*--- description: super.x in StatementList of eval (direct eval) esid: sec-performeval-rules-in-initializer features: [class, class-fields-public] flags: [generated] info: | Additional Early Error Rules for Eval Inside Initializer These static semantics are applied by PerformEval when a direct eval call occurs inside a class field initializer. ScriptBody : StatementList ... The remaining eval rules apply as outside a constructor, inside a method, and inside a function. Additional Early Error Rules for Eval Outside Methods These static semantics are applied by PerformEval when a direct eval call occurs outside of a MethodDefinition. ScriptBody : StatementList It is a Syntax Error if StatementList Contains SuperProperty. ---*/ var executed = false; class A {} class C extends A { x = eval('executed = true; super.x;'); } new C(); assert.sameValue(executed, true);
// flow-typed signature: bbdbc6a9f99912296748be5c5eec24f9 // flow-typed version: <<STUB>>/cross-env_v^5.1.1/flow_v0.59.0 /** * This is an autogenerated libdef stub for: * * 'cross-env' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'cross-env' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ declare module 'cross-env/dist/bin/cross-env-shell' { declare module.exports: any; } declare module 'cross-env/dist/bin/cross-env' { declare module.exports: any; } declare module 'cross-env/dist/command' { declare module.exports: any; } declare module 'cross-env/dist/index' { declare module.exports: any; } declare module 'cross-env/dist/variable' { declare module.exports: any; } // Filename aliases declare module 'cross-env/dist/bin/cross-env-shell.js' { declare module.exports: $Exports<'cross-env/dist/bin/cross-env-shell'>; } declare module 'cross-env/dist/bin/cross-env.js' { declare module.exports: $Exports<'cross-env/dist/bin/cross-env'>; } declare module 'cross-env/dist/command.js' { declare module.exports: $Exports<'cross-env/dist/command'>; } declare module 'cross-env/dist/index.js' { declare module.exports: $Exports<'cross-env/dist/index'>; } declare module 'cross-env/dist/variable.js' { declare module.exports: $Exports<'cross-env/dist/variable'>; }
import React from 'react'; import { Router ,Route, hashHistory, IndexRoute} from 'react-router'; import App from '../layout/App'; import Index from 'pages/Test/App'; // import Index from 'pages/Test1/App'; // import Index from 'pages/Test2/App'; const Routers = ( <Router history={hashHistory}> <Route exact path="/" component={App}> <IndexRoute component={Index} /> </Route> </Router> ) export default Routers
import React from 'react' import {graphql, Link, StaticQuery} from 'gatsby' //import Layout from "../components/layout" const Homebanner = () => ( <StaticQuery query={graphql ` { allWordpressPage { edges { node { id title excerpt slug } } } allWordpressPost { edges { node { title excerpt slug } } } } ` }render = {props => ( <> <div> <h1>Pages</h1> {props.allWordpressPage.edges.map(({ node }) => ( <div key={node.slug}> <Link to={node.slug}> <h2>{node.title}</h2> </Link> <h3>{node.excerpt}</h3> </div> ))} </div> <h1>Posts</h1> {props.allWordpressPost.edges.map(({ node }) => ( <div key={node.slug}> <Link to={node.slug}> <h2>{node.title}</h2> </Link> <h3>{node.excerpt}</h3> </div> ))} </> )} /> ) export default Homebanner
function solve(n, array) { let newArr = []; for (let i = 0; i < n; i++){ newArr[i] = array[i]; } let output = ''; for (let j = newArr.length-1; j >= 0; j--){ output += `${Number(newArr[j])} `; } console.log (output); } solve (3, [10, 20, 30, 40, 50]); solve (4, [-1, 20, 99, 5]); solve (2, [66, 43, 75, 89, 47]);
import expect from 'expect.js'; import sinon from 'sinon'; import jsdom from 'mocha-jsdom'; import Widget from '../src/widget'; describe('Widget', () => { jsdom({url: 'http://localhost/'}); let widget; beforeEach(() => { widget = new Widget( document.createElement('div'), function handler(el) { this.onActivate = sinon.spy(); this.onDeactivate = sinon.spy(); this.onInitialize = sinon.spy(); this.onDispose = sinon.spy(); }, {}, 'dummy-handled' ); widget.init(); }); describe('#init()', () => { it('calls the onInitialize hook', () => { expect(widget.onInitialize.called).to.be.ok(); }); it('calls the onInitialize only once', () => { widget.init(); expect(widget.onInitialize.callCount).to.eql(1); }); it('adds the handled class on the target element', () => { expect(widget.element.classList.contains('dummy-handled')).to.be.ok(); }); }); describe('#activate()', () => { beforeEach(() => { widget.activate(); }); it('calls the onActivate hook', () => { expect(widget.onActivate.called).to.be.ok(); }); it('calls the onActivate only once', () => { widget.activate(); expect(widget.onActivate.callCount).to.eql(1); }); }); describe('#deactivate()', () => { beforeEach(() => { widget.activate(); widget.deactivate(); }); it('calls the onDeactivate hook', () => { expect(widget.onDeactivate.called).to.be.ok(); }); it('calls the onDeactivate only once', () => { widget.deactivate(); expect(widget.onDeactivate.callCount).to.eql(1); }); }); describe('#dispose()', () => { let element; beforeEach(() => { element = widget.element; widget.dispose(); }); it('calls the onDispose hook', () => { expect(widget.onDispose.called).to.be.ok(); }); it('calls the onDispose only once', () => { widget.dispose(); expect(widget.onDispose.callCount).to.eql(1); }); it('removes the handled class from the target element', () => { expect(element.classList.contains('dummy-handled')).not.to.be.ok(); }); }); });
/* global $this: true */ /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "animationsSlider" }] */ if ($.cookie('themeCSSpath')) { $('link#theme-stylesheet').attr('href', $.cookie('themeCSSpath')) } if ($.cookie('themeLayout')) { $('body').addClass($.cookie('themeLayout')) } $(function () { sliderHomepage() sliders() fullScreenContainer() productDetailGallery(4000) menuSliding() productDetailSizes() utils() animations() counters() demo() contactFormAjax() }) // Ajax contact function contactFormAjax () { var form = $('.contact-form-ajax') if (typeof form === 'undefined') return false form.submit(function () { $this = $(this) $.post($(this).attr('action'), $this.serialize(), function () { $this[0].reset() // clear form $('#contact-message') .html('<div class="alert alert-success" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>Thank you for getting in touch. We will get back to you soon!</div>') .fadeIn() } , 'json') return false }) } /* for demo purpose only - can be deleted */ function demo () { if ($.cookie('themeCSSpath')) { $('link#theme-stylesheet').attr('href', $.cookie('themeCSSpath')) } $('#colour').change(function () { if ($(this).val() !== '') { var themeCSSpath = 'css/style.' + $(this).val() + '.css' $('link#theme-stylesheet').attr('href', themeCSSpath) $.cookie('themeCSSpath', themeCSSpath, {expires: 365, path: '/'}) } return false }) $('#layout').change(function () { if ($(this).val() !== '') { var themeLayout = $(this).val() $('body').removeClass('wide') $('body').removeClass('boxed') $('body').addClass(themeLayout) $.cookie('themeLayout', themeLayout, {expires: 365, path: '/'}) } return false }) } /* slider homepage */ function sliderHomepage () { if ($('#slider').length) { // var owl = $('#slider') $('#slider').owlCarousel({ autoPlay: 3000, items: 4, itemsDesktopSmall: [900, 3], itemsTablet: [600, 3], itemsMobile: [500, 2] }) } } /* sliders */ function sliders () { if ($('.owl-carousel').length) { $('.customers').owlCarousel({ items: 6, itemsDesktopSmall: [990, 4], itemsTablet: [768, 2], itemsMobile: [480, 1] }) $('.testimonials').owlCarousel({ items: 4, itemsDesktopSmall: [990, 3], itemsTablet: [768, 2], itemsMobile: [480, 1] }) $('.project').owlCarousel({ navigation: true, // Show next and prev buttons navigationText: ['<i class="fas fa-angle-left"></i>', '<i class="fas fa-angle-right"></i>'], slideSpeed: 300, paginationSpeed: 400, autoPlay: true, stopOnHover: true, singleItem: true, afterInit: '', lazyLoad: true }) $('.homepage').owlCarousel({ navigation: false, // Show next and prev buttons navigationText: ['<i class="fas fa-angle-left"></i>', '<i class="fas fa-angle-right"></i>'], slideSpeed: 2000, paginationSpeed: 1000, autoPlay: true, stopOnHover: true, singleItem: true, lazyLoad: false, addClassActive: true, afterInit: function () { // animationsSlider() }, afterMove: function () { // animationsSlider() } }) } } /* menu sliding */ function menuSliding () { $('.dropdown').on('show.bs.dropdown', function () { if ($(window).width() > 750) { $(this).find('.dropdown-menu').first().stop(true, true).slideDown() } else { $(this).find('.dropdown-menu').first().stop(true, true).show() } }) $('.dropdown').on('hide.bs.dropdown', function () { if ($(window).width() > 750) { $(this).find('.dropdown-menu').first().stop(true, true).slideUp() } else { $(this).find('.dropdown-menu').first().stop(true, true).hide() } }) } /* animations */ function animations () { var delayTime = 0 $('[data-animate]').css({opacity: '0'}) $('[data-animate]').waypoint(function () { delayTime += 150 $(this).delay(delayTime).queue(function (next) { $(this).toggleClass('animated') $(this).toggleClass($(this).data('animate')) delayTime = 0 next() // $(this).removeClass('animated') // $(this).toggleClass($(this).data('animate')) }) }, { offset: '90%', triggerOnce: true }) $('[data-animate-hover]').hover(function () { $(this).css({opacity: 1}) $(this).addClass('animated') $(this).removeClass($(this).data('animate')) $(this).addClass($(this).data('animate-hover')) }, function () { $(this).removeClass('animated') $(this).removeClass($(this).data('animate-hover')) }) } function animationsSlider () { var delayTimeSlider = 400 $('.owl-item:not(.active) [data-animate-always]').each(function () { $(this).removeClass('animated') $(this).removeClass($(this).data('animate-always')) $(this).stop(true, true, true).css({opacity: 0}) }) $('.owl-item.active [data-animate-always]').each(function () { delayTimeSlider += 500 $(this).delay(delayTimeSlider).queue(function () { $(this).addClass('animated') $(this).addClass($(this).data('animate-always')) console.log($(this).data('animate-always')) }) }) } /* counters */ function counters () { $('.counter').counterUp({ delay: 10, time: 1000 }) } /* picture zoom */ function pictureZoom () { $('.product .image, .post .image, .photostream div').each(function () { var imgHeight = $(this).find('img').height() if (imgHeight) { $(this).height(imgHeight) } }) } /* full screen intro */ function fullScreenContainer () { var screenWidth = $(window).width() + 'px' var screenHeight = '500px' if ($(window).height() > 500) { screenHeight = $(window).height() + 'px' } $('#intro, #intro .item').css({ width: screenWidth, height: screenHeight }) } function utils () { /* tooltips */ $('[data-toggle="tooltip"]').tooltip() /* click on the box activates the radio */ $('#checkout').on('click', '.box.shipping-method, .box.payment-method', function () { var radio = $(this).find(':radio') radio.prop('checked', true) }) /* click on the box activates the link in it */ $('.box.clickable').on('click', function () { window.location = $(this).find('a').attr('href') }) /* external links in new window */ $('.external').on('click', function (e) { e.preventDefault() window.open($(this).attr('href')) }) /* animated scrolling */ $('.scroll-to, .scroll-to-top').click(function (event) { var fullUrl = this.href var parts = fullUrl.split('#') if (parts.length > 1) { scrollTo(fullUrl) event.preventDefault() } }) function scrollTo (fullUrl) { var parts = fullUrl.split('#') var trgt = parts[1] var targetOffset = $('#' + trgt).offset() var targetTop = targetOffset.top - 100 if (targetTop < 0) { targetTop = 0 } $('html, body').animate({ scrollTop: targetTop }, 1000) } } /* product detail gallery */ function productDetailGallery (confDetailSwitch) { $('.thumb:first').addClass('active') var timer = setInterval(autoSwitch, confDetailSwitch) $('.thumb').click(function (e) { switchImage($(this)) clearInterval(timer) timer = setInterval(autoSwitch, confDetailSwitch) e.preventDefault() }) $('#mainImage').hover(function () { clearInterval(timer) }, function () { timer = setInterval(autoSwitch, confDetailSwitch) }) function autoSwitch () { var nextThumb = $('.thumb.active').closest('div').next('div').find('.thumb') if (nextThumb.length === 0) { nextThumb = $('.thumb:first') } switchImage(nextThumb) } function switchImage (thumb) { $('.thumb').removeClass('active') var bigUrl = thumb.attr('href') thumb.addClass('active') $('#mainImage img').attr('src', bigUrl) } } /* product detail sizes */ function productDetailSizes () { $('.sizes a').click(function (e) { e.preventDefault() $('.sizes a').removeClass('active') $('.size-input').prop('checked', false) $(this).addClass('active') $(this).next('input').prop('checked', true) }) } $.fn.alignElementsSameHeight = function () { $('.same-height-row').each(function () { var maxHeight = 0 var children = $(this).find('.same-height') children.height('auto') if ($(window).width() > 768) { children.each(function () { if ($(this).innerHeight() > maxHeight) { maxHeight = $(this).innerHeight() } }) children.innerHeight(maxHeight) } maxHeight = 0 children = $(this).find('.same-height-always') children.height('auto') children.each(function () { if ($(this).height() > maxHeight) { maxHeight = $(this).innerHeight() } }) children.innerHeight(maxHeight) }) } var windowWidth $(function () { windowWidth = $(window).width() $(this).alignElementsSameHeight() pictureZoom() }) $(window).resize(function () { var newWindowWidth = $(window).width() if (windowWidth !== newWindowWidth) { setTimeout(function () { $(this).alignElementsSameHeight() fullScreenContainer() pictureZoom() }, 205) windowWidth = newWindowWidth } })
import request from '@/utils/request' export function login(data) { return request({ url: '/adminUser/login', method: 'post', data }) } export function getAdminList(data) { return request({ url: '/adminUser', method: 'get', params: data }) } export function deleteById(userId) { return request({ url: '/adminUser/' + userId, method: 'delete' }) } export function getAdminById(userId) { return request({ url: '/adminUser/' + userId, method: 'get' }) } export function addAdmin(data) { return request({ url: '/adminUser', method: 'post', data }) } export function updateAdmin(data) { return request({ url: '/adminUser', method: 'put', data }) } // TODO 删除下面的方法 export function getInfo(token) { return request({ url: '/vue-admin-template/user/info', method: 'get', params: { token } }) } export function logout() { return request({ url: '/vue-admin-template/user/logout', method: 'post' }) }
const _ = require('lodash'); const Knex = require('knex'); const expect = require('expect.js'); const Promise = require('bluebird'); const objection = require('../../../'); const { isFunction } = require('../../../lib/utils/objectUtils'); const knexMocker = require('../../../testUtils/mockKnex'); const RelationOwner = require('../../../lib/relations/RelationOwner').RelationOwner; const Model = objection.Model; const QueryBuilder = objection.QueryBuilder; const ManyToManyRelation = objection.ManyToManyRelation; describe('ManyToManyRelation', () => { let mockKnexQueryResults = []; let executedQueries = []; let mockKnex = null; let OwnerModel = null; let RelatedModel = null; let JoinModel = null; let relation; let compositeKeyRelation; beforeEach(() => { let knex = Knex({ client: 'pg' }); mockKnex = knexMocker(knex, function(mock, oldImpl, args) { executedQueries.push(this.toString()); let result = mockKnexQueryResults.shift() || []; let promise = Promise.resolve(result); return promise.then.apply(promise, args); }); }); beforeEach(() => { mockKnexQueryResults = []; executedQueries = []; OwnerModel = class OwnerModel extends Model { static get tableName() { return 'OwnerModel'; } }; RelatedModel = class RelatedModel extends Model { static get tableName() { return 'RelatedModel'; } static get modifiers() { return { modifier: builder => builder.where('filteredProperty', true) }; } }; JoinModel = class JoinModel extends Model { static get tableName() { return 'JoinModel'; } }; OwnerModel.knex(mockKnex); RelatedModel.knex(mockKnex); JoinModel.knex(mockKnex); }); beforeEach(() => { relation = new ManyToManyRelation('nameOfOurRelation', OwnerModel); relation.setMapping({ modelClass: RelatedModel, relation: ManyToManyRelation, join: { from: 'OwnerModel.oid', through: { from: 'JoinModel.ownerId', to: 'JoinModel.relatedId', extra: ['extra1', 'extra2'] }, to: 'RelatedModel.rid' } }); compositeKeyRelation = new ManyToManyRelation('nameOfOurRelation', OwnerModel); compositeKeyRelation.setMapping({ modelClass: RelatedModel, relation: ManyToManyRelation, join: { from: ['OwnerModel.aid', 'OwnerModel.bid'], through: { from: ['JoinModel.ownerAId', 'JoinModel.ownerBId'], to: ['JoinModel.relatedCId', 'JoinModel.relatedDId'] }, to: ['RelatedModel.cid', 'RelatedModel.did'] } }); }); it('should accept a join table in join.through object', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'OwnerModel.id', through: { from: 'JoinModel.ownerId', to: 'JoinModel.relatedId' }, to: 'RelatedModel.ownerId' } }); expect(relation.joinTable).to.equal('JoinModel'); expect(relation.joinTableOwnerProp.cols).to.eql(['ownerId']); expect(relation.joinTableRelatedProp.cols).to.eql(['relatedId']); }); it('should accept a join model in join.through object', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'OwnerModel.id', through: { modelClass: JoinModel, from: 'JoinModel.ownerId', to: 'JoinModel.relatedId' }, to: 'RelatedModel.ownerId' } }); expect(relation.joinTable).to.equal('JoinModel'); expect(relation.joinTableOwnerProp.cols).to.eql(['ownerId']); expect(relation.joinTableRelatedProp.props).to.eql(['relatedId']); expect(isSubclassOf(relation.joinModelClass, JoinModel)).to.equal(true); }); it('should accept an absolute file path to a join model in join.through object', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'OwnerModel.id', through: { modelClass: __dirname + '/files/JoinModel', from: 'JoinModel.ownerId', to: 'JoinModel.relatedId' }, to: 'RelatedModel.ownerId' } }); expect(relation.joinTable).to.equal('JoinModel'); expect(relation.joinTableOwnerProp.cols).to.eql(['ownerId']); expect(relation.joinTableRelatedProp.cols).to.eql(['relatedId']); expect(isSubclassOf(relation.joinModelClass, require('./files/JoinModel'))).to.equal(true); }); it('should accept a composite keys in join.through object (1)', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: ['OwnerModel.name', 'OwnerModel.dateOfBirth'], through: { from: ['JoinModel.ownerName', 'JoinModel.ownerDateOfBirth'], to: 'JoinModel.relatedId' }, to: 'RelatedModel.ownerId' } }); expect(relation.joinTable).to.equal('JoinModel'); expect(relation.joinTableOwnerProp.cols).to.eql(['ownerName', 'ownerDateOfBirth']); expect(relation.joinTableRelatedProp.cols).to.eql(['relatedId']); }); it('should accept a composite keys in join.through object (2)', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: ['OwnerModel.name', 'OwnerModel.dateOfBirth'], through: { from: ['JoinModel.ownerName', 'JoinModel.ownerDateOfBirth'], to: ['JoinModel.relatedA', 'JoinModel.relatedB'] }, to: ['RelatedModel.A', 'RelatedModel.B'] } }); expect(relation.joinTable).to.equal('JoinModel'); expect(relation.joinTableOwnerProp.cols).to.eql(['ownerName', 'ownerDateOfBirth']); expect(relation.joinTableRelatedProp.cols).to.eql(['relatedA', 'relatedB']); }); it('should accept an array in through.extra', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'OwnerModel.id', through: { from: 'JoinModel.ownerId', to: 'JoinModel.relatedId', extra: ['extra1', 'extra2'] }, to: 'RelatedModel.ownerId' } }); expect(relation.joinTableExtras[0].joinTableCol).to.equal('extra1'); expect(relation.joinTableExtras[1].joinTableCol).to.equal('extra2'); }); it('should accept a string in through.extra', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'OwnerModel.id', through: { from: 'JoinModel.ownerId', to: 'JoinModel.relatedId', extra: 'extra1' }, to: 'RelatedModel.ownerId' } }); expect(relation.joinTableExtras[0].joinTableCol).to.equal('extra1'); }); it('should accept an object in through.extra', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'OwnerModel.id', through: { from: 'JoinModel.ownerId', to: 'JoinModel.relatedId', extra: { extra1: 'extraColumn' } }, to: 'RelatedModel.ownerId' } }); expect(relation.joinTableExtras[0].joinTableCol).to.equal('extraColumn'); expect(relation.joinTableExtras[0].joinTableProp).to.equal('extraColumn'); expect(relation.joinTableExtras[0].aliasCol).to.equal('extra1'); }); it('should fail if join.through.modelClass is not a subclass of Model', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); expect(() => { relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'RelatedModel.ownerId', through: { modelClass: function() {}, from: 'JoinModel.relatedId', to: 'JoinModel.ownerId' }, to: 'OwnerModel.id' } }); }).to.throwException(err => { expect(err.message).to.equal( 'OwnerModel.relationMappings.testRelation: join.through.modelClass: is not a subclass of Model or a file path to a module that exports one. You may be dealing with a require loop. See the documentation section about require loops.' ); }); }); it('should fail if join.through.modelClass is an invalid path', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); expect(() => { relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'RelatedModel.ownerId', through: { modelClass: '/not/a/path/to/a/model', from: 'JoinModel.relatedId', to: 'JoinModel.ownerId' }, to: 'OwnerModel.id' } }); }).to.throwException(err => { expect(err.message).to.contain( "OwnerModel.relationMappings.testRelation: Cannot find module '/not/a/path/to/a/model'" ); }); }); it('should fail if join.through.to is missing', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); expect(() => { relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'RelatedModel.ownerId', through: { from: 'JoinModel.relatedId' }, to: 'OwnerModel.id' } }); }).to.throwException(err => { expect(err.message).to.contain( 'OwnerModel.relationMappings.testRelation: join.through must be an object that describes the join table. For example: {from: "JoinTable.someId", to: "JoinTable.someOtherId"}' ); }); }); it('should fail if join.through.from is missing', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); expect(() => { relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'RelatedModel.ownerId', through: { to: 'JoinModel.ownerId' }, to: 'OwnerModel.id' } }); }).to.throwException(err => { expect(err.message).to.contain( 'OwnerModel.relationMappings.testRelation: join.through must be an object that describes the join table. For example: {from: "JoinTable.someId", to: "JoinTable.someOtherId"}' ); }); }); it('join.through.from should have format joinTable.columnName', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); expect(() => { relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'RelatedModel.ownerId', through: { from: 'relatedId', to: 'JoinModel.ownerId' }, to: 'OwnerModel.id' } }); }).to.throwException(err => { expect(err.message).to.contain( 'OwnerModel.relationMappings.testRelation: join.through.from must have format JoinTable.columnName. For example "JoinTable.someId" or in case of composite key ["JoinTable.a", "JoinTable.b"].' ); }); }); it('join.through.to should have format JoinModel.columnName', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); expect(() => { relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'RelatedModel.ownerId', through: { from: 'JoinModel.relatedId', to: 'ownerId' }, to: 'OwnerModel.id' } }); }).to.throwException(err => { expect(err.message).to.contain( 'OwnerModel.relationMappings.testRelation: join.through.to must have format JoinTable.columnName. For example "JoinTable.someId" or in case of composite key ["JoinTable.a", "JoinTable.b"].' ); }); }); it('join.through `to` and `from` should point to the same table', () => { let relation = new ManyToManyRelation('testRelation', OwnerModel); expect(() => { relation.setMapping({ relation: ManyToManyRelation, modelClass: RelatedModel, join: { from: 'RelatedModel.ownerId', through: { from: 'JoinModel.relatedId', to: 'OtherTable.ownerId' }, to: 'OwnerModel.id' } }); }).to.throwException(err => { expect(err.message).to.contain( 'OwnerModel.relationMappings.testRelation: join.through `from` and `to` must point to the same join table.' ); }); }); describe('find', () => { it('should generate a find query', () => { let owner = OwnerModel.fromJson({ oid: 666 }); let expectedResult = [ { a: 1, objectiontmpjoin0: 666 }, { a: 2, objectiontmpjoin0: 666 } ]; mockKnexQueryResults = [expectedResult]; let builder = QueryBuilder.forClass(RelatedModel) .where('name', 'Teppo') .orWhere('age', '>', 60) .findOperationFactory(builder => { return relation.find(builder, RelationOwner.create(owner)); }); return builder.then(result => { expect(result).to.have.length(2); expect(result).to.eql(expectedResult); expect(owner.nameOfOurRelation).to.eql(expectedResult); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal( [ 'select "RelatedModel".*, "JoinModel"."extra1" as "extra1", "JoinModel"."extra2" as "extra2", "JoinModel"."ownerId" as "objectiontmpjoin0"', 'from "RelatedModel"', 'inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId"', 'where "JoinModel"."ownerId" in (666)', 'and "name" = \'Teppo\'', 'or "age" > 60' ].join(' ') ); }); }); it('should generate a find query (composite key)', () => { let owner = OwnerModel.fromJson({ aid: 11, bid: 22 }); let expectedResult = [ { a: 1, objectiontmpjoin0: 11, objectiontmpjoin1: 22 }, { a: 2, objectiontmpjoin0: 11, objectiontmpjoin1: 22 } ]; mockKnexQueryResults = [expectedResult]; let builder = QueryBuilder.forClass(RelatedModel) .where('name', 'Teppo') .orWhere('age', '>', 60) .findOperationFactory(builder => { return compositeKeyRelation.find(builder, RelationOwner.create(owner)); }); return builder.then(result => { expect(result).to.have.length(2); expect(result).to.eql(expectedResult); expect(owner.nameOfOurRelation).to.eql(expectedResult); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal( [ 'select "RelatedModel".*, "JoinModel"."ownerAId" as "objectiontmpjoin0", "JoinModel"."ownerBId" as "objectiontmpjoin1"', 'from "RelatedModel"', 'inner join "JoinModel" on "RelatedModel"."cid" = "JoinModel"."relatedCId" and "RelatedModel"."did" = "JoinModel"."relatedDId"', 'where ("JoinModel"."ownerAId", "JoinModel"."ownerBId") in ((11, 22))', 'and "name" = \'Teppo\'', 'or "age" > 60' ].join(' ') ); }); }); it('should find for multiple owners', () => { let owners = [OwnerModel.fromJson({ oid: 666 }), OwnerModel.fromJson({ oid: 667 })]; let expectedResult = [ { a: 1, objectiontmpjoin0: 666 }, { a: 2, objectiontmpjoin0: 666 }, { a: 3, objectiontmpjoin0: 667 }, { a: 4, objectiontmpjoin0: 667 } ]; mockKnexQueryResults = [expectedResult]; let builder = QueryBuilder.forClass(RelatedModel) .where('name', 'Teppo') .orWhere('age', '>', 60) .findOperationFactory(function() { return relation.find(this, RelationOwner.create(owners)); }); return builder.then(result => { expect(result).to.have.length(4); expect(result).to.eql(expectedResult); expect(owners[0].nameOfOurRelation).to.eql([{ a: 1 }, { a: 2 }]); expect(owners[1].nameOfOurRelation).to.eql([{ a: 3 }, { a: 4 }]); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); expect(result[2]).to.be.a(RelatedModel); expect(result[3]).to.be.a(RelatedModel); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal( [ 'select "RelatedModel".*, "JoinModel"."extra1" as "extra1", "JoinModel"."extra2" as "extra2", "JoinModel"."ownerId" as "objectiontmpjoin0"', 'from "RelatedModel"', 'inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId"', 'where "JoinModel"."ownerId" in (666, 667)', 'and "name" = \'Teppo\'', 'or "age" > 60' ].join(' ') ); }); }); it('should find for multiple owners (composite key)', () => { let owners = [ OwnerModel.fromJson({ aid: 11, bid: 22 }), OwnerModel.fromJson({ aid: 11, bid: 33 }) ]; let expectedResult = [ { a: 1, objectiontmpjoin0: 11, objectiontmpjoin1: 22 }, { a: 2, objectiontmpjoin0: 11, objectiontmpjoin1: 22 }, { a: 3, objectiontmpjoin0: 11, objectiontmpjoin1: 33 }, { a: 4, objectiontmpjoin0: 11, objectiontmpjoin1: 33 } ]; mockKnexQueryResults = [expectedResult]; let builder = QueryBuilder.forClass(RelatedModel) .where('name', 'Teppo') .orWhere('age', '>', 60) .findOperationFactory(function() { return compositeKeyRelation.find(this, RelationOwner.create(owners)); }); return builder.then(result => { expect(result).to.have.length(4); expect(result).to.eql(expectedResult); expect(owners[0].nameOfOurRelation).to.eql([{ a: 1 }, { a: 2 }]); expect(owners[1].nameOfOurRelation).to.eql([{ a: 3 }, { a: 4 }]); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); expect(result[2]).to.be.a(RelatedModel); expect(result[3]).to.be.a(RelatedModel); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal( [ 'select "RelatedModel".*, "JoinModel"."ownerAId" as "objectiontmpjoin0", "JoinModel"."ownerBId" as "objectiontmpjoin1"', 'from "RelatedModel"', 'inner join "JoinModel" on "RelatedModel"."cid" = "JoinModel"."relatedCId" and "RelatedModel"."did" = "JoinModel"."relatedDId"', 'where ("JoinModel"."ownerAId", "JoinModel"."ownerBId") in ((11, 22), (11, 33))', 'and "name" = \'Teppo\'', 'or "age" > 60' ].join(' ') ); }); }); it('explicit selects should override the RelatedModel.*', () => { let owner = OwnerModel.fromJson({ oid: 666 }); let expectedResult = [ { a: 1, objectiontmpjoin0: 666 }, { a: 2, objectiontmpjoin0: 666 } ]; mockKnexQueryResults = [expectedResult]; let builder = QueryBuilder.forClass(RelatedModel) .where('name', 'Teppo') .orWhere('age', '>', 60) .select('name') .findOperationFactory(function() { return relation.find(this, RelationOwner.create(owner)); }); return builder.then(result => { expect(result).to.have.length(2); expect(result).to.eql(expectedResult); expect(owner.nameOfOurRelation).to.eql(expectedResult); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal( [ 'select "JoinModel"."ownerId" as "objectiontmpjoin0", "RelatedModel"."rid", "name"', 'from "RelatedModel"', 'inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId"', 'where "JoinModel"."ownerId" in (666)', 'and "name" = \'Teppo\'', 'or "age" > 60' ].join(' ') ); }); }); // TODO expectedResult array is changed in-place and the items in it are replaced with model instances. SHOULD FIX THAT! it('should apply the modifier', () => { createModifiedRelation({ someColumn: 100 }); let owner = OwnerModel.fromJson({ oid: 666 }); let expectedResult = [ { a: 1, objectiontmpjoin0: 666 }, { a: 2, objectiontmpjoin0: 666 } ]; mockKnexQueryResults = [expectedResult]; let builder = QueryBuilder.forClass(RelatedModel) .where('name', 'Teppo') .orWhere('age', '>', 60) .findOperationFactory(function() { return relation.find(this, RelationOwner.create(owner)); }); return builder.then(result => { expect(result).to.have.length(2); expect(result).to.eql(expectedResult); expect(owner.nameOfOurRelation).to.eql(expectedResult); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal( [ 'select "RelatedModel".*, "JoinModel"."ownerId" as "objectiontmpjoin0"', 'from "RelatedModel"', 'inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId"', 'where "JoinModel"."ownerId" in (666)', 'and "someColumn" = 100', 'and "name" = \'Teppo\'', 'or "age" > 60' ].join(' ') ); }); }); // TODO expectedResult array is changed in-place and the items in it are replaced with model instances. SHOULD FIX THAT! it('should support modifiers', () => { createModifiedRelation('modifier'); let owner = OwnerModel.fromJson({ oid: 666 }); let expectedResult = [ { a: 1, objectiontmpjoin0: 666 }, { a: 2, objectiontmpjoin0: 666 } ]; mockKnexQueryResults = [expectedResult]; let builder = QueryBuilder.forClass(RelatedModel) .where('name', 'Teppo') .orWhere('age', '>', 60) .findOperationFactory(function() { return relation.find(this, RelationOwner.create(owner)); }); return builder.then(result => { expect(result).to.have.length(2); expect(result).to.eql(expectedResult); expect(owner.nameOfOurRelation).to.eql(expectedResult); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal( [ 'select "RelatedModel".*, "JoinModel"."ownerId" as "objectiontmpjoin0"', 'from "RelatedModel"', 'inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId"', 'where "JoinModel"."ownerId" in (666)', 'and "filteredProperty" = true', 'and "name" = \'Teppo\'', 'or "age" > 60' ].join(' ') ); }); }); }); describe('insert', () => { it('should generate an insert query', () => { mockKnexQueryResults = [[1, 2]]; let owner = OwnerModel.fromJson({ oid: 666 }); let related = [ RelatedModel.fromJson({ a: 'str1', rid: 3 }), RelatedModel.fromJson({ a: 'str2', rid: 4 }) ]; owner.nameOfOurRelation = [RelatedModel.fromJson({ a: 'str0', id: 3 })]; let builder = QueryBuilder.forClass(RelatedModel) .insertOperationFactory(builder => { return relation.insert(builder, RelationOwner.create(owner)); }) .insert(related); let toString = builder.toKnexQuery().toString(); let toSql = builder.toKnexQuery().toString(); return builder.then(result => { expect(executedQueries).to.have.length(2); expect(executedQueries[0]).to.equal(toString); expect(executedQueries[0]).to.equal(toSql); expect(executedQueries[0]).to.equal( 'insert into "RelatedModel" ("a", "rid") values (\'str1\', 3), (\'str2\', 4) returning "id"' ); expect(executedQueries[1]).to.equal( 'insert into "JoinModel" ("ownerId", "relatedId") values (666, 3), (666, 4) returning "relatedId"' ); expect(_.sortBy(owner.nameOfOurRelation, 'id')).to.eql([ { a: 'str1', id: 1, rid: 3 }, { a: 'str2', id: 2, rid: 4 }, { a: 'str0', id: 3 } ]); expect(result).to.eql([ { a: 'str1', id: 1, rid: 3 }, { a: 'str2', id: 2, rid: 4 } ]); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); }); }); it('should generate an insert query (composite key)', () => { mockKnexQueryResults = [ [ { id: 1, cid: 33, did: 44 }, { id: 2, cid: 33, did: 55 } ] ]; let owner = OwnerModel.fromJson({ aid: 11, bid: 22 }); let related = [ RelatedModel.fromJson({ a: 'str1', cid: 33, did: 44 }), RelatedModel.fromJson({ a: 'str2', cid: 33, did: 55 }) ]; owner.nameOfOurRelation = [RelatedModel.fromJson({ a: 'str0', id: 3 })]; let builder = QueryBuilder.forClass(RelatedModel) .insertOperationFactory(builder => { return compositeKeyRelation.insert(builder, RelationOwner.create(owner)); }) .insert(related); let toString = builder.toKnexQuery().toString(); let toSql = builder.toKnexQuery().toString(); return builder.then(result => { expect(executedQueries).to.have.length(2); expect(executedQueries[0]).to.equal(toString); expect(executedQueries[0]).to.equal(toSql); expect(executedQueries[0]).to.equal( 'insert into "RelatedModel" ("a", "cid", "did") values (\'str1\', 33, 44), (\'str2\', 33, 55) returning "id"' ); expect(executedQueries[1]).to.equal( 'insert into "JoinModel" ("ownerAId", "ownerBId", "relatedCId", "relatedDId") values (11, 22, 33, 44), (11, 22, 33, 55) returning "relatedCId", "relatedDId"' ); expect(_.sortBy(owner.nameOfOurRelation, 'id')).to.eql([ { a: 'str1', id: 1, cid: 33, did: 44 }, { a: 'str2', id: 2, cid: 33, did: 55 }, { a: 'str0', id: 3 } ]); expect(result).to.eql([ { a: 'str1', id: 1, cid: 33, did: 44 }, { a: 'str2', id: 2, cid: 33, did: 55 } ]); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); }); }); it('should accept json object array', () => { mockKnexQueryResults = [[1, 2]]; let owner = OwnerModel.fromJson({ oid: 666 }); let related = [ { a: 'str1', rid: 3 }, { a: 'str2', rid: 4 } ]; let builder = QueryBuilder.forClass(RelatedModel) .insertOperationFactory(builder => { return relation.insert(builder, RelationOwner.create(owner)); }) .insert(related); let toString = builder.toKnexQuery().toString(); let toSql = builder.toKnexQuery().toString(); return builder.then(result => { expect(executedQueries).to.have.length(2); expect(executedQueries[0]).to.equal(toString); expect(executedQueries[0]).to.equal(toSql); expect(executedQueries[0]).to.equal( 'insert into "RelatedModel" ("a", "rid") values (\'str1\', 3), (\'str2\', 4) returning "id"' ); expect(executedQueries[1]).to.equal( 'insert into "JoinModel" ("ownerId", "relatedId") values (666, 3), (666, 4) returning "relatedId"' ); expect(owner.nameOfOurRelation).to.eql([ { a: 'str1', id: 1, rid: 3 }, { a: 'str2', id: 2, rid: 4 } ]); expect(result).to.eql([ { a: 'str1', id: 1, rid: 3 }, { a: 'str2', id: 2, rid: 4 } ]); expect(result[0]).to.be.a(RelatedModel); expect(result[1]).to.be.a(RelatedModel); }); }); it('should accept single model', () => { mockKnexQueryResults = [[1]]; let owner = OwnerModel.fromJson({ oid: 666 }); let related = RelatedModel.fromJson({ a: 'str1', rid: 2 }); let builder = QueryBuilder.forClass(RelatedModel) .insertOperationFactory(builder => { return relation.insert(builder, RelationOwner.create(owner)); }) .insert(related); let toString = builder.toKnexQuery().toString(); let toSql = builder.toKnexQuery().toString(); return builder.then(result => { expect(executedQueries).to.have.length(2); expect(executedQueries[0]).to.equal(toString); expect(executedQueries[0]).to.equal(toSql); expect(executedQueries[0]).to.equal( 'insert into "RelatedModel" ("a", "rid") values (\'str1\', 2) returning "id"' ); expect(executedQueries[1]).to.equal( 'insert into "JoinModel" ("ownerId", "relatedId") values (666, 2) returning "relatedId"' ); expect(result).to.eql({ a: 'str1', id: 1, rid: 2 }); expect(result).to.be.a(RelatedModel); }); }); it('should accept single json object', () => { mockKnexQueryResults = [[1]]; let owner = OwnerModel.fromJson({ oid: 666 }); let related = { a: 'str1', rid: 2 }; let builder = QueryBuilder.forClass(RelatedModel) .insertOperationFactory(builder => { return relation.insert(builder, RelationOwner.create(owner)); }) .insert(related); let toString = builder.toKnexQuery().toString(); let toSql = builder.toKnexQuery().toString(); return builder.then(result => { expect(executedQueries).to.have.length(2); expect(executedQueries[0]).to.equal(toString); expect(executedQueries[0]).to.equal(toSql); expect(executedQueries[0]).to.equal( 'insert into "RelatedModel" ("a", "rid") values (\'str1\', 2) returning "id"' ); expect(executedQueries[1]).to.equal( 'insert into "JoinModel" ("ownerId", "relatedId") values (666, 2) returning "relatedId"' ); expect(result).to.eql({ a: 'str1', id: 1, rid: 2 }); expect(result).to.be.a(RelatedModel); }); }); it('should insert extra properties to join table', () => { mockKnexQueryResults = [[1, 2]]; let owner = OwnerModel.fromJson({ oid: 666 }); let related = RelatedModel.fromJson({ a: 'str2', rid: 4, extra1: 'extraVal1', extra2: 'extraVal2' }); owner.nameOfOurRelation = [RelatedModel.fromJson({ a: 'str0', id: 3 })]; let builder = QueryBuilder.forClass(RelatedModel) .insertOperationFactory(builder => { return relation.insert(builder, RelationOwner.create(owner)); }) .insert(related); let toString = builder.toKnexQuery().toString(); let toSql = builder.toKnexQuery().toString(); return builder.then(result => { expect(executedQueries).to.have.length(2); expect(executedQueries[0]).to.equal(toString); expect(executedQueries[0]).to.equal(toSql); expect(executedQueries[0]).to.equal( 'insert into "RelatedModel" ("a", "rid") values (\'str2\', 4) returning "id"' ); expect(executedQueries[1]).to.equal( 'insert into "JoinModel" ("extra1", "extra2", "ownerId", "relatedId") values (\'extraVal1\', \'extraVal2\', 666, 4) returning "relatedId"' ); expect(_.sortBy(_.invokeMap(owner.nameOfOurRelation, 'toJSON'), 'id')).to.eql([ { a: 'str2', id: 1, rid: 4, extra1: 'extraVal1', extra2: 'extraVal2' }, { a: 'str0', id: 3 } ]); expect(result).to.be.a(RelatedModel); expect(result.toJSON()).to.eql({ a: 'str2', id: 1, rid: 4, extra1: 'extraVal1', extra2: 'extraVal2' }); }); }); it('should insert extra properties to join table (not all)', () => { mockKnexQueryResults = [[1, 2]]; let owner = OwnerModel.fromJson({ oid: 666 }); let related = RelatedModel.fromJson({ a: 'str2', rid: 4, extra2: 'extraVal2' }); owner.nameOfOurRelation = [RelatedModel.fromJson({ a: 'str0', id: 3 })]; let builder = QueryBuilder.forClass(RelatedModel) .insertOperationFactory(builder => { return relation.insert(builder, RelationOwner.create(owner)); }) .insert(related); let toString = builder.toKnexQuery().toString(); let toSql = builder.toKnexQuery().toString(); return builder.then(result => { expect(executedQueries).to.have.length(2); expect(executedQueries[0]).to.equal(toString); expect(executedQueries[0]).to.equal(toSql); expect(executedQueries[0]).to.equal( 'insert into "RelatedModel" ("a", "rid") values (\'str2\', 4) returning "id"' ); expect(executedQueries[1]).to.equal( 'insert into "JoinModel" ("extra2", "ownerId", "relatedId") values (\'extraVal2\', 666, 4) returning "relatedId"' ); expect(_.sortBy(_.invokeMap(owner.nameOfOurRelation, 'toJSON'), 'id')).to.eql([ { a: 'str2', id: 1, rid: 4, extra2: 'extraVal2' }, { a: 'str0', id: 3 } ]); expect(result).to.be.a(RelatedModel); expect(result.toJSON()).to.eql({ a: 'str2', id: 1, rid: 4, extra2: 'extraVal2' }); }); }); }); describe('update', () => { it('should generate an update query', () => { mockKnexQueryResults = [42]; let owner = OwnerModel.fromJson({ oid: 666 }); let update = RelatedModel.fromJson({ a: 'str1' }); let builder = QueryBuilder.forClass(RelatedModel) .updateOperationFactory(builder => { return relation.update(builder, RelationOwner.create(owner)); }) .update(update) .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored'); return builder.then(numUpdated => { expect(numUpdated).to.equal(42); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( `update "RelatedModel" set "a" = 'str1' where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666) and "gender" = 'male' and "thingy" is not null)` ); }); }); it('should generate an update query (composite key)', () => { mockKnexQueryResults = [42]; let owner = OwnerModel.fromJson({ aid: 11, bid: 22 }); let update = RelatedModel.fromJson({ a: 'str1' }); let builder = QueryBuilder.forClass(RelatedModel) .updateOperationFactory(builder => { return compositeKeyRelation.update(builder, RelationOwner.create(owner)); }) .update(update) .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored'); return builder.then(numUpdated => { expect(numUpdated).to.equal(42); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( `update "RelatedModel" set "a" = 'str1' where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."cid" = "JoinModel"."relatedCId" and "RelatedModel"."did" = "JoinModel"."relatedDId" where ("JoinModel"."ownerAId", "JoinModel"."ownerBId") in ((11, 22)) and "gender" = 'male' and "thingy" is not null)` ); }); }); it('should accept json object', () => { mockKnexQueryResults = [42]; let owner = OwnerModel.fromJson({ oid: 666 }); let update = { a: 'str1' }; return QueryBuilder.forClass(RelatedModel) .updateOperationFactory(builder => { return relation.update(builder, RelationOwner.create(owner)); }) .update(update) .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored') .then(numUpdated => { expect(numUpdated).to.equal(42); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.eql( `update "RelatedModel" set "a" = 'str1' where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666) and "gender" = 'male' and "thingy" is not null)` ); }); }); it('should apply the modifier', () => { createModifiedRelation({ someColumn: 100 }); let owner = OwnerModel.fromJson({ oid: 666 }); let update = RelatedModel.fromJson({ a: 'str1' }); return QueryBuilder.forClass(RelatedModel) .updateOperationFactory(builder => { return relation.update(builder, RelationOwner.create(owner)); }) .update(update) .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored') .then(() => { expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.eql( `update "RelatedModel" set "a" = 'str1' where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666) and "someColumn" = 100 and "gender" = 'male' and "thingy" is not null)` ); }); }); }); describe('patch', () => { it('should generate a patch query', () => { mockKnexQueryResults = [42]; let owner = OwnerModel.fromJson({ oid: 666 }); let patch = RelatedModel.fromJson({ a: 'str1' }); let builder = QueryBuilder.forClass(RelatedModel) .patchOperationFactory(builder => { return relation.patch(builder, RelationOwner.create(owner)); }) .patch(patch) .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored'); return builder.then(numUpdated => { expect(numUpdated).to.equal(42); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( `update "RelatedModel" set "a" = 'str1' where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666) and "gender" = 'male' and "thingy" is not null)` ); }); }); it('should accept json object', () => { mockKnexQueryResults = [42]; RelatedModel.jsonSchema = { type: 'object', required: ['b'], properties: { id: { type: 'number' }, a: { type: 'string' }, b: { type: 'string' } } }; let owner = OwnerModel.fromJson({ oid: 666 }); let patch = { a: 'str1' }; return QueryBuilder.forClass(RelatedModel) .patchOperationFactory(builder => { return relation.patch(builder, RelationOwner.create(owner)); }) .patch(patch) .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored') .then(numUpdated => { expect(numUpdated).to.equal(42); expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.eql( `update "RelatedModel" set "a" = 'str1' where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666) and "gender" = 'male' and "thingy" is not null)` ); }); }); it('should work with increment', () => { let owner = OwnerModel.fromJson({ oid: 666 }); return QueryBuilder.forClass(RelatedModel) .patchOperationFactory(builder => { return relation.patch(builder, RelationOwner.create(owner)); }) .increment('test', 1) .then(() => { expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.eql( `update "RelatedModel" set "test" = "test" + 1 where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666))` ); }); }); it('should work with decrement', () => { let owner = OwnerModel.fromJson({ oid: 666 }); return QueryBuilder.forClass(RelatedModel) .patchOperationFactory(builder => { return relation.patch(builder, RelationOwner.create(owner)); }) .decrement('test', 10) .then(() => { expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.eql( `update "RelatedModel" set "test" = "test" - 10 where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666))` ); }); }); it('should apply the modifier', () => { createModifiedRelation({ someColumn: 100 }); let owner = OwnerModel.fromJson({ oid: 666 }); let patch = RelatedModel.fromJson({ a: 'str1' }); return QueryBuilder.forClass(RelatedModel) .patchOperationFactory(builder => { return relation.patch(builder, RelationOwner.create(owner)); }) .patch(patch) .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored') .then(() => { expect(executedQueries).to.have.length(1); expect(executedQueries[0]).to.eql( `update "RelatedModel" set "a" = 'str1' where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666) and "someColumn" = 100 and "gender" = 'male' and "thingy" is not null)` ); }); }); }); describe('delete', () => { it('should generate a delete query', () => { let owner = OwnerModel.fromJson({ oid: 666 }); let builder = QueryBuilder.forClass(RelatedModel) .deleteOperationFactory(builder => { return relation.delete(builder, RelationOwner.create(owner)); }) .delete() .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored'); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql({}); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( `delete from "RelatedModel" where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666) and "gender" = 'male' and "thingy" is not null)` ); }); }); it('should generate a delete query (composite key)', () => { let owner = OwnerModel.fromJson({ aid: 11, bid: 22 }); let builder = QueryBuilder.forClass(RelatedModel) .deleteOperationFactory(builder => { return compositeKeyRelation.delete(builder, RelationOwner.create(owner)); }) .delete() .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored'); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql({}); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( `delete from "RelatedModel" where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."cid" = "JoinModel"."relatedCId" and "RelatedModel"."did" = "JoinModel"."relatedDId" where ("JoinModel"."ownerAId", "JoinModel"."ownerBId") in ((11, 22)) and "gender" = 'male' and "thingy" is not null)` ); }); }); it('should apply the modifier', () => { createModifiedRelation({ someColumn: 100 }); let owner = OwnerModel.fromJson({ oid: 666 }); return QueryBuilder.forClass(RelatedModel) .deleteOperationFactory(builder => { return relation.delete(builder, RelationOwner.create(owner)); }) .delete() .where('gender', 'male') .whereNotNull('thingy') .select('shouldBeIgnored') .then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql({}); expect(executedQueries[0]).to.eql( `delete from "RelatedModel" where "RelatedModel"."id" in (select "RelatedModel"."id" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666) and "someColumn" = 100 and "gender" = 'male' and "thingy" is not null)` ); }); }); }); describe('relate', () => { it('should generate a relate query', () => { mockKnexQueryResults = [[5]]; let owner = OwnerModel.fromJson({ oid: 666 }); let builder = QueryBuilder.forClass(RelatedModel) .relateOperationFactory(builder => { return relation.relate(builder, RelationOwner.create(owner)); }) .relate(10); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( [ 'insert into "JoinModel" ("ownerId", "relatedId") values (666, 10) returning "relatedId"' ].join(' ') ); }); }); it('should generate a relate query (array value)', () => { mockKnexQueryResults = [[5, 6, 7]]; let owner = OwnerModel.fromJson({ oid: 666 }); let builder = QueryBuilder.forClass(RelatedModel) .relateOperationFactory(builder => { return relation.relate(builder, RelationOwner.create(owner)); }) .relate([10, 20, 30]); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql(3); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( [ 'insert into "JoinModel" ("ownerId", "relatedId") values (666, 10), (666, 20), (666, 30) returning "relatedId"' ].join(' ') ); }); }); it('should generate a relate query (object value)', () => { mockKnexQueryResults = [[5, 6, 7]]; let owner = OwnerModel.fromJson({ oid: 666 }); let builder = QueryBuilder.forClass(RelatedModel) .relateOperationFactory(builder => { return relation.relate(builder, RelationOwner.create(owner)); }) .relate([{ rid: 10 }, { rid: 20 }, { rid: 30 }]); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql(3); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( [ 'insert into "JoinModel" ("ownerId", "relatedId") values (666, 10), (666, 20), (666, 30) returning "relatedId"' ].join(' ') ); }); }); it('should generate a relate query (composite key)', () => { mockKnexQueryResults = [ [ { relatedCId: 33, relatedDId: 44 }, { relatedCId: 33, relatedDId: 55 }, { relatedCId: 66, relatedDId: 77 } ] ]; let owner = OwnerModel.fromJson({ aid: 11, bid: 22 }); let builder = QueryBuilder.forClass(RelatedModel) .relateOperationFactory(builder => { return compositeKeyRelation.relate(builder, RelationOwner.create(owner)); }) .relate([ [33, 44], [33, 55], [66, 77] ]); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql(3); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( [ 'insert into "JoinModel" ("ownerAId", "ownerBId", "relatedCId", "relatedDId") values (11, 22, 33, 44), (11, 22, 33, 55), (11, 22, 66, 77) returning "relatedCId", "relatedDId"' ].join(' ') ); }); }); it('should generate a relate query (composite key with object value)', () => { mockKnexQueryResults = [ [ { relatedCId: 33, relatedDId: 44 }, { relatedCId: 33, relatedDId: 55 }, { relatedCId: 66, relatedDId: 77 } ] ]; let owner = OwnerModel.fromJson({ aid: 11, bid: 22 }); let builder = QueryBuilder.forClass(RelatedModel) .relateOperationFactory(builder => { return compositeKeyRelation.relate(builder, RelationOwner.create(owner)); }) .relate([ { cid: 33, did: 44 }, { cid: 33, did: 55 }, { cid: 66, did: 77 } ]); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.equal(3); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( [ 'insert into "JoinModel" ("ownerAId", "ownerBId", "relatedCId", "relatedDId") values (11, 22, 33, 44), (11, 22, 33, 55), (11, 22, 66, 77) returning "relatedCId", "relatedDId"' ].join(' ') ); }); }); it('should accept one id', () => { mockKnexQueryResults = [[5]]; let owner = OwnerModel.fromJson({ oid: 666 }); return QueryBuilder.forClass(RelatedModel) .relateOperationFactory(builder => { return relation.relate(builder, RelationOwner.create(owner)); }) .relate(11) .then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql(1); expect(executedQueries[0]).to.eql( 'insert into "JoinModel" ("ownerId", "relatedId") values (666, 11) returning "relatedId"' ); }); }); it('should also insert extra properties', () => { mockKnexQueryResults = [[5]]; let owner = OwnerModel.fromJson({ oid: 666 }); let builder = QueryBuilder.forClass(RelatedModel) .relateOperationFactory(builder => { return relation.relate(builder, RelationOwner.create(owner)); }) .relate({ rid: 10, extra2: 'foo', shouldNotBeInQuery: 'bar' }); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql(1); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( [ 'insert into "JoinModel" ("extra2", "ownerId", "relatedId") values (\'foo\', 666, 10) returning "relatedId"' ].join(' ') ); }); }); }); describe('unrelate', () => { it('should generate a unrelate query', () => { mockKnexQueryResults = [123]; createModifiedRelation({ someColumn: 100 }); let owner = OwnerModel.fromJson({ oid: 666 }); let builder = QueryBuilder.forClass(RelatedModel) .unrelateOperationFactory(builder => { return relation.unrelate(builder, RelationOwner.create(owner)); }) .unrelate() .whereIn('code', [55, 66, 77]); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql(123); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( `delete from "JoinModel" where "JoinModel"."relatedId" in (select "RelatedModel"."rid" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."rid" = "JoinModel"."relatedId" where "JoinModel"."ownerId" in (666) and "someColumn" = 100 and "code" in (55, 66, 77)) and "JoinModel"."ownerId" in (666)` ); }); }); it('should generate a unrelate query (composite key)', () => { let owner = OwnerModel.fromJson({ aid: 11, bid: 22 }); let builder = QueryBuilder.forClass(RelatedModel) .unrelateOperationFactory(builder => { return compositeKeyRelation.unrelate(builder, RelationOwner.create(owner)); }) .unrelate() .whereIn('code', [55, 66, 77]) .where('someColumn', 100); return builder.then(result => { expect(executedQueries).to.have.length(1); expect(result).to.eql({}); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.equal(builder.toKnexQuery().toString()); expect(executedQueries[0]).to.eql( `delete from "JoinModel" where ("JoinModel"."relatedCId","JoinModel"."relatedDId") in (select "RelatedModel"."cid", "RelatedModel"."did" from "RelatedModel" inner join "JoinModel" on "RelatedModel"."cid" = "JoinModel"."relatedCId" and "RelatedModel"."did" = "JoinModel"."relatedDId" where ("JoinModel"."ownerAId", "JoinModel"."ownerBId") in ((11, 22)) and "code" in (55, 66, 77) and "someColumn" = 100) and ("JoinModel"."ownerAId", "JoinModel"."ownerBId") in ((11, 22))` ); }); }); }); function createModifiedRelation(modify) { relation = new ManyToManyRelation('nameOfOurRelation', OwnerModel); relation.setMapping({ modelClass: RelatedModel, relation: ManyToManyRelation, modify: modify, join: { from: 'OwnerModel.oid', through: { from: 'JoinModel.ownerId', to: 'JoinModel.relatedId' }, to: 'RelatedModel.rid' } }); } }); function isSubclassOf(Constructor, SuperConstructor) { if (!isFunction(SuperConstructor)) { return false; } while (isFunction(Constructor)) { if (Constructor === SuperConstructor) { return true; } Constructor = Object.getPrototypeOf(Constructor); } return false; }
const validatePhoneNumberOptional = require("./validatePhoneNumberOptional"); describe("Function: validate secondary contact", () => { it("Should return false when type is not string", () => { // Arrange const badNumber = [[], {}, null, undefined]; // Act badNumber.forEach(number => { // Assert const valid = validatePhoneNumberOptional(number); expect(valid).toBe(false); }); }); it("Should remove the plus from the beginning of a number", () => { //Arrange const goodNumber = "+54875875"; //Act const valid = validatePhoneNumberOptional(goodNumber); //Assert expect(valid).toBe(true); }); it("Should return true when the input is non-empty and numeric", () => { //Arrange const goodNumber = ["447462458575", "2874827482", "110248940242920"]; //Act goodNumber.forEach(number => { //Assert const valid = validatePhoneNumberOptional(number); expect(valid).toBe(true); }); }); it("Should return true when input is empty", () => { // Arrange const phoneNumber = ""; // Act const valid = validatePhoneNumberOptional(phoneNumber); //Assert expect(valid).toBe(true); }); it("Should return false if string contains non numeric characters", () => { //Arrange const badNumbers = ["djdheiu7373", "wuyewixx@$", ".+()-9w"]; //Act badNumbers.forEach(number => { //Assert const valid = validatePhoneNumberOptional(number); expect(valid).toBe(false); }); }); });
var nconf = require('nconf'), path = require('path'), amqp = require('amqp'), exchange, exchangeOptions, connection; nconf.argv().env(); nconf.file({ file: path.join(__dirname, '..', 'config.json') }); exchange = nconf.get("rabbit:exchange:name"); exchangeOptions = nconf.get("rabbit:exchange:options"); logLevel = nconf.get("website:logLevel"); connection = amqp.createConnection(nconf.get("rabbit:connection")); if (logLevel >= 4) { console.log("lib/queueRequester.js | Connecting to RabbitMQ"); } var connectedExchange; var exchangeIsOpen = function(ex) { if (logLevel >= 4) { console.log("lib/queueRequester.js | " + ex.name + ' Exchange is open.'); } connectedExchange = ex; }; connection.once('ready', function() { connection.exchange(exchange, exchangeOptions, exchangeIsOpen); }); connection.once("error", function(err) { if (logLevel >= 2) { console.log("lib/queueRequester.js | An error occurred while trying to connect to RabbitMQ!"); console.log(connection); console.log(err); } }); connection.once("end", function() { if (logLevel >= 4) { console.log("lib/queueRequester.js | Connection to RabbitMQ has ended."); } }); module.exports = { "processCollections": function(username, callback) { var $this = this; if (!connectedExchange) { if (logLevel >= 2) { console.log("lib/queueRequester.js | Delaying message - RabbitMQ not connected yet."); } setTimeout(function() { $this.processCollections(username, callback); }, 1000); } else { connectedExchange.publish("processCollections", { username: username }, { contentType: "application/json" }, function(e) { callback(e); }); } }, "destroy": connection.destroy };
import React, { Component } from "react"; import { Link } from "react-router-dom"; import PropTypes from "prop-types"; import Container from "../../components/Container"; import api from "../../services/api"; import { Loading, Owner, IssueList } from "./styles"; export default class Repository extends Component { state = { repository: {}, issues: [], loading: true }; async componentDidMount() { const { match } = this.props; const repoName = decodeURIComponent(match.params.repository); // api.github.com/repos/facebook/react const [repository, issues] = await Promise.all([ api.get(`repos/${repoName}`), api.get(`repos/${repoName}/issues`, { params: { state: "open", per_page: 5 } }) ]); this.setState({ repository: repository.data, issues: issues.data, loading: false }); console.log(repository); console.log(issues); } render() { const { repository, issues, loading } = this.state; if (loading) { return <Loading>Carregando</Loading>; } return ( <Container> <Owner> <Link to="/">Voltar aos repositórios</Link> <img src={repository.owner.avatar_url} alt={repository.owner.login} /> <h1>{repository.name}</h1> <p>{repository.description}</p> </Owner> <IssueList> {issues.map(issue => ( <li key={String(issue.id)}> <img src={issue.user.avatar_url} alt={issue.user.login} /> <div> <strong> <a href={issue.html_url}>{issue.title} </a> {issue.labels.map(label => ( <span key={String(label.id)}> {label.name} </span> ))} </strong> <p>{issue.user.login}</p> </div> </li> ))} </IssueList> </Container> ); } }
import React from 'react' import p from 'prop-types' import Grid from '@material-ui/core/Grid' import Card from '@material-ui/core/Card' import CardContent from '@material-ui/core/CardContent' import withStyles from '@material-ui/core/styles/withStyles' import gql from 'graphql-tag' import CreateFAB from '../lists/CreateFAB' import FlatList from '../lists/FlatList' import Query from '../util/Query' import OtherActions from '../util/OtherActions' import ServiceLabelSetDialog from './ServiceLabelCreateDialog' import ServiceLabelEditDialog from './ServiceLabelEditDialog' import ServiceLabelDeleteDialog from './ServiceLabelDeleteDialog' const query = gql` query($serviceID: ID!) { service(id: $serviceID) { id # need to tie the result to the correct record labels { key value } } } ` const styles = theme => ({ spacing: { marginBottom: 96 }, }) const sortItems = (a, b) => { if (a.key.toLowerCase() < b.key.toLowerCase()) return -1 if (a.key.toLowerCase() > b.key.toLowerCase()) return 1 if (a.key < b.key) return -1 if (a.key > b.key) return 1 return 0 } @withStyles(styles) export default class ServiceLabelList extends React.PureComponent { static propTypes = { serviceID: p.string.isRequired, } state = { create: false, editKey: null, deleteKey: null, } renderQuery() { return ( <Query query={query} variables={{ serviceID: this.props.serviceID }} render={({ data }) => this.renderList(data.service.labels)} /> ) } renderList(labels) { const items = (labels || []) .slice() .sort(sortItems) .map(label => ({ title: label.key, subText: label.value, secondaryAction: ( <OtherActions actions={[ { label: 'Edit', onClick: () => this.setState({ editKey: label.key }), }, { label: 'Delete', onClick: () => this.setState({ deleteKey: label.key }), }, ]} /> ), })) return ( <FlatList data-cy='label-list' emptyMessage='No labels exist for this service.' items={items} /> ) } render() { return ( <React.Fragment> <Grid item xs={12} className={this.props.classes.spacing}> <Card> <CardContent>{this.renderQuery()}</CardContent> </Card> </Grid> <CreateFAB onClick={() => this.setState({ create: true })} title='Add Label' /> {this.state.create && ( <ServiceLabelSetDialog serviceID={this.props.serviceID} onClose={() => this.setState({ create: false })} /> )} {this.state.editKey && ( <ServiceLabelEditDialog serviceID={this.props.serviceID} labelKey={this.state.editKey} onClose={() => this.setState({ editKey: null })} /> )} {this.state.deleteKey && ( <ServiceLabelDeleteDialog serviceID={this.props.serviceID} labelKey={this.state.deleteKey} onClose={() => this.setState({ deleteKey: null })} /> )} </React.Fragment> ) } }
// In production, we register a service worker to serve assets from local cache. // This lets the app load faster on subsequent visits in production, and gives // it offline capabilities. However, it also means that developers (and users) // will only see deployed updates on the "N+1" visit to a page, since previously // cached resources are updated in the background. // To learn more about the benefits of this model, read https://goo.gl/KwvDNy. // This link also includes instructions on opting out of this behavior. const isLocalhost = Boolean( window.location.hostname === 'localhost' || // [::1] is the IPv6 localhost address. window.location.hostname === '[::1]' || // 127.0.0.1/8 is considered localhost for IPv4. window.location.hostname.match( /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); export default function register() { if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { // The URL constructor is available in all browsers that support SW. const publicUrl = new URL(process.env.PUBLIC_URL, window.location); if (publicUrl.origin !== window.location.origin) { // Our service worker won't work if PUBLIC_URL is on a different origin // from what our page is served on. This might happen if a CDN is used to // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 return; } window.addEventListener('load', () => { const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; if (!isLocalhost) { // Is not local host. Just register service worker registerValidSW(swUrl); } else { // This is running on localhost. Lets check if a service worker still exists or not. // checkValidServiceWorker(swUrl); } }); } } function registerValidSW(swUrl) { navigator.serviceWorker .register(swUrl) .then(registration => { registration.onupdatefound = () => { const installingWorker = registration.installing; installingWorker.onstatechange = () => { if (installingWorker.state === 'installed') { if (navigator.serviceWorker.controller) { // At this point, the old content will have been purged and // the fresh content will have been added to the cache. // It's the perfect time to display a "New content is // available; please refresh." message in your web app. console.log('New content is available; please refresh.'); } else { // At this point, everything has been precached. // It's the perfect time to display a // "Content is cached for offline use." message. console.log('Content is cached for offline use.'); } } }; }; }) .catch(error => { console.error('Error during service worker registration:', error); }); } function checkValidServiceWorker(swUrl) { // Check if the service worker can be found. If it can't reload the page. fetch(swUrl) .then(response => { // Ensure service worker exists, and that we really are getting a JS file. if ( response.status === 404 || response.headers.get('content-type').indexOf('javascript') === -1 ) { // No service worker found. Probably a different app. Reload the page. navigator.serviceWorker.ready.then(registration => { registration.unregister().then(() => { window.location.reload(); }); }); } else { // Service worker found. Proceed as normal. registerValidSW(swUrl); } }) .catch(() => { console.log( 'No internet connection found. App is running in offline mode.' ); }); } export function unregister() { if ('serviceWorker' in navigator) { navigator.serviceWorker.ready.then(registration => { registration.unregister(); }); } }
import React from "react" import SlideShow from "../carousel/index" import YouTubePlayer from "react-player" import portfolioStyles from "./portfolio.module.scss" const Portfolio = () => { return ( <section id="portfolio" className={portfolioStyles.container}> <SlideShow /> <div className={portfolioStyles.video_container}> <YouTubePlayer className={portfolioStyles.videocontent} url="https://www.youtube.com/embed/MFzCkIsnxVU" playing="true" loop="true" controls volume="0" muted="true" /> </div> </section> ) } export default Portfolio
import React from 'react' const Photos = () => { return ( <div className="containe"> <div className="row"> <div className="photo"> <img src="http://peoplesideconsulting.com/wp-content/uploads/2015/08/techology-people.jpg" style={{width:"100%"}}/> </div> <div className="photo"> <img src ="https://www.trainingzone.co.uk/sites/default/files/styles/inline_banner/public/istock-857834298.jpg?itok=zjZiF343" style={{width:"100%"}}/> </div> </div> </div> ) } export default Photos
window.peopleAlsoBoughtJSON = [{"asin":"B00CHQSR14","authors":"Clive Barker","cover":"51kLWw-gqPL","length":"6 hrs and 51 mins","narrators":"Simon Vance, Dick Hill, Peter Berkrot, and others","title":"The Books of Blood, Volume 1"},{"asin":"B00UHEOI16","authors":"Clive Barker","cover":"51i3sCQL7iL","length":"37 hrs and 20 mins","narrators":"Simon Vance","title":"Imajica"},{"asin":"B0191VQDH2","authors":"Brian Lumley","cover":"51f+jE7Q5PL","length":"17 hrs and 24 mins","narrators":"James Langton","title":"Necroscope"},{"asin":"B002VAEJ8G","authors":"Stephen King","cover":"614G19KjRKL","length":"9 hrs and 34 mins","narrators":"Stephen King, Tim Curry, Rob Lowe, and others","title":"Nightmares & Dreamscapes, Volume I"},{"asin":"1684576849","authors":"Otto Penzler","cover":"51iwWbgTGlL","length":"53 hrs and 43 mins","narrators":"Amy Landon, Joel Richards","subHeading":"Big Book Series","title":"The Big Book of Ghost Stories"},{"asin":"B098TWVZVD","authors":"Neil Gaiman, Dirk Maggs","cover":"51bJGmUXS9L","length":"13 hrs and 47 mins","narrators":"Neil Gaiman, James McAvoy, Emma Corrin, and others","title":"The Sandman: Act II"},{"asin":"B07Q511RPN","authors":"Ian Gordon, Algernon Blackwood, Robert Bloch, and others","cover":"51rMAmfFAbL","length":"25 hrs and 5 mins","narrators":"Ian Gordon","title":"HorrorBabble's Ultimate Weird Tales Collection, Volume 1"},{"asin":"B002UZKVI4","authors":"Stephen King, Peter Straub","cover":"51zfgkZF+BL","length":"28 hrs","narrators":"Frank Muller","title":"The Talisman"},{"asin":"1684576822","authors":"Otto Penzler","cover":"614nIshZkUL","length":"73 hrs and 18 mins","narrators":"Daniel Thomas May, Traci Odom, Eric Jason Martin","subHeading":"The Best Crime Stories from the Pulps During Their Golden Age - The '20s, '30s & '40s (Big Book Series)","title":"The Black Lizard Big Book of Pulps"},{"asin":"B01H63H54M","authors":"Stephen King","cover":"516BP4dhP4L","length":"22 hrs and 29 mins","narrators":"Stephen King, Matthew Broderick, Michael C. Hall, and others","title":"Skeleton Crew"},{"asin":"B013GOW2AW","authors":"Clive Barker","cover":"516lU6uFtwL","length":"22 hrs and 24 mins","narrators":"Chet Williamson","title":"Great & Secret Show"},{"asin":"B00GNDBETE","authors":"Clive Barker","cover":"51AnZqORf5L","length":"21 hrs and 20 mins","narrators":"Frank Muller","subHeading":"A Hollywood Ghost Story","title":"Coldheart Canyon"},{"asin":"B003V6DMPA","authors":"Montague Rhodes James","cover":"51VbXGm5XfL","length":"23 mins","narrators":"David Collings","title":"Wailing Well"},{"asin":"B01JSE4M5C","authors":"P. G. Wodehouse","cover":"61ukf1TJi1L","length":"36 mins","narrators":"B. J. Harrison","title":"The Man Upstairs [Classic Tales Edition]"},{"asin":"B09GS6VZB7","authors":"William Ingram, Richard Davies, Maurice Travers, and others","cover":"51O7bTOmMkL","length":"9 hrs and 31 mins","narrators":"Vincent Price, Maurice Denham, Annette Crosbie, and others","subHeading":"A BBC Radio 4 Vintage Horror Series","title":"The Price of Fear: 20 Tales of Suspense Told by Vincent Price"},{"asin":"0525640479","authors":"Dacre Stoker, J.D. Barker","cover":"41oowPdyY7L","length":"16 hrs and 25 mins","narrators":"Pete Bradbury, Vikas Adam, Saskia Maarleveld, and others","title":"Dracul"},{"asin":"B003E2VIRA","authors":"Robert E. Howard","cover":"61RWu4CWR7L","length":"23 hrs and 39 mins","narrators":"Robertson Dean","title":"The Horror Stories of Robert E. Howard"},{"asin":"B015WVQUBO","authors":"Anne Rice","cover":"51XlsMKH5hL","length":"50 hrs and 1 min","narrators":"Kate Reading","title":"The Witching Hour"}]; window.bookSummaryJSON = "<p><i>The Vampire Archives</i> is the biggest, hungriest, undeadliest collection of vampire stories, as well as the most comprehensive bibliography of vampire fiction ever assembled. Dark, stormy, and delicious, once it sinks its teeth into you there’s no escape.&nbsp;</p> <p>Vampires! Whether imagined by Bram Stoker or Anne Rice, they are part of the human lexicon and as old as blood itself. They are your neighbors, your friends, and they are always lurking. Now Otto Penzler—editor of the best-selling <i>Black Lizard Big Book of Pulps</i>—has compiled the darkest, the scariest, and by far the most evil collection of vampire stories ever, with over 80 stories, including the works of Stephen King and D. H. Lawrence, alongside Lord Byron and Tanith Lee, not to mention Edgar Allan Poe and Harlan Ellison. <i>The Vampire Archives</i> will drive a stake through the heart of any other collection out there.&nbsp;</p> <p>Other contributors include Arthur Conan Doyle, Ray Bradbury, Ambrose Bierce, H. P. Lovecraft, Harlan Ellison, Roger Zelazny, Robert Bloch, and Clive Barker.</p>";
// methods import curry from './curry'; import filter from './filter'; import reduce from './reduce'; // utils import isArray from './_utils/isArray'; import isObject from './_utils/isObject'; /** * @function pickArray * * @description * pick the values from the given array based on the existence of the indices * * @param {Array<number>} indices the indices to match * @param {Array<*>} array the array to pick from * @returns {Array<*>} the array with the picked values */ function pickArray(indices, array) { return filter((ignored, index) => ~indices.indexOf(index), array); } /** * @function pickObject * * @description * pick the values from the given object based on the existence of the keys * * @param {Array<number>} keys the keys to match * @param {Array<*>} object the object to pick from * @returns {Array<*>} the object with the picked values */ function pickObject(keys, object) { return reduce( (newObject, key) => { if (object.hasOwnProperty(key)) { newObject[key] = object[key]; } return newObject; }, {}, keys ); } /** * @function pick * * @description * pick specific keys from the object passed * * @param {Array<number|string>} keys the keys to pick from the object * @param {Array<*>|Object} collection the object to pick the keys from * @returns {Array<*>|Object} the object with specific keys picked */ export default curry(function pick(keys, collection) { return isArray(collection) ? pickArray(keys, collection) : isObject(collection) ? pickObject(keys, collection) : {}; });
/*! For license information please see a9a7754c-8b6772b9d0a10ec64145.js.LICENSE.txt */ (self.webpackChunkgatsby_starter_ghost=self.webpackChunkgatsby_starter_ghost||[]).push([[112],{4297:function(c,n,e){"use strict";e.d(n,{AYu:function(){return i},hwn:function(){return t},lLR:function(){return f},mdU:function(){return r}});var i={prefix:"fab",iconName:"facebook-f",icon:[320,512,[],"f39e","M279.14 288l14.22-92.66h-88.91v-60.13c0-25.35 12.42-50.06 52.24-50.06h40.42V6.26S260.43 0 225.36 0c-73.22 0-121.08 44.38-121.08 124.72v70.62H22.89V288h81.39v224h100.17V288z"]},t={prefix:"fab",iconName:"linkedin-in",icon:[448,512,[],"f0e1","M100.28 448H7.4V148.9h92.88zM53.79 108.1C24.09 108.1 0 83.5 0 53.8a53.79 53.79 0 0 1 107.58 0c0 29.7-24.1 54.3-53.79 54.3zM447.9 448h-92.68V302.4c0-34.7-.7-79.2-48.29-79.2-48.29 0-55.69 37.7-55.69 76.7V448h-92.78V148.9h89.08v40.8h1.3c12.4-23.5 42.69-48.3 87.88-48.3 94 0 111.28 61.9 111.28 142.3V448z"]},f={prefix:"fab",iconName:"quora",icon:[448,512,[],"f2c4","M440.5 386.7h-29.3c-1.5 13.5-10.5 30.8-33 30.8-20.5 0-35.3-14.2-49.5-35.8 44.2-34.2 74.7-87.5 74.7-153C403.5 111.2 306.8 32 205 32 105.3 32 7.3 111.7 7.3 228.7c0 134.1 131.3 221.6 249 189C276 451.3 302 480 351.5 480c81.8 0 90.8-75.3 89-93.3zM297 329.2C277.5 300 253.3 277 205.5 277c-30.5 0-54.3 10-69 22.8l12.2 24.3c6.2-3 13-4 19.8-4 35.5 0 53.7 30.8 69.2 61.3-10 3-20.7 4.2-32.7 4.2-75 0-107.5-53-107.5-156.7C97.5 124.5 130 71 205 71c76.2 0 108.7 53.5 108.7 157.7.1 41.8-5.4 75.6-16.7 100.5z"]},r={prefix:"fab",iconName:"twitter",icon:[512,512,[],"f099","M459.37 151.716c.325 4.548.325 9.097.325 13.645 0 138.72-105.583 298.558-298.558 298.558-59.452 0-114.68-17.219-161.137-47.106 8.447.974 16.568 1.299 25.34 1.299 49.055 0 94.213-16.568 130.274-44.832-46.132-.975-84.792-31.188-98.112-72.772 6.498.974 12.995 1.624 19.818 1.624 9.421 0 18.843-1.3 27.614-3.573-48.081-9.747-84.143-51.98-84.143-102.985v-1.299c13.969 7.797 30.214 12.67 47.431 13.319-28.264-18.843-46.781-51.005-46.781-87.391 0-19.492 5.197-37.36 14.294-52.954 51.655 63.675 129.3 105.258 216.365 109.807-1.624-7.797-2.599-15.918-2.599-24.04 0-57.828 46.782-104.934 104.934-104.934 30.213 0 57.502 12.67 76.67 33.137 23.715-4.548 46.456-13.32 66.599-25.34-7.798 24.366-24.366 44.833-46.132 57.827 21.117-2.273 41.584-8.122 60.426-16.243-14.292 20.791-32.161 39.308-52.628 54.253z"]}}}]); //# sourceMappingURL=a9a7754c-8b6772b9d0a10ec64145.js.map
var $class = function() { var _super, init; if (arguments.length === 1) { init = arguments[0]; } else { _super = arguments[0]; init = arguments[1]; } var skip = false; var clss = function() { if (skip) { return; } this.init.apply(this, arguments); }; if (_super !== undefined) { _super._setSkip(); clss.prototype = new _super(); _super._clrSkip(); clss.prototype.constructor = clss; clss._super = _super.prototype; } clss.prototype.init = init; clss._setSkip = function() { skip = true; }; clss._clrSkip = function() { skip = false; }; return clss; };
import React from 'react'; import { Grid } from '@material-ui/core'; import Widget from '../../components/Widget'; import ApexLineChart from './components/ApexLineChart'; import ApexHeatmap from './components/ApexHeatmap' import { CartesianGrid, Legend, Line, LineChart, Pie, PieChart, ResponsiveContainer, Sector, Tooltip, XAxis, YAxis } from "recharts"; import {withTheme} from "@material-ui/core"; import PageTitle from "../../components/PageTitle"; const lineChartData = [ { name: 'Page A', uv: 4000, pv: 2400, amt: 2400, }, { name: 'Page B', uv: 3000, pv: 1398, amt: 2210, }, { name: 'Page C', uv: 2000, pv: 9800, amt: 2290, }, { name: 'Page D', uv: 2780, pv: 3908, amt: 2000, }, { name: 'Page E', uv: 1890, pv: 4800, amt: 2181, }, { name: 'Page F', uv: 2390, pv: 3800, amt: 2500, }, { name: 'Page G', uv: 3490, pv: 4300, amt: 2100, }, ]; const pieChartData = [ { name: 'Group A', value: 400 }, { name: 'Group B', value: 300 }, { name: 'Group C', value: 300 }, { name: 'Group D', value: 200 }, ]; const renderActiveShape = (props) => { const RADIAN = Math.PI / 180; const { cx, cy, midAngle, innerRadius, outerRadius, startAngle, endAngle, fill, payload, percent, value, } = props; const sin = Math.sin(-RADIAN * midAngle); const cos = Math.cos(-RADIAN * midAngle); const sx = cx + (outerRadius + 10) * cos; const sy = cy + (outerRadius + 10) * sin; const mx = cx + (outerRadius + 30) * cos; const my = cy + (outerRadius + 30) * sin; const ex = mx + (cos >= 0 ? 1 : -1) * 22; const ey = my; const textAnchor = cos >= 0 ? 'start' : 'end'; return ( <g> <text x={cx} y={cy} dy={8} textAnchor="middle" fill={fill}>{payload.name}</text> <Sector cx={cx} cy={cy} innerRadius={innerRadius} outerRadius={outerRadius} startAngle={startAngle} endAngle={endAngle} fill={fill} /> <Sector cx={cx} cy={cy} startAngle={startAngle} endAngle={endAngle} innerRadius={outerRadius + 6} outerRadius={outerRadius + 10} fill={fill} /> <path d={`M${sx},${sy}L${mx},${my}L${ex},${ey}`} stroke={fill} fill="none" /> <circle cx={ex} cy={ey} r={2} fill={fill} stroke="none" /> <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} textAnchor={textAnchor} fill="#333">{`PV ${value}`}</text> <text x={ex + (cos >= 0 ? 1 : -1) * 12} y={ey} dy={18} textAnchor={textAnchor} fill="#999"> {`(Rate ${(percent * 100).toFixed(2)}%)`} </text> </g> ); }; const ChartsView = (props) => ( <React.Fragment> <PageTitle title="Charts Page - Data Display" button="Latest Reports" /> <Grid container spacing={32}> <Grid item xs={12} md={6}> <Widget title="Apex Line Chart" upperTitle noBodyPadding> <ApexLineChart /> </Widget> </Grid> <Grid item xs={12} md={6}> <Widget title="Apex Heatmap" upperTitle noBodyPadding> <ApexHeatmap /> </Widget> </Grid> <Grid item xs={12} md={8}> <Widget title="Simple Line Chart" noBodyPadding upperTitle> <ResponsiveContainer width="100%" height={350}> <LineChart width={500} height={300} data={lineChartData} margin={{ top: 5, right: 30, left: 20, bottom: 5, }} > <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="name" /> <YAxis /> <Tooltip /> <Legend /> <Line type="monotone" dataKey="pv" stroke={props.theme.palette.primary.main} activeDot={{ r: 8 }} /> <Line type="monotone" dataKey="uv" stroke={props.theme.palette.secondary.main} /> </LineChart> </ResponsiveContainer> </Widget> </Grid> <Grid item xs={12} md={4}> <Widget title="Pie Chart with Tooltips" noBodyPadding upperTitle> <ResponsiveContainer width="100%" height={300}> <PieChart width={200} height={300}> <Pie activeIndex={props.activeIndex} activeShape={renderActiveShape} data={pieChartData} cx={200} cy={150} innerRadius={60} outerRadius={80} fill={props.theme.palette.primary.main} dataKey="value" onMouseEnter={props.changeActiveIndexId} /> </PieChart> </ResponsiveContainer> </Widget> </Grid> </Grid> </React.Fragment> ); export default withTheme(ChartsView);
import React from 'react' import PropTypes from 'prop-types' class Title extends React.Component { render() { const {title, subtitle} = this.props return ( <div> <div className='head'> <h3>{title}</h3> <h5>{subtitle}</h5> </div> <style jsx>{` .head { display: flex; justify-content: space-between; align-items: center; } `}</style> </div> ) } } Title.propTypes = { title: PropTypes.string.isRequired, subtitle: PropTypes.string.isRequired } export default Title
define("p3/JobManager", ['dojo/_base/Deferred', 'dojo/topic', 'dojo/request/xhr', 'dojo/promise/all', 'dojo/store/Memory', 'dojo/store/Observable', 'dojo/when' ], function ( Deferred, Topic, xhr, All, MemoryStore, Observable, when ) { var self = this; var TIME_OUT = 5000; // in ms // state model of filters applied to jobs self.filters = { app: 'all', status: null }; // state of status (used to detect changes) var StatusSummary = { init: null }; var _DataStore = new MemoryStore({ idProperty: 'id', data: [] }); /** * updates the job list (see JobsGrid.js) */ function updateJobsList(cb) { Topic.publish('/Jobs', { status: 'loading' }); var prom = window.App.api.service('AppService.enumerate_tasks', [0, 30000]); return prom.then(function (res) { // filter out jobs marked as deleted (includes killed jobs) var jobs = res[0].filter(function (job) { return job.status !== 'deleted'; }); _DataStore.setData(jobs); // perform any callback action before filtering if (cb) cb(); if (self.filters.app || self.filters.status) { Topic.publish('/Jobs', { status: 'filtered', jobs: _DataStore.data }); Topic.publish('/JobFilter', self.filters); return; } Topic.publish('/Jobs', { status: 'updated', jobs: _DataStore.data }); }); } /** * sets status locally, publishes status for jobs ticker, and returns True if any changes */ function getStatus() { var prom = window.App.api.service('AppService.query_task_summary', []); return prom.then(function (res) { var status = res[0]; var queued = (status.queued || 0) + (status.pending || 0) + (status.init || 0); var inProgress = status['in-progress'] || 0; var completed = status.completed || 0; var failed = status.failed || 0; // check for any changes in status var change = false; if (queued !== StatusSummary.queued || inProgress !== StatusSummary.inProgress || completed !== StatusSummary.completed || failed !== StatusSummary.failed) { change = true; } StatusSummary = { queued: queued, inProgress: inProgress, completed: completed, failed: failed }; // publish job status for jobs ticker Topic.publish('/JobStatus', StatusSummary); return change; // bool }); } function PollJobs() { // leaving this here since instantiation order is unpredictable if (!(window.App && window.App.api && window.App.api.service)) { setTimeout(PollJobs, 1000); return; } // check for status change. if change, update jobs list var prom = getStatus(); prom.then(function (statusChange) { if (statusChange) { updateJobsList().then(function () { setTimeout(PollJobs, TIME_OUT); }); return; } setTimeout(PollJobs, TIME_OUT); }); } // kick off the polling setTimeout(PollJobs, 1000); /** * listen for job filtering to store filter state locally */ Topic.subscribe('/JobFilter', function (filter) { Object.assign(self.filters, filter); }); return { queryTaskDetail: function (id, stdout, stderr) { return Deferred.when(window.App.api.service('AppService.query_task_details', [id]), function (detail) { detail = detail[0]; var defs = []; if (detail.stderr_url && stderr) { defs.push(Deferred.when(xhr.get(detail.stderr_url, { headers: { Authorization: 'Oauth ' + window.App.authorizationToken, 'X-Requested-With': false } }), function (txt) { detail.stderr = txt; })); } if (detail.stdout_url && stdout) { defs.push(Deferred.when(xhr.get(detail.stdout_url, { headers: { Authorization: 'Oauth ' + window.App.authorizationToken, 'X-Requested-With': false } }), function (txt) { detail.stdout = txt; })); } if (defs.length < 1) { return detail; } return Deferred.when(All(defs), function () { return detail; }); }); }, getStore: function () { return _DataStore; }, killJob: function (id) { Topic.publish('/Notification', { message: '<span class="default">Terminating job ' + id + '...</span>', type: 'default', duration: 50000 }); window.App.api.service('AppService.kill_task', [id]).then(function (res) { updateJobsList(function () { Topic.publish('/Notification', { message: 'Job terminated.', type: 'message' }); }); }); } }; });
const inpt = document.getElementById("input"); const btn = document.getElementById("button"); const output = document.getElementById("count"); function countUp(n) { if (n < 1) { return []; } else { const arr = countUp(n - 1); arr.push(n); return arr; } } btn.addEventListener('click', function() { output.innerHTML = countUp(inpt.value); })
'use strict'; const express = require('express'); const app = express(); const router = express.Router(); const moment = require('moment'); const padEnd = require('pad-end'); const path = require('path'); const config = require('./config'); const curPath = __dirname + '/'; const mongoose = require('mongoose'); const passport = require('passport'); require('./config/passport')(passport); const morgan = require('morgan'); const cookieParser = require('cookie-parser'); const session = require('express-session'); const flash = require('connect-flash'); const configDB = require('./config/database.js'); const bodyParser = require('body-parser'); app.disable('etag'); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.set('trust proxy', true); // mongoose.connect(config.get('MONGO_URL')); mongoose.connect(configDB.url); // app.use(morgan('dev')); app.use(cookieParser()); app.use(bodyParser()); app.use(session({ secret: 'abrakadabra' })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); router.use(function (req, res, next) { console.log( padEnd((req.method + " " + req.path), 60, ' ') + moment().format('H:mm:ss')); next(); }); app.use('/books', require('./books/crud')); app.use('/records', require('./records/crud')); app.use('/chat', require('./chat/crud')); function getBooks () { return require(`./books/model-${require('./config').get('DATA_BACKEND')}`); } function getMessages () { return require(`./chat/model-${require('./config').get('DATA_BACKEND')}`); } const recordPerPage = 5; router.get('/', (req, res) => { let user; if (isLoggedIn) { user = req.user } else { user = '' } getMessages().list(recordPerPage, req.query.page * recordPerPage || 0, (err, entities, cursor) => { if (err) { next(err); return; } const page = req.query.page; res.render('index.pug', { user: user, messages: entities, nextPageToken: cursor / recordPerPage, prevPageToken: page !== '0', page: page, activeLink: 'books' }); }); }); router.get('/login', (req, res) => { res.render('login.pug', { message: req.flash('loginMessage') }); }); router.post('/login', passport.authenticate('local-login', { successRedirect: '/profile', failureRedirect: '/login', failureFlash: true })); router.get('/signup', (req, res) => { res.render('signup.pug', { message: req.flash('signupMessage') }); }); router.post('/signup', passport.authenticate('local-signup', { successRedirect: '/profile', failureRedirect: '/signup', failureFlash: true })); router.get('/profile', isLoggedIn, function(req, res) { res.render('profile.pug', { user: req.user }) }); router.get('/logout', function(req, res) { req.logout(); res.redirect('/'); }); router.get("/about", function(req, res) { res.sendFile(curPath + "about.html"); }); router.get("/products", function(req, res) { res.sendFile(curPath + "products.html"); }); router.get("/store", function(req, res) { res.sendFile(curPath + "store.html"); }); router.get("/test", function(req, res) { res.render("test.pug", { }) }); router.get("/test2", function(req, res) { res.render("test2.pug", { }) }); app.use("/", router); app.use(express.static('public')); // app.use(function(req, res, next) { // const err = new Error('Oops!'); // err.status = 404; // next(err); // }); // app.use(function(err, req, res, next) { // res.locals.message = err.message; // res.locals.error = req.app.get('env') === 'development' ? err : {}; // // res.status(err.status || 500); // res.render('error'); // }); function isLoggedIn(req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/'); } const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`App listening on port ${PORT}`); }); module.exports = app;
import { connect } from 'react-redux'; import { getWidgetFooterProps } from './selectors'; import Component from './component'; export default connect(getWidgetFooterProps)(Component);
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([[1],{YjbW:function(e,E,t){"use strict";t.d(E,"a",function(){return o}),t.d(E,"b",function(){return C});var n=t("o0o1"),r=t.n(n),I=t("yXPU"),a=t.n(I),i=t("vDqi"),c=t.n(i),o={INSPIRE_ME:"INSPIRE_ME",INSPIRE_ME_SUCCESS:"INSPIRE_ME_SUCCESS",INSPIRE_ME_FAILURE:"INSPIRE_ME_FAILURE"};function C(e){var E=[...e.education.map(e=>e.name).join(" ").split(" "),...e.jobs.map(e=>e.role).join(" ").split(" "),...e.person.professionalHeadline.split(" "),...e.strengths.map(e=>e.name).join(" ").split(" ")];return E=E.filter((e,t)=>{return e.length>4&&E.indexOf(e)===t}),function(){var e=a()(r.a.mark(function e(t){var n;return r.a.wrap(function(e){while(1)switch(e.prev=e.next){case 0:return t({type:o.INSPIRE_ME,payload:E}),e.prev=1,e.next=4,c.a.get(`http://ec2-54-209-252-217.compute-1.amazonaws.com:8091/v1/inspire-me?subjects=${E.join(",")}`);case 4:n=e.sent,t({type:o.INSPIRE_ME_SUCCESS,payload:n.data.result}),e.next=11;break;case 8:e.prev=8,e.t0=e["catch"](1),t({type:o.INSPIRE_ME_FAILURE,payload:e.t0});case 11:case"end":return e.stop()}},e,this,[[1,8]])}));return function(E){return e.apply(this,arguments)}}()}},pPYQ:function(e,E,t){"use strict";t.d(E,"a",function(){return o}),t.d(E,"b",function(){return C});var n=t("o0o1"),r=t.n(n),I=t("yXPU"),a=t.n(I),i=t("vDqi"),c=t.n(i),o={TORRE_PEOPLE:"TORRE_PEOPLE",TORRE_PEOPLE_SUCCESS:"TORRE_PEOPLE_SUCCESS",TORRE_PEOPLE_FAILURE:"TORRE_PEOPLE_FAILURE"};function C(e){return function(){var E=a()(r.a.mark(function E(t){var n;return r.a.wrap(function(E){while(1)switch(E.prev=E.next){case 0:return t({type:o.TORRE_PEOPLE}),E.prev=1,E.next=4,c.a.get(`http://ec2-54-209-252-217.compute-1.amazonaws.com:8090/v1/people?q=${e}`);case 4:n=E.sent,t({type:o.TORRE_PEOPLE_SUCCESS,payload:n.data.result}),E.next=11;break;case 8:E.prev=8,E.t0=E["catch"](1),t({type:o.TORRE_PEOPLE_FAILURE,payload:E.t0});case 11:case"end":return E.stop()}},E,this,[[1,8]])}));return function(e){return E.apply(this,arguments)}}()}},tCqT:function(e,E,t){"use strict";t.r(E);t("B9cy");var n=t("Ol7k"),r=t("q1tI"),I=t.n(r),a=t("/MKj"),i=t("ANjH"),c=t("sINF"),o=t("9Gtd"),C=t("MVZn"),p=t.n(C),Q=t("YjbW"),g=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},E=arguments.length>1?arguments[1]:void 0;switch(E.type){case Q["a"].INSPIRE_ME:return p()({},e,{loading:!0,inspireMeSubjects:E.payload});case Q["a"].INSPIRE_ME_SUCCESS:return p()({},e,{loading:!1,error:!1,inspireMeRes:E.payload});case Q["a"].INSPIRE_ME_FAILURE:return p()({},e,{loading:!1,error:E.payload,inspireMeRes:[]});default:return e}},u=t("pPYQ"),R=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},E=arguments.length>1?arguments[1]:void 0;switch(E.type){case u["a"].TORRE_PEOPLE:return p()({},e,{loading:!0});case u["a"].TORRE_PEOPLE_SUCCESS:return p()({},e,{loading:!1,error:!1,torrePeople:E.payload});case u["a"].TORRE_PEOPLE_FAILURE:return p()({},e,{loading:!1,error:E.payload,torrePeople:void 0});default:return e}},y=Object(i["c"])({form:o["a"],inspirerReducer:g,torreReducer:R}),d=Object(i["d"])(y,Object(i["a"])(c["a"]));E["default"]=class extends I.a.Component{render(){return I.a.createElement(a["a"],{store:d},I.a.createElement(n["a"],null,I.a.createElement(n["a"].Header,null,I.a.createElement("p",{align:"center"},I.a.createElement("img",{height:64,src:t("zwU1")}))),I.a.createElement(n["a"].Content,null,this.props.children)))}}},zwU1:function(e,E){e.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAABgjSURBVHhe7Z1bcBTVusd985FHH3nkkUeeTuWROnWUiFyiouSgQBTRUS5GcesoYHArlV11yhNAYMI1yG0CCOE+2QJGtrsq5+WcEQJOBJIhkDBJCAyErfT5f92rh+npy1x7MiT/X9WqmVlr9eqe7v73+tbt62cIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQggh5Olm6ZH+Ke8dHgi/e6hfQ+hc2nqrViURMrEJtA5Oeu/QQBwCEXHoYWlrv7bk4K3pKgshE5dA60CtiCNTIO+Eb4dVFkImLoHW2wEngSwJ346oLIRMXPT2x6GBpK0Gab2tvXWwL6CyETJxgUCiTgJBLSIhLO0UlZWQ8hJsf1CFUCefn0W0Z1V02Qi09lenTKzDAw1Ljt56LtB6czLaIJ1KINrb4VvRxQd6p6hNCPGfNeceTF/942j8i78/1CR83v5A+zzyIAGhlLWLFcII6wI5NBCfH+lOCXR+c/ezS8L9LUog2lsH+hJvH+irVsmE+Mfa9vvT1pwb1SAQXRwpgSBAIFrwTLJGZfWVQOutqQGz9kBjXUVbkHaILpCDRqjbfzOokgjxh9XnRju8BPLZ2WSiHObW+4fvhHWBoJEuppWKtlHXerNKahBdIAf6tEUH+trmt3azXUJKj9z4Ig7PGiSSxOe9qWoTX1h2pH/K+0fuaLpAjtxpVNGuQCSTUZt0ikAWi0j2x2ML9/X4eoxkArKu/cHkXATylzP3fG2LQByNukCy1B7pSLsEAmkRgSzefxMiuZlctK+nLOYgmUCsOfcwkU0gn569H/v0zP06P0ytFRAEzKukqkFaVHTOLN7XF1AC0cOb++NZa6By8kJTdNqMTZcbZ2y8HHlhw6/Bf//2f3N6AJAKYc25R6FsAvnMEAlqkvuJT07fD8LkKtlFXnY0odceukDQUFfReYHGetWifTcTIpCF++ISItIueeP73uoF3/eGFuzpbVuw50YQtU5Z2yrVGy7XVm+8rEmAQLQZGy5pz2+4lBDRqCyk0gm2a5MgkKiTQCCMWPDM/cCnZ5NREYgSifbJ6ZHkJ2fvhz4+cbeo8YjPIt3Pvn8kodce0khX0QVRt+fmZAikUwlEe3NvrwaB6AECQejR/nN3T7x2V3naKnNQU7y48XIyUyAvIPxHUzSqspGnATGdVp8bbfji7w+iukAiyejnkQeNwfYno9YQRjUEEhGBoE2ifSLh9D1t1amRto9ODBU02xYmVeCDHxJ67fHB4YGin6rSLlm4P97iKpCWHm1+y42o5FOb+Eb1pkvVL27q0sWRKZDnm37Vqjf8OlllJeOJVSfvTYVQQimBnB7RPj41on10aiRaf3y4Ntd2iqo94kognSq6JCzc2xt3E0ithJ03fDdxZm66XOMlkOf/6xJnA4xnpB2y6tT9BogjIQLRRXLyLsJwvP7kcHDFUe92ygc/GLWHhMCR/pKOinvVILpAdl3zfYZA9cZLAQ+BxFU2Mt6RGuOjU3frIJCYIZC7Wj3CyuNDyQ9P3A3VHx90NCU+OJqI6gIpce0hLNzXG/OuQa75OjN45ndXGkQcrgL57//jNJmJyIcnh2ogkA4RyIcnhvUAoWgrjg+Flx8bqlvZlggtP5qILTs6qC07atQeMK/q1OYlQ7p6PQWy+4Y2f9eNcO2e7pK2A6Rt89LmKy0QiC4OhLjUJAgtL2y8HJux4dc29mCRZz5sG5628sRwiykQXSRtEga15cdEHOkCSdSrzUqG6uLtdBBIcv7unpguEITXd11Pvr7zmnT/Ft1or27ungRxdCBoukA2dnWyIU48EfNqZdtQxEsgfrRBBLnp39jTUwuBJHWBtPREavfcqJJ4CCT4+u4byfm7rotItNd2Xou/tqO74FH4Od9dnjpry5WYiMMQyNVwOXrKyDggF4HAzPJtSe0b3/fERCC1EIuK0qlt7n5u/q5rYREIahERifbqjmuRV5u78xonmb35yvRZm68kIBBdHAgVNZJPKhhpwEMYyawCOXwnKd2+arOS4iYQk3k7b1RBHFERyDwJO37XXtnxexNqgKyj7rO2dNXN3npVm7VFAsyq77pK3p4i45hA++CkbG0QVYPIPCxfepayCcRk3vbu+ld3XkuIQF4VkWz/PfFyc7frMc0J/dYo4tAFghpkJmoSlURI7kAc8VwEIiGXqe75kqtABDG75m3/PSQCeXW7LhLt5W2xaE1zd5XKojfGIY4wgi6O2VuuxqQNopIJyY+Vx4cbsgtkIKFqEVlRGE5fblss+QjEZF5z9zSIo0ME8sq2boikW6vZFguLUOaGfutE0EQgs7Ze7ZwDUanNCMmPFSeGpmdvg9wJBloHJ0MgnUog4rChM9d1IdkoRCAmMLHqXtkWixsCQWiOaXMlGAJpYU/VU8L6n7Qp6y8+bvr64uPIXy8+Dn118dGYD0aJOCAMXRyGQIablrcNxlMC+UEXRMrG192OHh6I6E4bEJYe6o+JnyyVXDDFCESQxjpE0pghkJBKJpXO+ota9fp//Jn85h+PtW8uPtYgEu3rn//Uvur4w9fpFF6Y4ngykj6YujkDxwcnu/m2EtMK7ZCQXouIT6xDtxPvtPan7P9CKFYgJq80d0+pCf2W0AWy9WpZZgSTIvnb/2iT1v/yOL5exJEhkL/+/EfyS9QsKmvZkKnvEIYuDgnp4siV9w7116c5jksuKcLDe6kEIsxtvlJtmlizWYtUPt/8U6ta/4umOQuk/LWIiKMe4jDnYhUiDhN57QEEkjQ9K7598HaDSsqLUgpEmBuKhcxG+ktbrnDSYSWjm1eeAvkz5Mc6cidMcZizeYsRh4mYV++ExcwyvSreDuVr2pRaILJ/MbH0bt4tVxLsxapg/vazNtlTIAjrfvpXHCH4dbvm24UUcUAYujh0gRwfLsnNKCw90D8FIomluR6N5OOft9QCEeY2d02bvfVqUg0U0vN8JYM2SJOXQGBmaesk/PQoCaE0rfv5QV4zTIPtd6d8evZ+8C9n7zXpKwlP3w/KqkKV/MxHpw1xmAumSikOExEExNGRcj168FZUfGOpZE/8EIgwZ+tv9Uog2kubu0o+I5mUCDGhvvnlcUOGQJok/quf/qiBODoMgfxLa5Bw4ZG29sKj8Nrz3l3BwfYHkz+LPGxL92oiwVyTvurMvciqUyOBj08Z4pDghzhMxLSBQMIp16O6d8W+rN3ZfglEkNrDEMiV5MzvurjOo9KR8RD11cJXEMO6C3+ETYF8KSI5/0gcxnWsPjdqm+YtnhSV82qL2590gWSuSa8/6Z840oFAGlO+eQ/0JRftu+k5Td1PgUj7Q9oharIiu36fdsS8Wnd+tOnLC6NJEcja84ZXRYTYF+0PdMdwstYc4og7+cVyE8hHp0YK6mEqlMX7++pM37y6Z8V9va69dX4KRJCeLHM278zNV9j1Ox7QfWGdHw1CIHElENNxXAIh5uY4zl0gd0u+rjwbiw/emi41SMr16IGbTSrJgt8CEWZt/S2UWg+y6RK7fscLUmOs/vFBLQTi6DguHxOrUN9YxbBw362pEEY8zfWozdN7OQQippWYWLpAvutKzPmWXb/jjtXtD6shjs6CBVJmM8tEerMgkE4lEO3NvfFO8bKokssiEEEa6QhJEQk+2fU7HkE7JFiEQMbsVc1Sa0jtIQIxXI/2xiCMmgXf9zalrUnvqN3VU+tnQ/rFzV31hkDEq8kldv2ON4LtDwNPo0BMFu2Phzx987aI69GehJ+eFWFiRQyvJpeTM5vY9TuugCCqChXIxydHHBvJ5UZqj2yeFefvvpGESIqaJeyGdP3O3NSV0P1ibeyK/hu7fscP0rtVqEDqT4/4csPlw8J9N2uz1SCm47jXd1/3refNdFwtYcbGLnb9jicgkFAhAhmLXqxMIJBorgIRx3F+1SICxBESgRhuR7tCz2+is+pxgdQin0eS+lhIXiaWbmbdbSzX7OFMVENdNdJzE8jru6755qZHOgMgkFi6b156WhwnBNvvB3IRyKpTI8mPT4+ELJMVTw5Hi32xTiEs/L5vWt4C2XnN19dISxvE4ry6KcqeracdqQFyrEE6TCHIp7wfRAQiQVYUrmgbKsvNML91cJK8vNPazZuzQHxdUPbipiuNlhrkW7oHeuqxtkHuB+QtUzClpkMcQQl/OTNSkz7d3USEJSaWUYso7+7Hh9vS3xMi09aX/zBYJSGfNR2ZGIODfXV1B/ra0t5yq4d8BFK7s9vXbljxoTWj6VI9xBF+YcOvvg5UkjKAGmN6qhcrkixoNFhfWXhyOG6uSV95fCixvG2oZvmxoUYHtz+hXIWypPXWVFl2K+9HT5vNa0xWFGHsj8cW7YtHchWIn71YZByiunjjukCMqe4FNyjF5ajUHkog3q5HjyQibn55l7b2VS9tHWh6p/V2PG1FobEexBCITDEJLj7Qm2rzLNprDBZmF8iN5Gs7rtNdKMmNL3582CLikABxlMQcgDDqsjuOS6T88kptAkHUvnt4oEUcNiivJrrTBlMgb4VhVol55bGiUETiJpD5u3viMK+SRi/WdREJZ98Sb2TRVNps3jYVXRIgjFg2gbx/+E78/SN3IqZnRdMvlgRx2rCktb/lrYM3a/Jpt7y59/r0BXt7whBI54KW3rj+fpCWGwHpfpXxD9QgidT7QXZ0s31AnJEFUmvOjcbN9SDyWyUVTT7e3dN882rvHRqIoxZpevfwLd9MIHlfOsSRMN8PMm+7uyd3MoFZ8+No2FwwFWxPFvyWJTdyMbF0gRy+E4VAGgJojKtNfad2d/eU13Zdj5kv0Jnn87gIecpYayyW0lcUShtERZeUFceHOnIwscZsJrC8yDPjBToVMemSjBEyXvGlLLc99yiy9vzDhBJIvJSmVTrLjw9WZRPIB4fvjGlvEtolk17bca0z9Yap7b+HXm7uno7Ptle2xSIvb4s1yJiGyk7GM19eeNRmejUxnTbIsluV7Asrjw3VLT82lHQSCMyqimggi0jkHYXmG6bMF+iY7weZuy1GryXjnbUXRqemu/0pl0CEZUfuToFAmpYdS0QgDglNgdbBipq8JwKAMNqcBCKvP5jbfJUN+fGMOItzEgjaH5xEp5i3s7vKVSChGNd2jGf09seFR3GrQB4m17aPchKdQt5T6CGQMXFMQcqImFkQR9QQyMOEk2fFiY5uZmUIBG2QpLxER2UhZOKiN9ilByslkFh8dnM3520Rko402llrEEIIIWVH07RnEbgQPws4RzRTJhIijMePH7fhUwffO/HBKdMZ4LzUISTVOYojNOErp2yMd9SFdmLMnadVCjhH09Q5sYD4RpWFjFdwkWPqemfCEWkFzkXQOCVWcO64Fny8g4scUdfbAuI56KbA6ag1zooVnCNfptWTCgIXeRpCQl1zHfwec+/mlQROibTTLA8S/I7jgw32iQAu9HMIYkYEceE5yuoCzk2dOkfyyQY6IYSUFDxZZTylqhRP2LSySmrKoAaQXqkxnfWL/U+W/6d+eiLHilCSc1oI6lhzPl8qf8mOV8pR5ZX/mqkdW8ANFFPJKRBta6gin76mAF+n4HubbGekGOB3AiGMrznd4Mg3FfkbECIIYuNbUOXJmI0ci+3kI82pR06/EZHWhCBjPBYQ14EPKc/zZtUz27F1hat4CypexF6P/cl/08dTgOPArMQjSF7b/5FtEVrwtWgfWCjDqfNBd/aAfUxHkGNNtU/VviXOttgKcdKWbZE8KrsOfud1D5hgG9m/rTwBcXJepEng/8A2dlKUQPAhF9L2J9JR6Z7dxsjTaOTODVWm5YmCOCeBVCM+qr67ovK4XkQjl42cBAKeQ/kixExsFxj5UgOS2UA+6TgoeP09tnW6pvKAalA/XUEeeVDpDxV8DyBkvQckn75jD5BVzpVjz2omuZZZFNhPwQLJF5Tr2HWMeLfBSlecjlHiVHJBYHs54Y5OoFWWTHISCMq01YYKi0CQT2qGvMA28oQv6EmK7Yq6pth3RwHH7DoAjTSxRNzOlSvYxj/vLSi/nAKRP28xjfBb7GsbyGtW52awPKHw26maL0ogAsqQY7Q9lY1UG7nWIG6kbmx8rzei7OCY5EaUc+D4/yQdH3k7YcA2RV/TfMGxOg6uIknMYMeaHvEytUe/D1SUE/5Mj0LBRQsE+eVmbkSoQRDbUappy9hKGhZTS/Kq+BSIcxyAQ9JkVba0JWw3BOJdBYI0MQnkv0pbQLq1XU0vxNv2r5IyyUsgKNcUvfxnsaH1hwU+3R4SUrNaxIo4Ob+2/4m4vE0NbOZ1TeVBoXf747MWn6n5em4gj7QZpAu8Cp9yndzMLtt5Q16biY04ab9YrA5ET3LJK/sqfScGCi1KIMgrJ9Jmu0ucOmgLiLM4C5DfKikF4goaxcd2bgJx9DKIeDnZTg1328k2UmzkLBCUKU95xzYO0pwuuOtgLdKkQZxZo0ZVcs5gM7drKg8OWy2KeC9T2PYEl+NUaRYQbxEzoqT2yByslv/nao4h3emclf41dCi3WIG4PrmQZjuhiOtQyTr47fRHpUqVJ1G+PR9OT1a52K7mB9Lcnt6ZTy4nchIIypKL7dqYRrpTbev537GNk+2fVzco8rtdU8fBYiRJ75oN5Ldc03SQZqt5EGeZ5InfNSophWynkh1BFun6tZBtm4JAucWaWK4XHmm2bTLLRlS1keIOtjHNEsnrWo1K2foGach2KtkV5HEytSy1jorLJFeBuB4Dkm0XWsA2us3tEZxqy7y6fpHf8ZqqZEewX5tVAFz9AEuakeUJKMNyIyPKKU9M/U+vkFmL2u7bokG5BQtEDlAlO4IsOZWNOOknzwnZJz6kQZtTGwRxWatdp/0jztIzoqIzyVUgrseAZMcarBCwn7zaIdgk6wMsE0lXWdNxbSBLmpHlCSjD8sYv/LaZ2YWiiiwdKLMYgXieTGTJqWwBSdIQdGvY20Bem50sZRupT0BcLgLJagao6ExybYO42tJIK5lAQF4e3ZE/682bidM5Bl7/jwJxA1lyFoiAZDE3RCjSG5J1sAh5Mm1ZJ4FkXdSEPL6aWMDrBnIzscyernyC636cQP6KEAii5NgtqGuS+f+yBlVk6UChFSMQJ7CJ9IZJ97HTU97ScyNlq6QUiJNeNq9Guu0YBdmnyqKjojMpWiCCOkYLiCtJjwyKki5Xt8HPihAIfjs10j2vW9nAQYy5QBAtZobnaDDSZfzChkrWkbJVtAXEO460IkmmNdhqD8RJO8dycYwUG6USiNNYkJibrr1SSJMHh/QAOt5EiBdhpISH7/I/LT1j+F0RAkGUdPM6PSTkoej1cBNrw9/lGdjJmAsEcfpYBD71SXgItp4xxNlGmpE/aw1igjQZjZYnlRyT3Dwy58l2UQTE2xw7q6RMSiIQpItQbb1DiJOBMhGBHLM8IPRZrYhLDcLh0+lYZXzH6YbLvDErQiACosVEsoG8uhMRBF3c8okgg7y6RYFPOQ+e57copHDZUTpyElRyCkT7IhBEuXbzIq/ZnefYeEe8pftUylZJBaPKsHUlG6k2SiIQAfu1mRm5gm0zOxRs5z2N1H/D90oSiNQiThM6s4LtPGvbokDBYyoQ/LaNZOeC2s5S/UrZRmphYHvXE23ksFEygQjI5zofywsct9xY6Te+2+CnxXTE94oRiIAkR5M3G/K/EEo/ii6g/DETCH7KU0PMBUdTxw3klx4u21NeyjZyPEGVn/XJpPK4toOMXDZKKhABxyHTSHK6SZBPbnjbMgLEyXl1mkJjmWOGqIoSiIBk/Z4wcmYHeaMIjp0QJQH7kEVK6aOTEmyT9RBnLqDxzJdOrmULiJeeqrDKYxEMfnciiM0pdqrrxUAep4unD2LhUybeSdkWc03KRcg690ttawnY3Fbb5JovG9hOzncIwSIW+a3KlP/jemMgXSZ2ph4M+C5jDZaHCuKcrqlntzjS9S749IByXf8f0vPeh4AypTaRdqJcn8xrJmVIe9VxwJi4gJPmKhBCJjwUCCEeUCCEeECBEOIBBUKIBxQIIR5AILLEU8Ze0oPrgi5CCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEJceOaZ/wft5JYoNhJLKgAAAABJRU5ErkJggg=="}}]);
define({ gadgetRegistry: [ { name: "SimpleGadget", gadget: "SimpleGadget" } ], layoutData: { "address": "/windows[0]", "subAreas": [ { "address": "/windows[0]/top", "gadget": { "name": "SimpleGadget" }, "subAreas": [] } ] } });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), moment = require('moment'), Schema = mongoose.Schema; /** * Password Request Schema */ var PassResReqSchema = new Schema({ email: { type: String, default: '', trim: true }, token: { type: String, default: '', trim: true }, created: { type: Number, default: function(){ return moment().valueOf(); } } }); /** * Statics */ PassResReqSchema.statics.load = function(id, cb) { this.findOne({ _id: id }).exec(cb); }; mongoose.model('PasswordResetRequest', PassResReqSchema);
var e=Object.defineProperty,t=Object.defineProperties,a=Object.getOwnPropertyDescriptors,l=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,r=Object.prototype.propertyIsEnumerable,s=(t,a,l)=>a in t?e(t,a,{enumerable:!0,configurable:!0,writable:!0,value:l}):t[a]=l,o=(e,t)=>{for(var a in t||(t={}))n.call(t,a)&&s(e,a,t[a]);if(l)for(var a of l(t))r.call(t,a)&&s(e,a,t[a]);return e},c=(e,l)=>t(e,a(l));import{j as i,h as m,R as u,E as d,r as p,t as E,l as b,x as y,ap as f,aq as v,ar as g,as as C,at as h,au as O,M as j,G as x,J as k,K as w,N as S,O as q,af as P,Q as _}from"./vendor.300ed9b7.js";import{a as z}from"./index.e9d3fa6c.js";import{F as D}from"./form-item.fbfad929.js";import"./index.650959c9.js";import"./index.09572d96.js";import"./index.esm.d1ca93b9.js";import"./useTitle.0be7584e.js";const F={id:0,name:"",type:"",root_folder:"",status:"",index:0};function G(e){switch(e){case"string":return"";case"bool":return!1;case"select":return"";case"number":return 0}}const I=[{name:"name",label:"name",type:"string",required:!0},{name:"index",label:"index",type:"number",required:!0,description:"for sort"}],J=()=>{const e=i(),{t:t}=m(),[a,l]=u.useState([]),[n,r]=u.useState({}),[s,J]=u.useState(F),[K,L]=u.useState(!1),[M,N]=u.useState(!1),Q=d(),R=()=>{N(!0),z.get("accounts").then((a=>{N(!1);const n=a.data;200!==n.code?e({title:t(n.message),status:"error",duration:3e3,isClosable:!0}):l(n.data)}))};return p.exports.useEffect((()=>{R(),z.get("drivers").then((a=>{const l=a.data;200!==l.code?e({title:t(l.message),status:"error",duration:3e3,isClosable:!0}):r(l.data)}))}),[]),u.createElement(E,{w:"full"},u.createElement(b,null,u.createElement(y,{onClick:()=>{J(F),L(!1),Q.onOpen()}},t("add")),u.createElement(y,{colorScheme:"orange",isLoading:M,onClick:()=>{R()}},t("refresh"))),u.createElement(E,{overflowX:"auto"},u.createElement(f,{w:"full"},u.createElement(v,null,u.createElement(g,null,u.createElement(C,null,t("name")),u.createElement(C,null,t("type")),u.createElement(C,null,t("root_folder")),u.createElement(C,null,t("index")),u.createElement(C,null,t("status")),u.createElement(C,null,t("operation")))),u.createElement(h,null,a.map((a=>u.createElement(g,{key:a.id},u.createElement(O,null,a.name),u.createElement(O,null,a.type),u.createElement(O,null,a.root_folder),u.createElement(O,null,a.index),u.createElement(O,null,a.status),u.createElement(O,{whiteSpace:"nowrap"},u.createElement(y,{onClick:()=>{J(a),L(!0),Q.onOpen()}},t("edit")),u.createElement(y,{colorScheme:"red",ml:"1",onClick:()=>{z.delete("account",{params:{id:a.id}}).then((a=>{const l=a.data;200!==l.code?e({title:t(l.message),status:"error",duration:3e3,isClosable:!0}):(e({title:t(l.message),status:"success",duration:3e3,isClosable:!0}),R())}))}},t("delete"))))))))),u.createElement(j,{isOpen:Q.isOpen,onClose:Q.onClose,size:"6xl"},u.createElement(x,null),u.createElement(k,null,u.createElement(w,null,t(K?"save":"add")),u.createElement(S,null),u.createElement(q,{pb:6},u.createElement(P,{minChildWidth:"250px",spacing:"2"},u.createElement(D,{type:"select",readOnly:K,required:!0,label:t("type"),value:s.type,values:Object.keys(n),onChange:e=>{const t=o({},s);t.type=e;for(const a of n[e])Object.keys(t).includes(a.name)||(t[a.name]=G(a.type));J(t)}}),I.map((e=>{var t;return u.createElement(D,{key:e.name,type:e.type,label:e.label,value:s[e.name],description:e.description,required:e.required,values:null==(t=e.values)?void 0:t.split(","),onChange:t=>{"bool"!==e.type?J(c(o({},s),{[e.name]:t})):J(c(o({},s),{[e.name]:!s[e.name]}))}})})),s.type&&n[s.type].map((e=>{var t;return u.createElement(D,{key:e.name,type:e.type,label:e.label,value:s[e.name],description:e.description,required:e.required,values:null==(t=e.values)?void 0:t.split(","),onChange:t=>{"bool"!==e.type?J(c(o({},s),{[e.name]:t})):J(c(o({},s),{[e.name]:!s[e.name]}))}})})))),u.createElement(_,null,u.createElement(y,{mr:3,colorScheme:"gray",onClick:Q.onClose},t("cancle")),u.createElement(y,{onClick:()=>{console.log(s),z.post("account/"+(K?"save":"create"),s).then((a=>{const l=a.data;200!==l.code?(e({title:t(l.message),status:"error",duration:3e3,isClosable:!0}),K||(R(),Q.onClose())):(e({title:t(l.message),status:"success",duration:3e3,isClosable:!0}),R(),Q.onClose())}))}},t("save"))))))};export{J as default};
module.exports={A:{A:{"1":"E A B","2":"P F D rB"},B:{"1":"C I J K L M N v s Q VB GB"},C:{"1":"0 1 2 3 4 5 6 7 8 9 V W X Y Z a b c d e f g h i j k l m n o p q r R t u O w x y z SB WB AB BB CB DB EB H FB MB NB OB PB QB RB IB TB UB v s Q kB","2":"uB LB","260":"G T P F D E A B C I J K L M N U jB iB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 G T P F D E A B C I J K L M N U V W X Y Z a b c d e f g h i j k l m n o p q r R t u O w x y z SB WB AB BB CB DB EB H FB MB NB OB PB QB RB IB TB UB v s Q VB GB dB aB 1B bB"},E:{"1":"G T P F D E A eB fB gB hB XB","2":"cB YB","513":"B C I J S HB lB mB"},F:{"1":"0 1 2 3 4 5 6 7 8 9 B C K L M N U V W X Y Z a b c d e f g h i j k l m n o p q r R t u O w x y z AB BB CB DB EB H FB pB qB S KB sB HB","2":"E nB oB"},G:{"1":"D YB tB JB vB wB xB yB zB 0B ZB 2B","513":"3B 4B 5B 6B 7B 8B 9B AC BC"},H:{"2":"CC"},I:{"1":"LB G Q FC GC JB HC IC","132":"DC EC"},J:{"1":"F A"},K:{"1":"B C O S KB HB","2":"A"},L:{"1":"GB"},M:{"1":"H"},N:{"1":"A B"},O:{"1":"JC"},P:{"1":"G KC LC MC NC OC XB PC QC"},Q:{"1":"RC"},R:{"1":"SC"},S:{"1":"TC"}},B:1,C:"Video element"};
module.exports = { siteMetadata: { title: `Melissa Masia`, description: `Melissa Masia's personal website`, author: `Melissa Masia`, }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `gatsby-starter-default`, short_name: `starter`, start_url: `/`, background_color: `#663399`, theme_color: `#663399`, display: `minimal-ui`, }, }, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, `gatsby-plugin-typescript`, { resolve: `gatsby-plugin-typography`, options: { pathToConfigModule: `src/utils/typography`, }, }, { resolve: `gatsby-plugin-styled-components`, }, ], }
<<<<<<< HEAD import Big from "big.js"; import operate from "./operate"; import isNumber from "./isNumber"; /** * Given a button name and a calculator data object, return an updated * calculator data object. * * Calculator data object contains: * total:String the running total * next:String the next number to be operated on with the total * operation:String +, -, etc. */ export default function calculate(obj, buttonName) { if (buttonName === "AC") { return { total: null, next: null, operation: null, }; } if (isNumber(buttonName)) { if (buttonName === "0" && obj.next === "0") { return {}; } // If there is an operation, update next if (obj.operation) { if (obj.next) { return { next: obj.next + buttonName }; } return { next: buttonName }; } // If there is no operation, update next and clear the value if (obj.next) { const next = obj.next === "0" ? buttonName : obj.next + buttonName; return { next, total: null, }; } return { next: buttonName, total: null, }; } if (buttonName === "%") { if (obj.operation && obj.next) { const result = operate(obj.total, obj.next, obj.operation); return { total: Big(result) .div(Big("100")) .toString(), next: null, operation: null, }; } if (obj.next) { return { next: Big(obj.next) .div(Big("100")) .toString(), }; } return {}; } if (buttonName === ".") { if (obj.next) { // ignore a . if the next number already has one if (obj.next.includes(".")) { return {}; } return { next: obj.next + "." }; } return { next: "0." }; } if (buttonName === "=") { if (obj.next && obj.operation) { return { total: operate(obj.total, obj.next, obj.operation), next: null, operation: null, }; } else { // '=' with no operation, nothing to do return {}; } } if (buttonName === "+/-") { if (obj.next) { return { next: (-1 * parseFloat(obj.next)).toString() }; } if (obj.total) { return { total: (-1 * parseFloat(obj.total)).toString() }; } return {}; } // Button must be an operation // When the user presses an operation button without having entered // a number first, do nothing. // if (!obj.next && !obj.total) { // return {}; // } // User pressed an operation button and there is an existing operation if (obj.operation) { return { total: operate(obj.total, obj.next, obj.operation), next: null, operation: buttonName, }; } // no operation yet, but the user typed one // The user hasn't typed a number yet, just save the operation if (!obj.next) { return { operation: buttonName }; } // save the operation and shift 'next' into 'total' return { total: obj.next, next: null, operation: buttonName, }; } export function emptyString() { return ""; } ======= import Big from "big.js"; import operate from "./operate"; import isNumber from "./isNumber"; /** * Given a button name and a calculator data object, return an updated * calculator data object. * * Calculator data object contains: * total:String the running total * next:String the next number to be operated on with the total * operation:String +, -, etc. */ export default function calculate(obj, buttonName) { if (buttonName === "AC") { return { total: null, next: null, operation: null, }; } if (isNumber(buttonName)) { if (buttonName === "0" && obj.next === "0") { return {}; } // If there is an operation, update next if (obj.operation) { if (obj.next) { return { next: obj.next + buttonName }; } return { next: buttonName }; } // If there is no operation, update next and clear the value if (obj.next) { const next = obj.next === "0" ? buttonName : obj.next + buttonName; return { next, total: null, }; } return { next: buttonName, total: null, }; } if (buttonName === "%") { if (obj.operation && obj.next) { const result = operate(obj.total, obj.next, obj.operation); return { total: Big(result) .div(Big("100")) .toString(), next: null, operation: null, }; } if (obj.next) { return { next: Big(obj.next) .div(Big("100")) .toString(), }; } return {}; } if (buttonName === ".") { if (obj.next) { // ignore a . if the next number already has one if (obj.next.includes(".")) { return {}; } return { next: obj.next + "." }; } return { next: "0." }; } if (buttonName === "=") { if (obj.next && obj.operation) { return { total: operate(obj.total, obj.next, obj.operation), next: null, operation: null, }; } else { // '=' with no operation, nothing to do return {}; } } if (buttonName === "+/-") { if (obj.next) { return { next: (-1 * parseFloat(obj.next)).toString() }; } if (obj.total) { return { total: (-1 * parseFloat(obj.total)).toString() }; } return {}; } // Button must be an operation // When the user presses an operation button without having entered // a number first, do nothing. // if (!obj.next && !obj.total) { // return {}; // } // User pressed an operation button and there is an existing operation if (obj.operation) { return { total: operate(obj.total, obj.next, obj.operation), next: null, operation: buttonName, }; } // no operation yet, but the user typed one // The user hasn't typed a number yet, just save the operation if (!obj.next) { return { operation: buttonName }; } // save the operation and shift 'next' into 'total' return { total: obj.next, next: null, operation: buttonName, }; } export function emptyString() { return ""; } >>>>>>> b99d80534c0f058a53bf688f49098beb6d82d353
const electronConnect = require('electron-connect'); class ElectronConnectReplacementWebpackPlugin { constructor(pluginOptions, electronOptions) { this._pluginOptions = pluginOptions ? pluginOptions : {}; this._electronOptions = electronOptions ? electronOptions : {}; this.apply = this.apply.bind(this); this.done = this.done.bind(this); } apply(compiler) { if (this._server === undefined) { this._server = electronConnect.server.create(this._electronOptions); } // Start browser process this._server.start(); compiler.plugin('done', this.done); } done() { console.log('[ECR]: Enabled'); // Reload renderer process this._server.reload(); } } export default ElectronConnectReplacementWebpackPlugin;
"use strict"; /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ Object.defineProperty(exports, "__esModule", { value: true }); exports.ThemingApiMigration = void 0; const core_1 = require("@angular-devkit/core"); const schematics_1 = require("@angular/cdk/schematics"); const migration_1 = require("./migration"); /** Migration that switches all Sass files using Material theming APIs to `@use`. */ class ThemingApiMigration extends schematics_1.DevkitMigration { constructor() { super(...arguments); this.enabled = this.targetVersion === schematics_1.TargetVersion.V12; } visitStylesheet(stylesheet) { if (core_1.extname(stylesheet.filePath) === '.scss') { const content = stylesheet.content; const migratedContent = content ? migration_1.migrateFileContent(content, '~@angular/material/', '~@angular/cdk/', '~@angular/material', '~@angular/cdk', undefined, /material\/prebuilt-themes|cdk\/.*-prebuilt/) : content; if (migratedContent && migratedContent !== content) { this.fileSystem.edit(stylesheet.filePath) .remove(0, stylesheet.content.length) .insertLeft(0, migratedContent); ThemingApiMigration.migratedFileCount++; } } } /** Logs out the number of migrated files at the end of the migration. */ static globalPostMigration(_tree, context) { const count = ThemingApiMigration.migratedFileCount; if (count > 0) { context.logger.info(`Migrated ${count === 1 ? `1 file` : `${count} files`} to the ` + `new Angular Material theming API.`); ThemingApiMigration.migratedFileCount = 0; } } } exports.ThemingApiMigration = ThemingApiMigration; /** Number of files that have been migrated. */ ThemingApiMigration.migratedFileCount = 0; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGhlbWluZy1hcGktbWlncmF0aW9uLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vLi4vc3JjL21hdGVyaWFsL3NjaGVtYXRpY3MvbmctdXBkYXRlL21pZ3JhdGlvbnMvdGhlbWluZy1hcGktdjEyL3RoZW1pbmctYXBpLW1pZ3JhdGlvbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUE7Ozs7OztHQU1HOzs7QUFFSCwrQ0FBNkM7QUFFN0Msd0RBQXlGO0FBQ3pGLDJDQUErQztBQUUvQyxvRkFBb0Y7QUFDcEYsTUFBYSxtQkFBb0IsU0FBUSw0QkFBcUI7SUFBOUQ7O1FBSUUsWUFBTyxHQUFHLElBQUksQ0FBQyxhQUFhLEtBQUssMEJBQWEsQ0FBQyxHQUFHLENBQUM7SUE0QnJELENBQUM7SUExQlUsZUFBZSxDQUFDLFVBQTRCO1FBQ25ELElBQUksY0FBTyxDQUFDLFVBQVUsQ0FBQyxRQUFRLENBQUMsS0FBSyxPQUFPLEVBQUU7WUFDNUMsTUFBTSxPQUFPLEdBQUcsVUFBVSxDQUFDLE9BQU8sQ0FBQztZQUNuQyxNQUFNLGVBQWUsR0FBRyxPQUFPLENBQUMsQ0FBQyxDQUFDLDhCQUFrQixDQUFDLE9BQU8sRUFDMUQscUJBQXFCLEVBQUUsZ0JBQWdCLEVBQUUsb0JBQW9CLEVBQUUsZUFBZSxFQUM5RSxTQUFTLEVBQUUsNENBQTRDLENBQUMsQ0FBQyxDQUFDLENBQUMsT0FBTyxDQUFDO1lBRXJFLElBQUksZUFBZSxJQUFJLGVBQWUsS0FBSyxPQUFPLEVBQUU7Z0JBQ2xELElBQUksQ0FBQyxVQUFVLENBQUMsSUFBSSxDQUFDLFVBQVUsQ0FBQyxRQUFRLENBQUM7cUJBQ3RDLE1BQU0sQ0FBQyxDQUFDLEVBQUUsVUFBVSxDQUFDLE9BQU8sQ0FBQyxNQUFNLENBQUM7cUJBQ3BDLFVBQVUsQ0FBQyxDQUFDLEVBQUUsZUFBZSxDQUFDLENBQUM7Z0JBQ2xDLG1CQUFtQixDQUFDLGlCQUFpQixFQUFFLENBQUM7YUFDekM7U0FDRjtJQUNILENBQUM7SUFFRCx5RUFBeUU7SUFDekUsTUFBTSxDQUFVLG1CQUFtQixDQUFDLEtBQWMsRUFBRSxPQUF5QjtRQUMzRSxNQUFNLEtBQUssR0FBRyxtQkFBbUIsQ0FBQyxpQkFBaUIsQ0FBQztRQUVwRCxJQUFJLEtBQUssR0FBRyxDQUFDLEVBQUU7WUFDYixPQUFPLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxZQUFZLEtBQUssS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDLFFBQVEsQ0FBQyxDQUFDLENBQUMsR0FBRyxLQUFLLFFBQVEsVUFBVTtnQkFDL0QsbUNBQW1DLENBQUMsQ0FBQztZQUN6RCxtQkFBbUIsQ0FBQyxpQkFBaUIsR0FBRyxDQUFDLENBQUM7U0FDM0M7SUFDSCxDQUFDOztBQS9CSCxrREFnQ0M7QUEvQkMsK0NBQStDO0FBQ3hDLHFDQUFpQixHQUFHLENBQUMsQ0FBQyIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQGxpY2Vuc2VcbiAqIENvcHlyaWdodCBHb29nbGUgTExDIEFsbCBSaWdodHMgUmVzZXJ2ZWQuXG4gKlxuICogVXNlIG9mIHRoaXMgc291cmNlIGNvZGUgaXMgZ292ZXJuZWQgYnkgYW4gTUlULXN0eWxlIGxpY2Vuc2UgdGhhdCBjYW4gYmVcbiAqIGZvdW5kIGluIHRoZSBMSUNFTlNFIGZpbGUgYXQgaHR0cHM6Ly9hbmd1bGFyLmlvL2xpY2Vuc2VcbiAqL1xuXG5pbXBvcnQge2V4dG5hbWV9IGZyb20gJ0Bhbmd1bGFyLWRldmtpdC9jb3JlJztcbmltcG9ydCB7U2NoZW1hdGljQ29udGV4dH0gZnJvbSAnQGFuZ3VsYXItZGV2a2l0L3NjaGVtYXRpY3MnO1xuaW1wb3J0IHtEZXZraXRNaWdyYXRpb24sIFJlc29sdmVkUmVzb3VyY2UsIFRhcmdldFZlcnNpb259IGZyb20gJ0Bhbmd1bGFyL2Nkay9zY2hlbWF0aWNzJztcbmltcG9ydCB7bWlncmF0ZUZpbGVDb250ZW50fSBmcm9tICcuL21pZ3JhdGlvbic7XG5cbi8qKiBNaWdyYXRpb24gdGhhdCBzd2l0Y2hlcyBhbGwgU2FzcyBmaWxlcyB1c2luZyBNYXRlcmlhbCB0aGVtaW5nIEFQSXMgdG8gYEB1c2VgLiAqL1xuZXhwb3J0IGNsYXNzIFRoZW1pbmdBcGlNaWdyYXRpb24gZXh0ZW5kcyBEZXZraXRNaWdyYXRpb248bnVsbD4ge1xuICAvKiogTnVtYmVyIG9mIGZpbGVzIHRoYXQgaGF2ZSBiZWVuIG1pZ3JhdGVkLiAqL1xuICBzdGF0aWMgbWlncmF0ZWRGaWxlQ291bnQgPSAwO1xuXG4gIGVuYWJsZWQgPSB0aGlzLnRhcmdldFZlcnNpb24gPT09IFRhcmdldFZlcnNpb24uVjEyO1xuXG4gIG92ZXJyaWRlIHZpc2l0U3R5bGVzaGVldChzdHlsZXNoZWV0OiBSZXNvbHZlZFJlc291cmNlKTogdm9pZCB7XG4gICAgaWYgKGV4dG5hbWUoc3R5bGVzaGVldC5maWxlUGF0aCkgPT09ICcuc2NzcycpIHtcbiAgICAgIGNvbnN0IGNvbnRlbnQgPSBzdHlsZXNoZWV0LmNvbnRlbnQ7XG4gICAgICBjb25zdCBtaWdyYXRlZENvbnRlbnQgPSBjb250ZW50ID8gbWlncmF0ZUZpbGVDb250ZW50KGNvbnRlbnQsXG4gICAgICAgICd+QGFuZ3VsYXIvbWF0ZXJpYWwvJywgJ35AYW5ndWxhci9jZGsvJywgJ35AYW5ndWxhci9tYXRlcmlhbCcsICd+QGFuZ3VsYXIvY2RrJyxcbiAgICAgICAgdW5kZWZpbmVkLCAvbWF0ZXJpYWxcXC9wcmVidWlsdC10aGVtZXN8Y2RrXFwvLiotcHJlYnVpbHQvKSA6IGNvbnRlbnQ7XG5cbiAgICAgIGlmIChtaWdyYXRlZENvbnRlbnQgJiYgbWlncmF0ZWRDb250ZW50ICE9PSBjb250ZW50KSB7XG4gICAgICAgIHRoaXMuZmlsZVN5c3RlbS5lZGl0KHN0eWxlc2hlZXQuZmlsZVBhdGgpXG4gICAgICAgICAgLnJlbW92ZSgwLCBzdHlsZXNoZWV0LmNvbnRlbnQubGVuZ3RoKVxuICAgICAgICAgIC5pbnNlcnRMZWZ0KDAsIG1pZ3JhdGVkQ29udGVudCk7XG4gICAgICAgIFRoZW1pbmdBcGlNaWdyYXRpb24ubWlncmF0ZWRGaWxlQ291bnQrKztcbiAgICAgIH1cbiAgICB9XG4gIH1cblxuICAvKiogTG9ncyBvdXQgdGhlIG51bWJlciBvZiBtaWdyYXRlZCBmaWxlcyBhdCB0aGUgZW5kIG9mIHRoZSBtaWdyYXRpb24uICovXG4gIHN0YXRpYyBvdmVycmlkZSBnbG9iYWxQb3N0TWlncmF0aW9uKF90cmVlOiB1bmtub3duLCBjb250ZXh0OiBTY2hlbWF0aWNDb250ZXh0KTogdm9pZCB7XG4gICAgY29uc3QgY291bnQgPSBUaGVtaW5nQXBpTWlncmF0aW9uLm1pZ3JhdGVkRmlsZUNvdW50O1xuXG4gICAgaWYgKGNvdW50ID4gMCkge1xuICAgICAgY29udGV4dC5sb2dnZXIuaW5mbyhgTWlncmF0ZWQgJHtjb3VudCA9PT0gMSA/IGAxIGZpbGVgIDogYCR7Y291bnR9IGZpbGVzYH0gdG8gdGhlIGAgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICBgbmV3IEFuZ3VsYXIgTWF0ZXJpYWwgdGhlbWluZyBBUEkuYCk7XG4gICAgICBUaGVtaW5nQXBpTWlncmF0aW9uLm1pZ3JhdGVkRmlsZUNvdW50ID0gMDtcbiAgICB9XG4gIH1cbn1cbiJdfQ==
'use strict'; /* Services */ /* global angular */ /* global moment */ /* jshint strict : true */ /* jshint undef : true */ /* jshint unused : true */ /* jshint globalstrict : true */ var settings = require('./shared/configuration'); angular.module( 'myApp.services.data', [] ). factory('dataService', function() { var status = { 'database': false, 'server': false }, insertAverage = function (data, props, avg_props) { var i, j, d, adu, totalDays = 0; if (data.interval === 'year') { // years for ( j = 0; j < data.items.length; j++ ) { // assumes all years have a full year of data -- assumption var daysInYear = 365; if ( moment( data.items[j].date ).isLeapYear() ) { daysInYear++; } for ( i = 0; i < props.length; i++ ) { adu = data.items[j][ props[i] ] / daysInYear; data.items[j][ avg_props[i] ] = adu; } totalDays = totalDays + daysInYear; } } else { // months for ( j = 0; j < data.items.length; j++ ) { for ( i = 0; i < props.length; i++ ) { var daysInMonth = moment( data.items[j].date ).daysInMonth(); adu = data.items[j][ props[i] ] / daysInMonth; data.items[j][ avg_props[i] ] = adu; } totalDays = totalDays + daysInMonth; } } // total for ( i = 0; i < props.length; i++ ) { adu = data.totals[ props[i] ] / totalDays; data.totals[ avg_props[i] ] = adu; } //console.log(JSON.stringify(data)); return data; }, getRange = function() { var range = {}; range.monthsArr = []; range.start = moment(settings.readSettings('startdate'), 'YYYY-MM-DD'); range.end = moment(settings.readSettings('enddate'), 'YYYY-MM-DD'); range.months = range.end.diff(range.start, 'months')+1; for (var m=0; m<range.months; m++) { range.monthsArr.push( range.start.clone().add(m, 'M').format('YYYY-MM-DD') ); } return range; } return { status : status, insertAverage : insertAverage, getRange : getRange }; });
var _ = require('lodash'); var dev = require('./development'); var test = require('./testing'); var prod = require('./production'); // default config obj for our api var config = { dev: 'development', test: 'testing', prod: 'production', //port: process.env.OPENSHIFT_NODEJS_PORT || 8080, db: {url: 'mongodb://127.0.0.1:27017/booksave'}, //db: {url: 'mongodb://jj:test@ec2-54-69-209-87.us-west-2.compute.amazonaws.com:27017/dummyDB'}, expireTime: '5d', secrets: { jwt: process.env.JWT || 'sushi', stripe: process.env.STRIPE || 'sk_test_BQokikJOvBiI2HlWgH4olfQ2' } }; process.env.NODE_ENV = process.env.NODE_ENV || config.dev; config.env = process.env.NODE_ENV; var envConfig = require('./' + config.env); module.exports = _.merge(config, envConfig);
var taskit = function () { return { getRowData: function (elem,table) {// get el row de un datatable para no tener que pasar el id en ninguna clase var current_row = $(elem).parents('tr'); if (current_row.hasClass('child')) {//Check if the current row is a child row current_row = current_row.prev();//If it is, then point to the row before it (its 'parent') } var aData = $(table).DataTable().row(current_row).data(); return aData; }, getTextByEtiqueta: function (text) {// quitar todo las etiquetas html de un texto cleanText = text.replace(/<[^>]*>?/g, ''); return cleanText; }, validateSpecialCharacters: function(){ // agregarse a cualquier clase que necesite caracteres especiales $.validator.addMethod("specialCharacters", function(value, element) { var validate = true; var characters = '\/:*?<>|$#@&^%'; for(var i=0; i < characters.length; i++ ) { if(value.indexOf(characters.charAt(i)) !== -1) { validate = false; break; } } return validate; }, "Letters, numbers, and underscores only please"); }, validateSpecialCharacters1: function(){ // agregarse a cualquier clase que necesite caracteres especiales $.validator.addMethod("specialCharacters1", function(value, element) { var validate = true; var characters = '\/:*?<>|$#@&^% '; for(var i=0; i < characters.length; i++ ) { if(value.indexOf(characters.charAt(i)) !== -1) { validate = false; break; } } return validate; }, "Letters, numbers, and underscores only please"); }, eventExpandAccordion: function(){//evento para que cambie el accordion cuando expanda y se recoja $(".expand").on( "click", function() { $expand = $(this).find(">:first-child"); if($expand.text() == "+") { $expand.text("-"); } else { $expand.text("+"); } }); }, settings: {} }; }();
// Message types passed between worker and UI Thread export const EVENT = 'event'; export const RENDER_TIME = 'render_time'; export const RENDER = 'render'; // Operations to be performed while rendering export const RENDER_QUEUE = 'renderQueue'; export const CONSTRUCTOR = 'constructor'; export const ADD_CHILD = 'appendChild'; export const ADD_CHILD_INDEX = 'addChildIndex'; export const REMOVE_CHILD = 'removeChild'; export const REMOVE_CHILD_INDEX = 'removeChildIndex'; export const REPLACE_AT = 'replaceAt'; export const SET_CONTENT = 'setContent'; export const SET_ATTRIBUTES = 'setAttributes'; export const ADD_EVENT_HANDLERS = 'addEventListeners'; export const REMOVE_EVENT_HANDLERS = 'removeEventHandlers'; // Other constants export const MAX_QUEUE_SIZE = 500;
'use strict'; const op = {}; exports.op = op; const refs = require('./refs.js'); const NQPInt = require('./nqp-int.js'); const NQPNum = require('./nqp-num.js'); const NQPStr = require('./nqp-str.js'); const NQPException = require('./nqp-exception.js'); const nullStr = require('./null_s.js'); const Null = require('./null.js'); const Capture = require('./capture.js'); const StaticCtx = require('./static-ctx.js'); const BOOT = require('./BOOT.js'); const nativeArgs = require('./native-args.js'); const JSBI = require('jsbi'); const asIntN = require('./as-int-n.js'); const globalContext = require('./global-context.js'); const NativeIntArg = exports.NativeIntArg = nativeArgs.NativeIntArg; const NativeUIntArg = exports.NativeUIntArg = nativeArgs.NativeUIntArg; const NativeNumArg = exports.NativeNumArg = nativeArgs.NativeNumArg; const NativeStrArg = exports.NativeStrArg = nativeArgs.NativeStrArg; const NativeNumRet = exports.NativeNumRet = nativeArgs.NativeNumRet; const NativeUIntRet = exports.NativeUIntRet = nativeArgs.NativeUIntRet; const stripMarks = require('./strip-marks.js'); const foldCase = require('fold-case'); const graphemes = require('./graphemes.js'); const fs = process.browser ? null : require('fs'); exports.NQPInt = NQPInt; exports.NQPNum = NQPNum; exports.NQPStr = NQPStr; function loadOps(module) { for (const name in module.op) { op[name] = module.op[name]; } } exports.loadOps = loadOps; const core = require('./core.js'); loadOps(core); exports.hash = core.hash; exports.slurpyNamed = core.slurpyNamed; exports.slurpyPos = core.slurpyPos; exports.named = core.named; exports.unwrapNamed = core.unwrapNamed; exports.arg = core.arg; exports.intToObj = core.intToObj; exports.numToObj = core.numToObj; exports.strToObj = core.strToObj; exports.int64ToObj = core.int64ToObj; exports.EvalResult = core.EvalResult; let browser; if (!process.browser) { const io = require('./io.js'); loadOps(io); } else { browser = require('./browser.js'); loadOps(browser); } const bignum = require('./bignum.js'); loadOps(bignum); const nfa = require('./nfa.js'); loadOps(nfa); const cclass = require('./cclass.js'); loadOps(cclass); const hll = require('./hll.js'); loadOps(hll); loadOps(require('./multicache.js')); const deserialization = require('./deserialization.js'); exports.wval = deserialization.wval; loadOps(deserialization); const serialization = require('./serialization.js'); loadOps(serialization); if (!process.browser) { const nativecall = require('./nativecall.js'); loadOps(nativecall); } const CodeRef = require('./code-ref.js'); exports.CodeRef = CodeRef; const continuations = process.browser ? require('./async-continuations.js') : require('./fiber-continuations.js'); loadOps(continuations); exports.CodeRefWithStateVars = require('./code-ref-with-statevars.js'); exports.CurLexpad = require('./curlexpad.js'); const Ctx = require('./ctx.js'); module.exports.Ctx = Ctx; module.exports.CtxWithStatic = require('./ctx-with-static.js'); module.exports.CtxJustHandler = require('./ctx-just-handler.js'); const bootstrap = require('./bootstrap.js'); module.exports.knowhowattr = bootstrap.knowhowattr; module.exports.knowhow = bootstrap.knowhow; loadOps(refs); for (const name in refs.helpers) { exports[name] = refs.helpers[name]; } const coercions = require('./coercions.js'); exports.strToNum = coercions.strToNum; exports.numToStr = coercions.numToStr; let libpath = []; exports.libpath = function(paths) { libpath = paths.map(path => (typeof path === 'string' || !path.$$getStr) ? path : path.$$getStr()); }; exports.loaderCtx = null; /* dependencies */ function loadWithCache(code) { const loadedCache = globalContext.context.loadedCache; if (!loadedCache.has(code)) { loadedCache.set(code, code(module.exports, false)); } return loadedCache.get(code); } if (process.browser) { op.loadbytecode = /*async*/ function(ctx, file) { if (file == 'Perl6/BOOTSTRAP.js') { file = 'Perl6::BOOTSTRAP'; } const oldLoaderCtx = exports.loaderCtx; exports.loaderCtx = ctx; file = file.replace(/\./g, '_'); file = file.replace(/\_js$/, ''); file = file.replace(/::/g, '-'); /*await*/ loadWithCache(require('./' + file + '.nqp-raw-runtime')); exports.loaderCtx = oldLoaderCtx; }; exports.requireExtraStuff = function(path) { return require(path); }; } else { op.loadbytecode = /*async*/ function(ctx, file) { // HACK - temporary hack for rakudo-js if (file == 'Perl6/BOOTSTRAP.js') { file = 'Perl6::BOOTSTRAP'; } let loadFrom; if (ctx && ((loadFrom = ctx.lookupDynamic('$*LOADBYTECODE_FROM')) !== Null)) { } else { loadFrom = module; } const oldLoaderCtx = exports.loaderCtx; exports.loaderCtx = ctx; const mangled = file.replace(/::/g, '-'); const prefixes = libpath.slice(); // TODO - think if we should be adding those prefixes.push('./', './nqp-js-on-js/'); let found = false; for (const prefix of prefixes) { try { if (typeof prefix === 'string') { /*await*/ loadWithCache(loadFrom.require(prefix + '/' + mangled)); } else { /*await*/ loadWithCache(prefix.module.require(prefix.prefix + '/' + mangled)); } found = true; break; } catch (e) { if (e.code !== 'MODULE_NOT_FOUND') { throw e; } } } if (!found) throw `can't find: ${file}, looking in: ${prefixes.join(', ')} from ${loadFrom.filename}`; exports.loaderCtx = oldLoaderCtx; return file; }; } const realModule = module; op.loadbytecodefh = function(ctx, fh, file) { // HACK - loadbytecodefh shouldn't use eval const module = {require: function(path) { return realModule.require(path); }}; const oldLoaderCtx = exports.loaderCtx; exports.loaderCtx = ctx; const js = fs.readFileSync(fh.fd, {encoding: 'utf8'}); eval(js); module.exports(realModule.exports, false); exports.loaderCtx = oldLoaderCtx; }; op.ctxlexpad = function(ctx) { if (ctx instanceof Ctx) { return ctx; } else if (ctx instanceof StaticCtx) { return ctx; } else { console.trace('ctxlexpad needs a ctx as an argument'); throw 'ctxlexpad needs a ctx as an argument'; } }; op.lexprimspec = function(pad, key) { // HACK return 0; }; op.ctxouter = function(ctx) { return ctx.$$outer === null ? Null : ctx.$$outer; }; exports.currentDispatcherFor = undefined; op.setdispatcherfor = function(dispatcher, dispatcherFor) { exports.currentDispatcher = dispatcher; let spec; if (dispatcherFor instanceof CodeRef) { exports.currentDispatcherFor = dispatcherFor; } else if (spec = dispatcherFor.$$STable.invocationSpec) { if (spec.classHandle) { exports.currentDispatcherFor = dispatcherFor.$$getattr(spec.classHandle, spec.attrName); } else { throw 'setdispatcherfor needs simple invokable target'; } } else { throw 'setdispatcherfor needs invokable target'; } }; exports.toStr = /*async*/ function(arg_, ctx) { if (!arg_.$$decont) { console.log('#2'); console.log(arg_); console.trace('got raw promise'); } const arg = /*await*/ arg_.$$decont(ctx); if (arg instanceof NQPStr) { return arg.value; } else if (arg === Null) { return ''; } else if (arg === nullStr) { return arg; } else if (arg.$$typeObject) { return ''; } else if (arg.$$getStr) { return arg.$$getStr(); } else if (arg.p6$Str) { const ret = /*await*/ arg.p6$Str(ctx, null, arg); // eslint-disable-line new-cap return (typeof ret === 'string' ? ret : (/*await*/ ret.$$decont(ctx)).$$getStr()); } else if (arg.$$getNum) { return coercions.numToStr(arg.$$getNum()); } else if (arg.$$getInt) { return arg.$$getInt().toString(); } else { throw new NQPException(`Can't convert to str`); } }; exports.toNum = /*async*/ function(arg_, ctx) { const arg = /*await*/ arg_.$$decont(ctx); if (arg === Null) { return 0; } else if (arg instanceof NQPStr) { return coercions.strToNum(arg.value); } else if (arg.$$STable && arg.$$STable.methodCache && arg.$$STable.methodCache.get('Num')) { const result = /*await*/ arg.p6$Num(ctx, null, arg); // eslint-disable-line new-cap if (typeof result === 'number') { return result; } else if (result.$$getNum) { return result.$$getNum(); } else if (result.$$numify) { return result.$$numify(); } else { throw new NQPException('we can\'t numify result of toNum'); } } else if (arg.$$typeObject) { return 0; } else if (arg.$$getNum) { return arg.$$getNum(); } else if (arg.$$getInt) { return arg.$$getInt(); } else if (arg.$$numify) { return arg.$$numify(); } else { throw new NQPException(`Can't convert to num`); } }; exports.toInt = /*async*/ function(arg, ctx) { return ((/*await*/ exports.toNum(arg, ctx)) | 0); }; exports.retval = function(currentHLL, arg) { if (typeof arg === 'number') { return core.intToObj(currentHLL, arg); } else if (typeof arg === 'string' || arg === nullStr) { return core.strToObj(currentHLL, arg); } else if (arg instanceof NativeNumRet) { return core.numToObj(currentHLL, arg.value); } else if (arg instanceof NativeUIntRet) { return core.intToObj(currentHLL, arg.value); } else { return arg; } }; exports.retval_bool = function(ctx, arg) { if (typeof arg === 'number') { return arg === 0 ? 0 : 1; } else if (typeof arg === 'string') { return arg === '' ? 0 : 1; } else if (arg === nullStr) { return 0; } else { return arg.$$toBool(ctx); } }; exports.retval_i = function(ctx, arg) { if (typeof arg === 'number') { return arg; } else if (typeof arg === 'string' || arg === nullStr) { return coercions.strToNum(arg)|0; } else { return exports.toInt(arg, ctx); } }; exports.retval_n = function(ctx, arg) { if (typeof arg === 'number') { return arg; } else if (typeof arg === 'string' || arg === nullStr) { return coercions.strToNum(arg); } else { return exports.toNum(arg, ctx); } }; exports.retval_s = function(ctx, arg) { if (typeof arg === 'string' || arg === nullStr) { return arg; } else if (typeof arg === 'number') { return arg.toString(); } else { return exports.toStr(arg, ctx); } }; // Placeholder exports.topContext = function() { return null; }; // helper for regexs exports.regexPeek = function(bstack, mark) { let ptr = bstack.length; while (ptr >= 0) { if (bstack[ptr] == mark) break; ptr -= 4; } return ptr; }; exports.regexCommit = function(bstack, mark) { let ptr = bstack.length; let caps; if (ptr > 0) { caps = bstack[ptr - 1]; } else { caps = 0; } while (ptr >= 0) { if (bstack[ptr] == mark) { break; } ptr -= 4; } bstack.length = ptr; if (caps > 0) { if (ptr > 0) { /* top mark frame is an autofail frame, reuse it to hold captures */ if (bstack[ptr - 3] < 0) { bstack[ptr - 1] = caps; } } /* push a new autofail frame onto bstack to hold the captures */ bstack.push(0, -1, 0, caps); } }; exports.NYI = function(msg) { console.trace(msg); return null; }; exports.args = function(isMain) { return isMain ? process.argv.slice(1).map(arg => new NativeStrArg(arg)) : []; }; exports.NQPException = NQPException; exports.wrapException = function(e) { return new NQPException('<<wrapped exception:\n' + e.stack + '\n>>\n'); }; exports.setCodeRefHLL = function(codeRefs, currentHLL, filename, originalFilename) { for (let i = 0; i < codeRefs.length; i++) { codeRefs[i].hll = currentHLL; codeRefs[i].filename = filename; codeRefs[i].originalFilename = originalFilename; } }; exports.null_s = nullStr; exports.Null = Null; exports.list = hll.list; exports.list_i = function lowlevelList(array) { const stable = BOOT.IntArray.$$STable; return stable.REPR.allocateFromArray(stable, array); }; exports.list_n = function lowlevelList(array) { const stable = BOOT.NumArray.$$STable; return stable.REPR.allocateFromArray(stable, array); }; exports.list_s = function lowlevelList(array) { const stable = BOOT.StrArray.$$STable; return stable.REPR.allocateFromArray(stable, array); }; exports.slurpyArray = hll.slurpyArray; exports.createArray = require('./BOOT.js').createArray; exports.createIntArray = require('./BOOT.js').createIntArray; const containerSpecs = require('./container-specs.js'); exports.extraRuntime = function(lang, path) { if (lang != 'perl6') throw 'only loading extra runtime for perl 6 is supported'; const runtime = typeof path === 'string' ? require(path) : path.require(lang + '-runtime'); if (!runtime.loaded) { runtime.loaded = true; runtime.load(exports, CodeRef, Capture, containerSpecs); } }; exports.paramcheckfailed = function(currentHLL, ctx, args) { const capture = new Capture(args[1], Array.prototype.slice.call(args, 2)); return currentHLL.get('bind_error').$$call(ctx, null, capture); }; let execname; exports.execname = function(path) { execname = path; }; op.execname = function() { return execname; }; exports.exitHandler = function(ctx, currentHLL, value) { return currentHLL.get('exit_handler').$$call(ctx, null, ctx.codeRef(), value === undefined ? Null : value); }; exports.NativeRef = require('./reprs.js').NativeRef; exports.getHLL = hll.getHLL; let once = true; exports.run = /*async*/ function(code, isMain) { const doRun = /*async*/ function() { let ret = /*await*/ code(); if (exports.afterRun && isMain === true) { /*await*/ hll.op.gethllsym(exports.afterRun.hll, exports.afterRun.sym).$$call(null, null); } return ret; }; if (once && browser && typeof window !== 'undefined' && window.__rakudo__ && window.__rakudo__.waitForStart) { once = false; window.__rakudo__.waitForStart.push(/*async*/ () => { browser.op.getstdout().start(); try { /*await*/ doRun(); } catch (e) { if (e instanceof browser.Exit) { } else { throw e; } } browser.op.getstdout().end(); }); } else if (browser && typeof window === 'undefined') { // We are bundled for browser use but in fact running under node.js try { return /*await*/ doRun(); } catch (e) { if (e instanceof browser.Exit) { global.process.exit(e.status); } else { throw e; } } } else if (once && typeof window !== 'undefined' && window.NQP_END_EVENT) { once = false; let ret; try { ret = /*await*/ doRun() } catch (e) { if (e instanceof browser.Exit) { console.info('exit', e.status); } else { throw e; } } console.info('end'); return ret; } else { return /*await*/ doRun(); } }; exports.tooFewPos = function(got, expected) { throw new NQPException(`Too few positionals passed; expected ${expected-2} arguments but got ${got-2}`); }; exports.tooManyPos = function(got, expected) { throw new NQPException(`Too many positionals passed; expected ${expected-2} arguments but got ${got-2}`); }; exports.arg_i = function(ctx, contedArg) { if (contedArg instanceof NativeIntArg) { return contedArg.value; } else if (contedArg instanceof NativeUIntArg) { return contedArg.value|0; } else if (contedArg instanceof NativeNumArg) { throw new NQPException('Expected native int argument, but got num'); } else if (contedArg instanceof NativeStrArg) { throw new NQPException('Expected native int argument, but got str'); } const arg = contedArg.$$decont(ctx); if (arg instanceof NQPInt) { return arg.value; } else if (arg.$$getInt) { return arg.$$getInt(); } else { throw new NQPException('Expected native int argument, but got something else'); } }; exports.arg_i64 = function(ctx, contedArg) { if (contedArg instanceof NativeIntArg) { return JSBI.BigInt(contedArg.value); } else if (contedArg instanceof NativeUIntArg) { return JSBI.BigInt(contedArg.value); } else if (contedArg instanceof NativeNumArg) { throw new NQPException('Expected native int64 argument, but got num'); } else if (contedArg instanceof NativeStrArg) { throw new NQPException('Expected native int64 argument, but got str'); } const arg = contedArg.$$decont(ctx); if (arg instanceof NQPInt) { return JSBI.BigInt(arg.value); } else if (arg.$$getInt64) { return JSBI.BigInt(arg.$$getInt64()); } else { throw new NQPException('Expected native int64 argument, but got something else'); } }; exports.arg_u64 = function(ctx, contedArg) { if (contedArg instanceof NativeIntArg) { return asIntN.asUintN(64, JSBI.BigInt(contedArg.value)); } else if (contedArg instanceof NativeUIntArg) { return JSBI.BigInt(contedArg.value); } else if (contedArg instanceof NativeNumArg) { throw new NQPException('Expected native uint64 argument, but got num'); } else if (contedArg instanceof NativeStrArg) { throw new NQPException('Expected native uint64 argument, but got str'); } const arg = contedArg.$$decont(ctx); if (arg instanceof NQPInt) { return asIntN.asUintN(64, JSBI.BigInt(arg.value)); } else if (arg.$$getUint64) { return arg.$$getUint64(); } else { throw new NQPException('Expected native uint64 argument, but got something else'); } }; exports.arg_n = function(ctx, contedArg) { if (contedArg instanceof NativeNumArg) { return contedArg.value; } else if (contedArg instanceof NativeIntArg) { throw new NQPException('Expected native num argument, but got int'); } else if (contedArg instanceof NativeStrArg) { throw new NQPException('Expected native num argument, but got str'); } const arg = contedArg.$$decont(ctx); if (arg.$$getNum) { return arg.$$getNum(); } else { throw new NQPException('Expected native num argument, but got something else'); } }; exports.arg_s = function(ctx, contedArg) { if (contedArg instanceof NativeStrArg) { return contedArg.value; } else if (contedArg instanceof NQPStr) { return contedArg.value; } else if (contedArg instanceof NativeIntArg) { throw new NQPException('Expected native str argument, but got int'); } else if (contedArg instanceof NativeNumArg) { throw new NQPException('Expected native str argument, but got num'); } const arg = contedArg.$$decont(ctx); if (typeof arg === 'string') { return arg; } else if (arg.$$getStr) { return arg.$$getStr(); } else { throw new NQPException('Expected native str argument, but got something else'); } }; exports.missingNamed = function(name) { throw new NQPException(`Required named parameter '${name}' not passed`); }; const chunkNamesToTypes = { T_OBJ: 0, T_INT: 1, T_NUM: 2, T_STR: 3, T_BOOL: 4, T_CALL_ARG: 5, T_INT16: 6, T_INT8: 7, T_RETVAL: 8, T_UINT16: 9, T_UINT8: 10, T_UINT32: 11, T_INT64: 12, T_UINT64: 13, T_VOID: -1, T_NONVAL: -2, T_ARGS: -3, T_ARGS_ARRAY: -4, }; const chunkTypesToNames = {}; for (const name of Object.keys(chunkNamesToTypes)) { chunkTypesToNames[chunkNamesToTypes[name]] = name; } exports.coercion = function(got, expected) { throw new Error('Can\'t convert, got: ' + chunkTypesToNames[got] + ' expected:' + chunkTypesToNames[expected]); }; exports.charrange_i = function(char, lower, upper) { return ( lower <= char.toLowerCase().charCodeAt(0) && char.toLowerCase().charCodeAt(0) <= upper ) || ( lower <= char.toUpperCase().charCodeAt(0) && char.toUpperCase().charCodeAt(0) <= upper ); }; exports.charrange_m = function(char, lower, upper) { const codePoint = stripMarks(char).codePointAt(0); return (lower <= codePoint && codePoint <= upper); }; exports.charrange_im = function(char, lower, upper) { const stripped = stripMarks(char); return ( lower <= stripped.toLowerCase().codePointAt(0) && stripped.toLowerCase().codePointAt(0) <= upper ) || ( lower <= stripped.toUpperCase().codePointAt(0) && stripped.toUpperCase().codePointAt(0) <= upper ); }; // TODO - optimize function fuzzyMatch(fuzzy, target, pos, literal) { let end = pos; let result = -1; let matched = ''; const foldedLiteral = fuzzy(literal); while (foldedLiteral.startsWith(matched)) { if (matched === foldedLiteral) { result = end - pos; } if (end === target.length) break; end = graphemes.nextBreak(target, end); matched = fuzzy(target.substring(pos, end)); } return result; } exports.literal_i = function(target, pos, literal) { return fuzzyMatch(foldCase, target, pos, literal); }; exports.literal_m = function(target, pos, literal) { return fuzzyMatch(stripMarks, target, pos, literal); }; exports.literal_im = function(target, pos, literal) { return fuzzyMatch(string => foldCase(stripMarks(string)), target, pos, literal); }; exports.literal = function(target, pos, literal) { if (target.substr(pos, literal.length) == literal) { if (graphemes.graphemeBoundary(target, pos + literal.length)) { return literal.length; } else { return -1; } } else { return -1; } }; // TODO astral characters, multi character graphemes exports.enumcharlist_m = function(negate, target, pos, charlist) { if (pos >= target.length) return -1; const found = charlist.indexOf(stripMarks(target.substr(pos, 1))) != -1; if (negate) { return found ? -1 : 1; } else { return found ? 1 : -1; } }; exports.enumcharlist = function(negate, target, pos, charlist, zerowidth) { if (pos >= target.length) return (zerowidth && negate ? 0 : -1); const graphemeEnd = graphemes.nextBreak(target, pos); const found = charlist.indexOf(target.substring(pos, graphemeEnd)) != -1; if (negate ? !found : found) { return (graphemeEnd - pos); } else { return -1; } }; exports.nextGrapheme = graphemes.nextBreak; exports.noNamed = function(_NAMED) { if (Object.keys(_NAMED) != 0) { throw new NQPException(`Unexpected named argument ${Object.keys(_NAMED)[0]} passed`); } }; exports.checkNamed = function(known, _NAMED) { for (const named in _NAMED) { if (!known[named]) { throw new NQPException(`Unexpected named argument ${named} passed`); } } }; const props = require('./unicode-props.js'); for (const prop in props) { exports[prop] = props[prop]; } exports.buildSourceMap = core.buildSourceMap; exports.createSourceMap = core.createSourceMap; exports.ZERO = JSBI.BigInt(0); exports.asIntN = asIntN.asIntN; exports.asUintN = asIntN.asUintN; exports.BigInt = JSBI.BigInt; module.exports.freshGlobalContext = (setup) => globalContext.freshGlobalContext(setup); module.exports.setGlobalContext = (context) => globalContext.setGlobalContext(context); module.exports.saveThisGlobalContext = (callback) => globalContext.saveThisGlobalContext(callback); module.exports.restoreThisGlobalContext = (callback) => globalContext.restoreThisGlobalContext(callback); exports.loadCompileTimeDependency = /*async*/ function(unit) { const fakeModule = {}; unit(fakeModule); /*await*/ fakeModule.exports(module.exports, false); };
import axios from 'axios'; import getConfig from 'next/config'; import ApiError from './api.error'; const { publicRuntimeConfig: { apiUrl }, } = getConfig(); // Do not throw errors on 'bad' server response codes axios.interceptors.response.use(axiosConfig => axiosConfig, error => error.response); const generalError = { general: ['Unexpected Error Occurred'] }; const throwApiError = ({ data, status }) => { console.error('API: Error Ocurred', status, data); //eslint-disable-line throw new ApiError(data, status); }; const httpRequest = method => async (url, data) => { let options = {}; if (data) { if (method === 'get') { options.params = data; } else { options = data; } } let urlWithSlash = url; if (urlWithSlash[0] !== '/') { urlWithSlash = `/${urlWithSlash}`; } const response = await axios[method](`${apiUrl}${urlWithSlash}`, options); if (response.status >= 200 && response.status < 300) { return response.data || { }; } if (response.status === 400) { throwApiError(response); } throwApiError({ errors: [generalError] }); return null; }; export const getRequest = httpRequest('get'); export const postRequest = httpRequest('post'); export const putRequest = httpRequest('put'); export const deleteRequest = httpRequest('delete'); const apiClient = { get: getRequest, post: postRequest, put: putRequest, delete: deleteRequest, }; export default apiClient;
'use strict'; var common = require('./common'); // copy relevant convienient constants var config = require('../config'); var SATOSHI_FACTOR = config.SATOSHI_FACTOR; var FUDGE_FACTOR = config.FUDGE_FACTOR; exports.sendBitcoins = function (address, satoshis, fee, callback) { var amount = (satoshis / SATOSHI_FACTOR).toFixed(8); common.authRequest('bitcoinWithdrawal', { amount: amount, address: address }, function(err, response) { if (err) return callback(err); if (response.error) return callback(processError(response)); callback(null, response.data.toString()); }); }; exports.newAddress = function (info, callback) { common.authRequest('bitcoinDepositAddresses', null, function(err, response) { if (err) return callback(err); if (response.error) return callback(processError(response)); if (Object.keys(response.data).length > 0) { callback(null, response.data[0]); } else { callback(null, new Error('No deposit addresses!')); } }); }; function processError(response) { var error = response.errorMessage; var err = new Error(error); return err; }
dojo._xdResourceLoaded({ depends: [["provide", "dojox.charting.scaler"]], defineResource: function(dojo){if(!dojo._hasResource["dojox.charting.scaler"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojox.charting.scaler"] = true; dojo.provide("dojox.charting.scaler"); (function(){ var deltaLimit = 3; // pixels var isText = function(val, text){ val = val.toLowerCase(); for(var i = 0; i < text.length; ++i){ if(val == text[i]){ return true; } } return false; }; var calcTicks = function(min, max, kwArgs, majorTick, minorTick, microTick, span){ kwArgs = dojo.clone(kwArgs); if(!majorTick){ if(kwArgs.fixUpper == "major"){ kwArgs.fixUpper = "minor"; } if(kwArgs.fixLower == "major"){ kwArgs.fixLower = "minor"; } } if(!minorTick){ if(kwArgs.fixUpper == "minor"){ kwArgs.fixUpper = "micro"; } if(kwArgs.fixLower == "minor"){ kwArgs.fixLower = "micro"; } } if(!microTick){ if(kwArgs.fixUpper == "micro"){ kwArgs.fixUpper = "none"; } if(kwArgs.fixLower == "micro"){ kwArgs.fixLower = "none"; } } var lowerBound = isText(kwArgs.fixLower, ["major"]) ? Math.floor(min / majorTick) * majorTick : isText(kwArgs.fixLower, ["minor"]) ? Math.floor(min / minorTick) * minorTick : isText(kwArgs.fixLower, ["micro"]) ? Math.floor(min / microTick) * unit : min, upperBound = isText(kwArgs.fixUpper, ["major"]) ? Math.ceil(max / majorTick) * majorTick : isText(kwArgs.fixUpper, ["minor"]) ? Math.ceil(max / minorTick) * minorTick : isText(kwArgs.fixUpper, ["unit"]) ? Math.ceil(max / unit) * unit : max, majorStart = (isText(kwArgs.fixLower, ["major"]) || !majorTick) ? lowerBound : Math.ceil(lowerBound / majorTick) * majorTick, minorStart = (isText(kwArgs.fixLower, ["major", "minor"]) || !minorTick) ? lowerBound : Math.ceil(lowerBound / minorTick) * minorTick, microStart = (isText(kwArgs.fixLower, ["major", "minor", "micro"]) || ! microTick) ? lowerBound : Math.ceil(lowerBound / microTick) * microTick, majorCount = !majorTick ? 0 : (isText(kwArgs.fixUpper, ["major"]) ? Math.round((upperBound - majorStart) / majorTick) : Math.floor((upperBound - majorStart) / majorTick)) + 1, minorCount = !minorTick ? 0 : (isText(kwArgs.fixUpper, ["major", "minor"]) ? Math.round((upperBound - minorStart) / minorTick) : Math.floor((upperBound - minorStart) / minorTick)) + 1, microCount = !microTick ? 0 : (isText(kwArgs.fixUpper, ["major", "minor", "micro"]) ? Math.round((upperBound - microStart) / microTick) : Math.floor((upperBound - microStart) / microTick)) + 1, minorPerMajor = minorTick ? Math.round(majorTick / minorTick) : 0, microPerMinor = microTick ? Math.round(minorTick / microTick) : 0, majorPrecision = majorTick ? Math.floor(Math.log(majorTick) / Math.LN10) : 0, minorPrecision = minorTick ? Math.floor(Math.log(minorTick) / Math.LN10) : 0, scale = span / (upperBound - lowerBound); if(!isFinite(scale)){ scale = 1; } return { bounds: { lower: lowerBound, upper: upperBound }, major: { tick: majorTick, start: majorStart, count: majorCount, prec: majorPrecision }, minor: { tick: minorTick, start: minorStart, count: minorCount, prec: minorPrecision }, micro: { tick: microTick, start: microStart, count: microCount, prec: 0 }, minorPerMajor: minorPerMajor, microPerMinor: microPerMinor, scale: scale }; }; dojox.charting.scaler = function(min, max, span, kwArgs){ var h = {fixUpper: "none", fixLower: "none", natural: false}; if(kwArgs){ if("fixUpper" in kwArgs){ h.fixUpper = String(kwArgs.fixUpper); } if("fixLower" in kwArgs){ h.fixLower = String(kwArgs.fixLower); } if("natural" in kwArgs){ h.natural = Boolean(kwArgs.natural); } } if(max <= min){ return calcTicks(min, max, h, 0, 0, 0, span); // Object } var mag = Math.floor(Math.log(max - min) / Math.LN10), major = kwArgs && ("majorTick" in kwArgs) ? kwArgs.majorTick : Math.pow(10, mag), minor = 0, micro = 0, ticks; // calculate minor ticks if(kwArgs && ("minorTick" in kwArgs)){ minor = kwArgs.minorTick; }else{ do{ minor = major / 10; if(!h.natural || minor > 0.9){ ticks = calcTicks(min, max, h, major, minor, 0, span); if(ticks.scale * ticks.minor.tick > deltaLimit){ break; } } minor = major / 5; if(!h.natural || minor > 0.9){ ticks = calcTicks(min, max, h, major, minor, 0, span); if(ticks.scale * ticks.minor.tick > deltaLimit){ break; } } minor = major / 2; if(!h.natural || minor > 0.9){ ticks = calcTicks(min, max, h, major, minor, 0, span); if(ticks.scale * ticks.minor.tick > deltaLimit){ break; } } return calcTicks(min, max, h, major, 0, 0, span); // Object }while(false); } // calculate micro ticks if(kwArgs && ("microTick" in kwArgs)){ micro = kwArgs.microTick; ticks = calcTicks(min, max, h, major, minor, micro, span); }else{ do{ micro = minor / 10; if(!h.natural || micro > 0.9){ ticks = calcTicks(min, max, h, major, minor, micro, span); if(ticks.scale * ticks.micro.tick > deltaLimit){ break; } } micro = minor / 5; if(!h.natural || micro > 0.9){ ticks = calcTicks(min, max, h, major, minor, micro, span); if(ticks.scale * ticks.micro.tick > deltaLimit){ break; } } micro = minor / 2; if(!h.natural || micro > 0.9){ ticks = calcTicks(min, max, h, major, minor, micro, span); if(ticks.scale * ticks.micro.tick > deltaLimit){ break; } } micro = 0; }while(false); } return micro ? ticks : calcTicks(min, max, h, major, minor, 0, span); // Object }; })(); } }});
/* global location */ import React, { Suspense } from 'react' import ReactDOM from 'react-dom' import HeadManager from './head-manager' import { createRouter, makePublicRouterInstance } from 'next/router' import mitt from '../next-server/lib/mitt' import { loadGetInitialProps, getURL, SUPPORTS_PERFORMANCE_USER_TIMING } from '../next-server/lib/utils' import PageLoader from './page-loader' import * as envConfig from '../next-server/lib/runtime-config' import { HeadManagerContext } from '../next-server/lib/head-manager-context' import { DataManagerContext } from '../next-server/lib/data-manager-context' import { RouterContext } from '../next-server/lib/router-context' import { DataManager } from '../next-server/lib/data-manager' import { parse as parseQs, stringify as stringifyQs } from 'querystring' import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic' // Polyfill Promise globally // This is needed because Webpack's dynamic loading(common chunks) code // depends on Promise. // So, we need to polyfill it. // See: https://webpack.js.org/guides/code-splitting/#dynamic-imports if (!window.Promise) { window.Promise = Promise } const data = JSON.parse(document.getElementById('__NEXT_DATA__').textContent) window.__NEXT_DATA__ = data export const version = process.env.__NEXT_VERSION const { props, err, page, query, buildId, assetPrefix, runtimeConfig, dynamicIds } = data const d = JSON.parse(window.__NEXT_DATA__.dataManager) export const dataManager = new DataManager(d) const prefix = assetPrefix || '' // With dynamic assetPrefix it's no longer possible to set assetPrefix at the build time // So, this is how we do it in the client side at runtime __webpack_public_path__ = `${prefix}/_next/` //eslint-disable-line // Initialize next/config with the environment configuration envConfig.setConfig({ serverRuntimeConfig: {}, publicRuntimeConfig: runtimeConfig || {} }) const asPath = getURL() const pageLoader = new PageLoader(buildId, prefix) const register = ([r, f]) => pageLoader.registerPage(r, f) if (window.__NEXT_P) { window.__NEXT_P.map(register) } window.__NEXT_P = [] window.__NEXT_P.push = register const headManager = new HeadManager() const appElement = document.getElementById('__next') let lastAppProps let webpackHMR export let router export let ErrorComponent let Component let App class Container extends React.Component { componentDidCatch (err, info) { this.props.fn(err, info) } componentDidMount () { this.scrollToHash() // If page was exported and has a querystring // If it's a dynamic route or has a querystring if ( data.nextExport && (isDynamicRoute(router.pathname) || location.search || data.skeleton) ) { // update query on mount for exported pages router.replace( router.pathname + '?' + stringifyQs({ ...router.query, ...parseQs(location.search.substr(1)) }), asPath, { // WARNING: `_h` is an internal option for handing Next.js // client-side hydration. Your app should _never_ use this property. // It may change at any time without notice. _h: 1 } ) } } componentDidUpdate () { this.scrollToHash() } scrollToHash () { let { hash } = location hash = hash && hash.substring(1) if (!hash) return const el = document.getElementById(hash) if (!el) return // If we call scrollIntoView() in here without a setTimeout // it won't scroll properly. setTimeout(() => el.scrollIntoView(), 0) } render () { return this.props.children } } export const emitter = mitt() export default async ({ webpackHMR: passedWebpackHMR } = {}) => { // This makes sure this specific lines are removed in production if (process.env.NODE_ENV === 'development') { webpackHMR = passedWebpackHMR } App = await pageLoader.loadPage('/_app') let initialErr = err try { Component = await pageLoader.loadPage(page) if (process.env.NODE_ENV !== 'production') { const { isValidElementType } = require('react-is') if (!isValidElementType(Component)) { throw new Error( `The default export is not a React Component in page: "${page}"` ) } } } catch (error) { // This catches errors like throwing in the top level of a module initialErr = error } if (window.__NEXT_PRELOADREADY) { await window.__NEXT_PRELOADREADY(dynamicIds) } // if auto prerendered and dynamic route wait to update asPath // until after mount to prevent hydration mismatch const initialAsPath = isDynamicRoute(page) && data.nextExport ? page : asPath router = createRouter(page, query, initialAsPath, { initialProps: props, pageLoader, App, Component, wrapApp, err: initialErr, subscription: ({ Component, props, err }, App) => { render({ App, Component, props, err, emitter }) } }) const renderCtx = { App, Component, props, err: initialErr, emitter } render(renderCtx) return emitter } export async function render (props) { if (props.err) { await renderError(props) return } try { await doRender(props) } catch (err) { await renderError({ ...props, err }) } } // This method handles all runtime and debug errors. // 404 and 500 errors are special kind of errors // and they are still handle via the main render method. export async function renderError (props) { const { App, err } = props // In development runtime errors are caught by react-error-overlay // In production we catch runtime errors using componentDidCatch which will trigger renderError if (process.env.NODE_ENV !== 'production') { return webpackHMR.reportRuntimeError(webpackHMR.prepareError(err)) } // Make sure we log the error to the console, otherwise users can't track down issues. console.error(err) ErrorComponent = await pageLoader.loadPage('/_error') // In production we do a normal render with the `ErrorComponent` as component. // If we've gotten here upon initial render, we can use the props from the server. // Otherwise, we need to call `getInitialProps` on `App` before mounting. const AppTree = wrapApp(App) const appCtx = { Component: ErrorComponent, AppTree, router, ctx: { err, pathname: page, query, asPath, AppTree } } const initProps = props.props ? props.props : await loadGetInitialProps(App, appCtx) await doRender({ ...props, err, Component: ErrorComponent, props: initProps }) } // If hydrate does not exist, eg in preact. let isInitialRender = typeof ReactDOM.hydrate === 'function' function renderReactElement (reactEl, domEl) { // mark start of hydrate/render if (SUPPORTS_PERFORMANCE_USER_TIMING) { performance.mark('beforeRender') } // The check for `.hydrate` is there to support React alternatives like preact if (isInitialRender) { ReactDOM.hydrate(reactEl, domEl, markHydrateComplete) isInitialRender = false } else { ReactDOM.render(reactEl, domEl, markRenderComplete) } } function markHydrateComplete () { if (!SUPPORTS_PERFORMANCE_USER_TIMING) return performance.mark('afterHydrate') // mark end of hydration performance.measure( 'Next.js-before-hydration', 'navigationStart', 'beforeRender' ) performance.measure('Next.js-hydration', 'beforeRender', 'afterHydrate') clearMarks() } function markRenderComplete () { if (!SUPPORTS_PERFORMANCE_USER_TIMING) return performance.mark('afterRender') // mark end of render const navStartEntries = performance.getEntriesByName('routeChange', 'mark') if (!navStartEntries.length) { return } performance.measure( 'Next.js-route-change-to-render', navStartEntries[0].name, 'beforeRender' ) performance.measure('Next.js-render', 'beforeRender', 'afterRender') clearMarks() } function clearMarks () { ;['beforeRender', 'afterHydrate', 'afterRender', 'routeChange'].forEach( mark => performance.clearMarks(mark) ) /* * TODO: uncomment the following line when we have a way to * expose this to user code. */ // performance.clearMeasures() } function AppContainer ({ children }) { return ( <Container fn={error => renderError({ App, err: error }).catch(err => console.error('Error rendering page: ', err) ) } > <Suspense fallback={<div>Loading...</div>}> <RouterContext.Provider value={makePublicRouterInstance(router)}> <DataManagerContext.Provider value={dataManager}> <HeadManagerContext.Provider value={headManager.updateHead}> {children} </HeadManagerContext.Provider> </DataManagerContext.Provider> </RouterContext.Provider> </Suspense> </Container> ) } const wrapApp = App => props => { const appProps = { ...props, Component, err, router } return ( <AppContainer> <App {...appProps} /> </AppContainer> ) } async function doRender ({ App, Component, props, err }) { // Usual getInitialProps fetching is handled in next/router // this is for when ErrorComponent gets replaced by Component by HMR if ( !props && Component && Component !== ErrorComponent && lastAppProps.Component === ErrorComponent ) { const { pathname, query, asPath } = router const AppTree = wrapApp(App) const appCtx = { router, AppTree, Component: ErrorComponent, ctx: { err, pathname, query, asPath, AppTree } } props = await loadGetInitialProps(App, appCtx) } Component = Component || lastAppProps.Component props = props || lastAppProps.props const appProps = { ...props, Component, err, router } // lastAppProps has to be set before ReactDom.render to account for ReactDom throwing an error. lastAppProps = appProps emitter.emit('before-reactdom-render', { Component, ErrorComponent, appProps }) // We catch runtime errors using componentDidCatch which will trigger renderError renderReactElement( <AppContainer> <App {...appProps} /> </AppContainer>, appElement ) emitter.emit('after-reactdom-render', { Component, ErrorComponent, appProps }) }
game.resources = [ /* Graphics. * @example * {name: "example", type:"image", src: "data/img/example.png"}, */ {name: "background-tiles", type:"image", src: "data/img/background-tiles.png"}, {name: "meta-tiles", type:"image", src: "data/img/meta-tiles.png"}, {name: "player", type:"image", src: "data/img/orcSpear.png"}, {name: "tower", type:"image", src: "data/img/tower_round.svg.png"}, {name: "creep1", type:"image", src: "data/img/brainmonster.png"}, {name: "title-screen", type:"image", src: "data/img/title.png"}, {name: "exp-screen", type:"image", src: "data/img/loadpic.png"}, {name: "load-screen", type:"image", src: "data/img/loadpic.png"}, {name: "gold-screen", type:"image", src: "data/img/spend.png"}, {name: "load-screen", type:"image", src: "data/img/loadpic.png"}, {name: "new-screen", type:"image", src: "data/img/newpic.png"}, {name: "minimap", type:"image", src: "data/img/juniorminimap.png"}, /* Atlases * @example * {name: "example_tps", type: "tps", src: "data/img/example_tps.json"}, */ /* Maps. * @example * {name: "example01", type: "tmx", src: "data/map/example01.tmx"}, * {name: "example01", type: "tmx", src: "data/map/example01.json"}, */ {name: "level01", type: "tmx", src: "data/map/test.tmx"}, /* Background music. * @example * {name: "example_bgm", type: "audio", src: "data/bgm/"}, */ /* Sound effects. * @example * {name: "example_sfx", type: "audio", src: "data/sfx/"} */ ];
import React, { Component } from 'react'; import { Container,Row,Col,Image } from 'react-bootstrap'; import { Link, StaticQuery, graphql } from 'gatsby' import banner1 from '../../images/home-section-4-img-2.png' import AboutScreen2 from '../AboutScreen/AboutScreen2' import AboutScreen2Heading from '../AboutScreen/AboutScreen2Heading' class Aboutsection2 extends Component { render() { return ( <> <section className="about-section-2"> <Container> <div className="title"> <AboutScreen2Heading/> </div> <Row> <AboutScreen2/> </Row> </Container> </section> </> ); } } export default Aboutsection2;
module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/recommended', 'prettier/@typescript-eslint', 'plugin:prettier/recommended', ], root: true, env: { node: true, jest: true, }, ignorePatterns: ['.eslintrc.js'], rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/explicit-module-boundary-types': 'off', '@typescript-eslint/no-explicit-any': 'off', "quotes": [2, "double", { "avoidEscape": true }] }, };
import React from 'react'; const Header = props => { return ( <nav className="navbar navbar-expand-sm navbar-dark bg-primary mb-3"> <div className="container"> <a className="navbar-brand" href="/"> React App </a> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" > <span className="navbar-toggler-icon" /> </button> <div className="collapse navbar-collapse" id="navbarNav"> <ul className="navbar-nav mr-auto"> <li className="nav-item"> <a className="nav-link" href="/"> Home </a> </li> <li className="nav-item"> <a className="nav-link" href="/about"> About </a> </li> </ul> <ul className="navbar-nav ml-auto"> <li className="nav-item"> <a href="/manage-orders" className="nav-link"> Orders </a> </li> <li className="nav-item"> <a href="/add-order" className="nav-link"> Add Order </a> </li> <li className="nav-item"> <a href="/login" className="nav-link"> Login </a> </li> <li className="nav-item"> <a href="/register" className="nav-link"> Register </a> </li> </ul> </div> </div> </nav> ); // you can access values passed to this component with props }; export default Header;
// @ts-check var fs = require('fs'); var path = require('./path'); var { warnn, logn, infon, debugn, errorn } = require('./log'); class AppDelegateLinker { constructor() { this.appDelegatePath = path.appDelegate; this.removeUnneededImportsSuccess = false; this.removeApplicationLaunchContentSuccess = false; } link() { if (!this.appDelegatePath) { errorn( ' AppDelegate not found! Does the file exist in the correct folder?\n Please check the manual installation docs:\n https://wix.github.io/react-native-navigation/docs/installing#native-installation' ); return; } logn('Linking AppDelegate...'); var appDelegateContents = fs.readFileSync(this.appDelegatePath, 'utf8'); try { appDelegateContents = this._removeUnneededImports(appDelegateContents); this.removeUnneededImportsSuccess = true; } catch (e) { errorn(' ' + e.message); } appDelegateContents = this._importNavigation(appDelegateContents); appDelegateContents = this._bootstrapNavigation(appDelegateContents); appDelegateContents = this._extraModulesForBridge(appDelegateContents); try { appDelegateContents = this._removeApplicationLaunchContent(appDelegateContents); this.removeApplicationLaunchContentSuccess = true; } catch (e) { errorn(' ' + e.message); } fs.writeFileSync(this.appDelegatePath, appDelegateContents); if (this.removeUnneededImportsSuccess && this.removeApplicationLaunchContentSuccess) { infon('AppDelegate linked successfully!\n'); } else { warnn( 'AppDelegate was partially linked, please check the details above and proceed with the manual installation documentation to complete the linking process.!\n' ); } } _removeUnneededImports(content) { debugn(' Removing Unneeded imports'); const unneededImports = [/#import\s+\<React\/RCTRootView.h>\s/]; let elementsRemovedCount = 0; unneededImports.forEach((unneededImport) => { if (unneededImport.test(content)) { content = content.replace(unneededImport, ''); elementsRemovedCount++; } }); if (unneededImports.length === elementsRemovedCount) { debugn(' All imports have been removed'); } else if (elementsRemovedCount === 0) { warnn( ' No imports could be removed. Check the manual installation docs to verify that everything is properly setup:\n https://wix.github.io/react-native-navigation/docs/installing#native-installation' ); } else { throw new Error( 'Some imports were removed. Check the manual installation docs to verify that everything is properly setup:\n https://wix.github.io/react-native-navigation/docs/installing#native-installation' ); } return content; } _importNavigation(content) { if (!this._doesImportNavigation(content)) { debugn(' Importing ReactNativeNavigation.h'); return content.replace( /#import\s+"AppDelegate.h"/, '#import "AppDelegate.h"\n#import <ReactNativeNavigation/ReactNativeNavigation.h>' ); } warnn(' AppDelegate already imports ReactNativeNavigation.h'); return content; } _bootstrapNavigation(content) { if (this._doesBootstrapNavigation(content)) { warnn(' Navigation Bootstrap already present.'); return content; } debugn(' Bootstrapping Navigation'); return content.replace( /RCTBridge.*];/, '[ReactNativeNavigation bootstrapWithDelegate:self launchOptions:launchOptions];' ); } _doesBootstrapNavigation(content) { return /ReactNativeNavigation\s+bootstrap/.test(content); } _extraModulesForBridge(content) { if (this._doesImplementsRNNExtraModulesForBridge(content)) { warnn(' extraModulesForBridge already present.'); return content; } else if (this._doesImplementsExtraModulesForBridge(content)) { throw new Error( 'extraModulesForBridge implemented for a different module and needs manual linking. Check the manual installation docs to verify that everything is properly setup:\n https://wix.github.io/react-native-navigation/docs/installing#native-installation' ); } debugn(' Implementing extraModulesForBridge'); return content.replace( /-.*\(NSURL.*\*\)sourceURLForBridge:\(RCTBridge.*\*\)bridge/, '- (NSArray<id<RCTBridgeModule>> *)extraModulesForBridge:(RCTBridge *)bridge {\n\ return [ReactNativeNavigation extraModulesForBridge:bridge];\n\ }\n\ \n\ - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge' ); } _doesImplementsExtraModulesForBridge(content) { return /-.*\(NSArray.*\*\)extraModulesForBridge:\(RCTBridge.*\*\)bridge/.test(content); } _doesImplementsRNNExtraModulesForBridge(content) { return /ReactNativeNavigation\s+extraModulesForBridge/.test(content); } _removeApplicationLaunchContent(content) { debugn(' Removing Application launch content'); const toRemove = [ /RCTRootView\s+\*rootView((.|\r|\s)*?)];\s+/, /if \(@available\(iOS 13\.0, \*\)\)\s{\s+ rootView.backgroundColor((.|\r)*)];\s+}\s+else {[^}]*}/, /self.window((.|\r)*)];\s+/, /UIViewController\s\*rootViewController((.|\r)*)];\s+/, /rootViewController\.view\s+=\s+rootView;\s+/, /self.window.rootViewController\s+=\s+rootViewController;\s+/, /\[self.window\s+makeKeyAndVisible];\s+/, ]; let elementsRemovedCount = 0; toRemove.forEach((element) => { if (element.test(content)) { content = content.replace(element, ''); elementsRemovedCount++; } }); if (toRemove.length === elementsRemovedCount) { debugn(' Application Launch content has been removed'); } else if (elementsRemovedCount === 0) { warnn( ' No elements could be removed. Check the manual installation docs to verify that everything is properly setup:\n https://wix.github.io/react-native-navigation/docs/installing#native-installation' ); } else { throw new Error( 'Some elements were removed. Check the manual installation docs to verify that everything is properly setup:\n https://wix.github.io/react-native-navigation/docs/installing#native-installation' ); } return content; } _doesImportNavigation(content) { return /#import\s+\<ReactNativeNavigation\/ReactNativeNavigation.h>/.test(content); } } module.exports = AppDelegateLinker;
const Stats = ({ stats, size }) => { if (Object.keys(stats).length === 0) return null const items = [ { name: 'Model Size', stat: size }, { name: 'Meshes', stat: stats.meshes.properties.length }, stats.faces === Number && { name: 'Faces', stat: stats.faces, }, { name: 'Vertices', stat: stats.vertices === Number ? stats.vertices : stats.vertices.vertices, }, { name: 'Textures', stat: stats.textures.properties.length }, stats.textures.properties.length ? { name: 'Texture Size', stat: stats.textures.properties[0].resolution, } : null, { name: 'Animations', stat: stats.animations.properties.length }, { name: 'Skinned', stat: stats.skinned }, stats.extensions ? { name: 'Extensions Required', stat: stats.extensions.join(', '), small: true, } : null, { name: 'Memory Consumption', stat: `~${stats.memoryConsumption}` }, ].filter((e) => e) return ( <div> <h3 className='text-lg font-medium text-gray-900 leading-6'> Model Stats </h3> <dl className='mt-5 grid grid-cols-1 gap-5 sm:grid-cols-5'> {items.map((item) => ( <div key={item.name} className='px-4 py-5 overflow-hidden bg-transparent rounded-lg shadow dark:border dark:border-gray-800 sm:p-6' > <dt className='text-sm font-medium text-gray-500 truncate'> {item.name} </dt> <dd className={`${ item.small ? `text-xs` : `text-3xl` } mt-1 font-semibold text-gray-900`} > {typeof item.stat === 'boolean' ? ( <svg xmlns='http://www.w3.org/2000/svg' className={`h-10 w-10 ${ item.stat ? 'text-green-600' : 'text-red-600' }`} fill='none' viewBox='0 0 24 24' stroke='currentColor' > {item.stat ? ( <path strokeLinecap='round' strokeLinejoin='round' strokeWidth={2} d='M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' /> ) : ( <path strokeLinecap='round' strokeLinejoin='round' strokeWidth={2} d='M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z' /> )} </svg> ) : ( item.stat )} </dd> </div> ))} </dl> </div> ) } export default Stats
// flow-typed signature: 6ff3f9327aea1e7e79d4967cafb49b1f // flow-typed version: <<STUB>>/home-dir_v^1.0.0/flow_v0.37.0 /** * This is an autogenerated libdef stub for: * * 'home-dir' * * Fill this stub out by replacing all the `any` types. * * Once filled out, we encourage you to share your work with the * community by sending a pull request to: * https://github.com/flowtype/flow-typed */ declare module 'home-dir' { declare module.exports: any; } /** * We include stubs for each file inside this npm package in case you need to * require those files directly. Feel free to delete any files that aren't * needed. */ // Filename aliases declare module 'home-dir/index' { declare module.exports: $Exports<'home-dir'>; } declare module 'home-dir/index.js' { declare module.exports: $Exports<'home-dir'>; }
import { createGlobalStyle } from 'styled-components' const GlobalStyle = createGlobalStyle` html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font-family: inherit; vertical-align: baseline; } article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { display: block; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote::before, blockquote::after, q::before, q::after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } * { box-sizing: border-box; } /* Site Specific Globals */ @import url('https://fonts.googleapis.com/css?family=Raleway:100,200,300,400,500,600,700,800,900'); body { background: white; color: white; line-height: 1; font-variant-ligatures: none; -moz-osx-font-smoothing: grayscale; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; text-shadow: rgba(0, 0, 0, .01) 0 0 1px; font-weight: 400; font-family: 'Raleway', sans-serif; } img { display: block; width: 100%; height: auto; } a { text-decoration: none; color: #121212; } /* NProgress stles */ .nprogress-busy { cursor: wait; } #nprogress .peg { display: none !important; } #nprogress .bar { height: 4px !important; } /* React Headroom */ .headroom { background-color: #fff; height: 65px; left: 0; margin: auto; max-width: none; padding: 0; position: fixed; right: 0; top: 0; transform: translateY(0%); transition: transform 0.25s ease-in, max-width 0.25s ease-in; z-index: 5; } .headroom--unfixed { position: fixed; transform: translateY(0%); transition: none; } .headroom--unpinned { position: fixed; transform: translateY(-100%); } .headroom--pinned { position: fixed; transform: translateY(0%); } /* Web Accessibility Stuff */ body:not(.user-is-tabbing) button:focus, body:not(.user-is-tabbing) input:focus, body:not(.user-is-tabbing) select:focus, body:not(.user-is-tabbing) textarea:focus, body:not(.user-is-tabbing) a:focus { outline: none; } button, input, textarea, select { color: #121212; font-family: inherit; font-size: inherit; background: none; border: none; appearance: none; border-radius: 0; resize: none; &:invalid { box-shadow: none; } &:focus { outline: 3px solid #497ecb; } } a:focus { outline: 3px solid #497ecb; } ` export default GlobalStyle
import React from "react" import { graphql, withPrefix } from "gatsby" import styles from "../pages/index.module.css" import Logo from "../components/Logo" import ThemeSwitch from "../components/ThemeSwitch" import "../pages/global.css" import "../pages/article.css" import Footer from "../components/Footer" import { Helmet } from "react-helmet" export default function Template({ data, // this prop will be injected by the GraphQL query below. }) { const { markdownRemark } = data // data.markdownRemark holds your post data const { frontmatter, html } = markdownRemark return ( <div className={`${styles.container}`}> <Helmet> <title>{frontmatter.title} - Oboo Cheng</title> <link rel="icon" href={withPrefix("/favicon.ico")} /> </Helmet> <div className={`${styles.content}`}> <section> <header className={styles.header}> <Logo /> <ThemeSwitch /> </header> <article> <h1>{frontmatter.title}</h1> <div className="blog-post-content" dangerouslySetInnerHTML={{ __html: html }} /> </article> </section> <Footer /> </div> </div> ) } export const pageQuery = graphql` query($slug: String!) { markdownRemark(frontmatter: { slug: { eq: $slug } }) { html frontmatter { date(formatString: "MMMM DD, YYYY") slug title } } } `
var mysql = require('mysql') var connection = mysql.createConnection({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database : process.env.DB_NAME }) connection.connect(); // connection.query('SELECT 1 + 1 AS solution', // function (error, results, fields) { // if(error) throw error; // console.log('The solution is: ', results[0].solution); // }); module.exports = connection;
/* eslint-disable react/no-deprecated */ import React from 'react'; // Containers import Menu from './Menu/Menu'; import Setup from './SetUp/Setup'; import Dashboard from './Dashboard/Dashboard.js'; import Monitors from './Monitors/Monitors'; import Infrastructure from './Infraestructure/Infrastructure'; import Synthetics from './Synthetics/Synthetics'; import Logs from './Logs/Logs'; import Metrics from './Metrics/Metrics'; // services import { deleteSetup, loadAccountId, readNerdStorage, readNerdStorageOnlyCollection, writeNerdStorageReturnData, writeNerdStorage, writeSecretKey, readSingleSecretKey } from '../services/NerdStorage/api'; import { sendLogsSlack } from '../services/Wigilabs/api'; import * as DD from '../services/Datadog/DD'; import * as DS from '../services/Datadog/DS'; import DatadogClient from '../services/Datadog/DatadogClient'; import DatadogService from '../services/Datadog/DatadogService'; import { Spinner, Toast } from 'nr1'; /** * Class that render de content * * @export * @class App * @extends {React.PureComponent} */ export default class App extends React.PureComponent { /** * Constructor for the class * * @param {array} props * @memberof App */ constructor(props) { super(props); this.state = { // CONFIGURATION accountId: null, apiserver: '', apikey: '', apikeyS: '***', appkeyS: '***', appkey: '', setupComplete: false, lastUpdate: '', selectedMenu: 0, loadingContent: true, writingSetup: false, fetchingData: false, hasErrorFetch: false, // DASHBOARDS dataDashboards: [], emptyData: false, // MONITORS monitorsTotal: 0, monitorsGraph: [ { name: 'Host', uv: 0, pv: 0 }, { name: 'Metric', uv: 0, pv: 0 }, { name: 'Anomaly', uv: 0, pv: 0 }, { name: 'Outlier', uv: 0, pv: 0 } ], monitorsData: [], // INFRASTRUCTURE infrastructureDataGraph: [], infraestructureList: [], totalActive: 0, total: 0, // LOGS logsData: { archives: [], pipelines: [], metrics: [], archivesStatus: 0, pipelinesStatus: 0, metricsStatus: 0 }, // Metrics metrics: [], fetchingMetrics: false, progressMetrics: 0, errorMetric: false, historyUpdateMetric: null, // SYNTHETICS testTotal: 0, testList: [], // LogsDashport logs: [], completed: 0, deleteSetup: false, datadogService: null }; } /** * Method called when the component was mounted * * @memberof App */ componentWillMount() { this.setState({ loadingContent: true }); this.loadAccount(); } /** * Method that changes the selected option in menu * * @param {number} value * @memberof App */ handleChangeMenu = value => { const { fetchingData, deleteSetup } = this.state; if (fetchingData) { Toast.showToast({ title: 'WAIT..', description: 'Please wait until the search is over', type: Toast.TYPE.NORMAL }); } else if (deleteSetup) { Toast.showToast({ title: 'WAIT..', description: 'Please wait delete data', type: Toast.TYPE.NORMAL }); } else { this.setState({ selectedMenu: value }); } }; /** * Method that change progress when fetching metrics is active * * @memberof App */ updateProgressMetrics = value => { value = parseInt(value); this.setState({ progressMetrics: value }); }; /** * Method that change the selected menu from other component * * @param {number} value * @memberof App */ ChangeMenuExternal = value => { this.setState({ selectedMenu: value }); }; /** * Method that instance datadog service for fetch metrics * * @param {*} keyApi * @param {*} keyApp * @returns * @memberof App */ createDatadogServiceInstance(keyApi, keyApp, region) { const datadogClient = new DatadogClient( keyApi, keyApp, region, this.reportLogFetch ); return new DatadogService(datadogClient); } /** * Method that load from NerdStorage the information from account * * @memberof App */ async loadAccount() { const accountId = await loadAccountId(); this.setState({ accountId }); const dataSetup = await readNerdStorage( accountId, 'setup', 'datadog', this.reportLogFetch ); if (dataSetup) { let retrys = 0; let keyApi = null; let keyApp = null; const keysName = ['apikey', 'appkey']; while (retrys !== 5) { if (!keyApi) keyApi = await readSingleSecretKey(keysName[0]); if (!keyApp) keyApp = await readSingleSecretKey(keysName[1]); if (keyApi && keyApp) { retrys = 5; } else { retrys += 1; } } if (keyApi && keyApp) { const datadogService = this.createDatadogServiceInstance( keyApi, keyApp, dataSetup.apiserver ); this.setState({ setupComplete: true, apikey: keyApi, apikeyS: dataSetup.apikeyS, appkey: keyApp, appkeyS: dataSetup.appkeyS, apiserver: dataSetup.apiserver, datadogService: datadogService }); const dateFetch = await readNerdStorage( accountId, 'ddFetch', 'dateFetch', this.reportLogFetch ); await this.loadViewData(); if (dateFetch !== null) { this.setState({ lastUpdate: dateFetch.lastUpdate }); } else { this.setState({ lastUpdate: 'never' }); } } else { this.setState({ selectedMenu: 0 }); } } this.setState({ loadingContent: false }); } /** * Method that loads the data from NerdStorage * @memberof App */ async loadViewData() { const { accountId, fetchingData } = this.state; // DASHBOARDS try { const list = []; let emptyData = false; const sizeList = await readNerdStorageOnlyCollection( accountId, 'dashboards', this.reportLogFetch ); for (let i = 0; i < sizeList.length - 1; i++) { const page = await readNerdStorage( accountId, 'dashboards', `dashboards-${i}`, this.reportLogFetch ); if (page) { for (const iterator of page) { list.push(iterator); } } } const dashboardObj = await readNerdStorage( accountId, 'dashboards', `dashboards-obj`, this.reportLogFetch ); if (dashboardObj && dashboardObj.status === 'EMPTY') { emptyData = true; } if (fetchingData) { this.updateProgressFetch(5); } this.setState({ dataDashboards: list, emptyData }); } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove dashboards data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // ALERTS try { const data = await readNerdStorage( accountId, 'monitors', 'monitors-obj', this.reportLogFetch ); if (data) { const sizeMonitors = await readNerdStorageOnlyCollection( accountId, 'monitors-monitors', this.reportLogFetch ); const listMonitors = []; for (let i = 0; i < sizeMonitors.length; i++) { let page = []; page = await readNerdStorage( accountId, 'monitors-monitors', `monitors-${i}`, this.reportLogFetch ); for (const iterator of page) { listMonitors.push(iterator); } } const sizeTypes = await readNerdStorageOnlyCollection( accountId, 'monitors-types', this.reportLogFetch ); const listTypes = []; for (let i = 0; i < sizeTypes.length; i++) { let page = []; page = await readNerdStorage( accountId, 'monitors-types', `monitors-${i}`, this.reportLogFetch ); for (const iterator of page) { listTypes.push(iterator); } } data.data.type = listTypes; data.data.monitors = listMonitors; let total = 0; for (const iterator of data.data.type) { total += iterator.count; } data.data.total = total; const monitorsGraph = []; for (const monitor of data.data.monitors) { const index = monitorsGraph.findIndex( element => element.name === monitor.type ); if (index !== -1) { monitorsGraph[index].uv = monitorsGraph[index].uv + 1; } else { monitorsGraph.push({ name: monitor.type, pv: data.data.monitors.length, uv: 1 }); } } this.setState({ monitorsTotal: data.data.total, monitorsGraph: monitorsGraph, monitorsData: data.data.monitors }); } if (fetchingData) { this.updateProgressFetch(5); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove alerts data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // INFRASTRUCTURE try { const infraestructureObj = await readNerdStorage( accountId, 'infraestructure', 'infraestructure-obj', this.reportLogFetch ); if (infraestructureObj) { const sizeInfraestructure = await readNerdStorageOnlyCollection( accountId, 'infraestructure', this.reportLogFetch ); const hostList = []; for (let i = 0; i < sizeInfraestructure.length - 1; i++) { let page = []; page = await readNerdStorage( accountId, 'infraestructure', `infraestructure-${i}`, this.reportLogFetch ); for (const iterator of page) { hostList.push(iterator); } } const sizeTypes = await readNerdStorageOnlyCollection( accountId, 'infraestructure-types', this.reportLogFetch ); const types = []; for (let i = 0; i < sizeTypes.length; i++) { let page = []; page = await readNerdStorage( accountId, 'infraestructure-types', `infraestructure-types-${i}`, this.reportLogFetch ); for (const iterator of page) { types.push(iterator); } } const { total, totalActive } = infraestructureObj.data; const hostsData = []; for (const type of types) { hostsData.push({ name: type.platform, uv: Math.abs(type.count), pv: Math.abs(total - type.count) }); } this.setState({ infrastructureDataGraph: hostsData, infraestructureList: hostList, totalActive, total }); } if (fetchingData) { this.updateProgressFetch(5); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove infraestructure data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // LOGS try { const archivesStatus = await readNerdStorage( accountId, 'logs', 'logs-archives-obj', this.reportLogFetch ); const sizeArchives = await readNerdStorageOnlyCollection( accountId, 'logs-archives', this.reportLogFetch ); const archives = []; for (let i = 0; i < sizeArchives.length; i++) { let page = []; page = await readNerdStorage( accountId, 'logs-archives', `logs-archives-${i}`, this.reportLogFetch ); for (const iterator of page) { archives.push(iterator); } } // metric log const metricsStatus = await readNerdStorage( accountId, 'logs', 'logs-metrics-obj', this.reportLogFetch ); const sizeMetricLog = await readNerdStorageOnlyCollection( accountId, 'logs-metrics', this.reportLogFetch ); const metricsLogs = []; for (let i = 0; i < sizeMetricLog.length; i++) { let page = []; page = await readNerdStorage( accountId, 'logs-metrics', `logs-metrics-${i}`, this.reportLogFetch ); for (const iterator of page) { metricsLogs.push(iterator); } } // Pipelines const pipelinesStatus = await readNerdStorage( accountId, 'logs', 'logs-pipelines-obj', this.reportLogFetch ); const sizePipelines = await readNerdStorageOnlyCollection( accountId, 'logs-pipelines', this.reportLogFetch ); const pipelines = []; for (let i = 0; i < sizePipelines.length; i++) { let page = []; page = await readNerdStorage( accountId, 'logs-pipelines', `logs-pipelines-${i}`, this.reportLogFetch ); for (const iterator of page) { pipelines.push(iterator); } } this.setState({ logsData: { metrics: metricsLogs, archives: archives, pipelines: pipelines, archivesStatus, pipelinesStatus, metricsStatus } }); if (fetchingData) { this.updateProgressFetch(5); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove logs data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // METRICS try { const metrics = await readNerdStorage( accountId, 'metrics', 'metrics-obj', this.reportLogFetch ); if (metrics) { const sizeMetrics = await readNerdStorageOnlyCollection( accountId, 'metrics', this.reportLogFetch ); const listMetrics = []; for (let j = 0; j < sizeMetrics.length - 1; j++) { let page = []; page = await readNerdStorage( accountId, 'metrics', `metrics-${j}`, this.reportLogFetch ); for (const iterator of page) { listMetrics.push(iterator); } } let historyUpdateMetric = await readNerdStorage( accountId, 'metricsUpdate', 'metricsUpdate', this.reportLogFetch ); if ( historyUpdateMetric && Object.entries(historyUpdateMetric).length === 0 ) historyUpdateMetric = null; metrics.data = listMetrics; this.setState({ metrics: metrics.data, historyUpdateMetric }); } if (fetchingData) { this.updateProgressFetch(5); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove metrics data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } // SYNTHETICS try { const synthetics = await readNerdStorage( accountId, 'synthetics', 'synthetics-obj', this.reportLogFetch ); if (synthetics) { const sizeList = await readNerdStorageOnlyCollection( accountId, 'synthetics-list', this.reportLogFetch ); const listSynthetics = []; for (let i = 0; i < sizeList.length; i++) { let page = []; page = await readNerdStorage( accountId, 'synthetics-list', `synthetics-${i}`, this.reportLogFetch ); for (const iterator of page) { listSynthetics.push(iterator); } } synthetics.list = listSynthetics; if (fetchingData) { this.updateProgressFetch(5); } this.setState({ testTotal: listSynthetics.length, testList: listSynthetics }); } } catch (err) { const response = { message: err.message, type: 'Error', event: `Recove synthetics data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } this.sendLogs(); } /** * Method that read nerdstorage * * @memberof App */ readNerdStorage = async (collection, documentId) => { let result = null; const { accountId } = this.state; await readNerdStorage( accountId, collection, documentId, this.reportLogFetch ).then(data => { result = data; }); return result; }; /** * Method that reads an document on the nerdStorage * @param {String} collection the document id to search * * @memberof App */ readNerdStorageOnlyCollection = async collection => { let result = null; const { accountId } = this.state; await readNerdStorageOnlyCollection( accountId, collection, this.reportLogFetch ).then(data => { result = data; }); return result; }; /** * Method that save data for parser file * * @memberof App */ finalDataWriter = async (collectionName, data) => { const { accountId, completed } = this.state; switch (collectionName) { case 'monitors': { const listMonitors = data.data.monitors; const listTypes = data.data.type; data.data.monitors = []; data.data.type = []; const monitorObj = data; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, monitorObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesMonitors = this.pagesOfData(listMonitors); for (const keyMonitor in pagesMonitors) { if (pagesMonitors[keyMonitor]) { await writeNerdStorage( accountId, `${collectionName}-monitors`, `${collectionName}-${keyMonitor}`, pagesMonitors[keyMonitor], this.reportLogFetch ).catch(err => { throw err; }); } } const pagesTypes = this.pagesOfData(listTypes); for (const keyTypes in pagesTypes) { if (pagesTypes[keyTypes]) { await writeNerdStorage( accountId, `${collectionName}-types`, `${collectionName}-${keyTypes}`, pagesTypes[keyTypes], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'dashboards': { const listDashboards = data.data.list; data.data.list = []; const dashBoardObj = data.data; listDashboards.length > 0 ? (dashBoardObj.status = 'OK') : (dashBoardObj.status = 'EMPTY'); await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, dashBoardObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesDashboards = this.pagesOfData(listDashboards); for (const keyDashboard in pagesDashboards) { if (pagesDashboards[keyDashboard]) { await writeNerdStorage( accountId, collectionName, `${collectionName}-${keyDashboard}`, pagesDashboards[keyDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'infraestructure': { // guardar el objeto // guardar la lista const pagesHost = this.pagesOfData(data.data.hostList); for (const keyHost in pagesHost) { if (pagesHost[keyHost]) { await writeNerdStorage( accountId, collectionName, `${collectionName}-${keyHost}`, pagesHost[keyHost], this.reportLogFetch ).catch(err => { throw err; }); } } data.data.hostList = []; const pagesTypes = this.pagesOfData(data.data.types); for (const keyTypes in pagesTypes) { if (pagesTypes[keyTypes]) { await writeNerdStorage( accountId, `${collectionName}-types`, `${collectionName}-types-${keyTypes}`, pagesTypes[keyTypes], this.reportLogFetch ).catch(err => { throw err; }); } } data.data.types = []; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, data, this.reportLogFetch ).catch(err => { throw err; }); } break; case 'logs': { await writeNerdStorage( accountId, collectionName, `${collectionName}-archives-obj`, data.data.archivesStatus, this.reportLogFetch ); const pagesArchives = this.pagesOfData(data.data.archives); for (const keyArchives in pagesArchives) { if (pagesArchives[keyArchives]) { await writeNerdStorage( accountId, `${collectionName}-archives`, `${collectionName}-archives-${keyArchives}`, pagesArchives[keyArchives], this.reportLogFetch ).catch(err => { throw err; }); } } await writeNerdStorage( accountId, collectionName, `${collectionName}-metrics-obj`, data.data.metricsStatus, this.reportLogFetch ).catch(err => { throw err; }); const pagesMetricsLogs = this.pagesOfData(data.data.metricsLogs); for (const keyMetricLog in pagesMetricsLogs) { if (pagesMetricsLogs[keyMetricLog]) { await writeNerdStorage( accountId, `${collectionName}-metrics`, `${collectionName}-metrics-${keyMetricLog}`, pagesMetricsLogs[keyMetricLog], this.reportLogFetch ).catch(err => { throw err; }); } } await writeNerdStorage( accountId, collectionName, `${collectionName}-pipelines-obj`, data.data.pipelinesStatus, this.reportLogFetch ).catch(err => { throw err; }); const pagesPipelines = this.pagesOfData(data.data.pipelines); for (const keyPipeline in pagesPipelines) { if (pagesPipelines[keyPipeline]) { await writeNerdStorage( accountId, `${collectionName}-pipelines`, `${collectionName}-pipelines-${keyPipeline}`, pagesPipelines[keyPipeline], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'metrics': { const listMetrics = data.data; data.data = []; const metricObj = data; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, metricObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesMetrics = this.pagesOfData(listMetrics); for (const keyMetric in pagesMetrics) { if (pagesMetrics[keyMetric]) { await writeNerdStorage( accountId, collectionName, `${collectionName}-${keyMetric}`, pagesMetrics[keyMetric], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'synthetics': { const list = data.data.test; // const listLocations = data.data.locations; data.data.list = []; // data.data.locations = []; const syntheticObj = data.data; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, syntheticObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesList = this.pagesOfData(list); for (const keyList in pagesList) { if (pagesList[keyList]) { await writeNerdStorage( accountId, `${collectionName}-list`, `${collectionName}-${keyList}`, pagesList[keyList], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'accounts': { const listUsers = data.data.data; data.data.data = []; const accountObj = data; await writeNerdStorage( accountId, collectionName, `${collectionName}-obj`, accountObj, this.reportLogFetch ).catch(err => { throw err; }); const pagesAccounts = this.pagesOfData(listUsers); for (const keyAccount in pagesAccounts) { if (pagesAccounts[keyAccount]) { await writeNerdStorage( accountId, collectionName, `${collectionName}-${keyAccount}`, pagesAccounts[keyAccount], this.reportLogFetch ).catch(err => { throw err; }); } } } break; default: { const response = { message: 'Collection name not found', type: 'Error', event: `Write data final`, date: new Date().toLocaleString() }; this.reportLogFetch(response); } break; } if (completed + 5 <= 70) { this.updateProgressFetch(5); } }; /** * Method that saves a log * * @param {Object} response Response object, expected: message, event, type, date * @memberof App */ reportLogFetch = async response => { const { logs } = this.state; const arrayLogs = logs; arrayLogs.push({ log: response.message, event: response.event, type: response.type, date: response.date }); this.setState({ logs: arrayLogs }); }; /** * Method that fetch the data from Datadog * * @memberof App */ fetchData = async () => { this.setState({ fetchingData: true, completed: 0 }); let error = false; const data = { lastUpdate: '' }; const { accountId, apikey, apiserver, appkey, datadogService } = this.state; const DDConfig = { DD_API_KEY: apikey, DD_APP_KEY: appkey, DD_SITE: apiserver, DD_SUMMARY: 'DashportData' }; await DD.callApis( DDConfig, this.dataWriter, this.reportLogFetch, datadogService ) .then(res => { data.lastUpdate = res.toLocaleString(); const response = { message: 'Call apis finish great', type: 'Sucess', event: `Call apis`, date: new Date().toLocaleString() }; this.reportLogFetch(response); }) .catch(err => { error = true; const response = { message: err, type: 'Error', event: 'Call apis', date: new Date().toLocaleString() }; this.reportLogFetch(response); }); if (!error) { await DS.apiDataDigest( this.readNerdStorage, this.finalDataWriter, this.reportLogFetch, this.readNerdStorageOnlyCollection ) .then(() => { const response = { message: 'Call format finish', type: 'Sucess', event: `Format data`, date: new Date().toLocaleString() }; this.reportLogFetch(response); }) .catch(err => { error = true; const response = { message: err, type: 'Error', event: 'Format data', date: new Date().toLocaleString() }; this.reportLogFetch(response); }); } if (error) { Toast.showToast({ title: 'FAILED FETCH ELEMENTS', description: 'something went wrong please retry', type: Toast.TYPE.CRITICAL, sticky: true }); if (this.state.lastUpdate !== 'never') { this.setState({ fetchingData: false, hasErrorFetch: true }); } else { this.setState({ fetchingData: false, lastUpdate: 'never' }); } } else { let lastUpdate = null; await writeNerdStorageReturnData( accountId, 'ddFetch', 'dateFetch', data, this.reportLogFetch ) .then(({ data }) => { lastUpdate = data.nerdStorageWriteDocument.lastUpdate; }) .catch(err => { const response = { message: err, type: 'Error', event: 'Write dateFetch', date: new Date().toLocaleString() }; this.reportLogFetch(response); }); await this.sendLogs(); await this.loadViewData(); this.setState({ fetchingData: false, lastUpdate, completed: 100 }); } }; /** * Method that call function for fetching metrics * * @memberof App */ updateMetricsSection = async (from, timeRangeMetrics) => { this.setState({ historyUpdateMetric: timeRangeMetrics }); const { datadogService, accountId, historyUpdateMetric } = this.state; let error = false; this.setState({ fetchingMetrics: true }); const metrics = await datadogService .fetchMetrics(from, null, this.updateProgressMetrics) .catch(err => { error = true; const response = { message: err, type: 'Error', event: 'Format data', date: new Date().toLocaleString() }; this.reportLogFetch(response); }); if (error) { Toast.showToast({ title: 'FAILED FETCH UPDATE METRICS', description: 'something went wrong please retry', type: Toast.TYPE.CRITICAL, sticky: true }); this.setState({ fetchingMetrics: false, errorMetric: true, historyUpdateMetric }); } else { await this.dataWriter('Get All Active Metrics', metrics).catch(err => { const response = { message: err, type: 'Error', event: 'Format data', date: new Date().toLocaleString() }; this.reportLogFetch(response); error = true; }); if (error) { Toast.showToast({ title: 'FAILED FETCH UPDATE METRICS', description: 'something went wrong please retry', type: Toast.TYPE.CRITICAL, sticky: true }); this.setState({ fetchingMetrics: false, errorMetric: true, historyUpdateMetric }); } else { await this.finalDataWriter('metrics', { data: metrics }).catch(err => { const response = { message: err, type: 'Error', event: 'Format data', date: new Date().toLocaleString() }; this.reportLogFetch(response); error = true; }); if (error) { Toast.showToast({ title: 'FAILED FETCH UPDATE METRICS', description: 'something went wrong please retry', type: Toast.TYPE.CRITICAL, sticky: true }); this.setState({ fetchingMetrics: false, errorMetric: true, historyUpdateMetric }); } else { // Guardar update await writeNerdStorageReturnData( accountId, 'metricsUpdate', 'metricsUpdate', timeRangeMetrics, this.reportLogFetch ); this.setState({ metrics: metrics, fetchingMetrics: false, progressMetrics: 100, historyUpdateMetric: timeRangeMetrics }); } } } }; /** * Method for view keys save for the user * * @memberof App */ viewKeyAction = async keyInput => { const { apikeyS, appkeyS } = this.state; if (keyInput === 'apikey') { if (apikeyS && apikeyS[0] === '*') { const keyRecove = await readSingleSecretKey(keyInput); if (keyRecove) { this.setState({ apikeyS: keyRecove }); } } else { this.setState({ apikeyS: '*'.repeat(apikeyS.length) }); } } else if (keyInput === 'appkey') { if (appkeyS && appkeyS[0] === '*') { const keyRecove = await readSingleSecretKey(keyInput); if (keyRecove) { this.setState({ appkeyS: keyRecove }); } } else { this.setState({ appkeyS: '*'.repeat(appkeyS.length) }); } } }; /** * Method for send logs to channel external * * @memberof App */ async sendLogs() { const { logs, accountId } = this.state; if (logs.length !== 0) { await sendLogsSlack(logs, accountId); this.setState({ logs: [] }); } } /** * Method that saves the fetch data on the NerdStorage * * @param {String} documentName Document name * @param {Object} documentData Document data * @memberof App */ dataWriter = async (documentName, documentData) => { const { accountId, completed } = this.state; switch (documentName) { case 'Get Dashboards Manual': { const allDashboards = documentData.dashboard_lists; const pagesDashboards = this.pagesOfData(allDashboards); for (const keyAllDashboard in pagesDashboards) { if (pagesDashboards[keyAllDashboard]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyAllDashboard}`, pagesDashboards[keyAllDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all Dashboards': { const allDashboards = documentData.dashboards; const pagesDashboards = this.pagesOfData(allDashboards); for (const keyAllDashboard in pagesDashboards) { if (pagesDashboards[keyAllDashboard]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyAllDashboard}`, pagesDashboards[keyAllDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all archives': { const archiverList = documentData.data.data; const archiveObj = documentData.status; const pagesArchives = this.pagesOfData(archiverList); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, archiveObj, this.reportLogFetch ).catch(err => { throw err; }); for (const keyArchives in pagesArchives) { if (pagesArchives[keyArchives]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyArchives}`, pagesArchives[keyArchives], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all log based metrics': { const basedMetrics = documentData.data.data; const basedObj = documentData.status; const pagesLogsMetrics = this.pagesOfData(basedMetrics); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, basedObj, this.reportLogFetch ).catch(err => { throw err; }); for (const keyLogsMetrics in pagesLogsMetrics) { if (pagesLogsMetrics[keyLogsMetrics]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyLogsMetrics}`, pagesLogsMetrics[keyLogsMetrics], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get a Dashboard': { const pagesDashboard = this.pagesOfData(documentData); for (const keyDashboard in pagesDashboard) { if (pagesDashboard[keyDashboard]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyDashboard}`, pagesDashboard[keyDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get Items of a Dashboard List': { const pagesDashboardList = this.pagesOfData(documentData); for (const keyItemDashboard in pagesDashboardList) { if (pagesDashboardList[keyItemDashboard]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyItemDashboard}`, pagesDashboardList[keyItemDashboard], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all Dashboard Lists': { const dashboards_list = documentData.dashboard_lists; const pagesAllDashboardsList = this.pagesOfData(dashboards_list); for (const keyAllDashboardList in pagesAllDashboardsList) { if (pagesAllDashboardsList[keyAllDashboardList]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyAllDashboardList}`, pagesAllDashboardsList[keyAllDashboardList], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get a Dashboard List': { const pagesDashboardsList = this.pagesOfData(documentData); for (const keyDashboardList in pagesDashboardsList) { if (pagesDashboardsList[keyDashboardList]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyDashboardList}`, pagesDashboardsList[keyDashboardList], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all embeddable graphs': { const pagesEmbeddable = this.pagesOfData(documentData); for (const keyEmbeddablet in pagesEmbeddable) { if (pagesEmbeddable[keyEmbeddablet]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyEmbeddablet}`, pagesEmbeddable[keyEmbeddablet], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Search hosts': { const hostList = documentData.host_list; documentData.host_list = []; const hostObj = documentData; const pagesHostList = this.pagesOfData(hostList); // guardo el host obj await writeNerdStorage( accountId, documentName, `${documentName}-obj`, hostObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo la lista de host con el for for (const keyHostList in pagesHostList) { if (pagesHostList[keyHostList]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyHostList}`, pagesHostList[keyHostList], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all indexes': { const { indexes } = documentData; const pagesIndexes = this.pagesOfData(indexes); // Guardo con el for normal for (const keyIndexes in pagesIndexes) { if (pagesIndexes[keyIndexes]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyIndexes}`, pagesIndexes[keyIndexes], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get indexes order': { const { index_names } = documentData; const pagesIndexesNames = this.pagesOfData(index_names); for (const keyIndexesNames in pagesIndexesNames) { if (pagesIndexesNames[keyIndexesNames]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyIndexesNames}`, pagesIndexesNames[keyIndexesNames], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get Pipeline Order': { const { pipeline_ids } = documentData; const pagesPipeline = this.pagesOfData(pipeline_ids); for (const keyPipeLine in pagesPipeline) { if (pagesPipeline[keyPipeLine]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyPipeLine}`, pagesPipeline[keyPipeLine], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all Pipelines': { const pipelineList = documentData.data; documentData.data = []; const pipeObj = documentData.status; const pagesAllPipeline = this.pagesOfData(pipelineList); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, pipeObj, this.reportLogFetch ).catch(err => { throw err; }); for (const keyAllPipeLine in pagesAllPipeline) { if (pagesAllPipeline[keyAllPipeLine]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyAllPipeLine}`, pagesAllPipeline[keyAllPipeLine], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Monitors meta': { const countsTypeList = documentData.countsType; documentData.countsType = []; const monitorObj = documentData; const pagesCountsTypeList = this.pagesOfData(countsTypeList); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, monitorObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo lista de metricas for (const keyMonitorMeta in pagesCountsTypeList) { if (pagesCountsTypeList[keyMonitorMeta]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyMonitorMeta}`, pagesCountsTypeList[keyMonitorMeta], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Monitor Search Pages': { const pagesMonitorsSearch = this.pagesOfData(documentData); for (const keyMonitorSearch in pagesMonitorsSearch) { if (pagesMonitorsSearch[keyMonitorSearch]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyMonitorSearch}`, pagesMonitorsSearch[keyMonitorSearch], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all tests': { const testList = documentData.tests; const pagesTest = this.pagesOfData(testList); for (const keyTest in pagesTest) { if (pagesTest[keyTest]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyTest}`, pagesTest[keyTest], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get devices for browser checks': { const devicesList = documentData.devices; const pageDevices = this.pagesOfData(devicesList); for (const keyDevices in pageDevices) { if (pageDevices[keyDevices]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyDevices}`, pageDevices[keyDevices], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get available locations': { const locationsList = documentData.locations; const pageLocations = this.pagesOfData(locationsList); for (const keyLocations in pageLocations) { if (pageLocations[keyLocations]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyLocations}`, pageLocations[keyLocations], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get all users': { const dataList = documentData.data; const includedList = documentData.included; documentData.data = []; documentData.included = []; const allUserObj = documentData; const pagesData = this.pagesOfData(dataList); const pagesIncluded = this.pagesOfData(includedList); // Guardo el objeto await writeNerdStorage( accountId, documentName, `${documentName}-obj`, allUserObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo la lista de pages data for (const keyData in pagesData) { if (pagesData[keyData]) { await writeNerdStorage( accountId, `${documentName}-data`, `${documentName}-${keyData}`, pagesData[keyData], this.reportLogFetch ).catch(err => { throw err; }); } } // guardo la lista de pages include for (const keyIncluded in pagesIncluded) { if (pagesIncluded[keyIncluded]) { await writeNerdStorage( accountId, `${documentName}-included`, `${documentName}-${keyIncluded}`, pagesIncluded[keyIncluded], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Monitor Group Search': { const listGroups = documentData.groups; documentData.groups = []; const monitorSearchObj = documentData; const pagesGroups = this.pagesOfData(listGroups); await writeNerdStorage( accountId, documentName, `${documentName}-obj`, monitorSearchObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo la lista de pages include for (const keyIncluded in pagesGroups) { if (pagesGroups[keyIncluded]) { await writeNerdStorage( accountId, `${documentName}`, `${documentName}-${keyIncluded}`, pagesGroups[keyIncluded], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get Tags': { const keysArr = Object.keys(documentData.tags); const valuesArr = Object.values(documentData.tags); const tags = []; for (const key in keysArr) { if (keysArr[key]) { tags.push({ tag: keysArr[key], data: valuesArr[key] }); } } const pagesTags = this.pagesOfData(tags); for (const keyTags in pagesTags) { if (pagesTags[keyTags]) { await writeNerdStorage( accountId, `${documentName}`, `${documentName}-${keyTags}`, pagesTags[keyTags], this.reportLogFetch ).catch(err => { throw err; }); } } } break; case 'Get All Active Metrics': { const metricsList = documentData.metrics; documentData.metrics = []; const metricObj = documentData; const pagesMetricsList = this.pagesOfData(metricsList); // guardo obj metrics await writeNerdStorage( accountId, documentName, `${documentName}-obj`, metricObj, this.reportLogFetch ).catch(err => { throw err; }); // guardo lista de metricas for (const keyMetrics in pagesMetricsList) { if (pagesMetricsList[keyMetrics]) { await writeNerdStorage( accountId, documentName, `${documentName}-${keyMetrics}`, pagesMetricsList[keyMetrics], this.reportLogFetch ).catch(err => { throw err; }); } } await writeNerdStorageReturnData( accountId, 'metricsUpdate', 'metricsUpdate', { value: '30 minutes', label: '30 minutes' }, this.reportLogFetch ); } break; default: // Guardo el get task tal cual // Guardo el Host totals tal cual await writeNerdStorage( accountId, documentName, `${documentName}-obj`, documentData, this.reportLogFetch ).catch(err => { throw err; }); break; } if (completed <= 50) { if (completed + 2 === 48) { this.updateProgressFetch(4); } else { this.updateProgressFetch(2); } } }; /** * Method that update progress of fetch principal * * @memberof App */ updateProgressFetch = value => { this.setState(prevState => ({ completed: prevState.completed + value })); }; pagesOfData = list => { const limit = 1000000; let page = []; const book = []; let pageTemporal = []; for (const key in list) { if (list[key]) { pageTemporal = [...page]; if (page) { pageTemporal.push(list[key]); if (JSON.stringify(pageTemporal).length >= limit) { if (page.length !== 0) { book.push(page); } page = []; page.push(list[key]); } else { page = pageTemporal; pageTemporal = []; } if (parseInt(key) === parseInt(list.length - 1)) { book.push(page); } } } } return book; }; /** * Method that validate the data and writes the form API into the datadog-setup document on NerdStorage * * @param {Object} values * @memberof App */ writeSetup = async values => { try { this.setState({ writingSetup: true }); const { accountId } = this.state; const { appkey, apikey } = values; let region = 'com'; let validKeys = await DD.validateKeys(apikey, appkey, 'com'); if (!validKeys.appkey && !validKeys.apikey) { validKeys = await DD.validateKeys(apikey, appkey, 'eu'); region = 'eu'; } const data = { apiserver: region, apikeyS: '*'.repeat(apikey.length), appkeyS: '*'.repeat(appkey.length) }; if (validKeys.apikey) { if (validKeys.appkey) { // guardar en el vault let saveApiKey = null; let saveAppKey = null; let retrys = 0; while (retrys !== 5) { if (!saveApiKey || saveApiKey.status !== 'SUCCESS') saveApiKey = await writeSecretKey('apikey', apikey); if (!saveAppKey || saveAppKey.status !== 'SUCCESS') saveAppKey = await writeSecretKey('appkey', appkey); if ( saveAppKey && saveAppKey.status === 'SUCCESS' && saveAppKey && saveAppKey.status === 'SUCCESS' ) { retrys = 5; } else { retrys++; } } if ( (saveApiKey && saveApiKey.status !== 'SUCCESS') || (saveAppKey && saveAppKey.status !== 'SUCCESS') ) { Toast.showToast({ title: 'FAILED', description: 'something went wrong please retry', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); } else { await writeNerdStorageReturnData( accountId, 'setup', 'datadog', data, this.reportLogFetch ) .then(() => { const datadogService = this.createDatadogServiceInstance( apikey, appkey, region ); this.setState({ writingSetup: false, apikey: apikey, appkey: appkey, apikeyS: '*'.repeat(apikey.length), appkeyS: '*'.repeat(appkey.length), apiserver: region, setupComplete: true, lastUpdate: 'never', datadogService: datadogService }); Toast.showToast({ title: 'VALID KEY', description: 'Valid key and correctly encrypted', type: Toast.TYPE.NORMAL }); }) .catch(err => { const response = { message: err, type: 'Error', event: 'Write setup', date: new Date().toLocaleString() }; this.reportLogFetch(response); Toast.showToast({ title: 'FAILED', description: 'something went wrong', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); }); } } else { Toast.showToast({ title: 'FAILED', description: 'The application key is not valid', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); } } else { Toast.showToast({ title: 'FAILED', description: 'The API key is not valid', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); } } catch (err) { Toast.showToast({ title: 'FAILED', description: 'Something went wrong', type: Toast.TYPE.NORMAL }); this.setState({ writingSetup: false }); const response = { message: err, type: 'Error', event: 'Write setup function', date: new Date().toLocaleString() }; this.reportLogFetch(response); } this.sendLogs(); }; /** * Method that open a Toast notification from confirm delete API setup * * @memberof App */ openToast = () => { const { accountId } = this.state; Toast.showToast({ title: 'ALERT', description: 'Are you sure you want to delete the datadog configuration?', actions: [ { label: 'DELETE', onClick: async () => { this.setState({ deleteSetup: true, writingSetup: true }); await deleteSetup(accountId); this.setState({ apikey: '', appkey: '', apiserver: '', lastUpdate: '', setupComplete: false, writingSetup: false, deleteSetup: false }); } } ], type: Toast.TYPE.NORMAL }); }; /** * Method that changes the component to render according to the selected menu option * * @returns * @memberof App */ renderContent() { const { selectedMenu, monitorsGraph, monitorsTotal, monitorsData, infrastructureDataGraph, infraestructureList, metrics, testTotal, testList, fetchingData, writingSetup, logsData, apikey, apikeyS, appkey, appkeyS, lastUpdate, setupComplete, completed, deleteSetup, dataDashboards, fetchingMetrics, progressMetrics, emptyData, errorMetric, hasErrorFetch, historyUpdateMetric, total, totalActive } = this.state; switch (selectedMenu) { case 0: return ( <Setup completed={completed} hasErrorFetch={hasErrorFetch} setupComplete={setupComplete} deleteSetup={deleteSetup} viewKeyAction={this.viewKeyAction} apikeyS={apikeyS} fetchingData={fetchingData} apikey={apikey} appkey={appkey} lastUpdate={lastUpdate} writingSetup={writingSetup} appkeyS={appkeyS} handlePlatformChange={this.handlePlatformChange} fetchData={this.fetchData} writeSetup={this.writeSetup} openToast={this.openToast} /> ); case 2: return ( <Dashboard dataDashboards={dataDashboards} emptyData={emptyData} /> ); case 3: return ( <Monitors monitorsGraph={monitorsGraph} monitorsTotal={monitorsTotal} monitorsData={monitorsData} /> ); case 4: return ( <Infrastructure infrastructureDataGraph={infrastructureDataGraph} infraestructureList={infraestructureList} total={total} totalActive={totalActive} /> ); case 5: return <Logs logsData={logsData} />; case 6: return ( <Metrics metrics={metrics} errorMetric={errorMetric} completed={progressMetrics} fetchingMetrics={fetchingMetrics} historyUpdateMetric={historyUpdateMetric} updateMetricsSection={this.updateMetricsSection} updateProgressMetrics={this.updateProgressMetrics} /> ); case 7: return <Synthetics testTotal={testTotal} testList={testList} />; default: return <div />; } } render() { const { loadingContent, selectedMenu, lastUpdate } = this.state; return ( <> {loadingContent ? ( <Spinner type={Spinner.TYPE.DOT} /> ) : ( <div className="main"> <> <div className="sidebar-container h100"> <Menu lastUpdate={lastUpdate} selectedMenu={selectedMenu} handleChangeMenu={this.handleChangeMenu} /> </div> <div className="h100" style={{ background: '#eceeee' }}> <div style={{ paddingTop: '1.8%', paddingRight: '1%', paddingLeft: '1.8%', height: '96%' }} > {this.renderContent()} </div> </div> </> </div> )} </> ); } }
/* Thank you Drew McLellan for starting us off with http://24ways.org/2006/tasty-text-trimmer */ function TextTrimmer(value) { var self = this; this.minValue = 0; this.maxValue = 100; this.chunks = false; this.prevValue = 0; if (value >= this.maxValue) { this.curValue = this.maxValue; } else if (value < this.minValue) { this.curValue = this.minValue; } else { this.curValue = value; } this.slider = new K2Slider('#trimmerhandle', '#trimmertrack', { minimum: 0, maximum: 10, value: 10, onSlide: function(x) { self.doTrim(x * 10); }, onChange: function(x) { self.doTrim(x * 10); } }); jQuery('#trimmermore').click(function() { self.slider.setValueBy(1); return false; }); jQuery('#trimmerless').click(function() { self.slider.setValueBy(-1); return false; }); jQuery('#trimmertrim').click(function() { self.slider.setValue(self.minValue); return false; }); jQuery('#trimmeruntrim').click(function() { self.slider.setValue(self.maxValue); return false; }); }; TextTrimmer.prototype.trimAgain = function() { this.loadChunks(); this.doTrim(this.curValue); }; TextTrimmer.prototype.loadChunks = function() { var everything = jQuery('#dynamic-content .entry-content'); this.chunks = []; for (i=0; i<everything.length; i++) { this.chunks.push({ ref: everything[i], html: jQuery(everything[i]).html(), text: jQuery.trim(jQuery(everything[i]).text()) }); } }; TextTrimmer.prototype.doTrim = function(interval) { /* Spit out the trimmed text */ if (!this.chunks) this.loadChunks(); /* var interval = parseInt(interval); */ this.curValue = interval; for (i=0; i<this.chunks.length; i++) { if (interval == this.maxValue) { jQuery(this.chunks[i].ref).html(this.chunks[i].html); } else if (interval == this.minValue) { jQuery(this.chunks[i].ref).html(''); } else { var a = this.chunks[i].text.split(' '); a = a.slice(0, Math.round(interval * a.length / 100)); jQuery(this.chunks[i].ref).html('<p>' + a.join(' ') + '&nbsp;[...]</p>'); } } /* Add 'trimmed' class to <BODY> while active */ if (this.curValue != this.maxValue) { jQuery('#dynamic-content').addClass("trimmed"); } else { jQuery('#dynamic-content').removeClass("trimmed"); } };
include("params.jscad"); function z_nut_support(width, length, excess) { var thick = glbl.thickness; var width2 = width/2; var thick2 = thick/2; var length2 = length/2; var z_nut_h = 4 * Math.sqrt(2); var scrwr = glbl.screwRadius; var ori_y = length/2 - 20; var body = cube({radius:[width2, length2 + excess/2, thick2], center:[0, excess/2, thick2]}) .subtract([ cylinder({radius:4.25, start:[0, ori_y, -1], end:[0, ori_y, thick+1]}), cylinder({radius:7.1, start:[0, ori_y, thick-3], end:[0, ori_y, thick+1], resolution:6}), cylinder({radius:scrwr, start:[ z_nut_h, ori_y+z_nut_h, -1], end:[ z_nut_h, ori_y+z_nut_h, thick+1 ]}), cylinder({radius:scrwr, start:[ z_nut_h, ori_y-z_nut_h, -1], end:[ z_nut_h, ori_y-z_nut_h, thick+1 ]}), cylinder({radius:scrwr, start:[ -z_nut_h, ori_y+z_nut_h, -1], end:[ -z_nut_h, ori_y+z_nut_h, thick+1 ]}), cylinder({radius:scrwr, start:[ -z_nut_h, ori_y-z_nut_h, -1], end:[ -z_nut_h, ori_y-z_nut_h, thick+1 ]}), ]); return body.setColor(glbl.partColor); } function x_carriage() { var clamp_hole = 26; var length = 135; var width = 31 + 2 * clamp_hole; var thick = glbl.thickness; var scrwr = glbl.screwRadius; var length2 = length/2; var width2 = width/2; var thick2 = thick/2; var x_motor_off = -15; var z_motor_off = 21; var motor_hole = 15.5; var motor_hole = 15.5; var clamp_off = length2 - 26; var z_nut_w = 12.5; var z_nut_h = 4 * Math.sqrt(2); var support = polygon([ [12.5,0], [12.5,2], [2.5,10], [-2.5,10], [-12.5,2], [-12.5,0] ]).extrude({offset: [0,0,thick]}); var body = cube({radius:[length2, width2, thick2], center:[0, 0, thick2]}).subtract([ cylinder({radius:12, start:[x_motor_off, 0, -1], end:[x_motor_off, 0, thick+1]}), cylinder({radius:scrwr, start:[ x_motor_off+motor_hole, motor_hole, -1], end:[x_motor_off+motor_hole, motor_hole, thick+1]}), cylinder({radius:scrwr, start:[ x_motor_off+motor_hole, -motor_hole, -1], end:[x_motor_off+motor_hole, -motor_hole, thick+1]}), cylinder({radius:scrwr, start:[ x_motor_off-motor_hole, motor_hole, -1], end:[x_motor_off-motor_hole, motor_hole, thick+1]}), cylinder({radius:scrwr, start:[ x_motor_off-motor_hole, -motor_hole, -1], end:[x_motor_off-motor_hole, -motor_hole, thick+1]}), cylinder({radius:scrwr, start:[-clamp_off, motor_hole, -1], end:[-clamp_off, motor_hole, thick+1]}), cylinder({radius:scrwr, start:[-clamp_off, -motor_hole, -1], end:[-clamp_off, -motor_hole, thick+1]}), cylinder({radius:scrwr, start:[ clamp_off, motor_hole, -1], end:[ clamp_off, motor_hole, thick+1]}), cylinder({radius:scrwr, start:[ clamp_off, -motor_hole, -1], end:[ clamp_off, -motor_hole, thick+1]}), cube({corner1:[-length2+28,-width2+20,-1], corner2:[-length2-1,-width2-1,thick+1]}), cube({corner1:[-length2+28, width2-20,-1], corner2:[-length2-1, width2+1,thick+1]}), cube({corner1:[ length2-60,-width2+20,-1], corner2:[ length2+1,-width2-1,thick+1]}), cube({corner1:[ length2-60, width2-20,-1], corner2:[ length2+1, width2+1,thick+1]}), ]).union([ z_nut_support(25,30,2).rotateX(-90).rotateZ(180).translate([z_motor_off,thick,thick + 15]), //z_motor_off support.rotateY(-90).rotateX(90).translate([z_motor_off + 12.5,thick-2.5, thick-2]), support.rotateY(-90).rotateX(90).translate([z_motor_off - 12.5 + thick,thick-2.5, thick-2]), ]); return body.setColor(glbl.partColor); } function z_nut_cover() { return z_nut_support(25,30,-10); } function x_carriage_with_z_nut() { return x_carriage().union(z_nut_cover().rotateX(-90).translate([21,-5.5,20])); }
// 自定义配置,参考 ./default/setting.config.js,需要自定义的属性在这里配置即可 module.exports = { theme: { mode: 'dark', color: '#1890ff', }, multiPage: true, animate: { disabled: false, name: 'fade', direction: 'right' } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Escalation definitions */ angular.module('flowableModeler').controller('FlowableEscalationDefinitionsCtrl', ['$scope', '$modal', function ($scope, $modal) { // Config for the modal window var opts = { template: 'editor-app/configuration/properties/escalation-definitions-popup.html?version=' + Date.now(), scope: $scope }; // Open the dialog _internalCreateModal(opts, $modal, $scope); }]); //Need a separate controller for the modal window due to https://github.com/angular-ui/bootstrap/issues/259 // Will be fixed in a newer version of Angular UI angular.module('flowableModeler').controller('FlowableEscalationDefinitionsPopupCtrl', ['$scope', '$q', '$translate', '$timeout', function ($scope, $q, $translate, $timeout) { // Put json representing signal definitions on scope if ($scope.property.value !== undefined && $scope.property.value !== null && $scope.property.value.length > 0) { if ($scope.property.value.constructor == String) { $scope.escalationDefinitions = JSON.parse($scope.property.value); } else { // Note that we clone the json object rather then setting it directly, // this to cope with the fact that the user can click the cancel button and no changes should have happened $scope.escalationDefinitions = angular.copy($scope.property.value); } } else { $scope.escalationDefinitions = []; } // Array to contain selected signal definitions (yes - we only can select one, but ng-grid isn't smart enough) $scope.selectedEscalationDefinition = undefined; $scope.translationsRetrieved = false; $scope.labels = {}; var idPromise = $translate('PROPERTY.ESCALATIONDEFINITIONS.ID'); var namePromise = $translate('PROPERTY.ESCALATIONDEFINITIONS.NAME'); $q.all([idPromise, namePromise]).then(function (results) { $scope.labels.idLabel = results[0]; $scope.labels.nameLabel = results[1]; $scope.translationsRetrieved = true; // Config for grid $scope.gridOptions = { data: $scope.escalationDefinitions, headerRowHeight: 28, enableRowSelection: true, enableRowHeaderSelection: false, multiSelect: false, modifierKeysToMultiSelect: false, enableHorizontalScrollbar: 0, enableColumnMenus: false, enableSorting: false, columnDefs: [ {field: 'id', displayName: $scope.labels.idLabel}, {field: 'name', displayName: $scope.labels.nameLabel}] }; $scope.gridOptions.onRegisterApi = function (gridApi) { //set gridApi on scope $scope.gridApi = gridApi; gridApi.selection.on.rowSelectionChanged($scope, function (row) { $scope.selectedEscalationDefinition = row.entity; }); }; }); // Click handler for add button $scope.addNewEscalationDefinition = function () { var newEscalationDefinition = {id: '', name: ''}; $scope.escalationDefinitions.push(newEscalationDefinition); $timeout(function () { $scope.gridApi.selection.toggleRowSelection(newEscalationDefinition); }); }; // Click handler for remove button $scope.removeEscalationDefinition = function () { var selectedItems = $scope.gridApi.selection.getSelectedRows(); if (selectedItems && selectedItems.length > 0) { var index = $scope.escalationDefinitions.indexOf(selectedItems[0]); $scope.gridApi.selection.toggleRowSelection(selectedItems[0]); $scope.escalationDefinitions.splice(index, 1); if ($scope.escalationDefinitions.length == 0) { $scope.selectedEscalationDefinition = undefined; } $timeout(function () { if ($scope.escalationDefinitions.length > 0) { $scope.gridApi.selection.toggleRowSelection($scope.escalationDefinitions[0]); } }); } }; // Click handler for save button $scope.save = function () { if ($scope.escalationDefinitions.length > 0) { $scope.property.value = $scope.escalationDefinitions; } else { $scope.property.value = null; } $scope.updatePropertyInModel($scope.property); $scope.close(); }; $scope.cancel = function () { $scope.property.mode = 'read'; $scope.$hide(); }; // Close button handler $scope.close = function () { $scope.property.mode = 'read'; $scope.$hide(); }; }]);
/** * Gets the repositories of the user from Github */ import { call, put, select, takeLatest } from 'redux-saga/effects'; import { LOAD_REPOS } from 'containers/App/constants'; import { reposLoaded, repoLoadingError } from 'containers/App/actions'; import request from 'utils/request'; import { makeSelectUsername } from 'containers/HomePage/selectors'; /** * Github repos request/response handler */ export function* getRepos() { // Select username from store const username = yield select(makeSelectUsername()); const requestURL = `https://api.github.com/users/${username}/repos?type=all&sort=updated`; try { // Call our request helper (see 'utils/request') const repos = yield call(request, requestURL); yield put(reposLoaded(repos, username)); } catch (err) { yield put(repoLoadingError(err)); } } export function* getRandomImage() { var image = document.createElement('img'); // image.src = 'imgur.com/random'; image.src = 'https://randomwordgenerator.com/picture.php'; document.appendChild(image); } /** * Root saga manages watcher lifecycle */ export default function* githubData() { // Watches for LOAD_REPOS actions and calls getRepos when one comes in. // By using `takeLatest` only the result of the latest API call is applied. // It returns task descriptor (just like fork) so we can continue execution // It will be cancelled automatically on component unmount yield takeLatest(LOAD_REPOS, getRepos); }
var validatorComponent = Vue.component('child', { props: { // basic type check (`null` means accept any type) propA: Number, // multiple possible types (1.0.21+) propM: [String, Number], // a required string propB: { type: String, required: true }, // a number with default value propC: { type: Number, default: 100 }, // object/array defaults should be returned from a // factory function propD: { type: Object, default: function() { return { msg: 'hello' } } }, // indicate this prop expects a two-way binding. will // raise a warning if binding type does not match. propE: { twoWay: true }, // custom validator function propF: { validator: function(value) { return value > 10 } }, // coerce function (new in 1.0.12) // cast the value before setting it on the component propG: { coerce: function(val) { return val + '' // cast the value to string } } }, template: '<span>{{propA}}</span></br>' + '<span>{{propM}}</span></br>' + '<span>{{propB}}</span></br>' + '<span>{{propC}}</span></br>' + '<span>{{propD}}</span></br>' + '<span>{{propE}}</span></br>' + '<span>{{propF}}</span></br>' + '<span>{{propG}}</span></br>' }) // register Vue.component('validator-component', validatorComponent) // create a root instance new Vue({ el: '#example' })
(function(){ 'use strict'; /** * invertedPathFilter - filter dataview by path: only items not in the given path are allowed * @param {jQueryObject} checkedCheckboxes - checked checkboxes list * @param {Array.<jQuery.fn.jplist.DataItemModel>} dataview - stores dataview * @return {Array.<jQuery.fn.jplist.DataItemModel>} */ jQuery.fn.jplist.FiltersService.invertedPathFilter = function(checkedCheckboxes, dataview){ var dataitem ,pathitem ,resultDataview = [] ,path ,dataPath ,addFlag = false ,cb; for(var i=0; i<dataview.length; i++){ //get dataitem dataitem = dataview[i]; //set flag to false addFlag = false; if(checkedCheckboxes && checkedCheckboxes.length > 0){ for(var j=0; j<checkedCheckboxes.length; j++){ //get checkboxe cb = checkedCheckboxes.eq(j); //get path dataPath = cb.attr('data-path').toString(); if(dataPath == 'default'){ addFlag = true; } else{ //get data path path = new jQuery.fn.jplist.PathModel(dataPath, null); //find value by path pathitem = dataitem.findPathitem(path); if(pathitem){ addFlag = true; } } } if(addFlag){ resultDataview.push(dataitem); } } } return resultDataview; }; })();
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import api from './api/GoogleCloudApi'; import DicomStoreList from './DicomStoreList'; import './googleCloud.css'; export default class DicomStorePicker extends Component { state = { error: null, loading: true, stores: [], locations: [], filterStr: '', }; static propTypes = { dataset: PropTypes.object, onSelect: PropTypes.func, accessToken: PropTypes.string.isRequired, }; async componentDidMount() { api.setAccessToken(this.props.accessToken); const response = await api.loadDicomStores(this.props.dataset.name); if (response.isError) { this.setState({ error: response.message, }); return; } this.setState({ stores: response.data.dicomStores || [], loading: false, }); } render() { const { stores, loading, error, filterStr } = this.state; const { onSelect } = this.props; return ( <div> <input className="form-control gcp-input" type="text" value={filterStr} onChange={e => this.setState({ filterStr: e.target.value })} /> <DicomStoreList stores={stores} loading={loading} error={error} filter={filterStr} onSelect={onSelect} /> </div> ); } }
//--------------------------------------------------------------- //All required packages //--------------------------------------------------------------- var friendsData = require("../data/friends"); //--------------------------------------------------------------- //Routing //--------------------------------------------------------------- module.exports = function (app) { app.get("/api/friends", function (req, res) { res.json(friendsData); }); app.get("/api/match", function (req, res) { var minMatchFactor = Number.MAX_VALUE; var matchIndex = -1; for (var i = 0; i < friendsData.length - 1; i++) { matchFactor = Math.abs(friendsData[friendsData.length - 1].answers[0] - friendsData[i].answers[0]) + Math.abs(friendsData[friendsData.length - 1].answers[1] - friendsData[i].answers[1]) + Math.abs(friendsData[friendsData.length - 1].answers[2] - friendsData[i].answers[2]) + Math.abs(friendsData[friendsData.length - 1].answers[3] - friendsData[i].answers[3]) + Math.abs(friendsData[friendsData.length - 1].answers[4] - friendsData[i].answers[4]) + Math.abs(friendsData[friendsData.length - 1].answers[5] - friendsData[i].answers[5]) + Math.abs(friendsData[friendsData.length - 1].answers[6] - friendsData[i].answers[6]) + Math.abs(friendsData[friendsData.length - 1].answers[7] - friendsData[i].answers[7]) + Math.abs(friendsData[friendsData.length - 1].answers[8] - friendsData[i].answers[8]) + Math.abs(friendsData[friendsData.length - 1].answers[9] - friendsData[i].answers[9]); //get the minimum matchFactor if (minMatchFactor >= matchFactor) { minMatchFactor = matchFactor; matchIndex = i; } } // console.log(friendsData[matchIndex]); res.send(friendsData[matchIndex]); }); app.post("/api/friends", function (req, res) { var answersArray = []; for (var i = 0; i < req.body.answers.length; i++) answersArray.push(parseInt(req.body.answers[i])); var newfriend = { name: req.body.name, photoURL: req.body.photoURL, answers: answersArray }; friendsData.push(newfriend); res.json(true); }); };
exports.JsonWebTokenError = require('./JsonWebTokenError.js'); exports.MessageError = require('./MessageError.js');
console.log("testing")
const date_picker_element = document.querySelector('.date-picker'); const dates_element = document.querySelector('.date-picker .dates'); const mth_element = document.querySelector('.date-picker .dates .month .mth'); const next_mth_element = document.querySelector('.date-picker .dates .month .next-mth'); const prev_mth_element = document.querySelector('.date-picker .dates .month .prev-mth'); const days_element = document.querySelector('.date-picker .dates .days'); const months = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']; let date = new Date(); let day = date.getDate(); let month = date.getMonth(); let year = date.getFullYear(); let selectedDate = date; let selectedDay = day; let selectedMonth = month; let selectedYear = year; mth_element.textContent = months[month] + ' ' + year; populateDates(); // EVENT LISTENERS next_mth_element.addEventListener('click', goToNextMonth); prev_mth_element.addEventListener('click', goToPrevMonth); function goToNextMonth (e) { month++; if (month > 11) { month = 0; year++; } mth_element.textContent = months[month] + ' ' + year; populateDates(); } function goToPrevMonth (e) { month--; if (month < 0) { month = 11; year--; } mth_element.textContent = months[month] + ' ' + year; populateDates(); } function populateDates (e) { days_element.innerHTML = ''; let amount_days = 31; if (month == 1) { amount_days = 28; } for (let i = 0; i < amount_days; i++) { const day_element = document.createElement('div'); day_element.classList.add('day'); day_element.textContent = i + 1; if (selectedDay == (i + 1) && selectedYear == year && selectedMonth == month) { day_element.classList.add('selected'); } day_element.addEventListener('click', function () { selectedDate = new Date(year + '-' + (month + 1) + '-' + (i + 1)); selectedDay = (i + 1); selectedMonth = month; selectedYear = year; populateDates(); }); days_element.appendChild(day_element); } } // HELPER FUNCTIONS function checkEventPathForClass (path, selector) { for (let i = 0; i < path.length; i++) { if (path[i].classList && path[i].classList.contains(selector)) { return true; } } return false; } function formatDate (d) { let day = d.getDate(); if (day < 10) { day = '0' + day; } let month = d.getMonth() + 1; if (month < 10) { month = '0' + month; } let year = d.getFullYear(); return day + ' / ' + month + ' / ' + year; }
(/* istanbul ignore next */ function (global, factory) { if (typeof define === "function" && define.amd) { define(['module', 'exports', '../get/parents', '../util/context-to-element', '../util/element-matches', '../util/tabindex-value', './valid-tabindex', './is.util', '../supports/supports'], factory); } else if (typeof exports !== "undefined") { factory(module, exports, require('../get/parents'), require('../util/context-to-element'), require('../util/element-matches'), require('../util/tabindex-value'), require('./valid-tabindex'), require('./is.util'), require('../supports/supports')); } else { var mod = { exports: {} }; factory(mod, mod.exports, global.parents, global.contextToElement, global.elementMatches, global.tabindexValue, global.validTabindex, global.is, global.supports); global.focusRelevant = mod.exports; } })(this, function (module, exports, _parents, _contextToElement, _elementMatches, _tabindexValue, _validTabindex, _is, _supports2) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _parents2 = _interopRequireDefault(_parents); var _contextToElement2 = _interopRequireDefault(_contextToElement); var _elementMatches2 = _interopRequireDefault(_elementMatches); var _tabindexValue2 = _interopRequireDefault(_tabindexValue); var _validTabindex2 = _interopRequireDefault(_validTabindex); var _supports3 = _interopRequireDefault(_supports2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var supports = void 0; // determine if an element supports.can be focused by script regardless // of the element actually being focusable at the time of execution // i.e. <input disabled> is conisdered focus-relevant, but not focusable function isFocusRelevantRules() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, context = _ref.context, _ref$except = _ref.except, except = _ref$except === undefined ? { flexbox: false, scrollable: false, shadow: false } : _ref$except; if (!supports) { supports = (0, _supports3.default)(); } var element = (0, _contextToElement2.default)({ label: 'is/focus-relevant', resolveDocument: true, context: context }); if (!except.shadow && element.shadowRoot) { // a ShadowDOM host receives focus when the focus moves to its content return true; } var nodeName = element.nodeName.toLowerCase(); if (nodeName === 'input' && element.type === 'hidden') { // input[type="hidden"] supports.cannot be focused return false; } if (nodeName === 'input' || nodeName === 'select' || nodeName === 'button' || nodeName === 'textarea') { return true; } if (nodeName === 'legend' && supports.focusRedirectLegend) { // specifics filtered in is/focusable return true; } if (nodeName === 'label') { // specifics filtered in is/focusable return true; } if (nodeName === 'area') { // specifics filtered in is/focusable return true; } if (nodeName === 'a' && element.hasAttribute('href')) { return true; } if (nodeName === 'object' && element.hasAttribute('usemap')) { // object[usemap] is not focusable in any browser return false; } if (nodeName === 'object') { var svgType = element.getAttribute('type'); if (!supports.focusObjectSvg && svgType === 'image/svg+xml') { // object[type="image/svg+xml"] is not focusable in Internet Explorer return false; } else if (!supports.focusObjectSwf && svgType === 'application/x-shockwave-flash') { // object[type="application/x-shockwave-flash"] is not focusable in Internet Explorer 9 return false; } } if (nodeName === 'iframe' || nodeName === 'object') { // browsing context containers return true; } if (nodeName === 'embed' || nodeName === 'keygen') { // embed is considered focus-relevant but not focusable // see https://github.com/medialize/ally.js/issues/82 return true; } if (element.hasAttribute('contenteditable')) { // also see CSS property user-modify below return true; } if (nodeName === 'audio' && (supports.focusAudioWithoutControls || element.hasAttribute('controls'))) { return true; } if (nodeName === 'video' && (supports.focusVideoWithoutControls || element.hasAttribute('controls'))) { return true; } if (supports.focusSummary && nodeName === 'summary') { return true; } var validTabindex = (0, _validTabindex2.default)(element); if (nodeName === 'img' && element.hasAttribute('usemap')) { // Gecko, Trident and Edge do not allow an image with an image map and tabindex to be focused, // it appears the tabindex is overruled so focus is still forwarded to the <map> return validTabindex && supports.focusImgUsemapTabindex || supports.focusRedirectImgUsemap; } if (supports.focusTable && (nodeName === 'table' || nodeName === 'td')) { // IE10-11 supports.can focus <table> and <td> return true; } if (supports.focusFieldset && nodeName === 'fieldset') { // IE10-11 supports.can focus <fieldset> return true; } var isSvgElement = nodeName === 'svg'; var isSvgContent = element.ownerSVGElement; var focusableAttribute = element.getAttribute('focusable'); var tabindex = (0, _tabindexValue2.default)(element); if (nodeName === 'use' && tabindex !== null && !supports.focusSvgUseTabindex) { // <use> cannot be made focusable by adding a tabindex attribute anywhere but Blink and WebKit return false; } if (nodeName === 'foreignobject') { // <use> can only be made focusable in Blink and WebKit return tabindex !== null && supports.focusSvgForeignobjectTabindex; } if ((0, _elementMatches2.default)(element, 'svg a') && element.hasAttribute('xlink:href')) { return true; } if ((isSvgElement || isSvgContent) && element.focus && !supports.focusSvgNegativeTabindexAttribute && tabindex < 0) { // Firefox 51 and 52 treat any natively tabbable SVG element with // tabindex="-1" as tabbable and everything else as inert // see https://bugzilla.mozilla.org/show_bug.cgi?id=1302340 return false; } if (isSvgElement) { return validTabindex || supports.focusSvg || supports.focusSvgInIframe // Internet Explorer understands the focusable attribute introduced in SVG Tiny 1.2 || Boolean(supports.focusSvgFocusableAttribute && focusableAttribute && focusableAttribute === 'true'); } if (isSvgContent) { if (supports.focusSvgTabindexAttribute && validTabindex) { return true; } if (supports.focusSvgFocusableAttribute) { // Internet Explorer understands the focusable attribute introduced in SVG Tiny 1.2 return focusableAttribute === 'true'; } } // https://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute if (validTabindex) { return true; } var style = window.getComputedStyle(element, null); if ((0, _is.isUserModifyWritable)(style)) { return true; } if (supports.focusImgIsmap && nodeName === 'img' && element.hasAttribute('ismap')) { // IE10-11 considers the <img> in <a href><img ismap> focusable // https://github.com/medialize/ally.js/issues/20 var hasLinkParent = (0, _parents2.default)({ context: element }).some(function (parent) { return parent.nodeName.toLowerCase() === 'a' && parent.hasAttribute('href'); }); if (hasLinkParent) { return true; } } // https://github.com/medialize/ally.js/issues/21 if (!except.scrollable && supports.focusScrollContainer) { if (supports.focusScrollContainerWithoutOverflow) { // Internet Explorer does will consider the scrollable area focusable // if the element is a <div> or a <span> and it is in fact scrollable, // regardless of the CSS overflow property if ((0, _is.isScrollableContainer)(element, nodeName)) { return true; } } else if ((0, _is.hasCssOverflowScroll)(style)) { // Firefox requires proper overflow setting, IE does not necessarily // https://developer.mozilla.org/en-US/docs/Web/CSS/overflow return true; } } if (!except.flexbox && supports.focusFlexboxContainer && (0, _is.hasCssDisplayFlex)(style)) { // elements with display:flex are focusable in IE10-11 return true; } var parent = element.parentElement; if (!except.scrollable && parent) { var parentNodeName = parent.nodeName.toLowerCase(); var parentStyle = window.getComputedStyle(parent, null); if (supports.focusScrollBody && (0, _is.isScrollableContainer)(parent, nodeName, parentNodeName, parentStyle)) { // scrollable bodies are focusable Internet Explorer // https://github.com/medialize/ally.js/issues/21 return true; } // Children of focusable elements with display:flex are focusable in IE10-11 if (supports.focusChildrenOfFocusableFlexbox) { if ((0, _is.hasCssDisplayFlex)(parentStyle)) { return true; } } } // NOTE: elements marked as inert are not focusable, // but that property is not exposed to the DOM // https://www.w3.org/TR/html5/editing.html#inert return false; } // bind exceptions to an iterator callback isFocusRelevantRules.except = function () { var except = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var isFocusRelevant = function isFocusRelevant(context) { return isFocusRelevantRules({ context: context, except: except }); }; isFocusRelevant.rules = isFocusRelevantRules; return isFocusRelevant; }; // provide isFocusRelevant(context) as default iterator callback var isFocusRelevant = isFocusRelevantRules.except({}); exports.default = isFocusRelevant; module.exports = exports['default']; }); //# sourceMappingURL=focus-relevant.js.map
/** * Copyright (c) 2015-present, Alibaba Group Holding Limited. * All rights reserved. * * @providesModule ReactDimensions */ 'use strict'; let dimensions = { // Not map to real window size, because that map to screen size in native env. window: { get width() { return document.documentElement.clientWidth; }, get height() { return document.documentElement.clientHeight; }, get scale() { return window.devicePixelRatio || 1; }, }, modalFullscreenView: { width: screen.width, height: screen.height } }; class Dimensions { /** * Initial dimensions are set before `runApplication` is called so they should * be available before any other require's are run, but may be updated later. * * Note: Although dimensions are available immediately, they may change (e.g * due to device rotation) so any rendering logic or styles that depend on * these constants should try to call this function on every render, rather * than caching the value (for example, using inline styles rather than * setting a value in a `StyleSheet`). * * @param {string} dim Name of dimension as defined when calling `set`. * @returns {Object?} Value for the dimension. */ static get(dim: string): Object { return dimensions[dim]; } static addEventListener(event, handler) { } static removeEventListener(event, handler) { } } export default Dimensions;
import React, { useContext } from "react" import { PageLayout, PageTitle } from "../components" import { Container, Image } from "react-bootstrap" import { Link, graphql } from "gatsby" import { ThemeContext, SEO } from "../utils" export default ({ data }) => { const MediaLink = ({ title, author, link }) => ( <li key={title} style={{ color: "gray" }}> <a rel="noopener noreferrer" href={link}> {title} </a> &nbsp;-<i>{author}</i> </li> ) const { author, occupation, readingList, showsList, designations, unemployed, } = data.site.siteMetadata const { toString } = useContext(ThemeContext) const bookLinks = readingList.map(book => MediaLink(book)) const showLinks = showsList.map(show => MediaLink(show)) return ( <PageLayout> <SEO title="About Me" /> <PageTitle title="About Me" /> <Container> <Image rounded width="140" height="140" src={`../../icons/luke-${toString()}.png`} alt={author} /> <article className="w-75 m-auto pt-2 text-justify"> <p className="text-center"> {designations.map((attr, i) => ( <span key={attr}> &nbsp;<b>{attr}</b>&nbsp; {i < designations.length - 1 && <>||</>} </span> ))} </p> <p className="i-5 mt-4 pt-2"> My name is Patrick Carland. I am a grad student at the University of Pennsylvania My research is Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> <p className="i-5"> In my spare time, Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> </article> <article className="w-75 m-auto"> {unemployed && ( <> <hr /> <p className="unemployed"> <small> I am <b>currently looking for new opportunities</b>! If you like what you <Link to="/resume">see</Link>, let's get in&nbsp; <a href="mailto:patrickcarland@gmail.com" target="_blank" rel="noopener noreferrer" > touch </a> ! </small> </p> </> )} <hr /> <h5 className="watch-list-title pt-4"> Here are a couple of books from my reading list: </h5> <ul style={{ fontSize: "0.9rem", listStyle: "none" }}>{bookLinks}</ul> <h5 className="watch-list-title pt-4"> Here are a couple of shows from my watch list: </h5> <ul style={{ fontSize: "0.9rem", listStyle: "none" }}>{showLinks}</ul> <h5 className="watch-list-title pt-4"> Here are a couple of movies from my watch list: </h5> <p> <i>...waaaay too many to list.</i> </p> </article> </Container> </PageLayout> ) } export const query = graphql` query { site { siteMetadata { unemployed occupation author designations readingList { title author link } showsList { title author link } } } } `
const path = require('path'); const fs = require('fs'); const getManifest = () => { try { return JSON.parse( fs.readFileSync( path.resolve(__dirname, '..', 'public/manifest.json') ) ); } catch (error) { console.log(error); } }; module.exports = getManifest;
(function (root) { "use strict"; var buster = root.buster || require("buster"); var sinon = root.sinon || require("../lib/sinon"); var assert = buster.assert; var refute = buster.refute; buster.testCase("sinon.assert", { setUp: function () { this.global = typeof window !== "undefined" ? window : global; this.setUpStubs = function () { this.stub = sinon.stub.create(); sinon.stub(sinon.assert, "fail").throws(); sinon.stub(sinon.assert, "pass"); }; this.tearDownStubs = function () { sinon.assert.fail.restore(); sinon.assert.pass.restore(); }; }, "is object": function () { assert.isObject(sinon.assert); }, "supports proxy property": function () { var failed = false; var api = { method: function () {} }; api.method.proxy = function () {}; sinon.spy(api, "method"); api.method(); try { sinon.assert.calledOnce(api.method); } catch (e) { failed = true; } assert.isFalse(failed); }, ".fail": { setUp: function () { this.exceptionName = sinon.assert.failException; }, tearDown: function () { sinon.assert.failException = this.exceptionName; }, "throws exception": function () { var failed = false; var exception; try { sinon.assert.fail("Some message"); failed = true; } catch (e) { exception = e; } assert.isFalse(failed); assert.equals(exception.name, "AssertError"); }, "throws configured exception type": function () { sinon.assert.failException = "RetardError"; assert.exception(function () { sinon.assert.fail("Some message"); }, "RetardError"); } }, ".match": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when arguments to not match": function () { assert.exception(function () { sinon.assert.match("foo", "bar"); }); assert(sinon.assert.fail.calledOnce); }, "passes when argumens match": function () { sinon.assert.match("foo", "foo"); assert(sinon.assert.pass.calledOnce); } }, ".called": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method does not exist": function () { assert.exception(function () { sinon.assert.called(); }); assert(sinon.assert.fail.called); }, "fails when method is not stub": function () { assert.exception(function () { sinon.assert.called(function () {}); }); assert(sinon.assert.fail.called); }, "fails when method was not called": function () { var stub = this.stub; assert.exception(function () { sinon.assert.called(stub); }); assert(sinon.assert.fail.called); }, "does not fail when method was called": function () { var stub = this.stub; stub(); refute.exception(function () { sinon.assert.called(stub); }); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { var stub = this.stub; stub(); refute.exception(function () { sinon.assert.called(stub); }); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("called")); } }, ".notCalled": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method does not exist": function () { assert.exception(function () { sinon.assert.notCalled(); }); assert(sinon.assert.fail.called); }, "fails when method is not stub": function () { assert.exception(function () { sinon.assert.notCalled(function () {}); }); assert(sinon.assert.fail.called); }, "fails when method was called": function () { var stub = this.stub; stub(); assert.exception(function () { sinon.assert.notCalled(stub); }); assert(sinon.assert.fail.called); }, "passes when method was not called": function () { var stub = this.stub; refute.exception(function () { sinon.assert.notCalled(stub); }); assert.isFalse(sinon.assert.fail.called); }, "should call pass callback": function () { var stub = this.stub; sinon.assert.notCalled(stub); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("notCalled")); } }, ".calledOnce": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method does not exist": function () { assert.exception(function () { sinon.assert.calledOnce(); }); assert(sinon.assert.fail.called); }, "fails when method is not stub": function () { assert.exception(function () { sinon.assert.calledOnce(function () {}); }); assert(sinon.assert.fail.called); }, "fails when method was not called": function () { var stub = this.stub; assert.exception(function () { sinon.assert.calledOnce(stub); }); assert(sinon.assert.fail.called); }, "passes when method was called": function () { var stub = this.stub; stub(); refute.exception(function () { sinon.assert.calledOnce(stub); }); assert.isFalse(sinon.assert.fail.called); }, "fails when method was called more than once": function () { var stub = this.stub; stub(); stub(); assert.exception(function () { sinon.assert.calledOnce(stub); }); assert(sinon.assert.fail.called); }, "calls pass callback": function () { var stub = this.stub; stub(); sinon.assert.calledOnce(stub); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("calledOnce")); } }, ".calledTwice": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails if called once": function () { var stub = this.stub; this.stub(); assert.exception(function () { sinon.assert.calledTwice(stub); }); }, "passes if called twice": function () { var stub = this.stub; this.stub(); this.stub(); refute.exception(function () { sinon.assert.calledTwice(stub); }); }, "calls pass callback": function () { var stub = this.stub; stub(); stub(); sinon.assert.calledTwice(stub); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("calledTwice")); } }, ".calledThrice": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails if called once": function () { var stub = this.stub; this.stub(); assert.exception(function () { sinon.assert.calledThrice(stub); }); }, "passes if called thrice": function () { var stub = this.stub; this.stub(); this.stub(); this.stub(); refute.exception(function () { sinon.assert.calledThrice(stub); }); }, "calls pass callback": function () { var stub = this.stub; stub(); stub(); stub(); sinon.assert.calledThrice(stub); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("calledThrice")); } }, ".callOrder": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "passes when calls where done in right order": function () { var spy1 = sinon.spy(); var spy2 = sinon.spy(); spy1(); spy2(); refute.exception(function () { sinon.assert.callOrder(spy1, spy2); }); }, "fails when calls where done in wrong order": function () { var spy1 = sinon.spy(); var spy2 = sinon.spy(); spy2(); spy1(); assert.exception(function () { sinon.assert.callOrder(spy1, spy2); }); assert(sinon.assert.fail.called); }, "passes when many calls where done in right order": function () { var spy1 = sinon.spy(); var spy2 = sinon.spy(); var spy3 = sinon.spy(); var spy4 = sinon.spy(); spy1(); spy2(); spy3(); spy4(); refute.exception(function () { sinon.assert.callOrder(spy1, spy2, spy3, spy4); }); }, "fails when one of many calls where done in wrong order": function () { var spy1 = sinon.spy(); var spy2 = sinon.spy(); var spy3 = sinon.spy(); var spy4 = sinon.spy(); spy1(); spy2(); spy4(); spy3(); assert.exception(function () { sinon.assert.callOrder(spy1, spy2, spy3, spy4); }); assert(sinon.assert.fail.called); }, "calls pass callback": function () { var stubs = [sinon.spy(), sinon.spy()]; stubs[0](); stubs[1](); sinon.assert.callOrder(stubs[0], stubs[1]); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("callOrder")); }, "passes for multiple calls to same spy": function () { var first = sinon.spy(); var second = sinon.spy(); first(); second(); first(); refute.exception(function () { sinon.assert.callOrder(first, second, first); }); }, "fails if first spy was not called": function () { var first = sinon.spy(); var second = sinon.spy(); second(); assert.exception(function () { sinon.assert.callOrder(first, second); }); }, "fails if second spy was not called": function () { var first = sinon.spy(); var second = sinon.spy(); first(); assert.exception(function () { sinon.assert.callOrder(first, second); }); } }, ".calledOn": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method does not exist": function () { var object = {}; sinon.stub(this.stub, "calledOn"); assert.exception(function () { sinon.assert.calledOn(null, object); }); assert.isFalse(this.stub.calledOn.calledWith(object)); assert(sinon.assert.fail.called); }, "fails when method is not stub": function () { var object = {}; sinon.stub(this.stub, "calledOn"); assert.exception(function () { sinon.assert.calledOn(function () {}, object); }); assert.isFalse(this.stub.calledOn.calledWith(object)); assert(sinon.assert.fail.called); }, "fails when method fails": function () { var object = {}; sinon.stub(this.stub, "calledOn").returns(false); var stub = this.stub; assert.exception(function () { sinon.assert.calledOn(stub, object); }); assert(sinon.assert.fail.called); }, "passes when method doesn't fail": function () { var object = {}; sinon.stub(this.stub, "calledOn").returns(true); var stub = this.stub; sinon.assert.calledOn(stub, object); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { var obj = {}; this.stub.call(obj); sinon.assert.calledOn(this.stub, obj); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("calledOn")); } }, ".calledWithNew": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method does not exist": function () { sinon.stub(this.stub, "calledWithNew"); assert.exception(function () { sinon.assert.calledWithNew(null); }); assert.isFalse(this.stub.calledWithNew.called); assert(sinon.assert.fail.called); }, "fails when method is not stub": function () { sinon.stub(this.stub, "calledWithNew"); assert.exception(function () { sinon.assert.calledWithNew(function () {}); }); assert.isFalse(this.stub.calledWithNew.called); assert(sinon.assert.fail.called); }, "fails when method fails": function () { sinon.stub(this.stub, "calledWithNew").returns(false); var stub = this.stub; assert.exception(function () { sinon.assert.calledWithNew(stub); }); assert(sinon.assert.fail.called); }, "passes when method doesn't fail": function () { sinon.stub(this.stub, "calledWithNew").returns(true); var stub = this.stub; sinon.assert.calledWithNew(stub); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { new this.stub(); // eslint-disable-line no-new, new-cap sinon.assert.calledWithNew(this.stub); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("calledWithNew")); } }, ".alwaysCalledWithNew": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method does not exist": function () { sinon.stub(this.stub, "alwaysCalledWithNew"); assert.exception(function () { sinon.assert.alwaysCalledWithNew(null); }); assert.isFalse(this.stub.alwaysCalledWithNew.called); assert(sinon.assert.fail.called); }, "fails when method is not stub": function () { sinon.stub(this.stub, "alwaysCalledWithNew"); assert.exception(function () { sinon.assert.alwaysCalledWithNew(function () {}); }); assert.isFalse(this.stub.alwaysCalledWithNew.called); assert(sinon.assert.fail.called); }, "fails when method fails": function () { sinon.stub(this.stub, "alwaysCalledWithNew").returns(false); var stub = this.stub; assert.exception(function () { sinon.assert.alwaysCalledWithNew(stub); }); assert(sinon.assert.fail.called); }, "passes when method doesn't fail": function () { sinon.stub(this.stub, "alwaysCalledWithNew").returns(true); var stub = this.stub; sinon.assert.alwaysCalledWithNew(stub); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { new this.stub(); // eslint-disable-line no-new, new-cap sinon.assert.alwaysCalledWithNew(this.stub); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("alwaysCalledWithNew")); } }, ".calledWith": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method fails": function () { var object = {}; sinon.stub(this.stub, "calledWith").returns(false); var stub = this.stub; assert.exception(function () { sinon.assert.calledWith(stub, object, 1); }); assert(this.stub.calledWith.calledWith(object, 1)); assert(sinon.assert.fail.called); }, "passes when method doesn't fail": function () { var object = {}; sinon.stub(this.stub, "calledWith").returns(true); var stub = this.stub; refute.exception(function () { sinon.assert.calledWith(stub, object, 1); }); assert(this.stub.calledWith.calledWith(object, 1)); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { this.stub("yeah"); sinon.assert.calledWith(this.stub, "yeah"); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("calledWith")); }, "works with spyCall": function () { var spy = sinon.spy(); var object = {}; spy(); spy(object); sinon.assert.calledWith(spy.lastCall, object); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("calledWith")); }, "fails when spyCall failed": function () { var spy = sinon.spy(); var object = {}; spy(); spy(object); assert.exception(function () { sinon.assert.calledWith(spy.lastCall, 1); }); assert(sinon.assert.fail.called); } }, ".calledWithExactly": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method fails": function () { var object = {}; sinon.stub(this.stub, "calledWithExactly").returns(false); var stub = this.stub; assert.exception(function () { sinon.assert.calledWithExactly(stub, object, 1); }); assert(this.stub.calledWithExactly.calledWithExactly(object, 1)); assert(sinon.assert.fail.called); }, "passes when method doesn't fail": function () { var object = {}; sinon.stub(this.stub, "calledWithExactly").returns(true); var stub = this.stub; refute.exception(function () { sinon.assert.calledWithExactly(stub, object, 1); }); assert(this.stub.calledWithExactly.calledWithExactly(object, 1)); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { this.stub("yeah"); sinon.assert.calledWithExactly(this.stub, "yeah"); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("calledWithExactly")); } }, ".neverCalledWith": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method fails": function () { var object = {}; sinon.stub(this.stub, "neverCalledWith").returns(false); var stub = this.stub; assert.exception(function () { sinon.assert.neverCalledWith(stub, object, 1); }); assert(this.stub.neverCalledWith.calledWith(object, 1)); assert(sinon.assert.fail.called); }, "passes when method doesn't fail": function () { var object = {}; sinon.stub(this.stub, "neverCalledWith").returns(true); var stub = this.stub; refute.exception(function () { sinon.assert.neverCalledWith(stub, object, 1); }); assert(this.stub.neverCalledWith.calledWith(object, 1)); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { this.stub("yeah"); sinon.assert.neverCalledWith(this.stub, "nah!"); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("neverCalledWith")); } }, ".threwTest": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method fails": function () { sinon.stub(this.stub, "threw").returns(false); var stub = this.stub; assert.exception(function () { sinon.assert.threw(stub, 1, 2); }); assert(this.stub.threw.calledWithExactly(1, 2)); assert(sinon.assert.fail.called); }, "passes when method doesn't fail": function () { sinon.stub(this.stub, "threw").returns(true); var stub = this.stub; refute.exception(function () { sinon.assert.threw(stub, 1, 2); }); assert(this.stub.threw.calledWithExactly(1, 2)); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { sinon.stub(this.stub, "threw").returns(true); this.stub(); sinon.assert.threw(this.stub); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("threw")); } }, ".callCount": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails when method fails": function () { this.stub(); this.stub(); var stub = this.stub; assert.exception(function () { sinon.assert.callCount(stub, 3); }); assert(sinon.assert.fail.called); }, "passes when method doesn't fail": function () { var stub = this.stub; this.stub.callCount = 3; refute.exception(function () { sinon.assert.callCount(stub, 3); }); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { this.stub(); sinon.assert.callCount(this.stub, 1); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("callCount")); } }, ".alwaysCalledOn": { setUp: function () { this.setUpStubs(); }, tearDown: function () { this.tearDownStubs(); }, "fails if method is missing": function () { assert.exception(function () { sinon.assert.alwaysCalledOn(); }); }, "fails if method is not fake": function () { assert.exception(function () { sinon.assert.alwaysCalledOn(function () {}, {}); }); }, "fails if stub returns false": function () { var stub = sinon.stub(); sinon.stub(stub, "alwaysCalledOn").returns(false); assert.exception(function () { sinon.assert.alwaysCalledOn(stub, {}); }); assert(sinon.assert.fail.called); }, "passes if stub returns true": function () { var stub = sinon.stub.create(); sinon.stub(stub, "alwaysCalledOn").returns(true); sinon.assert.alwaysCalledOn(stub, {}); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { this.stub(); sinon.assert.alwaysCalledOn(this.stub, this); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("alwaysCalledOn")); } }, ".alwaysCalledWith": { setUp: function () { sinon.stub(sinon.assert, "fail").throws(); sinon.stub(sinon.assert, "pass"); }, tearDown: function () { sinon.assert.fail.restore(); sinon.assert.pass.restore(); }, "fails if method is missing": function () { assert.exception(function () { sinon.assert.alwaysCalledWith(); }); }, "fails if method is not fake": function () { assert.exception(function () { sinon.assert.alwaysCalledWith(function () {}); }); }, "fails if stub returns false": function () { var stub = sinon.stub.create(); sinon.stub(stub, "alwaysCalledWith").returns(false); assert.exception(function () { sinon.assert.alwaysCalledWith(stub, {}, []); }); assert(sinon.assert.fail.called); }, "passes if stub returns true": function () { var stub = sinon.stub.create(); sinon.stub(stub, "alwaysCalledWith").returns(true); sinon.assert.alwaysCalledWith(stub, {}, []); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { var spy = sinon.spy(); spy("Hello"); sinon.assert.alwaysCalledWith(spy, "Hello"); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("alwaysCalledWith")); } }, ".alwaysCalledWithExactly": { setUp: function () { sinon.stub(sinon.assert, "fail"); sinon.stub(sinon.assert, "pass"); }, tearDown: function () { sinon.assert.fail.restore(); sinon.assert.pass.restore(); }, "fails if stub returns false": function () { var stub = sinon.stub.create(); sinon.stub(stub, "alwaysCalledWithExactly").returns(false); sinon.assert.alwaysCalledWithExactly(stub, {}, []); assert(sinon.assert.fail.called); }, "passes if stub returns true": function () { var stub = sinon.stub.create(); sinon.stub(stub, "alwaysCalledWithExactly").returns(true); sinon.assert.alwaysCalledWithExactly(stub, {}, []); assert.isFalse(sinon.assert.fail.called); }, "calls pass callback": function () { var spy = sinon.spy(); spy("Hello"); sinon.assert.alwaysCalledWithExactly(spy, "Hello"); assert(sinon.assert.pass.calledOnce); assert(sinon.assert.pass.calledWith("alwaysCalledWithExactly")); } }, ".expose": { "exposes asserts into object": function () { var test = {}; sinon.assert.expose(test); assert.isFunction(test.fail); assert.isString(test.failException); assert.isFunction(test.assertCalled); assert.isFunction(test.assertCalledOn); assert.isFunction(test.assertCalledWith); assert.isFunction(test.assertCalledWithExactly); assert.isFunction(test.assertThrew); assert.isFunction(test.assertCallCount); }, "exposes asserts into global": function () { sinon.assert.expose(this.global, { includeFail: false }); assert.equals(typeof failException, "undefined"); /*eslint-disable no-undef*/ assert.isFunction(assertCalled); assert.isFunction(assertCalledOn); assert.isFunction(assertCalledWith); assert.isFunction(assertCalledWithExactly); assert.isFunction(assertThrew); assert.isFunction(assertCallCount); /*eslint-enable no-undef*/ }, "fails exposed asserts without errors": function () { sinon.assert.expose(this.global, { includeFail: false }); try { assertCalled(sinon.spy()); // eslint-disable-line no-undef } catch (e) { assert.equals(e.message, "expected spy to have been called at least once but was never called"); } }, "exposes asserts into object without prefixes": function () { var test = {}; sinon.assert.expose(test, { prefix: "" }); assert.isFunction(test.fail); assert.isString(test.failException); assert.isFunction(test.called); assert.isFunction(test.calledOn); assert.isFunction(test.calledWith); assert.isFunction(test.calledWithExactly); assert.isFunction(test.threw); assert.isFunction(test.callCount); }, "does not expose 'expose'": function () { var test = {}; sinon.assert.expose(test, { prefix: "" }); refute(test.expose, "Expose should not be exposed"); }, "throws if target is undefined": function () { assert.exception(function () { sinon.assert.expose(); }, "TypeError"); }, "throws if target is null": function () { assert.exception(function () { sinon.assert.expose(null); }, "TypeError"); } }, message: { setUp: function () { this.obj = { doSomething: function () {} }; sinon.spy(this.obj, "doSomething"); this.message = function (method) { try { sinon.assert[method].apply(sinon.assert, [].slice.call(arguments, 1)); } catch (e) { return e.message; } }; }, "assert.called exception message": function () { assert.equals(this.message("called", this.obj.doSomething), "expected doSomething to have been called at " + "least once but was never called"); }, "assert.notCalled exception message one call": function () { this.obj.doSomething(); assert.equals(this.message("notCalled", this.obj.doSomething).replace(/ at.*/g, ""), "expected doSomething to not have been called " + "but was called once\n doSomething()"); }, "assert.notCalled exception message four calls": function () { this.obj.doSomething(); this.obj.doSomething(); this.obj.doSomething(); this.obj.doSomething(); assert.equals(this.message("notCalled", this.obj.doSomething).replace(/ at.*/g, ""), "expected doSomething to not have been called " + "but was called 4 times\n doSomething()\n " + "doSomething()\n doSomething()\n doSomething()"); }, "assert.notCalled exception message with calls with arguments": function () { this.obj.doSomething(); this.obj.doSomething(3); this.obj.doSomething(42, 1); this.obj.doSomething(); assert.equals(this.message("notCalled", this.obj.doSomething).replace(/ at.*/g, ""), "expected doSomething to not have been called " + "but was called 4 times\n doSomething()\n " + "doSomething(3)\n doSomething(42, 1)\n doSomething()"); }, "assert.callOrder exception message": function () { var obj = { doop: function () {}, foo: function () {} }; sinon.spy(obj, "doop"); sinon.spy(obj, "foo"); obj.doop(); this.obj.doSomething(); obj.foo(); var message = this.message("callOrder", this.obj.doSomething, obj.doop, obj.foo); assert.equals(message, "expected doSomething, doop, foo to be called in " + "order but were called as doop, doSomething, foo"); }, "assert.callOrder with missing first call exception message": function () { var obj = { doop: function () {}, foo: function () {} }; sinon.spy(obj, "doop"); sinon.spy(obj, "foo"); obj.foo(); var message = this.message("callOrder", obj.doop, obj.foo); assert.equals(message, "expected doop, foo to be called in " + "order but were called as foo"); }, "assert.callOrder with missing last call exception message": function () { var obj = { doop: function () {}, foo: function () {} }; sinon.spy(obj, "doop"); sinon.spy(obj, "foo"); obj.doop(); var message = this.message("callOrder", obj.doop, obj.foo); assert.equals(message, "expected doop, foo to be called in " + "order but were called as doop"); }, "assert.callCount exception message": function () { this.obj.doSomething(); assert.equals(this.message("callCount", this.obj.doSomething, 3).replace(/ at.*/g, ""), "expected doSomething to be called thrice but was called " + "once\n doSomething()"); }, "assert.calledOnce exception message": function () { this.obj.doSomething(); this.obj.doSomething(); assert.equals(this.message("calledOnce", this.obj.doSomething).replace(/ at.*/g, ""), "expected doSomething to be called once but was called " + "twice\n doSomething()\n doSomething()"); this.obj.doSomething(); assert.equals(this.message("calledOnce", this.obj.doSomething).replace(/ at.*/g, ""), "expected doSomething to be called once but was called " + "thrice\n doSomething()\n doSomething()\n doSomething()"); }, "assert.calledTwice exception message": function () { this.obj.doSomething(); assert.equals(this.message("calledTwice", this.obj.doSomething).replace(/ at.*/g, ""), "expected doSomething to be called twice but was called " + "once\n doSomething()"); }, "assert.calledThrice exception message": function () { this.obj.doSomething(); this.obj.doSomething(); this.obj.doSomething(); this.obj.doSomething(); assert.equals( this.message("calledThrice", this.obj.doSomething).replace(/ at.*/g, ""), "expected doSomething to be called thrice but was called 4 times\n" + " doSomething()\n doSomething()\n doSomething()\n doSomething()" ); }, "assert.calledOn exception message": function () { this.obj.toString = function () { return "[Oh yeah]"; }; var obj = { toString: function () { return "[Oh no]"; } }; var obj2 = { toString: function () { return "[Oh well]"; } }; this.obj.doSomething.call(obj); this.obj.doSomething.call(obj2); assert.equals( this.message("calledOn", this.obj.doSomething, this.obj), "expected doSomething to be called with [Oh yeah] as this but was called with [Oh no], [Oh well]" ); }, "assert.alwaysCalledOn exception message": function () { this.obj.toString = function () { return "[Oh yeah]"; }; var obj = { toString: function () { return "[Oh no]"; } }; var obj2 = { toString: function () { return "[Oh well]"; } }; this.obj.doSomething.call(obj); this.obj.doSomething.call(obj2); this.obj.doSomething(); assert.equals( this.message("alwaysCalledOn", this.obj.doSomething, this.obj), "expected doSomething to always be called with [Oh yeah] as this but was called with " + "[Oh no], [Oh well], [Oh yeah]" ); }, "assert.calledWithNew exception message": function () { this.obj.doSomething(); assert.equals(this.message("calledWithNew", this.obj.doSomething), "expected doSomething to be called with new"); }, "assert.alwaysCalledWithNew exception message": function () { new this.obj.doSomething(); // eslint-disable-line no-new, new-cap this.obj.doSomething(); assert.equals(this.message("alwaysCalledWithNew", this.obj.doSomething), "expected doSomething to always be called with new"); }, "assert.calledWith exception message": function () { this.obj.doSomething(1, 3, "hey"); assert.equals(this.message("calledWith", this.obj.doSomething, 4, 3, "hey").replace(/ at.*/g, ""), "expected doSomething to be called with arguments 4, 3, " + "hey\n doSomething(1, 3, hey)"); }, "assert.calledWith match.any exception message": function () { this.obj.doSomething(true, true); assert.equals( this.message("calledWith", this.obj.doSomething, sinon.match.any, false).replace(/ at.*/g, ""), "expected doSomething to be called with arguments any, false\n doSomething(true, true)" ); }, "assert.calledWith match.defined exception message": function () { this.obj.doSomething(); assert.equals( this.message("calledWith", this.obj.doSomething, sinon.match.defined).replace(/ at.*/g, ""), "expected doSomething to be called with arguments defined\n doSomething()" ); }, "assert.calledWith match.truthy exception message": function () { this.obj.doSomething(); assert.equals( this.message("calledWith", this.obj.doSomething, sinon.match.truthy).replace(/ at.*/g, ""), "expected doSomething to be called with arguments truthy\n doSomething()" ); }, "assert.calledWith match.falsy exception message": function () { this.obj.doSomething(true); assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match.falsy).replace(/ at.*/g, ""), "expected doSomething to be called with arguments " + "falsy\n doSomething(true)"); }, "assert.calledWith match.same exception message": function () { this.obj.doSomething(); assert.equals( this.message("calledWith", this.obj.doSomething, sinon.match.same(1)).replace(/ at.*/g, ""), "expected doSomething to be called with arguments same(1)\n doSomething()" ); }, "assert.calledWith match.typeOf exception message": function () { this.obj.doSomething(); var matcher = sinon.match.typeOf("string"); assert.equals( this.message("calledWith", this.obj.doSomething, matcher).replace(/ at.*/g, ""), "expected doSomething to be called with arguments typeOf(\"string\")\n doSomething()" ); }, "assert.calledWith match.instanceOf exception message": function () { this.obj.doSomething(); var matcher = sinon.match.instanceOf(function CustomType() {}); assert.equals( this.message("calledWith", this.obj.doSomething, matcher).replace(/ at.*/g, ""), "expected doSomething to be called with arguments instanceOf(CustomType)\n doSomething()" ); }, "assert.calledWith match object exception message": function () { this.obj.doSomething(); var matcher = sinon.match({ some: "value", and: 123 }); assert.equals( this.message("calledWith", this.obj.doSomething, matcher).replace(/ at.*/g, ""), "expected doSomething to be called with arguments match(some: value, and: 123)\n doSomething()" ); }, "assert.calledWith match boolean exception message": function () { this.obj.doSomething(); assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match(true)).replace(/ at.*/g, ""), "expected doSomething to be called with arguments " + "match(true)\n doSomething()"); }, "assert.calledWith match number exception message": function () { this.obj.doSomething(); assert.equals(this.message("calledWith", this.obj.doSomething, sinon.match(123)).replace(/ at.*/g, ""), "expected doSomething to be called with arguments " + "match(123)\n doSomething()"); }, "assert.calledWith match string exception message": function () { this.obj.doSomething(); var matcher = sinon.match("Sinon"); assert.equals(this.message("calledWith", this.obj.doSomething, matcher).replace(/ at.*/g, ""), "expected doSomething to be called with arguments " + "match(\"Sinon\")\n doSomething()"); }, "assert.calledWith match regexp exception message": function () { this.obj.doSomething(); assert.equals( this.message("calledWith", this.obj.doSomething, sinon.match(/[a-z]+/)).replace(/ at.*/g, ""), "expected doSomething to be called with arguments match(/[a-z]+/)\n doSomething()" ); }, "assert.calledWith match test function exception message": function () { this.obj.doSomething(); var matcher = sinon.match({ test: function custom() {} }); assert.equals( this.message("calledWith", this.obj.doSomething, matcher).replace(/ at.*/g, ""), "expected doSomething to be called with arguments match(custom)\n doSomething()" ); }, "assert.calledWithMatch exception message": function () { this.obj.doSomething(1, 3, "hey"); assert.equals(this.message("calledWithMatch", this.obj.doSomething, 4, 3, "hey").replace(/ at.*/g, ""), "expected doSomething to be called with match 4, 3, " + "hey\n doSomething(1, 3, hey)"); }, "assert.alwaysCalledWith exception message": function () { this.obj.doSomething(1, 3, "hey"); this.obj.doSomething(1, "hey"); assert.equals(this.message("alwaysCalledWith", this.obj.doSomething, 1, "hey").replace(/ at.*/g, ""), "expected doSomething to always be called with arguments 1" + ", hey\n doSomething(1, 3, hey)\n doSomething(1, hey)"); }, "assert.alwaysCalledWithMatch exception message": function () { this.obj.doSomething(1, 3, "hey"); this.obj.doSomething(1, "hey"); assert.equals( this.message("alwaysCalledWithMatch", this.obj.doSomething, 1, "hey").replace(/ at.*/g, ""), "expected doSomething to always be called with match 1" + ", hey\n doSomething(1, 3, hey)\n doSomething(1, hey)" ); }, "assert.calledWithExactly exception message": function () { this.obj.doSomething(1, 3, "hey"); assert.equals(this.message("calledWithExactly", this.obj.doSomething, 1, 3).replace(/ at.*/g, ""), "expected doSomething to be called with exact arguments 1" + ", 3\n doSomething(1, 3, hey)"); }, "assert.alwaysCalledWithExactly exception message": function () { this.obj.doSomething(1, 3, "hey"); this.obj.doSomething(1, 3); assert.equals(this.message("alwaysCalledWithExactly", this.obj.doSomething, 1, 3).replace(/ at.*/g, ""), "expected doSomething to always be called with exact " + "arguments 1, 3\n doSomething(1, 3, hey)\n " + "doSomething(1, 3)"); }, "assert.neverCalledWith exception message": function () { this.obj.doSomething(1, 2, 3); assert.equals(this.message("neverCalledWith", this.obj.doSomething, 1, 2).replace(/ at.*/g, ""), "expected doSomething to never be called with " + "arguments 1, 2\n doSomething(1, 2, 3)"); }, "assert.neverCalledWithMatch exception message": function () { this.obj.doSomething(1, 2, 3); assert.equals(this.message("neverCalledWithMatch", this.obj.doSomething, 1, 2).replace(/ at.*/g, ""), "expected doSomething to never be called with match " + "1, 2\n doSomething(1, 2, 3)"); }, "assert.threw exception message": function () { this.obj.doSomething(1, 3, "hey"); this.obj.doSomething(1, 3); assert.equals(this.message("threw", this.obj.doSomething).replace(/ at.*/g, ""), "doSomething did not throw exception\n" + " doSomething(1, 3, hey)\n doSomething(1, 3)"); }, "assert.alwaysThrew exception message": function () { this.obj.doSomething(1, 3, "hey"); this.obj.doSomething(1, 3); assert.equals(this.message("alwaysThrew", this.obj.doSomething).replace(/ at.*/g, ""), "doSomething did not always throw exception\n" + " doSomething(1, 3, hey)\n doSomething(1, 3)"); }, "assert.match exception message": function () { assert.equals(this.message("match", { foo: 1 }, [1, 3]), "expected value to match\n" + " expected = [1, 3]\n" + " actual = { foo: 1 }"); } } }); }(this));
/****************************************************************************** * * Copyright (c) 2017, the Perspective Authors. * * This file is part of the Perspective library, distributed under the terms of * the Apache License 2.0. The full license can be found in the LICENSE file. * */ import arrow from "../arrow/test-null.arrow"; var arrow_psp_internal_schema = [9, 10, 1, 2, 3, 4, 11, 19, 19, 12, 12, 12, 2]; module.exports = (perspective, mode) => { describe("Internal API", function() { it("is actually using the correct runtime", async function() { expect(perspective.__module__.wasmJSMethod).toEqual(mode === "ASMJS" ? "asmjs" : "native-wasm"); }); it("['z'], sum with new column syntax with wrong column arity errors", async function() { var table = perspective.table(arrow.slice()); let anon = function() { table.view({ row_pivot: ["char"], aggregate: [{op: "sum", column: ["f16", "f32"]}] }); }; expect(anon).toThrow(); }); it("Arrow schema types are mapped correctly", async function() { // This only works for non parallel var table = perspective.table(arrow.slice()); let schema, stypes; let types = []; try { schema = table.gnode.get_tblschema(); stypes = schema.types(); for (let i = 0; i < stypes.size(); i++) { types.push(stypes.get(i).value); } expect(arrow_psp_internal_schema).toEqual(types); } finally { if (schema) { schema.delete(); } if (stypes) { stypes.delete(); } } }); }); };
const utils = require('../utils'); const functionalComponentCompose = require('../compose/functionalComponent'); // TODO: Badge with typeof value === 'string' should use RNE Text rather than native one... const COMPOSE_NAME = 'Badge'; const compose = functionalComponentCompose.construct(COMPOSE_NAME); module.exports = { name: COMPOSE_NAME, compose, override: new utils.ModuleOverride( COMPOSE_NAME, require('react-native-elements/src/badge/badge'), compose, true, ), };
'use strict'; var request = require('request'); var cheerio = require('cheerio'); const TARGET_URL = 'https://service.berlin.de/terminvereinbarung/termin/tag.php?termin=1&anliegen[]=121627&dienstleisterlist=122210,122217,122219,122227,122231,122238,122243,122252,122260,122262,122254,122271,122273,122277,122280,122282,122284,122291,122285,122286,122296,150230,122301,122297,122294,122312,122314,122304,122311,122309,317869,324433,325341,324434,122281,324414,122283,122279,122276,122274,122267,122246,122251,122257,122208,122226,121646&herkunft=http%3A%2F%2Fservice.berlin.de%2Fdienstleistung%2F121627%2F'; var checkForAvailableTermin = () => { console.log('> checking for termins...'); request(TARGET_URL, (error, response, body) => { if(error) { console.log("Error: " + error); } console.log("Status code: " + response.statusCode); var $ = cheerio.load(body); let availableTerminList = $('.calendar-month-table:first-child td.buchbar a'); if (availableTerminList.length > 0) { availableTerminList.each((index) => { //we have a open booking let day = $(this).text(); let month = $(this).parentsUntil('th.month').text() console.log('!!!! OPEN BOOKING ON %s %s ! Go, go, go!', day, month); }); } else { console.log('> No available termins found') } }); }; console.log('>> Starting script') checkForAvailableTermin(); setInterval(checkForAvailableTermin, 60000)
function main() { const v2 = []; const v3 = {keyFor:"undefined",race:1337,trimEnd:1337,MAX_SAFE_INTEGER:1337,ignoreCase:v2,acosh:v2}; const v5 = [485105.67948907684,485105.67948907684]; function v6(v7,v8,v9,v10) { } function v11(v12,v13,v14,v15) { if (v15) { } else { const v20 = []; const v22 = [v20,13.37]; function v23(v24,v25,v26,v27) { } function v28(v29,v30,v31,v32) { } const v33 = {preventExtension:v28,get:v23,deleteProperty:v28,has:v28,defineProperty:v28,getOwnPropertyDescriptor:v23,call:v23,set:"undefined",ownKeys:v28,setPrototypeOf:v23,construct:v28}; const v35 = new BigInt64Array(v22,v33); } const v38 = [13.37,13.37,13.37,13.37,13.37]; const v40 = [1177788906,1177788906,13.37,1177788906]; const v41 = [v38]; const v42 = {LN10:Boolean,clear:v38,multiline:"3WGX7UQqsB",isSafeInteger:v38,exec:3127154443,assign:v41,call:13.37}; const v43 = {parseFloat:v40,asinh:1177788906,lastMatch:v42,subarray:3127154443,toExponential:1177788906}; let v46 = v11; const v47 = new Promise(v46,v43,13.37,v43); } const v48 = {preventExtension:v11,get:v6,deleteProperty:v11,has:v11,defineProperty:v11,getOwnPropertyDescriptor:v6,call:v6,set:v11,ownKeys:v11,setPrototypeOf:v6,construct:v11}; const v50 = new Proxy(v5,v48); const v51 = "undefined"[v3]; const v52 = v11(v50,v6,v11,v6,v51); } %NeverOptimizeFunction(main); main();
var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); // homework 4 var ordersRouter = require('./routes/orders'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); 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'))); app.use('/', indexRouter); app.use('/users', usersRouter); // homework 4 app.use('/orders',ordersRouter); // catch 404 and forward to error handler app.use(function(req, res, next) { next(createError(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('error'); }); module.exports = app;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _express = require('express'); var _express2 = _interopRequireDefault(_express); var _verify = require('./verify'); var _verify2 = _interopRequireDefault(_verify); var _config = require('./config'); var _config2 = _interopRequireDefault(_config); var _pg = require('pg'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var router = _express2.default.Router(); _config2.default.connect().then(function () { return console.log('connected'); }).catch(function (err) { return console.error('connection error', err.stack); }); _config2.default.connect().then(function () { return console.log('connected'); }).catch(function (err) { return console.error('connection error', err.stack); }); router.route('/').get(_verify2.default.verifyAdmin, function (req, res) { _config2.default.query(' SELECT user_tbl.id,order_tbl.order_id, username , address,instruction,status,phone,food,createdate,modifiedate FROM user_tbl INNER JOIN order_tbl ON uid = user_tbl.id', function (error, results) { if (error) { res.json({ "code": 400, "failed": 'The order Table was not Generated' }); } else { res.json({ "code": 200, "success": "The order Table was Generated", "table": results.rows }); } }); }); router.route('/:id').get(_verify2.default.verifyAdmin, function (req, res) { var id = +req.params.id; _config2.default.query('SELECT * FROM order_tbl WHERE order_id = $1', [id], function (error, results) { if (error) { res.json({ "code": 400, "failed": 'The order Table was not Generated, ' + id + ' must be an interger' }); } else { var successMessage = results.rows.length ? 'The order related to the id ' + id + ' was fetched' : 'There is no order related to the provided id ' + id; res.json({ "code": 200, "success": successMessage, "table": results.rows }); } }); }); router.route('/:id').put(_verify2.default.verifyAdmin, function (req, res) { var orderId = +req.params.id; var status = req.body.status; var statusPattern = /(completed|new|processing|cancelled)/i; if (statusPattern.test(status)) status = req.body.status; _config2.default.query('UPDATE order_tbl SET (status,modifiedate) = ($1,current_timestamp) WHERE order_id = $2', [status, orderId], function (error) { if (error) { res.json({ "code": 400, "failed": error }); } else { res.json({ "code": 200, "success": "Order Status has been updated" }); } }); }); router.post('/', function (req, res) { var phone = void 0; var uid = +req.body.uid; var address = req.body.address; var instruction = req.body.instruction; var Originalfood = req.body.food; var phonePattern = /[0-9]{11}/; if (phonePattern.test(req.body.phone) && req.body.phone.length === 11) { phone = req.body.phone; } var food = Originalfood.map(function (value) { return value + ""; }); _config2.default.query('INSERT INTO order_tbl (uid,address,instruction,phone,food,createdate,modifiedate) VALUES ($1,$2,$3,$4,ARRAY [$5],current_timestamp,current_timestamp)', [uid, address, instruction, phone, food], function (error, results) { if (error) { res.json({ "code": 400, "failed": error.detail }); } else { var addedOrder = { uid: uid, address: address, instruction: instruction, phone: phone, food: food }; res.json({ "code": 200, "message": "Your order has been placed!", addedOrder: addedOrder }); } }); }); exports.default = router; module.exports = exports.default;
window.Mapbender = Mapbender || {}; window.Mapbender.WmsSourceLayer = (function() { function WmsSourceLayer() { Mapbender.SourceLayer.apply(this, arguments); } Mapbender.SourceLayer.typeMap['wms'] = WmsSourceLayer; WmsSourceLayer.prototype = Object.create(Mapbender.SourceLayer.prototype); Object.assign(WmsSourceLayer.prototype, { constructor: WmsSourceLayer, getId: function() { return this.options.id; }, getSelected: function() { return this.options.treeOptions.selected; }, setSelected: function(state) { this.options.treeOptions.selected = !!state; }, getSelectedList: function() { var selectedLayers = []; if (this.getSelected()) { selectedLayers.push(this); } for (var i = 0; i < this.children.length; ++i) { selectedLayers = selectedLayers.concat(this.children[i].getSelectedList()); } return selectedLayers; }, isInScale: function(scale) { // NOTE: undefined / "open" limits are null, but it's safe to treat zero and null // equivalently var min = this.options.minScale; var max = this.options.maxScale; if (min && min > scale) { return false; } else { return !(max && max < scale); } }, intersectsExtent: function(extent, srsName) { var layerExtent = this.getBounds('EPSG:4326', false); if (layerExtent === null) { // unlimited layer extent return true; } var extent_; if (srsName !== 'EPSG:4326') { extent_ = Mapbender.mapEngine.transformBounds(extent, srsName, 'EPSG:4326'); } else { extent_ = extent; } return Mapbender.Util.extentsIntersect(extent_, layerExtent); } }); return WmsSourceLayer; }()); window.Mapbender.WmsSource = (function() { // @todo: add containing Layerset object to constructor (currently post-instantiation-patched in application setup) function WmsSource(definition) { Mapbender.Source.apply(this, arguments); var customParams = {}; if (definition.customParams) { $.extend(this.customParams, definition.customParams); } (definition.configuration.options.dimensions || []).map(function(dimensionConfig) { if (dimensionConfig.default) { customParams[dimensionConfig.__name] = dimensionConfig.default; } }); this.customParams = customParams; } WmsSource.prototype = Object.create(Mapbender.Source.prototype); WmsSource.prototype.constructor = WmsSource; Mapbender.Source.typeMap['wms'] = WmsSource; Object.assign(WmsSource.prototype, { // We must remember custom params for serialization in getMapState()... customParams: {}, // ... but we will not remember the following ~standard WMS params the same way _runtimeParams: ['LAYERS', 'STYLES', 'EXCEPTIONS', 'QUERY_LAYERS', 'INFO_FORMAT', '_OLSALT'], /** * @param {String} srsName * @param {Object} [mapOptions] * @return {Array<Object>} */ createNativeLayers: function(srsName, mapOptions) { return [Mapbender.mapEngine.createWmsLayer(this, mapOptions)]; }, /** * @return {SourceSettings} */ getSettings: function() { var selectedLayers = this.configuration.children[0].getSelectedList(); var selectedIds = selectedLayers.map(function(layer) { return layer.getId(); }); return Object.assign(Mapbender.Source.prototype.getSettings.call(this), { selectedIds: selectedIds }); }, /** * @param {SourceSettingsDiff|null} diff */ applySettingsDiff: function(diff) { Mapbender.Source.prototype.applySettingsDiff.call(this, diff); if (diff && ((diff.activate || []).length || (diff.deactivate || []).length)) { Mapbender.Util.SourceTree.iterateLayers(this, false, function(layer) { if (-1 !== (diff.activate || []).indexOf(layer.getId())) { layer.setSelected(true); } if (-1 !== (diff.deactivate || []).indexOf(layer.getId())) { layer.setSelected(false); } }); } }, getSelected: function() { // delegate to root layer return this.configuration.children[0].getSelected(); }, addParams: function(params) { for (var i = 0; i < this.nativeLayers.length; ++i) { Mapbender.mapEngine.applyWmsParams(this.nativeLayers[i], params); } var rtp = this._runtimeParams; $.extend(this.customParams, _.omit(params, function(value, key) { return -1 !== rtp.indexOf(('' + key).toUpperCase()); })); }, removeParams: function(names) { // setting a param to null effectively removes it from the generated URL // see https://github.com/openlayers/ol2/blob/release-2.13.1/lib/OpenLayers/Util.js#L514 // see https://github.com/openlayers/ol2/blob/release-2.13.1/lib/OpenLayers/Layer/HTTPRequest.js#L197 // see https://github.com/openlayers/openlayers/blob/v4.6.5/src/ol/uri.js#L16 var nullParams = _.object(names, names.map(function() { return null; })); this.addParams(nullParams); }, toJSON: function() { var s = Mapbender.Source.prototype.toJSON.apply(this, arguments); s.customParams = this.customParams; return s; }, updateEngine: function() { var layers = [], styles = []; Mapbender.Util.SourceTree.iterateSourceLeaves(this, false, function(layer) { // Layer names can be emptyish, most commonly on root layers // Suppress layers with empty names entirely if (layer.options.name && layer.state.visibility) { layers.push(layer.options.name); styles.push(layer.options.style || ''); } }); var engine = Mapbender.mapEngine; var targetVisibility = !!layers.length && this.getActive(); var olLayer = this.getNativeLayer(0); var visibilityChanged = targetVisibility !== engine.getLayerVisibility(olLayer); var paramsChanged = engine.compareWmsParams(olLayer, layers, styles); if (!visibilityChanged && !paramsChanged) { return; } if (paramsChanged && olLayer.map && olLayer.map.tileManager) { olLayer.map.tileManager.clearTileQueue({ object: olLayer }); } if (!targetVisibility) { engine.setLayerVisibility(olLayer, false); } else { var newParams = { LAYERS: layers, STYLES: styles }; if (visibilityChanged) { // Prevent the browser from reusing the loaded image. This is almost equivalent // to a forced redraw (c.f. olLayer.redraw(true)), but without the undesirable // side effect of loading the layer twice on first activation. // @see https://github.com/openlayers/ol2/blob/master/lib/OpenLayers/Layer/HTTPRequest.js#L157 newParams['_OLSALT'] = Math.random(); } engine.applyWmsParams(olLayer, newParams); engine.setLayerVisibility(olLayer, true); } }, /** * @return {Array<WmsSourceLayer>} */ getFeatureInfoLayers: function() { var layers = []; Mapbender.Util.SourceTree.iterateSourceLeaves(this, false, function(layer) { // Layer names can be emptyish, most commonly on root layers // Suppress layers with empty names entirely if (layer.options.name && layer.state.info) { layers.push(layer); } }); return layers; }, /** * Overview support hack: get names of all 'selected' leaf layers (c.f. instance backend), * disregarding 'allowed', disregarding 'state', not recalculating out of scale / out of bounds etc. */ getActivatedLeaves: function() { var layers = []; Mapbender.Util.SourceTree.iterateSourceLeaves(this, false, function(node, index, parents) { var selected = node.options.treeOptions.selected; for (var pi = 0; selected && pi < parents.length; ++pi) { selected = selected && parents[pi].options.treeOptions.selected; } if (selected) { layers.push(node); } }); return layers; }, hasVisibleLayers: function(srsName) { var activatedLayers = this.getActivatedLeaves(); var nonEmptyLayerNames = activatedLayers.map(function(sourceLayer) { return sourceLayer.options.name; }).filter(function(layerName) { return !!layerName; }); return !!nonEmptyLayerNames.length; }, /** * Build base params (no SRS / CRS / BBOX considerations) for GetMap * request. * * @return Object<String, (String | (Array<String>)) */ getGetMapRequestBaseParams: function() { var params = { LAYERS: [], STYLES: [], VERSION: this.configuration.options.version, FORMAT: this.configuration.options.format || null }; var activatedLeaves = this.getActivatedLeaves(); for (var i = 0; i < activatedLeaves.length; ++i) { var sourceLayer = activatedLeaves[i]; // skip layers with empty name (valid for group container layers that cannot be requested directly) if (!!sourceLayer.options.name) { params.LAYERS.push(sourceLayer.options.name); // @todo: use configured style params.STYLES.push(''); } } return params; }, _isBboxFlipped: function(srsName) { if (this.configuration.options.version === '1.3.0') { return Mapbender.mapEngine.isProjectionAxisFlipped(srsName); } else { return false; } }, /** * @param {*} bounds * @param {Number} scale * @param {String} srsName * @return {Array<Object>} */ getPrintConfigs: function(bounds, scale, srsName) { var baseUrl = Mapbender.mapEngine.getWmsBaseUrl(this.getNativeLayer(0), srsName, true); var extraParams = { REQUEST: 'GetMap', // required for tunnel resolution VERSION: this.configuration.options.version, FORMAT: this.configuration.options.format || 'image/png' }; var dataOut = []; var leafInfoMap = Mapbender.Geo.SourceHandler.getExtendedLeafInfo(this, scale, bounds); var resFromScale = function(scale) { return (scale && Mapbender.Model.scaleToResolution(scale, undefined, srsName)) || null; }; var commonOptions = Object.assign({}, this._getPrintBaseOptions(), { changeAxis: this._isBboxFlipped(srsName) }); _.forEach(leafInfoMap, function(item) { if (item.state.visibility) { var replaceParams = Object.assign({}, extraParams, { LAYERS: item.layer.options.name, STYLES: item.layer.options.style || '' }); var layerUrl = Mapbender.Util.replaceUrlParams(baseUrl, replaceParams, false); dataOut.push(Object.assign({}, commonOptions, { url: layerUrl, minResolution: resFromScale(item.layer.options.minScale), maxResolution: resFromScale(item.layer.options.maxScale), order: item.order })); } }); return dataOut.sort(function(a, b) { return a.order - b.order; }); } }); return WmsSource; }()); if(window.OpenLayers) { /** * This suppresses broken requests from MapQuery layers that get stuck with a * constantly empty LAYERS=... param. * * @return {boolean} Whether the layer is in range or not */ OpenLayers.Layer.WMS.prototype.calculateInRange = function(){ if(!this.params.LAYERS || !this.params.LAYERS.length) { return false; } return OpenLayers.Layer.prototype.calculateInRange.apply(this, arguments); } }
let i = 100; let iarr = [1, 2, 3]; let s2 = ''; let j = 99; addj(iarr); for (let j = 0; j < iarr.length; ++j) { let s1 = 'Hello'; s2 = s1; i = j; console.log(iarr[j]); } //console.log(s1) // Error let s1 = 'World'; console.log(s1, s2); console.log('i=', i); console.log('j=', j); j = 0; function addj(arr) { console.log('j=', j); for (let i = 0; i < arr.length; ++i) { arr[i] += j; } }
var name = "Friend of the Urth"; var collection_type = 0; var is_secret = 0; var desc = "Made 53 wholesome Urth Blocks"; var status_text = "From the dirt packed under your fingernails, the mud in your hair, and the ripe smell of Glitchly sweat emanating from your underpits, everyone knows you are a true Friend of the Urth. Also because you have this badge! Yay!"; var last_published = 1340307652; var is_shareworthy = 0; var url = "friend-of-the-urth"; var category = "industrial"; var url_swf = "http:\/\/c2.glitch.bz\/achievements\/2012-06-14\/friend_of_the_urth_1339698045.swf"; var url_img_180 = "http:\/\/c2.glitch.bz\/achievements\/2012-06-14\/friend_of_the_urth_1339698045_180.png"; var url_img_60 = "http:\/\/c2.glitch.bz\/achievements\/2012-06-14\/friend_of_the_urth_1339698045_60.png"; var url_img_40 = "http:\/\/c2.glitch.bz\/achievements\/2012-06-14\/friend_of_the_urth_1339698045_40.png"; function on_apply(pc){ } var conditions = { 698 : { type : "counter", group : "making_known_recipe", label : "190", value : "53" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_level()/4); } } pc.stats_add_xp(round_to_5(300 * multiplier), true); pc.stats_add_favor_points("alph", round_to_5(60 * multiplier)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } } var rewards = { "xp" : 300, "favor" : { "giant" : "alph", "points" : 60 } }; //log.info("friend_of_the_urth.js LOADED"); // generated ok (NO DATE)
"use strict"; /** * Kubernetes * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1.21.1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.V1Subject = void 0; /** * Subject contains a reference to the object or user identities a role binding applies to. This can either hold a direct API object reference, or a value for non-objects such as user and group names. */ class V1Subject { static getAttributeTypeMap() { return V1Subject.attributeTypeMap; } } exports.V1Subject = V1Subject; V1Subject.discriminator = undefined; V1Subject.attributeTypeMap = [ { "name": "apiGroup", "baseName": "apiGroup", "type": "string" }, { "name": "kind", "baseName": "kind", "type": "string" }, { "name": "name", "baseName": "name", "type": "string" }, { "name": "namespace", "baseName": "namespace", "type": "string" } ]; //# sourceMappingURL=v1Subject.js.map
import {mount} from 'enzyme'; import * as Preact from '#preact'; import * as intersectionObserver from '#preact/component/intersection-observer'; import {xhrUtils} from '#preact/utils/xhr'; import {waitFor} from '#testing/helpers/service'; import {cleanHtml} from './utils'; import {BentoList} from '../component'; const CONTENTS = '[test-id="contents"]'; function snapshot(component) { return cleanHtml(component.find(CONTENTS).html(), ['aria-label']); } describes.sandboxed('BentoList preact component v1.0', {}, (env) => { let fetchJson; beforeEach(() => { fetchJson = env.sandbox .stub(xhrUtils, 'fetchJson') .resolves({items: ['one', 'two', 'three']}); }); async function waitForData(component, callCount = 1) { await waitFor( () => fetchJson.callCount === callCount, 'expected fetchJson to have been called' + (callCount > 1 ? ` ${callCount} times` : '') ); // Ensure everything has settled: await new Promise((r) => setTimeout(r, 0)); component.update(); } describe('default behavior', () => { it('should render a "loading" state first', async () => { const component = mount(<BentoList src="" />); expect(snapshot(component)).to.equal( '<div><span aria-label="Loading"></span></div>' ); }); it('should load data, and display in a list', async () => { const component = mount(<BentoList src="TEST.json" />); expect(snapshot(component)).to.equal( '<div><span aria-label="Loading"></span></div>' ); await waitForData(component); expect(fetchJson).calledWith('TEST.json'); expect(snapshot(component)).to.equal( `<div><div>one</div><div>two</div><div>three</div></div>` ); }); it('the list should have aria-roles defined', async () => { const component = mount(<BentoList src="TEST.json" />); await waitForData(component); expect(component.find(CONTENTS).html()).to.equal( `<div role="list"><div role="listitem">one</div><div role="listitem">two</div><div role="listitem">three</div></div>` ); }); it("changing the 'src' should fetch the data", async () => { const component = mount(<BentoList src="TEST.json" />); expect(snapshot(component)).to.equal( '<div><span aria-label="Loading"></span></div>' ); await waitForData(component); expect(snapshot(component)).to.equal( `<div><div>one</div><div>two</div><div>three</div></div>` ); fetchJson.resolves({items: ['second', 'request']}); // Prop doesn't change, no fetch: component.setProps({src: 'TEST.json'}); expect(fetchJson).callCount(1); expect(snapshot(component)).to.equal( `<div><div>one</div><div>two</div><div>three</div></div>` ); // Prop changes, new fetch: component.setProps({src: 'TEST2.json'}); expect(fetchJson).callCount(2).calledWith('TEST2.json'); await waitForData(component, 2); expect(snapshot(component)).to.equal( `<div><div>second</div><div>request</div></div>` ); }); }); describe('itemsKey', () => { describe('with a flat array payload', () => { const results = ['flat', 'array']; beforeEach(() => { fetchJson.resolves(results); }); it('by default, it should not render the data', async () => { const component = mount(<BentoList src="" />); await waitForData(component); expect(component.text()).to.equal(''); }); it('itemsKey="" should render the payload', async () => { const component = mount(<BentoList src="" itemsKey="" />); await waitForData(component); expect(snapshot(component)).to.equal( '<div><div>flat</div><div>array</div></div>' ); }); it('itemsKey="." should also render the payload', async () => { const component = mount(<BentoList src="" itemsKey="." />); await waitForData(component); expect(snapshot(component)).to.equal( '<div><div>flat</div><div>array</div></div>' ); }); }); describe('when a custom itemsKey is supplied', () => { beforeEach(() => { fetchJson.resolves({ NUMBERS: [1, 2, 3], LETTERS: ['A', 'B', 'C'], NESTED: { OBJECTS: { TOO: ['ONE', 'TWO', 'THREE'], }, }, }); }); it('should extract the correct property', async () => { const component = mount(<BentoList src="" itemsKey="NUMBERS" />); await waitForData(component); expect(snapshot(component)).to.equal( '<div><div>1</div><div>2</div><div>3</div></div>' ); }); it('changing itemsKey should not require refetching the data', async () => { const component = mount(<BentoList src="" itemsKey="NUMBERS" />); await waitForData(component); expect(snapshot(component)).to.equal( '<div><div>1</div><div>2</div><div>3</div></div>' ); component.setProps({itemsKey: 'LETTERS'}); expect(snapshot(component)).to.equal( '<div><div>A</div><div>B</div><div>C</div></div>' ); component.setProps({itemsKey: 'NUMBERS'}); expect(snapshot(component)).to.equal( '<div><div>1</div><div>2</div><div>3</div></div>' ); // Ensure data was only fetched once! expect(fetchJson).callCount(1); }); describe('dot-separated lists', () => { it('should access dot-separated property lists', async () => { const component = mount( <BentoList src="" itemsKey="NESTED.OBJECTS.TOO" /> ); await waitForData(component); expect(snapshot(component)).to.equal( '<div><div>ONE</div><div>TWO</div><div>THREE</div></div>' ); }); it('should fail gracefully when the properties are not defined', async () => { const component = mount(<BentoList src="" itemsKey="invalid" />); await waitForData(component); expect(component.text()).to.equal(''); component.setProps({itemsKey: 'invalid.invalid'}); expect(component.text()).to.equal(''); component.setProps({itemsKey: 'LETTERS.invalid'}); expect(component.text()).to.equal(''); component.setProps({itemsKey: 'NESTED.invalid.invalid'}); expect(component.text()).to.equal(''); component.setProps({itemsKey: 'NESTED.OBJECTS.invalid'}); expect(component.text()).to.equal(''); component.setProps({itemsKey: 'NESTED.OBJECTS.TOO.invalid'}); expect(component.text()).to.equal(''); // Just to ensure it DOES indeed work when valid: component.setProps({itemsKey: 'NESTED.OBJECTS.TOO'}); expect(component.text()).to.equal('ONETWOTHREE'); }); }); }); }); describe('maxItems', () => { it('should limit the max number of items', async () => { const component = mount(<BentoList src="TEST.json" maxItems={1} />); await waitForData(component); expect(snapshot(component)).to.equal(`<div><div>one</div></div>`); }); it('should do nothing if there are already fewer items', async () => { const component = mount(<BentoList src="TEST.json" maxItems={99} />); await waitForData(component); expect(snapshot(component)).to.equal( `<div><div>one</div><div>two</div><div>three</div></div>` ); }); }); describe('template', () => { it('should allow for custom rendering of the data', async () => { const component = mount( <BentoList src="" template={(item) => <li>{item}</li>} wrapperTemplate={(list) => <ul>{list}</ul>} /> ); await waitForData(component); expect(component.find(CONTENTS).html()).to.equal( `<ul role="list"><li role="listitem">one</li><li role="listitem">two</li><li role="listitem">three</li></ul>` ); }); }); describe('load-more', () => { const mockData = [ { items: ['one', 'two', 'three'], 'load-more-src': 'page-2.json', }, { items: ['four', 'five'], 'load-more-src': 'page-3.json', }, { items: ['six', 'seven', 'eight', 'nine'], 'load-more-src': null, }, ]; beforeEach(() => { mockData.forEach((page, index) => { fetchJson.onCall(index).resolves(page); }); }); describe('manual', () => { const expectedPage1 = `<div><div>one</div><div>two</div><div>three</div></div><div><button><label>See More</label></button></div>`; const expectedPage2 = `<div><div>one</div><div>two</div><div>three</div><div>four</div><div>five</div></div><div><button><label>See More</label></button></div>`; const expectedPage3 = `<div><div>one</div><div>two</div><div>three</div><div>four</div><div>five</div><div>six</div><div>seven</div><div>eight</div><div>nine</div></div>`; let component; beforeEach(async () => { component = mount(<BentoList src="page-1.json" loadMore="manual" />); await waitForData(component); }); it('should render a "See More" button', async () => { expect(component.find('button').html()).to.equal( `<button load-more-button="true"><label>See More</label></button>` ); expect(snapshot(component)).to.equal(expectedPage1); }); it('clicking the button should keep loading more data', async () => { // Check page 1: expect(snapshot(component)).to.equal(expectedPage1); // Load page 2: simulateClickWithPropagation( component.find('button[load-more-button]') ); expect(fetchJson).callCount(2).calledWith('page-2.json'); expect(snapshot(component)).to.equal(expectedPage1); await waitForData(component, 2); expect(snapshot(component)).to.equal(expectedPage2); // Load page 3: simulateClickWithPropagation( component.find('button[load-more-button]') ); expect(fetchJson).callCount(3).calledWith('page-3.json'); expect(snapshot(component)).to.equal(expectedPage2); await waitForData(component, 3); expect(snapshot(component)).to.equal(expectedPage3); }); }); describe('auto', () => { beforeEach(() => { env.sandbox .stub(intersectionObserver, 'useIsInViewport') .returns(false); }); function simulateViewportVisible(component, isInViewport) { intersectionObserver.useIsInViewport.returns(isInViewport); component.setProps({}); // trigger a rerender } const expectedLoading = '<div><span aria-label="Loading"></span></div><span></span>'; const expectedPage1 = `<div><div>one</div><div>two</div><div>three</div></div><span></span>`; const expectedPage2 = `<div><div>one</div><div>two</div><div>three</div><div>four</div><div>five</div></div><span></span>`; const expectedPage3 = `<div><div>one</div><div>two</div><div>three</div><div>four</div><div>five</div><div>six</div><div>seven</div><div>eight</div><div>nine</div></div><span></span>`; let component; beforeEach(async () => { component = mount(<BentoList src="" loadMore="auto" />); }); it('should automatically load the first page', async () => { expect(snapshot(component)).to.equal(expectedLoading); await waitForData(component, 1); expect(snapshot(component)).to.equal(expectedPage1); }); it('should only load the first page when not in viewport', async () => { await waitForData(component, 1); await expect(waitForData(component, 2)).to.be.rejected; }); it('when the element is scrolled into the viewport, it loads more data', async () => { await waitForData(component, 1); // Bring it into view, then pretend the rerender caused it to grow: simulateViewportVisible(component, true); simulateViewportVisible(component, false); await waitForData(component, 2); expect(snapshot(component)).to.equal(expectedPage2); // Bring it into view for 1 render again: simulateViewportVisible(component, true); simulateViewportVisible(component, false); await waitForData(component, 3); expect(snapshot(component)).to.equal(expectedPage3); }); }); }); describe('loadMoreBookmark', () => { const mockData = [ { items: ['one', 'two', 'three'], METADATA: {'NEXT_PAGE_URL': 'page-2.json'}, }, { items: ['four', 'five'], METADATA: {'NEXT_PAGE_URL': 'page-3.json'}, }, { items: ['six', 'seven', 'eight', 'nine'], METADATA: {'NEXT_PAGE_URL': null}, }, ]; let component; beforeEach(async () => { mockData.forEach((page, index) => { fetchJson.onCall(index).resolves(page); }); component = mount( <BentoList src="page-1.json" loadMore="manual" loadMoreBookmark="METADATA.NEXT_PAGE_URL" /> ); await waitForData(component); }); const expectedPage1 = `<div><div>one</div><div>two</div><div>three</div></div><div><button><label>See More</label></button></div>`; const expectedPage2 = `<div><div>one</div><div>two</div><div>three</div><div>four</div><div>five</div></div><div><button><label>See More</label></button></div>`; const expectedPage3 = `<div><div>one</div><div>two</div><div>three</div><div>four</div><div>five</div><div>six</div><div>seven</div><div>eight</div><div>nine</div></div>`; it('should render the first page of data, as normal', async () => { expect(snapshot(component)).to.equal(expectedPage1); }); it('clicking the button should keep loading more data', async () => { // Check page 1: expect(snapshot(component)).to.equal(expectedPage1); // Load page 2: simulateClickWithPropagation(component.find('button[load-more-button]')); expect(fetchJson).callCount(2).calledWith('page-2.json'); expect(snapshot(component)).to.equal(expectedPage1); await waitForData(component, 2); expect(snapshot(component)).to.equal(expectedPage2); // Load page 3: simulateClickWithPropagation(component.find('button[load-more-button]')); expect(fetchJson).callCount(3).calledWith('page-3.json'); expect(snapshot(component)).to.equal(expectedPage2); await waitForData(component, 3); expect(snapshot(component)).to.equal(expectedPage3); }); }); describe('API', () => { let ref; let component; beforeEach(async () => { ref = Preact.createRef(); component = mount(<BentoList src="TEST.json" ref={ref} />); await waitForData(component); }); describe('refresh', () => { it('should be defined', () => { expect(ref.current.refresh).to.be.a('function'); }); it('should refresh the data', async () => { expect(fetchJson).to.have.callCount(1); expect(snapshot(component)).to.equal( `<div><div>one</div><div>two</div><div>three</div></div>` ); fetchJson.resolves({items: [1, 2, 3]}); ref.current.refresh(); await waitForData(component, 2); expect(snapshot(component)).to.equal( `<div><div>1</div><div>2</div><div>3</div></div>` ); }); }); }); }); function simulateClickWithPropagation(wrapper) { // Unlike `wrapper.simulate('click')`, this approach will propagate through DOM ancestors: wrapper.getDOMNode().click(); }
import React, {Component} from 'react'; import Range from './Range'; import Blender from './Blender'; import '../css/Controllers.css'; class Controllers extends Component { constructor() { super(); this._filters = [ 'brightness', 'contrast', 'saturation', 'exposure', 'vibrance', 'hue', 'gamma', 'clip', 'stackBlur', 'sepia', 'noise', 'sharpen' ]; this._blenders = [ 'vintage', 'lomo', 'clarity', 'sinCity', 'sunrise', 'crossProcess', 'orangePeel', 'love', 'grungy', 'jarques', 'pinhole', 'oldBoot', 'glowingSun', 'hazyDays', 'herMajesty', 'nostalgia', 'hemingway', 'concentrate' ]; } render() { const rangs = this._filters.map((filter, index) => { if (index <= 5) return <Range key={index} filter={filter} min={-100} max={100} /> return <Range key={index} filter={filter} min={0} max={100} /> }); const button_blenders = this._blenders.map((blender, index) => { const blender_name = blender.charAt(0).toUpperCase() + blender.slice(1); return <Blender key={index} name={blender_name} blender={blender} /> }); return( <div className="Controllers"> <h3 className="Controllers__header">Filters</h3> <div className="Controllers__filters">{rangs}</div> <h3 className="Controllers__header">Blenders</h3> <div className="Controllers__blenders">{button_blenders}</div> </div> ); } } export default Controllers;
define(function(){ return Toolbox.Base.extend({ constructor: function(options){ this.position = options.position || {x:0,y:0}; this.collision = options.collision; this.tileset = options.tileset; }, doMove: function(moveX,moveY){ this.position.x = this.collision.getPosition(0, this.position.x, this.position.y, moveX); this.position.y = this.collision.getPosition(1, this.position.x, this.position.y, moveY); }, setPosition: function(pos){ pos = pos || {}; this.position.x = pos.x || 0; this.position.y = pos.y || 0; }, getSprite: function(){ return this.tileset.sprite; }, getTileId: function(){ return (Math.floor(new Date().getTime()/500)%2) ? 'standing' : 'standing_alt'; }, getTileSpec: function(){ return this.tileset.tileSpec; } }); });
/** * Auto-generated action file for "Trello" API. * * Generated at: 2019-05-07T14:44:29.558Z * Mass generator version: 1.1.0 * * flowground :- Telekom iPaaS / trello-com-connector * Copyright © 2019, Deutsche Telekom AG * contact: flowground@telekom.de * * All files of this connector are licensed under the Apache 2.0 License. For details * see the file LICENSE on the toplevel directory. * * * Operation: 'updateActionsByIdAction' * Endpoint Path: '/actions/{idAction}' * Method: 'put' * */ const Swagger = require('swagger-client'); const processWrapper = require('../services/process-wrapper'); const spec = require('../spec.json'); // this wrapers offers a simplified emitData(data) function module.exports.process = processWrapper(processAction); // parameter names for this call const PARAMETERS = [ "idAction", "key", "token" ]; // mappings from connector field names to API field names const FIELD_MAP = { "idAction": "idAction", "key": "key", "token": "token", "text": "text", "requestBody": "requestBody" }; function processAction(msg, cfg) { var isVerbose = process.env.debug || cfg.verbose; if (isVerbose) { console.log(`---MSG: ${JSON.stringify(msg)}`); console.log(`---CFG: ${JSON.stringify(cfg)}`); console.log(`---ENV: ${JSON.stringify(process.env)}`); } const contentType = 'application/json'; const body = msg.body; mapFieldNames(body); let parameters = {}; for(let param of PARAMETERS) { parameters[param] = body[param]; } // credentials for this operation let securities = {}; securities['api_key'] = cfg['api_key']; securities['api_token'] = cfg['api_token']; let callParams = { spec: spec, operationId: 'updateActionsByIdAction', pathName: '/actions/{idAction}', method: 'put', parameters: parameters, requestContentType: contentType, requestBody: body.requestBody, securities: {authorized: securities}, server: spec.servers[cfg.server] || cfg.otherServer, }; if (isVerbose) { let out = Object.assign({}, callParams); out.spec = '[omitted]'; console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`); } // Call operation via Swagger client return Swagger.execute(callParams).then(data => { // emit a single message with data this.emitData(data); // if the response contains an array of entities, you can emit them one by one: // data.obj.someItems.forEach((item) => { // this.emitData(item); // } }); } function mapFieldNames(obj) { if(Array.isArray(obj)) { obj.forEach(mapFieldNames); } else if(typeof obj === 'object' && obj) { Object.keys(obj).forEach(key => { mapFieldNames(obj[key]); let goodKey = FIELD_MAP[key]; if(goodKey && goodKey !== key) { obj[goodKey] = obj[key]; delete obj[key]; } }); } }
(window.webpackJsonp=window.webpackJsonp||[]).push([[106],{2960:function(t,e,n){"use strict";n.r(e),n.d(e,"icon",(function(){return c}));n(11),n(2),n(5),n(8),n(4),n(10);var r=n(0),i=n.n(r);function o(){return(o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}function l(t,e){if(null==t)return{};var n,r,i=function(t,e){if(null==t)return{};var n,r,i={},o=Object.keys(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||(i[n]=t[n]);return i}(t,e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(r=0;r<o.length;r++)n=o[r],e.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(t,n)&&(i[n]=t[n])}return i}var a=function(t){var e=t.title,n=t.titleId,r=l(t,["title","titleId"]);return i.a.createElement("svg",o({width:16,height:16,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","aria-labelledby":n},r),e?i.a.createElement("title",{id:n},e):null,i.a.createElement("path",{d:"M8 4V3h6v1H8zM4 7V6h10v1H4zm4 3V9h6v1H8zm-4 3v-1h10v1H4z"}))},c=a;a.__docgenInfo={description:"",methods:[],displayName:"EuiIconEditorAlignRight"}}}]); //# sourceMappingURL=icon.editor_align_right-js.min.js.map
import React, { useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { green } from '@material-ui/core/colors'; import TextField from '@material-ui/core/TextField'; import Grid from '@material-ui/core/Grid'; import InputLabel from '@material-ui/core/InputLabel'; import FormControl from '@material-ui/core/FormControl'; import Select from '@material-ui/core/Select'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import DateFnsUtils from '@date-io/date-fns'; import { MuiPickersUtilsProvider, KeyboardDatePicker } from '@material-ui/pickers'; import Radio from '@material-ui/core/Radio'; import RadioGroup from '@material-ui/core/RadioGroup'; import FormLabel from '@material-ui/core/FormLabel'; import InputAdornment from '@material-ui/core/InputAdornment'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; import { useGlobalStore } from '../GlobalStore'; import API from '../../utils/API'; import processServerReturn from '../../utils/processServerReturn'; import ResponsiveSubmit from '../ResponsiveSubmit'; import Input from '@material-ui/core/Input'; import Fab from '@material-ui/core/Fab'; import AddIcon from '@material-ui/icons/Add'; import Slide from '@material-ui/core/Slide'; import NotificationsIcon from '@material-ui/icons/Notifications'; import ReminderDialog from '../ReminderDialog'; import Tooltip from '@material-ui/core/Tooltip'; import { withStyles } from '@material-ui/core/styles'; import ContactsSection from './ContactsSection'; import InterviewSection from './InterviewSection'; const Transition = React.forwardRef(function Transition(props, ref) { return <Slide direction="up" ref={ref} {...props} />; }); const RedRadio = withStyles({ root: { color: 'red', '&$checked': { color: 'red', }, }, checked: {}, })((props) => <Radio color="default" {...props} />); const YellowRadio = withStyles({ root: { color: 'yellow', '&$checked': { color: 'yellow', }, }, checked: {}, })((props) => <Radio color="default" {...props} />); const GreenRadio = withStyles({ root: { color: 'green', '&$checked': { color: 'green', }, }, checked: {}, })((props) => <Radio color="default" {...props} />); const BlueRadio = withStyles({ root: { color: 'blue', '&$checked': { color: 'blue', }, }, checked: {}, })((props) => <Radio color="default" {...props} />); const PurpleRadio = withStyles({ root: { color: 'purple', '&$checked': { color: 'purple', }, }, checked: {}, })((props) => <Radio color="default" {...props} />); const useStyles = makeStyles((theme) => ({ root: { '& > *': { marginBottom: theme.spacing(2), }, }, modal: { maxWidth: '100vw', [theme.breakpoints.down('sm')]: { '& .MuiDialog-paper': { margin: '10px', }, }, }, responsiveWrapper: { display: 'inline-block', }, changeWidth: { width: '90%', marginTop: theme.spacing(2), }, addButton: { [theme.breakpoints.down('xs')]: { position: 'fixed', zIndex: 10, bottom: theme.spacing(8), right: theme.spacing(2), }, [theme.breakpoints.up('sm')]: { display: 'none', }, green: { color: green[400], '&$checked': { color: green[600], }, }, }, })); export default function SimpleModal(props) { const [, dispatch] = useGlobalStore(); const [loading, setLoading] = useState(false); const [reminderDialogOpen, setReminderDialogOpen] = useState(false); const date = new Date(); const defaultValues = { color: '', company: '', companyLogoImage: '', postingType: '', title: '', location: '', salary: '', notes: '', postLink: '', appliedDate: Date.now(), heardBackDate: Date.now(), interviewState: null, interviewNote: '', companyContact: [], interviews: [], }; const [values, setValues] = useState(defaultValues); const classes = useStyles(); const [open, setOpen] = useState(false); //eslint-disable-next-line const [scroll, setScroll] = useState('paper'); const handleOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const handleChange = (prop) => (event) => { setValues({ ...values, [prop]: event.target.value }); }; // const handleCheckChange = (prop) => (event) => { // setValues({...values, [prop]: event.target.checked}) // } const handleDateChange = (prop) => (date) => { setValues({ ...values, [prop]: date }); }; const handleSubmit = async (event) => { event.preventDefault(); setLoading(true); const success = await submitChange(); setTimeout(() => setLoading(false), 500); if (success) { setOpen(false); props.rerender(); setValues(defaultValues); } }; const handleReset = async (event) => { event.preventDefault(); setValues(defaultValues); }; const submitChange = async () => { let serverMessage = { ...values }; //Validate the fields are valid for the DB //company can't be empty if (serverMessage.company === '') { dispatch({ do: 'setMessage', type: 'error', message: 'The company name cannot be empty.' }); setTimeout(() => dispatch({ do: 'clearMessage' }), 2000); return; } //title can't be empty if (serverMessage.title === '') { dispatch({ do: 'setMessage', type: 'error', message: 'The title cannot be empty.' }); setTimeout(() => dispatch({ do: 'clearMessage' }), 2000); return; } if (serverMessage.postingType === '') { dispatch({ do: 'setMessage', type: 'error', message: 'Please choose your posting type.' }); setTimeout(() => dispatch({ do: 'clearMessage' }), 2000); return; } //postLink has to be a valid URL const verifyURL = (url) => { //eslint-disable-next-line const re = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/; if (re.test(url)) { if (!url.includes('http://') && !url.includes('https://') && url.includes('www.')) { return 'http://' + url; } else { return url; } } return false; }; if (serverMessage.postLink.trim() !== '') { const validurl = verifyURL(serverMessage.postLink.trim()); if (validurl === false) { dispatch({ do: 'setMessage', type: 'error', message: 'Not a valid url.' }); setTimeout(() => dispatch({ do: 'clearMessage' }), 2000); return; } serverMessage.postLink = validurl; } if (!['applied', 'interview', 'offer', 'reject'].includes(serverMessage.postingType)) { delete serverMessage.appliedDate; } if (!['interview', 'offer', 'reject'].includes(serverMessage.postingType)) { delete serverMessage.heardBackDate; } //removing any empty fields from the put statement Object.keys(serverMessage).forEach((key) => { if (!serverMessage[key]) { delete serverMessage[key]; } }); const serverResponse = await API.post('/api/posts/', serverMessage); processServerReturn(serverResponse, dispatch); return !serverResponse.error; }; //Reminder adding modal stuff const addReminder = (reminderDate) => { //when okay is clicked in reminder dialog, add to the values setValues({ ...values, reminder: reminderDate }); setReminderDialogOpen(false); }; const body = ( <Grid container direction="column" className={classes.root}> <Grid container direction="row" justify="space-between"> <MuiPickersUtilsProvider utils={DateFnsUtils}> {/* <Grid container alignItems="flex-end"> */} <KeyboardDatePicker disableToolbar variant="inline" format="MM/dd/yyyy" margin="normal" id="date-picker-inline" label="Date Added" value={new Date()} onChange={() => { console.log('no'); }} KeyboardButtonProps={{ 'aria-label': 'change date', }} /> {/* </Grid> */} </MuiPickersUtilsProvider> <Tooltip title="Reminder"> <Button onClick={() => { setReminderDialogOpen(true); }} > <NotificationsIcon /> </Button> </Tooltip> </Grid> <FormControl component="fieldset"> <FormLabel component="legend">Box Color</FormLabel> <RadioGroup row aria-label="color" name="color" value={values.color} onChange={handleChange('color')}> <FormControlLabel value="red" control={<RedRadio />} label="Red" labelPlacement="bottom" /> <FormControlLabel value="yellow" control={<YellowRadio />} label="Yellow" labelPlacement="bottom" /> <FormControlLabel value="green" control={<GreenRadio />} label="Green" labelPlacement="bottom" /> <FormControlLabel value="blue" control={<BlueRadio />} label="Blue" labelPlacement="bottom" /> <FormControlLabel value="purple" control={<PurpleRadio />} label="Purple" labelPlacement="bottom" /> <FormControlLabel value="none" control={<Radio />} label="None" labelPlacement="bottom" /> </RadioGroup> </FormControl> <TextField id="company-text" label="Company" value={values.company} onChange={handleChange('company')} /> <TextField id="title-text" label="Title" value={values.title} onChange={handleChange('title')} /> <Grid container alignItems="flex-end"> <Grid item md={4} xs={12}> <FormControl style={{ width: '90%' }}> <InputLabel htmlFor="PostingType">Posting Type</InputLabel> <Select native value={values.postingType} onChange={handleChange('postingType')} inputProps={{ name: 'Post Type', id: 'PostingType', }} > <option value=""></option> <option value="wishlists">Wishlists</option> <option value="applied">Applied</option> <option value="interview">Interview</option> <option value="offer">Offer</option> <option value="reject">Reject</option> </Select> </FormControl> </Grid> <Grid item md={4} xs={12}> <TextField id="location" label="Location" value={values.location} onChange={handleChange('location')} className={classes.changeWidth} /> </Grid> <Grid item md={4} xs={12}> <FormControl className={classes.changeWidth}> <InputLabel htmlFor="salasalary">Monthly Salary</InputLabel> <Input id="salary" type="number" value={values.salary} onChange={handleChange('salary')} startAdornment={<InputAdornment position="start">$</InputAdornment>} /> </FormControl> </Grid> <Grid item xs={12}> {(values.postingType === 'applied' || values.postingType === 'interview' || values.postingType === 'offer' || values.postingType === 'reject') && ( <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDatePicker label="Applied Date" disableToolbar variant="inline" format="MM/dd/yyyy" margin="normal" id="dateChooser" value={values.appliedDate} onChange={handleDateChange('appliedDate')} KeyboardButtonProps={{ 'aria-label': 'change date', }} /> </MuiPickersUtilsProvider> )} </Grid> {values.postingType === 'interview' || values.postingType === 'offer' || values.postingType === 'reject' ? ( <Grid item xs={12} md={5}> <MuiPickersUtilsProvider utils={DateFnsUtils}> <KeyboardDatePicker label="Interviewed Date" disableToolbar variant="inline" format="MM/dd/yyyy" margin="normal" id="dateChooser" value={values.heardBackDate} onChange={handleDateChange('heardBackDate')} KeyboardButtonProps={{ 'aria-label': 'change date', }} /> </MuiPickersUtilsProvider> </Grid> ) : ( '' )} {values.postingType === 'interview' || values.postingType === 'offer' || values.postingType === 'reject' ? ( <Grid item xs={12} md={7}> <FormControl component="fieldset"> <FormLabel component="legend">Interview Type</FormLabel> <RadioGroup row aria-label="interviewState" name="interviewState" value={values.interviewState} onChange={handleChange('interviewState')} > <FormControlLabel value="emailInterview" control={<Radio />} label="Email" labelPlacement="bottom" /> <FormControlLabel value="phoneInterview" control={<Radio />} label="Phone" labelPlacement="bottom" /> <FormControlLabel value="onsiteInterview" control={<Radio />} label="Onsite" labelPlacement="bottom" /> <FormControlLabel value="" control={<Radio />} label="None" labelPlacement="bottom" /> </RadioGroup> </FormControl> </Grid> ) : ( '' )} {values.postingType === 'interview' || values.postingType === 'offer' || values.postingType === 'reject' ? ( <Grid item xs={12}> <TextField className="interviewNote" value={values.interviewNote} onChange={handleChange('interviewNote')} id="outlined-multiline-static" multiline label="Interview Notes" rows={6} variant="outlined" style={{ width: '100%' }} /> </Grid> ) : ( '' )} </Grid> {/* {(values.postingType === 'interview' || values.postingType === 'offer' || values.postingType === 'reject') && (<InterviewSection values={values} setValues={setValues} />)} */} <TextField id="postLink" label="Post Link" value={values.postLink} onChange={handleChange('postLink')} /> <TextField id="companyLogoImage" label="Company Logo Image URL" value={values.companyLogoImage} onChange={handleChange('companyLogoImage')} helperText="Optional: Add Employer Logo image url" /> <TextField onChange={handleChange('notes')} id="outlined-multiline-static" multiline label="Notes" rows={8} variant="outlined" value={values.notes} /> <ContactsSection values={values} setValues={setValues} /> </Grid> ); return ( <div> <button className="create-button" type="button" onClick={handleOpen}> Add new job </button> <Fab color="primary" className={classes.addButton} aria-label="add post" onClick={handleOpen}> <AddIcon /> </Fab> <ReminderDialog open={reminderDialogOpen} handleOk={addReminder} handleCancel={() => setReminderDialogOpen(false)} /> <Dialog open={open} onClose={handleClose} className={classes.modal} scroll={scroll} aria-labelledby="scroll-dialog-title" aria-describedby="scroll-dialog-description" TransitionComponent={Transition} > <DialogTitle id="scroll-dialog-title"> New Job{' '} <span style={{ float: 'right' }}> {date.getFullYear() + ' / ' + (date.getMonth() + 1) + ' / ' + date.getDate()} </span> </DialogTitle> <DialogContent dividers={scroll === 'paper'} style={{ margin: '0' }}> {body} </DialogContent> <DialogActions> <Button onClick={handleReset}>Reset</Button> <Button onClick={handleClose} color="secondary"> Close </Button> <ResponsiveSubmit submit={handleSubmit} loading={loading} name="Save" wrapperClass={classes.responsiveWrapper} size="small" /> </DialogActions> </Dialog> </div> ); }
import React from 'react' import styled from 'styled-components' import PropTypes from 'prop-types' import FontAwesomeIcon from '@fortawesome/react-fontawesome' import { faGithub, faLinkedinIn, faInstagram, faMedium, faTwitter, } from '@fortawesome/fontawesome-free-brands' import CookieConsent from 'react-cookie-consent' import { colors, pageLinks } from './constants' import { media } from './Breakpoints' const FooterWrapperStyled = styled.div` padding: 5px; grid-area: footer; display: grid; z-index: 1; &, h3 { text-align: center; font-size: 1rem; } &:hover { background-color: ${colors.contentWrappersBackground}; } ` const SocialWrapperStyled = styled.div` display: grid; grid-auto-flow: column; justify-content: center; grid-gap: 1rem; justify-content: center; ${media.tablet` justify-content: stretch; `}; ${media.phone` grid-gap: unset; `}; ` const SocialLinkStyled = styled.a` padding: 5px 8px; border-radius: 3px; font-size: 2rem; transition: transform 200ms ease; max-height: 40px; &:hover { transform: scale(1.1); color: ${colors.lightTextColor}; background-color: ${props => props.color}; } ${media.phone` font-size: 1.5rem; `}; ` const CookiesContent = styled.div` margin-right: 15px; a { color: ${colors.lightTextColor}; } ` SocialLinkStyled.propsTypes = { color: PropTypes.string, } SocialLinkStyled.defaultProps = { color: '#fff', } const Footer = () => { const socialLinks = [ { label: 'Github', link: 'https://github.com/robertovg', color: '#4183c4', icon: faGithub, }, { label: 'LinkedIn', link: 'https://www.linkedin.com/in/robertovg', color: '#007BB5', icon: faLinkedinIn, }, { label: 'Instagram', link: 'https://www.instagram.com/robertovg/', color: '#C32AA3', icon: faInstagram, }, { label: 'Medium', link: 'https://medium.com/@robertovg', color: '#000000', icon: faMedium, }, { label: 'Twitter', link: 'https://twitter.com/robertovg24', color: '#1DA1F2', icon: faTwitter, }, ] return ( <FooterWrapperStyled> <h3>You can follow me</h3> <SocialWrapperStyled> {socialLinks.map(socialLink => ( <SocialLinkStyled key={socialLink.label} target="_blank" rel="noopener noreferrer" color={socialLink.color} href={socialLink.link} > <FontAwesomeIcon icon={socialLink.icon} /> </SocialLinkStyled> ))} </SocialWrapperStyled> <CookieConsent location="bottom" buttonText="Got it!" cookieName="robertovg" style={{ background: pageLinks[0].gradientTop, display: 'grid', gridAutoFlow: 'column', justifyContent: 'center', }} buttonStyle={{ backgroundColor: pageLinks[0].gradientBottom, fontSize: 'large', cursor: 'pointer', padding: '0.3rem 1rem', borderRadius: '3px', right: 'unset', position: 'unset', marginRight: '1rem', }} > <CookiesContent> This website uses cookies to ensure you get the best experience on our website.{' '} <a target="_blank" rel="noopener noreferrer" href="http://cookiesandyou.com/"> Learn more </a>{' '} </CookiesContent> </CookieConsent> </FooterWrapperStyled> ) } export default Footer
import { css, html, LitElement } from "https://unpkg.com/lit-element/lit-element.js?module"; export class TreeView extends LitElement { static get properties() { return { headline: { type: String }, data: { type: Object } }; } constructor() { super(); //In the real project replace this data with your actual data this.data = { Component: { What: { Name: "Tree View" }, Why: { Purpose: "To present fetched data in a user-friendly way" } }, Creator: { Name: "Anastazja Galuza", City: "Copenhagen" } }; } static get styles() { return [ css` summary::-webkit-details-marker { display: none; } summary:before { content: "+ "; } details[open] summary:before { content: "- "; } summary { font-weight: bold; cursor: pointer; border-bottom: 1px solid grey; } summary, p { padding: 20px 0 16px 24px; } span { font-weight: bold; } p { margin: 0; border-bottom: 1px solid grey; overflow: hidden; } ` ]; } render() { const entries = Object.entries(this.data); return html` ${this.data != null ? entries.map(([key, value], i) => { if (Array.isArray(value) || (typeof value === "object" && value != null)) { return html` <details> <summary>${key}</summary> <tree-view style="margin: 0 0 0 20px; display: block;" .data="${value}"></tree-view> </details> `; } return html` <p><span>${key}:</span> ${value}</p> `; }) : undefined} `; } } customElements.define("tree-view", TreeView);
$(document).ready(function(){ $("#buscarAsig").hide(); checkRb('#inlineRadio1'); }); function obtenerDatos() { var id_sedes = $("#id_sede option:selected").attr("data-sedes"); var id_carrera = $("#id_carrera option:selected").attr("data-carreras"); var id_jornada = $("#id_jornada option:selected").attr("data-jornada"); var id_paralelo = $("#id_paralelo option:selected").attr("data-paralelos"); var datos = [ dato1 = {"id_sedes":id_sedes}, dato2 = {"id_carrera":id_carrera}, dato3 = {"id_jornada":id_jornada}, dato4 = {"id_paralelo":id_paralelo}, ] return datos; } function checkRb(selector) { //var op = $('input:radio[name='+selector+']:checked').val(); var op = $(selector).attr('value'); if (op == 1) { console.log(op); $("#buscarAsig").hide(); $("#guardarAsig").show(); $("#cont_paralelo").show(); } if(op == 2){ console.log(op); $("#guardarAsig").hide(); $("#buscarAsig").show(); $("#cont_paralelo").hide(); } } function guardarAsignacion() { var arreglo = obtenerDatos(); console.log('Datos: '+arreglo[0].id_sedes+' '+arreglo[1].id_carrera+' '+arreglo[2].id_jornada+' '+arreglo[3].id_paralelo); if (validarCampos(arreglo[1].id_carrera,arreglo[0].id_sedes,arreglo[2].id_jornada,arreglo[3].id_paralelo)) { $.post(ruta_global+'/admin/asignacion/validar',{'id_carrera':arreglo[1].id_carrera,'id_sede':arreglo[0].id_sedes,'id_jornada':arreglo[2].id_jornada,'id_paralelo':arreglo[3].id_paralelo},function success(data){ //console.info(data[0].paralelo); if (data[0].paralelo!=0) { alert('Paralelo ya registrado'); } else { $.post(ruta_global+'/admin/asignacion/guardar',{'id_carrera':arreglo[1].id_carrera,'id_sede':arreglo[0].id_sedes,'id_jornada':arreglo[2].id_jornada,'id_paralelo':arreglo[3].id_paralelo},function success(data){ //console.log(data); }); } }); //Ponemos por defecto los selectores $("#id_carrera").val('0'); $("#id_sede").val('0'); $("#id_jornada").val('0'); $("#id_paralelo").val('0'); } else alert('Error'); } function consultarAsignacion(op) { console.log(op); var arreglo = obtenerDatos(); console.info(arreglo); $.post(ruta_global+'/admin/asignacion/paralelos',{'op':op,'id_carrera':arreglo[1].id_carrera,'id_sede':arreglo[0].id_sedes,'id_jornada':arreglo[2].id_jornada,'id_paralelo':arreglo[3].id_paralelo},function success(data){ console.log(data); llenarTabla(data); $(".link_asignacion").removeClass('disabled'); }); } function getParalelos(op){ var arreglo = obtenerDatos(); console.log(arreglo); headerAjax(); $.ajax({ url: ruta_global+'/admin/asignacion/paralelos', type: 'post', dataType: 'json', data:{'op':op,'id_carrera':arreglo[1].id_carrera,'id_sede':arreglo[0].id_sedes,'id_jornada':arreglo[2].id_jornada,'id_paralelo':arreglo[3].id_paralelo}, success: function (data) { console.info(data); llenarTabla(data); } }); } function editarAsignacion(id) { //alert(id); ruta = ruta_global+"/admin/asignacion/"+id+"/edit"; $("#formEdit").attr('action',ruta); $("#formEdit").attr('method','get'); $("#formEdit").submit(); } function llenarTabla(data) { $("#tabla").empty(); $.each(data, function(i, item){ btnEdit = '<button type="button" class="btn btn-warning disabled link_asignacion" onclick="editarAsignacion('+item.id+')">Editar</button>'; $("#tabla").append("<tr><th>"+item.nombre_paralelo+"</th>"+ "<th>"+btnEdit+"</th></tr>"); }); } function llenarCmb(data) { $("#id_paralelo").empty(); $("#id_paralelo").append("<option value='0' data-paralelos='0'>--Seleccione--</option>"); $.each(data,function(i,item){ $("#id_paralelo").append("<option value='"+item.id+"' data-paralelos='"+item.id+"'>"+item.nombre_paralelo+"</option>"); }); } function validarCampos(id_carrera,id_sede,id_jornada,id_paralelo) { if((id_carrera && id_carrera.lenght !== 0) && (id_sede && id_sede.lenght !== 0) && (id_jornada && id_jornada.lenght !== 0) && (id_paralelo && id_paralelo.lenght !== 0)) return true; else return false; } function headerAjax(){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); }
import { undo, redo } from "prosemirror-history"; import { Slice } from "prosemirror-model"; import { Selection, TextSelection } from "prosemirror-state"; import { Fragment } from "prosemirror-model"; export class TestState { constructor(state, cmds = {}) { this.state = state; this.cmds = cmds; this.clipboard = null; } runCommand(name, ...runArgs) { const cmd = this.cmds[name]; if (!cmd) { throw new Error(`Command ${name} not registered with TestState`); } cmd(...runArgs)(this.state, (tr) => this.apply(tr)); return this; } enter(n = 1) { for (let i = 0; i < n; i += 1) { this.apply(this.tr.split(this.selection.from)); } return this; } get leftPos() { return Selection.near(this.doc.resolve(this.selection.$anchor.pos - 1), -1); } left(n = 1) { for (let i = 0; i < n; i += 1) { this.setSelection(this.leftPos); } return this; } get rightPos() { return Selection.near(this.doc.resolve(this.selection.$anchor.pos + 1)); } right(n = 1) { for (let i = 0; i < n; i += 1) { this.setSelection(this.rightPos); } return this; } undo(n = 1) { for (let i = 0; i < n; i += 1) { undo(this.state, (tr) => this.apply(tr)); } return this; } redo(n = 1) { for (let i = 0; i < n; i += 1) { redo(this.state, (tr) => this.apply(tr)); } return this; } backspace(n = 1) { for (let i = 0; i < n; i += 1) { const { $cursor } = this.selection; const { from, to } = $cursor ? new Selection(this.leftPos.$from, this.selection.$from) : this.selection; this.apply(this.tr.replace(from, to, Slice.empty)); } return this; } delete(n = 1) { for (let i = 0; i < n; i += 1) { const { $cursor } = this.selection; const { from, to } = $cursor ? new Selection(this.selection.$from, this.rightPos.$from) : this.selection; this.apply(this.tr.replace(from, to, Slice.empty)); } return this; } selectRight(n = 1) { const { $from } = this.state.selection; let { $to } = this.state.selection; for (let i = 0; i < n; i += 1) { const $pos = this.state.doc.resolve($to.pos + 1); $to = Selection.near($pos).$to; } return this.setSelection(new TextSelection($from, $to)); } setSelection(sel) { return this.apply(this.tr.setSelection(sel)); } replaceSelection(content, paste = false) { let tr = this.tr.replaceSelection(content); if (paste) { tr = tr.setMeta("paste", true); } return this.apply(tr); } deleteSelection() { return this.replaceSelection(Slice.empty); } copy() { this.clipboard = this.selection.content(); return this; } cut(n = 1) { for (let i = 0; i < n; i += 1) { this.copy(); this.deleteSelection(); } return this; } paste(n = 1) { for (let i = 0; i < n; i += 1) { this.replaceSelection(this.clipboard, true); } return this; } type(text) { return this.apply(this.tr.insertText(text)); } apply(tr) { this.state = this.state.apply(tr); return this; } get tr() { return this.state.tr; } get doc() { return this.state.doc; } get selection() { return this.state.selection; } } export const removeTags = (_node) => { const node = _node.copy(_node.content); delete node.tag; const children = []; for (let i = 0; i < node.content.childCount; i += 1) { const child = node.content.child(i); children.push(removeTags(child)); } return node.copy(Fragment.from(children)); };
// number unless otherwise specified var n1 = n1++; var n2 = n2 + n2; var n3 /* any */ = n3 + n3; // string unless otherwise specified var s1 = s1 + ''; var s2 /* any */ = s2 + s2; var s3 = s3 + s3; var s4 = '' + s4; // boolean unless otherwise specified var b1 = !b1; var b2 = !!b2; var b3 = !b3 || b3; // expected boolean here. actually 'any' var b4 = !b4 && b4; // expected boolean here. actually 'any' // (x:string) => any var f = (x)=>f(x);
require('./angular-mocks'); module.exports = 'ngMock';
var request = require('./request'); var alerts = require('../alerts'); module.exports = function (payload, callback) { return request(payload) .then(function (result) { if (result.body.alerts) { alerts.registerAlerts(result.body.alerts); } // make callbacks and promises work if (callback) { callback(null, result.res, result.body); } return result; }) .catch(function (error) { if (callback) { callback(error); } throw error; }); };
const {schema} = require('@octokit/graphql-schema') module.exports = schema.json
/*! jQuery Validation Plugin - v1.19.3 - 1/9/2021 * https://jqueryvalidation.org/ * Copyright (c) 2021 Jörn Zaefferer; Licensed MIT */ !function(a){"function"==typeof define&&define.amd?define(["jquery","../jquery.validate.min"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){return a.extend(a.validator.messages,{required:"Kötelező megadni.",maxlength:a.validator.format("Legfeljebb {0} karakter hosszú legyen."),minlength:a.validator.format("Legalább {0} karakter hosszú legyen."),rangelength:a.validator.format("Legalább {0} és legfeljebb {1} karakter hosszú legyen."),email:"Érvényes e-mail címnek kell lennie.",url:"Érvényes URL-nek kell lennie.",date:"Dátumnak kell lennie.",number:"Számnak kell lennie.",digits:"Csak számjegyek lehetnek.",equalTo:"Meg kell egyeznie a két értéknek.",range:a.validator.format("{0} és {1} közé kell esnie."),max:a.validator.format("Nem lehet nagyobb, mint {0}."),min:a.validator.format("Nem lehet kisebb, mint {0}."),creditcard:"Érvényes hitelkártyaszámnak kell lennie.",remote:"Kérem javítsa ki ezt a mezőt.",dateISO:"Kérem írjon be egy érvényes dátumot (ISO).",step:a.validator.format("A {0} egyik többszörösét adja meg.")}),a});
module.exports = { preset: 'ts-jest', testEnvironment: 'node', modulePathIgnorePatterns: ['cypress'], globals: { 'ts-jest': { tsconfig: './tests/tsconfig.json', }, }, };