code
stringlengths
2
1.05M
describe("Unittest.CommodityController: When clicking a commodity", function () { var $scope, $q; var CommodityController, CommodityService, CommodityRepository, CommodityServiceSpy, PopupExtension; beforeEach(function () { module("whattobuy"); inject(function (_$q_, $rootScope, $injector, $controller, _PopupExtension_) { $scope = $rootScope.$new(); $q = _$q_; CommodityService = $injector.get(serviceNames.CommodityService); CommodityRepository = $injector.get(repositoryNames.CommodityRepository); PopupExtension = _PopupExtension_; spyOn(CommodityRepository, "getCommoditiesOrCached").and.callFake(function () { var deferred = $q.defer(); deferred.resolve([{}]); return deferred.promise; }); CommodityServiceSpy = spyOn(CommodityService, "saveCommodity"); spyOn(PopupExtension, "showAlert"); spyOn(PopupExtension, "showError"); var mockFactory = $injector.get(toolNames.MockFactory); var ErrorStoreMock = mockFactory.ErrorStoreMock; expect(getMethods(ErrorStoreMock)).toEqual(getMethods($injector.get(dataproviderNames.ErrorStore))); CommodityController = $controller("CommodityController", { $scope: $scope, ErrorStore : ErrorStoreMock }); CommodityController.feedList = [{ feedId : 'abc0', name : 'Ikea2013'}, { feedId : 'nmo1', name : 'Kiwi'}]; CommodityController.selectedFeed = CommodityController.feedList[0]; }); }); it("should buy a commodity successfully", function () { var clickedCommodity = { commodityGuid : 'aa738f8d26054233983296811620b5e3', isPurchased : false, lastUpdated : '2014-04-18T15:08:49', name : 'Pølse' }; var clonedClickedCommodity = { commodityGuid : 'aa738f8d26054233983296811620b5e3', isPurchased : true, lastUpdated : '2014-04-18T15:08:49', name : 'Pølse' }; CommodityServiceSpy.and.callFake(function (feedId, commodity) { var deferred = $q.defer(); expect(feedId).toEqual(CommodityController.selectedFeed.feedId); expect(commodity).toEqual(clonedClickedCommodity); deferred.resolve({isSuccess: true}); return deferred.promise; }); CommodityController.clickedCommodity(clickedCommodity); $scope.$digest(); expect(clickedCommodity.isPurchased).toEqual(clonedClickedCommodity.isPurchased); expect(PopupExtension.showAlert).not.toHaveBeenCalled(); }); it("should buy a commodity UNsuccessfully", function () { var clickedCommodity = { commodityGuid : 'aa738f8d26054233983296811620b5e3', isPurchased : false, lastUpdated : '2014-04-18T15:08:49', name : 'Pølse' }; var clonedClickedCommodity = { commodityGuid : 'aa738f8d26054233983296811620b5e3', isPurchased : true, lastUpdated : '2014-04-18T15:08:49', name : 'Pølse' }; CommodityServiceSpy.and.callFake(function (feedId, commodity) { var deferred = $q.defer(); expect(feedId).toEqual(CommodityController.selectedFeed.feedId); expect(commodity).toEqual(clonedClickedCommodity); deferred.reject("Oh noes!!"); return deferred.promise; }); CommodityController.clickedCommodity(clickedCommodity); $scope.$digest(); expect(clickedCommodity.isPurchased).not.toEqual(clonedClickedCommodity.isPurchased); expect(PopupExtension.showError).toHaveBeenCalled(); }); });
(function(){ Template.__checkName("before_post_item"); Template["before_post_item"] = new Template("Template.before_post_item", (function() { var view = this; return HTML.Raw("<!-- before post item -->"); })); })();
// Copyright 2020-2021, University of Colorado Boulder /** * * @author Michael Kauzmann (PhET Interactive Simulations) */ import BasicActionsKeyboardHelpSection from '../../scenery-phet/js/keyboard/help/BasicActionsKeyboardHelpSection.js'; import { Node } from '../../scenery/js/imports.js'; import joist from './joist.js'; class HomeScreenKeyboardHelpContent extends Node { constructor() { super( { children: [ new BasicActionsKeyboardHelpSection() ] } ); } } joist.register( 'HomeScreenKeyboardHelpContent', HomeScreenKeyboardHelpContent ); export default HomeScreenKeyboardHelpContent;
var struct_int = [ [ "length", "struct_int.html#a2894ba17eb6001ea4990dc72b54b75a8", null ], [ "pointer", "struct_int.html#a3f4ea8274904dcbc6a8ec0d26070cb48", null ] ];
const LOAD = 'redux-example/auth/LOAD'; const LOAD_SUCCESS = 'redux-example/auth/LOAD_SUCCESS'; const LOAD_FAIL = 'redux-example/auth/LOAD_FAIL'; const LOGIN = 'redux-example/auth/LOGIN'; const LOGIN_SUCCESS = 'redux-example/auth/LOGIN_SUCCESS'; const LOGIN_FAIL = 'redux-example/auth/LOGIN_FAIL'; const LOGOUT = 'redux-example/auth/LOGOUT'; const LOGOUT_SUCCESS = 'redux-example/auth/LOGOUT_SUCCESS'; const LOGOUT_FAIL = 'redux-example/auth/LOGOUT_FAIL'; const initialState = { loaded: false }; export default function reducer(state = initialState, action = {}) { switch (action.type) { case LOAD: return { ...state, loading: true }; case LOAD_SUCCESS: return { ...state, loading: false, loaded: true, user: action.result }; case LOAD_FAIL: return { ...state, loading: false, loaded: false, error: action.error }; case LOGIN: return { ...state, loggingIn: true }; case LOGIN_SUCCESS: return { ...state, loggingIn: false, user: action.result }; case LOGIN_FAIL: return { ...state, loggingIn: false, user: null, loginError: action.error }; case LOGOUT: return { ...state, loggingOut: true }; case LOGOUT_SUCCESS: return { ...state, loggingOut: false, user: null }; case LOGOUT_FAIL: return { ...state, loggingOut: false, logoutError: action.error }; default: return state; } } export function isLoaded(globalState) { return globalState.auth && globalState.auth.loaded; } export function load() { return { types: [LOAD, LOAD_SUCCESS, LOAD_FAIL], promise: (client) => client.get('/loadAuth') }; } export function login(name) { return { types: [LOGIN, LOGIN_SUCCESS, LOGIN_FAIL], promise: (client) => client.post('/login', { data: { name: name } }) }; } export function logout() { return { types: [LOGOUT, LOGOUT_SUCCESS, LOGOUT_FAIL], promise: (client) => client.get('/logout') }; }
/** * Created by whobird on 17/4/10. */ $(document).ready(function(){ var slideCount=$(".section-wrapper").find(".section-slide").length; console.log(slideCount); var prevIndex=0; var lastProgress=0; var mySwiper = new Swiper('.swiper-container', { // slidesPerView: 3.2, freeMode:true, freeModeMomentum:false, slidesPerView: 'auto', observer:true, observerParents:true, mousewheelControl:true, watchSlidesProgress : true, touchRatio:3, shortSwipes:false, threshold : 100, /*freeModeSticky:true, freeModeMomentumBounce : true, freeModeMomentumBounceRatio:10,*/ grabCursor : true, onProgress: function(swiper, progress){ //console.log(mySwiper.realIndex); console.log("**********************************************************************") console.log("progress==========================="); console.log("progress:"+progress); console.log("lastProgress:"+lastProgress); //console.log(mySwiper.realIndex); //根据 progress 计算当前的index var indexRate=100/(slideCount-1); var index=Math.round(progress*100/indexRate); if(index>(slideCount-1)){ index=slideCount-1; } console.log(index); console.log("index progress====================="); var indexProgress=swiper.slides[index].progress; console.log(indexProgress); console.log("==================================================*************"); console.log("translate3d("+((-20*(index))-(20*indexProgress))+" %"); lastProgress=swiper.progress; $(".section-wrapper").css({ "transform": "translate3d("+((-20*(index))-(20*indexProgress) )+"%, 0px, 0px)", }) }, onTransitionEnd: function(swiper){ console.log("transitionEnd======================"); } }); $(".nav-panel").on("click",function(e){ $(".main").toggleClass("nav-active"); }); $("body").on("click",function(e){ console.log(e); }); });
/** * Created by Katie on 4/1/14. */ var mongoose = require('mongoose'); // define var logSchema = mongoose.Schema({ user_id : String, content : String, module_name : String, postDate : Date }); module.exports = mongoose.model('Log', logSchema);
var fortuneCookies = [ 'Conquer your fears or they will conquer you', 'Rivers need springs', 'Do not fear what you don\'t know', 'You will have a pleasant surprise', 'Whenever possible, keep it simple' ]; exports.getFortune = function(){ var idx = Math.floor(Math.random() * fortuneCookies.length); return fortuneCookies[idx]; }
/** * @license * jQuery Tools 1.2.4 Tabs- The basics of UI design. * * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE. * * http://flowplayer.org/tools/tabs/ * * Since: November 2008 * Date: Sun Aug 15 08:16:31 2010 +0000 */ (function($) { // static constructs $.tools = $.tools || {version: '1.2.4'}; $.tools.tabs = { conf: { tabs: 'a', current: 'current', onBeforeClick: null, onClick: null, effect: 'default', initialIndex: 0, event: 'click', rotate: false, // 1.2 history: false }, addEffect: function(name, fn) { effects[name] = fn; } }; var effects = { // simple "toggle" effect 'default': function(i, done) { this.getPanes().hide().eq(i).show(); done.call(); }, /* configuration: - fadeOutSpeed (positive value does "crossfading") - fadeInSpeed */ fade: function(i, done) { var conf = this.getConf(), speed = conf.fadeOutSpeed, panes = this.getPanes(); if (speed) { panes.fadeOut(speed); } else { panes.hide(); } panes.eq(i).fadeIn(conf.fadeInSpeed, done); }, // for basic accordions slide: function(i, done) { this.getPanes().slideUp(200); this.getPanes().eq(i).slideDown(400, done); }, /** * AJAX effect */ ajax: function(i, done) { this.getPanes().eq(0).load(this.getTabs().eq(i).attr("href"), done); } }; var w; /** * Horizontal accordion * * @deprecated will be replaced with a more robust implementation */ $.tools.tabs.addEffect("horizontal", function(i, done) { // store original width of a pane into memory if (!w) { w = this.getPanes().eq(0).width(); } // set current pane's width to zero this.getCurrentPane().animate({width: 0}, function() { $(this).hide(); }); // grow opened pane to it's original width this.getPanes().eq(i).animate({width: w}, function() { $(this).show(); done.call(); }); }); function Tabs(root, paneSelector, conf) { var self = this, trigger = root.add(this), tabs = root.find(conf.tabs), panes = paneSelector.jquery ? paneSelector : root.children(paneSelector), current; // make sure tabs and panes are found if (!tabs.length) { tabs = root.children(); } if (!panes.length) { panes = root.parent().find(paneSelector); } if (!panes.length) { panes = $(paneSelector); } // public methods $.extend(this, { click: function(i, e) { var tab = tabs.eq(i); if (typeof i == 'string' && i.replace("#", "")) { tab = tabs.filter("[href*=" + i.replace("#", "") + "]"); i = Math.max(tabs.index(tab), 0); } if (conf.rotate) { var last = tabs.length -1; if (i < 0) { return self.click(last, e); } if (i > last) { return self.click(0, e); } } if (!tab.length) { if (current >= 0) { return self; } i = conf.initialIndex; tab = tabs.eq(i); } // current tab is being clicked if (i === current) { return self; } // possibility to cancel click action e = e || $.Event(); e.type = "onBeforeClick"; trigger.trigger(e, [i]); if (e.isDefaultPrevented()) { return; } // call the effect effects[conf.effect].call(self, i, function() { // onClick callback e.type = "onClick"; trigger.trigger(e, [i]); }); // default behaviour current = i; tabs.removeClass(conf.current); tab.addClass(conf.current); return self; }, getConf: function() { return conf; }, getTabs: function() { return tabs; }, getPanes: function() { return panes; }, getCurrentPane: function() { return panes.eq(current); }, getCurrentTab: function() { return tabs.eq(current); }, getIndex: function() { return current; }, next: function() { return self.click(current + 1); }, prev: function() { return self.click(current - 1); }, destroy: function() { tabs.unbind(conf.event).removeClass(conf.current); panes.find("a[href^=#]").unbind("click.T"); return self; } }); // callbacks $.each("onBeforeClick,onClick".split(","), function(i, name) { // configuration if ($.isFunction(conf[name])) { $(self).bind(name, conf[name]); } // API self[name] = function(fn) { if (fn) { $(self).bind(name, fn); } return self; }; }); if (conf.history && $.fn.history) { $.tools.history.init(tabs); conf.event = 'history'; } // setup click actions for each tab tabs.each(function(i) { $(this).bind(conf.event, function(e) { self.click(i, e); return e.preventDefault(); }); }); // cross tab anchor link panes.find("a[href^=#]").bind("click.T", function(e) { self.click($(this).attr("href"), e); }); // open initial tab if (location.hash && conf.tabs === "a" && root.find(conf.tabs + location.hash).length) { self.click(location.hash); } else { if (conf.initialIndex === 0 || conf.initialIndex > 0) { self.click(conf.initialIndex); } } } // jQuery plugin implementation $.fn.tabs = function(paneSelector, conf) { // return existing instance var el = this.data("tabs"); if (el) { el.destroy(); this.removeData("tabs"); } if ($.isFunction(conf)) { conf = {onBeforeClick: conf}; } // setup conf conf = $.extend({}, $.tools.tabs.conf, conf); this.each(function() { el = new Tabs($(this), paneSelector, conf); $(this).data("tabs", el); }); return conf.api ? el: this; }; }) (jQuery);
Todos.TodosIndexRoute = Ember.Route.extend({ model: function () { return this.modelFor('todos'); } });
'use strict'; // Channels controller angular.module('channels').controller('ChannelsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Channels', function ($scope, $stateParams, $location, Authentication, Channels) { $scope.authentication = Authentication; // Create new Channel $scope.create = function (isValid) { $scope.error = null; if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'channelForm'); return false; } // Create new Channel object var channel = new Channels({ title: this.title, file: this.file }); // Redirect after save channel.$save(function (response) { $location.path('channels/' + response._id); // Clear form fields $scope.title = ''; $scope.file = ''; }, function (errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Channel $scope.remove = function (channel) { if (channel) { channel.$remove(); for (var i in $scope.channels) { if ($scope.channels[i] === channel) { $scope.channels.splice(i, 1); } } } else { $scope.channel.$remove(function () { $location.path('channels'); }); } }; // Update existing Channel $scope.update = function (isValid) { $scope.error = null; if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'channelForm'); return false; } var channel = $scope.channel; channel.$update(function () { $location.path('channels/' + channel._id); }, function (errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Channels $scope.find = function () { $scope.channels = Channels.query(); }; // Find existing Channel $scope.findOne = function () { $scope.channel = Channels.get({ channelId: $stateParams.channelId }); }; } ]);
(function (R, $) { // input commands var LEFT = 1, RIGHT = 2, DOWN = 3, CLOCKWISE = 4, COUNTER_CLOCKWISE = 5, DROP = 6; // grid dimensions var ROWS = 25, COLS = 10; var Hatetris = function (raphael) { this.raphael = raphael; $(this.ready.bind(this)); } Hatetris.prototype.ready = function () { $(document).keypress(this.keypress.bind(this)); this.scale_x = this.raphael.width / COLS; this.scale_y = this.raphael.height / ROWS; this.drawGrid(); this.current(Tetromino.T()); this.drawPolyomino(this.current()); } Hatetris.prototype.keypress = function (event) { // translate keypress event into input command switch (event.keyCode || event.charCode) { case 32: this.input(DROP); break; case 37: this.input(LEFT); break; case 39: this.input(RIGHT); break; case 40: this.input(DOWN); break; case 38: this.input(CLOCKWISE); break; case 120: this.input(CLOCKWISE); break; case 122: this.input(COUNTER_CLOCKWISE); break; default: return; } // cancel the event event.preventDefault(); } Hatetris.prototype.current = function (polyomino) { return polyomino !== undefined ? this._current = polyomino : this._current; } Hatetris.prototype.input = function (command) { var acceptable = this.acceptable.bind(this); if (command === CLOCKWISE) { this.current().clockwise(acceptable); this.drawPolyomino(this.current()); } if (command === COUNTER_CLOCKWISE) { this.current().counter_clockwise(acceptable); this.drawPolyomino(this.current()); } if (command === LEFT) { this.current().translate(-1, 0, acceptable); this.drawPolyomino(this.current()); } if (command === RIGHT) { this.current().translate(1, 0, acceptable); this.drawPolyomino(this.current()); } if (command === DOWN) { this.current().translate(0, 1, acceptable); this.drawPolyomino(this.current()); } } Hatetris.prototype.acceptable = function (polyomino) { if (polyomino.x < 0 || polyomino.y < 0) return false; if (polyomino.ext[0] + polyomino.x > COLS) return false; if (polyomino.ext[1] + polyomino.y > ROWS) return false; return true; } Hatetris.prototype.drawGrid = function () { if (this.grid) return; this.grid = this.raphael.set(); for (var i = 1; i < COLS; i++) { this.grid.push( this.raphael.path(['M', i*this.scale_x, 0, i*this.scale_x, this.raphael.height]) .attr('stroke', '#DDD') ); } for (var i = 1; i < ROWS; i++) { this.grid.push( this.raphael.path(['M', 0, i*this.scale_y, this.raphael.height, i*this.scale_y]) .attr('stroke', '#DDD') ); } this.grid.push( this.raphael.rect(0, 0, this.raphael.width - 1, this.raphael.height - 1) ); } Hatetris.prototype.drawPolyomino = function (polyomino) { if (polyomino.set) { polyomino.set.remove(); } else { polyomino.set = this.raphael.set(); } $.each(polyomino.coordinates(), function (i, p) { polyomino.set.push( this.raphael.rect(p[0] * this.scale_x, p[1] * this.scale_y, this.scale_x, this.scale_y) .attr('fill', '#999') ); }.bind(this)); } R.fn.hatetris = function () { new Hatetris(this); return this; } })(Raphael, jQuery);
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Router from 'react-routing/src/Router'; import fetch from './core/fetch'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; import BlogPage from './components/BlogPage'; import LoginPage from './components/LoginPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}>{component}</App>; }); on('/contact', async () => <ContactPage />); on('/blog', async () => <BlogPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const query = `/graphql?query={content(path:"${state.path}"){path,title,content,component}}`; const response = await fetch(query); const { data } = await response.json(); return data && data.content && <ContentPage {...data.content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
'use strict'; /** * Our first store. This is what is going to * hold the application state and logic. In * general Stores manage the state of many * objects, and not a particular instance of it. * It will manage app state for a DOMAIN (Todo * stuff) within the application. * * TodoStore will register itself with * AppDispatcher (which inherits from our base * Dispatcher) providing it with a callback, * which is going to receive action's painted * payload from the call of AppDispatcher's * `dispatch` method. */ var AppDispatcher = require('../dispatcher/AppDispatcher') , EventEmitter = require('events').EventEmitter , TodoConstants = require('../constants/TodoConstants') , merge = require('react/lib/merge') , CHANGE_EVENT = 'change' // will persist our data while our application // lives. As it lives outside the class, but // within the closure of the module, it will // remain private. , _todos = {}; /** * Auxiliary Functions */ function create (text) { var id = Date.now(); _todos[id] = { id: id, complete: false, text: text }; } function areNotAllComplete () { return _todos.some(elem => elem.complete ? false : true); } function destroy (id) { delete _todos[id]; } /** * Definition of our Store. Notice that it * inherits from EventEmitter, which provides us * the basic functionality that we expect, i.e, * the possibility of emitting events and * letting others register with them. */ var TodoStore = merge(EventEmitter.prototype, { // exposes the data (which is private, contained // in the module's closure) so that the view can // fetch it when it want's to get the state. We // often pass the entire state of the store down // the chain of views in a single object so that // different descendants are able to use what // they need. getAll () { return _todos; }, // emits the 'change' event to whatever // controller-views are listening to it. This // will actually be fired in the callback that // we provided to the Dispatcher when we do its // registration (below). emitChange () { this.emit(CHANGE_EVENT); }, // provide do our controller-views to register // themselves with the store. addChangeListener (cb) { this.on(CHANGE_EVENT, cb); }, // opposite of addChangeListener removeChangeListener (cb) { this.removeListener(CHANGE_EVENT, cb); }, /** * The index of the Store's callback in the * Dispatcher registry. Here we are actually * registering the Store's callback function * with the Dispatcher and just storing the * index that the registry returns to us. * * Note that the callback receives a painted * payload, which comes from the action. * Within this callback is were we distinguish * between the types of action, do some * changes in the state of the application and * then finally emit the 'change' event for * those controller-views that are listening * to the 'change' event. */ dispatcherIndex: AppDispatcher.register(payload => { var action = payload.action; var text; switch (action.actionType) { case TodoConstants.TODO_CREATE: text = action.text.trim(); if (text) { create(text); TodoStore.emitChange(); } break; case TodoConstants.TODO_DESTROY: destroy(action.id); TodoStore.emitChange(); break; case TodoConstants.TODO_DESTROY: destroy(action.id); TodoStore.emitChange(); break; default: throw new Error('No handle for ' + action.actionType + ' action.'); } // so that the promise is resolved, and not // rejected - as we expect :D return true; }) }); module.exports = TodoStore;
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('messages.jquery.json'), clean: { files: ['dist'] }, concat: { options: { stripBanners: true }, dist: { src: ['src/<%= pkg.name %>.js'], dest: 'dist/<%= pkg.name %>.js' }, }, uglify: { dist: { src: '<%= concat.dist.dest %>', dest: 'dist/<%= pkg.name %>.min.js' }, }, qunit: { files: ['test/**/*.html'] }, jshint: { gruntfile: { options: { jshintrc: '.jshintrc' }, src: 'Gruntfile.js' }, src: { options: { jshintrc: 'src/.jshintrc' }, src: ['src/**/*.js'] }, test: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/**/*.js'] }, }, watch: { gruntfile: { files: '<%= jshint.gruntfile.src %>', tasks: ['jshint:gruntfile'] }, src: { files: '<%= jshint.src.src %>', tasks: ['jshint:src', 'qunit'] }, test: { files: '<%= jshint.test.src %>', tasks: ['jshint:test', 'qunit'] }, }, }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['jshint', 'qunit', 'clean', 'concat', 'uglify']); };
const { exec } = require('shelljs') const os = require('os') const platform = os.platform() console.log('platform:', platform) const cmd = platform.startsWith('win') ? 'node_modules\\.bin\\cross-env NODE_ENV=development node_modules\\.bin\\electron -r dotenv/config src\\app\\app' : 'node_modules/.bin/cross-env NODE_ENV=development node_modules/.bin/electron -r dotenv/config src/app/app' exec(cmd)
// Zepto.js // (c) 2010-2016 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. import $ from './zepto'; var prefix = '', eventPrefix, vendors = {Webkit: 'webkit', Moz: '', O: 'o'}, testEl = document.createElement('div'), supportedTransforms = /^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i, transform, transitionProperty, transitionDuration, transitionTiming, transitionDelay, animationName, animationDuration, animationTiming, animationDelay, cssReset = {} function dasherize(str) { return str.replace(/([a-z])([A-Z])/, '$1-$2').toLowerCase() } function normalizeEvent(name) { return eventPrefix ? eventPrefix + name : name.toLowerCase() } $.each(vendors, function (vendor, event) { if (testEl.style[vendor + 'TransitionProperty'] !== undefined) { prefix = '-' + vendor.toLowerCase() + '-' eventPrefix = event return false } }) transform = prefix + 'transform' cssReset[transitionProperty = prefix + 'transition-property'] = cssReset[transitionDuration = prefix + 'transition-duration'] = cssReset[transitionDelay = prefix + 'transition-delay'] = cssReset[transitionTiming = prefix + 'transition-timing-function'] = cssReset[animationName = prefix + 'animation-name'] = cssReset[animationDuration = prefix + 'animation-duration'] = cssReset[animationDelay = prefix + 'animation-delay'] = cssReset[animationTiming = prefix + 'animation-timing-function'] = '' $.fx = { off: (eventPrefix === undefined && testEl.style.transitionProperty === undefined), speeds: {_default: 400, fast: 200, slow: 600}, cssPrefix: prefix, transitionEnd: normalizeEvent('TransitionEnd'), animationEnd: normalizeEvent('AnimationEnd') } $.fn.animate = function (properties, duration, ease, callback, delay) { if ($.isFunction(duration)) callback = duration, ease = undefined, duration = undefined if ($.isFunction(ease)) callback = ease, ease = undefined if ($.isPlainObject(duration)) ease = duration.easing, callback = duration.complete, delay = duration.delay, duration = duration.duration if (duration) duration = (typeof duration == 'number' ? duration : ($.fx.speeds[duration] || $.fx.speeds._default)) / 1000 if (delay) delay = parseFloat(delay) / 1000 return this.anim(properties, duration, ease, callback, delay) } $.fn.anim = function (properties, duration, ease, callback, delay) { var key, cssValues = {}, cssProperties, transforms = '', that = this, wrappedCallback, endEvent = $.fx.transitionEnd, fired = false if (duration === undefined) duration = $.fx.speeds._default / 1000 if (delay === undefined) delay = 0 if ($.fx.off) duration = 0 if (typeof properties == 'string') { // keyframe animation cssValues[animationName] = properties cssValues[animationDuration] = duration + 's' cssValues[animationDelay] = delay + 's' cssValues[animationTiming] = (ease || 'linear') endEvent = $.fx.animationEnd } else { cssProperties = [] // CSS transitions for (key in properties) if (supportedTransforms.test(key)) transforms += key + '(' + properties[key] + ') ' else cssValues[key] = properties[key], cssProperties.push(dasherize(key)) if (transforms) cssValues[transform] = transforms, cssProperties.push(transform) if (duration > 0 && typeof properties === 'object') { cssValues[transitionProperty] = cssProperties.join(', ') cssValues[transitionDuration] = duration + 's' cssValues[transitionDelay] = delay + 's' cssValues[transitionTiming] = (ease || 'linear') } } wrappedCallback = function (event) { if (typeof event !== 'undefined') { if (event.target !== event.currentTarget) return // makes sure the event didn't bubble from "below" $(event.target).unbind(endEvent, wrappedCallback) } else $(this).unbind(endEvent, wrappedCallback) // triggered by setTimeout fired = true $(this).css(cssReset) callback && callback.call(this) } if (duration > 0) { this.bind(endEvent, wrappedCallback) // transitionEnd is not always firing on older Android phones // so make sure it gets fired setTimeout(function () { if (fired) return wrappedCallback.call(that) }, ((duration + delay) * 1000) + 25) } // trigger page reflow so new elements can animate this.size() && this.get(0).clientLeft this.css(cssValues) if (duration <= 0) setTimeout(function () { that.each(function () { wrappedCallback.call(this) }) }, 0) return this } testEl = null
module.exports = { 'timeout': 2000, 'base': '', 'grep': null, 'directory': 'specs', 'pattern': '**/*.spec.js', 'ui': 'bdd', 'reporter': 'dot', 'require': { 'base': 'public', 'paths': {} }, 'mocks': {}, 'server': { 'port': 9876 } };
'use strict'; module.exports = { db: 'mongodb://localhost/mean-dev', app: { name: 'MEAN - FullStack JS - Development' }, facebook: { clientID: 'APP_ID', clientSecret: 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: 'CONSUMER_KEY', clientSecret: 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, github: { clientID: 'APP_ID', clientSecret: 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/github/callback' }, google: { clientID: 'APP_ID', clientSecret: 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: 'API_KEY', clientSecret: 'SECRET_KEY', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, smtpdetails:{ transporthost : 'smtp.gmail.com"', transportport: '465', fromaddress: 'nashvilleprofessionaltaxi@gmail.com', pass:'' } };
app.service('UserService', function($rootScope, NotifyService) { var _isLoggedIn = false; this.isLoggedIn = function() { return _isLoggedIn; } this.doCredentialsLogin = function(email, password) { console.log(email, password); //_isLoggedIn = true; //$rootScope.$broadcast('userStateChanged'); }; this.doLogout = function() { _isLoggedIn = false; $rootScope.$broadcast('userStateChanged'); }; });
module.exports = { fetchRooms: require('./fetchRooms'), fetchStays: require('./fetchStays'), createRoom: require('./createRoom'), deleteRoom: require('./deleteRoom'), checkIn: require('./checkIn'), checkAuth: require('./checkAuth'), makeAvailable: require('./makeAvailable'), fetchCharges: require('./fetchCharges'), saveCharges: require('./saveCharges'), employeeLogin: require('./employeeLogin'), getHotelInfo: require('./getHotelInfo'), saveHotelProfile: require('./saveHotelProfile') }
'use strict'; /** * Directive to augment forms with some common functionality. * * Marks each control as touched when a form is submitted. This allows form * errors to show when clicking submit of a pristine form. * * Also, allows for attaching form-wide validator objects. The format of this * object is keyed by the "name" values of each input field. A generic "*" * property can be specified to provide common validators for the whole form. */ angular.module('test.form') .directive('form', function () { return { restrict: 'E', require: 'form', scope: { validators: '=?' }, link: function (scope, element, attrs, FormController) { // Bind the form-wide validator to the form controller. if (angular.isDefined(scope.validators)) { FormController.$lsValidators = scope.validators; } } }; });
import {add_task} from "../sdk"; import {get_tasks} from "../sdk"; import {delete_task} from "../sdk"; //actions dispatch an object only on receiving data from built.io backend export function addTaskAction(taskObject) { return function(dispatch){ return add_task(taskObject) .then(function(res){ dispatch({ type: "addTask", taskItem: res.data }) }) } } export function getTasksAction() { return function(dispatch){ return get_tasks() .then(function(res){ var tasks = res.map(function(data){ return data.data }) dispatch({ type : "getTasks", taskItems: tasks }) }) } } export function deleteTaskAction(task_uid) { return function(dispatch){ return delete_task(task_uid) .then(function(res){ dispatch({ type : "deleteTask", task_id: task_uid }) }) } }
'use strict'; angular.module('conversionrobotApp') .controller('NavbarCtrl', function ($scope, $location, Auth) { $scope.menu = [{ 'title': 'Home', 'link': '/' }]; $scope.isCollapsed = true; $scope.isLoggedIn = Auth.isLoggedIn; $scope.isAdmin = Auth.isAdmin; $scope.getCurrentUser = Auth.getCurrentUser; $scope.logout = function() { Auth.logout(); $location.path('/login'); }; $scope.isActive = function(route) { return route === $location.path(); }; });
import { noRegistryFunctionReturn } from 'config/errors'; import { warnIfDebug } from 'utils/log'; import { fillGaps, hasOwn } from 'utils/object'; import parser from 'src/Ractive/config/runtime-parser'; import { findInstance } from 'shared/registry'; import { isArray, isFunction } from 'utils/is'; import { addFunctions } from 'shared/getFunction'; export default function getPartialTemplate(ractive, name, up) { // If the partial in instance or view heirarchy instances, great let partial = getPartialFromRegistry(ractive, name, up || {}); if (partial) return partial; // Does it exist on the page as a script tag? partial = parser.fromId(name, { noThrow: true }); if (partial) { // parse and register to this ractive instance const parsed = parser.parseFor(partial, ractive); // register extra partials on the ractive instance if they don't already exist if (parsed.p) fillGaps(ractive.partials, parsed.p); // register (and return main partial if there are others in the template) return (ractive.partials[name] = parsed.t); } } function getPartialFromRegistry(ractive, name, up) { // if there was an instance up-hierarchy, cool let partial = findParentPartial(name, up.owner); if (partial) return partial; // find first instance in the ractive or view hierarchy that has this partial const instance = findInstance('partials', ractive, name); if (!instance) { return; } partial = instance.partials[name]; // partial is a function? let fn; if (isFunction(partial)) { fn = partial; // super partial if (fn.styleSet) return fn; fn = partial.bind(instance); fn.isOwner = hasOwn(instance.partials, name); partial = fn.call(ractive, parser); } if (!partial && partial !== '') { warnIfDebug(noRegistryFunctionReturn, name, 'partial', 'partial', { ractive }); return; } // If this was added manually to the registry, // but hasn't been parsed, parse it now if (!parser.isParsed(partial)) { // use the parseOptions of the ractive instance on which it was found const parsed = parser.parseFor(partial, instance); // Partials cannot contain nested partials! // TODO add a test for this if (parsed.p) { warnIfDebug('Partials ({{>%s}}) cannot contain nested inline partials', name, { ractive }); } // if fn, use instance to store result, otherwise needs to go // in the correct point in prototype chain on instance or constructor const target = fn ? instance : findOwner(instance, name); // may be a template with partials, which need to be registered and main template extracted target.partials[name] = partial = parsed.t; } // store for reset if (fn) partial._fn = fn; // if the partial is a pre-parsed template object, import any expressions and update the registry if (partial.v) { addFunctions(partial); return (instance.partials[name] = partial.t); } else { return partial; } } function findOwner(ractive, key) { return hasOwn(ractive.partials, key) ? ractive : findConstructor(ractive.constructor, key); } function findConstructor(constructor, key) { if (!constructor) { return; } return hasOwn(constructor.partials, key) ? constructor : findConstructor(constructor.Parent, key); } function findParentPartial(name, parent) { if (parent) { if ( parent.template && parent.template.p && !isArray(parent.template.p) && hasOwn(parent.template.p, name) ) { return parent.template.p[name]; } else if (parent.up && parent.up.owner) { return findParentPartial(name, parent.up.owner); } } }
'use strict'; angular.module('resources').factory('KnowledgeNodes', ['$resource', function ($resource) { return $resource('api/knowledgeNodes', { resourceId: '@_id' }, { query: { method: 'get', isArray: true } }); } ]);
/** * Our Database Interface */ var mongoose = require('mongoose'); var UserModel = require('./schemas/user'); // Connections var developmentDb = 'mongodb://localhost/test'; var productionDb = 'urlToProductionMongoDb'; var database; var environment = process.env.NODE_ENV || 'development'; if (environment === 'development') { database = developmentDb; mongoose.connect(database); mongoose.set('debug', true); } if (environment === 'production') { database = productionDb; mongoose.connect(database); } // Gets an instance of our connection to our database var db = mongoose.connection; // Logs that the connection has successfully been opened db.on('error', console.error.bind(console, 'connection error:')); // Open the connection db.once('open', function callback () { console.log('Database Connection Successfully Opened at ' + database); }); exports.users = UserModel;
"use strict"; module.exports = {Bag: require("./bag")}; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbImluZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBRUEsS0FBSyxRQUFRLEVBQUksRUFDYixHQUFFLENBQUcsQ0FBQSxPQUFNLEFBQUMsQ0FBQyxPQUFNLENBQUMsQ0FDeEIsQ0FBQztBQUFBIiwiZmlsZSI6ImNvbGxlY3Rpb25zL2luZGV4LmpzIiwic291cmNlUm9vdCI6ImxpYi9lczYiLCJzb3VyY2VzQ29udGVudCI6WyJcInVzZSBzdHJpY3RcIjtcclxuXHJcbm1vZHVsZS5leHBvcnRzID0ge1xyXG4gICAgQmFnOiByZXF1aXJlKFwiLi9iYWdcIilcclxufTsiXX0=
if (typeof define !== 'function') { var define = require('amdefine')(module); } define([ 'thehelp-test', '../../../src/both/thehelp-core/breadcrumbs' ], function( test, Breadcrumbs ) { 'use strict'; var expect = test.expect; var sinon = test.sinon; describe('breadcrumbs', function() { var breadcrumbs; beforeEach(function() { breadcrumbs = new Breadcrumbs(); }); // Public API // ======== if (typeof console === 'undefined' || typeof console.log === 'undefined') { window.console = { log: function() {} }; } describe('#newError', function() { it('is well-formed', function wellFormed() { var err = breadcrumbs.newError('random', {x: 1, y: 2}); console.log(err.stack); var message = err.message || err.description; expect(message).to.equal('random'); expect(err).to.have.property('x', 1); expect(err).to.have.property('y', 2); var stack = err.stack; expect(stack).to.exist; expect(stack).to.match(/test_breadcrumbs.js/); var lines = stack.split('\n'); if (lines[0] === 'Error: random') { expect(lines[1]).to.match(/test_breadcrumbs.js/); } else { expect(lines[0]).to.match(/test_breadcrumbs.js/); } }); }); describe('#add', function() { it('adds current file into error\'s stack', function addCurrent() { var err = breadcrumbs.newError('something'); breadcrumbs.add(err, null, {left: 1, right: 2}); console.log(err.stack); expect(err).to.have.property('stack').that.match(/test_breadcrumbs.js/); var lines = err.stack.split('\n'); if (lines[0] === 'Error: random') { expect(lines[1]).to.match(/\*\*breadcrumb:/); expect(lines[1]).to.match(/test_breadcrumbs.js/); expect(lines[2]).not.to.match(/\*\*breadcrumb:/); expect(lines[2]).to.match(/test_breadcrumbs.js/); } else { expect(lines[0]).to.match(/\*\*breadcrumb:/); expect(lines[0]).to.match(/test_breadcrumbs.js/); expect(lines[1]).not.to.match(/\*\*breadcrumb:/); expect(lines[1]).to.match(/test_breadcrumbs.js/); } }); it('merges keys into error', function() { var err = new Error(); breadcrumbs.add(err, null, {left: 1, right: 2}); expect(err).to.have.property('left', 1); expect(err).to.have.property('right', 2); }); it('does not overwrite message', function() { var err = new Error('original message'); breadcrumbs.add(err, null, {message: 'new message'}); expect(err).to.have.property('message', 'original message'); }); it('does just fine with no err', function() { breadcrumbs.add(); }); it('calls callback and returns true if err provided', function() { var cb = sinon.stub(); var actual = breadcrumbs.add({}, cb); expect(actual).to.equal(true); expect(cb).to.have.property('callCount', 1); }); it('does not call callback and returns false if err provided', function() { var cb = sinon.stub(); var actual = breadcrumbs.add(null, cb); expect(actual).to.equal(false); expect(cb).to.have.property('callCount', 0); }); }); describe('#toString', function() { var err; beforeEach(function() { err = breadcrumbs.newError('Error Message', {one: 1, two: 'two'}); err.stack = 'overridden stack'; }); it('returns empty string if err is null', function() { var actual = breadcrumbs.toString(); expect(actual).to.equal(''); }); it('handles a non-vanilla error', function() { var err = new TypeError('something'); var actual = breadcrumbs.toString(err); console.log(actual); var r = /TypeError/g; var match = actual.match(r); if (!match) { return; } expect(match).to.have.property('length').that.is.below(2); }); it('includes callstack when log is not set', function() { var actual = breadcrumbs.toString(err); console.log(actual); expect(actual).to.match(/overridden stack/); }); it('include callstack if log is "error"', function() { err.log = 'error'; var actual = breadcrumbs.toString(err); expect(actual).to.match(/overridden stack/); }); it('include callstack if log is "warn"', function() { err.log = 'warn'; var actual = breadcrumbs.toString(err); expect(actual).to.match(/overridden stack/); }); it('does not include callstack if log is "info"', function() { err.log = 'info'; var actual = breadcrumbs.toString(err); expect(actual).not.to.match(/overridden stack/); }); }); // Helper functions // ======== describe('#_get', function() { it('returns the current line', function currentLine() { var actual = breadcrumbs._get(); console.log(actual); expect(actual).to.match(/test_breadcrumbs.js/); }); it('removes " at " at start of breadcrumb', function() { breadcrumbs._getStackTrace = sinon.stub().returns([' at blah']); var actual = breadcrumbs._get(); expect(actual).to.equal('**breadcrumb: blah\n'); }); it('handles a no " at " breadcrumb', function() { breadcrumbs._getStackTrace = sinon.stub().returns(['blah']); var actual = breadcrumbs._get(); expect(actual).to.equal('**breadcrumb: blah\n'); }); it('empty returned if no stacktrace', function() { breadcrumbs._getStackTrace = sinon.stub().returns([]); var actual = breadcrumbs._get(); expect(actual).to.equal('**breadcrumb: <empty>\n'); }); }); describe('#_insert', function() { var toInsert; beforeEach(function() { toInsert = 'randomString\n'; breadcrumbs._get = sinon.stub().returns(toInsert); }); it('puts current file into stack', function() { var err = { stack: 'Error: something\n' + ' at line 1\n' + ' at line 2\n' }; breadcrumbs._insert(err); expect(err).to.have.property('stack').that.match(/randomString/); var lines = err.stack.split('\n'); expect(lines).to.have.property('1', ' at randomString'); }); it('does just fine with an err with no " at " lines', function() { var err = { stack: 'some random text' }; breadcrumbs._insert(err); expect(err).to.have.property('stack').that.match(/randomString/); var lines = err.stack.split('\n'); expect(lines).to.have.property('0', 'randomString'); }); it('does just fine with no err', function() { breadcrumbs._insert(); }); }); describe('#_prepareStack', function() { it('removes everything up to first at "Error:"', function() { var err = { stack: 'Error: error message\nsecond part of error\nthird part of error\n' + ' at second line\n' + ' at third line' }; var expected = ' at second line\n' + ' at third line'; var actual = breadcrumbs._prepareStack(err); expect(actual).to.equal(expected); }); it('doesn\'t remove first line if no "Error"', function() { var err = { stack: ' at second line\n' + ' at third line' }; var actual = breadcrumbs._prepareStack(err); expect(actual).to.equal(err.stack); }); if (typeof process !== 'undefined') { it('removes process.cwd()', function() { var err = { stack: process.cwd() + ' ' + process.cwd() + ' ' + process.cwd() }; var actual = breadcrumbs._prepareStack(err); expect(actual).to.equal(' '); }); } }); }); });
var React = require('react'); var ReactPropTypes = React.PropTypes; var classnames = require('classnames'); var Input = React.createClass({ propTypes: { className: ReactPropTypes.string, id: ReactPropTypes.string, onClick: ReactPropTypes.func, onChange: ReactPropTypes.func, type: ReactPropTypes.string.isRequired, floatingLabel: ReactPropTypes.bool, errorMessage: ReactPropTypes.string, expandable: ReactPropTypes.bool, expandableHolder: ReactPropTypes.bool, isInvalid: ReactPropTypes.bool, pattern: ReactPropTypes.string, placeholder: ReactPropTypes.string, hidden: ReactPropTypes.bool, autoFocus: ReactPropTypes.bool, disabled: ReactPropTypes.bool, value: ReactPropTypes.string, label: ReactPropTypes.string }, /** * Get default props * @returns {{autoFocus: boolean}} */ getDefaultProps: function() { return { autoFocus: false } }, /** * @return {object} */ render: function() { var $this = this; var wrapperClassName = classnames( 'mdl-textfield', 'mdl-js-textfield', { 'hidden': $this.props.hidden, 'mdl-textfield--floating-label': $this.props.floatingLabel, 'mdl-textfield__error': $this.props.error, 'mdl-textfield--expandable': $this.props.expandable, 'mdl-input__expandable-holder': $this.props.expandableHolder, 'is-invalid': $this.props.isInvalid }); var inputClassName = classnames( 'mdl-textfield__input', this.props.className); return ( <div className={wrapperClassName}> <input id={this.props.id} className={inputClassName} onClick={this.props.onClick} autoFocus={this.props.autoFocus} type={this.props.type} disabled={this.props.disabled} pattern={this.props.pattern} placeholder={this.props.placeholder} value={this.props.value} onChange={this._onChange} > </input> <label className="mdl-textfield__label" htmlFor={this.props.id}> {this.props.label} </label> <span className="mdl-textfield__error">{this.props.errorMessage}</span> </div> ); }, /** * On change * @param event * @private */ _onChange: function(event) { this.props.onChange(event); this.setState({value: event.target.value}); } }); module.exports = Input;
const atob = require('atob') const oAuthState = require('../helpers/oauth-state') /** * initializes the oAuth flow for a provider. * * @param {object} req * @param {object} res */ module.exports = function connect (req, res) { const { secret } = req.companion.options let state = oAuthState.generateState(secret) if (req.query.state) { const origin = JSON.parse(atob(req.query.state)) state = oAuthState.addToState(state, origin, secret) } if (req.companion.options.server.oauthDomain) { state = oAuthState.addToState(state, { companionInstance: req.companion.buildURL('', true) }, secret) } if (req.companion.clientVersion) { state = oAuthState.addToState(state, { clientVersion: req.companion.clientVersion }, secret) } if (req.query.uppyPreAuthToken) { state = oAuthState.addToState(state, { preAuthToken: req.query.uppyPreAuthToken }, secret) } res.redirect(req.companion.buildURL(`/connect/${req.companion.provider.authProvider}?state=${state}`, true)) }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import TestHookStore from './TestHookStore'; // Public: Higher-order React component to factilitate adding hooks to the // global test hook store. // // WrappedComponent - Component to be wrapped, will be passed an initial // property called 'generateTestHook' which is a function // generator that will add a component to the test hook // store. // // Example // // import { hook } from 'cavy'; // // class MyComponent extends React.Component { // // .... // } // // const TestableMyComponent = hook(MyComponent); // export default TestableMyComponent; // // Returns the new component. export default function hook(WrappedComponent, enableTesting = false) { if (enableTesting) { const wrapperComponent = class extends Component { constructor(props, context) { super(props, context); this.generateTestHook = this.generateTestHook.bind(this); } // Public: Call `this.props.generateTestHook` in a ref within your // component to add it to the test hook store for later use in a spec. // // React calls this function twice during the render lifecycle; once to // 'unset' the ref, and once to set it. // // identifier - String, the key the component will be stored under in the // test hook store. // f - Your own ref generating function (optional). // // Examples // // <TextInput // ref={this.props.generateTestHook('MyComponent.textinput', (c) => this.textInput = c)} // // ... // /> // // <Button // ref={this.props.generateTestHook('MyComponent.button')} // title="Press me!" // /> // // Returns the ref-generating anonymous function which will be called by // React. generateTestHook(identifier, f = () => {}) { return component => { if (!this.context.testHooks) { f(component); return; } if (component) { this.context.testHooks.add(identifier, component); } else { this.context.testHooks.remove(identifier, component); } f(component); }; } render() { return <WrappedComponent generateTestHook={this.generateTestHook} {...this.props} />; } }; wrapperComponent.contextTypes = { testHooks: PropTypes.instanceOf(TestHookStore) }; return wrapperComponent; } else { return WrappedComponent; } }
/* * sortable_events.js */ (function($) { module("sortable: events"); test("start", function() { expect( 7 ); var hash; $("#sortable").sortable({ start: function( e, ui ) { hash = ui; } }).find("li:eq(0)").simulate( "drag", { dy: 10 }); ok(hash, 'start event triggered'); ok(hash.helper, 'UI hash includes: helper'); ok(hash.placeholder, 'UI hash includes: placeholder'); ok(hash.item, 'UI hash includes: item'); ok(!hash.sender, 'UI hash does not include: sender'); // todo: see if these events should actually have sane values in them ok('position' in hash, 'UI hash includes: position'); ok('offset' in hash, 'UI hash includes: offset'); }); test("sort", function() { expect( 7 ); var hash; $("#sortable").sortable({ sort: function( e, ui ) { hash = ui; } }).find("li:eq(0)").simulate( "drag", { dy: 10 }); ok(hash, 'sort event triggered'); ok(hash.helper, 'UI hash includes: helper'); ok(hash.placeholder, 'UI hash includes: placeholder'); ok(hash.position && ('top' in hash.position && 'left' in hash.position), 'UI hash includes: position'); ok(hash.offset && (hash.offset.top && hash.offset.left), 'UI hash includes: offset'); ok(hash.item, 'UI hash includes: item'); ok(!hash.sender, 'UI hash does not include: sender'); }); test("change", function() { expect( 8 ); var hash; $("#sortable").sortable({ change: function( e, ui ) { hash = ui; } }).find("li:eq(0)").simulate( "drag", { dx: 1, dy: 1 }); ok(!hash, '1px drag, change event should not be triggered'); $("#sortable").sortable({ change: function( e, ui ) { hash = ui; } }).find("li:eq(0)").simulate( "drag", { dy: 22 }); ok(hash, 'change event triggered'); ok(hash.helper, 'UI hash includes: helper'); ok(hash.placeholder, 'UI hash includes: placeholder'); ok(hash.position && ('top' in hash.position && 'left' in hash.position), 'UI hash includes: position'); ok(hash.offset && (hash.offset.top && hash.offset.left), 'UI hash includes: offset'); ok(hash.item, 'UI hash includes: item'); ok(!hash.sender, 'UI hash does not include: sender'); }); test("beforeStop", function() { expect( 7 ); var hash; $("#sortable").sortable({ beforeStop: function( e, ui ) { hash = ui; } }).find("li:eq(0)").simulate( "drag", { dy: 20 }); ok(hash, 'beforeStop event triggered'); ok(hash.helper, 'UI hash includes: helper'); ok(hash.placeholder, 'UI hash includes: placeholder'); ok(hash.position && ('top' in hash.position && 'left' in hash.position), 'UI hash includes: position'); ok(hash.offset && (hash.offset.top && hash.offset.left), 'UI hash includes: offset'); ok(hash.item, 'UI hash includes: item'); ok(!hash.sender, 'UI hash does not include: sender'); }); test("stop", function() { expect( 7 ); var hash; $("#sortable").sortable({ stop: function( e, ui ) { hash = ui; } }).find("li:eq(0)").simulate( "drag", { dy: 20 }); ok(hash, 'stop event triggered'); ok(!hash.helper, 'UI should not include: helper'); ok(hash.placeholder, 'UI hash includes: placeholder'); ok(hash.position && ('top' in hash.position && 'left' in hash.position), 'UI hash includes: position'); ok(hash.offset && (hash.offset.top && hash.offset.left), 'UI hash includes: offset'); ok(hash.item, 'UI hash includes: item'); ok(!hash.sender, 'UI hash does not include: sender'); }); test("update", function() { expect( 8 ); var hash; $("#sortable").sortable({ update: function( e, ui ) { hash = ui; } }).find("li:eq(0)").simulate( "drag", { dx: 1, dy: 1 }); ok(!hash, '1px drag, update event should not be triggered'); $("#sortable").sortable({ update: function( e, ui ) { hash = ui; } }).find("li:eq(0)").simulate( "drag", { dy: 22 }); ok(hash, 'update event triggered'); ok(!hash.helper, 'UI hash should not include: helper'); ok(hash.placeholder, 'UI hash includes: placeholder'); ok(hash.position && ('top' in hash.position && 'left' in hash.position), 'UI hash includes: position'); ok(hash.offset && (hash.offset.top && hash.offset.left), 'UI hash includes: offset'); ok(hash.item, 'UI hash includes: item'); ok(!hash.sender, 'UI hash does not include: sender'); }); test("#3019: Stop fires too early", function() { expect(2); var helper = null, el = $("#sortable").sortable({ stop: function(event, ui) { helper = ui.helper; } }); TestHelpers.sortable.sort($("li", el)[0], 0, 44, 2, 'Dragging the sortable'); equal(helper, null, "helper should be false"); }); test('#4752: link event firing on sortable with connect list', function () { expect( 10 ); var fired = {}, hasFired = function (type) { return (type in fired) && (true === fired[type]); }; $('#sortable').clone().attr('id', 'sortable2').insertAfter('#sortable'); $('#qunit-fixture ul').sortable({ connectWith: '#qunit-fixture ul', change: function () { fired.change = true; }, receive: function () { fired.receive = true; }, remove: function () { fired.remove = true; } }); $('#qunit-fixture ul').bind('click.ui-sortable-test', function () { fired.click = true; }); $('#sortable li:eq(0)').simulate('click'); ok(!hasFired('change'), 'Click only, change event should not have fired'); ok(hasFired('click'), 'Click event should have fired'); // Drag an item within the first list fired = {}; $('#sortable li:eq(0)').simulate('drag', { dx: 0, dy: 40 }); ok(hasFired('change'), '40px drag, change event should have fired'); ok(!hasFired('receive'), 'Receive event should not have fired'); ok(!hasFired('remove'), 'Remove event should not have fired'); ok(!hasFired('click'), 'Click event should not have fired'); // Drag an item from the first list to the second, connected list fired = {}; $('#sortable li:eq(0)').simulate('drag', { dx: 0, dy: 150 }); ok(hasFired('change'), '150px drag, change event should have fired'); ok(hasFired('receive'), 'Receive event should have fired'); ok(hasFired('remove'), 'Remove event should have fired'); ok(!hasFired('click'), 'Click event should not have fired'); }); /* test("receive", function() { ok(false, "missing test - untested code is broken code."); }); test("remove", function() { ok(false, "missing test - untested code is broken code."); }); test("over", function() { ok(false, "missing test - untested code is broken code."); }); test("out", function() { ok(false, "missing test - untested code is broken code."); }); test("activate", function() { ok(false, "missing test - untested code is broken code."); }); test("deactivate", function() { ok(false, "missing test - untested code is broken code."); }); */ })(jQuery);
import Router from '../../../src/http/routing/router' import Route from '../../../src/http/routing/route' import Request from '../../../src/http/request' var expect = require('chai').expect describe('http/routing/router.js', () => { let router, route, name, path beforeEach(() => { name = 'home' path = '/my-path' router = new Router() route = new Route(name, Request.METHOD_POST, path) }) it('[add] should allow to add a new route', () => { expect(router.length).to.equal(0) router.add(route) expect(router.length).to.equal(1) router.add({name: 'another'}) expect(router.length).to.equal(2) }) it('[has] should return false at first, and true on latter call', () => { expect(router.has(name)).to.be.false router.add(route) expect(router.has(name)).to.be.true }) it('[remove] should a specific route by name', () => { router.add(route) expect(router.has(name)).to.be.true router.remove(name) expect(router.has(name)).to.be.false }) it('[route] should return appropriate route', () => { let request = new Request() request.getUri().set(Request.URI_HOST, 'vn.domain.com') request.getUri().set(Request.URI_PATH, '/accounts/1988-john') let route_1 = Route.from({ name: 'user_account_id', host: '{country}.domain.com', path: '/accounts/{id}', requirements: { id: /\d+/ } }) let route_2 = Route.from({ name: 'user_account_name', host: '{country}.domain.com', path: '/accounts/{id}-{name}', requirements: { id: /\d+/ } }) router.add(route_1) router.add(route_2) route = router.route(request) expect(route.getName()).to.equal('user_account_name') expect(route.getMatches()).to.deep.equal({ country: 'vn', id: '1988', name: 'john' }) expect(request.getAttributes().all()).to.deep.equal({ country: 'vn', id: '1988', name: 'john' }) }) })
class ContactListController { constructor($http) { this.$http = $http; }; $postLink() { this.$http.get('http://www.json-generator.com/api/json/get/bVespqTlrC?indent=2') .then(response => this.list = response.data); } updateContact(contact, prop, value) { contact[prop] = value; }; deleteContact(contact) { const index = this.list.indexOf(contact); this.list.splice(index, 1); }; addContact(name, location) { const newContact = { name: name, location: location }; this.list.push(newContact); this.name = ''; this.location = ''; }; } angular.module('app') .component('contactList', { template: `<h1>Список контактов</h1> <form name="AddNewContactForm" ng-submit="$ctrl.addContact($ctrl.name, $ctrl.location);"> <label>Имя нового контакта: <input ng-model="$ctrl.name"> </label> <label>Город нового контакта: <input ng-model="$ctrl.location"> </label> <button type="submit" ng-disabled="!$ctrl.name">Добавить в список контактов</button> </form> <contact-detail ng-repeat="person in $ctrl.list | orderBy: 'name' track by $index" contact="person" on-delete="$ctrl.deleteContact(contact)" on-update="$ctrl.updateContact(contact, prop, value)"> </contact-detail> <p>{{$ctrl.list}}</p>`, controller: ContactListController });
var oAngTestApp, oShout; oShout = function() { alert("this is another one"); }; oAngTestApp = angular.module("AppNgenterTest", ["ngEnterBinder"]); /* create a test controller */ oAngTestApp.controller("TestCtrl", [ "$scope", function($scope) { $scope.shoutOut = function() { alert("Enter has been pressed"); }; } ]);
// original code from doT.js - 2011, Laura Doktorova https://github.com/olado/doT // simplified version of the template which allows only interpolation mucilage.template = function(str) { str = ( "var out='" + str.replace(/\s*<!\[CDATA\[\s*|\s*\]\]>\s*|[\r\n\t]|(\/\*[\s\S]*?\*\/)/g, '') .replace(/\\/g, '\\\\') .replace(/'/g, "\\'") .replace(/\{\{=([\s\S]+?)\}\}/g, function(match, code) { return "'+(" + code.replace(/\\'/g, "'").replace(/\\\\/g,"\\").replace(/[\r\t\n]/g, ' ') + ")+'"; }) + "';return out;" ) .replace(/\n/g, '\\n') .replace(/\t/g, '\\t') .replace(/\r/g, '\\r') .split("out+='';").join('') .split("var out='';out+=").join('var out='); try { return new Function('$', str); } catch (e) { throw e; } };
'use strict'; /** * Module dependencies. */ var path = require('path'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')), logHandler = require(path.resolve('./modules/mago/server/controllers/logs.server.controller')), db = require(path.resolve('./config/lib/sequelize')).models, sequelize_t = require(path.resolve('./config/lib/sequelize')), DBModel = db.vod, querstring = require('querystring'), fs = require('fs'), winston = require(path.resolve('./config/lib/winston')), saas_functions = require(path.resolve('./custom_functions/saas_functions')); const download = require('download'); const axios = require('axios').default; const { Op } = require('sequelize'); const { getStorage } = require('../../../../config/lib/storage_manager'); const { downloadToStorage } = require('../../../../custom_functions/storage'); function link_vod_with_genres(vod_id,array_category_ids, db_model, company_id) { var transactions_array = []; //todo: references must be updated to non-available, not deleted return db_model.update( { is_available: false }, { where: { vod_id: vod_id, category_id: {[Op.notIn]: array_category_ids}, company_id: company_id } } ).then(function (result) { return sequelize_t.sequelize.transaction(function (t) { for (var i = 0; i < array_category_ids.length; i++) { transactions_array.push( db_model.upsert({ vod_id: vod_id, category_id: array_category_ids[i], is_available: true, company_id: company_id, }, {transaction: t}).catch(function(error){ winston.error(error); }) ) } return Promise.all(transactions_array, {transaction: t}); //execute transaction }).then(function (result) { return {status: true, message:'transaction executed correctly'}; }).catch(function (err) { winston.error("Error at link vod with genres, error: ",err); return {status: false, message:'error executing transaction'}; }) }).catch(function (err) { winston.error("Error at deleting existing packages, error: ", err); return {status: false, message:'error deleting existing packages'}; }) } function link_vod_with_packages(item_id, data_array, model_instance, company_id) { var transactions_array = []; var destroy_where = (data_array.length > 0) ? { vod_id: item_id, package_id: {[Op.notIn]: data_array}, company_id: company_id } : { vod_id: item_id, company_id: company_id }; return model_instance.destroy({ where: destroy_where }).then(function (result) { return sequelize_t.sequelize.transaction(function (t) { for (var i = 0; i < data_array.length; i++) { transactions_array.push( model_instance.upsert({ vod_id: item_id, package_id: data_array[i], company_id: company_id }, {transaction: t}) ) } return Promise.all(transactions_array, {transaction: t}); //execute transaction }).then(function (result) { return {status: true, message:'transaction executed correctly'}; }).catch(function (err) { winston.error("Error at linking vod with packages, error: ",err); return {status: false, message:'error executing transaction'}; }) }).catch(function (err) { winston.error(err); return {status: false, message:'error deleteting existing packages'}; }) } /** * Create */ exports.create = async (req, res) => { if(!req.body.clicks) req.body.clicks = 0; if(!req.body.duration) req.body.duration = 0; if (!req.body.original_title) req.body.original_title = req.body.title; var array_vod_vod_categories = req.body.vod_vod_categories || []; delete req.body.vod_vod_categories; var array_package_vod = req.body.package_vods || []; delete req.body.package_vods; req.body.company_id = req.token.company_id; //save record for this company var limit = req.app.locals.backendsettings[req.token.company_id].asset_limitations.vod_limit; try { let storage = await getStorage(req.token.company_id); if(!req.body.icon_url.startsWith("/files/vod/")) { var origin_url_icon_url = 'https://image.tmdb.org/t/p/w500'+req.body.icon_url; var destination_path_icon_url = "files/vod"; var vod_filename_icon_url = req.body.icon_url; //get name of new file try { await downloadToStorage(origin_url_icon_url, storage, destination_path_icon_url + vod_filename_icon_url); winston.info("Success downloading tmdb image"); } catch (error) { winston.error("Error downloading tmdb image ", error); } // delete req.body.poster_path; req.body.icon_url = '/files/vod'+vod_filename_icon_url; } if(!req.body.image_url.startsWith("/files/vod/")) { var origin_url_image_url = 'https://image.tmdb.org/t/p/original'+req.body.image_url; var destination_path_image_url = "files/vod"; var vod_filename_image_url = req.body.image_url; //get name of new file try { await downloadToStorage(origin_url_image_url, storage, destination_path_image_url + vod_filename_image_url); winston.info("Success downloading tmdb image"); } catch (error) { winston.error("Error downloading tmdb image ", error); } // delete req.body.backdrop_path; req.body.image_url = '/files/vod'+vod_filename_image_url; } } catch(err) { winston.error("Failed accessing storage ", err); } saas_functions.check_limit('vod', req.token.company_id, limit).then(function(limit_reached){ if(limit_reached === true) return res.status(400).send({message: "You have reached the limit number of vod items you can create for this plan. "}); else{ DBModel.create(req.body).then(function(result) { if (!result) { return res.status(400).send({message: 'fail create data'}); } else { logHandler.add_log(req.token.id, req.ip.replace('::ffff:', ''), 'created', JSON.stringify(req.body)); return link_vod_with_genres(result.id,array_vod_vod_categories, db.vod_vod_categories, req.token.company_id).then(function(t_result) { if (t_result.status) { return link_vod_with_packages(result.id, array_package_vod, db.package_vod, req.token.company_id).then(function(t_result) { if (t_result.status) { return res.jsonp(result); } else { return res.send(t_result); } }) } else { return res.send(t_result); } }) } }).catch(function(err) { winston.error("Error at creating vod, error: ",err); return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); }); } }).catch(function(error){ winston.error("Error checking for the limit number of vod items for company with id ",req.token.company_id," - ", error); return res.status(400).send({message: "The limit number of vod items you can create for this plan could not be verified. Check your log file for more information."}); }); }; /** * Show current */ exports.read = async (req, res) => { const id = req.params.tmdbId if (!(id % 1 === 0)) { //check if it's integer return res.status(404).send({ message: 'Data is invalid' }); } const options = { method: 'GET', url: `https://api.themoviedb.org/3/movie/${id}?` + querstring.stringify({ language: 'en-US', api_key: 'fe4104e791060715f23f1244a51b926a', append_to_response: 'credits,videos' }) }; try { let response = await axios(options); var b; var starring_array = ''; for (b = 0; b < response.data.credits.cast.length; b++) { starring_array += response.data.credits.cast[b].name + ','; } //./get all starring/cast from tmdb //get director from tmdb var c; var director_array = ''; for (c = 0; c < response.data.credits.crew.length; c++) { if (response.data.credits.crew[c].job === 'Director') director_array += response.data.credits.crew[c].name; } //./get director from tmdb //get trailer url if (response.data.videos.results.length > 0) { response.data.trailer_url = 'https://www.youtube.com/watch?v=' + response.data.videos.results[0].key; } else { response.data.trailer_url = ''; } //./get trailer url response.data.description = response.data.overview; delete response.data.overview; response.data.duration = response.data.runtime; delete response.data.runtime; response.data.adult_content = response.data.adult; delete response.data.adult; response.data.icon_url = response.data.poster_path; delete response.data.poster_path; response.data.image_url = response.data.backdrop_path; delete response.data.backdrop_path; response.data.starring = starring_array; delete response.data.credits; response.data.director = director_array; res.send(response.data); } catch (error) { winston.error("There has been an error getting tmdb of movie, check tmdb token", error); return res.status(500).send({ status: 500, message: "There has been an error getting tmbd of movie, check tmbd token" }); } }; exports.list = async (req, res) => { let query = req.query; let page = query.page || 1; if (!query.q) { res.json([]); return; } if (parseInt(query._start)) page = parseInt(query._start); const options = { method: 'GET', url: 'https://api.themoviedb.org/3/search/movie?' + querstring.stringify({ page: page, query: query.q, api_key: 'fe4104e791060715f23f1244a51b926a', language: "en-US" }) }; try { let response = await axios(options) res.send(response.data.results); } catch (error) { winston.error("There has been an error getting tmdb list of movies, check tmdb token", error); return res.status(500).send({ status: 500, message: "There has been an error getting tmbd list of movies, check tmbd token" }); } };
var React = require('react'); var cs = require('classnames'); var $ = React.DOM; // Some shared attrs for JsonTable and JsonRow var defaultSettings = { header: true, noRowsMessage: 'No items', classPrefix: 'json' }, getSetting = function( name ){ var settings = this.props.settings; if( !settings || typeof settings[ name ] == 'undefined' ) return defaultSettings[ name ]; return settings[ name ]; } ; var JsonTable = React.createClass({ getSetting: getSetting, render: function(){ if (!this.props.rows || this.props.rows.length === 0) { var noRowsMessage = this.getSetting('noRowsMessage'); if (typeof(noRowsMessage) === 'object') { // If noRowsMessage is an element, return it return noRowsMessage; } else { // If it's a string, render it within a <div> element return $.div({}, this.getSetting('noRowsMessage')); } } var cols = this.normalizeColumns(), contents = [this.renderRows( cols )] ; if( this.getSetting('header') ) contents.unshift( this.renderHeader( cols ) ); var tableClass = cs( this.getSetting( 'classPrefix' ) + 'Table', this.props.className ); return $.table({ className: tableClass }, contents ); }, renderHeader: function( cols ){ var me = this, prefix = this.getSetting( 'classPrefix' ), headerClass = this.getSetting( 'headerClass' ), cells = cols.map( function(col){ var className = prefix + 'Column'; if (headerClass) { className = headerClass( className, col.key ); } if (col.label.indexOf('$') > -1 || col.label.indexOf('GP') > -1 || col.label.indexOf('Revenue') > -1) { className += " text-right"; } return $.th( { className: className, key: col.key, onClick: me.onClickHeader, "data-key": col.key }, col.label ); }) ; return $.thead({ key: 'th'}, $.tr({ key: this.getSetting('classPrefix') + 'THead', className: prefix + 'Header' }, cells ) ); }, renderRows: function( cols ){ var me = this, items = this.props.rows, settings = this.props.settings || {}; var rows = items.map( function( item, index ){ var key = me.getKey( item ); return React.createElement(Row, { key: index, reactKey: key, item: item, settings: settings, columns: cols, i: index, onClickRow: me.onClickRow, onClickCell: me.onClickCell }); }); return $.tbody({ key: this.getSetting('classPrefix') + 'TBody' }, rows); }, getItemField: function( item, field ){ return item[ field ]; }, normalizeColumns: function(){ var getItemField = this.getItemField, cols = this.props.columns, items = this.props.rows ; if( !cols ){ if( !items || !items.length ) return []; return Object.keys( items[0] ).map( function( key ){ return { key: key, label: key, cell: getItemField }; }); } return cols.map( function( col ){ var key; if( typeof col == 'string' ){ return { key: col, label: col, cell: getItemField }; } if( typeof col == 'object' ){ key = col.key || col.label; // This is about get default column definition // we use label as key if not defined // we use key as label if not defined // we use getItemField as cell function if not defined return { key: key, label: col.label || key, cell: col.cell || getItemField }; } return { key: 'unknown', name:'unknown', cell: 'Unknown' }; }); }, getKey: function( item ){ var field = this.props.settings && this.props.settings.keyField; if( field && item[ field ] ) return item[ field ]; if( item.id ) return item.id; if( item._id ) return item._id; }, shouldComponentUpdate: function(){ return true; }, onClickRow: function( e, item ){ if( this.props.onClickRow ){ this.props.onClickRow( e, item ); } }, onClickHeader: function( e ){ if( this.props.onClickHeader ){ this.props.onClickHeader( e, e.target.dataset.key ); } }, onClickCell: function( e, key, item ){ if( this.props.onClickCell ){ this.props.onClickCell( e, key, item ); } } }); var Row = React.createClass({ getSetting: getSetting, render: function() { var me = this, props = this.props, cellClass = this.getSetting('cellClass'), rowClass = this.getSetting('rowClass'), prefix = this.getSetting('classPrefix'), cells = props.columns.map(function(col) { var content = col.cell, key = col.key, className = prefix + 'Cell ' + prefix + 'Cell_' + key; if (cellClass) className = cellClass( className, key, props.item ); if (typeof content == 'function') { content = content(props.item, key); } // Make sure content is not null content = content || ''; if (content.toString().indexOf('$') === 0 || content.toString().indexOf('$') === 1) { // Currency - align right className += " text-right"; } if (content.toString().trim().length === 0) { // Put in a space so the row isn't all stupid content = '<div>&nbsp;</div>'; } return $.td( { className: className, key: key, "data-key": key, onClick: me.onClickCell, dangerouslySetInnerHTML: {__html: content} }); }) ; var className = prefix + 'Row ' + prefix + (props.i % 2 ? 'Odd' : 'Even') ; if( props.reactKey ) className += ' ' + prefix + 'Row_' + props.reactKey; if( rowClass ) className = rowClass( className, props.item ); return $.tr({ className: className, onClick: me.onClickRow }, cells ); }, onClickCell: function( e ){ this.props.onClickCell( e, e.target.dataset.key, this.props.item ); }, onClickRow: function( e ){ this.props.onClickRow( e, this.props.item ); } }); module.exports = JsonTable;
export const ic_music_note_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"circle","attribs":{"cx":"10.01","cy":"17","opacity":".3","r":"2"},"children":[]},{"name":"path","attribs":{"d":"M12 3l.01 10.55c-.59-.34-1.27-.55-2-.55C7.79 13 6 14.79 6 17s1.79 4 4.01 4S14 19.21 14 17V7h4V3h-6zm-1.99 16c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"},"children":[]}]};
// 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. // // Copyright 2009 Google Inc. All Rights Reserved /** * Defines a Timestamp class for representing a 64-bit two's-complement * integer value, which faithfully simulates the behavior of a Java "Timestamp". This * implementation is derived from TimestampLib in GWT. * * Constructs a 64-bit two's-complement integer, given its low and high 32-bit * values as *signed* integers. See the from* functions below for more * convenient ways of constructing Timestamps. * * The internal representation of a Timestamp is the two given signed, 32-bit values. * We use 32-bit pieces because these are the size of integers on which * Javascript performs bit-operations. For operations like addition and * multiplication, we split each number into 16-bit pieces, which can easily be * multiplied within Javascript's floating-point representation without overflow * or change in sign. * * In the algorithms below, we frequently reduce the negative case to the * positive case by negating the input(s) and then post-processing the result. * Note that we must ALWAYS check specially whether those values are MIN_VALUE * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as * a positive number, it overflows back into a negative). Not handling this * case would often result in infinite recursion. * * @class Represents the BSON Timestamp type. * @param {Number} low the low (signed) 32 bits of the Timestamp. * @param {Number} high the high (signed) 32 bits of the Timestamp. */ function Timestamp(low, high) { if(!(this instanceof Timestamp)) return new Timestamp(low, high); this._bsontype = 'Timestamp'; /** * @type {number} * @api private */ this.low_ = low | 0; // force into 32 signed bits. /** * @type {number} * @api private */ this.high_ = high | 0; // force into 32 signed bits. }; /** * Return the int value. * * @return {Number} the value, assuming it is a 32-bit integer. * @api public */ Timestamp.prototype.toInt = function() { return this.low_; }; /** * Return the Number value. * * @return {Number} the closest floating-point representation to this value. * @api public */ Timestamp.prototype.toNumber = function() { return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); }; /** * Return the JSON value. * * @return {String} the JSON representation. * @api public */ Timestamp.prototype.toJSON = function() { return this.toString(); } /** * Return the String value. * * @param {Number} [opt_radix] the radix in which the text should be written. * @return {String} the textual representation of this value. * @api public */ Timestamp.prototype.toString = function(opt_radix) { var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (this.isZero()) { return '0'; } if (this.isNegative()) { if (this.equals(Timestamp.MIN_VALUE)) { // We need to change the Timestamp value before it can be negated, so we remove // the bottom-most digit in this base and then recurse to do the rest. var radixTimestamp = Timestamp.fromNumber(radix); var div = this.div(radixTimestamp); var rem = div.multiply(radixTimestamp).subtract(this); return div.toString(radix) + rem.toInt().toString(radix); } else { return '-' + this.negate().toString(radix); } } // Do several (6) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); var rem = this; var result = ''; while (true) { var remDiv = rem.div(radixToPower); var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); var digits = intval.toString(radix); rem = remDiv; if (rem.isZero()) { return digits + result; } else { while (digits.length < 6) { digits = '0' + digits; } result = '' + digits + result; } } }; /** * Return the high 32-bits value. * * @return {Number} the high 32-bits as a signed value. * @api public */ Timestamp.prototype.getHighBits = function() { return this.high_; }; /** * Return the low 32-bits value. * * @return {Number} the low 32-bits as a signed value. * @api public */ Timestamp.prototype.getLowBits = function() { return this.low_; }; /** * Return the low unsigned 32-bits value. * * @return {Number} the low 32-bits as an unsigned value. * @api public */ Timestamp.prototype.getLowBitsUnsigned = function() { return (this.low_ >= 0) ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; }; /** * Returns the number of bits needed to represent the absolute value of this Timestamp. * * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. * @api public */ Timestamp.prototype.getNumBitsAbs = function() { if (this.isNegative()) { if (this.equals(Timestamp.MIN_VALUE)) { return 64; } else { return this.negate().getNumBitsAbs(); } } else { var val = this.high_ != 0 ? this.high_ : this.low_; for (var bit = 31; bit > 0; bit--) { if ((val & (1 << bit)) != 0) { break; } } return this.high_ != 0 ? bit + 33 : bit + 1; } }; /** * Return whether this value is zero. * * @return {Boolean} whether this value is zero. * @api public */ Timestamp.prototype.isZero = function() { return this.high_ == 0 && this.low_ == 0; }; /** * Return whether this value is negative. * * @return {Boolean} whether this value is negative. * @api public */ Timestamp.prototype.isNegative = function() { return this.high_ < 0; }; /** * Return whether this value is odd. * * @return {Boolean} whether this value is odd. * @api public */ Timestamp.prototype.isOdd = function() { return (this.low_ & 1) == 1; }; /** * Return whether this Timestamp equals the other * * @param {Timestamp} other Timestamp to compare against. * @return {Boolean} whether this Timestamp equals the other * @api public */ Timestamp.prototype.equals = function(other) { return (this.high_ == other.high_) && (this.low_ == other.low_); }; /** * Return whether this Timestamp does not equal the other. * * @param {Timestamp} other Timestamp to compare against. * @return {Boolean} whether this Timestamp does not equal the other. * @api public */ Timestamp.prototype.notEquals = function(other) { return (this.high_ != other.high_) || (this.low_ != other.low_); }; /** * Return whether this Timestamp is less than the other. * * @param {Timestamp} other Timestamp to compare against. * @return {Boolean} whether this Timestamp is less than the other. * @api public */ Timestamp.prototype.lessThan = function(other) { return this.compare(other) < 0; }; /** * Return whether this Timestamp is less than or equal to the other. * * @param {Timestamp} other Timestamp to compare against. * @return {Boolean} whether this Timestamp is less than or equal to the other. * @api public */ Timestamp.prototype.lessThanOrEqual = function(other) { return this.compare(other) <= 0; }; /** * Return whether this Timestamp is greater than the other. * * @param {Timestamp} other Timestamp to compare against. * @return {Boolean} whether this Timestamp is greater than the other. * @api public */ Timestamp.prototype.greaterThan = function(other) { return this.compare(other) > 0; }; /** * Return whether this Timestamp is greater than or equal to the other. * * @param {Timestamp} other Timestamp to compare against. * @return {Boolean} whether this Timestamp is greater than or equal to the other. * @api public */ Timestamp.prototype.greaterThanOrEqual = function(other) { return this.compare(other) >= 0; }; /** * Compares this Timestamp with the given one. * * @param {Timestamp} other Timestamp to compare against. * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. * @api public */ Timestamp.prototype.compare = function(other) { if (this.equals(other)) { return 0; } var thisNeg = this.isNegative(); var otherNeg = other.isNegative(); if (thisNeg && !otherNeg) { return -1; } if (!thisNeg && otherNeg) { return 1; } // at this point, the signs are the same, so subtraction will not overflow if (this.subtract(other).isNegative()) { return -1; } else { return 1; } }; /** * The negation of this value. * * @return {Timestamp} the negation of this value. * @api public */ Timestamp.prototype.negate = function() { if (this.equals(Timestamp.MIN_VALUE)) { return Timestamp.MIN_VALUE; } else { return this.not().add(Timestamp.ONE); } }; /** * Returns the sum of this and the given Timestamp. * * @param {Timestamp} other Timestamp to add to this one. * @return {Timestamp} the sum of this and the given Timestamp. * @api public */ Timestamp.prototype.add = function(other) { // Divide each number into 4 chunks of 16 bits, and then sum the chunks. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xFFFF; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xFFFF; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xFFFF; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xFFFF; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 + b00; c16 += c00 >>> 16; c00 &= 0xFFFF; c16 += a16 + b16; c32 += c16 >>> 16; c16 &= 0xFFFF; c32 += a32 + b32; c48 += c32 >>> 16; c32 &= 0xFFFF; c48 += a48 + b48; c48 &= 0xFFFF; return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns the difference of this and the given Timestamp. * * @param {Timestamp} other Timestamp to subtract from this. * @return {Timestamp} the difference of this and the given Timestamp. * @api public */ Timestamp.prototype.subtract = function(other) { return this.add(other.negate()); }; /** * Returns the product of this and the given Timestamp. * * @param {Timestamp} other Timestamp to multiply with this. * @return {Timestamp} the product of this and the other. * @api public */ Timestamp.prototype.multiply = function(other) { if (this.isZero()) { return Timestamp.ZERO; } else if (other.isZero()) { return Timestamp.ZERO; } if (this.equals(Timestamp.MIN_VALUE)) { return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; } else if (other.equals(Timestamp.MIN_VALUE)) { return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().multiply(other.negate()); } else { return this.negate().multiply(other).negate(); } } else if (other.isNegative()) { return this.multiply(other.negate()).negate(); } // If both Timestamps are small, use float multiplication if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { return Timestamp.fromNumber(this.toNumber() * other.toNumber()); } // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. // We can skip products that would overflow. var a48 = this.high_ >>> 16; var a32 = this.high_ & 0xFFFF; var a16 = this.low_ >>> 16; var a00 = this.low_ & 0xFFFF; var b48 = other.high_ >>> 16; var b32 = other.high_ & 0xFFFF; var b16 = other.low_ >>> 16; var b00 = other.low_ & 0xFFFF; var c48 = 0, c32 = 0, c16 = 0, c00 = 0; c00 += a00 * b00; c16 += c00 >>> 16; c00 &= 0xFFFF; c16 += a16 * b00; c32 += c16 >>> 16; c16 &= 0xFFFF; c16 += a00 * b16; c32 += c16 >>> 16; c16 &= 0xFFFF; c32 += a32 * b00; c48 += c32 >>> 16; c32 &= 0xFFFF; c32 += a16 * b16; c48 += c32 >>> 16; c32 &= 0xFFFF; c32 += a00 * b32; c48 += c32 >>> 16; c32 &= 0xFFFF; c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; c48 &= 0xFFFF; return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); }; /** * Returns this Timestamp divided by the given one. * * @param {Timestamp} other Timestamp by which to divide. * @return {Timestamp} this Timestamp divided by the given one. * @api public */ Timestamp.prototype.div = function(other) { if (other.isZero()) { throw Error('division by zero'); } else if (this.isZero()) { return Timestamp.ZERO; } if (this.equals(Timestamp.MIN_VALUE)) { if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE } else if (other.equals(Timestamp.MIN_VALUE)) { return Timestamp.ONE; } else { // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. var halfThis = this.shiftRight(1); var approx = halfThis.div(other).shiftLeft(1); if (approx.equals(Timestamp.ZERO)) { return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; } else { var rem = this.subtract(other.multiply(approx)); var result = approx.add(rem.div(other)); return result; } } } else if (other.equals(Timestamp.MIN_VALUE)) { return Timestamp.ZERO; } if (this.isNegative()) { if (other.isNegative()) { return this.negate().div(other.negate()); } else { return this.negate().div(other).negate(); } } else if (other.isNegative()) { return this.div(other.negate()).negate(); } // Repeat the following until the remainder is less than other: find a // floating-point that approximates remainder / other *from below*, add this // into the result, and subtract it from the remainder. It is critical that // the approximate value is less than or equal to the real value so that the // remainder never becomes negative. var res = Timestamp.ZERO; var rem = this; while (rem.greaterThanOrEqual(other)) { // Approximate the result of division. This may be a little greater or // smaller than the actual value. var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); // We will tweak the approximate result by changing it in the 48-th digit or // the smallest non-fractional digit, whichever is larger. var log2 = Math.ceil(Math.log(approx) / Math.LN2); var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); // Decrease the approximation until it is smaller than the remainder. Note // that if it is too large, the product overflows and is negative. var approxRes = Timestamp.fromNumber(approx); var approxRem = approxRes.multiply(other); while (approxRem.isNegative() || approxRem.greaterThan(rem)) { approx -= delta; approxRes = Timestamp.fromNumber(approx); approxRem = approxRes.multiply(other); } // We know the answer can't be zero... and actually, zero would cause // infinite recursion since we would make no progress. if (approxRes.isZero()) { approxRes = Timestamp.ONE; } res = res.add(approxRes); rem = rem.subtract(approxRem); } return res; }; /** * Returns this Timestamp modulo the given one. * * @param {Timestamp} other Timestamp by which to mod. * @return {Timestamp} this Timestamp modulo the given one. * @api public */ Timestamp.prototype.modulo = function(other) { return this.subtract(this.div(other).multiply(other)); }; /** * The bitwise-NOT of this value. * * @return {Timestamp} the bitwise-NOT of this value. * @api public */ Timestamp.prototype.not = function() { return Timestamp.fromBits(~this.low_, ~this.high_); }; /** * Returns the bitwise-AND of this Timestamp and the given one. * * @param {Timestamp} other the Timestamp with which to AND. * @return {Timestamp} the bitwise-AND of this and the other. * @api public */ Timestamp.prototype.and = function(other) { return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); }; /** * Returns the bitwise-OR of this Timestamp and the given one. * * @param {Timestamp} other the Timestamp with which to OR. * @return {Timestamp} the bitwise-OR of this and the other. * @api public */ Timestamp.prototype.or = function(other) { return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); }; /** * Returns the bitwise-XOR of this Timestamp and the given one. * * @param {Timestamp} other the Timestamp with which to XOR. * @return {Timestamp} the bitwise-XOR of this and the other. * @api public */ Timestamp.prototype.xor = function(other) { return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); }; /** * Returns this Timestamp with bits shifted to the left by the given amount. * * @param {Number} numBits the number of bits by which to shift. * @return {Timestamp} this shifted to the left by the given amount. * @api public */ Timestamp.prototype.shiftLeft = function(numBits) { numBits &= 63; if (numBits == 0) { return this; } else { var low = this.low_; if (numBits < 32) { var high = this.high_; return Timestamp.fromBits( low << numBits, (high << numBits) | (low >>> (32 - numBits))); } else { return Timestamp.fromBits(0, low << (numBits - 32)); } } }; /** * Returns this Timestamp with bits shifted to the right by the given amount. * * @param {Number} numBits the number of bits by which to shift. * @return {Timestamp} this shifted to the right by the given amount. * @api public */ Timestamp.prototype.shiftRight = function(numBits) { numBits &= 63; if (numBits == 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Timestamp.fromBits( (low >>> numBits) | (high << (32 - numBits)), high >> numBits); } else { return Timestamp.fromBits( high >> (numBits - 32), high >= 0 ? 0 : -1); } } }; /** * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. * * @param {Number} numBits the number of bits by which to shift. * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. * @api public */ Timestamp.prototype.shiftRightUnsigned = function(numBits) { numBits &= 63; if (numBits == 0) { return this; } else { var high = this.high_; if (numBits < 32) { var low = this.low_; return Timestamp.fromBits( (low >>> numBits) | (high << (32 - numBits)), high >>> numBits); } else if (numBits == 32) { return Timestamp.fromBits(high, 0); } else { return Timestamp.fromBits(high >>> (numBits - 32), 0); } } }; /** * Returns a Timestamp representing the given (32-bit) integer value. * * @param {Number} value the 32-bit integer in question. * @return {Timestamp} the corresponding Timestamp value. * @api public */ Timestamp.fromInt = function(value) { if (-128 <= value && value < 128) { var cachedObj = Timestamp.INT_CACHE_[value]; if (cachedObj) { return cachedObj; } } var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); if (-128 <= value && value < 128) { Timestamp.INT_CACHE_[value] = obj; } return obj; }; /** * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. * * @param {Number} value the number in question. * @return {Timestamp} the corresponding Timestamp value. * @api public */ Timestamp.fromNumber = function(value) { if (isNaN(value) || !isFinite(value)) { return Timestamp.ZERO; } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { return Timestamp.MIN_VALUE; } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { return Timestamp.MAX_VALUE; } else if (value < 0) { return Timestamp.fromNumber(-value).negate(); } else { return new Timestamp( (value % Timestamp.TWO_PWR_32_DBL_) | 0, (value / Timestamp.TWO_PWR_32_DBL_) | 0); } }; /** * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. * * @param {Number} lowBits the low 32-bits. * @param {Number} highBits the high 32-bits. * @return {Timestamp} the corresponding Timestamp value. * @api public */ Timestamp.fromBits = function(lowBits, highBits) { return new Timestamp(lowBits, highBits); }; /** * Returns a Timestamp representation of the given string, written using the given radix. * * @param {String} str the textual representation of the Timestamp. * @param {Number} opt_radix the radix in which the text is written. * @return {Timestamp} the corresponding Timestamp value. * @api public */ Timestamp.fromString = function(str, opt_radix) { if (str.length == 0) { throw Error('number format error: empty string'); } var radix = opt_radix || 10; if (radix < 2 || 36 < radix) { throw Error('radix out of range: ' + radix); } if (str.charAt(0) == '-') { return Timestamp.fromString(str.substring(1), radix).negate(); } else if (str.indexOf('-') >= 0) { throw Error('number format error: interior "-" character: ' + str); } // Do several (8) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); var result = Timestamp.ZERO; for (var i = 0; i < str.length; i += 8) { var size = Math.min(8, str.length - i); var value = parseInt(str.substring(i, i + size), radix); if (size < 8) { var power = Timestamp.fromNumber(Math.pow(radix, size)); result = result.multiply(power).add(Timestamp.fromNumber(value)); } else { result = result.multiply(radixToPower); result = result.add(Timestamp.fromNumber(value)); } } return result; }; // NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the // from* methods on which they depend. /** * A cache of the Timestamp representations of small integer values. * @type {Object} * @api private */ Timestamp.INT_CACHE_ = {}; // NOTE: the compiler should inline these constant values below and then remove // these variables, so there should be no runtime penalty for these. /** * Number used repeated below in calculations. This must appear before the * first call to any from* function below. * @type {number} * @api private */ Timestamp.TWO_PWR_16_DBL_ = 1 << 16; /** * @type {number} * @api private */ Timestamp.TWO_PWR_24_DBL_ = 1 << 24; /** * @type {number} * @api private */ Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; /** * @type {number} * @api private */ Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; /** * @type {number} * @api private */ Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; /** * @type {number} * @api private */ Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; /** * @type {number} * @api private */ Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; /** @type {Timestamp} */ Timestamp.ZERO = Timestamp.fromInt(0); /** @type {Timestamp} */ Timestamp.ONE = Timestamp.fromInt(1); /** @type {Timestamp} */ Timestamp.NEG_ONE = Timestamp.fromInt(-1); /** @type {Timestamp} */ Timestamp.MAX_VALUE = Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); /** @type {Timestamp} */ Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); /** * @type {Timestamp} * @api private */ Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); /** * Expose. */ exports.Timestamp = Timestamp;
var gulp = require('gulp'); var open = require('gulp-open'); var rename = require('gulp-rename'); var serve = require('gulp-serve'); var uglify = require('gulp-uglify'); gulp.task('build', function(){ gulp.src('src/game-controller.js') .pipe(uglify({mangle: { GameController: false, window: false, exports: false, module: false, requestAnimationFrame: false, cancelAnimationFrame: false }})) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('dist')); }); gulp.task('open', function(){ gulp.src('tests/index.html') .pipe(open({uri: 'http://localhost:3000'})); }); gulp.task('default', ['build']); gulp.task('serve', serve(['src', 'tests', 'dist'])); gulp.task('test', ['serve', 'open']);
/** * @copyright 2013 Sonia Keys * @copyright 2016 commenthol * @license MIT * @module eclipse */ /** * Eclipse: Chapter 54, Eclipses. */ import base from './base.js' import moonphase from './moonphase.js' /** * @private */ const g = function (k, jm, c1, c2) { // (k, jm, c1, c2 float64) (eclipse bool, jdeMax, γ, u, Mʹ float64) const ck = 1 / 1236.85 const p = Math.PI / 180 const T = k * ck const F = base.horner(T, 160.7108 * p, 390.67050284 * p / ck, -0.0016118 * p, -0.00000227 * p, 0.000000011 * p) if (Math.abs(Math.sin(F)) > 0.36) { return [false] // no eclipse } const eclipse = true const E = base.horner(T, 1, -0.002516, -0.0000074) const M = base.horner(T, 2.5534 * p, 29.1053567 * p / ck, -0.0000014 * p, -0.00000011 * p) const Mʹ = base.horner(T, 201.5643 * p, 385.81693528 * p / ck, 0.0107582 * p, 0.00001238 * p, -0.000000058 * p) const Ω = base.horner(T, 124.7746 * p, -1.56375588 * p / ck, 0.0020672 * p, 0.00000215 * p) const sΩ = Math.sin(Ω) const F1 = F - 0.02665 * p * sΩ const A1 = base.horner(T, 299.77 * p, 0.107408 * p / ck, -0.009173 * p) // (54.1) p. 380 const jdeMax = jm + c1 * Math.sin(Mʹ) + c2 * Math.sin(M) * E + 0.0161 * Math.sin(2 * Mʹ) + -0.0097 * Math.sin(2 * F1) + 0.0073 * Math.sin(Mʹ - M) * E + -0.005 * Math.sin(Mʹ + M) * E + -0.0023 * Math.sin(Mʹ - 2 * F1) + 0.0021 * Math.sin(2 * M) * E + 0.0012 * Math.sin(Mʹ + 2 * F1) + 0.0006 * Math.sin(2 * Mʹ + M) * E + -0.0004 * Math.sin(3 * Mʹ) + -0.0003 * Math.sin(M + 2 * F1) * E + 0.0003 * Math.sin(A1) + -0.0002 * Math.sin(M - 2 * F1) * E + -0.0002 * Math.sin(2 * Mʹ - M) * E + -0.0002 * sΩ const P = 0.207 * Math.sin(M) * E + 0.0024 * Math.sin(2 * M) * E + -0.0392 * Math.sin(Mʹ) + 0.0116 * Math.sin(2 * Mʹ) + -0.0073 * Math.sin(Mʹ + M) * E + 0.0067 * Math.sin(Mʹ - M) * E + 0.0118 * Math.sin(2 * F1) const Q = 5.2207 + -0.0048 * Math.cos(M) * E + 0.002 * Math.cos(2 * M) * E + -0.3299 * Math.cos(Mʹ) + -0.006 * Math.cos(Mʹ + M) * E + 0.0041 * Math.cos(Mʹ - M) * E const [sF1, cF1] = base.sincos(F1) const W = Math.abs(cF1) const γ = (P * cF1 + Q * sF1) * (1 - 0.0048 * W) const u = 0.0059 + 0.0046 * Math.cos(M) * E + -0.0182 * Math.cos(Mʹ) + 0.0004 * Math.cos(2 * Mʹ) + -0.0005 * Math.cos(M + Mʹ) return [eclipse, jdeMax, γ, u, Mʹ] // (eclipse bool, jdeMax, γ, u, Mʹ float64) } /** * Eclipse type identifiers returned from Solar and Lunar. */ export const TYPE = { None: 0, Partial: 1, // for solar eclipses Annular: 2, // solar AnnularTotal: 3, // solar Penumbral: 4, // for lunar eclipses Umbral: 5, // lunar Total: 6 // solar or lunar } /** * Snap returns k at specified quarter q nearest year y. * Cut and paste from moonphase. Time corresponding to k needed in these * algorithms but otherwise not meaningful enough to export from moonphase. */ const snap = function (y, q) { // (y, q float64) float64 const k = (y - 2000) * 12.3685 // (49.2) p. 350 return Math.floor(k - q + 0.5) + q } /** * Solar computes quantities related to solar eclipses. * * Argument year is a decimal year specifying a date. * * eclipseType will be None, Partial, Annular, AnnularTotal, or Total. * If None, none of the other return values may be meaningful. * * central is true if the center of the eclipse shadow touches the Earth. * * jdeMax is the jde when the center of the eclipse shadow is closest to the * Earth center, in a plane through the center of the Earth. * * γ is the distance from the eclipse shadow center to the Earth center * at time jdeMax. * * u is the radius of the Moon's umbral cone in the plane of the Earth. * * p is the radius of the penumbral cone. * * mag is eclipse magnitude for partial eclipses. It is not valid for other * eclipse types. * * γ, u, and p are in units of equatorial Earth radii. */ export function solar (year) { // (year float64) (eclipseType int, central bool, jdeMax, γ, u, p, mag float64) let eclipseType = TYPE.None let mag const [e, jdeMax, γ, u, _] = g(snap(year, 0), moonphase.meanNew(year), -0.4075, 0.1721) // eslint-disable-line no-unused-vars const p = u + 0.5461 if (!e) { return { type: eclipseType } // no eclipse } const aγ = Math.abs(γ) if (aγ > 1.5433 + u) { return { type: eclipseType } // no eclipse } const central = aγ < 0.9972 // eclipse center touches Earth if (!central) { eclipseType = TYPE.Partial // most common case if (aγ < 1.026) { // umbral cone may touch earth if (aγ < 0.9972 + Math.abs(u)) { // total or annular eclipseType = TYPE.Total // report total in both cases } } } else if (u < 0) { eclipseType = TYPE.Total } else if (u > 0.0047) { eclipseType = TYPE.Annular } else { const ω = 0.00464 * Math.sqrt(1 - γ * γ) if (u < ω) { eclipseType = TYPE.AnnularTotal } else { eclipseType = TYPE.Annular } } if (eclipseType === TYPE.Partial) { // (54.2) p. 382 mag = (1.5433 + u - aγ) / (0.5461 + 2 * u) } return { type: eclipseType, central: central, jdeMax: jdeMax, magnitude: mag, distance: γ, umbral: u, penumbral: p } } /** * Lunar computes quantities related to lunar eclipses. * * Argument year is a decimal year specifying a date. * * eclipseType will be None, Penumbral, Umbral, or Total. * If None, none of the other return values may be meaningful. * * jdeMax is the jde when the center of the eclipse shadow is closest to the * Moon center, in a plane through the center of the Moon. * * γ is the distance from the eclipse shadow center to the moon center * at time jdeMax. * * σ is the radius of the umbral cone in the plane of the Moon. * * ρ is the radius of the penumbral cone. * * mag is eclipse magnitude. * * sd- return values are semidurations of the phases of the eclipse, in days. * * γ, σ, and ρ are in units of equatorial Earth radii. */ export function lunar (year) { // (year float64) (eclipseType int, jdeMax, γ, ρ, σ, mag, sdTotal, sdPartial, sdPenumbral float64) let eclipseType = TYPE.None let mag let sdTotal let sdPartial let sdPenumbral const [e, jdeMax, γ, u, Mʹ] = g(snap(year, 0.5), moonphase.meanFull(year), -0.4065, 0.1727) if (!e) { return { type: eclipseType } // no eclipse } const ρ = 1.2848 + u const σ = 0.7403 - u const aγ = Math.abs(γ) mag = (1.0128 - u - aγ) / 0.545 // (54.3) p. 382 if (mag > 1) { eclipseType = TYPE.Total } else if (mag > 0) { eclipseType = TYPE.Umbral } else { mag = (1.5573 + u - aγ) / 0.545 // (54.4) p. 382 if (mag < 0) { return { type: eclipseType } // no eclipse } eclipseType = TYPE.Penumbral } const p = 1.0128 - u const t = 0.4678 - u const n = 0.5458 + 0.04 * Math.cos(Mʹ) const γ2 = γ * γ /* eslint-disable no-fallthrough */ switch (eclipseType) { case TYPE.Total: { sdTotal = Math.sqrt(t * t - γ2) / n / 24 } case TYPE.Umbral: { sdPartial = Math.sqrt(p * p - γ2) / n / 24 } default: { const h = 1.5573 + u sdPenumbral = Math.sqrt(h * h - γ2) / n / 24 } } /* eslint-enable */ return { type: eclipseType, jdeMax: jdeMax, magnitude: mag, distance: γ, umbral: σ, penumbral: ρ, sdTotal: sdTotal, sdPartial: sdPartial, sdPenumbral: sdPenumbral } } export default { TYPE, solar, lunar }
var app = function() {} app.prototype.init = function() {} app.prototype.run = function() {} module.exports = app
// Initializes the `scrape` service on path `/scrape` const createService = require('./scrape.class.js') const hooks = require('./scrape.hooks') module.exports = function (app) { const paginate = app.get('paginate') const options = { name: 'scrape', paginate } // Initialize our service with any options it requires app.use('/scrape', createService(options)) // Get our initialized service so that we can register hooks and filters const service = app.service('scrape') service.hooks(hooks) }
import {h, div, ul, li, a, nav, h1, h2} from '@cycle/dom' const view = () => { return div([ h1('.brand-title', [`An APP`]), h2('.brand-tagline', [`Showcasing Cycle.js`]), nav('.nav', [ ul('.nav-list', [ li('.nav-item .link', [ a('.pure-button', {href: `/`}, [`Home`]) ]), li('.nav-item .link', [ a('.pure-button', {href: `/page1`}, [`Page 1`]) ]), li('.nav-item .link .testlink', [ a('.pure-button', {href: `/page2`}, [`Page 2`]) ]) ]) ])]) }; export default view;
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/dist/"; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(145); /***/ }, /***/ 3: /***/ function(module, exports) { /* globals __VUE_SSR_CONTEXT__ */ // this module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle module.exports = function normalizeComponent ( rawScriptExports, compiledTemplate, injectStyles, scopeId, moduleIdentifier /* server only */ ) { var esModule var scriptExports = rawScriptExports = rawScriptExports || {} // ES6 modules interop var type = typeof rawScriptExports.default if (type === 'object' || type === 'function') { esModule = rawScriptExports scriptExports = rawScriptExports.default } // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (compiledTemplate) { options.render = compiledTemplate.render options.staticRenderFns = compiledTemplate.staticRenderFns } // scopedId if (scopeId) { options._scopeId = scopeId } var hook if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || (this.$vnode && this.$vnode.ssrContext) // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = injectStyles } if (hook) { // inject component registration as beforeCreate hook var existing = options.beforeCreate options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } return { esModule: esModule, exports: scriptExports, options: options } } /***/ }, /***/ 14: /***/ function(module, exports) { module.exports = require("element-ui/lib/mixins/emitter"); /***/ }, /***/ 145: /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _dropdownItem = __webpack_require__(146); var _dropdownItem2 = _interopRequireDefault(_dropdownItem); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* istanbul ignore next */ _dropdownItem2.default.install = function (Vue) { Vue.component(_dropdownItem2.default.name, _dropdownItem2.default); }; exports.default = _dropdownItem2.default; /***/ }, /***/ 146: /***/ function(module, exports, __webpack_require__) { var Component = __webpack_require__(3)( /* script */ __webpack_require__(147), /* template */ __webpack_require__(148), /* styles */ null, /* scopeId */ null, /* moduleIdentifier (server only) */ null ) module.exports = Component.exports /***/ }, /***/ 147: /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _emitter = __webpack_require__(14); var _emitter2 = _interopRequireDefault(_emitter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { name: 'ElDropdownItem', mixins: [_emitter2.default], props: { command: null, disabled: Boolean, divided: Boolean }, methods: { handleClick: function handleClick(e) { this.dispatch('ElDropdown', 'menu-item-click', [this.command, this]); } } }; // // // // // // // // // // // // /***/ }, /***/ 148: /***/ function(module, exports) { module.exports={render:function (){var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('li', { staticClass: "el-dropdown-menu__item", class: { 'is-disabled': _vm.disabled, 'el-dropdown-menu__item--divided': _vm.divided }, on: { "click": _vm.handleClick } }, [_vm._t("default")], 2) },staticRenderFns: []} /***/ } /******/ });
var path = require('path'); var chai = require('chai'); var assert = chai.assert; var expect = chai.expect; var RestDescription = require(path.dirname(__filename) + '/../lib/rest-description'); var Schema = require(path.dirname(__filename) + '/../lib/schema'); var Context = require(path.dirname(__filename) + '/../lib/context'); var DISCOVERY_FILE = path.dirname(__filename) + '/discovery.json'; describe('EndpointResource', function () { beforeEach(function () { Context.set('resource', new RestDescription(DISCOVERY_FILE)); }); it('should pass creation', function () { new Schema('test'); }); it('should cache a single instance per id', function () { expect(Schema.get('test')).to.equal(Schema.get('test')); }); });
(function(jsenvy) { /** } * Scope Creep * === * A fun way to creep on people's scope. Lets you: * - Update a scope to see the scope difference * - View the current contents of the scope, in case you forgot what you're creeping on */ jsenvy.ScopeCreep = function(victim, ignores) { var properties = [], methods = []; ignores = ignores || {properties: [], methods: []}; //a setter for the scope properties and methods function setScope(scope) { if (typeof scope !== "object") { scope = enumerateScope(); } properties = scope.properties; methods = scope.methods; } //an updater for the scope that returns the difference function update() { var diff = getScopeDiff(); setScope(diff.scope); return diff; } //the actually scope dissection function enumerateScope() { var properties = [], methods = [], thingsToIgnore = ["length", "__CommandLineAPI"]; for(var key in victim) { if (thingsToIgnore.indexOf(key) === -1) { if (typeof victim[key] === 'function') { methods.push(key); } else { properties.push(key); } } } return { properties: properties, methods: methods }; } //retrieve the scope diff without setting the scope function getScopeDiff() { var newScope = enumerateScope(); var propertyDiff = arrayDiff(ignores.properties, arrayDiff(properties, newScope.properties)), methodDiff = arrayDiff(ignores.methods, arrayDiff(methods, newScope.methods)); return { properties: propertyDiff, methods: methodDiff, scope: newScope }; } function arrayDiff(array1, array2) { var difference = []; array2.forEach(function(item) { if (array1.indexOf(item) === -1) { difference.push(item); } }); return difference; } setScope(); return { update: update, peek: getScopeDiff, get: enumerateScope } }; })(jsenvy);
export default { name: 'sidr', // Name for the 'sidr' speed: 200, // Accepts standard jQuery effects speeds (i.e. fast, normal or milliseconds) side: 'left', // Accepts 'left' or 'right' source: null, // Override the source of the content. renaming: true, // The ids and classes will be prepended with a prefix when loading existent content body: 'body', // Page container selector, displace: true, // Displace the body content or not timing: 'ease', // Timing function for CSS transitions method: 'toggle', // The method to call when element is clicked bind: 'click', // The event to trigger the menu onOpen () { }, // Callback when sidr start opening onClose () { }, // Callback when sidr start closing onOpenEnd () { }, // Callback when sidr end opening onCloseEnd () { } // Callback when sidr end closing }
import React, { Component } from 'react'; import { connect } from 'react-redux'; import * as actions from '../../actions'; class Feature extends Component { componentWillMount() { this.props.fetchMessage(); } render () { return <div>{this.props.message}</div>; } } function mapStateToProps(state) { return { message: state.auth.message }; } export default connect(mapStateToProps, actions)(Feature);
require('./app.less')
import Model from './model'; import { inherit } from 'content-kit-utils/src/object-utils'; /** * Ensures block markups at the same index are always in a specific order. * For example, so all bold links are consistently marked up * as <a><b>text</b></a> instead of <b><a>text</a></b> */ function sortBlockMarkups(markups) { return markups.sort(function(a, b) { if (a.start === b.start && a.end === b.end) { return b.type - a.type; } return 0; }); } /** * @class BlockModel * @constructor * @extends Model */ function BlockModel(options) { options = options || {}; Model.call(this, options); this.value = options.value || ''; this.markup = sortBlockMarkups(options.markup || []); } inherit(BlockModel, Model); export default BlockModel;
"use strict"; var piece_1 = require('./piece'); (function (GameState) { GameState[GameState["ON"] = 0] = "ON"; GameState[GameState["OVER"] = 1] = "OVER"; })(exports.GameState || (exports.GameState = {})); var GameState = exports.GameState; var Game = (function () { function Game(starts) { this.pieces = Game.START_POSITIONS; this.pieceCount = {}; this.captured = {}; this.state = GameState.ON; this.whoseTurn = starts; this.captured[this.WHITE] = []; this.captured[this.BLACK] = []; this.pieceCount[this.WHITE] = 4; this.pieceCount[this.BLACK] = 4; } Object.defineProperty(Game.prototype, "WHITE", { get: function () { return piece_1.Piece.side_to_string(piece_1.Side.WHITE); }, enumerable: true, configurable: true }); Object.defineProperty(Game.prototype, "BLACK", { get: function () { return piece_1.Piece.side_to_string(piece_1.Side.BLACK); }, enumerable: true, configurable: true }); Object.defineProperty(Game, "START_POSITIONS", { get: function () { return [ [piece_1.Piece.B_BISHOP, piece_1.Piece.B_KING, piece_1.Piece.B_ROOK], [piece_1.Piece.EMPTY, piece_1.Piece.B_PAWN, piece_1.Piece.EMPTY], [piece_1.Piece.EMPTY, piece_1.Piece.W_PAWN, piece_1.Piece.EMPTY], [piece_1.Piece.W_ROOK, piece_1.Piece.W_KING, piece_1.Piece.W_BISHOP], ]; }, enumerable: true, configurable: true }); Game.prototype.clone = function () { var that = new Game(this.whoseTurn); for (var i = 0; i < this.pieces.length; i++) { for (var j = 0; j < this.pieces[0].length; j++) { that.pieces[i][j] = this.pieces[i][j].clone(); } } that.pieceCount[this.WHITE] = this.pieceCount[this.WHITE]; that.pieceCount[this.BLACK] = this.pieceCount[this.BLACK]; that.selected = this.selected; for (var _i = 0, _a = this.captured[this.WHITE]; _i < _a.length; _i++) { var c = _a[_i]; that.captured[this.WHITE].push(c.clone()); } for (var _b = 0, _c = this.captured[this.BLACK]; _b < _c.length; _b++) { var c = _c[_b]; that.captured[this.BLACK].push(c.clone()); } that.won = this.won; that.state = this.state; return that; }; Game.prototype.makeMove = function (move, intervalMs) { var _this = this; this.selectPiece(move.src); if (intervalMs == undefined) { this.clicked(move.dst); } else { setTimeout(function () { _this.clicked(move.dst); }, intervalMs); } }; Game.prototype.clicked = function (c) { var piece = this.getPiece(c); switch (piece.state) { case "none": this.selectPiece(c); break; case "selected": this.unselectAll(); break; case "available": this.movePiece(c); break; case "attacked": this.capturePiece(c); break; } }; Game.prototype.getPiece = function (c) { if (c.x >= 0) { return this.pieces[c.x][c.y]; } else if (c.x == -1) { return this.captured[this.WHITE][c.y]; } else { return this.captured[this.BLACK][c.y]; } }; Game.prototype.selectPiece = function (c) { if (this.state == GameState.OVER) { return; } var piece = this.getPiece(c); if (!piece.canBeSelected()) { return; } if (piece.side != this.whoseTurn) { return; } this.unselectAll(); piece.state = "selected"; this.selected = c; if (c.x >= 0) { this.updateAvailableOrAttacked(c); } else { this.updateAllEmptyToAvailable(); } }; Game.prototype.updateAvailableOrAttacked = function (c) { var piece = this.pieces[c.x][c.y]; for (var _i = 0, _a = piece.movements(); _i < _a.length; _i++) { var pos = _a[_i]; var x2 = c.x + pos[0]; var y2 = c.y + pos[1]; if (this.isOutOfBounds(x2, y2)) { continue; } var otherPiece = this.pieces[x2][y2]; if (otherPiece.side == piece_1.Side.NONE) { otherPiece.state = "available"; } else if (otherPiece.side == piece.side) { } else { otherPiece.state = "attacked"; } } }; Game.prototype.isOutOfBounds = function (x, y) { return x < 0 || x >= this.pieces.length || y < 0 || y >= this.pieces[0].length; }; Game.prototype.movePiece = function (c) { if (this.selected.x >= 0) { this.movePieceOnBoard(c); } else { this.putPieceOnBoard(c); } }; Game.prototype.movePieceOnBoard = function (c) { var movedPiece = this.pieces[this.selected.x][this.selected.y]; var emptyPiece = this.pieces[c.x][c.y]; this.pieces[c.x][c.y] = movedPiece; this.pieces[this.selected.x][this.selected.y] = emptyPiece; this.unselectAll(); this.onPieceMoved(c, movedPiece, false); }; Game.prototype.putPieceOnBoard = function (c) { var side = this.selected.x == -1 ? piece_1.Side.WHITE : piece_1.Side.BLACK; console.log("side: " + side); var movedPiece = this.captured[piece_1.Piece.side_to_string(side)][this.selected.y]; this.pieces[c.x][c.y] = movedPiece; this.captured[piece_1.Piece.side_to_string(side)].splice(this.selected.y, 1); this.unselectAll(); this.onPieceMoved(c, movedPiece, true); }; Game.prototype.capturePiece = function (c) { var movedPiece = this.pieces[this.selected.x][this.selected.y]; var moveToPiece = this.pieces[c.x][c.y]; this.pieces[c.x][c.y] = movedPiece; this.pieces[this.selected.x][this.selected.y] = piece_1.Piece.EMPTY; this.captured[piece_1.Piece.side_to_string(movedPiece.side)].push(moveToPiece.getOpposite()); this.unselectAll(); this.onPieceMoved(c, movedPiece, false); this.onPieceCaptured(moveToPiece); }; Game.prototype.onPieceMoved = function (c, piece, wasCaptured) { this.whoseTurn = this.opposite(this.whoseTurn); if (piece.type == piece_1.Type.KING) { if (c.x == 0 && piece.side == piece_1.Side.WHITE) { this.gameOver(piece_1.Side.WHITE); } else if (c.x == this.pieces.length - 1 && piece.side == piece_1.Side.BLACK) { this.gameOver(piece_1.Side.BLACK); } } if (piece.type == piece_1.Type.PAWN && !wasCaptured) { if (c.x == 0 || c.x == this.pieces.length - 1) { this.pieces[c.x][c.y] = new piece_1.Piece(piece.side, piece_1.Type.SUPERPAWN); } } }; Game.prototype.onPieceCaptured = function (capturedPiece) { if (capturedPiece.type == piece_1.Type.KING) { this.gameOver(this.opposite(capturedPiece.side)); } this.pieceCount[piece_1.Piece.side_to_string(capturedPiece.side)]--; this.pieceCount[piece_1.Piece.side_to_string(this.opposite(capturedPiece.side))]++; }; Game.prototype.unselectAll = function () { this.selected = undefined; for (var _i = 0, _a = this.pieces; _i < _a.length; _i++) { var row = _a[_i]; for (var _b = 0, row_1 = row; _b < row_1.length; _b++) { var piece = row_1[_b]; piece.state = "none"; } } for (var side in this.captured) { for (var _c = 0, _d = this.captured[side]; _c < _d.length; _c++) { var piece = _d[_c]; piece.state = "none"; } } }; Game.prototype.updateAllEmptyToAvailable = function () { for (var _i = 0, _a = this.pieces; _i < _a.length; _i++) { var row = _a[_i]; for (var _b = 0, row_2 = row; _b < row_2.length; _b++) { var piece = row_2[_b]; if (piece.type == piece_1.Type.EMPTY) { piece.state = "available"; } } } }; Game.prototype.gameOver = function (winning) { console.log("game over"); this.won = winning; this.state = GameState.OVER; }; Game.prototype.opposite = function (side) { return side == piece_1.Side.BLACK ? piece_1.Side.WHITE : piece_1.Side.BLACK; }; return Game; }()); exports.Game = Game; //# sourceMappingURL=game.js.map
(function() { 'use strict'; angular.module('sideNavDirective', []) /* * <side-nav> Directive. * Builds the left navigation from a list of navItems */ .directive('sideNav', function() { return { restrict: 'E', replace: true, templateUrl: 'components/nav/side-nav.html', controller: 'NavCtrl' }; }) /* * Navigation Controller * Uses the navItem array to build a list of navigation. * Provides an isActive filter to determine if the provided route is active */ .controller('NavCtrl', ['$scope', '$location', function($scope, $location) { // Items to show in the side navigation. // Object with a title and route property. If no route // is provided the lowercase'd title will be used $scope.navItems = [{ title: 'Dashboard', }, { title: 'News' }, { title: 'Sales Reports', route: 'sales-reports' }, { title: 'Trends' }, { title: 'Analyze' }, { title: 'Configuration' }]; // Used to set the active class on the nav li elements $scope.isActive = function(route) { return route === $location.path(); }; } ]); })();
iris.ui(function(self) { var editable = false; var editor = null; var field = null; var item = null; var schema = null; var filter = ""; var onchange = null; self.settings({"table": null}); self.create = function() { field = self.setting('field'); item = self.setting('item'); schema = field.schema; editable = schema.autoedit; self.item = item; self.schema = schema; self.tmplMode(self.APPEND); if (self.setting("table") && schema.inline !== false) { self.tmpl(iris.path.ui.field_cell.html); } else { self.tmpl(iris.path.ui.field.html); } self.get('field').addClass("field " + field.name); self.get('name').text(field.name + ":"); self.get('value').text(field.value); if (schema.inline) { if (!self.setting("table")) { self.get('field').addClass("inline"); } self.get('name').hide(); } if (schema.show_title === false) { self.get('name').hide(); } if (schema.value_as_css) { self.get('field').addClass(field.value); self.setting("parent").get("item").addClass(field.value); } if (schema.autoedit) { onchange = function(value) { item[field.name] = value; field.value = value; self.get('value').text(value); }; } ; editor = self.ui('editor', iris.path.ui[(field.schema && field.schema.view || 'input') + '_field'].js, {value: field.value, name: field.name, schema: schema, "onchange": onchange}, self.APPEND); //render(); }; self.setEditable = function(state) { editable = schema.autoedit || state; render(); } self.val = function() { return editor.val(); } self.save = function() { if (schema.value_as_css) { self.get('field').removeClass(field.value).addClass(editor.val()); self.setting("parent").get("item").removeClass(field.value).addClass(editor.val()); } item[field.name] = editor.val(); field.value = editor.val(); self.get('value').text(field.value); self.setEditable(false); }; self.cancel = function() { if (field.value) { editor.val(field.value); } else { editor.get(0).get(0).value = ""; } self.setEditable(true); }; self.filter = function(f) { filter = f; var regExp = filter; var fieldName = ""; var pos = f.indexOf(":"); if (pos > -1) { fieldName = filter.substr(0, pos); regExp = filter.substr(pos + 1); } //console.log("filter=" + filter + " field.name =" + field.name + " field.value =" + field.value) var match = !filter || new RegExp(regExp, "ig").test(field.value); if (match && fieldName) { match = fieldName === field.name; } if (schema.show) { self.get('field').toggle(match === true); } return match; }; function render() { self.get('editor').toggle(editable); self.get('value').toggle(!editable); if (schema.show === false) { self.get().toggle(editable); } } }, iris.path.ui.field.js);
(function () { angular .module('app.core') .factory('dataservice', dataservice); dataservice.$inject = ['$firebaseArray']; function dataservice($firebaseArray) { return { getLocations: getLocations }; function getLocations() { var firebaseRef = new Firebase('https://iwashere.firebaseio.com/locations'); var locations = $firebaseArray(firebaseRef); return locations.$loaded() .then(getLocationsComplete) .catch(getLocationsFailed); function getLocationsComplete(locations) { return { type: 'FeatureCollection', metadata: { title: 'Steve Mink Territory Clients', status: 200, api: '1.0.0', count: locations.length }, features: locations }; } function getLocationsFailed(error) { console.log('getLocations failed: ' + error); } } } })();
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import './header.css'; import LogModal from '../loginmodal/Modal' class Header extends Component { constructor(props) { super(props); this.state = { showModal: false } this.close = this.close.bind(this); this.open = this.open.bind(this); } close() { this.setState({showModal: false}); } open() { this.setState({showModal: true}); } renderContent() { switch (this.props.auth) { case null: return; case false: return ( <div> <a className="waves-effect waves-light btn" onClick={this.open}><i className="material-icons right">menu</i>Login</a> </div> ) default: return ( <div> <li><Link to='/beer'>Search Beer</Link></li> <li><Link to='/breweries'>Search Breweries</Link></li> <li><a href="/api/logout">Logout</a></li> </div> ) } } render() { return ( <div> <nav className="header-nav"> <div className="nav-wrapper black"> <Link to={this.props.auth ? '/dashboard' : '/'} className="left brand-logo" > BottleShare </Link> <ul className="right"> {this.renderContent()} </ul> </div> { this.state.showModal ? <LogModal showModal={this.state.showModal} close={this.close} open={this.open} /> : null } </nav> { this.state.showModal ? <LogModal showModal={this.state.showModal} close={this.close} open={this.open} /> : null } </div> ) } } function mapStateToProps({ auth }) { return { auth } } export default connect(mapStateToProps)(Header)
module.exports = { entry: './src/app.js', output: { path: './public/js', filename: 'app.bundle.js' }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }] } };
module.exports={A:{A:{"132":"L H G E A B jB"},B:{"132":"C D d K I N J","388":"BB"},C:{"132":"0 1 2 3 5 6 7 8 9 gB IB F L H G E A B C D d K I N J P Q R S T U V W X Y Z a b c e f g h i j k l m n o M q r s t u v w x y z AB CB DB EB O GB HB aB ZB"},D:{"132":"2 3 5 F L H G E A B C D d K I N J P Q R S T U V W X Y Z a b c e f g","388":"0 1 6 7 8 9 h i j k l m n o M q r s t u v w x y z AB CB DB EB O GB HB TB PB NB mB OB LB BB QB RB"},E:{"132":"2 4 F L H G E A B C D SB KB UB VB WB XB YB p bB"},F:{"132":"3 4 E B C K I N J P Q R S T cB dB eB fB p FB hB","388":"0 1 5 U V W X Y Z a b c e f g h i j k l m n o M q r s t u v w x y z"},G:{"132":"G D KB iB JB kB lB MB nB oB pB qB rB sB tB uB vB"},H:{"132":"wB"},I:{"132":"IB F O xB yB zB 0B JB 1B 2B"},J:{"132":"H A"},K:{"132":"4 A B C p FB","388":"M"},L:{"388":"LB"},M:{"132":"O"},N:{"132":"A B"},O:{"132":"3B"},P:{"132":"F","388":"4B 5B 6B 7B 8B"},Q:{"388":"9B"},R:{"388":"AC"},S:{"132":"BC"}},B:5,C:"CSS text-indent"};
// @flow import lonlat from '@conveyal/lonlat' import {decode as decodePolyline} from '@mapbox/polyline' import fetch from 'isomorphic-fetch' import type {LonLatC} from '../types' const GRAPHHOPPER_API_URL = 'https://graphhopper.com/api/1/route' export default async function getRoutePolyline (start: LonLatC, end: LonLatC) { const startPoint = lonlat.toLatFirstString(start) const endPoint = lonlat.toLatFirstString(end) const response = await fetch(`${GRAPHHOPPER_API_URL}?key=${process.env.GRAPHHOPPER_API_KEY || ''}&point=${startPoint}&point=${endPoint}&instructions=false`) const json = await response.json() return decodePolyline(json.paths[0].points).map(c => ([c[1], c[0]])) // [lat,lon] -> [lon,lat] }
// ==UserScript== // @name Facebook Event Exporter // @namespace http://boris.joff3.com // @version 1.3.11 // @description Export Facebook events // @author Boris Joffe // @match https://www.facebook.com/* // @grant unsafeWindow // ==/UserScript== /* jshint -W097 */ /* globals console*/ /* eslint-disable no-console, no-unused-vars */ 'use strict'; /* The MIT License (MIT) Copyright (c) 2015, 2017, 2018 Boris Joffe 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. */ // Util var qs = document.querySelector.bind(document), qsa = document.querySelectorAll.bind(document), err = console.error.bind(console), log = console.log.bind(console), euc = encodeURIComponent; var DEBUG = false; function dbg() { if (DEBUG) console.log.apply(console, arguments); return arguments[0]; } function qsv(elmStr, parent) { var elm = parent ? parent.querySelector(elmStr) : qs(elmStr); if (!elm) err('(qs) Could not get element -', elmStr); return elm; } function qsav(elmStr, parent) { var elm = parent ? parent.querySelectorAll(elmStr) : qsa(elmStr); if (!elm) err('(qsa) Could not get element -', elmStr); return elm; } /* function setProp(parent, path, val) { if (!parent || typeof parent !== 'object') return; path = Array.isArray(path) ? Array.from(path) : path.split('.'); var child, prop; while (path.length > 1) { prop = path.shift(); child = parent[prop]; if (!child || typeof child !== 'object') parent[prop] = {}; parent = parent[prop]; } parent[path.shift()] = val; } function getProp(obj, path, defaultValue) { path = Array.isArray(path) ? Array.from(path) : path.split('.'); var prop = obj; while (path.length && obj) { prop = obj[path.shift()]; } return prop != null ? prop : defaultValue; } */ // ==== Scrape ===== // == Title == function getTitle() { // only include the first host for brevity return document.title + ' (' + getHostedByText()[0] + ')'; } // == Dates == function convertDateString(dateObj) { return dateObj.toISOString() .replace(/-/g, '') .replace(/:/g, '') .replace('.000Z', ''); } function getDates() { return qsv('#event_time_info ._2ycp') .getAttribute('content') .split(' to ') .map(date => new Date(date)) .map(convertDateString); } function getStartDate() { return getDates()[0]; } function getEndDate() { return getDates()[1]; } // == Location / Address == function getLocation() { var hovercard = qsv('[data-hovercard]', qs('#event_summary')); return hovercard ? hovercard.innerText : ''; } function getAddress() { var hovercard = qsv('[data-hovercard]', qs('#event_summary')), addr = qsv('#u_0_1h'); if (hovercard) return hovercard.nextSibling.innerText || 'No Address Specified'; else if (addr) return addr.innerText; else // certain addresses like GPS coordinates // e.g. https://facebook.com/events/199708740636288/ // HACK: don't have a unique way to get the text (matches time and address - address is second) return Array.from(qsav('._5xhk')).slice(-1)[0].innerText; } function getLocationAndAddress() { return getLocation() ? (getLocation() + ', ' + getAddress()) : getAddress(); } // == Description == function getDescription() { var seeMore = qsv('.see_more_link'); if (seeMore) seeMore.click(); // expand description return location.href + '\n\n' + qsv('[data-testid="event-permalink-details"]').innerText; // Zip text array with links array? //'\n\nHosted By:\n' + //getHostedByText().join(', ') + '\n' + getHostedByLinks().join('\n') + } function getHostedByText() { var el = qsv('._5gnb [content]'); var text = el.getAttribute('content'); if (text.lastIndexOf(' & ') !== -1) text = text.substr(0, text.lastIndexOf(' & ')); // chop off trailing ' & ' return text.split(' & '); } // ==== Make Export URL ===== function makeExportUrl() { console.time('makeExportUrl'); var ev = { title : getTitle(), startDate : getStartDate(), endDate : getEndDate() || getStartDate(), // set to startDate if undefined locAndAddr : getLocationAndAddress(), description : getDescription() }; var totalLength = 0; for (var prop in ev) if (ev.hasOwnProperty(prop)) { ev[prop] = euc(dbg(ev[prop], ' - ' + prop)); totalLength += ev[prop].length; } // max is about 8200 chars but allow some slack for the base URL const MAX_URL_LENGTH = 8000; console.info('event props totalLength', totalLength); if (totalLength > MAX_URL_LENGTH) { var numCharsOverLimit = totalLength - MAX_URL_LENGTH; var maxEventDescriptionChars = ev.description.length - numCharsOverLimit; // will only happen if event title or location is extremely long // FIXME: truncate event title / location if necessary if (maxEventDescriptionChars < 1) { console.warn('maxEventDescriptionChars is', maxEventDescriptionChars); } console.warn('Event description truncated from', ev.description.length, 'characters to', maxEventDescriptionChars, 'characters'); ev.description = ev.description.substr(0, maxEventDescriptionChars) + '...'; } // gcal format - http://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar // Create link, use UTC timezone to be compatible with toISOString() var exportUrl = 'https://calendar.google.com/calendar/render?action=TEMPLATE&text=[TITLE]&dates=[STARTDATE]/[ENDDATE]&details=[DETAILS]&location=[LOCATION]&ctz=UTC'; exportUrl = exportUrl .replace('[TITLE]', ev.title) .replace('[STARTDATE]', ev.startDate) .replace('[ENDDATE]', ev.endDate) .replace('[LOCATION]', ev.locAndAddr) .replace('[DETAILS]', ev.description); console.info('exportUrl length =', exportUrl.length); console.timeEnd('makeExportUrl'); return dbg(exportUrl, ' - Export URL'); } function addExportLink() { console.time('addExportLink'); log('Event Exporter running'); var evBarElm = qsv('#event_button_bar'), exportElmLink = qsv('a', evBarElm), exportElmParent = exportElmLink.parentNode; exportElmLink = exportElmLink.cloneNode(); exportElmLink.href = makeExportUrl(); exportElmLink.textContent = 'Export Event'; // Disable Facebook event listeners (that are attached due to cloning element) exportElmLink.removeAttribute('ajaxify'); exportElmLink.removeAttribute('rel'); exportElmLink.removeAttribute('data-onclick'); // Open in new tab exportElmLink.target = '_blank'; exportElmParent.appendChild(exportElmLink); var evBarLinks = qsav('a', evBarElm); Array.from(evBarLinks).forEach(function (a) { // fix styles a.style.display = 'inline-block'; }); console.timeEnd('addExportLink'); } (function (oldPushState) { // monkey patch pushState so that script works when navigating around Facebook window.history.pushState = function () { dbg('running pushState'); oldPushState.apply(window.history, arguments); setTimeout(addExportLinkWhenLoaded, 1000); }; dbg('monkey patched pushState'); })(window.history.pushState); // onpopstate is sometimes null causing the following error: // 'Cannot set property onpopstate of #<Object> which has only a getter' if (window.onpopstate) { window.onpopstate = function () { dbg('pop state event fired'); setTimeout(addExportLinkWhenLoaded, 1000); }; } else { dbg('Unable to set "onpopstate" event', window.onpopstate); } function addExportLinkWhenLoaded() { if (location.href.indexOf('/events/') === -1) { dbg('not an event page. skipping...'); return; } else if (!qs('#event_button_bar') || !qs('#event_summary')) { // not loaded dbg('page not loaded...'); setTimeout(addExportLinkWhenLoaded, 1000); } else { // loaded dbg('page loaded...adding link'); addExportLink(); } } var onLoad = addExportLinkWhenLoaded; window.addEventListener('load', onLoad, true);
'use strict'; var got = require('got'); module.exports = function (userName, callback) { if (!(typeof userName === 'string' && userName.length !== 0)) { throw new Error('User Name required'); } got('https://api.github.com/users/' + userName.toLowerCase(), function (err, data) { if (err) { if (err.statusCode === 404) { callback(null, true); return; } callback(err); return; } var jsonObject = JSON.parse(data); if (jsonObject.hasOwnProperty('login')) { callback(null, false); return; } }); };
#!/usr/bin/env node var electron = require('./') var proc = require('child_process') var child = proc.spawn(electron, process.argv.slice(2), {stdio: 'inherit'}) child.on('close', function (code) { process.exit(code) }) const handleTerminationSignal = function (signal) { process.on(signal, function signalHandler () { if (!child.killed) { child.kill(signal) } }) } handleTerminationSignal('SIGINT') handleTerminationSignal('SIGTERM')
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), errorHandler = require('../errors.server.controller'), mongoose = require('mongoose'), passport = require('passport'), User = mongoose.model('User'), config = require('../../../config/config'), nodemailer = require('nodemailer'), async = require('async'), crypto = require('crypto'); /** * Forgot for reset password (forgot POST) */ exports.forgot = function(req, res, next) { async.waterfall([ // Generate random token function(done) { crypto.randomBytes(20, function(err, buffer) { var token = buffer.toString('hex'); done(err, token); }); }, // Lookup user by username function(token, done) { if (req.body.username) { User.findOne({ username: req.body.username }, '-salt -password', function(err, user) { if (!user) { return res.status(400).send({ message: 'No account with that email has been found' }); } else { user.resetPasswordToken = token; user.resetPasswordExpires = Date.now() + 3600000; // 1 hour user.save(function(err) { done(err, token, user); }); } }); } else { return res.status(400).send({ message: 'Email field must not be blank' }); } }, function(token, user, done) { res.render('templates/reset-password-email', { name: user.displayName, appName: config.app.title, url: 'http://' + req.headers.host + '/auth/reset/' + token }, function(err, emailHTML) { done(err, emailHTML, user); }); }, // If valid email, send reset email using service function(emailHTML, user, done) { var smtpTransport = nodemailer.createTransport(config.mailer.options); var mailOptions = { to: user.email, from: config.mailer.from, subject: 'Password Reset', html: emailHTML }; smtpTransport.sendMail(mailOptions, function(err) { if (!err) { res.send({ message: 'An email has been sent to ' + user.email + ' with further instructions.' }); } done(err); }); } ], function(err) { if (err) return next(err); }); }; /** * Reset password GET from email token */ exports.validateResetToken = function(req, res) { User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) { if (!user) { return res.redirect('/#!/password/reset/invalid'); } res.redirect('/#!/password/reset/' + req.params.token); }); }; /** * Reset password POST from email token */ exports.reset = function(req, res, next) { // Init Variables var passwordDetails = req.body; async.waterfall([ function(done) { User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) { if (!err && user) { if (passwordDetails.newPassword === passwordDetails.verifyPassword) { user.password = passwordDetails.newPassword; user.resetPasswordToken = undefined; user.resetPasswordExpires = undefined; user.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { req.login(user, function(err) { if (err) { res.status(400).send(err); } else { // Return authenticated user res.json(user); done(err, user); } }); } }); } else { return res.status(400).send({ message: 'Passwords do not match' }); } } else { return res.status(400).send({ message: 'Password reset token is invalid or has expired.' }); } }); }, function(user, done) { res.render('templates/reset-password-confirm-email', { name: user.displayName, appName: config.app.title }, function(err, emailHTML) { done(err, emailHTML, user); }); }, // If valid email, send reset email using service function(emailHTML, user, done) { var smtpTransport = nodemailer.createTransport(config.mailer.options); var mailOptions = { to: user.email, from: config.mailer.from, subject: 'Your password has been changed', html: emailHTML }; smtpTransport.sendMail(mailOptions, function(err) { done(err, 'done'); }); } ], function(err) { if (err) return next(err); }); }; /** * Change Password */ exports.changePassword = function(req, res) { // Init Variables var passwordDetails = req.body; if (req.user) { if (passwordDetails.newPassword) { User.findById(req.user.id, function(err, user) { if (!err && user) { if (user.authenticate(passwordDetails.currentPassword)) { if (passwordDetails.newPassword === passwordDetails.verifyPassword) { user.password = passwordDetails.newPassword; user.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { req.login(user, function(err) { if (err) { res.status(400).send(err); } else { res.send({ message: 'Password changed successfully' }); } }); } }); } else { res.status(400).send({ message: 'Passwords do not match' }); } } else { res.status(400).send({ message: 'Current password is incorrect' }); } } else { res.status(400).send({ message: 'User is not found' }); } }); } else { res.status(400).send({ message: 'Please provide a new password' }); } } else { res.status(400).send({ message: 'User is not signed in' }); } };
var searchData= [ ['progress',['progress',['../struct_log_type.html#a42f5153a559d41c697e4763ed36ff217aaf0ab04c6e780051a63639d0df57eb20',1,'LogType']]] ];
"use strict"; var commandToBuffer = require("./commandToBuffer"); var Animations = module.exports = function(self) { this.self = self; }; Animations.prototype.startAnimation = function(anim) { var buffer = commandToBuffer(0, "Animations", "StartAnimation", anim); this.self._writePacket(this.self._networkFrameGenerator(buffer)); return this.self; }; Animations.prototype.stopAnimation = function(anim) { var buffer = commandToBuffer(0, "Animations", "StopAnimation", anim); this.self._writePacket(this.self._networkFrameGenerator(buffer)); return this.self; }; Animations.prototype.stopAllAnimations = function() { var buffer = commandToBuffer(0, "Animations", "StopAllAnimations"); this.self._writePacket(this.self._networkFrameGenerator(buffer)); return this.self; };
/** * Copyright (c) 2012 eBay Inc. * Author: Senthil Padmanabhan * * Released under the MIT License * http://www.opensource.org/licenses/MIT * * A standalone rules array to hold the basic spof rules * @property rules * @type Object[] */ var rules = []; /** * A global function to check if a given URL belongs to the a third party domain. * A block pattern is maintained which lists all the possible third party scripts * that can be included in a page * @param {String} url The url to be verified * @return {Boolean} The flag indicating if the given url belongs to a third party domain * @method is3P */ function is3P(url) { // Known 3rd-party assets // Ref: https://github.com/pmeenan/spof-o-matic/blob/master/src/background.js var BLOCK_PATTERN = [ 'platform\.twitter\.com', 'connect\.facebook\.net', 'platform\.linkedin\.com', 'assets\.pinterest\.com', 'widgets\.digg\.com', '.*\.addthis\.com', 'ajax\.googleapis\.com', 'code\.jquery\.com', 'cdn\.jquerytools\.org', 'apis\.google\.com', '.*\.google-analytics\.com', '.*\.chartbeat\.com', 'static\.chartbeat\.com', '.*\.2o7\.net', '.*\.revsci\.net', '.*\.omtrdc\.net', 'b\.scorecardresearch\.com', 'cdn\.sailthru\.com', '.*browserid\.org', 'ad\.doubleclick\.net', 'js\.adsonar\.com', 'ycharts\.com', '.*\.googlecode\.com', '.*\.gstatic\.com', '.*\.quantserve\.com', '.*\.brightcove\.com', '.*\.disqus\.com', '.*\.lognormal\.com' ], i, l, regEx; for (i = 0, l = BLOCK_PATTERN.length; i < l; i++) { regEx = new RegExp(BLOCK_PATTERN[i], 'im'); if (regEx.test(url)) { return true; } } return false; } /** * Rule: Load 3rd party JS Asynchronously */ rules.push({ // Rule metadata id: "3rdparty-scripts", name: "Load 3rd Party JS Asynchronously", desc: "Always load 3rd party external scripts asyncronously in a non-blocking pattern", // The check function to verify the rule check: function($, cssContent, reporter) { var rule = this, html = $('html').html(), pageLength = html.length, scripts = $('script'), /** * Determines the SPOF score for the script url in the page * @param {String} src The script source for which the score should be determined * @return {int} The score * @method getScore */ getScore = function(src) { var value = 100 - (((html.indexOf(src) + src.length) / pageLength) * 100); return Math.round(value); }, i, l, script, src; for (i = 0, l = scripts.length; i < l; i++) { script = scripts[i]; src = script.src; if (src && is3P(src)) { if (!script.defer || !script.async) { reporter.error("ERROR: Possible SPOF attack due to 3rd party script - " + src, src, getScore(src), rule); } } } } }); /** * Rule: Load Application JS Non-blocking */ rules.push({ // Rule metadata id: "application-js", name: "Load Application JS Non-blocking", desc: "Load application JS in a non-blocking pattern or towards the end of page", // The check function to verify the rule check: function($, cssContent, reporter) { var rule = this, html = $('html').html(), pageLength = html.length, scripts = $('script'), /** * Determines the SPOF score for the script url in the page * @param {String} src The script source for which the score should be determined * @return {int} The score * @method getScore */ getScore = function(src) { var value = 100 - (((html.indexOf(src) + src.length) / pageLength) * 100); return Math.round(value); }, i, l, script, src, score; for (i = 0, l = scripts.length; i < l; i++) { script = scripts[i]; src = script.src; if (src && !is3P(src)) { score = getScore(src); if (score > 50 && (!script.defer || !script.async)) { reporter.warn("WARNING: Possible SPOF attack due to script " + src, src, score, rule); } } } } }); /** * Rule: Stylesheet With @font-face */ rules.push({ // Rule metadata id: "fontface-stylesheet", name: "Stylesheet With @font-face", desc: "Try to inline @font-face style. Also make the font files compressed and cacheable", // The check function to verify the rule check: function($, cssContent, reporter) { var rule = this, pattern = /@font-face[\s\n]*{([^{}]*)}/gim, // RegEx pattern for retrieving all the font-face styles urlPattern = /url\s*\(\s*['"]?([^'"]*)['"]?\s*\)/gim, // RegEx pattern for retrieving the urls font-face styles fontFaceMatches, fontUrl; if (!cssContent || cssContent === "") { // Return immediately if CSS content is empty return; } fontFaceMatches = cssContent.match(pattern); if (!fontFaceMatches) { // Return if no font-face style return; } fontFaceMatches.forEach(function(match) { while (fontUrl = urlPattern.exec(match)) { fontUrl[1] && reporter.warn("WARNING: Possible SPOF attack due to @font-face style in external stylesheet", fontUrl[1], "NA", rule); } }); } }); /** * Rule: Inline @font-face */ rules.push({ // Rule metadata id: "fontface-inline", name: "Inline @font-face", desc: "Make sure the fonts files are compressed, cached and small in size", // The check function to verify the rule check: function($, cssContent, reporter) { var rule = this, html = $('html').html(), pattern = /@font-face[\s\n]*{([^{}]*)}/gim, // RegEx pattern for retrieving all the font-face styles urlPattern = /url\s*\(\s*['"]?([^'"]*)['"]?\s*\)/gim, // RegEx pattern for retrieving the urls font-face styles fontFaceMatches, fontUrl; fontFaceMatches = html.match(pattern); if (!fontFaceMatches) { // Return if no font-face style return; } fontFaceMatches.forEach(function(match) { while (fontUrl = urlPattern.exec(match)) { fontUrl[1] && reporter.warn("WARNING: Possible SPOF attack due to inline @font-face style", fontUrl[1], "NA", rule); } }); } }); /** * Rule: Inline @font-face precede Script tag IE issue */ rules.push({ // Rule metadata id: "fontface-inline-precede-script-IE", name: "Inline @font-face precede Script tag IE issue", desc: "Make sure inlined @font-face is not preceded by a SCRIPT tag, causes SPOF in IE", // The check function to verify the rule check: function($, cssContent, reporter) { var rule = this, html = $('html').html(), scriptStylePattern = /<script[^>]*>[\s\S]*?<\/script>\s*<style[^>]*>[\s\S]*?<\/style>/gim, scriptStyleMatches, multipleMsg; scriptStyleMatches = html.match(scriptStylePattern); if (!scriptStyleMatches) { // Return if no font-face style return; } multipleMsg = scriptStyleMatches.length > 1 ? 'multiple occurances of ' : ''; reporter.warn("WARNING: Possible SPOF attack in IE due to " + multipleMsg + "inline @font-face preceded by a SCRIPT tag", "NA", "NA", rule); } }); // Exporting the rules for node environment if (typeof exports != 'undefined') { exports.rules = rules; }
/* Browser detection script - modified from http://www.quirksmode.org/js/detect.html */ elation.extend("browser", new function() { this.checkIt = function (string) { this.place = detect.indexOf(string) + 1; this.tmpstring = string; return this.place; } var detect = navigator.userAgent.toLowerCase(); if (this.checkIt('konqueror')) { this.type = "Konqueror"; this.OS = "Linux"; } else if (this.checkIt('iphone')) this.type = "iphone" else if (this.checkIt('android')) this.type = "android" else if (this.checkIt('safari')) this.type = "safari" else if (this.checkIt('omniweb')) this.type = "omniweb" else if (this.checkIt('opera')) this.type = "opera" else if (this.checkIt('webtv')) this.type = "webtv"; else if (this.checkIt('icab')) this.type = "icab" else if (this.checkIt('msie')) this.type = "msie" else if (this.checkIt('firefox')) this.type = "firefox" else if (!this.checkIt('compatible')) { this.type = "netscape" this.version = detect.charAt(8); } else this.type = "unknown"; if (!this.version) this.version = detect.charAt(this.place + this.tmpstring.length); if (!this.OS) { if (this.checkIt('linux')) this.OS = "linux"; else if (this.checkIt('x11')) this.OS = "unix"; else if (this.checkIt('mac')) this.OS = "mac" else if (this.checkIt('win')) this.OS = "windows" else this.OS = "unknown"; } }); // Fake console.log to prevent scripts from erroring out in browsers without firebug if (typeof window.console == 'undefined') { console = new function() { this.log = function(str) { //alert(str); } } }
/*! * jQuery UI Droppable 1.11.4 * http://jqueryui.com * * Copyright jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/droppable/ */ (function (factory) { if (typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define([ "jquery", "./core", "./widget", "./mouse", "./draggable" ], factory); } else { // Browser globals factory(jQuery); } }(function ($) { $.widget("ui.droppable", { version: "1.11.4", widgetEventPrefix: "drop", options: { accept: "*", activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: "default", tolerance: "intersect", // callbacks activate: null, deactivate: null, drop: null, out: null, over: null }, _create: function () { var proportions, o = this.options, accept = o.accept; this.isover = false; this.isout = true; this.accept = $.isFunction(accept) ? accept : function (d) { return d.is(accept); }; this.proportions = function (/* valueToWrite */) { if (arguments.length) { // Store the droppable's proportions proportions = arguments[0]; } else { // Retrieve or derive the droppable's proportions return proportions ? proportions : proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; } }; this._addToManager(o.scope); o.addClasses && this.element.addClass("ui-droppable"); }, _addToManager: function (scope) { // Add the reference and positions to the manager $.ui.ddmanager.droppables[scope] = $.ui.ddmanager.droppables[scope] || []; $.ui.ddmanager.droppables[scope].push(this); }, _splice: function (drop) { var i = 0; for (; i < drop.length; i++) { if (drop[i] === this) { drop.splice(i, 1); } } }, _destroy: function () { var drop = $.ui.ddmanager.droppables[this.options.scope]; this._splice(drop); this.element.removeClass("ui-droppable ui-droppable-disabled"); }, _setOption: function (key, value) { if (key === "accept") { this.accept = $.isFunction(value) ? value : function (d) { return d.is(value); }; } else if (key === "scope") { var drop = $.ui.ddmanager.droppables[this.options.scope]; this._splice(drop); this._addToManager(value); } this._super(key, value); }, _activate: function (event) { var draggable = $.ui.ddmanager.current; if (this.options.activeClass) { this.element.addClass(this.options.activeClass); } if (draggable) { this._trigger("activate", event, this.ui(draggable)); } }, _deactivate: function (event) { var draggable = $.ui.ddmanager.current; if (this.options.activeClass) { this.element.removeClass(this.options.activeClass); } if (draggable) { this._trigger("deactivate", event, this.ui(draggable)); } }, _over: function (event) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if (!draggable || ( draggable.currentItem || draggable.element )[0] === this.element[0]) { return; } if (this.accept.call(this.element[0], ( draggable.currentItem || draggable.element ))) { if (this.options.hoverClass) { this.element.addClass(this.options.hoverClass); } this._trigger("over", event, this.ui(draggable)); } }, _out: function (event) { var draggable = $.ui.ddmanager.current; // Bail if draggable and droppable are same element if (!draggable || ( draggable.currentItem || draggable.element )[0] === this.element[0]) { return; } if (this.accept.call(this.element[0], ( draggable.currentItem || draggable.element ))) { if (this.options.hoverClass) { this.element.removeClass(this.options.hoverClass); } this._trigger("out", event, this.ui(draggable)); } }, _drop: function (event, custom) { var draggable = custom || $.ui.ddmanager.current, childrenIntersection = false; // Bail if draggable and droppable are same element if (!draggable || ( draggable.currentItem || draggable.element )[0] === this.element[0]) { return false; } this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function () { var inst = $(this).droppable("instance"); if ( inst.options.greedy && !inst.options.disabled && inst.options.scope === draggable.options.scope && inst.accept.call(inst.element[0], ( draggable.currentItem || draggable.element )) && $.ui.intersect(draggable, $.extend(inst, {offset: inst.element.offset()}), inst.options.tolerance, event) ) { childrenIntersection = true; return false; } }); if (childrenIntersection) { return false; } if (this.accept.call(this.element[0], ( draggable.currentItem || draggable.element ))) { if (this.options.activeClass) { this.element.removeClass(this.options.activeClass); } if (this.options.hoverClass) { this.element.removeClass(this.options.hoverClass); } this._trigger("drop", event, this.ui(draggable)); return this.element; } return false; }, ui: function (c) { return { draggable: ( c.currentItem || c.element ), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = (function () { function isOverAxis(x, reference, size) { return ( x >= reference ) && ( x < ( reference + size ) ); } return function (draggable, droppable, toleranceMode, event) { if (!droppable.offset) { return false; } var x1 = ( draggable.positionAbs || draggable.position.absolute ).left + draggable.margins.left, y1 = ( draggable.positionAbs || draggable.position.absolute ).top + draggable.margins.top, x2 = x1 + draggable.helperProportions.width, y2 = y1 + draggable.helperProportions.height, l = droppable.offset.left, t = droppable.offset.top, r = l + droppable.proportions().width, b = t + droppable.proportions().height; switch (toleranceMode) { case "fit": return ( l <= x1 && x2 <= r && t <= y1 && y2 <= b ); case "intersect": return ( l < x1 + ( draggable.helperProportions.width / 2 ) && // Right Half x2 - ( draggable.helperProportions.width / 2 ) < r && // Left Half t < y1 + ( draggable.helperProportions.height / 2 ) && // Bottom Half y2 - ( draggable.helperProportions.height / 2 ) < b ); // Top Half case "pointer": return isOverAxis(event.pageY, t, droppable.proportions().height) && isOverAxis(event.pageX, l, droppable.proportions().width); case "touch": return ( ( y1 >= t && y1 <= b ) || // Top edge touching ( y2 >= t && y2 <= b ) || // Bottom edge touching ( y1 < t && y2 > b ) // Surrounded vertically ) && ( ( x1 >= l && x1 <= r ) || // Left edge touching ( x2 >= l && x2 <= r ) || // Right edge touching ( x1 < l && x2 > r ) // Surrounded horizontally ); default: return false; } }; })(); /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: {"default": []}, prepareOffsets: function (t, event) { var i, j, m = $.ui.ddmanager.droppables[t.options.scope] || [], type = event ? event.type : null, // workaround for #2317 list = ( t.currentItem || t.element ).find(":data(ui-droppable)").addBack(); droppablesLoop: for (i = 0; i < m.length; i++) { // No disabled and non-accepted if (m[i].options.disabled || ( t && !m[i].accept.call(m[i].element[0], ( t.currentItem || t.element )) )) { continue; } // Filter out elements in the current dragged item for (j = 0; j < list.length; j++) { if (list[j] === m[i].element[0]) { m[i].proportions().height = 0; continue droppablesLoop; } } m[i].visible = m[i].element.css("display") !== "none"; if (!m[i].visible) { continue; } // Activate the droppable if used directly from draggables if (type === "mousedown") { m[i]._activate.call(m[i], event); } m[i].offset = m[i].element.offset(); m[i].proportions({width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight}); } }, drop: function (draggable, event) { var dropped = false; // Create a copy of the droppables in case the list changes during the drop (#9116) $.each(( $.ui.ddmanager.droppables[draggable.options.scope] || [] ).slice(), function () { if (!this.options) { return; } if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance, event)) { dropped = this._drop.call(this, event) || dropped; } if (!this.options.disabled && this.visible && this.accept.call(this.element[0], ( draggable.currentItem || draggable.element ))) { this.isout = true; this.isover = false; this._deactivate.call(this, event); } }); return dropped; }, dragStart: function (draggable, event) { // Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil("body").bind("scroll.droppable", function () { if (!draggable.options.refreshPositions) { $.ui.ddmanager.prepareOffsets(draggable, event); } }); }, drag: function (draggable, event) { // If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if (draggable.options.refreshPositions) { $.ui.ddmanager.prepareOffsets(draggable, event); } // Run through all droppables and check their positions based on specific tolerance options $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function () { if (this.options.disabled || this.greedyChild || !this.visible) { return; } var parentInstance, scope, parent, intersects = $.ui.intersect(draggable, this, this.options.tolerance, event), c = !intersects && this.isover ? "isout" : ( intersects && !this.isover ? "isover" : null ); if (!c) { return; } if (this.options.greedy) { // find droppable parents with same scope scope = this.options.scope; parent = this.element.parents(":data(ui-droppable)").filter(function () { return $(this).droppable("instance").options.scope === scope; }); if (parent.length) { parentInstance = $(parent[0]).droppable("instance"); parentInstance.greedyChild = ( c === "isover" ); } } // we just moved into a greedy child if (parentInstance && c === "isover") { parentInstance.isover = false; parentInstance.isout = true; parentInstance._out.call(parentInstance, event); } this[c] = true; this[c === "isout" ? "isover" : "isout"] = false; this[c === "isover" ? "_over" : "_out"].call(this, event); // we just moved out of a greedy child if (parentInstance && c === "isout") { parentInstance.isout = false; parentInstance.isover = true; parentInstance._over.call(parentInstance, event); } }); }, dragStop: function (draggable, event) { draggable.element.parentsUntil("body").unbind("scroll.droppable"); // Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if (!draggable.options.refreshPositions) { $.ui.ddmanager.prepareOffsets(draggable, event); } } }; return $.ui.droppable; }));
/** * @fileOverview _h3.js traverse throught DOM and assign a11y labels. * * @author Gagandeep Singh <robi_osahan@yahoo.com> * @version 1.0.0 */ (function(window, $, undefined){ a11y._h3 = function(scope, options){ var ele = scope.find("h3"), self = this, labeler = { init: function(){ if( ele.length > 0){ this.assignLabels(); } }, assignLabels: function(){ $.each(ele, function() { var $this = $(this), role = $this.prop("role"); self.keepTrack( $this ); if( typeof role === "undefined"){ $this.attr("role", "heading"); } }); } }; labeler.init(); }; })(this, jQuery);
'use strict'; module.exports = { db: 'mongodb://localhost/the-thriftshop-test', port: 3001, app: { title: 'The Thriftshop - Test Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'http://localhost:3000/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'http://localhost:3000/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
import isEmpty from './isEmpty' import declination from './declination' const declDays = declination([ 'день', 'дня', 'дней' ]); const declWeeks = declination([ 'неделя', 'недели', 'недель' ]); const declHours = declination([ 'час', 'часа', 'часов' ]); export default __data => { if (isEmpty(__data)) return 'Свежее'; const current = new Date(); let currentYear = current.getFullYear().toString(); let currentMonth = (current.getMonth()+1).toString(); const date = new Date(__data); let day = date.getDate().toString(); let month = (date.getMonth()+1).toString(); let year = date.getFullYear().toString(); if (year === currentYear && month === currentMonth) { const currentDay = parseInt(current.getDate().toString(), 10); const objectDay = parseInt(day, 10); const currentHour = current.getHours(); const objectHour = date.getHours(); const dayDifference = currentDay - objectDay; if (objectDay === currentDay) { const hourDifference = currentHour - objectHour; if (hourDifference <= 12) { if (hourDifference < 1) { return 'Только что' } return `${hourDifference} ${declHours(hourDifference)} назад` } return 'Сегодня' } if (dayDifference === 1) { return 'Вчера' } if (dayDifference < 7) { return `${dayDifference} ${declDays(dayDifference)} назад` } if (dayDifference >= 7 && dayDifference <= 14) { const weeks = parseInt(dayDifference / 7); return `${weeks} ${declWeeks(weeks)} назад` } } if (day.length < 2) { day = `0${day}` } if (month.length < 2) { month = `0${month}` } return `${day}.${month}.${year}` }
import PolygonLayer from 'ember-leaflet/components/polygon-layer'; /** * A class for drawing rectangle overlays on a map. * * @class RectangleLayer * @extends PolygonLayer */ export default class RectangleLayer extends PolygonLayer { createLayer() { return this.L.rectangle(...this.requiredOptions, this.options); } }
"use strict" /** * Created by garusis on 04/05/17. */ export {providers} from "./availableList" export {strategies} from "./strategies"
var fs = require('fs') var childProcess = require('child_process') var AWS = require('aws-sdk') var s3 = new AWS.S3() exports.handler = function(event, context) { var filename = 'nodejs.tgz' var cmd = 'tar -cpzf /tmp/' + filename + ' --numeric-owner --ignore-failed-read /var/runtime /var/lang' var child = childProcess.spawn('sh', ['-c', event.cmd || cmd]) child.stdout.setEncoding('utf8') child.stderr.setEncoding('utf8') child.stdout.on('data', console.log.bind(console)) child.stderr.on('data', console.error.bind(console)) child.on('error', context.done.bind(context)) child.on('close', function() { if (event.cmd) return context.done() console.log('Zipping done! Uploading...') s3.upload({ Bucket: 'lambci', Key: 'fs/' + filename, Body: fs.createReadStream('/tmp/' + filename), ACL: 'public-read', }, function(err, data) { if (err) return context.done(err) console.log('Uploading done!') console.log(process.execPath) console.log(process.execArgv) console.log(process.argv) console.log(process.cwd()) console.log(__filename) console.log(process.env) console.log(context) context.done() }) }) } // /usr/bin/node // [ '--max-old-space-size=1229', '--max-new-space-size=153', '--max-executable-size=153', '--expose-gc' ] // [ '/usr/bin/node', '/var/runtime/node_modules/awslambda/bin/awslambda' ] // /var/task // /var/task/index.js // { // PATH: '/usr/local/bin:/usr/bin/:/bin:/opt/bin', // LANG: 'en_US.UTF-8', // LD_LIBRARY_PATH: '/lib64:/usr/lib64:/var/runtime:/var/runtime/lib:/var/task:/var/task/lib:/opt/lib', // LAMBDA_TASK_ROOT: '/var/task', // LAMBDA_RUNTIME_DIR: '/var/runtime', // AWS_REGION: 'us-east-1', // AWS_DEFAULT_REGION: 'us-east-1', // AWS_LAMBDA_LOG_GROUP_NAME: '/aws/lambda/dump-node010', // AWS_LAMBDA_LOG_STREAM_NAME: '2017/03/23/[$LATEST]c079a84d433534434534ef0ddc99d00f', // AWS_LAMBDA_FUNCTION_NAME: 'dump-node010', // AWS_LAMBDA_FUNCTION_MEMORY_SIZE: '1536', // AWS_LAMBDA_FUNCTION_VERSION: '$LATEST', // _AWS_XRAY_DAEMON_ADDRESS: '169.254.79.2', // _AWS_XRAY_DAEMON_PORT: '2000', // AWS_XRAY_DAEMON_ADDRESS: '169.254.79.2:2000', // AWS_XRAY_CONTEXT_MISSING: 'LOG_ERROR', // _X_AMZN_TRACE_ID: 'Root=1-dc99d00f-c079a84d433534434534ef0d;Parent=91ed514f1e5c03b2;Sampled=0', // AWS_EXECUTION_ENV: 'AWS_Lambda_nodejs', // NODE_PATH: '/var/runtime:/var/task:/var/runtime/node_modules', // AWS_ACCESS_KEY_ID: 'ASIA...C37A', // AWS_SECRET_ACCESS_KEY: 'JZvD...BDZ4L', // AWS_SESSION_TOKEN: 'FQoDYXdzEMb//////////...0oog7bzuQU=' // } // { // awsRequestId: '1fcdc383-a9e8-4228-bc1c-8db17629e183', // invokeid: '1fcdc383-a9e8-4228-bc1c-8db17629e183', // logGroupName: '/aws/lambda/dump-node010', // logStreamName: '2017/03/23/[$LATEST]c079a84d433534434534ef0ddc99d00f', // functionName: 'dump-node010', // memoryLimitInMB: '1536', // functionVersion: '$LATEST', // invokedFunctionArn: 'arn:aws:lambda:us-east-1:879423879432:function:dump-node010', // getRemainingTimeInMillis: [Function], // succeed: [Function], // fail: [Function], // done: [Function] // }
import { connect } from 'react-redux' import { dealCard, increment, resetTable } from '../modules/trackCount' /* This is a container component. Notice it does not contain any JSX, nor does it import React. This component is **only** responsible for wiring in the actions and state necessary to render a presentational component - in this case, the counter: */ import TrackCount from '../components/TrackCount' /* Object of action creators (can also be function that returns object). Keys will be passed as props to presentational components. Here we are implementing our wrapper around increment; the component doesn't care */ const mapDispatchToProps = { dealCard, increment, resetTable, } const mapStateToProps = (state) => ({ upCard: state.trackCount.upCard, cardsDealt: state.trackCount.cardsDealt, }) /* Note: mapStateToProps is where you should use `reselect` to create selectors, ie: import { createSelector } from 'reselect' const counter = (state) => state.counter const tripleCount = createSelector(counter, (count) => count * 3) const mapStateToProps = (state) => ({ counter: tripleCount(state) }) Selectors can compute derived data, allowing Redux to store the minimal possible state. Selectors are efficient. A selector is not recomputed unless one of its arguments change. Selectors are composable. They can be used as input to other selectors. https://github.com/reactjs/reselect */ export default connect(mapStateToProps, mapDispatchToProps)(TrackCount)
const assert = require('assert'); const util = require('./../util/util.js'); describe('assembly expressions', () => { it('should compile after instrumenting an assembly function with spaces in parameters', () => { const info = util.instrumentAndCompile('assembly/spaces-in-function'); util.report(info.solcOutput.errors); }); it('should compile after instrumenting an assembly if statement', () => { const info = util.instrumentAndCompile('assembly/if'); util.report(info.solcOutput.errors); }); });
// All code points in the `Duployan` script as per Unicode v9.0.0: [ 0x1BC00, 0x1BC01, 0x1BC02, 0x1BC03, 0x1BC04, 0x1BC05, 0x1BC06, 0x1BC07, 0x1BC08, 0x1BC09, 0x1BC0A, 0x1BC0B, 0x1BC0C, 0x1BC0D, 0x1BC0E, 0x1BC0F, 0x1BC10, 0x1BC11, 0x1BC12, 0x1BC13, 0x1BC14, 0x1BC15, 0x1BC16, 0x1BC17, 0x1BC18, 0x1BC19, 0x1BC1A, 0x1BC1B, 0x1BC1C, 0x1BC1D, 0x1BC1E, 0x1BC1F, 0x1BC20, 0x1BC21, 0x1BC22, 0x1BC23, 0x1BC24, 0x1BC25, 0x1BC26, 0x1BC27, 0x1BC28, 0x1BC29, 0x1BC2A, 0x1BC2B, 0x1BC2C, 0x1BC2D, 0x1BC2E, 0x1BC2F, 0x1BC30, 0x1BC31, 0x1BC32, 0x1BC33, 0x1BC34, 0x1BC35, 0x1BC36, 0x1BC37, 0x1BC38, 0x1BC39, 0x1BC3A, 0x1BC3B, 0x1BC3C, 0x1BC3D, 0x1BC3E, 0x1BC3F, 0x1BC40, 0x1BC41, 0x1BC42, 0x1BC43, 0x1BC44, 0x1BC45, 0x1BC46, 0x1BC47, 0x1BC48, 0x1BC49, 0x1BC4A, 0x1BC4B, 0x1BC4C, 0x1BC4D, 0x1BC4E, 0x1BC4F, 0x1BC50, 0x1BC51, 0x1BC52, 0x1BC53, 0x1BC54, 0x1BC55, 0x1BC56, 0x1BC57, 0x1BC58, 0x1BC59, 0x1BC5A, 0x1BC5B, 0x1BC5C, 0x1BC5D, 0x1BC5E, 0x1BC5F, 0x1BC60, 0x1BC61, 0x1BC62, 0x1BC63, 0x1BC64, 0x1BC65, 0x1BC66, 0x1BC67, 0x1BC68, 0x1BC69, 0x1BC6A, 0x1BC70, 0x1BC71, 0x1BC72, 0x1BC73, 0x1BC74, 0x1BC75, 0x1BC76, 0x1BC77, 0x1BC78, 0x1BC79, 0x1BC7A, 0x1BC7B, 0x1BC7C, 0x1BC80, 0x1BC81, 0x1BC82, 0x1BC83, 0x1BC84, 0x1BC85, 0x1BC86, 0x1BC87, 0x1BC88, 0x1BC90, 0x1BC91, 0x1BC92, 0x1BC93, 0x1BC94, 0x1BC95, 0x1BC96, 0x1BC97, 0x1BC98, 0x1BC99, 0x1BC9C, 0x1BC9D, 0x1BC9E, 0x1BC9F ];
version https://git-lfs.github.com/spec/v1 oid sha256:5f9dc37e4b4dbcde5986961ff6492dab9b0d51ad59411d4bdd645cd4f47f9f34 size 964
/** @module view */ /* Copyright (c) 2016 Murray J Brown; All rights reserved. */ // // This module processes changes to the application state(s) // (as a result of DOM input effects, i.e., human intents, or // HTTP response messages received) and renders corresponding // virtual DOM elements to be processed by the DOM driver. // import {Observable} from 'rx'; import {a, button, div, hr, h2, h4, input, label, p, span} from "@cycle/dom"; /** * Produce Cycle.js virtual DOM tree states from model states * @function view * @param {Object} states - model state streams * @param {Object} components - component Virtual DOM tree streams * @return {Observable} vtree$ - application Virtual DOM tree stream */ export default function view(states, components) { function bgColourButton(bgColour) { return button('.colour-game-background', 'Generate random background colour'); } function formError(msg) { let errorMsg = ""; if (msg) { errorMsg = [ p('.error', msg) ]; } return errorMsg; } function queryForm(user) { return div(".query-form", [ hr(), h4('Query user information from test server'), label('Number: '), input('.input-user-id', {style: 'text'}), button('.button-get-user-info', 'Get user info'), formError(user.error), hr() ]); } function queryResult(info) { let result = ""; let infoQuery = ""; let infoError = ""; let userDetails = ""; if ( typeof info === 'object' ) { if ( 'query' in info ) { infoQuery = div(".query", [ span('.query .slug', 'Query: '), info.query ? span('.query .url', info.query) : '', hr() ]); } if( 'error' in info ) { infoError = formError(info.error); } if ( 'id' in info ) { userDetails = div(".details", [ div(".user-details", [ h2('.user-name', String(info.id) + ": " + info.name), h4('.user-email', info.email), a('.user-website', {href: info.website}, info.website) ]) ]); } result = div(".query-result", [ infoQuery, infoError, userDetails ]); } return result; } // construct virtual DOM tree const vtree$ = Observable.combineLatest( components.sphereSlider$, states.gameBackgroundColour$, states.userQuery$, states.userInfo$, (sphereSlider, gameBackgroundColour, userQuery, userInfo) => { return div([ bgColourButton(gameBackgroundColour), sphereSlider, queryForm(userQuery), queryResult(userInfo) ]); }); // return virtual DOM tree return vtree$; }
import BaseProvider from "./BaseProvider" export default class NonePruneProvider extends BaseProvider { constructor(props) { super(props) this.rpcUrl = props.url this.initContract() } getBalanceAtSpecificBlock(address, blockno) { return new Promise((resolve, reject) => { reject(new Error("Cannot use /getBalanceAtSpecificBlock with NonePruneProvider")) }) } getMaxCapAtSpecificBlock(address, blockno) { return new Promise((resolve, reject) => { reject(new Error("Cannot use /getMaxCapAtSpecificBlock with NonePruneProvider")) }) } getTokenBalanceAtSpecificBlock(address, ownerAddr, blockno) { return new Promise((resolve, reject) => { reject(new Error("Cannot use /getTokenBalanceAtSpecificBlock with NonePruneProvider")) }) } getAllBalancesTokenAtSpecificBlock(address, tokens, blockNo){ return new Promise((resolve, reject) => { reject(new Error("Cannot use /getAllBalancesTokenAtSpecificBlock with NonePruneProvider")) }) } getAllowanceAtSpecificBlock(sourceToken, owner, blockno) { return new Promise((resolve, reject) => { reject(new Error("Cannot use /getAllowanceAtSpecificBlock with NonePruneProvider")) }) } wrapperGetGasCap(input, blockno) { return new Promise((resolve, reject) => { reject(new Error("Cannot use /wrapperGetGasCap with NonePruneProvider")) }) } wrapperGetConversionRate(reserve, input, blockno) { return new Promise((resolve, reject) => { reject(new Error("Cannot use /wrapperGetConversionRate with NonePruneProvider")) }) } wrapperGetReasons(reserve, input, blockno) { return new Promise((resolve, reject) => { reject(new Error("Cannot use /wrapperGetReasons with NonePruneProvider")) }) } wrapperGetChosenReserve(input, blockno) { return new Promise((resolve, reject) => { reject(new Error("Cannot use /wrapperGetChosenReserve with NonePruneProvider")) }) } }
/****** *任务工时统计相关操作 ******/ var taskTimeReportOps = { //更新项目报表对象 updateReport: function (vault, objId, newReportData) { //newPropsData:{ 'startDate', 'deadline''checkedItems':[task], 'reportInfo':string} reportOps.updateReport(vault, md.taskTimeReport.classAlias, objId, newReportData); }, _getMfDate: function(jsDate) { var ts = MFiles.CreateInstance('Timestamp'); //ts.SetValue(jsDate); ts.Year = jsDate.getFullYear(); ts.Month = jsDate.getMonth() + 1; ts.Day = jsDate.getDate(); return ts.GetValue(); }, //读取历史数据 getOldReportData: function (vault, props) { ////返回值:{ 'startDate': string, 'deadline': string, 'checkedItems': [{ "id": int, "label": string,"isChecked": bool }], 'reportInfo': string } return reportOps.getHistoryReportData(vault, md.taskTimeReport.classAlias, props); }, //筛选任务list getTasksOnCondition: function (vault, beginDate, endDate) { var tasks = this.getAllTasks(vault); var list = []; for (var j = 0; j < tasks.length; j++) { var item = tasks[j]; if (!beginDate && !endDate) { list.push(item); } if (!beginDate && endDate) { var endDateStr = item.EndDateString; if (endDateStr) { var eTime = new Date(endDateStr.replace(/\-/g, "/")); if (endDate >= eTime) { list.push(item); } } } if (beginDate && !endDate) { var beginDateStr = item.BeginDateString; if (beginDateStr) { var bTime = new Date(beginDateStr.replace(/\-/g, "/")); if (beginDate <= bTime) { list.push(item); } } } if (beginDate && endDate) { var flag = false; endDateStr = item.EndDateString; beginDateStr = item.BeginDateString; if (endDateStr && beginDateStr) { eTime = new Date(endDateStr.replace(/\-/g, "/")); bTime = new Date(beginDateStr.replace(/\-/g, "/")); if (endDate >= eTime && beginDate <= bTime) { list.push(item); } } } } return list; }, //搜索所有任务 getAllTasks: function (vault) { this.allTasks = this.allTasks || []; if (this.allTasks.length === 0) { var propIdBDate = MF.alias.propertyDef(vault, md.genericTask.propDefs.StartDate); var propIdEDate = MF.alias.propertyDef(vault, md.genericTask.propDefs.Deadline); var sConditons = MFiles.CreateInstance("SearchConditions"); var condition = MFiles.CreateInstance("SearchCondition"); condition.ConditionType = MFConditionTypeNotEqual; condition.Expression.DataPropertyValuePropertyDef = MFBuiltInPropertyDefClass; condition.TypedValue.SetValue(MFDatatypeLookup, -100); sConditons.Add(-1, condition); var objvns = MF.ObjectOps.SearchObjects(vault, MFBuiltInObjectTypeAssignment, sConditons); for (var i = 1; i <= objvns.Count; i++) { var item = objvns.Item(i); var beginDateString = vault.ObjectPropertyOperations.GetProperty(item.ObjVer, propIdBDate).Value.DisplayValue; var endDateString = vault.ObjectPropertyOperations.GetProperty(item.ObjVer, propIdEDate).Value.DisplayValue; this.allTasks.push({ 'ID': item.ObjVer.ID, 'Title': item.Title, 'BeginDateString': beginDateString, 'EndDateString': endDateString }); } } return this.allTasks; }, //转为checklist tasks2CheckList:function(tasks) { var checklist = []; for (var i = 0; i < tasks.length; i++) { checklist.push({ 'id': tasks[i].ID, 'label': tasks[i].Title, 'isChecked': false }); } return checklist; }, getTasksOnConditionEx: function (vault, beginDate, endDate) { var sConditons = MFiles.CreateInstance("SearchConditions"); var condition = MFiles.CreateInstance("SearchCondition"); condition.ConditionType = MFConditionTypeEqual; condition.Expression.DataPropertyValuePropertyDef = MFBuiltInPropertyDefClass; condition.TypedValue.SetValue(MFDatatypeLookup, -100); sConditons.Add(-1, condition); if (beginDate) { beginDate = this._getMfDate(beginDate); var propIdBDate = MF.alias.propertyDef(vault, md.genericTask.propDefs.StartDate); var scBDate = MFiles.CreateInstance("SearchCondition"); scBDate.ConditionType = MFConditionTypeGreaterThanOrEqual; scBDate.Expression.DataPropertyValuePropertyDef = propIdBDate; scBDate.TypedValue.SetValue(MFDatatypeDate, beginDate); sConditons.Add(-1, scBDate); } if (endDate) { endDate = this._getMfDate(endDate); var propIdEDate = MF.alias.propertyDef(vault, md.genericTask.propDefs.Deadline); var scEDate = MFiles.CreateInstance("SearchCondition"); scEDate.ConditionType = MFConditionTypeLessThanOrEqual; scEDate.Expression.DataPropertyValuePropertyDef = propIdEDate; scEDate.TypedValue.SetValue(MFDatatypeDate, endDate); sConditons.Add(-1, scEDate); } var objvns = MF.ObjectOps.SearchObjects(vault, MFBuiltInObjectTypeAssignment, sConditons); var tasks = []; for (var i = 1; i <= objvns.Count; i++) { var item = objvns.Item(i); tasks.push({ 'id': item.ObjVer.ID, 'label': item.Title, 'isChecked': false }); } return tasks; }, //获取工时统计信息 getJobTimeReportData: function (vault, tasks) { //tasks:[] var statistics = [];// { id:1, man: "刘建立", finished: 30, unfinished: 20, total: 50 }, for (var i = 0; i < tasks.length; i++) { var taskInfo = this.getTaskJobTime(vault, tasks[i]); if (taskInfo) { var finishedMen = taskInfo.finishedMen; var unfinishedMen = taskInfo.unfinishedMen; for (var j = 0; j < finishedMen.length; j++) { this._add2Statistics(statistics, finishedMen[j], true); } for (var k = 0; k < unfinishedMen.length; k++) { this._add2Statistics(statistics, unfinishedMen[k], false); } } } var totalMan = {'id':0, 'man':'总计', 'finished':0,'unfinished':0,'total':0} for (var l = 0; l < statistics.length; l++) { var item = statistics[l]; totalMan.finished += item.finished; totalMan.unfinished += item.unfinished; totalMan.total += item.total; } statistics.push(totalMan); var reportData = { 'statistics': statistics }; return reportData; }, _add2Statistics: function(statistics, man, finished) { var flag = false; for (var i = 0; i < statistics.length; i++) { if (statistics[i].id === man.ID) { if (finished) { statistics[i].finished += man.Hours; } else { statistics[i].unfinished += man.Hours; } statistics[i].total += man.Hours; flag = true; break; } } if (!flag) { var hours = 0; var unHours = 0; if (finished) { hours = man.Hours; } else { unHours = man.Hours; } statistics.push({ 'id': man.ID, 'man': man.Name, 'finished': hours, 'unfinished': unHours, 'total': man.Hours }); } }, //从任务中读取工时信息 getTaskJobTime: function (vault, task) { //task:{id, label} var typeId = MF.alias.objectType(vault, md.genericTask.typeAlias); var pIdAssignTop = MF.alias.propertyDef(vault, md.genericTask.propDefs.AssignedTo); var pIdMarkedBy = MF.alias.propertyDef(vault, md.genericTask.propDefs.CompletedBy); var pIdTimeHour = MF.alias.propertyDef(vault, md.genericTask.propDefs.JobTime); var objId = task.id; var oObjVer = MFiles.CreateInstance('ObjVer'); oObjVer.SetIDs(typeId, objId, -1); var props = vault.ObjectPropertyOperations.GetProperties(oObjVer, false); if (props.IndexOf(pIdTimeHour) == -1) return undefined; var hours = 0.0; var timeHourTvalue = props.SearchForProperty(pIdTimeHour).Value; if (timeHourTvalue.IsNULL() == false) { hours = timeHourTvalue.Value; } var assignTos = []; var assignToTvalue = props.SearchForProperty(pIdAssignTop).Value; if (assignToTvalue.IsNULL() == false) { var ups = assignToTvalue.GetValueAsLookups(); for (var i = 1; i <= ups.Count; i++) { assignTos.push({ 'ID': ups.Item(i).Item, 'Name': ups.Item(i).DisplayValue ,'Hours': 0}); } } var markedBys = []; var markedByTvalue = props.SearchForProperty(pIdMarkedBy).Value; if (markedByTvalue.IsNULL() == false) { var ups2 = markedByTvalue.GetValueAsLookups(); for (var j = 1; j <= ups2.Count; j++) { markedBys.push({ 'ID': ups2.Item(j).Item, 'Name': ups2.Item(j).DisplayValue, 'Hours': 0 }); } } var len = assignTos.length + markedBys.length; if (len == 0) return undefined; var hour = hours / len; //hour = new Number(hour.toFixed(2)); for (var k = 0; k < assignTos.length; k++) { assignTos[k].Hours = hour; } for (var l = 0; l < markedBys.length; l++) { markedBys[l].Hours = hour; } return { 'finishedMen': markedBys, 'unfinishedMen': assignTos }; } }
var spawn = require('child_process').spawn, assert = require('assert'), config = require('../config/'), port = config.port, rootDir = config.rootDir; describe('server', function () { it('starts', function (done) { var server = spawn('node', [rootDir]); process.on('exit', function () { server.kill(); }); server.stderr.on('data', function (data) { console.log('server can not start'); console.log('make sure port %d is available', port); process.exit(); }); server.stdout.on('data', function (data) { if (/started/.test(data)) { done(); } }); }); require('./units/models'); require('./units/api'); });
(function(){ var Socket; if(typeof window === 'undefined'){ Socket = require('ws'); }else { if (!("WebSocket" in window)){ console.error('Myo.js : Sockets not supported :('); } Socket = WebSocket; } /** * Utils */ var extend = function(){ var result = {}; for(var i in arguments){ var obj = arguments[i]; for(var propName in obj){ if(obj.hasOwnProperty(propName)){ result[propName] = obj[propName]; } } } return result; }; var unique_counter = 0; var getUniqueId = function(){ unique_counter++; return new Date().getTime() + "" + unique_counter; }; var eventTable = { 'pose' : function(myo, data){ if(myo.lastPose != 'rest' && data.pose == 'rest'){ myo.trigger(myo.lastPose, false); myo.trigger('pose', myo.lastPose, false); } myo.trigger(data.pose, true); myo.trigger('pose', data.pose, true); myo.lastPose = data.pose; }, 'rssi' : function(myo, data){ myo.trigger('bluetooth_strength', data.rssi); }, 'orientation' : function(myo, data){ myo._lastQuant = data.orientation; var imu_data = { orientation : { x : data.orientation.x - myo.orientationOffset.x, y : data.orientation.y - myo.orientationOffset.y, z : data.orientation.z - myo.orientationOffset.z, w : data.orientation.w - myo.orientationOffset.w }, accelerometer : { x : data.accelerometer[0], y : data.accelerometer[1], z : data.accelerometer[2] }, gyroscope : { x : data.gyroscope[0], y : data.gyroscope[1], z : data.gyroscope[2] } }; if(!myo.lastIMU) myo.lastIMU = imu_data; myo.trigger('orientation', imu_data.orientation); myo.trigger('accelerometer', imu_data.accelerometer); myo.trigger('gyroscope', imu_data.gyroscope); myo.trigger('imu', imu_data); myo.lastIMU = imu_data; }, 'arm_synced' : function(myo, data){ myo.arm = data.arm; myo.direction = data.x_direction; myo.trigger(data.type, data); }, 'arm_unsynced' : function(myo, data){ myo.arm = undefined; myo.direction = undefined; myo.trigger(data.type, data); }, 'connected' : function(myo, data){ myo.connect_version = data.version.join('.'); myo.isConnected = true; myo.trigger(data.type, data); }, 'disconnected' : function(myo, data){ myo.isConnected = false; myo.trigger(data.type, data); }, 'emg' : function(myo, data){ myo.trigger(data.type, data.emg); } }; var handleMessage = function(msg){ var data = JSON.parse(msg.data)[1]; if(Myo.myos[data.myo] && eventTable[data.type]){ eventTable[data.type](Myo.myos[data.myo], data); } }; /** * Eventy-ness */ var trigger = function(events, eventName, args){ var self = this; // events.map(function(event){ if(event.name == eventName) event.fn.apply(self, args); if(event.name == '*'){ args.unshift(eventName); event.fn.apply(self, args); } }); return this; }; var on = function(events, name, fn){ var id = getUniqueId(); events.push({ id : id, name : name, fn : fn }); return id; }; var off = function(events, name){ events = events.reduce(function(result, event){ if(event.name == name || event.id == name) { return result; } result.push(event); return result; }, []); return events; }; var myoInstance = { isLocked : false, isConnected : false, orientationOffset : {x : 0,y : 0,z : 0,w : 0}, lastIMU : undefined, socket : undefined, arm : undefined, direction : undefined, events : [], trigger : function(eventName){ var args = Array.prototype.slice.apply(arguments).slice(1); trigger.call(this, Myo.events, eventName, args); trigger.call(this, this.events, eventName, args); return this; }, on : function(eventName, fn){ return on(this.events, eventName, fn); }, off : function(eventName){ this.events = off(this.events, eventName); }, timer : function(status, timeout, fn){ if(status){ this.timeout = setTimeout(fn.bind(this), timeout); }else{ clearTimeout(this.timeout); } }, lock : function(){ if(this.isLocked) return true; Myo.socket.send(JSON.stringify(["command", { "command": "lock", "myo": this.id }])); this.isLocked = true; this.trigger('lock'); return this; }, unlock : function(timeout){ var self = this; clearTimeout(this.lockTimeout); if(timeout){ Myo.socket.send(JSON.stringify(["command", { "command": "unlock", "myo": this.id, "type": "hold" }])); this.lockTimeout = setTimeout(function(){ self.lock(); }, timeout); } else { Myo.socket.send(JSON.stringify(["command", { "command": "unlock", "myo": this.id, "type": "timed" }])); } if(!this.isLocked) return this; this.isLocked = false; this.trigger('unlock'); return this; }, zeroOrientation : function(){ this.orientationOffset = this._lastQuant; this.trigger('zero_orientation'); return this; }, setLockingPolicy: function (policy) { policy = policy || "standard"; Myo.socket.send(JSON.stringify(['command',{ "command": "set_locking_policy", "type": policy }])); return this; }, vibrate : function(intensity){ intensity = intensity || 'medium'; Myo.socket.send(JSON.stringify(['command',{ "command": "vibrate", "myo": this.id, "type": intensity }])); return this; }, requestBluetoothStrength : function(){ Myo.socket.send(JSON.stringify(['command',{ "command": "request_rssi", "myo": this.id }])); return this; }, streamEMG : function(enabled){ var type = 'enabled'; if(enabled === false) type = 'disabled'; Myo.socket.send(JSON.stringify(['command',{ "command": "set_stream_emg", "myo": this.id, "type" : type }])); return this; }, }; Myo = { options : { api_version : 3, socket_url : "ws://127.0.0.1:10138/myo/" }, events : [], myos : [], /** * Myo Constructor * @param {number} id * @param {object} options * @return {myo} */ create : function(id, options){ if(!Myo.socket) Myo.initSocket(); if(!id) id = 0; if(typeof id === "object") options = id; options = options || {}; var newMyo = Object.create(myoInstance); newMyo.options = extend(Myo.options, options); newMyo.events = []; newMyo.id = id; Myo.myos[id] = newMyo; return newMyo; }, /** * Event functions */ trigger : function(eventName){ var args = Array.prototype.slice.apply(arguments).slice(1); trigger.call(Myo, Myo.events, eventName, args); return Myo; }, on : function(eventName, fn){ return on(Myo.events, eventName, fn); }, initSocket : function(){ Myo.socket = new Socket(Myo.options.socket_url + Myo.options.api_version); Myo.socket.onmessage = handleMessage; Myo.socket.onerror = function(){ console.error('ERR: Myo.js had an error with the socket. Double check the API version.'); }; } }; if(typeof module !== 'undefined') module.exports = Myo; })();
var debug = require('debug')('snippet-app-api'); module.exports = function (app) { app.get("/snippet", function(req, res) { debug('Getting all snippets...'); var user = req.query.user; debug(user); if (user) { app.db.findSnippetsByUser(user, function(err, snippets) { err ? pong(res, 500, {"result": "Unable to find snippets!"}) : pong(res, 200, snippets) }); } else { app.db.findAllSnippets(function(err, snippets) { err ? pong(res, 500, {"result": "Unable to find snippets!"}) : pong(res, 200, snippets) }); } }); app.get("/snippet/:id", function(req, res) { debug('Getting snippet with id...'); debug(req.params.id); app.db.findSnippetById(req.params.id, function(err, snippet) { err ? pong(res, 500, {"result": "Unable to find snippet!"}) : pong(res, 200, snippet) }); }); app.post("/snippet", function(req, res) { debug('Saving snippet...'); debug(req.body.lang); debug(req.body.file); debug(req.body.code); debug(req.body.user); app.db.saveSnippet(req.body, function (err, result) { err ? pong(res, 500, {"result": "Unable to save snippet!"}) : pong(res, 200, result) }); }); app.put("/snippet/:id", function(req, res) { debug('Updating snippet...'); debug(req.params.id); debug(req.body); app.db.updateSnippet(req.params.id, req.body.code, function (err, result) { err ? pong(res, 500, {"result": "Unable to update snippet!"}) : pong(res, 200, result) }); }); app.delete("/snippet/:id", function(req, res) { debug('Deleting snippet...'); debug(req.params.id); app.db.deleteSnippet(req.params.id, function (err, result) { err ? pong(res, 500, {"result": "Unable to delete snippet!"}) : pong(res, 200, result) }); }); return app; } function pong(res, code, data) { res.writeHead(code, {'Content-Type': 'application/json'}); debug(data); (typeof data === "string") ? res.write(data) : res.write(JSON.stringify(data)); res.end(); }
/*jslint regexp: true, nomen: true, sloppy: true */ /*global require, define, alert, applicationConfig, location, document, window, setTimeout, Countable */ define(['jquery', 'bxslider', 'validation', 'modal'], function ($) { var module = {}; module.initSlider = function () { var promoSlide = document.getElementById('promo-slide'); if (promoSlide) { var slider; if($(window).width() > 768){ slider = $('#promo-slide').bxSlider({ mode: 'vertical', auto: true, speed: 1500, pause: 4000, preloadImages:'visible', preventDefaultSwipeX:true }); }else{ $('body').addClass('slide-mode-h'); slider = $('#promo-slide').bxSlider({ mode: 'horizontal', auto: true, speed: 700, pause: 4000, preloadImages:'visible' }); } $('.slide-content .btn').hover(function(){ slider.stopAuto(); }, function(){ slider.startAuto(); }) } }; module.gmaps = function () { var mapCanvas = document.getElementById('contact-map'); if (mapCanvas) { var myLatlng = new google.maps.LatLng(54.897688, 23.888458), pinImage = WEBFOLDER + '/wp-content/themes/asta-uskaite/content/images/icn-pin-flower.png', mapOptions = { zoom: 18, center: myLatlng, disableDefaultUI: true, scrollwheel: false, mapTypeId: 'custom_style' }, map = new google.maps.Map(mapCanvas, mapOptions); var marker = new google.maps.Marker({ position: new google.maps.LatLng(54.897888, 23.888678), map: map, title: 'Asta Uskaite', icon: pinImage }); var featureOpts = [ { "elementType": "geometry.fill", "stylers": [ { "weight": 7 }, { "visibility": "on" }, { "lightness": 30 }, { "hue": "#ffc300" }, { "saturation": -34 } ] }, { featureType: 'water', stylers: [ { color: '#AFC6CF' } ] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ { "color": "#ffffff" } ] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [ { "color": "#E3E1D9" } ] }, { "featureType": "road.local", "elementType": "geometry.fill", "stylers": [ { "color": "#ffffff" }, { "weight": 8 } ] }, { "featureType": "road.local", "elementType": "geometry.stroke", "stylers": [ { "color": "#E3E1D9" }, { "weight": 1 } ] }, { "featureType": "road.local", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road.arterial", "elementType": "geometry.fill", "stylers": [ { "color": "#ffffff" }, { "weight": 8 } ] }, { "featureType": "road.arterial", "elementType": "geometry.stroke", "stylers": [ { "color": "#E3E1D9" }, { "weight": 1 } ] } ]; var infowindow = new google.maps.InfoWindow({ content: '<div class="infowindow" style="width:220px; height: 80px;"><a class="icon-info-close js-info-close"></a> <strong style="font-size: 16px">Asta Uskaite</strong> <br>Valanciaus g. 12-8, Kaunas, Kaunas <br>Tel.: +370 612 32789</div>' }); var styledMapOptions = { name: 'Custom Style' }; var customMapType = new google.maps.StyledMapType(featureOpts, styledMapOptions); map.mapTypes.set('custom_style', customMapType); //Toggle Form $('.js-contact').on('click', function(e){ e.preventDefault(); $('body').toggleClass('show-map'); infowindow.open(map,marker); $('.js-info-close').on('click', function(){ infowindow.close(); $('body').toggleClass('show-map'); }); }); } }; module.mixedFunctions = function () { var catPage = 1; //Load more $('.js-load-more').on('click', function(){ thisButton = $(this); if (thisButton.hasClass('no-more-items')) { return false; } thisButton.toggleClass('loading'); var catId = $('.accessory-page-data').data('category'); $.ajax({ type: "GET", url: WEBFOLDER + "?p=128", dataType: "html", data: { 'fetchContent' : true, 'catId' : catId, 'catPage' : catPage } }).done(function( html ) { catPage++; if (html == "no result") { thisButton.hide(); } else { $( ".gallery" ).append( html ); } thisButton.toggleClass('loading'); }); }); //Toggle drawer var elDrawer = $('.js-drawer'); if (elDrawer.length > 0) { $('html').on('click touch', function () { if (elDrawer.hasClass('opened')) { elDrawer.removeClass('opened'); } }); $('.js-show-form').on('click touch', function (e) { e.preventDefault(); e.stopPropagation(); elDrawer.toggleClass('opened'); $('.ferror').hide(); $('.fsuccess').hide(); $('.js-contact-form').show(); $(window).scrollTop(0); }); $('.js-drawer-close').on('click touch', function (e) { e.preventDefault(); elDrawer.removeClass('opened'); }); elDrawer.on('click touch', function (e) { e.stopPropagation(); }); } //Main navigation toggle $('.js-nav-toggler').on('click touch', function(e){ e.preventDefault(); $('.page-header').toggleClass('opened'); }); //Toggle gallery navigation on mobile screens $('.js-nav-catalog a.active').on('click touch', function(e){ e.preventDefault(); $('.js-nav-catalog').toggleClass('opened'); }); }; module.validateForms = function () { $('form').each(function () { $(this).validate(); }); //On form submit $('form.wpcf7-form').submit(function() { thisForm = $(this); $('.form-response').children().each(function() { $(this).hide(); }); if (!$(this).valid()) { return false; } var href = $(this).attr('action'); var _wpcf7 = $("input[name='_wpcf7']").val(); var _wpcf7_version = $("input[name='_wpcf7_version']").val(); var _wpcf7_locale = $("input[name='_wpcf7_locale']").val(); var _wpcf7_unit_tag = $("input[name='_wpcf7_unit_tag']").val(); var _wpnonce = $("input[name='_wpnonce']").val(); var _m_fname = $("input[name='m_fname']").val(); var _m_lname = $("input[name='m_lname']").val(); var _m_email = $("input[name='m_email']").val(); var _m_phone = $("input[name='m_phone']").val(); var _m_zinute = $("textarea[name='m_zinute']").val(); var _m_product_url = ''; if ($('#real-product-url').length > 0) { _m_product_url = $("#real-product-url").html(); } $.ajax({ type: "post", url: href, dataType: "html", data: { _wpcf7 : _wpcf7, _wpcf7_version : _wpcf7_version, _wpcf7_locale : _wpcf7_locale, _wpcf7_unit_tag : _wpcf7_unit_tag, _wpnonce : _wpnonce, m_fname : _m_fname, m_lname : _m_lname, m_email : _m_email, m_phone : _m_phone, m_zinute : _m_zinute, m_product_url : _m_product_url } }).done(function( htmlContent ) { if (htmlContent.indexOf("wpcf7-mail-sent-ok") > 0) { $(window).scrollTop(0); $('.js-product-form').fadeOut(); $('.fsuccess').fadeIn(); $('.js-reload').on('click', function(e){ e.preventDefault(); location.reload(); }) } else { $('.ferror').fadeIn(); } thisForm.find("input[type='text']").val(''); thisForm.find("input[type='email']").val(''); thisForm.find("textarea").val(''); }); return false; }); }; module.initModal = function (){ $(document).on('click', '[data-modal]', function (e) { var largeImg = $(this).attr('data-image'); if(largeImg.length > 0){ e.preventDefault(); $(this).openModal({ closeOnBlur: false, templateId: 'image-template' }); } }); }; module.init = function () { module.initSlider(); module.initModal(); module.gmaps(); module.mixedFunctions(); module.validateForms(); }; return module; });
import { fromRef } from '../observable/fromRef'; import { Observable } from 'rxjs/Observable'; import { positionFor, positionAfter } from './utils'; import 'rxjs/add/operator/scan'; import 'rxjs/add/observable/merge'; export function listChanges(ref, events) { const childEvent$ = events.map(event => fromRef(ref, event)); return Observable.merge(...childEvent$) .scan((current, action) => { const { payload, type, prevKey, key } = action; switch (action.type) { case 'child_added': return [...current, action]; case 'child_removed': return current.filter(x => x.payload.key !== payload.key); case 'child_changed': return current.map(x => x.payload.key === key ? action : x); case 'child_moved': const curPos = positionFor(current, payload.key); if (curPos > -1) { const data = current.splice(curPos, 1)[0]; const newPost = positionAfter(current, prevKey); current.splice(newPost, 0, data); return current; } return current; default: return current; } }, []); } //# sourceMappingURL=changes.js.map
import { useEffect, useState } from 'react' import { format, fromUnixTime, formatDistance } from 'date-fns' import { BsTrash } from 'react-icons/bs' import { AiOutlineWarning } from 'react-icons/ai' import ErrorMessages from './ErrorMessages' import Avatar from './Avatar' import Modal from './Modal' import Table from './Table' import Pagination from './Pagination' import Loader from './Loader' import ServerSelector from './admin/ServerSelector' import { useApi, useMutateApi } from '../utils' const query = ` query listPlayerPunishmentRecords($serverId: ID!, $player: UUID!, $type: RecordType!, $limit: Int, $offset: Int) { listPlayerPunishmentRecords(serverId: $serverId, player: $player, type: $type, limit: $limit, offset: $offset) { total records { ... on PlayerMuteRecord { id actor { id name } pastActor { id name } created pastCreated expired createdReason reason acl { delete } } } } }` const PlayerMuteRow = ({ row, dateFormat, serverId, onDeleted }) => { const [open, setOpen] = useState(false) const { load, data, loading, errors } = useMutateApi({ query: `mutation deletePlayerMuteRecord($id: ID!, $serverId: ID!) { deletePlayerMuteRecord(id: $id, serverId: $serverId) { id } }` }) const showConfirmDelete = (e) => { e.preventDefault() setOpen(true) } const handleConfirmDelete = async () => { await load({ id: row.id, serverId: serverId }) } const handleDeleteCancel = () => setOpen(false) useEffect(() => { if (!data) return if (Object.keys(data).some(key => !!data[key].id)) { setOpen(false) onDeleted(data) } }, [data]) return ( <Table.Row> <Table.Cell><p>{row.reason}</p></Table.Cell> <Table.Cell> <div className='flex items-center'> <div className='flex-shrink-0'> <Avatar uuid={row.pastActor.id} height='26' width='26' /> </div> <div className='ml-3'> <p className='whitespace-no-wrap'> {row.pastActor.name} </p> </div> </div> </Table.Cell> <Table.Cell>{format(fromUnixTime(row.pastCreated), dateFormat)}</Table.Cell> <Table.Cell>{row.expired === 0 ? 'Permanent' : formatDistance(fromUnixTime(row.pastCreated), fromUnixTime(row.expired), { includeSeconds: true })}</Table.Cell> <Table.Cell> <div className='flex items-center'> <div className='flex-shrink-0'> <Avatar uuid={row.actor.id} height='26' width='26' /> </div> <div className='ml-3'> <p className='whitespace-no-wrap'> {row.actor.name} </p> </div> </div> </Table.Cell> <Table.Cell>{row.createdReason}</Table.Cell> <Table.Cell>{format(fromUnixTime(row.created), dateFormat)}</Table.Cell> <Table.Cell> <div className='flex items-center space-x-8'> {row.acl.delete && <> <Modal icon={<AiOutlineWarning className='h-6 w-6 text-red-600' aria-hidden='true' />} title='Delete mute record' confirmButton='Delete' open={open} onConfirm={handleConfirmDelete} onCancel={handleDeleteCancel} loading={loading} > <ErrorMessages errors={errors} /> <p className='pb-1'>Are you sure you want to delete this mute record?</p> <p className='pb-1'>This action cannot be undone</p> </Modal> <a href='#' onClick={showConfirmDelete}> <BsTrash className='w-6 h-6' /> </a> </>} </div> </Table.Cell> </Table.Row> ) } export default function PlayerMutes ({ id, color, limit = 10 }) { const [tableState, setTableState] = useState({ type: 'PlayerMuteRecord', activePage: 1, limit, offset: 0, player: id, serverId: null }) const { loading, data, mutate } = useApi({ query: !tableState.serverId ? null : query, variables: tableState }) const handlePageChange = ({ activePage }) => setTableState({ ...tableState, activePage, offset: (activePage - 1) * limit }) if (loading) return <Loader /> const dateFormat = 'yyyy-MM-dd HH:mm:ss' const rows = data?.listPlayerPunishmentRecords?.records || [] const total = data?.listPlayerPunishmentRecords.total || 0 const totalPages = Math.ceil(total / limit) const onDeleted = ({ deletePlayerMuteRecord: { id } }) => { const records = rows.filter(c => c.id !== id) mutate({ ...data, listPlayerPunishmentRecords: { records, total: total - 1 } }, false) } return ( <div> <h1 style={{ borderColor: `${color}` }} className='text-2xl font-bold pb-4 mb-4 border-b border-accent-200 leading-none' > <div className='flex items-center'> <p className='mr-6'>Past Mutes</p> <div className='w-40 inline-block'> <ServerSelector onChange={serverId => setTableState({ ...tableState, serverId })} /> </div> </div> </h1> {data?.listPlayerPunishmentRecords?.total > 0 && ( <Table> <Table.Header> <Table.Row> <Table.HeaderCell>Reason</Table.HeaderCell> <Table.HeaderCell>By</Table.HeaderCell> <Table.HeaderCell>On</Table.HeaderCell> <Table.HeaderCell>Length</Table.HeaderCell> <Table.HeaderCell>Unmuted By</Table.HeaderCell> <Table.HeaderCell>For</Table.HeaderCell> <Table.HeaderCell>At</Table.HeaderCell> <Table.HeaderCell /> </Table.Row> </Table.Header> <Table.Body> {loading ? <Table.Row><Table.Cell colSpan='4'><Loader /></Table.Cell></Table.Row> : rows.map((row, i) => (<PlayerMuteRow row={row} dateFormat={dateFormat} key={i} serverId={tableState.serverId} onDeleted={onDeleted} />))} </Table.Body> <Table.Footer> <Table.Row> <Table.HeaderCell colSpan='8' border={false}> <Pagination totalPages={totalPages} activePage={tableState.activePage} onPageChange={handlePageChange} /> </Table.HeaderCell> </Table.Row> </Table.Footer> </Table> )} {!data?.listPlayerPunishmentRecords?.total && ( <div className='flex items-center'> <div className='bg-black w-full rounded-lg flex flex-col justify-center sm:justify-start items-center sm:items-start sm:flex-row space-x-5 p-8'> None </div> </div> )} </div> ) }
var South = { name: "S", spin: function(direction){ if(direction === "L"){ return Cardinals.E } else { return Cardinals.W } } }, West = {name: "W", spin: function(direction){ if(direction === "L"){ return Cardinals.S } else { return Cardinals.N } } }, East = {name: "E", spin: function(direction){ if(direction === "L"){ return Cardinals.N } else { return Cardinals.S } } }, North = { name: "N", spin: function(direction){ if(direction === "L"){ return Cardinals.W } else { return Cardinals.E } } } var Cardinals = { N: North, E: East, W: West, S: South, isValid: function(cardinal){ return cardinal.name === "N" || cardinal.name === "S" || cardinal.name === "E" || cardinal.name === "W" } } Object.freeze(Cardinals)
trim(string);
import minifier from 'uglify-js' const options = { fromString: true } export default function (contents, callback) { try { let result = minifier.minify(contents, options).code callback(null, result) } catch (err) { callback(err) } }
var express = require('express'); var app = express() , http = require('http') , server = http.createServer(app) app.configure(function() { app.use(express.static(__dirname + '/public')); }); /* app.get('/', function(req, res){ res.render('home.jade'); });*/ //for M-jpeg streaming /* fs = require('fs') if not fs.existsSync('/tmp/stream'){ fs.mkdirSync('/tmp/stream') } var spawn = require('child_process').spawn; var exec = require('child_process').exec, var ls = spawn('ls', ['-lh', '/usr']); app.get('/eyes.mjpeg', function(request, res) { res.writeHead(200, { 'Content-Type': 'multipart/x-mixed-replace; boundary=myboundary', 'Cache-Control': 'no-cache', 'Connection': 'close', 'Pragma': 'no-cache' }); var i = 0; var stop = false; res.connection.on('close', function() { stop = true; }); var send_next = function() { if (stop) return; i = (i+1) % 100; var filename = i + ".jpg"; fs.readFile(__dirname + '/resources/' + filename, function (err, content) { res.write("--myboundary\r\n"); res.write("Content-Type: image/jpeg\r\n"); res.write("Content-Length: " + content.length + "\r\n"); res.write("\r\n"); res.write(content, 'binary'); res.write("\r\n"); setTimeout(send_next, 500); }); }; send_next(); }); */ //video streaming //raspistill -w 320 -h 240 -q 65 -o /tmp/stream/pic.jpg -tl 20 -t 9999999 -th 0:0:0 & //LD_LIBRARY_PATH=./ ./mjpg_streamer -i "input_file.so -f /tmp/stream" -o "output_http.so -w ./www" //for controls & sensors require('coffee-script'); var Robot = require('./server/robot'); var body = new Robot(); var io = require('socket.io').listen(server); io.sockets.on('connection', function (socket) { console.log("Connected"); socket.on('setPseudo', function (data) { socket.set('pseudo', data); }); socket.on('rotation', function (message) { console.log("rotation: " , message); body.rotateHead(message.x,message.y); }); socket.on('message', function (message) { console.log("we got sent this : " , message); if(message.command == "left") { var move = message.value; console.log("rotate left fin to",move); body.rotateLeftFin(move); } if(message.command == "right") { var move = message.value; console.log("rotate right fin to",move); body.rotateRightFin(move); } if(message.command == "caudSeg1") { var move = message.value; console.log("rotate caudal fin segment1 to",move); body.rotateCaudalSeg1(move); } if(message.command == "caudSeg2") { var move = message.value; console.log("rotate caudal fin segment2 to",move); body.rotateCaudalSeg2(move); } if(message.command == "headLight") { var intensity = message.value; console.log("seting light intensity",intensity); body.setLight(intensity); } if(message.command == "turn") { var move = message.value; console.log("turning",move); body.turn(move); } if(message.command == "dive") { var move = message.value; console.log("diving",move); body.dive(move); } //socket.broadcast.emit('message', data); }); }); /* //server broadcast function boom() { io.sockets.emit('message', { 'message' : "fish is sinking !", pseudo : "PirO" } ); } setInterval(boom, 5000); */ server.listen(3000); console.log('Server started on port %d', server.address().port);
var logger = require('winston'); module.exports = { backupNow: function (instanceName, dbNames) { // console.log('Starting directory: ' + process.cwd()); // try { // process.chdir(''); // console.log('New directory: ' + process.cwd()); // } // catch (err) { // console.error('chdir: ' + err); // } var exec = require('child_process').exec; exec(path + 'mongodump -d ' + dbNames, function (error, stdout, stderr) { if (error || stderr) { logger.error(error); logger.error(stderr); } logger.log(stdout); }); }, schedule: function (opts) { } };
let globalTeardown = () => {} if (process.env.BROWSERSTACK) { globalTeardown = () => global.browserStackLocal.killAllProcesses(() => {}) } module.exports = async () => { await globalTeardown() }
/***************************************************************** typeface.js, version 0.15 | typefacejs.neocracy.org Copyright (c) 2008 - 2009, David Chester davidchester@gmx.net Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *****************************************************************/ (function() { var _typeface_js = { faces: {}, loadFace: function(typefaceData) { var familyName = typefaceData.familyName.toLowerCase(); if (!this.faces[familyName]) { this.faces[familyName] = {}; } if (!this.faces[familyName][typefaceData.cssFontWeight]) { this.faces[familyName][typefaceData.cssFontWeight] = {}; } var face = this.faces[familyName][typefaceData.cssFontWeight][typefaceData.cssFontStyle] = typefaceData; //console.log( face ); //console.log( typefaceData.glyphs ); face.loaded = true; }, log: function(message) { if (this.quiet) { return; } message = "typeface.js: " + message; if (this.customLogFn) { this.customLogFn(message); } else if (window.console && window.console.log) { window.console.log(message); } }, pixelsFromPoints: function(face, style, points, dimension) { var pixels = points * parseInt(style.fontSize) * 72 / (face.resolution * 100); if (dimension == 'horizontal' && style.fontStretchPercent) { pixels *= style.fontStretchPercent; } return pixels; }, pointsFromPixels: function(face, style, pixels, dimension) { var points = pixels * face.resolution / (parseInt(style.fontSize) * 72 / 100); if (dimension == 'horizontal' && style.fontStretchPrecent) { points *= style.fontStretchPercent; } return points; }, cssFontWeightMap: { normal: 'normal', bold: 'bold', 400: 'normal', 700: 'bold' }, cssFontStretchMap: { 'ultra-condensed': 0.55, 'extra-condensed': 0.77, 'condensed': 0.85, 'semi-condensed': 0.93, 'normal': 1, 'semi-expanded': 1.07, 'expanded': 1.15, 'extra-expanded': 1.23, 'ultra-expanded': 1.45, 'default': 1 }, fallbackCharacter: '.', configure: function(args) { var configurableOptionNames = [ 'customLogFn', 'customClassNameRegex', 'customTypefaceElementsList', 'quiet', 'verbose', 'disableSelection' ]; for (var i = 0; i < configurableOptionNames.length; i++) { var optionName = configurableOptionNames[i]; if (args[optionName]) { if (optionName == 'customLogFn') { if (typeof args[optionName] != 'function') { throw "customLogFn is not a function"; } else { this.customLogFn = args.customLogFn; } } else { this[optionName] = args[optionName]; } } } }, getTextExtents: function(face, style, text) { var extentX = 0; var extentY = 0; var horizontalAdvance; var textLength = text.length; for (var i = 0; i < textLength; i++) { var glyph = face.glyphs[text.charAt(i)] ? face.glyphs[text.charAt(i)] : face.glyphs[this.fallbackCharacter]; var letterSpacingAdjustment = this.pointsFromPixels(face, style, style.letterSpacing); // if we're on the last character, go with the glyph extent if that's more than the horizontal advance extentX += i + 1 == textLength ? Math.max(glyph.x_max, glyph.ha) : glyph.ha; extentX += letterSpacingAdjustment; horizontalAdvance += glyph.ha + letterSpacingAdjustment; } return { x: extentX, y: extentY, ha: horizontalAdvance }; }, pixelsFromCssAmount: function(cssAmount, defaultValue, element) { var matches = undefined; if (cssAmount == 'normal') { return defaultValue; } else if (matches = cssAmount.match(/([\-\d+\.]+)px/)) { return matches[1]; } else { // thanks to Dean Edwards for this very sneaky way to get IE to convert // relative values to pixel values var pixelAmount; var leftInlineStyle = element.style.left; var leftRuntimeStyle = element.runtimeStyle.left; element.runtimeStyle.left = element.currentStyle.left; if (!cssAmount.match(/\d(px|pt)$/)) { element.style.left = '1em'; } else { element.style.left = cssAmount || 0; } pixelAmount = element.style.pixelLeft; element.style.left = leftInlineStyle; element.runtimeStyle.left = leftRuntimeStyle; return pixelAmount || defaultValue; } }, capitalizeText: function(text) { return text.replace(/(^|\s)[a-z]/g, function(match) { return match.toUpperCase() } ); }, getElementStyle: function(e) { if (window.getComputedStyle) { return window.getComputedStyle(e, ''); } else if (e.currentStyle) { return e.currentStyle; } }, getRenderedText: function(e) { var browserStyle = this.getElementStyle(e.parentNode); var inlineStyleAttribute = e.parentNode.getAttribute('style'); if (inlineStyleAttribute && typeof(inlineStyleAttribute) == 'object') { inlineStyleAttribute = inlineStyleAttribute.cssText; } if (inlineStyleAttribute) { var inlineStyleDeclarations = inlineStyleAttribute.split(/\s*\;\s*/); var inlineStyle = {}; for (var i = 0; i < inlineStyleDeclarations.length; i++) { var declaration = inlineStyleDeclarations[i]; var declarationOperands = declaration.split(/\s*\:\s*/); inlineStyle[declarationOperands[0]] = declarationOperands[1]; } } var style = { color: browserStyle.color, fontFamily: browserStyle.fontFamily.split(/\s*,\s*/)[0].replace(/(^"|^'|'$|"$)/g, '').toLowerCase(), fontSize: this.pixelsFromCssAmount(browserStyle.fontSize, 12, e.parentNode), fontWeight: this.cssFontWeightMap[browserStyle.fontWeight], fontStyle: browserStyle.fontStyle ? browserStyle.fontStyle : 'normal', fontStretchPercent: this.cssFontStretchMap[inlineStyle && inlineStyle['font-stretch'] ? inlineStyle['font-stretch'] : 'default'], textDecoration: browserStyle.textDecoration, lineHeight: this.pixelsFromCssAmount(browserStyle.lineHeight, 'normal', e.parentNode), letterSpacing: this.pixelsFromCssAmount(browserStyle.letterSpacing, 0, e.parentNode), textTransform: browserStyle.textTransform }; var face; if ( this.faces[style.fontFamily] && this.faces[style.fontFamily][style.fontWeight] ) { face = this.faces[style.fontFamily][style.fontWeight][style.fontStyle]; } var text = e.nodeValue; if ( e.previousSibling && e.previousSibling.nodeType == 1 && e.previousSibling.tagName != 'BR' && this.getElementStyle(e.previousSibling).display.match(/inline/) ) { text = text.replace(/^\s+/, ' '); } else { text = text.replace(/^\s+/, ''); } if ( e.nextSibling && e.nextSibling.nodeType == 1 && e.nextSibling.tagName != 'BR' && this.getElementStyle(e.nextSibling).display.match(/inline/) ) { text = text.replace(/\s+$/, ' '); } else { text = text.replace(/\s+$/, ''); } text = text.replace(/\s+/g, ' '); if (style.textTransform && style.textTransform != 'none') { switch (style.textTransform) { case 'capitalize': text = this.capitalizeText(text); break; case 'uppercase': text = text.toUpperCase(); break; case 'lowercase': text = text.toLowerCase(); break; } } if (!face) { var excerptLength = 12; var textExcerpt = text.substring(0, excerptLength); if (text.length > excerptLength) { textExcerpt += '...'; } var fontDescription = style.fontFamily; if (style.fontWeight != 'normal') fontDescription += ' ' + style.fontWeight; if (style.fontStyle != 'normal') fontDescription += ' ' + style.fontStyle; this.log("couldn't find typeface font: " + fontDescription + ' for text "' + textExcerpt + '"'); return; } var words = text.split(/\b(?=\w)/); var containerSpan = document.createElement('span'); containerSpan.className = 'typeface-js-vector-container'; var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { var word = words[i]; var vector = this.renderWord(face, style, word); if (vector) { containerSpan.appendChild(vector.element); if (!this.disableSelection) { var selectableSpan = document.createElement('span'); selectableSpan.className = 'typeface-js-selected-text'; var wordNode = document.createTextNode(word); selectableSpan.appendChild(wordNode); if (this.vectorBackend != 'vml') { selectableSpan.style.marginLeft = -1 * (vector.width + 1) + 'px'; } selectableSpan.targetWidth = vector.width; //selectableSpan.style.lineHeight = 1 + 'px'; if (this.vectorBackend == 'vml') { vector.element.appendChild(selectableSpan); } else { containerSpan.appendChild(selectableSpan); } } } } return containerSpan; }, renderDocument: function(callback) { if (!callback) callback = function(e) { e.style.visibility = 'visible' }; var elements = document.getElementsByTagName('*'); var elementsLength = elements.length; for (var i = 0; i < elements.length; i++) { if (elements[i].className.match(/(^|\s)typeface-js(\s|$)/) || elements[i].tagName.match(/^(H1|H2|H3|H4|H5|H6)$/)) { this.replaceText(elements[i]); if (typeof callback == 'function') { callback(elements[i]); } } } if (this.vectorBackend == 'vml') { // lamely work around IE's quirky leaving off final dynamic shapes var dummyShape = document.createElement('v:shape'); dummyShape.style.display = 'none'; document.body.appendChild(dummyShape); } }, replaceText: function(e) { var childNodes = []; var childNodesLength = e.childNodes.length; for (var i = 0; i < childNodesLength; i++) { this.replaceText(e.childNodes[i]); } if (e.nodeType == 3 && e.nodeValue.match(/\S/)) { var parentNode = e.parentNode; if (parentNode.className == 'typeface-js-selected-text') { return; } var renderedText = this.getRenderedText(e); if ( parentNode.tagName == 'A' && this.vectorBackend == 'vml' && this.getElementStyle(parentNode).display == 'inline' ) { // something of a hack, use inline-block to get IE to accept clicks in whitespace regions parentNode.style.display = 'inline-block'; parentNode.style.cursor = 'pointer'; } if (this.getElementStyle(parentNode).display == 'inline') { parentNode.style.display = 'inline-block'; } if (renderedText) { if (parentNode.replaceChild) { parentNode.replaceChild(renderedText, e); } else { parentNode.insertBefore(renderedText, e); parentNode.removeChild(e); } if (this.vectorBackend == 'vml') { renderedText.innerHTML = renderedText.innerHTML; } var childNodesLength = renderedText.childNodes.length for (var i; i < childNodesLength; i++) { // do our best to line up selectable text with rendered text var e = renderedText.childNodes[i]; if (e.hasChildNodes() && !e.targetWidth) { e = e.childNodes[0]; } if (e && e.targetWidth) { var letterSpacingCount = e.innerHTML.length; var wordSpaceDelta = e.targetWidth - e.offsetWidth; var letterSpacing = wordSpaceDelta / (letterSpacingCount || 1); if (this.vectorBackend == 'vml') { letterSpacing = Math.ceil(letterSpacing); } e.style.letterSpacing = letterSpacing + 'px'; e.style.width = e.targetWidth + 'px'; } } } } }, applyElementVerticalMetrics: function(face, style, e) { if (style.lineHeight == 'normal') { style.lineHeight = this.pixelsFromPoints(face, style, face.lineHeight); } var cssLineHeightAdjustment = style.lineHeight - this.pixelsFromPoints(face, style, face.lineHeight); e.style.marginTop = Math.round( cssLineHeightAdjustment / 2 ) + 'px'; e.style.marginBottom = Math.round( cssLineHeightAdjustment / 2) + 'px'; }, vectorBackends: { canvas: { _initializeSurface: function(face, style, text) { var extents = this.getTextExtents(face, style, text); var canvas = document.createElement('canvas'); if (this.disableSelection) { canvas.innerHTML = text; } canvas.height = Math.round(this.pixelsFromPoints(face, style, face.lineHeight)); canvas.width = Math.round(this.pixelsFromPoints(face, style, extents.x, 'horizontal')); this.applyElementVerticalMetrics(face, style, canvas); if (extents.x > extents.ha) canvas.style.marginRight = Math.round(this.pixelsFromPoints(face, style, extents.x - extents.ha, 'horizontal')) + 'px'; var ctx = canvas.getContext('2d'); var pointScale = this.pixelsFromPoints(face, style, 1); ctx.scale(pointScale * style.fontStretchPercent, -1 * pointScale); ctx.translate(0, -1 * face.ascender); ctx.fillStyle = style.color; return { context: ctx, canvas: canvas }; }, _renderGlyph: function(ctx, face, char, style) { var glyph = face.glyphs[char]; if (!glyph) { //this.log.error("glyph not defined: " + char); return this.renderGlyph(ctx, face, this.fallbackCharacter, style); } if (glyph.o) { var outline; if (glyph.cached_outline) { outline = glyph.cached_outline; } else { outline = glyph.o.split(' '); glyph.cached_outline = outline; } var outlineLength = outline.length; for (var i = 0; i < outlineLength; ) { var action = outline[i++]; switch(action) { case 'm': ctx.moveTo(outline[i++], outline[i++]); break; case 'l': ctx.lineTo(outline[i++], outline[i++]); break; case 'q': var cpx = outline[i++]; var cpy = outline[i++]; ctx.quadraticCurveTo(outline[i++], outline[i++], cpx, cpy); break; case 'b': var x = outline[i++]; var y = outline[i++]; ctx.bezierCurveTo(outline[i++], outline[i++], outline[i++], outline[i++], x, y); break; } } } if (glyph.ha) { var letterSpacingPoints = style.letterSpacing && style.letterSpacing != 'normal' ? this.pointsFromPixels(face, style, style.letterSpacing) : 0; ctx.translate(glyph.ha + letterSpacingPoints, 0); } }, _renderWord: function(face, style, text) { var surface = this.initializeSurface(face, style, text); var ctx = surface.context; var canvas = surface.canvas; ctx.beginPath(); ctx.save(); var chars = text.split(''); var charsLength = chars.length; for (var i = 0; i < charsLength; i++) { this.renderGlyph(ctx, face, chars[i], style); } ctx.fill(); if (style.textDecoration == 'underline') { ctx.beginPath(); ctx.moveTo(0, face.underlinePosition); ctx.restore(); ctx.lineTo(0, face.underlinePosition); ctx.strokeStyle = style.color; ctx.lineWidth = face.underlineThickness; ctx.stroke(); } return { element: ctx.canvas, width: Math.floor(canvas.width) }; } }, vml: { _initializeSurface: function(face, style, text) { var shape = document.createElement('v:shape'); var extents = this.getTextExtents(face, style, text); shape.style.width = shape.style.height = style.fontSize + 'px'; shape.style.marginLeft = '-1px'; // this seems suspect... if (extents.x > extents.ha) { shape.style.marginRight = this.pixelsFromPoints(face, style, extents.x - extents.ha, 'horizontal') + 'px'; } this.applyElementVerticalMetrics(face, style, shape); var resolutionScale = face.resolution * 100 / 72; shape.coordsize = (resolutionScale / style.fontStretchPercent) + "," + resolutionScale; shape.coordorigin = '0,' + face.ascender; shape.style.flip = 'y'; shape.fillColor = style.color; shape.stroked = false; shape.path = 'hh m 0,' + face.ascender + ' l 0,' + face.descender + ' '; return shape; }, _renderGlyph: function(shape, face, char, offsetX, style, vmlSegments) { var glyph = face.glyphs[char]; if (!glyph) { this.log("glyph not defined: " + char); this.renderGlyph(shape, face, this.fallbackCharacter, offsetX, style); return; } vmlSegments.push('m'); if (glyph.o) { var outline, outlineLength; if (glyph.cached_outline) { outline = glyph.cached_outline; outlineLength = outline.length; } else { outline = glyph.o.split(' '); outlineLength = outline.length; for (var i = 0; i < outlineLength;) { switch(outline[i++]) { case 'q': outline[i] = Math.round(outline[i++]); outline[i] = Math.round(outline[i++]); case 'm': case 'l': outline[i] = Math.round(outline[i++]); outline[i] = Math.round(outline[i++]); break; } } glyph.cached_outline = outline; } var prevX, prevY; for (var i = 0; i < outlineLength;) { var action = outline[i++]; var x = Math.round(outline[i++]) + offsetX; var y = Math.round(outline[i++]); switch(action) { case 'm': vmlSegments.push('xm ', x, ',', y); break; case 'l': vmlSegments.push('l ', x, ',', y); break; case 'q': var cpx = outline[i++] + offsetX; var cpy = outline[i++]; var cp1x = Math.round(prevX + 2.0 / 3.0 * (cpx - prevX)); var cp1y = Math.round(prevY + 2.0 / 3.0 * (cpy - prevY)); var cp2x = Math.round(cp1x + (x - prevX) / 3.0); var cp2y = Math.round(cp1y + (y - prevY) / 3.0); vmlSegments.push('c ', cp1x, ',', cp1y, ',', cp2x, ',', cp2y, ',', x, ',', y); break; case 'b': var cp1x = Math.round(outline[i++]) + offsetX; var cp1y = outline[i++]; var cp2x = Math.round(outline[i++]) + offsetX; var cp2y = outline[i++]; vmlSegments.push('c ', cp1x, ',', cp1y, ',', cp2x, ',', cp2y, ',', x, ',', y); break; } prevX = x; prevY = y; } } vmlSegments.push('x e'); return vmlSegments; }, _renderWord: function(face, style, text) { var offsetX = 0; var shape = this.initializeSurface(face, style, text); var letterSpacingPoints = style.letterSpacing && style.letterSpacing != 'normal' ? this.pointsFromPixels(face, style, style.letterSpacing) : 0; letterSpacingPoints = Math.round(letterSpacingPoints); var chars = text.split(''); var vmlSegments = []; for (var i = 0; i < chars.length; i++) { var char = chars[i]; vmlSegments = this.renderGlyph(shape, face, char, offsetX, style, vmlSegments); offsetX += face.glyphs[char].ha + letterSpacingPoints ; } if (style.textDecoration == 'underline') { var posY = face.underlinePosition - (face.underlineThickness / 2); vmlSegments.push('xm ', 0, ',', posY); vmlSegments.push('l ', offsetX, ',', posY); vmlSegments.push('l ', offsetX, ',', posY + face.underlineThickness); vmlSegments.push('l ', 0, ',', posY + face.underlineThickness); vmlSegments.push('l ', 0, ',', posY); vmlSegments.push('x e'); } // make sure to preserve trailing whitespace shape.path += vmlSegments.join('') + 'm ' + offsetX + ' 0 l ' + offsetX + ' ' + face.ascender; return { element: shape, width: Math.floor(this.pixelsFromPoints(face, style, offsetX, 'horizontal')) }; } } }, setVectorBackend: function(backend) { this.vectorBackend = backend; var backendFunctions = ['renderWord', 'initializeSurface', 'renderGlyph']; for (var i = 0; i < backendFunctions.length; i++) { var backendFunction = backendFunctions[i]; this[backendFunction] = this.vectorBackends[backend]['_' + backendFunction]; } }, initialize: function() { // quit if this function has already been called if (arguments.callee.done) return; // flag this function so we don't do the same thing twice arguments.callee.done = true; // kill the timer if (window._typefaceTimer) clearInterval(_typefaceTimer); this.renderDocument( function(e) { e.style.visibility = 'visible' } ); } }; // IE won't accept real selectors... var typefaceSelectors = ['.typeface-js', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']; if (document.createStyleSheet) { var styleSheet = document.createStyleSheet(); for (var i = 0; i < typefaceSelectors.length; i++) { var selector = typefaceSelectors[i]; styleSheet.addRule(selector, 'visibility: hidden'); } styleSheet.addRule( '.typeface-js-selected-text', '-ms-filter: \ "Chroma(color=black) \ progid:DXImageTransform.Microsoft.MaskFilter(Color=white) \ progid:DXImageTransform.Microsoft.MaskFilter(Color=blue) \ alpha(opacity=30)" !important; \ color: black; \ font-family: Modern; \ position: absolute; \ white-space: pre; \ filter: alpha(opacity=0) !important;' ); styleSheet.addRule( '.typeface-js-vector-container', 'position: relative' ); } else if (document.styleSheets) { if (!document.styleSheets.length) { (function() { // create a stylesheet if we need to var styleSheet = document.createElement('style'); styleSheet.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(styleSheet); })() } var styleSheet = document.styleSheets[0]; document.styleSheets[0].insertRule(typefaceSelectors.join(',') + ' { visibility: hidden; }', styleSheet.cssRules.length); document.styleSheets[0].insertRule( '.typeface-js-selected-text { \ color: rgba(128, 128, 128, 0); \ opacity: 0.30; \ position: absolute; \ font-family: Arial, sans-serif; \ white-space: pre \ }', styleSheet.cssRules.length ); try { // set selection style for Mozilla / Firefox document.styleSheets[0].insertRule( '.typeface-js-selected-text::-moz-selection { background: blue; }', styleSheet.cssRules.length ); } catch(e) {}; try { // set styles for browsers with CSS3 selectors (Safari, Chrome) document.styleSheets[0].insertRule( '.typeface-js-selected-text::selection { background: blue; }', styleSheet.cssRules.length ); } catch(e) {}; // most unfortunately, sniff for WebKit's quirky selection behavior if (/WebKit/i.test(navigator.userAgent)) { document.styleSheets[0].insertRule( '.typeface-js-vector-container { position: relative }', styleSheet.cssRules.length ); } } var backend = window.CanvasRenderingContext2D || document.createElement('canvas').getContext ? 'canvas' : !!(window.attachEvent && !window.opera) ? 'vml' : null; if (backend == 'vml') { document.namespaces.add("v","urn:schemas-microsoft-com:vml","#default#VML"); var styleSheet = document.createStyleSheet(); styleSheet.addRule('v\\:shape', "display: inline-block;"); } _typeface_js.setVectorBackend(backend); window._typeface_js = _typeface_js; if (/WebKit/i.test(navigator.userAgent)) { var _typefaceTimer = setInterval(function() { if (/loaded|complete/.test(document.readyState)) { _typeface_js.initialize(); } }, 10); } if (document.addEventListener) { window.addEventListener('DOMContentLoaded', function() { _typeface_js.initialize() }, false); } /*@cc_on @*/ /*@if (@_win32) document.write("<script id=__ie_onload_typeface defer src=//:><\/script>"); var script = document.getElementById("__ie_onload_typeface"); script.onreadystatechange = function() { if (this.readyState == "complete") { _typeface_js.initialize(); } }; /*@end @*/ try { console.log('initializing typeface.js') } catch(e) {}; })();
//>>built define("dojo/cldr/nls/fi/number",{"group":" ","percentSign":"%","exponential":"E","scientificFormat":"#E0","percentFormat":"#,##0 %","list":";","infinity":"∞","patternDigit":"#","minusSign":"-","decimal":",","nan":"epäluku","nativeZeroDigit":"0","perMille":"‰","decimalFormat":"#,##0.###","currencyFormat":"#,##0.00 ¤","plusSign":"+"});
var Phaser = require('phaser'); var colors = require('./colors'); /** * Paddle class. * @class * @param {object} game * @param {number} x * @param {number} y * @param {boolean} isGhost */ Paddle = function (game, x, y, isGhost) { Phaser.Sprite.call(this, game, x, y, 'paddle'); this.game = game; this.game.physics.arcade.enable(this); this.scale.x = 0.4; this.scale.y = 7; this.anchor.setTo(0.5, 0.5); this.body.bounce.setTo(1, 1); this.body.immovable = true; this.body.collideWorldBounds = true; this.alpha = Paddle.defaultAlpha; this.tint = colors.themes[this.game.theme].paddle; this.isGhost = isGhost || false; this.alive = true; }; Paddle.prototype = Object.create(Phaser.Sprite.prototype); Paddle.prototype.constructor = Paddle; Paddle.defaultAlpha = 0.6; /** * Phaser update. * @public */ Paddle.prototype.update = function () { if (this.game.pongPaused) { this.body.velocity.set(0); } // If this is the master paddle, move it to the closest ball. if (this.closestBall && !this.isGhost) { var yDiff = 0; if (this.y > this.closestBall.dest.y) { yDiff = this.y - this.closestBall.dest.y; } else { yDiff = this.closestBall.dest.y - this.y; } if (yDiff < 30) { this.body.velocity.set(0); } else { this.game.physics.arcade.moveToXY( this, Math.round(this.x), Math.round(this.closestBall.dest.y), 100, this.closestBall.arrival * 1000 ); } } this.tint = colors.hexStringToInt(colors.themes[this.game.theme].paddle); // Fade out ghost paddles. if (this.isGhost) { // If we're paused, remove them immediately. if (this.game.pongPaused) { this.alpha = 0; } this.alpha -= 0.1; if (this.alpha < 0) { this.alpha = 0; this.alive = false; } return; } this.alpha -= 0.05; if (this.alpha < 0.6) { this.alpha = 0.6; } this._keyboard(); Phaser.Sprite.prototype.update.call(this); }; /** * Handle keyboard. * @private */ Paddle.prototype._keyboard = function () { if (this.game.pongPaused || !this.game.playMode) { return; } var yVelocity = 0; if (this.game.downKey.isDown) { yVelocity = 300; } if (this.game.upKey.isDown) { yVelocity = -300; } this.body.velocity.y = yVelocity; }; module.exports = Paddle;
define(['handlebars'], function(handlebars){ var template = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, stack2, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div class=\"post\">\n <div class=\"post-title\">\n <a href=\"#\">"; if (stack1 = helpers.title) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.title; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "</a> / "; if (stack1 = helpers.subreddit) { stack1 = stack1.call(depth0, {hash:{},data:data}); } else { stack1 = depth0.subreddit; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } buffer += escapeExpression(stack1) + "\n </div>\n <div class=\"post-time\">\n " + escapeExpression(((stack1 = ((stack1 = depth0.schedule),stack1 == null || stack1 === false ? stack1 : stack1.date)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " " + escapeExpression(((stack1 = ((stack1 = depth0.schedule),stack1 == null || stack1 === false ? stack1 : stack1.time)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </div>\n <div class=\"post-content\">"; if (stack2 = helpers.urlOrDetails) { stack2 = stack2.call(depth0, {hash:{},data:data}); } else { stack2 = depth0.urlOrDetails; stack2 = typeof stack2 === functionType ? stack2.apply(depth0) : stack2; } buffer += escapeExpression(stack2) + "</div>\n</div>\n"; return buffer; }) return template });
'use strict'; var extend = require('extend'); var format = require('util').format; var request = require('./request'); var util = require('./util'); var debug = require('debug')('lego-client:info'); /* info(args, config) * args * name: the package name * version: the package version * config: see client.config */ module.exports = function* info(args, config) { args = extend({}, require('./config')(), config, args); // 1. 获得所有的包信息 var req = {}; req.url = format('%s/repository/%s/', args.registry, args.name); req.method = 'GET'; req.json = true; debug('get package info %s@%s~%s url %s', args.name, args.version || '-', args.tag || '-', req.url); var res = yield* request(req); util.errorHandle(req, res); // 2. 获得目标版本 var targetVersion = getTargetVersion(res.body, args); // 3. 通过目标版本获得包信息 var body = res.body.packages[targetVersion]; if (!body) { var err = new Error('no matched package ' + args.name + (args.version ? ' ~ ' + args.version : '')); err.statusCode = res.statusCode; throw err; } debug('response body %j', body); // 4. 返回结果 return body; }; /** * 根据算法,获得指定版本 * http://stackoverflow.com/questions/22343224/difference-between-tilde-and-caret-in-package-json * http://fredkschott.com/post/2014/02/npm-no-longer-defaults-to-tildes/ */ function getTargetVersion(body, args) { var versionArr = Object.keys(body.packages), argsVersion = args.version || 'stable'; argsVersion = argsVersion.trim(); // 如果package.json中配置了db:*,则返回最新版本 if(argsVersion == '*'){ // 获取最新 } // db 或 db@stable: lego install db或者lego install db@stable else if(argsVersion.indexOf('.') < 0){ versionArr = versionArr.filter(function(cur) { return body.packages[cur].tag === argsVersion; }); } // 如果package.json中配置了db:~1.2.3,则返回 1.2.*<= version < 1.3.* // 但有特例,以0开始的版本,db:~0.1.2 和 db:^0.1.2,都返回 0.1.x <= version < 0.2.* else if (argsVersion.indexOf('~') === 0 || argsVersion.indexOf('^0') === 0) { // 只要比较第一位和第二位数字相同即可 var targetArr = getArrFromVersion(argsVersion.substr(1)); if (targetArr.length > 1) { versionArr = versionArr.filter(function(cur) { var curArr = getArrFromVersion(cur); return curArr.length > 1 && curArr[0] === targetArr[0] && curArr[1] === targetArr[1]; }); } } // 如果package.json中配置了db:^1.2.3,则返回 1.2.*<= version < 2.*.* // 但有特例,以0开始的版本,db:~0.1.2 和 db:^0.1.2,都返回 0.1.x <= version < 0.2.* else if (argsVersion.indexOf('^') === 0) { // 只要比较第一位和第二位数字相同即可 var targetArr = getArrFromVersion(argsVersion.substr(1)); if (targetArr.length > 1) { versionArr = versionArr.filter(function(cur) { var curArr = getArrFromVersion(cur); return curArr.length > 1 && curArr[0] === targetArr[0]; }); } } // 其他情况只考虑指定版本,例如 lego install db@1.2.3或者在package.json中定义了db:1.2.3 else { versionArr = versionArr.filter(function(cur) { return cur === argsVersion; }); } // 排序使版本号从大到小 versionArr.sort(function(a, b) { var aArr = a.split('.'), bArr = b.split('.'); for (var i = 0; i < 3; i++) { var na = parseInt(aArr[i], 10), nb = parseInt(bArr[i], 10); if (na > nb) { return -1; } else if (na < nb) { return 1; } } return 0; }); // 返回排序之后的最大的版本号 return versionArr[0]; } function getArrFromVersion(version) { return version.split('.'); }