code
stringlengths
2
1.05M
import mongoose from 'mongoose' const BookSchema = new mongoose.Schema({ isbn: String, title: String, author: String, description: String, published_date: { type: Date }, publisher: String, updated_date: { type: Date, default: Date.now } }) export default mongoose.model('Book', BookSchema)
var path = require('path'); var util = require('util'); var autoprefixer = require('autoprefixer'); var pkg = require('../package.json'); var loaders = require('./loaders'); var plugins = require('./plugins'); var DEBUG = process.env.NODE_ENV === 'development'; var TEST = process.env.NODE_ENV === 'test'; var jsBundle = util.format('[name]/app.%s.js', pkg.version); var entry = { simple: ['./simple/js/App.jsx'], // material: ['./material/js/App.jsx'], // reveal: ['./reveal/js/App.jsx'], }; if (DEBUG) { Object.keys(entry).forEach(app => { entry[app].push( util.format( 'webpack-dev-server/client?http://%s:%d', pkg.config.devHost, pkg.config.devPort ) ); entry[app].push('webpack/hot/dev-server'); }); } var config = { context: path.join(__dirname, '../examples'), cache: DEBUG, debug: DEBUG, target: 'web', devtool: DEBUG || TEST ? 'inline-source-map' : false, entry: entry, output: { path: path.resolve(pkg.config.buildDir), publicPath: '/', filename: jsBundle, pathinfo: false }, module: { loaders: loaders }, postcss: [ autoprefixer ], plugins: plugins, resolve: { extensions: ['', '.js', '.json', '.jsx'] }, devServer: { contentBase: path.resolve(pkg.config.buildDir), headers: { "Access-Control-Allow-Origin": "*" }, hot: true, noInfo: false, inline: true, stats: { colors: true } } }; module.exports = config;
// @flow strict import React from 'react'; import Utterances from '../Utterances'; import { useSiteMetadata } from '../../../hooks'; const Comments = () => { const { utterances } = useSiteMetadata(); if (!utterances) { return null; } return ( <Utterances utterances={utterances} /> ); }; export default Comments;
import test from 'ava' import {PreErrors} from './Pre' import Pre from './Pre' test(t => { t.deepEqual(new Pre().analyse(),{t:undefined, e:[PreErrors.MISSING_BASE]}) t.deepEqual(new Pre({}).analyse(),{t:undefined, e:[PreErrors.MISSING_BASE]}) t.deepEqual(new Pre('in').analyse(),{t:'in', e:[]}) t.deepEqual(new Pre({base:'in'}).analyse(),{t:'in', e:[]}) })
(function () { "use strict"; var StateExt = Class.extend({ excludeNextStateChangeFromHistory: false, targetParams: null, targetState: null, $injector: null, $location: null, $state: null, session: null, history: [], initialize: function ($cookieStore, $http, $injector, $location, $state, authorizationContextResolver) { this.$injector = $injector; this.$location = $location; this.$state = $state; this.session = $injector.get('session'); }, authorizeAndNavigate: function (authorization, sessionTimeoutSeconds, byReferenceId) { this.session.authorize(authorization, sessionTimeoutSeconds, byReferenceId); if (this.targetState == null) { this.$location.path('/home/index'); } else { this.$state.transitionTo(this.targetState, this.targetParams); this.targetState = null; this.targetParams = null; } }, back: function (state, params) { this.excludeNextStateChangeFromHistory = true; if (this.history.length < 1) { if (state == null) { this.$injector.get('$window').history.back(); } else { this.$state.go(state, params); } return; } var to = this.history.pop(); this.$state.go(to.state, to.params); }, onStateChangeStart: function (event, toState, toParams, fromState, fromParams) { if (event.defaultPrevented) { return; } var requiresAuthorization = toState.data == null ? false : toState.data.secure; if (requiresAuthorization && !this.session.isAuthorized()) { this.targetState = toState; this.targetParams = toParams; this.$location.path('/login'); event.preventDefault(); } else { // this.$injector.get('$rootScope').pageReady = false; } }, onStateChangeSuccess: function (event, toState, toParams, fromState, fromParams) { var historyMode = fromState.data == null ? "" : fromState.data.history; if (fromState.abstract || historyMode == 'exclude' || this.excludeNextStateChangeFromHistory) { this.excludeNextStateChangeFromHistory = false; return; } if (historyMode == 'reset') { this.history = []; } this.history.push({ state: fromState, params: fromParams }); } }); angular.module('stx.core') .provider('stateExt', Class.extend({ instance: new StateExt(), $get: ['$cookieStore', '$http', '$injector', '$location', '$state', 'authorizationContextResolver', function ($cookieStore, $http, $injector, $location, $state, authorizationContextResolver) { this.instance.initialize($cookieStore, $http, $injector, $location, $state, authorizationContextResolver); return this.instance; } ] })) ; }());
require('styles/paper-theme.css'); require('styles/App.css'); import React from 'react'; import { TestComponent, Header, CurrentlyPlayingComponent, Navigation, Menu } from './index'; import _ from 'lodash'; import { Grid, Row, Col, Button, Glyphicon } from 'react-bootstrap'; class AppComponent extends React.Component { constructor(...args) { super(...args); console.log('[AppComponent] constructor: ', ...args); } render() { return ( <div> <Navigation/> <div className="main-content"> {this.props.children} </div> </div> ); } } AppComponent.defaultProps = {}; export default AppComponent;
export { select } from 'd3-selection' export { geoPath, geoMercator } from 'd3-geo'
var _ = require("underscore"); var r = require('../db'); module.exports = function(apiRoutes){ var model='settings' apiRoutes .get ("/settings", function(request, response){ return r.table(model) .orderBy(r.desc('createdAt')) .coerceTo('array') .run(r.conn) .then(function (result) { return response.status(200).json(result); }).error(handleError(response)); }) .get ("/settings/getItem", function(request, response){ var id = request.query.id; var key = request.query._key; return r.table(model) .filter( r.row(key).eq(id) ) .coerceTo('array') .run(r.conn) .then(function (result) { return response.status(200).json(result); }).error(handleError(response)); }) .post ("/settings", function(request, response){ var objRequest = request.body; objRequest.createdAt = r.now(); return r.table(model) .insert(objRequest) .run(r.conn) .then(function(result){ response .status(200) .json({results: result}); }) .error(handleError(response)); }) .put ("/settings", function(request, response){ var objRequest = request.body; return r.table(model) .filter( r.row(objRequest._key).eq(objRequest[objRequest._key]) ) .update(objRequest) .run(r.conn) .then(function (result) { response .status(200) .json({results: result}); }).error(handleError(response)); }) .delete ("/settings/:id", function(request, response){ var id = request.params.id; return r.table(model) .get(id) .delete() .run(r.conn) .then(function() { response.status(200).json({ result:{ msg:'Remove complate' } }) }).error(handleError(response)); }); function handleError(res) { return function(error) { return res.status(500).json({error: error.message}); } } };
var helper=require("./test-helper.js"),Stream=require("..").WritableStream,fs=require("fs"),path=require("path");helper.mochaTest("Stream",__dirname,function(e,t){var n=path.join(__dirname,"Documents",e.file);fs.createReadStream(n).pipe(new Stream(helper.getEventCollector(function(r,i){t(r,i);var s=helper.getEventCollector(t),o=new Stream(s,e.options);fs.readFile(n,function(e,t){if(e)throw e;o.end(t)})}),e.options)).on("error",t)});
var colors = ["#FF6384", "#4BC0C0", "#FFCE56", "#E7E9ED", "#36A2EB", "#F38630", "#E0E4CC", "#69D2E7", "#F7464A", "#E2EAE9", "#D4CCC5", "#949FB1", "#4D5360"]; function getChartColors(len) { if (len >= colors.length) { return colors; } return colors.slice(0, len); } function getChartColor(i) { if (i >= colors.length) { return colors[i % colors.length]; } return colors[i]; } function getChartColors2(len) { if (len >= colors.length) { var newColor = new Array(); for (var i = 0; i < len; i++) { newColor[i] = getChartColor(i); } return newColor; } return colors; }
// suites/camelize require('../../../lib/node/monad'); var camelize = define.camelize; var assert = require('assert'); /* TESTS START HERE */ suite('camelize'); test('exists', function () { assert(typeof camelize == 'function'); }); test('path/to/file', function () { assert(camelize('path/to/file') === 'file'); }); test('path/to/some-file', function () { assert(camelize('path/to/some-module') === 'someModule'); }); test('path/to/some-other-module', function () { assert(camelize('path/to/some-other-module') === 'someOtherModule'); }); test('path/to/dot.name.ext', function () { assert(camelize('path/to/dot.name.ext') === 'dotName'); }); test('path/to/ WHITE SPACE ', function () { assert(camelize('path/to/ WHITE SPACE ') === 'WHITESPACE'); }); test('replace windows backslash with *nix forslash', function () { assert(camelize(__filename) === 'camelize'); }); suite('does not camelize'); test('path/to/under_score', function () { assert(camelize('path/to/under_score') === 'under_score'); }); test('path/to/this', function () { assert(camelize('path/to/this') === 'this'); }); test('path/to/undefined', function () { assert(camelize('path/to/undefined') === 'undefined'); }); test('path/to/null', function () { assert(camelize('path/to/null') === 'null'); }); test('path/to/""', function () { assert(camelize('path/to/""') === '""'); }); test('path/to/0', function () { assert(camelize('path/to/0') === '0'); }); test('path/to/""', function () { assert(camelize('path/to/-1') === '-1'); }); test('path/to/true', function () { assert(camelize('path/to/true') === 'true'); }); test('path/to/false', function () { assert(camelize('path/to/false') === 'false'); });
'use strict'; import Camera from './camera'; import Recognizer from './recognizer'; import Authenticator from './authenticator'; import Gate from './gate'; export default () => { const camera = new Camera; const recognizer = new Recognizer; const gate = new Gate; const authenticator = new Authenticator; camera.on('image', image => recognizer.enqueue(image)); recognizer .on('plates', (plates) => { authenticator .check(plates) .then(() => gate.open()); }) .start(); camera.start(); };
exports.levelText = { // __for developement__ // 1: [ "ab", "cd", "ef", "gh"], // 2: [ "ij", "kl", "mn", "op"], // 3: [ "qr", "st", "uv", "wx"], // 4: [ "yz", "ba", "dc", "fe"], // 5: [ "ji", "lk", "vn", "kd"], // 6: [ "ha", "uh", "mq", "yb"] //__actual challenge texts__ 1: ["ene ite nee inet one ene ite etee tent at", "eat anne tea oat tea oat neat tea oat ina", "too toon too enot not enot not anot enota", "reat ran arrai errit aar tarie erren airo"], 2: ["asdir lne ndarh ardlo rleit iehn ecnt rth", "das ohds tdlo ocd irtd ascio set toln cde", "hao asr hresd tlera sah hdc deal ictea sn", "ither htd eihar cih tilsn orcse dliah tli"], 3: ["yug ltyrn ydlf lnm sen lys mwoy lhd cwlfu", "mtyhs glhmu fuwc hong secol olgw iua ghle", "hias mci dlyat mcg ahn hfa asmhf dal gumc", "ywio nho ewas mar fle mroew frey ahsd cwo"], 4: ["uenf svgme tcdfl agkuy hsp juf yel ynm nix", "ewiut hwtpm tdhjv vymn djkgo gjpc cymwv cj", "vdrd irmof rkn uvpxk ltdy vfin jikgu joh m", "dni kwu ncroi ehjxs dpek tsd vwldj kxd ntw"], 5: ["vel aut pariatur maxime reprehenderit amet", "repellendus et asperiores illo itaque quis", "facere quisquam officia et labore voluptas", "magnam iste architecto reprehenderit rerum"], 6: ["the quick brown fox jumps over the lazy dog", "woven silk pyjamas exchanged for blue quartz", "brawny gods flocked up to quiz and vex him", "waxy and quivering, jocks fumble the pizza", "quilt frenzy jackdaws gave them best pox"] };
// *- SKIP function a$def() { eff(1) + eff(2); } M.option({ expr: "seq" }); function a$seq() { eff(1) + eff(2); }
/** * Created by gaurangdave on 9/15/16. */ module.exports = function (grunt, options) { var utils = require("./utils"); return { "lazyload": { "src": "package.json", "dest": utils.getTmpFolder() + "modules/" }, "update":{ "src": "package.json", "dest": "." } } };
$(document).ready(function() { $("#myonoffswitch").change(function(){ var check= $('#myonoffswitch').attr('checked'); if(check){ $('#myonoffswitch').attr('checked',false); current_check = false; }else{ $('#myonoffswitch').attr('checked',true); current_check = true; } $.post( onoff_notifi, { 'checked': current_check, 'type' : 'sales', 'get_csrf_token_name':get_csrf_hash } ); }); $("#myonoffswitch2").change(function(){ var check= $('#myonoffswitch2').attr('checked'); if(check){ $('#myonoffswitch2').attr('checked',false); current_check = false; }else{ $('#myonoffswitch2').attr('checked',true); current_check = true; } $.post( onoff_notifi, { 'checked': current_check, 'type' : 'request', 'get_csrf_token_name':get_csrf_hash } ); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SQRT2Docs = void 0; var SQRT2Docs = { name: 'SQRT2', category: 'Constants', syntax: ['SQRT2'], description: 'Returns the square root of 2, approximately equal to 1.414', examples: ['SQRT2', 'sqrt(2)'], seealso: [] }; exports.SQRT2Docs = SQRT2Docs;
'use strict'; var RollingSpider = source("driver"); describe("Cylon.Drivers.RollingSpider", function () { var driver = new RollingSpider({ connection: {} }); it("needs tests"); });
"use strict"; var debug = require('debug')('ansijet-job-processor'), co = require('co'), path = require('path'), thunkify = require('thunkify'), waigo = require('waigo'); var timers = waigo.load('support/timers'); var buildTimerHandler = function(app, maxParallelJobs) { return co(function*() { var activeJobs = yield app.models.Job.getActive(); debug('Processing ' + activeJobs.length + ' jobs'); /* Rules: - No more than maxParallelJobs jobs in progress at the same time - No more than one job for any given playbook in progress at a time By 'in progress' we mean job state === 'processing'. */ var pendingJobs = [], processingJobs = [], playbookProcessingJobs = {}; activeJobs.forEach(function(job) { if ('processing' === job.status) { processingJobs.push(job); playbookProcessingJobs[job.trigger.playbook] = true; } else if ('created' === job.status) { pendingJobs.push(job); } }); var jobsToExecute = []; while (maxParallelJobs > processingJobs.length && 0 < pendingJobs.length) { // list is in reverse chrono order and we want to deal with the oldest job first var nextPendingJob = pendingJobs.pop(); // check that we're not already executing the given playbook if (playbookProcessingJobs[nextPendingJob.trigger.playbook]) { continue; } else { // add this job to execution queue jobsToExecute.push(nextPendingJob); // update other lists processingJobs.push(nextPendingJob); playbookProcessingJobs[nextPendingJob.trigger.playbook] = true; } } // run all the new jobs in parallel yield jobsToExecute.map(function(j) { return j.execute(); }); }); }; /** * Start the job processor. * * This should be the last startup step which gets run to ensure that the * rest of app is ready and loaded. * * The job processor picks up newly created jobs and processes them. * * @param {Object} app The application. */ module.exports = function*(app) { app.logger.info('Mark previously active jobs as stale'); // since app has just started up ensure there are no active jobs from a previous instance var activeJobs = yield app.models.Job.getActive(); yield activeJobs.map(function(j){ j.status = 'stale'; return thunkify(j.save).call(j); }); var parallelJobs = app.config.jobsInParallel || 1; debug('Max parallel jobs: ' + parallelJobs); app.logger.info('Start job processing timer'); timers.new( buildTimerHandler(app, parallelJobs), app.config.jobProcessingIntervalMs, { repeat: true, async: true, onError: function(err) { app.logger.error('Job processing error: ' + err.message); } } ).start(); };
7.0-alpha1:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.0-alpha2:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.0-alpha3:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.0-alpha4:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.0-alpha5:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.0-alpha6:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.0-alpha7:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.0-beta1:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.0-beta2:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.0-beta3:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091 7.1:273d0a104707f9364922df60765f865076802b621c1eedb3b1ce98f69a056490 7.2:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.3:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.4:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.5:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.6:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.7:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.8:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.9:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.10:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.11:b51b4d44117f4c595f352cae8290242f586e9bf9f856845a95a7b9513106853a 7.12:c5d8fd579702508f5878ed6e2491a0eaccfccbae84eb4c0479bd21c5f13fb73b 7.13:c5d8fd579702508f5878ed6e2491a0eaccfccbae84eb4c0479bd21c5f13fb73b 7.14:fc41e6250dc4ab647e4da1a7771063b5fcc0e90c50cdd9bfaace58c47bf04a1a 7.15:fc41e6250dc4ab647e4da1a7771063b5fcc0e90c50cdd9bfaace58c47bf04a1a 7.16:fc41e6250dc4ab647e4da1a7771063b5fcc0e90c50cdd9bfaace58c47bf04a1a 7.17:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.18:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.19:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.20:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.21:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.22:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.23:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.24:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.25:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.26:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.27:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.28:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.29:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.30:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.31:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.32:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.33:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.34:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.35:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.36:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.37:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.38:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.39:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.40:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.41:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.42:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.43:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.44:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.50:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.51:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.52:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.53:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.54:61d339f438a194769c2e7d90970426ec0eea86d65566cec7db73fc3b802464fe 7.0:84ba5e3811fef6fb8a24452ed62e382505a9fa41eb0c841eb41b37d43ee17091
var PixelManager = function (mount) { var self = this; self.pixels = new Array(); for(var row = 0; row < P.height; row++){ for(var column = 0; column < P.width; column++){ var pixel = new Pixel(P.random(P.width),P.random(P.height)); // pixel.showBody(); self.pixels.push(pixel); } } _.times(P.height,function(){ var row = new Array(P.width); self.pixels.push(row); }); _.each(self.pixels,function(pixel){ // if(pixel.radius > 32) pixel.showLinks(self.pixels); }); }
'use strict'; function weightedMean(weightedValues) { var totalWeight = weightedValues.reduce(function (sum, weightedValue) { return sum + weightedValue[1]; }, 0); return weightedValues.reduce(function (mean, weightedValue) { return mean + weightedValue[0] * weightedValue[1] / totalWeight; }, 0); } module.exports = weightedMean;
var _; //globals describe("About Applying What We Have Learnt", function() { var products; beforeEach(function () { products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false }, { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true }, { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true } ]; }); /*********************************************************************************/ it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () { var i,j,hasMushrooms, productsICanEat = []; for (i = 0; i < products.length; i+=1) { //go through all products if (products[i].containsNuts === false) { //filter contains nuts hasMushrooms = false; for (j = 0; j < products[i].ingredients.length; j+=1) { //any ingredient with mushrooms is a no if (products[i].ingredients[j] === "mushrooms") { hasMushrooms = true; } } if (!hasMushrooms) productsICanEat.push(products[i]); } } expect(productsICanEat.length).toBe(1); }); it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { var productsICanEat = []; productsICanEat = _.filter(products, function(x){ return x.containsNuts === false; }); productsICanEat = _.filter(productsICanEat, function(product){ return _.all(product.ingredients, function(y){ return y !== "mushrooms" }); }) /* solve using filter() & all() / any() */ expect(productsICanEat.length).toBe(1); }); /*********************************************************************************/ it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { var sum = 0; for(var i=1; i<1000; i+=1) { if (i % 3 === 0 || i % 5 === 0) { sum += i; } } expect(sum).toBe(233168); }); it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { var sum = _.range(0,1000,1).filter(function(x){ if (x % 3 === 0 || x % 5 === 0) return x;}.reduce(function(a,b){ return a+b; }); /* try chaining range() and reduce() */ expect(233168).toBe(sum); }); /*********************************************************************************/ it("should count the ingredient occurrence (imperative)", function () { var ingredientCount = { "{ingredient name}": 0 }; for (i = 0; i < products.length; i+=1) { for (j = 0; j < products[i].ingredients.length; j+=1) { ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1; } } expect(ingredientCount['mushrooms']).toBe(2); }); it("should count the ingredient occurrence (functional)", function () { var ingredientCount = { "{ingredient name}": 0 }; ingredientCount = _.chain().map(function(product){return product.ingredients};) .flatten().filter(function(x){if x==="mushrooms" return x;}) .reduce(function(){return ingredientCount.length}) .value(); /* chain() together map(), flatten() and reduce() */ expect(ingredientCount['mushrooms']).toBe(2); }); /*********************************************************************************/ /* UNCOMMENT FOR EXTRA CREDIT */ /* it("should find the largest prime factor of a composite number", function () { }); it("should find the largest palindrome made from the product of two 3 digit numbers", function () { }); it("should find the smallest number divisible by each of the numbers 1 to 20", function () { }); it("should find the difference between the sum of the squares and the square of the sums", function () { }); it("should find the 10001st prime", function () { }); */ });
/** * pubfood * * Errors live here.. */ 'use strict'; var ERR_NAME = 'PubfoodError'; /** * Pubfood Error * @class * @param {string} message - the error description * @return {pubfood.PubfoodError} */ function PubfoodError(message) { this.name = ERR_NAME; /** @property {string} message The error message */ this.message = message || 'Pubfood integration error.'; /** @property {string} stack The error stack trace */ this.stack = (new Error()).stack; } PubfoodError.prototype = Object.create(Error.prototype); PubfoodError.prototype.constructor = PubfoodError; PubfoodError.prototype.name = ERR_NAME; PubfoodError.prototype.is = function(err) { return err && err.name === ERR_NAME; }; module.exports = PubfoodError;
application.whenConnected('something')
module.exports = (function() { function ParameterTrackModel(parameter, dataModel) { this.parameter = parameter; this.dataModel = dataModel; this.graphColumn = undefined; dataModel.addListener(this); // Returns an array with parameter value objects this.getParameterPath = function() { return this.dataModel.getValuesForParameter(this.parameter); }; this.rangeChanged = function() { this.parameterTrack.render(); }; this.layoutChanged = function() { this.parameterTrack.render(); }; this.render = function() { this.parameterTrack.render(); }; this.getParameter = function() { return this.parameter; }; this.setParameterTrack = function(parameterTrack) { this.parameterTrack = parameterTrack; }; this.getRange = function() { return { min: this.dataModel.getMin(parameter), max: this.dataModel.getMax(parameter) }; }; this.updateMarkerLine = function(yCoord) { this.parameterTrack.drawMarkerLine(yCoord); }; }; return ParameterTrackModel; })();
'use strict'; const request = require('supertest'); const assert = require('assert'); const Koa = require('../..'); describe('ctx.state', function(){ it('should provide a ctx.state namespace', function(done){ const app = new Koa(); app.use(function *(ctx){ assert.deepEqual(ctx.state, {}); }); const server = app.listen(); request(server) .get('/') .expect(404) .end(done); }); });
module.exports = function(sequelize, db) { return sequelize.define("Search", { name: db.STRING, profile_type: db.STRING, image: db.STRING, document: db.STRING, slug: db.STRING }, { classMethods: { search: (query, filter) => { if (sequelize.options.dialect !== "postgres") { console.log("Search is only implemented on POSTGRES database"); return; } let filterByProfileType; if (filter !== "all") { filterByProfileType = " AND profile_type='" + filter + "'"; } else { filterByProfileType = ""; } // query = sequelize.getQueryInterface().escape(query+":*"); return sequelize .query('SELECT * FROM "' + Search.tableName + '" WHERE document @@ plainto_tsquery(:query)' + filterByProfileType, { replacements: { query: query + ":*" }, model: Search, type: sequelize.QueryTypes.SELECT }); } }, timestamps: false, tableName: "Search" }); };
var fs = require('fs'); var path = require('path'); var glob = require('glob'); var defer = require('node-promise').defer; var http = require('http'); var connect = require('connect'); var io = require('socket.io'); var assets = { scripts: {}, styles: {} }; var connectionPort = 8111; var clientdir = path.join(process.cwd(), 'client'); var app = connect().use(connect.static(clientdir)); var server = http.createServer(app); var socket = io.listen(server); socket.sockets.on('connection', function(socket) { console.log('Socket connection.'); socket.emit('assets', assets); }); function appendScript(filename, script) { assets.scripts[filename] = script; } function appendStyle(filename, style) { assets.styles[filename] = style; } function loadAssetsFromDir(dirGlob, appender) { var dfd = defer(); glob(dirGlob, function(err, matches) { var count = (matches) ? matches.length : 0; if(err) { console.error('Could not load scripts: ' + err); dfd.resolve(); } matches.forEach(function(filepath) { fs.readFile(filepath, function(err, data) { if(!err) { appender.call(null, path.basename(filepath), data.toString()); } if(--count === 0) { dfd.resolve(); } }); }); }); return dfd; } loadAssetsFromDir(path.join(clientdir, 'script', '*.js'), appendScript) .then(function() { loadAssetsFromDir(path.join(clientdir, 'style', '*.css'), appendStyle); }) .then(function() { server.listen(connectionPort, function() { console.log('Server started at http://localhost:' + connectionPort); }); });
import path from 'path' import fs from 'fs' import mkdirp from 'mkdirp' /** * All files in dir */ function getFileList (dir) { return fs.readdirSync(dir).reduce((list, file) => { const name = path.join(dir, file) const isDir = fs.statSync(name).isDirectory() if (isDir) { list.push({ isDir: true, files: getFileList(`${dir}/${file}`), dirName: file }) } else { list.push(file) } return list }, []) }; /** * Write files recursively */ function writeFiles (fileName, componentName, componentPath, templatePath, dirName = '') { if (fileName.isDir) { fs.mkdirSync(path.join(componentPath, fileName.dirName)) fileName.files.forEach((file) => { writeFiles(file, componentName, componentPath, templatePath, fileName.dirName) }) } else { const data = fs.readFileSync(path.join(templatePath, dirName, fileName), 'utf-8') const newFileName = fileName.replace(/\.template/, '').replace('MyComponent', componentName) fs.writeFileSync( path.join(componentPath, dirName, newFileName), data.replace(/MyComponent/g, componentName) ) } } /** * Create story folder in stories */ async function generate () { let componentPath = process.argv[process.argv.length - 1] || '' if (componentPath.length === 0) { console.error('Error: Specify story name, for example: npm run generate:story Todo') return } const paths = componentPath.split('/') let componentName = paths[paths.length - 1] // Capitalize component name componentName = componentName.charAt(0).toUpperCase() + componentName.slice(1) paths[paths.length - 1] = componentName componentPath = path.join('stories', paths.join('/')) const isDirExist = fs.existsSync(componentPath) if (isDirExist) { console.error(`Error: Story "${componentPath}" already exist.`, 'Choose another story name') return } mkdirp(componentPath, {}, () => { const templatePath = path.join('helpers', 'scripts', 'generator', 'templates', 'story') // foreach template getFileList(templatePath).forEach((fileName) => { writeFiles(fileName, componentName, componentPath, templatePath) }) // register component to components/index.js fs.appendFile('stories/preface.js', `import './${componentName}'\n`, (err) => { if (err) { console.log('Error: ', err) } else { console.log('Success! Your new component is', componentName) } }) }) } export default generate
exports.post = function(req, res) { var DiaryItem = require('../models/diaryItem'); var diaryitem = new DiaryItem(req.body.diaryitem); diaryitem.addedBy = req.user._id; diaryitem.addedByName = req.user.firstName + ' ' + req.user.lastName; diaryitem.addedOn = new Date(); diaryitem.save(function(err) { if(err) throw err; var item = diaryitem.toObject(); item.canEdit = diaryitem.addedBy.toString() == req.user._id; res.send({diaryitem: item}); }); }; exports.put = function(req, res) { var DiaryItem = require('../models/diaryItem'); var diaryitem = req.body.diaryitem; var id = req.param('id'); DiaryItem.findOneAndUpdate({_id: id},{$set: diaryitem }).lean().exec(function(err, doc) { if(err) throw err; doc.canEdit = doc.addedBy.toString() == req.user._id; res.send({diaryitem: doc}); }); }; exports.delete = function(req, res) { var DiaryItem = require('../models/diaryItem'); var diaryitem = req.param('id'); DiaryItem.remove({_id: diaryitem}, function(err) { if(err) throw err; res.send(null); }); };
var myApp = angular.module('myApp', []); myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) { //set 'this' to the variable self var self = this; //is set to true when editing a contact self.editModeActive = false; //get data from server $http.get("/contactList") .then(function(dataResponse){ console.log("GOT THE DATA FROM MY OWN API YAYAYAYAYAA"); console.log("dataResponse ", dataResponse); self.contactList = dataResponse.data; }); //post request self.addNewContact = function(){ console.log("contact is requested - ", self.contact) //send the contact object to the server $http.post('/contactList', self.contact) .success(function(response){ console.log("response ", response); //push new contact into array self.contactList.push(response); //clear inputs self.contact = ""; }); } // delete request self.removeContact = function(id){ console.log("id ", id); //delete request $http.delete('/contactList/'+id) .success(function(response){ console.log("delete response ", response); //remove the deleted contact from array var updatedArray = [] self.contactList.map(function(item){ if(item._id === id){ console.log("thats it"); } else { updatedArray.push(item) } }) self.contactList = updatedArray; //make this more efficient with splice method or sumn }); } //update existing people in db self.updateContact = function(contact){ console.log("contact to update is ", contact); console.log("contact id is ", contact.id); //send contact object in put request $http.put("/contactList/"+contact.id, contact) .success(function(response){ //on success log response, clear inputs, and replace item in array self.contact=""; //splice out the old one and put in the new self.contactList.map(function(item,index){ if(item._id === response._id){ self.contactList.splice(index, 1, response); } }); //turn off edit mode self.editModeActive = false; }); } //switch contact to edit mode self.editContact = function(contact){ console.log("contact ", contact); self.editModeActive = true; self.contact = { name : contact.name, email : contact.email, phone : contact.phone, id : contact._id } } }]);
export default function calculateMidpoint(entity) { return { left: entity.position.left + (entity.size.width / 2), top: entity.position.top + (entity.size.height / 2), }; }
const assert = require('assert'); const Retracer = require('../retracer'); const mappingFile1 = "com.example.test.AnotherClass -> o.w:\n" + " java.lang.String TAG -> `\n" + " android.content.Context mContext -> ,\n" + " android.net.Uri mContentUri -> .\n" + " 52429:52430:void checkSelfPermission(android.content.Context,java.lang.String):125:126 -> ˋ\n" + " 321:325:void com.example.test.AnotherClass.doSomething():404:409 -> ˋ\n" + "com.example.test.TestClass -> o.wM:\n" + " java.lang.String TAG -> ॱ\n" + " android.content.Context mContext -> ˏ\n" + " android.net.Uri mContentUri -> ˎ\n" + " 512:515:com.example.test.TestClass doSomethingElse():202:205 -> ˋ\n"; describe('Retracer', function() { describe('generateMap', function() { it('should return an object', function() { assert.equal(typeof {}, typeof Retracer.generateMap("")); }); it('should interpret class name when raw mappings are provided', function() { assert.equal("com.example.test.TestClass", Retracer.generateMap(mappingFile1)["o.wM"].class); }); it('should interpret member methods when raw mappings are provided', function() { assert.equal("void checkSelfPermission(android.content.Context,java.lang.String):125:126", Retracer.generateMap(mappingFile1)["o.w"].members['52429:52430:ˋ'].name); }); }); describe('retrace', function() { it('should return string', function() { assert.equal(typeof "", typeof Retracer.retrace("", {})); }); it('should return the actual class name from mappings', function() { assert.equal("com.example.test.AnotherClass.run()", Retracer.retrace("o.w.run()", Retracer.generateMap(mappingFile1))); }); it('should return the actual class name from mappings when there are similar symbols', function() { assert.equal("com.example.test.TestClass.run()", Retracer.retrace("o.wM.run()", Retracer.generateMap(mappingFile1))); }); it('should return the actual method name from mappings', function() { assert.equal("com.example.test.AnotherClass.[void checkSelfPermission(android.content.Context,java.lang.String):125:126]()", Retracer.retrace("o.w.ˋ(:52429)", Retracer.generateMap(mappingFile1))); }); it('should return the actual method name from mappings when line number is within range', function() { assert.equal("com.example.test.AnotherClass.[void com.example.test.AnotherClass.doSomething():404:409]()", Retracer.retrace("o.w.ˋ(:322)", Retracer.generateMap(mappingFile1))); }); it('should retrace class names in the log summary', function() { assert.equal("java.lang.RuntimeException: Unable to resume activity {com.example.test/.MainActivity}: java.lang.NullPointerException: Attempt to read from field 'com.example.test.TestClass com.example.test.TestClass.ˋ' on a null object reference", Retracer.retrace("java.lang.RuntimeException: Unable to resume activity {com.example.test/.MainActivity}: java.lang.NullPointerException: Attempt to read from field 'o.wM com.example.test.TestClass.ˋ' on a null object reference", Retracer.generateMap(mappingFile1))); }); }); });
var ActionAtADistance = function() { var _socket, _lastRequestedUrl, _currentlyLoadedUrl, _uuid, _lastEvalResp, _connected = false, _onCallback, _initCallback, _onDisconnect; function _log(msg) { if (typeof console !== 'undefined' && (typeof console.log === 'function' || typeof console.log === 'object')) { console.log(msg); } } function _logJson(msg) { if (typeof JSON !== 'undefined' && (typeof JSON.stringify === 'function' || typeof JSON.stringify === 'object')) { _log(JSON.stringify(msg)); } } function _loadSocketIO(callback) { $.getScript('/aaad-socket-uri.js', function(data, textStatus, jqxhr) { var socketIOUrl = 'http://' + document.location.hostname + aaadSocketURI; _log('SocketIO URL: ' + socketIOUrl); $.getScript(socketIOUrl + "socket.io/socket.io.js", function(data, textStatus, jqxhr) { _socket = io.connect(socketIOUrl, {'force new connection': true}); _socket.on('connect', function () { _socket.emit('init'); }); _socket.on('disconnect', function () { if (typeof _onDisconnect !== 'undefined') { _onDisconnect(); } }); _socket.on('callback', function (data) { if (data.action === 'start') { _currentlyLoadedUrl = _lastRequestedUrl; //TODO pass the URL as part of the Socket.io response data }else if (data.action === 'documentLoaded') { _currentlyLoadedUrl = data.documentLocationHref; } else if (data.action === 'evaluate') { _lastEvalResp = data; } _onCallback(data); }); callback(); }); }); } return { connect: function(port, callback) { _loadSocketIO(port, callback); }, init: function() { _socket.on('initResp', function (data) { _uuid = data.uuid; _connected = true; _initCallback(); }); }, onDisconnect: function (callback) { _onDisconnect = callback; }, start: function(url) { _lastRequestedUrl = url; _socket.emit('start', {url: _lastRequestedUrl}); }, startAndLogin: function(url, formName, userInputName, passInputName, user, pass) { _lastRequestedUrl = url; _socket.emit('startAndLogin', {url: _lastRequestedUrl, formName: formName, userInputName: userInputName, passInputName: passInputName, user: user, pass: pass}); }, evaluate: function(data) { _socket.emit('evaluate', {action: data}); }, connected: function() { return _connected; }, currentlyLoadedUrl: function() { return _currentlyLoadedUrl; }, lastEvalResponse: function() { return _lastEvalResp; }, uuid: function() { return _uuid; }, log: function(msg) { _log(msg); }, logJson: function(msg) { _logJson(msg); }, on: function(event, callback) { if (event === 'callback') { _onCallback = callback; } else if (event === 'initResp') { _initCallback = callback; } } }; } if (typeof exports == 'object' && exports) { exports = module.exports = ActionAtADistance; }
"use strict"; var ensureDatabase = require('dbjs/valid-dbjs') , ensureString = require('es5-ext/object/validate-stringifiable-value') , ensureObject = require('es5-ext/object/valid-object') , queryMaster = require('../../query-master/slave') , defineUser = require('../../../../model/user'); module.exports = exports = function (db) { ensureDatabase(db); defineUser(db); return function (query) { var userId = ensureString(ensureObject(query).userId) , data = ensureObject(query.data) , user = db.User.getById(userId); user.delete('isDemo'); user.password = 'invalid'; Object.keys(data).forEach(function (key) { user[key] = data[key]; }); return queryMaster('loadInitialBusinessProcesses', { userId: userId })(function () { user.initialBusinessProcesses.forEach(function (businessProcess) { businessProcess.delete('isDemo'); }); return userId; }); }; };
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z" /> , 'KeyboardArrowUp');
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M15 1H9v2h6V1zm4.03 6.39l1.42-1.42c-.43-.51-.9-.99-1.41-1.41l-1.42 1.42C16.07 4.74 14.12 4 12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9 9-4.03 9-9c0-2.12-.74-4.07-1.97-5.61zM12 20c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm-.32-5H6.35c.57 1.62 1.82 2.92 3.41 3.56l-.11-.06 2.03-3.5zm5.97-4c-.57-1.6-1.78-2.89-3.34-3.54L12.26 11h5.39zm-7.04 7.83c.45.11.91.17 1.39.17 1.34 0 2.57-.45 3.57-1.19l-2.11-3.9-2.85 4.92zM7.55 8.99C6.59 10.05 6 11.46 6 13c0 .34.04.67.09 1h4.72L7.55 8.99zm8.79 8.14C17.37 16.06 18 14.6 18 13c0-.34-.04-.67-.09-1h-4.34l2.77 5.13zm-3.01-9.98C12.9 7.06 12.46 7 12 7c-1.4 0-2.69.49-3.71 1.29l2.32 3.56 2.72-4.7z" /> , 'ShutterSpeedSharp');
/* Create an issue link */ module.exports = function (task, jira, grunt, callback) { 'use strict'; // ## Create an issue link between two issues ## // ### Takes ### // // * link: a link object // * callback: for when it’s done // // ### Returns ### // * error: string if there was an issue, null if success // // [Jira Doc](http://docs.atlassian.com/jira/REST/latest/#id288232) /* { * 'type': { * 'name': 'requirement' * }, * 'inwardIssue': { * 'key': 'SYS-2080' * }, * 'outwardIssue': { * 'key': 'SYS-2081' * }, * 'comment': { * 'body': 'Linked related issue!', * 'visibility': { * 'type': 'GROUP', * 'value': 'jira-users' * } * } * } */ var link = task.getValue('link'); jira.issueLink(link, callback); };
var express = require('express'); var router = express.Router(); var rsssection = require('../app/models/rsssection'); var rssfeed = require('../app/models/rssfeed'); var coaching = require('../app/models/coaching'); var user = require('../app/models/user'); var email = require('../app/models/email'); var mongodb = require('mongodb'); var readingTime = require('reading-time'); const cheerio = require('cheerio'); router.get('/remove/:rsssectionId', function(req, res) { var rsssectionId = req.params.rsssectionId.toString(); var allRssfeeds = rssfeed .find({rsssections: rsssectionId}, {rsssections: 1, title:1 }) .exec(function (err, allRssfeeds) { var nRssfeeds = allRssfeeds.length; var counter = 0; allRssfeeds.forEach(function(thisRssfeed, bindex){ thisTag = thisRssfeed.rsssections; var tagIndex = thisTag.indexOf(rsssectionId); if(tagIndex != -1){ thisRssfeed.rsssections.splice(tagIndex, 1); console.log('Removed from blog: ' + thisRssfeed.title); thisRssfeed.save(function(err, thisRssfeed) { if (err) return console.error(err); counter += 1; if(counter == nRssfeeds){ rsssection.remove({_id: new mongodb.ObjectID(rsssectionId)}, function(err, result) { if (err) { console.log(err); } else { console.log(rsssectionId + ' removed!'); res.json(true); } }); } }); } }); }); }); router.get('/usedinBlogs/:rsssectionId', function(req, res) { var rsssectionId = req.params.rsssectionId.toString(); var allRssfeeds = rssfeed .find({rsssections: rsssectionId}, {rsssections: 1, title:1, urlslug:1 }) .exec(function (err, allRssfeeds) { res.json(allRssfeeds); }); }); router.get('/rsssectionsCount', function(req, res) { rsssection.count({active: true}, function(err, docs) { if (!err){ res.json(docs); } else {throw err;} }); }); router.get('/rsssectionsSummary', function(req, res) { var allBlogs = rssfeed .find({}, {rsssections: 1}) .exec(function (err, allBlogs) { if (!err){ var allRssSectionsId = []; var allRssSections = []; var thisRssSection = null; var addRssSection = null; allBlogs.forEach(function(thisBlog, bindex){ if(thisBlog.rsssections){ thisRssSection = thisBlog.rsssections; } if(thisRssSection && thisRssSection.length > 0){ thisRssSection.forEach(function(thisTag, tindex){ var tagIndex = allRssSectionsId.indexOf(thisTag.toString()); if(tagIndex == -1){ allRssSectionsId.push(thisTag.toString()); addRssSection = { _id: thisTag, count: 1 }; allRssSections.push(addRssSection); }else{ allRssSections[tagIndex].count += 1; } }); } }); res.json(allRssSections); } else {throw err;} }); }); router.get('/', function(req, res) { var rsssections = rsssection .find({}) .exec(function (err, rsssections) { if (!err){ res.json(rsssections); } else {throw err;} }); }); //to get a particular rsssection with _id rsssectionId router.get('/edit/:rsssectionId', function(req, res) { var rsssectionId = req.params.rsssectionId; var thisRssSection = rsssection .findOne({ '_id': rsssectionId }) .exec(function (err, thisRssSection) { if (!err){ res.json(thisRssSection); } else {throw err;} }); }); router.get('/deactivate/:rsssectionId', function(req, res) { var rsssectionId = req.params.rsssectionId; var thisRssSection = rsssection .findOne({ '_id': rsssectionId }) //.deepPopulate('coupon') .exec(function (err, thisRssSection) { if (!err && thisRssSection){ thisRssSection.active = false; thisRssSection.save(function(err, thisRssSection) { if (err) return console.error(err); res.json(thisRssSection); }); } else {res.json(false);} }); }); router.get('/activate/:rsssectionId', function(req, res) { var rsssectionId = req.params.rsssectionId; var thisRssSection = rsssection .findOne({ '_id': rsssectionId }) //.deepPopulate('coupon') .exec(function (err, thisRssSection) { if (!err && thisRssSection){ thisRssSection.active = true; thisRssSection.save(function(err, thisRssSection) { if (err) return console.error(err); res.json(thisRssSection); }); } else {res.json(false);} }); }); router.get('/enable/:rsssectionId', function(req, res) { var rsssectionId = req.params.rsssectionId; var thisRssSection = rsssection .findOne({ '_id': rsssectionId }) //.deepPopulate('coupon') .exec(function (err, thisRssSection) { if (!err){ thisRssSection.active = true; thisRssSection.save(function(err, thisRssSection) { if (err) return console.error(err); res.json(thisRssSection._id); }); } else {throw err;} }); }); router.post('/save', function(req, res) { var rsssectionForm = req.body; var rsssectionId = rsssectionForm._id; if(rsssectionId){ var existingRssSection = rsssection .findOne({_id: rsssectionId}) .exec(function (err, existingRssSection) { if (!err){ for (var property in rsssectionForm) { existingRssSection[property] = rsssectionForm[property]; } existingRssSection.save(function(err, existingRssSection) { if (err) return console.error(err); res.json(existingRssSection); }); } else {throw err;} }); }else{ var newrsssection = new rsssection({}); for (var property in rsssectionForm) { newrsssection[property] = rsssectionForm[property]; } newrsssection.save(function(err, newrsssection) { if (err) return console.error(err); res.json(newrsssection); }); } }); router.post('/bulksave', function(req, res) { console.log("Starting Bulk Save"); var rsssectionForm = req.body; console.log(rsssectionForm); if(rsssectionForm && rsssectionForm.length > 0){ var nSections = rsssectionForm.length; var counter = 0; rsssectionForm.forEach(function(thisRsssection, sindex){ var this_rsssection = new rsssection(thisRsssection); this_rsssection.save(function(err, this_rsssection) { if (err) return console.error(err); counter += 1; if(counter == nSections){ res.json(true); } }); }); }else{ res.json(false); } }); module.exports = router;
/* Copyright (c) 2011, Chris Umbel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict' const PorterStemmer = require('../stemmers/porter_stemmer') const events = require('events') const parallelTrainer = require('./classifier_train_parallel') const Classifier = function (classifier, stemmer) { this.classifier = classifier this.docs = [] this.features = {} this.stemmer = stemmer || PorterStemmer this.lastAdded = 0 this.events = new events.EventEmitter() } function addDocument (text, classification) { // Ignore further processing if classification is undefined if (typeof classification === 'undefined') return // If classification is type of string then make sure it's dosen't have blank space at both end if (typeof classification === 'string') { classification = classification.trim() } if (typeof text === 'string') { text = this.stemmer.tokenizeAndStem(text, this.keepStops) } if (text.length === 0) { // ignore empty documents return } this.docs.push({ label: classification, text: text }) for (let i = 0; i < text.length; i++) { const token = text[i] this.features[token] = (this.features[token] || 0) + 1 } } function removeDocument (text, classification) { const docs = this.docs let doc let pos if (typeof text === 'string') { text = this.stemmer.tokenizeAndStem(text, this.keepStops) } for (let i = 0, ii = docs.length; i < ii; i++) { doc = docs[i] if (doc.text.join(' ') === text.join(' ') && doc.label === classification) { pos = i } } // Remove if there's a match if (!isNaN(pos)) { this.docs.splice(pos, 1) for (let i = 0, ii = text.length; i < ii; i++) { delete this.features[text[i]] } } } function textToFeatures (observation) { const features = [] if (typeof observation === 'string') { observation = this.stemmer.tokenizeAndStem(observation, this.keepStops) } for (const feature in this.features) { if (observation.indexOf(feature) > -1) { features.push(1) } else { features.push(0) } } return features } function train () { const totalDocs = this.docs.length for (let i = this.lastAdded; i < totalDocs; i++) { const features = this.textToFeatures(this.docs[i].text) this.classifier.addExample(features, this.docs[i].label) this.events.emit('trainedWithDocument', { index: i, total: totalDocs, doc: this.docs[i] }) this.lastAdded++ } this.events.emit('doneTraining', true) this.classifier.train() } function retrain () { this.classifier = new (this.classifier.constructor)() this.lastAdded = 0 this.train() } function getClassifications (observation) { return this.classifier.getClassifications(this.textToFeatures(observation)) } function classify (observation) { return this.classifier.classify(this.textToFeatures(observation)) } function restore (classifier, stemmer) { classifier.stemmer = stemmer || PorterStemmer classifier.events = new events.EventEmitter() return classifier } function save (filename, callback) { const data = JSON.stringify(this) const fs = require('fs') const classifier = this fs.writeFile(filename, data, 'utf8', function (err) { if (callback) { callback(err, err ? null : classifier) } }) } function load (filename, callback) { const fs = require('fs') if (!callback) { return } fs.readFile(filename, 'utf8', function (err, data) { if (err) { callback(err, null) } else { const classifier = JSON.parse(data) callback(err, classifier) } }) } function setOptions (options) { this.keepStops = !!(options.keepStops) } Classifier.prototype.addDocument = addDocument Classifier.prototype.removeDocument = removeDocument Classifier.prototype.train = train if (parallelTrainer.Threads) { Classifier.prototype.trainParallel = parallelTrainer.trainParallel Classifier.prototype.trainParallelBatches = parallelTrainer.trainParallelBatches Classifier.prototype.retrainParallel = parallelTrainer.retrainParallel } Classifier.prototype.retrain = retrain Classifier.prototype.classify = classify Classifier.prototype.textToFeatures = textToFeatures Classifier.prototype.save = save Classifier.prototype.getClassifications = getClassifications Classifier.prototype.setOptions = setOptions Classifier.restore = restore Classifier.load = load module.exports = Classifier
var config = require('../config'); if(!config.tasks.fonts) return; var browserSync = require('browser-sync'); var changed = require('gulp-changed'); var gulp = require('gulp'); var path = require('path'); var paths = { src: path.join(config.root.src, config.tasks.fonts.src, '/**/*'), dest: path.join(config.root.dest, config.tasks.fonts.dest) }; var fontsTask = function() { return gulp.src(paths.src) .pipe(changed(paths.dest)) // Ignore unchanged files .pipe(gulp.dest(paths.dest)) .pipe(browserSync.stream()); }; gulp.task('fonts', fontsTask); module.exports = fontsTask;
import {createPartStore, createReducer} from '../index'; let modelState = { name: 'Tom', age: 12, isboy: true, address: { city: 'Guangzhou', school: 'SCUT' } }; let initState = modelState; const namespace = 'merge'; const partStore = createPartStore(namespace, modelState); const reducer = createReducer(namespace, initState); export { namespace , partStore, reducer }
import { combineReducers } from 'redux'; import actionCableReducer from './action-cable-reducer'; export default combineReducers({ actionCable: actionCableReducer });
/** * @namespace tetris */ define(function () { 'use strict'; /** * @class tetris.Logger */ function Logger(name) { this._name = name; this._console = 'console' in window ? window.console : null; } Logger.prototype.error = function (msg) { this._log('error', msg); }; Logger.prototype.warn = function (msg) { this._log('warn', msg); }; Logger.prototype.info = function (msg) { this._log('info', msg); }; Logger.prototype.debug = function (msg) { this._log('debug', msg); }; Logger.prototype._log = function (level, msg) { var console = this._console, output; if (!console) return; output = this._name + ' [' + level.toUpperCase() + '] ' + msg; if (level in console) { console[level](output); } else if ('log' in console) { console.log(output); } }; return Logger; });
version https://git-lfs.github.com/spec/v1 oid sha256:ebb7daa36c51853820ec193e5e56aa0d47e36900b3bb4874b150e4c1c530ad4b size 1407
describe('FeatureManagerService', function() { var featureMgrService; var mapService; var serverService; var configService; var exclusiveModeService; var translateService; var q; var defer; var rootScope; var httpBackend; var dialogService; var window; //include the whole application to initialize all services and modules beforeEach(module('MapLoom')); beforeEach(inject(function (_featureManagerService_, _mapService_, _serverService_, _exclusiveModeService_, _configService_, _dialogService_,$translate, $httpBackend, $q, $rootScope, $window) { featureMgrService = _featureManagerService_; mapService = _mapService_; serverService = _serverService_; configService = _configService_; translateService = $translate; exclusiveModeService = _exclusiveModeService_; dialogService = _dialogService_; httpBackend = $httpBackend; q = $q; rootScope = $rootScope; window = $window; })); describe('show', function() { beforeEach(function() { //spyOn(rootScope, '$broadcast'); defer = q.defer(); defer.resolve(); mapService.loadLayers(); rootScope.$apply(); spyOn(mapService, 'addToEditLayer'); spyOn(featureMgrService, 'getSelectedItemLayer').and.returnValue({layer:mapService.map.getLayers().array_[0]}); spyOn(featureMgrService, 'getSelectedItemMediaByProp'); }); it('should set state_ to \'layer\' and selectedItem_ should be set to the object passed as the parameter, if object has a defined property called features', function() { //set a features property on pre-existing layer mapService.map.getLayers().array_[0].features = 1; featureMgrService.show(mapService.map.getLayers().array_[0]); expect(featureMgrService.getState()).toBe('layer'); expect(mapService.map.getLayers().array_[0]).toBe(featureMgrService.getSelectedItem()); }); it('should set state_ to \'feature\' and selectedItem_ should be set to the object passed as the parameter, if object has defined properties called features, properties, and geometry', function () { //cook up some data to make sure we can get through all function calls mapService.map.getLayers().array_[0].features = 1; mapService.map.getLayers().array_[0].properties = 1; mapService.map.getLayers().array_[0].geometry = 1; mapService.editLayer.getSource().featuresCollection_ = new ol.Collection(); var feature = new ol.Feature({ geometry: new ol.geom.Circle([45,45], 10), labelPoint: new ol.geom.Point([90, 45]), name: 'My Polygon' }); mapService.editLayer.getSource().featuresCollection_.push(feature); //call the actual method we are testing featureMgrService.show(mapService.map.getLayers().array_[0]); //run through assertions for dealing with a feature expect(featureMgrService.getState()).toBe('feature'); expect(mapService.map.getLayers().array_[0]).toBe(featureMgrService.getSelectedItem()); expect(featureMgrService.getSelectedItemLayer).toHaveBeenCalled(); expect(mapService.addToEditLayer).toHaveBeenCalled(); expect(featureMgrService.getSelectedItemMediaByProp).toHaveBeenCalled(); }); it('should set state_ to \'layers\' and selectedItem_ should be set to the object passed as the parameter, if the object is an array and elements have a defined property called features', function() { mapService.map.getLayers().array_[0].features = 1; featureMgrService.show(mapService.map.getLayers().array_); expect(featureMgrService.getState()).toBe('layers'); expect(mapService.map.getLayers().array_).toBe(featureMgrService.getSelectedItem()); expect(featureMgrService.getSelectedItemLayer).not.toHaveBeenCalled(); }); it('should not add anything to the edit layer if there is no geometry defined in the object that is passed as a parameter', function () { //cook up some data to make sure we can get through all function calls mapService.map.getLayers().array_[0].features = 1; mapService.map.getLayers().array_[0].properties = 1; mapService.editLayer.getSource().featuresCollection_ = new ol.Collection(); var feature = new ol.Feature({ geometry: new ol.geom.Circle([45,45], 10), labelPoint: new ol.geom.Point([90, 45]), name: 'My Polygon' }); mapService.editLayer.getSource().featuresCollection_.push(feature); //call the actual method we are testing featureMgrService.show(mapService.map.getLayers().array_[0]); //run through assertions for dealing with a feature expect(featureMgrService.getState()).toBe('feature'); expect(mapService.map.getLayers().array_[0]).toBe(featureMgrService.getSelectedItem()); expect(featureMgrService.getSelectedItemLayer).toHaveBeenCalled(); expect(mapService.addToEditLayer).not.toHaveBeenCalled(); expect(featureMgrService.getSelectedItemMediaByProp).toHaveBeenCalled(); }); }); describe('hide', function() { beforeEach(function() { spyOn(mapService, 'clearEditLayer'); }); it('should reset private variables and call clearEditLayer', function() { featureMgrService.hide(); expect(featureMgrService.getSelectedItem()).toBe(null); expect(featureMgrService.getState()).toBe(null); expect(featureMgrService.getSelectedItemLayer()).toBe(null); expect(featureMgrService.getSelectedItemProperties()).toBe(null); expect(featureMgrService.getSelectedItemMedia()).toBe(null); expect(mapService.clearEditLayer).toHaveBeenCalled(); }); }); describe('startFeatureInsert', function() { beforeEach(function() { spyOn(featureMgrService, 'hide'); spyOn(exclusiveModeService, 'startExclusiveMode'); defer = q.defer(); defer.resolve(); mapService.loadLayers(); rootScope.$apply(); mapService.map.getLayers().getArray()[0].values_.metadata.schema = {geom: {_name:'geom', _type:'gml:PointPropertyType' } }; }); it('shoud call hide on the current layer', function() { featureMgrService.startFeatureInsert(mapService.map.getLayers().getArray()[0]); expect(featureMgrService.hide).toHaveBeenCalled(); }); it('should disable double-click zoom interaction on the map since the user is about to draw', function() { featureMgrService.startFeatureInsert(mapService.map.getLayers().getArray()[0]); expect(mapService.map.interactions_.array_[1].values_.active).toBe(false); }); it('should start exclusive mode and set exclusiveModeService.addMode to true', function() { //expect(mapService.editLayer.getSource().getFeatures().length).toBe(0); featureMgrService.startFeatureInsert(mapService.map.getLayers().getArray()[0]); expect(exclusiveModeService.startExclusiveMode).toHaveBeenCalled(); expect(exclusiveModeService.addMode).toBe(true); }); it('should set the internal selected layer to the layer provided as a parameter', function() { featureMgrService.startFeatureInsert(mapService.map.getLayers().getArray()[0]); expect(featureMgrService.getSelectedLayer()).toBe(mapService.map.getLayers().getArray()[0]); }); it('shoud add the edit layer to the map for editing', function() { featureMgrService.startFeatureInsert(mapService.map.getLayers().getArray()[0]); var found = false; for(var i = 0; i < mapService.map.getLayers().getArray().length; i++) { if(mapService.editLayer == mapService.map.getLayers().getArray()[i]) { found = true; } } expect(found).toBe(true); }); it('should call mapService.addDraw if the layer geometry is homogenous', function() { spyOn(mapService,'addDraw'); featureMgrService.startFeatureInsert(mapService.map.getLayers().getArray()[0]); expect(mapService.addDraw).toHaveBeenCalled(); }); it('should show a dialog with different geometry types to draw if the layer geometry is NOT homogenous', function() { spyOn($.fn,'modal'); mapService.map.getLayers().getArray()[0].values_.metadata.schema = {geom: {_name:'geom', _type:'gml:GeometryPropertyType' } }; featureMgrService.startFeatureInsert(mapService.map.getLayers().getArray()[0]); expect($.fn.modal).toHaveBeenCalled(); }); it('should broadcast to other components that startFeatureInsert has been called', function() { spyOn(rootScope, '$broadcast'); featureMgrService.startFeatureInsert(mapService.map.getLayers().getArray()[0]); expect(rootScope.$broadcast).toHaveBeenCalledWith('startFeatureInsert'); }); }); describe('endFeatureInsert', function() { beforeEach(function() { defer = q.defer(); defer.resolve(); mapService.loadLayers(); rootScope.$apply(); }); it('should re-enable double-click zoom interaction on the map', function() { featureMgrService.endFeatureInsert(); expect(mapService.map.interactions_.array_[1].values_.active).toBe(true); }); describe('(save = true)', function() { beforeEach(function() { //spy on this service to stub the call without the actual implementation being called spyOn(mapService, 'addToEditLayer'); //spyOn so we can return the value we want spyOn(featureMgrService, 'getSelectedItemLayer').and.returnValue({layer:mapService.map.getLayers().array_[0]}); //fudge some data for the various calls so we can make it all the way through, //note that the value of geometry coordinates in the following line affects test outcomes //also note that selectedItem_ (in the service) will be mapService.map.getLayers().array_[0] mapService.map.getLayers().array_[0].properties = 1; mapService.map.getLayers().array_[0].geometry = {coordinates:[55,55]}; mapService.editLayer.getSource().featuresCollection_ = new ol.Collection(); var feature1 = new ol.Feature({ geometry: new ol.geom.Point([90, 45]), labelPoint: new ol.geom.Point([90, 45]), name: 'My Polygon' }); mapService.editLayer.getSource().featuresCollection_.push(feature1); var feature = new ol.Feature({ geometry: new ol.geom.Point([90, 45]), labelPoint: new ol.geom.Point([90, 45]), name: 'My Polygon' }); mapService.editLayer.getSource().addFeature(feature); //call show to initialize some internal private vars to the service featureMgrService.show(mapService.map.getLayers().array_[0]); }); describe('coordinates of the feature (selectedItem_) are identical to the one\'s provided to the method', function() { it('should add the geometry of the feature to the map\'s edit layer', function () { //todo mock this in the object itself and remove the method from the feature service //something like this - mapService.map.getLayers().array_[0].values_.metadata.schema = [{0: 'evento'}, {0: 'situacion_crit'}]; var props = [{0: 'evento'}, {0: 'situacion_crit'}]; featureMgrService.setSelectedItemProperties(props); featureMgrService.endFeatureInsert(true, props, [55, 55]); expect(mapService.addToEditLayer).toHaveBeenCalled(); expect(mapService.addToEditLayer.calls.mostRecent().args[0]).toBe(mapService.map.getLayers().array_[0].geometry); expect(mapService.addToEditLayer.calls.count()).toBe(2); }); it('should issue a WFS post message with the updated attribute and geometry data', function() { //add some data to ensure http request indludes the values mapService.map.getLayers().array_[0].values_.metadata.nativeName = 'freedom'; mapService.map.getLayers().array_[0].values_.metadata.name = 'map:sixpoint'; //intercept the http request and hold onto the url and data for validity checks below var wfsURL; var wfsData; httpBackend.when('POST').respond(function(method, url, data, headers, params){ wfsData = data; wfsURL = url; return {'status': 200}; }); var props = [{0: 'evento'}, {0: 'situacion_crit'}]; featureMgrService.setSelectedItemProperties(props); featureMgrService.endFeatureInsert(true, props, [55, 55]); httpBackend.flush(); httpBackend.expectPOST(); expect(wfsURL.indexOf('wfs')).not.toBe(-1); expect(wfsData.indexOf('wfs')).not.toBe(-1); expect(wfsData.indexOf('Insert')).not.toBe(-1); expect(wfsData.indexOf('sixpoint')).not.toBe(-1); expect(wfsData.indexOf('freedom')).not.toBe(-1); }); }); describe('coordinates of the feature (selectedItem_) are NOT identical to the one\'s provided to the method', function() { var origGeomCoords; var newGeomCoords; beforeEach(function() { origGeomCoords = mapService.editLayer.getSource().getFeatures()[0].getGeometry().getCoordinates(); spyOn(mapService.map.getView(),'setCenter'); //todo mock this in the object itself and remove the method from the feature service //something like this - mapService.map.getLayers().array_[0].values_.metadata.schema = [{0: 'evento'}, {0: 'situacion_crit'}]; var props = [{0: 'evento'}, {0: 'situacion_crit'}]; featureMgrService.setSelectedItemProperties(props); //call the actual method to test featureMgrService.endFeatureInsert(true, props, [0, 0]); //keep track of the coordinates to see if the method made any changes to them newGeomCoords = mapService.editLayer.getSource().getFeatures()[0].getGeometry().getCoordinates(); }); it('should NOT add the geometry of the feature to the map\'s edit layer', function () { expect(mapService.addToEditLayer.calls.count()).toBe(1); }); it('should update the feature in the edit layer i.e. transform it by the new coordinates',function() { expect(newGeomCoords).not.toBe(origGeomCoords); }); it('should pan the map to the new feature position', function() { expect(mapService.map.getView().setCenter).toHaveBeenCalledWith(newGeomCoords); }); }); }); describe('(save = false)', function() { beforeEach(function() { //spy on this service to stub the call without the actual implementation being called spyOn(mapService, 'addToEditLayer'); //spyOn so we can return the value we want spyOn(featureMgrService, 'getSelectedItemLayer').and.returnValue({layer:mapService.map.getLayers().array_[0]}); //fudge some data for the various calls so we can make it all the way through, //also note that selectedItem_ (in the service) will be mapService.map.getLayers().array_[0] mapService.map.getLayers().array_[0].properties = 1; mapService.map.getLayers().array_[0].geometry = {coordinates:[55,55]}; mapService.editLayer.getSource().featuresCollection_ = new ol.Collection(); var feature1 = new ol.Feature({ geometry: new ol.geom.Point([90, 45]), labelPoint: new ol.geom.Point([90, 45]), name: 'My Polygon' }); mapService.editLayer.getSource().featuresCollection_.push(feature1); var feature = new ol.Feature({ geometry: new ol.geom.Point([90, 45]), labelPoint: new ol.geom.Point([90, 45]), name: 'My Polygon' }); mapService.editLayer.getSource().addFeature(feature); //call show to initialize some internal private vars to the service featureMgrService.show(mapService.map.getLayers().array_[0]); }); it('should just call hide() on the service and stop displaying the pop-up', function() { spyOn(featureMgrService, 'hide'); featureMgrService.endFeatureInsert(false, null, [55, 55]); expect(featureMgrService.hide).toHaveBeenCalled(); }); }); }); describe('startGeometryEditing', function() { beforeEach(function() { spyOn(rootScope, '$broadcast'); spyOn(mapService,'addSelect'); spyOn(mapService, 'addModify'); spyOn(mapService,'selectFeature'); spyOn(exclusiveModeService,'startExclusiveMode'); mapService.map.layers = null; defer = q.defer(); defer.resolve(); mapService.loadLayers(); rootScope.$apply(); //fudge some data for the various calls so we can make it all the way through, mapService.editLayer.getSource().featuresCollection_ = new ol.Collection(); var feature = new ol.Feature({ geometry: new ol.geom.MultiPoint([[90, 45], [120,120]]), labelPoint: new ol.geom.Point([90, 45]), name: 'My Polygon' }); mapService.editLayer.getSource().featuresCollection_.push(feature); }); it('should broadcast to other components that startGeometryEditing has been called', function() { featureMgrService.getSelectedItem().geometry = {coordinates:[55,55], type:'point'}; featureMgrService.startGeometryEditing(); expect(rootScope.$broadcast).toHaveBeenCalledWith('startGeometryEdit'); }); it('should clear the edit layer and split the geometry into separate features for editing, if the geometry is \'multi\' type', function() { //get the array of coordinates for the multi type; var multiCoords = mapService.editLayer.getSource().getFeatures()[0].getGeometry().getCoordinates(); var numCoords = multiCoords.length; multiCoords =[multiCoords[numCoords-1]]; spyOn(window, 'transformGeometry'); spyOn(mapService.editLayer.getSource(), 'clear'); spyOn(mapService.editLayer.getSource(), 'addFeature'); featureMgrService.getSelectedItem().geometry = {coordinates:[55,55], type:'Multi'}; //call the actual method featureMgrService.startGeometryEditing(); expect(mapService.editLayer.getSource().clear).toHaveBeenCalled(); expect(window.transformGeometry.calls.mostRecent().args[0].type).toBe('Multi'); expect(window.transformGeometry.calls.mostRecent().args[0].coordinates).toEqual(multiCoords); expect(mapService.editLayer.getSource().addFeature).toHaveBeenCalled(); expect(mapService.editLayer.getSource().addFeature.calls.count()).toBe(numCoords); }); it('should clear the edit layer and split the geometry into separate features for editing, if the geometry is \'collection\' type', function() { //clear the edit layer ourselves and add a new feature comprised of multiple geometry (3 points) mapService.editLayer.getSource().featuresCollection_.clear(); var featureNew = new ol.Feature({ geometry: new ol.geom.GeometryCollection([new ol.geom.Point([90, 90]),new ol.geom.Point([66, 66]), new ol.geom.Point([45, 45])]), labelPoint: new ol.geom.Point([90, 45]), name: 'My Polygon' }); mapService.editLayer.getSource().featuresCollection_.push(featureNew); spyOn(window, 'transformGeometry'); spyOn(mapService.editLayer.getSource(), 'clear'); spyOn(mapService.editLayer.getSource(), 'addFeature'); featureMgrService.getSelectedItem().geometry = {coordinates:[55,55], type:'geometrycollection'}; //call the actual method featureMgrService.startGeometryEditing(); expect(mapService.editLayer.getSource().clear).toHaveBeenCalled(); expect(window.transformGeometry.calls.mostRecent().args[0].type).toBe('Point'); expect(window.transformGeometry.calls.mostRecent().args[0].coordinates).toEqual([45, 45]); expect(mapService.editLayer.getSource().addFeature).toHaveBeenCalled(); //expect the number of calls to be 3 because we are dealing with 3 points expect(mapService.editLayer.getSource().addFeature.calls.count()).toBe(3); }); it('should start the exclusive mode with \'editing_geometry\' as the main parameter', function() { featureMgrService.getSelectedItem().geometry = {coordinates:[55,55], type:'point'}; featureMgrService.startGeometryEditing(); expect(exclusiveModeService.startExclusiveMode.calls.mostRecent().args[0]).toBe(translateService.instant('editing_geometry')); }); it('should call mapService.addSelect', function() { featureMgrService.getSelectedItem().geometry = {coordinates:[55,55], type:'point'}; featureMgrService.startGeometryEditing(); expect(mapService.addSelect).toHaveBeenCalled(); }); it('should call mapService.addModify', function() { featureMgrService.getSelectedItem().geometry = {coordinates:[55,55], type:'point'}; featureMgrService.startGeometryEditing(); expect(mapService.addModify).toHaveBeenCalled(); }); it('should call mapService.selectFeature', function() { featureMgrService.getSelectedItem().geometry = {coordinates:[55,55], type:'point'}; featureMgrService.startGeometryEditing(); expect(mapService.selectFeature).toHaveBeenCalled(); }); }); describe('endGeometryEditing', function() { beforeEach(function() { spyOn(rootScope, '$broadcast'); spyOn(window,'transformGeometry').and.callThrough(); spyOn(mapService.editLayer.getSource(),'addFeature'); mapService.map.layers = null; defer = q.defer(); defer.resolve(); mapService.loadLayers(); rootScope.$apply(); //fudge some data for the various calls so we can make it all the way through, mapService.editLayer.getSource().featuresCollection_ = new ol.Collection(); var feature = new ol.Feature({ geometry: new ol.geom.MultiPoint([[90, 45], [120,120]]), labelPoint: new ol.geom.Point([90, 45]), name: 'My Polygon' }); mapService.editLayer.getSource().featuresCollection_.push(feature); }); describe('(save = true)', function() { describe('selectedItem_ geoemtry is a \'multi\' type such as ol.geom.MultiPoint etc', function() { beforeEach(function() { //trick the selectedItem_ into thinking it is a 'multi' type featureMgrService.getSelectedItem().geometry = {type:'MultiPoint'}; //add 3 separate features to the edit layer that will be merged together mapService.editLayer.getSource().featuresCollection_ = new ol.Collection(); for(var i = 0; i < 3; i++) { var feature = new ol.Feature({ geometry: new ol.geom.MultiPoint([[i*10, i*10]]), name: 'MyPoint'+i }); mapService.editLayer.getSource().featuresCollection_.push(feature); } //call the actual method featureMgrService.endGeometryEditing(true); }); it('should merge the separate coordinates/features from mapService.editLayer into one feature/geometry', function() { //make sure the merged coordinates match the separate ones we added earlier var mergedCoords = mapService.editLayer.getSource().addFeature.calls.mostRecent().args[0].getGeometry().getCoordinates(); expect(mergedCoords[0]).toEqual([0,0]); expect(mergedCoords[1]).toEqual([10,10]); expect(mergedCoords[2]).toEqual([20,20]); }); it('should call the global method transformGeometry with the separate coordinates to be merged', function() { //ensure transformGeometry was called with the correct parameters matching the data we cooked up var mergedCoords = mapService.editLayer.getSource().addFeature.calls.mostRecent().args[0].getGeometry().getCoordinates(); expect(window.transformGeometry.calls.mostRecent().args[0].type).toBe('MultiPoint'); expect(window.transformGeometry.calls.mostRecent().args[0].coordinates).toEqual(mergedCoords); }); it('should issue a WFS post message with the \'update\' parameter and updated feature', function () { var wfsData, wfsURL; httpBackend.when('POST').respond(function(method, url, data, headers, params){ wfsData = data; wfsURL = url; return {'status': 200}; }); httpBackend.flush(); httpBackend.expectPOST(); //ensure all of our cooked up coordinates made it into the xml data expect(wfsData.indexOf('0,0')).not.toBe(-1); expect(wfsData.indexOf('10,10')).not.toBe(-1); expect(wfsData.indexOf('20,20')).not.toBe(-1); //ensure that the feature type makes it into the xml as well expect(wfsData.indexOf('MultiPoint')).not.toBe(-1); }); }); describe('selectedItem_ geoemtry is a \'collection\' type (ol.geom.GeometryCollection)', function() { beforeEach(function() { //trick the selectedItem_ into thinking it is a 'geometrycollection' type featureMgrService.getSelectedItem().geometry = {type: 'GeometryCollection'}; //add 3 separate features to the edit layer that will be merged together mapService.editLayer.getSource().featuresCollection_ = new ol.Collection(); for (var i = 0; i < 3; i++) { var feature = new ol.Feature({ geometry: new ol.geom.Point([i * 10, i * 10]), name: 'MyPoint' + i }); mapService.editLayer.getSource().featuresCollection_.push(feature); } //call the actual method featureMgrService.endGeometryEditing(true); }); it('should merge the separate geometries into a single feature, if the selectedItem type is a geometry \'collection\'', function () { //make sure the merged geometry coordinates match the coords from the separate features/geoms var mergedGeoms = mapService.editLayer.getSource().addFeature.calls.mostRecent().args[0].getGeometry().getGeometries(); expect(mergedGeoms[0].getCoordinates()).toEqual([0, 0]); expect(mergedGeoms[1].getCoordinates()).toEqual([10, 10]); expect(mergedGeoms[2].getCoordinates()).toEqual([20, 20]); }); it('should call the global method transformGeometry with the separate geometries passed in the \'coordinates\' property', function() { //ensure transformGeometry was called with the correct parameters matching the data we cooked up expect(window.transformGeometry.calls.mostRecent().args[0].type).toBe('multigeometry'); var mergedGeoms = mapService.editLayer.getSource().addFeature.calls.mostRecent().args[0].getGeometry().getGeometries(); //note that the coordinates property passed to the method is actually an ol.geometry object expect(window.transformGeometry.calls.mostRecent().args[0].coordinates[0].getCoordinates()).toEqual(mergedGeoms[0].getCoordinates()); expect(window.transformGeometry.calls.mostRecent().args[0].coordinates[1].getCoordinates()).toEqual(mergedGeoms[1].getCoordinates()); expect(window.transformGeometry.calls.mostRecent().args[0].coordinates[2].getCoordinates()).toEqual(mergedGeoms[2].getCoordinates()); }); it('should issue a WFS post message with the \'update\' parameter and updated feature', function () { var wfsData, wfsURL; httpBackend.when('POST').respond(function(method, url, data, headers, params){ wfsData = data; wfsURL = url; return {'status': 200}; }); httpBackend.flush(); httpBackend.expectPOST(); //ensure all of our cooked up coordinates made it into the xml data expect(wfsData.indexOf('0,0')).not.toBe(-1); expect(wfsData.indexOf('10,10')).not.toBe(-1); expect(wfsData.indexOf('20,20')).not.toBe(-1); //ensure that the feature type makes it into the xml as well expect(wfsData.indexOf('MultiGeometry')).not.toBe(-1); }); }); }); describe('(save = false)', function() { beforeEach(function() { spyOn(mapService, 'clearEditLayer'); spyOn(mapService, 'addToEditLayer'); //call the actual method featureMgrService.endGeometryEditing(false); }); it('should clear mapService.editLayer', function() { expect(mapService.clearEditLayer).toHaveBeenCalled(); }); it('should add the selectedItem_ geometry back to the mapService.editLayer', function() { expect(mapService.addToEditLayer).toHaveBeenCalled(); expect(mapService.addToEditLayer.calls.mostRecent().args[0]).toBe(featureMgrService.getSelectedItem().geometry); }); it('should NOT issue a WFS post message', function() { httpBackend.verifyNoOutstandingRequest(); }); }); }); });
function eventline() { // Default values for each of the plot's properties. // These may be retrieved/modified via the getters/setters // at the end of this file. // An object specifying the margins around the plot. // Must contain values for 'top', 'right', 'bottom', 'left'. var margin = {top: 10, right: 10, bottom: 10, left: 10}, // The width of the plot (including margins), in pixels. width = 750, // The height of each individual eventline (and the contained events), // in pixels. eventHeight = 20, // The functions used to retrieve the start and end dates of each // event object. eventStart = function(d) { return d.start; }, eventEnd = function(d) { return d.end; }, // The margin between the stacked eventlines, in pixels. bandMargin = 5, // The domain of the plot (the x-axis) as a two-element array of Dates, // the 0th element being the start date of the domain, and the 1st element // being the end date. domain = [ new Date(2012, 0, 1, 0, 0, 0, 0), new Date(2012, 11, 31, 23, 59, 59, 999) ], // An object containing the arguments to be passed to the D3 axis generation. // See https://github.com/mbostock/d3/wiki/SVG-Axes for possible parameters. axisArgs = { "labelFormat": "%b", "tickSize": d3.time.month, "tickInterval": 1 }, // The amount of horizontal space to provide for the y-axis labels before // they are truncated. labelMargin = 50; function chart(selection) { selection.each(function (data) { var axisH = 30; var height = (margin.top + data.length * (eventHeight + bandMargin) - bandMargin + margin.bottom + axisH); var bandWidth = (width - margin.left - labelMargin - margin.right); var xScale = d3.time.scale() .domain(domain) .range([0, bandWidth]); // We bind to an array containing this set of data so that we have at // most one SVG that needs creation. var svg = d3.select(this).selectAll("svg").data([data]); var svgEnter = svg.enter().append("svg") .attr("width", width) .attr("height", height) var bg = svgEnter.append("rect") .attr("width", width) .attr("height", height) .attr("class", "background"); // This will contain all of our "bands" of events (the individual eventlines) var stack = svg.append("g") .attr("transform", "translate(" + (margin.left + labelMargin) + "," + margin.top + ")"); var bands = stack.selectAll("g").data(data); var axisGen = d3.svg.axis().scale(xScale) .orient("bottom") .tickFormat(d3.time.format(axisArgs.labelFormat)) .ticks(axisArgs.tickSize, axisArgs.tickInterval) .innerTickSize(height - 40) .outerTickSize(height - 40); var axis = stack.append("g") .attr("class", "axis") .call(axisGen); // Position axis labels between tick marks axis.selectAll(".axis text") .attr("x", function(d) { return (width / (xScale.ticks( axisArgs.tickSize, axisArgs.tickInterval).length * 2)); }); var bandEnter = bands.enter().append("g") .attr("transform", function(d, i) { return "translate(0, " + (i * (eventHeight + bandMargin)) + ")"; }); // Labels come first to place them below the grid bandEnter.append("text") .attr("class", "label") .attr("x", -1 * labelMargin) .attr("y", eventHeight / 2) .text(function(d) { return d.label; }); // Draw the outline "grid" around each new band bandEnter.append("rect") .attr("class", "grid") .attr("width", bandWidth) .attr("height", eventHeight) .attr("x", 0) .attr("y", 0); bandEnter.append("g"); // these groups will hold our events var events = bands.selectAll("g").selectAll("rect") .data(function(d) { return d.events; }); var eventEnter = events.enter().append("rect") .attr("class", "event") .attr("x", function(d) { return xScale(d.start); }) .attr("y", 0) .attr("width", function(d) { return xScale(d.end) - xScale(d.start); }) .attr("height", eventHeight) .on("mouseover", function(d) { d3.select(this.parentNode).selectAll(".event").sort(function(a, b) { if (a != d) { return -1; } else { return 1; } }); d3.select(this).classed("focus", true); }) .on("mouseout", function() { d3.select(this).classed("focus", false); }); }); } chart.margin = function (val) { if (!arguments.length) return margin; margin = val; return chart; }; chart.width = function (val) { if (!arguments.length) return width; width = val; return chart; }; chart.eventHeight = function (val) { if (!arguments.length) return eventHeight; eventHeight = val; return chart; }; chart.eventStart = function (val) { if (!arguments.length) return eventStart; eventStart = val; return chart; }; chart.eventEnd = function (val) { if (!arguments.length) return eventEnd; eventEnd = val; return chart; }; chart.bandMargin = function (val) { if (!arguments.length) return bandMargin; bandMargin = val; return chart; }; chart.domain = function (val) { if (!arguments.length) return domain; domain = val; return chart; }; chart.axisArgs = function (val) { if (!arguments.length) return axisArgs; axisArgs = val; return chart; }; chart.labelMargin = function (val) { if (!arguments.length) return labelMargin; labelMargin = val; return chart; }; return chart; }
/*! * numbro.js language configuration * language : German * locale: Liechtenstein * author : Michael Piefel : https://github.com/piefel (based on work from Marco Krage : https://github.com/sinky) */ (function () { 'use strict'; var language = { langLocaleCode: 'de-LI', cultureCode: 'de-LI', delimiters: { thousands: '\'', decimal: '.' }, abbreviations: { thousand: 'k', million: 'm', billion: 'b', trillion: 't' }, ordinal: function () { return '.'; }, currency: { symbol: 'CHF', position: 'postfix', code: 'CHF' }, defaults: { currencyFormat: ',4 a' }, formats: { fourDigits: '4 a', fullWithTwoDecimals: ',0.00 $', fullWithTwoDecimalsNoCurrency: ',0.00', fullWithNoDecimals: ',0 $' } }; // CommonJS if (typeof module !== 'undefined' && module.exports) { module.exports = language; } // Browser if (typeof window !== 'undefined' && window.numbro && window.numbro.culture) { window.numbro.culture(language.cultureCode, language); } }.call(typeof window === 'undefined' ? this : window));
const symbols = require('../symbols'); const createToken = require('../create-token'); const cleanToken = require('./clean'); let depthPointer = 0; const addTokenToExprTree = (ast, token) => { let level = ast; for (let i = 0; i < depthPointer; i++) { //set the level to the rightmost deepest branch level = level[level.length - 1]; } level.push(token); }; const popExpr = () => depthPointer--; const pushExpr = (ast) => { addTokenToExprTree(ast, []); depthPointer++; }; module.exports = (_tokens) => { // Reset depth pointer depthPointer = 0; const tokens = _tokens .map(t => Object.assign({}, t)) .map(cleanToken); let ast = []; for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; if (token.type === symbols.LPAREN) { pushExpr(ast); continue; } else if (token.type === symbols.RPAREN) { popExpr(); continue; } addTokenToExprTree(ast, token); } return ast; };
'use strict'; var CongestReset = Symbol( ); function implementation( Promise ) { function defer( ) { var obj = { }; obj.promise = new Promise( ( resolve, reject ) => { obj.resolve = resolve; obj.reject = reject; } ); return obj; } function promise_try( fn, args ) { args = args || [ ]; return new Promise( ( resolve, reject ) => { try { Promise.resolve( fn( ...args ) ) .then( resolve, reject ); } catch ( err ) { reject( err ); } } ); } function _finally( fn ) { return { success: function( val ) { return promise_try( fn ) .then( _ => val ); }, fail: function( err ) { return promise_try( fn ) .then( _ => { throw err; } ); } }; } function forward( defer ) { return { success: function( val ) { defer.resolve( val ); return val; }, fail: function( err ) { defer.reject( err ); throw err; } }; } class CongestItem { constructor( value ) { this.value = value; this.defer = defer( ); } } class Congest { constructor( canceler ) { this._canceler = canceler || function( ) { }; this._backlog = [ ]; this._canceled = false; this._next = null; this[ CongestReset ]( ); } /** * Push data to this iterator. * * Will return a promise which will be forwarded the result from the * consume function once it has gotten this particular value. This * applies to both if the consume function returned a value or threw * an exception. * * If 'this' is cancelled with 'immediate', values might get thrown * away. If the data to this function is thrown away, the returned * promise is rejected with an Error object with the data in the * property 'value'. * * If this.hasCanceled( ), the returned promise is rejected. * * @return P{Mixed} */ push( data ) { if ( this._canceled ) return Promise.reject( new Error( "The congest instance has canceled" ) ); var item = new CongestItem( data ); this._backlog.push( item ); this._next.resolve( ); return item.defer.promise; } /** * @return Boolean */ hasCanceled( ) { return this._canceled; } /** * Register a function which will consume all iterator values. * * If fn throws or returns a promise with an error, the iteration * ends, cancel is called (with immediate as true). This means values * can be lost. If this is not preferred, you must make sure fn does * not fail. * * NOTE; The returned promise from this function is resolve when * iteration has ended. * * @return P{void || first error from (fn)} */ consume( fn ) { var self = this; return new Promise( ( resolve, reject ) => { function recurse( ) { var scheduleRecurse = _ => setImmediate( recurse ); function success( ) { if ( self._backlog.length === 0 ) { if ( self._canceled ) return resolve( ); else { self[ CongestReset ]( ); return scheduleRecurse( ); } } var fin = _finally( scheduleRecurse ); var worker = self._backlog.shift( ); var forwardPush = forward( worker.defer ); self._next.promise = promise_try( fn, [ worker.value ] ) .then( forwardPush.success, forwardPush.fail ) .then( fin.success, fin.fail ); } function fail( err ) { var fin = _finally( _ => { reject( err ); } ); var cancel = self.cancel.bind( self ); return promise_try( cancel, [ true ] ) .then( fin.success, fin.fail ) .catch( err => { console.error( "[prevents] consume function threw " + "exception, followed by the canceler " + "throwing:", err.stack ); } ); } self._next.promise .then( success, fail ); } recurse( ); } ); } /** * Cancels the iterator, will tell upstream to cancel by calling the * canceler function. The return value of the canceler function will * eventually be returned by this function. * * If immediate is truthy, the backlog of values, and potential values * being pushed while canceling will be ignore and lost. * If immediate is falsy (default), all values will be awaited and * iterated. * * @return P{return_type<canceler>} */ cancel( immediate ) { if ( immediate ) { // Throw away the backlog, but first, reject all their // promises. this._backlog.forEach( item => { var err = new Error( "Congest item was thrown away" ); err.value = item.value; item.defer.reject( err ); } ); this._backlog.length = 0; this._canceled = true; return promise_try( this._canceler ); } else { var fin = _finally( _ => { this._canceled = true; } ); return promise_try( this._canceler ) .then( fin.success, fin.fail ); } } } Congest.prototype[ CongestReset ] = function( ) { this._next = defer( ); } Congest.using = Promise => implementation( Promise ); return Congest; } module.exports = implementation( Promise );
var app = require('./app'); var config = require('config'); var util = require('util'); module.exports = app.listen(process.env.PORT || config.port || 3000, function() { util.log('Server started: http://%s:%s/', this.address().address, this.address().port); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _api = require('./api'); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var details = function details(result) { if (result.length === 0) { return noResults; } var item = result[0]; var eta = (0, _moment2.default)().add(item.etaSec, 'seconds'); return { "attachments": [{ "color": item.percentProgressMils === 1000 ? "good" : "#439FE0", // "pretext": "Torrents list", "title": item.name, "text": ':slack: ' + item.hash.toLowerCase(), "fields": [{ "title": "Status", "value": item.status + ' (' + progress(item) + '%)', "short": true }, { "title": "Size", "value": humanFileSize(item.size), "short": true }, { "title": "Downloaded", "value": humanFileSize(item.downloadedBytes), "short": true }, { "title": "Uploaded", "value": humanFileSize(item.uploadedBytes), "short": true }, { "title": "Seeds", "value": item.seedsConnected + ' / ' + item.seedsSwarm, "short": true }, { "title": "Peers", "value": item.peersConnected + ' / ' + item.peersSwarm, "short": true }, { "title": "ETA", "value": '' + (item.etaSec > 0 ? (0, _moment2.default)().to(eta) : '--'), "short": true }] }] }; }; function humanFileSize(bytes) { var si = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var thresh = si ? 1000 : 1024; if (Math.abs(bytes) < thresh) { return bytes + ' B'; } var units = si ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; var u = -1; do { bytes /= thresh; ++u; } while (Math.abs(bytes) >= thresh && u < units.length - 1); return bytes.toFixed(1) + ' ' + units[u]; } var progress = function progress(item) { return Math.round(item.percentProgressMils / 10, 2); }; var torrent = function torrent(item) { return progress(item) + '% *' + item.name + '*\n\t:slack: ' + item.hash; }; var statusColor = function statusColor(status) { switch (status.toLowerCase()) { case 'stopped': return 'danger'; case 'finished': return 'good'; case 'queued': return 'warning'; case 'downloading': return '#439FE0'; default: return 'warning'; } }; var noResults = 'mmm :thinking_face: no results'; var list = function list(result) { if (result.length === 0) { return noResults; } return { "attachments": result.map(function (item) { return { "fallback": "Torrents list:", "color": statusColor(item.status), "author_name": item.status + ' (' + progress(item) + '%)', "title": item.name, "text": ':slack: ' + item.hash.toLowerCase().substring(0, 8) }; }).slice(0, 50) }; }; var showParams = function showParams(params) { return Object.keys(params).map(function (param) { return !params[param].required ? '[' + param + ']' : param; }).join(' '); }; var paramsDescription = function paramsDescription(params) { return Object.keys(params).map(function (param) { return ' _' + param + ': ' + params[param].description + '_'; }).join('\n'); }; var showAliases = function showAliases(aliases) { return '\n Alias: ' + aliases.map(function (alias) { return '*' + alias + '*'; }).join(', '); }; var help = function help(_) { return Object.keys(_api.commands).map(function (command) { return '*' + command + '* ' + showParams(_api.commands[command].params) + '\n _' + _api.commands[command].description + '_' + (_api.commands[command].hasOwnProperty('alias') ? showAliases(_api.commands[command].alias) : '') + '\n Arguments:\n' + paramsDescription(_api.commands[command].params) + '\n'; }).join('\n'); }; var error = function error(err) { return { "attachments": [{ "fallback": "Error!", "color": "danger", // "author_name": ":fire::fire::fire::fire::fire::fire::fire::fire:", "title": ':fire: ' + err.error.message + ' :fire:', "text": err.type !== 'api' ? "Run \"help\" to get more info" : '' }] }; }; var files = function files(result) { return { "attachments": result.map(function (item) { return { "fallback": "Torrent files:", "color": statusColor(item.fileSize > item.downloadedSize ? 'downloading' : 'finished'), "author_name": item.fileName, // "text": `:slack: ${item.hash.toLowerCase().substring(0, 8)}` "fields": [{ "title": "Size", "value": humanFileSize(item.fileSize), "short": true }, { "title": "Downloaded", "value": humanFileSize(item.downloadedSize), "short": true }] }; }).slice(0, 50) }; }; var helpMessage = help(); var commandsMap = { error: error, list: list, files: files, details: details, start: list, stop: list, help: function help(_) { return helpMessage; } }; var messages = function messages(command, result) { if (!commandsMap.hasOwnProperty(command)) { return 'Done :white_check_mark:'; } return commandsMap[command](result); }; exports.default = messages;
"use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var fs = require('fs'), helper = require('./helper.js'), REPORT_FILE = './reports/report.json', RETRY_STR = '_RETRY_'; /** * Helper class responsible for the report file manipulation */ var ReportCreator = function () { function ReportCreator() { _classCallCheck(this, ReportCreator); } _createClass(ReportCreator, null, [{ key: 'init', /** * Creates the folder structure for the final report file and initiates the final report. * @param reportFile The name (with path) of the final report file */ value: function init(reportFile) { helper.createFolderStructure(REPORT_FILE); REPORT_FILE = reportFile; this.writeReport('['); } /** * Overwrites the final report file with the provided parameter * @param content The content to be written into the file */ }, { key: 'writeReport', value: function writeReport(content) { try { fs.writeFileSync(REPORT_FILE, content); } catch (ex) { console.error("There was an exception during the creation of report file: " + ex); } } }, { key: 'extendReport', /** * Extends the final report with the report got in parameter * @param pathToReport Path of the report to add to the final one */ value: function extendReport(pathToReport) { var finalReport = JSON.parse(fs.readFileSync(REPORT_FILE, 'utf8') + ']'), actualReport = JSON.parse(fs.readFileSync(pathToReport, 'utf8'))[0], needToAdd = true; if (finalReport.length == 0) { finalReport.push(actualReport); } else { if (pathToReport.indexOf(RETRY_STR) != -1) { actualReport.name = actualReport.name + RETRY_STR + helper.getRetryCountFromPath(pathToReport); actualReport.id = actualReport.id + RETRY_STR + helper.getRetryCountFromPath(pathToReport); } finalReport.map(function (existingReport) { if (existingReport.id + existingReport.line == actualReport.id + actualReport.line) { existingReport.elements.push(actualReport.elements[0]); needToAdd = false; } }); if (needToAdd) { finalReport.push(actualReport); } } this.writeReport(JSON.stringify(finalReport).slice(0, -1)); } }, { key: 'finalizeReport', /** * Adds the closing parentheses to the report so that it's finished and processable. */ value: function finalizeReport() { this.writeReport(fs.readFileSync(REPORT_FILE, 'utf8') + ']'); } }]); return ReportCreator; }(); module.exports = ReportCreator;
const {ipcRenderer} = require('electron') const printPDFBtn = document.getElementById('print-pdf') printPDFBtn.addEventListener('click', (event) => { ipcRenderer.send('print-to-pdf') }) ipcRenderer.on('wrote-pdf', (event, path) => { const message = `Wrote PDF to: ${path}` document.getElementById('pdf-path').innerHTML = message })
import React, { Component } from 'react'; import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css'; import './App.css'; import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink, Container, Row, Col, Jumbotron, Button } from 'reactstrap'; class App extends Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { message: null, isOpen: false, fetching: true }; } componentDidMount() { fetch('/api') .then(response => { if (!response.ok) { throw new Error(`status ${response.status}`); } console.log(response) return response.json(); }) .then(json => { this.setState({ message: json.message, fetching: false }); }).catch(e => { this.setState({ message: `API call failed: ${e}`, fetching: false }); }) } toggle() { this.setState({ isOpen: !this.state.isOpen }); } render() { return ( <div> <Navbar color="inverse" light expand="md"> <NavbarBrand href="/">reactstrap</NavbarBrand> <NavbarToggler onClick={this.toggle} /> <Collapse isOpen={this.state.isOpen} navbar> <Nav className="ml-auto" navbar> <NavItem> <NavLink href="/components/">Components</NavLink> </NavItem> <NavItem> <NavLink href="https://github.com/reactstrap/reactstrap">Github</NavLink> </NavItem> </Nav> </Collapse> </Navbar> <Jumbotron> <Container> <Row> <Col> <h1>Welcome to React</h1> <p> <Button tag="a" color="success" size="large" href="http://reactstrap.github.io" target="_blank" > View Reactstrap Docs </Button> </p> </Col> </Row> </Container> </Jumbotron> <p className="App-intro"> {this.state.fetching ? 'Fetching message from API' : this.state.message} </p> </div> ); } } export default App;
'use strict'; const _ = require('lodash'); const moment = require('moment-timezone'); const inherits = require('../../utils/inherits'); module.exports = BaseTypes => { BaseTypes.ABSTRACT.prototype.dialectTypes = 'https://mariadb.com/kb/en/library/resultset/#field-types'; /** * types: [buffer_type, ...] * @see documentation : https://mariadb.com/kb/en/library/resultset/#field-types * @see connector implementation : https://github.com/MariaDB/mariadb-connector-nodejs/blob/master/lib/const/field-type.js */ BaseTypes.DATE.types.mariadb = ['DATETIME']; BaseTypes.STRING.types.mariadb = ['VAR_STRING']; BaseTypes.CHAR.types.mariadb = ['STRING']; BaseTypes.TEXT.types.mariadb = ['BLOB']; BaseTypes.TINYINT.types.mariadb = ['TINY']; BaseTypes.SMALLINT.types.mariadb = ['SHORT']; BaseTypes.MEDIUMINT.types.mariadb = ['INT24']; BaseTypes.INTEGER.types.mariadb = ['LONG']; BaseTypes.BIGINT.types.mariadb = ['LONGLONG']; BaseTypes.FLOAT.types.mariadb = ['FLOAT']; BaseTypes.TIME.types.mariadb = ['TIME']; BaseTypes.DATEONLY.types.mariadb = ['DATE']; BaseTypes.BOOLEAN.types.mariadb = ['TINY']; BaseTypes.BLOB.types.mariadb = ['TINYBLOB', 'BLOB', 'LONGBLOB']; BaseTypes.DECIMAL.types.mariadb = ['NEWDECIMAL']; BaseTypes.UUID.types.mariadb = false; BaseTypes.ENUM.types.mariadb = false; BaseTypes.REAL.types.mariadb = ['DOUBLE']; BaseTypes.DOUBLE.types.mariadb = ['DOUBLE']; BaseTypes.GEOMETRY.types.mariadb = ['GEOMETRY']; BaseTypes.JSON.types.mariadb = ['JSON']; function DECIMAL(precision, scale) { if (!(this instanceof DECIMAL)) { return new DECIMAL(precision, scale); } BaseTypes.DECIMAL.apply(this, arguments); } inherits(DECIMAL, BaseTypes.DECIMAL); DECIMAL.prototype.toSql = function toSql() { let definition = BaseTypes.DECIMAL.prototype.toSql.apply(this); if (this._unsigned) { definition += ' UNSIGNED'; } if (this._zerofill) { definition += ' ZEROFILL'; } return definition; }; function DATE(length) { if (!(this instanceof DATE)) { return new DATE(length); } BaseTypes.DATE.apply(this, arguments); } inherits(DATE, BaseTypes.DATE); DATE.prototype.toSql = function toSql() { return `DATETIME${this._length ? `(${this._length})` : ''}`; }; DATE.prototype._stringify = function _stringify(date, options) { date = BaseTypes.DATE.prototype._applyTimezone(date, options); return date.format('YYYY-MM-DD HH:mm:ss.SSS'); }; DATE.parse = function parse(value, options) { value = value.string(); if (value === null) { return value; } if (moment.tz.zone(options.timezone)) { value = moment.tz(value, options.timezone).toDate(); } else { value = new Date(`${value} ${options.timezone}`); } return value; }; function DATEONLY() { if (!(this instanceof DATEONLY)) { return new DATEONLY(); } BaseTypes.DATEONLY.apply(this, arguments); } inherits(DATEONLY, BaseTypes.DATEONLY); DATEONLY.parse = function parse(value) { return value.string(); }; function UUID() { if (!(this instanceof UUID)) { return new UUID(); } BaseTypes.UUID.apply(this, arguments); } inherits(UUID, BaseTypes.UUID); UUID.prototype.toSql = function toSql() { return 'CHAR(36) BINARY'; }; function GEOMETRY(type, srid) { if (!(this instanceof GEOMETRY)) { return new GEOMETRY(type, srid); } BaseTypes.GEOMETRY.apply(this, arguments); if (_.isEmpty(this.type)) { this.sqlType = this.key; } else { this.sqlType = this.type; } } inherits(GEOMETRY, BaseTypes.GEOMETRY); GEOMETRY.prototype.toSql = function toSql() { return this.sqlType; }; function ENUM() { if (!(this instanceof ENUM)) { const obj = Object.create(ENUM.prototype); ENUM.apply(obj, arguments); return obj; } BaseTypes.ENUM.apply(this, arguments); } inherits(ENUM, BaseTypes.ENUM); ENUM.prototype.toSql = function toSql(options) { return `ENUM(${this.values.map(value => options.escape(value)).join(', ')})`; }; function JSONTYPE() { if (!(this instanceof JSONTYPE)) { return new JSONTYPE(); } BaseTypes.JSON.apply(this, arguments); } inherits(JSONTYPE, BaseTypes.JSON); JSONTYPE.prototype._stringify = function _stringify(value, options) { return options.operation === 'where' && typeof value === 'string' ? value : JSON.stringify(value); }; const exports = { ENUM, DATE, DATEONLY, UUID, GEOMETRY, DECIMAL, JSON: JSONTYPE }; _.forIn(exports, (DataType, key) => { if (!DataType.key) { DataType.key = key; } if (!DataType.extend) { DataType.extend = function extend(oldType) { return new DataType(oldType.options); }; } }); return exports; };
var fs = require('fs') var moduleName = 'mnGroup' var controllerName = moduleName + 'Controller' var template = fs.readFileSync(__dirname + '/template.html') var directiveFn = function () { return { controller: controllerName, controllerAs: 'vm', bindToController: true, template: template, scope: { mnTournamentId: '=', mnGroupId: '=' } } } var dependencies = [require('../mn-players').name] module.exports = angular.module(moduleName, dependencies) .controller(controllerName, require('./controller')) .directive(moduleName, directiveFn)
var wallabify = require('wallabify'); var wallabyPostprocessor = wallabify({ // browserify options, such as // insertGlobals: false } // you may also pass an initializer function to chain other // browserify options, such as transformers // , b => b.exclude('mkdirp').transform(require('babelify')) ); module.exports = function () { return { // set `load: false` to all of the browserified source files and tests, // as they should not be loaded in browser, // their browserified versions will be loaded instead files: [ {pattern: 'index.js', load: false}, {pattern: 'isVoid.js', load: false}, {pattern: 'safe*.js', load: false} ], tests: [ {pattern: 'test/specs/*.spec.js', load: false}, {pattern: 'test/specs/deepCopy.js', load: false} ], postprocessor: wallabyPostprocessor, bootstrap: function () { // required to trigger tests loading window.__moduleBundler.loadTests(); } }; };
/* jshint node: true, esnext: true */ 'use strict'; var React = require('react'); var modes = require('js-git/lib/modes'); var BlobBox = require('./blob-box'); var TreeBox = React.createClass({ getInitialState : function () { return this._getState(); }, componentDidMount: function() { this.props.objects.onChange(this._onChange); this.props.display.onChange(this._onChange); }, componentWillUnmount: function() { this.props.objects.offChange(this._onChange); this.props.display.offChange(this._onChange); }, _onChange : function (counter) { // TODO triggers a warning when hiding a tree because replaceState is called even though component is unmounted this.replaceState(this._getState()); }, _getState : function () { var tree = this.props.objects.getObject(this.props.tree); if (!tree) { this.props.objectActions.requestObject(this.props.config.getStore(), 'tree', this.props.tree); } return { tree, details : this.props.display.getDisplayedChildren(this.props.path) }; }, render : function () { if (!this.state.tree || this.state.tree.loading) { return React.DOM.div(null, 'Loading...'); } return React.DOM.ul(null, Object.keys(this.state.tree.body).map(child => { var item = this.state.tree.body[child]; if (this.state.details.indexOf(child) >= 0) { var elem; if (item.mode === modes.file) { elem = React.createElement(BlobBox, { blob : item.hash }); } else if (item.mode === modes.tree) { elem = React.createElement(TreeBox, { objects : this.props.objects, config : this.props.config, objectActions : this.props.objectActions, display : this.props.display, dispatch : this.props.dispatch, tree : item.hash, path : this.props.path + '/' + child }); } else { throw new Error('Invalid mode: ' + item.mode); } return React.DOM.li({ key : child }, React.DOM.span({ onClick : this._hideChildren.bind(this, child) }, '- ' + child), elem); } else { return React.DOM.li({ key : child, onClick : this._displayChildren.bind(this, child) }, '+ ' + child); } })); }, _displayChildren : function (child) { this.props.dispatch({ action : 'PATH_DISPLAYED', path : this.props.path, child }); }, _hideChildren : function (child) { this.props.dispatch({ action : 'PATH_HIDDEN', path : this.props.path, child }); } }); module.exports = TreeBox;
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Kontakt Schema */ var KontaktSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Kontakt name', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Kontakt', KontaktSchema);
/* eslint-env mocha */ 'use strict' import { expect } from 'chai' import trumpet from 'trumpet' import fs from 'fs' import path from 'path' import { trumpetInnerText, trumpetClasses, trumpetAttr } from '../../../lib/html-parsers/index' describe('HTML parsers tools', () => { it('trumpetInnerText function delivers a function', () => { const f = trumpetInnerText(() => {}) expect(f).to.be.a.function }) it('trumpetInnerText delivers a stream parser that calls callback with inner text', (done) => { const f = trumpetInnerText((innerText) => { expect(innerText).to.equal('my text') done() }) const tr = trumpet() tr.select('#test1', f) fs.createReadStream(path.join(__dirname, 'mock.html')).pipe(tr) }) it('trumpetInnerText delivers a stream parser that calls callback with trimmed text', (done) => { const f = trumpetInnerText((innerText) => { expect(innerText).to.equal('my text') done() }) const tr = trumpet() tr.select('#test1b', f) fs.createReadStream(path.join(__dirname, 'mock.html')).pipe(tr) }) it('trumpetInnerText delivers a stream parser that never callback for wrong stream format', (done) => { const f = trumpetInnerText(() => { done('Failed, should not call callback!') }) const tr = trumpet() tr.select('#test1', f) fs.createReadStream(path.join(__dirname, 'mock.json')).pipe(tr) tr.on('end', done) }) it('trumpetClasses function delivers a function', () => { const f = trumpetClasses(() => {}) expect(f).to.be.a.function }) it('trumpetClasses delivers a function that calls callback with classes', (done) => { const f = trumpetClasses((classes) => { expect(classes).to.include('class_test_1') expect(classes).to.include('class_test_2') expect(classes).to.have.lengthOf(2) done() }) const tr = trumpet() tr.select('#test2', f) fs.createReadStream(path.join(__dirname, 'mock.html')).pipe(tr) }) it('trumpetAttr function delivers a function', () => { const f = trumpetAttr('id', () => {}) expect(f).to.be.a.function }) it('trumpetAttr delivers a function that calls callback with an attribute value', (done) => { const f = trumpetAttr('class', (classes) => { expect(classes).to.equal('class_test_1 class_test_2') done() }) const tr = trumpet() tr.select('#test2', f) fs.createReadStream(path.join(__dirname, 'mock.html')).pipe(tr) }) })
module.exports = function(grunt) { const DEST = 'lib/expaste.js'; const DEST_MIN = 'lib/expaste.min.js'; var pkg = grunt.file.readJSON('package.json'); grunt.initConfig({ pkg: pkg, meta: { banner: '/**\n' + ' * <%= pkg.name %> - v<%= pkg.version %>\n' + ' * update: <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * Author: <%= pkg.author %> [<%= pkg.website %>]\n' + ' * Github: <%= pkg.repository.url %>\n' + ' * License: Licensed under the <%= pkg.license %> License\n' + ' */' }, uglify: { dist: { options: { banner: '<%= meta.banner %>' + '\n' + '\n' + '', report: 'gzip', sourceMap: true }, src: [DEST], dest: DEST_MIN }, }, qunit: { all: [ 'test/*.html' ] } }); grunt.registerTask('default', [ 'uglify', 'qunit' ]); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-qunit'); };
"use strict"; function kotools() { var self = this; var today = new Date(); self.currentYear = today.getFullYear(); self.currentMonth = today.getMonth(); self.isEmpty = function (str) { return (!str || 0 === str.length); }; Date.prototype.toFormattedString = function () { var cDate = this.getDate(); var cMonth = this.getMonth() + 1; //Months are zero based var cYear = this.getFullYear(); return cDate + "/" + cMonth + "/" + cYear; }; Array.prototype.setOrAdd = function (x, y, value) { if (this[x] === null || this[x] === undefined) { this[x] = []; } if (this[x][y] === null || isNaN(this[x][y])){ this[x][y] = value; } else{ this[x][y] += value; } }; Array.prototype.set = function (x, y, value) { if (!this[x]){ this[x] = []; } this[x][y] = value; }; Date.prototype.addDays = function (days) { var dat = new Date(this.valueOf()); dat.setDate(dat.getDate() + days); return dat; }; self.getQuarter = function(item) { if (item.Year !== null && item.Quarter !== null) { return "Q" + item.Quarter + item.Year; } return null; }; self.paddy = function (n, p, c) { var pad_char = c !== 'undefined' ? c : '0'; var pad = [1 + p].join(pad_char); return (pad + n).slice(-pad.length); }; self.getMonth = function(item) { if (item.Year !== null && item.Month !== null) { return String(item.Year) + self.paddy(item.Month, 2).toString(); } return null; }; self.monthsComparer = function(item1, item2) { if (self.isString(item1)) { var year1 = parseInt(item1.substring(0, 4), 10); var month1 = parseInt(item1.substring(4, item1.length), 10); var year2 = parseInt(item2.substring(0, 4), 10); var month2 = parseInt(item2.substring(4, item2.length), 10); if (year1 === year2) { return d3.ascending(month1, month2); } return d3.ascending(year1, year2); } return d3.ascending(item1, item2); }; self.monthsIncrementer = function(item) { var year = parseInt(item.substring(0, 4), 10); var month = parseInt(item.substring(4, item.length), 10); if (month === 12) { month = 1; year++; } else { month++; } var yyyy = year.toString(); var mm = month.toString(); return yyyy + (mm[1] ? mm : "0" + mm[0]); }; self.quartersComparer = function(item1, item2) { var q1 = item1.substring(1, 2); var year1 = item1.substring(2, 6); var q2 = item2.substring(1, 2); var year2 = item2.substring(2, 6); if (year1 === year2) { return d3.ascending(q1, q2); } return d3.ascending(year1, year2); }; var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; self.getYearAndMonthLabel = function(i) { if (!self.isString(i)) { return ""; } var month = monthNames[parseInt(i.substring(4, i.length), 10) - 1]; return month; }; self.getProperty = function(key, d) { if (typeof key === "function") { return key(d); } return d[key]; }; self.getWidth = function(el) { if (el.clientWidth){ return el.clientWidth; } if (Array.isArray(el) && el.length > 0) { return self.getWidth(el[0]); } return null; }; self.getHeight = function(el) { if (el.clientHeight && el.clientHeight !== 0){ return el.clientHeight; } if (Array.isArray(el) && el.length > 0) { return self.getHeight(el[0]); } if (el.parentElement !== null) { return self.getHeight(el.parentElement); } return null; }; self.find = function(data, predicate) { var i = 0; for (i = 0; i < data.length; i++) { if (predicate(data[i])) { return data[i]; } } return null; }; self.isString = function(x) { return typeof x === 'string'; }; self.isNumber = function(n) { return !isNaN(parseFloat(n)) && isFinite(n); }; self.isValidNumber = function(n) { return n !== null && !isNaN(n); }; self.isDate = function(d) { return Object.prototype.toString.call(d) === "[object Date]"; }; Number.prototype.formatMoney = function(c, d, t) { var n = this; c = isNaN(c = Math.abs(c)) ? 2 : c; d = d === undefined ? "." : d; t = t === undefined ? "," : t; var s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + "", j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; self.parseDate = function(input) { if (input instanceof Date) { return input; } //first get rid of the hour & etc... var firstSpace = input.indexOf(" "); if (firstSpace !== -1) { input = input.substring(0, firstSpace); var separator = "/"; var parts = []; if (input.indexOf("-") !== -1) { separator = "-"; parts = input.split(separator); if (parts.length === 3) { return new Date(parts[0], parts[1] - 1, parts[2]); } else if (input.indexOf("/") !== -1) { return new Date(parts[2], parts[0] - 1, parts[1]); } } } return new Date(Date.parse(input)); }; //verify that the date is valid => object is date-time and there is a meaningful value self.isValidDate = function(d) { if (!self.isDate(d)) { return false; } return !isNaN(d.getTime()); }; self.compare = function(x, y) { for (var propertyName in x) { if (x[propertyName] !== y[propertyName]) { return false; } } return true; }; self.toLength = function(val, length) { if (val.length >= length) { return val.substring(0, length); } var returnVal = ""; for (var i = 0; i < length; i++) { returnVal += val[i % val.length]; } return returnVal; }; Number.prototype.toCurrencyString = function(cur, decSpaces) { var formatted = this.toFixed(decSpaces).replace(/(\d)(?=(\d{3})+\b)/g, '$1 '); if (cur != null) formatted += ' ' + cur; return formatted; }; self.toPercent = function(val) { if (val === null) return 0; return (val * 100).toFixed(1) + " %"; }; //Size of the object - equivalent of array length Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; var objToString = Object.prototype.toString; function isString(obj) { return objToString.call(obj) == '[object String]'; } String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; //difference in 2 arrays self.diff = function(a1, a2) { return a1.filter(function(i) { return a2.indexOf(i) < 0; }); }; self.tryConvertToNumber = function(orgValue) { var intValue = parseInt(orgValue); var decimalValue = parseFloat(orgValue); var value = intValue != null ? intValue : (decimalValue != null ? decimalValue : orgValue); return value; }; self.toBoolean = function(string) { if (string == null) return false; switch (string.toLowerCase()) { case "true": case "yes": case "1": return true; case "false": case "no": case "0": case null: return false; default: return Boolean(string); } }; self.dateToFrenchString = function(date) { var month = date.getMonth() + 1; return date.getDate() + "/" + month + "/" + date.getFullYear(); }; self.dateToUSString = function(date) { var month = date.getMonth() + 1; return month + "/" + date.getDate() + "/" + date.getFullYear(); }; self.getYearAndMonth = function(date) { var yyyy = date.getFullYear().toString(); var mm = (date.getMonth() + 1).toString(); return yyyy + (mm[1] ? mm : "0" + mm[0]); }; self.splitMonthAndYear = function(monthAndYear) { return { year: self.tryConvertToNumber(monthAndYear.substring(0, 4)), month: self.tryConvertToNumber(monthAndYear.substring(4, 6)) }; }; self.distinct = function(data, mapper) { var mapped = data.map(mapper); return mapped.filter(function(v, i) { return mapped.indexOf(v) == i; }); }; self.convertSeriesToXYPairs = function(data) { var converted = []; for (var i = 0; i < data.length; i++) { converted.push({ x: i, y: data[i] }); } return converted; }; self.convertAllSeriesToXYPairs = function (data) { if (data == null) { return null; } for (var i = 0; i < data.length; i++) { if (data[i] != null && data[i].values != null) { if (self.isNumber(data[i].values[0])) { data[i].values = self.convertSeriesToXYPairs(data[i].values); } } } return data; }; self.setDefaultOptions = function (defaultConfig, config) { config = config || {}; for (var key in defaultConfig) { config[key] = config[key] != null ? config[key] : defaultConfig[key]; } return config; }; self.getIdealDateFormat = function(range) { var min = range[0]; var max = range[1]; var oneDay = 24*60*60*1000; var diffDays = Math.round(Math.abs((max.getTime() - min.getTime())/(oneDay))); if(diffDays > 5){ return function(d){ var val = d.toFormattedString(); return val; }; }else { var diffHours = Math.abs(max - min) / 36e5; if(diffHours > 2){ return function(d){ return d.getHours() + ":" + d.getMinutes(); }; }else{ return function(d) { return d.getMinutes() + ":" + d.getSeconds();}; } } } } module.exports = new kotools();
import path from 'path'; import HtmlWebpackPlugin from 'html-webpack-plugin'; export default { debug: true, devtool: 'inline-source-map', noInfo: false, entry: [ path.resolve(__dirname, 'src/index') ], target: 'web', output: { path: path.resolve(__dirname, 'src'), publicPath: '/', filename: 'bundle.js' }, plugins: [ // Create HTML file that includes reference to bundled JS. new HtmlWebpackPlugin({ template: 'src/index.html', inject: true }) ], module: { loaders: [ {test: /\.js$/, exclude: /node_modules/, loaders: ['babel']}, {test: /\.css$/, loaders: ['style', 'css']} ] } }
import { Actions } from 'flummox'; class CounterActions extends Actions { increment() { return true; } decrement() { return true; } incrementAsync() { return new Promise(resolve => { setTimeout(() => { resolve(true); }, 1000) }); } } export default CounterActions;
import chai from 'chai' import QueueDS from './queue' chai.should() describe('[Data Structure] Queue', () => { it('Get the length() of the queue', (done) => { const queue = new QueueDS() queue.enqueue(1).enqueue(2).enqueue(3) // Assertions. queue.length().should.equal(3) done() }) it('enqueue(1...3) items', (done) => { const queue = new QueueDS() queue.enqueue(1).enqueue(2).enqueue(3) // Assertions. queue.getQueue().should.deep.equal([1, 2, 3]) done() }) it('enqueue(1...3) items and dequeue() 2x', (done) => { const queue = new QueueDS() queue.enqueue(1).enqueue(2).enqueue(3) // Assertions. queue.getQueue().should.deep.equal([1, 2, 3]) queue.dequeue() queue.getQueue().should.deep.equal([2, 3]) queue.dequeue() queue.getQueue().should.deep.equal([3]) done() }) it('enqueue(1...3) items peek() then dequeue() and peek() again.', (done) => { const queue = new QueueDS() queue.enqueue(1).enqueue(2).enqueue(3) // Assertions. queue.getQueue().should.deep.equal([1, 2, 3]) queue.peek().should.deep.equal(1) queue.dequeue() queue.peek().should.deep.equal(2) queue.dequeue() queue.peek().should.deep.equal(3) done() }) })
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc.5-master-7f01138 */ function createDirective(e,i){return["$mdUtil",function(n){return{restrict:"A",multiElement:!0,link:function(t,o,r){var a=t.$on("$md-resize-enable",function(){a();var c=window.getComputedStyle(o[0]);t.$watch(r[e],function(e){if(!!e===i){n.nextTick(function(){t.$broadcast("$md-resize")});var r={cachedTransitionStyles:c};n.dom.animator.waitTransitionEnd(o,r).then(function(){t.$broadcast("$md-resize")})}})})}}}]}goog.provide("ng.material.components.showHide"),goog.require("ng.material.core"),angular.module("material.components.showHide",["material.core"]).directive("ngShow",createDirective("ngShow",!0)).directive("ngHide",createDirective("ngHide",!1)),ng.material.components.showHide=angular.module("material.components.showHide");
define(function (require) { // imports var RAF = require('../lib/RequestAnimationFrame'); var Container = require('Container'); var Sprite = require('Sprite'); var TestBasic = function(canvas) { console.log('[TestBasic] Initializing'); this.stageWidth = canvas.width = window.innerWidth; this.stageHeight = canvas.height = window.innerHeight; this.canvas = canvas; this.ctx = canvas.getContext('2d'); this.sprites = []; this.numSprites = 20; this.stage = new Container(); var spacing = 70, offX = 50, offY = 80, rowX = 0, rowY = 0, rowMax = Math.floor((this.stageWidth - offX) / spacing), img = document.getElementById('beetle'), i, o; var settings = { regX: 25, regY: 25 }; /*this._merge(this.stage, { regX: window.innerWidth / 2, regY: window.innerHeight / 2 });*/ for (i = 0; i < this.numSprites; i++) { o = new Sprite(img); o.position.reset((rowX * spacing) + offX, (rowY * spacing) + offY); this._merge(o, settings); this.sprites[i] = o; this.stage.addChild(o); rowX++; if (rowX === rowMax) { rowX = 0; rowY++; } } this.raf = new RAF(this); this.raf.start(); console.log('[TestBasic] Running'); }; TestBasic.prototype = { update: function () { var i, o; // this.ctx.setTransform(1, 0, 0, 1, 0, 0); this.ctx.clearRect(0, 0, this.stageWidth, this.stageHeight); // update for (i = 0; i < this.numSprites; i++) { o = this.sprites[i]; o.position.x += 1; o.angle += 0.01; /*o.skewX += 0.01; o.skewY -= 0.01; o.scaleX += 0.01; if (o.scaleX > 2) o.scaleX = 0.5; o.scaleY += 0.01; if (o.scaleY > 2) o.scaleY = 0.5;*/ if (o.position.x > this.stageWidth) { o.position.x = 0; } } // this.stage.scaleX += 0.01; // this.stage.scaleY += 0.01; this.stage.draw(this.ctx); }, _merge: function(host, augment) { for (var n in augment) { host[n] = augment[n]; } } }; return TestBasic; });
<% if(includeNeturalNotice) {%>import companyNotice from './companyNotice';<% } %><% if(includeMojito) {%> import mojitoSetup from './mojitoSetup';<% } %>
var pg = require("pg"); var async = require("async"); var fs = require("fs"); function getEnvironmentVariables(filepath, existingVariables) { var vars = {}; // Copy over existing variables for (var key in existingVariables) { vars[key] = existingVariables[key]; } if (fs.existsSync(filepath)) { var fileOfVariables = fs.readFileSync(filepath, "utf8").split("\n"); // For every line in the .env file, parse out the key-value pairs // and add them to the vars object. fileOfVariables.forEach(function (variable) { var key = variable.substring(0, variable.indexOf("=")); var value = variable.substring(variable.indexOf("=") + 1); if (key && value) { vars[key.replace(" ", "")] = value; } }); } else { console.log("ERROR", filepath, "not found"); // This should only happen on Travis CI if (process.env.DATABASE_URL) { vars.DATABASE_URL = process.env.DATABASE_URL; } } return vars; } module.exports = function (grunt) { var packageFile = grunt.file.readJSON("package.json"); grunt.initConfig({ pkg: packageFile, jshint: { all: [ "Gruntfile.js", "app.js", "config.js", "controllers/*.js", "controllers/validators/*.js", "public/js/egress-*.js", "routes/*.js", "test/*.js" ], options: packageFile.jshintConfig }, jade: { "temp/jade": ["jade/*.jade", "jade/*/*.jade"] }, clean: { jade: "temp" // Remove the temp directory containing the compiled jade file from above } }); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-contrib-jade"); grunt.loadNpmTasks("grunt-contrib-clean"); grunt.registerTask("default", ["jshint", "jade", "clean"]); grunt.registerTask("postgres:init", "Used to run any SQL scripts for a Postgres database.", function () { var callback = this.async(); // TODO: check that the tables already exist before creating them... var config = require("./config"); config = getEnvironmentVariables(".env", config); var scripts = { create: fs.readFileSync("databases/create-tables.sql", "utf8"), functions: fs.readFileSync("databases/functions.sql", "utf8"), init: fs.readFileSync("databases/init-tables.sql", "utf8") }; if (!config.DATABASE_URL) { grunt.fail.fatal("The DATABASE_URL environment variable was not set. Found the following config object:\n" + JSON.stringify(config, null, 4)); callback(false); } else { // TODO: check that tables exist with a query like so: var checkTableQuery = "select * from information_schema.tables where table_name='users'"; var client = new pg.Client(config.DATABASE_URL); async.waterfall([ function (done) { client.connect(done); }, function (client, done) { console.log("Running create scripts"); client.query(scripts.create, done); }, function (result, done) { console.log("Running init scripts"); client.query(scripts.init, done); }, function (result, done) { console.log("Running functions scripts"); client.query(scripts.functions, done); }, function (result, done) { console.log("All done."); done(); } ], function (err) { if (err) { grunt.fail.warn("Found an error:" + err); } callback(err ? false : null); } ); } }); grunt.registerTask("dist", ["postgres:init"]); // When deploying, run the PG scripts. };
import React from 'react' import NavHelper from './components/nav-helper' export default React.createClass({ displayName: 'Layout', render () { return ( <NavHelper> <nav className='top-nav top-nav-light cf' role='navigation'> <input id='menu-toggle' className='menu-toggle' type='checkbox'/> <label htmlFor='menu-toggle'>Menu</label> <ul className='list-unstyled list-inline cf'> <li>Labelr</li> <li><a href='/repos'>Repos</a></li> <li className='pull-right'><a href='/'>Logout</a></li> </ul> </nav> <div className='container'> {this.props.children} </div> </NavHelper> ) } })
import angular from 'angular' import './components' import './controllers' import './dependencies' import './routes' import './style' const MODULE_NAME = 'app.core' angular.module(MODULE_NAME, [ 'app.core.components', 'app.core.controllers', 'app.core.dependencies', 'app.core.routes', 'app.core.style' ]) export default MODULE_NAME
var gulp = require('gulp'); var browserSync = require('browser-sync'); // Watch Files For Changes & Reload gulp.task('serve', function () { browserSync({ notify: false, snippetOptions: { rule: { match: '<span id="browser-sync-binding"></span>', fn: function (snippet) { return snippet; } } }, // Run as an https by uncommenting 'https: true' // Note: this uses an unsigned certificate which on first access // will present a certificate warning in the browser. // https: true, server: { baseDir: ['.tmp', '.'], routes: { '/bower_components': 'bower_components' } } }); });
var Character = require('../models/character'); function charactersIndex(req, res){ Character.find({}, function(err, characters){ if (err) return res.status(404).json({ message: "Error while finding characters." }); res.status(200).json({ characters: characters }); }); } function characterCreate(req, res){ if (!req.body.String || !req.body.kMandarin || !req.body.kDefinition){ return res.status(400).json({ message: "String, kMandarin, and kDefinition are required fields." }); } var character = new Character({ String : req.body.String, kMandarin : req.body.kMandarin, kDefinition : req.body.kDefinition, kFrequency : req.body.kFrequency, kTraditionalVariant : req.body.kTraditionalVariant }); character.save(function(err){ if (err) return res.status(200).json({ message: "Unable to save character." + err }); res.status(201).json(character); }); } function characterShow(req, res){ Character.findById(req.params.id, function(err, character){ if (!character) return res.status(404).json({ message: "Character not found."}); if (err) return res.status(500).json({ message: err }); res.status(200).json({ character: character }); }); } function characterUpdate(req, res){ Character.findById(req.params.id, function(err, character){ if (!character) return res.status(404).json({ message: "Character not found."}); if (err) return res.status(500).json({ message: err }); character.String = req.body.String || character.String; character.kMandarin = req.body.kMandarin || character.kMandarin; character.kDefinition = req.body.kDefinition || character.kDefinition; character.kFrequency = req.body.kFrequency || character.kFrequency; character.kTraditionalVariant = req.body.kTraditionalVariant || character.kTraditionalVariant; character.save(function(err){ if (err) return res.status(500).json({ message: err }); res.status(200).json({ message: "Character successfully updated" }); }); }); } function characterDestroy(req, res){ Character.findByIdAndRemove({ _id: req.params.id }, function(err){ if (err) return res.status(500).json({ message: err }); res.status(200).json({ message: "Character successfully deleted." }); }); } // FOR SEEDING DATA ONLY: function charactersCreateInBulk(req, res){ console.log("received " + req.body.count + "records") var errorCount = 0; req.body.forEach(function(character){ // console.log(i, character); var newCharacter = new Character({ String : character.String, kMandarin : character.kMandarin, kDefinition : character.kDefinition, kFrequency : character.kFrequency, kTraditionalVariant : character.kTraditionalVariant }); newCharacter.save(function(err){ if (err) errorCount++; }); }); res.status(200).json({ message: "Characters added to database with " + errorCount + " errors."}); } module.exports = { charactersIndex : charactersIndex, characterShow : characterShow, characterCreate : characterCreate, characterUpdate : characterUpdate, characterDestroy : characterDestroy, charactersCreateInBulk : charactersCreateInBulk }
import React from 'react'; import {Decorator as Cerebral} from 'cerebral-view-react'; import styles from '../styles.css'; import currentLoader from '../../../computed/currentLoader'; @Cerebral({ loader: currentLoader }) class JadeConfig extends React.Component { render() { const loader = this.props.loader; return ( <div> <div className={styles.description}> With the .jade extension you can load Jade templates as template functions </div> </div> ); } } export default JadeConfig;
/* eslint no-empty-pattern: "off" */ /* eslint no-magic-numbers: ["error", { "ignore": [2] }] */ export default function createSuggestedActionsStyle({ paddingRegular, suggestedActionsStackedHeight, suggestedActionsStackedOverflow, transcriptOverlayButtonBackground, transcriptOverlayButtonBackgroundOnDisabled, transcriptOverlayButtonBackgroundOnFocus, transcriptOverlayButtonBackgroundOnHover, transcriptOverlayButtonColor, transcriptOverlayButtonColorOnDisabled, transcriptOverlayButtonColorOnFocus, transcriptOverlayButtonColorOnHover }) { return { '&.webchat__suggested-actions': { '& .webchat__suggested-actions__carousel': { paddingBottom: paddingRegular / 2, paddingTop: paddingRegular / 2, '& .react-film__filmstrip': { scrollbarWidth: 'none', '& .react-film__filmstrip__item:first-child': { paddingLeft: paddingRegular / 2 }, '& .react-film__filmstrip__item:last-child': { paddingRight: paddingRegular / 2 } }, '& .react-film__flipper': { '&:disabled, &[aria-disabled="true"]': { '& .react-film__flipper__body': { backgroundColor: transcriptOverlayButtonBackgroundOnDisabled, color: transcriptOverlayButtonColorOnDisabled } }, '&:focus .react-film__flipper__body': { backgroundColor: transcriptOverlayButtonBackgroundOnFocus, color: transcriptOverlayButtonColorOnFocus || transcriptOverlayButtonColor }, '&:hover .react-film__flipper__body': { backgroundColor: transcriptOverlayButtonBackgroundOnHover, color: transcriptOverlayButtonColorOnHover || transcriptOverlayButtonColor }, '& .react-film__flipper__body': { background: transcriptOverlayButtonBackground, color: transcriptOverlayButtonColor, outline: 0 } } }, '& .webchat__suggested-actions__stack': { maxHeight: suggestedActionsStackedHeight || 'auto', overflowY: suggestedActionsStackedOverflow || 'auto', paddingBottom: paddingRegular / 2, paddingLeft: paddingRegular / 2, paddingRight: paddingRegular / 2, paddingTop: paddingRegular / 2 } } }; }
var gulp = require('gulp'); var filter = require('gulp-filter'); var minifyCss = require('gulp-minify-css'); var rename = require('gulp-rename'); var uglify = require('gulp-uglify'); gulp.task('deploy', ['deploy:dist']); gulp.task('deploy:dist', ['sass:foundation', 'javascript:foundation'], function() { var cssFilter = filter(['*.css']); var jsFilter = filter(['*.js']); return gulp.src(['./_build/assets/css/foundation.css', '_build/assets/js/foundation.js']) .pipe(cssFilter) .pipe(gulp.dest('./dist')) .pipe(minifyCss()) .pipe(rename('foundation.min.css')) .pipe(gulp.dest('./dist')) .pipe(cssFilter.restore()) .pipe(jsFilter) .pipe(gulp.dest('./dist')) .pipe(uglify()) .pipe(rename('foundation.min.js')) .pipe(gulp.dest('./dist')); }); gulp.task('deploy:custom', ['sass:foundation', 'javascript:foundation'], function() { var cssFilter = filter(['*.css']); var jsFilter = filter(['*.js']); return gulp.src(['./_build/assets/css/foundation.css', '_build/assets/js/foundation.js']) .pipe(cssFilter) .pipe(gulp.dest('./_build/assets/css')) .pipe(minifyCss()) .pipe(rename('foundation.min.css')) .pipe(gulp.dest('./_build/assets/css')) .pipe(cssFilter.restore()) .pipe(jsFilter) .pipe(gulp.dest('./_build/assets/js')) .pipe(uglify()) .pipe(rename('foundation.min.js')) .pipe(gulp.dest('./_build/assets/js')); });
var IRC = function IRC(nickname, password, callback) { // Varable d'instance var self = this; self.socket = io(); self.callbacks = []; // Envoyer une commande en brute sur le réseau IRC self.sendCommand = function sendCommand(command) { console.log("> " + command); self.socket.emit("command", command); } // Envoyer un message sur un salon où à quelqu'un self.sendMessage = function sendMessage(channel, message) { self.sendCommand("PRIVMSG " + channel + " :" + message); } // Envoyer une requête pour récupérer la liste des utilisateurs d'un salon self.sendNamesQuery = function sendNamesQuery(channel, callback) { console.log("> NAMES " + channel); var callbackId = self.callbacks.length; self.callbacks.push(callback); self.socket.emit("names", channel, callbackId); } // Envoyer une requête pour récupérer le topic d'un salon self.sendTopicQuery = function sendTopicQuery(channel, callback) { console.log("> TOPIC " + channel); var callbackId = self.callbacks.length; self.callbacks.push(callback); self.socket.emit("topic", channel, callbackId); } // Envoie d'une requête d'enregistrement au serveur node self.socket.emit("register", nickname, password); // Active un événement sur la réception des messages du serveur node self.socket.on("IRCMessage", function(IRCMessage){ // Récupère chaque ligne du message reçu et l'affiche en console lines = IRCMessage.trim().split("\r\n") for (var index in lines) { var line = lines[index]; console.log(line) var scope = angular.element(document.body).scope(); addText(scope.channels, "Console", "", "raw", new Date(), line); scope.$apply() if (!self.connected) { // Si on a pas encore reçu le MOTD if (line.indexOf("End of message of the day") > -1) { self.connected = true; // Ok on est connecté ! callback(); break; // On passe les autres messages du MOTD } } else { // Sinon si on est en phase de connexion normal var linex = line.split(" "); // On récupère chaque mot de la ligne // Si le 1e mot est PING, on renvoit le PONG correspondant if (linex[0] == "PING") self.sendCommand("PONG " + linex[1] + "\r\n"); else if (linex.length >= 2) { // Sinon on regarde chaque 2e mot (le 1e étant alors :<nickname>!<hostname>@<mask>) switch (linex[1]) { case "PRIVMSG": // :Julien00859!Julien@host-85-201-171-39.dynamic.voo.be PRIVMSG #Dev :Hello world :D // ^^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^ var sender = linex[0].slice(1, linex[0].indexOf("!")); var channel = linex[2]; var msg = linex.slice(3).join(" ").slice(1); onPrivMsg(sender, channel, msg) break; case "JOIN": // :Julien00859!Julien@host-85-201-171-39.dynamic.voo.be JOIN :#Dev // ^^^^^^^^^^^ ^^^^ // :127.0.0.1 332 Julien00859 #Dev :Salut tout le monde :D // ^^^^^^^^^^^^^^^^^^^^^^ // :127.0.0.1 333 Julien00859 #Dev Julien008!Julien@94.111.231.0 1453514793 // :127.0.0.1 353 Julien = #Dev :Juilen @Julien008 jsfljdflkjkflsj // [^^^^^^,^^^^^^^^^^,^^^^^^^^^^^^^^^] // :127.0.0.1 366 Julien00859 #Dev :End of /NAMES list. var sender = linex[0].slice(1, linex[0].indexOf("!")); var channel = linex[2].slice(1); // Truc de gros porc :D var topicAndName; var topic; var names; for (var i in lines.slice(index)) { if (lines[parseInt(index) + parseInt(i)].indexOf(":End of /NAMES list.") >= 0) { topicAndName = lines.slice(index, parseInt(index) + parseInt(i) + 1); if (topicAndName.length >= 5) { topic = topicAndName[1].split(" ").slice(4).join(" ").slice(1); } if (topicAndName.length >= 3 && topicAndName.slice(-1)[0].indexOf(":End of /NAMES list.") >= 0) { names = topicAndName.slice(-2, -1)[0].split(" ").slice(5).join(" ").slice(1).trim(); } break; } } onJoin(sender, channel, topic, names); break; case "KICK": // :Julien008!Julien@host-85-201-171-39.dynamic.voo.be KICK #Dev Julien00859 :You have been kicked // ^^^^^^^^^ ^^^^ ^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^ var sender = linex[0].slice(1, linex[0].indexOf("!")); var channel = linex[2]; var target = linex[3]; var kickMessage = linex.slice(4).join(" ").slice(1); onKick(sender, channel, target, kickMessage); break; case "PART": // :Julien00859!Julien@host-85-201-171-39.dynamic.voo.be PART #Dev :"Gonna bake some cookies..." // ^^^^^^^^^^^ ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ var sender = linex[0].slice(1, linex[0].indexOf("!")); var channel = linex[2]; var partMessage = linex.slice(3).join(" ").slice(1); onPart(sender, channel, partMessage); break case "QUIT": // :Julien00859!Julien@host-85-201-171-39.dynamic.voo.be QUIT :Quit: Keep calm and do not rage quit // ^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ var sender = linex[0].slice(1, linex[0].indexOf("!")); var quitMessage = linex.slice(3).join(" "); onQuit(sender, quitMessage); break; case "MODE": // :Julien008!Julien@host-85-201-171-39.dynamic.voo.be MODE #Dev +h Julien00859 // ^^^^^^^^^ ^^^^ ^^ ^^^^^^^^^^^ var sender = linex[0].slice(1, linex[0].indexOf("!")); var channel = linex[2]; var mode = linex[3]; var target = linex[4]; onMode(sender, channel, mode, target); break; case "NICK": // :Julien008!Julien@94.111.168.53 NICK Julien // ^^^^^^^^^ ^^^^^^ var sender = linex[0].slice(1, linex[0].indexOf("!")); var newNick = linex[2]; onNick(sender, newNick); } } } }; }); self.socket.on("topic", function(messages, callbackId){ // :127.0.0.1 332 Julien008 #Dev :Hello world // "^^^^^^^^^^^" // :127.0.0.1 333 Julien008 #Dev Julien008!Julien@host-85-201-171-39.dynamic.voo.be 1453335926 var topic = messages.split("\r\n")[0].split(" ").slice(4).join(" ").slice(1); self.callbacks[callbackId](topic); }); self.socket.on("names", function(messages, callbackId) { // :127.0.0.1 353 Julien008 = #Dev :@Julien008 @MrRobot %Mathieu Jean-Kevin // [^^^^^^^^^^,^^^^^^^^,^^^^^^^^,^^^^^^^^^^] // :127.0.0.1 366 Julien008 #Dev :End of /NAMES list. var names = messages.split("\r\n")[0].split(" ").slice(5).join(" ").slice(1).trim(); self.callbacks[callbackId](names); }); }
var Tecnotek = Tecnotek || {}; Tecnotek.Reports = { List: { init : function() { $('#btnPrint').click(function(event){ $("#report").printElement({printMode:'popup', pageTitle:$(this).attr('rel')}); }); $("#activityTypeId").change(function(event){ event.preventDefault(); $('#activitiesOptions').append('<option value="-1">Seleccione</option>'); Tecnotek.Reports.loadGroupActivities($(this).val()); }); $("#activitiesOptions").change(function(event){ event.preventDefault(); Tecnotek.Reports.loadGroupPatients($("#activityTypeId").val(), $(this).val()); }); } }, loadGroupActivities: function($entity) { console.debug("Load groups of activity: " + $entity); if(($entity!==null || $entity!= '-1')){ $('#activitiesOptions').children().remove(); $('#activitiesOptions').append('<option value="-1">Seleccione</option>'); //$('#patientsTable').empty(); Tecnotek.ajaxCall(Tecnotek.UI.urls["loadGroupsOfActivity"], { entity: $entity }, function(data){ console.debug("Total: " + data.activities.length); if(data.error === true) { Tecnotek.showErrorMessage(data.message,true, "", false); } else { for(i=0; i<data.activities.length; i++) { $('#activitiesOptions').append('<option value="' + data.activities[i].id + '">' + data.activities[i].name + '</option>'); } } }, function(jqXHR, textStatus){ Tecnotek.showErrorMessage("Error getting data: " + textStatus + ".", true, "", false); $(this).val(""); }, true); } }, loadGroupPatients: function($entity, $activityId) { console.debug("Load groups of patients: " + $entity +"-"+$activityId); if(($entity!==null || $entity!= '-1' || $activityId!= '-1')){ //$('#activitiesOptions').children().remove(); $('#patientsTable').empty(); $('#patientsTable').append('<tr><td style="float: left; width:120px;">Identificación</td><td style="float: left; width:300px;">Nombre</td></tr>'); $('#activityLabel').empty(); $('#activityTypeLabel').empty(); $('#activityLabel').append($('#activityTypeId :selected').text()); $('#activityTypeLabel').append($('#activitiesOptions :selected').text()); Tecnotek.ajaxCall(Tecnotek.UI.urls["loadGroupsOfPatients"], { entity: $entity, activityId: $activityId }, function(data){ console.debug("Total: " + data.patients.length); if(data.error === true) { Tecnotek.showErrorMessage(data.message,true, "", false); } else { for(i=0; i<data.patients.length; i++) { $('#patientsTable').append('<tr><td style="float: left; width:120px;">' + data.patients[i].id + '</td><td style="float: left; width:300px;">' + data.patients[i].name + '</td></tr>'); } } }, function(jqXHR, textStatus){ Tecnotek.showErrorMessage("Error getting data: " + textStatus + ".", true, "", false); $(this).val(""); }, true); } } };
/*global todomvc */ 'use strict'; /** * Directive that executes an expression when the element it is applied to loses focus */ todomvc.directive('todoBlur', function () { return function (scope, elem, attrs) { elem.bind('blur', function () { scope.$apply(attrs.todoBlur); }); }; });
/* eslint-disable max-len */ import classNames from 'classnames' import React, { Component } from 'react' import PropTypes from 'prop-types' import urlManager from './../utils/urlManager.js' import nameUtil from './../utils/nameUtil.js' const Navigation = ({ domain, locationClass, isHomepage }) => { const baseURL = urlManager(domain).base('nav') const mayorURL = `${urlManager(domain).base()}/mayor` const councilURL = `${urlManager(domain).base()}/boston/city-council` const mainClass = classNames('g-nav', locationClass) const p1 = `?p1=BG_election_nav_${isHomepage ? 'hp_':''}` return ( <nav className={mainClass} key='nav'> <ul className='g-nav__list'> <li className='g-nav__item'> <a className='g-nav__link nav-election benton-bold icon--election' href={`${urlManager(domain).base()}${p1}central`}>Election 2017</a> </li> <li className='g-nav__item'> <a className='g-nav__link nav-mayor benton-bold icon--mayor' href={`${urlManager(domain).base()}/mayor${p1}mayor`}>Mayor Central</a> </li> <li className='g-nav__item'> <a className='g-nav__link nav-city-council benton-bold icon--president' href={`${urlManager(domain).base()}/boston/city-council${p1}council `}>Boston City Council</a> </li> <li className='g-nav__item'> <a className='g-nav__link nav-mayor-boston benton-bold icon--race' href={`${urlManager(domain).base()}/boston/mayor${p1}mayor_boston`}>Boston Mayor</a> </li> </ul> </nav> ) } Navigation.propTypes = { domain: PropTypes.object, } export default Navigation
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ function chunkContainsModule(chunk, module) { var chunks = module.chunks; var modules = chunk.modules; if(chunks.length < modules.length) { return chunks.indexOf(chunk) >= 0; } else { return modules.indexOf(module) >= 0; } } function hasModule(chunk, module, checkedChunks) { if(chunkContainsModule(chunk, module)) return [chunk]; if(chunk.entry) return false; return allHaveModule(chunk.parents.filter(function(c) { return checkedChunks.indexOf(c) < 0; }), module, checkedChunks); } function allHaveModule(someChunks, module, checkedChunks) { if(!checkedChunks) checkedChunks = []; var chunks = []; for(var i = 0; i < someChunks.length; i++) { checkedChunks.push(someChunks[i]); var subChunks = hasModule(someChunks[i], module, checkedChunks); if(!subChunks) return false; addToSet(chunks, subChunks); } return chunks; } function addToSet(set, items) { items.forEach(function(item) { if(set.indexOf(item) < 0) set.push(item); }); } function debugIds(chunks) { var list = chunks.map(function(chunk) { return chunk.debugId; }); if(list.some(function(dId) { return typeof dId !== "number"; })) return "no"; list.sort(); return list.join(","); } function RemoveParentModulesPlugin() {} module.exports = RemoveParentModulesPlugin; RemoveParentModulesPlugin.prototype.apply = function(compiler) { compiler.plugin("compilation", function(compilation) { compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], function(chunks) { chunks.forEach(function(chunk) { var cache = {}; chunk.modules.slice().forEach(function(module) { if(chunk.entry) return; var dId = "$" + debugIds(module.chunks); var parentChunksWithModule; if((dId in cache) && dId !== "$no") { parentChunksWithModule = cache[dId]; } else { parentChunksWithModule = cache[dId] = allHaveModule(chunk.parents, module); } if(parentChunksWithModule) { module.rewriteChunkInReasons(chunk, parentChunksWithModule); chunk.removeModule(module); } }); }); }); }); };
/** * Recompile library for AngularJS * version: TODO * * NOTE: It's best to not directly edit this file. Checkout * this repo and edit the files in src/. Then run 'grunt' on the * command line to rebuild dist/recompile.js */ (function() { 'use strict'; /** * NOTE: It's best to change the namespace within the source code (located in * src/namespace.js) and then rebuild the distribution code via grunt * * Set the namespace here! MY_NAMESPACE = 'foo' will produce: * module: angular.module('room77.foo') * directives: foo-watch, foo-deep-watch... * * NOTE: We assume that this variable will be all lowercase letters or numbers * with underscores seperating words. Anything different might screw up how * directive naming works in directives.js and in the tests. */ var MY_NAMESPACE = 'recompile'; angular.module('room77.' + MY_NAMESPACE, []); (function() { 'use strict'; angular.module('room77.' + MY_NAMESPACE).controller('RecompileCtrl', [ '$scope', RecompileCtrlConstructor ]); return; function RecompileCtrlConstructor($scope) { var RecompileCtrl = {}, _recompile_fns = []; RecompileCtrl.RegisterFn = function(fn) { _recompile_fns.push(fn); }; RecompileCtrl.RunFns = function() { for (var i = 0; i < _recompile_fns.length; i++) _recompile_fns[i](); }; RecompileCtrl.DeregisterFn = function(fn) { var i; for (i = 0; i < _recompile_fns.length; i++) { if (angular.equals(fn, _recompile_fns[i])) break; } if (i < _recompile_fns.length) { _recompile_fns.splice(i, 1); } }; $scope.$on('$destroy', function() { _recompile_fns = []; }); return RecompileCtrl; } })(); // End recompile controller (function() { 'use strict'; /** * The recompile trigger directives are enumerated in the following array * * Object: { * name: (in lowercase, separated by underscores) e.g. 'watch_collection' * * (The following are all properties, if set to true, they cause certain * behavior in the watch that is created) * deep_check: Object deep comparison in watch * only_when_true: only fires if watch value is Javascript true * watch_array: Array comparision in watch (see $watchCollection) * once: watch removes itself after firing once * * NOTE: the name will automatically be translated into the right syntaxes * i.e. camelCase for directives and dash-separated for HTML attribute * NOTE: the recompile namespace will be prepended to the directive * e.g. if MY_NAMESPACE = 'recompile', then the directive name for * 'deep_watch' will be recompile-deep-watch */ var recompile_triggers = [ { name: 'watch' }, { name: 'deep_watch', deep_check: true }, { name: 'when', only_when_true: true }, { name: 'watch_collection', watch_array: true }, { name: 'once_when', only_when_true: true, once: true } ]; var module = angular.module('room77.' + MY_NAMESPACE), // This is an array of the directives, used by the recompile-html directive // to obtain the controllers of the recompile triggers recompile_triggers_require_array = []; angular.forEach(recompile_triggers, function(recompile_trigger) { var angular_name = _AngularName(recompile_trigger.name); // Requires are both optional and can be on the parent recompile_triggers_require_array.push('?^' + angular_name); // Register trigger directive module.directive(angular_name, function() { return { controller: 'RecompileCtrl', scope: true, link: _RecompileTriggerLinkFn(recompile_trigger) }; }); }); // Register the directive that recompiles the html module.directive(_AngularName('html'), function() { return { restrict: 'EA', require: recompile_triggers_require_array, transclude: true, link: _RecompileHtmlLinkFn() }; }); // recompile-until has to be paired with a recompile-html module.directive(_AngularName('until'), function() { return { link: function(scope, elt, attrs) { if (!attrs.hasOwnProperty(_AngularName('html'))) { throw 'recompile-until needs to be paired with recompile-html'; } } }; }); // recompile-stop-watch-if has to be paired with a recompile trigger module.directive(_AngularName('stop_watch_if'), function() { // Only need to look for recompile triggers on this element var recompile_triggers_on_this_elt_require_array = recompile_triggers_require_array.map(function(directive) { return directive.replace('^', ''); }); return { require: recompile_triggers_on_this_elt_require_array, link: function(scope, elt, attrs, Ctrls) { var ctrl_exists = false; for (var i = 0; i < Ctrls.length; i++) { if (Ctrls[i]) { ctrl_exists = true; break; } } if (!ctrl_exists) { throw 'recompile-stop-watch-if needs to be paired with a ' + 'recompile trigger'; } } }; }); return; /*** Private fns below ***/ /** * Switches the name to camelCase and puts the desired namespace in front of * the name */ function _AngularName(name) { return (MY_NAMESPACE + '_' + name).replace(/_(\w)/g, _Capitalize); function _Capitalize(match, letter) { return letter.toUpperCase(); } } /* Switches the name to use dashes instead of underscores and puts the * desired namespace in front of the name */ function _HtmlName(name) { // TODO return (MY_NAMESPACE + '_' + name).replace(/_/g, '-'); } // TODO add comments function _RecompileTriggerLinkFn(recompile_trigger) { return function(scope, elt, attrs, RecompileCtrl) { var angular_name = _AngularName(recompile_trigger.name), watch_fn; // Choose between normal watch, or array watch if (recompile_trigger.watch_array) watch_fn = scope.$watchCollection; else watch_fn = scope.$watch; var watch_remover = watch_fn.call( scope, attrs[angular_name], _WatchFn, recompile_trigger.deep_check ); scope.$on('$destroy', function() { watch_remover = null; }); return; function _WatchFn(new_val) { // We trigger the recompile fns if no 'true' condition specified // or if the val is actually true if (!recompile_trigger.only_when_true || new_val) { RecompileCtrl.RunFns(); if (recompile_trigger.once || _RemoveTriggerWatch(scope, attrs, new_val)) { watch_remover(); watch_remover = null; } } } }; } function _RemoveTriggerWatch(scope, attrs, watch_val) { var angular_name = _AngularName('stop_watch_if'); if (attrs[angular_name]) { return watch_val === scope.$eval(attrs[angular_name]); } return false; } /** * This is where the HTML is actually recompiled (we use the translude fn * that's passed by the link fn, and create a new $scope each time a * recompile is triggered) */ function _RecompileHtmlLinkFn() { return function(scope, elt, attrs, Ctrls, transclude_fn) { var RecompileCtrl = null, // We keep track if our transclude fn was deregistered deregistered = false, child_scope = null; var current_elt = elt; while (current_elt.length > 0) { // Let's look on elt for the right attributes angular.forEach(recompile_triggers, function(recompile_trigger, i) { var html_name = _HtmlName(recompile_trigger.name); if (typeof current_elt.attr(html_name) !== 'undefined') { // We keep this loop going to make sure that two recompile // triggers are not on the same elt if (RecompileCtrl) { throw Error('Two recompile triggers on the same elt'); } RecompileCtrl = Ctrls[i]; } }); if (RecompileCtrl) break; current_elt = current_elt.parent(); } if (!RecompileCtrl) throw Error('Cannot find recompile trigger'); var until_angular_name = _AngularName('until'); if (attrs[until_angular_name]) { var until_watch_remover = scope.$watch(attrs[until_angular_name], function UntilWatch(new_val) { if (new_val) { _Deregister(); until_watch_remover(); until_watch_remover = null; } } ); } // Initialize the elt _TranscludeElt(); RecompileCtrl.RegisterFn(_TranscludeElt); scope.$on('$destroy', function() { _Deregister(); }); return; function _TranscludeElt() { if (child_scope) child_scope.$destroy(); child_scope = scope.$new(); transclude_fn(child_scope, function(clone) { elt.empty().append(clone); }); } function _Deregister() { if (!deregistered) { deregistered = true; // Clean up variables RecompileCtrl.DeregisterFn(_TranscludeElt); RecompileCtrl = null; child_scope = null; } } }; // End link array. } })(); })(); // End initial closure.
/* 内容 (content[string],回答内容) 回答时间 (addTime[string]) 热度 (heat[int],被赞+1,被踩-1) 回答者ID (answererID[ObjectID],回答者的ID) 回答者nickname (answererNickname[string],回答者的nickname) 评价过这条回答的人ID (viewers[ObjectID数组]) 是否被采纳 (isBest[bool]) */ Template['questionDetail'].events({ 'click #selectBest': function(e) { e.preventDefault(); var curUrl = Router.current().url; var items = curUrl.split('/'); var questionId = items[items.length-1]; var question = Questions.findOne(questionId); // 当前问题isHandled,问题中当前回答isBest var answers = question.answers; for (var i = 0; i < answers.length; i++) { if (answers[i].answererId == this.answererId) { answers[i].isBest = true; break; } } Questions.update(questionId, { $set: {answers: answers, isHandled: true} }, function(error) { if (error) { alert(error.reason); } else { alert("成功"); } }); // 回答者totalBest加一,answers中该问题isBest,积分加悬赏分 var answerer = Meteor.users.findOne(this.answererId); var answererScore = answerer.profile.score; var answererBest = answerer.profile.totalBest; var answererAnswers = answerer.profile.answers; for (i = 0; i < answererAnswers.length; i++) { if (answererAnswers[i].questionId == questionId) { answererAnswers[i].isBest = true; break; } } Meteor.users.update(this.answererId, { $set: {'profile.score': answererScore+question.reward, 'profile.totalBest': answererBest+1, 'profile.answers': answererAnswers} }, function(error) { if (error) { console.log(error.reason); } else { console.log("处理回答者成功"); } }); // 提问者当前问题isHandled var asker = Meteor.users.findOne(question.askerID); var askerQuestions = asker.profile.questions; for (i = 0; i < askerQuestions.length; i++) { if (askerQuestions[i].questionId == questionId) { askerQuestions[i].isHandled = true; break; } } Meteor.users.update(question.askerID, { $set: {'profile.questions': askerQuestions} }, function(error) { if (error) { console.log(error.reason); } else { console.log("处理提问者成功"); } }); }, 'submit form': function(e) { e.preventDefault(); // 每个问题只能回答一次,不能回答自己的问题,登陆才能回答 if (!Meteor.user()) { alert('请先登录!'); Router.go('/login'); } var answers = this.Question.answers; for (var i = 0; i < answers.length; i++) { if (answers[i].answererId == Meteor.user()._id) { alert("你已回答过此问题!"); return; } } if (this.Question.askerID == Meteor.user()._id) { alert("不能回答自己的问题!"); return; } // 获取当前时间 var formatDate = function(date, format) { var o = { "M+" : date.getMonth()+1, //month "d+" : date.getDate(), //day "h+" : date.getHours(), //hour "m+" : date.getMinutes(), //minute "s+" : date.getSeconds(), //second "q+" : Math.floor((date.getMonth()+3)/3), //quarter "S" : date.getMilliseconds() //millisecond } if(/(y+)/.test(format)) { format = format.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); } for(var k in o) { if(new RegExp("("+ k +")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length)); } } return format; } var now = new Date(); var time = formatDate(now, "yyyy-MM-dd hh:mm"); // 当前问题的answers中加入该回答 var answer = { content: $(e.target).find('[name=answerContent]').val(), addTime: time, heat: 0, answererId: Meteor.user()._id, answererNickname: Meteor.user().profile.nickname, viewers: [], isBest: false }; var count = this.Question.totalAnswer + 1; answers.push(answer); Questions.update(this.Question._id, { $set: {answers: answers, totalAnswer: count} }, function(error) { if (error) { alert(error.reason); } else { alert("成功,,获得5积分!"); } }); // 回答者的answers中加入该问题 var myAnswers = Meteor.user().profile.answers; var targetQuestion = { questionId: this.Question._id, title: this.Question.title, addTime: answer.addTime, category: this.Question.category, heat: 0, isBest: false // whether this user's answer is selected to be the best one } myAnswers.push(targetQuestion); var count = Meteor.user().profile.totalAnswer+1; var score = Meteor.user().profile.score; Meteor.users.update(Meteor.user()._id, { $set: {'profile.answers': myAnswers, 'profile.totalAnswer': count, 'profile.score': score+5} }, function(error) { if (error) { console.log(error.reason); } else { console.log("回答者的answers中加入该问题成功"); } }); }, 'click #approve': function(e) { e.preventDefault(); // 登陆才可以点赞 if (!Meteor.user()) { alert("登陆后才可以进行该操作!"); return; } // 不能评价自己的评论 if (Meteor.user()._id == this.answererId) { alert("不能评价自己的评论!"); return; } // 每个人只能对每条评论评价一次 var viewers = this.viewers; for (var i = 0; i < viewers.length; i++) { if (Meteor.user()._id == viewers[i]) { alert("你已评价过这条评论!"); return; } } // 该评论的viewers中加入当前用户ID, 该评论heat+1 var curUrl = Router.current().url; var items = curUrl.split('/'); var questionId = items[items.length-1]; var question = Questions.findOne(questionId); var answers = question.answers; for (i = 0; i < answers.length; i++) { if (answers[i].answererId == this.answererId) { answers[i].viewers.push(Meteor.user()._id); answers[i].heat += 1; break; } } Questions.update(questionId, { $set: {answers: answers} }, function(error) { if (error) { alert(error.reason); } else { alert("成功"); } }); // 该用户被赞数+1,对应回答被赞数+1 var answerer = Meteor.users.findOne(this.answererId); var answererAnswers = answerer.profile.answers; var answererLikes = answerer.profile.totalLike; for (i = 0; i < answererAnswers.length; i++) { if (answererAnswers[i].questionId == questionId) { answererAnswers[i].heat += 1; break; } } Meteor.users.update(this.answererId, { $set: {'profile.totalLike': answererLikes+1, 'profile.answers': answererAnswers} }, function(error) { if (error) { console.log(error.reason); } else { console.log("处理回答者成功"); } }); }, 'click #best-approve': function(e) { e.preventDefault(); // 登陆才可以点赞 if (!Meteor.user()) { alert("登陆后才可以进行该操作!"); return; } // 不能评价自己的评论 if (Meteor.user()._id == this.answererId) { alert("不能评价自己的评论!"); return; } // 每个人只能对每条评论评价一次 var viewers = this.viewers; for (var i = 0; i < viewers.length; i++) { if (Meteor.user()._id == viewers[i]) { alert("你已评价过这条评论!"); return; } } // 该评论的viewers中加入当前用户ID, 该评论heat+1 var curUrl = Router.current().url; var items = curUrl.split('/'); var questionId = items[items.length-1]; var question = Questions.findOne(questionId); var answers = question.answers; for (i = 0; i < answers.length; i++) { if (answers[i].answererId == this.answererId) { answers[i].viewers.push(Meteor.user()._id); answers[i].heat += 1; break; } } Questions.update(questionId, { $set: {answers: answers} }, function(error) { if (error) { alert(error.reason); } else { alert("成功"); } }); // 该用户被赞数+1,对应回答被赞数+1 var answerer = Meteor.users.findOne(this.answererId); var answererAnswers = answerer.profile.answers; var answererLikes = answerer.profile.totalLike; for (i = 0; i < answererAnswers.length; i++) { if (answererAnswers[i].questionId == questionId) { answererAnswers[i].heat += 1; break; } } Meteor.users.update(this.answererId, { $set: {'profile.totalLike': answererLikes+1, 'profile.answers': answererAnswers} }, function(error) { if (error) { console.log(error.reason); } else { console.log("处理回答者成功"); } }); }, 'click #best-against': function(e) { e.preventDefault(); // 登陆才可以点赞 if (!Meteor.user()) { alert("登陆后才可以进行该操作!"); return; } // 不能评价自己的评论 if (Meteor.user()._id == this.answererId) { alert("不能评价自己的评论!"); return; } // 每个人只能对每条评论评价一次 var viewers = this.viewers; for (var i = 0; i < viewers.length; i++) { if (Meteor.user()._id == viewers[i]) { alert("你已评价过这条评论!"); return; } } // 该评论的viewers中加入当前用户ID, 该评论heat+1 var curUrl = Router.current().url; var items = curUrl.split('/'); var questionId = items[items.length-1]; var question = Questions.findOne(questionId); var answers = question.answers; for (i = 0; i < answers.length; i++) { if (answers[i].answererId == this.answererId) { answers[i].viewers.push(Meteor.user()._id); answers[i].heat -= 1; break; } } Questions.update(questionId, { $set: {answers: answers} }, function(error) { if (error) { alert(error.reason); } else { alert("成功"); } }); // 该用户被赞数+1,对应回答被赞数+1 var answerer = Meteor.users.findOne(this.answererId); var answererAnswers = answerer.profile.answers; for (i = 0; i < answererAnswers.length; i++) { if (answererAnswers[i].questionId == questionId) { answererAnswers[i].heat -= 1; break; } } Meteor.users.update(this.answererId, { $set: {'profile.answers': answererAnswers} }, function(error) { if (error) { console.log(error.reason); } else { console.log("处理回答者成功"); } }); }, 'click #against': function(e) { e.preventDefault(); // 登陆才可以点赞 if (!Meteor.user()) { alert("登陆后才可以进行该操作!"); return; } // 不能评价自己的评论 if (Meteor.user()._id == this.answererId) { alert("不能评价自己的评论!"); return; } // 每个人只能对每条评论评价一次 var viewers = this.viewers; for (var i = 0; i < viewers.length; i++) { if (Meteor.user()._id == viewers[i]) { alert("你已评价过这条评论!"); return; } } // 该评论的viewers中加入当前用户ID, 该评论heat+1 var curUrl = Router.current().url; var items = curUrl.split('/'); var questionId = items[items.length-1]; var question = Questions.findOne(questionId); var answers = question.answers; for (i = 0; i < answers.length; i++) { if (answers[i].answererId == this.answererId) { answers[i].viewers.push(Meteor.user()._id); answers[i].heat -= 1; break; } } Questions.update(questionId, { $set: {answers: answers} }, function(error) { if (error) { alert(error.reason); } else { alert("成功"); } }); // 该用户被赞数+1,对应回答被赞数+1 var answerer = Meteor.users.findOne(this.answererId); var answererAnswers = answerer.profile.answers; for (i = 0; i < answererAnswers.length; i++) { if (answererAnswers[i].questionId == questionId) { answererAnswers[i].heat -= 1; break; } } Meteor.users.update(this.answererId, { $set: {'profile.answers': answererAnswers} }, function(error) { if (error) { console.log(error.reason); } else { console.log("处理回答者成功"); } }); } });
import {OPEN, CLOSE, RECEIVE_COMPONENT} from '../actions/modal_actions'; import merge from 'lodash/merge'; const initialState = { isOpen: false, component: '' }; const ModalReducer = (state = initialState, action) => { Object.freeze(state); switch(action.type){ case RECEIVE_COMPONENT: let component = action.component; return Object.assign({}, state, { component }); case OPEN: return Object.assign({}, state, {component: action.component, isOpen: true}); case CLOSE: return Object.assign({}, state, {component: null, isOpen: false}); default: return state; } }; export default ModalReducer;
/** * Client entry file */ console.log('Blocker - The Hunter is welcome!') const config = require('./../../../common/config') const blocker = require('./blocker') const socketUrl = location.protocol + '//' + location.hostname + ':' + config.serverPort window.COMMON_MODULE = require('./../../../common/module') window.UI = require('./ui') window.UTIL = require('./../../../common/util') window.EVENT_NAME = config.eventName window.IS_DEBUG = config.isDebug window.GAME_WORLD_WIDTH = config.game.worldWidth window.GAME_WORLD_HEIGHT = config.game.worldHeight window.SOCKET = io(socketUrl) window.WINDOW_WIDTH = window.innerWidth window.WINDOW_HEIGHT = window.innerHeight window.CLIENT_HEARTHBEAT = 1000 window.GAME = new Phaser.Game(WINDOW_WIDTH, WINDOW_HEIGHT, Phaser.CANVAS, 'game-wrap') UI.init() GAME.state.add('Boot', blocker.Boot) GAME.state.add('Load', blocker.Load) GAME.state.add('Play', blocker.Play) GAME.state.start('Boot')
/** * @preserve jquery-param (c) 2015 KNOWLEDGECODE | MIT */ /*global define */ (function (global) { 'use strict'; var param = function (a) { var add = function (s, k, v) { v = typeof v === 'function' ? v() : v === null ? '' : v === undefined ? '' : v; s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v); }, buildParams = function (prefix, obj, s) { var i, len, key; if (Object.prototype.toString.call(obj) === '[object Array]') { for (i = 0, len = obj.length; i < len; i++) { buildParams(prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']', obj[i], s); } } else if (obj && obj.toString() === '[object Object]') { for (key in obj) { if (obj.hasOwnProperty(key)) { if (prefix) { buildParams(prefix + '[' + key + ']', obj[key], s, add); } else { buildParams(key, obj[key], s, add); } } } } else if (prefix) { add(s, prefix, obj); } else { for (key in obj) { add(s, key, obj[key]); } } return s; }; return buildParams('', a, []).join('&').replace(/%20/g, '+'); }; if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = param; } else if (typeof define === 'function' && define.amd) { define([], function () { return param; }); } else { global.param = param; } }(this));
var mongoose = require('mongoose') var User = mongoose.model('User') var LocalStrategy = require('passport-local').Strategy var bCrypt = require('bcrypt-nodejs') module.exports = function(passport){ // Passport needs to be able to serialize and deserialize users to support persistent login sessions passport.serializeUser(function(user, done) { done(null, user._id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); passport.use('login', new LocalStrategy({ passReqToCallback : true }, function(req, username, password, done) { // check in mongo if a user with username exists or not User.findOne({ 'username' : username }, function(err, user) { // In case of any error, return using the done method if (err) return done(err); // Username does not exist, log the error and redirect back if (!user){ console.log('User Not Found with username '+username); return done(null, false); } // User exists but wrong password, log the error if (!isValidPassword(user, password)){ console.log('Invalid Password'); return done(null, false); // redirect back to login page } // User and password both match, return user from done method // which will be treated like success return done(null, user); } ); } )); passport.use('signup', new LocalStrategy({ passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, username, password, done) { // find a user in mongo with provided username User.findOne({ 'username' : username }, function(err, user) { // In case of any error, return using the done method if (err){ console.log('Error in SignUp: '+err); return done(err); } // already exists if (user) { console.log('User already exists with username: '+username); return done(null, false); } else { // if there is no user, create the user var newUser = new User(); // set the user's local credentials newUser.username = username; newUser.password = createHash(password); // save the user newUser.save(function(err) { if (err){ console.log('Error in Saving user: '+err); throw err; } console.log(newUser.username + ' Registration succesful'); return done(null, newUser); }); } }); }) ); var isValidPassword = function(user, password){ return bCrypt.compareSync(password, user.password); }; // Generates hash using bCrypt var createHash = function(password){ return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null); }; };
'use strict'; var grunt = require('grunt'); /* ======== 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) */ exports.yui_template = { setUp: function(done) { // setup here if necessary done(); }, micro: function(test) { test.expect(1); var expected = grunt.file.read('test/expected/foo.js'); var actual = grunt.file.read('tmp/foo.js'); test.equal(actual, expected, 'should match expected output.'); test.done(); } };
/*! * baguetteBox.js * @author feimosi * @version 1.11.1 * @url https://github.com/feimosi/baguetteBox.js */ /* global define, module */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.baguetteBox = factory(); } }(this, function () { 'use strict'; // SVG shapes used on the buttons var leftArrow = '<svg width="44" height="60">' + '<polyline points="30 10 10 30 30 50" stroke="rgba(255,255,255,0.5)" stroke-width="4"' + 'stroke-linecap="butt" fill="none" stroke-linejoin="round"/>' + '</svg>', rightArrow = '<svg width="44" height="60">' + '<polyline points="14 10 34 30 14 50" stroke="rgba(255,255,255,0.5)" stroke-width="4"' + 'stroke-linecap="butt" fill="none" stroke-linejoin="round"/>' + '</svg>', closeX = '<svg width="30" height="30">' + '<g stroke="rgb(160,160,160)" stroke-width="4">' + '<line x1="5" y1="5" x2="25" y2="25"/>' + '<line x1="5" y1="25" x2="25" y2="5"/>' + '</g></svg>'; // Global options and their defaults var options = {}, defaults = { captions: true, buttons: 'auto', fullScreen: false, noScrollbars: false, bodyClass: 'baguetteBox-open', titleTag: false, async: false, preload: 2, animation: 'slideIn', afterShow: null, afterHide: null, onChange: null, overlayBackgroundColor: 'rgba(0,0,0,.8)' }; // Object containing information about features compatibility var supports = {}; // DOM Elements references var overlay, slider, previousButton, nextButton, closeButton; // An array with all images in the current gallery var currentGallery = []; // Current image index inside the slider var currentIndex = 0; // Visibility of the overlay var isOverlayVisible = false; // Touch event start position (for slide gesture) var touch = {}; // If set to true ignore touch events because animation was already fired var touchFlag = false; // Regex pattern to match image files var regex = /.+\.(gif|jpe?g|png|webp)/i; // Object of all used galleries var data = {}; // Array containing temporary images DOM elements var imagesElements = []; // The last focused element before opening the overlay var documentLastFocus = null; var overlayClickHandler = function(event) { // Close the overlay when user clicks directly on the background if (event.target.id.indexOf('baguette-img') !== -1) { hideOverlay(); } }; var previousButtonClickHandler = function(event) { event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true; // eslint-disable-line no-unused-expressions showPreviousImage(); }; var nextButtonClickHandler = function(event) { event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true; // eslint-disable-line no-unused-expressions showNextImage(); }; var closeButtonClickHandler = function(event) { event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true; // eslint-disable-line no-unused-expressions hideOverlay(); }; var touchstartHandler = function(event) { touch.count++; if (touch.count > 1) { touch.multitouch = true; } // Save x and y axis position touch.startX = event.changedTouches[0].pageX; touch.startY = event.changedTouches[0].pageY; }; var touchmoveHandler = function(event) { // If action was already triggered or multitouch return if (touchFlag || touch.multitouch) { return; } event.preventDefault ? event.preventDefault() : event.returnValue = false; // eslint-disable-line no-unused-expressions var touchEvent = event.touches[0] || event.changedTouches[0]; // Move at least 40 pixels to trigger the action if (touchEvent.pageX - touch.startX > 40) { touchFlag = true; showPreviousImage(); } else if (touchEvent.pageX - touch.startX < -40) { touchFlag = true; showNextImage(); // Move 100 pixels up to close the overlay } else if (touch.startY - touchEvent.pageY > 100) { hideOverlay(); } }; var touchendHandler = function() { touch.count--; if (touch.count <= 0) { touch.multitouch = false; } touchFlag = false; }; var contextmenuHandler = function() { touchendHandler(); }; var trapFocusInsideOverlay = function(event) { if (overlay.style.display === 'block' && (overlay.contains && !overlay.contains(event.target))) { event.stopPropagation(); initFocus(); } }; // forEach polyfill for IE8 // http://stackoverflow.com/a/14827443/1077846 /* eslint-disable */ if (![].forEach) { Array.prototype.forEach = function(callback, thisArg) { for (var i = 0; i < this.length; i++) { callback.call(thisArg, this[i], i, this); } }; } // filter polyfill for IE8 // https://gist.github.com/eliperelman/1031656 if (![].filter) { Array.prototype.filter = function(a, b, c, d, e) { c = this; d = []; for (e = 0; e < c.length; e++) a.call(b, c[e], e, c) && d.push(c[e]); return d; }; } /* eslint-enable */ // Script entry point function run(selector, userOptions) { // Fill supports object supports.transforms = testTransformsSupport(); supports.svg = testSvgSupport(); supports.passiveEvents = testPassiveEventsSupport(); buildOverlay(); removeFromCache(selector); return bindImageClickListeners(selector, userOptions); } function bindImageClickListeners(selector, userOptions) { // For each gallery bind a click event to every image inside it var galleryNodeList = document.querySelectorAll(selector); var selectorData = { galleries: [], nodeList: galleryNodeList }; data[selector] = selectorData; [].forEach.call(galleryNodeList, function(galleryElement) { if (userOptions && userOptions.filter) { regex = userOptions.filter; } // Get nodes from gallery elements or single-element galleries var tagsNodeList = []; if (galleryElement.tagName === 'A') { tagsNodeList = [galleryElement]; } else { tagsNodeList = galleryElement.getElementsByTagName('a'); } // Filter 'a' elements from those not linking to images, and not containing <img> tags (PATCHED) tagsNodeList = [].filter.call(tagsNodeList, function(element) { if (element.className.indexOf(userOptions && userOptions.ignoreClass) === -1 && element.getElementsByTagName("img").length > 0) { return regex.test(element.href); } }); if (tagsNodeList.length === 0) { return; } var gallery = []; [].forEach.call(tagsNodeList, function(imageElement, imageIndex) { var imageElementClickHandler = function(event) { event.preventDefault ? event.preventDefault() : event.returnValue = false; // eslint-disable-line no-unused-expressions prepareOverlay(gallery, userOptions); showOverlay(imageIndex); }; var imageItem = { eventHandler: imageElementClickHandler, imageElement: imageElement }; bind(imageElement, 'click', imageElementClickHandler); gallery.push(imageItem); }); selectorData.galleries.push(gallery); }); return selectorData.galleries; } function clearCachedData() { for (var selector in data) { if (data.hasOwnProperty(selector)) { removeFromCache(selector); } } } function removeFromCache(selector) { if (!data.hasOwnProperty(selector)) { return; } var galleries = data[selector].galleries; [].forEach.call(galleries, function(gallery) { [].forEach.call(gallery, function(imageItem) { unbind(imageItem.imageElement, 'click', imageItem.eventHandler); }); if (currentGallery === gallery) { currentGallery = []; } }); delete data[selector]; } function buildOverlay() { overlay = getByID('baguetteBox-overlay'); // Check if the overlay already exists if (overlay) { slider = getByID('baguetteBox-slider'); previousButton = getByID('previous-button'); nextButton = getByID('next-button'); closeButton = getByID('close-button'); return; } // Create overlay element overlay = create('div'); overlay.setAttribute('role', 'dialog'); overlay.id = 'baguetteBox-overlay'; document.getElementsByTagName('body')[0].appendChild(overlay); // Create gallery slider element slider = create('div'); slider.id = 'baguetteBox-slider'; overlay.appendChild(slider); // Create all necessary buttons previousButton = create('button'); previousButton.setAttribute('type', 'button'); previousButton.id = 'previous-button'; previousButton.setAttribute('aria-label', 'Previous'); previousButton.innerHTML = supports.svg ? leftArrow : '&lt;'; overlay.appendChild(previousButton); nextButton = create('button'); nextButton.setAttribute('type', 'button'); nextButton.id = 'next-button'; nextButton.setAttribute('aria-label', 'Next'); nextButton.innerHTML = supports.svg ? rightArrow : '&gt;'; overlay.appendChild(nextButton); closeButton = create('button'); closeButton.setAttribute('type', 'button'); closeButton.id = 'close-button'; closeButton.setAttribute('aria-label', 'Close'); closeButton.innerHTML = supports.svg ? closeX : '&times;'; overlay.appendChild(closeButton); previousButton.className = nextButton.className = closeButton.className = 'baguetteBox-button'; bindEvents(); } function keyDownHandler(event) { switch (event.keyCode) { case 37: // Left arrow showPreviousImage(); break; case 39: // Right arrow showNextImage(); break; case 27: // Esc hideOverlay(); break; case 36: // Home showFirstImage(event); break; case 35: // End showLastImage(event); break; } } function bindEvents() { var passiveEvent = supports.passiveEvents ? { passive: false } : null; var nonPassiveEvent = supports.passiveEvents ? { passive: true } : null; bind(overlay, 'click', overlayClickHandler); bind(previousButton, 'click', previousButtonClickHandler); bind(nextButton, 'click', nextButtonClickHandler); bind(closeButton, 'click', closeButtonClickHandler); bind(slider, 'contextmenu', contextmenuHandler); bind(overlay, 'touchstart', touchstartHandler, nonPassiveEvent); bind(overlay, 'touchmove', touchmoveHandler, passiveEvent); bind(overlay, 'touchend', touchendHandler); bind(document, 'focus', trapFocusInsideOverlay, true); } function unbindEvents() { var passiveEvent = supports.passiveEvents ? { passive: false } : null; var nonPassiveEvent = supports.passiveEvents ? { passive: true } : null; unbind(overlay, 'click', overlayClickHandler); unbind(previousButton, 'click', previousButtonClickHandler); unbind(nextButton, 'click', nextButtonClickHandler); unbind(closeButton, 'click', closeButtonClickHandler); unbind(slider, 'contextmenu', contextmenuHandler); unbind(overlay, 'touchstart', touchstartHandler, nonPassiveEvent); unbind(overlay, 'touchmove', touchmoveHandler, passiveEvent); unbind(overlay, 'touchend', touchendHandler); unbind(document, 'focus', trapFocusInsideOverlay, true); } function prepareOverlay(gallery, userOptions) { // If the same gallery is being opened prevent from loading it once again if (currentGallery === gallery) { return; } currentGallery = gallery; // Update gallery specific options setOptions(userOptions); // Empty slider of previous contents (more effective than .innerHTML = "") while (slider.firstChild) { slider.removeChild(slider.firstChild); } imagesElements.length = 0; var imagesFiguresIds = []; var imagesCaptionsIds = []; // Prepare and append images containers and populate figure and captions IDs arrays for (var i = 0, fullImage; i < gallery.length; i++) { fullImage = create('div'); fullImage.className = 'full-image'; fullImage.id = 'baguette-img-' + i; imagesElements.push(fullImage); imagesFiguresIds.push('baguetteBox-figure-' + i); imagesCaptionsIds.push('baguetteBox-figcaption-' + i); slider.appendChild(imagesElements[i]); } overlay.setAttribute('aria-labelledby', imagesFiguresIds.join(' ')); overlay.setAttribute('aria-describedby', imagesCaptionsIds.join(' ')); } function setOptions(newOptions) { if (!newOptions) { newOptions = {}; } // Fill options object for (var item in defaults) { options[item] = defaults[item]; if (typeof newOptions[item] !== 'undefined') { options[item] = newOptions[item]; } } /* Apply new options */ // Change transition for proper animation slider.style.transition = slider.style.webkitTransition = (options.animation === 'fadeIn' ? 'opacity .4s ease' : options.animation === 'slideIn' ? '' : 'none'); // Hide buttons if necessary if (options.buttons === 'auto' && ('ontouchstart' in window || currentGallery.length === 1)) { options.buttons = false; } // Set buttons style to hide or display them previousButton.style.display = nextButton.style.display = (options.buttons ? '' : 'none'); // Set overlay color try { overlay.style.backgroundColor = options.overlayBackgroundColor; } catch (e) { // Silence the error and continue } } function showOverlay(chosenImageIndex) { if (options.noScrollbars) { document.documentElement.style.overflowY = 'hidden'; document.body.style.overflowY = 'scroll'; } if (overlay.style.display === 'block') { return; } bind(document, 'keydown', keyDownHandler); currentIndex = chosenImageIndex; touch = { count: 0, startX: null, startY: null }; loadImage(currentIndex, function() { preloadNext(currentIndex); preloadPrev(currentIndex); }); updateOffset(); overlay.style.display = 'block'; if (options.fullScreen) { enterFullScreen(); } // Fade in overlay setTimeout(function() { overlay.className = 'visible'; if (options.bodyClass && document.body.classList) { document.body.classList.add(options.bodyClass); } if (options.afterShow) { options.afterShow(); } }, 50); if (options.onChange) { options.onChange(currentIndex, imagesElements.length); } documentLastFocus = document.activeElement; initFocus(); isOverlayVisible = true; } function initFocus() { if (options.buttons) { previousButton.focus(); } else { closeButton.focus(); } } function enterFullScreen() { if (overlay.requestFullscreen) { overlay.requestFullscreen(); } else if (overlay.webkitRequestFullscreen) { overlay.webkitRequestFullscreen(); } else if (overlay.mozRequestFullScreen) { overlay.mozRequestFullScreen(); } } function exitFullscreen() { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } } function hideOverlay() { if (options.noScrollbars) { document.documentElement.style.overflowY = 'auto'; document.body.style.overflowY = 'auto'; } if (overlay.style.display === 'none') { return; } unbind(document, 'keydown', keyDownHandler); // Fade out and hide the overlay overlay.className = ''; setTimeout(function() { overlay.style.display = 'none'; if (document.fullscreen) { exitFullscreen(); } if (options.bodyClass && document.body.classList) { document.body.classList.remove(options.bodyClass); } if (options.afterHide) { options.afterHide(); } documentLastFocus && documentLastFocus.focus(); isOverlayVisible = false; }, 500); } function loadImage(index, callback) { var imageContainer = imagesElements[index]; var galleryItem = currentGallery[index]; // Return if the index exceeds prepared images in the overlay // or if the current gallery has been changed / closed if (typeof imageContainer === 'undefined' || typeof galleryItem === 'undefined') { return; } // If image is already loaded run callback and return if (imageContainer.getElementsByTagName('img')[0]) { if (callback) { callback(); } return; } // Get element reference, optional caption and source path var imageElement = galleryItem.imageElement; var thumbnailElement = imageElement.getElementsByTagName('img')[0]; var imageCaption = typeof options.captions === 'function' ? options.captions.call(currentGallery, imageElement) : imageElement.getAttribute('data-caption') || imageElement.title; var imageSrc = getImageSrc(imageElement); // Prepare figure element var figure = create('figure'); figure.id = 'baguetteBox-figure-' + index; figure.innerHTML = '<div class="baguetteBox-spinner">' + '<div class="baguetteBox-double-bounce1"></div>' + '<div class="baguetteBox-double-bounce2"></div>' + '</div>'; // Insert caption if available if (options.captions && imageCaption) { var figcaption = create('figcaption'); figcaption.id = 'baguetteBox-figcaption-' + index; figcaption.innerHTML = imageCaption; figure.appendChild(figcaption); } imageContainer.appendChild(figure); // Prepare gallery img element var image = create('img'); image.onload = function() { // Remove loader element var spinner = document.querySelector('#baguette-img-' + index + ' .baguetteBox-spinner'); figure.removeChild(spinner); if (!options.async && callback) { callback(); } }; image.setAttribute('src', imageSrc); image.alt = thumbnailElement ? thumbnailElement.alt || '' : ''; if (options.titleTag && imageCaption) { image.title = imageCaption; } figure.appendChild(image); // Run callback if (options.async && callback) { callback(); } } // Get image source location, mostly used for responsive images function getImageSrc(image) { // Set default image path from href var result = image.href; // If dataset is supported find the most suitable image if (image.dataset) { var srcs = []; // Get all possible image versions depending on the resolution for (var item in image.dataset) { if (item.substring(0, 3) === 'at-' && !isNaN(item.substring(3))) { srcs[item.replace('at-', '')] = image.dataset[item]; } } // Sort resolutions ascending var keys = Object.keys(srcs).sort(function(a, b) { return parseInt(a, 10) < parseInt(b, 10) ? -1 : 1; }); // Get real screen resolution var width = window.innerWidth * window.devicePixelRatio; // Find the first image bigger than or equal to the current width var i = 0; while (i < keys.length - 1 && keys[i] < width) { i++; } result = srcs[keys[i]] || result; } return result; } // Return false at the right end of the gallery function showNextImage() { return show(currentIndex + 1); } // Return false at the left end of the gallery function showPreviousImage() { return show(currentIndex - 1); } // Return false at the left end of the gallery function showFirstImage(event) { if (event) { event.preventDefault(); } return show(0); } // Return false at the right end of the gallery function showLastImage(event) { if (event) { event.preventDefault(); } return show(currentGallery.length - 1); } /** * Move the gallery to a specific index * @param `index` {number} - the position of the image * @param `gallery` {array} - gallery which should be opened, if omitted assumes the currently opened one * @return {boolean} - true on success or false if the index is invalid */ function show(index, gallery) { if (!isOverlayVisible && index >= 0 && index < gallery.length) { prepareOverlay(gallery, options); showOverlay(index); return true; } if (index < 0) { if (options.animation) { bounceAnimation('left'); } return false; } if (index >= imagesElements.length) { if (options.animation) { bounceAnimation('right'); } return false; } currentIndex = index; loadImage(currentIndex, function() { preloadNext(currentIndex); preloadPrev(currentIndex); }); updateOffset(); if (options.onChange) { options.onChange(currentIndex, imagesElements.length); } return true; } /** * Triggers the bounce animation * @param {('left'|'right')} direction - Direction of the movement */ function bounceAnimation(direction) { slider.className = 'bounce-from-' + direction; setTimeout(function() { slider.className = ''; }, 400); } function updateOffset() { var offset = -currentIndex * 100 + '%'; if (options.animation === 'fadeIn') { slider.style.opacity = 0; setTimeout(function() { supports.transforms ? slider.style.transform = slider.style.webkitTransform = 'translate3d(' + offset + ',0,0)' : slider.style.left = offset; slider.style.opacity = 1; }, 400); } else { supports.transforms ? slider.style.transform = slider.style.webkitTransform = 'translate3d(' + offset + ',0,0)' : slider.style.left = offset; } } // CSS 3D Transforms test function testTransformsSupport() { var div = create('div'); return typeof div.style.perspective !== 'undefined' || typeof div.style.webkitPerspective !== 'undefined'; } // Inline SVG test function testSvgSupport() { var div = create('div'); div.innerHTML = '<svg/>'; return (div.firstChild && div.firstChild.namespaceURI) === 'http://www.w3.org/2000/svg'; } // Borrowed from https://github.com/seiyria/bootstrap-slider/pull/680/files /* eslint-disable getter-return */ function testPassiveEventsSupport() { var passiveEvents = false; try { var opts = Object.defineProperty({}, 'passive', { get: function() { passiveEvents = true; } }); window.addEventListener('test', null, opts); } catch (e) { /* Silence the error and continue */ } return passiveEvents; } /* eslint-enable getter-return */ function preloadNext(index) { if (index - currentIndex >= options.preload) { return; } loadImage(index + 1, function() { preloadNext(index + 1); }); } function preloadPrev(index) { if (currentIndex - index >= options.preload) { return; } loadImage(index - 1, function() { preloadPrev(index - 1); }); } function bind(element, event, callback, options) { if (element.addEventListener) { element.addEventListener(event, callback, options); } else { // IE8 fallback element.attachEvent('on' + event, function(event) { // `event` and `event.target` are not provided in IE8 event = event || window.event; event.target = event.target || event.srcElement; callback(event); }); } } function unbind(element, event, callback, options) { if (element.removeEventListener) { element.removeEventListener(event, callback, options); } else { // IE8 fallback element.detachEvent('on' + event, callback); } } function getByID(id) { return document.getElementById(id); } function create(element) { return document.createElement(element); } function destroyPlugin() { unbindEvents(); clearCachedData(); unbind(document, 'keydown', keyDownHandler); document.getElementsByTagName('body')[0].removeChild(document.getElementById('baguetteBox-overlay')); data = {}; currentGallery = []; currentIndex = 0; } return { run: run, show: show, showNext: showNextImage, showPrevious: showPreviousImage, hide: hideOverlay, destroy: destroyPlugin }; }));
import $ from 'jquery'; import _ from 'lodash'; import FontFaceObserver from 'fontfaceobserver'; import React from 'react'; import ReactDom from 'react-dom'; import { IndexLink } from 'react-router'; import ReactVTT from '../../common/components/ReactVTT'; import VideoTrack from '../../common/components/VideoTrack'; import styles from './style.css'; const CLICK = 1; const SPACE = 32; const ESC = 27; export default class KaraokePage extends React.Component { constructor(props) { super(props); var track = this.fetchTrack(); var font = this.fetchFont(); this.state = { track: track, font: font, isPlaying: false, trackIsLoaded: !!track, fontIsLoaded: false, cues: {}, activeCue: null, currentTime: 0 }; this.updateTick = null; this.updateKaraoke = this.updateKaraoke.bind(this); this.handleTogglePlay = this.handleTogglePlay.bind(this); this.handleEnded = this.handleEnded.bind(this); } fetchTrack() { if(!this.props.trackStore.tracks.length) { return null; } if(this.props.location.query.track) { return this.props.trackStore.getTrackByName(this.props.location.query.track); } return this.props.trackStore.getRandom(); } fetchFont() { return this.props.fontStore.fonts.length ? this.props.fontStore.getFontByName(this.props.params.id) : null; } togglePlay(toState = null) { var toggleState = toState === null ? !this.state.isPlaying : toState; var toggleMethod = toggleState ? 'play' : 'pause'; var overlayMethod = toggleState ? 'addClass' : 'removeClass'; // only change the state if we can change the element's state if(this.refs.audio) { $(this.refs.overlay)[overlayMethod]('hide'); this.refs.audio[toggleMethod](); this.setState({ isPlaying: !this.refs.audio.paused }); } } play() { this.togglePlay(true); } pause() { this.togglePlay(false); } handleTogglePlay(event) { var $target = $(event.target); // if we're trying to go back, don't toggle play if ($target.attr('id') === 'back') { return; } switch (event.which) { case CLICK: this.togglePlay(); break; case SPACE: this.togglePlay(); break; case ESC: $('#back')[0].click(); break; } } handleEnded(event) { this.props.history.push('/'); } updateKaraoke() { // we can't do anything with no audio element if (!this.refs.audio) { console.warn('no audio to update karaoke'); return; } var updates = { currentTime: this.refs.audio.currentTime }; this.state.cues.update(updates.currentTime); if(this.state.cues.activeCues[0]) { updates.activeCue = this.state.cues.activeCues[0]; } this.setState(updates); // FIXME maybe avoid doing the above work by checking isPlaying earlier if(updates.activeCue && this.state.isPlaying) { ReactDom.render(<VideoTrack data={ ReactVTT.separate(this.state.activeCue) } currentTime={ this.state.currentTime } color={ this.state.font.color }/>, document.getElementById('video-vtt')); } this.updateTick = requestAnimationFrame(this.updateKaraoke); } initRecording() { var self = this; if(this.isLoading()) { return; } ReactVTT.parse(ReactVTT.fromSelectorOrPath('track#cues'), function(videoCues) { self.setState({ cues: videoCues }); self.updateTick = requestAnimationFrame(self.updateKaraoke); }); } isLoading(otherState) { var state = otherState ? otherState : this.state; return !state.fontIsLoaded || !state.trackIsLoaded; } componentWillReceiveProps(nextProps) { var track = this.fetchTrack(); var font = this.fetchFont(); this.setState({ track: track, font: font, trackIsLoaded: !!track }); } shouldComponentUpdate(nextProps, nextState) { return !_.isEqual(this.state.track, nextState.track) || this.isLoading() !== this.isLoading(nextState); } componentDidUpdate(prevProps, prevState) { this.initRecording(); } componentDidMount() { var self = this; var $document = $(document); $document.on('keyup click touch', this.handleTogglePlay); // wait for our font to load and then update when it has // pretty hacky var font = new FontFaceObserver(this.props.params.id); font.load(null, 5000) .then(function () { // set that we have loaded the font self.setState({ fontIsLoaded: true }) }) .catch(function() { // something wrong, try reloading the page window.location.reload(); }); // http://stackoverflow.com/questions/30855662/inline-html5-video-on-iphone } componentWillUnmount() { var $document = $(document); window.cancelAnimationFrame(this.updateTick); $document.off('keyup click touch'); } render() { var fontFace = ''; var overlay = (<div ref="overlay" className={ styles.description }>loading...</div>); if(this.state.font) { var fontFace = ` @font-face { font-family: "${this.state.font.name}"; src: url("${this.state.font.url}") format("opentype"); font-weight: normal; font-style: normal; } .kfont { font-family: "${this.state.font.name}"; } `; overlay = ( <div ref="overlay" className={ styles.description }> <p> { this.state.font.description } <a className={ styles.toggle } href="javascript:;">Test { this.state.font.name }</a> </p> </div> ); } if(this.isLoading()) { return ( <div id="content" className={ styles.content }> <style> { fontFace } </style> <IndexLink id="back" className={ styles.back } to="/"></IndexLink> { overlay } </div> ); } return ( <div id="content" className={ styles.content + ' kfont' } onEnded={ this.handleEnded }> <style> { fontFace } </style> <IndexLink id="back" className={ styles.back } to="/"></IndexLink> <audio ref="audio" className={ styles.audio }> <source src={ this.state.track.recording } type={ this.state.track.contentType }/> </audio> <video ref="video" className={ styles.video }> <source src={ this.state.track.recording } type={ this.state.track.contentType }/> <track id="cues" kind="subtitles" src={ this.state.track.getSubtitlesUrl() } srcLang="en" label="English" default/> </video> { overlay } <div id="video-vtt"> <VideoTrack/> </div> </div> ); } }
/* * Kendo UI v2014.2.716 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["bs-Latn-BA"] = { name: "bs-Latn-BA", numberFormat: { pattern: ["-n"], decimals: 2, ",": ".", ".": ",", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "%" }, currency: { pattern: ["-n $","n $"], decimals: 2, ",": ".", ".": ",", groupSize: [3], symbol: "KM" } }, calendars: { standard: { days: { names: ["nedjelja","ponedjeljak","utorak","srijeda","četvrtak","petak","subota"], namesAbbr: ["ned","pon","uto","sri","čet","pet","sub"], namesShort: ["ne","po","ut","sr","če","pe","su"] }, months: { names: ["januar","februar","mart","april","maj","juni","juli","avgust","septembar","oktobar","novembar","decembar",""], namesAbbr: ["jan","feb","mar","apr","maj","jun","jul","avg","sep","okt","nov","dec",""] }, AM: [""], PM: [""], patterns: { d: "d.M.yyyy", D: "d. MMMM yyyy", F: "d. MMMM yyyy H:mm:ss", g: "d.M.yyyy H:mm", G: "d.M.yyyy H:mm:ss", m: "d. MMMM", M: "d. MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "H:mm", T: "H:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM yyyy", Y: "MMMM yyyy" }, "/": ".", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
angular.module('maktaba.services') .factory('Documents', ['$resource', function($resource) { return $resource('/api/documents/:id', { id: '@id' }, { update: { // this method issues a PUT request method: 'PUT' } }, { stripTrailingSlashes: false }); }]);
var React = require("react"); var {Type, Node} = require("./base"); var {View} = require("./workbench"); var {CSideEffect} = require("./util"); var {ButtonGroup, Button, Glyphicon, Table} = require("react-bootstrap"); var saveAs = require("browser-filesaver"); // TODO Use a CSV lib? function csvLine(fields) { var line = ""; fields.forEach(field => { if (line.length > 0) line += ";" line += typeof field === "number" ? field : '"' + field.toString().replace(/"/g, '""') + '"'; }); line += "\n"; return line; } class BOMView { // TODO Replace itemList with something more generic, e.g., a // function mapping the item to extra info (but in what format?). constructor(name, itemList, bom) { this.name = name; var itemMap = {}; itemList.forEach(entry => itemMap[entry.itemId] = entry); this.__itemMap = itemMap; this.__bom = bom; } render() { return <div> <ButtonGroup> <Button onClick={() => this.exportCSV()}><Glyphicon glyph="th"/> export as CSV</Button> </ButtonGroup> {this.renderBOM()} </div>; } exportCSV() { var csv = []; var itemMap = this.__itemMap; this.__bom.mapItems( (item, quantity) => { var entry = itemMap[item]; var label = entry == undefined ? "" : entry.label; var matNo = entry == undefined ? "" : entry.materialNumber; csv.push(csvLine([quantity, item, label, matNo])); }); var blob = new Blob(csv, {type: "text/csv;charset=utf-8"}); saveAs(blob, "openCPQ.csv"); } renderBOM() { var itemMap = this.__itemMap; return <Table className="bom"> <colgroup> <col className="bom-col-quantity"/> <col className="bom-col-item"/> <col className="bom-col-description"/> <col className="bom-col-material-number"/> </colgroup> <thead> <tr> <th className="bom-quantity-head">#</th> <th className="bom-item-head">Item ID</th> <th className="bom-description-head">Description</th> <th className="bom-material-number-head">Material No.</th> </tr> </thead> <tbody> {this.__bom.empty() ? <tr><td colSpan={4}> <div className="validate validate-info">(no entries)</div> </td></tr> : this.__bom.mapItems( (item, quantity) => { var entry = itemMap[item]; var label = entry == undefined ? "(missing)" : entry.label; var matNo = entry == undefined ? "(missing)" : entry.materialNumber; return <tr> <td className="bom-quantity">{quantity}</td> <td className="bom-item">{item}</td> <td className="bom-description">{label}</td> <td className="bom-material-number">{matNo}</td> </tr>; } )} </tbody></Table>; } } function VBOM(itemList, {bom}) { return new BOMView("bom", itemList, bom); } function CBOMEntry(name, quantity, type) { return CSideEffect((node, {bom}) => bom.add(name, quantity), type) } module.exports = {VBOM, BOMView, CBOMEntry, csvLine};
import { ok } from 'assert' import { execSync } from 'child_process' import { statSync, readFileSync, writeFileSync } from 'fs' import { binary } from 'dr-js/module/common/format' import { createDirectory } from 'dr-js/module/node/file/File' import { getFileList } from 'dr-js/module/node/file/Directory' import { runSync } from 'dr-js/module/node/system/Run' import { modify } from 'dr-js/module/node/file/Modify' import { __VERBOSE__ } from './main' const initOutput = async ({ fromRoot, fromOutput, deleteKeyList = [ 'private', 'scripts', 'devDependencies' ], copyPathList = [ 'LICENSE', 'README.md' ], logger: { padLog, log } }) => { padLog('reset output') await modify.delete(fromOutput()).catch(() => {}) await createDirectory(fromOutput()) padLog(`init output package.json`) const packageJSON = require(fromRoot('package.json')) for (const deleteKey of deleteKeyList) { delete packageJSON[ deleteKey ] log(`dropped key: ${deleteKey}`) } writeFileSync(fromOutput('package.json'), JSON.stringify(packageJSON)) padLog(`init output file`) for (const copyPath of copyPathList) { if (copyPath === 'README.md') { // trim README.md NON_PACKAGE_CONTENT writeFileSync( fromOutput(copyPath), readFileSync(fromRoot(copyPath)).toString() .split(`[//]: # (NON_PACKAGE_CONTENT)`)[ 0 ] .trim() ) log(`copied: ${copyPath} (with NON_PACKAGE_CONTENT trimmed)`) } else { await modify.copy(fromRoot(copyPath), fromOutput(copyPath)) log(`copied: ${copyPath}`) } } return packageJSON } const packOutput = async ({ fromRoot, fromOutput, logger: { padLog, log } }) => { padLog('run pack output') execSync('npm --no-update-notifier pack', { cwd: fromOutput(), stdio: __VERBOSE__ ? 'inherit' : [ 'ignore', 'ignore' ], shell: true }) log('move to root path') const packageJSON = require(fromOutput('package.json')) const packName = `${packageJSON.name.replace(/^@/, '').replace('/', '-')}-${packageJSON.version}.tgz` await modify.move(fromOutput(packName), fromRoot(packName)) padLog(`pack size: ${binary(statSync(fromRoot(packName)).size)}B`) return fromRoot(packName) } const verifyOutputBinVersion = async ({ fromOutput, packageJSON, // optional if directly set `matchStringList` matchStringList = [ packageJSON.name, packageJSON.version ], logger: { padLog, log } }) => { padLog('verify output bin working') const outputBinTest = execSync('node bin --version', { cwd: fromOutput(), stdio: 'pipe', shell: true }).toString() log(`bin test output: ${outputBinTest}`) for (const testString of matchStringList) ok(outputBinTest.includes(testString), `should output contain: ${testString}`) } const verifyNoGitignore = async ({ path, logger: { padLog } }) => { padLog(`verify no gitignore file left`) const badFileList = (await getFileList(path)).filter((path) => path.includes('gitignore')) badFileList.length && console.error(`found gitignore file:\n - ${badFileList.join('\n - ')}`) ok(!badFileList.length, `${badFileList.length} gitignore file found`) } const getPublishFlag = (flagList) => { const isDev = flagList.includes('publish-dev') const isPublish = isDev || flagList.includes('publish') return { isPublish, isDev } } const checkPublishVersion = ({ isDev, version }) => isDev ? REGEXP_PUBLISH_VERSION_DEV.test(version) : REGEXP_PUBLISH_VERSION.test(version) const REGEXP_PUBLISH_VERSION = /^\d+\.\d+\.\d+$/ // 0.0.0 const REGEXP_PUBLISH_VERSION_DEV = /^\d+\.\d+\.\d+-dev\.\d+$/ // 0.0.0-dev.0 const publishOutput = async ({ flagList, packageJSON, pathPackagePack, // the .tgz output of pack extraArgs = [], logger }) => { const { isPublish, isDev } = getPublishFlag(flagList) if (!isPublish) return logger.padLog(`skipped publish output, no flag found`) if (!pathPackagePack || !pathPackagePack.endsWith('.tgz')) throw new Error(`[publishOutput] invalid pathPackagePack: ${pathPackagePack}`) if (!checkPublishVersion({ isDev, version: packageJSON.version })) throw new Error(`[publishOutput] invalid version: ${packageJSON.version}, isDev: ${isDev}`) logger.padLog(`${isDev ? 'publish-dev' : 'publish'}: ${packageJSON.version}`) runSync({ command: 'npm', argList: [ '--no-update-notifier', 'publish', pathPackagePack, '--tag', isDev ? 'dev' : 'latest', ...extraArgs ] }) } export { initOutput, packOutput, verifyOutputBinVersion, verifyNoGitignore, getPublishFlag, checkPublishVersion, publishOutput }
"use strict"; var commandToBuffer = require("./commandToBuffer"); var AudioState = module.exports = function(self) { this.self = self; }; AudioState.prototype.audioStreamingRunning = function(running) { var buffer = commandToBuffer(0, "AudioState", "AudioStreamingRunning", running); this.self._writePacket(this.self._networkFrameGenerator(buffer)); return this.self; };
'use strict'; var key_arr = document.getElementsByClassName('key'); var border = document.getElementById('key-container'); var keycode_letters = { key_nums: [82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76],//key codes key_letters: ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'],//array of keys key_sounds: ['sounds/lastsound.mp3', 'sounds/sound2.mp3', 'sounds/sound3.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound7.mp3', 'sounds/sound8.mp3', 'sounds/sound9.mp3' , 'sounds/last_sound2.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound4.mp3', 'sounds/sound5.mp3', 'sounds/sound6.mp3' , 'sounds/sound10.mp3'],//array of file names for sounds }; //var rotate = document.getElementsByClassName('record-div'); //rotate[i].classList.toggle('spinning-div'); //adds a listener to the page that records keycodes and plays corresponding sounds + vids window.addEventListener('keydown', keyHandler); window.addEventListener('keyup', upHandler); function keyHandler (event) { if(keycode_letters.key_nums.includes(event.keyCode)){ for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i]) { var audio = document.getElementById(event.keyCode.toString()); var filepath = keycode_letters.key_sounds[i]; audio.src = filepath; audio.play(); key_arr[i].classList.toggle('keythree'); border.style.boxShadow = '2px 2px 5px 5px white'; } } } }; function upHandler (event) { if(keycode_letters.key_nums.includes(event.keyCode)){ border.style.boxShadow = 'none'; for (var i = 0; i < keycode_letters.key_nums.length; i++) { key_arr[i].classList.toggle('keytwo'); if (event.keyCode === keycode_letters.key_nums[i]) { key_arr[i].classList.toggle('keythree'); } } } } //toggle method, class list
var through = require('through2'); var gutil = require('gulp-util'); var pathModule = require('path'); var sass = require('node-sass'); var less = require('less'); var fs = require('fs'); var autoprefixer = require('autoprefixer'); var postcss = require('postcss'); var PluginError = gutil.PluginError; // Constants // const PLUGIN_NAME = 'gulp-angular2-embed-sass'; module.exports = function (options) { options = options || {}; var content; var base; var matches; var styleUrlRegexp = /styleUrls[\'"\s]*:[\s]*\[(.*)\]/; const FOUND_SUCCESS = {}; const FOUND_ERROR = {}; const CODE_EXIT = {}; var debug = false; function log() { if (debug) { console.log.apply(console, arguments); } } // Calls sass compiler on the file // function compileSass(sassPaths, cb) { if (sassPaths.length > 0) { var path = pathModule.join(base, sassPaths.shift()); sass.render({ file: path, includePaths: options.includePaths || [] }, function(err, result) { if (err) { cb(FOUND_ERROR, 'Error while compiling sass template "' + path + '". Error from "node-sass" plugin: ' + err); } if (options.autoprefixer) { // Call autoprefixer on current built css postcss([ autoprefixer(options.autoprefixer) ]) .process(result.css) .then(function(prefixedResult) { // escape any backticks that comeup in the compiled css cb(FOUND_SUCCESS, prefixedResult.css.toString().replace(/\\([\s\S])|(`)/g,"\\$1$2"), sassPaths); }); } else { // escape any backticks that comeup in the compiled css cb(FOUND_SUCCESS, result.css.toString().replace(/\\([\s\S])|(`)/g,"\\$1$2"), sassPaths); } }); } else { cb(CODE_EXIT); } } // Calls sass compiler on the file // function compileLess(lessPaths, cb) { if (lessPaths.length > 0) { var path = pathModule.join(base, lessPaths.shift()); var content = fs.readFileSync(path, 'utf8'); less.render( content, function(err, result) { if (err) { cb(FOUND_ERROR, 'Error while compiling less template "' + path + '". Error from "less" plugin: ' + err); } if (options.autoprefixer) { // Call autoprefixer on current built css postcss([ autoprefixer(options.autoprefixer) ]) .process(result.css) .then(function(prefixedResult) { // escape any backticks that comeup in the compiled css cb(FOUND_SUCCESS, prefixedResult.css.toString().replace(/\\([\s\S])|(`)/g,"\\$1$2"), lessPaths); }); } else { // escape any backticks that comeup in the compiled css cb(FOUND_SUCCESS, result.css.toString().replace(/\\([\s\S])|(`)/g,"\\$1$2"), lessPaths); } }); } else { cb(CODE_EXIT); } } // Writes the new css strings to the file buffer // function joinParts(entrances) { var parts = []; parts.push(Buffer(content.substring(0, matches.index))); parts.push(Buffer('styles: [`')); for (var i=0; i<entrances.length; i++) { parts.push(Buffer(entrances[i].replace(/\n/g, ''))); if (i < entrances.length - 1) { parts.push(Buffer('`, `')); } } parts.push(Buffer('`]')); parts.push(Buffer(content.substr(matches.index + matches[0].length))); return Buffer.concat(parts); } function transform(file, enc, cb) { var pipe = this; var entrances = []; var compilers = { sass: compileSass, less: compileLess } // Ignore empty files // if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { throw new PluginError(PLUGIN_NAME, 'Streaming not supported. particular file: ' + file.path); } content = file.contents.toString('utf-8'); base = options.basePath ? options.basePath : pathModule.dirname(file.path); matches = styleUrlRegexp.exec(content); var compiler = compilers[options.type || 'sass']; // No matches // if (matches === null) { compileCallback(CODE_EXIT); return; } log('\nfile.path: ' + file.path); log('matches: ' + matches[1]); var sassPaths = matches[1].replace(/[\ '"]/g,"").split(','); compiler(sassPaths, compileCallback); function compileCallback(code, _string, sassPaths) { if (code === FOUND_SUCCESS) { entrances.push(_string); compiler(sassPaths, compileCallback); } else if (code === FOUND_ERROR) { if (options.skipErrors) { gutil.log( PLUGIN_NAME, gutil.colors.yellow('[Warning]'), gutil.colors.magenta(_string) ); compiler(sassPaths, compileCallback); } else { pipe.emit('error', new PluginError(PLUGIN_NAME, _string)); } } else if (code === CODE_EXIT) { if (entrances.length) { file.contents = joinParts(entrances); } cb(null, file); } } } return through.obj(transform); };
const test = require('ava') const evaluate = require('../evaluate') test('works', t => { t.is(evaluate('foo', { foo: 'hehe' }), 'hehe') })