text
stringlengths
2
6.14k
var HomeController = require("./Base"), View = require("../views/Base"), Service = require("../domain/concrete/services/HomeService.js"); module.exports = HomeController.extend({ name: "Home", // index action for home index: function(req, res, next) { var view = new View(res, 'home'); view.render({ title: 'Home' }); }, users: function(req, res, next) { var self = this; var view = new View(res, 'home'); var service = new Service(); var result = null; view.render({ title: 'Home Sweet Home + Users' }); } });
let point = require('./gis/protobuf/point_pb'); module.exports.Point2D = point.Point2D; module.exports.Point3D = point.Point3D; module.exports.MultiPoint2D = point.MultiPoint2D; module.exports.MultiPoint3D = point.MultiPoint3D; let linestring = require('./gis/protobuf/linestring_pb'); module.exports.LineString2D = linestring.LineString2D; module.exports.LineString3D = linestring.LineString3D; module.exports.MultiLineString2D = linestring.MultiLineString2D; module.exports.MultiLineString3D = linestring.MultiLineString3D; let polygon = require('./gis/protobuf/polygon_pb'); module.exports.Polygon2D = polygon.Polygon2D; module.exports.Polygon3D = polygon.Polygon3D; module.exports.MultiPolygon2D = polygon.MultiPolygon2D; module.exports.MultiPolygon3D = polygon.MultiPolygon3D;
'use strict'; import React from "react"; var RefreshButton = React.createClass({ render: function() { return ( <button type="button" className="refresh-button btn btn-info navbar-btn" title="Sync" onClick={this.props.onRefreshClick}> <span className={"fa fa-refresh" + (this.props.isSyncing ? " fa-spin" : "")}></span> </button> ); } }); export default RefreshButton;
var is = require('annois'); module.exports = function(op, y, x) { return is.number(op(y, x)); };
'use strict'; var mongoose = require('mongoose'), Schema = mongoose.Schema; var BookSchema = new Schema({ name: {type: String, required: true}, info: String, author: {type: String, required: true}, user: {type: Schema.Types.ObjectId, ref: 'User', required: true}, bookcase: {type: Schema.Types.ObjectId, ref: 'Bookcase', required: true}, shelf: {type: Number, required: true}, line: {type: Number, required: true}, active: Boolean }); module.exports = mongoose.model('Book', BookSchema);
'use strict'; const _ = require('lodash'); const Script = require('smooch-bot').Script; const scriptRules = require('./script.json'); module.exports = new Script({ processing: { //prompt: (bot) => bot.say('Beep boop...'), receive: () => 'processing' }, start: { receive: (bot) => { return bot.say('So you want to know more about MikeBot? Just say BOT to wake me up :) %[BOT](postback:bot)') .then(() => 'speak'); } }, speak: { receive: (bot, message) => { let upperText = message.text.trim().toUpperCase(); function updateSilent() { switch (upperText) { case "CONTACT TO MIKE": return bot.setProp("silent", false); case "MIKEBOT BACK": return bot.setProp("silent", false); default: return Promise.resolve(); } } function getSilent() { return bot.getProp("silent"); } function processMessage(isSilent) { if (isSilent) { return Promise.resolve("speak"); } if (!_.has(scriptRules, upperText)) { return bot.say(`So, I'm good at structured conversations but some stickers, emoji and sentences still confuse me :'(\nSay GOT IT to chat about something else.%[Got it](postback:got_it)`).then(() => 'speak'); } var response = scriptRules[upperText]; var lines = response.split('\n'); var p = Promise.resolve(); _.each(lines, function(line) { line = line.trim(); p = p.then(function() { console.log(line); return bot.say(line); }); }) return p.then(() => 'speak'); } return updateSilent() .then(getSilent) .then(processMessage); } } });
/* * @title Bump * @description A task to bump the bower and package version numbers * @summary Allowed bump types: major, minor, patch * @default patch * @example (cli) env BUMP_TYPE=major gulp bump */ /********************************************************************************* 1. DEPENDENCIES *********************************************************************************/ var bump = require('gulp-bump'); var gulp = require('gulp'); /********************************************************************************* 2. TASK *********************************************************************************/ gulp.task('bump', function () { return gulp .src(['./bower.json', './package.json']) .pipe(bump({ type: process.env.BUMP_TYPE })) .pipe(gulp.dest('./')); });
import jwt from 'jsonwebtoken'; import ErrorConstants from '../constants/ErrorConstants'; import { User } from '../models'; import Constants from '../constants/Constants'; const { userDeleteUnauthorizedError, voidUserDeleteError, } = ErrorConstants; /** * @description allows users to delete only his account. * Allows admin to delete all accounts * * @param {Request} request Http request object from express * @param {Response} response HTTP response object from express * @param {function} next next function provided by the express. * it passes control to the next middleware * * @returns {Promise | void} Promise from express HTTP response */ const deleteUserAuthorization = (request, response, next) => { let token = request.headers.authorization; token = token.split(' ')[1]; const user = jwt.decode(token).data; let statusCode = 400; const idToBeDeleted = request.params.id; User.findById(idToBeDeleted) .then((queryResult) => { const error = new Error(); if (!queryResult) { statusCode = 404; error.message = voidUserDeleteError; throw error; } const expectedUserId = queryResult.dataValues.id; if (expectedUserId !== user.id && user.roleId !== Constants.adminRole) { error.message = userDeleteUnauthorizedError; statusCode = 403; throw error; } next(); }) .catch(error => response .status(statusCode) .json({ error: error.message }) ); }; export default deleteUserAuthorization;
/* * Copyright (c) 2017. MIT-license for Jari Van Melckebeke * Note that there was a lot of educational work in this project, * this project was (or is) used for an assignment from Realdolmen in Belgium. * Please just don't abuse my work */ define(function (require) { 'use strict'; var zrUtil = require('zrender/core/util'); var graphic = require('../../util/graphic'); var AxisBuilder = require('./AxisBuilder'); var axisBuilderAttrs = [ 'axisLine', 'axisLabel', 'axisTick', 'axisName' ]; var selfBuilderAttrs = [ 'splitLine', 'splitArea' ]; require('../../echarts').extendComponentView({ type: 'radiusAxis', render: function (radiusAxisModel, ecModel) { this.group.removeAll(); if (!radiusAxisModel.get('show')) { return; } var polarModel = ecModel.getComponent('polar', radiusAxisModel.get('polarIndex')); var angleAxis = polarModel.coordinateSystem.getAngleAxis(); var radiusAxis = radiusAxisModel.axis; var polar = polarModel.coordinateSystem; var ticksCoords = radiusAxis.getTicksCoords(); var axisAngle = angleAxis.getExtent()[0]; var radiusExtent = radiusAxis.getExtent(); var layout = layoutAxis(polar, radiusAxisModel, axisAngle); var axisBuilder = new AxisBuilder(radiusAxisModel, layout); zrUtil.each(axisBuilderAttrs, axisBuilder.add, axisBuilder); this.group.add(axisBuilder.getGroup()); zrUtil.each(selfBuilderAttrs, function (name) { if (radiusAxisModel.get(name +'.show')) { this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords); } }, this); }, /** * @private */ _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) { var splitLineModel = radiusAxisModel.getModel('splitLine'); var lineStyleModel = splitLineModel.getModel('lineStyle'); var lineColors = lineStyleModel.get('color'); var lineCount = 0; lineColors = lineColors instanceof Array ? lineColors : [lineColors]; var splitLines = []; for (var i = 0; i < ticksCoords.length; i++) { var colorIndex = (lineCount++) % lineColors.length; splitLines[colorIndex] = splitLines[colorIndex] || []; splitLines[colorIndex].push(new graphic.Circle({ shape: { cx: polar.cx, cy: polar.cy, r: ticksCoords[i] }, silent: true })); } // Simple optimization // Batching the lines if color are the same for (var i = 0; i < splitLines.length; i++) { this.group.add(graphic.mergePath(splitLines[i], { style: zrUtil.defaults({ stroke: lineColors[i % lineColors.length], fill: null }, lineStyleModel.getLineStyle()), silent: true })); } }, /** * @private */ _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) { var splitAreaModel = radiusAxisModel.getModel('splitArea'); var areaStyleModel = splitAreaModel.getModel('areaStyle'); var areaColors = areaStyleModel.get('color'); var lineCount = 0; areaColors = areaColors instanceof Array ? areaColors : [areaColors]; var splitAreas = []; var prevRadius = ticksCoords[0]; for (var i = 1; i < ticksCoords.length; i++) { var colorIndex = (lineCount++) % areaColors.length; splitAreas[colorIndex] = splitAreas[colorIndex] || []; splitAreas[colorIndex].push(new graphic.Sector({ shape: { cx: polar.cx, cy: polar.cy, r0: prevRadius, r: ticksCoords[i], startAngle: 0, endAngle: Math.PI * 2 }, silent: true })); prevRadius = ticksCoords[i]; } // Simple optimization // Batching the lines if color are the same for (var i = 0; i < splitAreas.length; i++) { this.group.add(graphic.mergePath(splitAreas[i], { style: zrUtil.defaults({ fill: areaColors[i % areaColors.length] }, areaStyleModel.getAreaStyle()), silent: true })); } } }); /** * @inner */ function layoutAxis(polar, radiusAxisModel, axisAngle) { return { position: [polar.cx, polar.cy], rotation: axisAngle / 180 * Math.PI, labelDirection: -1, tickDirection: -1, nameDirection: 1, labelRotation: radiusAxisModel.getModel('axisLabel').get('rotate'), // Over splitLine and splitArea z2: 1 }; } });
define(["jquery","Velocity","easing"], function ($,velocity) { $.fn.collapsible = function(options) { var defaults = { accordion: undefined }; options = $.extend(defaults, options); return this.each(function() { var $this = $(this), $panel_headers = $(this).find('> li > .collapsible-header'), collapsible_type = $this.data("collapsible"); $this.off('click.collapse', '.collapsible-header'); $panel_headers.off('click.collapse'); function accordionOpen(object) { $panel_headers = $this.find('> li > .collapsible-header'); if (object.hasClass('active')) object.parent().addClass('active'); else object.parent().removeClass('active'); if (object.parent().hasClass('active')) object.siblings('.collapsible-body').stop(true,false).slideDown({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}}); else object.siblings('.collapsible-body').stop(true,false).slideUp({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}}); $panel_headers.not(object).removeClass('active').parent().removeClass('active'); $panel_headers.not(object).parent().children('.collapsible-body').stop(true,false).slideUp({ duration: 350,easing: "easeOutQuart",queue: false, complete: function() { $(this).css('height', ''); }}); } function expandableOpen(object) { if (object.hasClass('active')) object.parent().addClass('active'); else object.parent().removeClass('active'); if (object.parent().hasClass('active')) object.siblings('.collapsible-body').stop(true,false).slideDown({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}}); else object.siblings('.collapsible-body').stop(true,false).slideUp({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}}); } function isChildrenOfPanelHeader(object) { var panelHeader = getPanelHeader(object); return panelHeader.length > 0; } function getPanelHeader(object) { return object.closest('li > .collapsible-header'); } if (options.accordion || collapsible_type === "accordion" || collapsible_type === undefined) { // Handle Accordion $panel_headers = $this.find('> li > .collapsible-header'); $panel_headers.on('click.collapse', function (e) { var element = $(e.target); if (isChildrenOfPanelHeader(element)) element = getPanelHeader(element); element.toggleClass('active'); accordionOpen(element); }); accordionOpen($panel_headers.filter('.active').first()); } else { // Handle Expandables $panel_headers.each(function () { $(this).on('click.collapse', function (e) { var element = $(e.target); if (isChildrenOfPanelHeader(element)) element = getPanelHeader(element); element.toggleClass('active'); expandableOpen(element); }); if ($(this).hasClass('active')) expandableOpen($(this)); }); } }); }; });
fetch('https://foo.com/form-data') .then((response) => response.formData()) .then((formData) => console.log(formData.get('foo')); // bar BodyFormDataExample02.js
import Joi from 'joi'; import pluck from 'lodash/map'; import dates from '../lib/dates'; import validate from '../lib/validate'; import payoutMethods from '../ui/payout_methods'; import i18n from '../lib/i18n'; /** * New expense schema */ const schema = Joi.object().keys({ attachment: Joi.string().uri() .label('Photo') .allow(null), name: Joi.string().required() .label('Name'), email: Joi.string().email().required() .label('Email'), description: Joi.string().required() .label('Description'), amount: Joi.number().integer().min(1).required() .label('Amount'), // TODO add currency vat: Joi.number().precision(2).min(0).allow(null) .label('VAT'), incurredAt: Joi.date().max(dates().tomorrow).required() .raw() // doesn't convert date into Date object .label('IncurredAt'), category: Joi.string().required() .label('Category'), payoutMethod: Joi.string().valid(pluck(payoutMethods(i18n('en')), 'value')) // i18n.getString not used here .label('Reimbursement method'), paypalEmail: Joi.string().email() .label('PayPal email') .allow(null), notes: Joi.string() .label('Notes') .allow(null) }); export default (obj) => validate(obj, schema);
$(function(){ // set-up the favs_people table if it doesn't exist $(document).ready(function(){ db.transaction( function(transaction) { transaction.executeSql( 'CREATE TABLE IF NOT EXISTS favs_people '+ ' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, givenname TEXT NOT NULL, surname TEXT NOT NULL);' ); } ); }); // after loading the main people view load the number of favs out of the local database $('#people').live('pageAnimationEnd', function(event, info){ if (info.direction == 'out') { $(this).removeClass('active'); } else { // get number of favorites db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { $(".pfavscount").html('<small id="pfavscount" class="counter">'+results.rows.length+'</small>'); }, sqlError ); } ); $('#people-favorites').remove(); } }); // when animating into the people detail see if this item is a favorite or not $('#people-detail').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { checkPeopleFav(); } }); // draw the list of people favorites, use a hidden li item w/ id of #fav-ppl-clone to clone items $('#people-favorites').live('pageAnimationStart', function(event, info){ if (info.direction == 'in') { db.transaction( function(transaction) { transaction.executeSql( 'SELECT * FROM favs_people ORDER BY surname;', [], function(transaction,results) { var string_sep = 'A'; var string_sep_check = false; (results.rows.length > 0) ? $('#fav-ppl-info').hide() : $('#fav-ppl-info').show(); for (var i=0; i < results.rows.length; i++) { var row = results.rows.item(i); if ((string_sep_check == false) && (row.surname.substr(0,1) == 'A')) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep_check = true; } else if (string_sep != row.surname.substr(0,1)) { // duplicate an entry for a separator var newSepRow = $('#fav-ppl-clone').clone(); newSepRow.removeAttr('id'); newSepRow.removeAttr('style'); newSepRow.addClass('sep'); newSepRow.addClass('fav-ppl-sep'); newSepRow.appendTo('#fav-ppl-list'); newSepRow.html(row.surname.substr(0,1)); string_sep = row.surname.substr(0,1); } // duplicate an entry for a person var newFavRow = $('#fav-ppl-clone').clone(); newFavRow.removeAttr('id'); newFavRow.removeAttr('style'); newFavRow.data('entryId',row.id); newFavRow.addClass('fav-ppl-entry'); newFavRow.appendTo('#fav-ppl-list'); newFavRow.html("<a href=\"/people/?username="+row.username+"\"><span class='thin'>"+row.givenname+"</span> "+row.surname+"</a>"); } }, sqlError ); } ); } }); // when unloading the people details delete the div holding the old detail so divs with that ID load properly in future // also delete the sessionStorage data so the options can be re-populated cleanly in the future $('.people-list').live('pageAnimationEnd', function(event, info){ if (info.direction == 'in') { $('#people-detail').remove(); peopleFavSelected = false; delete sessionStorage.givenName; delete sessionStorage.surname; delete sessionStorage.username; } else { $('.fav-ppl-entry').remove(); $('.fav-ppl-sep').remove(); } }); // toggle fav graphic on and off when tapped as well as add and remove data from db $('#people-favorite-detail').live('tap',function(){ peopleFav(); }); }); var peopleFavSelected = false; // mark or unmark the item as a favorite function peopleFav() { if (peopleFavSelected == true) { db.transaction( function(transaction) { transaction.executeSql( 'DELETE FROM favs_people WHERE username = ?;', [sessionStorage.username], function() { peopleFavSelected = false; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); }, sqlError ); } ); } else if (peopleFavSelected == false) { db.transaction( function(transaction) { transaction.executeSql( 'INSERT INTO favs_people (username, givenname, surname) VALUES (?,?,?);', [sessionStorage.username, sessionStorage.givenName, sessionStorage.surname], function() { peopleFavSelected = true; $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); }, sqlError ); } ); } } // the actual function that checks if there is a favorite for the directory entry function checkPeopleFav() { db.transaction( function(transaction) { transaction.executeSql( 'SELECT id FROM favs_people WHERE username = ?;', [sessionStorage.username], function(transaction,results) { if (results.rows.length > 0) { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png'); peopleFavSelected = true; } else { $('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png'); peopleFavSelected = false; } }, sqlError ); } ); }
import { assert, JSData } from '../../_setup' import { productSchema } from './_productSchema' describe('Schema.pick', function () { it('has the right exports', function () { assert.isFunction(JSData.Schema.prototype.pick) }) it('Copies a value based on the properties defined in the schema', function () { const schema = new JSData.Schema(productSchema) const data = { id: 1, foo: 'bar', dimensions: { length: 1234, beep: 'boop' } } const copy = schema.pick(data) assert.deepEqual(copy, { id: 1, dimensions: { height: undefined, length: 1234, width: undefined }, name: undefined, price: undefined, tags: undefined, warehouseLocation: undefined }) }) it('Copies a value based on the items defined in the schema allowing extra properties', function () { const schema = new JSData.Schema({ type: 'object', properties: { id: { type: 'number' }, tags: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, id: { type: 'number' } }, additionalProperties: true } } }, additionalProperties: true }) const data = { id: 1, foo: 'bar', tags: [ { name: 'foo', beep: 'boop' } ] } const copy = schema.pick(data) assert.deepEqual(copy, { id: 1, foo: 'bar', tags: [ { name: 'foo', id: undefined, beep: 'boop' } ] }) }) it('Copies a value based on the items defined in the schema disallowing extra properties', function () { const schema = new JSData.Schema({ type: 'object', properties: { id: { type: 'number' }, tags: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, id: { type: 'number' } } } } } }) const data = { id: 1, foo: 'bar', tags: [ { name: 'foo', beep: 'boop' } ] } const copy = schema.pick(data, { strict: true }) assert.deepEqual(copy, { id: 1, // foo was stripped tags: [ { name: 'foo', id: undefined // beep was stripped } ] }) }) it('Copies a value based on the parent schema', function () { const schema = new JSData.Schema({ type: 'object', extends: productSchema, properties: { id: { type: 'number' }, roles: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, id: { type: 'number' } } } } } }) const data = { id: 1, foo: 'bar', roles: [ { name: 'foo', beep: 'boop' } ], dimensions: {} } const copy = schema.pick(data) assert.deepEqual(copy, { id: 1, dimensions: { height: undefined, length: undefined, width: undefined }, price: undefined, name: undefined, tags: undefined, roles: [ { name: 'foo', id: undefined } ], warehouseLocation: undefined }) }) it('should ignore undefined properties', function () { const store = new JSData.DataStore() const countrySchema = new JSData.Schema({ type: 'object', properties: { code: { type: 'string', indexed: true } } }) store.defineMapper('country', { schema: countrySchema }) store.add('country', [ { code: 'foo' }, { code: 'bar' } ]) const addressSchema = new JSData.Schema({ type: 'object', properties: { uid: { type: 'string' }, tag: { type: ['string', 'null'] }, country: { type: 'object', extends: countrySchema, get () { return store.getAll('country', this.tag, { index: 'code' })[0] } } } }) store.defineMapper('address', { schema: addressSchema }) const address = store.createRecord('address', { uid: '123', tag: 'foo' }) const address2 = store.createRecord('address', { uid: '789', tag: 'beep' }) assert.deepEqual(address.toJSON(), { uid: '123', tag: 'foo', country: { code: 'foo' } }) assert.deepEqual(address2.toJSON(), { uid: '789', tag: 'beep', country: undefined }) }) })
var puremvc = window.puremvc; var TodoProxy = require('../../model/proxy/TodoProxy'); class PrepModelCommand extends puremvc.SimpleCommand { execute() { this.facade.registerProxy(new TodoProxy()); } } module.exports = PrepModelCommand;
import Enzyme, { mount } from 'enzyme' import Adapter from 'enzyme-adapter-react-16' Enzyme.configure({ adapter: new Adapter() }) import { Line } from './Line' describe('<Line />', () => { let wrapper beforeEach(() => { wrapper = mount(<Line />) }) test('Should renderer', () => { expect(wrapper).toBeDefined() }) })
var gulp = require('gulp'); var ts = require('gulp-typescript'); var gutil = require('gulp-util'); var sourcemaps = require('gulp-sourcemaps'); var ddescribeIit = require('gulp-ddescribe-iit'); var shell = require('gulp-shell'); var ghPages = require('gulp-gh-pages'); var del = require('del'); var merge = require('merge2'); var clangFormat = require('clang-format'); var gulpFormat = require('gulp-clang-format'); var runSequence = require('run-sequence'); var webpack = require('webpack'); var webpackDemoConfig = require('./webpack.demo.js'); var PATHS = {src: 'src/**/*.ts', specs: 'src/**/*.spec.ts', demo: 'demo/**/*.ts', demoDist: 'demo/dist/**/*'}; // Transpiling & Building var buildProject = ts.createProject('tsconfig.json', {declaration: true}); gulp.task('clean:build', function() { return del('dist/'); }); gulp.task('cjs', function() { var tsResult = gulp.src([PATHS.src, '!' + PATHS.specs]).pipe(ts(buildProject)); return merge([tsResult.dts.pipe(gulp.dest('dist/cjs')), tsResult.js.pipe(gulp.dest('dist/cjs'))]); }); gulp.task('umd', function(cb) { webpack( { entry: './dist/cjs/core.js', output: {filename: 'dist/global/ng-bootstrap.js', library: 'ngb', libraryTarget: 'umd'}, externals: { 'angular2/angular2': {root: 'ng', commonjs: 'angular2/angular2', commonjs2: 'angular2/angular2', amd: 'angular2/angular2'} } }, function(err, stats) { if (err) throw new gutil.PluginError('webpack', err); gutil.log("[webpack]", stats.toString()); cb(); }); }); // Testing var testProject = ts.createProject('tsconfig.json'); function startKarmaServer(isTddMode, done) { var karmaServer = require('karma').Server; var travis = process.env.TRAVIS; var config = {configFile: __dirname + '/karma.conf.js', singleRun: !isTddMode, autoWatch: isTddMode}; if (travis) { config['reporters'] = ['dots']; config['browsers'] = ['Firefox']; } new karmaServer(config, done).start(); } gulp.task('clean:tests', function() { return del('temp/'); }); gulp.task('build:tests', function() { var tsResult = gulp.src(PATHS.src).pipe(sourcemaps.init()).pipe(ts(testProject)); return tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('temp')); }); gulp.task('clean:build-tests', function(done) { runSequence('clean:tests', 'build:tests', done); }); gulp.task( 'ddescribe-iit', function() { return gulp.src(PATHS.specs).pipe(ddescribeIit({allowDisabledTests: false})); }); gulp.task('test', ['clean:build-tests'], function(done) { startKarmaServer(false, done); }); gulp.task('tdd', ['clean:build-tests'], function(done) { startKarmaServer(true, function(err) { done(err); process.exit(1); }); gulp.watch(PATHS.src, ['build:tests']); }); // Formatting gulp.task('check-format', function() { return doCheckFormat().on( 'warning', function(e) { console.log("NOTE: this will be promoted to an ERROR in the continuous build"); }); }); gulp.task('enforce-format', function() { return doCheckFormat().on('warning', function(e) { console.log("ERROR: You forgot to run clang-format on your change."); console.log("See https://github.com/ng-bootstrap/core/blob/master/DEVELOPER.md#clang-format"); process.exit(1); }); }); function doCheckFormat() { return gulp.src(['gulpfile.js', 'karma-test-shim.js', PATHS.src, PATHS.demo]) .pipe(gulpFormat.checkFormat('file', clangFormat)); } // Demo gulp.task('clean:demo', function() { return del('demo/dist'); }); gulp.task('clean:demo-cache', function() { return del('.publish/'); }); gulp.task('copy:polyfills-demo', function() { gulp.src('./node_modules/angular2/bundles/angular2-polyfills.js').pipe(gulp.dest('./demo/dist/lib/')); }); gulp.task( 'demo-server', ['copy:polyfills-demo'], shell.task(['webpack-dev-server --config webpack.demo.js --inline --progress'])); gulp.task('build:demo', function(done) { var config = Object.create(webpackDemoConfig); config.plugins = config.plugins.concat(new webpack.optimize.UglifyJsPlugin()); webpack(config, function(err, stats) { if (err) throw new gutil.PluginError('build:demo', err); gutil.log('[build:demo]', stats.toString({colors: true})); done(); }); }); gulp.task('demo-push', function() { return gulp.src(PATHS.demoDist).pipe(ghPages()); }); // Public Tasks gulp.task('build', function(done) { runSequence('enforce-format', 'ddescribe-iit', 'test', 'clean:build', 'cjs', 'umd', done); }); gulp.task('deploy-demo', function(done) { runSequence('clean:demo', 'copy:polyfills-demo', 'build:demo', 'demo-push', 'clean:demo-cache', done); }); gulp.task('default', function(done) { runSequence('enforce-format', 'ddescribe-iit', 'test', done); });
/** * @license * Copyright (c) 2016 Nicholas Nelson * * 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. */ import GameTimer from './GameTimer'; import SceneHandler from './SceneHandler'; import ViewRenderer from './ViewRenderer'; /** * The Engine class, manages all aspects of the game */ class Engine { /** * Constructor for the game engine * @param {Element} canvas The HTML canvas to render on */ constructor(canvas) { this.timer = new GameTimer(); this.sceneHandler = new SceneHandler(); this.sceneHandler.init(); this.renderer = new ViewRenderer({ canvas: canvas, scene: this.sceneHandler.scene, world: this.sceneHandler.world}); } /** * Run one game tick, normally will be called by requestUpdateFrame * from app.js */ tick() { this.timer.update(); this.sceneHandler.update(this.timer.deltaTime); this.renderer.update(); this.renderer.render(this.sceneHandler); } } export { Engine as default };
var router = require('express').Router(); var Q = require('q'); var KEY = require('./key'); var User = require('../models/user.js'); var Comm = require('../comm'); var ERR = Comm.ERR; var FailProcess = Comm.FailProcess; /* * get: 注册页面 * post: 提交注册 */ router.route('/') .get(function(req, res){ return res.render('register', { title: 'Register', key: KEY.REGISTER }); }) .post(function(req, res){ var name = Comm.clearSpace(req.body.username); var nick = Comm.clearSpace(req.body.nick); var password = req.body.password; var vcode = Comm.clearSpace(req.body.vcode); var school = Comm.clearSpace(req.body.school); var email = Comm.clearSpace(req.body.email); var sig = Comm.clearSpace(req.body.signature); var ret = ERR.SYS; Q.fcall(function(){ if (!name || !nick || !Comm.isString(password) || !password || !vcode || school.length > 50 || email.length > 50 || sig.length > 200 || !Comm.isUsername(name)) { ret = ERR.ARGS; throw new Error('invalid args.'); } if (vcode.toLowerCase() !== req.session.verifycode) { ret = ERR.ARGS; throw new Error('wrong verify code.'); } return User.watch(name); }) .then(function(user){ if (user) { ret = ERR.ARGS; throw new Error('the user name has already been registered.'); } return (new User({ name: name, password: Comm.MD5(password), regTime: (new Date()).getTime(), nick: nick, school: school, email: email, signature: sig })).save(); }) .then(function(user){ req.session.user = user; req.session.msg = 'Welcome, '+name+'. :)'; res.send({ret: ERR.OK}); }) .fail(function(err){ FailProcess(err, res, ret); }) .done(); }); module.exports = router;
angular.module('demoApp').config([function() { }]);
/* */ var _curry1 = require('./internal/_curry1'); var curryN = require('./curryN'); module.exports = _curry1(function curry(fn) { return curryN(fn.length, fn); });
var GoogleMalwareList = require('./GoogleMalwareList'); var GooglePhishingList = require('./GooglePhishingList'); var DefaultLists = [ GoogleMalwareList, GooglePhishingList ]; module.exports = DefaultLists;
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' // 'starter.controllers' is found in controllers.js app = angular.module('suca', ['ionic', 'ionic-material']) .run([ '$rootScope', '$window', '$ionicPlatform', function($rootScope, $window, $ionicPlatform) { $ionicPlatform.ready(function() { // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard // for form inputs) if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if (window.StatusBar) { // org.apache.cordova.statusbar required StatusBar.styleDefault(); } }); $rootScope.user = {}; }]) .config([ '$stateProvider','$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider .state('login', { url: '/login', templateUrl: 'views/login/login.html', controller: 'LoginCtrl' }) .state('app', { url: '/app', abstract: true, templateUrl: 'views/menu/menu.html', controller: 'MenuCtrl' }) .state('app.search', { url: '/search', views: { //The menuContent works with Ionic widget 'menuContent': { templateUrl: 'views/search/search.html', controller: 'SearchCtrl' } } }) .state('app.photo', { url: '/photo', views: { 'menuContent': { templateUrl: 'views/photo/photo.html', controller: 'PhotoCtrl' } } }) .state('app.challenge', { url: '/challenge', views: { 'menuContent': { templateUrl: 'views/challenge/challenge.html', controller: 'ChallengeCtrl' } } }) .state('app.restaurant', { url: '/restaurant', views: { 'menuContent': { templateUrl: 'views/restaurant/restaurant.html', controller: 'RestaurantCtrl' } } }) .state('app.picture', { url: '/picture', views: { 'menuContent': { templateUrl: 'views/pictures/pictures.html', controller: 'PicturesCtrl' } } }) .state('app.settings', { url: '/settings', views: { 'menuContent': { templateUrl: 'views/settings/settings.html', controller: 'SettingsCtrl' } } }); /*.state('app.single', { url: '/playlists/:playlistId', views: { 'menuContent': { templateUrl: 'views/playlist.html', controller: 'PlaylistCtrl' } } });*/ // if none of the above states are matched, use this as the fallback $urlRouterProvider.otherwise('/login'); }]);
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M17 6H3v8h14V6zm-7 7c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z" opacity=".3" /><path d="M17 4H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM3 14V6h14v8H3z" /><path d="M10 7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zm13 0v11c0 1.1-.9 2-2 2H4v-2h17V7h2z" /></React.Fragment> , 'PaymentsTwoTone');
// let info = { // user: 'X', // comp: 'O' // }; // const settings = (state = info, action) => { // switch (action.type) { // case 'SET_USER_MARKER': // return { // user: action.marker, // comp: action.marker === 'X' ? 'O' : 'X' // }; // default: // return state; // } // }; // export default settings;
const assert = require('assert'); const is = require('is_js'); function StringBuilder() { const chars = []; //appends a value to the string function append(value) { assert.equal(is.not.object(value), true); value + ''; for (let i = 0; i < value.length; i++) { chars.push(value[i]); } } // removes any instance of the value from within the string function remove(value) { assert.equal(is.not.object(value), true); let j = 0; let strs = []; for (let i = 0; i < chars.length; i++) { if (chars[i] == value[j]) { let str = chars.slice(i, i + value.length); let matches = true; for (let k = 0; k < str.length; k++) { if (str[k] != value[j]) { matches = false; break; } j++; } if (matches) { chars.splice(i, value.length); } i = j; j = 0; } } } // returns the string let toString = function toString() { return chars.reduce((x, char) => { return x + char; }); } return { append: append, remove: remove, toString: toString, }; } module.exports = StringBuilder;
/* eslint-env node */ const GetterRegex = /^(?:chronology|dayOf(?:Month|Week|Year)|hashCode|hour|instant|millis|minute|month|monthValue|name|nano|lengthOf(?:Month|Year)|offset|ordinal|second|value|year)$/; module.exports = function({ types: t }) { const idEmber = t.identifier('Ember'); const idEmberObject = t.identifier('EmberObject'); const idGet = t.identifier('get'); const ComparableMixin = t.memberExpression( idEmber, t.identifier('Comparable') ); const assert = t.memberExpression(idEmber, t.identifier('assert')); return { visitor: { Program(path) { path.unshiftContainer( 'body', t.importDeclaration( [ t.importDefaultSpecifier(idEmberObject), t.importSpecifier(idGet, idGet) ], t.stringLiteral('@ember/object') ), t.importDeclaration( [t.importDefaultSpecifier(idEmber)], t.stringLiteral('ember') ) ); }, ClassDeclaration(path) { let didExtend = false; if (!path.node.superClass) { if ( ![ 'OffsetIdPrinterParser', 'ValueRange', 'DateTimeFormatter', 'FractionPrinterParser' ].includes(path.node.id.name) // FIXME: this is stupid ) { // extend leaf super classes from EmberObject path.node.superClass = idEmberObject; didExtend = true; } } for (const methodPath of path.get('body.body')) { if ( methodPath.node.type === 'ClassMethod' && !methodPath.node.static ) { if (didExtend && methodPath.node.kind === 'constructor') { // insert missing super call methodPath .get('body') .unshiftContainer('body', t.callExpression(t.super(), [])); } else if (methodPath.node.kind == 'method') { if (methodPath.node.key.name === 'compareTo') { // add compare method const a = t.identifier('a'); const b = t.identifier('b'); methodPath.insertAfter( t.classMethod( 'method', t.identifier('compare'), [a, b], t.blockStatement([ t.expressionStatement( t.callExpression(assert, [ t.stringLiteral( 'ember-joda: a must be equal to the object you are comparing on (this).' ), t.binaryExpression('===', t.thisExpression(), a) ]) ), t.returnStatement( t.callExpression( t.memberExpression( t.thisExpression(), methodPath.node.key ), [b] ) ) ]) ) ); // mixin Comparable mixin for comparable classes path .getStatementParent() .insertAfter( t.expressionStatement( t.callExpression( t.memberExpression( path.node.id, t.identifier('reopen') ), [ComparableMixin] ) ) ); } else if (methodPath.node.key.name === 'get') { // re-wrap Ember get method const bodyPath = methodPath.get('body'); bodyPath.replaceWith( t.blockStatement([ t.ifStatement( t.binaryExpression( '===', t.unaryExpression('typeof', methodPath.node.params[0]), t.stringLiteral('string') ), t.blockStatement([ t.returnStatement( t.callExpression(idGet, [ t.thisExpression(), methodPath.node.params[0] ]) ) ]), bodyPath.node ) ]) ); } else if ( methodPath.node.params.length === 0 && GetterRegex.test(methodPath.node.key.name) ) { // turn all getter methods into real getters methodPath.node.kind = 'get'; } } } } }, CallExpression(path) { // turn all getter call expressions into member expressions if ( path.node.arguments.length === 0 && t.isMemberExpression(path.node.callee) && t.isIdentifier(path.node.callee.property) && GetterRegex.test(path.node.callee.property.name) ) { path.replaceWith(path.node.callee); } } } }; }; module.exports.baseDir = function() { return __dirname; };
describe("About Expects", function() { //We shall contemplate truth by testing reality, via spec expectations. it("should expect true", function() { expect(true).toBeTruthy(); //This should be true }); //To understand reality, we must compare our expectations against reality. it("should expect equality", function () { var expectedValue = 2; var actualValue = 1 + 1; expect(actualValue === expectedValue).toBeTruthy(); }); //Some ways of asserting equality are better than others. it("should assert equality a better way", function () { var expectedValue = 3-1; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); //Sometimes you need to be really exact about what you "type". it("should assert equality with ===", function () { var expectedValue = "2"; var actualValue = (1 + 1).toString(); // toBe() will always use === to compare. expect(actualValue).toBe(expectedValue); }); //Sometimes we will ask you to fill in the values. it("should have filled in values", function () { expect(1 + 1).toEqual(2); }); });
import React from 'react'; import { Link } from 'react-router'; class Navbar extends React.Component { constructor(props) { super(props); this.url = location.href.split('#')[0]; this.updateContent = props.updateContent || function(){}; } componentDidMount() { this.initEvent(); } componentDidUpdate(prevProps) { } updateMenu(){ let urlparams = location.href.split('#/'); if(!!urlparams && urlparams.length>1){ let urlparam = urlparams[1].split("?_k=")[0]; if(!!urlparam){ $(".nav .active").removeClass("active"); $(".nav .nav_"+urlparam.replace("/","_")).addClass("active"); } } } initEvent(){ //var that = this; //$('.menu_li').click(function (e) { //e.preventDefault() //$(".active").removeClass("active"); //$(this).tab('show') //console.log('click:') //that.updateContent(); //}) /* <li className="menu_li nav_author nav_author_calligraphy"><Link to='/author/calligraphy'>美术字</Link></li> <li className="menu_li nav_author nav_author_self-portrait"><Link to='/author/self-portrait'>自画像</Link></li> <li className="menu_li nav_author nav_author_cloudscape"><Link to='/author/cloudscape'>云景</Link></li> <li className="menu_li nav_author nav_author_sculpture"><Link to='/author/sculpture'>雕刻</Link></li> */ } render() { return ( <div className="nav" id='nav'> <li className="nav_title" title="作品">作品</li> <li className="menu_li nav_art_all active"><Link to='/art/all'>全部</Link></li> <li className="nav_title" title="作者">作者</li> <li className="menu_li nav_author nav_author_all"><Link to='/author/all'>全部</Link></li> <li className="menu_li nav_author nav_author_abstract"><Link to='/author/abstract'>抽象概念</Link></li> <li className="menu_li nav_author nav_author_cityscape"><Link to='/author/cityscape'>城市景观</Link></li> <li className="menu_li nav_author nav_author_design"><Link to='/author/design'>结构</Link></li> <li className="menu_li nav_author nav_author_photo"><Link to='/author/photo'>照片</Link></li> <li className="menu_li nav_author nav_author_portrait"><Link to='/author/portrait'>人物描写</Link></li> <li className="menu_li nav_author nav_author_miniature"><Link to='/author/miniature'>微型画</Link></li> <li className="menu_li nav_author nav_author_illustration"><Link to='/author/illustration'>插图</Link></li> <li className="menu_li nav_author nav_author_painting"><Link to='/author/painting'>油画</Link></li> <li className="menu_li nav_author nav_author_landscape"><Link to='/author/landscape'>乡村风景画</Link></li> </div> ); } } export default Navbar;
/*global js_beautify: true */ /*jshint node:true */ var SanityTest = require('./sanitytest'), Urlencoded = require('../unpackers/urlencode_unpacker'), js_beautify = require('../beautify').js_beautify, run_beautifier_tests = require('./beautify-tests').run_beautifier_tests; function node_beautifier_tests() { var results = run_beautifier_tests(new SanityTest(), Urlencoded, js_beautify); console.log(results.results_raw()); return results; } if (require.main === module) { process.exit(node_beautifier_tests().get_exitcode()); } exports.node_beautifier_tests = node_beautifier_tests;
var jsonfile = require('jsonfile'); var logger = require('../logger.js'); var middleware = require('swagger-express-middleware'); var recursive = require('recursive-readdir'); var DataStoreLoader = {}; module.exports = DataStoreLoader; DataStoreLoader.load = function(myDB, baseDir) { // Filter function var ignoreFunc = function(file, stats) { return stats.isFile() && !file.endsWith('.json'); }; // Scan through the /db directory for all *.json files and add them into the custom data store recursive(baseDir, [ignoreFunc], function(err, files) { for (var i = 0; i < files.length; i++) { var file = files[i]; var path = file.slice(baseDir.length, file.length - 5).replace(/\\/g, '/'); var data = jsonfile.readFileSync(file, 'utf8'); logger.debug(`Loading file: ${file}, and configured path to: ${path}`); myDB.save(new middleware.Resource(path, data)); } }); }
const React = require('react') const ReactDOM = require('react-dom') const App = require('./App') ReactDOM.hydrate(React.createElement(App), document.getElementById('root'))
const onUpdatedProfileInfoSubscriptionsStub = [ { type: 'email', topic: 'News', isSubscribed: true }, { type: 'email', topic: 'Offers', isSubscribed: false }, { type: 'sms', isSubscribed: true } ] const onUpdatedProfileInfoStub = { operation: 'UpdateProfile', data: { customer: { authenticationTicket: 'xxxxx', ids: { bitrixId: 'user123' }, firstName: 'John', lastName: 'Dow', email: 'test@driveback.ru', mobilePhone: '79374134389', customFields: { source: 'Driveback', city: 'Moscow', b2b: true, childrenNames: [ 'Helen', 'Bob' ] }, subscriptions: [ { pointOfContact: 'Email', topic: 'News', isSubscribed: true }, { pointOfContact: 'Email', topic: 'Offers', isSubscribed: false }, { pointOfContact: 'Sms', isSubscribed: true } ] } } } export { onUpdatedProfileInfoSubscriptionsStub, onUpdatedProfileInfoStub }
'use strict'; var crayon = require('@ccheever/crayon'); function log() { var prefix = crayon.gray('[') + crayon.gray('exp') + crayon.gray(']'); var args = [prefix].concat(Array.prototype.slice.call(arguments, 0)); console.error.apply(console, args); } log.error = function error() { var prefix = crayon.red('[') + crayon.gray('exp') + crayon.red(']') + crayon.red.bold(' Error:'); var args = [prefix].concat(Array.prototype.slice.call(arguments, 0).map(function (x) { return crayon.red(x); })); console.error.apply(console, args); }; log.warn = function warn() { var prefix = crayon.yellow('[') + crayon.gray('exp') + crayon.yellow(']'); var args = [prefix].concat(Array.prototype.slice.call(arguments, 0).map(function (x) { return crayon.yellow(x); })); console.warn.apply(console, args); }; log.gray = function () { var prefix = '[exp]'; var args = [prefix].concat(Array.prototype.slice.call(arguments, 0)); crayon.gray.error.apply(crayon, args); }; log.crayon = crayon; module.exports = log; //# sourceMappingURL=sourcemaps/log.js.map
var Bob = function() { var isShouting = function(input) { return input.toUpperCase() === input && input.toLowerCase() !== input; }; var isQuestion = function(input) { return input.charAt(input.length - 1) === '?'; }; var isSilent = function(input) { return /^\s*$/.test(input); }; this.hey = function(input) { if (isSilent(input)) { return 'Fine. Be that way!'; } if (isShouting(input)) { return 'Whoa, chill out!'; } if (isQuestion(input)) { return 'Sure.'; } return 'Whatever.'; }; }; module.exports = Bob;
'use strict'; define(function () { return function () { return { firebase : { url : 'https://xxx.firebaseio.com/' }, /* * isLast() : gets if an index of an array is on the last index or not */ isLast : function (isLast) { return (isLast); }, /* * getLength() : gets the length of given array */ getLength : function(arr) { return (arr ? arr.length : 0); } }; } });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const express = require("express"); const app = express(); app.use(express.static('../frontend')); app.listen(3000, function () { console.log('listening on port 3000'); }); //# sourceMappingURL=index.js.map
(function() { 'use strict'; /** * Complex prototype for computation with complex numbers */ var Complex = function(real, imag) { if (!(this instanceof Complex)) { return new Complex(real, imag); } this.real = Number(real) || 0; this.imag = Number(imag) || 0; }; Complex.prototype.clone = function() { return new Complex(this.real, this.imag); }; Complex.toComplex = function(other) { if (other instanceof Complex) { return other; } else { return new Complex(Number(other) || 0, 0); } }; Complex.prototype.add = function(other) { return this.clone().iadd(other); }; Complex.prototype.iadd = function(other) { other = Complex.toComplex(other); this.real = this.real + other.real; this.imag = this.imag + other.imag; return this; }; Complex.prototype.sub = function(other) { return this.clone().isub(other); }; Complex.prototype.isub = function(other) { other = Complex.toComplex(other); this.real = this.real - other.real; this.imag = this.imag - other.imag; return this; }; Complex.prototype.mult = function(other) { return this.clone().imult(other); }; Complex.prototype.imult = function(other) { other = Complex.toComplex(other); var real = this.real * other.real - this.imag * other.imag, imag = this.imag * other.real + this.real * other.imag; this.real = real; this.imag = imag; return this; }; Complex.prototype.div = function(other) { return this.clone().idiv(other); }; Complex.prototype.idiv = function(other) { other = Complex.toComplex(other); var denom = other.real * other.real + other.imag * other.imag, real = (this.real * other.real + this.imag * other.imag) / denom, imag = (this.imag * other.real - this.real * other.imag) / denom; this.real = real; this.imag = imag; return this; }; Complex.prototype.conjugate = function() { return this.clone().iconjugate(); }; Complex.prototype.iconjugate = function() { this.imag = -this.imag; return this; }; Complex.prototype.abs = function() { return Math.sqrt(this.real * this.real + this.imag * this.imag); }; Complex.prototype.pow = function(n) { return this.clone().ipow(n); }; Complex.prototype.ipow = function(n) { var i, c; n = Number(n) || 0; if (n === 0) { this.real = 1; this.imag = 0; } else if (n < 0) { // Negative exponent n = -n; c = this.clone(); for (i = 1; i < n; i++) { c.imult(this); } this.real = 1; this.imag = 0; this.idiv(c); } else { // Normal exponent c = this.clone(); for (i = 1; i < n; i++) { c.imult(this); } this.real = c.real; this.imag = c.imag; } return this; }; Complex.prototype.squared = function() { return this.clone().ipow(2); }; Complex.prototype.isquared = function() { return this.ipow(2); }; // Export library module.exports = Complex; })();
import React from "react"; import DocSection from "../../docs/DocSection"; import { wrapSection } from "../../../hocs/WrapSection"; const enhancer = wrapSection( require.context("./examples", false, /.js$/), require.context("!!raw-loader!./examples", false, /.js$/), // eslint-disable-next-line import/no-webpack-loader-syntax require("!!react-docgen-loader!../../../../modules/marker/MarkerIcon"), ); function MarkerIconSection(props) { return <DocSection {...props} name="<MarkerIcon />" />; } export default enhancer(MarkerIconSection);
function makeRequest(page,divid) { var http_request = getHttpRequest(); http_request.onreadystatechange = function() { handle_request(http_request,divid); }; http_request.open('GET', page, true); http_request.send(null); return false; } function handle_request(handle,divid) { if (handle.readyState != 4) { document.getElementById(divid).innerHTML = 'Anropet misslyckades, kontakta oss om detta!'; return; } if (handle.status && handle.status != 200) { document.getElementById(divid).innerHTML = 'Ett fel har uppstått. Felkod: ' + handle.status; return; } document.getElementById(divid).innerHTML = handle.responseText; } //Returnerar ett XMLHttpRequest objekt function getHttpRequest() { var handle = false; if (window.XMLHttpRequest) { // Firefox, Opera, Safari handle = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Internet Explorer try { handle = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { handle = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if (!handle) { alert('Kan inte skapa ett XMLHTTP objekt'); return false; } return handle; }
//inicializamos eventos y procesos desde el DOM $(document).ready(function(){ IniciarEventos();} ); function IniciarEventos(){ $('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); $('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); fechaactual('fecdesde') fechaactual('fechasta') reloadList(rlink) $('#viewfaults').click(function(){ //call API changed state reloadList(rlink) }) $('#modalview').on('hidden.bs.modal', function () { $('#content').empty(); $(this).data('bs.modal', null); //<---- empty() to clear the modal }) } function reloadList(link){ serialize=$('#filter').serialize() $('#cargandodatos').show(1) $.post(link,serialize, function(data) { $('#listfaultcars').html(data); var divPaginationLinks = '#listfaultcars'+" .pagination a,.sort a"; $(divPaginationLinks).click(function(){ var thisHref = $(this).attr("href"); reloadList(thisHref); //recarmamos el proceso de carga return false; }); }).always(function() { $('#cargandodatos').hide(1) }); } function changestate(id){ if(typeof(id) != 'undefined'){ $.ajax({url:'/faultcars/faultcarschangedstatenj.json', type:'post', dataType:'json', headers: { 'Security-Access-PublicToken':'A33esaSP9skSjasdSfFSssEwS2IksSZxPlA4asSJ4GEW4S' }, data:{id:id,state:1}, success: function(data){ $.each( data, function( key, val ) { if(val.error != ''){ alert('Error: '+val.error) }else{ $('#faultend'+id).hide(1) } }); } }) } } function getubication(lat,lng){ $('#modalview').modal({ show: true, remote: '/faultcars/getubicationmaps/'+lat+'/'+lng }); return false }
function OrbitCamera(basecam) { this._cam = basecam; this._viewpos = new THREE.Vector3(0.0,0.0,0.0); this._theta = 0; this._phi = 0; this._rate = 0.05; this._minradius = 0.1; this._maxradius = 20.0; this._radius = 5.0; this._tarphi = 0.0; this._tartheta = 0.0; this._reftheta = 0.0; this._tracked = false; this._trackslope = 0.6; this._tracktheta = 0.0; } function sphericalToCartesian(phi, theta, rad, offset) { var y = Math.sin(phi) * rad; var r2 = Math.cos(phi) * rad; var x = Math.cos(theta) * r2; var z = Math.sin(theta) * r2; var ret = new THREE.Vector3(x, y, z); if(offset) { ret.add(offset); } return ret; } OrbitCamera.prototype.setTracking = function(trackstate) { if(trackstate == true) { this._tracked = true; this._tracktheta = this._reftheta; } else { this._tracked = false; this._viewpos.set(0,0,0); } }; OrbitCamera.prototype.updateTrack = function() { var trackdist = -this._trackslope * this._radius; this._tracktheta += ( this._reftheta - this._tracktheta ) * this._rate; var viewx = Math.cos(this._tracktheta) * trackdist; var viewz = Math.sin(this._tracktheta) * trackdist; this._viewpos.set(viewx, 0.0, viewz); }; OrbitCamera.prototype.updateCam = function() { if(this._tracked) { this.updateTrack(); } this._theta += ( this._tartheta + this._reftheta - this._theta ) * this._rate; this._phi += ( this._tarphi - this._phi ) * this._rate; this._cam.position.copy(sphericalToCartesian(this._phi, this._theta, this._radius, this._viewpos)); this._cam.lookAt( this._viewpos ); }; OrbitCamera.prototype.updateSpherical = function(targettheta, targetphi) { this._tarphi = targetphi; this._tartheta = targettheta; this.updateCam(); }; OrbitCamera.prototype.updateScreen = function(sx, sy, sw, sh) { var phi = ((sy / sh) * 2.0 - 1.0) * Math.PI; var theta = ((sx / sw) * 2.0 - 1.0) * Math.PI * 2.0; this.updateSpherical(theta, phi); }; OrbitCamera.prototype.updateZoomDelta = function(dzoom) { this._radius = Math.max(this._minradius, Math.min(this._maxradius, this._radius + dzoom)); this.updateCam(); }; OrbitCamera.prototype.setRefTheta = function(reftheta) { this._reftheta = reftheta; }; OrbitCamera.prototype.updateScreenDelta = function(dx, dy, sw, sh) { var dphi = ((dy / sh) * 1.0) * Math.PI; var dtheta = ((dx / sw) * 1.0) * Math.PI * 2.0; //console.log("sw: " + sw + ", sh: " + sh); //console.log("dphi: " + dphi + ", dtheta: " + dtheta); this._tartheta += dtheta; this._tarphi = Math.max(-Math.PI/2.0, Math.min(Math.PI/2.0, this._tarphi + dphi)); //console.log("tphi: " + this._tarphi + ", ttheta: " + this._tartheta); this.updateCam(); }; OrbitCamera.prototype.panScreenDelta = function(dx, dy, sw, sh) { var du = (dx / sw) * 100.0; var dv = (dy / sh) * 100.0; var ct = Math.cos(this._theta); var st = Math.sin(this._theta); var dz = du * ct - dv * st; var dx = -du * st - dv * ct; this._viewpos.x += dx; this._viewpos.z += dz; this.updateCam(); }; OrbitCamera.prototype.resetViewPos = function() { this._viewpos.set(0,0,0); }; var ocam; var mouseDownState = false; var mouseX = 0, mouseY = 0; var prevMouseX = 0, prevMouseY = 0; var mouseDX = 0, mouseDY = 0; var zoomButtonDown = false; var zoomButtonKeycode = 16; // shift var panButtonDown = false; var panButtonKeycode = 17; // ctrl function initOrbitCamera(rawcamera) { ocam = new OrbitCamera(rawcamera); document.addEventListener( 'mousedown', onCamMouseDown, false ); document.addEventListener( 'mouseup', onCamMouseUp, false ); document.addEventListener( 'mousemove', onCamDocumentMouseMove, false ); document.addEventListener( 'keydown', onCamDocumentKeyDown, false ); document.addEventListener( 'keyup', onCamDocumentKeyUp, false ); } function updateCamera() { mouseDX = mouseX - prevMouseX; mouseDY = mouseY - prevMouseY; prevMouseX = mouseX; prevMouseY = mouseY; if(mouseDownState == true) { //console.log("Dx: " + mouseDX + ", Dy: " + mouseDY) ocam.updateScreenDelta(mouseDX, mouseDY, windowX, windowY); } else if(zoomButtonDown) { ocam.updateZoomDelta(mouseDY / 10.0); } else if(panButtonDown) { ocam.panScreenDelta(mouseDX, mouseDY, windowX, windowY); } else { ocam.updateCam(); } } function onCamMouseDown() { mouseDownState = true; } function onCamMouseUp() { mouseDownState = false; } function onWindowResize() { getSize(); camera.aspect = windowX / windowY; camera.updateProjectionMatrix(); renderer.setSize( windowX, windowY ); } function onCamDocumentKeyDown(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = true; } if(event.keyCode == panButtonKeycode) { panButtonDown = true; } } function onCamDocumentKeyUp(event) { if(event.keyCode == zoomButtonKeycode) { zoomButtonDown = false; } if(event.keyCode == panButtonKeycode) { panButtonDown = false; } } function onCamDocumentMouseMove( event ) { mouseX = event.clientX - windowHalfX; mouseY = event.clientY - windowHalfY; }
import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as userInterfaceActions from '../actions/user_interface_actions'; import Dashboard from './dashboard'; const PortfolioApp = React.createClass({ render() { return ( <Dashboard {...this.props}/> ); } }); function mapStateToProps(state) { return { ...state.mainReducer }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ ...userInterfaceActions }, dispatch); } export default connect( mapStateToProps, mapDispatchToProps )(PortfolioApp);
import { TICK, TOGGLE, CLEAR, RANDOM } from '../constants/ActionTypes'; import { makeGrid, makeBlankGrid } from '../lib/grid'; import { nextState, toggle } from '../lib/game'; const GRID_SIZE = 30; const randomizer = (y, x) => Math.random(x + y) > 0.8; const DEFAULT_STATE = makeGrid(randomizer, GRID_SIZE); const clone = (xs) => xs.slice(); export default function grid(state = DEFAULT_STATE, action) { switch (action.type) { case TICK: return nextState(state); case TOGGLE: return toggle(action.coordinates, action.current, clone(state)); case CLEAR: return makeBlankGrid(GRID_SIZE, GRID_SIZE); case RANDOM: return makeGrid(randomizer, GRID_SIZE); default: return state; } }
'use strict'; module.exports.validateEmail = (email) => { let re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; let valid = re.test(email); let error = valid ? "" : "invalid e-mail"; return { valid: valid, value: email, error : error } /* NOTE: The regular expression used here DOES NOT comply to the required standard. In my book - however - this is good enough though. Mind that actual e-mail validation is about people submitting an e-mail address that actually works and that they have access to ... not about format. Oh and yes, regex is not my strong suit ... I learn it, use it, don't use it for a long time, forget it, need to learn it again ;) */ }
const path = require('path'); const docsConfig = require('./docs.config'); module.exports = Object.assign( {}, docsConfig, { plugins: [], devtool: 'module-source-map', devServer: { contentBase: path.resolve(__dirname, '../examples'), stats: { colors: true }, }, }, );
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const chalk_1 = require("chalk"); const command_1 = require("@ionic/cli-utils/lib/command"); const serve_1 = require("@ionic/cli-utils/lib/serve"); let DocsCommand = class DocsCommand extends command_1.Command { run(inputs, options) { return tslib_1.__awaiter(this, void 0, void 0, function* () { const { isSuperAgentError } = yield Promise.resolve().then(() => require('@ionic/cli-utils/guards')); const { createRequest } = yield Promise.resolve().then(() => require('@ionic/cli-utils/lib/http')); const browser = options['browser'] ? String(options['browser']) : undefined; const opn = yield Promise.resolve().then(() => require('opn')); const docsHomepage = 'https://ionicframework.com/docs'; let url = docsHomepage; const project = this.env.project.directory ? yield this.env.project.load() : undefined; if (project) { if (project.type === 'ionic1') { url = 'https://ionicframework.com/docs/v1/'; } else if (project.type === 'ionic-angular') { url = 'https://ionicframework.com/docs/api'; // TODO: can know framework version, HEAD request, etc } } try { const { req } = yield createRequest(this.env.config, 'head', url); yield req; } catch (e) { if (isSuperAgentError(e)) { if (e.response.status === 404) { this.env.log.warn(`Docs not found for your specific version of Ionic. Directing you to latest docs.`); opn(`${docsHomepage}/api`, { wait: false }); return; } } throw e; } yield opn(url, { app: browser, wait: false }); this.env.log.ok('Launched Ionic docs in your browser!'); }); } }; DocsCommand = tslib_1.__decorate([ command_1.CommandMetadata({ name: 'docs', type: 'global', description: 'Open the Ionic documentation website', options: [ { name: 'browser', description: `Specifies the browser to use (${serve_1.BROWSERS.map(b => chalk_1.default.green(b)).join(', ')})`, aliases: ['w'], advanced: true, }, ], }) ], DocsCommand); exports.DocsCommand = DocsCommand;
'use strict'; angular.module('simpleCharts', []);
/* * grunt-fea-build * https://github.com/bpletzer/FET-build-dep * * Copyright (c) 2013 Benedikt Pletzer * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>', ], options: { jshintrc: '.jshintrc', }, }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'], }, // Configuration to be run (and then tested). fea_build: { default_options: { options: { }, files: { 'tmp/default_options': ['test/fixtures/testing', 'test/fixtures/123'], }, }, custom_options: { options: { separator: ': ', punctuation: ' !!!', }, files: { 'tmp/custom_options': ['test/fixtures/testing', 'test/fixtures/123'], }, }, }, // Unit tests. nodeunit: { tests: ['test/*_test.js'], }, }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'fea_build', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
// Generated by CoffeeScript 1.3.3 (function() { var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; app.views.PostList = (function(_super) { __extends(PostList, _super); function PostList() { this.render = __bind(this.render, this); return PostList.__super__.constructor.apply(this, arguments); } PostList.prototype.el = function() { return document.getElementById('content'); }; PostList.prototype.render = function() { var $view, model, _i, _len, _ref, _results; this.$el = $(this.el); this.$el.html(''); _ref = this.model.models; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { model = _ref[_i]; $view = new app.views.Post[app.theme]({ model: model }).render(); if ($view != null) { _results.push($view.appendTo(this.el)); } else { _results.push(void 0); } } return _results; }; return PostList; })(Backbone.View); }).call(this);
modules.define('component', ['inherit'], function (provide, inherit) { /** * Base component * @implements IComponent */ provide(inherit({ _isStarted: false, start: function () { this._isStarted = true; }, stop: function () { this._isStarted = false; }, isStarted: function () { return this._isStarted; } }, { getName: function () {} })); });
// For development only!! // Add sample data to window object that used for initializing appendGrid. window.myAppendGridInitData = [{ "uid": "d4c74a61-a24e-429f-9db0-3cf3aaa22425", "name": "Monique Zebedee", "company": "Welch LLC", "country": "Japan", "memberSince": "2012-02-18", "orderPlaced": 111, "level": "Bronze", "isNPO": true }, { "uid": "afdf285d-da5c-4fa8-9225-201c858a173d", "name": "Daryle McLaren", "company": "Bogisich Group", "country": "United States", "memberSince": "2016-10-08", "orderPlaced": 261, "level": "Diamond", "isNPO": false }, { "uid": "202a8afb-130b-476b-b415-c659f21a73e7", "name": "Glori Spellecy", "company": "Grady and Sons", "country": "Germany", "memberSince": "2014-07-28", "orderPlaced": 282, "level": "Gold", "isNPO": false }, { "uid": "08c9adee-abdd-43d5-866d-ce540be19be8", "name": "Blondy Boggis", "company": "Eichmann, Parker and Herzog", "country": "Malaysia", "memberSince": "2010-08-17", "orderPlaced": 308, "level": "Platinum", "isNPO": true }, { "uid": "57644023-cd0c-47ec-a556-fd8d4e21a4e7", "name": "Batholomew Zecchii", "company": "Corwin-Fahey", "country": "Malaysia", "memberSince": "2016-09-20", "orderPlaced": 881, "level": "Gold", "isNPO": true }, { "uid": "38e08e8a-c7eb-41eb-9191-6bb2df1fd39b", "name": "Paulie Poel", "company": "MacGyver, Rohan and West", "country": "United Kingdom", "memberSince": "2016-12-26", "orderPlaced": 387, "level": "Silver", "isNPO": false }, { "uid": "d7bf56d4-f955-4dca-b3db-b30eab590028", "name": "Jessica Levett", "company": "Lind, O'Kon and Hamill", "country": "United States", "memberSince": "2015-04-26", "orderPlaced": 984, "level": "Gold", "isNPO": false }, { "uid": "b9075764-5228-4ca7-9435-7c362ce097e5", "name": "Fonsie Spring", "company": "McKenzie, Block and Wiegand", "country": "Japan", "memberSince": "2013-11-08", "orderPlaced": 875, "level": "Silver", "isNPO": false }];
const api = "http://127.0.0.1:3001/" let token = localStorage.token if (!token) token = localStorage.token = Math.random().toString(36).substr(-8) const headers = { 'Authorization': token, 'Content-Type': 'application/json', 'Accept': 'application/json' }; export const getCategories = () => { const url = api + "categories"; return fetch(url, {method: "GET", headers}).then(res => res.json()) }; export const getPostsByCategory = (categoryName) => { const url = api + categoryName + "/posts"; return fetch(url, {method: "GET", headers}).then(res => res.json()) }; export const getPosts = () => { const url = api + "posts"; return fetch(url, {method: "GET", headers}).then(res => res.json()) }; export const addPost = ({id, timestamp, title, body, author, category}) => { const url = api + "posts"; let post = {id, timestamp, title, body, author, category}; return fetch(url, {method: "POST", headers, body: JSON.stringify(post)}).then(res => res.json()) }; export const getPostDetail = (postId) => { const url = api + "posts/" + postId; return fetch(url, {method: "GET", headers}).then(res => res.json()) }; export const upVotePost = (postId) => { const url = api + "posts/" + postId; return fetch(url, { method: "POST", headers, body: JSON.stringify({option: "upVote"}) }).then(res => res.json()) }; export const downVotePost = (postId) => { const url = api + "posts/" + postId; return fetch(url, { method: "POST", headers, body: JSON.stringify({option: "downVote"}) }).then(res => res.json()) }; export const updatePost = ({id, title, body}) => { const url = api + "posts/" + id; const post = { title, body } return fetch(url, {method: "PUT", headers, body: JSON.stringify(post)}).then(res => res.json()) }; export const deletePost = (postId) => { const url = api + "posts/" + postId; return fetch(url, {method: "DELETE", headers}).then(res => res.json()) }; export const getAllComentsByPost = (postId) => { const url = api + "posts/" + postId + "/comments"; return fetch(url, {method: "GET", headers}).then(res => res.json()) }; export const addComment = ({id, timestamp, body, author, parentId}) => { const url = api + "comments"; const comment = {id, timestamp, body, author, parentId}; return fetch(url, {method: "POST", headers, body: JSON.stringify(comment)}).then(res => res.json()) }; export const getCommentDetail = (commentId) => { const url = api + "/comments/" + commentId; return fetch(url, {method: "POST", headers}).then(res => res.json()) }; export const upVoteComment = (commentId) => { const url = api + "comments/" + commentId; return fetch(url, { method: "POST", headers, body: JSON.stringify({option: "upVote"}) }).then(res => res.json()) }; export const downVoteComment = (commentId) => { const url = api + "comments/" + commentId; return fetch(url, { method: "POST", headers, body: JSON.stringify({option: "downVote"}) }).then(res => res.json()) }; export const updateComment = ({id, timestamp, body}) => { const url = api + "comments/" + id; const comment = {timestamp, body}; return fetch(url, {method: "PUT", headers, body: JSON.stringify(comment)}).then(res => res.json()) }; export const deleteComment = (commentId) => { const url = api + "comments/" + commentId; return fetch(url, {method: "DELETE", headers}).then(res => res.json()) };
const fs = require("fs") const dialog = require('./luis.js') fs.readdirSync('bot/luis/matches').forEach(file => require('./matches/' + file)) module.exports = dialog
(function (tree) { // // A function call node. // tree.Call = function (name, args, index) { this.name = name; this.args = args; this.index = index; }; tree.Call.prototype = { // // When evaluating a function call, // we either find the function in `tree.functions` [1], // in which case we call it, passing the evaluated arguments, // or we simply print it out as it appeared originally [2]. // // The *functions.js* file contains the built-in functions. // // The reason why we evaluate the arguments, is in the case where // we try to pass a variable to a function, like: `saturate(@color)`. // The function should receive the value, not the variable. // eval: function (env) { var args = this.args.map(function (a) { return a.eval(env) }); if (this.name in tree.functions) { // 1. try { return tree.functions[this.name].apply(tree.functions, args); } catch (e) { throw { type: e.type || "Runtime", message: "error evaluating function `" + this.name + "`" + (e.message ? ': ' + e.message : ''), index: this.index }; } } else { // 2. return new(tree.Anonymous)(this.name + "(" + args.map(function (a) { return a.toCSS() }).join(', ') + ")"); } }, toCSS: function (env) { return this.eval(env).toCSS(); } }; })(require('../tree'));
export default function (q1, q2, precision = 1e-6) { return ( Math.abs(q1[0] - q2[0]) <= precision && Math.abs(q1[1] - q2[1]) <= precision && Math.abs(q1[2] - q2[2]) <= precision && Math.abs(q1[3] - q2[3]) <= precision ); }
version https://git-lfs.github.com/spec/v1 oid sha256:c4eff6147e4aa3cd83b559adb30b75a42f984ca68528744b89729bb6f4fb4370 size 50687
'use strict'; const redirects = function (request, h) { return h.redirect('/').takeover(); }; module.exports = redirects;
const views = { engines: { pug: require('pug') }, relativeTo: __dirname, path: '../views' }; module.exports = views;
(function(){ 'use strict'; angular.module('playlistApp.track', []) .directive('pbTrack', function(){ return { restrict: 'E', templateUrl: 'components/track/track.html', scope: { track: '=', list: '=', index: '=' }, controller: function($scope, UserData, PlayerData){ $scope.addTrack = function(track){ UserData.addToCollection(track); }; $scope.playTrack = function(track){ PlayerData.setTrack(track, $scope.list, $scope.index); }; $scope.minutes = Math.floor(Math.round($scope.track.duration / 1000) / 60); $scope.seconds = Math.floor(Math.round($scope.track.duration / 1000) % 60); $scope.formattedDuration = $scope.minutes + ':' + $scope.seconds; }, link: function (scope, element, attrs) { } } }) })();
import React from 'react'; import highlight from './highlight'; export default options => { const { loader, isLanguageRegistered, registerLanguage, languageLoaders, noAsyncLoadingLanguages } = options; class ReactAsyncHighlighter extends React.PureComponent { static astGenerator = null; static highlightInstance = highlight(null, {}); static astGeneratorPromise = null; static languages = new Map(); static supportedLanguages = options.supportedLanguages || Object.keys(languageLoaders || {}); static preload() { return ReactAsyncHighlighter.loadAstGenerator(); } static async loadLanguage(language) { const languageLoader = languageLoaders[language]; if (typeof languageLoader === 'function') { return languageLoader(ReactAsyncHighlighter.registerLanguage); } else { throw new Error(`Language ${language} not supported`); } } static isSupportedLanguage(language) { return ( ReactAsyncHighlighter.isRegistered(language) || typeof languageLoaders[language] === 'function' ); } static isRegistered = language => { if (noAsyncLoadingLanguages) { return true; } if (!registerLanguage) { throw new Error( "Current syntax highlighter doesn't support registration of languages" ); } if (!ReactAsyncHighlighter.astGenerator) { // Ast generator not available yet, but language will be registered once it is. return ReactAsyncHighlighter.languages.has(language); } return isLanguageRegistered(ReactAsyncHighlighter.astGenerator, language); }; static registerLanguage = (name, language) => { if (!registerLanguage) { throw new Error( "Current syntax highlighter doesn't support registration of languages" ); } if (ReactAsyncHighlighter.astGenerator) { return registerLanguage( ReactAsyncHighlighter.astGenerator, name, language ); } else { ReactAsyncHighlighter.languages.set(name, language); } }; static loadAstGenerator() { ReactAsyncHighlighter.astGeneratorPromise = loader().then( astGenerator => { ReactAsyncHighlighter.astGenerator = astGenerator; if (registerLanguage) { ReactAsyncHighlighter.languages.forEach((language, name) => registerLanguage(astGenerator, name, language) ); } } ); return ReactAsyncHighlighter.astGeneratorPromise; } componentDidUpdate() { if ( !ReactAsyncHighlighter.isRegistered(this.props.language) && languageLoaders ) { this.loadLanguage(); } } componentDidMount() { if (!ReactAsyncHighlighter.astGeneratorPromise) { ReactAsyncHighlighter.loadAstGenerator(); } if (!ReactAsyncHighlighter.astGenerator) { ReactAsyncHighlighter.astGeneratorPromise.then(() => { this.forceUpdate(); }); } if ( !ReactAsyncHighlighter.isRegistered(this.props.language) && languageLoaders ) { this.loadLanguage(); } } loadLanguage() { const { language } = this.props; if (language === 'text') { return; } ReactAsyncHighlighter.loadLanguage(language) .then(() => { return this.forceUpdate(); }) .catch(() => {}); } normalizeLanguage(language) { return ReactAsyncHighlighter.isSupportedLanguage(language) ? language : 'text'; } render() { return ( <ReactAsyncHighlighter.highlightInstance {...this.props} language={this.normalizeLanguage(this.props.language)} astGenerator={ReactAsyncHighlighter.astGenerator} /> ); } } return ReactAsyncHighlighter; };
function validSlug(value) { return /^([a-zA-Z0-9-]*)?$/i.test(value); } function addSlugValidation(inputSlugId){ var inputSlug = $vic('#' + inputSlugId); displaySlugIcons(inputSlugId, inputSlug.val()); inputSlug.on('keyup', function(){ displaySlugIcons(inputSlugId, $vic(this).val()); }); } function displaySlugIcons(inputSlugId, slug){ var correctSlugIcon = $vic('#' + inputSlugId + '-correct'); var notCorrectSlugIcon = $vic('#' + inputSlugId + '-not-correct'); if (slug != 'undefined' && slug != "") { if (validSlug(slug)) { correctSlugIcon.removeClass('vic-hidden'); notCorrectSlugIcon.addClass('vic-hidden'); }else{ correctSlugIcon.addClass('vic-hidden'); notCorrectSlugIcon.removeClass('vic-hidden'); }; }else{ correctSlugIcon.removeClass('vic-hidden'); notCorrectSlugIcon.addClass('vic-hidden'); }; }
var request = require('request'); var Q = require('q'); module.exports = (function () { function FlickrAPI() {} FlickrAPI.ENDPOINT = 'https://api.flickr.com/services/rest/'; FlickrAPI.APIKey = '7c8048f68c6cffcf51b58b17380a90f5'; FlickrAPI.Secret = 'fb5c317f514c35b4'; FlickrAPI.prototype.tags = { getRelated: function (tag) { var deferred = Q.defer(); var query = { method: 'flickr.tags.getRelated', api_key: FlickrAPI.APIKey, tag: tag, format: 'json', nojsoncallback: 1 }; console.log('query', query); request({ uri: FlickrAPI.ENDPOINT, qs: query }, function (error, response, body) { console.log('got body: ', body); if (body) { deferred.resolve(JSON.parse(body)); } else { deferred.reject('error!'); } }); return deferred.promise; } }; return FlickrAPI; }());
/** * 把组件 MD 文档转为 hexo 最终渲染 MD,主要功能: * 1、增加头部信息,用于渲染左侧多级菜单 * 2、把组件内的 jsdoc 注释转为 MD 追加到尾部,用于生成 API 文档 * 3、把 DEMO 代码实例化为组件 * * author: Cody Chan <int64ago@gmail.com> 2017-02-08 */ /* eslint no-param-reassign: 0 */ const fs = require('fs-extra'); const path = require('path'); const glob = require('glob'); const jsdoc2md = require('jsdoc-to-markdown'); // 分类的顺序跟下面保持一致,每个分类下的组件顺序不作保证 const CATES = [ { cate: 'layout', name: '布局', startOrder: 100 }, { cate: 'form', name: '表单', startOrder: 200 }, { cate: 'notice', name: '通知', startOrder: 300 }, { cate: 'navigation', name: '导航', startOrder: 400 }, { cate: 'widget', name: '其它', startOrder: 500 }, ]; const DOC_PATH = __dirname; const COMPONENTS_PATH = path.join(__dirname, '../../src/js/components'); const COMPONENTS_DEST = path.join(DOC_PATH, 'components'); const getComponents = (cate) => { const fullPath = path.join(COMPONENTS_PATH, cate); return fs.readdirSync(fullPath).filter(f => fs.statSync(path.join(fullPath, f)).isDirectory()); }; const getDemoCode = (demo) => { const rglMatch = /(```(xml|html))([\s\S]*?)(```)/g.exec(demo); const jsMatch = /(```javascript)([\s\S]*?)(```)/g.exec(demo); return { rgl: rglMatch ? rglMatch[3] : '', js: jsMatch ? jsMatch[2] : 'var component = new NEKUI.Component({template: template});', }; }; const injectComponents = (md) => { const demos = []; const reg = /(<div class="grid-item" markdown="1">)([\s\S]*?)(</div>)/g; let match = reg.exec(md); while (match) { demos.push(getDemoCode(match[2])); match = reg.exec(md); } if (demos.length === 0) return md; let demosScript = '\n\n<script>\nvar index = 0;\n'; demos.forEach((demo) => { const tempJs = demo.js.replace(/`/gim, '\\`'); demosScript += ` (function(index) { var template = NEKUI._.multiline(function(){/* ${demo.rgl} */}); ${demo.js} component.$inject(document.querySelectorAll('.m-example')[index]); var gridItem = document.querySelectorAll('.grid-item')[index]; var codeDemo = document.createElement('div'); codeDemo.className = 'm-code'; var child = gridItem.childNodes; child.forEach(function(item,index){ if(item.tagName == 'FIGURE'){ codeDemo.appendChild(item); } }); gridItem.appendChild(codeDemo); var codeComponent = new DemoWrap({ data: { htmlTpl: codeDemo.innerHTML, htmlCode: \`${demo.rgl}\`, jsCode: \`${tempJs}\` } }); codeDemo.innerHTML = ''; codeComponent.$inject(codeDemo); })(index++); `; }); demosScript += '\n</script>\n'; return md + demosScript; }; const partial = glob.sync(path.join(DOC_PATH, 'partials/**/*.hbs')); const injectAPI = (md, source) => { const docs = jsdoc2md.renderSync({ source, 'no-cache': true, partial, configure: path.join(__dirname, 'jsdoc.json'), }); return `${md}\n# API\n${docs}`; }; const doc = (isDev, callback) => { // 其它文档 if (!isDev) { const mds = glob.sync(path.join(DOC_PATH, '**/*.md')); mds.forEach((md) => { fs.writeFileSync(md, injectComponents(fs.readFileSync(md, 'utf8'))); }); } // 组件文档 CATES.forEach((c) => { const components = getComponents(c.cate).filter((comp) => { // if (isDev && !/^KL(Sidebar|Modal|Draggable|Button|Loading|ImagePreview)$/.test(comp)) { // return false; // } const mdPath = path.join(COMPONENTS_PATH, c.cate, comp, 'index.md'); if (fs.existsSync(mdPath)) return true; return false; }); components.forEach((comp, i) => { const compPath = path.join(COMPONENTS_PATH, c.cate, comp); const mdPath = path.join(compPath, 'index.md'); const jsPath = path.join(compPath, 'index.js'); const appendContent = `type: components\nname: ${comp}\ncate: ${c.name}\norder: ${c.startOrder + i}\n`; let md = fs.readFileSync(mdPath, 'utf8'); // 插入文档头部信息 md = md.replace(/(^---)([\s\S]*?)(---)/g, `$1$2${appendContent}$3`); // 插入 API 文档 if (fs.existsSync(jsPath)) { md = injectAPI(md, fs.readFileSync(jsPath, 'utf8')); } // 插入实例化组件的脚本 md = injectComponents(md); fs.writeFileSync(path.join(COMPONENTS_DEST, `${c.cate}_${comp}_.md`), md); }); }); callback && callback(); }; module.exports = doc; </int64ago@gmail.com>
var structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial = [ [ "FloatAxial", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#addb3b8ac33094e21bd68f06c05af9ecf", null ], [ "FloatAxial", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#a04a78a140b41b1220373d94fb91dab28", null ], [ "ToFloatCubic", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#add3cd1669f683ed8aedc7926862ff265", null ], [ "q", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#a302dfd83ed44787f6fcccd3bdfa76a02", null ], [ "r", "structca_1_1axoninteractive_1_1_geometry_1_1_hex_1_1_float_axial.html#a2e3f908780aca1283e5f8793f9839279", null ] ];
import { withRouter } from 'next/router' function useWithRouter (props) { return <div>I use withRouter</div> } useWithRouter.getInitialProps = () => ({}) export default withRouter(useWithRouter)
import callApi from '../../util/apiCaller'; // Export Constants export const ACTIONS = { SET_ADMIN_SEARCH: 'SET_ADMIN_SEARCH', SET_ADMIN_CURRENT_PAGE: 'SET_ADMIN_CURRENT_PAGE', SET_ADMIN_MAX_PAGE: 'SET_ADMIN_MAX_PAGE', SET_ADMIN: 'SET_ADMIN', }; export function setSearch(search) { return { type: ACTIONS.SET_ADMIN_SEARCH, search }; } export function setCurrentPage(page) { return { type: ACTIONS.SET_ADMIN_CURRENT_PAGE, page }; } export function setMaxPage(page) { return { type: ACTIONS.SET_ADMIN_MAX_PAGE, page }; } export function setAdmin(admin) { return { type: ACTIONS.SET_ADMIN, admin }; } export function getAdminSearch(search, page) { return (dispatch) => { return callApi(`admin?search=${search}&page=${page}`, 'get', '' ).then(res => { dispatch(setAdmin(res.admin)); }); }; } export function deleteAdmin(del) { return () => { return callApi('admin/delete', 'post', '', {del}).then(res => { return res; }); }; } export function recoverAdmin(recover) { return () => { return callApi('admin/recover', 'post', '', {recover}).then(res => { return res; }); }; } export function createAdmin(admin) { return () => { return callApi('admin', 'post', '', {admin}).then(res => { return res.admin; }); }; }
export default { signupInitialState: { success: false, welcome: false, errors: null, fails: null }, signinInitialState: { success: false, errors: null, fails: null }, passwordInitialState: { message: null, success: false, errors: null, fails: null, resetMessage: null, resetSuccess: false, resetErrors: null, resetFails: null }, groupInitialState: { error: null, addUserErr: null, addUserSuccess: false, postMessageErr: null, groupMessagesErr: null, groupMessages: null, groupViewMessage: null, groupViewMessageErr: null, groupUsersStore: null, groupUsersError: null, userGroupsStore: null, userGroupsError: null, boardMessagesStore: null, boardMessagesError: null, usersSearch: null, usersSearchErr: null, messageRead: false, messageReadErr: null } };
define([ 'utils/Debug', 'core/Config', 'core/PubSub', 'core/Hub', 'utils/Dom', 'backbone', 'views/PageView', 'views/ToDoCollectionView', 'collections/ToDoCollection', 'caches/TodoCollectionCache' ], function( Debug, Config, PubSub, Hub, Dom, Backbone, PageView, ToDoCollectionView, ToDoCollection, ToDoCollectionCache ) { 'use strict'; // To supress REST warnings. Backbone.emulateHTTP = true; var log = Debug.log, moduleName = Config.moduleName, event = Config.event; /** * */ return { /** * */ run : function() { log('>>>bootstrap.run'); var toDos, toDoCollectionView, pageView, root = window[Config.ROOT_NAMESPACE] = {}; Hub.initialize(); toDos = new ToDoCollection(); log('[bootstrap] created collection'); toDos.add(ToDoCollectionCache.getAll()); log('[bootstrap] populated collection'); toDoCollectionView = new ToDoCollectionView({collection : toDos}); Hub.register(moduleName.MAIN_COLLECTION_VIEW, toDoCollectionView); log('[bootstrap] created collection view'); pageView = new PageView(); Hub.register(moduleName.MAIN_PAGE_VIEW, pageView); log('[bootstrap] created page view'); PubSub.publish(event.BOOTSTRAP_COMPLETE); root.hub = Hub; log('<<<bootstrap.run'); } }; });
module.exports = function(redis_client){ this.redis = redis_client; this.init = { kakao_rest_key: "653ef2a8cf89b38765bd83528f3c9012", kakao_redirect: "http://localhost:3000/oauth" }; this.MD5_SALT = { kakao: "VERyStronGPassword:)forKakaO" }; this.redis_key = { user: "DWT:user:", session: "DWT:session:" }; this.session = { time: 24*60*60 }; return this; };
{ 'type': 'game', // game or console 'name': 'Breakout', 'authors': [ 'Nolan Bushnell', 'Steve Bristow'], 'company': ['Atari, Inc'], 'year': '1976', 'date': '13-05-1976', // Day, Month, Year 'headline': 'Break blocs!', 'resume': [ 'Breakout é um jogo eletrônico para Arcade desenvolvido', 'pela Atari, Inc. Influenciado pelo pong, seu objetivo', 'é destruir todos os blocos da parte de cima', 'com uma bola, sem deixá-la cair, controlando uma barra na', 'parte de baixo da tela. Uma curiosidade é que o protótipo', 'foi feito por Steve Jobs e Woz, mais tarde, fundadores da apple.' ].join(''), 'full_text': [ 'Breakout é um jogo eletrônico para Arcade desenvolvido pela Atari,', 'Inc e lançado em 13 de maio de 1976. Foi idealizado por Nolan Bushnell', 'e Steve Bristow e influenciado pelo jogo de arcade de 1972 Pong, também da Atari.', 'O jogo foi convertido para os consoles e atualizado como Super Breakout.', 'Além disso, Breakout foi a base e inspiração para livros, ', 'jogos, e o computador Apple II. No jogo, uma camada de tijolos são alinhados no topo da tela.', 'A bola passa pela tela, rebatendo nas paredes laterais e superiores da tela.', 'Quando um tijolo é atingido, a bola rebate de volta e o tijolo é destruído.', 'O jogador perde uma vida quando a bola toca a parte inferior da tela.', 'Para prevenir que isso aconteça, o jogador move uma paleta para rebater a bola', 'para cima, mantendo-a no jogo. O breakout foi baseado no Pong, mudando apenas a mecânica do jogo' ].join(''), 'thumbnail': 'thumbnail_example.png', 'main_img': {'name': 'main_picture.png', 'caption': "Flyer Breakout"}, 'images': [ {'name': 'picture1.png', 'caption': "Gameplay do Breakout"}, {'name': 'picture2.png', 'caption': "Arcade do Breakout"}, {'name': 'picture3.png', 'caption': "Cartucho para Atari 2600"} ], 'video_gameplay': [ {'url': 'https://www.youtube.com/watch?v=JRAPnuwnpRs', 'caption': "Um vídeo de gameplay do Breakout", 'type': "youtube"} // type: youtube or vimeo ], 'demos': [ {'url': 'http://www.atari2600.com.br/Atari/Roms/0154/Breakout', 'caption': "Um simulador de breakout"} ], 'references': [ {'url': 'http://en.wikipedia.org/wiki/Breakout_%28video_game%29', 'caption': "Wikipédia"} {'url': 'http://pt.slideshare.net/gabrielalonso927/breakout-1976', 'caption': "Slides"} ] }
import { Meteor } from 'meteor/meteor'; import { Mongo } from 'meteor/mongo'; import { check } from 'meteor/check'; import { EasySearch } from 'meteor/easy:search' import { _ } from 'meteor/underscore'; // 스키마 임포트. import { EventSchema } from '/imports/schemas/event.js'; // 컬렉션 익스포트. export const Events = new Mongo.Collection('events'); // 컬렉션에 스키마 어태치. Events.attachSchema(EventSchema); // 검색용 인덱스 설정. export const EventsIndex = new EasySearch.Index({ engine: new EasySearch.MongoDB({ sort: function () { return { createdAt: -1 }; }, selector: function (searchObject, options, aggregation) { let selector = this.defaultConfiguration().selector(searchObject, options, aggregation), groupFilter = options.search.props.groupFilter; if (_.isString(groupFilter) && !_.isEmpty(groupFilter)) { selector.group = groupFilter; } return selector; } }), collection: Events, fields: ['title', 'createdAt'], defaultSearchOptions: { limit: 10 }, permission: () => { //console.log(Meteor.userId()); return true; } }); // 서버에서만 실행. if (Meteor.isServer) { // 퍼블리싱. Meteor.publish('events', function publication() { return Events.find(); }); }; Meteor.methods({ 'events.insert'(event) { // check arguments. check(event, { title: String, text: String, start: String, end: String, titleImage: String, eventImage: String }); // Insert. Events.insert(event, { clean: false, validate: true, filter: false }, function(error, result) { if (error) { console.log("Error:", error); return error; } }); }, 'events.findOne'(id) { // Find(1). check(id, String); Events.findOne(id); }, 'events.update'(id, event) { // check arguments. check(id, String); check(event, { title: String, text: String, start: String, end: String, titleImage: String, eventImage: String }); // Update. Events.update(id, {$set: event}, { clean: false, validate: true, filter: false }, function(error, result) { if (error) { console.log("Error:", error); } }); }, 'events.remove'(id) { // Remove. check(id, String); Events.remove(id); }, });
'use strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var PostcardSchema = new mongoose.Schema({ user: [{ type: Schema.ObjectId, ref: 'User' }], candidate: [{ type: Schema.ObjectId, ref: 'Candidate' }], message: String, state: [{ type: Schema.ObjectId, ref: 'State' }], price: Number, from: { name: String, street_address: String, city: String, state: String, zip: Number }, payment_id : String }); module.exports = mongoose.model('Postcard', PostcardSchema);
"use strict" var MINUTE = 60000 var EventEmitter = require('events') var format = require('python-format') var WebSocketClient = require('websocket').client var request = require('request') function objectHas(object, key) { return Object.prototype.hasOwnProperty.call(object, key) } function copySafely(target, configuration, keys) { var added = 0 for (var key in configuration) { if (!objectHas(configuration, key)) return if (!objectHas(keys, key)) { throw new TypeError(format("Unrecognized key '{}'", key)) } target[key] = configuration[key] added += 1 } if (added !== Object.keys(keys).length) { var message = format("Expected {} keys, got {}.", keys.size, added) throw new TypeError(message) } } function Showdown(configuration) { this.queue = Promise.resolve() copySafely(this, configuration, Showdown.keys) } Showdown.keys = { server: true, serverport: true, serverid: true, nickname: true, password: true, room: true } Showdown.commands = new Map([ ['challstr', 'finalize'], ['c:', 'onChatMessage'], ]) Showdown.prototype = new EventEmitter Showdown.prototype.connect = function connect() { var connection = new WebSocketClient connection.on('connectFailed', this.onConnectionFailure.bind(this)) connection.on('connect', this.onConnect.bind(this)) var connectionString = this.getConnectionString() connection.connect(connectionString, []) } Showdown.prototype.getConnectionString = function getConnectionString() { return format( 'ws://{}:{}/showdown/websocket', this.server, this.serverport ) } Showdown.prototype.onConnectionFailure = function onConnectionFailure(error) { console.error('Error occured (%s), will connect in a minute', error) setTimeout(this.connect.bind(this), MINUTE) } Showdown.prototype.onConnect = function onConnect(connection) { this.connection = connection var onConnectionFailure = this.onConnectionFailure.bind(this) connection.on('error', onConnectionFailure) connection.on('close', onConnectionFailure) connection.on('message', this.onMessage.bind(this)) console.info('Connected to Showdown server') } Showdown.prototype.onMessage = function onMessage(message) { if (message.type !== 'utf8') return this.parseMessage(message.utf8Data) } Showdown.prototype.parseMessage = function parseMessage(message) { console.log(message) var parts = message.split('|') if (Showdown.commands.has(parts[1])) { this[Showdown.commands.get(parts[1])](parts) } } Showdown.prototype.finalize = function finalize(parts) { var id = parts[2] var str = parts[3] var nickname = this.nickname var password = this.password request.post( format('https://play.pokemonshowdown.com/~~{}/action.php', this.serverid), { form: { act: 'login', challengekeyid: id, challenge: str, name: nickname, pass: password } }, function finish(error, response, body) { var result = JSON.parse(body.replace(/^]/, "")) var assertion = result.assertion var command = format('/trn {},0,{}', nickname, assertion) this.report(command) this.report('/join ' + this.room) this.report('/away') }.bind(this) ) } Showdown.prototype.onChatMessage = function onChatMessage(parts) { this.emit('message', parts[3], parts.slice(4).join('|')) } Showdown.prototype.report = function report(message) { this.queue = this.queue.then(() => { this.connection.send(`${this.room}|${message}`) return new Promise(resolve => { setTimeout(resolve, 500) }) }) } module.exports = Showdown
var HOME = "app_dev.php/"; var first_time = 1; var app_container = $("#backbone_container"); function showPrettyBackground() { $('<canvas class="blur" src='+canvasbg+' width="500" height="357">').appendTo( $('#container') ); $(".blur").each(function() { var element = this; var img = new Image; img.onload = function() { t = new CanvasImage(element, this); t.blur(5); }; img.src = $(this).attr("src"); }); $('.blur').animate({ opacity: 0.7 }, 1000, function() {}); } function firstTime() { $('#container').removeClass('hide'); setTimeout(showPrettyBackground, 200); $('#html_container').animate({ opacity: 1 }, 300, function() {}); first_time = 0; } $(function() { var doc_width = $('#below_header').width(); var animeteLogoInterval = null; var template = function(template, data) { return _.template( $("#" + template).html(), data ); } var animateLogo = function() { $('.logo').animate({ 'background-position-y': '26' }, 1000, function() { $('.logo').css('background-position-y', '0'); }) } $(document).ajaxStop(function() { $("html, body").animate({ scrollTop: 0 }, "fast"); }); $('#html_container').css('opacity', 0.1); $('#html_container').html(''); window.App = { Models: {}, Views: {}, Collections: {}, Router: {} } App.Models.Post = Backbone.Model.extend({ url: Routing.generate('blog_getarticles') }); App.Collections.Posts = Backbone.Collection.extend({ model: App.Models.Post, url: Routing.generate('blog_getarticles') }); App.Views.Page = Backbone.View.extend({ initialize: function(options) { this.options = options; this.events = _.extend({}, App.Views.Page.prototype.events, this.events) this.render(); }, events: { 'click a[data-href]': function(e) { approuter.navigate( $(e.target).attr('href'), true ); e.preventDefault(); } }, doStuffAfterFetch: function() { if (first_time == 1) { firstTime(); } else { window.clearInterval(animeteLogoInterval); $('#below_header').animate({ 'margin-right': '0px', 'opacity': 1 }, 200); } } }); App.Views.PostListSingle = App.Views.Page.extend({ template: template("article_list_single"), render: function() { this.$el.html( this.template({ article: this.model.toJSON() })); return this; } }) App.Views.PostList = App.Views.Page.extend({ render: function() { var self = this; var opt = {}; if (this.options.tag) { opt.tag = this.options.tag; } self.options.collection.fetch({ data: $.param( opt ), success: function() { self.$el.empty(); $('#comments_container').empty(); self.options.collection.each(function(post) { var postView = new App.Views.PostListSingle({ model: post }); self.$el.append( postView.render().el ); }); self.doStuffAfterFetch(); } }); } }) App.Views.PostSingle = App.Views.Page.extend({ render: function() { var self = this; self.options.model.fetch({ data: $.param({ id: this.options.id }), success: function() { var article = template("article_single", { data: self.options.model.toJSON() } ); var comments = template("article_comments", { data: self.options.model.toJSON() } ); self.$el.html( article ); $('#comments_container').html( comments ); self.doStuffAfterFetch(); } }); } }); App.Router = Backbone.Router.extend({ initialize: function() { this.bind("all", this.change) }, change: function() { if (!first_time) { animateLogo(); animeteLogoInterval = setInterval(animateLogo, 1000); $('#below_header').animate({ 'margin-right': '30px', 'opacity': 0.5 }, 200); } }, routes: { "app_dev.php/post/:id": "getPost", "app_dev.php/tag/:id": "getPostsWithTag", "*actions": "getIndex" } }); var approuter = new App.Router(); approuter.on('route:getIndex', function() { new App.Views.PostList({ el: $("#html_container"), collection: new App.Collections.Posts }); }); approuter.on('route:getPostsWithTag', function(tag) { new App.Views.PostList({ el: $("#html_container"), collection: new App.Collections.Posts, tag: tag }); }); approuter.on('route:getPost', function(link) { new App.Views.PostSingle({ el: $("#html_container"), model: new App.Models.Post, id: link }); }); App.Views.Header = Backbone.View.extend({ el: '#header', events: { 'click .logo': function(e) { approuter.navigate( Routing.generate('blog_homepage'), true ); e.preventDefault(); } } }) new App.Views.Header; Backbone.history.start({ pushState: true }); });
import * as Fathom from 'fathom-client'; function getSupport() { window.open('https://github.com/gotdibbs/Dynamics-365-Toolkit/issues/', '_new'); Fathom.trackGoal('GFT1EFPR', 0); } export default { action: getSupport, key: 'get-support', title: 'Get Support', description: 'Takes you to a form to submit an issue or request.', requiresForm: false };
'use strict'; import Mraa from 'mraa'; import config from 'config'; import logger from './logger'; const Gate = function () { const { port, time } = config.get('gate'); Mraa.init(); const pin = new Mraa.Gpio(port); pin.dir(Mraa.DIR_OUT); let timeout; this.open = () => { logger.info('requesting gate open'); pin.write(1); clearTimeout(timeout); timeout = setTimeout(this.close, time); }; this.close = () => { logger.info('requesting gate close'); pin.write(0); }; }; export default Gate;
import Theme from '../../../src/utils/theme'; function getHighlightResult( fillMode, color, isDark, bgClass = '', contentClass = '', ) { let styles = {}; let classes = {}; if (bgClass) { classes.class = bgClass; } if (contentClass) { classes.contentClass = contentClass; } switch (fillMode) { case 'none': { styles = { style: { backgroundColor: isDark ? 'var(--gray-900)' : 'var(--white)', border: '2px solid', borderColor: isDark ? `var(--${color}-200)` : `var(--${color}-700)`, borderRadius: 'var(--rounded-full)', }, contentStyle: { color: isDark ? `var(--${color}-100)` : `var(--${color}-900)`, fontWeight: 'var(--font-bold)', }, }; break; } case 'light': { styles = { style: { backgroundColor: isDark ? `var(--${color}-800)` : `var(--${color}-200)`, opacity: isDark ? 0.75 : 1, borderRadius: 'var(--rounded-full)', }, contentStyle: { color: isDark ? `var(--${color}-100)` : `var(--${color}-900)`, fontWeight: 'var(--font-bold)', }, }; break; } case 'solid': { styles = { style: { backgroundColor: isDark ? `var(--${color}-500)` : `var(--${color}-600)`, borderRadius: 'var(--rounded-full)', }, contentStyle: { color: 'var(--white)', fontWeight: 'var(--font-bold)', }, }; break; } } return { fillMode, color, isDark, ...styles, }; } describe('Theme', () => { const lightTheme = new Theme({ color: 'blue', isDark: false }); const darkTheme = new Theme({ color: 'red', isDark: true }); const themes = [lightTheme, darkTheme]; themes.forEach(theme => { // Check highlight with `true` it('should create highlight with `true`', () => { const highlight = theme.normalizeHighlight(true); const targets = { base: 'light', start: 'solid', end: 'solid', }; Object.entries(targets).forEach(([t, fillMode]) => { expect(highlight[t]).toEqual( getHighlightResult(fillMode, theme.color, theme.isDark), ); }); }); // Check highlights with fill modes const fillModes = ['none', 'light', 'solid']; fillModes.forEach(fillMode => { it('should create highlight with fillMode = ' + fillMode, () => { const highlight = theme.normalizeHighlight({ fillMode }); ['base', 'start', 'end'].forEach(t => { expect(highlight[t]).toEqual( getHighlightResult(fillMode, theme.color, theme.isDark), ); }); }); }); // Check highlights with class it('should create highlight with `class`', () => { const config = { class: 'highlight_class', }; const highlight = theme.normalizeHighlight(config); ['base', 'start', 'end'].forEach(t => { expect(highlight[t].class).toEqual(config.class); }); }); // Check highlights with content class it('should create highlight with `contentClass`', () => { const config = { contentClass: 'highlight_content_class', }; const highlight = theme.normalizeHighlight(config); ['base', 'start', 'end'].forEach(t => { expect(highlight[t].contentClass).toEqual(config.contentClass); }); }); // Check highlights with `style` it('should create highlight with `style`', () => { const config = { style: { backgroundColor: '#fafafa', opacity: 1, pointerEvents: 'none', }, }; const highlight = theme.normalizeHighlight(config); ['base', 'start', 'end'].forEach(t => { Object.entries(config.style).forEach(([p, v]) => { expect(highlight[t].style[p]).toEqual(v); }); }); }); // Check highlights with `contentStyle` it('should create highlight with `contentStyle`', () => { const config = { contentStyle: { color: '#fafafa', opacity: 0.5, }, }; const highlight = theme.normalizeHighlight(config); ['base', 'start', 'end'].forEach(t => { Object.entries(config.contentStyle).forEach(([p, v]) => { expect(highlight[t].contentStyle[p]).toEqual(v); }); }); }); // Check highlights with classes and styles it('should create highlight with classes and styles', () => { const config = { class: 'highlight_class', contentClass: 'highlight_content_class', style: { backgroundColor: '#fafafa', opacity: 1, pointerEvents: 'none', }, contentStyle: { color: '#fafafa', opacity: 0.5, }, }; const highlight = theme.normalizeHighlight(config); ['base', 'start', 'end'].forEach(t => { expect(highlight[t].class).toEqual(config.class); expect(highlight[t].contentClass).toEqual(config.contentClass); Object.entries(config.style).forEach(([p, v]) => { expect(highlight[t].style[p]).toEqual(v); }); Object.entries(config.contentStyle).forEach(([p, v]) => { expect(highlight[t].contentStyle[p]).toEqual(v); }); }); }); }); });
var express = require('express'), fs = require('fs'), app = express(); var cors = require('cors'); var app = express(); app.use(cors()); var ip = process.env.IP || process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'; app.get('http://quarkus-customer-service:8080/customers', function(req, res) { res.send(res.json()); }); app.listen(8080, ip); module.exports = app;
/** * Select the text of an element. * * @param {htmlelement} $el - The element. * @return {undefined} - Nothing. * * @resource [https://www.sanwebe.com/2014/04/select-all-text-in-element-on-click] */ var selection = function($el) { // Clear any current selection. selection.clear(); // Create the selection... var sel, range; if (window.getSelection && document.createRange) { //Browser compatibility sel = window.getSelection(); if (sel.toString() === "") { //no text selection window.setTimeout(function() { range = document.createRange(); //range object range.selectNodeContents($el); //sets Range sel.removeAllRanges(); //remove all ranges from selection sel.addRange(range); //add Range to a Selection. }, 1); } } else if (document.selection) { //older ie sel = document.selection.createRange(); if (sel.text === "") { //no text selection range = document.body.createTextRange(); //Creates TextRange object range.moveToElementText($el); //sets Range range.select(); //make selection. } } }; selection.clear = function() { // First clear any current range selection. // [https://stackoverflow.com/a/3171348] var sel = window.getSelection ? window.getSelection() : document.selection; if (sel) { if (sel.removeAllRanges) { sel.removeAllRanges(); } else if (sel.empty) { sel.empty(); } } };
import {throttle} from 'lodash' // use like this within a react component: // constructor(props){ // super(props) // rerenderOnWindowResize(this) // } export default function rerenderOnWindowResize(that) { that.updateDimensions = throttle(() => { if (that.props.disabled) return that.forceUpdate() }, 250); const componentDidMount = that.componentDidMount const componentWillUnmount = that.componentWillUnmount that.componentDidMount = (...args)=> { componentDidMount && componentDidMount.bind(that)(...args) window.addEventListener("resize", that.updateDimensions); } that.componentWillUnmount = (...args)=> { componentWillUnmount && componentWillUnmount.bind(that)(...args) window.removeEventListener("resize", that.updateDimensions); } }
/* Get value at location described by dot notion path */ import pathway from './pathway' export const get = (obj, path) => { path = pathway.split(path) path.some((key, i) => { if (typeof obj !== 'object') throw Error(`Get path '${path.join('.')}' cannot navigate past key '${path[i - 1]}', '${path[i - 1]}' is non-object value '${obj}'.`) obj = obj[key] return Boolean(obj === undefined) // Stop navigating the path if we get to undefined value }) return obj } export default get
var io = require('cheerio'); var reader = { readPart: function(body, index) { var $ = io.load(body); var part = { }; var title = ''; var items = []; $('#divMiddleList > div:nth-child(' + index + ')').each(function (index, object) { title = $(object).find('span.brand').text(); }); $('#divMiddleList > div:nth-child(' + (++index) + ') > div.song_item').each(function (index, object) { var image = $(object).find('div.song_item_img > a > img').attr('src') || $(object).find('div.song_item_img > img').attr('src'); var title = $(object).find('div.song_item_title > a').text(); var link = $(object).find('div.song_item_title > a').attr('href'); var artiste = $(object).find('div.song_item_artist > a').text(); var tag = $(object).find('div.song_item_tag > a').text(); var song = $(object).find('div.song_item_playa > div.playa').attr('rel') || ''; var item = { 'link': 'http://www.livingelectro.com/' + link, 'image': 'http://www.livingelectro.com/' + image, 'title': title, 'artiste': artiste, 'tag': tag, 'song': song }; items.push(item); }); part[title] = items; return part; }, readDownloadLink: function (body, completion) { var $ = io.load(body); $('div.song_download_link').each(function (index, object) { var song = $(object).find('a').attr('href'); completion(song); }); } }; module.exports = reader;
import React from 'react'; import RaisedButton from 'material-ui/RaisedButton'; import QueueAnim from 'rc-queue-anim'; const mWidthStyle = { minWidth: '135px' }; const Section1 = () => ( <div className="container-fluid with-maxwidth"> <article className="article"> <h2 className="article-title">Basic</h2> <div className="box box-default"> <div className="box-body"> <div className="call-to-action cta-inline"> <div className="cta-inner"> <span className="cta-text">Download it now and get up and running in minutes</span> <div className="cta-btn"> <RaisedButton style={mWidthStyle} label="Free Download" secondary /> </div> </div> </div> </div> </div> </article> </div> ); const Section2 = () => ( <div> <div className="container-fluid with-maxwidth"> <article className="article no-margin-bttom"> <h2 className="article-title">Full Width (Inline)</h2> </article> </div> <div className="call-to-action cta-inline cta-full-width card-white"> <div className="cta-inner"> <span className="cta-text">Download it now and get up and running in minutes</span> <div className="cta-btn"> <RaisedButton style={mWidthStyle} label="Free Download" secondary /> </div> </div> </div> <div className="divider" /> </div> ); const Section3 = () => ( <div> <div className="container-fluid with-maxwidth"> <article className="article no-margin-bttom"> <h2 className="article-title">Full Width</h2> </article> </div> <div className="call-to-action cta-full-width card-white"> <div className="cta-inner"> <span className="cta-text">Download it now and get up and running in minutes</span> <div className="cta-btn"> <RaisedButton style={mWidthStyle} label="Free Download" secondary /> </div> <div className="cta-muted">No spam! We promise, only the best stuff.</div> </div> </div> <div className="divider" /> </div> ); const Section4 = () => ( <div> <div className="container-fluid with-maxwidth"> <article className="article no-margin-bttom"> <h2 className="article-title">Image Background</h2> </article> </div> <div className="call-to-action cta-bg-img cta-full-width" style={{backgroundImage: 'url(assets/images-demo/covers/photo-1456374407032-6e4baf58fb62.jpg)'}}> <div className="cta-inner"> <span className="cta-text">Download it now and get up and running in minutes</span> <div className="cta-btn"> <RaisedButton style={mWidthStyle} label="Free Download" secondary /> </div> <div className="cta-muted">No spam! We promise, only the best stuff.</div> </div> </div> </div> ); const CallToActions = () => ( <section className="chapter"> <QueueAnim type="bottom" className="ui-animate"> <div key="1"><Section1 /></div> <div key="2"><Section2 /></div> <div key="3"><Section3 /></div> <div key="4"><Section4 /></div> </QueueAnim> </section> ); module.exports = CallToActions;
'use strict'; const serverErrorCode = 500; module.exports = function serverError (data) { var req = this.req; var res = this.res; var sails = req._sails; res.status(serverErrorCode); if (data === undefined) { sails.log.error('Sending empty 500 ("Server Error") response'); } else { sails.log.error('Sending 500 ("Server Error") response: \n', data); } if (sails.config.environment === 'production') { data = undefined; } return res.jsonx(data); };
'use strict'; angular.module('gamePlatformServerApp') .directive('navbar', () => ({ templateUrl: 'components/navbar/navbar.html', restrict: 'E', controller: 'NavbarController', controllerAs: 'nav' }));
import styles from './ModelHeader.css'; import React, { Component } from 'react'; export default class ModelHeader extends Component { render() { return <div className={styles.root}> Complaints<br />by <b>Model</b> </div> } }
var structRT__TASK__INFO = [ [ "name", "structRT__TASK__INFO.html#a3e5d47277ecea23aa3a5730e0b6b2d13", null ], [ "pid", "structRT__TASK__INFO.html#a70c731ca5877ff4a6235fa81caa77798", null ], [ "prio", "structRT__TASK__INFO.html#a632e09c1d8dabc29c020c828abf62ac6", null ], [ "stat", "structRT__TASK__INFO.html#ae327f3dca3f2ae89c8aa5bd0033ed4b0", null ] ];
const React = require('react'); class DonationOptions extends React.Component { constructor(props) { super(props); this.state = {selectedDonationOption: 'option1', btnActiveID: "donation-option-1"}; } btnIsActive = (value) => { return 'btn btn-primary ' + ((value===this.state.btnActiveID) ? 'active':''); } handleDonationOptionChange = (changeEvent) => { this.setState({ selectedDonationOption: changeEvent.target.value, btnActiveID: changeEvent.target.id }, console.log(changeEvent.target.value)) } render() { return( <div className="btn-group donation-buttons"> <div className="row"> <div className="col-xs-12 p-0"> <div className="col-xs-4"> <label className={this.btnIsActive("donation-option-1")}> <input type="checkbox" name="options" className="donation-options" id="donation-option-1" value="option1" checked={this.state.selectedDonationOption === "option1"} onChange={this.handleDonationOptionChange}/>$25 </label> </div> <div className="col-xs-4"> <label className={this.btnIsActive("donation-option-2")}> <input type="checkbox" name="options" className="donation-options" id="donation-option-2" value="option2" checked={this.state.selectedDonationOption === "option2"} onChange={this.handleDonationOptionChange}/>$50 </label> </div> <div className="col-xs-4"> <label className={this.btnIsActive("donation-option-3")}> <input type="checkbox" name="options" className="donation-options" id="donation-option-3" value="option3" checked={this.state.selectedDonationOption === "option3"} onChange={this.handleDonationOptionChange}/>$100 </label> </div> </div> </div> </div> ) } } export default DonationOptions;
import { ToggleTimerBar } from '../../Config/SpecificToggles'; import ToggleBotBar from '../../Config/Toggles/ToggleBotBar'; import UpdateBackground from './UpdateBackground'; /** * This function disables and shows the bars created by CookieMonster when the game is "ascending" * It is called by CM.Disp.Draw() */ export default function UpdateAscendState() { if (Game.OnAscend) { l('game').style.bottom = '0px'; if (Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.settings.BotBar === 1) l('CMBotBar').style.display = 'none'; if (Game.mods.cookieMonsterFramework.saveData.cookieMonsterMod.settings.TimerBar === 1) l('CMTimerBar').style.display = 'none'; } else { ToggleBotBar(); ToggleTimerBar(); } UpdateBackground(); }
var questions = [ { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-1', inputs: { looptotal: 10 } }, { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-2', inputs: { looptotal: 9 } }, { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-3', inputs: { looptotal: 11 } }, { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-4', inputs: { looptotal: 59 } }, { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-5', inputs: { looptotal: 100 } }, { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-6', inputs: { looptotal: 110 } }, { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-7', inputs: { looptotal: 10400 } }, { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-8', inputs: { looptotal: 4 } }, { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-9', inputs: { looptotal: 6 } }, { question: 'How many times will the code inside the loop execute?', inputGroup: 'question-10', inputs: { looptotal: 3 } } ]; questions.forEach(function (item, i) { questions[i].onStart = function () { document.getElementById('looptotal').focus(); Prism.highlightElement(document.querySelector('.language-javascript')); }; }); FormValidator(ActivityRunner(), questions);
/** * @ngdoc directive * @name barchart * @module angular-graphael * @description * Creates a bar chart. * @link http://g.raphaeljs.com/reference.html#Paper.barchart */ angular.module('angular-graphael').directive('barchart', function ($window, mapData) { 'use strict'; return { restrict: 'E', scope: { width: '=', height: '=', x: '=', y: '=', options: '=', values: '=' }, template: '<div></div>', link: function (scope, element) { // Right now we only care about watching if the data changes. scope.$watch('values', function () { var r, // X coordinate x = scope.x || 100, // Y coordinate y = scope.y || 100, // Width width = scope.width || 100, // Height height = scope.height || 100; // If you don't remove the old chart, you're gonna have a bad time. element[0].innerHTML = ''; // Set up the canvas r = $window.Raphael(element[0]); // Add the chart to the canvas with all of our options and data. r.barchart(x, y, width, height, mapData(scope.values), scope.options); }); } }; });
var mongoose = require('mongoose'), models = require('../models'); module.exports = function (config) { mongoose.connect(config.db); var db = mongoose.connection; db.once('open', function (error) { if (error) { console.log('Database could not be opened: ' + error); return; } console.log('Database up and running...') }); db.on('error', function (error) { console.log('Database error: ' + error); }); models.user.seedInitialUsers(); };
import test from 'ava' import sinon from 'sinon' import pokeapiEndpoints from './' test('pokeapi-endpoints', (t) => { const results = [{ 'name': 'berry', 'url': 'https://pokeapi.co/api/v2/berry/' }, { 'name': 'berry-firmness', 'url': 'https://pokeapi.co/api/v2/berry-firmness/' }, { 'name': 'berry-flavor', 'url': 'https://pokeapi.co/api/v2/berry-flavor/' }, { 'name': 'contest-type', 'url': 'https://pokeapi.co/api/v2/contest-type/' }, { 'name': 'contest-effect', 'url': 'https://pokeapi.co/api/v2/contest-effect/' }, { 'name': 'super-contest-type', 'url': 'https://pokeapi.co/api/v2/super-contest-type/' }, { 'name': 'encounter-method', 'url': 'https://pokeapi.co/api/v2/encounter-method/' }, { 'name': 'encounter-condition', 'url': 'https://pokeapi.co/api/v2/encounter-condition/' }, { 'name': 'encounter-method-value', 'url': 'https://pokeapi.co/api/v2/encounter-method-value/' }, { 'name': 'evolution-chain', 'url': 'https://pokeapi.co/api/v2/evolution-chain/' }, { 'name': 'evolution-trigger', 'url': 'https://pokeapi.co/api/v2/evolution-trigger/' }, { 'name': 'generation', 'url': 'https://pokeapi.co/api/v2/generation/' }, { 'name': 'pokedex', 'url': 'https://pokeapi.co/api/v2/pokedex/' }, { 'name': 'version', 'url': 'https://pokeapi.co/api/v2/version/' }, { 'name': 'version-group', 'url': 'https://pokeapi.co/api/v2/version-group/' }, { 'name': 'item', 'url': 'https://pokeapi.co/api/v2/item/' }, { 'name': 'item-attribute', 'url': 'https://pokeapi.co/api/v2/item-attribute/' }, { 'name': 'item-category', 'url': 'https://pokeapi.co/api/v2/item-category/' }, { 'name': 'item-fling-effect', 'url': 'https://pokeapi.co/api/v2/item-fling-effect/' }, { 'name': 'item-pocket', 'url': 'https://pokeapi.co/api/v2/item-pocket/' }, { 'name': 'machine', 'url': 'https://pokeapi.co/api/v2/machine/' }, { 'name': 'move', 'url': 'https://pokeapi.co/api/v2/move/' }, { 'name': 'move-ailment', 'url': 'https://pokeapi.co/api/v2/move-ailment/' }, { 'name': 'move-battle-style', 'url': 'https://pokeapi.co/api/v2/move-battle-style/' }, { 'name': 'move-category', 'url': 'https://pokeapi.co/api/v2/move-category/' }, { 'name': 'move-damage-class', 'url': 'https://pokeapi.co/api/v2/move-damage-class/' }, { 'name': 'move-learn-method', 'url': 'https://pokeapi.co/api/v2/move-learn-method/' }, { 'name': 'move-target', 'url': 'https://pokeapi.co/api/v2/move-target/' }, { 'name': 'location', 'url': 'https://pokeapi.co/api/v2/location/' }, { 'name': 'location-area', 'url': 'https://pokeapi.co/api/v2/location-area/' }, { 'name': 'pal-park-area', 'url': 'https://pokeapi.co/api/v2/pal-park-area/' }, { 'name': 'region', 'url': 'https://pokeapi.co/api/v2/region/' }, { 'name': 'ability', 'url': 'https://pokeapi.co/api/v2/ability/' }, { 'name': 'characteristic', 'url': 'https://pokeapi.co/api/v2/characteristic/' }, { 'name': 'egg-group', 'url': 'https://pokeapi.co/api/v2/egg-group/' }, { 'name': 'gender', 'url': 'https://pokeapi.co/api/v2/gender/' }, { 'name': 'growth-rate', 'url': 'https://pokeapi.co/api/v2/growth-rate/' }, { 'name': 'nature', 'url': 'https://pokeapi.co/api/v2/nature/' }, { 'name': 'pokeathlon-stat', 'url': 'https://pokeapi.co/api/v2/pokeathlon-stat/' }, { 'name': 'pokemon', 'url': 'https://pokeapi.co/api/v2/pokemon/' }, { 'name': 'pokemon-color', 'url': 'https://pokeapi.co/api/v2/pokemon-color/' }, { 'name': 'pokemon-form', 'url': 'https://pokeapi.co/api/v2/pokemon-form/' }, { 'name': 'pokemon-habitat', 'url': 'https://pokeapi.co/api/v2/pokemon-habitat/' }, { 'name': 'pokemon-shape', 'url': 'https://pokeapi.co/api/v2/pokemon-shape/' }, { 'name': 'pokemon-species', 'url': 'https://pokeapi.co/api/v2/pokemon-species/' }, { 'name': 'stat', 'url': 'https://pokeapi.co/api/v2/stat/' }, { 'name': 'type', 'url': 'https://pokeapi.co/api/v2/type/' }, { 'name': 'language', 'url': 'https://pokeapi.co/api/v2/language/' }] const done = sinon.spy() const context = { done } pokeapiEndpoints(context) t.true(done.calledOnce) t.true(done.calledWithExactly()) t.deepEqual(context.res, { results }) })
'use strict'; (function() { describe('HomeController', function() { //Initialize global variables var scope, HomeController; // Load the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); beforeEach(inject(function($controller, $rootScope) { scope = $rootScope.$new(); HomeController = $controller('HomeController', { $scope: scope }); })); it('should expose the authentication service', function() { expect(scope.authentication).toBeTruthy(); }); }); })();
/* * StoryQuest 2 * * Copyright (c) 2014 Questor GmbH * * 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. */ function modalYesNo(label, text, done) { $("#modalYesNoDoYes, #modalYesNoDoNo").click(function(event) { $("#modalYesNoDoYes").unbind("click"); $("#modalYesNoDoNo").unbind("click"); done($(event.target).is($("#modalYesNoDoYes"))?true:false); }); $("#modalYesNoLabel").html(label); $("#modalYesNoText").html(text); $("#modalYesNo").modal(); } function modalOk(label, text, done) { $("#modalOkDoOk").click(function(event) { $("#modalOkDoOk").unbind("click"); done(); }); $("#modalOkLabel").html(label); $("#modalOkText").html(text); $("#modalOk").modal(); } function modalOkCancel(label, text, done) { $("#modalOkCancelDoOk").click(function(event) { $("#modalOkCancelDoOk").unbind("click"); $("#modalOkCancelDoCancel").unbind("click"); done($(event.target).is($("#modalOkCancelDoOk"))?true:false); }); $("#modalOkCancelLabel").html(label); $("#modalOkCancelText").html(text); $("#modalOkCancel").modal(); } function modalWarning(label, text) { $("#modalWarningLabel").html(label); $("#modalWarningText").html(text); $("#modalWarning").modal(); } function modalQR(link, projectId) { $("#previewqr").empty(); $("#previewqr").qrcode({width: 200, height: 200, text: link}); $("#devmodeurl").attr("href", "/api/p/" + projectId + "/index.html"); $("#modalQR").modal(); } function modalError(text) { $("#modalWarningLabel").html("Error"); $("#modalWarningText").html(text); $("#modalWarning").modal(); } function modalWait(text) { $("#modalWaitLabel").html(text); $("#modalWait").modal(); return $("#modalWait"); }
import React from 'react' import PropTypes from 'prop-types' import Colors from '../constants/Colors' import Styles from '../styles/PersonCreate' import HeaderTitle from '../components/HeaderTitle' import PersonCreateView from '../components/PersonCreateView' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import * as allActions from '../actions' class PersonCreate extends React.Component { static propTypes = { createPerson: PropTypes.func.isRequired, cleanPersonCreateResponse: PropTypes.func.isRequired, creatingPerson: PropTypes.bool.isRequired, errorCreatingPerson: PropTypes.bool.isRequired, successCreatingPerson: PropTypes.bool.isRequired, } static route = { navigationBar: { title: 'Nuevo', backgroundColor: Colors.white, borderBottomWidth: 1, renderTitle: () => ( <HeaderTitle title={'Crear'} /> ), }, } createPerson = (person) => { this.props.createPerson(person) } cleanPersonCreateResponse = () => { this.props.cleanPersonCreateResponse() } render() { return ( <PersonCreateView styles={Styles} creatingPerson={this.props.creatingPerson} errorCreatingPerson={this.props.errorCreatingPerson} successCreatingPerson={this.props.successCreatingPerson} createPerson={this.createPerson} cleanPersonCreateResponse={this.cleanPersonCreateResponse} /> ) } } function mapStateToProps (state) { return { creatingPerson: state.personCreate.creatingPerson, errorCreatingPerson: state.personCreate.errorCreatingPerson, successCreatingPerson: state.personCreate.successCreatingPerson, } } function mapDispatchToProps (dispatch) { const actions = bindActionCreators(allActions, dispatch) return { createPerson: actions.createPerson, cleanPersonCreateResponse: actions.cleanPersonCreateResponse, } } export default connect( mapStateToProps, mapDispatchToProps )(PersonCreate)
var mongoose = require('mongoose'), Sync = require('sync'), uniqueValidator = require('mongoose-unique-validator'); var studentAbsencesSchema = mongoose.Schema({ number: { type: Number, required: true, unique: true, match: /^\d{1,2}$/, min: 1, max: 30, sprace: true }, excused: { type: Number, min: 0, max: 999 }, inexcused: { type: String, validate: /(^\d+$)|(^\d+\/\d+$)|(^\d+\s+\d+\/\d+$)/ }, allExcused: Number, allInexcused: String, averageExcused: Number, averageInexcused: Number }); var classAbsencesSchema = mongoose.Schema({ schoolClass: { type: mongoose.Schema.ObjectId, unique: true }, absences: [studentAbsencesSchema] }); var StudentAbsences = mongoose.model('StudentAbsences', studentAbsencesSchema); var Absences = mongoose.model('Absences', classAbsencesSchema); module.exports = { seedSchoolClassAbsences: function(schoolClass, callback) { var newSchoolClassAbsences = new Absences({ schoolClass: schoolClass, absences: [] }); newSchoolClassAbsences.save(function(err, res) { if (err) { console.log('error seeding class absences: ' + err); return; } console.log('absences for class seeded!' + res); return callback(); }); }, seedUserAbsences: function(schoolClass, number, callback) { Absences.update({ schoolClass: schoolClass, }, { $push: { absences: { number: parseInt(number), excused: 0, inexcused: '0' } } }, function(err, absence) { if (err) { console.log('error seeding user absences: ' + err); return; } console.log('absences for user seeded:'); console.log(absence); return callback(); }); } // seedInitialAbsences: function(schoolClass, callback) { // // Absences.remove({}, function(err) { // Absences.findOne({ // schoolClass: schoolClass // }, function(err, absences) { // if (err) { // console.log('Absences were not seeded: ' + err); // return callback(); // } // if (absences) { // console.log("absences: " + absences); // } // if (!absences) { // Sync(function() { // var arrToSave = []; // for (var i = 0; i < 25; i++) { // numberToCreate = i + 1; // arrToSave[i] = {}; // arrToSave[i].number = numberToCreate; // arrToSave[i].excused = 0; // arrToSave[i].inexcused = '0'; // } // return arrToSave; // }, function(err, result) { // console.log(result); // Absences.create({ // schoolClass: schoolClass, // absences: result // }, function(err, result) { // if (err) { // console.log('Absences seeding err: ' + err); // return callback(); // } // console.log(result); // console.log('Absences for schoolClass ' + schoolClass + ' seeded!'); // return callback(); // }); // }); // } // }); // }); // } };
'use strict' const client = require('../octopus-client') const getAll = async (take, skip) => { const url = `/channels?${take ? `take=${take}` : ''}&${skip ? `skip=${skip}` : ''}` return client.get(url) } module.exports = { getAll }
'use strict'; module.exports = { 'rules': { 'accessor-pairs': 'off', 'array-bracket-spacing': [ 'error', 'never' ], 'brace-style': [ 'error', '1tbs', { 'allowSingleLine': false } ], 'camelcase': [ 'error', { 'properties': 'always' } ], 'comma-dangle': [ 'error', 'never' ], 'comma-spacing': [ 'error', { 'after': true, 'before': false } ], 'comma-style': [ 2, 'last' ], 'complexity': [ 'error', 7 ], 'computed-property-spacing': [ 'error', 'never' ], 'consistent-return': 'error', 'consistent-this': [ 'error', 'self' ], 'curly': [ 'error', 'all' ], 'default-case': 'error', 'dot-location': 'off', 'dot-notation': 'error', 'eol-last': 'error', 'eqeqeq': [ 'error', 'smart' ], 'func-names': 'off', 'func-style': [ 'error', 'expression' ], 'guard-for-in': 'error', 'handle-callback-err': [ 'error', '^(err|error)$' ], 'indent': [ 'error', 2, { 'SwitchCase': 1 } ], 'key-spacing': [ 'off', { 'align': 'value' } ], 'keyword-spacing': [ 'error', { 'after': true, 'before': true, 'overrides': {} } ], 'linebreak-style': [ 'error', 'unix' ], 'lines-around-comment': 'off', 'max-len': ['error', { code: 200 }], 'max-nested-callbacks': [ 'error', 3 ], 'multiline-ternary': ['error', 'never'], 'new-cap': [ 'error', { 'capIsNew': true, 'newIsCap': true } ], 'new-parens': 'error', 'newline-after-var': 'off', 'no-alert': 'error', 'no-array-constructor': 'error', 'no-caller': 'error', 'no-catch-shadow': 'error', 'no-cond-assign': [ 'error', 'always' ], 'no-console': 'warn', 'no-constant-condition': 'error', 'no-continue': 'error', 'no-control-regex': 'error', 'no-debugger': 'error', 'no-delete-var': 'error', 'no-div-regex': 'error', 'no-dupe-args': 'error', 'no-dupe-keys': 'error', 'no-duplicate-case': 'error', 'no-else-return': 'error', 'no-empty': 'error', 'no-empty-character-class': 'error', 'no-eq-null': 'error', 'no-eval': 'error', 'no-ex-assign': 'error', 'no-extend-native': 'error', 'no-extra-bind': 'error', 'no-extra-boolean-cast': 'error', 'no-extra-semi': 'error', 'no-fallthrough': 'error', 'no-floating-decimal': 'error', 'no-func-assign': 'error', 'no-implied-eval': 'error', 'no-inline-comments': 'off', 'no-inner-declarations': 'error', 'no-invalid-regexp': 'error', 'no-irregular-whitespace': 'error', 'no-iterator': 'error', 'no-label-var': 'error', 'no-labels': 'error', 'no-lone-blocks': 'error', 'no-lonely-if': 2, 'no-loop-func': 2, 'no-mixed-requires': [ 0, true ], 'no-mixed-spaces-and-tabs': 2, 'no-multi-spaces': 2, 'no-multi-str': 2, 'no-multiple-empty-lines': [ 2, { 'max': 1 } ], 'no-native-reassign': 2, 'no-negated-in-lhs': 2, 'no-nested-ternary': 2, 'no-new': 2, 'no-new-func': 2, 'no-new-object': 2, 'no-new-require': 2, 'no-new-wrappers': 2, 'no-obj-calls': 2, 'no-octal': 2, 'no-octal-escape': 2, 'no-param-reassign': 2, 'no-path-concat': 2, 'no-process-env': 0, 'no-process-exit': 2, 'no-proto': 2, 'no-prototype-builtins': 2, 'no-redeclare': 2, 'no-regex-spaces': 2, 'no-restricted-modules': 0, 'no-return-assign': 2, 'no-script-url': 2, 'no-self-compare': 2, 'no-sequences': 2, 'no-shadow': 0, 'no-shadow-restricted-names': 2, 'no-spaced-func': 2, 'no-sparse-arrays': 2, 'no-sync': 2, 'no-ternary': 0, 'no-throw-literal': 2, 'no-trailing-spaces': 2, 'no-undef': 2, 'no-undef-init': 2, 'no-undefined': 0, 'no-underscore-dangle': 2, 'no-unneeded-ternary': 2, 'no-unreachable': 2, 'no-unused-expressions': 2, 'no-unused-vars': 'error', 'no-use-before-define': 2, 'no-var': 0, 'no-void': 2, 'no-warning-comments': [ 2, { 'location': 'anywhere', 'terms': [ 'fixme', 'fuck', 'todo', 'xxx' ] } ], 'no-with': 2, 'object-curly-spacing': [ 2, 'always' ], 'object-shorthand': ['error', 'never'], 'one-var': 'off', 'operator-assignment': [ 2, 'always' ], 'operator-linebreak': [ 2, 'before' ], 'padded-blocks': [ 0, 'always' ], 'prefer-arrow-callback': 2, 'prefer-const': 2, 'quotes': [ 2, 'single' ], 'radix': 2, 'semi': [ 'error', 'always' ], 'semi-spacing': [ 2, { 'after': true, 'before': false } ], 'sort-imports': 0, 'sort-keys': 0, 'sort-vars': [ 0, { 'ignoreCase': true } ], 'space-before-blocks': [ 2, 'always' ], 'space-before-function-paren': [ 2, { 'anonymous': 'always', 'named': 'never' } ], 'space-in-parens': [ 2, 'never' ], 'space-infix-ops': [ 2, { 'int32Hint': false } ], 'space-unary-ops': [ 2, { 'nonwords': false, 'words': true } ], 'strict': [ 2, 'global' ], 'use-isnan': 2, 'valid-jsdoc': 0, 'valid-typeof': 2, 'vars-on-top': 'off', 'wrap-iife': 2, 'wrap-regex': 2, 'yoda': [ 2, 'never' ] } };