text
stringlengths
2
6.14k
var RamAppDispatcher = require('../dispatcher/RamAppDispatcher'); var RamConstants = require('../constants/RamConstants'); var ActionTypes = RamConstants.ActionTypes; var LayoutActions = { setLayout: function(layoutId) { RamAppDispatcher.handleViewAction({ type: ActionTypes.SET_LAYOUT, layoutId: layoutId }); } }; module.exports = LayoutActions;
ivar.namespace('ivar.random'); ivar.random.integer = function(min, max) { }; ivar.random.float = function(min, max) { }; ivar.random.string = function(min, max, first_capital) { }; ivar.random.date = function(min, max) { }; ivar.random.array = function(min, max, type) { }; ivar.random.gender = function(min, max) { }; ivar.random.nameFormatedString = function(middle) { }; ivar.random.address = function(middle) { }; ivar.random.name = function(middle) { };
'use strict'; define(function() { return function($scope, events, Posts, Categories, Users) { $scope.configCover = { fileName: 'cover_photo', url: 'cms-api/posts' }; $scope.configGallery = { fileName: 'slider_photos', url: 'cms-api/posts' }; $scope.configGrid = { fileName: 'grid_photo', url: 'cms-api/posts' }; $scope.dpOpen = false; $scope.dpOptions = { showWeeks: false }; $scope.post = { datasets: [''], datasets_ext: [''], slider_photos: [''], name: '', section: '' }; $scope.sections = Categories.query({ page: 1, per_page: 99999, select: 'name', type: 'SECTION' }); $scope.tags = Categories.query({ page: 1, per_page: 99999, select: 'name', type: 'TAG' }); $scope.authors = Users.query({ page: 1, per_page: 9999, type: { $gte: 1 } }); $scope.create = function() { if ($scope.postForm.$valid && $scope.post.author && $scope.post.name && $scope.post.content) { console.log('ess', $scope.postForm.$valid); $scope.post.author = $scope.post.author.replace(/<br>/g, ''); $scope.post.content = $scope.post.content.replace(/<br>/g, ''); $scope.post.name = $scope.post.name.replace(/<br>/g, ''); $scope.post.slug = slug($scope.post.name, { lower: true }); var result = Posts.create($scope.post); result.$promise.then(function (data) { alert('Registro guardado.') }, function(err) { if(err.status === 403) { alert('El título del contenido ya existe.'); } }); } else { alert('Datos Incompletos'); } }; $scope.datasetAdd = function() { $scope.post.datasets.push(''); }; $scope.datasetRemove = function(i) { $scope.post.datasets.splice(i, 1); }; $scope.datasetExtAdd = function() { $scope.post.datasets_ext.push(''); }; $scope.datasetExtRemove = function(i) { $scope.post.datasets_ext.splice(i, 1); }; $scope.photoAdd = function() { $scope.post.slider_photos.push(''); }; $scope.photoRemove = function() { $scope.post.slider_photos.pop(); }; $scope.open = function() { $scope.dpOpen = true; }; $scope.$on(events.FILEUPLOADER_DONE, function(e, data) { if (Object.keys(data)[0] == 'slider_photos') { $scope.post.slider_photos[parseInt(data.index, 10)] = data[Object.keys(data)[0]]; } else { $scope.post[Object.keys(data)[0]] = data[Object.keys(data)[0]]; } }); $scope.$on(Posts.getEvent('CREATED'), function() { $scope.$state.go('posts.list'); }); $scope.$on('POST_SAVE', function() { $scope.create(); }); $scope.$watch('post.section', function(section) { if (section) { $scope.categories = Categories.query({ page: 1, per_page: 99999, section: section, select: 'name', type: 'CATEGORY' }); for (var i = 0; i < $scope.sections.length; i++) { if (section == $scope.sections[i]._id) { $scope.sectionName = $scope.sections[i].name; } } } }); if ($scope.user.type > 1) { $scope.post.created_by = $scope.user._id; } }; });
module.exports = { // the database url to connect url : 'mongodb://172.17.42.1:27017/orxan' //url : 'mongodb://localhost:27017/orxan' }
angular.module('storyCtrl', ['storyService']) .controller('StoryController', function(Story, socketio) { var vm = this; Story.all() .success(function(data) { vm.stories = data; }); vm.createStory = function() { vm.processing = true; vm.message = ''; Story.create(vm.storyData) .success(function(data) { vm.processing = false; //clear up the form vm.storyData = {}; vm.message = data.message; }); }; socketio.on('story', function(data) { vm.stories.push(data); }) }) .controller('AllStoriesController', function(stories, socketio) { var vm = this; vm.stories = stories.data; socketio.on('story', function(data) { vm.stories.push(data); }); });
module.exports = PriorityQueueMock; var _map; function PriorityQueueMock(comparer) { _map = new Map(); } PriorityQueueMock.prototype.queue = function (task) { _map.set(task, task); }; PriorityQueueMock.prototype.length = function () { return _map.size; }; PriorityQueueMock.prototype.peek = function () { };
'use strict' const { gql } = require('apollo-server-micro') module.exports = gql` """ Domains are required to track views. You can create as many domains as you want, but it's recommended to create on domain per project/site. This allows you to view facts and statistics separately. """ type Domain { """ Domain identifier. """ id: ID! """ Title of the domain. """ title: String! """ Facts about a domain. Usually simple data that can be represented in one value. """ facts: Facts! """ Statistics of a domain. Usually data that needs to be represented in a list or chart. """ statistics: DomainStatistics! """ Identifies the date and time when the object was created. """ created: DateTime! """ Identifies the date and time when the object was updated. """ updated: DateTime! } input CreateDomainInput { """ Title of the domain. """ title: String! } type CreateDomainPayload { """ Indicates that the domain creation was successful. Might be 'null' otherwise. """ success: Boolean """ The newly created domain. """ payload: Domain } input UpdateDomainInput { """ Title of the domain. """ title: String! } type UpdateDomainPayload { """ Indicates that the domain update was successful. Might be 'null' otherwise. """ success: Boolean """ The updated domain. """ payload: Domain } type DeleteDomainPayload { """ Indicates that the domain deletion was successful. Might be 'null' otherwise. """ success: Boolean } type Query { """ Data of a specific domain. """ domain(id: ID!): Domain """ Data of all existing domains. """ domains: [Domain!] } type Mutation { """ Create a new domain. """ createDomain(input: CreateDomainInput!): CreateDomainPayload! """ Update an existing domain. """ updateDomain(id: ID!, input: UpdateDomainInput!): UpdateDomainPayload! """ Delete an existing domain. """ deleteDomain(id: ID!): DeleteDomainPayload! } `
'use strict'; // Collects keyboard inputs state collection of keycodes that currently pressed, // if its not true then it false and its up // ----------------------------------------- (function () { var state = {}, defaultHidState = { down: 0, up: 0 }; window.document.addEventListener('keydown', function (e) { state[e.keyCode] = state[e.keyCode] || _.clone(defaultHidState); state[e.keyCode].down = e.timeStamp; state[e.keyCode].pressed = true; e.preventDefault(); }, false); window.document.addEventListener('keyup', function (e) { state[e.keyCode] = state[e.keyCode] || _.clone(defaultHidState); state[e.keyCode].up = e.timeStamp; state[e.keyCode].pressed = false; e.preventDefault(); }, false); new CONV.System.IO({ name: 'Keyboard', isStatic: true, dependencies: [], component: function () { return state; } }); })();
// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. 'use strict'; /*eslint no-console: 0*/ var assert = require('assert'); var console = require('console'); var setTimeout = require('timers').setTimeout; var TChannel = require('../channel.js'); var counter = 2; var server = new TChannel(); var client = new TChannel(); var serverChan = server.makeSubChannel({ serviceName: 'server' }); // normal response serverChan.register('func1', function onReq(req, res, arg2, arg3) { console.log('func1 responding with a small delay', { arg2: arg2.toString(), arg3: arg3.toString() }); setTimeout(function onTimeout() { res.headers.as = 'raw'; res.sendOk('result', 'indeed it did'); }, Math.random() * 1000); }); // err response serverChan.register('func2', function onReq2(req, res) { res.headers.as = 'raw'; res.sendNotOk(null, 'it failed'); }); server.listen(4040, '127.0.0.1', function onListen() { var clientChan = client.makeSubChannel({ serviceName: 'server', peers: [server.hostPort], requestDefaults: { hasNoParent: true, headers: { 'as': 'raw', 'cn': 'example-client' } } }); clientChan.request({ serviceName: 'server', timeout: 1500 }).send('func1', 'arg 1', 'arg 2', function onResp(err, res, arg2, arg3) { if (err) { finish(err); } else { assert.equal(res.ok, true); console.log('normal res:', { arg2: arg2.toString(), arg3: arg3.toString() }); finish(); } }); clientChan.request({ serviceName: 'server' }).send('func2', 'arg 1', 'arg 2', function onResp(err, res, arg2, arg3) { if (err) { finish(err); } else { assert.equal(res.ok, false); console.log('err res: ', { ok: res.ok, message: String(arg3) }); finish(); } }); }); function finish(err) { if (err) { throw err; } if (--counter === 0) { server.close(); client.close(); } }
/* Copyright (c) 2014-2017 Richard Rodger and other contributors, MIT License */ var Code = require('code') var Lab = require('lab') var Seneca = require('seneca') var lab = exports.lab = Lab.script() var describe = lab.describe var it = lab.it var expect = Code.expect describe('info', function () { it('happy', function (done) { Seneca() // Place Seneca into test mode. Errors will be passed to done callback, // so no need to handle them in callbacks. .test(done) // Uncomment if you want to see detailed logs // .test(done, 'print') // Load the info plugin .use('..') // Define mock messages. .add('role:info,need:part', function (msg, reply) { this .act('role:info,collect:part',{ name: msg.name, part: 'npm', data: {name: msg.name, version:'1.0.0'} }) .act('role:info,collect:part',{ name: msg.name, part: 'github', data: {name: msg.name, stars:2} }) }) .act('role:info,cmd:get,name:foo', function (ignore, out) { expect(out.npm).to.equal({ name: 'foo', version: '1.0.0' }) expect(out.github).to.equal({ name: 'foo', stars: 2 }) done() }) }) })
/*! * SmartMenus jQuery Plugin Bootstrap Addon - v0.1.0 - January 19, 2014 * http://www.smartmenus.org/ * * Copyright 2014 Vasil Dinkov, Vadikom Web Ltd. * http://vadikom.com * * Licensed MIT */ jQuery(function( $ ) { // init all menus $('ul.navbar-nav').each(function() { var $this = $(this); //console.log( $this.attr('id' ) ); $this.addClass('sm').smartmenus({ // these are some good default options that should work for all // you can, of course, tweak these as you like subMenusSubOffsetX: 2, subMenusSubOffsetY: -6, subIndicators: false, /* bootstrap already creates them itself */ /*subIndicatorsPos: 'append', subIndicatorsText: '...',*/ collapsibleShowFunction: null, collapsibleHideFunction: null, rightToLeftSubMenus: $this.hasClass('navbar-right'), bottomToTopSubMenus: $this.closest('.navbar').hasClass('navbar-fixed-bottom') }) // set Bootstrap's "active" class to SmartMenus "current" items (should someone decide to enable markCurrentItem: true) //.find('a.current').parent().addClass('active'); // adaption for WP menu .find('.current-menu-item').addClass('active'); }) .bind({ // set/unset proper Bootstrap classes for some menu elements 'show.smapi': function(e, menu) { var $menu = $(menu), $scrollArrows = $menu.dataSM('scroll-arrows'), obj = $(this).data('smartmenus'); if ($scrollArrows) { // they inherit border-color from body, so we can use its background-color too $scrollArrows.css('background-color', $(document.body).css('background-color')); } $menu.parent().addClass('open' + (obj.isCollapsible() ? ' collapsible' : '')); }, 'hide.smapi': function(e, menu) { $(menu).parent().removeClass('open collapsible'); }, // click the parent item to toggle the sub menus (and reset deeper levels and other branches on click) 'click.smapi': function(e, item) { var obj = $(this).data('smartmenus'); if (obj.isCollapsible()) { var $item = $(item), $sub = $item.parent().dataSM('sub'); if ($sub && $sub.dataSM('shown-before') && $sub.is(':visible')) { obj.itemActivate($item); obj.menuHide($sub); return false; } } } }); // fix collapsible menu detection for Bootstrap 3 $.SmartMenus.prototype.isCollapsible = function() { return this.$firstLink.parent().css('float') != 'left'; }; });
// All symbols in the `Myanmar` script as per Unicode v4.1.0: [ '\u1000', '\u1001', '\u1002', '\u1003', '\u1004', '\u1005', '\u1006', '\u1007', '\u1008', '\u1009', '\u100A', '\u100B', '\u100C', '\u100D', '\u100E', '\u100F', '\u1010', '\u1011', '\u1012', '\u1013', '\u1014', '\u1015', '\u1016', '\u1017', '\u1018', '\u1019', '\u101A', '\u101B', '\u101C', '\u101D', '\u101E', '\u101F', '\u1020', '\u1021', '\u1023', '\u1024', '\u1025', '\u1026', '\u1027', '\u1029', '\u102A', '\u102C', '\u102D', '\u102E', '\u102F', '\u1030', '\u1031', '\u1032', '\u1036', '\u1037', '\u1038', '\u1039', '\u1040', '\u1041', '\u1042', '\u1043', '\u1044', '\u1045', '\u1046', '\u1047', '\u1048', '\u1049', '\u104A', '\u104B', '\u104C', '\u104D', '\u104E', '\u104F', '\u1050', '\u1051', '\u1052', '\u1053', '\u1054', '\u1055', '\u1056', '\u1057', '\u1058', '\u1059' ];
// All symbols in the Geometric Shapes block as per Unicode v6.1.0: [ '\u25A0', '\u25A1', '\u25A2', '\u25A3', '\u25A4', '\u25A5', '\u25A6', '\u25A7', '\u25A8', '\u25A9', '\u25AA', '\u25AB', '\u25AC', '\u25AD', '\u25AE', '\u25AF', '\u25B0', '\u25B1', '\u25B2', '\u25B3', '\u25B4', '\u25B5', '\u25B6', '\u25B7', '\u25B8', '\u25B9', '\u25BA', '\u25BB', '\u25BC', '\u25BD', '\u25BE', '\u25BF', '\u25C0', '\u25C1', '\u25C2', '\u25C3', '\u25C4', '\u25C5', '\u25C6', '\u25C7', '\u25C8', '\u25C9', '\u25CA', '\u25CB', '\u25CC', '\u25CD', '\u25CE', '\u25CF', '\u25D0', '\u25D1', '\u25D2', '\u25D3', '\u25D4', '\u25D5', '\u25D6', '\u25D7', '\u25D8', '\u25D9', '\u25DA', '\u25DB', '\u25DC', '\u25DD', '\u25DE', '\u25DF', '\u25E0', '\u25E1', '\u25E2', '\u25E3', '\u25E4', '\u25E5', '\u25E6', '\u25E7', '\u25E8', '\u25E9', '\u25EA', '\u25EB', '\u25EC', '\u25ED', '\u25EE', '\u25EF', '\u25F0', '\u25F1', '\u25F2', '\u25F3', '\u25F4', '\u25F5', '\u25F6', '\u25F7', '\u25F8', '\u25F9', '\u25FA', '\u25FB', '\u25FC', '\u25FD', '\u25FE', '\u25FF' ];
import { StyleSheet } from 'react-native'; export default StyleSheet.create({ boardMenu: { flex: 1, }, board: { flex: 2, justifyContent: 'center', alignItems: 'center', }, selector: { flex: 1, }, game: { flex: 1, alignItems: 'center', backgroundColor: '#f2f2f2', }, });
import { define, render, WeElement, html } from '../../src/omi' define('my-clock', class extends WeElement { install = this.updateTime updateTime() { const time = new Date() this.hours = time.getHours() this.minutes = time.getMinutes() this.seconds = time.getSeconds() } installed() { setInterval(() => { this.updateTime() this.update() }, 1000) } arr = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55] render() { const { hours, minutes, seconds } = this return ( <svg viewBox='-50 -50 100 100'> <circle class='clock-face' r='48' /> {this.arr.map(i => ( <line class='major' y1='35' y2='45' transform={`rotate(${30 * i})`} /> ))} {this.arr.map(i => ( [1, 2, 3, 4].map(o => <line class='minor' y1='42' y2='45' transform={`rotate(${6 * (i + o)})`} />) ))} <line class='hour' y1='2' y2='-20' transform={`rotate(${30 * hours + minutes / 2})`} /> <line class='minute' y1='4' y2='-30' transform={`rotate(${6 * minutes + seconds / 10})`} /> <g transform={`rotate(${6 * seconds})`}> <line class='second' y1='10' y2='-38' /> <line class='second-counterweight' y1='10' y2='2' /> </g> </svg> ) } static css = ` svg { width: 100%; height: 100%; } .clock-face { stroke: #333; fill: white; } .minor { stroke: #999; stroke-width: 0.5; } .major { stroke: #333; stroke-width: 1; } .hour { stroke: #333; } .minute { stroke: #666; } .second, .second-counterweight { stroke: rgb(180, 0, 0); } .second-counterweight { stroke-width: 3; } ` }) render(<my-clock></my-clock>, 'body')
import './css/t.scss'; import './css/modifier/t-red.scss'; import './js/t';
'use strict'; define(["exports", "./array.js", "./block.js", "./caml_array.js"], function(exports, $$Array, Block, Caml_array){ 'use strict'; function int32_to_value(x) { return /* Int32 */Block.__(0, [x]); } function int64_to_value(x) { return /* Int64 */Block.__(1, [x]); } function int_to_value(x) { return /* Int */Block.__(2, [x]); } function nativeint_to_value(x) { return /* Nativeint */Block.__(3, [x]); } function bool_to_value(x) { return /* Bool */Block.__(4, [x]); } function float_to_value(x) { return /* Float */Block.__(5, [x]); } function char_to_value(x) { return /* Char */Block.__(6, [x]); } function string_to_value(x) { return /* String */Block.__(7, [x]); } function array_map(f, a) { var l = a.length; if (l) { var r = Caml_array.caml_make_vect(l, f(a[0])); for(var i = 1 ,i_finish = l - 1 | 0; i <= i_finish; ++i){ r[i] = f(a[i]); } return r; } else { return /* array */[]; } } function array_to_value(k) { return (function (x) { return /* Array */Block.__(10, [array_map(k, x)]); }); } function list_to_value(k) { return (function (x) { return /* Array */Block.__(10, [array_map(k, $$Array.of_list(x))]); }); } function record_to_value(labels, v) { return /* Record */Block.__(12, [ labels, v ]); } function variant_to_value(labels, tag, vs) { return /* Variant */Block.__(13, [ labels, tag, vs ]); } function tuple_2_to_value(k0, k1) { return (function (param) { return /* Tuple */Block.__(9, [/* array */[ k0(param[0]), k1(param[1]) ]]); }); } function tuple_3_to_value(k0, k1, k2) { return (function (param) { return /* Tuple */Block.__(9, [/* array */[ k0(param[0]), k1(param[1]), k2(param[2]) ]]); }); } function tuple_4_to_value(k0, k1, k2, k3) { return (function (param) { return /* Tuple */Block.__(9, [/* array */[ k0(param[0]), k1(param[1]), k2(param[2]), k3(param[3]) ]]); }); } function tuple_5_to_value(k0, k1, k2, k3, k4) { return (function (param) { return /* Tuple */Block.__(9, [/* array */[ k0(param[0]), k1(param[1]), k2(param[2]), k3(param[3]), k4(param[4]) ]]); }); } function tuple_6_to_value(k0, k1, k2, k3, k4, k5) { return (function (param) { return /* Tuple */Block.__(9, [/* array */[ k0(param[0]), k1(param[1]), k2(param[2]), k3(param[3]), k4(param[4]), k5(param[5]) ]]); }); } function option_to_value(k) { return (function (x) { if (x) { return /* OptionSome */Block.__(8, [k(x[0])]); } else { return /* OptionNone */0; } }); } function shape_of_record(labels) { return labels; } function shape_of_variant(constructors, arities) { return /* record */[ /* constructors */constructors, /* arities */arities ]; } exports.int32_to_value = int32_to_value; exports.int64_to_value = int64_to_value; exports.int_to_value = int_to_value; exports.nativeint_to_value = nativeint_to_value; exports.bool_to_value = bool_to_value; exports.float_to_value = float_to_value; exports.char_to_value = char_to_value; exports.string_to_value = string_to_value; exports.array_to_value = array_to_value; exports.list_to_value = list_to_value; exports.option_to_value = option_to_value; exports.record_to_value = record_to_value; exports.variant_to_value = variant_to_value; exports.tuple_2_to_value = tuple_2_to_value; exports.tuple_3_to_value = tuple_3_to_value; exports.tuple_4_to_value = tuple_4_to_value; exports.tuple_5_to_value = tuple_5_to_value; exports.tuple_6_to_value = tuple_6_to_value; exports.shape_of_variant = shape_of_variant; exports.shape_of_record = shape_of_record; }) /* No side effect */
const HTTP_CODE = { OK: 200, BAD_REQUEST: 400 }; class ResponseHelper { /** * @description * Sends success response to the user * * @param {Object} res response object * @param {Object} [data] content to return */ static success(res, data) { const result = data || {}; result.status = 'ok'; res.send(HTTP_CODE.OK, result); } /** * @description * Sends error response to the user * * @param {Object} res response object * @param {Object} [data] content to return * @param {Number} [code=400] error code */ static fail(res, data, code) { const result = data || {}; result.status = 'error'; result.code = code || HTTP_CODE.BAD_REQUEST; res.send(data.code, result); } /** * @description * Recoursively masks fields in object * * @param {Object} object * @param {Array<String>} fields List of field names to mask * @returns {Object} */ static maskFields(object, fields) { Object.keys(object).forEach(propertyName => { if (fields.indexOf(propertyName) !== -1) object[propertyName] = '******'; else if ( typeof object[propertyName] === 'object' && !Array.isArray(object) ) { object[propertyName] = ResponseHelper.maskFields( object[propertyName], fields ); } }); return object; } } module.exports = ResponseHelper;
import ExtractTextPlugin from 'extract-text-webpack-plugin'; import autoprefixer from 'autoprefixer'; import constants from './constants'; import path from 'path'; import webpack from 'webpack'; import webpackIsomorphicAssets from './assets'; import WebpackIsomorphicToolsPlugin from 'webpack-isomorphic-tools/plugin'; import ip from 'ip'; const webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(webpackIsomorphicAssets); // cheap-module-eval-source-map, because we want original source, but we don't // care about columns, which makes this devtool faster than eval-source-map. // http://webpack.github.io/docs/configuration.html#devtool const devtools = 'cheap-module-eval-source-map'; const loaders = { css: '', // Why not LESS or Stylus? The battle is over, let's focus on inline styles. scss: '!sass-loader', sass: '!sass-loader?indentedSyntax' }; const serverIp = ip.address(); export default function makeConfig(isDevelopment) { function stylesLoaders() { return Object.keys(loaders).map(ext => { const prefix = 'css-loader!postcss-loader'; const extLoaders = prefix + loaders[ext]; const loader = isDevelopment ? `style-loader!${extLoaders}` : ExtractTextPlugin.extract('style-loader', extLoaders); return { loader, test: new RegExp(`\\.(${ext})$`) }; }); } const config = { hotPort: constants.HOT_RELOAD_PORT, cache: isDevelopment, debug: isDevelopment, devtool: isDevelopment ? devtools : '', entry: { app: isDevelopment ? [ `webpack-hot-middleware/client?path=http://${serverIp}:${constants.HOT_RELOAD_PORT}/__webpack_hmr`, path.join(constants.SRC_DIR, 'browser/main.js') ] : [ path.join(constants.SRC_DIR, 'browser/main.js') ] }, module: { loaders: [{ loader: 'url-loader?limit=10000', test: /\.(gif|jpg|png|svg)$/ }, { loader: 'url-loader?limit=1', test: /favicon\.ico$/ }, { loader: 'url-loader?limit=100000', test: /\.(ttf|eot|woff(2)?)(\?[a-z0-9]+)?$/ }, { test: /\.js$/, exclude: constants.NODE_MODULES_DIR, loader: 'babel', query: { cacheDirectory: true, plugins: ['transform-runtime', 'add-module-exports'], presets: ['es2015', 'react', 'stage-1'], env: { development: { presets: ['react-hmre'] }, production: { plugins: [ 'transform-react-constant-elements', 'transform-react-inline-elements' ] } } } }].concat(stylesLoaders()) }, output: isDevelopment ? { path: constants.BUILD_DIR, filename: '[name].js', chunkFilename: '[name]-[chunkhash].js', publicPath: `http://${serverIp}:${constants.HOT_RELOAD_PORT}/build/` } : { path: constants.BUILD_DIR, filename: '[name]-[hash].js', chunkFilename: '[name]-[chunkhash].js', publicPath: process.env.IS_SERVERLESS ? 'assets/' : '/assets/' }, plugins: (() => { const plugins = [ new webpack.DefinePlugin({ 'process.env': { IS_BROWSER: true, // Because webpack is used only for browser code. IS_SERVERLESS: JSON.stringify(process.env.IS_SERVERLESS || false), NODE_ENV: JSON.stringify(isDevelopment ? 'development' : 'production'), SERVER_URL: JSON.stringify(process.env.SERVER_URL || '') } }) ]; if (isDevelopment) { plugins.push( new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin(), webpackIsomorphicToolsPlugin.development() ); } else { plugins.push( // Render styles into separate cacheable file to prevent FOUC and // optimize for critical rendering path. new ExtractTextPlugin('app-[hash].css', { allChunks: true }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { screw_ie8: true, // eslint-disable-line camelcase warnings: false // Because uglify reports irrelevant warnings. } }), webpackIsomorphicToolsPlugin ); } return plugins; })(), postcss: () => [autoprefixer({ browsers: 'last 2 version' })], resolve: { extensions: ['', '.js'], // .json is ommited to ignore ./firebase.json modulesDirectories: ['src', 'node_modules'], root: constants.ABSOLUTE_BASE, alias: { react$: require.resolve(path.join(constants.NODE_MODULES_DIR, 'react')) } } }; return config; }
import { cpus } from 'os'; import R from 'ramda'; import './init-config'; import { start } from './discord'; import { subscriber, publisher, ee, waitForConnections } from './redis'; import sentry from './sentry'; import logger from './logger'; let argv = require('minimist')(process.argv.slice(2)); // With sharding enabled, each instance on a machine will boot (CPU-COUNT - 1) concurrently, // leaving 1 CPU available for other system process'. When a shard has booted, it'll emit to a redis pub/sub // to notify the other shards it's finished and to begin booting the next in line. // Before booting, a redis message is emited to see if another instance is alive meaning a cluster has already been started, // and then skips the queuing process and boots. let skip_queue_timeout; let booting = false; if (argv.shardmode) { const cpu_count = cpus().length; const concurrency = cpu_count === 1 ? 1 : cpu_count - 1; // Leave 1 CPU available for other system processing. const shard_number = Number(argv.shardid); waitForConnections() .then(() => publisher.pubsubAsync('NUMSUB', 'active_shard')) .then(R.nth(1)) .then(active_shards => { if (!active_shards && shard_number > (concurrency - 1)) { logger.info('Queueing up to boot'); ee.on('shard_done', shard_id => { // TODO: Shards wait for others to boot even if on other systems. // This needs to also include a system check to continue starting. shard_id = (Number(shard_id) + 1); if (shard_id === shard_number && !booting) { booting = true; if (skip_queue_timeout) clearTimeout(skip_queue_timeout); start(); } // If other shards are having some issues booting, skip queue and continue. if ((shard_id + 1) === shard_number && !booting) { logger.info('Setting skipped queue timeout'); skip_queue_timeout = setTimeout(() => { logger.info('Previous shard is taking too long to boot. Start booting.'); booting = true; start(); }, 120000); } }); subscriber.subscribe('shard_done'); } else { start(); } }) .catch(err => sentry(err)); } else { start(); }
/* jshint ignore:start */ var model = { data: {} , sortKey: "id" , reverseOrder: false , searchStory: "" , toggles: {} , allExpanded: false , options : { hideDoneStories: false, hideStoryLabels: false, hideDoneTasks: false } }; /* jshint ignore:end */
import * as THREE from 'three'; import PropTypes from 'prop-types'; import GeometryDescriptorBase from './GeometryDescriptorBase'; class TextGeometryDescriptor extends GeometryDescriptorBase { constructor(react3RendererInstance) { super(react3RendererInstance); this.hasProp('text', { type: PropTypes.string.isRequired, update: this.triggerRemount, default: 'TEXT MISSING', }); this.hasProp('font', { type: PropTypes.instanceOf(THREE.Font).isRequired, update: this.triggerRemount, }); this.hasProp('size', { type: PropTypes.number.isRequired, update: this.triggerRemount, }); this.hasProp('height', { type: PropTypes.number, update: this.triggerRemount, default: 50, }); this.hasProp('curveSegments', { type: PropTypes.number, update: this.triggerRemount, default: 12, }); this.hasProp('bevelEnabled', { type: PropTypes.bool, update: this.triggerRemount, default: false, }); this.hasProp('bevelThickness', { type: PropTypes.number, update: this.triggerRemount, default: 10, }); this.hasProp('bevelSize', { type: PropTypes.number, update: this.triggerRemount, default: 8, }); } construct(props) { // props from https://threejs.org/docs/#api/geometries/TextGeometry: const { text, // string font, // THREE.Font size, // number height, // number curveSegments, // number bevelEnabled, // bool bevelThickness, // number bevelSize, // number } = props; return new THREE.TextGeometry(text, { font, size, height, curveSegments, bevelEnabled, bevelThickness, bevelSize, }); } } module.exports = TextGeometryDescriptor;
export const AccountAction = { TYPE: { READY: '@@account/READY', SUBMIT: '@@account/SUBMIT', ERROR: '@@account/ERROR', DONE: '@@account/DONE', }, COMMAND: { SIGN_IN: 'sign-in', SIGN_UP: 'sign-up', FORGOT_PASSWORD: 'forgot-password', FACEBOOK_LOGIN: 'facebook-login', }, }; const initialState = { submitted: false, account: { email: '', password: '', state: 'ready', }, errors: {}, }; export function accountReducer(state = initialState, { type, command, payload }) { switch (type) { case AccountAction.TYPE.READY: return { command, submitted: false, account: payload && payload.account, }; case AccountAction.TYPE.SUBMIT: return { command, submitted: true, account: payload && payload.account, }; case AccountAction.TYPE.ERROR: return { command, submitted: false, account: payload && payload.account, errors: payload && payload.errors, }; } state.command = command; return state; } /* export function accountSignInReducer(state = initialSignInState, { type, payload }) { switch (type) { case AccountAction.TYPE.READY: return { submitted: false, account: payload && payload.account, }; case AccountAction.TYPE.SUBMIT: return { submitted: true, account: payload && payload.account, }; case AccountAction.TYPE.ERROR: return { submitted: false, account: payload && payload.account, errors: payload && payload.errors, }; } state.command = command; return state; } const initialSignUpState = { command: AccountAction.COMMAND.SIGN_UP, submitted: false, account: { email: '', password: '', state: 'ready', }, errors: {}, }; export function accountSignUpReducer(state = initialSignInState, { type, payload }) { switch (type) { case AccountAction.TYPE.READY: return { submitted: false, account: payload && payload.account, }; case AccountAction.TYPE.SUBMIT: return { submitted: true, account: payload && payload.account, }; case AccountAction.TYPE.ERROR: return { submitted: false, account: payload && payload.account, errors: payload && payload.errors, }; } state.command = command; return state; } const initialForgotPasswordState = { submitted: false, account: { email: '', state: 'ready', }, errors: {}, }; export function accountForgotPasswordReducer(state = initialForgotPasswordState, { type, payload }) { switch (type) { case AccountAction.FORGOT_PASSWORD.READY: return { submitted: false, account: payload && payload.account, }; case AccountAction.FORGOT_PASSWORD.SUBMIT: return { submitted: true, account: payload && payload.account, }; case AccountAction.FORGOT_PASSWORD.ERROR: return { submitted: false, account: payload && payload.account, errors: payload && payload.errors, }; } return state; } */
var frames = require("ui/frame"); function onTap_About() { var navigationEntry = { moduleName: "views/about/about", transition: { name: "slideBottom" } }; frames.topmost().navigate(navigationEntry); } exports.onTap_About = onTap_About; function onTap_ContactUs() { var navigationEntry = { moduleName: "views/contact-us/contact-us", transition: { name: "slideBottom" } }; frames.topmost().navigate(navigationEntry); } exports.onTap_ContactUs = onTap_ContactUs; function onTap_Products() { var navigationEntry = { moduleName: "views/products/products", // clearHistory: true, transition: { name: "slideBottom" } }; frames.topmost().navigate(navigationEntry); } exports.onTap_Products = onTap_Products;
// volontary written in ES5, so that it works with Node 4.x var path = require('path'); var webpack = require('webpack'); var ProgressBarPlugin = require('progress-bar-webpack-plugin'); var HasteMapWebPackResolver = require('haste-map-webpack-resolver'); var currentDir = path.resolve(__dirname, '.'); var hasteMapWebPackResolver = new HasteMapWebPackResolver({ rootPath: path.resolve(__dirname, '.'), }); module.exports = { context: currentDir, entry: './entry-point.js', output: { path: './dist', filename: 'entry-point.bundle.js', library: 'entry-point', libraryTarget: 'umd', umdNamedDefine: true }, devtool: 'sourcemap', target: 'node', module: { rules: [ { test: /\.js/, exclude: /(node_modules)/, use: [ { loader: 'babel-loader', query: { presets: ['babel-preset-es2015'] }, } ] } ], }, resolve: { plugins: [hasteMapWebPackResolver.resolver], }, plugins: [ new webpack.BannerPlugin( { banner: 'require("source-map-support").install();', raw: true, entryOnly: false, } ), new ProgressBarPlugin(), hasteMapWebPackResolver, ], };
var definition = { friendlyName: 'simplepipe', description: 'recieve a number and pluse 1.', inputs: { in: { description: 'recieved number.', } }, exits: { success: { description: 'computated result.' } }, fn: function(inputs, exits){ exits.success(inputs.in+1); } }; function provideComponent(options) { return definition; }; module.exports = { definition: definition, provideComponent: provideComponent }
var crypto = require('crypto'); var hashPassword = exports.hashPassword = function (password) { return crypto.createHash('sha1', conf.passwordKey) .update(password).update(conf.passwordSalt).digest('base64'); } ,randomBin = exports.randomBin = function (length, pre, post) { pre = pre || ''; post = post || ''; var buf = new Buffer(length+pre.length+post.length) ,i = pre.length; buf.write(pre); for (;i < length; i++) { buf[i] = Math.round(Math.random()*255); } buf.write(post, i); return buf; } ,encodeBase64Url = exports.encodeBase64Url = function (buf) { return buf.toString('base64').replace(/=+$/, '').replace(/\//g, '_').replace(/\+/g, '-'); } ,decodeBase64Url = exports.decodeBase64Url = function (str) { return new Buffer(str.replace(/_/g, '/').replace(/-/g, '+'), 'base64'); } ,generateRefreshToken = exports.generateRefreshToken = function () { return encodeBase64Url(randomBin(32, '1/')); } ,generateAccessToken = exports.generateAccessToken = function () { return encodeBase64Url(randomBin(16, '1/')); };
var structtesting_1_1internal_1_1_callable_traits = [ [ "ResultType", "structtesting_1_1internal_1_1_callable_traits.html#a242d198dd1c56a153ba931d7166ec7f3", null ], [ "StorageType", "structtesting_1_1internal_1_1_callable_traits.html#a23cc0c86a3bd18b2f8dd159dd44e1168", null ] ];
ReactiveCycle = function (template, containerSel, itemSel) { console.log("template", template); console.log("containerSel", containerSel); console.log("itemSel", itemSel); } ReactiveObject.prototype.something = function(x) { console.log(x); };
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import PENS from './../../pens'; const draw = v => Object.keys(PENS).reduce((a, c) => { if (PENS[c] === v) return c.toLowerCase(); return a; }, PENS.EMPTY); class Cell extends Component { shouldComponentUpdate(next) { return next.value !== this.props.value; } render() { return (<div className={`cell ${draw(this.props.value)}`}></div>) } } export default Cell;
import React from 'react'; import AppBar from 'material-ui/AppBar'; import { Toolbar, ToolbarTitle } from 'material-ui/Toolbar'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import IconButton from 'material-ui/IconButton/IconButton'; import MenuIcon from 'material-ui/svg-icons/navigation/menu'; import { Link } from 'react-router'; export default class App extends React.Component { render() { const options = { '/': 'Home', '/rsvp': 'RSVP', '/hotel': 'Hotels', '/registry': 'Registry' } const menuItems = Object.keys(options).map(key => { const link = <Link to={key}>{options[key]}</Link>; return (<MenuItem key={key} primaryText={link} />); }); const menu = ( <IconMenu children={menuItems} iconButtonElement={<IconButton><MenuIcon /></IconButton>} /> ); return ( <div> <AppBar title="Jeff and Nicole's Wedding" iconElementLeft={menu} /> { this.props.children } </div> ); } }
/** * Copyright 2014 Telerik AD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["ha-Latn-NG"] = { name: "ha-Latn-NG", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "%" }, currency: { pattern: ["$-n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3], symbol: "N" } }, calendars: { standard: { days: { names: ["Lahadi","Litinin","Talata","Laraba","Alhamis","Juma\u0027a","Asabar"], namesAbbr: ["Lah","Lit","Tal","Lar","Alh","Jum","Asa"], namesShort: ["L","L","T","L","A","J","A"] }, months: { names: ["Januwaru","Febreru","Maris","Afrilu","Mayu","Yuni","Yuli","Agusta","Satumba","Oktocba","Nuwamba","Disamba",""], namesAbbr: ["Jan","Feb","Mar","Afr","May","Yun","Yul","Agu","Sat","Okt","Nuw","Dis",""] }, AM: ["Safe","safe","SAFE"], PM: ["Yamma","yamma","YAMMA"], patterns: { d: "d/M/yyyy", D: "dddd, MMMM dd, yyyy", F: "dddd, MMMM dd, yyyy h:mm:ss tt", g: "d/M/yyyy h:mm tt", G: "d/M/yyyy h:mm:ss tt", m: "MMMM dd", M: "MMMM dd", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "h:mm tt", T: "h:mm:ss tt", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "/", ":": ":", firstDay: 0 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
'use strict'; var path = require('path'); var _ = require('lodash'); function convertToUnixPath(dir) { if (!_.isString(dir)) { throw new Error('Expected path to be a string'); } if (path.sep === '\\') { dir = path.normalize(dir); dir = dir.split(path.sep).join('/'); } return dir; } function generateModuleNames(moduleName, prefix) { return _buildNameObject(moduleName, 'module', prefix); } function generateRouteNames(routeName, prefix) { return _buildNameObject(routeName, 'route', prefix); } function generateConfigurationNames(configurationName, prefix) { return _buildNameObject(configurationName, 'configuration', prefix); } function generateRunNames(runName, prefix) { return _buildNameObject(runName, 'run', prefix); } function generateServiceNames(serviceName, prefix) { return _buildNameObject(serviceName, 'service', prefix); } function generateProviderNames(providerName, prefix) { return _buildNameObject(providerName, 'provider', prefix); } function generateControllerNames(controllerName, prefix) { return _buildNameObject(controllerName, 'controller', prefix); } function generateDirectiveNames(directiveName, prefix) { return _buildNameObject(directiveName, 'directive', prefix); } function getServiceTemplatePath() { return path.join('service', '_service.ts'); } function getControllerTemplatePath() { return path.join('controller', '_controller.ts'); } function _buildNameObject(name, type, prefix) { name = _.camelCase(name); prefix = prefix || ''; var objectName = name + _.capitalize(type); if (prefix.length !== 0) { objectName = prefix + _.upperFirst(objectName); } return { name: objectName, className: _.upperFirst(name) + _.capitalize(type), fileName: _.upperFirst(name) + '.' + type + '.ts' }; } module.exports = { convertToUnixPath: convertToUnixPath, generateModuleNames: generateModuleNames, generateRouteNames: generateRouteNames, generateConfigurationNames: generateConfigurationNames, generateRunNames: generateRunNames, generateServiceNames: generateServiceNames, generateProviderNames: generateProviderNames, generateControllerNames: generateControllerNames, generateDirectiveNames: generateDirectiveNames, getServiceTemplatePath: getServiceTemplatePath, getControllerTemplatePath: getControllerTemplatePath };
var Promise = require('bluebird') var jm = require('jm-dao') var logger = jm.getLogger('acl') module.exports = function (service, opts) { opts || (opts = {}) opts.modelName || (opts.modelName = 'role') opts.schema || (opts.schema = require('../schema/role')()) var model = jm.dao(opts) jm.enableEvent(model) require('./common')(model) model.on('loading', function () { service.emit('loading', model.modelName) }) model.on('loaded', function () { service.emit('loaded', model.modelName) }) model.__create = model.create var create = function (opts) { return new Promise(function (resolve, reject) { model.__create(opts, function (err, doc) { if (err) { return reject(err, doc) } if (opts.parents) { service.acl.addRoleParents(opts.code, opts.parents, function (_err, _doc) { if (err) { return reject(_err, _doc) } resolve(doc) }) } else { resolve(doc) } if (opts.allows) { for (var i in opts.allows) { var allow = opts.allows[i] service.acl.allow(opts.code, allow.resource, allow.permissions) } } }) }) } model.create = function (opts, cb) { create(opts) .then(function (doc) { cb(null, doc) }) .catch(function (err) { cb(err) }) return this } model.init = function (opts, cb) { var self = this model.remove({}, function (err, doc) { if (err) return cb(err, doc) Promise.map(opts, function (item, index) { return create(item) }).then(function (results) { cb(null, true) service.reloadByName('role') }).catch(function (e) { logger.error(e.stack) cb(null, false) }) }) } var createOrUpdate = function (opts) { return new Promise(function (resolve, reject) { model.findOneAndUpdate({code: opts.code}, opts, {upsert: true, new: true, setDefaultsOnInsert: true}, function (err, doc) { if (err) { return reject(err, doc) } if (opts.parents) { service.acl.addRoleParents(opts.code, opts.parents, function (_err, _doc) { if (err) { return reject(_err, _doc) } resolve(doc) }) } else { resolve(doc) } if (opts.allows) { for (var i in opts.allows) { var allow = opts.allows[i] service.acl.allow(opts.code, allow.resource, allow.permissions) } } }) }) } model.createOrUpdate = function (opts, cb) { Promise.map(opts, function (item, index) { return createOrUpdate(item) }).then(function (results) { cb(null, true) service.reloadByName('role') }).catch(function (e) { logger.error(e && e.stack) cb(e, false) }) } return model }
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var isArray = require('util').isArray; /** * isWholeNumberArray is a utility function that takes an array * it checks if the elements in the array are numbers. * returns true if all elements are js numbers or js string that are numbers * returns false otherwise */ var isWholeNumberArray = function isWholeNumberArray(array) { if (!isArray(array) || !array.length) { return false; } var digitPattern = new RegExp('^\\d+$'), len = array.length, i = 0; for (; i < len; ++i) { if (!digitPattern.test(array[i])) { return false; } } return true; }; exports['default'] = isWholeNumberArray; module.exports = exports['default'];
const express = require('express') const router = express.Router() const User = require('../../models/User').User const Student = require('../../models/Student').Student const Teacher = require('../../models/Teacher').Teacher const mongoose = require('../../libs/mongoose') const db = mongoose.connection const log = require('../../libs/log')(module) router.post('/', (req, res) => { if (!req.body) { res.statusCode = 400 return res.json({success: false, error: 'Missing data'}) } if (!req.body.username) { res.statusCode = 400 return res.json({success: false, error: 'Missing username'}) } if (!req.body.password) { res.statusCode = 400 return res.json({success: false, error: 'Missing password'}) } if (!req.body.firstName) { res.statusCode = 400 return res.json({success: false, error: 'Missing First Name'}) } if (!req.body.lastName) { res.statusCode = 400 return res.json({success: false, error: 'Missing Last Name'}) } if (!req.body.type) { res.statusCode = 400 return res.json({success: false, error: 'Missing type'}) } if (req.body.type !== 'student' && req.body.type !== 'teacher') { res.statusCode = 400 return res.json({success: false, error: 'Wrong type'}) } if (req.body.dateBirthday) { if (new Date(req.body.dateBirthday).getTime() > Date.now()) { res.statusCode = 400 return res.json({success: false, error: 'dateBirthday cannot be more than Date.now()'}) } if (new Date(req.body.dateBirthday).getTime() < new Date(1930, 1, 1).getTime()) { res.statusCode = 400 return res.json({success: false, error: 'dateBirthday cannot be less than 1930 year'}) } } User.find({username: req.body.username}) .then(users => { if (!users) { res.statusCode = 404 throw new Error('Cannot find users') } if (users.length > 0) { res.statusCode = 400 throw new Error('registration.error.username.exist') } if (req.body.type === 'teacher') { let teacher = new Teacher({ username: req.body.username, password: req.body.password, email: req.body.email ? req.body.email : null, firstName: req.body.firstName, lastName: req.body.lastName, type: req.body.type, secondName: req.body.secondName ? req.body.secondName : null, phoneNumber: req.body.phoneNumber ? req.body.phoneNumber : null, dateBirthday: req.body.dateBirthday ? new Date(req.body.dateBirthday).getTime() : null, //TODO: ????????? ????????? ???? ? ??????? avatar: req.body.avatar ? req.body.avatar : null }) return [teacher.save(), null] } if (req.body.type === 'student') { if (!req.body.idTeacher) { res.statusCode = 400 throw new Error('Missing teacher id') } let student = new Student({ username: req.body.username, password: req.body.password, email: req.body.email ? req.body.email : null, firstName: req.body.firstName, lastName: req.body.lastName, type: req.body.type, secondName: req.body.secondName ? req.body.secondName : null, phoneNumber: req.body.phoneNumber ? req.body.phoneNumber : null, dateBirthday: req.body.dateBirthday ? new Date(req.body.dateBirthday).getTime() : null, avatar: req.body.avatar ? req.body.avatar : null }) return [student, Teacher.findById(req.body.idTeacher)] } }) .spread((user, teacher) => { if (req.body.type !== 'student') { return user } if (!teacher) { res.statusCode = 400 throw new Error('Teacher doesn\'t exist') } user.idTeacher = teacher._id return user.save() }) .then(user => { if (!user) { res.statusCode = 404 throw new Error('Cannot find user') } log.info(`User id: ${user.userId} with name ${user.username} was added`) res.statusCode = 201 return res.json({success: true}) }) .catch(err => { log.error(err.message) if (res.statusCode === 200) { res.statusCode = 500 } return res.json({success: false, error: err.message}) }) }) router.get('/', (req, res) => { db.collection('users').find({ [req.query.firstName ? 'firstName' : '']: req.query.name ? new RegExp(req.query.name, 'i') : undefined, [req.query.lastName ? 'lastName' : '']: req.query.name ? new RegExp(req.query.name, 'i') : undefined, [req.query.type ? 'type' : '']: req.query.type ? new RegExp(req.query.type, 'i') : undefined, [req.query.approved ? 'approved' : '']: req.query.approved ? req.query.approved === 'true' : undefined }).toArray((err, users) => { if (err) { log.error(err) res.statusCode = 500 res.send({error: err.message}) return res.end() } res.send(users) return res.end() }) }) module.exports = router
var mutil = require('miaow-util'); module.exports = function (root, module) { return module.url || mutil.relative(root, module.destAbsPathWithHash) .replace(/\.js$/, ''); };
module.exports = require('./lib/bayon.js');
async = require("async"); // Helper library to handle populating nested associations var allowed_tables = { "possibleanswers": _PopulatePossibleAnswers, "checkins": _PopulateCheckins, "classbonuses": _PopulateClassBonuses, "roles": _PopulateRoles }; function PopulateExtrasException(message) { this.message = message; this.name = "PopulateExtrasException"; }; function _PopulatePossibleAnswers(reval, nexts, quit) { // add class_bonuses set_to_populate = null; if ( typeof(reval) != "undefined" ) { if ( typeof(reval.possible_answers) != "undefined" && reval.possible_answers.length > 0 ) { set_to_populate = reval.possible_answers; } if ( typeof(reval.questions) != "undefined" && reval.questions.length > 0 ) { set_to_populate = reval.questions; } } if (set_to_populate != null) { var counter = 0; set_to_populate.forEach(function (element) { element._possible_answers = []; PossibleAnswers.find({where: {question_id: element.id}}).exec(function (err, possibleAnswers) { if ( possibleAnswers.length != 0 ) { possibleAnswers.forEach(function (each_possible) { delete each_possible.createdAt; delete each_possible.updatedAt; delete each_possible.question_id; element._possible_answers.push(each_possible); }); } counter += 1; if ( counter == set_to_populate.length ) { if (nexts.length == 0) { quit(); } else { next = nexts.pop(); next(reval, nexts, quit); } } }); }); } else { if (nexts.length == 0) { quit(); } else { next = nexts.pop(); next(reval, nexts, quit); } } }; function _PopulateCheckins(reval, nexts, quit) { // add checkins if ( typeof(reval) != "undefined" && typeof(reval.checkins) != "undefined" && reval.checkins.length > 0 ) { reval._checkins = []; reval.checkins.forEach(function(element) { reval._checkins.push(element.date_scanned); }); } if (nexts.length == 0) { quit(); } else { next = nexts.pop(); next(reval, nexts, quit); } } function _PopulateClassBonuses(reval, nexts, quit) { // add class_bonuses if ( typeof(reval) != "undefined" && typeof(reval.class_bonuses) != "undefined" && reval.class_bonuses.length > 0 ) { reval._class_bonuses = []; var counter = 0; reval.class_bonuses.forEach(function (element) { ClassBonus.find({where: {id: element.class_bonus_id}}).exec(function (err, bonus) { if ( bonus.length != 0 ) { delete bonus[0].id; delete bonus[0].createdAt; delete bonus[0].updatedAt; bonus[0].class_bonus_id = element.class_bonus_id; reval._class_bonuses.push(bonus[0]); } counter += 1; if ( counter == reval.class_bonuses.length ) { if (nexts.length == 0) { quit(); } else { next = nexts.pop(); next(reval, nexts, quit); } } }); }); } else { if (nexts.length == 0) { quit(); } else { next = nexts.pop(); next(reval, nexts, quit); } } } function _PopulateRoles(reval, nexts, quit) { if ( typeof(reval) != "undefined" && typeof(reval.roles) != "undefined" && reval.roles.length > 0 ) { reval._roles = []; var counter = 0; reval.roles.forEach(function (element) { Roles.find({where: {id: element.role_id}}).exec(function (err, role) { if (role.length != 0) { reval._roles.push(role[0].name); } counter += 1; if (counter == reval.roles.length) { if (nexts.length == 0) { quit(); } else { next = nexts.pop(); next(reval, nexts, quit); } } }); }); } else { if (nexts.length == 0) { quit(); } else { next = nexts.pop(); next(reval, nexts, quit); } } } // Wrapper function for populate call all tables function PopulateAll(rows, cb) { Populate(rows, Object.keys(allowed_tables), cb); } function Populate(rows, tables, cb) { func_chain = []; if ( ! Array.isArray(rows) ) { func_chain.push(cb); } if (Array.isArray(tables)) { tables.forEach( function (element) { if (element in allowed_tables) { func_chain.push(allowed_tables[element]); } else { throw new PopulateExtraException(element + " is not an accepted column"); } }); } else { throw new PopulateExtraException("Tables is not a array"); } start = func_chain.pop(); if (Array.isArray(rows)) { async.eachSeries(rows, function (each_row, callback){ func_chain_copy = func_chain.slice(0); start(each_row, func_chain_copy, callback); }, function (err) { if (err) { console.log(err); } cb(rows); }); } else { start(rows, func_chain); } } module.exports = { PopulateAll: PopulateAll, Populate: Populate, AllowedTables: Object.keys(allowed_tables), };
export class Board { // Sets up wins, rows and cells fro game; constructor() { // setup the square array for external use this.rows = []; // winning combos this.wins = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]; // sets up the cells this.setupCells(); // shows the winner or tie this.gameEnd; } // Method to set 3 rows of 3 squares setupCells() { for (var i = 0; i < 3; i++) { this.rows.push([]); for (var j = 0; j < 3; j++) { this.rows[i].push(null); } } return true; } // Method to select a cell selectCell(row, col, shape, turn) { if (this.rows[row][col] === null) { this.rows[row][col] = shape; return true; } else { console.log('cell taken'); return false; } } // Evaluation of board for win and full evaluate(playerShape) { var flatBoard = this.flatten(); // see if there is a winner if (!this.isWin(playerShape, flatBoard)) { // no winner yet // is the board full? if (!this.isFull(flatBoard)) { // nope! -> next player's turn return true; } else { this.gameEnd = 'Tied!'; } } else { this.gameEnd = 'Computer win'; } } // Flattens the board for easier evaluation flatten() { var flat = []; var reduction = this.rows.reduce(function(a, b) { return a.concat(b);}); for (var i = 0; i < reduction.length; i++) { flat.push(reduction[i]); } return flat; } // Maps the flattend location to board location mapKeyToCell(key) { for (var i = 0; i < this.rows.length; i++) { for (var j = 0; j < this.rows[i].length; j++) { if (i * 3 + j === key) { return [i, j]; } } } } // TODO: Abstract these two functions - duplicated in MiniMax // Check the mapped cells against the winning combos isWin(player, board) { for (var i = 0; i < this.wins.length; i++) { if(board[this.wins[i][0]] == player && board[this.wins[i][1]] == player && board[this.wins[i][2]] == player) { return true; } } return false; } // A check to see if the board is full isFull(board) { for (var i = 0; i < board.length; i++) { if (board[i] == null) { return false; } } return true; } }
var LinksObserver = (function () { 'use strict'; let callbacks = new Set(); let links = new Set(); // Create a set of all tab-enabled elements that are not document.body. function getLinks() { var elements = document.body.querySelectorAll('*'); for (var el of elements) { if (el.tabIndex !== -1 && el !== document.body) { links.add(el); } } } // Send links to all callbacks/listeners. function invokeCallbacks() { callbacks.forEach(cb => { cb(links); }); } let observer = new MutationObserver(mutations => { mutations.forEach(record => { for (let node of record.addedNodes) { if (node.tabIndex !== -1) { links.add(node); } } for (let node of record.removedNodes) { if (node.tabIndex !== -1) { links.delete(node); } } invokeCallbacks(); }) }); let config = { childList: true, attributes: true, subtree: true, characterData: true }; function connect(callback) { if (!callbacks.has(callback)) { callbacks.add(callback); if (callbacks.size === 1) { getLinks(); observer.observe(document.body, config); invokeCallbacks(); } } } function disconnect(callback) { if (callbacks.has(callback)) { callbacks.devare(callback); if (callbacks.size === 0) { observer.disconnect(); links.clear(); } } } return { connect, disconnect }; }());
var ThreadWatcher = require('../../lib/2ch').ThreadWatcher, watcher = new ThreadWatcher('番組ch(NHK)', /NHK総合を常に実況し続けるスレ/, 5000), loaded = false; watcher.on('update', function(messages) { if (!loaded) { loaded = true; return; } messages.forEach(function(message) { console.log( message.number, message.name.replace(/<[^<>]+>/g, ''), message.postedAt.format('YYYY/MM/DD HH:mm:ss'), // moment object. message.tripId, message.body.replace(/<[^<>]+>/g, '') ); }); }); watcher.on('error', function(error) { console.log(error); watcher.stop(); }); watcher.on('reload', function(title) { console.log(title, 'のスレッドが再読込されました'); loaded = false; }); watcher.on('begin', function(title) { console.log(title, 'のスレッドが開始しました'); }); watcher.on('end', function(title) { console.log(title, 'のスレッドが終了しました'); }); watcher.start();
var User = require('../models/user'); module.exports = { /* * logs in the user * @param req the request the user sends * @param res the response that the user recieves */ login: function (req, res) { var name = req.body.name; var password = req.body.password; User.findOne({ name: name }, function (err, user) { if (err) { console.log(err); res.render('error', {message: "Please try again later."}); } else if (user === null) { res.render('error', {message: "Username not found"}); } else { user.checkPassword(password, function (match) { if (!match) { res.render('error', {message: "Invalid password"}); } else { // save user cookie, show all tweets req.session.name = user.name; req.session.userID = user.id; req.session.save(function (err) { res.redirect('/allTweets'); }); } }); } }); }, /* * registers new users * @param req the request the user sends * @param res the response that the user recieves */ register: function (req, res) { var name = req.body.name; var password = req.body.password; if (name.length < 1 || password.length < 1) { res.render('error', {message: "Please do not leave any fields blank"}); } var user = new User({ name: name, password: password}); user.save(function (err, user) { if (err) { if (err.code === 11000) { res.render('error', {message: "This name is taken"}); } else { console.log(err); res.render('error', {message: "Please try again later"}); } } else { // success! redirect to feed req.session.name = user.name; req.session.userID = user.id; req.session.save(function (err) { res.redirect('/allTweets'); }); } }); }, /* * logs out logged in users * @param req the request the user sends * @param res the response that the user recieves */ logout: function (req, res) { req.session.destroy(function (err) { if (err) { console.log(err); res.render('error', {message: "Can't currently log out, please try again"}); } else { res.render('login', {user: "express"}); } }); }, /* * gets the user profile that displays a list of their own tweets and users they don't follow * @param req the request the user sends * @param res the response that the user recieves */ getProfile: function (req, res) { var name = req.session.name; User.findOne({ name: name }, function (err, user) { if (err) { return res.render('error', {message: "Can't access profile, please try again"}); } user.getOwnTweets(function (err, ownTweets) { if (err) { console.log(err); return res.render('error', {message: "can't get own tweet"}); } user.getNotFollowing(function (err, notFollowed) { if (err) { return res.render('error', {message: "can't get not following users"}); } return res.render('profile', {user: name, tweetsList: ownTweets, tweeterList: notFollowed}); }); }); }); }, /* * gets either all tweets or following tweets * @param req the request the user sends * @param res the response that the user recieves */ getTweets: function (req, res, isFollowingOnly) { var error = req.query.error; var success = req.query.success; var name = req.session.name; if (name === undefined) { return res.render('error', {message: "Please log in"}); } User.findOne({ name: name }, function (err, user) { if (err || user === null) { console.error(err); res.render('error', {message: "Please try again"}); } else { if (isFollowingOnly) { User.getFollowingTweets(name, function (err, tweets) { if (err) { console.error(err); res.render('error', {message: "Please try again"}); } else { res.render('index', {user: name, tweetsList: tweets}); } }); } else { User.getAllTweets(function (err, tweets) { if (err) { console.error(err); res.render('error', {message: "Please try again"}); } else { res.render('index', {user: name, tweetsList: tweets}); } }); } } }); }, /* * follows another user * @param req the request the user sends * @param res the response that the user recieves */ follow: function (req, res) { var name = req.session.name; var userIDToFollow = req.body.tweetAuthorID; var follow = req.body.follow === "true"; // boolean- follow or unfollow User.follow(name, userIDToFollow, follow, function (err) { if (err) { console.error(err); res.render('error', {message: "Please try again"}); } else { res.redirect('back'); } }); } };
// Generated by CoffeeScript 1.7.1 $(function() { test("a basic test example", function() { var value; ok(true, "this test is fine"); value = "hello"; return equal("hello", value, "We expect value to be hello"); }); test("getItemData", function() { var logic; logic = h5.core.logic(ItemSearchController.itemSearchLogic); return logic._getItemData(1).then(function(data) { return equal(data.length, 20, "We expect data length is 20."); }); }); return test("getItemList", function() { var logic; logic = h5.core.logic(ItemSearchController.itemSearchLogic); return logic.getItemList(1).then(function(data1) { equal(data1.length, 20, "We expect data length is 20."); return logic._getItemData(1).then(function(data2) { return equal(data1.length, data2.length, "We expect data1 length is equal to data2 length"); }); }); }); });
'use strict'; let jwt = require('jsonwebtoken'), secrets = require('../../../config').secrets; /* * Verify that the decoded json web token includes an * unique identifier (jit) and that this identifier is * the same than the user token id. */ module.exports = function(model) { let payload = jwt.decode(model.token); return jwt.verify(model.token, secrets.jwt) && (payload.jit === model.token_id || payload.jit === model.id); };
import { resolverForGivenFunction, dataObjBuilder, metaFunctionBuilder } from './core.js' import { dataDefaults } from './defaults.js' export default function AsyncDataMixinBuilder(dataGlobalDefaults, meta) { const metaRefresh = metaFunctionBuilder('refresh', meta) const metaLoading = metaFunctionBuilder('loading', meta) const metaError = metaFunctionBuilder('error', meta) const metaDefault = metaFunctionBuilder('default', meta) const metaMore = metaFunctionBuilder('more', meta) const metaReset = metaFunctionBuilder('reset', meta) const metas = { metaLoading, metaError, metaDefault, metaReset } return { beforeCreate() { let properties = this.$options.asyncData || {} let methods = this.$options.methods = this.$options.methods || {} for (const [propName, prop] of Object.entries(properties)) { const opt = dataDefaults(prop, dataGlobalDefaults) if (!opt.get) throw `An asyncData was created without a get method: ${opt}` methods[metaRefresh(propName)] = resolverForGivenFunction.call(this, propName, metas, opt.get, opt.default, opt.transform, opt.error) // load more stuff if (opt.more) { methods[metaMore(propName)] = resolverForGivenFunction.call(this, propName, metas, opt.more.get, opt.default, opt.transform, opt.error, opt.more.concat) } } }, // for all non lazy properties, call refresh methods beforeMount() { const properties = this.$options.asyncData || {} for (const [propName, prop] of Object.entries(properties)) { const opt = dataDefaults(prop, dataGlobalDefaults) if (!opt.lazy) { this[metaRefresh(propName)]() } } }, data() { return dataObjBuilder(this.$options.asyncData, metas, false) } }}
'use strict'; module.exports = function(grunt) { grunt.config('watch', { test: { files: ['src/**/*.js', 'test/tests/**/*.js'], tasks: ['mochaTest:runDry'], options: { interrupt: true, }, }, }); grunt.loadNpmTasks('grunt-contrib-watch'); };
(function () { function load() { if (!window.ontando_scriptLoader) { setTimeout(load, 500); } else { var loadRemoteAsync = window.ontando_scriptLoader.loadRemoteAsync; // Loading tools loadRemoteAsync("devTools/loaderConfig.js"); } } $(document).ready(load); })();
import togglable from 'patterns/tx-togglable'; const ACTIVE_CLASS_NAME_SUFFIX = '-is-active'; export default function offscreenNav(toggleID, navigationID) { let navigation; let activeClassName; function toggleNavigation() { navigation.classList.toggle(activeClassName); } const toggle = document.getElementById(toggleID); navigation = document.getElementById(navigationID); activeClassName = `${navigationID}${ACTIVE_CLASS_NAME_SUFFIX}`; return togglable(toggle, toggleNavigation); }
/* eslint-disable import/no-extraneous-dependencies */ import Vue from 'vue'; import Router from 'vue-router'; import pages from './pages'; Vue.use(Router); const routes = pages.map((page) => { const { name } = page; return { path: `/${name}`, name, component: page, }; }); routes.push({ path: '*', redirect: '/demo-basic', }); export default new Router({ routes });
'use strict'; var angular = require('angular'); var template = require('./template.html'); angular.module('Application') .directive('sidebarMeasures', [ 'Configuration', function(Configuration) { return { template: template, replace: false, restrict: 'E', scope: { measures: '=', params: '=' }, link: function($scope) { $scope.$on(Configuration.events.sidebar.listItemChange, function($event, item, isSelected, listKey) { $event.stopPropagation(); $scope.$emit(Configuration.events.sidebar.changeMeasure, item.key); }); } }; } ]);
describe('convolutional layer: SeparableConv2D', function() { const assert = chai.assert const styles = testGlobals.styles const logTime = testGlobals.logTime const stringifyCondensed = testGlobals.stringifyCondensed const approxEquals = KerasJS.testUtils.approxEquals const layers = KerasJS.layers const testParams = [ { inputShape: [5, 5, 2], attrs: { filters: 4, kernel_size: [3, 3], strides: [1, 1], padding: 'valid', data_format: 'channels_last', depth_multiplier: 1, activation: 'linear', use_bias: true } }, { inputShape: [5, 5, 2], attrs: { filters: 4, kernel_size: [3, 3], strides: [1, 1], padding: 'valid', data_format: 'channels_last', depth_multiplier: 2, activation: 'relu', use_bias: true } }, { inputShape: [5, 5, 4], attrs: { filters: 16, kernel_size: [3, 3], strides: [1, 1], padding: 'valid', data_format: 'channels_last', depth_multiplier: 3, activation: 'relu', use_bias: true } }, { inputShape: [5, 5, 2], attrs: { filters: 4, kernel_size: [3, 3], strides: [2, 2], padding: 'valid', data_format: 'channels_last', depth_multiplier: 1, activation: 'relu', use_bias: true } }, { inputShape: [5, 5, 2], attrs: { filters: 4, kernel_size: [3, 3], strides: [1, 1], padding: 'same', data_format: 'channels_last', depth_multiplier: 1, activation: 'relu', use_bias: true } }, { inputShape: [5, 5, 2], attrs: { filters: 4, kernel_size: [3, 3], strides: [1, 1], padding: 'same', data_format: 'channels_last', depth_multiplier: 2, activation: 'relu', use_bias: false } }, { inputShape: [5, 5, 2], attrs: { filters: 4, kernel_size: [3, 3], strides: [2, 2], padding: 'same', data_format: 'channels_last', depth_multiplier: 2, activation: 'relu', use_bias: true } } ] before(function() { console.log('\n%cconvolutional layer: SeparableConv2D', styles.h1) }) /********************************************************* * CPU *********************************************************/ describe('CPU', function() { before(function() { console.log('\n%cCPU', styles.h2) }) testParams.forEach(({ inputShape, attrs }, i) => { const key = `convolutional.SeparableConv2D.${i}` const title = `[${key}] [CPU] test: ${attrs.filters} ${attrs.kernel_size} filters on ${inputShape} input, strides=${attrs.strides}, padding='${attrs.padding}', data_format='${attrs.data_format}', depth_multiplier=${attrs.depth_multiplier}, activation='${attrs.activation}', use_bias=${attrs.use_bias}` it(title, function() { console.log(`\n%c${title}`, styles.h3) let testLayer = new layers.SeparableConv2D(attrs) testLayer.setWeights(TEST_DATA[key].weights.map(w => new KerasJS.Tensor(w.data, w.shape))) let t = new KerasJS.Tensor(TEST_DATA[key].input.data, TEST_DATA[key].input.shape) console.log('%cin', styles.h4, stringifyCondensed(t.tensor)) const startTime = performance.now() t = testLayer.call(t) const endTime = performance.now() console.log('%cout', styles.h4, stringifyCondensed(t.tensor)) logTime(startTime, endTime) const dataExpected = new Float32Array(TEST_DATA[key].expected.data) const shapeExpected = TEST_DATA[key].expected.shape assert.deepEqual(t.tensor.shape, shapeExpected) assert.isTrue(approxEquals(t.tensor, dataExpected)) }) }) }) /********************************************************* * GPU *********************************************************/ describe('GPU', function() { before(function() { console.log('\n%cGPU', styles.h2) }) testParams.forEach(({ inputShape, attrs }, i) => { const key = `convolutional.SeparableConv2D.${i}` const title = `[${key}] [GPU] test: ${attrs.filters} ${attrs.kernel_size} filters on ${inputShape} input, strides=${attrs.strides}, padding='${attrs.padding}', data_format='${attrs.data_format}', depth_multiplier=${attrs.depth_multiplier}, activation='${attrs.activation}', use_bias=${attrs.use_bias}` it(title, function() { console.log(`\n%c${title}`, styles.h3) let testLayer = new layers.SeparableConv2D(Object.assign(attrs, { gpu: true })) testLayer.setWeights(TEST_DATA[key].weights.map(w => new KerasJS.Tensor(w.data, w.shape))) let t = new KerasJS.Tensor(TEST_DATA[key].input.data, TEST_DATA[key].input.shape) console.log('%cin', styles.h4, stringifyCondensed(t.tensor)) const startTime = performance.now() t = testLayer.call(t) const endTime = performance.now() console.log('%cout', styles.h4, stringifyCondensed(t.tensor)) logTime(startTime, endTime) const dataExpected = new Float32Array(TEST_DATA[key].expected.data) const shapeExpected = TEST_DATA[key].expected.shape assert.deepEqual(t.tensor.shape, shapeExpected) assert.isTrue(approxEquals(t.tensor, dataExpected)) }) }) }) })
// All symbols in the `Samaritan` script as per Unicode v5.2.0: [ '\u0800', '\u0801', '\u0802', '\u0803', '\u0804', '\u0805', '\u0806', '\u0807', '\u0808', '\u0809', '\u080A', '\u080B', '\u080C', '\u080D', '\u080E', '\u080F', '\u0810', '\u0811', '\u0812', '\u0813', '\u0814', '\u0815', '\u0816', '\u0817', '\u0818', '\u0819', '\u081A', '\u081B', '\u081C', '\u081D', '\u081E', '\u081F', '\u0820', '\u0821', '\u0822', '\u0823', '\u0824', '\u0825', '\u0826', '\u0827', '\u0828', '\u0829', '\u082A', '\u082B', '\u082C', '\u082D', '\u0830', '\u0831', '\u0832', '\u0833', '\u0834', '\u0835', '\u0836', '\u0837', '\u0838', '\u0839', '\u083A', '\u083B', '\u083C', '\u083D', '\u083E' ];
/** @namespace lsn.forms */ ECMAScript.Extend('lsn.forms', function (ecma) { var CInputBase = this.InputBase; var _proto = ecma.lang.createPrototype(CInputBase); /** * @class InputBoolean */ this.InputBoolean = function (elem) { CInputBase.apply(this, [elem]); this.value = this.emptyValue = new Boolean(); }; this.InputBoolean.prototype = _proto; _proto.marshal = function (dataValue) { try { return dataValue.valueOf() ? 1 : 0; } catch (ex) { js.console.log(ex); return 0; } }; _proto.unmarshal = function (ctrlValue) { return new Boolean(ecma.util.asInt(ctrlValue)); }; _proto.deserialize = function (storedValue) { this.setValue(new Boolean(ecma.util.asInt(storedValue))); return this; }; _proto.serialize = function () { return this.getValue().valueOf() ? '1' : '0'; }; });
var express = require("express"), router = express.Router(), User = require('../models/user'); router.get("/:userId/followeralert", (req, res) => { if (req.params.userId) { User.findById(req.params.userId, (err, user) => { if(err) return; res.render("followeralert", { defaults: res.locals, token: user.token }); }); }else{ } }); module.exports = router;
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.chrome_extension_reload = { setUp: function(done) { // setup here if necessary done(); }, default_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/default_options'); var expected = grunt.file.read('test/expected/default_options'); test.equal(actual, expected, 'should describe what the default behavior is.'); test.done(); }, custom_options: function(test) { test.expect(1); var actual = grunt.file.read('tmp/custom_options'); var expected = grunt.file.read('test/expected/custom_options'); test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); test.done(); }, };
import React from 'react'; import PropTypes from 'prop-types'; import generateId from 'extensions/generateId'; import Skeleton from 'skeletons/Skeleton'; import * as styles from './styles'; /** * A simple `Toggle` component thta can be turned on and off. Use `checked` to set * whether the `Toggle` is selected. */ class Toggle extends React.PureComponent { static propTypes = { /** * Adds a class name to the input element. */ className: PropTypes.string, /** * Adds an id to the input element. */ id: PropTypes.string, /** * The literal value this toggle represents. For example, if this toggle * represents whether the app is in "Dark Mode", you might provide "darkMode" * to this prop to represent that value key. */ value: PropTypes.string, /** * Whether the toggle is 'on' or 'off'. */ checked: PropTypes.bool, /** * Whether the toggle is required for form submission. */ required: PropTypes.bool, /** * Whether the user is prevented from interacting with the toggle. */ disabled: PropTypes.bool, /** * Adds a name to the underlying input. */ name: PropTypes.string, /** * A description to display next to the toggle. */ description: PropTypes.node, /** * Callback for the onChange event of the input. */ onChange: PropTypes.func, /** * A component to render the container around the toggle and label */ Container: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), /** * A component to render the input element, usually hidden */ Input: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), /** * A component to render the label, which usually also renders the toggle itself */ Label: PropTypes.oneOfType([PropTypes.func, PropTypes.object]), }; static defaultProps = { className: "scl-toggle", id: null, value: undefined, checked: undefined, name: null, required: false, disabled: false, description: null, onChange: () => null, Container: styles.Container, Input: styles.Input, Label: styles.Label, }; static styles = styles; defaultId = generateId('toggle'); render() { const { className, disabled, required, name, description, onChange, Container, Input, Label, id, value, checked, ...rest } = this.props; const finalId = id || this.defaultId; return ( <Container> <Input id={finalId} className={className} name={name} type="checkbox" disabled={disabled} checked={checked} value={value} required={required} onChange={onChange} {...rest} /> <Label htmlFor={finalId}>{description}</Label> </Container> ); } } Toggle.Skeleton = props => ( <Toggle Input={() => <Skeleton width="58px" height="30px" />} Label={() => ( <Skeleton style={{ marginLeft: '15px' }} width="150px" height="30px" /> )} {...props} /> ); export default Toggle;
'use strict'; // Init the application configuration module for AngularJS application var ApplicationConfiguration = (function() { // Init module configuration options var applicationModuleName = 'indsa'; var applicationModuleVendorDependencies = ['ngResource', 'ui.router', 'ui.bootstrap', 'ui.utils']; // Add a new vertical module var registerModule = function(moduleName, dependencies) { // Create angular module angular.module(moduleName, dependencies || []); // Add the module to the AngularJS configuration file angular.module(applicationModuleName).requires.push(moduleName); }; return { applicationModuleName: applicationModuleName, applicationModuleVendorDependencies: applicationModuleVendorDependencies, registerModule: registerModule }; })();
#!/usr/bin/env node 'use strict'; var app = require(__dirname + '/../lib/index.js'); var arg = process.argv[2]; var fs = require('fs'); var data = fs.readFileSync(arg, 'utf8'); console.log(app.createItems(data));
import React from 'react'; import PropTypes from 'prop-types'; import RefHolder from '../models/ref-holder'; import GitTabContainer from '../containers/git-tab-container'; export default class GitTabItem extends React.Component { static propTypes = { repository: PropTypes.object.isRequired, } static uriPattern = 'atom-github://dock-item/git' static buildURI() { return this.uriPattern; } constructor(props) { super(props); this.refController = new RefHolder(); } render() { return ( <GitTabContainer controllerRef={this.refController} {...this.props} /> ); } serialize() { return { deserializer: 'GitDockItem', uri: this.getURI(), }; } getTitle() { return 'Git'; } getIconName() { return 'git-commit'; } getDefaultLocation() { return 'right'; } getPreferredWidth() { return 400; } getURI() { return this.constructor.uriPattern; } getWorkingDirectory() { return this.props.repository.getWorkingDirectoryPath(); } // Forwarded to the controller instance when one is present rememberLastFocus(...args) { return this.refController.map(c => c.rememberLastFocus(...args)); } restoreFocus(...args) { return this.refController.map(c => c.restoreFocus(...args)); } hasFocus(...args) { return this.refController.map(c => c.hasFocus(...args)); } focus() { return this.refController.map(c => c.restoreFocus()); } focusAndSelectStagingItem(...args) { return this.refController.map(c => c.focusAndSelectStagingItem(...args)); } focusAndSelectCommitPreviewButton() { return this.refController.map(c => c.focusAndSelectCommitPreviewButton()); } quietlySelectItem(...args) { return this.refController.map(c => c.quietlySelectItem(...args)); } focusAndSelectRecentCommit() { return this.refController.map(c => c.focusAndSelectRecentCommit()); } }
importScripts('/poc/orbits/javascripts/geometry/vector3.js'); (function () { var root = this, P = (root.P = {}); P.R = 7000000; // Polar unit vector var ax = 0.423, ay = 0, az = 0.906; // fixed vector var polar = V3.build(ax, ay, az); P.polar = polar; // Base unit vector for long = 0, lat = 0 var bx = 0, by = 1, bz = 0; // change over lday var base = V3.build(bx, by, bz); function equiZero(lday) {// lday: local time var phi = - 2 * Math.PI * (lday - Math.floor(lday)); var cos = Math.cos(phi), sin = Math.sin(phi); //by Rodrigues' rotation formula return V3.add(V3.expand(base, cos), V3.expand(V3.cross(polar, base), sin)); } P.equiZero = equiZero; // The normal unit vector for any point on the surface function vector(lng, lat, lday) { var equo = equiZero(lday); var cos = Math.cos(lng), sin = Math.sin(lng); var temp = V3.add(V3.expand(equo, cos), V3.expand(V3.cross(polar, equo), sin)); var axis = V3.cross(polar, temp); cos = Math.cos(lat); sin = Math.sin(lat); var vec = V3.add(V3.expand(temp, cos), V3.expand(V3.cross(axis, temp), sin)); return vec; } P.norm = vector; function cut(val) { return val > 0 ? val : 0; } P.evolve = function (progress, delta, orbit) { progress("calculating day and night on planet..."); return { light1: function (lng, lat) { return orbit.l1 * cut(V3.inner(vector(lng, lat, delta.lday), orbit.u31)); }, light2: function (lng, lat) { return orbit.l2 * cut(V3.inner(vector(lng, lat, delta.lday), orbit.u32)); }, light: function (lng, lat) { return orbit.l1 * cut(V3.inner(vector(lng, lat, delta.lday), orbit.u31)) + orbit.l2 * cut(V3.inner(vector(lng, lat, delta.lday), orbit.u32)); } }; }; })();
/** * Route Mappings * (sails.config.routes) * * Your routes map URLs to views and controllers. * * If Sails receives a URL that doesn't match any of the routes below, * it will check for matching files (images, scripts, stylesheets, etc.) * in your assets directory. e.g. `http://localhost:1337/images/foo.jpg` * might match an image file: `/assets/images/foo.jpg` * * Finally, if those don't match either, the default 404 handler is triggered. * See `api/responses/notFound.js` to adjust your app's 404 logic. * * Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies * flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or * CoffeeScript for the front-end. * * For more information on configuring custom routes, check out: * http://sailsjs.org/#!/documentation/concepts/Routes/RouteTargetSyntax.html */ module.exports.routes = { /*************************************************************************** * * * Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, * * etc. depending on your default view engine) your home page. * * * * (Alternatively, remove this and add an `index.html` file in your * * `assets` directory) * * * ***************************************************************************/ '/': { view: 'layout' }, /** * APIs */ 'GET /posts': 'PostController.getPosts', 'POST /post': 'PostController.createPost', 'POST /post-comment': 'PostController.commentToPost' /*************************************************************************** * * * Custom routes here... * * * * If a request to a URL doesn't match any of the custom routes above, it * * is matched against Sails route blueprints. See `config/blueprints.js` * * for configuration options and examples. * * * ***************************************************************************/ };
'use strict'; /* jshint -W098 */ angular.module('mean.moviescode').controller('MoviescodeController', ['$scope', 'Global', 'Moviescode', function($scope, Global, Moviescode) { $scope.global = Global; $scope.package = { name: 'moviescode' }; } ]);
define([ 'soundcloud', 'backbone', 'c/favourites', 'constants' ], function( SC, Backbone, FavouritesCollection, c ){ return Backbone.Model.extend({ defaults: { favourites: null }, url: function() { return '/me'; }, initialize: function() { _.extend(this, this.options); }, fetch: function() { var def = new $.Deferred(), _this = this, favourites = []; SC.initialize(c('clientAuth')); SC.connect(function() { SC.get('/me', function(user) { _this.set(user); window.localStorage.setItem('scUser', JSON.stringify(user)); console.log('User ' + _this.get('username') + ' fetched'); getFaves = function(userId, limit) { var i = 0, count = 0, pageSize = 200, url = '/users/' + userId + '/favorites.json', defs = [], goGet = function(pageSize, offset, dfd) { SC.get(url, { limit: pageSize, offset: offset }, function(resp) { favourites = favourites.concat(resp); dfd.resolve(); // returning from the fn fixed the $.when block return; }); }; while( i <= limit ) { var d = new $.Deferred(); goGet(pageSize, i, d); defs.push(d.promise()); i += pageSize; count++; } // return the array of deferreds return defs; }; var promises = getFaves(_this.get('id'), _this.get('public_favorites_count')); $.when.apply($, promises).done(function() { window.localStorage.setItem('favourites', JSON.stringify(favourites)); _this.set('favourites', new FavouritesCollection()); _this.get('favourites').reset(favourites); console.log(_this.get('favourites').length + ' favourites fetched'); def.resolve(); }); }); }); return def.promise(); } }); });
'use strict'; module.exports = function(req, res, next) { if (req.locals.result) { res.status(200); res.send(req.locals.result); } else { next(); } }
var inherits; if (typeof Object.create === 'function'){ inherits = function inherits(ctor, superCtor) { // implementation from standard node.js 'util' module ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { inherits = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } export default inherits; // module.exports = inherits; // export default inherits;
/** * Mock a simple plugin that takes a file input and just strips any linebreak * or return characters. */ module.exports = function() { return require('through2').obj(function ( targetFile, encoding, done ) { targetFile.contents = new Buffer( targetFile.contents.toString().replace(/\r?\n|\r/g, '') ); this.push(targetFile); done(); }); };
var winston = require('winston'); winston.loggers.add('http_access',{ file: { filename: process.cwd()+'/logs/http_access.log' } }); winston.loggers.add('newUsers',{ file: { filename: process.cwd()+'/logs/newUsers.log' } }); winston.loggers.add('notifies',{ file: { filename: process.cwd()+'/logs/notifies.log' } }); winston.loggers.add('errors',{ file: { filename: process.cwd()+'/logs/errors.log' } }); var httpLog = winston.loggers.get('http_access'), newUserLog = winston.loggers.get('newUsers'), notifyLog = winston.loggers.get('notifies'), errorLog = winston.loggers.get('errors'); exports.name = 'kabamPluginLoggerFile'; exports.listeners = { 'http' : httpLog.info, 'error': errorLog.error, //logging errors //logging new users 'users:signUp': newUserLog.info, 'users:signUpByEmailOnly': newUserLog.info, 'users:completeProfile': newUserLog.info, 'users:findOneByApiKeyAndVerify': newUserLog.info, //logging roles managment - todo - create proper security logging for it 'users:revokeRole': function(){}, 'users:grantRole': function(){}, //notifications 'notify:email': notifyLog.info, 'notify:sio': notifyLog.info };
import { combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux'; import auth from './auth'; export default combineReducers({ router: routerReducer, auth, });
import reducer from '../../src/reducers/NavigationReducer'; import * as types from '../../src/actions/types'; describe('navigation reducer', () => { it('should return the initial state', () => { expect(reducer(undefined, {})).toEqual( { leftClicked: false, rightClicked: false, currentView: '', updateAchievementsView: false, updateProfileView: false, updateHighscoreView: false } ); }); it('should click left', () => { expect( reducer([], { type: types.LEFT_CLICK, payload: { show: true, view: 'view' } }) ).toEqual( { leftClicked: true, currentView: 'view' } ); }); it('should click right', () => { expect( reducer([], { type: types.RIGHT_CLICK, payload: { show: true, view: 'view' } }) ).toEqual( { rightClicked: true, currentView: 'view' } ); }); it('should update view highscore', () => { expect( reducer([], { type: types.UPDATE_VIEW_HIGHSCORE, payload: true }) ).toEqual( { updateHighscoreView: true } ); }); it('should update view achievements', () => { expect( reducer([], { type: types.UPDATE_VIEW_ACHIEVEMENTS, payload: true }) ).toEqual( { updateAchievementsView: true } ); }); it('should update ivew profile', () => { expect( reducer([], { type: types.UPDATE_VIEW_PROFILE, payload: true }) ).toEqual( { updateProfileView: true } ); }); });
// pageObjectExample1.js // This is a simple page object pattern example that does the following: // open page // verify copyright // fill in search form and submit // wait for results on results page // verify results // Page objects are used to provide another layer of abstraction between // the page information and the actual tests. // To Run: // $ wdio wdio.conf-pObjEx1.js // Updated to support version >4 of webdriverio // required libraries var webdriverio = require('webdriverio'), should = require('should'); var WebPage = require('./pageobjects/web-page'); // a test script block or suite describe('Page Object Example #1 for Web Driver IO - Tutorial Test Page Website', function() { it('should open page using pageObjects', function () { WebPage.open(); }); it('should verify copyright using pageObjects', function () { var cr = WebPage.getCopyright(); (cr).should.equal("Tony Keith - tlkeith.com @ 2015-2017 - All rights reserved."); }); it('should fill, submit the search form and verfiy results using pageObjects', function () { WebPage.setFirstname("John"); var fn = WebPage.getFirstname(); (fn).should.be.equal("John"); console.log("First Name: " + fn); WebPage.setLastname('Doe'); var ln = WebPage.getLastname(); (ln).should.be.equal("Doe"); WebPage.submit(); WebPage.waitForResults(); var rs = WebPage.getResults(); (rs).should.equal("Welcome " + "John" + " " + "Doe" + "."); }); });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPost, deletePost } from '../actions'; class PostsShow extends Component { componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); } onDeleteClick(){ const { id } = this.props.match.params; this.props.deletePost(id, () => { this.props.history.push('/'); }); } render() { const { post } = this.props; if (!post) { return <div>Loading...</div>; } return( <div> <Link to="/">Back to Index</Link> <button className="btn btn-danger pull-xs-right" onClick={this.onDeleteClick.bind(this)} >Delete Post </button> <h3>{post.title}</h3> <h6>Categories: {post.categories}</h6> <p>{post.content}</p> </div> ); } } function mapStateToProps({ posts }, ownProps) { return { post: posts[ownProps.match.params.id] }; } export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
'use strict'; /** * Module dependencies. */ var passport = require('passport'); module.exports = function(app) { // User Routes var users = require('../controllers/users.server.controller'); // Setting up the users profile api app.route('/api/users/me').get(users.me); app.route('/api/users').put(users.update); app.route('/api/users/initiatePayment').post(users.initiatePayment); // Finish by binding the user middleware app.param('userId', users.userByID); };
const helpers = require('./helpers'); const webpackMerge = require('webpack-merge'); // used to merge webpack configs const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev /** * Webpack Plugins */ const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin'); const DefinePlugin = require('webpack/lib/DefinePlugin'); const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin'); const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin'); /** * Webpack Constants */ const ENV = process.env.ENV = process.env.NODE_ENV = 'development'; const HOST = process.env.HOST || '0.0.0.0'; const PORT = process.env.PORT || 3000; const HMR = helpers.hasProcessFlag('hot'); const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, { host: HOST, port: PORT, ENV: ENV, HMR: HMR }); module.exports = function (options) { return webpackMerge(commonConfig({env: ENV}), { devtool: 'cheap-module-source-map', output: { path: helpers.root('dist'), filename: '[name].bundle.js', sourceMapFilename: '[file].map', chunkFilename: '[id].chunk.js', library: 'ac_[name]', libraryTarget: 'var', }, module: { rules: [ { test: /\.css$/, use: ['style-loader', 'css-loader'], include: [helpers.root('src', 'styles')] }, { test: /\.scss$/, use: ['style-loader', 'css-loader', 'sass-loader'], include: [helpers.root('src', 'styles')] }, ] }, plugins: [ /** * Plugin: DefinePlugin * Description: Define free variables. * Useful for having development builds with debug logging or adding global constants. **/ new DefinePlugin({ 'ENV': JSON.stringify(METADATA.ENV), 'HMR': METADATA.HMR, 'process.env': { 'ENV': JSON.stringify(METADATA.ENV), 'NODE_ENV': JSON.stringify(METADATA.ENV), 'HMR': METADATA.HMR, } }), new AddAssetHtmlPlugin([ { filepath: helpers.root('src/assets/js', 'jquery-3.1.0.min.js'), includeSourcemap: false }, { filepath: helpers.root('src/assets/js', 'bootstrap.min.js'), includeSourcemap: false }, { filepath: helpers.root('src/assets/js', 'arrive.min.js'), includeSourcemap: false }, { filepath: helpers.root('src/assets/js', 'material.min.js'), includeSourcemap: false }, { filepath: helpers.root('src/assets/js', 'bootstrap-notify.js'), includeSourcemap: false }, { filepath: helpers.root('src/assets/js', 'material-dashboard.js'), includeSourcemap: false }, { filepath: helpers.root('src/assets/js', 'demo.js'), includeSourcemap: false }, { filepath: helpers.root('node_modules/reflect-metadata', 'Reflect.js'), includeSourcemap: false } ]), new LoaderOptionsPlugin({ debug: true, options: { } }), ], // webpack dev server configurations devServer: { port: METADATA.port, host: METADATA.host, historyApiFallback: true, watchOptions: { ignored: /node_modules/ }, setup: function(app) { } }, // Node configuration node: { global: true, crypto: 'empty', process: true, module: false, clearImmediate: false, setImmediate: false } }); }
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react/lib/ReactTestUtils'; import { Home } from './home'; describe('home', () => { var props, result; beforeEach(() => { props = { auth: { authenticated: true }, application: { started: true }, banks: [], items: [], settings: { qBankHost: "qbankhost" }, assessment_offered: { bankId: "bankId", id: "offeredId" }, locales: ['en'] }; result = TestUtils.renderIntoDocument(<Home {...props}/>); }); it('renders', () => { expect(ReactDOM.findDOMNode(result).textContent).toContain("Filter Tree"); }); });
module.exports = { data: { badguys: [] }, methods: { generate_badguys: function () { var amount = 1000 // generate code here this.badguys = null // replace null with an array of objects // this will be the structure of the generated code // this is temporary data (more like a story to me) // entities: [ // { // id: 1, // sprite: '@', // goodguy greg yay :D ggg (aka gennady gennadyevich golovkin) // bind: 'player' // }, // { // id: 2, // sprite: 'w', // badguy bruce boo :C bbb // location: { // x: 2, // y: 2, // z: 0 // }, // health: 1000, // stamina: 40 // } // ], }, behavior_badguys: function () { // if player is within x radius move postition of badguy 1 block closer to player // if touching player, attack player // upon death of baguy remove badguy from badguys array } } }
/** * DocuSign REST API * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient', 'model/UserInformation'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient'), require('./UserInformation')); } else { // Browser globals (root is window) if (!root.Docusign) { root.Docusign = {}; } root.Docusign.NewUsersDefinition = factory(root.Docusign.ApiClient, root.Docusign.UserInformation); } }(this, function(ApiClient, UserInformation) { 'use strict'; /** * The NewUsersDefinition model module. * @module model/NewUsersDefinition */ /** * Constructs a new <code>NewUsersDefinition</code>. * @alias module:model/NewUsersDefinition * @class */ var exports = function() { var _this = this; }; /** * Constructs a <code>NewUsersDefinition</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/NewUsersDefinition} obj Optional instance to populate. * @return {module:model/NewUsersDefinition} The populated <code>NewUsersDefinition</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('newUsers')) { obj['newUsers'] = ApiClient.convertToType(data['newUsers'], [UserInformation]); } } return obj; } /** * * @member {Array.<module:model/UserInformation>} newUsers */ exports.prototype['newUsers'] = undefined; return exports; }));
module.exports = function(config){ config.set({ basePath : '../', files : [ 'app/lib/angular/angular.js', 'app/lib/angular/angular-*.js', 'app/js/**/*.js', 'test/unit/**/*.js' ], exclude : [ 'app/lib/angular/angular-loader.js', 'app/lib/angular/*.min.js', 'app/lib/angular/angular-scenario.js' ], autoWatch : true, frameworks: ['jasmine'], browsers : ['Firefox'], plugins : [ 'karma-junit-reporter', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-script-launcher', 'karma-jasmine' ], junitReporter : { outputFile: 'test_out/unit.xml', suite: 'unit' } }); };
module.exports = function(grunt) { require('load-grunt-tasks')(grunt); var debug = grunt.option('env') !== 'production'; grunt.config('env.' + grunt.option('env'), true); grunt.config('clean', ['./client/build']); grunt.config('browserify', { options: { debug: debug, watch: true }, app: { files: [ { src: './client/src/index.js', dest: './client/build/assets/index.js' } ] } }); grunt.config('uglify', { scripts: { src: './client/build/assets/index.js', dest: './client/build/assets/index.min.js', options: { mangle: false } } }); grunt.config('copy', { html: { src: './client/src/index.html', dest: './client/build/index.html', options: { process: function(content, srcpath) { return grunt.template.process(content); } } } }); grunt.config('less', { styles: { src: './client/src/styles.less', dest: './client/build/assets/styles.css', options: { dumpLineNumbers: debug ? 'all' : false, sourceMap: debug, outputSourceFiles: debug, cleancss: !debug } } }); grunt.config('concurrent', { options: { logConcurrentOutput: true }, develop: { tasks: ['watch', 'nodemon'] } }); grunt.config('nodemon', { develop: { script: './server/app', options: { watch: ['./server'], env: { NODE_ENV: 'development', NODE_CONFIG_DIR: './server/config' } } } }); grunt.config('jshint', { options: { jshintrc: true }, all: ['./Gruntfile.js', './client/src/**/*.js'] }); grunt.config('watch', { html: { files: ['./client/src/index.html'], tasks: ['copy:html'] }, less: { files: ['./client/src/**/*.less'], tasks: ['less'] }, jshint: { files: ['./Gruntfile.js', './client/src/**/*.js'], tasks: ['jshint'] } }); grunt.registerTask('develop', ['build', 'concurrent:develop']); grunt.registerTask('build', ['clean', 'jshint', 'browserify:app', 'uglify', 'copy', 'less']); grunt.registerTask('default', ['build']); };
const { expect } = require('chai'); const path = require('path'); const output = require('./output'); describe('Webpack -> Output', () => { it('Builds the output object', () => { const BUILD = 'BUILD'; const BUNDLE = 'BUNDLE'; const ROOT = '../ROOT'; const VENDOR = false; const configuration = { build: { vendor: VENDOR }, output: { app: BUNDLE }, paths: { build: BUILD, root: ROOT }, }; const expected = { filename: `./${BUNDLE}`, library: '', path: path.join(__dirname, ROOT, BUILD), publicPath: '/', }; expect(output(configuration)).to.deep.equal(expected); }); it('Adds the vendor library when it is a vendor build', () => { const BUILD = 'BUILD'; const BUNDLE = 'BUNDLE'; const ROOT = '../ROOT'; const VENDOR = true; const configuration = { build: { vendor: VENDOR }, output: { app: BUNDLE }, paths: { build: BUILD, root: ROOT }, }; const expected = { filename: `./${BUNDLE}`, library: 'vendor', path: path.join(__dirname, ROOT, BUILD), publicPath: '/', }; expect(output(configuration)).to.deep.equal(expected); }); });
import defprotocol from '../defprotocol' import Function from '../types/Function' const IPersistentStack = defprotocol({ peek: Function, pop: Function, push: Function }) export default IPersistentStack
'use strict'; var path = require('path'); module.exports = function (config, storages) { config.port = process.env.MEDIA_SERVICE_PORT || 80; config.autoRestart = true; config.progressive = true; config.metadata = false; config.quality = 90; config.webp = true; // access control config.enableAccessControl = true; config.accessControl = { // [ '192.168.*.*', '127.0.0.1' ] write: [ '127.0.0.1' ], read: [ '127.0.0.1' ] }; // log config.logDir = process.env.MEDIA_SERVICE_LOG_DIR || path.join(__dirname, 'log'); config.logBackCopies = process.env.MEDIA_SERVICE_LOG_BACK_COPIES || 3; // size config.sizes = { 'small-avatar': '16x16:center', 'avatar': '120x120:center', 'big-avatar': '240x240:center' }; // mobile detect config.enableMobileDetect = true; config.mobileSizes = { phone: { 'avatar': 'small-avatar', 'big-avatar': 'avatar' } }; // storages var localStorage = new storages.LocalStorage('local', { baseUrl: 'http://localhost', dir: path.join(__dirname, 'medias') }); config.storages = [ localStorage ]; };
function EditWorksCtrl($scope, QuoteService) { QuoteService.findOrCreateForWorks($scope); $scope.remove = function(idx) { $scope.utils.remove($scope.editing.works, idx); $scope.qot.initRowNumbers($scope.editing.works); $scope.qot.updateWorksTotal($scope, $scope.editing); } $scope.add = function(idx) { idx = $scope.utils.add($scope.editing.works, $scope.qot.newWork(), idx); $scope.qot.initRowNumbers($scope.editing.works); $scope.loadWork(idx); $scope.focus('work_' + idx); } $scope.down = function(idx) { $scope.utils.down($scope.editing.works, idx); $scope.qot.initRowNumbers($scope.editing.works); } $scope.up = function(idx) { $scope.utils.up($scope.editing.works, idx); $scope.qot.initRowNumbers($scope.editing.works); } $scope.loadWork = function(idx) { $scope.$log.info("load Work edit works " + idx); $scope.work = $scope.editing.works[idx]; } } EditWorksCtrl.$inject = ['$scope', 'QuoteService'];
var assert = require('chai').assert; var user = require('../util/models/user'); var util = require('./rest-builder-util'); var putObj = { key: 'value' }; var putData = { q: putObj }; describe('RestBuilder', function() { describe('definePut', function() { util.setUp(); describe('no processors', function() { it('should call db.del', function(done) { this.rb.definePut('users', user, [], []); this.client.put('/users/1', putData, function(err, req, res) { assert.ifError(err); util.mockDB.update.assertCalledOnceWithArgsIncluding( ['1', user, putObj] ); done(); }); }); }); describe('with preprocessors', function () { it('should call a single preprocessor', function(done) { var mockPre = util.getMockPre(); this.rb.definePut('users', user, [mockPre], []); this.client.put('/users/1', putData, function(err, req, res) { mockPre.assertCalled('should call preprocessors'); assert.ifError(err); util.mockDB.update.assertCalledOnceWithArgsIncluding( ['1', user, putObj] ); done(); }); }); it('should call all the preprocessors', function (done) { var mockPre = util.getMockPre(); var _mockPre = util.getMockPre(); this.rb.definePut('users', user, [mockPre, _mockPre], []); this.client.put('/users/1', putData, function(err, req, res) { mockPre.assertCalled('should call first preprocessor'); _mockPre.assertCalled('should call second preprocessor'); assert.ifError(err); util.mockDB.update.assertCalledOnceWithArgsIncluding( ['1', user, putObj] ); done(); }); }); }); }); });
'use strict'; angular.module('myApp.list-downloading', [ 'ngRoute' ]) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/list-downloading', { templateUrl: 'list-downloading/list-downloading.html', controller: 'ListDownloadingCtrl' }); }]) .controller('ListDownloadingCtrl', ['$rootScope', '$scope', function($rootScope, $scope) { $scope.files = $rootScope.listFiles.downloading; }]);
$(document).ready(function(){ $('.page-add-gallery .form-colors [data-toggle="buttons"] .btn-color').click(function(){ if($(this).hasClass('active')) { // alert('active'); }else { if($('.page-add-gallery .form-colors [data-toggle="buttons"] .active').length >= 3) { event.stopPropagation(); } // alert('NOT active'); } }); });
import Ember from 'ember'; import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin'; export default Ember.Route.extend(AuthenticatedRouteMixin, { model() { return this.store.query('order', { filter: { simple: { active: false } } }); }, renderTemplate(controller, model) { this.render('orders.index', { model }); } });
import { combineReducers } from 'redux' import { FETCH_NEWS, FETCH_NEWS_FULFILLED, FETCH_NEWS_REJECTED } from '../actions/news' import { FETCH_STORY, FETCH_STORY_REJECTED, FETCH_STORY_FULFILLED } from '../actions/story' import { CLOSE_DIALOG } from '../actions/dialog' const isFetching = (state = false, action) => { switch (action.type) { case FETCH_NEWS: case FETCH_STORY: return true case FETCH_NEWS_FULFILLED: case FETCH_STORY_FULFILLED: return false default: return state } } const error = (state = false, action) => { switch (action.type) { case FETCH_NEWS_REJECTED: case FETCH_STORY_REJECTED: return true case CLOSE_DIALOG: return false default: return state } } const msg = (state = '', action) => { switch (action.type) { case FETCH_NEWS_REJECTED: case FETCH_STORY_REJECTED: return action.payload || '' default: return state } } const status = combineReducers({ isFetching, error, msg }) export default status
"use strict"; /* globals AccountsAnonymous, AccountsMultiple, Hook */ Accounts.registerLoginHandler("anonymous", function(options) { if (!options || !options.anonymous || Meteor.userId()) { return undefined; } var newUserId = Accounts.insertUserDoc(options, {}); return { userId: newUserId }; }); AccountsAnonymous._onAbandonedHook = new Hook({ bindEnvironment: false, debugPrintExceptions: "AccountsAnonymous.onAbandoned callback" }); AccountsAnonymous.onAbandoned = function(func) { var self = this; return self._onAbandonedHook.register(func); }; var callbackSet = { onSwitch: function(attemptingUser /* , attempt (unused) */) { if (isAnonymous(attemptingUser)) { AccountsAnonymous._onAbandonedHook.each(function(callback) { callback(attemptingUser); return true; }); } } }; AccountsAnonymous._init = function() { AccountsMultiple.register(callbackSet); }; AccountsAnonymous._init(); function isAnonymous(user) { // A user is anonymous if they don't have any services other than "resume" return (user.services && _.size(user.services) === 1 && user.services.resume); }
import React, { Component } from 'react' import BodySection1 from './BodySection1' import BodySection2 from './BodySection2' import BodySection3 from './BodySection3' import { Link } from 'react-router' import injectTapEventPlugin from 'react-tap-event-plugin'; import { Parallax } from 'react-parallax'; class Body extends Component { render(){ return( <Parallax bgImage="assets/1.jpg" width = {100} strength={400}> <div className="generic-center dummy-height"> <BodySection1 /> <p></p> <BodySection2 /> <p></p> <BodySection3 /> </div> </Parallax> ) } } export default Body
'use strict'; var fs = require('fs'); var path = require('path'); function numFiles(dir, items, callback) { var total = items.length; var files = 0; var completed = 0; if (total === 0) { callback(null, 0); } items.forEach(function(item) { fs.stat(path.join(dir, item), function(err, stats) { if (err) { return callback(err); } if (stats && stats.isFile()) { ++files; } ++completed; if (completed === total) { callback(null, files); } }); }); } /** * Count the number of files in a directory. * @param {string} dir Path to directory. * @param {function(Error, number)} callback Callback. */ module.exports = exports = function(dir, callback) { fs.readdir(dir, function(err, items) { if (err) { return callback(err); } numFiles(dir, items, callback); }); };
module.exports = (Bluebird) => { Bluebird.prototype.spread = function spread(fn) { return this.all().then(results => fn(...results)); }; }
const types = require('./packages/mjml-core/lib/types/type.js') const enumtype = types.initializeType('enum(top,left,center)') const colortype = types.initializeType('color') const booleantype = types.initializeType('boolean') const unittype = types.initializeType('unit(px,%){1,3}') const stringtype = types.initializeType('string') console.log(stringtype) const output = (t) => { console.log(`Type: ${t.constructor.name} — Value: ${t.value} — isValid: ${t.isValid()} ${t.getErrorMessage()}`) } [new colortype('grey'), new colortype('rgba(0,255,3,0.3)'), new colortype('#DDF'), new colortype('#DF'), new booleantype('true'), new booleantype('false'), new booleantype('banana'), new unittype('10 20px 20'), new unittype('10px 20px 20px'), new unittype('10px'), new unittype('10%'), new unittype('10px 10px'), new unittype('0'), new stringtype('hello world'), ].map(output)
$(function () { // There is a class name set on the nav-item that is the same as path // else assume we are on startpage currentpageclass = window.location.pathname.replace(/^\/|\/$/g, ""); // If no path then assume we are on startpage if (currentpageclass == "") { $('.startsida').addClass('active'); } else { $('.' + currentpageclass).addClass('active'); } });
define(['../string/typecast', '../lang/isString', '../lang/isArray', '../object/hasOwn'], function (typecast, isString, isArray, hasOwn) { /** * Decode query string into an object of keys => vals. */ function decode(queryStr, shouldTypecast) { var queryArr = (queryStr || '').replace('?', '').split('&'), count = -1, length = queryArr.length, obj = {}, item, pValue, pName, toSet; while (++count < length) { item = queryArr[count].split('='); pName = item[0]; if (!pName || !pName.length){ continue; } pValue = shouldTypecast === false ? item[1] : typecast(item[1]); toSet = isString(pValue) ? decodeURIComponent(pValue) : pValue; if (hasOwn(obj,pName)){ if(isArray(obj[pName])){ obj[pName].push(toSet); } else { obj[pName] = [obj[pName],toSet]; } } else { obj[pName] = toSet; } } return obj; } return decode; });
"use strict"; module.exports = { array: require('./array'), debug: require("./debug"), livereload: require("./livereload"), log: require("./log"), module: require("./module"), regexp: require("./regexp") };
var listen = require('./client/display.js').listen var $ = require('jquery') $(() => { listen() })
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { name: 'attribute-sets', connection: 'default', useAuth: true, useACL: true, useBuildInEndPoints: ['list', 'read', 'create', 'edit', 'delete'], schema: { title: { type: 'string', selectable: true, changable: true, sortable: true, filters: ['substring'], required: true, unique: true }, attributes: { type: 'array', required: true, selectable: true, changable: true, connectWith: 'attributes', items: { type: 'id' } } } };
import * as CES from 'ces'; import * as BABYLON from '../lib/babylon'; import { c_light } from '../components/c_light'; /** * ... * @author Brendon Smith * http://seacloud9.org * LightWeight 3D System Design engine */ export class e_light{ constructor(_defaults = null){ this._defaults = _defaults == null ? this.defaults(): _defaults; this.entity = new CES.Entity(); this.init(); } static defaults(){ return{ _type:'Hemispheric', e_type:'e_light', name:'Hemispheric', _position:'0,0,0', _rotation:'0,0,0', _material:{ _alpah:1.0, _texture:null, _uScale: 1.0, _vScale: 1.0, _backFaceCulling: true, _vOffset: 0.0, _uOffset: 0.0, _hasAlpha:false, _diffuseColor: '127, 0, 140', }, _scene:{} } } init(){ this.entity.addComponent(new c_light(this._defaults)); } }
export function assertIsString(x, name) { if (typeof x !== "string") { throw new Error(`Expected ${name} to be a string, got ${x}.`); } } export function assertIsNonEmptyString(x) { if (typeof x !== "string" || x.length === 0) { throw new Error(`Expected a non-empty string, got ${x}`); } } export function assertIsValidHorizontalAlign(x) { switch (x) { case "left": return; case "center": return; case "right": return; default: throw new Error(`Unexpected horizontalAlign (acceptable values are "left", "center", and "right"); got ${x}`); } } export function assertIsValidVerticalAlign(x) { switch (x) { case "top": return; case "middle": return; case "bottom": return; default: throw new Error(`Unexpected verticalAlign (acceptable values are "top", "middle", and "bottom"); got ${x}`); } } export function assertIsNumber(x, name) { if (typeof x !== "number") { throw new Error(`Expected ${name} to be a number, got ${x}`); } } export function assertIsBoolean(x, name) { if (typeof x !== "boolean") { throw new Error(`Expected ${name} to be a boolean, got ${x}`); } } export function assertIsPositiveNumber(x, name) { if (typeof x !== "number") { throw new Error(`Expected ${name} to be a number, got ${x}`); } if (x <= 0) { throw new Error(`Expected ${name} to be positive, got ${x}`); } } export function assertIsNonNegativeNumber(x, name) { if (typeof x !== "number") { throw new Error(`Expected ${name} to be a number, got ${x}`); } if (x < 0) { throw new Error(`Expected ${name} to be non-negative, got ${x}`); } }