text
stringlengths
2
6.14k
module.exports = { 'throttle': 10, 'hash': true, 'gzip': false, 'baseDir': 'public', 'buildDir': 'build', 'prefix': '' };
var modules = { "success" : [ {id: 1, name:"控制台", code:"console", protocol:"http", domain:"console.ecc.com", port:"18333", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}, {id: 2, name:"服务中心", code:"service-center", protocol:"http", domain:"sc.ecc.com", port:"18222", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'} ], "error" : { code : "0200-ERROR", msg : "There are some errors occured." } } module.exports = { "modules": modules }
const { createServer, plugins: { queryParser, serveStatic } } = require('restify'); const { join } = require('path'); const fetch = require('node-fetch'); const proxy = require('http-proxy-middleware'); const { PORT = 5000 } = process.env; const server = createServer(); server.use(queryParser()); server.get('/', async (req, res, next) => { if (!req.query.b) { const tokenRes = await fetch('https://webchat-mockbot.azurewebsites.net/directline/token', { headers: { origin: 'http://localhost:5000' }, method: 'POST' }); if (!tokenRes.ok) { return res.send(500); } const { token } = await tokenRes.json(); return res.send(302, null, { location: `/?b=webchat-mockbot&t=${encodeURIComponent(token)}` }); } return serveStatic({ directory: join(__dirname, 'dist'), file: 'index.html' })(req, res, next); }); server.get('/embed/*/config', proxy({ changeOrigin: true, target: 'https://webchat.botframework.com/' })); server.listen(PORT, () => console.log(`Embed dev server is listening to port ${PORT}`));
/** * @author: * @date: 2016/1/21 */ define(["core/js/layout/Panel"], function (Panel) { var view = Panel.extend({ /*Panel的配置项 start*/ title:"表单-", help:"内容", brief:"摘要", /*Panel 配置 End*/ oninitialized:function(triggerEvent){ this._super(); this.mainRegion={ comXtype:$Component.TREE, comConf:{ data:[this.getModuleTree("core/js/base/AbstractView")], } }; var that = this; this.footerRegion = { comXtype: $Component.TOOLSTRIP, comConf: { /*Panel的配置项 start*/ textAlign: $TextAlign.RIGHT, items: [{ text: "展开所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().expandAll(); }, },{ text: "折叠所有节点", onclick: function (e) { that.getMainRegionRef().getComRef().collapseAll(); }, }] /*Panel 配置 End*/ } }; }, getModuleTree:function(moduleName,arr){ var va = window.rtree.tree[moduleName]; var tree = {title: moduleName}; if(!arr){ arr = []; }else{ if(_.contains(arr,moduleName)){ return false; } } arr.push(moduleName); if(va&&va.deps&&va.deps.length>0){ tree.children = []; tree.folder=true; for(var i=0;i<va.deps.length;i++){ var newTree = this.getModuleTree(va.deps[i],arr); if(newTree){ tree.children.push(newTree); }else{ if(!tree.count){ tree.count = 0; } tree.count++; } } } return tree; } }); return view; });
$('#modalUploader').on('show.bs.modal', function (event) { var uploader = new qq.FileUploaderBasic({ element: document.getElementById('file-uploader-demo1'), button: document.getElementById('areaSubir'), action: '/Files/Upload', params: { ruta: $('#RutaActual').val() }, allowedExtensions: ['jpg', 'jpeg', 'png', 'gif', 'doc', 'docx', 'pdf'], multiple: false, onComplete: function (id, fileName, responseJSON) { $.gritter.add({ title: 'Upload file', text: responseJSON.message }); }, onSubmit: function (id, fileName) { var strHtml = "<li>" + fileName + "</li>"; $("#dvxArchivos").append(strHtml); } }); }); $('#modalUploader').on('hidden.bs.modal', function () { RecargarRuta(); }) function AbrirCarpeta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function AbrirRuta(pCarpeta) { $("#RutaSolicitada").val(pCarpeta); $("#frmMain").submit(); } function RecargarRuta() { AbrirCarpeta($("#RutaActual").val()); } function EliminarArchivo(pRuta) { if (confirm("Are you sure that want to delete this file?")) { $.gritter.add({ title: 'Delete file', text: "File deleted" }); $("#ArchivoParaEliminar").val(pRuta); AbrirCarpeta($("#RutaActual").val()); } } function SubirNivel() { if ($("#TieneSuperior").val() == "1") { var strRutaAnterior = $("#RutaSuperior").val(); AbrirRuta(strRutaAnterior); } } function IrInicio() { AbrirRuta($("#RutaRaiz").val()); } function AbrirDialogoArchivo() { $("#modalUploader").modal(); } function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if (results == null) return ""; else return decodeURIComponent(results[1].replace(/\+/g, " ")); }
// setToken when re-connecting var originalReconnect = Meteor.connection.onReconnect; Meteor.connection.onReconnect = function() { setToken(); if(originalReconnect) { originalReconnect(); } }; if(Meteor.status().connected) { setToken(); } function setToken() { var firewallHumanToken = Cookie.get('sikka-human-token'); Meteor.call('setSikkaHumanToken', firewallHumanToken); } // reloading the page window.sikkaCommands = sikkaCommands = new Mongo.Collection('sikka-commands'); sikkaCommands.find({}).observe({ added: function(command) { if(command._id === "reload") { location.reload(); } } });
import React from 'react'; import ReactDOM from 'react-dom'; import componentOrElement from 'react-prop-types/lib/componentOrElement'; import ownerDocument from './utils/ownerDocument'; import getContainer from './utils/getContainer'; /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ let Portal = React.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: React.PropTypes.oneOfType([ componentOrElement, React.PropTypes.func ]), /** * Classname to use for the Portal Component */ className: React.PropTypes.string }, componentDidMount() { this._renderOverlay(); }, componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = getContainer(nextProps.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); if (this.props.className) { this._overlayTarget.className = this.props.className; } this._portalContainerNode = getContainer(this.props.container, ownerDocument(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay() { let overlay = !this.props.children ? null : React.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = ReactDOM.unstable_renderSubtreeIntoContainer( this, overlay, this._overlayTarget ); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay() { if (this._overlayTarget) { ReactDOM.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render() { return null; }, getMountNode(){ return this._overlayTarget; }, getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return ReactDOM.findDOMNode(this._overlayInstance); } return null; } }); export default Portal;
dojo.provide("plugins.dijit.SyncDialog"); // HAS A dojo.require("dijit.Dialog"); dojo.require("dijit.form.Button"); dojo.require("dijit.form.ValidationTextBox"); // INHERITS dojo.require("plugins.core.Common"); dojo.declare( "plugins.dijit.SyncDialog", [ dijit._Widget, dijit._Templated, plugins.core.Common ], { //Path to the template of this widget. templatePath: dojo.moduleUrl("plugins", "dijit/templates/syncdialog.html"), // OR USE @import IN HTML TEMPLATE cssFiles : [ dojo.moduleUrl("plugins", "dijit/css/syncdialog.css") ], // Calls dijit._Templated.widgetsInTemplate widgetsInTemplate : true, // PARENT plugins.workflow.Apps WIDGET parentWidget : null, // DISPLAYED MESSAGE message : null, //////}} constructor : function(args) { console.log("SyncDialog.constructor args:"); console.dir({args:args}); // LOAD CSS this.loadCSS(); }, postCreate : function() { //////console.log("SyncDialog.postCreate plugins.dijit.SyncDialog.postCreate()"); this.startup(); }, startup : function () { ////console.log("SyncDialog.startup plugins.dijit.SyncDialog.startup()"); ////console.log("SyncDialog.startup this.parentWidget: " + this.parentWidget); this.inherited(arguments); // SET UP DIALOG this.setDialogue(); // SET KEY LISTENER this.setKeyListener(); // ADD CSS NAMESPACE CLASS FOR TITLE CSS STYLING this.setNamespaceClass("syncDialog"); }, setKeyListener : function () { dojo.connect(this.dialog, "onkeypress", dojo.hitch(this, "handleOnKeyPress")); }, handleOnKeyPress: function (event) { var key = event.charOrCode; console.log("SyncDialog.handleOnKeyPress key: " + key); if ( key == null ) return; event.stopPropagation(); if ( key == dojo.keys.ESCAPE ) this.hide(); }, setNamespaceClass : function (ccsClass) { // ADD CSS NAMESPACE CLASS dojo.addClass(this.dialog.domNode, ccsClass); dojo.addClass(this.dialog.titleNode, ccsClass); dojo.addClass(this.dialog.closeButtonNode, ccsClass); }, show: function () { // SHOW THE DIALOGUE this.dialog.show(); this.message.focus(); }, hide: function () { // HIDE THE DIALOGUE this.dialog.hide(); }, doEnter : function(type) { // RUN ENTER CALLBACK IF 'ENTER' CLICKED console.log("SyncDialog.doEnter plugins.dijit.SyncDialog.doEnter()"); var inputs = this.validateInputs(["message", "details"]); console.log("SyncDialog.doEnter inputs:"); console.dir({inputs:inputs}); if ( ! inputs ) { console.log("SyncDialog.doEnter inputs is null. Returning"); return; } // RESET this.message.set('value', ""); this.details.value = ""; // HIDE this.hide(); // DO CALLBACK this.dialog.enterCallback(inputs); }, validateInputs : function (keys) { console.log("Hub.validateInputs keys: "); console.dir({keys:keys}); var inputs = new Object; this.isValid = true; for ( var i = 0; i < keys.length; i++ ) { console.log("Hub.validateInputs Doing keys[" + i + "]: " + keys[i]); inputs[keys[i]] = this.verifyInput(keys[i]); } console.log("Hub.validateInputs inputs: "); console.dir({inputs:inputs}); if ( ! this.isValid ) return null; return inputs; }, verifyInput : function (input) { console.log("Aws.verifyInput input: "); console.dir({this_input:this[input]}); var value = this[input].value; console.log("Aws.verifyInput value: " + value); var className = this.getClassName(this[input]); console.log("Aws.verifyInput className: " + className); if ( className ) { console.log("Aws.verifyInput this[input].isValid(): " + this[input].isValid()); if ( ! value || ! this[input].isValid() ) { console.log("Aws.verifyInput input " + input + " value is empty. Adding class 'invalid'"); dojo.addClass(this[input].domNode, 'invalid'); this.isValid = false; } else { console.log("SyncDialog.verifyInput value is NOT empty. Removing class 'invalid'"); dojo.removeClass(this[input].domNode, 'invalid'); return value; } } else { if ( input.match(/;/) || input.match(/`/) ) { console.log("SyncDialog.verifyInput value is INVALID. Adding class 'invalid'"); dojo.addClass(this[input], 'invalid'); this.isValid = false; return null; } else { console.log("SyncDialog.verifyInput value is VALID. Removing class 'invalid'"); dojo.removeClass(this[input], 'invalid'); return value; } } return null; }, doCancel : function() { // RUN CANCEL CALLBACK IF 'CANCEL' CLICKED ////console.log("SyncDialog.doCancel plugins.dijit.SyncDialog.doCancel()"); this.dialog.cancelCallback(); this.dialog.hide(); }, setDialogue : function () { // APPEND DIALOG TO DOCUMENT document.body.appendChild(this.dialog.domNode); this.dialog.parentWidget = this; // AVOID this._fadeOutDeferred NOT DEFINED ERROR this._fadeOutDeferred = function () {}; }, load : function (args) { console.log("SyncDialog.load args:"); console.dir({args:args}); if ( args.title ) { console.log("SyncDialog.load SETTING TITLE: " + args.title); this.dialog.set('title', args.title); } this.headerNode.innerHTML = args.header; if (args.message) this.message.set('value', args.message); if (args.details) this.details.value = args.details; //if (args.details) this.details.innerHTML(args.details); this.dialog.enterCallback = args.enterCallback; this.show(); } });
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosHeart extends React.Component { render() { if(this.props.bare) { return <g> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </g>; } return <IconBase> <path d="M359.385,80C319.966,80,277.171,97.599,256,132.8C234.83,97.599,192.034,80,152.615,80C83.647,80,32,123.238,32,195.779 c0,31.288,12.562,71.924,40.923,105.657c28.359,33.735,45.229,51.7,100.153,88C228,425.738,256,432,256,432s28-6.262,82.924-42.564 c54.923-36.3,71.794-54.265,100.153-88C467.438,267.703,480,227.067,480,195.779C480,123.238,428.353,80,359.385,80z"></path> </IconBase>; } };IosHeart.defaultProps = {bare: false}
import React, {PropTypes} from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as courseActions from '../../actions/courseActions'; import CourseForm from './CourseForm'; import {authorsFormattedForDropdown} from '../../selectors/selectors'; import toastr from 'toastr'; export class ManageCoursePage extends React.Component { constructor(props, context) { super(props, context); this.state = { course: Object.assign({}, props.course), errors: {}, saving: false }; this.updateCourseState = this.updateCourseState.bind(this); this.saveCourse = this.saveCourse.bind(this); } componentWillReceiveProps(nextProps) { if (this.props.course.id != nextProps.course.id) { // Necessary to populate form when existing course is loaded directly. this.setState({course: Object.assign({}, nextProps.course)}); } } updateCourseState(event) { // handler for each form field const field = event.target.name; let course = this.state.course; course[field] = event.target.value; return this.setState({course: course}); } courseFormValid() { let formIsValid = true; let errors = {}; if (this.state.course.title.length < 5) { errors.title = 'Title must be at least 5 characters.'; formIsValid = false; } this.setState({errors: errors}); return formIsValid; } saveCourse(event) { event.preventDefault(); if (!this.courseFormValid()) { return; } this.setState({saving: true}); this.props.actions.saveCourse(this.state.course) .then(() => this.redirect()) .catch(error => { toastr.error(error); this.setState({saving: false}); }); } redirect() { // redirect to courses route this.setState({saving: false}); toastr.success('Course saved!'); this.context.router.push('/courses'); } render() { return ( <CourseForm allAuthors={this.props.authors} onChange={this.updateCourseState} onSave={this.saveCourse} errors={this.state.errors} course={this.state.course} saving={this.state.saving}/> ); } } ManageCoursePage.propTypes = { course: PropTypes.object.isRequired, authors: PropTypes.array.isRequired, actions: PropTypes.object.isRequired }; //Pull in the React Router context so router is available on this.context.router. ManageCoursePage.contextTypes = { router: PropTypes.object }; function getCourseById(courses, id) { const course = courses.filter(course => course.id == id); if (course.length) return course[0]; //since filter returns an array, have to grab the first. return null; } function mapStateToProps(state, ownProps) { let course = { id: "", title: "", watchHref: "", authorId: "", length: "23", category: "" }; const courseId = ownProps.params.id; // from the path `/course/:id` if (courseId && state.courses.length > 0) { course = getCourseById(state.courses, courseId); } return { course: course, authors: authorsFormattedForDropdown(state.authors) } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(courseActions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(ManageCoursePage);
define([ 'angular' ], function (ng) { 'use strict'; return ng.module('backgroundModule', []); });
const pkg = state => state.pkg const app = state => state.app const device = state => state.app.device const sidebar = state => state.app.sidebar const effect = state => state.app.effect const menuitems = state => state.menu.items const componententry = state => { return state.menu.item.filter(c => c.meta && c.meta.label === 'Components')[0] } export { pkg, app, device, sidebar, effect, menuitems, componententry }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ angular.module('MetronicApp').controller('UsuariosCtrl', function ($scope, GetSv, $rootScope, PostSv,toaster) { $scope.usuarios = []; $scope.add = false; $scope.edit = false; $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers = function () { GetSv.getData("usuarios").then(function (data) { if (data.Error) { $scope.error = true; } else { $scope.usuarios = data; $scope.error = false; } }, function (e) { $scope.error = true; }); }; $scope.getUsers(); $scope.closeEdit = function () { $scope.a_editar = {}; $scope.edit = false; }; $scope.openEdit = function (item) { $scope.a_editar = item; $scope.edit = true; }; $scope.closeAdd = function () { $scope.add = false; }; $scope.openAdd = function (item) { $scope.a_editar = {}; $scope.add = true; }; $scope.sendUser = function (servlet, user) { PostSv.postData(servlet, {usuario: JSON.stringify(user)}).then(function (data) { if (data.Error) { toaster.pop('error', "Error", data.Error); } else { toaster.pop('success', "Exito", data.Exito); $scope.a_editar = {}; $scope.usuario = {}; $scope.getUsers(); $scope.add = false; $scope.edit = false; } }, function (e) { toaster.pop('error', "Error", "Error fatal"); } ); }; $scope.roles = $rootScope.roles; });
/* * This file exports the configuration Express.js back to the application * so that it can be used in other parts of the product. */ var path = require('path'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var RedisStore = require('connect-redis')(session); exports.setup = function(app, express) { app.set('views', path.join(__dirname + '../../public/views')); app.engine('html', require('ejs').renderFile); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(session({ cookie: { maxAge: (24*3600*1000*30) }, store: new RedisStore({ host: 'localhost', port: 6379, db: 1, pass: '' }), secret: 'mylittlesecret', resave: false, saveUninitialized: false })); app.use(express.static(path.join(__dirname + '../../public'))); }
chrome.app.runtime.onLaunched.addListener(function(){ chrome.app.window.create('index.html', { bounds: { width: Math.round(window.screen.availWidth - 100), height: Math.round(window.screen.availHeight - 100) } }); });
"use strict"; /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ var task = require("../tasks/tar.gz"), fs = require("fs"); exports["targz"] = { setUp: function(done) { // setup here done(); }, "targz sqlite3": function(test) { test.expect(1); var actual; actual = fs.statSync("tmp/node_sqlite3.node"); test.equal(actual.size, 831488); test.done(); } };
if (Zepto.ajax.restore) { Zepto.ajax.restore(); } sinon.stub(Zepto, "ajax") .yieldsTo("success", { responseStatus : 200, responseDetails : null, responseData : { feed: { link : "http://github.com", title : "GitHub Public Timeline", entries : [ { title : "Croaky signed up", link : "http://github.com/Croaky/openbeerdatabase", author : "", publishedDate : "Thu, 24 Nov 2011 19:00:00 -0600", content : "\u003cstrong\u003eCroaky\u003c/strong\u003e signed up for GitHub.", contentSnippet : "Croaky signed up for GitHub.", categories : [] } ] } } });
var baseURL; $.validator.addMethod("alfanumerico", function(value, element) { return this.optional(element) || /^[-._a-z0-9\- ]+$/i.test(value); }, "Este campo es alfanumerico."); $("#frmGuardaTipoDocumento").validate({ rules : { descripcion : "required", codigo : {required:true,alfanumerico:true}, }, messages : { descripcion : "Ingrese este campo.", codigo : {required:"Ingrese este campo.",alfanumerico:"Este campo es alfanumerico."}, }, submitHandler : function(form) { $.ajax(form.action, { async : false, type : "POST", data : $(form).serialize(), success : function(contenido) { //alert("contenido :"+ contenido); if(contenido=="error"){ var mensaje="Este tipo de documento ya ha sido registrado"; alert(mensaje); } else{ baseURL = $("#baseURL").val(); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos?info="+contenido, function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado"); }); } } }); } }); function cancelarTipoDocumento(){ var baseURL; baseURL = $("#baseURL").val(); $("#contenidoPrincipal").html("Cargando . . ."); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos", function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado"); }); }
export { default } from 'ember-flexberry-designer/controllers/fd-interface-edit-form/new';
var today = new Date(); console.log(today);
({ baseUrl: "../linesocial/public/js", paths: { jquery: "public/js/libs/jquery-1.9.1.js" }, name: "main", out: "main-built.js" })
/* * This file is part of the easy framework. * * (c) Julien Sergent <sergent.julien@icloud.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const ConfigLoader = require( 'easy/core/ConfigLoader' ) const EventsEmitter = require( 'events' ) /** * @class Database */ class Database { /** * @constructor */ constructor( config ) { this._config = config this.stateEmitter = new EventsEmitter() this.name = config.config.name this.init() } /** * init - init attributes */ init() { this._instance = null this._connector = this._config.connector this.resetProperties() } /** * Reset instance and connected state * * @memberOf Database */ resetProperties() { this._connected = false this._connectionError = null } /** * load - load database config */ async start() { await this.connect() } /** * restart - restart database component */ async restart() { this.resetProperties() await this.start() } /** * connect - connect database to instance */ async connect() { const { instance, connected, error } = await this.config.connector() const oldConnected = this.connected this.instance = instance this.connected = connected this.connectionError = error if ( this.connected !== oldConnected ) { this.stateEmitter.emit( 'change', this.connected ) } if ( error ) { throw new Error( error ) } } /** * Reset database connection and instance * * @memberOf Database */ disconnect() { const oldConnected = this.connected this.resetProperties() if ( this.connected !== oldConnected ) { this.stateEmitter.emit( 'change', this.connected ) } } /** * verifyConnectionHandler - handler called by daemon which indicates if database still available or not * * @returns {Promise} * * @memberOf Database */ verifyConnectionHandler() { return this.config.verifyConnectionHandler() } /** * Branch handler on database state events * * @param {Function} handler * * @memberOf Database */ connectToStateEmitter( handler ) { this.stateEmitter.on( 'change', handler ) } /** * get - get database instance * * @returns {Object} */ get instance() { return this._instance } /** * set - set database instance * * @param {Object} instance * @returns {Object} */ set instance( instance ) { this._instance = instance return this._instance } /** * get - get database connection state * * @returns {Object} */ get connected() { return this._connected } /** * set - set database connection state * * @param {boolean} connected * @returns {Database} */ set connected( connected ) { this._connected = connected return this } /** * get - get database configurations * * @returns {Object} */ get config() { return this._config } /** * Get connection error * * @readonly * * @memberOf Database */ get connectionError() { return this._connectionError } /** * Set connection error * * @returns {Database} * * @memberOf Database */ set connectionError( error ) { this._connectionError = error return this } } module.exports = Database
import {writeFile} from 'fs-promise'; import {get, has, merge, set} from 'lodash/fp'; import flatten from 'flat'; import fs from 'fs'; import path from 'path'; const data = new WeakMap(); const initial = new WeakMap(); export default class Config { constructor(d) { data.set(this, d); initial.set(this, Object.assign({}, d)); } clone() { return Object.assign({}, data.get(this)); } get(keypath) { return get(keypath, data.get(this)); } has(keypath) { return has(keypath, data.get(this)); } inspect() { return data.get(this); } merge(extra) { data.set(this, merge(data.get(this), extra)); } set(keypath, value) { return set(keypath, data.get(this), value); } async save() { const out = this.toString(); return await writeFile(`.boilerizerc`, out); } toJSON() { const keys = Object.keys(flatten(data.get(this), {safe: true})); const init = initial.get(this); let target; try { const filepath = path.join(process.cwd(), `.boilerizerc`); // Using sync here because toJSON can't have async functions in it // eslint-disable-next-line no-sync const raw = fs.readFileSync(filepath, `utf8`); target = JSON.parse(raw); } catch (e) { if (e.code !== `ENOENT`) { console.error(e); throw e; } target = {}; } return keys.reduce((acc, key) => { if (!has(key, init) || has(key, target)) { const val = this.get(key); acc = set(key, val, acc); } return acc; }, target); } toString() { return JSON.stringify(this, null, 2); } }
// Karma configuration // Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'], plugins: [ 'karma-mocha', 'karma-chai', 'karma-sinon-chai', 'karma-chrome-launcher', 'karma-phantomjs-launcher', 'karma-jquery', 'karma-chai-jquery', 'karma-mocha-reporter' ], // list of files / patterns to load in the browser files: [ 'bower/angular/angular.js', 'bower/angular-sanitize/angular-sanitize.js', 'bower/angular-mocks/angular-mocks.js', 'dist/ac-components.min.js', 'test/unit/**/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['mocha'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
export default function _isString(obj) { return toString.call(obj) === '[object String]' }
var class_mock = [ [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "Mock", "class_mock.html#a2b9528f2e7fcf9738201a5ea667c1998", null ], [ "MOCK_METHOD0", "class_mock.html#ae710f23cafb1a2f17772e8805d6312d2", null ], [ "MOCK_METHOD1", "class_mock.html#ada59eea6991953353f332e3ea1e74444", null ], [ "MOCK_METHOD1", "class_mock.html#a2db4d82b6f92b4e462929f651ac4c3b1", null ], [ "MOCK_METHOD1", "class_mock.html#ae73b4ee90bf6d84205d2b1c17f0b8433", null ], [ "MOCK_METHOD1", "class_mock.html#a2cece30a3ea92b34f612f8032fe3a0f9", null ], [ "MOCK_METHOD1", "class_mock.html#ac70c052254fa9816bd759c006062dc47", null ], [ "MOCK_METHOD1", "class_mock.html#ae2379efbc030f1adf8b032be3bdf081d", null ], [ "MOCK_METHOD1", "class_mock.html#a3fd62026610c5d3d3aeaaf2ade3e18aa", null ], [ "MOCK_METHOD1", "class_mock.html#a890668928abcd28d4d39df164e7b6dd8", null ], [ "MOCK_METHOD1", "class_mock.html#a50e2bda4375a59bb89fd5652bd33eb0f", null ] ];
"use strict" const messages = require("..").messages const ruleName = require("..").ruleName const rules = require("../../../rules") const rule = rules[ruleName] testRule(rule, { ruleName, config: ["always"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBefore(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBefore(), line: 1, column: 25, }, { code: "a { background-size: 0\n, 0; }", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\r\n, 0; }", description: "CRLF", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBefore(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["always-single-line"], accept: [ { code: "a { background-size: 0 , 0; }", }, { code: "a { background-size: 0 ,0; }", }, { code: "a { background-size: 0 ,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0 ,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo,bar,baz\"; }", description: "strings", }, { code: "a { transform: translate(1,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\n}", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0, 0;\r\n}", description: "CRLF", message: messages.expectedBeforeSingleLine(), line: 1, column: 23, }, { code: "a { background-size: 0 , 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.expectedBeforeSingleLine(), line: 1, column: 24, } ], }) testRule(rule, { ruleName, config: ["never-single-line"], accept: [ { code: "a { background-size: 0, 0; }", }, { code: "a { background-size: 0,0; }", }, { code: "a { background-size: 0,0;\n}", description: "single-line list, multi-line block", }, { code: "a { background-size: 0,0;\r\n}", description: "single-line list, multi-line block with CRLF", }, { code: "a { background-size: 0 ,\n0; }", description: "ignores multi-line list", }, { code: "a { background-size: 0 ,\r\n0; }", description: "ignores multi-line list with CRLF", }, { code: "a::before { content: \"foo ,bar ,baz\"; }", description: "strings", }, { code: "a { transform: translate(1 ,1); }", description: "function arguments", } ], reject: [ { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\n}", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0;\r\n}", description: "CRLF", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, }, { code: "a { background-size: 0 , 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 25, }, { code: "a { background-size: 0\t, 0; }", message: messages.rejectedBeforeSingleLine(), line: 1, column: 24, } ], })
var test = require('tap').test; var CronExpression = require('../lib/expression'); test('Fields are exposed', function(t){ try { var interval = CronExpression.parse('0 1 2 3 * 1-3,5'); t.ok(interval, 'Interval parsed'); CronExpression.map.forEach(function(field) { interval.fields[field] = []; t.throws(function() { interval.fields[field].push(-1); }, /Cannot add property .*?, object is not extensible/, field + ' is frozen'); delete interval.fields[field]; }); interval.fields.dummy = []; t.same(interval.fields.dummy, undefined, 'Fields is frozen'); t.same(interval.fields.second, [0], 'Second matches'); t.same(interval.fields.minute, [1], 'Minute matches'); t.same(interval.fields.hour, [2], 'Hour matches'); t.same(interval.fields.dayOfMonth, [3], 'Day of month matches'); t.same(interval.fields.month, [1,2,3,4,5,6,7,8,9,10,11,12], 'Month matches'); t.same(interval.fields.dayOfWeek, [1,2,3,5], 'Day of week matches'); } catch (err) { t.error(err, 'Interval parse error'); } t.end(); });
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, fillIn } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; module('Integration | Component | inputs/text-input', function (hooks) { setupRenderingTest(hooks); hooks.beforeEach(async function () { this.config = { value: '123 hello', name: 'myInput', disabled: false, autocomplete: 'name', texts: { placeholder: 'Your name', }, }; await render(hbs`<Inputs::TextInput @config={{config}} />`); }); test('it renders', async function (assert) { assert.dom('textarea').hasAttribute('name', 'myInput'); assert.dom('textarea').hasAttribute('autocomplete', 'name'); assert.dom('textarea').hasAttribute('placeholder', 'Your name'); }); test('it updates value', async function (assert) { assert.dom('textarea').hasValue('123 hello'); this.set('config.value', 'hello?'); assert.dom('textarea').hasValue('hello?'); await fillIn('textarea', 'bye!'); assert.equal(this.config.value, 'bye!'); }); test('it can be disabled', async function (assert) { assert.dom('textarea').isNotDisabled(); this.set('config.disabled', true); assert.dom('textarea').isDisabled(); }); test('it supports presence validations', async function (assert) { assert.dom('textarea').doesNotHaveAttribute('required'); this.set('config.validations', { required: true }); assert.dom('textarea').hasAttribute('required'); }); });
#!/usr/bin/env node var listCommand = []; require('./listCommand')(listCommand) var logDetail = (str) => { console.log(' > '+str); } var printHelp = () => { var txtHelp = ""; var h = ' '; var t = ' '; txtHelp += "\n"+h+"Usage : rider [command] \n"; txtHelp += "\n"+h+"Command List : \n"; var maxText = 0; if(listCommand == undefined){ logDetail("not found help detail"); return; } Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; if(maxText < item.name.length+item.params.length) maxText = item.name.length+item.params.length+4; }); var maxT = Math.ceil(maxText/4); Object.keys(listCommand).forEach((keyName) => { var item = listCommand[keyName]; var x = (item.name.length+item.params.length+4)/4; x = Math.ceil(x); var space = '\t'; for (var i = 0; i < maxT-x-1; i++) { space += '\t'; } var txt = ""; if(item.params.length > 0){ space += '\t'; txt = '\t'+item.name +" [" +item.params+"] " + space +item.desc+"\n"; }else{ txt = '\t'+item.name + space +item.desc+"\n"; } txtHelp +=txt; txtHelp +"\n"; }); console.log(txtHelp); process.exit(0); } var parseParams = (params, cb) => { if(params.length < 3){ return cb(true); } cb(false); } var checkCommand = (cmd) => { var foundCmd = false; Object.keys(listCommand).forEach((keyName) => { if(keyName == cmd){ foundCmd = true; return; } }); return !foundCmd; } var runCommand = (params, cb) => { var opt = params[2]; var objRun = listCommand[opt]; if(objRun != undefined && objRun != null){ objRun.runCommand(params, cb); } } var main = () => { console.log(">> Rider ... "); var params = process.argv; parseParams(params, (err) => { if(err){ printHelp(); return; } var opt = params[2]; if(opt == "-h" || opt == "--help"){ printHelp(); return; } if(checkCommand(opt)){ printHelp(); return; } runCommand(params, () => { process.exit(0); }); }); } // -- call main function -- main();
define('exports@*', [], function(require, exports, module){ exports.a = 1; });
jQuery(document).ready(function(){ jQuery('.carousel').carousel() var FPS = 30; var player = $('#player') var pWidth = player.width(); $window = $(window) var wWidth = $window.width(); setInterval(function() { update(); }, 1000/FPS); function update() { if(keydown.space) { player.shoot(); } if(keydown.left) { console.log('go left') player.css('left', '-=10'); } if(keydown.right) { console.log('go right') var x = player.position().left; if(x + pWidth > wWidth) { player.css('left', '0') } else if(x < 0 ) { var p = wWidth + x - pWidth; var t = p + 'px' player.css('left', t) } else { player.css('left', '+=10'); } } } $('') })
'use strict'; // Configuring the Articles module angular.module('about').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('mainmenu', 'About Us', 'about', 'left-margin', '/about-us', true, null, 3); } ]);
export default function closest(n, arr) { let i let ndx let diff let best = Infinity let low = 0 let high = arr.length - 1 while (low <= high) { // eslint-disable-next-line no-bitwise i = low + ((high - low) >> 1) diff = arr[i] - n if (diff < 0) { low = i + 1 } else if (diff > 0) { high = i - 1 } diff = Math.abs(diff) if (diff < best) { best = diff ndx = i } if (arr[i] === n) break } return arr[ndx] }
/** * 斐波那契数列 */ export default function fibonacci(n){ if(n <= 2){ return 1; } let n1 = 1, n2 = 1, sn = 0; for(let i = 0; i < n - 2; i ++){ sn = n1 + n2; n1 = n2; n2 = sn; } return sn; }
import * as UTILS from '@utils'; const app = new WHS.App([ ...UTILS.appModules({ position: new THREE.Vector3(0, 40, 70) }) ]); const halfMat = { transparent: true, opacity: 0.5 }; const box = new WHS.Box({ geometry: { width: 30, height: 2, depth: 2 }, modules: [ new PHYSICS.BoxModule({ mass: 0 }) ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.mesh, ...halfMat }), position: { y: 40 } }); const box2 = new WHS.Box({ geometry: { width: 30, height: 1, depth: 20 }, modules: [ new PHYSICS.BoxModule({ mass: 10, damping: 0.1 }) ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.softbody, ...halfMat }), position: { y: 38, z: 12 } }); const pointer = new WHS.Sphere({ modules: [ new PHYSICS.SphereModule() ], material: new THREE.MeshPhongMaterial({ color: UTILS.$colors.mesh }) }); console.log(pointer); pointer.position.set(0, 60, -8); pointer.addTo(app); box.addTo(app); box2.addTo(app).then(() => { const constraint = new PHYSICS.DOFConstraint(box2, box, new THREE.Vector3(0, 38, 1) ); app.addConstraint(constraint); constraint.enableAngularMotor(10, 20); }); UTILS.addPlane(app, 250); UTILS.addBasicLights(app); app.start();
import React from 'react' import { PlanItineraryContainer } from './index' const PlanMapRoute = () => { return ( <div> <PlanItineraryContainer /> </div> ) } export default PlanMapRoute
const path = require('path'); module.exports = { lazyLoad: true, pick: { posts(markdownData) { return { meta: markdownData.meta, description: markdownData.description, }; }, }, plugins: [path.join(__dirname, '..', 'node_modules', 'bisheng-plugin-description')], routes: [{ path: '/', component: './template/Archive', }, { path: '/posts/:post', dataPath: '/:post', component: './template/Post', }, { path: '/tags', component: './template/TagCloud', }], };
// Init ES2015 + .jsx environments for .require() require('babel-register'); var express = require('express'); var fluxexapp = require('./fluxexapp'); var serverAction = require('./actions/server'); var fluxexServerExtra = require('fluxex/extra/server'); var app = express(); // Provide /static/js/main.js fluxexServerExtra.initStatic(app); // Mount test page at /test app.use('/product', fluxexServerExtra.createMiddlewareByAction(fluxexapp, serverAction.samplePage)); // Start server app.listen(process.env.TESTPORT || 3000); console.log('Fluxex started! Go http://localhost:3001/product?id=124');
"use strict"; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var qs = require("querystring"); var partial = require("lodash.partial"); var endpoints = require("./stats-endpoints"); var dicts = require("./dicts"); var translateKeys = require("./util/translate-keys"); var transport = require("./get-json"); var translate = partial(translateKeys, dicts.jsToNbaMap); var stats = Object.create({ setTransport: function setTransport(_transport) { transport = _transport; }, getTransport: function getTransport() { return transport; } }); Object.keys(endpoints).forEach(function (key) { stats[key] = makeStatsMethod(endpoints[key]); }); function makeStatsMethod(endpoint) { return function statsMethod(query, callback) { if (typeof query === "function") { callback = query; query = {}; } if (typeof callback !== "function") { throw new TypeError("Must pass a callback function."); } var params = _extends({}, endpoint.defaults, translate(query)); transport(endpoint.url, params, function (err, response) { if (err) return callback(err); if (response == null) return callback(); // response is something like "GameID is required" if (typeof response === "string") return callback(new Error(response)); if (endpoint.transform) return callback(null, endpoint.transform(response)); callback(null, response); }); }; } module.exports = stats;
import React from 'react'; import ErrorIcon from './ErrorIcon'; export const symbols = { 'ErrorIcon -> with filled': <ErrorIcon filled={true} />, 'ErrorIcon -> without filled': <ErrorIcon filled={false} /> };
import QUnit from 'qunit'; import { registerDeprecationHandler } from '@ember/debug'; let isRegistered = false; let deprecations = new Set(); let expectedDeprecations = new Set(); // Ignore deprecations that are not caused by our own code, and which we cannot fix easily. const ignoredDeprecations = [ // @todo remove when we can land https://github.com/emberjs/ember-render-modifiers/pull/33 here /Versions of modifier manager capabilities prior to 3\.22 have been deprecated/, /Usage of the Ember Global is deprecated./, /import .* directly from/, /Use of `assign` has been deprecated/, ]; export default function setupNoDeprecations({ beforeEach, afterEach }) { beforeEach(function () { deprecations.clear(); expectedDeprecations.clear(); if (!isRegistered) { registerDeprecationHandler((message, options, next) => { if (!ignoredDeprecations.some((regex) => message.match(regex))) { deprecations.add(message); } next(message, options); }); isRegistered = true; } }); afterEach(function (assert) { // guard in if instead of using assert.equal(), to not make assert.expect() fail if (deprecations.size > expectedDeprecations.size) { assert.ok( false, `Expected ${expectedDeprecations.size} deprecations, found: ${[...deprecations] .map((msg) => `"${msg}"`) .join(', ')}` ); } }); QUnit.assert.deprecations = function (count) { if (count === undefined) { this.ok(deprecations.size, 'Expected deprecations during test.'); } else { this.equal(deprecations.size, count, `Expected ${count} deprecation(s) during test.`); } deprecations.forEach((d) => expectedDeprecations.add(d)); }; QUnit.assert.deprecationsInclude = function (expected) { let found = [...deprecations].find((deprecation) => deprecation.includes(expected)); this.pushResult({ result: !!found, actual: deprecations, message: `expected to find \`${expected}\` deprecation. Found ${[...deprecations] .map((d) => `"${d}"`) .join(', ')}`, }); if (found) { expectedDeprecations.add(found); } }; }
module.exports = function(grunt) { // Add our custom tasks. grunt.loadTasks('../../../tasks'); // Project configuration. grunt.initConfig({ mochaTest: { options: { reporter: 'spec', grep: 'tests that match grep', invert: true }, all: { src: ['*.js'] } } }); // Default task. grunt.registerTask('default', ['mochaTest']); };
import React, { Component } from 'react'; class Main extends Component { render() { return ( <main className='Main'> <h1 className='Main-headline'>Web solutions focused on<br/>Simplicity & Reliability.</h1> <h2 className='Main-subhead'>Bleeding edge technology paired with amazing <em>talent</em> and <em>creativity</em>.</h2> <a href='#' className='Main-button'>Work With Us</a> </main> ); } } export default Main;
'use strict'; angular.module('main', ['ngRoute', 'ngResource', 'ui.route', 'main.system', 'main.index', 'main.events']); angular.module('main.system', []); angular.module('main.index', []); angular.module('main.events', []); 'use strict'; //Setting HTML5 Location Mode angular.module('main').config(['$locationProvider', function ($locationProvider) { $locationProvider.hashPrefix('!'); } ]); 'use strict'; angular.module('main.system') .factory('Global', [ function () { var obj = this; obj._data = { app: window.app || false }; return obj._data; } ]); 'use strict'; angular.element(document).ready(function() { //Fixing facebook bug with redirect if (window.location.hash === '#_=_') window.location.hash = '#!'; //Then init the app angular.bootstrap(document, ['main']); }); 'use strict'; angular.module('main').config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', { templateUrl: '/views/index.html' }) .otherwise({ redirectTo: '/' }); } ]); 'use strict'; angular.module('main.index') .controller('IndexCtrl', ['$scope', '$routeParams', '$http', '$location', 'Global', 'Event', function ($scope, $routeParams, $http, $location, Global, Event) { $scope.global = Global; $scope.getEvents = function(){ Event.query(function(data){ $scope.events = data; }); }; $scope.init = function(){ $scope.getEvents(); }; } ]); 'use strict'; angular.module('main.events') .factory('Event', [ '$resource', function ($resource) { return $resource("/api/events/:id"); } ]);
/** * StaticText.js * Text that cannot be changed after loaded by the game */ import GamePiece from './GamePiece.js'; import Info from './Info.js'; import Text from './Text.js'; export default class StaticText extends Text { constructor (config) { super(config); this.static = true; } }
import React from 'react'; import { string, node } from 'prop-types'; import classNames from 'classnames'; const TileAction = ({ children, className, ...rest }) => { return ( <div className={classNames('tile-action', className)} {...rest}> {children} </div> ); }; /** * TileAction property types. */ TileAction.propTypes = { className: string, children: node }; /** * TileAction default properties. */ TileAction.defaultProps = {}; export default TileAction;
M.profile("generators"); function* forOfBlockScope() { let a = [1, 2, 3, 4, 5, 6, 7, 8]; let b = [10, 11, 12, 13, 14, 15, 16]; const funs = []; for (const i of a) { let j = 0; funs.push(function* iter() { yield `fo1: ${i} ${j++}`; }); } for (var i of a) { var j = 0; funs.push(function* iter() { yield `fo2: ${i} ${j++}`; }); } for (const i of a) { for (let j of b) { funs.push(function* iter() { yield `fo3: ${i} ${j++}`; }); } } for (const i of a) { for (let j of b) { yield `fo4: ${j}`; funs.push(function* iter() { yield `fo5: ${i} ${j++}`; }); } } for (const i of a) { yield `fo6: ${i}`; for (let j of b) { funs.push(function* iter() { yield `fo7: ${i} ${j++}`; }); } } for (const i of a) { yield `fo8 ${i}`; for (let j of b) { yield `fo9: ${i}`; funs.push(function* iter() { yield `fo10: ${i} ${j++}`; }); } } for (const i of funs) yield* i(); funs.length = 0; for (const i of a) { funs.push(function* iter() { yield `fo11: ${i}`; }); } for (const i of a) { yield `fo12 ${i}`; funs.push(function* iter() { yield `fo13 ${i}`; }); } let k = 0; for (const i of a) { yield `fo14 ${i} ${k} {m}`; let m = k; k++; if (k === 3) continue; if (k === 5) break; funs.push(function* iter() { yield `fo15 ${i} ${k} {m}`; }); } k = 0; up1: for (const i of a) { let m = k; k++; for (const j of b) { let n = m; m++; if (k === 3) continue up1; if (k === 5) break up1; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo18: ${i} ${j} ${k} ${m} ${n}`; }); } } k = 0; up2: for (const i of a) { let m = 0; k++; yield `fo16: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; if (k === 3) continue up2; if (k === 5) break up2; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo18: ${i} ${j} ${k} ${m} ${n}`; }); } } k = 0; up3: for (const i of a) { let m = 0; k++; for (const j of b) { let n = m; m++; yield `fo19 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) { continue up3; } if (k === 5) break up3; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo20: ${i} ${j} ${k} ${m} ${n}`; }); } } bl1: { let k = 0; yield `fo21: ${i} ${k}`; up4: for (const i of a) { let m = 0; k++; yield `fo22: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; yield `fo23 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) continue up4; if (k === 5) break bl1; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo24: ${i} ${j} ${k} ${m} ${n}`; }); } } } bl2: { let k = 0; yield `fo25`; up5: for (const i of a) { let m = 0; k++; yield `fo26: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; yield `fo27 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) continue up5; if (k === 5) break bl2; if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo28: ${i} ${j} ${k} ${m} ${n}`; }); } } } bl3: { let k = 0; up6: for (const i of a) { let m = 0; k++; yield `fo29: ${i} ${k} ${m}`; for (const j of b) { let n = m; m++; yield `fo30 ${i} ${j} ${k} ${m} ${n}`; if (k === 3) continue up6; if (k === 5) { for (const i of funs) yield* i(); return `r: ${i} ${j} ${k} ${m} ${n}`; } if (n === 3) continue; if (n === 5) break; funs.push(function* iter() { n++; yield `fo31: ${i} ${j} ${k} ${m} ${n}`; }); } } } }
/* * Webpack development server configuration * * This file is set up for serving the webpack-dev-server, which will watch for changes and recompile as required if * the subfolder /webpack-dev-server/ is visited. Visiting the root will not automatically reload. */ 'use strict'; import webpack from 'webpack'; import path from 'path'; import autoprefixer from 'autoprefixer'; const API_URL = process.env['__API_URL__'] || 'http://localhost:3001/'; //eslint-disable-line export default { output: { path: path.join(__dirname, '.tmp'), filename: 'bundle.js', publicPath: '/static/' }, devtool: 'eval-source-map', entry: [ 'whatwg-fetch', 'webpack-dev-server/client?http://0.0.0.0:3000', 'webpack/hot/only-dev-server', 'react-hot-loader/patch', './src/index.js' ], module: { preLoaders: [{ test: /\.(js|jsx)$/, exclude: [/node_modules/, /vendor/], loader: 'eslint-loader' }], loaders: [{ test: /\.(js|jsx)$/, include: path.join(__dirname, 'src'), loader: 'babel-loader' }, { test: /\.scss/, loader: 'style-loader!css-loader!postcss-loader!sass-loader' }, { test: /\.json/, loader: 'json-loader' }, { test: /\.(png|jpg|ttf|svg|eot|woff|woff2)/, loader: 'url-loader?limit=8192' }] }, postcss: [ autoprefixer({ browsers: 'last 2 versions' }) ], plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.DefinePlugin({ __DEV__: true, __DEVTOOLS__: false, __API_URL__: `\'${API_URL}\'` }) ] };
// This code will add an event listener to each anchor of the topbar after being dynamically replaced by "interchange" $("body").on("click", function(event){ // If the active element is one of the topbar's links continues if($(event.target).hasClass("topbarLink")) { // The parent li element of the current active link is stored var activeLink = $(event.target).parent(); // Takes each link and checks if its parent li element is active, removing "active" class if so. $("#topNavContent li:not(.divider)").each(function(){ // If the li element has nested li's with links they are checked also. if($(this).hasClass("has-dropdown")){ var dropdownList = $(this).children(".dropdown").children().not(".divider"); dropdownList.each(function(){ if($(this).hasClass("active")){ $(this).removeClass("active"); } }); } // The direct li element's "active" class is removed if($(this).hasClass("active")){ $(this).removeClass("active"); } }); // After having all topbar li elements deactivated, "active" class is added to the currently active link's li parent if(!$(activeLink).hasClass("active")){ $(activeLink).addClass("active"); } } }); // This variable is used to know if this script will be loaded at the time of checking it in the JS manager activeLinkActivatorLoaded = true;
const elixir = require('laravel-elixir'); elixir((mix) => { // Mix all Sass files into one mix.sass('app.scss'); // Mix all vendor scripts together mix.scripts( [ 'jquery/dist/jquery.min.js', 'bootstrap-sass/assets/javascripts/bootstrap.min.js', 'bootstrap-sass/assets/javascripts/bootstrap/dropdown.js' ], 'resources/assets/js/vendor.js', 'node_modules' ); // Mix all script files into one mix.scripts( ['vendor.js', 'app.js'], 'public/js/app.js' ); // Copy vendor assets to public mix.copy('node_modules/bootstrap-sass/assets/fonts/bootstrap/','public/fonts/bootstrap') .copy('node_modules/font-awesome/fonts', 'public/fonts'); }); /* var elixir = require('laravel-elixir'); elixir(function(mix) { // Mix all scss files into one css file mix.sass([ 'charts.scss', 'app.scss' ], 'public/css/app.css'); // Mix all chart JS files into a master charts file mix.scriptsIn( 'resources/assets/js/charts', 'public/js/charts.js' ); // Mix common JS files into one file mix.scripts([ 'app.js' ], 'public/js/app.js'); }); */
import {Map} from 'immutable'; export function getInteractiveLayerIds(mapStyle) { let interactiveLayerIds = []; if (Map.isMap(mapStyle) && mapStyle.has('layers')) { interactiveLayerIds = mapStyle.get('layers') .filter(l => l.get('interactive')) .map(l => l.get('id')) .toJS(); } else if (Array.isArray(mapStyle.layers)) { interactiveLayerIds = mapStyle.layers.filter(l => l.interactive) .map(l => l.id); } return interactiveLayerIds; }
var textDivTopIndex = -1; /** * Creates a div that contains a textfiled, a plus and a minus button * @param {String | undefined} textContent string to be added to the given new textField as value * @returns new div */ function createTextDiv( textContent ) { textDivTopIndex++; var newTextDiv = document.createElement("DIV"); newTextDiv.className = "inputTextDiv form-group row"; newTextDiv.id = "uriArray"+textDivTopIndex; newTextDiv.setAttribute("index", textDivTopIndex); //newTextDiv.innerHTML = "hasznaltauto.hu url:"; //textfield that asks for a car uri and its align-responsible container var textField = document.createElement("INPUT"); textField.id = uriInputFieldIdPrefix + textDivTopIndex; textField.type = "url"; textField.name = "carUri"+textDivTopIndex; textField.className = "form-control"; textField.placeholder = "hasznaltauto.hu url"; textField.value = (textContent === undefined) ? "" : textContent; //all textfield has it, but there is to be 10 at maximum so the logic overhead would be greater(always the last one should have it) than this efficiency decrease addEvent( textField, "focus", addOnFocus); var textFieldAlignerDiv = document.createElement("DIV"); textFieldAlignerDiv.className = "col-xs-10 col-sm-10 col-sm-10"; textFieldAlignerDiv.appendChild(textField); //add a new input field, or remove current var inputButtonMinus = document.createElement("BUTTON"); inputButtonMinus.className = "btn btn-default btn-sm col-xs-1 col-sm-1 col-md-1 form-control-static"; inputButtonMinus.type = "button"; //avoid submit, which is default for buttons on forms inputButtonMinus.innerHTML = "-"; inputButtonMinus.id = "inputButtonMinus" + textDivTopIndex; newTextDiv.appendChild(textFieldAlignerDiv); newTextDiv.appendChild(inputButtonMinus); currentInputUriCount++; return newTextDiv } function addOnFocus(event) { if ( isLastField(event.target) && currentInputUriCount < 10 ) { var addedTextDiv = createTextDiv(); formElement.insertBefore(addedTextDiv, sendButtonDiv); event.stopPropagation(); } } function isLastField(field) { textDivTopIndex = 0; $(".inputTextDiv").each(function(index) { textDivTopIndex = ( $(this).attr("index") > textDivTopIndex ) ? $(this).attr("index") : textDivTopIndex; }); return textDivTopIndex == field.parentElement.parentElement.getAttribute("index") || currentInputUriCount === 1; }
'use strict'; /** * Stripe library * * @module core/lib/c_l_stripe * @license MIT * @copyright 2016 Chris Turnbull <https://github.com/christurnbull> */ module.exports = function(app, db, lib) { return { /** * Donate */ donate: function(inObj, cb) { var number, expiry, cvc, currency; try { number = parseInt(inObj.body.number); var exp = inObj.body.expiry.split('/'); expiry = { month: parseInt(exp[0]), year: parseInt(exp[1]) }; cvc = parseInt(inObj.body.cvc); currency = inObj.body.currency.toLowerCase(); } catch (e) { return cb([{ msg: 'Invalid details.', desc: 'Payment has not been made' }], null); } // stripe supported zero-decimal currencies var zeroDecimal = { BIF: 'Burundian Franc', CLP: 'Chilean Peso', DJF: 'Djiboutian Franc', GNF: 'Guinean Franc', JPY: 'Japanese Yen', KMF: 'Comorian Franc', KRW: 'South Korean Won', MGA: 'Malagasy Ariary', PYG: 'Paraguayan Guaraní', RWF: 'Rwandan Franc', VND: 'Vietnamese Đồng', VUV: 'Vanuatu Vatu', XAF: 'Central African Cfa Franc', XOF: 'West African Cfa Franc', XPF: 'Cfp Franc' }; var amount = inObj.body.amount; if (!zeroDecimal.hasOwnProperty(currency.toUpperCase())) { // all other supoprted currencies are decimal amount = amount * 100; } var stripeData = { amount: amount, currency: currency.toLowerCase(), description: 'Donation from ' + inObj.body.name, source: { number: number, exp_month: expiry.month, exp_year: expiry.year, cvc: cvc, object: 'card', customer: inObj.body.customer, email: inObj.body.email } }; lib.core.stripe.charges.create(stripeData, function(err, charge) { if (err) { return cb(err, null); } // save to database etc... return cb(null, [charge]); }); } }; };
/* artifact generator: C:\My\wizzi\v5\node_modules\wizzi-js\lib\artifacts\js\module\gen\main.js primary source IttfDocument: c:\my\wizzi\v5\plugins\wizzi-core\src\ittf\root\legacy.js.ittf */ 'use strict'; module.exports = require('wizzi-legacy-v4');
#!/bin/env node 'use strict'; var winston = require('winston'), path = require('path'), mcapi = require('mailchimp-api'), Parser = require('./lib/parser'), ApiWrapper = require('./lib/api-wrapper'); var date = new Date(); date = date.toJSON().replace(/(-|:)/g, '.'); winston.remove(winston.transports.Console); winston.add(winston.transports.Console, { level: 'silly'}); winston.add(winston.transports.File, { filename: path.join('./', 'logs', 'sxla' + date + '.log'), level: 'silly', timestamp: true }); winston.info('*********** APPLICATION STARTED ***********'); var apiKey = process.env.MAILCHIMP_SXLA_API_KEY; var listId = process.env.MAILCHIMP_SXLA_LIST_ID; winston.debug('apiKey: ', apiKey); winston.debug('listId: ', listId); var api = new ApiWrapper(mcapi, apiKey, listId, winston); var parser = new Parser(winston); parser.parseCsv(__dirname + '/data/soci14-15.csv', function (data) { api.batchSubscribe(data); });
module.exports = { normalizeEntityName: function() {}, afterInstall: function() { this.addBowerPackageToProject('jsoneditor'); } };
import AMD from '../../amd/src/amd.e6'; import Core from '../../core/src/core.e6'; import Event from '../../event/src/event.e6'; import Detect from '../../detect/src/detect.e6'; import Module from '../../modules/src/base.es6'; import ModulesApi from '../../modules/src/api.e6'; window.Moff = new Core(); window.Moff.amd = new AMD(); window.Moff.event = new Event(); window.Moff.Module = new Module(); window.Moff.detect = new Detect(); window.Moff.modules = new ModulesApi();
/** * Module dependencies */ const express = require('express'); const cluster = require('cluster'); const numCPUs = require('os').cpus().length; const compression = require('compression'); const helmet = require('helmet'); const hpp = require('hpp'); const config = require('./config'); const api = require('./api'); const pages = require('./app'); /** * Create app and router */ const app = express(); /** * Set express trust proxy */ app.set('trust proxy', true); /** * Set static directory */ app.use(express.static(__dirname + '/public')); /** * Add middlewares */ app.use(compression()); app.use(helmet()); app.use(hpp()); /** * Ping route */ app.get('/ping', (req, res) => res.send('Pong')); /** * Add router */ app.use('/api', api); /** * Mount template router */ app.use('/', pages); /** * Port */ const port = process.env.PORT || config.server.port; /** * Cluster */ if (cluster.isMaster) { for (let i = 0; i < numCPUs; i += 1) { cluster.fork(); } cluster.on('online', (worker) => { console.log(`Worker ${worker.process.pid} is online`); }); cluster.on('exit', (worker) => { console.log(`Worker ${worker.process.pid} died`); console.log('Starting a new worker'); cluster.fork(); }); } else { app.listen(port, '0.0.0.0', () => { console.log(`App listening on port ${port}.`); }); } /** * Handle unhandled exceptions */ process.on('unhandledException', err => console.log(err.toString())); /** * Expose app */ module.exports = app;
angular.module('myApp.toDoController', []). controller('ToDoCtrl', ['$scope', '$state', '$http', '$route', function ($scope, $state, $http, $route) { $scope.$state = $state; $scope.addToDo = function() { // Just in case... if ($scope.toDoList.length > 50) { alert("Exceeded to-do limit!!!"); return; } if (!$scope.newToDoName || !$scope.newToDoDesc) { alert("Please fill out both fields!"); return; } var newToDo = { 'todo': $scope.newToDoName, 'description': $scope.newToDoDesc }; $http.post('/to-dos/add-to-do', newToDo). success(function(data, status, headers, config) { }). then(function(answer){ $scope.newToDoName = ''; $scope.newToDoDesc = ''; getToDos(); }); }; $scope.editToDoId = ''; $scope.editToDo = function(toDo) { // Set the ID of the todo being edited $scope.editToDoId = toDo._id; // Reset the to do list in case we were editing other to dos getToDos(); }; $scope.confirmEditToDo = function() { // Get the data from the ToDo of interest var toDoToEdit = ''; for (var i=0; i<$scope.toDoList.length; i++) { if ($scope.toDoList[i]._id === $scope.editToDoId){ toDoToEdit = { "todo" : $scope.toDoList[i].todo, "description" : $scope.toDoList[i].description }; break; } } if (!toDoToEdit) { alert("Could not get edited to-do!"); return; } else if (!toDoToEdit.todo || !toDoToEdit.description) { alert("Please fill out both fields!"); return; } $http.put('/to-dos/update-to-do/' + $scope.editToDoId, toDoToEdit). success(function(data, status, headers, config) { $scope.editToDoId = ''; }). then(function(answer){ getToDos(); }); }; $scope.deleteToDo = function(toDo) { var confirmation = confirm('Are you sure you want to delete?'); if (!confirmation){ return; } $http.delete('/to-dos/delete-to-do/' + toDo._id). success(function(data, status, headers, config) { }). then(function(answer){ getToDos(); }); }; $scope.cancelEditToDo = function() { $scope.editToDoId = ''; getToDos(); }; var getToDos = function() { $http.get('/to-dos/to-dos').success(function(data, status, headers, config) { $scope.toDoList = data; }); }; // Execute these functions on page load angular.element(document).ready(function () { getToDos(); }); }]);
import CommuniqueApp from './communique-app'; CommuniqueApp.open();
module.exports = [ 'babel-polyfill', 'react', 'react-redux', 'react-router', 'react-dom', 'redux', 'redux-thunk', 'seamless-immutable', 'react-router-redux', 'history', 'lodash', 'styled-components', 'prop-types', ];
import nextConnect from 'next-connect' import auth from '../../middleware/auth' import { deleteUser, updateUserByUsername } from '../../lib/db' const handler = nextConnect() handler .use(auth) .get((req, res) => { // You do not generally want to return the whole user object // because it may contain sensitive field such as !!password!! Only return what needed // const { name, username, favoriteColor } = req.user // res.json({ user: { name, username, favoriteColor } }) res.json({ user: req.user }) }) .use((req, res, next) => { // handlers after this (PUT, DELETE) all require an authenticated user // This middleware to check if user is authenticated before continuing if (!req.user) { res.status(401).send('unauthenticated') } else { next() } }) .put((req, res) => { const { name } = req.body const user = updateUserByUsername(req, req.user.username, { name }) res.json({ user }) }) .delete((req, res) => { deleteUser(req) req.logOut() res.status(204).end() }) export default handler
import { injectReducer } from 'STORE/reducers' export default store => ({ path : 'checkHistoryList.html', getComponent(nextState, cb) { require.ensure([], (require) => { const CheckHistoryList = require('VIEW/CheckHistoryList').default const reducer = require('REDUCER/checkHistoryList').default injectReducer(store, { key: 'checkHistoryList', reducer }) cb(null, CheckHistoryList) }, 'checkHistoryList') } })
;(function() { angular.module('app.core') .config(config); /* @ngInject */ function config($stateProvider, $locationProvider, $urlRouterProvider) { $stateProvider /** * @name landing * @type {route} * @description First page for incoming users, and for default routing * for all failed routes. */ .state('landing', { url: '/', templateUrl: '/html/modules/landing/landing.html', controller: 'LandingController', controllerAs: 'vm' }) /** * @name home * @type {route} * @description User landing page, the main display. */ .state('home', { url: '', abstract: true, views: { '': { templateUrl: 'html/modules/home/template.html' }, 'current-routes@home': { templateUrl: 'html/modules/layout/current-routes.html', controller: 'CurrentRoutesController', controllerAs: 'vm' }, 'add-routes@home': { templateUrl: 'html/modules/layout/add-routes.html', controller: 'AddRoutesController', controllerAs: 'vm' } } }) .state('home.home', { url: '/home', authenticate: true, views: { 'container@home': { templateUrl: 'html/modules/home/welcome.html' } } }) .state('home.new-route', { url: '/new-route/:route', authenticate: true, views: { 'container@home': { templateUrl: 'html/modules/routes/new-route.html', controller: 'NewRouteController', controllerAs: 'vm' } } }) /** * @name editRoute * @type {route} * @description View for editing a specific route. Provides options * to edit or delete the route. */ .state('home.edit-route', { url: '/routes/{route:.*}', authenticate: true, views: { 'container@home': { templateUrl: '/html/modules/routes/edit-routes.html', controller: 'EditRoutesController', controllerAs: 'vm', } } }) /** * @name Docs * @type {route} * @description View for the project documentation * */ .state('docs',{ url:'', abstract: true, views: { '': { templateUrl: '/html/modules/docs/docs.html' }, 'doc-list@docs': { templateUrl: '/html/modules/docs/docs-list.html', controller: 'DocsController', controllerAs: 'vm' } } }) .state('docs.docs', { url: '/docs', views: { 'container@docs': { templateUrl: '/html/modules/docs/current-doc.html' } } }) .state('docs.current-doc', { url: '/docs/:doc', views: { 'container@docs': { templateUrl: function($stateParams) { return '/html/modules/docs/pages/' + $stateParams.doc + '.html'; } } } }) .state('home.analytics', { url: '/analytics/{route:.*}', authenticate: true, views: { 'container@home': { templateUrl: '/html/modules/analytics/analytics.html', controller: 'AnalyticsController', controllerAs: 'vm' } } }); // default uncaught routes to landing page $urlRouterProvider.otherwise('/'); // enable HTML5 mode $locationProvider.html5Mode(true); } }).call(this);
import Route from '@ember/routing/route'; import { A } from '@ember/array'; import { hash } from 'rsvp'; import EmberObject from '@ember/object' export default Route.extend({ model: function() { return hash({ exampleModel: EmberObject.create(), disableSubmit: false, selectedLanguage: null, selectOptions: A([ {label: 'French', value: 'fr'}, {label: 'English', value: 'en'}, {label: 'German', value: 'gr'} ]), radioOptions: A([ {label: 'Ruby', value: 'ruby'}, {label: 'Javascript', value: 'js'}, {label: 'Cold Fusion', value: 'cf'} ]) }); }, actions: { submit: function() { window.alert('You triggered a form submit!'); }, toggleErrors: function() { var model = this.get('currentModel').exampleModel; if(model.get('errors')) { model.set('errors', null); }else{ var errors = { first_name: A(['That first name is wrong']), last_name: A(['That last name is silly']), language: A(['Please choose a better language']), isAwesome: A(['You must be awesome to submit this form']), bestLanguage: A(['Wrong, Cold Fusion is the best language']), essay: A(['This essay is not very good']) }; model.set('errors', errors); } }, toggleSelectValue: function() { if(this.get('currentModel.exampleModel.language')) { this.set('currentModel.exampleModel.language', null); }else{ this.set('currentModel.exampleModel.language', 'fr'); } }, toggleSubmit: function() { if(this.get('currentModel.disableSubmit')) { this.set('currentModel.disableSubmit', false); }else{ this.set('currentModel.disableSubmit', true); } }, toggleCheckbox: function() { if(this.get('currentModel.exampleModel.isAwesome')) { this.set('currentModel.exampleModel.isAwesome', false); } else { this.set('currentModel.exampleModel.isAwesome', true); } }, toggleRadio: function() { if(this.get('currentModel.exampleModel.bestLanguage')) { this.set('currentModel.exampleModel.bestLanguage', null); }else{ this.set('currentModel.exampleModel.bestLanguage', 'js'); } } } });
import lowerCaseFirst from 'lower-case-first'; import {handles} from 'marty'; import Override from 'override-decorator'; function addHandlers(ResourceStore) { const {constantMappings} = this; return class ResourceStoreWithHandlers extends ResourceStore { @Override @handles(constantMappings.getMany.done) getManyDone(payload) { super.getManyDone(payload); this.hasChanged(); } @Override @handles(constantMappings.getSingle.done) getSingleDone(payload) { super.getSingleDone(payload); this.hasChanged(); } @handles( constantMappings.postSingle.done, constantMappings.putSingle.done, constantMappings.patchSingle.done ) changeSingleDone(args) { // These change actions may return the inserted or modified object, so // update that object if possible. if (args.result) { this.getSingleDone(args); } } }; } function addFetch( ResourceStore, { actionsKey = `${lowerCaseFirst(this.name)}Actions` } ) { const {methodNames, name, plural} = this; const {getMany, getSingle} = methodNames; const refreshMany = `refresh${plural}`; const refreshSingle = `refresh${name}`; return class ResourceStoreWithFetch extends ResourceStore { getActions() { return this.app[actionsKey]; } [getMany](options, {refresh} = {}) { return this.fetch({ id: `c${this.collectionKey(options)}`, locally: () => this.localGetMany(options), remotely: () => this.remoteGetMany(options), refresh }); } [refreshMany](options) { return this[getMany](options, {refresh: true}); } localGetMany(options) { return super[getMany](options); } remoteGetMany(options) { return this.getActions()[getMany](options); } [getSingle](id, options, {refresh} = {}) { return this.fetch({ id: `i${this.itemKey(id, options)}`, locally: () => this.localGetSingle(id, options), remotely: () => this.remoteGetSingle(id, options), refresh }); } [refreshSingle](id, options) { return this[getSingle](id, options, {refresh: true}); } localGetSingle(id, options) { return super[getSingle](id, options); } remoteGetSingle(id, options) { return this.getActions()[getSingle](id, options); } fetch({refresh, ...options}) { if (refresh) { const baseLocally = options.locally; options.locally = function refreshLocally() { if (refresh) { refresh = false; return undefined; } else { return this::baseLocally(); } }; } return super.fetch(options); } }; } export default function extendStore( ResourceStore, { useFetch = true, ...options } ) { ResourceStore = this::addHandlers(ResourceStore, options); if (useFetch) { ResourceStore = this::addFetch(ResourceStore, options); } return ResourceStore; }
$('.js-toggle-menu').click(function(e){ e.preventDefault(); $(this).siblings().toggle(); }); $('.nav--primary li').click(function(){ $(this).find('ul').toggleClass('active'); });
function solve(message) { let tagValidator = /^<message((?:\s+[a-z]+="[A-Za-z0-9 .]+"\s*?)*)>((?:.|\n)+?)<\/message>$/; let tokens = tagValidator.exec(message); if (!tokens) { console.log("Invalid message format"); return; } let [match, attributes, body] = tokens; let attributeValidator = /\s+([a-z]+)="([A-Za-z0-9 .]+)"\s*?/g; let sender = ''; let recipient = ''; let attributeTokens = attributeValidator.exec(attributes); while (attributeTokens) { if (attributeTokens[1] === 'to') { recipient = attributeTokens[2]; } else if (attributeTokens[1] === 'from') { sender = attributeTokens[2]; } attributeTokens = attributeValidator.exec(attributes); } if (sender === '' || recipient === '') { console.log("Missing attributes"); return; } body = body.replace(/\n/g, '</p>\n <p>'); let html = `<article>\n <div>From: <span class="sender">${sender}</span></div>\n`; html += ` <div>To: <span class="recipient">${recipient}</span></div>\n`; html += ` <div>\n <p>${body}</p>\n </div>\n</article>`; console.log(html); } solve(`<message from="John Doe" to="Alice">Not much, just chillin. How about you?</message>`); /* solve( `<message to="Bob" from="Alice" timestamp="1497254092">Hey man, what's up?</message>`, `<message from="Ivan Ivanov" to="Grace">Not much, just chillin. How about you?</message>` ); */
'use strict'; const test = require('ava'); const hashSet = require('../index'); const MySet = hashSet(x => x); test('should not change empty set', t => { const set = new MySet(); set.clear(); t.is(set.size, 0); }); test('should clear set', t => { const set = new MySet(); set.add(1); set.clear(); t.is(set.size, 0); });
'use strict'; const path = require('path'); const jwt = require('jsonwebtoken'); const AuthConfig = require(path.resolve('./config')).Auth; const jwtSecret = AuthConfig.jwt.secret; const tokenExpirePeriod = AuthConfig.jwt.tokenExpirePeriod; function generateToken(payLoad) { const isObject = (typeof payLoad === 'object'); if (payLoad) { if (isObject) { return new Promise((resolve, reject) => { jwt.sign(payLoad, jwtSecret, { expiresIn: tokenExpirePeriod }, (error, token) => { if (error) { reject(error); } else { resolve(token); } }); }) } else { const error = new TypeError('Token Payload Must Be An Object'); return Promise.reject(error); } } else { const error = new Error('Token Payload Should Not Be Empty'); return Promise.reject(error); } } function verifyToken(token) { if (token) { return new Promise((resolve, reject) => { jwt.verify(token, jwtSecret, (error, decodedToken) => { if (error) { reject(error); } else { resolve(decodedToken); } }); }) } else { const error = new Error('Token Should Not Be Empty'); return Promise.reject(error); } } module.exports = { generate: generateToken, verify: verifyToken };
/*! Slidebox.JS - v1.0 - 2013-11-30 * http://github.com/trevanhetzel/slidebox * * Copyright (c) 2013 Trevan Hetzel <trevan.co>; * Licensed under the MIT license */ slidebox = function (params) { // Carousel carousel = function () { var $carousel = $(params.container).children(".carousel"), $carouselItem = $(".carousel li"), $triggerLeft = $(params.leftTrigger), $triggerRight = $(params.rightTrigger), total = $carouselItem.length, current = 0; var moveLeft = function () { if ( current > 0 ) { $carousel.animate({ "left": "+=" + params.length + "px" }, params.speed ); current--; } }; var moveRight = function () { if ( current < total - 2 ) { $carousel.animate({ "left": "-=" + params.length + "px" }, params.speed ); current++; } }; // Initiliaze moveLeft on trigger click $triggerLeft.on("click", function () { moveLeft(); }); // Initiliaze moveRight on trigger click $triggerRight.on("click", function () { moveRight(); }); // Initiliaze moveLeft on left keypress $(document).keydown(function (e){ if (e.keyCode == 37) { moveLeft(); } }); // Initiliaze moveRight on right keypress $(document).keydown(function (e){ if (e.keyCode == 39) { moveRight(); } }); }, // Lightbox lightbox = function () { var trigger = ".carousel li a"; // Close lightbox when pressing esc key $(document).keydown(function (e){ if (e.keyCode == 27) { closeLightbox(); } }); $(document) // Close lightbox on any click .on("click", function () { closeLightbox(); }) // If clicked on a thumbnail trigger, proceed .on("click", trigger, function (e) { var $this = $(this); // Prevent from clicking through e.preventDefault(); e.stopPropagation(); // Grab the image URL dest = $this.attr("href"); // Grab the caption from data attribute capt = $this.children("img").data("caption"); enlarge(dest, capt); /* If clicked on an enlarged image, stop propagation so it doesn't get the close function */ $(document).on("click", ".lightbox img", function (e) { e.stopPropagation(); }); }); closeLightbox = function () { $(".lightbox-cont").remove(); $(".lightbox").remove(); }, enlarge = function (dest, capt) { // Create new DOM elements $("body").append("<div class='lightbox-cont'></div><div class='lightbox'></div>"); $(".lightbox").html(function () { return "<img src='" + dest + "'><div class='lightbox-caption'>" + capt + "</div>"; }); } } // Initialize functions carousel(); lightbox(); };
import test from 'ava'; import Server from '../../src/server'; import IO from '../../src/socket-io'; test.cb('mock socket invokes each handler with unique reference', t => { const socketUrl = 'ws://roomy'; const server = new Server(socketUrl); const socket = new IO(socketUrl); let handlerInvoked = 0; const handler3 = function handlerFunc() { t.true(true); handlerInvoked += 1; }; // Same functions but different scopes/contexts socket.on('custom-event', handler3.bind(Object.create(null))); socket.on('custom-event', handler3.bind(Object.create(null))); // Same functions with same scope/context (only one should be added) socket.on('custom-event', handler3); socket.on('custom-event', handler3); // not expected socket.on('connect', () => { socket.join('room'); server.to('room').emit('custom-event'); }); setTimeout(() => { t.is(handlerInvoked, 3, 'handler invoked too many times'); server.close(); t.end(); }, 500); }); test.cb('mock socket invokes each handler per socket', t => { const socketUrl = 'ws://roomy'; const server = new Server(socketUrl); const socketA = new IO(socketUrl); const socketB = new IO(socketUrl); let handlerInvoked = 0; const handler3 = function handlerFunc() { t.true(true); handlerInvoked += 1; }; // Same functions but different scopes/contexts socketA.on('custom-event', handler3.bind(socketA)); socketB.on('custom-event', handler3.bind(socketB)); // Same functions with same scope/context (only one should be added) socketA.on('custom-event', handler3); socketA.on('custom-event', handler3); // not expected socketB.on('custom-event', handler3.bind(socketB)); // expected because bind creates a new method socketA.on('connect', () => { socketA.join('room'); socketB.join('room'); server.to('room').emit('custom-event'); }); setTimeout(() => { t.is(handlerInvoked, 4, 'handler invoked too many times'); server.close(); t.end(); }, 500); });
import React from 'react' import PropTypes from 'prop-types' import VelocityTrimControls from './VelocityTrimControls' import Instrument from '../../images/Instrument' import styles from '../../styles/velocityTrim' import { trimShape } from '../../reducers/velocityTrim' const handleKeyDown = (event, item, bank, userChangedTrimEnd) => { let delta = 0 event.nativeEvent.preventDefault() switch (event.key) { case 'ArrowUp': delta = 1 break case 'ArrowDown': delta = -1 break case 'PageUp': delta = 5 break case 'PageDown': delta = -5 break case 'Enter': delta = 100 break case 'Escape': delta = -100 break default: break } if (delta !== 0) { delta += item.trim if (delta < 0) delta = 0 if (delta > 100) delta = 100 userChangedTrimEnd(item.note, delta, bank) } } const VelocityTrim = (props) => { const { item, bank, selected, playNote, selectTrim, userChangedTrimEnd } = props const { note, trim, group, name } = item return ( <section tabIndex={note} onKeyDown={e => handleKeyDown(e, item, bank, userChangedTrimEnd)} onMouseUp={() => (selected ? null : selectTrim(note))} className={selected ? styles.selected : ''} role="presentation" > <div className={styles.header} onMouseUp={() => playNote(note, Math.round(127 * (trim / 100)), bank)} role="button" tabIndex={note} > <div>{note}</div> <div>{group}</div> <div>{Instrument(group)}</div> </div> <div className={styles.noteName} title={name} > {name} </div> <VelocityTrimControls {...props} /> </section> ) } VelocityTrim.propTypes = { item: trimShape.isRequired, selected: PropTypes.bool.isRequired, playNote: PropTypes.func.isRequired, selectTrim: PropTypes.func.isRequired, userChangedTrimEnd: PropTypes.func.isRequired, bank: PropTypes.number.isRequired, } export default VelocityTrim
/** * @fileoverview Rule to flag use of implied eval via setTimeout and setInterval * @author James Allardice */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const astUtils = require("./utils/ast-utils"); const { getStaticValue } = require("eslint-utils"); //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { type: "suggestion", docs: { description: "disallow the use of `eval()`-like methods", category: "Best Practices", recommended: false, url: "https://eslint.org/docs/rules/no-implied-eval" }, schema: [], messages: { impliedEval: "Implied eval. Consider passing a function instead of a string." } }, create(context) { const EVAL_LIKE_FUNCS = Object.freeze(["setTimeout", "execScript", "setInterval"]); const GLOBAL_CANDIDATES = Object.freeze(["global", "window", "globalThis"]); /** * Checks whether a node is evaluated as a string or not. * @param {ASTNode} node A node to check. * @returns {boolean} True if the node is evaluated as a string. */ function isEvaluatedString(node) { if ( (node.type === "Literal" && typeof node.value === "string") || node.type === "TemplateLiteral" ) { return true; } if (node.type === "BinaryExpression" && node.operator === "+") { return isEvaluatedString(node.left) || isEvaluatedString(node.right); } return false; } /** * Checks whether a node is an Identifier node named one of the specified names. * @param {ASTNode} node A node to check. * @param {string[]} specifiers Array of specified name. * @returns {boolean} True if the node is a Identifier node which has specified name. */ function isSpecifiedIdentifier(node, specifiers) { return node.type === "Identifier" && specifiers.includes(node.name); } /** * Checks a given node is a MemberExpression node which has the specified name's * property. * @param {ASTNode} node A node to check. * @param {string[]} specifiers Array of specified name. * @returns {boolean} `true` if the node is a MemberExpression node which has * the specified name's property */ function isSpecifiedMember(node, specifiers) { return node.type === "MemberExpression" && specifiers.includes(astUtils.getStaticPropertyName(node)); } /** * Reports if the `CallExpression` node has evaluated argument. * @param {ASTNode} node A CallExpression to check. * @returns {void} */ function reportImpliedEvalCallExpression(node) { const [firstArgument] = node.arguments; if (firstArgument) { const staticValue = getStaticValue(firstArgument, context.getScope()); const isStaticString = staticValue && typeof staticValue.value === "string"; const isString = isStaticString || isEvaluatedString(firstArgument); if (isString) { context.report({ node, messageId: "impliedEval" }); } } } /** * Reports calls of `implied eval` via the global references. * @param {Variable} globalVar A global variable to check. * @returns {void} */ function reportImpliedEvalViaGlobal(globalVar) { const { references, name } = globalVar; references.forEach(ref => { const identifier = ref.identifier; let node = identifier.parent; while (isSpecifiedMember(node, [name])) { node = node.parent; } if (isSpecifiedMember(node, EVAL_LIKE_FUNCS)) { const parent = node.parent; if (parent.type === "CallExpression" && parent.callee === node) { reportImpliedEvalCallExpression(parent); } } }); } //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { CallExpression(node) { if (isSpecifiedIdentifier(node.callee, EVAL_LIKE_FUNCS)) { reportImpliedEvalCallExpression(node); } }, "Program:exit"() { const globalScope = context.getScope(); GLOBAL_CANDIDATES .map(candidate => astUtils.getVariableByName(globalScope, candidate)) .filter(globalVar => !!globalVar && globalVar.defs.length === 0) .forEach(reportImpliedEvalViaGlobal); } }; } };
import NodeFunction from '../core/NodeFunction.js'; import NodeFunctionInput from '../core/NodeFunctionInput.js'; const declarationRegexp = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i; const propertiesRegexp = /[a-z_0-9]+/ig; const pragmaMain = '#pragma main'; const parse = ( source ) => { const pragmaMainIndex = source.indexOf( pragmaMain ); const mainCode = pragmaMainIndex !== - 1 ? source.substr( pragmaMainIndex + pragmaMain.length ) : source; const declaration = mainCode.match( declarationRegexp ); if ( declaration !== null && declaration.length === 5 ) { // tokenizer const inputsCode = declaration[ 4 ]; const propsMatches = []; let nameMatch = null; while ( ( nameMatch = propertiesRegexp.exec( inputsCode ) ) !== null ) { propsMatches.push( nameMatch ); } // parser const inputs = []; let i = 0; while ( i < propsMatches.length ) { const isConst = propsMatches[ i ][ 0 ] === 'const'; if ( isConst === true ) { i ++; } let qualifier = propsMatches[ i ][ 0 ]; if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) { i ++; } else { qualifier = ''; } const type = propsMatches[ i ++ ][ 0 ]; let count = Number.parseInt( propsMatches[ i ][ 0 ] ); if ( Number.isNaN( count ) === false ) i ++; else count = null; const name = propsMatches[ i ++ ][ 0 ]; inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) ); } // const blockCode = mainCode.substring( declaration[ 0 ].length ); const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : ''; const type = declaration[ 2 ]; const presicion = declaration[ 1 ] !== undefined ? declaration[ 1 ] : ''; const headerCode = pragmaMainIndex !== - 1 ? source.substr( 0, pragmaMainIndex ) : ''; return { type, inputs, name, presicion, inputsCode, blockCode, headerCode }; } else { throw new Error( 'FunctionNode: Function is not a GLSL code.' ); } }; class GLSLNodeFunction extends NodeFunction { constructor( source ) { const { type, inputs, name, presicion, inputsCode, blockCode, headerCode } = parse( source ); super( type, inputs, name, presicion ); this.inputsCode = inputsCode; this.blockCode = blockCode; this.headerCode = headerCode; } getCode( name = this.name ) { const headerCode = this.headerCode; const presicion = this.presicion; let declarationCode = `${ this.type } ${ name } ( ${ this.inputsCode.trim() } )`; if ( presicion !== '' ) { declarationCode = `${ presicion } ${ declarationCode }`; } return headerCode + declarationCode + this.blockCode; } } export default GLSLNodeFunction;
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var router_1 = require('@angular/router'); var app_service_1 = require("./app-service"); var AppComponent = (function () { function AppComponent(breadCrumbSvc, _router) { this.breadCrumbSvc = breadCrumbSvc; this._router = _router; this.breadCrumbSvc.setBreadCrumb('Project Dashboard'); } AppComponent.prototype.navigateHome = function () { this._router.navigate(['home']); ; }; AppComponent = __decorate([ core_1.Component({ selector: 'ts-app', templateUrl: '/app/app-component.html' }), __metadata('design:paramtypes', [app_service_1.BreadcrumbService, router_1.Router]) ], AppComponent); return AppComponent; }()); exports.AppComponent = AppComponent;
/** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++i < length) { array[i] = source[i]; } return array; } module.exports = arrayCopy;
export default (callback) => { setTimeout(() => { callback(); setTimeout(() => { callback(); }, 3000); }, 3000); }
'use strict' const reduce = Function.bind.call(Function.call, Array.prototype.reduce); const isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable); const concat = Function.bind.call(Function.call, Array.prototype.concat); const keys = Reflect.ownKeys; if (!Object.values) { Object.values = (O) => reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []); } if (!Object.entries) { Object.entries = (O) => reduce(keys(O), (e, k) => concat(e, typeof k === 'string' && isEnumerable(O, k) ? [ [k, O[k]] ] : []), []); } //from //https://medium.com/@_jh3y/throttling-and-debouncing-in-javascript-b01cad5c8edf#.jlqokoxtu //or //https://remysharp.com/2010/07/21/throttling-function-calls function debounce(callback, delay) { let timeout; return function() { const context = this, args = arguments; clearTimeout(timeout); timeout = setTimeout(() => callback.apply(context, args), delay); }; }; function throttle(func, limit) { let inThrottle, lastFunc, throttleTimer; return function() { const context = this, args = arguments; if (inThrottle) { clearTimeout(lastFunc); return lastFunc = setTimeout(function() { func.apply(context, args); inThrottle = false; }, limit); } else { func.apply(context, args); inThrottle = true; return throttleTimer = setTimeout(() => inThrottle = false, limit); } }; }; /*END POLIFILL*/
var htmlparser = require('htmlparser2'); var _ = require('lodash'); var ent = require('ent'); module.exports = sanitizeHtml; function sanitizeHtml(html, options) { var result = ''; if (!options) { options = sanitizeHtml.defaults; } else { _.defaults(options, sanitizeHtml.defaults); } // Tags that contain something other than HTML. If we are not allowing // these tags, we should drop their content too. For other tags you would // drop the tag but keep its content. var nonTextTagsMap = { script: true, style: true }; var allowedTagsMap = {}; _.each(options.allowedTags, function(tag) { allowedTagsMap[tag] = true; }); var selfClosingMap = {}; _.each(options.selfClosing, function(tag) { selfClosingMap[tag] = true; }); var allowedAttributesMap = {}; _.each(options.allowedAttributes, function(attributes, tag) { allowedAttributesMap[tag] = {}; _.each(attributes, function(name) { allowedAttributesMap[tag][name] = true; }); }); var depth = 0; var skipMap = {}; var skipText = false; var parser = new htmlparser.Parser({ onopentag: function(name, attribs) { var skip = false; if (!_.has(allowedTagsMap, name)) { skip = true; if (_.has(nonTextTagsMap, name)) { skipText = true; } skipMap[depth] = true; } depth++; if (skip) { // We want the contents but not this tag return; } result += '<' + name; if (_.has(allowedAttributesMap, name)) { _.each(attribs, function(value, a) { if (_.has(allowedAttributesMap[name], a)) { result += ' ' + a; if ((a === 'href') || (a === 'src')) { if (naughtyHref(value)) { return; } } if (value.length) { // Values are ALREADY escaped, calling escapeHtml here // results in double escapes result += '="' + value + '"'; } } }); } if (_.has(selfClosingMap, name)) { result += " />"; } else { result += ">"; } }, ontext: function(text) { if (skipText) { return; } // It is NOT actually raw text, entities are already escaped. // If we call escapeHtml here we wind up double-escaping. result += text; }, onclosetag: function(name) { skipText = false; depth--; if (skipMap[depth]) { delete skipMap[depth]; return; } if (_.has(selfClosingMap, name)) { // Already output /> return; } result += "</" + name + ">"; } }); parser.write(html); parser.end(); return result; function escapeHtml(s) { if (s === 'undefined') { s = ''; } if (typeof(s) !== 'string') { s = s + ''; } return s.replace(/\&/g, '&amp;').replace(/</g, '&lt;').replace(/\>/g, '&gt;').replace(/\"/g, '&quot;'); } function naughtyHref(href) { // So we don't get faked out by a hex or decimal escaped javascript URL #1 href = ent.decode(href); // Browsers ignore character codes of 32 (space) and below in a surprising // number of situations. Start reading here: // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab href = href.replace(/[\x00-\x20]+/, ''); // Case insensitive so we don't get faked out by JAVASCRIPT #1 var matches = href.match(/^([a-zA-Z]+)\:/); if (!matches) { // No scheme = no way to inject js (right?) return false; } var scheme = matches[1].toLowerCase(); return (!_.contains(['http', 'https', 'ftp', 'mailto' ], scheme)); } } // Defaults are accessible to you so that you can use them as a starting point // programmatically if you wish sanitizeHtml.defaults = { allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div', 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ], allowedAttributes: { a: [ 'href', 'name', 'target' ], // We don't currently allow img itself by default, but this // would make sense if we did img: [ 'src' ] }, // Lots of these won't come up by default because we don't allow them selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ] };
(function(){ 'use strict' angular .module("jobDetail") .service("jobDetailService",jobDetailService); jobDetailService.$inject = ['apiService','apiOptions']; function jobDetailService(apiService,apiOptions) { var jobId; this.getJobDetail=function(jobId) { // return "ok"; return apiService.get("job/"+jobId); }; }; })();
var STATE_START = 0; var STATE_END = 1; var STATE_GROUND = 2; var STATE_FOREST = 3; var STATE_WATER = 4; function Cell(col, row) { this.col = col; this.row = row; this.state = STATE_GROUND; } Cell.prototype.draw = function() { stroke(66); switch (this.state) { case STATE_START: Color.Material.light_green[5].fill(); break; case STATE_END: Color.Material.red[5].fill(); break; case STATE_GROUND: Color.Material.green[5].fill(); break; case STATE_FOREST: Color.Material.green[9].fill(); break; case STATE_WATER: Color.Material.light_blue[5].fill(); break; default: fill(255, 0, 0); } rect(this.col * scl, this.row * scl, scl, scl); }; Cell.prototype.incrementState = function(bool) { if (bool) { // Cycle from 0 to 1 this.state = (++this.state > 1) ? 0 : this.state; } else { // Cycle from 2 to 4 this.state = (++this.state < 2 || this.state > 4) ? 2 : this.state; } //this.state = (++this.state > 4) ? 0 : this.state; //loop(); };
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('baApp.services', []). value('version', '0.1');
/* Noble cread UART service example This example uses Sandeep Mistry's noble library for node.js to read and write from Bluetooth LE characteristics. It looks for a UART characteristic based on a proprietary UART service by Nordic Semiconductor. You can see this service implemented in Adafruit's BLEFriend library. created 30 Nov 2015 by Tom Igoe */ var noble = require('noble'); //noble library var util = require('util'); // utilities library // make an instance of the eventEmitter library: var EventEmitter = require('events').EventEmitter; // constructor function, so you can call new BleUart(): var BleUart = function (uuid) { var service = '6e400001b5a3f393e0a9e50e24dcca9e'; // the service you want var receive, transmit; // transmit and receive BLE characteristics var self = this; // reference to the instance of BleUart self.connected = false; // whether the remote peripheral's connected self.peripheral; // the remote peripheral as an object EventEmitter.call(self); // make a copy of EventEmitter so you can emit events if (uuid) { // if the constructor was called with a different UUID, service = uuid; // then set that as the service to search for } // The scanning function: function scan(state) { if (state === 'poweredOn') { // if the radio's on, scan for this service noble.startScanning([service], false); } // emit a 'scanning' event: self.emit('scanning', state); } // the connect function: self.connect = function(peripheral) { self.peripheral = peripheral; peripheral.connect(); // start connection attempts // the connect function. This is local to the discovery function // because it needs to know the peripheral to discover services: function discover() { // once you know you have a peripheral with the desired // service, you can stop scanning for others: noble.stopScanning(); // get the service you want on this peripheral: peripheral.discoverServices([service],explore); } // called only when the peripheral has the service you're looking for: peripheral.on('connect', discover); // when a peripheral disconnects, run disconnect: peripheral.on('disconnect', self.disconnect); } // the services and characteristics exploration function: // once you're connected, this gets run: function explore(error, services) { // this gets run by the for-loop at the end of the // explore function, below: function getCharacteristics(error, characteristics) { for (var c in characteristics) { // loop over the characteristics if (characteristics[c].notify) { // if one has the notify property receive = characteristics[c]; // then it's the receive characteristic receive.notify(true); // turn on notifications // whenever a notify event happens, get the result. // this handles repeated notifications: receive.on('data', function(data, notification) { if (notification) { // if you got a notification self.emit('data', String(data)); // emit a data event } }); } if (characteristics[c].write) { // if a characteristic has a write property transmit = characteristics[c]; // then it's the transmit characteristic } } // end of getCharacteristics() // if you've got a valid transmit and receive characteristic, // then you're truly connected. Emit a connected event: if (transmit && receive) { self.connected = true; self.emit('connected', self.connected); } } // iterate over the services discovered. If one matches // the UART service, look for its characteristics: for (var s in services) { if (services[s].uuid === service) { services[s].discoverCharacteristics([], getCharacteristics); return; } } } // the BLE write function. If there's a valid transmit characteristic, /// then write data out to it as a Buffer: self.write = function(data) { if (transmit) { transmit.write(new Buffer(data)); } } // the BLE disconnect function: self.disconnect = function() { self.connected = false; } // when the radio turns on, start scanning: noble.on('stateChange', scan); // if you discover a peripheral with the appropriate service, connect: noble.on('discover', self.connect); } util.inherits(BleUart, EventEmitter); // BleUart inherits all the EventEmitter properties module.exports = BleUart; // export BleUart
var db = require('mongoose'); var Log = require('log'), log = new Log('info'); var clienttracking = require('./clienttracking.js'); var mapreduce = require('./mapreduce.js'); var io = null; exports.server = require('./adnoceserver.js'); exports.setDatabase = function(databaseConfiguration, callback) { var port = databaseConfiguration.port || '27017'; var opts = databaseConfiguration.options || {}; db.connect('mongodb://'+databaseConfiguration.host+':'+port+'/'+databaseConfiguration.name, opts, function(){ log.info('adnoce core - creating database connection to "%s" on host "%s:%s", status: %s', databaseConfiguration.name, databaseConfiguration.host, port, db.connection.readyState); if (db.connection.readyState != 1) { log.error('adnoce core - database connection not ready yet'); } if (typeof(callback) === 'function') callback(db); }); } exports.setServerSocketIO = function(io_, path_) { var path = path_ || '/adnoce'; io = io_.of(path).authorization(function (handshakeData, callback) { // @TODO: auth (e.g. ip-based on handshakeData.address) callback(null, true); }).on('connection', socketConnection); clienttracking.setSocketIO(io); } var socketConnection = function(socket_) { log.info('adnoce core - server socket client "%s" connected to endpoint "%s"', socket_.handshake.address.address, socket_.flags.endpoint); } exports.clientTrackingScript = function(req, res) { res.set({'Content-Type': 'application/javascript', 'Cache-Control': 'no-cache'}); res.send(200, clienttracking.getClientTrackingScript(req)); var additionalData = req.adnoceData || {}; additionalData.adnocetype = 1; clienttracking.processRequest(req, additionalData); }; exports.clientTrackingScriptUpdate = function(req, res) { res.set({'Content-Type': 'text/plain', 'Cache-Control': 'no-cache'}); if (!req.param('p')) res.send(400, '0'); else { res.send(200, '1'); var additionalData = req.adnoceData || {}; if (req.param('t')) additionalData.adnocetype = req.param('t'); clienttracking.updateSessionData(req.sessionID, req.param('p'), additionalData); } }; exports.addEvent = function(type, name, sessionId, additionalData) { clienttracking.addEvent(type, name, sessionId, additionalData); }; exports.MapReduce = mapreduce.MapReduce; var pushServerHealth = function(serverOSObject) { io.emit('health', {uptime: serverOSObject.uptime(), load: serverOSObject.loadavg(), memory: {total: serverOSObject.totalmem(), free: serverOSObject.freemem()}}); } exports.pushServerHealth = pushServerHealth;
// Karma configuration file, see link for more information // https://karma-runner.github.io/1.0/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['jasmine', '@angular-devkit/build-angular'], plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-spec-reporter', '@angular-devkit/build-angular/plugins/karma', ], client: { clearContext: false // leave Jasmine Spec Runner output visible in browser }, reporters: ['spec'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
'use strict'; const util = require('util'); const colors = require('colors/safe'); Object.entries({ info: colors.blue, warn: colors.yellow, error: colors.red }).map(([method, color]) => { const _ = global.console[method]; global.console[method] = (...args) => { if (args.length) { let msg = args.shift(); if ('string' == typeof msg) { msg = color(msg); } args.unshift(msg); } _(...args); }; });
require.ensure([], function(require) { require("./73.async.js"); require("./147.async.js"); require("./294.async.js"); require("./588.async.js"); }); module.exports = 589;
<rtl code> var m = function (){ function T(){ this.a = []; } var r = new T(); var a = RTL$.makeArray(3, 0); var dynamicInt = []; var dynamicString = []; var dynamicChar = []; var dynamicByte = []; var dynamicRecord = []; var dynamicArrayOfStaticArrayInt = []; var i = 0; var s = ''; var byte = 0; function assignDynamicArrayFromStatic(){ var static$ = RTL$.makeArray(3, 0); var dynamic = []; Array.prototype.splice.apply(dynamic, [0, Number.MAX_VALUE].concat(static$)); } function returnOuterArray(){ return a.slice(); } function passArrayBeRef(a/*VAR ARRAY * OF INTEGER*/){ var static$ = RTL$.makeArray(3, 0); a[0] = 1; a[0] = a[1]; Array.prototype.splice.apply(a, [0, Number.MAX_VALUE].concat(static$)); Array.prototype.splice.apply(a, [0, Number.MAX_VALUE].concat(dynamicInt)); } function passArrayOfRecordsByRef(a/*VAR ARRAY * OF T*/){ var result = []; RTL$.copy(result, a, {array: {record: {a: {array: null}}}}); } function passArrayOfArraysByRef(a/*VAR ARRAY *, 3 OF INTEGER*/){ var result = []; RTL$.copy(result, a, {array: {array: null}}); } function arrayOfRecords(){ var $scope1 = $scope + ".arrayOfRecords"; function T(){ } var a = []; a.push(new T()); } function arrayOfArrays(){ var aa = []; function f(){ var a = []; return a; } aa.push(f()); } function optimizeTemporartArrayReturn(){ function f(){ var a = []; return a; } return f(); } function optimizeLocalArrayReturn(){ var a = []; return a; } function optimizeLocalArrayReturnWhenStatic(){ var a = RTL$.makeArray(3, 0); return a; } function cannotOptimizeArgArrayReturn(a/*ARRAY OF INTEGER*/){ return a.slice(); } function cannotOptimizeVarArgArrayReturn(a/*VAR ARRAY OF INTEGER*/){ return a.slice(); } function cannotOptimizeVarArgDynamicArrayReturn(a/*VAR ARRAY * OF INTEGER*/){ return a.slice(); } function arrayOfMaps(){ var aa = []; function f(){ var a = {}; return a; } aa.push(f()); } dynamicInt.push(3); dynamicInt.push(i); dynamicInt.push(byte); dynamicString.push("abc"); dynamicString.push("\""); dynamicString.push(s); dynamicChar.push(34); dynamicByte.push(byte); dynamicByte.push(i & 0xFF); dynamicRecord.push(RTL$.clone(r, {record: {a: {array: null}}}, T)); dynamicArrayOfStaticArrayInt.push(a.slice()); RTL$.assert(dynamicInt.indexOf(i) != -1); RTL$.assert(dynamicChar.indexOf(34) != -1); dynamicInt.splice(i, 1); dynamicInt.splice(0, Number.MAX_VALUE); passArrayBeRef(dynamicInt); passArrayOfRecordsByRef(dynamicRecord); passArrayOfArraysByRef(dynamicArrayOfStaticArrayInt); }();
var expect = require('chai').expect; var assert = require('chai').assert; var sinon = require('sinon'); var Config = require('../lib/config'); describe('config', function() { describe('#constructor', function() { it('creates a new object with the config defaults', function() { sinon.spy(Config.prototype, 'set'); var options = {}; var config = new Config(options); assert(Config.prototype.set.calledWith(options)); Config.prototype.set.restore(); }); it('call .set with any passed options', function() { var config = new Config(); expect(config.source).to.equal('.'); expect(config.destination).to.equal('_site'); }); }); describe('#set', function() { it('merges the passed options with the config defaults', function() { var config = new Config(); config.set({ source: './foo', destination: './bar', fizz: 'buzz' }); expect(config.source).to.equal('./foo'); expect(config.destination).to.equal('./bar'); // a default expect(config.env).to.equal('production'); // a new value expect(config.fizz).to.equal('buzz'); }); it('always includes certain default, even if overridden', function() { var config = new Config(); config.set({ excludeFiles: ['foo'], watchExcludes: ['bar'] }); expect(config.excludeFiles).to.deep.equal([ 'foo', '.*', '_*', '_*/**/*', 'package.json', 'bower_components', 'node_modules' ]); expect(config.watchExcludes).to.deep.equal([ 'bar', 'node_modules', config.destination ]); }); }); });
import Vue from 'vue'; import VueForm from 'vue-form'; Vue.use(VueForm, { validators: { 'step': function(value, stepValue) { return stepValue === `any` || Number(value) % Number(stepValue) === 0; }, 'data-exclusive-minimum': function(value, exclusiveMinimum) { return Number(value) > Number(exclusiveMinimum); }, 'data-exclusive-maximum': function(value, exclusiveMaximum) { return Number(value) < Number(exclusiveMaximum); }, 'complete-range': function(range) { return range === null || (range[0] !== null && range[1] !== null); }, 'valid-range': function(range) { if (range === null) { // allowed range return true; } if (range[0] === null || range[1] === null) { // let complete-range validator handle this return true; } if (Number.isNaN(range[0]) || Number.isNaN(range[1])) { // let number validator handle this return true; } return range[0] <= range[1]; }, 'categories-not-empty': function(categories) { return categories.length > 0; }, 'complete-dimensions': function(dimensions) { return dimensions === null || (dimensions[0] !== null && dimensions[1] !== null && dimensions[2] !== null); }, 'start-with-uppercase-or-number': function(value) { return /^[\dA-Z]/.test(value); }, 'no-mode-name': function(value) { return !/\bmode\b/i.test(value); }, 'no-fine-channel-name': function(value) { if (/\bfine\b|\d+[\s_-]*bit/i.test(value)) { return false; } return !/\bLSB\b|\bMSB\b/.test(value); }, 'entity-complete': function(value, attributeValue, vnode) { const component = vnode.componentInstance; if (component.hasNumber) { return component.selectedNumber !== `` && component.selectedNumber !== null; } return true; }, 'entities-have-same-units': function(value, attributeValue, vnode) { return vnode.componentInstance.hasSameUnit; }, 'valid-color-hex-list': function(value) { return /^\s*#[\da-f]{6}(?:\s*,\s*#[\da-f]{6})*\s*$/i.test(value); }, 'max-file-size': function(file, attributeValue) { if (typeof file === `object`) { let maxSize = Number.parseInt(attributeValue, 10); if (attributeValue.includes(`M`)) { maxSize *= 1000 * 1000; } else if (attributeValue.includes(`k`)) { maxSize *= 1000; } return file.size <= maxSize; } return true; }, }, });
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M20 15H4c-.55 0-1 .45-1 1s.45 1 1 1h16c.55 0 1-.45 1-1s-.45-1-1-1zm0-5H4c-.55 0-1 .45-1 1v1c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-1c0-.55-.45-1-1-1zm0-6H4c-.55 0-1 .45-1 1v2c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm.5 15h-17c-.28 0-.5.22-.5.5s.22.5.5.5h17c.28 0 .5-.22.5-.5s-.22-.5-.5-.5z" }), 'LineWeightRounded');
import {normalize, resolve} from "path"; import {existsSync, readFileSync} from "fs"; import {sys, ScriptSnapshot, resolveModuleName, getDefaultLibFilePath} from "typescript"; export function createServiceHost(options, filenames, cwd) { const normalizePath = (path) => resolve(normalize(path)); const moduleResolutionHost = createModuleResolutionHost(); const files = {}; // normalized filename => {version, snap, text} filenames.forEach(filename => files[normalizePath(filename)] = null); return { getDirectories: sys.getDirectories, directoryExists: sys.directoryExists, readDirectory: sys.readDirectory, getDefaultLibFileName: getDefaultLibFilePath, fileExists(filename) { filename = normalizePath(filename); return filename in files || sys.fileExists(filename); }, readFile(filename) { return readFileSync(normalizePath(filename), "utf-8"); }, getCompilationSettings() { return options; }, getCurrentDirectory() { return cwd; }, getScriptFileNames() { return Object.keys(files); }, getScriptVersion(filename) { const f = files[normalizePath(filename)]; return f ? f.version.toString() : ""; }, getScriptSnapshot(filename) { let f = files[normalizePath(filename)]; if(!f) { f = this.addFile(filename, this.readFile(filename)); } return f.snap; }, resolveModuleNames(moduleNames, containingFile) { return moduleNames.map(name => this.resolveModuleName(name, containingFile)); }, getNewLine() { return options.newLine || sys.newLine; }, // additional methods containsFile(filename) { return normalizePath(filename) in files; }, resolveModuleName(moduleName, containingFile) { const {resolvedModule} = resolveModuleName(moduleName, containingFile, options, moduleResolutionHost); if(resolvedModule) { resolvedModule.resolvedFileName = normalizePath(resolvedModule.resolvedFileName); resolvedModule.originalFileName = resolvedModule.resolvedFileName; } return resolvedModule; }, addFile(filename, text) { filename = normalizePath(filename); const snap = ScriptSnapshot.fromString(text); snap.getChangeRange = () => {}; let file = files[filename]; if(!file) { file = {version: 0}; files[filename] = file; } ++file.version; file.snap = snap; file.text = text; return file; }, }; } function createModuleResolutionHost() { return { fileExists(filename) { return existsSync(filename); }, readFile(filename) { return readFileSync(filename, "utf-8") }, }; }
import path from 'path'; import {runScheduler} from './scheduler'; import logger from '../util/logger'; import dotenv from 'dotenv'; import {loadConfig} from '../../config'; import {initQueue} from './pipeline.queue'; logger.info(" _____ _ _ _ _ _ _ _ _ "); logger.info("| | |_|___| | | |_| |_|_|"); logger.info("| --| | | | | | | | '_| |"); logger.info("|_____|_|_|_|_|_____|_|_,_|_|"); logger.info('ClinWiki data pipeline starting...'); const envPath = path.resolve(process.cwd()+'/../', '.env'); logger.info('Loading .env from '+envPath); dotenv.config({ path: envPath }); loadConfig(); logger.info('Initializing pipeline queue'); initQueue(); logger.info('Running...'); runScheduler();
define(['backbone', 'marionette', 'mustache', 'jquery', 'text!templates/ctrldialog.html'], function(Backbone, Marionette, Mustache, $, template) { return Marionette.ItemView.extend({ initialize: function(options) { if (!options.icon_name) { options.icon_name = 'bird'; } this.model = new Backbone.Model( options ); this.render(); }, template: function(serialized_model) { return Mustache.render(template, serialized_model); }, ui: { 'ok': '.btn-ok', 'cancel': '.btn-cancel', 'dialog': '.dialog', 'close': '.dialog-close' }, events: { 'tap @ui.ok': 'onOk', 'tap @ui.cancel': 'onCancel', 'tap @ui.close': 'onCancel' }, onOk: function(ev) { this.trigger('ok'); this.destroy(); }, onCancel: function(ev) { this.trigger('cancel'); this.destroy(); }, onRender: function() { $('body').append(this.$el); this.ui.dialog.css({ 'marginTop': 0 - this.ui.dialog.height()/2 }); this.ui.dialog.addClass('bounceInDown animated'); }, onDestory: function() { this.$el.remove(); this.model.destroy(); }, className: 'dialogContainer' }); });
import { InvalidArgumentError } from '../errors/InvalidArgumentError'; import { NotImplementedError } from '../errors/NotImplementedError'; import mustache from 'mustache'; import '../utils/Function'; // The base class for a control export class Control { // The constructor of a control // id: The id of the control // template: The template used for rendering the control // localCSS: An object whose properties are CSS class names and whose values are the localized CSS class names // The control will change the matching CSS class names in the templates. constructor(id, template, localCSS) { if (typeof id !== 'string' || !isNaN(id)) { throw new InvalidArgumentError('Cannot create the control because the id is not a string'); } if (id.length < 1) { throw new InvalidArgumentError('Cannot create the control because the id is not a non-empty string'); } if (null === template || undefined === template) { throw new InvalidArgumentError('Cannot create the control because the template cannot be null or undefined'); } if (typeof template !== 'string') { throw new InvalidArgumentError('Cannot create the control because the template is not a string'); } this.id = id; this.template = template; if (template && localCSS) { // localize the CSS class names in the templates for (const oCN in localCSS) { const nCN = localCSS[oCN]; this.template = this.template .replace(new RegExp(`class="${oCN}"`, 'gi'), `class="${nCN}"`) .replace(new RegExp(`class='${oCN}'`, 'gi'), `class='${nCN}'`); } } this.controls = {}; } // Adds a child control to the control // control: The Control instance addControl(control) { if (!(control instanceof Control)) { throw new InvalidArgumentError('Cannot add sub-control because it is invalid'); } this.controls[control.id] = control; } // Removes a child control from the control // val: Either a controlId or a Control instance removeControl(val) { if (val instanceof Control) { delete this.controls[val.id]; } else { delete this.controls[val]; } } // Renders the control (and all its contained controls) // data: The object that contains the data to substitute into the template // eventObj: Event related data for the event that caused the control to render render(data, eventObj) { if (this.controls) { const controlData = {}; for (let controlId in this.controls) { const control = this.controls[controlId]; controlData[control.constructor.getConstructorName()] = {}; controlData[control.constructor.getConstructorName()][control.id] = control.render(data, eventObj); } for (let key in controlData) { data[key] = controlData[key]; } } return mustache.render(this.template, data); } // This method is invoked so the control can bind events after the DOM has been updated // domContainerElement: The DOM container element into which the control was rendered // eventObj: Event related data for the event that caused the control to render onDOMUpdated(domContainerElement, eventObj) { if (this.onDOMUpdatedNotification) { this.onDOMUpdatedNotification(domContainerElement, eventObj); } if (this.controls) { for (let controlId in this.controls) { const control = this.controls[controlId]; control.onDOMUpdated(domContainerElement, eventObj); } } } // The Control classes that extend this type can add custom logic here to be executed after the domContainerElement // has been updated // domContainerElement: The DOM container element into which the control was rendered // eventObj: Event related data for the event that caused the control to render onDOMUpdatedNotification(domContainerElement, eventObj) { } };
'use strict'; /* jasmine specs for filters go here */ describe('filter', function() { });
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; var util = require('util'); var session = require('express-session'); var passport = require('passport'); module.exports = (app, url, appEnv, User) => { app.use(session({ secret: process.env.SESSION_SECRET, name: 'freelancalot', proxy: true, resave: true, saveUninitialized: true })); app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser((user, done) => { var id = user.get('id'); console.log('serializeUser: ' + id) done(null, id); }); passport.deserializeUser((id, done) => { User.findById(id).then((user) => { done(null, user); }) }); var googleOAuth = appEnv.getService('googleOAuth'), googleOAuthCreds = googleOAuth.credentials; passport.use(new GoogleStrategy({ clientID: googleOAuthCreds.clientID, clientSecret: googleOAuthCreds.clientSecret, callbackURL: util.format("http://%s%s", url, googleOAuthCreds.callbackPath) }, (token, refreshToken, profile, done) => { process.nextTick(() => { User.findOrCreate({ where: { googleId: profile.id }, defaults: { name: profile.displayName, email: profile.emails[0].value, photo: profile.photos[0].value } }) .spread((user, created) => { done(null, user); }) }); })); app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] })); app.get('/auth/google/callback', passport.authenticate('google', { successRedirect: '/' })); app.get('/logout', (req, res) => { req.logout(); res.redirect('/'); }); }
const path = require('path'); const express = require('express'); const bodyParser = require('body-parser'); const auth = require('http-auth'); // const basicAuth = require('basic-auth-connect'); const apiHandler = require('./api-handler') /** * Installs routes that serve production-bundled client-side assets. * It is set up to allow for HTML5 mode routing (404 -> /dist/index.html). * This should be the last router in your express server's chain. */ console.log('running node-app-server.js'); module.exports = (app) => { const distPath = path.join(__dirname, '../dist'); const indexFileName = 'index.html'; console.log('Setting up Express'); console.log(' distPath=%s',distPath); console.log(' indexFileName=%s',indexFileName); // configure app to use bodyParser() // this will let us get the data from a POST // app.use(bodyParser.urlencoded({ extended: true })); // app.use(bodyParser.json()); // basic authentication. not production-ready // TODO: add more robust authentication after POC console.log ("__dirname = " + __dirname); var basic = auth.basic({ realm: "Project NLS.", file: __dirname + "/users.htpasswd" // username === "nielsen" && password === "W@ts0n16" } ); app.use( auth.connect(basic)); // var router = express.Router(); // middleware to use for all requests app.use(function(req, res, next) { // do logging console.log('Router request %s',req.url); next(); // make sure we go to the next routes and don't stop here }); // app.get() app.get(/localapi\/.*$/, (req, res) => apiHandler(req, res) ); app.post(/localapi\/.*$/, (req, res) => apiHandler(req, res) ); // note: this regex exludes API app.use( express.static(distPath)); app.get('*', (req, res) =>res.sendFile(path.join(distPath, indexFileName)));; }