text
stringlengths
2
6.14k
import { fromJS } from 'immutable'; import { SET_USER, DESTROY_USER, DEFAULT_USER_STATE, SET_PROFILE } from '../../constants/user'; const initialUserState = DEFAULT_USER_STATE; export default function reducer(state = fromJS(initialUserState), action) { switch (action.type) { case SET_USER: return fromJS(action.payload.user); case DESTROY_USER: return fromJS(DEFAULT_USER_STATE); case SET_PROFILE: return state.merge({ profile: action.payload.profile }); default: return state; } }
$(document).ready(function() { }); function showTip(ele_id) { var offset = $('#'+ele_id).offset(); if(ele_id == 'otc-rig-hotspot1') { $('#mpps-rig-tip1').removeClass('display_none'); $('#'+ele_id).mouseout(function(){ $('#mpps-rig-tip1').addClass('display_none'); }); } else if(ele_id == 'otc-rig-hotspot2') { $('#mpps-rig-tip2').removeClass('display_none'); $('#'+ele_id).mouseout(function(){ $('#mpps-rig-tip2').addClass('display_none'); }); } else if(ele_id == 'otc-rig-hotspot3') { $('#mpps-rig-tip3').removeClass('display_none'); $('#'+ele_id).mouseout(function(){ $('#mpps-rig-tip3').addClass('display_none'); }); } else if(ele_id == 'otc-rig-hotspot4') { $('#mpps-rig-tip4').removeClass('display_none'); $('#'+ele_id).mouseout(function(){ $('#mpps-rig-tip4').addClass('display_none'); }); } else if(ele_id == 'otc-rig-hotspot5') { $('#mpps-rig-tip5').removeClass('display_none'); $('#'+ele_id).mouseout(function(){ $('#mpps-rig-tip5').addClass('display_none'); }); } else if(ele_id == 'otc-rig-hotspot6') { $('#mpps-rig-tip6').removeClass('display_none'); $('#'+ele_id).mouseout(function(){ $('#mpps-rig-tip6').addClass('display_none'); }); } else if(ele_id == 'otc-rig-hotspot7') { $('#mpps-rig-tip7').removeClass('display_none'); $('#'+ele_id).mouseout(function(){ $('#mpps-rig-tip7').addClass('display_none'); }); } else if(ele_id == 'otc-rig-hotspot8') { $('#mpps-rig-tip8').removeClass('display_none'); $('#'+ele_id).mouseout(function(){ $('#mpps-rig-tip8').addClass('display_none'); }); } } function removeValidationMsg(strEleId) { $("#"+strEleId).attr("err_msg", ""); $("#"+strEleId).removeClass("err_field"); if($("#err_wrap_"+strEleId).length) { $("#err_wrap_"+strEleId).remove(); } } function resetValidationMsgs() { $(".err_field").each(function(nIndex, ele){ removeValidationMsg($(ele).attr("id")); }); } function jAlert(strTitle, strMesg) { $("#alert").dialog({ buttons : { Ok: function() { $(this).dialog("close"); //closing on Ok click } } }); $('#alert').html(strMesg); $('#alert').css('background-color', "#FFF"); $('#alert').dialog('option', 'title', strTitle); $('#alert').dialog('open'); } function showAjaxLoader(){ $('#mpps_ajax_busy').hide(); $('#mpps_ajax_busy').show(); $('#inner_content').removeClass('block_overlay'); $('#inner_content').addClass('block_overlay'); } function hideAjaxLoader(){ $('#mpps_ajax_busy').hide(); $('#inner_content').removeClass('block_overlay'); }
(function() { 'use strict'; // Watch changes and apply tasks var utils = require('../utils'); var runSequence = require('run-sequence'); exports.task = function() { gulp .watch(config.typescriptServer, function() { runSequence( ['clean'], ['compile-server'], ['test-server'] ); }) .on('change', utils.logWatch); }; })();
'use strict'; import React from 'react'; import PropTypes from 'prop-types'; import ClassNames from 'classnames'; import Icon from '../Icon'; class ItemArrow extends React.Component { render() { const { className, children, materialIcon, ...restProps } = this.props; const clx = ClassNames({ ...( className && { [ className ]: true } ), 'mdui-collapse-item-arrow': true }); const props = { ...restProps, className: clx, ...( !children && { materialIcon } ) }; return ( <Icon { ...props }> { children } </Icon> ); } } ItemArrow.propTypes = { style: PropTypes.object, className: PropTypes.string, children: PropTypes.node, materialIcon: PropTypes.string }; ItemArrow.defaultProps = { materialIcon: String.fromCharCode( 0xe313 ) }; export default ItemArrow;
define(['KBaseSearch.GenomeSet', 'KBModeling'], (Widget, kbm) => { 'use strict'; describe('Test the KBaseSearch.GenomeSet widget', () => { it('Should load the module', () => { const api = new KBModeling('token'); expect(api.KBaseSearch_GenomeSet).toEqual(jasmine.any(Function)); }); }); });
(function(ViewModels, Base, ko) { 'use strict' ViewModels.templateVM = function () { var self = this; self.field = ko.observable("A field data of templateVM"); self.fields = ko.observableArray([]); }; // ViewModel methods ViewModels.templateVM.templateFunction = function () { console.log("templateFunction() called"); Base.baseFunction() }; // run code ViewModels.templateVM.templateFunction(); })(MyApp.ViewModels, MyApp.Base, ko);
import subscribeModule from './subscribe' export default { modules: { subscribe: subscribeModule }, namespaced: true }
import Vue from 'vue' import NumAbbr from 'number-abbreviate' import formatDate from 'date-fns/format' import addMonths from 'date-fns/add_months' import pluralize from 'pluralize' import * as constants from '~/helpers/constants' Vue.filter('abbreviateNumber', (value, decimals) => { if (value) { var numAbbr = new NumAbbr() var abbreviatedNumber = numAbbr.abbreviate(value, decimals) return abbreviatedNumber } }) Vue.filter('formatCategory', value => { if (value) { var category = value.charAt(0).toUpperCase() + value.slice(1).replace('-', ' ') return category } }) Vue.filter('formatDate', (value, format) => { if (value) { return formatDate(value, format) } }) Vue.filter('addMonths', (value, num) => { if (value) { return addMonths(value, num) } }) Vue.filter('escapeHtmlTags', value => { if (value) { return value.replace(/<.+?>/g, '') } }) Vue.filter('capitalize', value => { if (value) { return value.charAt(0).toUpperCase() + value.slice(1) } }) Vue.filter('firstLetter', value => { if (value) { return value.charAt(0) } }) Vue.filter('pluralize', (value, num) => { if (value) { return pluralize(value, num) } }) Vue.filter('truncate', (value, length) => { if (value) { return value.length > length ? value.substr(0, length - 1) + '…' : value } }) Vue.filter('removeEmptyArrayItems', value => { var items = value || [] return items.filter(entry => entry.trim() !== '') }) Vue.filter('formatDappBadge', value => { if (value) { let badge = '' switch (value) { case 'complete': badge = 'complete profile' break case 'metamask': badge = 'supports Metamask' break case 'status-im': badge = 'supports Status IM' break case 'token': badge = 'has token' break default: badge = value } return badge } }) Vue.filter('formatDappStatus', value => { if (value) { let status = '' switch (value) { case 'wip': status = 'Work in progress' break default: status = value } return status } }) Vue.filter('formatDappTabOptions', value => { var tab = '' var options = constants.dappRefineTabOptions || [] if (options.indexOf(value) !== -1) { tab = value.toString().replace('-', ' ') } else { tab = options[0] } return tab }) Vue.filter('formatEventCategory', value => { if (value) { let category = '' switch (value) { case 'ico': category = 'ICO' break default: category = value } return category } }) Vue.filter('uppercase', value => { if (value) { return value.toUpperCase() } })
import {promisify} from 'bluebird'; import {r} from './thinky'; async function clearDatabase() { const tableList = r.tableList(); const tables = await promisify(tableList.run, tableList)(); // $lab:coverage:off$ await* tables.map(table => { const del = r.table(table).delete(); return promisify(del.run, del)(); }); // $lab:coverage:on$ } export default { clearDatabase };
"use strict"; debugger; let one = [1, 2, 3, 4, 5]; console.log(one.copyWithin(0, 3)); let two = [1, 2, 3, 4, 5]; console.log(two.copyWithin(0, 2, 4)); let three = [1, 2, 3, 4, 5]; console.log(three.copyWithin(3)); let dummy;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = route; var _immutable = require('immutable'); var _immutable2 = _interopRequireDefault(_immutable); var _reactRouterRedux = require('react-router-redux'); var _constants = require('../constants.js'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var initialState = _immutable2['default'].fromJS({ locationBeforeTransitions: null }); function route() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments[1]; switch (action.type) { case _reactRouterRedux.LOCATION_CHANGE: return state.merge({ locationBeforeTransitions: action.payload }); case _constants.INITIALIZE_ROUTE: return state.merge({ locationBeforeTransitions: { "pathname": action.route, "action": "PUSH", "search": "", "hash": "", "state": null, "query": {}, "$searchBase": { "search": "", "searchBase": "" } } }); default: return state; } } //# sourceMappingURL=route.js.map
if (Meteor.isClient) { Countries = function() { return [ { name: 'Afghanistan' }, { name: 'Albania' }, { name: 'Algeria' }, { name: 'Andorra' }, { name: 'Angola' }, { name: 'Antigua and Barbuda' }, { name: 'Argentina' }, { name: 'Armenia' }, { name: 'Aruba' }, { name: 'Australia' }, { name: 'Austria' }, { name: 'Azerbaijan' }, { name: 'Bahamas, The' }, { name: 'Bahrain' }, { name: 'Bangladesh' }, { name: 'Barbados' }, { name: 'Belarus' }, { name: 'Belgium' }, { name: 'Belize' }, { name: 'Benin' }, { name: 'Bhutan' }, { name: 'Bolivia' }, { name: 'Bosnia and Herzegovina' }, { name: 'Botswana' }, { name: 'Brazil' }, { name: 'Brunei' }, { name: 'Bulgaria' }, { name: 'Burkina Faso' }, { name: 'Burma' }, { name: 'Burundi' }, { name: 'Cambodia' }, { name: 'Cameroon' }, { name: 'Canada' }, { name: 'Cape Verde' }, { name: 'Central African Republic' }, { name: 'Chad' }, { name: 'Chile' }, { name: 'China' }, { name: 'Colombia' }, { name: 'Comoros' }, { name: 'Congo, Democratic Republic of the' }, { name: 'Congo, Republic of the' }, { name: 'Costa Rica' }, { name: 'Cote d\'Ivoire' }, { name: 'Croatia' }, { name: 'Cuba' }, { name: 'Curacao' }, { name: 'Cyprus' }, { name: 'Czech Republic' }, { name: 'Denmark' }, { name: 'Djibouti' }, { name: 'Dominica' }, { name: 'Dominican Republic' }, { name: 'East Timor (see Timor-Leste)' }, { name: 'Ecuador' }, { name: 'Egypt' }, { name: 'El Salvador' }, { name: 'Equatorial Guinea' }, { name: 'Eritrea' }, { name: 'Estonia' }, { name: 'Ethiopia' }, { name: 'Fiji' }, { name: 'Finland' }, { name: 'France' }, { name: 'Gabon' }, { name: 'Gambia, The' }, { name: 'Georgia' }, { name: 'Germany' }, { name: 'Ghana' }, { name: 'Greece' }, { name: 'Grenada' }, { name: 'Guatemala' }, { name: 'Guinea' }, { name: 'Guinea-Bissau' }, { name: 'Guyana' }, { name: 'Haiti' }, { name: 'Holy See' }, { name: 'Honduras' }, { name: 'Hong Kong' }, { name: 'Hungary' }, { name: 'Iceland' }, { name: 'India' }, { name: 'Indonesia' }, { name: 'Iran' }, { name: 'Iraq' }, { name: 'Ireland' }, { name: 'Israel' }, { name: 'Italy' }, { name: 'Jamaica' }, { name: 'Japan' }, { name: 'Jordan' }, { name: 'Kazakhstan' }, { name: 'Kenya' }, { name: 'Kiribati' }, { name: 'Korea, North' }, { name: 'Korea, South' }, { name: 'Kosovo' }, { name: 'Kuwait' }, { name: 'Kyrgyzstan' }, { name: 'Laos' }, { name: 'Latvia' }, { name: 'Lebanon' }, { name: 'Lesotho' }, { name: 'Liberia' }, { name: 'Libya' }, { name: 'Liechtenstein' }, { name: 'Lithuania' }, { name: 'Luxembourg' }, { name: 'Macau' }, { name: 'Macedonia' }, { name: 'Madagascar' }, { name: 'Malawi' }, { name: 'Malaysia' }, { name: 'Maldives' }, { name: 'Mali' }, { name: 'Malta' }, { name: 'Marshall Islands' }, { name: 'Mauritania' }, { name: 'Mauritius' }, { name: 'Mexico' }, { name: 'Micronesia' }, { name: 'Moldova' }, { name: 'Monaco' }, { name: 'Mongolia' }, { name: 'Montenegro' }, { name: 'Morocco' }, { name: 'Mozambique' }, { name: 'Namibia' }, { name: 'Nauru' }, { name: 'Nepal' }, { name: 'Netherlands' }, { name: 'Netherlands Antilles' }, { name: 'New Zealand' }, { name: 'Nicaragua' }, { name: 'Niger' }, { name: 'Nigeria' }, { name: 'North Korea' }, { name: 'Norway' }, { name: 'Oman' }, { name: 'Pakistan' }, { name: 'Palau' }, { name: 'Palestinian Territories' }, { name: 'Panama' }, { name: 'Papua New Guinea' }, { name: 'Paraguay' }, { name: 'Peru' }, { name: 'Philippines' }, { name: 'Poland' }, { name: 'Portugal' }, { name: 'Qatar' }, { name: 'Romania' }, { name: 'Russia' }, { name: 'Rwanda' }, { name: 'Saint Kitts and Nevis' }, { name: 'Saint Lucia' }, { name: 'Saint Vincent and the Grenadines' }, { name: 'Samoa ' }, { name: 'San Marino' }, { name: 'Sao Tome and Principe' }, { name: 'Saudi Arabia' }, { name: 'Senegal' }, { name: 'Serbia' }, { name: 'Seychelles' }, { name: 'Sierra Leone' }, { name: 'Singapore' }, { name: 'Sint Maarten' }, { name: 'Slovakia' }, { name: 'Slovenia' }, { name: 'Solomon Islands' }, { name: 'Somalia' }, { name: 'South Africa' }, { name: 'South Korea' }, { name: 'South Sudan' }, { name: 'Spain ' }, { name: 'Sri Lanka' }, { name: 'Sudan' }, { name: 'Suriname' }, { name: 'Swaziland ' }, { name: 'Sweden' }, { name: 'Switzerland' }, { name: 'Syria' }, { name: 'Taiwan' }, { name: 'Tajikistan' }, { name: 'Tanzania' }, { name: 'Thailand ' }, { name: 'Timor-Leste' }, { name: 'Togo' }, { name: 'Tonga' }, { name: 'Trinidad and Tobago' }, { name: 'Tunisia' }, { name: 'Turkey' }, { name: 'Turkmenistan' }, { name: 'Tuvalu' }, { name: 'Uganda' }, { name: 'Ukraine' }, { name: 'United Arab Emirates' }, { name: 'United Kingdom' }, { name: 'United States' }, { name: 'Uruguay' }, { name: 'Uzbekistan' }, { name: 'Vanuatu' }, { name: 'Venezuela' }, { name: 'Vietnam' }, { name: 'Yemen' }, { name: 'Zambia' }, { name: 'Zimbabwe' } ]; } UI.registerHelper('countries', function() { return Countries(); }); }
var browserify = require('browserify'); var gulp = require('gulp'); var concat = require('gulp-concat'); var plumber = require('gulp-plumber'); var sourcemaps = require('gulp-sourcemaps'); var merge = require('merge-stream'); var stylus = require('gulp-stylus'); var typescript = require('gulp-typescript'); var uglify = require('gulp-uglify'); var gutil = require('gulp-util'); var nib = require('nib'); var tsify = require('tsify'); var buffer = require('vinyl-buffer'); var source = require('vinyl-source-stream'); gulp.task('server', function () { var tsProject = typescript.createProject('./website/tsconfig.json'); return merge( tsProject.src() .pipe(plumber()) .pipe(typescript(tsProject)) .pipe(gulp.dest('./build/website')), gulp.src('./website/static/**/*') .pipe(gulp.dest('build/website/static')), gulp.src('./website/views/**/*') .pipe(gulp.dest('build/website/views')) ); }); gulp.task('js', function () { return merge( gulp.src('./bower_components/tween.js/src/Tween.js'), browserify({entries: './website/js/index.ts'}) .plugin(tsify) .bundle() .on('error', function (err) { console.log(err); this.emit('end'); }) .pipe(source('index.js')) .pipe(buffer()) ) .pipe(gulp.env.dev ? sourcemaps.init() : gutil.noop()) .pipe(concat('index.js')) .pipe(gulp.env.dev ? gutil.noop() : uglify()) .pipe(gulp.env.dev ? sourcemaps.write() : gutil.noop()) .pipe(gulp.dest('build/website/static')); }); gulp.task('css', function () { return gulp.src('./website/css/index.styl') .pipe(plumber()) .pipe(stylus({paths: ['vendor'], use: [nib()], compress: !gulp.env.dev})) .pipe(gulp.dest('./build/website/static')); }); gulp.task('build-website', ['server', 'js', 'css']); gulp.task('watch-website', ['server', 'js', 'css'], function () { gulp.watch('website/**/*', ['server']); gulp.watch('website/**/*.ts', ['js']); gulp.watch('website/**/*.styl', ['css']); });
/** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../../..' export const run = editor => { Editor.liftNodes(editor, { match: ([, p]) => p.length === 3 }) } export const input = ( <editor> <block a> <block b> <block c> <cursor /> one </block> </block> </block> </editor> ) export const output = ( <editor> <block a> <block c> <cursor /> one </block> </block> </editor> )
var searchData= [ ['shuffle',['SHUFFLE',['../namespacetracery.html#ad14bf013269f3bf1b71343273b964ef3a32c8c28c94e87c28834c2137bc386d66',1,'tracery']]] ];
'use strict'; /** * @class NotesDetailCtrl * @classdesc The note detail * @ngInject */ function NotesDetailCtrl ($state, app, note) { var vm = this; vm.title = 'Note Details'; vm.note = note; /** * @description Saves the note */ vm.save = function () { app .saveNote(vm.note) .then(function () { $state.go('notes.index'); }); }; vm.cancel = function () { $state.go('notes.index'); }; } NotesDetailCtrl.template = require('./detail.html'); NotesDetailCtrl.resolve = { note: function ($q, $stateParams, app) { if ($stateParams.id === 'new') { return $q.when({}); } return app.getNote($stateParams.id); } }; module.exports = NotesDetailCtrl;
import actionTypes from './actionTypes'; const initialState = { allGames: [] }; export default function reducers(state = initialState, action) { let allGames; let game; let newGame; let updatedGame; let previousSlugGame; let gameIndex; let newGames; switch (action.type) { case actionTypes.FETCH_GAMES: return { ...state, allGames: action.games }; case actionTypes.DELETE_GAME: game = action.game; allGames = state.allGames.filter((gameInState) => gameInState.slug !== game.slug); return { ...state, allGames }; case actionTypes.CREATE_GAME: newGame = action.game; return { ...state, allGames: state.allGames.concat([newGame]) }; case actionTypes.EDIT_GAME: updatedGame = action.game; previousSlugGame = action.previousGame.slug; gameIndex = state.allGames.findIndex((g) => g.slug === previousSlugGame); newGames = state.allGames.slice(); newGames[gameIndex] = updatedGame; return { ...state, allGames: newGames }; default: return state; } }
const Q = require('q'); const readtorrent = require('read-torrent'); const async = require('async'); const Tracker = require('node-tracker'); module.exports = function(torrent) { const defer = Q.defer(); let results = []; let health = {}; readtorrent(torrent, function(err, torrentInfo) { if (err) { defer.reject(err); } else { async.eachLimit( torrentInfo.announce, 10, function(tr, cb) { // Complete tracker announce if not set if (tr.indexOf('/announce') === -1) { tr += '/announce'; } const tracker = new Tracker(tr); setTimeout(function() { const resolved = null; // Timeout and continue with other sources const timeout = setTimeout(function() { if (!resolved) { tracker.close(); return cb(); } }, 3000); tracker.scrape([torrentInfo.infoHash], function(err, msg) { clearTimeout(timeout); if (err) { return cb(); } if (msg[torrentInfo.infoHash]) { results.push({ seeds: msg[torrentInfo.infoHash].seeders, peers: msg[torrentInfo.infoHash].leechers }); } resolved = true; tracker.close(); return cb(); }); }, 1000); }, function(err) { const totalSeeds = 0; const totalPeers = 0; for (let r in results) { totalSeeds += parseInt(results[r].seeds); totalPeers += parseInt(results[r].peers); } health.seeds = Math.round(totalSeeds / results.length) || 0; health.peers = Math.round(totalPeers / results.length) || 0; defer.resolve(health); } ); } }); return defer.promise; };
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: 'da35e844aaf216ca186b05939f646534', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ cookie: { maxAge: 24 * 60 * 60 * 1000 }, /*************************************************************************** * * * In production, uncomment the following lines to set up a shared redis * * session store that can be shared across multiple Sails.js servers * ***************************************************************************/ adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * https://github.com/visionmedia/connect-redis * * * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password> // prefix: 'sess:' /*************************************************************************** * * * Uncomment the following lines to use your Mongo adapter as a session * * store * * * ***************************************************************************/ // adapter: 'mongo', // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', /*************************************************************************** * * * Optional Values: * * * * # Note: url will override other connection settings url: * * 'mongodb://user:pass@host:port/database/collection', * * * ***************************************************************************/ // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
'use strict'; module.exports = function(grunt) { var _ = require('underscore'), packageConfig = grunt.file.readJSON('package.json'), pluginConfig = grunt.file.readJSON('paprcolumns.jquery.json'), lumbarConfig = grunt.file.readJSON('lumbar.json'); // Project configuration. var config = { meta: _.extend({}, packageConfig, pluginConfig), concat: {}, jshint: {}, uglify: {}, copy: {}, compress: {}, clean: {} }; config.clean.files = ['dist']; config.concat.options = { separator: '\n\n', stripBanners: true }; config.concat.dist = { src: lumbarConfig.modules.paprcolumns.scripts, dest: 'dist/<%= meta.name %>.js' }; // we replace variables in place config.concat.moduleVariables = { options: { process: true }, expand: true, cwd: 'dist/', src: ['*.js', '*.css', 'jquery*' ], dest: 'dist' }; config.jshint.gruntfile = { options: { jshintrc: '.jshintrc' }, src: ['Gruntfile.js'] }; config.jshint.dist = { options: { jshintrc: 'src/.jshintrc' }, src: [config.concat.dist.dest] }; config.jshint.test = { options: { jshintrc: 'test/.jshintrc' }, src: ['test/**/*.js'] }; config.uglify = { dist: { src: '<%= concat.dist.dest %>', dest: 'dist/<%= meta.name %>.min.js' } }; config.qunit = { files: [ 'test/**/*.html' ] }; grunt.initConfig(config); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-jshint'); var allTasks = [ 'clean', 'jshint:gruntfile', 'jshint:test', 'concat:dist', 'concat:moduleVariables', 'jshint:dist', 'qunit', 'uglify' ]; // Default task. grunt.registerTask('default', allTasks); // for now the travis task is the same as default, but since that might change // we went ahead and set it up here so that the travis config wouldn't need to // also change if we want to tweak how grunt runs when we are using travis grunt.registerTask('travis', allTasks); grunt.registerTask('notest', _.without(_.extend([], allTasks), 'qunit')); };
version https://git-lfs.github.com/spec/v1 oid sha256:dc2fecf332db6cffaa90ea5d8f0b77a4af434f3deaa33e4bead308cc8417f392 size 3512
/* jshint node: true */ 'use strict'; var VersionChecker = require('ember-cli-version-checker'); module.exports = { name: 'ember-cli-pagination', init: function() { this._super.init && this._super.init.apply(this, arguments); var checker = new VersionChecker(this); var dep = checker.for('ember-cli', 'npm'); dep.assertAbove('1.13.0'); } };
import getBaseUrl from './get-base-url' import objectToQueryString from './object-to-query-string' import fieldsToParams from './fields-to-params' export default function buildEventUrl( trackingId, timestamp, userId, params = {}, anonymizeIp = false ) { const paramsQueryString = objectToQueryString(fieldsToParams(params)) return ( getBaseUrl() + (paramsQueryString ? '&' + paramsQueryString : '') + (anonymizeIp ? '&aip=1' : '') + '&cid=' + userId + '&tid=' + trackingId + '&z=' + timestamp ) }
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import Paper from 'material-ui/Paper'; import { translate, crudGetMany as crudGetManyAction } from 'admin-on-rest'; import compose from 'recompose/compose'; class Basket extends Component { componentDidMount() { this.fetchData(); } fetchData() { const { record: { basket }, crudGetMany } = this.props; crudGetMany('products', basket.map(item => item.product_id)); } render() { const { record, products, translate } = this.props; const { basket } = record; return ( <Paper style={{ width: '42em', float: 'right' }} zDepth={2}> <Table selectable={false}> <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> <TableHeaderColumn> {translate('resources.commands.fields.basket.reference')} </TableHeaderColumn> <TableHeaderColumn style={{ textAlign: 'right' }}> {translate('resources.commands.fields.basket.unit_price')} </TableHeaderColumn> <TableHeaderColumn style={{ textAlign: 'right' }}> {translate('resources.commands.fields.basket.quantity')} </TableHeaderColumn> <TableHeaderColumn style={{ textAlign: 'right' }}> {translate('resources.commands.fields.basket.total')} </TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false}> {basket.map(item => products[item.product_id] && ( <TableRow key={item.product_id}> <TableRowColumn> {products[item.product_id].reference} </TableRowColumn> <TableRowColumn style={{ textAlign: 'right' }}> {products[item.product_id].price.toLocaleString(undefined, { style: 'currency', currency: 'USD' })} </TableRowColumn> <TableRowColumn style={{ textAlign: 'right' }}> {item.quantity} </TableRowColumn> <TableRowColumn style={{ textAlign: 'right' }}> {(products[item.product_id].price * item.quantity).toLocaleString(undefined, { style: 'currency', currency: 'USD' })} </TableRowColumn> </TableRow>) )} <TableRow> <TableRowColumn colSpan={2} /> <TableRowColumn>{translate('resources.commands.fields.basket.sum')}</TableRowColumn> <TableRowColumn style={{ textAlign: 'right' }}> {record.total_ex_taxes.toLocaleString(undefined, { style: 'currency', currency: 'USD' })} </TableRowColumn> </TableRow> <TableRow> <TableRowColumn colSpan={2} /> <TableRowColumn>{translate('resources.commands.fields.basket.delivery')}</TableRowColumn> <TableRowColumn style={{ textAlign: 'right' }}> {record.delivery_fees.toLocaleString(undefined, { style: 'currency', currency: 'USD' })} </TableRowColumn> </TableRow> <TableRow> <TableRowColumn colSpan={2} /> <TableRowColumn>{translate('resources.commands.fields.basket.tax_rate')}</TableRowColumn> <TableRowColumn style={{ textAlign: 'right' }}> {record.tax_rate.toLocaleString(undefined, { style: 'percent' })} </TableRowColumn> </TableRow> <TableRow> <TableRowColumn colSpan={2} /> <TableRowColumn style={{ fontWeight: 'bold' }}>{translate('resources.commands.fields.basket.total')}</TableRowColumn> <TableRowColumn style={{ textAlign: 'right', fontWeight: 'bold' }}> {record.total.toLocaleString(undefined, { style: 'currency', currency: 'USD' })} </TableRowColumn> </TableRow> </TableBody> </Table> </Paper> ); } } const mapStateToProps = (state, props) => { const { record: { basket } } = props; const productIds = basket.map(item => item.product_id); return { products: productIds .map(productId => state.admin.products.data[productId]) .filter(r => typeof r !== 'undefined') .reduce((prev, next) => { prev[next.id] = next; return prev; }, {}), }; }; const enhance = compose( translate, connect(mapStateToProps, { crudGetMany: crudGetManyAction, }) ); export default enhance(Basket);
if(process.env.VCAP_SERVICES){ var env = JSON.parse(process.env.VCAP_SERVICES); var mongo = env['mongodb-1.8'][0]['credentials']; } else{ var mongo = { "hostname":"localhost", "port":27017, "username":"", "password":"", "name":"", "db":"senarium" } } var generate_mongo_url = function(obj){ obj.hostname = (obj.hostname || 'localhost'); obj.port = (obj.port || 27017); obj.db = (obj.db || 'test'); if(obj.username && obj.password){ return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db; } else{ return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db; } } module.exports = generate_mongo_url(mongo);
// // Drawphone Chain // import WordLink from "./link/wordlink.js"; import FirstWordLink from "./link/firstwordlink.js"; // A chain is the 'chain' of drawings and words. // A link is the individual drawing or word in the chain. class Chain { constructor(firstWord, owner, id, timeLimit, showNeighbors, playerList) { this.owner = owner; this.links = []; this.id = id; this.timeLimit = timeLimit; this.showNeighbors = showNeighbors; this.playerList = playerList; this.lastPlayerSentTo = owner.getJson(); if (!firstWord) { this.addLink(new FirstWordLink(this.owner)); } else { this.addLink(new WordLink(this.owner, firstWord)); } } addLink(link) { this.links.push(link); } getLastLink() { return this.links[this.links.length - 1]; } getLength() { if (this.links[0] && this.links[0].type === "first-word") { return this.links.length - 1; } return this.links.length; } //returns true if the player has a link in this chain already playerHasLink({ id }) { for (let i = 0; i < this.links.length; i++) { if (this.links[i].player.id === id) { return true; } } return false; } sendLastLinkToThen(player, finalCount, next) { let count = this.getLength(); if (this.links[0] && this.links[0].type === "first-word") { count++; } else { finalCount--; } //sends the link, then runs the second function // when the 'finishedLink' event is received player.sendThen( "nextLink", { link: this.getLastLink(), chainId: this.id, count, finalCount, timeLimit: this.timeLimit, showNeighbors: this.showNeighbors, players: this.showNeighbors ? this.playerList : null, thisPlayer: player.getJson(), }, "finishedLink", next ); } getJson() { return { owner: this.owner.getJson(), links: this.links, id: this.id, }; } } export default Chain;
import cx from 'classnames' import _ from 'lodash' import PropTypes from 'prop-types' import React, { Component } from 'react' import { childrenUtils, createShorthandFactory, customPropTypes, getUnhandledProps, getElementType, META, useKeyOnly, } from '../../lib' /** * A section sub-component for Breadcrumb component. */ export default class BreadcrumbSection extends Component { static propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Style as the currently active section. */ active: PropTypes.bool, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.contentShorthand, /** Render as an `a` tag instead of a `div` and adds the href attribute. */ href: customPropTypes.every([ customPropTypes.disallow(['link']), PropTypes.string, ]), /** Render as an `a` tag instead of a `div`. */ link: customPropTypes.every([ customPropTypes.disallow(['href']), PropTypes.bool, ]), /** * Called on click. When passed, the component will render as an `a` * tag by default instead of a `div`. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props. */ onClick: PropTypes.func, } static _meta = { name: 'BreadcrumbSection', type: META.TYPES.COLLECTION, parent: 'Breadcrumb', } computeElementType = () => { const { link, onClick } = this.props if (link || onClick) return 'a' } handleClick = e => _.invoke(this.props, 'onClick', e, this.props) render() { const { active, children, className, content, href, } = this.props const classes = cx( useKeyOnly(active, 'active'), 'section', className, ) const rest = getUnhandledProps(BreadcrumbSection, this.props) const ElementType = getElementType(BreadcrumbSection, this.props, this.computeElementType) return ( <ElementType {...rest} className={classes} href={href} onClick={this.handleClick}> {childrenUtils.isNil(children) ? content : children} </ElementType> ) } } BreadcrumbSection.create = createShorthandFactory(BreadcrumbSection, content => ({ content, link: true }))
export { default as BreakdownList } from "./Breakdown"; export { default as Head } from "./Head"; export { default as SVGIcon } from "./SVGIcon";
'use strict'; var pages = require('./pages/pages.js'); describe('Main page spec', function() { it('should open main page', function() { pages.mainPage.get(); expect(pages.mainPage.logo().getText()).toEqual('Docs'); }); });
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.4.4.14-2-9 description: > Array.prototype.indexOf - 'length' is own accessor property that overrides an inherited accessor property includes: [runTestCase.js] ---*/ function testcase() { var proto = {}; Object.defineProperty(proto, "length", { get: function () { return 0; }, configurable: true }); var Con = function () {}; Con.prototype = proto; var child = new Con(); child[1] = true; Object.defineProperty(child, "length", { get: function () { return 2; }, configurable: true }); return Array.prototype.indexOf.call(child, true) === 1; } runTestCase(testcase);
(function() { 'use strict'; angular.module('ui.gridster') .controller('GridsterController', ['$scope', '$element', '$attrs', function($scope, $element, $attrs) { this.scope = $scope; this.element = $element; $scope.$dragEnabled = true; $scope.$modelValue = null; var gridster = null; $scope.init = function(element, options) { gridster = element.gridster(options).data('gridster'); return gridster; }; this.addItem = function(element, sizeX, sizeY, col, row) { if (gridster) { return gridster.add_widget(element, sizeX, sizeY, col, row); } return null; }; this.removeItem = function(element) { if (gridster) { gridster.remove_widget(element, function() { $scope.$apply(); }); } }; this.resizeItem = function(widget, sizeX, sizeY) { if (gridster && widget) { gridster.resize_widget(widget, sizeX, sizeY); } }; $scope.serializeToJson = function() { var s = gridster.serialize(); return JSON.stringify(s); }; $scope.applyChanges = function() { var items = gridster.serialize(); angular.forEach(items, function(item, index) { var widget = $scope.$modelValue[index]; widget.sizeX = item.size_x; widget.sizeY = item.size_y; widget.row = item.row; widget.col = item.col; }); }; } ]); })();
import { module, test } from 'qunit'; import codec from 'gatemedia-data/utils/codec'; module('Codec - string'); test('encode works', function (assert) { assert.equal(codec.string.encode('paf'), 'paf'); }); test('decode works', function (assert) { assert.equal(codec.string.decode('paf'), 'paf'); }); module('Codec - number'); test('encode works', function (assert) { assert.equal(codec.number.encode(42), 42); }); test('decode works', function (assert) { assert.equal(codec.number.decode('42'), 42); }); module('Codec - boolean'); test('encode works', function (assert) { assert.equal(codec.boolean.encode(true), true); assert.equal(codec.boolean.encode(false), false); assert.equal(codec.boolean.encode(null), false); }); test('decode works', function (assert) { assert.equal(codec.boolean.decode(true), true); assert.equal(codec.boolean.decode(false), false); assert.equal(codec.boolean.decode(null), null); }); module('Codec - array[number]'); test('encode works', function (assert) { assert.deepEqual(codec.array.encode([ 36, 42 ], 'number'), [ 36, 42 ]); }); test('decode works', function (assert) { assert.deepEqual(codec.array.decode([ 36, 42 ], 'number'), [ 36, 42 ]); }); module('Codec - date'); test('encode works', function (assert) { assert.equal(codec.date.encode(moment('20141202', 'YYYYMMDD')), '2014-12-02'); assert.equal(codec.date.encode(null), null); }); test('decode works', function (assert) { assert.equal(codec.date.decode('2014-12-02').format(), moment('20141202', 'YYYYMMDD').format()); assert.equal(codec.date.decode(null), null); }); module('Codec - time'); test('encode works', function (assert) { assert.equal(codec.time.encode(moment('10:24', 'HH:mm')), '10:24'); assert.equal(codec.time.encode(null), null); }); test('decode works', function (assert) { assert.equal(codec.time.decode('10:24').format(), moment('10:24', 'HH:mm').format()); assert.equal(codec.time.decode(null), null); }); module('Codec - datetime'); test('encode works', function (assert) { assert.equal(codec.datetime.encode(moment.utc('20141202T10:24:44', 'YYYYMMDDTHH:mm:ss')), '2014-12-02T10:24:44+00:00'); assert.equal(codec.datetime.encode(null), null); }); test('decode works', function (assert) { assert.equal(codec.datetime.decode('2014-12-02T10:24:44').format(), moment.utc('20141202T10:24:44', 'YYYYMMDDTHH:mm:ss').format()); assert.equal(codec.datetime.decode(null), null); }); module('Codec - json'); test('encode works', function (assert) { // deepEqual(codec.json.encode({ a: 42, b: 'hop' }), '{"a":42,"b":"hop"}'); assert.deepEqual(codec.json.encode('{"a":42,"b":"hop"}'), { a: 42, b: 'hop' }); }); test('decode works', function (assert) { // deepEqual(codec.json.decode('{"a":42,"b":"hop"}'), { a: 42, b: 'hop' }); assert.deepEqual(codec.json.decode({ a: 42, b: 'hop' }), '{"a":42,"b":"hop"}'); });
/* * * StatusPage reducer * */ import { fromJS } from 'immutable'; import { random, shuffle } from 'lodash'; import { Personality } from '../../corpus'; import { genLiveStatusLineData } from '../ProfilePage/utils'; import { DEFAULT_ACTION, } from './constants'; const personalities = shuffle(Personality).slice(0, 94).map((personality) => ( { label: personality, percentage: random(0, 100), checked: false, } )); const initialState = fromJS({ bulkApperception: { title: 'bulk apperception', min: 1, max: 20, current: 14, }, aggression: { title: 'aggression', min: 0, max: 20, current: 6, }, loyalty: { title: 'loyalty', min: 0, max: 20, current: 17, }, cordination: { title: 'cordination', min: 0, max: 20, current: 12, }, selfPreservation: { title: 'self preservation', min: 0, max: 20, current: 12, }, personalities, selectedItem: { outerLabel: 'amnt:[0]%', innerLabel: 'prblty:[0]%', title: 'Bulk Apperception', }, profile: { hostId: 'Host id:AC273812', tags: ['fixed', 'old generation', 'alive'], metrics: [ { metricType: 'text', title: 'CPU 1', content: '123', }, { metricType: 'column', title: 'CPU 2', data: [10, 23, 12, 3, 45, 14, 86], }, { metricType: 'text', title: 'GPU 1', content: '123', }, { metricType: 'column', title: 'GPU 2', data: [10, 23, 12, 3, 45, 14, 86], }, { metricType: 'heat', title: 'Fan 1', value: 7, }, { metricType: 'progress', title: 'Upload 1', value: 29, }, ], liveStatusInfo: { title: 'live status', liveStatuses: [ { title: 'Live 1', maxX: 20 * 120, maxY: 120, data: genLiveStatusLineData(120, 20, 120), }, { title: 'Live 2', maxX: 20 * 120, maxY: 120, data: genLiveStatusLineData(120, 20, 120), }, { title: 'Live 3', maxX: 20 * 120, maxY: 120, data: genLiveStatusLineData(120, 20, 120), }, { title: 'Live 4', maxX: 20 * 120, maxY: 120, data: genLiveStatusLineData(120, 20, 120), }, ], }, liveNumbers: [ { title: 'HP', value: 110, min: 80, max: 140, }, { title: 'MP', value: 92, min: 60, max: 100, }, { title: 'RR', value: 40, min: 30, max: 60, }, ], }, }); function statusPageReducer(state = initialState, action) { switch (action.type) { case DEFAULT_ACTION: return state; default: return state; } } export default statusPageReducer;
const express = require('express'); const passport = require('passport'); const bcrypt = require('bcrypt'); const { isLoggedIn, isNotLoggedIn } = require('./middlewares'); const { User } = require('../models'); const router = express.Router(); router.post('/join', isNotLoggedIn, async (req, res, next) => { const { email, nick, password, money } = req.body; try { const exUser = await User.find({ where: { email } }); if (exUser) { req.flash('joinError', '이미 가입된 이메일입니다.'); return res.redirect('/join'); } const hash = await bcrypt.hash(password, 12); await User.create({ email, nick, password: hash, money, }); return res.redirect('/'); } catch (error) { console.error(error); return next(error); } }); router.post('/login', isNotLoggedIn, (req, res, next) => { passport.authenticate('local', (authError, user, info) => { if (authError) { console.error(authError); return next(authError); } if (!user) { req.flash('loginError', info.message); return res.redirect('/'); } return req.login(user, (loginError) => { if (loginError) { console.error(loginError); return next(loginError); } return res.redirect('/'); }); })(req, res, next); }); router.get('/logout', isLoggedIn, (req, res) => { req.logout(); req.session.destroy(); res.redirect('/'); }); module.exports = router;
"use strict"; function Maze(width, height) { this.width = width; this.height = height; this.startX = null; this.startY = null; this.startOrientation = null; this.endX = null; this.endY = null; this.directions = ["north", "east", "south", "west"]; this.spaces = []; var x, y; for(x = 1; x <= width; x += 1) { this.spaces[x] = []; for (y = 1; y <= height; y += 1) { this.spaces[x][y] = new MazeSpace(this.directions); } } } Maze.prototype.setStart = function(x, y, orientation) { if (this.isInBounds(x, y) && this.isValidDirection(orientation)) { this.startX = x; this.startY = y; this.startOrientation = orientation; return true; } return false; } Maze.prototype.setEnd = function (x, y) { if(!this.isInBounds(x, y)) { return false; } this.endX = x; this.endY = y; return true; } Maze.prototype.setWall = function(x, y, direction) { if(this.isInBounds(x, y) && this.isValidDirection(direction)) { this.spaces[x][y].setWall(direction); return true; } return false; } Maze.prototype.isValidDirection = function(direction) { return this.directions.indexOf(direction) !== -1; } Maze.prototype.isInBounds = function(x, y) { return x > 0 && x <= this.width && y > 0 && y <= this.height; } Maze.prototype.canMove = function(x, y, direction) { if(!this.isValidDirection(direction)) { return false; } if(!this.isInBounds(x, y)) { return false; } var forwardX, forwardY; switch (direction) { case "north": forwardX = x; forwardY = y + 1; break; case "east": forwardX = x + 1; forwardY = y; break; case "south": forwardX = x; forwardY = y - 1; break; case "west": forwardX = x - 1; forwardY = y; break; } if(!this.isInBounds(forwardX, forwardY)) { return false; } if(this.spaces[x][y][direction]) { return false; } var opposites = { north: "south", east: "west", south: "north", west: "east" } if(this.spaces[forwardX][forwardY][opposites[direction]]) { return false; } return true; }
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var exphbs = require('express-handlebars'); var helpers = require('./lib/helpers'); var logger = require('./lib/logger'); var routes = require('./routes/index'); var app = express(); app.use(require('morgan')("combined", { "stream": logger.stream })); // view engine setup app.set('views', path.join(__dirname, 'views')); app.engine('hbs', exphbs({ defaultLayout: 'layout', extname: '.hbs', // helpers: require('./public/js/helpers.js').helpers, // same file that gets used on our client partialsDir: 'views/partials/', // same as default, I just like to be explicit layoutsDir: 'views/layouts/', // same as default, I just like to be explicit helpers: helpers })); app.set('view engine', '.hbs'); // uncomment after placing your favicon in /public app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(require('less-middleware')(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public'))); app.use('*', routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; logger.debug('404 Warning. URL: ' + req.url); next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); logger.debug('Error: ' + (err.status || 500).toString() + ' ' + err); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); logger.debug('Error: ' + (err.status || 500).toString() + ' ' + err); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
var gulp = require('gulp'), rigger = require('gulp-rigger'), uglify = require('gulp-uglifyjs'), header = require('gulp-header'), pkg = require('./package.json'); var banner = ['/**', ' * <%= pkg.name %> - <%= pkg.description %>', ' * @version v<%= pkg.version %>', ' * @link <%= pkg.homepage %>', ' * @license <%= pkg.license %>', ' * @author <%= pkg.author %>', ' */', ''].join('\n'); gulp.task('rig', function () { gulp.src('src/smartflow.js') .pipe(rigger()) .pipe(header(banner, { pkg : pkg } )) .pipe(gulp.dest('./')); }); gulp.task('uglify',['rig'] , function() { gulp.src('smartflow.js') .pipe(uglify('smartflow.min.js')) .pipe(header(banner, { pkg : pkg } )) .pipe(gulp.dest('./')) });
export default { title: 'Pagination/Pagination/Links/Cascade' }; export const fontSize = () => ` <nav class="pagination" aria-labelledby="pagination-heading" role="navigation" style="font-size: 200%"> <span aria-live="polite" role="status"> <h2 class="clipped" id="pagination-heading">Results Pagination - Page 1</h2> </span> <a aria-disabled="true" aria-label="Previous Page" class="icon-link pagination__previous" href="http://www.ebay.com/sch/i.html?_nkw=guitars"> <svg class="icon icon--pagination-prev" focusable="false" height="24" width="24" aria-hidden="true"> <use xlink:href="#icon-pagination-prev"></use> </svg> </a> <ol class="pagination__items"> <li> <a aria-current="page" href="http://www.ebay.com/sch/i.html?_nkw=guitars" class="pagination__item">1</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=2" class="pagination__item">2</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=3" class="pagination__item">3</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=4" class="pagination__item">4</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=5" class="pagination__item">5</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=6" class="pagination__item">6</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=7" class="pagination__item">7</a> </li> </ol> <a aria-label="Next Page" class="icon-link pagination__next" href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=2"> <svg class="icon icon--pagination-next" focusable="false" height="24" width="24" aria-hidden="true"> <use xlink:href="#icon-pagination-next"></use> </svg> </a> </nav> `; export const color = () => ` <nav class="pagination" aria-labelledby="pagination-heading" role="navigation" style="color: green"> <span aria-live="polite" role="status"> <h2 class="clipped" id="pagination-heading">Results Pagination - Page 1</h2> </span> <a aria-disabled="true" aria-label="Previous Page" class="icon-link pagination__previous" href="http://www.ebay.com/sch/i.html?_nkw=guitars"> <svg class="icon icon--pagination-prev" focusable="false" height="24" width="24" aria-hidden="true"> <use xlink:href="#icon-pagination-prev"></use> </svg> </a> <ol class="pagination__items"> <li> <a aria-current="page" href="http://www.ebay.com/sch/i.html?_nkw=guitars" class="pagination__item">1</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=2" class="pagination__item">2</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=3" class="pagination__item">3</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=4" class="pagination__item">4</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=5" class="pagination__item">5</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=6" class="pagination__item">6</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=7" class="pagination__item">7</a> </li> </ol> <a aria-label="Next Page" class="icon-link pagination__next" href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=2"> <svg class="icon icon--pagination-next" focusable="false" height="24" width="24" aria-hidden="true"> <use xlink:href="#icon-pagination-next"></use> </svg> </a> </nav> `; export const RTL = () => ` <div dir="rtl"> <nav class="pagination" aria-labelledby="pagination-heading" role="navigation"> <span aria-live="polite" role="status"> <h2 class="clipped" id="pagination-heading">Results Pagination - Page 1</h2> </span> <a aria-disabled="true" aria-label="Previous Page" class="icon-link pagination__previous" href="http://www.ebay.com/sch/i.html?_nkw=guitars"> <svg class="icon icon--pagination-prev" focusable="false" height="24" width="24" aria-hidden="true"> <use xlink:href="#icon-pagination-prev"></use> </svg> </a> <ol class="pagination__items"> <li> <a aria-current="page" href="http://www.ebay.com/sch/i.html?_nkw=guitars" class="pagination__item">1</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=2" class="pagination__item">2</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=3" class="pagination__item">3</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=4" class="pagination__item">4</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=5" class="pagination__item">5</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=6" class="pagination__item">6</a> </li> <li> <a href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=7" class="pagination__item">7</a> </li> </ol> <a aria-label="Next Page" class="icon-link pagination__next" href="http://www.ebay.com/sch/i.html?_nkw=guitars&_pgn=2"> <svg class="icon icon--pagination-next" focusable="false" height="24" width="24" aria-hidden="true"> <use xlink:href="#icon-pagination-next"></use> </svg> </a> </nav> </div> `;
version https://git-lfs.github.com/spec/v1 oid sha256:4670f996f717851f640d120129dee1147193f06e490cd33839eb1d2e649a4d95 size 1625
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Cart = mongoose.model('Cart'), Category = mongoose.model('Category'), Good = mongoose.model('Good'), _ = require('lodash'); /** * Create a Cart */ exports.create = function(req, res) { var sgoods = req.body.detail.goods, sprice = req.body.detail.price, samount = req.body.detail.amount, _total = req.body.total ? _.ceil(req.body.total,2) : _.ceil(sprice*samount,2), _total_amount, _goods = { goods:sgoods, amount:samount, price:sprice, }; if (sgoods){ Cart.findOne({user:req.user,order_status:false,'detail.goods':sgoods},function(err,cart){ if (err){console.log(err);} else if(cart){ var i = cart.detail.length; while(i--){ if (sgoods.toString() === cart.detail[i].goods.toString()){ cart.detail[i].amount += 1; cart.total += sprice; } } if (i){ _total_amount = _.sum(cart.detail,'amount'); cart.save(function (err,cart){ if (err){console.log(err);} else { res.send(cart); } }); } else { cart.update({$push:{detail:_goods},$inc:{total:_total,total_amount:_goods.amount}},function (err,cart){ res.send(cart); }); } } else{ Cart.findOneAndUpdate({user:req.user,order_status:false},{$push:{detail:_goods},$inc:{total:_total,total_amount:_goods.amount}},function (err,cart){ if(err){console.log(err);} else if(cart){ res.send(cart); } else { var _cart = new Cart(req.body); _cart.user = req.user; _cart.detail = _goods; _cart.total = _total; _cart.total_amount = samount; _cart.save(function (err,cart) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.send(cart); } }); } }); } }); } }; /** * Show the current Cart */ exports.read = function(req, res) { res.jsonp(req.cart); }; /** * Update a Cart */ exports.update = function(req, res) { var cart = req.cart ; cart = _.extend(cart , req.body); cart.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(cart); } }); }; /** * Change the goods total in cart */ exports.changeAmount = function(req, res) { Cart.findOne({_id:req.body.cart._id},function (err,cart) { var i = cart.detail.length; while(i--){ if (req.body.goodId.toString() === cart.detail[i].goods.toString()){ cart.total += cart.detail[i].price * (req.body.cart_amount-cart.detail[i].amount); cart.detail[i].amount = req.body.cart_amount; } } cart.total_amount = req.body.total_amount; cart.save(function (err,cart){ if (err){console.log(err);} else { res.send(cart); } }); }); }; /** * Delete an Cart */ exports.delete = function(req, res) { var cart = req.cart ; cart.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(cart); } }); }; /** * Delete an Cart.goods */ exports.deleteGoods = function(req, res) { var _total, goodObj; Cart.findOne({_id:req.body.cart._id,'detail.goods':req.body.goodId._id},function (err,cart){ var i = cart.detail.length; if (i > 1){ while (i--){ if(req.body.goodId._id.toString() === cart.detail[i].goods.toString()){ goodObj = cart.detail[i]; _total = cart.detail[i].price * cart.detail[i].amount; } } Cart.findOneAndUpdate({_id:req.body.cart._id},{$pull:{detail:goodObj},$inc:{total:-_total}},function (err,cart){ if(err){console.log(err);} else { res.send(cart); } }); } else { Cart.remove({_id:req.body.cart._id},function (err){ if (err){console.log(err);} else { res.send('delete success'); } }); } }); }; /** * List of Carts */ exports.list = function(req, res) { if (req.user) { var userId = req.user._id; if (userId) { Cart.find({user:userId}).sort('-created').populate('detail.goods', 'category subcat main_img price spec weight origin delivery sale name title for_free free_try sold pv').exec(function(err, carts) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(carts); } }); } } }; /** * Count of Carts */ exports.count = function(req, res) { Cart.count().exec(function(err, carts) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(carts); } }); }; /** * Modify a Cart */ exports.modify = function(req, res) { var cartObj = req.body; Cart.findOneAndUpdate({_id:cartObj._id},{subcat:cartObj.subcat,name:cartObj.name,title:cartObj.title,price:cartObj.price},function (err,cart) { if (err) { console.log(err); return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(cart); } }); }; /** * Cart middleware */ exports.cartByID = function(req, res, next, id) { Cart.findById(id).populate('user', 'displayName').populate('detail.goods', 'main_img price spec sale title for_free free_try').exec(function(err, cart) { if (err) return next(err); if (! cart) return next(new Error('Failed to load Cart ' + id)); req.cart = cart ; next(); }); }; /** * Cart authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.cart.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
var documents = require('../documents.json') var expected = require('../data/idf-stem-rank-!facets.json') var options = { idf: true, stem: true, rank: false, facets: false } var inverted = process.env.INVERTED_COV ? require('../../lib-cov/inverted-index') : require('../../') var timehat = require('timehat') var level = require('level')(__dirname + '/../dbs/db-' + timehat()) var async = require('async') var assert = require('assert') var text = inverted(level, options, function(id, fn){ fn(null, documents[id].text) }) var index = function(fn){ async.forEach(Object.keys(documents), function(id, fn){ text.index(documents[id].text, id, documents[id].facets, fn) }, fn) } var getAllKeys = function(fn){ var keys = [] level.createKeyStream() .on('error', fn) .on('data', function(key){ keys.push([key, text.parseKey(key, true)]) }) .on('end', function(){ fn(null, keys) }) } module.exports = function(){ before(index) after(function(fn){ level.close(function(err){ fn(err) }) }) // describe('index', function(){ // it('should save the right keys', function(fn){ // getAllKeys(function(err, keys){ // if(err) return fn(err) // assert(expected.keys.length === keys.length) // assert(keys.filter(function(key){ // return expected.keys.indexOf(key[0]) >= 0 // }).length === keys.length) // fn() // }) // }) // }) describe('query', function(){ it('with limit', function(fn){ text.query('Node.js', { limit: 1 }, function(err, result){ assert(!err) assert(result.results.length === 1) var first = result.results[0] text.query({ last: result.last }, { limit: 1 }, function(err, result){ if(err) throw err assert(result.results[0] !== first) assert(result.results.length === 1) fn() }) }) }) it('with one facet', function(fn){ text.query('node.js', 'article', function(err, result){ assert(!err) assert(result.last.length) assert(result.results.length === 2) assert(!!~result.results.indexOf('4')) assert(!!~result.results.indexOf('5')) fn() }) }) it('with more than one facet', function(fn){ text.query('node.js', ['library', 'comment'], function(err, result){ assert(!err) assert(result.last.length) assert(result.results.length === 2) assert(!!~result.results.indexOf('4')) assert(!!~result.results.indexOf('5')) fn() }) }) it('without facets', function(fn){ text.query('webos', function(err, result){ assert(!err) assert(result.last.length) assert(result.results.length === 2) assert(!!~result.results.indexOf('6')) assert(!!~result.results.indexOf('7')) fn() }) }) it('with options and facets', function(fn){ text.query('webos', 'article', { limit: 1, ttl: 1 }, function(err, result){ assert(!err) assert(result.last.length) assert(result.results.length === 1) assert(!!~result.results.indexOf('6')) fn() }) }) }) describe('remove', function(){ it('should remove', function(fn){ text.remove('2', fn) }) it('should not have any keys from removed id', function(fn){ getAllKeys(function(err, keys){ assert(!err) assert(expected.keys.length !== keys.length) assert(keys.filter(function(key){ return key[1].id === '2' }).length === 0) fn() }) }) it('should return 0 results', function(fn){ text.query('vehicula', function(err, result){ assert(!err) assert(!result.results.length) fn() }) }) }) }
module.exports.tasks = { watch: { sass: { files: ['<%= settings.webAssets %>/**/*.scss'], tasks: ['sass'] }, index: { files: ['<%= settings.webAssets %>/**/*.html'], tasks: ['copy'] } } };
'use strict'; //Setting up route angular.module('manage-users').config(['$stateProvider', function($stateProvider) { // Manage users state routing $stateProvider. state('listManageUsers', { url: '/manage-users', templateUrl: 'modules/manage-users/views/list-manage-users.client.view.html', action:'list_users', title:'Users' }). state('createManageUser', { url: '/manage-users/create', templateUrl: 'modules/manage-users/views/create-manage-user.client.view.html', action:'create_user', title:'New user' }). state('searchManageUser', { url: '/manage-users/search', templateUrl: 'modules/manage-users/views/search-manage-users.client.view.html', action:'list_users', title:'Search Users' }). state('viewManageUser', { url: '/manage-users/:manageUserId', templateUrl: 'modules/manage-users/views/view-manage-user.client.view.html', action:'view_user', title:'View User' }). state('editManageUser', { url: '/manage-users/:manageUserId/edit', templateUrl: 'modules/manage-users/views/edit-manage-user.client.view.html', action:'edit_user', title:'Edit User' }); } ]);
/** * Copyright 2012-2020, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var Lib = require('../../lib'); var Template = require('../../plot_api/plot_template'); var axisIds = require('../../plots/cartesian/axis_ids'); var attributes = require('./attributes'); var oppAxisAttrs = require('./oppaxis_attributes'); module.exports = function handleDefaults(layoutIn, layoutOut, axName) { var axIn = layoutIn[axName]; var axOut = layoutOut[axName]; if(!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return; // not super proud of this (maybe store _ in axis object instead if(!Lib.isPlainObject(axIn.rangeslider)) { axIn.rangeslider = {}; } var containerIn = axIn.rangeslider; var containerOut = Template.newContainer(axOut, 'rangeslider'); function coerce(attr, dflt) { return Lib.coerce(containerIn, containerOut, attributes, attr, dflt); } var rangeContainerIn, rangeContainerOut; function coerceRange(attr, dflt) { return Lib.coerce(rangeContainerIn, rangeContainerOut, oppAxisAttrs, attr, dflt); } var visible = coerce('visible'); if(!visible) return; coerce('bgcolor', layoutOut.plot_bgcolor); coerce('bordercolor'); coerce('borderwidth'); coerce('thickness'); coerce('autorange', !axOut.isValidRange(containerIn.range)); coerce('range'); var subplots = layoutOut._subplots; if(subplots) { var yIds = subplots.cartesian .filter(function(subplotId) { return subplotId.substr(0, subplotId.indexOf('y')) === axisIds.name2id(axName); }) .map(function(subplotId) { return subplotId.substr(subplotId.indexOf('y'), subplotId.length); }); var yNames = Lib.simpleMap(yIds, axisIds.id2name); for(var i = 0; i < yNames.length; i++) { var yName = yNames[i]; rangeContainerIn = containerIn[yName] || {}; rangeContainerOut = Template.newContainer(containerOut, yName, 'yaxis'); var yAxOut = layoutOut[yName]; var rangemodeDflt; if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { rangemodeDflt = 'fixed'; } var rangeMode = coerceRange('rangemode', rangemodeDflt); if(rangeMode !== 'match') { coerceRange('range', yAxOut.range.slice()); } } } // to map back range slider (auto) range containerOut._input = containerIn; };
import Component from '@ember/component'; import { set, get, setProperties } from '@ember/object'; import { inject as service } from '@ember/service'; import layout from './template'; import RSVP from 'rsvp'; import opacity from 'ember-animated/motions/opacity'; import scale from 'ember-animated/motions/scale'; import move from 'ember-animated/motions/move'; import { easeInOut as easing } from 'ember-animated/easings/cosine'; /** `{{dialog-box}}`es are a modal dialog component. This component is used to both mount and render dialogs in apps. To mount the dialog, place the following code in your application template: ```htmlbars {{dialog-box}} ``` This lets the dialog box know where to render boxes that are rendered in other routes. When a dialog should be displayed, render it by showing it in an if: ```htmlbars {{#if sorting}} {{#with (action (mut sorting) false) as |dismiss|}} {{dialog-box (component 'sorting-hat-dialog' onsort=(pipe (action (mut house)) dismiss)) ondismiss=dismiss}} {{/with}} {{/if}} ``` This example has a few things worth noting. Dialogs do not dismiss automatically when an action is triggered. They must be dismissed after completing the action. This allows for the dialog to remain open while saving, etc. This can also be handled inside the component if you wish. `ondismiss` is a required action by `{{dialog-box}}`. This action should dismiss the dialog from the screen. Components created by the dialog box are given a hash with helpers provided by the dialog itself. These are: - `dismiss` @public @class DialogBox @extends Ember.Component */ export default Component.extend({ tagName: '', layout, open: service(), /** `ondismiss` is triggered when the dialog is dismissed. The action taken by this handler should remove the `{{dialog-box}}` component from the page. @event ondismiss */ ondismiss: null, duration: 200, /** `dialog-class` is a list of classes that will be added to the root of the dialog that's being rendered. @property dialog-class @default '' @type String */ 'dialog-class': '', didReceiveAttrs() { let send = { className: 'dialog-box', dismiss: this.ondismiss, dialog: this.dialog, group: this.group, class: this['dialog-class'] }; if (get(this, 'send.dialog')) { delete send.dialog; setProperties(this, 'send', send); } else { set(this, 'send', send); } }, fade: function* ({ insertedSprites, removedSprites }) { yield RSVP.all([ ...insertedSprites.map(sprite => opacity(sprite, { from: 0, to: 1 })), ...removedSprites.map(sprite => opacity(sprite, { from: 1, to : 0 })) ]); if (insertedSprites.length) { document.body.classList.add('noscroll'); } else { document.body.classList.remove('noscroll'); } }, show: function* ({ receivedSprites, sentSprites }) { yield RSVP.all([ ...receivedSprites.map(sprite => { return RSVP.all([ scale(sprite, { easing }), move(sprite, { easing }), opacity(sprite, { from: 0, to: 1, easing }) ]); }), ...sentSprites.map(sprite => { return RSVP.all([ scale(sprite, { easing }), move(sprite, { easing }), opacity(sprite, { from: 1, to: 0, easing }) ]); }) ]); } }).reopenClass({ positionalParams: ['dialog'] });
import step21 from "highlight.js/lib/languages/step21"; export default step21;
/* x-csrf token - requires unique */ 'use strict'; var typeOf = require('super-is').typeOf; var e = require('../../errors'); module.exports = { xcsrf: { enumerable: true, set: function (value) { if (!typeOf('string', value) || !value.trim().length) { throw new e.UnauthorizedError('Invalid XCSRF Token'); } return value; } } };
// Generated by CoffeeScript 1.7.1 (function() { var AbstractService, GetAgencies, __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; }; AbstractService = require('./AbstractService'); GetAgencies = (function(_super) { __extends(GetAgencies, _super); function GetAgencies() { return GetAgencies.__super__.constructor.apply(this, arguments); } GetAgencies.prototype._parse = function(obj) { var agencies, _A, _i, _len, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _ref9; agencies = {}; _ref4 = (_ref = obj != null ? (_ref1 = obj.RTT) != null ? (_ref2 = _ref1.AgencyList) != null ? (_ref3 = _ref2[0]) != null ? _ref3.Agency : void 0 : void 0 : void 0 : void 0) != null ? _ref : []; for (_i = 0, _len = _ref4.length; _i < _len; _i++) { _A = _ref4[_i]; if ((_A != null ? (_ref5 = _A['$']) != null ? _ref5.Name : void 0 : void 0)) { agencies[_A != null ? (_ref6 = _A['$']) != null ? _ref6.Name : void 0 : void 0] = { HasDirection: 'True' === (_A != null ? (_ref7 = _A['$']) != null ? _ref7.HasDirection : void 0 : void 0), Mode: (_ref8 = _A != null ? (_ref9 = _A['$']) != null ? _ref9.Mode : void 0 : void 0) != null ? _ref8 : null }; } } return agencies; }; return GetAgencies; })(AbstractService); module.exports = GetAgencies; }).call(this);
/** * @module constants */ /** * Constants used for mouse buttons. * * Identifier | Value * --------------------- | ------------------- * LEFT | `0` * MIDDLE | `1` * RIGHT | `2` * * * ## Usage examples * * var game = new tine.Game(null, { * update: function() { * if (game.mouse.isPressed(tine.buttons.LEFT)) { * console.log('mouse left pressed'); * } else if (game.mouse.isPressed(tine.buttons.MIDDLE)) { * console.log('mouse middle pressed'); * } * } * }) * * @class buttons */
google.load("jquery", "1.4.1"); google.load("jqueryui", "1.7.2"); google.setOnLoadCallback(function() { var nav = $('#tabs'); nav.tabs(); nav.bind('tabsselect', function(event, ui) { window.location.hash = ui.tab.hash; }); $('#uv-form').submit(function() { var theme = $('#theme').val(), data = $(this).serialize(); $.get("/api", data, function(result) { $('#tabs-result').html(themeLink(theme) + result); $('#src').text(result); nav.tabs('select', 1); loadTheme($('#theme').val()) }); return false; }); }); var loadedThemes = {} function loadTheme(theme){ if(!loadedThemes[theme]) { var url = "/stylesheets/themes/" + theme + ".css"; var fileref=document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", url); loadedThemes[theme] = true; if (typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref) } } function themeLink(theme) { var link = "/stylesheets/themes/" + theme + ".css" return "<p>Download the <a href=\"" + link + "\" title=\"Please don&apos;t hotlink this :)\">" + theme + "</a> theme.</p>" }
for (let s = "#"; s.length < 8; s += "#") { console.log(s); }
/** * This file is a part of nekland editor package * * (c) Nekland <nekland.fr@gmail.fr> * * For the full license, take a look to the LICENSE file * on the root directory of this project */ (function() { var formatModule = function(translator) { this.translator = translator; }; formatModule.prototype.getTemplateBefore = function() { var tpl = '<div class="btn-group">'; tpl += '<a class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="javascript:;">' + this.translator.translate('format', { ucfirst: true }) + ' <span class="caret"></span></a>'; tpl += '<ul class="dropdown-menu">'; tpl += '<li><a href="javascript:;" class="nekland-editor-command" data-editor-module="format" data-editor-command="p">' + this.translator.translate('formatNormal', { ucfirst: true }) + '</a></li>'; tpl += '<li><a href="javascript:;" class="nekland-editor-command nekland-editor-formath1" data-editor-module="format" data-editor-command="h1">' + this.translator.translate('formatH1', { ucfirst: true }) + '</a></li>'; tpl += '<li><a href="javascript:;" class="nekland-editor-command nekland-editor-formath2" data-editor-module="format" data-editor-command="h2">' + this.translator.translate('formatH2', { ucfirst: true }) + '</a></li>'; tpl += '<li><a href="javascript:;" class="nekland-editor-command nekland-editor-formath3" data-editor-module="format" data-editor-command="h3">' + this.translator.translate('formatH3', { ucfirst: true }) + '</a></li>'; tpl += '<li><a href="javascript:;" class="nekland-editor-command nekland-editor-formath4" data-editor-module="format" data-editor-command="h4">' + this.translator.translate('formatH4', { ucfirst: true }) + '</a></li>'; tpl += '<li><a href="javascript:;" class="nekland-editor-command nekland-editor-formath5" data-editor-module="format" data-editor-command="h5">' + this.translator.translate('formatH5', { ucfirst: true }) + '</a></li>'; tpl += '</ul></div>'; return tpl; }; formatModule.prototype.execute = function ($button) { var command = $button.data('editor-command'); document.execCommand('formatblock', false, command); return true; }; formatModule.prototype.getName = function() { return 'format'; }; window.nekland.Editor.modules.push(formatModule); })();
var Store = module.exports = function () { }; Store.prototype.hit = function (req, configuration, callback) { var self = this; var ip = req.ip; var path; if (configuration.pathLimiter) { path = (req.baseUrl) ? req.baseUrl.replace(req.path, '') : ''; ip += configuration.path || path; } var now = Date.now(); self.get(ip, function (err, limit) { if (err) { callback(err, undefined, now); return; }; if (limit) { //Existing user var limitDate = limit.date; var timeLimit = limitDate + configuration.innerTimeLimit; var resetInner = now > timeLimit; if (resetInner) { limit.date = now; } self.decreaseLimits(ip, limit, resetInner, configuration, function (error, result) { callback(error, result, limitDate); }); } else { //New User var outerReset = Math.floor((now + configuration.outerTimeLimit) / 1000); limit = { date: now, inner: configuration.innerLimit, outer: configuration.outerLimit, firstDate: now, outerReset: outerReset }; self.create(ip, limit, configuration, function (error, result) { callback(error, result, now); }); } }, configuration); }
let updateTask = function(input, state) { var path = ['tasks', input.ref]; state.merge(path, { id: input.id, isSaving: false }); }; export default updateTask;
/** A QuestionnaireItemMedia is the base class for QuestionnaireItems that present media, e.g., image, audio, or video. Playable media start playing automatically if loaded (canplaythrough=true) and `setEnabled(true)`. ATTENTION: answer is stored on calling releaseUI() and (if UI is created) getAnswer() only. @abstract @class QuestionnaireItemMedia @augments UIElement @augments UIElementInteractive @augments QuestionnaireItem */ class QuestionnaireItemMedia extends QuestionnaireItem { /** @param {string} [className] CSS class @param {string} [question] @param {boolean} [required=false] @param {string|array} url The URL of the media element to be loaded; if supported by the browser also data URI. A single resource can be provided as string or multiple resources of different formats as an array. @param {boolean} required Element must report ready before continue. @param {boolean} [readyOnError] Set `ready=true` if an error occures. */ constructor(className, question, required, url, readyOnError) { super(className, question, required); this.url = Array.isArray(url) ? url : [url]; this.isContentLoaded = false; this.stallingCount = 0; this.wasSuccessfullyPlayed = false; this.readyOnError = readyOnError; this.errorOccured = false; } load() { TheFragebogen.logger.info(this.constructor.name + ".load()", "Start loading for " + this.getURL() + "."); } isLoaded() { return this.isContentLoaded; } isReady() { if (!this.readyOnError && this.errorOccured) { return false; } return this.isRequired() ? this.wasSuccessfullyPlayed : true; } getURL() { return this.url; } setEnabled(enabled) { if (!this.isUIcreated()) { TheFragebogen.logger.warn(this.constructor.name + ".setEnabled()", "Cannot start playback on setEnabled without createUI()."); return; } this.enabled = enabled; if (enabled) { this._play(); } else { this._pause(); } } applyAnswerToUI() { //NOPE } releaseUI() { super.releaseUI(); this._updateAnswer(); } getAnswer() { if (this.isUIcreated()) { this._updateAnswer(); } return super.getAnswer(); } setAnswer(answer) { //NOTE: Omit calling super.setAnswer() as getAnswer() also triggers setAnswer() leading to recursion. this.answer = answer; } preload() { TheFragebogen.logger.debug(this.constructor.name + ".preload()", "Start preloading."); this.preloaded = false; this._loadMedia(); } _loadMedia() { TheFragebogen.logger.warn(this.constructor.name + "._loadMedia()", "This method must be overridden for correct preloading."); } //Media-related callbacks /** Start playback of playable media. */ _play() { TheFragebogen.logger.debug(this.constructor.name + "._play()", "This method must be overridden if playback is desired."); } /** Pause playback of playable media. */ _pause() { TheFragebogen.logger.debug(this.constructor.name + "._pause()", "This method must be overridden if playback is desired."); } _onLoading() { TheFragebogen.logger.info(this.constructor.name + "._onloading()", "This method might be overriden."); } _onLoaded() { TheFragebogen.logger.info(this.constructor.name + "._onloaded()", "Loading done for " + this.getURL() + "."); if (!this.isContentLoaded) { this.isContentLoaded = true; this._sendOnPreloadedCallback(); } //Autostart playback? if (this.isUIcreated()) { this.setEnabled(this.enabled); } } _onStalled(event) { this.stallingCount += 1; this._sendOnPreloadedCallback(); TheFragebogen.logger.warn(this.constructor.name + "._onstalled()", "Stalling occured (" + this.stallingCount + ") for " + this.getURL()); } _onError(event) { this.stallingCount += 1; this._sendOnPreloadedCallback(); TheFragebogen.logger.error(this.constructor.name + "._onerror()", "Stalling occured (" + this.stallingCount + ") for " + this.getURL()); } _onProgress(event) { TheFragebogen.logger.debug(this.constructor.name + "._onprogress()", "This method must be overridden if progress reporting is desired."); } _onEnded() { TheFragebogen.logger.info(this.constructor.name + "._onended", "Playback finished."); this.wasSuccessfullyPlayed = true; this._sendReadyStateChanged(); this.markRequired(); } /** Overwrite this method to add additional data to be reported. */ _updateAnswer() { this.setAnswer([this.url, this.time]); } }
import Message from '../' describe('Message', () => { let vm beforeEach(() => { vm = Message({ message: 'test', duration: 500, showClose: true, onClose() {}, iconClass: 'test', }) }) afterEach(() => { const el = document.querySelector('.message') if (el) { el.parentNode.removeChild(el) } if (vm) { vm.$destroy() } }) it('a string as a parameter', () => { vm = Message('test') expect(vm.$el.textContent).toBe('test') }) it('if message is closed automatically', done => { expect(document.querySelector('.message')).not.toBeNull() setTimeout(() => { expect(document.querySelector('.message')).toBeNull() done() }, 1000) }) it('closed message manually', done => { expect(document.querySelector('.message')).not.toBeNull() vm.$el.querySelector('.closeBtn').click() setTimeout(() => { expect(document.querySelector('.message')).toBeNull() done() }, 300) }) it('if callback function is triggered after message is closed', done => { const mockFn = jest.fn() vm.onClose = mockFn setTimeout(() => { expect(vm.onClose).toHaveBeenCalled() done() }, 3500) }) it('if clearTimeout is triggered after message is mouseentered', () => { expect(vm.timer).not.toBeNull() const event = new MouseEvent('mouseenter') document.querySelector('.message').dispatchEvent(event) expect(vm.timer).toBeNull() }) it('use custom icon if set iconClass to true', () => { expect(vm.$el.querySelector('.test')).not.toBeNull() }) })
/* * The MIT License * * Copyright 2014 s4if. * * 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. */ $.fn.datepicker.defaults.format = "yyyy/mm/dd";
version https://git-lfs.github.com/spec/v1 oid sha256:462df51fa9c562e77db86c3571a97eea28a908f301705c9b2343c44acb9fe7cb size 62087
(function() { // numeral.js locale configuration // locale : french (fr) // author : Adam Draper : https://github.com/adamwdraper return { delimiters: { thousands: String.fromCharCode(160), decimal: ',' }, abbreviations: { thousand: 'k', million: 'm', billion: 'b', trillion: 't' }, ordinal: function(number) { return number === 1 ? 'er' : 'e'; }, currency: { symbol: '€' } }; })();
// Copyright 2016 Las Venturas Playground. All rights reserved. // Use of this source code is governed by the MIT license, a copy of which can // be found in the LICENSE file. 'use strict'; const Step = require('../components/step'), child_process = require('child_process'), path = require('path'); // Step for verifying that the JavaScript portion of our gamemode continues to compile and be able // to execute all tests included in the source. class JavaScriptTestsStep extends Step { constructor(service) { super(service, 'javascript-compile', 'JavaScript tests'); } // Executes the step. Returns a promise that is to be resolved when the step is complete. run(log) { const serverDirectory = path.resolve('../server'), testRunnerDirectory = path.resolve('../playgroundjs-plugin/src/out'), testRunner = path.join(testRunnerDirectory, 'test_runner'); const command = `LD_LIBRARY_PATH=${testRunnerDirectory} ${testRunner}`; return new Promise((resolve, reject) => { log('$ ' + command + '\n'); const options = { cwd: serverDirectory, timeout: 30000 }; console.log('$ ' + command); child_process.exec(command, options, (error, stdout, stderr) => { log(stdout); console.log(stdout); log(stderr); console.log(stderr); if (error) log(error); console.log(error); if (error) this.setStatus(false, 'Found errors while testing the JavaScript code.'); else this.setStatus(true, 'Successfully tested the JavaScript code.'); resolve(); }); }); } }; module.exports = JavaScriptTestsStep;
/** * Blatantly a rip of the main html-gl demo's slider * https://raw.githubusercontent.com/PixelsCommander/HTML-GL/master/demo/js/slider.js */ /*global document, parseInt, undefined*/ import Ember from 'ember'; import Layout from './template'; const { Component } = Ember; const transformPropertyName = document.body.style.transform !== undefined ? 'transform' : 'WebkitTransform'; export default Component.extend({ layout: Layout, isDragging: false, startX: 0, startLeft: 0, defaultTitle: 'Quantum of solace', _start(event) { this.set('isDragging', true); this.set('startX', (event.pageX || event.x) || event.touches[0].pageX); this.set('startLeft', this._getSliderX()); }, _end(/*event*/) { this.set('isDragging', false); }, _move(event) { if (this.get('isDragging')) { let pageX = (event.pageX || event.x) || event.touches[0].pageX; this._setSliderX(pageX); } }, _setSliderX(x) { let startX = this.get('startX'); let startLeft = this.get('startLeft'); (this.element.styleGL || this.element.style)[transformPropertyName] = 'translateZ(0) translateX(' + (startLeft - (startX - (x || 0))) + 'px)'; }, _getSliderX() { return parseInt(parseCSSTransform((this.element.styleGL || this.element.style)[transformPropertyName]).translateX) || 0 }, mouseDown(e) { this._start(e); }, touchStart(e) { this._start(e); }, mouseUp(e) { this._end(e); }, touchEnd(e) { this._end(e); }, mouseMove(e) { this._move(e); }, touchMove(e) { this._move(e); }, didInsertElement() { //Slider logic, written in HTML / JS. //The only difference between HTML GL and basic HTML is that you should use element.styleGL.transform instead of element.style.transform this.$().find('img').each(function() { this.ondragstart = function () { return false; } }); this._super(); }, actions: { } }); function parseCSSTransform(transformString) { return (transformString.match(/([\w]+)\(([^\)]+)\)/g) || []) //make pairs of prop and value .map(function (it) { return it.replace(/\)$/, "").split(/\(/) }) //convert to key-value map/object .reduce(function (m, it) { return m[it[0]] = it[1], m }, {}); }
/** @module ember-ui-components */ import Component from '@ember/component'; import layout from '../templates/components/uic-modal-dialog'; import { computed } from '@ember/object'; import { inject as service } from '@ember/service'; import { typeOf } from '@ember/utils'; import $ from 'jquery'; /** @class ModalDialogComponent @namespace Components */ export default Component.extend({ layout, /** @property dialog @type {Object} @private */ dialog: service(), /** @property classNames @type {Array} @private @default `['uic-modal-dialog', 'no-outline']` */ classNames: ['uic-modal-dialog', 'no-outline'], /** @property classNameBindings @type {Array} @private @default `['dialogOpen:uic-modal-container', '_disablePointerEvents:uic-disable-pointer-events']` */ classNameBindings: ['dialog.open:uic-modal-container', '_disablePointerEvents:uic-disable-pointer-events'], /** @property attributeBindings @type {Array} @private @default `['tabindex']` */ attributeBindings: ['tabindex'], /** @property tabindex @type {Integer} @private @default `1` */ tabindex: 1, /** @property maskContent @type {Boolean} @default `true` */ maskContent: true, /** Computed property @property _maskContent @type {Boolean} @private */ _maskContent: computed('dialog.maskContent', 'maskContent', function () { let maskContent = this.get('dialog.maskContent'); if (typeOf(maskContent) === 'undefined') { maskContent = this.get('maskContent'); } return maskContent; }), /** ## clickOutsideModal Specify what should happen when the user clicks outside the modal dialog. Options * `Null` - do nothing * `Boolean` - `true` calls the `_confirm` method, `false` calls the `_cancel` method. * `String` - if a method is found on the component, then call it. * `Function` - calls the method Keywords & built-in methods * `confirm` calls the `_confirm` method * `cancel` calls the `_cancel` method * `shake` calls the `shake` method * `disable-pointer-events` applies the `uic-disable-pointer-events` class to the modal container @property clickOutsideModal @type {String|Function|Boolean|Null} @default false */ clickOutsideModal: false, /** Computed property. @property _clickOutsideModal @type {String|Function|Boolean} @private */ _clickOutsideModal: computed('dialog.clickOutsideModal', 'clickOutsideModal', function () { let clickOutsideModal = this.get('dialog.clickOutsideModal'); if (typeOf(clickOutsideModal) === 'undefined') { clickOutsideModal = this.get('clickOutsideModal'); } return clickOutsideModal; }), /** To disable pointer events set the `clickOutsideModal` property to the string `disable-pointer-events`. @property _disablePointerEvents @type {Boolean} @private */ _disablePointerEvents: computed('_clickOutsideModal', function () { let _clickOutsideModal = this.get('_clickOutsideModal'); return typeOf(_clickOutsideModal) === 'string' && _clickOutsideModal === 'disable-pointer-events'; }), /** @property disableScroll @type {Boolean} @default `false` */ disableScroll: false, /** @property _disableScroll @type {Boolean} @private */ _disableScroll: computed('dialog.disableScroll', 'disableScroll', '_disablePointerEvents', function () { let disableScroll = this.get('dialog.disableScroll'); if (typeOf(disableScroll) === 'undefined') { disableScroll = this.get('disableScroll'); } return disableScroll && !this.get('_disablePointerEvents'); }), /** @property displayModal @type {Boolean} @readonly @private */ displayModal: computed('dialog.{open,type}', '_disableScroll', function () { if (this.get('dialog.open') && typeOf(this.get('dialog.type')) === 'string') { $(this.get('element')).focus(); if (this.get('_disableScroll')) { $('body').addClass('modal-dialog-is-open'); } return true; } else { $('body').removeClass('modal-dialog-is-open'); return false; } }), /** @method _confirm @private */ _confirm() { this.get('dialog').resolve(); }, /** @method _cancel @private */ _cancel() { this.get('dialog').reject(); }, /** @method confirm */ confirm() { this._confirm(); }, /** @method cancel */ cancel() { this._cancel(); }, /** @method shake @param {Object} element */ shake(element) { let interval = 50; let distance = 10; let times = 4; if (!element) { element = this.$('.uic-modal'); } element.css('position', 'relative'); for(let i = 0, t = (times+1); i < t; i++) { element.animate({ left:((i%2===0 ? distance : distance *-1)) }, interval); } element.animate({ left: 0 }, interval); }, willDestroyElement() { this._super(...arguments); $('body').removeClass('modal-dialog-is-open'); }, /** @event keyDown @param {Object} event @private */ keyDown(event) { if (this.get('dialog.open')) { switch(event.keyCode) { case 13: // enter this._confirm(); break; case 27: // escape this._cancel(); break; } } }, /** @event click */ click(event) { if (event.target === this.get('element')) { let clickOutsideModal = this.get('_clickOutsideModal'); if (typeOf(clickOutsideModal) === 'boolean') { this[ clickOutsideModal ? '_confirm' : '_cancel' ](); } else if (typeOf(clickOutsideModal) === 'string' && typeOf(this[clickOutsideModal]) === 'function') { this[clickOutsideModal](); } else if (typeOf(clickOutsideModal) === 'function') { clickOutsideModal(); } } } });
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: HelloWorld }, ], linkExactActiveClass: 'active', mode: 'hash' })
// polyfill for IE require('es6-promise').polyfill(); require('whatwg-fetch'); import React from 'react'; import ReactDOM from 'react-dom'; import './normalize.css'; import './styles.css'; import './lib/nv.d3.css'; import './google-fonts.css'; import { Router, Route, IndexRoute, hashHistory } from 'react-router'; import GreetingController from './GreetingController'; import GreetingDisplay from './GreetingDisplay'; import Layout from './Layout'; const mountNode = document.getElementById('root'); const router = <Router history={hashHistory }> <Route path="/" component={Layout}> <IndexRoute component={GreetingController} /> <Route path="greet" component={GreetingDisplay} /> </Route> </Router>; ReactDOM.render(router, mountNode);
exports.viewProject = function(req, res) { //controller code goes here var name = req.params.name; console.log("The project name is: " + name); res.render('project', { 'projectName': name }); }
var test = require('tape'); var AmpersandIO = require('../ampersand-io'); var IOClient = require('socket.io-client'); console.log('Starting'); var MyClass = AmpersandIO.extend({ events: { test1: 'test-1', test2: 'test-2', test3: ['test-3-1', 'test-3-2'], } }); test('extend', function(t){ t.plan(3); var testObj = {test: 'test-extend'}; var testMethod = {test: function(){return 'test';}}; var testClass = AmpersandIO.extend({events: testObj, listeners: testObj}, testMethod); t.deepEqual(testMethod.test(), testClass.prototype.test()); t.deepEqual(testObj, testClass.prototype.events); t.deepEqual(testObj, testClass.prototype.listeners); }); test('constructor', function(t){ t.test('no arguments', function(subt){ subt.plan(4); var IO = new MyClass('http://localhost:3000'); subt.ok(IO.socket, 'socket object exists'); subt.equal(IO.events, MyClass.prototype.events); subt.deepEqual(IO.listeners, {}, 'listeners obj should not exist on prototype class #6'); subt.ok(typeof MyClass.prototype.listeners === 'undefined', 'listeners obj should not exist on prototype class #6'); }); t.test('socket', function(subt){ subt.plan(2); var socket = new IOClient('http://localhost:3000/otherChat'); var namespaceIO = new MyClass('http://localhost:3000/chat'); var socketIO = new MyClass(socket); subt.equal(namespaceIO.socket.nsp, '/chat'); subt.equal(socketIO.socket, socket); }); t.test('string and options', function (subt){ subt.plan(1); var options = { events:{ event: 'options-test' } }; var IO = new MyClass('http://localhost:3000', options); subt.equal(IO.events, options.events); }); t.test('socket and options', function (subt){ subt.plan(2); var socket = new IOClient('otherChat'); var options = { events: 'options-test' }; var socketIO = new MyClass(socket, options); subt.equal(socketIO.socket, socket); subt.equal(socketIO.events, options.events); }); }); test('emit', function(t){ var IO = new MyClass('http://localhost:3000'); t.plan(9); setTimeout(function waitForConnection(){ var testObj = { data: 'my-data', options: 'my-options' }; var cbTestObj = { data: 'my-other-data', options: { other: 'my-other-options' } }; cbTestObj.options.callback = function(request){ t.equal(request.data, cbTestObj.data, 'options callback'); t.equal(request.options.other, cbTestObj.options.other, 'options callback'); }; IO.emit('test1', testObj.data, testObj.options, function(request){ t.equal(request.data, testObj.data, 'simple event callback'); t.equal(request.options, testObj.options, 'simple event callback'); }); IO.emit('test3', testObj.data, testObj.options, function(request){ t.equal(request.data, testObj.data, 'multiple event callback'); t.equal(request.options, testObj.options, 'multiple event callback'); }); IO.emit('test1', cbTestObj.data, cbTestObj.options); IO.socket.on('response', function(){ t.pass('emit without data and callback'); }); IO.emit('test2'); setTimeout(function timeoutEnd(){ t.end(); },10000); },5000); }); test('listeners', function(t){ var IO = new MyClass('http://localhost:3000'); var IOExtend = new (MyClass.extend(IO, { events:{ test4: 'test-4' }, listeners: { test4:{ fn: function(){ t.pass('setListeners option'); t.deepEqual(this, IOExtend, 'correct \'this\' reference inside listener callback #4'); t.ok(this.otherMethod(), 'correct \'this\' reference inside extended ampersand io #4'); t.ok(this.otherProp, 'correct \'this\' reference inside extended ampersand io #4'); } } }, otherMethod: function(){ return 'test method #4'; }, otherProp: 'test prop #4' }))(null, {initListeners: true}); t.plan(24); IO.addListeners({ test1:{ fn: function(){ t.pass('listening to event property'); }, active: true }, test2:{ fn: function(){ t.fail('added listener without active flag'); } }, test3:{ fn: function(){ t.pass('listening to multiple events [array]'); }, active: true } }); t.ok(IO.listeners.test1.active, 'listener should be active'); t.notOk(IO.listeners.test2.active, 'listener should not be active'); t.ok(IO.listeners.test3.active, 'listener should be active'); IO.emit('request'); setTimeout(function() { IO.removeListeners(); t.notOk(IO.listeners.test1.active, 'listener should not be active'); t.notOk(IO.listeners.test2.active, 'listener should not be active'); t.notOk(IO.listeners.test3.active, 'listener should not be active'); t.equal((IO.socket._callbacks[IO.events.test1] || []).length, 0, 'listener should not be in the sockets callbacks'); t.equal((IO.socket._callbacks[IO.events.test2] || []).length, 0, 'listener should not be in the sockets callbacks'); t.equal((IO.socket._callbacks[IO.events.test3[0]] || []).length, 0, 'listener should not be in the sockets callbacks'); t.equal((IO.socket._callbacks[IO.events.test3[1]] || []).length, 0, 'listener should not be in the sockets callbacks'); IO.setListeners(); t.ok(IO.listeners.test1.active, 'listener should be active'); t.ok(IO.listeners.test2.active, 'listener should be active'); t.ok(IO.listeners.test3.active, 'listener should be active'); t.ok(IO.socket._callbacks[IO.events.test1], 'listener should be in the sockets callbacks'); t.ok(IO.socket._callbacks[IO.events.test2], 'listener should be in the sockets callbacks'); t.ok(IO.socket._callbacks[IO.events.test3[0]], 'listener should be in the sockets callbacks'); t.ok(IO.socket._callbacks[IO.events.test3[1]], 'listener should be in the sockets callbacks'); }, 5000); });
import gulp from 'gulp'; import mkdirp from 'mkdirp'; import config from '../config'; gulp.task('tmp', done => { mkdirp(config.tmpDir, done); }); gulp.task('copy:regulars', () => { const src = `${config.appDir}/{,*/}*.{ico,png,txt,xml,htaccess,appcache,mf}`; const pip = gulp.src(src) .pipe(gulp.dest(config.distDir)); return pip; }); gulp.task('copy:images', () => { const src = `${config.imagesDir}/{,*/}*.{gif,ico,jpg,jpeg,png,svg,webp}`; const dest = config.imagesDir.replace(config.appDir, config.distDir); const pip = gulp.src(src) .pipe(gulp.dest(dest)); return pip; }); gulp.task('copy:fonts', () => { const src = `${config.fontsDir}/{,*/}*.{eot,otf,svg,ttf,woff,woff2}`; const dest = config.fontsDir.replace(config.appDir, config.distDir); const pip = gulp.src(src) .pipe(gulp.dest(dest)); return pip; }); gulp.task('copy:custom', () => { const src = `${config.Dir}/**`; const dest = config.fontsDir.replace(config.appDir, config.distDir); const pip = gulp.src(src) .pipe(gulp.dest(dest)); return pip; }); const copyRouteTasks = config.routesCopy.map((k, i) => { const src = `${config.routes[k]}/**`; const dest = `${config.distDir}${k}`; const task = `route:copy:${i + 1}`; gulp.task(task, () => { const pip = gulp.src(src) .pipe(gulp.dest(dest)); return pip; }); return task; }); gulp.task('dist:copy:extra', [ 'copy:regulars', 'copy:images', 'copy:fonts', ...copyRouteTasks ]); gulp.task('dist:copy', ['dist:copy:extra'], () => gulp.start('dist:minify')); gulp.task('dist:copy:cdn', ['dist:copy:extra'], () => gulp.start('dist:minify:cdn'));
var kubeApp = angular.module('kubemonitor', ['ui.router', 'kubemonitor.routes']) .run(function($http) { // Sends this header with any AJAX request $http.defaults.headers.common['Access-Control-Allow-Origin'] = '*'; // Send this header only in post requests. Specifies you are sending a JSON object $http.defaults.headers.post['dataType'] = 'json'; });
(function(window, angular, undefined) { 'use strict'; angular.module('manageChallenge') .config(ManageChallengeConfig) .controller('AppController', AppController) function AppController($rootScope, $window, ConfigService) { $rootScope.$on("$routeChangeError", function (event, current, previous, rejection) { $window.location.href = ConfigService.getWwwUrl() + '/404'; }); } /** * @name ManageChallengeConfig * @desc * @param {!angular.$routeProvider} * @param {!angular.$locationProvider} * @returns * @ngInject */ function ManageChallengeConfig($routeProvider, $locationProvider) { $routeProvider //show a read-only version of the scorecard for a given submission .when("/challenges/:challengeId/scorecards/:scorecardId", { controller: "ReadonlyScorecardController", controllerAs: "vm", templateUrl: "/public/manage-challenge/scorecard/scorecard.html", resolve: { auth: function getAuth($cookies, $q, $route, $window, ConfigService, Utils) { var deferred = $q.defer(); var token = $window.sessionStorage.token || $cookies.tcjwt; if (token) { Utils.apiGet('/_auth_/checkAuth/challenges/' + $route.current.params.challengeId + '/scorecards/' + $route.current.params.scorecardId) .then(function(check) { deferred.resolve(token); }, function(err) { deferred.reject(err) }) } else { ConfigService.activate().then(function() { deferred.reject('No auth token') }); } return deferred.promise; }, resolvedScorecard: function getScorecard($route, ChallengeService) { //allow get scorecard if owner return ChallengeService.getScorecard($route.current.params.challengeId, $route.current.params.scorecardId); }, resolvedCurrentChallenge: function getChallenge($route, ChallengeService) { //allow get challenge return ChallengeService.getChallenge($route.current.params.challengeId); } } }); } })(window, window.angular);
/** * Created by ralphy on 18/02/17. */ /** * Created by ralphy on 24/01/17. * will cast a random spell * @class MANSION.SPELLS.Random */ O2.createClass('MANSION.SPELLS.Random', { run: function(g, aTypes) { // available spells for the random spell var SPELLS = { curse: [ 'Weakness', 'Darkness', 'Slow' ], buff: [ 'Light', 'Haste', 'Protect', 'Power', 'Heal', ], blessing: [ 'PermaResist', 'PermaPower', 'PermaVitality', ] }; function uniq(a) { var x = {}; a.forEach(function(s) { x[s] = true; }); return Object.keys(x); } function choose(sType) { if (typeof sType === 'string') { return MathTools.rndChoose(SPELLS[sType]); } else if (Array.isArray(sType)) { return uniq(sType.map(choose)); } } choose(aTypes).forEach(g.castSpell, g); } });
// Object.assign fill-in export const assign = (obj, ...props) => props.reduce((acc, prop) => { for (let i in prop) acc[i] = prop[i] return acc }, obj) // compose functions left-to-right export const compose = (...fns) => (initialValue) => fns.reduce((val, fn) => fn(val), initialValue)
import PipesAndFiltersUtils from "../utils/pipesAndFiltersUtils.js" export default class ActivePipe{ constructor(inputObject, activePipe, outputObject) { this.inputObject = inputObject; this.activePipe = activePipe; this.outputObject = outputObject; this.timeout = 100; this.whileCondition = true; this.utils = new PipesAndFiltersUtils(); } sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async pipeActive(filterCallback, drawCallback) { this.whileCondition = true; while (this.whileCondition && this.utils.isInView(this.activePipe.view)) { // show activ search this.activePipe.view.style.border = "2px solid green"; await this.sleep(300); // set to normal border this.activePipe.view.style.border = "1px solid black"; // get input buffer from input var bufferInput = this.inputObject.buffer; if (bufferInput === undefined) { bufferInput = this.inputObject.filterObject.bufferOutput; } // get new object from input var input = bufferInput.shift(); if (input !== undefined) { this.activePipe.buffer.push(input); drawCallback(); } // get output buffer input from var bufferOutputInput = this.outputObject.buffer; if (bufferOutputInput === undefined) { bufferOutputInput = this.outputObject.filterObject.bufferInput; } // get output buffer output from var bufferOutput = this.outputObject.buffer; if (bufferOutput === undefined) { bufferOutput = this.outputObject.filterObject.bufferOutput; } // push next pipe object to OutputObject var object = this.activePipe.buffer.shift(); if (object !== undefined) { bufferOutputInput.push(object) drawCallback(); var objectNew = await filterCallback(object); bufferOutputInput.shift() if (objectNew !== undefined) { bufferOutput.push(objectNew); } } drawCallback(); await this.sleep(this.timeout); } this.activePipe.view.style.borderColor = "black" } stop() { this.whileCondition = false; } start() { this.whileCondition = true; } }
import React, { Component } from 'react'; import { Link } from 'react-router-dom'; import logo from './logo.svg'; import './App.css'; import Table from './Table' import Footer from './Footer' import SocialBadge from './SocialBadge' class App extends Component { render() { return ( <div className="App"> <div className="App-header"> <div className="container"> <img src={logo} className="App-logo" alt="logo" /> <img src="http://mediafiles.cineplex.com/Promos/moneycash/Minions.png" /> <Link to="/donate" className="btn btn--donate">Donate</Link> </div> </div> <div className="container"> <Table /> </div> <Footer /> </div> ); } } export default App;
export { default } from "./MultiLogin";
'use strict' const options = require('./options') const fs = require('fs') const extend = require('extend') const colors = require('colors/safe') module.exports = function (program, server) { const start = program .command('start') .description('run the Solid server') options .filter((option) => !option.hide) .forEach((option) => { var name = '--' + option.name if (!option.flag) { name += ' [value]' } start.option(name, option.help) }) start.option('-v, --verbose', 'Print the logs to console') start.action((opts) => { let argv = extend({}, opts, { version: program.version() }) fs.readFile(process.cwd() + '/config.json', (err, file) => { // No file exists, not a problem if (err) { console.log(colors.cyan.bold('TIP'), 'create a config.json: `$ solid init`') } else { // Use flags with priority over config file const config = JSON.parse(file) Object.keys(config).forEach((option) => { argv[option] = argv[option] || config[option] }) } bin(argv, server) }) }) } function bin (argv, server) { if (!argv.email) { argv.email = { host: argv['emailHost'], port: argv['emailPort'], secure: true, auth: { user: argv['emailAuthUser'], pass: argv['emailAuthPass'] } } delete argv['emailHost'] delete argv['emailPort'] delete argv['emailAuthUser'] delete argv['emailAuthPass'] } // Set up --no-* argv.live = !argv.noLive // Set up debug environment if (argv.verbose) { process.env.DEBUG = 'solid:*' } // Set up port argv.port = argv.port || 3456 // Webid to be default in command line if (argv.webid !== false) { argv.webid = true } // Signal handling (e.g. CTRL+C) if (process.platform !== 'win32') { // Signal handlers don't work on Windows. process.on('SIGINT', function () { console.log('\nSolid stopped.') process.exit() }) } // Overwrite root .acl if owner is specified if (argv.owner) { let rootPath = argv.root if (!rootPath) { rootPath = process.cwd() } if (!(rootPath.endsWith('/'))) { rootPath += '/' } rootPath += (argv.suffixAcl || '.acl') const defaultAcl = `@prefix n0: <http://www.w3.org/ns/auth/acl#>. @prefix n2: <http://xmlns.com/foaf/0.1/>. <#owner> a n0:Authorization; n0:accessTo <./>; n0:agent <${argv.owner}>; n0:defaultForNew <./>; n0:mode n0:Control, n0:Read, n0:Write. <#everyone> a n0:Authorization; n0: n2:Agent; n0:accessTo <./>; n0:defaultForNew <./>; n0:mode n0:Read.` fs.writeFileSync(rootPath, defaultAcl) } // // Finally starting solid const solid = require('../../') let app try { app = solid.createServer(argv, server) } catch (e) { if (e.code === 'EACCES') { console.log(colors.red.bold('ERROR'), 'You need root privileges to start on this port') return 1 } if (e.code === 'EADDRINUSE') { console.log(colors.red.bold('ERROR'), 'The port ' + argv.port + ' is already in use') return 1 } console.log(colors.red.bold('ERROR'), e.message) return 1 } app.listen(argv.port, function () { console.log(`Solid server (${argv.version}) running on \u001b[4mhttps://localhost:${argv.port}/\u001b[0m`) console.log('Press <ctrl>+c to stop') }) }
/** * Webpack hot configuration */ var path = require("path"); var base = require("./webpack.config.dev"); var webpack = require("webpack"); var CleanPlugin = require("clean-webpack-plugin"); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var autoprefixer = require("autoprefixer-stylus"); module.exports = { cache: true, context: base.context, entry: [ "webpack-dev-server/client?http://127.0.0.1:3000", "webpack/hot/only-dev-server", base.entry ], output: base.output, module: { // Copy this because of `react-hot` injection. loaders: [ { test: /\.js(x|)?$/, include: path.join(process.cwd(), "client"), loaders: ["react-hot", "babel-loader"] }, { test: /\.styl$/, loader: ExtractTextPlugin.extract( "style-loader", "css-loader!stylus-loader") }, { test: /\.woff(2)?$/, loader: "url-loader?limit=10000&minetype=application/font-woff" }, { test: /\.(ttf|eot|svg|png)$/, loader: "file-loader" } ] }, stylus: base.stylus, resolve: base.resolve, resolveLoader: base.resolveLoader, devtool: "eval-source-map", plugins: base.plugins };
import parseMilliseconds from 'parse-ms' function padLeft (value, number, char) { let text = String(value) if (text.length < number) { let size = number - text.length while (size--) text = char + text } return text } export function formatTime (milliseconds) { const { minutes, seconds } = parseMilliseconds(milliseconds) return [minutes, seconds].map((value) => padLeft(value, 2, '0')).join(':') }
import { combineReducers } from 'redux'; import * as core from './core'; import * as body from './body'; import side from './side'; import * as cropper from './cropper'; export default combineReducers({ // settings setting: core.setting, // api api: core.api, // keyboard event keyboard: core.keyboard, // element element: core.element, // data tree tree: combineReducers({ side, body: combineReducers({ setting: body.setting, grid: body.grid, activeBlock: body.activeBlock }), cropper: combineReducers({ visible: cropper.visible, item: cropper.item, key: cropper.key }) }) });
define(function (require) { var registerSuite = require('intern!object'); var expect = require('intern/chai!expect'); var url = 'http://test.com/foo.html?foo=bar'; registerSuite({ name: 'index', 'It should parse domain': function () { return this.remote .get(require.toUrl('app/main.html')) .setFindTimeout(5000) .findByCssSelector('.container textarea') .click() .type(url) .end() .findByCssSelector('.debug-btn') .click() .end() .findByCssSelector('.domain span') .getVisibleText() .then(function (text) { expect(text).to.equal('http://test.com'); }); }, 'It should parse pages': function () { return this.remote .get(require.toUrl('app/main.html')) .setFindTimeout(5000) .findByCssSelector('.container textarea') .click() .type(url) .end() .findByCssSelector('.debug-btn') .click() .end() .findByCssSelector('.pages span') .getVisibleText() .then(function (text) { expect(text).to.equal('/foo.html'); }); }, 'It should parse query params': function () { return this.remote .get(require.toUrl('app/main.html')) .setFindTimeout(5000) .findByCssSelector('.container textarea') .click() .type(url) .end() .findByCssSelector('.debug-btn') .click() .end() .findByCssSelector('.query span') .getVisibleText() .then(function (text) { expect(text).to.equal('foo = bar'); }); } }); });
var BEM = require('bem'), Q = BEM.require('q'), VM = require('vm'); exports.techMixin = { getBemhtml: function(prefix) { var path = this.getPath(prefix, 'bemhtml.js'); return BEM.util.readFile(path) .then(function(c) { /** @name BEMHTML variable appears after runInThisContext() call */ VM.runInThisContext(c, path); return BEMHTML; }); }, getBemjson: function(prefix) { var path = this.getPath(prefix, 'bemjson.js'); return BEM.util.readFile(path) .then(function(c) { return VM.runInThisContext(c, path); }); }, getHtml: function(bemhtml, bemjson) { return Q.all([bemhtml, bemjson]) .spread(function(bemhtml, bemjson) { return bemhtml.apply(bemjson); }); }, getCreateResult: function(path, suffix, vars) { return this.getHtml( this.getBemhtml(vars.Prefix), this.getBemjson(vars.Prefix)); }, storeCreateResult: function(path, suffix, res, force) { // always overwrite html files return this.__base(path, suffix, res, true); }, getDependencies: function() { return ['bemjson.js', 'bemhtml.js']; } };
//~ name b252 alert(b252); //~ component b253.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports["default"] = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _inheritsLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/inheritsLoose")); var _react = require("react"); var _chart = require("chart.js"); var _configChart = _interopRequireDefault(require("./configChart")); var _merge = _interopRequireDefault(require("../../utils/merge")); var _deepEqual = _interopRequireDefault(require("../../utils/deepEqual")); var _omit = _interopRequireDefault(require("../../utils/omit")); var _jsxRuntime = require("react/jsx-runtime"); var IGNORED_PROPERTIES = ['id', 'width', 'height', 'onElementsClick']; _chart.Chart.register(_chart.LineElement, _chart.LineController, _chart.CategoryScale, _chart.LinearScale, _chart.PointElement, _chart.Legend, _chart.Tooltip); var _isFn = function _isFn(fn) { return typeof fn === 'function'; }, _configMerge = _merge["default"]; (0, _configChart["default"])(_chart.Chart); var DF_OPTIONS = { tooltips: { callbacks: { labelTextColor: function labelTextColor(tooltipItem, chartInst) { return chartInst.data.datasets[tooltipItem.datasetIndex].borderColor; } } } }; var ChartComponent = /*#__PURE__*/function (_Component) { (0, _inheritsLoose2["default"])(ChartComponent, _Component); function ChartComponent() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _Component.call.apply(_Component, [this].concat(args)) || this; _this._updateChart = function () { var _this$props = _this.props, data = _this$props.data, options = _this$props.options; if (!_this.chart_instance) return; if (options) { _this.chart_instance.options = _configMerge(_this.chart_instance.options, options); } _this.chart_instance.config.data = (0, _extends2["default"])({}, _this.chart_instance.config.data, data); _this.chart_instance.update(); }; _this._renderChart = function () { var _this$props2 = _this.props, data = _this$props2.data, options = _this$props2.options, type = _this$props2.type, _options = _configMerge(DF_OPTIONS, options); _this.chart_instance = new _chart.Chart(_this.rootNode, { type: type, data: data, options: _options }); }; _this._hClick = function (evt) { var elems = _this.chart_instance.getElementsAtEvent(evt); if (elems.length) { _this.props.onElementsClick(elems); } }; _this._refRoot = function (n) { return _this.rootNode = n; }; return _this; } var _proto = ChartComponent.prototype; _proto.componentDidMount = function componentDidMount() { this._renderChart(); }; _proto.componentDidUpdate = function componentDidUpdate() { if (this.props.redraw) { this.chart_instance.destroy(); this._renderChart(); } else { this._updateChart(); } }; _proto.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { var compareNext = (0, _omit["default"])(nextProps, IGNORED_PROPERTIES), compareNow = (0, _omit["default"])(this.props, IGNORED_PROPERTIES); return !(0, _deepEqual["default"])(compareNext, compareNow, { strict: true }); }; _proto.componentWillUnmount = function componentWillUnmount() { this.chart_instance.destroy(); }; _proto.render = function render() { var _this$props3 = this.props, height = _this$props3.height, width = _this$props3.width, onElementsClick = _this$props3.onElementsClick, _onClick = _isFn(onElementsClick) ? this._hClick : null; return /*#__PURE__*/(0, _jsxRuntime.jsx)("canvas", { ref: this._refRoot, height: height, width: width, onClick: _onClick }); }; return ChartComponent; }(_react.Component); ChartComponent.defaultProps = { type: 'line', height: 150, width: 300, redraw: false }; var _default = ChartComponent; exports["default"] = _default; //# sourceMappingURL=ChartComponent.js.map
'use strict'; var angular = require('angular'); // angular modules require('angular-ui-router'); require('./controllers/_index'); require('./services/_index'); require('./directives/_index'); // create and bootstrap application angular.element(document).ready(function() { var requires = [ 'ui.router', 'app.controllers', 'app.services', 'app.directives' ]; // mount on window for testing window.app = angular.module('app', requires); angular.module('app').constant('AppSettings', require('./constants')); angular.module('app').constant('addTEmpData', require('./constants2')); angular.module('app').constant('helloData', require('./constants3')); angular.module('app').constant('demoSettings', require('./constants4')); angular.module('app').config(require('./routes')); angular.module('app').run(require('./on_run')); angular.bootstrap(document, ['app']); });
// @flow import { Model } from 'alaska'; export default class AdminMenu extends Model<AdminMenu> { static label = 'Admin Menu'; static icon = 'bars'; static titleField = 'label'; static defaultColumns = 'icon label type parent sort service link ability super activated'; static defaultSort = '-sort'; static searchFields = '_id label link parent'; static defaultFilters = (ctx: Alaska$Context) => (ctx.state.superMode ? {} : { super: { $ne: true } }); static fields = { _id: { type: String }, label: { label: 'Title', type: String, required: true }, icon: { label: 'Icon', type: 'icon', default: '' }, type: { label: 'Type', type: 'select', default: 'link', switch: true, options: [{ label: '链接', value: 'link' }, { label: '组', value: 'group' }] }, ability: { label: 'Ability', ref: 'alaska-user.Ability' }, link: { label: 'Link', type: String, default: '', depends: { type: 'link' }, fullWidth: true }, parent: { label: 'Parent Menu', type: 'category', ref: 'AdminMenu', filters: { type: 'group' } }, service: { label: 'Service', type: String }, sort: { label: 'Sort', type: Number, default: 0 }, super: { label: 'Super', type: Boolean, super: true, noexport: true }, activated: { label: 'Activated', type: Boolean } }; label: string; icon: string; type: string; parent: Object; service: string; sort: number; super: boolean; activated: boolean; async preSave() { if (this.parent && this.parent === this._id) { throw new Error('Parent can not be self'); } } }
'use strict'; module.exports = function (vm) { return { submit: function submit(e) { if (e) e.preventDefault(); setTimeout(function () { var data = vm.formData(); if (vm.opts.resetFormAfterSubmit) { vm.reinitForm(); } vm.dispatch('sent', data); vm.getStatusBar().success(vm.opts.texts.sent); }, 50); return true; } }; };
/**! * optimized - test/optimized_strict_mode.test.js * * Copyright(c) 2014 fengmk2 and other contributors. * MIT Licensed * * Authors: * fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com) */ "use strict"; /** * Module dependencies. */ var should = require('should'); var optimized = require('../'); /** * reassign */ function defaultArgsReassign(a, b) { if (arguments.length < 2) { b = 5; } return b; } function reAssignParam1(a, b) { if (b === void 0) { b = 5; } return b; } function reAssignParam2(a, b) { if (b == null) { b = 5; } return b; } defaultArgsReassign().should.eql(reAssignParam1()); defaultArgsReassign().should.eql(reAssignParam2()); optimized(defaultArgsReassign).should.equal(true); optimized(reAssignParam1).should.equal(true); optimized(reAssignParam2).should.equal(true); /** * try catch */ var jsonstr = '{"foo": "bar"}'; function jsonparseWithoutTryCatch() { return JSON.parse(jsonstr); } function jsonparseWithTryCatch() { try { return JSON.parse(jsonstr); } catch (err) { return null; } } function tryCatch(fn, ctx, args) { try { return fn.apply(ctx, args); } catch (e) { return e; } } function jsonparseOutsideTryCatch() { var r = tryCatch(JSON.parse, JSON, [jsonstr]); if (r instanceof Error) { return null; } return r; } jsonparseOutsideTryCatch().should.eql(jsonparseWithTryCatch()); jsonparseOutsideTryCatch().should.eql(jsonparseWithoutTryCatch()); optimized(jsonparseWithoutTryCatch).should.equal(true); optimized(jsonparseWithTryCatch).should.equal(false); optimized(jsonparseOutsideTryCatch).should.equal(true); /** * Leaking arguments */ function leaksArguments1() { return arguments; } function leaksArguments3() { var a = arguments; return function() { return a; }; } function argumentsOutOfBound() { return arguments[2]; } function argumentsAvoidOutOfBound() { return arguments.length >= 3 ? arguments[2] : void 0; } function argumentsArraySlice() { var args = Array.prototype.slice.call(arguments); } function argumentsArrayApply() { var args = Array.prototype.slice.apply(arguments); } function doesntLeakArguments() { // .length is just an integer, this doesn't leak // the arguments object itself var args = []; for (var i = 0; i < arguments.length; i++) { // i is always valid index in the arguments object args[i] = arguments[i]; } return args; } function functionApplyArugments() { var r = argumentsAvoidOutOfBound.apply(undefined, arguments); } optimized(leaksArguments1).should.equal(false); optimized(leaksArguments3).should.equal(false); optimized(doesntLeakArguments).should.equal(true); optimized(argumentsOutOfBound).should.equal(false); optimized(argumentsAvoidOutOfBound).should.equal(true); optimized(argumentsArraySlice).should.equal(false); optimized(argumentsArrayApply).should.equal(false); optimized(functionApplyArugments).should.equal(false); /** * for in */ function nonLocalKey1() { var obj = {}; for (var key in obj) {} return function() { return key; }; } var key; function nonLocalKey2() { var obj = {}; for (key in obj) {} } function localKey1() { var obj = {}; for (var key in obj) {} } function localKey2() { var obj = {}; var key; for (key in obj) {} } optimized(nonLocalKey1).should.equal(false); optimized(nonLocalKey2).should.equal(false); optimized(localKey1).should.equal(true); optimized(localKey2).should.equal(true); /** * The object being iterated is not a "simple enumerable" */ function hashTableIteration() { var hashTable = {"-": 3}; // console.log(%HasFastProperties(hashTable)); // console.log(%HasFastProperties({'1-1': 123})); for (var key in hashTable) {} } function fastTableIteration() { var fastTable = {"_": 3, 'foo_bar': 4}; // console.log(%HasFastProperties(hashTable)); // console.log(%HasFastProperties({'1-1': 123})); for (var key in fastTable) {} } function iteratesOverArray() { var arr = [1, 2, 3]; for (var index in arr) {} } function iteratesInArray() { var arr = [1, 2, 3]; for (var i = 0; i < arr.length; i++) {} } optimized(hashTableIteration).should.equal(false); optimized(fastTableIteration).should.equal(true); optimized(iteratesOverArray).should.equal(false); optimized(iteratesInArray).should.equal(true); function testArguments(key, value) { var hashTable = {}; hashTable[key] = value; for (var k in hashTable) {} } optimized(testArguments, ['key', 'value']).should.equal(true); optimized(testArguments, ['key-key', 'value']).should.equal(false); // http://jsperf.com/the-arguments-object-s-effect-on-speed/5 function withoutArguments(a){ a; return true; } function withArguments(){ arguments; return true; } function deadArguments(a){ return true; arguments; } function withBothNamedParamenterAndArguments(a) { arguments; return true; } optimized(withoutArguments, [4]).should.equal(true); optimized(withArguments, [4]).should.equal(true); optimized(deadArguments, [4]).should.equal(true); optimized(withBothNamedParamenterAndArguments, ['args']).should.equal(true);
'use strict'; angular.module('app').controller('mvNavBarLoginCtrl', function($scope, $http, mvIdentity, mvNotifier, mvAuth, $location) { $scope.signInFormToggle = false; $scope.identity = mvIdentity; $scope.signin = function(username, password) { if (!$scope.signInFormToggle) { $scope.toggleSignInForm(); return; } mvAuth.authenticateUser(username, password).then(function(success) { if (success) { mvNotifier.success('You have successfully logged in!'); } else { mvNotifier.error('Username/Password combination is invalid!'); } }); }; $scope.signout = function() { $scope.toggleSignInForm(); mvAuth.logoutUser().then(function() { $scope.username = ""; $scope.password = ""; mvNotifier.success("You have successfully logged out."); $location.path('/'); }); }; $scope.toggleSignInForm = function() { $scope.signInFormToggle = !$scope.signInFormToggle }; });
module.exports = `Hello World`;
// Sonos Queue Song const { Sonos, Helpers } = require("sonos"); var Promise = require("promise"); module.exports = function(RED) { "use strict"; function Node(n) { RED.nodes.createNode(this, n); var playnode = RED.nodes.getNode(n.playnode); this.client = new Sonos(playnode.ipaddress); this.songuri = n.songuri; this.position = n.position; if (this.position === "empty") { this.position = ""; } this.positioninqueue = n.positioninqueue; var node = this; this.on("input", function(msg) { var payload = typeof msg.payload === "object" ? msg.payload : {}; var _songuri = node.songuri; if (payload.songuri) { _songuri = payload.songuri; } if (node.position === "next" || payload.position === "next") { node.log("Queueing URI next: " + _songuri); node.client .queue(Helpers.GenerateLocalMetadata(_songuri, ''),0) .then(result => { //node.client.queueNext(_songuri, function (err, result) { msg.payload = result; node.send(msg); //if (err) { // node.log(JSON.stringify(err)); //} node.log(JSON.stringify(result)); }) .catch(err => { node.log(JSON.stringify(err)); }); } else if ( node.position === "directplay" || payload.position === "directplay" ) { node.log("Direct play URI: " + _songuri); //.play(_songuri) node.client .setAVTransportURI(_songuri) .then(result => { //node.client.play(_songuri, function (err, result) { msg.payload = result; node.send(msg); //if (err) { // node.log(JSON.stringify(err)); //} node.log(JSON.stringify(result)); }) .catch(err => { node.log(JSON.stringify(err)); }); } else if ( node.position === "tuneinradio" || payload.position === "tuneinradio" ) { node.log("Play TuneIn Radio: " + _songuri); node.client .playTuneinRadio(_songuri) .then(result => { //node.client.playTuneinRadio(_songuri, function (err, result) { msg.payload = result; node.send(msg); //if (err) { // node.log(JSON.stringify(err)); //} node.log(JSON.stringify(result)); }) .catch(err => { node.log(JSON.stringify(err)); }); } else { // Default is queueing to the end of a queue var set_position = 0; // Evaluate different inputs (json payload preferred, node option second, default third) if (payload.position) { set_position = payload.position; } else if (node.positioninqueue) { if (isNaN(node.positioninqueue) == false) { set_position = parseInt(node.positioninqueue, 10); } } // Queue song now node.log("Queuing at " + set_position + " URI: " + _songuri); node.client .queue(Helpers.GenerateLocalMetadata(_songuri, ''), set_position) .then(result => { //node.client.queue(_songuri, set_position, function (err, result) { msg.payload = result; node.send(msg); //if (err) { // node.log(JSON.stringify(err)); //} node.log(JSON.stringify(result)); }) .catch(err => { node.log(JSON.stringify(err)); }); } }); } RED.nodes.registerType("sonos-queue", Node); };
import React, { Component } from 'react'; import Snackbar from 'material-ui/Snackbar'; class QuickNotice extends Component { constructor() { super() this.state = { open: false, message: '', autoHideDuration: 0 } } componentWillReceiveProps(nextProps) { if (nextProps.message && nextProps.message !== this.state.message) this.setState({ open: true, message: nextProps.message }) } handleRequestClose() { this.setState({ open: false, message: '' }); }; render() { return ( <Snackbar open={this.state.open} message={this.state.message} autoHideDuration={this.state.autoHideDuration} onRequestClose={this.handleRequestClose.bind(this)} /> ); } } export default QuickNotice;
$(function(){ /*! * JavaScript for Bootstrap's docs (http://getbootstrap.com) * Copyright 2011-2014 Twitter, Inc. * Licensed under the Creative Commons Attribution 3.0 Unported License. For * details, see http://creativecommons.org/licenses/by/3.0/. */ !function(a){a(function(){if(navigator.userAgent.match(/IEMobile\/10\.0/)){var b=document.createElement("style");b.appendChild(document.createTextNode("@-ms-viewport{width:auto!important}")),document.querySelector("head").appendChild(b)}{var c=a(window),d=a(document.body);a(".navbar").outerHeight(!0)+10}d.scrollspy({target:".bs-docs-sidebar"}),c.on("load",function(){d.scrollspy("refresh")}),a(".bs-docs-container [href=#]").click(function(a){a.preventDefault()}),setTimeout(function(){var b=a(".bs-docs-sidebar");b.affix({offset:{top:function(){var c=b.offset().top,d=parseInt(b.children(0).css("margin-top"),10),e=a(".bs-docs-nav").height();return this.top=c-e-d},bottom:function(){return this.bottom=a(".bs-docs-footer").outerHeight(!0)}}})},100),setTimeout(function(){a(".bs-top").affix()},100)})}(jQuery); }); $(function() { // build side menu var html = ''; $('.bs-docs-section').each(function() { var h1 = $(this).find('h1[id]').first(), h23 = $(this).find('h2[id], h3[id]:not([data-no-menu])'); if (h1.length) { html += '<li><a href="#' + h1[0].id + '">' + h1.clone().children().remove().end().text() + '</a>'; if (h23.length) { html += '<ul class="nav">'; h23.each(function() { html += '<li><a href="#' + this.id + '">' + $(this).clone().children().remove().end().text() + '</a></li>'; }); html += '</ul>'; } html += '</li>'; } }); if (html == '') { $('[role=complementary]').hide(); $('[role=main]').toggleClass('col-md-9 col-md-12'); } else { $('.bs-docs-sidenav').html(html); } // add heading anchors $('h1[id], h2[id], h3[id], h4[id], h5[id]').each(function() { $(this).prepend('<a href="#' + this.id + '" class="anchor-link">§</i>'); }); // enable bootbox $('[data-bootbox]').on('click', function() { var $target = $('#' + $(this).data('bootbox')); bootbox.alert({ title: $target.attr('title'), message: $target.html(), size: $(this).data('bootbox-size') }); }); }); function trianglify(color1, color2, seed) { var header = $('#content'); var pattern = Trianglify({ width: window.screen.width | header.outerWidth(), height: header.outerHeight(), cell_size: 90, seed: seed, x_colors: [color1, color2] }); header.css('background-image', 'url(' + pattern.png() + ')'); }
/* jshint node: true */ module.exports = function (environment) { var ENV = { modulePrefix: 'ggf', podModulePrefix: 'ggf/pods', environment: environment, baseURL: '/', locationType: 'hash', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created namespace: 'api/v1', host: '//' + process.env.APP_HOSTNAME }, contentSecurityPolicy: { 'connect-src': "'self' bam.nr-data.net " + process.env.APP_HOSTNAME, 'img-src': "'self' bam.nr-data.net " + process.env.APP_HOSTNAME, 'script-src': "'self' 'unsafe-inline' js-agent.newrelic.com bam.nr-data.net " + process.env.APP_HOSTNAME, 'style-src': "'self' 'unsafe-inline' fonts.googleapis.com", 'font-src': "'self' data: fonts.gstatic.com" }, /* torii */ torii: { // a 'session' property will be injected on routes and controllers sessionServiceName: 'session', providers: { 'facebook-oauth2': { apiKey: process.env.FACEBOOK_APP_ID, redirectUri: process.env.FACEBOOK_REDIRECT_URI } } }, flashMessageDefaults: { timeout: 5000, extendedTimeout: 0, priority: 200, showProgress: true, } }; if (environment === 'production') { ENV.APP.fingerprintEnabled = true; } if (environment === 'development' || environment === 'local') { ENV.APP.host = 'http://' + process.env.APP_HOSTNAME; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } ENV['simple-auth'] = { crossOriginWhitelist: [ENV.APP.host], authorizer: 'simple-auth-authorizer:oauth2-bearer', }; ENV['simple-auth-oauth2'] = { serverTokenEndpoint: ENV.APP.host + '/auth/facebook/token', serverTokenRevocationEndpoint: ENV.APP.host + '/auth/logout' } return ENV; };
/** * Main index file for jsmoney-server-api */ "use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); __export(require("./api-objects")); __export(require("./utils/utils")); __export(require("./validation/validation"));
import { on } from './event'; import { assign, noop } from './lang'; export function ajax(url, options) { const env = { data: null, method: 'GET', headers: {}, xhr: new XMLHttpRequest(), beforeSend: noop, responseType: '', ...options, }; return Promise.resolve() .then(() => env.beforeSend(env)) .then(() => send(url, env)); } function send(url, env) { return new Promise((resolve, reject) => { const { xhr } = env; for (const prop in env) { if (prop in xhr) { try { xhr[prop] = env[prop]; } catch (e) { // noop } } } xhr.open(env.method.toUpperCase(), url); for (const header in env.headers) { xhr.setRequestHeader(header, env.headers[header]); } on(xhr, 'load', () => { if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) { resolve(xhr); } else { reject( assign(Error(xhr.statusText), { xhr, status: xhr.status, }) ); } }); on(xhr, 'error', () => reject(assign(Error('Network Error'), { xhr }))); on(xhr, 'timeout', () => reject(assign(Error('Network Timeout'), { xhr }))); xhr.send(env.data); }); } export function getImage(src, srcset, sizes) { return new Promise((resolve, reject) => { const img = new Image(); img.onerror = (e) => { reject(e); }; img.onload = () => { resolve(img); }; sizes && (img.sizes = sizes); srcset && (img.srcset = srcset); img.src = src; }); }
import { ReactiveVar } from 'meteor/reactive-var'; import { hasPermission } from '../../app/authorization/client'; export const sidebarItems = new ReactiveVar([]); export const registerAdminSidebarItem = (itemOptions) => { sidebarItems.set([...sidebarItems.get(), itemOptions]); }; registerAdminSidebarItem({ href: 'admin-info', i18nLabel: 'Info', icon: 'info-circled', }); registerAdminSidebarItem({ href: 'admin-import', i18nLabel: 'Import', icon: 'import', permissionGranted: () => hasPermission('run-import'), }); registerAdminSidebarItem({ href: 'admin-users', i18nLabel: 'Users', icon: 'team', permissionGranted: () => hasPermission('view-user-administration'), }); registerAdminSidebarItem({ href: 'admin-rooms', i18nLabel: 'Rooms', icon: 'hashtag', permissionGranted: () => hasPermission('view-room-administration'), }); registerAdminSidebarItem({ href: 'invites', i18nLabel: 'Invites', icon: 'user-plus', permissionGranted: () => hasPermission('create-invite-links'), }); registerAdminSidebarItem({ icon: 'cloud-plus', href: 'cloud', i18nLabel: 'Connectivity_Services', permissionGranted: () => hasPermission('manage-cloud'), }); registerAdminSidebarItem({ href: 'admin-view-logs', i18nLabel: 'View_Logs', icon: 'post', permissionGranted: () => hasPermission('view-logs'), }); registerAdminSidebarItem({ href: 'custom-sounds', i18nLabel: 'Custom_Sounds', icon: 'volume', permissionGranted() { return hasPermission(['manage-sounds']); }, });
var searchData= [ ['webback',['webBack',['../namespaceweb_back.html',1,'']]], ['webback_2epy',['webBack.py',['../web_back_8py.html',1,'']]], ['whiletrue',['whiletrue',['../namespace____main____.html#a5cd663b7efff8164ad13f39d2f577eee',1,'__main__']]], ['whiletruethread',['whiletruethread',['../namespace____main____.html#a53ebc1b671bc860d557e274c6f7db716',1,'__main__']]], ['writetosql',['writeToSql',['../classgame_1_1_player_1_1player.html#a2aae31c5ae0c817b975b2dc4ae470e98',1,'game::Player::player']]] ];
export class Course { static json = require('AnyDumper/db/aws_csa_a.json'); static load() { return this.json; } }
// Karma configuration // http://karma-runner.github.io/0.12/config/configuration-file.html // Generated on 2015-03-16 using // generator-karma 0.9.0 module.exports = function(config) { 'use strict'; config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: '../', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/firebase/firebase.js', 'bower_components/angularfire/dist/angularfire.js', 'bower_components/angular-animate/angular-animate.js', 'bower_components/angular-aria/angular-aria.js', 'bower_components/angular-cookies/angular-cookies.js', 'bower_components/angular-messages/angular-messages.js', 'bower_components/angular-resource/angular-resource.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-sanitize/angular-sanitize.js', 'bower_components/angular-touch/angular-touch.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [ ], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: [ 'PhantomJS' ], // Which plugins to enable plugins: [ 'karma-phantomjs-launcher', 'karma-jasmine' ], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
var BPromise = require("bluebird"); var express = require("express"); var request = require("supertest-as-promised"); var MW = require("../../"); var st = require("../st.js"); describe("Integration suite - Methods", function () { var db; before(function () { return st.setup().then(function (dbConnection) { db = dbConnection; }); }); after(function () { return st.teardown(db); }); it("that do not exist", function () { var mw = new MW(db); var app = express().use("/", mw.getRouter()); return request(app) .post("/") .send({method: "nonexistentMethod", params: []}) .expect("Content-Type", /json/) .expect(404) .expect({error: "Method not found"}); }); it("that return undefined", function () { var mw = new MW(db); mw.methods({ "return:value": function () { } }); var app = express().use("/", mw.getRouter()); return request(app) .post("/") .send({method: "return:value", params: []}) .expect("Content-Type", /json/) .expect(200) .expect({result: null}); }); it("that return a value", function () { var mw = new MW(db); mw.methods({ "return:value": function () { return "return:value"; } }); var app = express().use("/", mw.getRouter()); return request(app) .post("/") .send({method: "return:value", params: []}) .expect("Content-Type", /json/) .expect(200) .expect({result: "return:value"}); }); it("that throw a MW.Error", function () { var mw = new MW(db); mw.methods({ "throw:mw-error": function () { throw new MW.Error(499, "MW.Error"); } }); var app = express().use("/", mw.getRouter()); return request(app) .post("/") .send({method: "throw:mw-error", params: []}) .expect("Content-Type", /json/) .expect(499) .expect({error: "MW.Error"}); }); it("that throw a generic error", function () { var mw = new MW(db); mw.methods({ "throw:generic-error": function () { throw new Error("Generic error"); } }); var app = express().use("/", mw.getRouter()); return request(app) .post("/") .send({method: "throw:generic-error", params: []}) .expect("Content-Type", /json/) .expect(500) .expect({error: "Internal server error"}); }); it("that return a promise which is eventually resolved", function () { var mw = new MW(db); mw.methods({ "return:promise:resolved": function () { return new BPromise(function (resolve, reject) { setTimeout(function () { resolve("return:promise:resolved"); }, 10); }); } }); var app = express().use("/", mw.getRouter()); return request(app) .post("/") .send({method: "return:promise:resolved", params: []}) .expect("Content-Type", /json/) .expect(200) .expect({result: "return:promise:resolved"}); }); it("that return a promise which is eventually rejected with an MW.Error", function () { var mw = new MW(db); mw.methods({ "return:promise:rejected:mw-error": function () { return new BPromise(function (resolve, reject) { setTimeout(function () { reject(new MW.Error(499, "MW.Error")); }, 10); }); } }); var app = express().use("/", mw.getRouter()); return request(app) .post("/") .send({method: "return:promise:rejected:mw-error", params: []}) .expect("Content-Type", /json/) .expect(499) .expect({error: "MW.Error"}); }); it("that return a promise which is eventually rejected with a generic error", function () { var mw = new MW(db); mw.methods({ "return:promise:rejected:generic-error": function () { return new BPromise(function (resolve, reject) { setTimeout(function () { reject(new Error("Generic error")); }, 10); }); } }); var app = express().use("/", mw.getRouter()); return request(app) .post("/") .send({method: "return:promise:rejected:generic-error", params: []}) .expect("Content-Type", /json/) .expect(500) .expect({error: "Internal server error"}); }); });
var jwt = require('jsonwebtoken'); var db = require('../server/schema'); module.exports = { register : function (req, res) { var username = req.body.username || ''; var password = req.body.password || ''; var email = req.body.email || ''; var passwordConfirmation = req.body.passwordConfirmation || ''; if (username == '' || password == '' || password != passwordConfirmation) { return res.status(400).send("Registration error"); } else { UserModel.findOne({username: req.body.username}, function (err, user) { if (err) { console.log(err); res.status(401).send("error finding username in DataBase"); } else if(user) { res.status(409).send("username already exists"); } else if (user == undefined) { var newUser = new UserModel( { username : req.body.username, password : req.body.password, is_admin : true, email : req.body.email }) newUser.save(function(err) { if (err) { console.log(err); res.status(500).send("Error: problem saving user to Database"); } else { return res.status(200).send("New user saved to Database"); } }); } }) }; }, login : function (req, res) { var username = req.body.username || ''; var password = req.body.password || ''; if (username == '' || password == '') { return res.status(401).send("username or password fields are empty"); } else { db.UserModel.findOne({username: req.body.username}, function (err, user) { if (err) { console.log(err); return res.status(401).end(); } if (user == undefined) { return res.status(401).send("User undefined"); } user.comparePassword(req.body.password, function(err, isMatch) { if (!isMatch) { console.log("Attempt failed to login with " + user.username); return res.status(401).send("Password does not match"); } var userProfile = { username: user.username, admin: user.is_admin, created: user.created, email: user.email }; res.json({ token: token }); }); }); }; }, logout : function(req, res) { res.status(200).end(); }, getAdmin : function (req, res) { console.log('user ' + req.username + ' is calling /admin'); console.info("req token=" +JSON.stringify(req.headers)); res.send(req.username); } };