code
stringlengths
2
1.05M
/** * Provides Firebolt's templating engine. * * @module tmpl * @requires core * @requires string/extras */ 'use strict'; //#region VARS var rgxTmpl = /([\r\n'\\])(?=(?:(?!%>)[\s\S])*(?:<%|$))|<%(=|-)([\s\S]*?)%>|(<%)|%>/g; //#endregion VARS function tmplFormat(s, p1, p2, p3, p4) { if (p1) { // Escape newline characters, single quotes, and backslashes in the HTML context return ( p1 === '\n' ? '\\n' : p1 === '\r' ? '' : '\\' + p1 ); } if (p2) { // Output escaped (<%= %>) or plain (<%- %>) text return '\'+__t(' + p3 + ')' + (p2 === '=' ? '.escapeHTML()' : '') + '+\''; } if (p4) { // JS evaluation start tag (<%) return '\';'; } // JS evaluation end tag (%>) return '__s+=\''; } /** * @summary Creates a compiled template function. * * @function Firebolt.tmpl * @param {String|HTMLScriptElement} template - The template string or `<script>` element * that contains the template string. * @param {String} [dataIdentifier='o'] - An identifer to be used in the template to access * the data passed into the compiled template function. * @returns {Function} The compiled template function. * * @description * The compiled function that this function returns can execute JavaScript in "evaluate" * delimiters (`<% %>`), interpolate data properties in "interpolate" delimiters (`<%- %>`), * and HTML-escape interpolated data properties in "escape" delimiters (`<%= %>`). Data * passed into the compiled function can be accessed by the special variable `o` or an * identifier specified as the second parameter to the `$.tmpl()` function. * * When compiling the template, you can either provide the template string directly * (usually either defined in your JavaScript or retrieved with an AJAX call) or * provide a `<script>` element that contains the template string. An example * template `<script>` could be the following: * * ```html * <script id="tmpl-example" type="text/x-fb-tmpl"> * <h3><%= o.title %></h3> * <p> * Released under the * <a href="<%= o.license.url %>"><%= o.license.name %></a>. * </p> * <h4>Features</h4> * <ul> * <% for (var i = 0; i <o.features.length; i++) { %> * <li><%= o.features[i] %></li> * <% } %> * </ul> * </script> * ``` * * Note that the script element's `type` must be something like `text/x-*` otherwise * the script will be evaluated by the browser like any other script element. * * To compile this particular template: * * ```js * var exampleTemplate = $.tmpl($$('tmpl-example')); * ``` * * Then to render the template with some data: * * ```js * var data = { * "title": "My Cool Project", * "license": { * "name": "MIT", * "url": "http://www.opensource.org/licenses/MIT" * }, * "features": [ * "New", * "Powerful", * "Easy to use" * ] * }; * * var rendered = exampleTemplate(data); * ``` * * The `rendered` variable would then be the following string: * * ```html * <h3>My Cool Project</h3> * <p> * Released under the * <a href="http://www.opensource.org/licenses/MIT">MIT</a>. * </p> * <h4>Features</h4> * <ul> * <li>New</li> * <li>Powerful</li> * <li>Easy to use</li> * </ul> * ``` * * You can then do anything you want with the rendered string, such as add it to the page: * * ```js * $1('.project-container').innerHTML = rendered; * ``` * * @example <caption>Access data with a custom variable name</caption> * var compiled = $.tmpl('<strong><%= data.value %></strong>', 'data'); * compiled({value: 'Hello!'}); * // -> '<strong>Hello!</strong>' * * @example <caption>Interpolate data without HTML-escaping it</caption> * var compiled = $.tmpl('<li><%- data.value %></li>', 'data'); * compiled({value: '<span class="my-span">Some info<span>'}); * // -> '<li><span class="my-span">Some info<span></li>' * * @example <caption>HTML-escape interpolated data</caption> * var compiled = $.tmpl('<li><%= data.value %></li>', 'data'); * compiled({value: '<span class="my-span">Some info<span>'}); * // -> '<li>&lt;span class=&quot;my-span&quot;&gt;Some info&lt;span&gt;</li>' */ Firebolt.tmpl = function(value, dataIdentifier) { /* jslint evil: true */ return Function( dataIdentifier || 'o', 'function __t(v){return v==null?\'\':\'\'+v}' + 'var __s=\'' + (typeofString(value) ? value : value.text).replace(rgxTmpl, tmplFormat) + '\';return __s' ); };
/* globals Vivus */ define('vivus', [], function() { 'use strict'; if (typeof FastBoot === 'undefined') { return { default: Vivus }; } return { default: undefined }; });
<!-- page js start here --> function SlimPageMain() { this.PAGE = 1;//当前第几页 | page now this.PAGE_SIZE = 20;//每页数据条数 | pagesize this.PAGES = 1;//总页数 | how many pages this.Params = new Object();//其他参数 | other params in get url this.Url = "";//链接地址 this.getPage = function(){ return this.PAGE; }; this.setPage = function(page){ this.PAGE = page; }; this.getPageSize = function(){ return this.PAGE_SIZE; }; this.setPageSize = function(pagesize){ this.PAGE_SIZE = pagesize; }; this.getPages = function(){ return this.PAGES; }; this.setPages = function(pages){ this.PAGES = pages; }; this.getParams = function(){ return this.Params; }; this.setParams = function(paramobj){ this.Params = paramobj; }; this.getUrl = function(){ return this.Url; }; this.setUrl = function(url){ this.Url = url; }; /** * [init 初始化] * @param {[type]} dom [需要添加分页区域的元素] | where u wannt to append a page area * @param {[type]} pagenow * @param {[type]} pagesize * @param {[type]} pages | how many pages here */ this.init = function(dom,pagenow,pagesize,pages){ $("#slimpage").remove(); $(dom).append("<ul class='pagination' id='slimpage'></ul>"); this.PAGE = pagenow; this.PAGE_SIZE = pagesize; this.PAGES = pages; var pathName=window.document.location.href; //去除参数以外的URL this.Url = pathName.substring(0,pathName.substr(1).lastIndexOf('?')+1).length > 0 ? pathName.substring(0,pathName.substr(1).lastIndexOf('?')+1):pathName ; return this; }; /** json对象转url get参数形式 | convert json obj to params string in get url */ this.json2paramStr = function(jsonObj){ var str = ''; var i=0; for ( var prm in jsonObj) { if(i==0){ str += "?"; }else{ str += "&"; } str += prm + '=' + jsonObj[prm]; i++; } return str; }; /** 把当前的params转成url get参数形式 | convert the Params in SlimPage to str for get url */ this.getParamStr = function(){ return this.json2paramStr(this.Params); }; /** 显示分页html | show the page html */ this.showPage = function(){ if($("#slimpage").length == 0){ alert("请添加#slimpage元素"); return false; } $("#slimpage").addClass("pagination"); var page = this.PAGE; var pages = this.PAGES; var html=""; var i=0; var p=0; if(page > 1){ html += "<li><a class='jump' p='"+(page-1)+"'><<</a></li>"; } html += "<li><a class='jump p1' p='"+1+"'>1</a></li>"; for(i=1;i<5&&i<pages;i++){ p=(i+1); html += "<li><a class='jump p"+p+"' p='"+p+"'>"+p+"</a></li>"; } if(page-5 > 5){ html+="<li><a>...</a></li>"; } $("#slimpage").append(html); html=""; for(i=page-5;i<=page+5;i++){ p=i; if($(".p"+i).length==0 && p<=pages && p>0){ html += "<li><a class='jump p"+p+"' p='"+p+"'>"+p+"</a></li>"; } } if(page+5 < pages-5){ html+="<li><a>...</a></li>"; } $("#slimpage").append(html); html=""; for(i=pages-4;i<=pages;i++){ p=i; if($(".p"+i).length==0 && p>=1){ html += "<li><a class='jump p"+p+"' p='"+p+"'>"+p+"</a></li>"; } } if(page < pages){ html += "<li><a class='jump' p='"+(page+1)+"'>>></a></li>"; } $("#slimpage").append(html); $(".p"+page).parent().addClass("active"); $("#slimpage .jump").click(function(){ SlimPage.Params.page = $(this).attr("p"); window.location.href = SlimPage.Url + SlimPage.getParamStr(); }); }; } var SlimPage = new SlimPageMain(); <!-- end page js -->
module.exports = function ({ $lookup }) { return { object: function () { return function ($buffer, $start) { let $_, $i = [] let object = { nudge: 0, array: null, sentry: 0 } object.nudge = $buffer[$start++] $_ = $buffer.indexOf(Buffer.from([ 13, 10 ]), $start) $_ = ~$_ ? $_ : $start object.array = [ $buffer.slice($start, $_) ] $start = $_ + 2 object.sentry = $buffer[$start++] return object } } () } }
(function () { angular.module('estagiarios').controller('cadastros.views.pessoas', function ($scope) { var vm = this; vm.nome = "Cadastro de Pessoas"; } ); })();
var chai = require('chai'); var should = chai.should(); var eventPlace = require('../../../lib/model/response/eventPlace'); describe('eventPlace model test', function () { var id = 'id'; var name = 'name'; var breadcrumbs = ['breadcrumbs']; var openingTimes = [{from: 'openingTimes'}]; it('should create model', function (done) { var placeModel = new eventPlace.EventPlace( id, name, breadcrumbs, openingTimes ); should.exist(placeModel); placeModel.id.should.be.equal(id); placeModel.name.should.be.equal(name); placeModel.breadcrumbs.should.be.equal(breadcrumbs); placeModel.openingTimes.should.be.equal(openingTimes); done(); }); it('should create model by builder', function (done) { var placeModel = new eventPlace.EventPlaceBuilder() .withId(id) .withName(name) .withBreadcrumbs(breadcrumbs) .withOpeningTimes(openingTimes) .build(); should.exist(placeModel); placeModel.id.should.be.equal(id); placeModel.name.should.be.equal(name); placeModel.breadcrumbs.should.be.equal(breadcrumbs); placeModel.openingTimes.should.be.equal(openingTimes); done(); }); });
/* eslint-env jest */ /* global jasmine */ import { join } from 'path' import { buildTS } from 'next-test-utils' jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2 const appDir = join(__dirname, '../') describe('Custom Server TypeScript', () => { it('should build server.ts correctly', async () => { await buildTS([], appDir) }) })
//Make a reducer file for each state in the store (which is like the main database for redux) //Every reducer runs every time there is an action, whether something actually changes in state is up to //programmer. //Reducer does the editing of the state, which is just a slice of data of the entire store. //Everytime an action is dispatched, every single reducer will run. We control which reducers do something with the action types export function registerReducer(state={ errorMsgs: "" }, action ) { switch (action.type) { case "ERROR_MSGS": { console.log("ERROR PAYLOAD", action.payload) return { ...state, errorMsgs: action.payload } } // case "GET_USER": { // return { ...state, user: } // } // case "GET_USER_ERROR": { // return {...state, error: payload.err } // } default: { return state; } } return state; } // export function allData(state = {}, action){ // return state; // }
/** * Created by 斌 on 2017/4/6. */ const router = require('express').Router(); router.get('/', (req, res) => { res.render(`newsletter`, {csrfToken: res.locals._csrfToken}); }); module.exports = router;
var FC = (function(){ var isLoading = false; var isEvsEndReached = 0; var evStart = 0; var evLim = 0; var isRendering = 0; var _getContent = function(params, callback){ $.ajax({ url: params.url, data: params.data, dataType: "JSON", success: function(res){ if(typeof callback === "function"){ callback(res); } } }); }; var _bindEvents = function(){ $(window).on('scroll', function() { // console.log(isRendering); // console.log(isEvsEndReached); if(($(this)[0].innerHeight + $(this)[0].scrollY) >= document.body.offsetHeight && isRendering == 0 && isEvsEndReached == 0) { // alert("s"); isRendering = 1; evStart += 4; var params = { url: base_url + "widgets/contents/get", data: { type: "events", d: $("#mapp-calendar").val(), start: evStart } }; _getContent(params, function(data){ if(Object.keys(data).length > 0){ var dom = _buildDom(data); $("#events-list").append(dom); isRendering = 0; } else { isEvsEndReached = 1; } }); } }); } var _buildEventDom = function(data){ var params = { url : base_url + "events/get_event", data: { id: data.id } } _getContent(params, function(res){ var html = ""; html += "<div style='display: table;'>"; html += '<div class="col-lg-2">'; html += ' What:'; html += '</div>'; html += '<div class="col-lg-10" id="e-what">'; html += res.event_title; html += '</div>'; html += '<div class="col-lg-2">'; html += ' When:'; html += '</div>'; html += '<div class="col-lg-10" id="e-when">'; html += res.event_date; html += '</div>'; html += '<div class="col-lg-2">'; html += ' Where:'; html += '</div>'; html += '<div class="col-lg-10" id="e-where">'; html += res.event_location; html += '</div>'; html += '<div class="col-lg-12" style="margin-top: 20px;">'; html += res.event_description; html += '</div>'; html += "</div>"; $(".event-container").html(html); }) }; var _buildDom = function(data){ var html = ""; for (var i = 0; i < data.length; i++) { html += "<div class='ev-container'>"; html += "<a href="+ base_url + "event/" + data[i].event_id +">"; html += "<div class='ev-title'>" + data[i].event_title + "</div>"; html += "<div class='ev-date'><strong>When:</strong> " + data[i].event_date + "</div>"; html += "<div class='ev-loc'><strong>Where:</strong> " + data[i].event_location + "</div>"; html += "</a>"; html += "</div>"; } return html; }; var _parseDate = function(date){ var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var splitDate = date.split("-"); var month = months[(parseInt(splitDate[1]) - 1)]; return month + " " + splitDate[2] + ", " + splitDate[0]; }; return { initCalendar: function(){ var dateToday = new Date(); $('#mapp-calendar').datepicker({ dateFormat: 'yy-mm-dd', minDate: dateToday, // beforeShowDay: function(date){ // console.log(date); // }, onSelect: function(date){ isEvsEndReached = 0; isRendering = 0; if(isLoading === false){ var params = { url: base_url + "events/get_events", data:{ d: $(this).val() } }; _getContent(params, (function(data){ // console.log(data); $("#selected-date").html("Events for " + _parseDate($(this).val())); if(Object.keys(data).length > 0){ var dom = _buildDom(data); $("#events-list").html(dom); } else { $("#events-list").html("No events for this date"); } }).bind($(this))); } } }); $('.ui-datepicker-current-day').click(); _bindEvents(); } }; })();
import isEnabled from "ember-metal/features"; if (isEnabled('ember-htmlbars-each-in')) { var shouldDisplay = function(object) { if (object === undefined || object === null) { return false; } return true; }; var eachInHelper = function([ object ], hash, blocks) { if (shouldDisplay(object)) { for (var prop in object) { if (!object.hasOwnProperty(prop)) { continue; } blocks.template.yieldItem(prop, [prop, object[prop]]); } } else if (blocks.inverse.yield) { blocks.inverse.yield(); } }; } export default eachInHelper;
'use strict'; var bunyan = require('bunyan'); var rootLogger = bunyan.createLogger({name: 'myAPI', level: 'info'}); var logger = require('../../../index')(rootLogger); var loopback = require('loopback'); var boot = require('loopback-boot'); var app = module.exports = loopback(); app.start = function() { // start the web server return app.listen(function() { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); console.log('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; console.log('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err; // start the server if `$ node server.js` if (require.main === module) app.start(); });
/** * @author: @AngularClass */ const helpers = require('./helpers'); const webpackMerge = require('webpack-merge'); // used to merge webpack configs const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev /** * Webpack Plugins */ const DefinePlugin = require('webpack/lib/DefinePlugin'); /** * Webpack Constants */ const ENV = process.env.ENV = process.env.NODE_ENV = 'development'; const HMR = helpers.hasProcessFlag('hot'); const METADATA = webpackMerge(commonConfig.metadata, { baseUrl: '/', host: 'localhost', port: 3001, ENV: ENV, HMR: HMR, USERS_API_URL: JSON.stringify('http://localhost:3000/users') }); /** * Webpack configuration * * See: http://webpack.github.io/docs/configuration.html#cli */ module.exports = webpackMerge(commonConfig, { /** * Merged metadata from webpack.common.js for index.html * * See: (custom attribute) */ metadata: METADATA, /** * Switch loaders to debug mode. * * See: http://webpack.github.io/docs/configuration.html#debug */ debug: true, /** * Developer tool to enhance debugging * * See: http://webpack.github.io/docs/configuration.html#devtool * See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps */ devtool: 'cheap-module-source-map', /** * Options affecting the output of the compilation. * * See: http://webpack.github.io/docs/configuration.html#output */ output: { /** * The output directory as absolute path (required). * * See: http://webpack.github.io/docs/configuration.html#output-path */ path: helpers.root('dist'), /** * Specifies the name of each output file on disk. * IMPORTANT: You must not specify an absolute path here! * * See: http://webpack.github.io/docs/configuration.html#output-filename */ filename: '[name].bundle.js', /** * The filename of the SourceMaps for the JavaScript files. * They are inside the output.path directory. * * See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename */ sourceMapFilename: '[name].map', /** The filename of non-entry chunks as relative path * inside the output.path directory. * * See: http://webpack.github.io/docs/configuration.html#output-chunkfilename */ chunkFilename: '[id].chunk.js' }, plugins: [ /** * Plugin: DefinePlugin * Description: Define free variables. * Useful for having development builds with debug logging or adding global constants. * * Environment helpers * * See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin */ // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts new DefinePlugin({ 'ENV': JSON.stringify(METADATA.ENV), 'HMR': METADATA.HMR, 'USERS_API_URL': METADATA.USERS_API_URL, 'process.env': { 'ENV': JSON.stringify(METADATA.ENV), 'NODE_ENV': JSON.stringify(METADATA.ENV), 'HMR': METADATA.HMR, } }) ], /** * Static analysis linter for TypeScript advanced options configuration * Description: An extensible linter for the TypeScript language. * * See: https://github.com/wbuchwalter/tslint-loader */ tslint: { emitErrors: true, failOnHint: false, resourcePath: 'src' }, /** * Webpack Development Server configuration * Description: The webpack-dev-server is a little node.js Express server. * The server emits information about the compilation state to the client, * which reacts to those events. * * See: https://webpack.github.io/docs/webpack-dev-server.html */ devServer: { port: METADATA.port, host: METADATA.host, historyApiFallback: true, watchOptions: { aggregateTimeout: 300, poll: 1000 }, outputPath: helpers.root('dist') }, /* * Include polyfills or mocks for various node stuff * Description: Node configuration * * See: https://webpack.github.io/docs/configuration.html#node */ node: { global: 'window', crypto: 'empty', process: true, module: false, clearImmediate: false, setImmediate: false } });
function isFlatArray(data) { return (Array.isArray(data) && typeof data[0] !== 'object'); } function isNestedArray(data) { return (Array.isArray(data) && Array.isArray(data[0])); } function isCollectionOfDict(data) { return (Array.isArray(data) && typeof data[0] === 'object'); } function isDict(data) { return (!Array.isArray(data) && typeof data === 'object'); } export default function (data) { let newData = []; switch (true) { case (isFlatArray(data)): break; case (isNestedArray(data)): console.log('yo'); break; case (isCollection(data)): console.log('yo'); break; case (isJSON(data)): console.log('yo'); break; default: console.log('yo'); } // data = [ // { // label: 1, // value: 1, // key: // } // ] return data; }
/* This is an example app to use as starting point for building a mydigitalstucture.cloud based nodejs app that you plan to host using AWS Lambda. To run it on your local computer your need to install https://www.npmjs.com/package/aws-lambda-local and then run as: $ lambda-local -f index.js -t 9000 -e learn-event.json -c learn-context.json - where the data in event.json will be passed to the handler as event and the settings.json data will passed as context. Also see learn.js for more example code using the mydigitalstructure node module. */ exports.handler = function (event, context) { var mydigitalstructure = require('mydigitalstructure') var _ = require('lodash') var moment = require('moment'); mydigitalstructure.set( { scope: 'learn', context: 'lambda', name: 'event', value: event }); /* mydigitalstructure. methods impact local data. mydigitalstructure.cloud. methods impact data managed by the mydigitalstructure.cloud service (remote). */ mydigitalstructure.init(main) function main(err, data) { /* [LEARN EXAMPLE #1] Use mydigitalstructure.add to add your controller methods to your app and mydigitalstructure.invoke to run them, as per example learn-log. */ mydigitalstructure.add( { name: 'learn-log', code: function () { console.log('Using mydigitalstructure module version ' + mydigitalstructure.VERSION); var eventData = mydigitalstructure.get( { scope: 'learn', context: 'lambda', name: 'event' }); mydigitalstructure.cloud.invoke( { object: 'core_debug_log', fields: { data: JSON.stringify(eventData), notes: 'Learn Lambda Log' }, callback: 'learn-log-saved' }); } }); mydigitalstructure.add( { name: 'learn-log-saved', code: function (param, response) { mydigitalstructure._util.message('learn-log event data saved to mydigitalstructure.cloud'); mydigitalstructure._util.message(param); mydigitalstructure._util.message(response); } }); mydigitalstructure.invoke('learn-log'); } }
const noteToFrequency = require(`../`); const song = [ `G`, `A`, `B`, `G`, `G`, `A`, `B`, `G` ].map(n => noteToFrequency(`${n}4`)); console.log(song);
'use strict'; var grunt = require('grunt'); /* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(actual, expected, [message]) test.notDeepEqual(actual, expected, [message]) test.strictEqual(actual, expected, [message]) test.notStrictEqual(actual, expected, [message]) test.throws(block, [error], [message]) test.doesNotThrow(block, [error], [message]) test.ifError(value) */ exports.angular_build_id = { setUp: function(done) { // setup here if necessary done(); }, string: function (test) { test.expect(1); var actual = grunt.file.read('tmp/string.html'); var expected = '<span>REPLACE</span><span>REPLACE</span>'; test.equal(actual, expected, 'should replace the regex match with REPLACE.'); test.done(); }, function: function (test) { test.expect(1); var actual = grunt.file.read('tmp/function.html'); var expected = '<span>ORIGINAL1 additional text</span><span>ORIGINAL2</span>'; test.equal(actual, expected, 'should append additional text to the match.'); test.done(); } };
import React, { Component, } from 'react' import { View, Text, StyleSheet, Dimensions, Modal, ActivityIndicator, ActivityIndicatorIOS, ProgressBarAndroid, } from 'react-native' import Button from 'react-native-smart-button' import TimerEnhance from 'react-native-smart-timer-enhance' import LoadingSpinnerOverlay from 'react-native-smart-loading-spinner-overlay' class LoadingSpinnerOverLayDemo extends Component { constructor(props) { super(props) this.state = {} } render() { return ( <View style={{ paddingTop: 64, flex: 1, backgroundColor: '#fff',}}> <Button onPress={this._showModalLoadingSpinnerOverLay} touchableType={Button.constants.touchableTypes.fadeContent} style={{margin: 10, height: 40, backgroundColor: 'red', borderRadius: 3, borderWidth: StyleSheet.hairlineWidth, borderColor: 'red', justifyContent: 'center',}} textStyle={{fontSize: 17, color: 'white'}} > show modal loading spinner (模态) </Button> <Button onPress={this._showPartModalLoadingSpinnerOverLay} touchableType={Button.constants.touchableTypes.highlight} underlayColor={'#C90000'} style={{margin: 10, justifyContent: 'center', height: 40, backgroundColor: 'red', borderRadius: 3, borderWidth: StyleSheet.hairlineWidth, borderColor: 'red', justifyContent: 'center',}} textStyle={{fontSize: 17, color: 'white'}} > [part modal]can click header (导航栏允许点击) </Button> <Button onPress={this._showNoModalLoadingSpinnerOverLay} touchableType={Button.constants.touchableTypes.blur} style={{margin: 10, justifyContent: 'center', height: 40, backgroundColor: 'red', borderRadius: 3, borderWidth: StyleSheet.hairlineWidth, borderColor: 'red', justifyContent: 'center',}} textStyle={{fontSize: 17, color: 'white'}} > show no modal loading spinner (非模态) </Button> <Button onPress={this._showImmediateLoadingSpinnerOverLayAndImmediateHide} touchableType={Button.constants.touchableTypes.fade} style={{margin: 10, justifyContent: 'center', height: 40, backgroundColor: 'red', borderRadius: 3, borderWidth: StyleSheet.hairlineWidth, borderColor: 'red', justifyContent: 'center',}} textStyle={{fontSize: 17, color: 'white'}} > show and hide immediately (无渐变) </Button> <Button onPress={this._showModal_2_LoadingSpinnerOverLay} touchableType={Button.constants.touchableTypes.fadeContent} style={{margin: 10, height: 40, backgroundColor: 'red', borderRadius: 3, borderWidth: StyleSheet.hairlineWidth, borderColor: 'red', justifyContent: 'center',}} textStyle={{fontSize: 17, color: 'white'}} > custom content (自定义内容) </Button> <LoadingSpinnerOverlay ref={ component => this._modalLoadingSpinnerOverLay = component }/> <LoadingSpinnerOverlay ref={ component => this._partModalLoadingSpinnerOverLay = component } modal={true} marginTop={64}/> <LoadingSpinnerOverlay ref={ component => this._LoadingSpinnerOverLay = component } modal={false}/> <LoadingSpinnerOverlay ref={ component => this._modalImmediateLoadingSpinnerOverLay = component }/> <LoadingSpinnerOverlay ref={ component => this._modal_2_LoadingSpinnerOverLay = component }> {this._renderActivityIndicator()} </LoadingSpinnerOverlay> </View> ) } _showModalLoadingSpinnerOverLay = () => { this._modalLoadingSpinnerOverLay.show() //simulate http request this.setTimeout( () => { this._modalLoadingSpinnerOverLay.hide() }, 3000) } _showPartModalLoadingSpinnerOverLay = () => { this._partModalLoadingSpinnerOverLay.show() //simulate http request this.setTimeout( () => { this._partModalLoadingSpinnerOverLay.hide() }, 3000) } _showNoModalLoadingSpinnerOverLay = () => { this._LoadingSpinnerOverLay.show() //simulate http request this.setTimeout( () => { this._LoadingSpinnerOverLay.hide() }, 3000) } _showImmediateLoadingSpinnerOverLayAndImmediateHide = () => { this._modalImmediateLoadingSpinnerOverLay.show({ duration: 0, children: this._renderActivityIndicator(), }) //simulate http request this.setTimeout( () => { this._modalImmediateLoadingSpinnerOverLay.hide({ duration: 0, }) }, 3000) } _showModal_2_LoadingSpinnerOverLay = () => { this._modal_2_LoadingSpinnerOverLay.show() //simulate http request this.setTimeout( () => { this._modal_2_LoadingSpinnerOverLay.hide() }, 3000) } _renderActivityIndicator() { return ActivityIndicator ? ( <ActivityIndicator animating={true} color={'#ff0000'} size={'small'}/> ) : Platform.OS == 'android' ? ( <ProgressBarAndroid color={'#ff0000'} styleAttr={'small'}/> ) : ( <ActivityIndicatorIOS animating={true} color={'#ff0000'} size={'small'}/> ) } } export default TimerEnhance(LoadingSpinnerOverLayDemo)
const path = require('path'); module.exports = { entry: "./src/index.js", //app entry point output: { filename: "./build/bundle.js" //output of all compiled/minified sources }, devtool: 'cheap-module-eval-source-map', module: { //transformation modules go here loaders: [ { test: /src.+\.js$/, //all files ending in .js loader: 'babel-loader', //run through babel-loader (integration of babel and webpack) query: { presets: ['react', 'es2015'], //selected babel presets: https://babeljs.io/docs/plugins/#presets plugins: ['transform-class-properties'] //babel plugins: https://babeljs.io/docs/plugins/#transform-plugins } } ] }, devServer: { disableHostCheck: true // necessary for c9.io apps }, watchOptions: { poll: true } };
export * from '../select-material-like/select-material-like-bundle'; import './select-lite-arrow.scss'; // override above imported SCSS
import PropTypes from 'prop-types'; import React from 'react'; import CSSTransition from 'react-transition-group/CSSTransition'; const FadeTransition = ({ children, ...props }) => ( <CSSTransition classNames="fade" timeout={375} {...props} appear > {children} </CSSTransition> ); FadeTransition.propTypes = { children: PropTypes.any.isRequired, }; export default FadeTransition;
/** * Simple AJAX request for resolve the jQuery dependencies * * http://youmightnotneedjquery.com/ */ (function () { var Axe; Axe = function () {}; Axe.configuration = { setRequestToken: function (_token) { this._token = _token; }, getRequestToken: function () { return this._token; }, hasRequestToken: function () { return typeof this._token === 'undefined' ? false : true; }, setRequestContentType: function (_contentType) { this._contentType = _contentType; }, getRequestContentType: function () { return this._contentType; }, hasRequestContentType: function () { return typeof this._contentType === 'undefined' ? false:true; } }; Axe.encodeObject = function (object) { var encodedString = ''; for (var prop in object) { if (object.hasOwnProperty(prop)) { if (encodedString.length > 0) { encodedString += '&'; } encodedString += encodeURI(prop + '=' + object[prop]); } } return encodedString; }; Axe.grab = function (url, callback) { var request = new XMLHttpRequest(); request.open('GET',url,true); request.onload = function () { if (request.status >= 200 && request.status < 400) { return callback(request.responseText); } else { return callback('error'); } }; request.onerror = function () { return callback('connection_error'); }; request.send(); }; Axe.cut = function (url, data, header, callback) { var request = new XMLHttpRequest(); request.open('POST', url, true); request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); if (header !== null && header.length > 0) { for (var key in header) { request.setRequestHeader(key, header[key]); } } if (Axe.configuration.hasRequestToken()) { request.setRequestHeader('X-CSRF-TOKEN', Axe.configuration.getRequestToken()); } request.onload = function () { if (request.status >= 200 && request.status < 400) { return callback(request.responseText); } else { return callback('error'); } }; request.onerror = function () { return callback('connection_error'); }; request.send(Axe.encodeObject(data)); }; Axe.slash = function (url, data, header, callback) { var request = new XMLHttpRequest(); request.open('PUT', url); request.setRequestHeader('Content-Type', Axe.configuration.hasRequestContentType() ? Axe.configuration.getRequestContentType() : 'application/json'); if (header !== null && header.length > 0) { for (var key in header) { request.setRequestHeader(key, header[key]); } } if (Axe.configuration.hasRequestToken()) { request.setRequestHeader('X-CSRF-TOKEN', Axe.configuration.getRequestToken()); } request.onload = function () { if (request.status >= 200 && request.status < 400) { return callback(JSON.parse(request.responseText)); } else { return callback('error'); } }; request.onerror = function () { return callback('connection_error'); }; request.send(JSON.stringify(data)); }; window.Axe = Axe; })();
/* globals chai, describe, inject, it */ 'use strict'; var expect = chai.expect; describe('empty', function() { it('should be empty', inject(function() { expect(1).to.equal(1); })); });
/** * Romanian translation for bootstrap-datepicker * Cristian Vasile <cristi.mie@gmail.com> */ ; (function ($) { $.fn.datepicker.dates['ro'] = { days : ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă", "Duminică"], daysShort : ["Dum", "Lun", "Mar", "Mie", "Joi", "Vin", "Sâm", "Dum"], daysMin : ["Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ", "Du"], months : ["Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"], monthsShort: ["Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Nov", "Dec"], today : "Astăzi", weekStart : 1 }; }(jQuery));
var path = require('path') var gulp = require('gulp') var config = require('./config.json') var del = require('del') var inline = require('gulp-inline-source') var htmlmin = require('gulp-htmlmin') var through = require('through2') var template = require('lodash.template') var statusCodes = require('http').STATUS_CODES gulp.task('clean', function() { return del(['build']) }) gulp.task('default', ['clean'], function() { return gulp.src('template.html') .pipe(inline()) .pipe((function() { return through.obj(function(file, enc, cb) { config.compile.forEach(function(code) { var data = { code: code + ' ' + statusCodes[code], title: null, body: null, nonce: null } if(config.content[code]) { data.title = config.content[code].title data.body = config.content[code].body } var clone = file.clone() clone.path = path.resolve(clone.path, '../' + code + '.html') clone.contents = new Buffer(template(clone.contents)(data)) this.push(clone) }, this) this.push(file) return cb() }) })()) .pipe(htmlmin({ collapseWhitespace: true, keepClosingSlash: true })) .pipe(gulp.dest('build')) })
var daykline = [ [20170517,177.24,172.13,175.14,173.27], [20170518,174.20,167.86,173.27,170.33], [20170519,170.66,168.67,170.22,169.45], [20170522,169.41,166.29,168.45,167.71], [20170523,172.68,167.27,167.60,170.90], [20170524,172.12,168.13,170.68,168.79], [20170525,170.82,168.57,168.79,170.49], [20170526,174.85,169.46,170.38,174.46], [20170527,174.68,173.90,174.46,174.35], [20170529,176.66,174.46,175.23,176.44], [20170530,177.65,174.90,176.44,177.21], [20170531,180.41,176.39,177.10,179.64], [20170601,181.50,177.85,179.64,180.37], [20170602,184.69,180.15,180.37,183.48], [20170603,184.57,183.04,183.48,184.35], [20170605,186.05,183.49,184.13,185.28], [20170606,187.90,184.30,185.28,186.90], [20170607,187.97,181.78,186.90,182.77], [20170608,188.02,181.89,182.77,188.02], [20170609,200.29,186.49,188.02,193.21], [20170610,193.64,192.55,193.21,192.99], [20170612,197.72,193.41,193.54,196.82], [20170613,197.15,192.85,196.82,193.57], [20170614,194.44,189.28,193.57,189.97], [20170615,191.83,186.49,189.86,187.25], [20170616,191.38,187.14,187.25,190.71], [20170617,191.81,189.84,190.71,190.49], [20170619,191.68,188.31,190.28,189.65], [20170620,191.35,188.67,189.65,191.24], [20170621,194.89,190.88,191.24,193.88], [20170622,197.02,193.55,193.88,195.68], [20170623,197.89,189.92,195.68,191.12], [20170624,191.78,189.58,191.12,190.13], [20170626,191.35,187.45,189.69,190.80], [20170627,191.85,189.06,190.91,189.68], [20170628,189.71,187.07,189.68,188.23], [20170629,188.71,185.80,188.34,185.91], [20170630,186.46,183.02,185.91,183.67], [20170701,184.87,183.02,183.67,184.11], [20170703,185.57,183.52,184.98,185.09], [20170704,188.58,184.76,185.09,186.62], [20170705,187.96,182.83,186.62,183.90], [20170706,185.83,181.80,183.69,181.94], [20170707,183.88,181.55,181.94,182.60], [20170708,184.57,182.38,182.49,184.24], [20170710,184.31,182.02,184.13,183.74], [20170711,186.46,183.30,183.74,185.90], [20170712,189.74,185.68,185.90,189.21], [20170713,190.74,186.26,189.21,186.80], [20170714,189.46,186.58,186.80,187.68], [20170715,188.33,187.24,187.68,187.68], [20170717,189.58,186.26,187.57,188.28], [20170718,189.60,187.45,188.28,188.59], [20170719,189.86,186.98,188.49,188.75], [20170720,188.97,181.84,188.75,183.86], [20170721,186.95,183.69,183.86,185.49], [20170722,185.47,183.58,185.47,184.07], [20170724,185.02,182.56,184.17,183.63], [20170725,188.33,183.52,183.63,187.42], [20170726,189.14,185.29,187.53,187.50], [20170727,192.43,187.39,187.50,190.99], [20170728,192.06,189.10,190.89,191.59], [20170729,192.03,191.16,191.59,191.59], [20170731,194.90,191.38,191.49,193.88], [20170801,194.74,191.18,193.88,193.75], [20170802,195.86,192.45,193.85,193.96], [20170803,194.18,191.63,193.96,192.63], [20170804,192.85,189.63,192.63,191.57], [20170805,191.89,189.62,191.57,190.16], [20170807,191.78,187.53,190.06,190.49], [20170808,194.14,190.16,190.49,192.76], [20170809,194.06,190.65,192.76,191.18], [20170810,194.03,190.86,191.18,192.46], [20170811,193.46,191.64,192.35,191.88], [20170812,192.53,191.35,191.99,192.10], [20170814,193.62,191.57,191.88,192.50], [20170815,193.23,189.94,192.50,191.94], [20170816,196.12,190.44,191.94,195.67], [20170817,199.89,194.81,195.67,199.28], [20170818,200.56,197.56,199.28,198.51], [20170819,199.04,198.18,198.40,198.83], [20170821,201.10,197.76,198.29,199.62], [20170822,201.66,198.99,199.62,199.21], [20170823,200.76,198.19,199.10,199.21], [20170824,200.80,198.46,198.99,200.16], [20170825,201.84,198.58,200.16,199.15], [20170826,199.58,198.29,199.15,198.61], [20170828,199.93,198.08,198.61,198.83], [20170829,201.60,198.41,198.83,200.21], [20170830,200.96,197.19,200.32,197.91], [20170831,199.68,197.28,197.91,198.52], [20170901,204.93,197.09,198.52,204.24], [20170902,207.40,204.13,204.24,207.08], [20170904,210.39,204.34,208.98,205.57], [20170905,208.72,203.99,205.25,205.29], [20170906,205.39,197.59,205.29,198.95], [20170907,199.89,196.05,198.95,199.27], [20170908,200.72,194.97,199.37,195.45], [20170909,196.29,195.24,195.45,195.24], [20170911,200.19,195.14,195.14,197.23], [20170912,199.53,196.29,197.23,198.46], [20170913,201.50,197.62,198.46,198.27], [20170914,199.15,195.17,198.37,195.71], [20170915,196.34,193.35,195.71,194.97], [20170918,198.52,194.55,194.76,197.63], [20170919,198.58,192.35,197.63,194.32], [20170920,194.42,190.91,194.32,192.89], [20170921,195.37,192.26,192.89,194.71], [20170922,195.27,192.51,194.71,195.17], [20170923,196.01,194.74,195.17,195.27], [20170925,196.84,194.08,195.06,194.57], [20170926,196.40,193.93,194.57,196.08], [20170927,197.45,194.52,195.87,196.26], [20170928,200.64,196.16,196.26,200.01], [20170929,201.91,199.00,200.01,200.76], [20170930,201.18,200.33,200.76,200.65], [20171002,201.18,196.26,201.08,196.69], [20171003,197.55,194.12,196.69,197.23], [20171004,198.40,196.26,197.23,197.87], [20171005,201.29,196.80,197.87,200.11], [20171006,202.68,196.58,200.11,198.40], [20171007,198.94,196.69,198.40,197.12], [20171009,198.74,196.13,197.55,198.21], [20171010,199.17,196.60,198.21,197.42], [20171011,203.09,197.10,197.42,202.66], [20171012,209.29,202.56,202.66,207.68], [20171013,211.21,206.09,207.68,210.27], [20171014,210.90,209.11,210.38,209.64], [20171016,213.89,206.89,209.85,207.84], [20171017,211.50,206.04,207.84,210.29], [20171018,210.82,204.77,210.29,205.41], [20171019,205.94,201.56,205.41,203.74], [20171020,208.42,203.00,203.64,205.40], [20171021,207.75,205.08,205.40,207.53], [20171023,207.78,204.83,207.75,205.90], [20171024,206.60,203.66,206.01,205.67], [20171025,208.15,203.85,205.67,206.73], [20171026,207.73,205.02,206.73,207.16], [20171027,208.23,205.81,207.16,206.68], [20171028,207.97,206.04,206.68,207.86], [20171030,208.91,206.00,207.65,206.42], [20171031,209.39,205.89,206.42,209.16], [20171101,213.44,209.05,209.16,211.97], [20171102,214.11,210.65,211.97,211.21], [20171103,213.39,210.36,211.21,211.63], [20171104,213.34,211.42,211.63,213.13], [20171106,214.60,211.70,213.34,213.07], [20171107,214.03,212.06,213.07,212.84], [20171108,216.00,212.31,212.84,215.44], [20171109,219.45,215.33,215.33,216.69], [20171110,217.01,212.67,216.69,214.27], [20171111,214.27,212.57,214.17,212.89], [20171113,214.67,211.21,212.94,212.32], [20171114,213.30,208.45,212.32,210.05], [20171115,211.76,207.70,210.05,209.54], [20171116,211.42,209.35,209.54,209.67], [20171117,212.94,209.45,209.67,211.46], [20171118,212.95,211.46,211.46,212.52], [20171120,213.62,211.78,212.10,212.68], [20171121,213.47,210.55,212.89,212.83], [20171122,214.68,212.31,212.83,212.84], [20171123,214.33,212.09,212.84,213.04] ]; var weekkline = [ [20111114,136.86,121.95,134.33,123.45], [20111121,124.54,115.96,123.41,116.19], [20111128,135.40,115.69,115.83,131.52], [20111205,140.90,128.85,131.95,140.11], [20111212,139.83,122.70,139.17,127.35], [20111219,135.56,123.65,127.24,135.48], [20111226,135.65,126.14,134.78,131.82], [20120102,135.70,124.01,132.25,124.51], [20120109,131.59,123.06,124.12,129.27], [20120116,138.44,127.83,129.42,137.41], [20120123,142.69,136.22,137.67,140.61], [20120130,145.18,138.17,140.13,143.05], [20120206,145.50,140.61,142.78,142.16], [20120213,143.26,137.16,142.32,139.37], [20120220,147.00,138.62,138.62,143.80], [20120227,146.74,141.28,143.87,144.26], [20120305,144.52,133.72,144.23,142.78], [20120312,144.57,140.04,143.10,142.27], [20120319,143.71,131.53,142.35,133.57], [20120326,136.73,129.90,133.95,132.15], [20120402,134.69,127.52,132.35,129.94], [20120409,133.11,127.50,130.91,130.42], [20120416,137.57,129.02,130.12,137.06], [20120423,138.58,132.19,137.26,138.46], [20120430,138.99,131.63,138.35,131.96], [20120507,132.77,121.80,131.42,121.91], [20120514,124.51,119.39,122.95,122.87], [20120521,126.02,119.03,122.25,120.48], [20120528,126.30,119.94,120.48,125.66], [20120604,129.34,123.65,125.14,125.19], [20120611,131.25,125.89,126.83,128.39], [20120618,130.31,123.62,127.59,124.34], [20120625,126.31,113.85,123.98,119.28], [20120702,123.38,117.35,119.08,118.02], [20120709,120.31,116.91,118.53,119.61], [20120716,120.03,117.77,119.88,117.78], [20120723,118.71,114.17,118.15,118.48], [20120730,121.51,115.89,118.67,118.27], [20120806,122.13,117.51,118.02,119.16], [20120813,124.43,117.12,118.91,124.12], [20120820,134.33,122.12,124.20,133.34], [20120827,134.21,123.66,133.51,128.33], [20120903,133.87,128.23,128.35,133.58], [20120910,143.34,133.18,133.28,141.22], [20120917,142.13,133.29,142.13,136.04], [20120924,135.75,125.03,135.75,128.84], [20121001,136.69,126.49,127.70,133.59], [20121008,134.77,128.14,132.33,128.45], [20121015,131.97,125.03,127.28,125.79], [20121022,126.94,118.06,125.22,119.74], [20121029,124.13,117.65,119.82,120.53], [20121105,125.60,119.73,122.71,122.27], [20121112,129.92,120.67,122.08,125.67], [20121119,134.12,125.49,125.49,133.44], [20121126,138.43,129.31,133.27,135.89], [20121203,140.08,134.56,136.44,139.05], [20121210,141.39,136.18,138.62,141.26], [20121217,141.41,134.86,141.01,136.63], [20121224,142.42,136.23,138.28,139.96], [20121231,143.84,136.53,139.15,137.76], [20130107,141.05,133.14,137.92,140.01], [20130114,146.44,138.94,139.93,144.22], [20130121,148.38,141.58,141.58,147.96], [20130128,152.19,146.99,148.01,151.44], [20130204,154.75,148.26,151.47,150.90], [20130211,155.65,149.16,150.62,151.33], [20130218,154.12,142.25,151.60,147.95], [20130225,150.82,142.90,148.05,144.37], [20130304,157.08,142.66,144.11,156.51], [20130311,156.70,151.37,156.19,154.79], [20130318,154.80,145.33,154.80,151.68], [20130325,154.74,150.68,151.26,153.89], [20130401,156.42,142.77,153.52,145.02], [20130408,147.25,140.34,145.66,140.48], [20130415,139.84,128.68,139.54,134.24], [20130422,136.10,132.28,134.39,134.89], [20130429,139.48,133.29,135.01,137.36], [20130506,141.17,134.15,137.12,139.58], [20130513,146.80,138.41,139.30,145.83], [20130520,149.06,142.31,145.95,143.26], [20130527,150.34,143.10,144.12,147.88], [20130603,150.65,146.83,147.64,149.16], [20130610,151.88,142.93,148.73,144.22], [20130617,144.22,129.23,144.08,133.35], [20130624,133.92,124.83,133.07,129.87], [20130701,137.19,129.86,129.95,134.57], [20130708,144.09,132.89,135.46,142.20], [20130715,148.32,142.55,143.09,147.50], [20130722,148.81,141.14,148.15,143.14], [20130729,147.43,142.35,143.55,143.91], [20130805,146.68,140.36,144.01,145.75], [20130812,150.90,144.48,146.84,150.02], [20130819,150.28,145.92,149.90,147.86], [20130826,148.72,141.65,148.17,141.90], [20130902,143.21,134.73,142.05,136.99], [20130909,138.20,134.32,137.11,137.78], [20130916,145.23,136.90,139.33,141.12], [20130923,144.49,139.12,141.57,143.41], [20130930,144.20,136.19,143.51,137.87], [20131007,141.07,136.98,138.26,140.09], [20131014,145.54,137.74,140.09,145.35], [20131021,147.70,143.39,146.03,145.34], [20131028,147.43,143.64,145.44,145.51], [20131104,149.86,144.80,144.80,148.44], [20131111,148.62,141.53,148.51,143.68], [20131118,143.39,139.28,143.19,140.47], [20131125,142.21,139.00,140.20,140.70], [20131202,145.28,138.97,140.64,143.39], [20131209,145.12,139.28,143.01,139.95], [20131216,140.69,135.66,140.63,136.34], [20131223,140.00,135.26,136.74,139.02], [20131230,142.71,137.42,138.47,141.45], [20140106,145.55,141.32,141.41,144.48], [20140113,146.55,142.58,144.05,145.09], [20140120,146.35,142.64,145.77,142.84], [20140127,143.70,136.60,142.94,137.38], [20140203,139.87,135.76,136.89,138.41], [20140210,144.63,138.41,138.41,143.56], [20140217,145.52,142.50,143.95,145.12], [20140224,147.74,143.06,144.65,146.80], [20140303,154.22,146.35,146.35,153.85], [20140310,155.80,150.56,153.85,152.73], [20140317,159.90,149.47,153.23,158.60], [20140324,159.60,151.11,159.20,154.69], [20140331,158.17,153.03,154.64,157.67], [20140407,162.13,152.08,157.77,160.42], [20140414,163.46,157.32,162.53,161.05], [20140421,163.45,153.08,160.38,162.75], [20140428,165.22,159.83,162.85,163.21], [20140505,164.45,159.36,163.31,160.28], [20140512,166.22,159.56,160.00,163.23], [20140519,168.40,163.14,163.53,166.82], [20140526,170.04,165.90,166.72,168.13], [20140602,170.21,166.83,168.03,170.21], [20140609,173.20,161.21,170.01,162.65], [20140616,167.97,161.78,163.93,164.43], [20140623,169.05,162.26,164.53,168.45], [20140630,173.09,167.95,168.75,172.56], [20140707,175.19,171.75,172.85,174.72], [20140714,177.44,172.05,174.52,175.75], [20140721,177.07,172.68,175.65,174.88], [20140728,176.92,171.16,174.78,172.26], [20140804,173.09,166.05,171.66,170.62], [20140811,177.03,169.53,170.72,176.69], [20140818,177.98,170.39,176.94,175.56], [20140825,179.74,174.12,175.30,178.85], [20140901,180.32,171.72,179.44,176.23], [20140908,176.97,161.74,175.38,164.90], [20140915,167.73,159.53,164.70,160.62], [20140922,163.02,153.55,161.11,153.95], [20140929,157.31,148.23,154.64,149.21], [20141006,159.65,145.27,148.42,155.13], [20141013,156.94,143.52,155.52,148.44], [20141020,155.76,148.05,148.45,153.30], [20141027,157.76,151.45,153.01,156.15], [20141103,159.34,146.90,155.50,152.07], [20141110,154.42,148.68,152.17,151.17], [20141117,156.56,149.84,150.68,155.57], [20141124,161.09,154.98,155.97,159.90], [20141201,161.12,156.72,160.69,158.77], [20141208,164.27,158.08,158.18,162.23], [20141215,162.61,154.01,162.23,161.40], [20141222,163.91,160.85,161.05,163.77], [20141229,164.21,158.29,163.47,159.19], [20150105,162.10,156.61,157.85,160.20], [20150112,163.40,149.08,159.76,150.98], [20150119,156.47,150.13,150.59,154.79], [20150126,160.69,152.49,155.79,156.06], [20150202,160.65,154.25,155.36,157.50], [20150209,159.30,153.13,157.70,158.10], [20150216,160.01,155.75,158.80,157.46], [20150223,165.69,155.95,156.55,165.09], [20150302,168.34,164.21,164.60,165.01], [20150309,167.07,158.05,165.41,160.08], [20150316,159.75,151.72,159.18,155.31], [20150323,156.65,147.88,155.21,148.28], [20150330,150.82,144.80,148.08,149.33], [20150406,155.79,149.67,151.93,155.69], [20150413,157.47,150.98,155.69,156.58], [20150420,157.42,150.38,156.52,153.56], [20150427,156.98,153.26,153.96,154.66], [20150504,160.10,154.46,154.56,159.21], [20150511,159.60,154.72,159.51,158.63], [20150518,159.88,153.52,158.73,156.41], [20150525,157.83,154.84,156.11,155.24], [20150601,155.47,148.97,155.14,150.37], [20150608,150.57,146.21,150.37,146.31], [20150615,147.92,141.14,146.61,141.54], [20150622,141.69,133.75,141.47,135.75], [20150629,140.87,132.82,136.05,136.97], [20150706,137.47,126.16,137.37,129.76], [20150713,133.83,122.98,130.96,123.48], [20150720,127.67,119.48,123.28,125.08], [20150727,126.57,121.39,124.88,121.89], [20150803,125.08,117.99,122.28,119.59], [20150810,129.37,118.69,118.99,127.21], [20150817,128.70,121.18,127.51,124.27], [20150824,123.86,107.78,123.76,120.84], [20150831,124.54,116.45,120.48,118.83], [20150907,122.68,117.15,117.50,122.05], [20150914,126.07,119.07,122.16,124.40], [20150921,139.05,121.66,124.20,136.48], [20150928,143.57,130.91,137.10,143.36], [20151005,147.78,140.30,143.26,144.80], [20151012,146.28,138.96,144.90,143.18], [20151019,143.49,136.45,141.86,141.74], [20151026,142.29,136.73,141.77,137.52], [20151102,138.54,121.74,137.62,125.62], [20151109,126.93,109.34,126.13,110.66], [20151116,114.55,107.87,110.94,113.83], [20151123,117.09,108.15,115.73,113.18], [20151130,117.63,107.49,113.10,117.32], [20151207,117.05,112.29,116.89,113.32], [20151214,119.24,112.55,112.86,115.86], [20151221,117.05,113.81,116.42,116.50], [20151228,118.16,112.88,116.49,115.04], [20160104,118.27,102.68,117.54,104.63], [20160111,105.99,95.57,105.16,103.10], [20160118,107.35,102.58,103.84,105.13], [20160125,106.57,103.16,105.43,105.29], [20160201,109.27,102.92,105.18,105.26], [20160208,112.23,103.88,106.53,111.28], [20160215,111.07,104.04,110.50,104.64], [20160222,105.57,100.98,105.08,101.83], [20160229,117.80,101.35,101.99,116.44], [20160307,122.21,114.84,116.34,121.39], [20160314,124.49,117.27,120.04,122.51], [20160321,127.08,119.78,122.72,120.85], [20160328,122.89,115.90,120.56,117.64], [20160404,117.74,110.64,117.53,111.97], [20160411,118.37,111.48,112.90,118.05], [20160418,128.88,116.77,118.05,126.35], [20160425,132.48,123.88,125.51,130.10], [20160502,131.25,124.52,130.10,126.98], [20160509,128.20,121.01,126.67,124.54], [20160516,125.57,117.14,124.75,117.35], [20160523,117.87,110.02,117.24,113.22], [20160530,118.85,112.05,113.00,116.02], [20160606,120.35,114.24,116.65,115.08], [20160613,117.21,111.50,115.47,112.77], [20160620,120.04,113.19,113.68,116.67], [20160627,129.78,116.87,117.03,129.35], [20160704,133.48,126.79,129.99,133.26], [20160711,140.75,132.23,133.48,138.59], [20160718,147.86,136.21,138.96,147.00], [20160725,152.46,144.85,146.35,151.03], [20160801,154.42,147.99,151.35,148.95], [20160808,159.64,145.30,148.74,146.36], [20160815,153.28,145.59,146.15,151.87], [20160822,151.97,145.48,151.44,147.74], [20160829,150.63,140.90,147.31,145.19], [20160905,152.25,144.81,145.09,145.41], [20160912,145.52,139.63,145.19,144.18], [20160919,151.39,144.07,144.39,150.64], [20160926,155.90,147.12,150.21,155.08], [20161003,155.83,141.89,154.87,143.50], [20161010,145.97,136.45,144.76,140.19], [20161017,141.79,133.74,139.65,135.21], [20161024,140.20,133.07,134.34,135.36], [20161031,138.45,132.98,135.58,135.77], [20161107,153.17,134.90,136.20,147.95], [20161114,162.76,146.53,147.73,160.90], [20161121,166.36,159.91,160.46,164.41], [20161128,172.13,163.00,165.97,164.14], [20161205,166.93,158.57,164.48,163.46], [20161212,164.09,151.92,162.13,154.66], [20161219,156.11,145.52,155.89,147.06], [20161226,153.39,146.96,147.20,152.17], [20170102,169.14,152.16,152.49,168.81], [20170109,171.51,165.06,168.58,167.06], [20170116,175.47,163.27,166.72,174.25], [20170123,175.76,157.47,174.47,164.33], [20170130,170.53,160.57,163.56,165.37], [20170206,174.15,164.59,164.82,173.16], [20170213,175.62,170.70,173.38,172.42], [20170220,173.74,168.77,171.97,169.94], [20170227,174.29,167.38,171.93,171.63], [20170306,172.65,164.87,172.08,165.83], [20170313,173.16,164.63,166.39,172.45], [20170320,180.70,171.55,172.68,179.20], [20170327,179.82,173.89,179.38,176.70], [20170403,181.03,176.14,177.36,178.04], [20170410,179.61,174.68,177.93,176.22], [20170417,178.88,170.81,176.54,175.78], [20170424,184.51,175.09,176.22,183.51], [20170501,183.95,174.70,183.95,180.88], [20170508,182.13,176.11,180.66,178.90], [20170515,181.82,167.86,179.01,169.45], [20170522,174.85,166.29,168.45,174.35], [20170529,184.69,174.46,175.23,184.35], [20170605,200.29,181.78,184.13,192.99], [20170612,197.72,186.49,193.54,190.49], [20170619,197.89,188.31,190.28,190.13], [20170626,191.85,183.02,189.69,184.11], [20170703,188.58,181.55,184.98,184.24], [20170710,190.74,182.02,184.13,187.68], [20170717,189.86,181.84,187.57,184.07], [20170724,192.43,182.56,184.17,191.59], [20170731,195.86,189.62,191.49,190.16], [20170807,194.14,187.53,190.06,192.10], [20170814,200.56,189.94,191.88,198.83], [20170821,201.84,197.76,198.29,198.61], [20170828,207.40,197.09,198.61,207.08], [20170904,210.39,194.97,208.98,195.24], [20170911,201.50,193.35,195.14,194.97], [20170918,198.58,190.91,194.76,195.27], [20170925,201.91,193.93,195.06,200.65], [20171002,202.68,194.12,201.08,197.12], [20171009,211.21,196.13,197.55,209.64], [20171016,213.89,201.56,209.85,207.53], [20171023,208.23,203.66,207.75,207.86], [20171030,214.11,205.89,207.65,213.13], [20171106,219.45,211.70,213.34,212.89], [20171113,214.67,207.70,212.94,212.52], [20171120,214.68,210.55,212.10,213.04] ]; var monthkline = [ [20111101,136.86,115.69,134.33,126.97], [20111201,140.90,122.70,126.82,131.82], [20120101,142.69,123.06,132.25,139.75], [20120201,147.00,137.16,139.75,143.94], [20120301,145.93,129.90,143.97,132.15], [20120401,138.82,127.50,132.35,137.47], [20120501,138.99,119.03,137.46,123.83], [20120601,131.25,113.85,123.83,119.28], [20120701,123.38,114.17,119.08,120.68], [20120801,134.33,115.89,120.67,127.66], [20120901,143.34,125.03,127.67,128.84], [20121001,136.69,117.65,127.70,121.73], [20121101,138.43,119.73,121.74,136.30], [20121201,142.42,134.56,136.32,140.74], [20130101,152.19,133.14,140.75,149.13], [20130201,155.65,142.25,149.09,146.48], [20130301,157.08,142.66,146.48,153.89], [20130401,156.42,128.68,153.52,138.34], [20130501,150.34,133.29,138.36,147.64], [20130601,151.88,124.83,147.64,129.87], [20130701,148.81,129.86,129.95,142.97], [20130801,150.90,140.36,142.98,141.90], [20130901,145.23,134.32,142.05,143.28], [20131001,147.70,136.19,143.38,144.71], [20131101,149.86,139.00,144.81,140.70], [20131201,145.28,135.26,140.64,138.20], [20140101,146.55,136.60,138.20,137.09], [20140201,147.74,135.76,137.09,147.30], [20140301,159.90,146.35,147.30,155.11], [20140401,163.61,152.08,155.11,163.21], [20140501,170.04,159.36,163.21,168.13], [20140601,173.20,161.21,168.03,169.24], [20140701,177.44,168.24,169.24,174.18], [20140801,179.74,166.05,174.18,178.85], [20140901,180.32,152.37,179.44,152.96], [20141001,159.65,143.52,152.96,155.36], [20141101,161.09,146.90,155.36,159.90], [20141201,164.27,154.01,160.69,160.09], [20150101,163.40,149.08,159.09,156.06], [20150201,165.69,153.13,155.36,165.09], [20150301,168.34,144.80,164.60,146.50], [20150401,157.47,146.10,146.40,154.36], [20150501,160.10,153.52,154.26,155.24], [20150601,155.47,132.82,155.14,134.57], [20150701,140.87,119.48,134.47,121.98], [20150801,129.37,107.78,121.98,123.11], [20150901,139.05,116.45,123.11,134.68], [20151001,147.78,132.94,134.68,137.52], [20151101,138.54,107.87,137.62,111.49], [20151201,119.24,107.49,111.49,115.04], [20160101,118.27,95.57,117.54,105.29], [20160201,112.23,100.98,105.18,103.64], [20160301,127.08,103.64,103.75,118.69], [20160401,132.48,110.64,118.69,130.10], [20160501,131.25,110.02,130.10,114.54], [20160601,127.60,111.50,114.54,126.75], [20160701,152.46,126.55,126.75,151.03], [20160801,159.64,143.34,151.35,143.99], [20160901,155.90,139.63,143.99,154.42], [20161001,155.83,132.98,154.42,134.19], [20161101,171.88,133.10,134.19,171.33], [20161201,172.13,145.52,171.22,152.17], [20170101,175.76,152.16,152.49,166.71], [20170201,175.62,163.93,166.71,171.45], [20170301,180.70,164.63,171.23,176.59], [20170401,184.51,170.81,176.59,183.51], [20170501,183.95,166.29,183.95,179.64], [20170601,200.29,177.85,179.64,183.67], [20170701,194.90,181.55,183.67,193.88], [20170801,201.84,187.53,193.88,198.52], [20170901,210.39,190.91,198.52,200.65], [20171001,213.89,194.12,201.08,209.16], [20171101,219.45,207.70,209.16,213.04] ]; window.localStorage.pd = JSON.stringify({kday:daykline,kweek:weekkline,kmonth:monthkline});
var bencode = require('..') var test = require('tape').test var Buffer = require('safe-buffer').Buffer test('abstract encoding', function (t) { t.test('encodingLength( value )', function (t) { var input = { string: 'Hello World', integer: 12345 } var output = Buffer.from('d7:integeri12345e6:string11:Hello Worlde') t.plan(1) t.equal(bencode.encodingLength(input), output.length) }) t.test('encode.bytes', function (t) { var output = bencode.encode({ string: 'Hello World', integer: 12345 }) t.plan(1) t.equal(output.length, bencode.encode.bytes) }) t.test('encode into an existing buffer', function (t) { var input = { string: 'Hello World', integer: 12345 } var output = Buffer.from('d7:integeri12345e6:string11:Hello Worlde') var target = Buffer.allocUnsafe(output.length) bencode.encode(input, target) t.plan(1) t.deepEqual(target, output) }) t.test('encode into a buffer with an offset', function (t) { var input = { string: 'Hello World', integer: 12345 } var output = Buffer.from('d7:integeri12345e6:string11:Hello Worlde') var target = Buffer.allocUnsafe(64 + output.length) // Pad with 64 bytes var offset = 48 bencode.encode(input, target, offset) t.plan(1) t.deepEqual(target.slice(offset, offset + output.length), output) }) t.test('decode.bytes', function (t) { var input = Buffer.from('d7:integeri12345e6:string11:Hello Worlde') bencode.decode(input) t.plan(1) t.equal(bencode.decode.bytes, input.length) }) t.test('decode from an offset', function (t) { var pad = '_______________________________' var input = Buffer.from(pad + 'd7:integeri12345e6:string11:Hello Worlde') var output = bencode.decode(input, pad.length, 'utf8') t.plan(1) t.deepEqual(output, { string: 'Hello World', integer: 12345 }) }) t.test('decode between an offset and end', function (t) { var pad = '_______________________________' var data = 'd7:integeri12345e6:string11:Hello Worlde' var input = Buffer.from(pad + data + pad) var output = bencode.decode(input, pad.length, pad.length + data.length, 'utf8') t.plan(1) t.deepEqual(output, { string: 'Hello World', integer: 12345 }) }) })
H5.calcLinePoint = (function () { 'use strict'; function calcLinePoint(time, line) { var x = line.startX + time * line.vectorX; var y = line.startY + time * line.vectorY; return { x: x, y: y }; } return calcLinePoint; })();
import DS from 'ember-data'; import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin'; import FormDataAdapterMixin from 'ember-cli-form-data/mixins/form-data-adapter'; export default DS.RESTAdapter.extend(DataAdapterMixin, FormDataAdapterMixin, { // namespace: 'api', authorizer: 'authorizer:oauth2', // host: 'http://q1q1.eu/employees', host: 'http://localhost:80/employees', // host: 'http://localhost:80/intranet-api' });
import doesReturnJSX from './doesReturnJSX' import getTypesFromFilename from './getTypesFromFilename' import isDisplayNameSet from './isDisplayNameSet' import makeDisplayName from './makeDisplayName' export { doesReturnJSX, getTypesFromFilename, isDisplayNameSet, makeDisplayName, }
/** * Chunk is a data structure that holds tile data for a Map * @class Chunk * @constructor */ function Chunk() { this.x = null this.y = null this.tiles = null } /** * Creates an empty chunk, where each tile is { } * @method newEmpty * @static */ Chunk.newEmpty = function() { var chunk = new Chunk() chunk.tiles = new Array(Chunk.dim * Chunk.dim) for (var i = 0; i < chunk.tiles.length; i++) { chunk.tiles[i] = { } } return chunk } /** * Creates a chunk, where each tile is self labeled with x, y * @method newTest * @static */ Chunk.newTest = function() { var chunk = new Chunk() chunk.tiles = new Array(Chunk.dim * Chunk.dim) for (var i = 0; i < Chunk.dim; i++) { for (var j = 0; j < Chunk.dim; j++) { // are i & j correct? or inverted? chunk.tiles[Chunk.index(i, j)] = { x: i, y: j } } } return chunk } /** * Converts 2D coords to 1D index * @method index * @static * @param {Integer} x The x coordinate in the context of this chunk * @param {Integer} y The y coordinate in the context of this chunk * @return {Integer} Returns index */ Chunk.index = function(x, y) { return (y * Chunk.dim) + x } /** * Converts 1D index to 2D coords * @method index * @static * @param {Integer} index * @return {Object} Returns object containing x, y */ Chunk.xy = function(index) { return { x: Math.floor(index / Chunk.dim), y: index % Chunk.dim } } /** * Gets a tile * @method getTile * @param {Integer} x The x coordinate in the context of this chunk * @param {Integer} y The y coordinate in the context of this chunk * @return {Object} Returns tile */ Chunk.prototype.getTile = function(x, y) { return this.tiles[Chunk.index(x, y)] } /** * Sets a tile * @method setTile * @param {Integer} x The x coordinate in the context of this chunk * @param {Integer} y The y coordinate in the context of this chunk */ Chunk.prototype.setTile = function(x, y, value) { this.tiles[Chunk.index(x, y)] = value } /** * The square dimensions of a chunk * @property dim * @type Integer * @static */ Chunk.dim = 32 module.exports = Chunk
(function() { 'use strict'; var app = io.express(), GETVOTERESULT = require('../adminApImplementation/voters/getIndex.js'), GETCOUNT = require('../adminApImplementation/voters/getIndex.js'), POSTADDVOTERS = require('../adminApImplementation/voters/postIndex.js'), POSTVOTERLOGIN = require('../adminApImplementation/voters/postIndex.js'), PUTVOTERSUBMIT = require('../adminApImplementation/voters/putIndex.js'); app.route('/addVoters') .post(io.authorize, io.xPoweredBy, POSTADDVOTERS.addVoters); app.route('/votersLogin') .post(POSTVOTERLOGIN.votersLogin); app.route('/votersSubmit') .put(PUTVOTERSUBMIT.votersSubmit); app.route('/votersResult') .get(GETVOTERESULT.votersResult); app.route('/count') .get(GETCOUNT.count); module.exports = app; }());
export { default } from 'ember-cenchat-ui/ui/components/cui-tab/component';
/** * A small shape * * @exports Thingie * @extends Sprite */ import { Sprite, Texture, Point } from 'pixi.js'; import ONE from './1.png'; import TWO from './2.png'; import FOUR from './4.png'; import FIVE from './5.png'; const assets = [ONE, TWO, FOUR, FIVE]; export default class Thingie extends Sprite { constructor() { const asset = assets[Math.floor(Math.random() * assets.length)]; const texture = Texture.from(asset); super(texture); this.speed = Math.random() / 2 + 0.25; this.offset = new Point(0, 0); this.targetOffset = new Point(0, 0); this.originPosition = new Point(0, 0); this.alpha = 0.9; } setInitialPoint(x, y) { this.position.set(x, y); this.originPosition.set(x, y); } update(mousepos) { const { x, y } = mousepos; const x1 = this.originPosition.x; const y1 = this.originPosition.y; const xDist = x1 - x; const yDist = y1 - y; const dist = Math.sqrt(xDist * xDist + yDist * yDist); if (dist < 200) { const angle = Math.atan2(yDist, xDist); const xaDist = Math.cos(angle) * dist; const yaDist = Math.sin(angle) * dist; this.targetOffset.set(xaDist, yaDist); } else { this.targetOffset.set(0, 0); } this.offset.x += (this.targetOffset.x - this.offset.x) * 0.01; this.offset.y += (this.targetOffset.y - this.offset.y) * 0.01; this.position.set( this.originPosition.x + this.offset.x, this.originPosition.y + this.offset.y ); } }
import React from 'react'; import PropTypes from 'prop-types'; import { gql, graphql } from 'react-apollo'; import compose from 'recompose/compose'; import Router from 'next/router'; import withData from '../../lib/withData'; import withAuth from '../../lib/withAuth'; import withGlobalStyles from '../../lib/withGlobalStyles'; import withIntl from '../../lib/withIntl'; import withValidation from '../../lib/withValidation'; import { signIn } from '../../lib/auth'; import Layout from '../../components/Layout'; import HeroCard from '../../components/HeroCard'; import { Error, Form, FormGroup, LinkButton, TextInput, Submit, Success } from '../../components/forms'; import Spinner from '../../components/Spinner'; const signinUser = gql` mutation($email: String!, $password: String!) { signinUser(email: { email: $email, password: $password }) { token } } `; export const SignUp = ({ onFieldChange, onSubmit, isValid, isSubmitting, submitSucceeded, submitFailed, validation, values: { email, password }, t, }) => ( <Layout title={t('sign-in.title')}> <HeroCard> <Form noValidate onSubmit={onSubmit}> <FormGroup> <label htmlFor="email">{t('sign-in.email')}</label> <TextInput id="email" name="email" type="email" required value={email} onChange={onFieldChange} /> {validation.email.touched && validation.email.errors && <Error>{t(validation.email.errors[0])}</Error>} </FormGroup> <FormGroup> <label htmlFor="password">{t('sign-in.password')}</label> <TextInput id="password" name="password" type="password" required value={password} onChange={onFieldChange} /> {validation.password.touched && validation.password.errors && <Error>{t(validation.password.errors[0])}</Error>} </FormGroup> <FormGroup> <Submit primary disabled={!isValid || isSubmitting} type="submit"> {t('sign-in.sign-in')} </Submit> <Spinner show={isSubmitting} /> {submitSucceeded && <Success inline>{t('sign-in.success')}</Success>} {submitFailed && <Error inline>{t('sign-in.error')}</Error>} <LinkButton prefetch href="/auth/sign-up"> {t('sign-in.no-account')} </LinkButton> </FormGroup> </Form> </HeroCard> </Layout> ); SignUp.propTypes = { values: PropTypes.shape({ email: PropTypes.string, password: PropTypes.string, }), isSubmitting: PropTypes.bool.isRequired, isValid: PropTypes.bool.isRequired, onFieldChange: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, submitFailed: PropTypes.bool.isRequired, submitSucceeded: PropTypes.bool.isRequired, t: PropTypes.func.isRequired, validation: PropTypes.shape({ email: PropTypes.shape({ touched: PropTypes.bool.isRequired, errors: PropTypes.arrayOf(PropTypes.string), }), password: PropTypes.shape({ touched: PropTypes.bool.isRequired, errors: PropTypes.arrayOf(PropTypes.string), }), }), }; export default compose( withData, withAuth, withGlobalStyles, withIntl, graphql(signinUser, { name: 'signinUser' }), withValidation( { email: { email: { message: 'sign-in.errors.email' }, presence: { message: 'sign-in.errors.required' }, }, password: { presence: { message: 'sign-in.errors.required' }, }, }, (variables, { signinUser }) => signinUser({ variables }).then(response => { signIn({ email: variables.email, token: response.data.signinUser.token, }); Router.push('/'); return true; }), ), )(SignUp);
const is = require('is') const fs = require('fs') const path = require('path') var async = require('async') const inquirer = require('inquirer') const logger = require('./index.js').logger const mergeNoUndefined = require('./index.js').mergeNoUndefined module.exports = function prompt(module, env, next) { let isString = is.string, isObject = is.object, isArray = is.array, isUndefined = is.undefined let localLogger = (local, type) => (msg, end = false, cb = next) => logger[type](msg, local, end, cb) let error = localLogger('prompt', 'error') let warning = localLogger('prompt', 'warning') let modules = this._metadata.modules if (!this._metadata.usePrompt) return next(null, 'No use Prompt') let p = this.promptPromise ? this.promptPromise : (this.promptPromise = new Promise((resolve, reject) => { async.series( [promptParent.bind(this), promptModule.bind(this)], resolve ) })) p .then(err => { next(err, 'prompt success') }) .catch(next) function promptParent(callback) { let { _prompts = [], prompts: parentPrompt, _promptSyncModule = [], promptSyncModule = [], promptIgnore } = this._metadata if (isString(promptIgnore)) promptIgnore = [promptIgnore] if (isString(promptSyncModule)) promptSyncModule = [promptSyncModule] let promptParentArr = _prompts.concat(parentPrompt || []) let promptParentSyncModuleArr = _promptSyncModule.concat(promptSyncModule) let promptParentFilterArr = isArray(promptIgnore) ? promptParentArr.filter(v => !promptIgnore.includes(v.name)) : promptParentArr if (!promptParentFilterArr.length) return callback(null) inquirer.prompt(promptParentFilterArr).then(answers => { Object.assign(this._metadata, answers) if (promptParentSyncModuleArr.length) { promptParentSyncModuleArr.forEach(v => { if (!isUndefined(answers[v])) { for (i in modules) { modules[i][v] = answers[v] } } }) } callback(null) }) } function promptModule(callback) { async.eachSeries( Object.keys(modules), (env, done) => { let sourcePrompt = modules[env].prompts let sourcePromptIgnore = modules[env].promptIgnore let promptModuleArr = sourcePrompt && modules[env].hasOwnProperty('prompts') ? sourcePrompt : [] let promptIgnore = sourcePromptIgnore && modules[env].hasOwnProperty('promptIgnore') ? sourcePromptIgnore : void 0 if (isString(promptIgnore)) promptIgnore = [promptIgnore] let promptModuleFilterArr = isArray(promptIgnore) ? promptModuleArr.filter(v => !promptIgnore.includes(v.name)) : promptModuleArr if (!promptModuleFilterArr.length) return done(null) inquirer.prompt(promptModuleFilterArr).then(answers => { Object.assign(modules[env], answers) done() }) }, callback ) } }
/* Set the defaults for DataTables initialisation */ $.extend(true, $.fn.dataTable.defaults, { "sDom": "<'row'<'col-sm-6'l><'col-sm-6'f>r>" + "t" + "<'row'<'col-sm-6'i><'col-sm-6'p>>", "oLanguage": { "sLengthMenu": "_MENU_ records per page" } }); /* Default class modification */ $.extend($.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline", "sFilterInput": "form-control input-sm", "sLengthSelect": "form-control input-sm" }); // In 1.10 we use the pagination renderers to draw the Bootstrap paging, // rather than custom plug-in if ($.fn.dataTable.Api) { $.fn.dataTable.defaults.renderer = 'bootstrap'; $.fn.dataTable.ext.renderer.pageButton.bootstrap = function(settings, host, idx, buttons, page, pages) { var api = new $.fn.dataTable.Api(settings); var classes = settings.oClasses; var lang = settings.oLanguage.oPaginate; var btnDisplay, btnClass; var attach = function(container, buttons) { var i, ien, node, button; var clickHandler = function(e) { e.preventDefault(); if (e.data.action !== 'ellipsis') { api.page(e.data.action).draw(false); } }; for (i = 0, ien = buttons.length; i < ien; i++) { button = buttons[i]; if ($.isArray(button)) { attach(container, button); } else { btnDisplay = ''; btnClass = ''; switch (button) { case 'ellipsis': btnDisplay = '&hellip;'; btnClass = 'disabled'; break; case 'first': btnDisplay = lang.sFirst; btnClass = button + (page > 0 ? '' : ' disabled'); break; case 'previous': btnDisplay = lang.sPrevious; btnClass = button + (page > 0 ? '' : ' disabled'); break; case 'next': btnDisplay = lang.sNext; btnClass = button + (page < pages - 1 ? '' : ' disabled'); break; case 'last': btnDisplay = lang.sLast; btnClass = button + (page < pages - 1 ? '' : ' disabled'); break; default: btnDisplay = button + 1; btnClass = page === button ? 'active' : ''; break; } if (btnDisplay) { node = $('<li>', { 'class': classes.sPageButton + ' ' + btnClass, 'aria-controls': settings.sTableId, 'tabindex': settings.iTabIndex, 'id': idx === 0 && typeof button === 'string' ? settings.sTableId + '_' + button : null }) .append($('<a>', { 'href': '#' }) .html(btnDisplay) ) .appendTo(container); settings.oApi._fnBindAction( node, { action: button }, clickHandler ); } } } }; attach( $(host).empty().html('<ul class="pagination"/>').children('ul'), buttons ); }; } else { // Integration for 1.9- $.fn.dataTable.defaults.sPaginationType = 'bootstrap'; /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function(oSettings) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil(oSettings.fnRecordsDisplay() / oSettings._iDisplayLength) }; }; /* Bootstrap style pagination control */ $.extend($.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function(oSettings, nPaging, fnDraw) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function(e) { e.preventDefault(); if (oSettings.oApi._fnPageChange(oSettings, e.data.action)) { fnDraw(oSettings); } }; $(nPaging).append( '<ul class="pagination">' + '<li class="prev disabled"><a href="#">&larr; ' + oLang.sPrevious + '</a></li>' + '<li class="next disabled"><a href="#">' + oLang.sNext + ' &rarr; </a></li>' + '</ul>' ); var els = $('a', nPaging); $(els[0]).bind('click.DT', { action: "previous" }, fnClickHandler); $(els[1]).bind('click.DT', { action: "next" }, fnClickHandler); }, "fnUpdate": function(oSettings, fnDraw) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, ien, j, sClass, iStart, iEnd, iHalf = Math.floor(iListLength / 2); if (oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if (oPaging.iPage <= iHalf) { iStart = 1; iEnd = iListLength; } else if (oPaging.iPage >= (oPaging.iTotalPages - iHalf)) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for (i = 0, ien = an.length; i < ien; i++) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for (j = iStart; j <= iEnd; j++) { sClass = (j == oPaging.iPage + 1) ? 'class="active"' : ''; $('<li ' + sClass + '><a href="#">' + j + '</a></li>') .insertBefore($('li:last', an[i])[0]) .bind('click', function(e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(), 10) - 1) * oPaging.iLength; fnDraw(oSettings); }); } // Add / remove disabled classes from the static elements if (oPaging.iPage === 0) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if (oPaging.iPage === oPaging.iTotalPages - 1 || oPaging.iTotalPages === 0) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } }); } /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ($.fn.DataTable.TableTools) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend(true, $.fn.DataTable.TableTools.classes, { "container": "DTTT btn-group", "buttons": { "normal": "btn btn-default", "disabled": "disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "DTTT_print_info modal" }, "select": { "row": "active" } }); // Have the collection use a bootstrap compatible dropdown $.extend(true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } }); }
function downloadCSV(csv, filename) { var csvFile; var downloadLink; // CSV file csvFile = new Blob([csv], {type: "text/csv"}); // Download link downloadLink = document.createElement("a"); // File name downloadLink.download = filename; // Create a link to the file downloadLink.href = window.URL.createObjectURL(csvFile); // Hide download link downloadLink.style.display = "none"; // Add the link to DOM document.body.appendChild(downloadLink); // Click download link downloadLink.click(); } function exportReview(category, tableid, filename) { var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var d = new Date(); var month = monthNames[d.getMonth()]; var year = d.getFullYear(); var csv = []; var rows = $(tableid).find("tbody tr:visible"); var header1 = ["Monthly Review of "+category,"","","","Month: "+month,"Year:"+year] var header2 = ["Property: Ascott Raffles Place Singapore"]//Property is hard coded for now var header3 = ["","","","","",""]; var header4 = ["Name","","Unit","Unit Price","Initial quantity","In","Value(In)","Out","Value(Out)","Remaining quantity"]; csv.push(header1.join(",")); csv.push(header2); csv.push(header3.join(",")); csv.push(header4.join(",")); for (var i = 0; i < rows.length; i++) { var row = [], cols = rows[i].querySelectorAll("td, th"); for (var j = 0; j < cols.length; j++) row.push(cols[j].innerText); csv.push(row.join(",")); } // Download CSV file downloadCSV(csv.join("\n"), filename); } function exportLogs(tableid, filename) { var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var d = new Date(); var month = monthNames[d.getMonth()]; var year = d.getFullYear(); var header1 = ["Logs in current month","","","","","","Month: "+month,"Year:"+year]; var header2 = ["Property: Ascott Raffles Place Singapore"];//Property is hard coded for now var header3 = ["","","","","",""]; var header4 = ["Date-Time","User","Item","Category","In/Out","Quantity change","Quantity remaining","Location"]; var csv = []; var rows = $(tableid).find("tbody tr:visible"); csv.push(header1) csv.push(header2) csv.push(header3.join(",")); csv.push(header4.join(",")); for (var i = 0; i < rows.length; i++) { var row = [], cols = rows[i].querySelectorAll("td,th"); for (var j = 0; j < cols.length; j++) row.push(cols[j].innerText); csv.push(row.join(",")); } // Download CSV file downloadCSV(csv.join("\n"), filename); }
import invariant from 'invariant' import { PUSH, POP } from './Actions' import { canUseDOM } from './ExecutionEnvironment' import { addEventListener, removeEventListener, getWindowPath, supportsHistory } from './DOMUtils' import { saveState, readState } from './DOMStateStorage' import createDOMHistory from './createDOMHistory' import createLocation from './createLocation' /** * Creates and returns a history object that uses HTML5's history API * (pushState, replaceState, and the popstate event) to manage history. * This is the recommended method of managing history in browsers because * it provides the cleanest URLs. * * Note: In browsers that do not support the HTML5 history API full * page reloads will be used to preserve URLs. */ function createBrowserHistory(options) { invariant( canUseDOM, 'Browser history needs a DOM' ) let isSupported = supportsHistory() function getCurrentLocation(historyState) { historyState = historyState || window.history.state || {} let path = getWindowPath() let { key } = historyState let state if (key) { state = readState(key) } else { state = null key = history.createKey() window.history.replaceState({ ...historyState, key }, null, path) } return createLocation(path, state, undefined, key) } function startPopStateListener({ transitionTo }) { function popStateListener(event) { if (event.state === undefined) return // Ignore extraneous popstate events in WebKit. transitionTo( getCurrentLocation(event.state) ) } addEventListener(window, 'popstate', popStateListener) return function () { removeEventListener(window, 'popstate', popStateListener) } } function finishTransition(location) { let { basename, pathname, search, state, action, key } = location if (action === POP) return // Nothing to do. saveState(key, state) let path = (basename || '') + pathname + search let historyState = { key } if (action === PUSH) { if (isSupported) { window.history.pushState(historyState, null, path) } else { window.location.href = path // Use page reload to preserve the URL. } } else { // REPLACE if (isSupported) { window.history.replaceState(historyState, null, path) } else { window.location.replace(path) // Use page reload to preserve the URL. } } } let history = createDOMHistory({ ...options, getCurrentLocation, finishTransition, saveState }) let listenerCount = 0, stopPopStateListener function listen(listener) { if (++listenerCount === 1) stopPopStateListener = startPopStateListener(history) let unlisten = history.listen(listener) return function () { unlisten() if (--listenerCount === 0) stopPopStateListener() } } return { ...history, listen } } export default createBrowserHistory
'use strict'; angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles', 'Socket', function($scope, $stateParams, $location, Authentication, Articles, Socket) { Socket.on('article.created', function(article) { console.log(article); }); $scope.authentication = Authentication; $scope.create = function() { var article = new Articles({ title: this.title, content: this.content }); article.$save(function(response) { $location.path('articles/' + response._id); $scope.title = ''; $scope.content = ''; }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.remove = function(article) { if (article) { article.$remove(); for (var i in $scope.articles) { if ($scope.articles[i] === article) { $scope.articles.splice(i, 1); } } } else { $scope.article.$remove(function() { $location.path('articles'); }); } }; $scope.update = function() { var article = $scope.article; article.$update(function() { $location.path('articles/' + article._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.find = function() { $scope.articles = Articles.query(); }; $scope.findOne = function() { $scope.article = Articles.get({ articleId: $stateParams.articleId }); }; } ]);
const defaults = require("./defaults.js") const Render = require("./render.js") const Style = require("./style.js") let counter = 0 const Factory = function (paramsArr) { const _configKey = Symbol.config let header = [] const body = [] let footer = [] let options = {} // handle different parameter scenarios switch (true) { // header, rows, footer, and options case (paramsArr.length === 4): header = paramsArr[0] body.push(...paramsArr[1]) // creates new array to store our rows (body) footer = paramsArr[2] options = paramsArr[3] break // header, rows, footer case (paramsArr.length === 3 && paramsArr[2] instanceof Array): header = paramsArr[0] body.push(...paramsArr[1]) // creates new array to store our rows footer = paramsArr[2] break // header, rows, options case (paramsArr.length === 3 && typeof paramsArr[2] === "object"): header = paramsArr[0] body.push(...paramsArr[1]) // creates new array to store our rows options = paramsArr[2] break // header, rows (rows, footer is not an option) case (paramsArr.length === 2 && paramsArr[1] instanceof Array): header = paramsArr[0] body.push(...paramsArr[1]) // creates new array to store our rows break // rows, options case (paramsArr.length === 2 && typeof paramsArr[1] === "object"): body.push(...paramsArr[0]) // creates new array to store our rows options = paramsArr[1] break // rows case (paramsArr.length === 1 && paramsArr[0] instanceof Array): body.push(...paramsArr[0]) break // adapter called: i.e. `require('tty-table')('automattic-cli')` case (paramsArr.length === 1 && typeof paramsArr[0] === "string"): return require(`../adapters/${paramsArr[0]}`) /* istanbul ignore next */ default: console.log("Error: Bad params. \nSee docs at github.com/tecfu/tty-table") process.exit() } // for "deep" copy, use JSON.parse const cloneddefaults = JSON.parse(JSON.stringify(defaults)) const config = Object.assign({}, cloneddefaults, options) // backfixes for shortened option names config.align = config.alignment || config.align config.headerAlign = config.headerAlignment || config.headerAlign // for truncate true is equivalent to empty string if (config.truncate === true) config.truncate = "" // if borderColor customized, color the border character set if (config.borderColor) { config.borderCharacters[config.borderStyle] = config.borderCharacters[config.borderStyle].map(function (obj) { Object.keys(obj).forEach(function (key) { obj[key] = Style.style(obj[key], config.borderColor) }) return obj }) } // save a copy for merging columnSettings into cell options config.columnSettings = header.slice(0) // header config.table.header = header // match header geometry with body array config.table.header = [config.table.header] // footer config.table.footer = footer // counting table enables fixed column widths for streams, // variable widths for multiple tables simulateously if (config.terminalAdapter !== true) { counter++ // fix columnwidths for streams } config.tableId = counter // create a new object with an Array prototype const tableObject = Object.create(body) // save configuration to new object tableObject[_configKey] = config /** * Add method to render table to a string * @returns {String} * @memberof Table * @example * ```js * let str = t1.render(); * console.log(str); //outputs table * ``` */ tableObject.render = function () { const output = Render.stringifyData(this[_configKey], this.slice(0)) // get string output tableObject.height = this[_configKey].height return output } return tableObject } const Table = function () { return new Factory(arguments) } Table.resetStyle = Style.resetStyle Table.style = Style.styleEachChar module.exports = Table
import { BaseClient, BaseResponse } from './base'; import { AbortError } from '../../utils'; class XHRResponse extends BaseResponse { /** * BaseResponse facade for XMLHttpRequest * @param {XMLHttpRequest} xhr * @param {ArrayBuffer} data */ constructor(xhr, data) { super(); this.xhr = xhr; this.data = data; } get status() { return this.xhr.status; } getHeader(name) { return this.xhr.getResponseHeader(name); } async getData() { return this.data; } } export class XHRClient extends BaseClient { constructRequest(headers, signal) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', this.url); xhr.responseType = 'arraybuffer'; for (const [key, value] of Object.entries(headers)) { xhr.setRequestHeader(key, value); } // hook signals xhr.onload = () => { const data = xhr.response; resolve(new XHRResponse(xhr, data)); }; xhr.onerror = reject; xhr.onabort = () => reject(new AbortError('Request aborted')); xhr.send(); if (signal) { if (signal.aborted) { xhr.abort(); } signal.addEventListener('abort', () => xhr.abort()); } }); } async request({ headers, signal } = {}) { const response = await this.constructRequest(headers, signal); return response; } }
import { nestedRowsFilter } from './nested-rows-filter' import { select } from 'd3-selection' import { wrap } from './wrap-row' export function createProcessRowData () { let cache let filters = [] let nestFriendlyFilters let skipRowLocking = false function processRowData (s) { s.each(processRowDataEach) } processRowData.filtersUse = function (filter) { filters.push(filter) return processRowData } processRowData.filters = function (v) { if (!arguments.length) return filters filters = v return processRowData } return processRowData function processRowDataEach (d, i) { nestFriendlyFilters = filters.map(nestedRowsFilter) if (!cache) cache = processRows(d, d.serverSideFilterAndSort) select(this).on('data-dirty.process-row-data', onDataDirty) d.rows = cache d.filters = nestFriendlyFilters } function processRows (d, skipFilters) { const rows = d.rows || d const rowGroups = group(rows, skipFilters, skipRowLocking, filter) const rowsTop = rowGroups.top const rowsFree = rowGroups.free const rowsBottom = rowGroups.bottom rowsTop.name = 'top' rowsFree.name = 'free' rowsBottom.name = 'bottom' let result = rowsTop.concat(rowsFree).concat(rowsBottom) result.top = rowsTop result.free = rowsFree result.bottom = rowsBottom result.hasNestedRows = rows.hasNestedRows return result function filter (d, i, a) { if (skipFilters) return true return nestFriendlyFilters.every(runFilter) function runFilter (f) { return f(d, i, a) } } } function onDataDirty () { cache = null } function group (rows, skipFilters, skipLock, filter) { const top = [] const bottom = [] const free = [] const out = [] let freeIndexShift = 0 if (skipFilters && skipLock) { return { top, bottom, free: rows, out } } rows.forEach(segregate) free.length = rows.length - (top.length + bottom.length + out.length) return { top, free, bottom, out } function segregate (originalRow, i) { if (!originalRow) return let row = wrap(originalRow) let locked = row.locked if (!skipFilters && !filter(row)) pluck(row, out) else if (!skipLock && locked === 'top') pluck(row, top) else if (!skipLock && locked === 'bottom') pluck(row, bottom) else free[i + freeIndexShift] = row function pluck (row, target) { target.push(row) freeIndexShift-- } } } }
import AppDispatcher from "../dispatcher/AppDispatcher.js" import {EventEmitter} from "events" import React from "react" import assign from "object-assign" import <NAME>constants from "../constants/<>constants.js" const ActionTypes = <NAME>constants.ActionTypes let _store = {} const <NAME>Store = assign({}, EventEmitter.prototype, { getSOMETHING: function() { return _store.something; }, emitChange: function() { this.emit('change'); }, addChangeListener: function(callback) { this.on('change', callback); }, removeChangeListener: function(callback) { this.removeListener('change', callback); } }) AppDispatcher.register(function(action) { // var text; // Define what to do for certain actions console.log(action.data); switch(action.type) { case ActionTypes.ACTIONNAME: someAction(action.data); break; default: return true; } // If action was acted upon, emit change event <NAME>Store.emitChange(); return true; }) export default <NAME>Store
'use strict'; /* Query Comments Controller */ mftApp.controller('CommentIndexCtrl', ['$scope', '$resource', 'Comment', '$routeParams', '$route', '$location', '$filter', function($scope, $resource, Comment, $routeParams, $route, $location, $filter) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; $scope.params = $routeParams; $scope.dateFormat = new Date().getTime(); //'M/d/yy h:mm:ss a'; $scope.commentList = Comment.get({id: $routeParams.id}); //Save Comments; POST to DB $scope.save = function() { Comment.post({id:$routeParams.id, CURRENT_USER:'aaron@bigcompass.com', COMMENT_FEED:$scope.commentList.results.COMMENT_FEED}, $scope.commentList, function() { $scope.commentList.results.COMMENT_FEED = ""; $route.reload(); console.log("saved!"); }, function() { $scope.commentList.results.COMMENT_FEED = ""; console.log("error"); }); }; } ]);
define(function () { var service_debug = true; var app = angular.module('webApp', ['ui.router']); var load = function (files) { return { load: ["$q", function ($q) { var delay = $q.defer(); require(files, function () { delay.resolve(); }); return delay.promise; }] }; } app.config(function ($stateProvider, $urlRouterProvider, $controllerProvider, $compileProvider, $filterProvider, $provide) { app.register = { controller: $controllerProvider.register, directive: $compileProvider.directive, filter: $filterProvider.register, service: $provide.service }; $stateProvider .state('dashboard', { url: '/', title: '控制面板', views: { "content": { controller: 'dashboardCtrl', templateUrl: 'views/dashboard/dashboard.html' } }, resolve: load(['../services/userService', '../views/dashboard/dashboard']) }) .state('table', { url: '/table', title: '用户列表', views: { "content": { controller: 'tableCtrl', templateUrl: 'views/table/table.html' } }, resolve: load(['../services/userService', '../views/table/table']) }) .state('table.create', { parene: 'table', url: '/create', title: '添加新用户', params: { subtitle: '' }, views: { "content": { controller: 'formCreateCtrl', templateUrl: 'views/form/create.html' } }, resolve: load(['../services/userService', '../views/form/create']) }) .state('table.edit', { parene: 'table', url: '/edit/{id}', title: '编辑用户信息', params: { subtitle: '', user: { number: '111111', name: '张一', mobile: '13485728901', gender: 1, birthday: '2000-7-7', like: {football: true, pingpong: true} } }, views: { "content": { controller: 'formEditCtrl', templateUrl: 'views/form/edit.html' } }, resolve: load(['../services/userService', '../views/form/edit']) }) .state('form_create', { url: '/form/create', title: '添加表单示例', params: { subtitle: '', user: {} }, views: { "content": { controller: 'formCreateCtrl', templateUrl: 'views/form/create.html' } }, resolve: load(['../services/userService', '../views/form/create']) }) .state('form_edit', { url: '/form/edit/{id}', title: '修改表单示例', views: { "content": { controller: 'formEditCtrl', templateUrl: 'views/form/edit.html' } }, resolve: load(['../services/userService', '../views/form/edit']) }) $urlRouterProvider.otherwise('/'); }) .run(function ($rootScope,$timeout) { // 回退按钮 $rootScope.goBack = function () { window.history.back(); }; // 消息通知 $rootScope.notify = function (message, type) { //type: error, success, info var humane = require('humane'); humane.log(message, {timeout: 3000, clickToClose: true, addnCls: 'humane-' + type}); }; $rootScope.alert = function (message) { var bootbox = require('bootbox'); bootbox.alert( { size: 'small', message: message } ); }; $rootScope.prompt = function (message, callback) { var bootbox = require('bootbox'); bootbox.prompt( { size: 'small', message: message, callback: callback } ); }; $rootScope.confirm = function (message, callback) { var bootbox = require('bootbox'); bootbox.confirm( { size: 'small', message: message, callback: callback } ); }; $rootScope.dialog = function (options) { var bootbox = require('bootbox'); bootbox.dialog(options); }; // 状态变化时刷新title $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) { $rootScope.title = toState.title; }); // bootstrap-table初始化设置 $rootScope.setTable = function (url, columns, toolbar, options) { var defaults = { cache: false, striped: true, mobileResponsive: true, pageSize: 10, pageList: [10, 50, 100], search: true, minimumCountColumns: 2, clickToSelect: false, maintainSelected: true, //tools showColumns: true, showRefresh: true, showExport: true, showToggle: true, searchPlaceholder:'搜索', //page pagination: true, sidePagination: 'server', idField: 'id', dataField: 'data', sortName: "id", sortOrder: "desc", url: url, columns: columns, toolbar: toolbar, //editable editableEmptytext: '未填写', editableMethod: "PUT", editableUrl: url } options = $.extend({}, defaults, options); return { options: options } } //select2设置 $rootScope.setSelect = function ($el, resource, options) { var defaults; if (typeof (resource) == 'string') { defaults = { ajax: { url: resource, dataType: 'json', delay: 250, data: function (params) { return { query: params.term, page: params.page, per_page: 10 }; }, processResults: function (data, params) { params.page = params.page || 1; return { results: data.data, pagination: { more: (params.page * 10) < data.total_count } }; }, cache: true }, minimumInputLength: 0 }; }else{ defaults = { data: resource } } options = $.extend({}, defaults, options); $timeout(function () { $el.select2(options); }, 50); } }) .factory('baseService', function ($http, $q) { return { // 错误响应 errorMsg: function (error) { var msg = { message: '', status: error.status, errors: [] } switch (error.status) { case 401: msg.message = '您的登录已超时,请重新登录'; break; case 403: msg.message = '您无权进行该操作'; break; case 404: msg.message = 'api地址或参数不正确'; break; case 422: msg.message = '输入参数不正确'; msg.errors = error.data.errors; break; default: msg.message = error.data.message; } this.debug(error); return msg; }, debug: function (rs) { if (service_debug) { if (rs.status >= 300) { console.group(rs.config.method + ' ' + rs.config.url); console.warn(rs.status); console.warn(rs.data); } else { console.groupCollapsed(rs.config.method + ' ' + rs.config.url); console.info(rs.data); } console.groupEnd(); } }, get: function (url, params) { var delay = $q.defer(), that = this, settings = {}; if (typeof (params) != 'undefined') { settings = {params: params} } $http.get(url, settings) .then(function (result) { that.debug(result); delay.resolve(result.data); }, function (error) { delay.reject(that.errorMsg(error)); }); return delay.promise; }, post: function (url, params) { var delay = $q.defer(), that = this; var form_config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, transformRequest: function (data) { if (!angular.isObject(data)) { return ((data == null) ? "" : data.toString()); } var buffer = []; for (var p in data) { if (!data.hasOwnProperty(p)) continue; buffer.push(encodeURIComponent(p) + "=" + encodeURIComponent((data[p] == null) ? "" : data[p])); } return buffer.join("&").replace(/%20/g, "+"); } } //remove last / url = url.replace(/\/+$/, ''); $http.post(url, params, form_config) .then(function (result) { that.debug(result); delay.resolve(result.data); }, function (error) { delay.reject(that.errorMsg(error)); }); return delay.promise; }, // 更新 put: function (url, params) { var delay = $q.defer(), that = this; $http.put(url, params) .then(function (result) { that.debug(result); delay.resolve(result.data); }, function (error) { delay.reject(that.errorMsg(error)); }); return delay.promise; }, // 删除 del: function (url) { var delay = $q.defer(), that = this; //ie8 fix $http.delete error $http['delete'](url) .then(function (result) { that.debug(result); delay.resolve(result.data); }, function (error) { delay.reject(that.errorMsg(error)); }); return delay.promise; } }; }) .directive('ngInput', function () { return { restrict: 'A', require: 'ngModel', link: function (scope, element, attrs, ngModel) { var el = $(element); el.bind('change', function () { scope.$apply(changeModel); }); function changeModel() { ngModel.$setViewValue(el.val()); ngModel.$render(); } } } }) .directive('bsTableControl', function ($timeout) { var CONTAINER_SELECTOR = '.bootstrap-table'; var SCROLLABLE_SELECTOR = '.fixed-table-body'; var SEARCH_SELECTOR = '.search input'; var bsTables = {}; function getBsTable(el) { var result; $.each(bsTables, function (id, bsTable) { if (!bsTable.$el.closest(CONTAINER_SELECTOR).has(el).length) return; result = bsTable; return true; }); return result; } $(window).resize(function () { $.each(bsTables, function (id, bsTable) { bsTable.$el.bootstrapTable('resetView'); }); }); $(document) .on('post-header.bs.table', CONTAINER_SELECTOR + ' table', function (evt) { // bootstrap-table calls .off('scroll') in initHeader so reattach here var bsTable = getBsTable(evt.target); if (!bsTable) return; bsTable.$el .closest(CONTAINER_SELECTOR) .find(SCROLLABLE_SELECTOR) .on('scroll', function () { var state = bsTable.$s.bsTableControl.state; bsTable.$s.$applyAsync(function () { state.scroll = bsTable.$el.bootstrapTable('getScrollPosition'); }); }); }) .on('sort.bs.table', CONTAINER_SELECTOR + ' table', function (evt, sortName, sortOrder) { var bsTable = getBsTable(evt.target); if (!bsTable) return; var state = bsTable.$s.bsTableControl.state; bsTable.$s.$applyAsync(function () { state.sortName = sortName; state.sortOrder = sortOrder; }); }) .on('page-change.bs.table', CONTAINER_SELECTOR + ' table', function (evt, pageNumber, pageSize) { var bsTable = getBsTable(evt.target); if (!bsTable) return; var state = bsTable.$s.bsTableControl.state; bsTable.$s.$applyAsync(function () { state.pageNumber = pageNumber; state.pageSize = pageSize; }); }) .on('search.bs.table', CONTAINER_SELECTOR + ' table', function (evt, searchText) { var bsTable = getBsTable(evt.target); if (!bsTable) return; var state = bsTable.$s.bsTableControl.state; bsTable.$s.$applyAsync(function () { state.searchText = searchText; }); }) .on('load-success.bs.table load-error.bs.table', CONTAINER_SELECTOR + ' table', function (evt) { var bsTable = getBsTable(evt.target); if (!bsTable) return; var state = bsTable.$s.bsTableControl.state; bsTable.$s.$applyAsync(function () { state.selected = []; }); }) .on('check.bs.table uncheck.bs.table check-all.bs.table uncheck-all.bs.table', CONTAINER_SELECTOR + ' table', function (evt) { var bsTable = getBsTable(evt.target); if (!bsTable) return; var state = bsTable.$s.bsTableControl.state; var selected = []; $.map(bsTable.$el.bootstrapTable('getSelections'), function (row) { selected.push(row.id); }); bsTable.$s.$applyAsync(function () { state.selected = selected; }); }) .on('focus blur', CONTAINER_SELECTOR + ' ' + SEARCH_SELECTOR, function (evt) { var bsTable = getBsTable(evt.target); if (!bsTable) return; var state = bsTable.$s.bsTableControl.state; bsTable.$s.$applyAsync(function () { state.searchHasFocus = $(evt.target).is(':focus'); }); }); return { restrict: 'EA', scope: {bsTableControl: '='}, link: function ($s, el) { $el = $(el); if (!$s.$applyAsync) { $s.$applyAsync = function (expr) { var scope = this; $timeout(function () { scope.$eval(expr); }, 20); } } $s.bsTableControl.$el = $el; $s.bsTableControl.call = function (method, params) { $el.bootstrapTable(method, params); } var bsTable = bsTables[$s.$id] = {$s: $s, $el: $el}; $s.instantiated = false; $s.$watch('bsTableControl.options', function (options) { if (!options) options = $s.bsTableControl.options = {}; var state = $s.bsTableControl.state || {}; if ($s.instantiated) $el.bootstrapTable('destroy'); $el.bootstrapTable(angular.extend(angular.copy(options), state)); $s.instantiated = true; // Update the UI for state that isn't settable via options if ('scroll' in state) $el.bootstrapTable('scrollTo', state.scroll); if ('searchHasFocus' in state) $el.closest(CONTAINER_SELECTOR).find(SEARCH_SELECTOR).focus(); // $el gets detached so have to recompute whole chain }, true); $s.$watch('bsTableControl.state', function (state) { if (!state) state = $s.bsTableControl.state = {}; $el.trigger('directive-updated.bs.table', [state]); }, true); $s.$on('$destroy', function () { delete bsTables[$s.$id]; }); } }; }); return app; })
import {capitalize} from "lodash"; import {sendSuccess} from "./jsend"; export default function getAll(req, res, next) { // Get the model const model = this.model(capitalize(req.params.type)); // Check to see that the model type requested, exists if (!model) { const error = new Error("Specified type doesn't exist"); error.statusCode = 400; return next(error); } model.find().exec() .then(function(models) { sendSuccess(res, models); }) .catch(function(err) { return next(err); }); }
// -------------- // resizing logic // -------------- $(window).resize(function() { // affects document height, in document flow: resize first. $('#left').css({ width: $('#name').height() }); $('#me').css({ height: $('#left').height() + parseInt($('#left').css('padding-top')) }); // not in document flow, dependent on positions; do last $('#credit_bg').css({ height: $('#credit_contents').height(), width: $('#credit_contents').width(), left: $('#credit_contents').offset().left, top: $('#credit_contents').offset().top }); $('#shade').css({ height: $('body').height() }); $('#logo_stripe').css({ top: $('#logo_pane').position().top, height: $('#logo_pane').outerHeight() }); }); $(document).ready(function() { $('img').each(function(index, elem) { $(elem).load(function() { $(window).resize(); }); }); }); $(window).load(function() { $(window).resize(); }); // credit: Drew Baker, bit.ly/1fcLElK // replace img-tagged svgs with the same svg's inlined. // Allows manipulation of svg's on the DOM, does not dispatch new requests // since they should be cached. function inline_all_svg_img() { $('.service_img').each(function(index, elem) { elem = $(elem); var img_id = elem.attr('id'); var img_class = elem.attr('class'); var img_url = elem.attr('src'); $.get(img_url, function(data) { // Get the SVG tag, ignore the rest var svg = $(data).find('svg'); // Add replaced image's ID to the new SVG if (typeof img_id !== 'undefined') { svg = svg.attr('id', img_id); } // Add replaced image's classes to the new SVG if (typeof img_class !== 'undefined') { svg = svg.attr('class', img_class); } // Remove any invalid XML tags as per http://validator.w3.org svg = svg.removeAttr('xmlns:a'); // Replace image with new SVG elem.replaceWith(svg); }, 'xml'); }); } function add_randomized_link_listeners() { $('.randomized').each(function(index, elem) { $(elem).on('click', function(e) { e.preventDefault(); var url = $(this).prop('href'); window.location.href = url.split('?')[0]; }); }); } // -------------------- // initialization logic // -------------------- $(document).ready(function() { if (Modernizr.svg) { inline_all_svg_img(); } add_randomized_link_listeners(); }); // ----------------- // Highlighter class // ----------------- // Requires jquery-color for svg highlighting // Add to application js: // jQuery.Color.hook('fill stroke'); var Highlighter = function(svg) { var svg_enabled = svg; var types = ['fill', 'stroke']; var normal_color = '#FFF'; var highlight_color = '#FF6D00'; var animation_speed = 200; var cache = {}; types.forEach(function(type, index, arr) { cache[type] = []; }); // for fallback to pngs var highlight_png = function(service, id, highlight) { var img_path = '/img/service/' + service; if (highlight) { img_path += '-hl'; } img_path += '.png'; $(elem).attr('data', img_path); }; // (un)highlights a particular svg element var update_svg_elem = function(elem, type, highlight) { var color = normal_color; if (highlight) { color = highlight_color; } var change = {}; change[type] = color; $(elem).animate(change, animation_speed); }; // finds all svgs to (un)highlight for a service, and executes var highlight_svg = function(service, elem, highlight) { var svg_elem = $(elem).get()[0].contentDocument; types.forEach(function(type, index, arr) { if (cache[type][service] !== undefined) { cache[type][service].forEach(function(elem, index, arr) { update_svg_elem(elem, type, highlight); }); } else { cache[type][service] = []; $(svg_elem).find('*[' + type + ']').each(function(index, elem) { // cache cache[type][service].push(elem); // act update_svg_elem(elem, type, highlight); }); } }); }; /** * Highlights a service button * @param {string} service * @param {bool} highlight */ this.highlight_service = function(service, highlight) { var elem = $('#' + service + '-btn'); var src = elem.attr('data'); var type = $(elem).attr('type'); if (type === undefined) return; if (type === 'image/svg+xml') { if (svg_enabled) { highlight_svg(service, elem, highlight); } } else if (type === 'image/png') { highlight_png(service, elem, highlight); } }; }; // turn svg highlighting off, since it's being displayed inline highlighter = new Highlighter(false);
/*! * zepto.fullpage.js v0.5.0 (https://github.com/yanhaijing/zepto.fullpage) * API https://github.com/yanhaijing/zepto.fullpage/blob/master/doc/api.md * Copyright 2014 yanhaijing. All Rights Reserved * Licensed under MIT (https://github.com/yanhaijing/zepto.fullpage/blob/master/LICENSE) */ (function($, window, undefined) { if (typeof $ === 'undefined') { throw new Error('zepto.fullpage\'s script requires Zepto'); } var fullpage = null; var d = { page: '.page', start: 0, duration: 500, loop: false, drag: false, dir: 'v', der: 0.1, change: function(data) {}, beforeChange: function(data) {}, afterChange: function(data) {}, orientationchange: function(orientation) {} }; function touchmove(e) { e.preventDefault(); } function fix(cur, pagesLength, loop) { if (cur < 0) { return !!loop ? pagesLength - 1 : 0; } if (cur >= pagesLength) { return !!loop ? 0 : pagesLength - 1; } return cur; } function move($ele, dir, dist) { var xPx = '0px', yPx = '0px'; if(dir === 'v') yPx = dist + 'px'; else xPx = dist + 'px'; $ele.css({ '-webkit-transform' : 'translate3d(' + xPx + ', ' + yPx + ', 0px);', 'transform' : 'translate3d(' + xPx + ', ' + yPx + ', 0px);' }); } function Fullpage($this, option) { var o = $.extend(true, {}, d, option); this.$this = $this; this.curIndex = -1; this.o = o; this.startY = 0; this.movingFlag = false; this.$this.addClass('fullPage-wp'); this.$parent = this.$this.parent(); this.$pages = this.$this.find(o.page).addClass('fullPage-page fullPage-dir-' + o.dir); this.pagesLength = this.$pages.length; this.update(); this.initEvent(); this.start(); } $.extend(Fullpage.prototype, { update: function() { if (this.o.dir === 'h') { this.width = this.$parent.width(); this.$pages.width(this.width); this.$this.width(this.width * this.pagesLength); } this.height = this.$parent.height(); this.$pages.height(this.height); this.moveTo(this.curIndex < 0 ? this.o.start : this.curIndex); }, initEvent: function() { var that = this; var $this = this.$this; $this.on('touchstart', function(e) { if (!that.status) {return 1;} //e.preventDefault(); if (that.movingFlag) { return 0; } that.startX = e.targetTouches[0].pageX; that.startY = e.targetTouches[0].pageY; }); $this.on('touchend', function(e) { if (!that.status) {return 1;} //e.preventDefault(); if (that.movingFlag) { return 0; } var sub = that.o.dir === 'v' ? (e.changedTouches[0].pageY - that.startY) / that.height : (e.changedTouches[0].pageX - that.startX) / that.width; var der = (sub > that.o.der || sub < -that.o.der) ? sub > 0 ? -1 : 1 : 0; that.moveTo(that.curIndex + der, true); }); if (that.o.drag) { $this.on('touchmove', function(e) { if (!that.status) {return 1;} //e.preventDefault(); if (that.movingFlag) { that.startX = e.targetTouches[0].pageX; that.startY = e.targetTouches[0].pageY; return 0; } var y = e.changedTouches[0].pageY - that.startY; if( (that.curIndex == 0 && y > 0) || (that.curIndex === that.pagesLength - 1 && y < 0) ) y /= 2; var x = e.changedTouches[0].pageX - that.startX; if( (that.curIndex == 0 && x > 0) || (that.curIndex === that.pagesLength - 1 && x < 0) ) x /= 2; var dist = (that.o.dir === 'v' ? (-that.curIndex * that.height + y) : (-that.curIndex * that.width + x)); $this.removeClass('anim'); move($this, that.o.dir, dist); }); } // 翻转屏幕提示 // ============================== window.addEventListener('orientationchange', function() { if (window.orientation === 180 || window.orientation === 0) { that.o.orientationchange('portrait'); } if (window.orientation === 90 || window.orientation === -90) { that.o.orientationchange('landscape'); } }, false); window.addEventListener('resize', function() { that.update(); }, false); }, holdTouch: function() { $(document).on('touchmove', touchmove); }, unholdTouch: function() { $(document).off('touchmove', touchmove); }, start: function() { this.status = 1; this.holdTouch(); }, stop: function() { this.status = 0; this.unholdTouch(); }, moveTo: function(next, anim) { var that = this; var $this = this.$this; var cur = this.curIndex; next = fix(next, this.pagesLength, this.o.loop); if (anim) { $this.addClass('anim'); } else { $this.removeClass('anim'); } if (next !== cur) { var flag = this.o.beforeChange({ next: next, cur: cur }); // beforeChange 显示返回false 可阻止滚屏的发生 if (flag === false) { return 1; } } this.movingFlag = true; this.curIndex = next; move($this, this.o.dir, -next * (this.o.dir === 'v' ? this.height : this.width)); if (next !== cur) { this.o.change({ prev: cur, cur: next }); } window.setTimeout(function() { that.movingFlag = false; if (next !== cur) { that.o.afterChange({ prev: cur, cur: next }); that.$pages.removeClass('cur').eq(next).addClass('cur'); } }, that.o.duration); return 0; }, movePrev: function(anim) { this.moveTo(this.curIndex - 1, anim); }, moveNext: function(anim) { this.moveTo(this.curIndex + 1, anim); }, getCurIndex: function () { return this.curIndex; }, destroy: function () { fullpage = null } }); $.fn.fullpage = function(option) { if (!fullpage) { fullpage = new Fullpage($(this), option); } return this; }; $.fn.fullpage.version = '0.5.0'; //暴露方法 $.each(['update', 'moveTo', 'moveNext', 'movePrev', 'start', 'stop', 'getCurIndex', 'holdTouch', 'unholdTouch', 'destroy'], function(key, val) { $.fn.fullpage[val] = function() { if (!fullpage) { return 0; } return fullpage[val].apply(fullpage, arguments); }; }); }(Zepto, window));
import React, { Component } from "react"; import { Dimensions, DrawerLayoutAndroid, View } from "react-native"; import { connect } from "react-redux"; import { styles } from "../styles.android"; import MenuLayout from "./Menu"; import MapLayout from "./Map"; const { width } = Dimensions.get('window'); export class MainLayout extends Component { constructor(props) { super(props); this.state = { drawerReducer: { instance: null, visible: false, } }; this.showDrawer = this.showDrawer.bind(this); this.hideDrawer = this.hideDrawer.bind(this); } componentWillReceiveProps(nextProps) { if (nextProps.drawerReducer && nextProps.drawerReducer !== this.state.drawerReducer) { this.setState({ drawer: Object.assign({}, this.state.drawerReducer, nextProps.drawerReducer), }); if (nextProps.drawerReducer.visible) { this.showDrawer(); } else { this.hideDrawer(); } } } showDrawer() { this.state.drawerReducer.instance.openDrawer(); } hideDrawer() { this.state.drawerReducer.instance.closeDrawer(); } render() { return ( <View style={styles.mainLayout}> <DrawerLayoutAndroid style={styles.AppContainer} ref={(drawer) => this.state.drawerReducer.instance = drawer} drawerWidth={width - (width / 5)} renderNavigationView={() => <MenuLayout/>}> <View style={{flex: 1, alignItems: 'center'}}> <MapLayout /> </View> </DrawerLayoutAndroid> </View> ); } } /* istanbul ignore next */ function mapStateToProps(state) { return { drawerReducer: state.drawerReducer, } } /* istanbul ignore next */ function mapDispatchToProps(dispatch) { return { }; } export default connect( mapStateToProps, mapDispatchToProps )(MainLayout);
'use strict'; /* * Defining the Package */ var Module = require('meanio').Module; var Articles = new Module('articles'); /* * All MEAN packages require registration * Dependency injection is used to define required modules */ Articles.register(function(app, auth, database, circles) { //We enable routing. By default the Package Object is passed to the routes Articles.routes(app, auth, database, circles); //We are adding a link to the main menu for all authenticated users Articles.menus.add({ title: 'View Articles', link: 'articles example page', roles: ['authenticated'], //anonymous menu: 'main' }); /** //Uncomment to use. Requires meanio@0.3.7 or above // Save settings with callback // Use this for saving data from administration pages Articles.settings({ 'someSetting': 'some value' }, function(err, settings) { //you now have the settings object }); // Another save settings example this time with no callback // This writes over the last settings. Articles.settings({ 'anotherSettings': 'some value' }); // Get settings. Retrieves latest saved settigns Articles.settings(function(err, settings) { //you now have the settings object }); */ return Articles; });
'use strict'; recipesApp.controller('AddRecipeController', function AddRecipeController($scope, $compile, $location, dataFetcher) { dataFetcher.getCategories.all().then(function(data){ $scope.$apply(function () { $scope.categories = data; }); }); var minutesArr = []; for (var i = 1; i <= 36; i++) { minutesArr.push(i*5); } $scope.minutes=minutesArr; $scope.products = ['']; $scope.directions = ['']; $scope.addProduct = function() { $scope.products.push(''); angular.element('#add-recepie-input-products') .append( $compile('<input type="text" class="form-control" ng-model="products['+ ($scope.products.length - 1) +']"/>')($scope) ); }; $scope.addDirection = function() { $scope.directions.push(''); angular.element('#add-recepie-input-directions') .append( $compile('<input type="text" class="form-control" ng-model="directions['+ ($scope.directions.length - 1) +']"/>')($scope) ); }; $scope.saveRecipe = function(recipe, invalidForm) { var i; if (invalidForm) { alert('Invalid recipe info!'); return; } // check for empty products or steps for (i = 0; i < $scope.products.length; i+=1) { if ($scope.products[i] === '') { $scope.products.splice(i,1); } } for (i = 0; i < $scope.directions.length; i+=1) { if ($scope.directions[i] === '') { $scope.directions.splice(i,1); } } recipe.Products = $scope.products; recipe.Directions = $scope.directions; dataFetcher.create.recipe(recipe, function() { alert('Recipe successfully created!'); }, function() { alert('Error - try again later!'); }); $location.path("/home" ); }; $scope.cancelEdit = function() { $location.path("/home" ); } });
/** * Browserjs.js : Browserjs * * @author Adnan M.Sagar, PhD. <adnan@websemantics.io> * @copyright 2002-2016 Web Semantics, Inc. (http://websemantics.io) * @license http://www.opensource.org/licenses/mit-license.php * @link http://oeasvg.com/browserjs * @since 9th August 2002 -> 27th Sept 2005 -> 4th May 2015 * @package websemantics/browserjs/mathml */ Browserjs.prototype = new Node(); function Browserjs() { var argv = Browserjs.arguments; var argc = Browserjs.length; var xhtmlNS = "http://www.w3.org/1999/xhtml"; /* String */ this.className = "Browserjs"; /* Vector */ this.documents = new Vector(); this.parse = function() { // Summary: // Parse the document for XHTML/MathML and SVG fragments /* NodeList */ nl = svgDocument.getElementsByTagNameNS(xhtmlNS, "html"); for (var i = 0; i < nl.length; i++) { var root = nl.item(i); // Add the default CSS style on the html element. var attr = new Attributes(root, true); root.setAttribute('style', attr.getStyle()); this.documents.addElement(new Browserjs.Document(root, this)); // var CSSParser = new Css.Parser(root); // var style = root.getElementsByTagName("style").item(0); // //alert(style.parentNode+" == "+style.firstChild.data); // //alert(style.parentNode.hasChildNodes()); // var CSSParser = new Css.Parser(root); } this.paint(); this.recalc(); } this.draw = function( /* Graphics */ g) { this.paint(g); } this.paint = function( /* Graphics */ g) { // Summary: // Paint all documents var e = new Enumerator(this.documents); while (e.hasMoreElements()) e.nextElement().paint(g); } this.recalc = function() { // Summary: // Recalc all documents found embbeded inside the SVG document. var e = new Enumerator(this.documents); while (e.hasMoreElements()) e.nextElement().recalc(); } }
import React, { Component } from 'React' import { StyleSheet } from 'react-native'; import Spinner from 'react-native-spinkit'; const Loader = (props) => { return <Spinner isVisible={props.isVisible} type={"Pulse"} size={50} color={"red"} style={props.style} /> }; export default Loader;
import Store from '../Store'; import TreeSubscription, {Node} from '../TreeSubscription'; describe('TreeSubscription', () => { describe('Node', () => { it('creates child nodes', () => { const node = new Node([]); const newNode = node.createNode('test'); expect(newNode).toBeInstanceOf(Node); expect(newNode.selectorPath).toEqual(['test']); }); it('correctly reports having a child node', () => { const node = new Node([]); node.createNode('test'); expect(node.hasNode('test')).toBe(true); }); it('correctly reports not having a child node', () => { const node = new Node([]); node.createNode('test'); expect(node.hasNode('testing')).toBe(false); }); it('retrives a child node', () => { const node = new Node([]); node.createNode('test'); const child = node.get('test'); expect(child).toBeInstanceOf(Node); expect(child.selectorPath).toEqual(['test']); }); it('doesn\'t error when removing a subscriber that isn\'t subscribed', () => { const node = new Node([]); const subscriber = jest.fn(); node.removeSubscriber(subscriber); }); }); describe('TreeSubscription', () => { it('collects top-level selector', () => { const STATE = {}; const store = new Store({}); const tree = new TreeSubscription(store); const subscriber = jest.fn(); const selector = []; tree.subscribeSelector(selector, subscriber); const subscribers = tree.collectSubscribers([]); expect(subscribers).toEqual([subscriber]); }); it('collects nested selector', () => { const store = new Store({one: {two: {}}}); const tree = new TreeSubscription(store); const subscriber = jest.fn(); const selector = ['one', 'two']; tree.subscribeSelector(selector, subscriber); const subscribers = tree.collectSubscribers(['one', 'two']); expect(subscribers).toEqual([subscriber]); }); it('collects selectors nested beyond the selector', () => { const store = new Store({one: {two: {}}}); const tree = new TreeSubscription(store); const subscriber = jest.fn(); const selector = ['one', 'two']; tree.subscribeSelector(selector, subscriber); const subscribers = tree.collectSubscribers(['one']); expect(subscribers).toEqual([subscriber]); }); it('collects parent selectors', () => { const store = new Store({one: {two: {}}}); const tree = new TreeSubscription(store); const subscriber = jest.fn(); const selector = ['one']; tree.subscribeSelector(selector, subscriber); const subscribers = tree.collectSubscribers(['one', 'two', 'three']); expect(subscribers).toEqual([subscriber]); }); it('doesn\'t error if no selectors match', () => { const store = new Store(); const tree = new TreeSubscription(store); const subscribers = tree.collectSubscribers(['one']); expect(subscribers).toEqual([]); }); it('doesn\'t collect an unsubscribed selector', () => { const store = new Store(); const tree = new TreeSubscription(store); const subscriber = jest.fn(); tree.subscribeSelector(['one', 'two'], subscriber); tree.unsubscribeSelector(['one', 'two'], subscriber); const subscribers = tree.collectSubscribers(['one', 'two']); expect(subscribers).toEqual([]); }); it('doesn\'t error when removing a non-subscribed subscriber', () => { const store = new Store(); const tree = new TreeSubscription(store); const subscriber = jest.fn(); tree.unsubscribeSelector(['one'], subscriber); }); it('collects multiple subscribers', () => { const TWO_STATE = {}; const ONE_STATE = {two: TWO_STATE}; const store = new Store({one: ONE_STATE}); const tree = new TreeSubscription(store); const subscriber1 = jest.fn(); const selector1 = ['one']; const subscriber2 = jest.fn(); const selector2 = ['one', 'two']; tree.subscribeSelector(selector1, subscriber1); tree.subscribeSelector(selector2, subscriber2); const subscribers = tree.collectSubscribers(['one']); expect(subscribers).toEqual([subscriber1, subscriber2]); }); it('only collects a subscriber once per collection', () => { const TWO_STATE = {}; const ONE_STATE = {two: TWO_STATE}; const store = new Store({one: ONE_STATE}); const tree = new TreeSubscription(store); const subscriber = jest.fn(); const selector1 = ['one']; const selector2 = ['one', 'two']; tree.subscribeSelector(selector1, subscriber); tree.subscribeSelector(selector2, subscriber); const subscribers = tree.collectSubscribers(['one']); expect(subscribers).toEqual([subscriber]); }); }); });
/* * src/samples/components/SearchBox.js */ 'use strict'; var React = require('react'); var Components = { searchBox: require('../../components/SearchBox/React.SearchBox') }; module.exports = React.createClass({ getInitialState: function() { return { disabled: false, value: '' }; }, render: function() { return ( React.DOM.article( null, React.DOM.a( { href: '#', onClick: this.handleClick }, this.state.disabled ? 'enable' : 'disable' ), React.DOM.section( null, React.DOM.h2( null, 'SearchBox' ), React.createElement( Components.searchBox, { onChange: this.handleChange, disabled: this.state.disabled, value: this.state.value, onReset: this.handleReset, eventKey: 'sb', label: 'Search' } ) ) ) ); }, handleChange: function(eventKey, event) { var value = event.target.value; console.log('handleChange: ' + eventKey + '=' + value); this.setState({value: value}); }, handleReset: function(eventKey) { var value = ''; console.log('handleReset: ' + eventKey + '=' + value); this.setState({value: value}); }, handleClick: function(event) { event.preventDefault(); event.stopPropagation(); this.setState({disabled: !this.state.disabled}); } });
'use strict'; const _ = require('yyf-core'); const DI = require('yyf-di'); class ServiceManager extends DI { populate(instance) { const self = this; _.keys(Object.getPrototypeOf(instance)) .filter( key => !key.toString().indexOf('$')) .forEach( key => self.proxifyService(instance, key.substr(1))); return this; } set (name, instance, options) { this.populate(instance); return super.set(name, instance, options); } resolveService(service, args){ var instance = super.resolveService(service, args); this.populate(instance); return instance; } } module.exports = ServiceManager;
import moment from 'moment'; import { AKTUALNI_ROK } from '../../constants'; import { getTypKategorie } from '../../entities/rocniky/rocnikyReducer'; export const getStartovniCislaProTyp = ({ odstartovani, rok = AKTUALNI_ROK, typ, kategorie, ucastnici, }) => { const results = []; ucastnici.allIds.forEach((id) => { const ucastnik = ucastnici.byIds[id]; if (ucastnik[rok]) { const { prihlaska, vykon } = ucastnik[rok]; if (odstartovani && vykon && vykon.startCislo) { const { cas, dokonceno, kategorie: kategorieId, startCislo } = vykon; if (typ === kategorie[kategorieId].typ) { const result = { id, dokonceno, startCislo }; if (cas) { result.cas = moment.duration(cas); } results.push(result); } } else if (!odstartovani && prihlaska && prihlaska.startCislo) { const { kategorie: kategorieId, startCislo } = prihlaska; if (typ === kategorie[kategorieId].typ) { results.push({ id, startCislo }); } } } }); return results.sort((a, b) => a.startCislo - b.startCislo); }; // Looks for startCislo and also id (so that it won't mark itself). export const isStartCisloTaken = ({ id, odstartovani, rok = AKTUALNI_ROK, startCislo, typ, kategorie, ucastnici, }) => !!getStartovniCislaProTyp({ odstartovani, rok, typ, kategorie, ucastnici }).find( (startovniCislo) => startovniCislo.startCislo === startCislo && startovniCislo.id !== id ); const findStartCislo = (startovniCisla, startCislo) => startovniCisla.find((element) => element.startCislo === startCislo); const populateRange = (start, end) => { if (end >= start) { return Array(end - start + 1) .fill(1) .map((val, index) => start + index); } return Array(start - end + 1) .fill(1) .map((val, index) => start - index); }; export const getStartovniCislaProTypVsechna = ({ odstartovani, rok = AKTUALNI_ROK, typ, kategorie, rocniky, ucastnici, }) => { const typKategorie = getTypKategorie({ rok, typ, rocniky }); const { startCisla: povolenaStartovniCisla } = typKategorie; if (!povolenaStartovniCisla) { return []; } const startovniCisla = getStartovniCislaProTyp({ odstartovani, rok, typ, kategorie, ucastnici }); const results = []; povolenaStartovniCisla.rozsahy.forEach((rozsah) => { let range = []; const parsed = rozsah.match(/(\d+)-(\d+)/); if (parsed) { range = populateRange(parseInt(parsed[1], 10), parseInt(parsed[2], 10)); } else { range = [parseInt(rozsah, 10)]; } const result = range.map( (cislo) => findStartCislo(startovniCisla, cislo) || { startCislo: cislo } ); results.push(...result); }); return results; };
/* * jQuery UI Slider 1.8rc2 * * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Slider * * Depends: * jquery.ui.core.js * jquery.ui.mouse.js * jquery.ui.widget.js */ (function($) { // number of pages in a slider // (how many times can you page up/down to go through the whole range) var numPages = 5; $.widget("ui.slider", $.ui.mouse, { widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: 'horizontal', range: false, step: 1, value: 0, values: null }, _create: function() { var self = this, o = this.options; this._keySliding = false; this._mouseSliding = false; this._animateOff = true; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass("ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); if (o.disabled) { this.element.addClass('ui-slider-disabled ui-disabled'); } this.range = $([]); if (o.range) { if (o.range === true) { this.range = $('<div></div>'); if (!o.values) o.values = [this._valueMin(), this._valueMin()]; if (o.values.length && o.values.length != 2) { o.values = [o.values[0], o.values[0]]; } } else { this.range = $('<div></div>'); } this.range .appendTo(this.element) .addClass("ui-slider-range"); if (o.range == "min" || o.range == "max") { this.range.addClass("ui-slider-range-" + o.range); } // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes this.range.addClass("ui-widget-header"); } if ($(".ui-slider-handle", this.element).length == 0) $('<a href="#"></a>') .appendTo(this.element) .addClass("ui-slider-handle"); if (o.values && o.values.length) { while ($(".ui-slider-handle", this.element).length < o.values.length) $('<a href="#"></a>') .appendTo(this.element) .addClass("ui-slider-handle"); } this.handles = $(".ui-slider-handle", this.element) .addClass("ui-state-default" + " ui-corner-all"); this.handle = this.handles.eq(0); this.handles.add(this.range).filter("a") .click(function(event) { event.preventDefault(); }) .hover(function() { if (!o.disabled) { $(this).addClass('ui-state-hover'); } }, function() { $(this).removeClass('ui-state-hover'); }) .focus(function() { if (!o.disabled) { $(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); } else { $(this).blur(); } }) .blur(function() { $(this).removeClass('ui-state-focus'); }); this.handles.each(function(i) { $(this).data("index.ui-slider-handle", i); }); this.handles.keydown(function(event) { var ret = true; var index = $(this).data("index.ui-slider-handle"); if (self.options.disabled) return; switch (event.keyCode) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: ret = false; if (!self._keySliding) { self._keySliding = true; $(this).addClass("ui-state-active"); self._start(event, index); } break; } var curVal, newVal, step = self._step(); if (self.options.values && self.options.values.length) { curVal = newVal = self.values(index); } else { curVal = newVal = self.value(); } switch (event.keyCode) { case $.ui.keyCode.HOME: newVal = self._valueMin(); break; case $.ui.keyCode.END: newVal = self._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = curVal + ((self._valueMax() - self._valueMin()) / numPages); break; case $.ui.keyCode.PAGE_DOWN: newVal = curVal - ((self._valueMax() - self._valueMin()) / numPages); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if(curVal == self._valueMax()) return; newVal = curVal + step; break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if(curVal == self._valueMin()) return; newVal = curVal - step; break; } self._slide(event, index, newVal); return ret; }).keyup(function(event) { var index = $(this).data("index.ui-slider-handle"); if (self._keySliding) { self._stop(event, index); self._change(event, index); self._keySliding = false; $(this).removeClass("ui-state-active"); } }); this._refreshValue(); this._animateOff = false; }, destroy: function() { this.handles.remove(); this.range.remove(); this.element .removeClass("ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-slider-disabled" + " ui-widget" + " ui-widget-content" + " ui-corner-all") .removeData("slider") .unbind(".slider"); this._mouseDestroy(); return this; }, _mouseCapture: function(event) { var o = this.options; if (o.disabled) return false; this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); var position = { x: event.pageX, y: event.pageY }; var normValue = this._normValueFromMouse(position); var distance = this._valueMax() - this._valueMin() + 1, closestHandle; var self = this, index; this.handles.each(function(i) { var thisDistance = Math.abs(normValue - self.values(i)); if (distance > thisDistance) { distance = thisDistance; closestHandle = $(this); index = i; } }); // workaround for bug #3736 (if both handles of a range are at 0, // the first is always used as the one with least distance, // and moving it is obviously prevented by preventing negative ranges) if(o.range == true && this.values(1) == o.min) { closestHandle = $(this.handles[++index]); } this._start(event, index); this._mouseSliding = true; self._handleIndex = index; closestHandle .addClass("ui-state-active") .focus(); var offset = closestHandle.offset(); var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle'); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - (closestHandle.width() / 2), top: event.pageY - offset.top - (closestHandle.height() / 2) - (parseInt(closestHandle.css('borderTopWidth'),10) || 0) - (parseInt(closestHandle.css('borderBottomWidth'),10) || 0) + (parseInt(closestHandle.css('marginTop'),10) || 0) }; normValue = this._normValueFromMouse(position); this._slide(event, index, normValue); this._animateOff = true; return true; }, _mouseStart: function(event) { return true; }, _mouseDrag: function(event) { var position = { x: event.pageX, y: event.pageY }; var normValue = this._normValueFromMouse(position); this._slide(event, this._handleIndex, normValue); return false; }, _mouseStop: function(event) { this.handles.removeClass("ui-state-active"); this._mouseSliding = false; this._stop(event, this._handleIndex); this._change(event, this._handleIndex); this._handleIndex = null; this._clickOffset = null; this._animateOff = false; return false; }, _detectOrientation: function() { this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal'; }, _normValueFromMouse: function(position) { var pixelTotal, pixelMouse; if ('horizontal' == this.orientation) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0); } var percentMouse = (pixelMouse / pixelTotal); if (percentMouse > 1) percentMouse = 1; if (percentMouse < 0) percentMouse = 0; if ('vertical' == this.orientation) percentMouse = 1 - percentMouse; var valueTotal = this._valueMax() - this._valueMin(), valueMouse = percentMouse * valueTotal, valueMouseModStep = valueMouse % this.options.step, normValue = this._valueMin() + valueMouse - valueMouseModStep; if (valueMouseModStep > (this.options.step / 2)) normValue += this.options.step; // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat(normValue.toFixed(5)); }, _start: function(event, index) { var uiHash = { handle: this.handles[index], value: this.value() }; if (this.options.values && this.options.values.length) { uiHash.value = this.values(index); uiHash.values = this.values(); } this._trigger("start", event, uiHash); }, _slide: function(event, index, newVal) { var handle = this.handles[index]; if (this.options.values && this.options.values.length) { var otherVal = this.values(index ? 0 : 1); if ((this.options.values.length == 2 && this.options.range === true) && ((index == 0 && newVal > otherVal) || (index == 1 && newVal < otherVal))){ newVal = otherVal; } if (newVal != this.values(index)) { var newValues = this.values(); newValues[index] = newVal; // A slide can be canceled by returning false from the slide callback var allowed = this._trigger("slide", event, { handle: this.handles[index], value: newVal, values: newValues }); var otherVal = this.values(index ? 0 : 1); if (allowed !== false) { this.values(index, newVal, true); } } } else { if (newVal != this.value()) { // A slide can be canceled by returning false from the slide callback var allowed = this._trigger("slide", event, { handle: this.handles[index], value: newVal }); if (allowed !== false) { this.value(newVal); } } } }, _stop: function(event, index) { var uiHash = { handle: this.handles[index], value: this.value() }; if (this.options.values && this.options.values.length) { uiHash.value = this.values(index); uiHash.values = this.values(); } this._trigger("stop", event, uiHash); }, _change: function(event, index) { if (!this._keySliding && !this._mouseSliding) { var uiHash = { handle: this.handles[index], value: this.value() }; if (this.options.values && this.options.values.length) { uiHash.value = this.values(index); uiHash.values = this.values(); } this._trigger("change", event, uiHash); } }, value: function(newValue) { if (arguments.length) { this.options.value = this._trimValue(newValue); this._refreshValue(); this._change(null, 0); } return this._value(); }, values: function(index, newValue) { if (arguments.length > 1) { this.options.values[index] = this._trimValue(newValue); this._refreshValue(); this._change(null, index); } if (arguments.length) { if ($.isArray(arguments[0])) { var vals = this.options.values, newValues = arguments[0]; for (var i = 0, l = vals.length; i < l; i++) { vals[i] = this._trimValue(newValues[i]); this._change(null, i); } this._refreshValue(); } else { if (this.options.values && this.options.values.length) { return this._values(index); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function(key, value) { $.Widget.prototype._setOption.apply(this, arguments); switch (key) { case 'disabled': if (value) { this.handles.filter(".ui-state-focus").blur(); this.handles.removeClass("ui-state-hover"); this.handles.attr("disabled", "disabled"); this.element.addClass("ui-disabled"); } else { this.handles.removeAttr("disabled"); this.element.removeClass("ui-disabled"); } case 'orientation': this._detectOrientation(); this.element .removeClass("ui-slider-horizontal ui-slider-vertical") .addClass("ui-slider-" + this.orientation); this._refreshValue(); break; case 'value': this._animateOff = true; this._refreshValue(); this._animateOff = false; break; case 'values': this._animateOff = true; this._refreshValue(); this._animateOff = false; break; } }, _step: function() { var step = this.options.step; return step; }, _value: function() { //internal value getter // _value() returns value trimmed by min and max var val = this.options.value; val = this._trimValue(val); return val; }, _values: function(index) { //internal values getter // _values() returns array of values trimmed by min and max // _values(index) returns single value trimmed by min and max if (arguments.length) { var val = this.options.values[index]; val = this._trimValue(val); return val; } else { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned var vals = this.options.values.slice(); for (var i = 0, l = vals.length; i < l; i++) { vals[i] = this._trimValue(vals[i]); } return vals; } }, _trimValue: function(val) { if (val < this._valueMin()) val = this._valueMin(); if (val > this._valueMax()) val = this._valueMax(); return val; }, _valueMin: function() { var valueMin = this.options.min; return valueMin; }, _valueMax: function() { var valueMax = this.options.max; return valueMax; }, _refreshValue: function() { var oRange = this.options.range, o = this.options, self = this; var animate = (!this._animateOff) ? o.animate : false; if (this.options.values && this.options.values.length) { var vp0, vp1; this.handles.each(function(i, j) { var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100; var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; $(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); if (self.options.range === true) { if (self.orientation == 'horizontal') { (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate); (i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); } else { (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate); (i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); } } lastValPercent = valPercent; }); } else { var value = this.value(), valueMin = this._valueMin(), valueMax = this._valueMax(), valPercent = valueMax != valueMin ? (value - valueMin) / (valueMax - valueMin) * 100 : 0; var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); (oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate); (oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); (oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate); (oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); } } }); $.extend($.ui.slider, { version: "1.8rc2" }); })(jQuery);
import React, { PropTypes } from 'react'; const BlogDetail = ({ blog }) => ( <div> <div className="media well"> <div className="media-body"> {blog.body} </div> </div> </div> ); BlogDetail.propTypes = { blog: PropTypes.object.isRequired }; export default BlogDetail;
/*! vimeo-data 06-05-2014 */ !function(a){"use strict";var b={};if(b.video={},b.video.url="video",b.video.getVideoById=function(a){var c=b.makeUrl(this.url,a,"json");return b.$getJson(c)},!a.jQuery)throw new Error("It dependes on jquery");b.url="http://vimeo.com/api/",b.apiVersion="v2",b.$getJson=a.jQuery.getJSON,b.$post=a.jQuery.post,b.VERSION="0.0.1",b.makeUrl=function(a,b,c){return this.url+this.apiVersion+"/"+a+"/"+b+"."+c},a.vimeoData=b}(this);
import Component from '@glimmer/component'; import moment from 'moment'; export default class DashboardWeekComponent extends Component { get expanded() { const lastSunday = moment().day(1).subtract(1, 'week').format('W'); const thisSunday = moment().day(1).format('W'); const nextSunday = moment().day(1).add(1, 'week').format('W'); return `${lastSunday}-${thisSunday}-${nextSunday}`; } get year() { return moment().year(); } get week() { //set day to Thursday to correctly calculate isoWeek return moment().day(4).isoWeek(); } }
module.exports = { prefix: 'fal', iconName: 'rectangle-wide', icon: [640, 512, [], "f2fc", "M592 96H48c-26.5 0-48 21.5-48 48v224c0 26.5 21.5 48 48 48h544c26.5 0 48-21.5 48-48V144c0-26.5-21.5-48-48-48zm16 272c0 8.8-7.2 16-16 16H48c-8.8 0-16-7.2-16-16V144c0-8.8 7.2-16 16-16h544c8.8 0 16 7.2 16 16v224z"] };
/** * resource viewer at the left sidebar */ const Command = require('./command'); const SourceViewer = require('./sourceViewer'); const $dom = $('#resources'); const ResourceViewer = { selectedUrl: null, resources: null, render(resources){ let html = resources.resources.filter(item => item.type === 'Script') .map(item => { let fileName = item.url.split('/').slice(-1)[0]; return `<span class="nav-group-item ${item.url === this.selectedUrl ? 'active': ''} resource-file" title="${item.url}"> ${fileName} </span>`; }); $dom.html(html); this.resources = resources; } }; $(document).on('click', '.resource-file', (e) => { let $target = $(e.target); let url = $target.attr('title'); Command('Page.getResourceContent', { frameId: ResourceViewer.resources.frame.id, url }).then(SourceViewer.render.bind(SourceViewer, url)); $target.siblings().removeClass('active'); $target.addClass('active'); }); module.exports = ResourceViewer;
'use strict'; var handyJS = {}; 'use strict'; //All bout file manipulate handyJS.file = {}; // sources: // http://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript handyJS.file.getExtension = function (fileName) { return fileName.slice((Math.max(0, fileName.lastIndexOf('.')) || Infinity) + 1); }; //usage: changeFileName('ding.js', 'dong'); => dong.js handyJS.file.changeName = function (originalName, newName) { var extension = this.getExtension(originalName); return newName + '.' + extension; }; 'use strict'; handyJS.string = {}; //remove whitespace, tab and new line handyJS.string.removeAllSpace = function (string) { return string.replace(/\s/g, ''); }; //only remove whitespace handyJS.string.removeWhitespace = function (string) { return string.replace(/ /g, ''); }; "use strict"; module.exports = handyJS;
// // Jala Project [http://opensvn.csie.org/traccgi/jala] // // Copyright 2004 ORF Online und Teletext GmbH // // Licensed under the Apache License, Version 2.0 (the ``License''); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an ``AS IS'' BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // $Revision: 314 $ // $LastChangedBy: robert $ // $LastChangedDate: 2007-11-09 12:45:00 +0100 (Fre, 09 Nov 2007) $ // $HeadURL: http://dev.orf.at/source/jala/trunk/util/HopKit/scripts/PoParser.js $ // /** * @fileoverview * A parser script that converts GNU Gettext .po files into plain JavaScript objects * for use with jala.I18n. To run it either start the build script of HopKit * or call it directly using the JavaScript shell of Rhino: * <code>java -cp rhino.jar org.mozilla.javascript.tools.shell.Main PoParser.js <input> <output> [namespace]</code> * * The accepted arguments are: * <ul> * <li><code>input</code>: Either a single .po file or a directory containing multiple files</li> * <li><code>output</code>: The directory where to put the generated message files</li> * <li><code>namespace</code>: An optional namespace in which the generated message object will reside * (eg. if the namespace is called "jala", the messages will be stored in global.jala.messages)</li> * </ul> */ /** * Constructs a new PoParser instance. * @class Instances of this class can generate JavaScript message files out * of GNU Gettext .po files for use with jala.I18n (and possibly other internationalization * environments too). * @param {String} handler An optional namespace where the parsed messages should be stored * @returns A newly created instance of PoParser * @constructor */ var PoParser = function(namespace) { /** * An array containing the parsed messages * @type Array */ this.messages = []; /** * The locale key string (eg. "de_AT") of the .po file * @type String */ this.localeKey = null; /** * The namespace (optional) where to store the generated messages * @type String */ this.namespace = namespace; return this; }; /** * A regular expression for splitting the contents of a .po file into * single lines * @type RegExp */ PoParser.REGEX_LINES = /\r\n|\r|\n|\u0085|\u2028|\u2029/; /** * A regular expression for parsing singular message keys * @type RegExp */ PoParser.REGEX_MSGID = /^\s*msgid(?!_plural)\s+\"(.*)\"\s*$/; /** * A regular expression for parsing plural message keys * @type RegExp */ PoParser.REGEX_MSGID_PLURAL = /^\s*msgid_plural\s+\"(.*)\"\s*$/; /** * A regular expression for parsing message key continuations * @type RegExp */ PoParser.REGEX_MSG_CONT = /^\s*\"(.*)\"\s*$/; /** * A regular expression for parsing a message translation * @type RegExp */ PoParser.REGEX_MSGSTR = /^\s*msgstr(?:\[(\d)\])?\s+\"(.*)\"\s*$/; /** * A regular expression used to detect lines other than whitespace * and comments * @type RegExp */ PoParser.REGEX_DATA = /^\s*msg/; PoParser.isData = function(str) { return PoParser.REGEX_DATA.test(str); }; /** * Reads the file passed as argument, assuming that it is UTF-8 encoded * @param {java.io.File} file The file to read * @returns The contents of the file * @type java.lang.String */ PoParser.readFile = function(file) { var inStream = new java.io.InputStreamReader(new java.io.FileInputStream(file), "UTF-8"); var buffer = new java.lang.reflect.Array.newInstance(java.lang.Character.TYPE, 2048); var read = 0; var r = 0; while ((r = inStream.read(buffer, read, buffer.length - read)) > -1) { read += r; if (read == buffer.length) { // grow input buffer var newBuffer = new java.lang.reflect.Array.newInstance(java.lang.Character.TYPE, buffer.length * 2); java.lang.System.arraycopy(buffer, 0, newBuffer, 0, buffer.length); buffer = newBuffer; } } inStream.close(); return new java.lang.String(buffer, 0, read); } /** * Parses the PO file passed as argument into the messages array * of this PoParser instance. * @param {java.io.File} file The .po file to parse */ PoParser.prototype.parse = function(file) { // parse the locale key out of the file name var fileName = file.getName(); if (!(this.localeKey = fileName.substring(0, fileName.indexOf(".")))) { throw "Invalid PO file name: " + fileName; } // read the PO file content and parse it into messages var content = PoParser.readFile(file); var start = new Date(); var lines = content.split(PoParser.REGEX_LINES); var idx = -1; var line = null; var m, value, nr; var msg; var hasMoreLines = function() { return idx < lines.length - 1; }; var nextLine = function() { return (line = lines[idx += 1]) != null; }; var getContinuation = function(str) { var nLine; while ((nLine = lines[idx + 1]) != null) { if ((m = nLine.match(PoParser.REGEX_MSG_CONT)) != null) { str += m[1]; nextLine(); } else { break; } } return str; } while (nextLine()) { if ((m = line.match(PoParser.REGEX_MSGID)) != null) { value = getContinuation(m[1]); if (value) { msg = this.messages[this.messages.length] = new Message(value); } } else if ((m = line.match(PoParser.REGEX_MSGID_PLURAL)) != null) { value = getContinuation(m[1]); if (value && msg != null) { msg.pluralKey = value; } } else if ((m = line.match(PoParser.REGEX_MSGSTR)) != null) { nr = m[1]; value = getContinuation(m[2]); if (value && msg != null) { nr = parseInt(nr, 10); msg.translations[nr || 0] = value; } } } return; }; /** * Converts the array containing the parsed messages into a message * catalog script file and saves it on disk. * @param {java.io.File} outputDir The directory where the message * file should be saved */ PoParser.prototype.writeToFile = function(output) { var buf = new java.lang.StringBuffer(); // write header buf.append('/**\n'); buf.append(' * Instantiate the messages namespace if it\'s not already existing\n'); buf.append(' */\n'); var objPath = ""; if (this.namespace) { objPath += this.namespace; buf.append('if (!global.' + objPath + ') {\n'); buf.append(' global.' + objPath + ' = {};\n'); buf.append('}\n'); objPath += "."; } objPath += "messages"; buf.append('if (!global.' + objPath + ') {\n'); buf.append(' global.' + objPath + ' = {};\n'); buf.append('}\n\n'); buf.append('/**\n'); buf.append(' * Messages for locale "' + this.localeKey + '"\n'); buf.append(' */\n'); objPath += "." + this.localeKey; buf.append('global.' + objPath + ' = {\n'); // write messages for (var i=0;i<this.messages.length; i++) { this.messages[i].write(buf); } // write footer buf.append('};\n'); // write the message catalog into the outFile var file = new java.io.File(output, objPath + ".js"); var writer = new java.io.FileWriter(file); writer.write(buf.toString()); // writer.write(buf.toString().getBytes("UTF-8")); writer.close(); print("generated messages file " + file.getAbsolutePath()); return; }; /** * Constructs a new message object containing the singular- and * plural key plus their translations * @param {String} singularKey The singular key of the message * @returns A newly created Message instance * @constructor */ var Message = function(singularKey) { this.singularKey = singularKey; this.pluralKey = null; this.translations = []; return this; } /** * Dumps this message as JavaScript literal key-value pair(s) * @param {java.lang.StringBuffer} buf The buffer to append the dumped * string to */ Message.prototype.write = function(buf) { var writeLine = function(key, value) { buf.append(' "'); buf.append(key); buf.append('": "'); if (value !== null && value !== undefined) { buf.append(value); } buf.append('",\n'); }; if (this.singularKey != null) { writeLine(this.singularKey, this.translations[0]); if (this.pluralKey != null) { writeLine(this.pluralKey, this.translations[1]); } } return; } /** * Main script body */ if (arguments.length < 2) { print("Usage:"); print("PoParser.js <input> <output> [namespace]"); print("<input>: Either a single .po file or a directory containing .po files"); print("<output>: The directory where the generated messages files should be stored"); print("[namespace]: An optional global namespace where the messages should be"); print(" stored (eg. a namespace like 'jala' will lead to messages"); print(" stored in global.jala.messages by their locale."); quit(); } var input = new java.io.File(arguments[0]); var output = new java.io.File(arguments[1]); var namespace = arguments[2]; // check if the output destination is a directory if (output.isFile()) { print("Invalid arguments: the output destination must be a directory."); quit(); } if (namespace && namespace.indexOf(".") != -1) { print("Invalid arguments: Please don't specify complex object paths, as this"); print("would corrupt the messages file."); quit(); } // parse the PO file(s) and create the message catalog files var parser; if (input.isDirectory()) { var files = input.listFiles(); var file; for (var i=0;i<files.length;i++) { file = files[i]; if (file.getName().endsWith(".po")) { parser = new PoParser(namespace); parser.parse(file); parser.writeToFile(output); } } } else { parser = new PoParser(namespace); parser.parse(input); parser.writeToFile(output); }
var fs = require('fs'); // fs.mkdirSync('./test'); fs.readdir('/Users/shengli/shengli/study/node/demos/fs/', (err, files) => { console.log(files); });
'use strict'; const debug = require('debug')('brunch:plugins'); const logger = require('loggy'); const profile = require('since-app-start').profile; const {flatten, deepFreeze} = require('./helpers'); const {sortByConfig} = require('../fs_utils/generate'); const BrunchError = require('./error'); const adapter = require('./plugin-adapter'); const sysPath = require('universal-path'); const loadPackage = pkgPath => { profile('Loading plugins'); const clearCache = () => delete require.cache[pkgPath]; try { clearCache(); const pkg = require(pkgPath); if (!pkg.dependencies) pkg.dependencies = {}; if (!pkg.devDependencies) pkg.devDependencies = {}; return deepFreeze(pkg, ['static', 'overrides']); } catch (error) { throw new BrunchError('CWD_INVALID', {error}); } finally { clearCache(); } }; const uniqueDeps = pkg => { const deps = pkg.dependencies; const names = Object.keys(deps); Object.keys(pkg.devDependencies).forEach(devDep => { if (devDep in deps) { logger.warn(`You have declared ${devDep} in package.json more than once`); } else { names.push(devDep); } }); return names; }; /* Load brunch plugins, group them and initialise file watcher. * * configParams - Object. Optional. Params will be set as default config items. * */ const ignoredPlugins = [ 'javascript-brunch', 'css-brunch', ]; const plugins = (config, craDeps) => { profile('Loaded config'); const absRoot = sysPath.resolve(config.paths.root); const pkgPath = sysPath.join(absRoot, config.paths.packageConfig); const npmPath = sysPath.join(absRoot, 'node_modules'); const pkg = config.cra ? {dependencies: craDeps} : loadPackage(pkgPath); const on = config.plugins.on; const off = config.plugins.off; const only = config.plugins.only; const order = config.plugins.order; const deps = uniqueDeps(pkg).filter(name => { if (!name.includes('brunch')) return false; if (ignoredPlugins.includes(name)) return false; if (off.includes(name)) return false; if (only.length && !only.includes(name)) return false; return true; }); const plugins = sortByConfig(deps, order) .reduce((plugins, name) => { try { const Plugin = require(sysPath.join(npmPath, name)); if (Plugin && Plugin.prototype && Plugin.prototype.brunchPlugin) { const plugin = new Plugin(config); plugin.brunchPluginName = name; plugins.push(adapter(plugin)); } } catch (error) { if (error.code === 'MODULE_NOT_FOUND' && name in pkg.dependencies) { throw new BrunchError('RUN_NPM_INSTALL', {error}); } logger.warn(`Loading of ${name} failed due to`, error); } return plugins; }, []) .filter(plugin => { // Does the user's config say this plugin should definitely be used? if (on.includes(plugin.brunchPluginName)) return true; // If the plugin is an optimizer that doesn't specify a defaultEnv // decide based on the config.optimize setting const env = plugin.defaultEnv; if (!env) { return plugin.optimize ? config.optimize : true; } // Finally, is it meant for either any environment or // an active environment? return env === '*' || config.env.includes(env); }); const respondTo = key => plugins.filter(plugin => { return typeof plugin[key] === 'function'; }); const compilers = respondTo('compile'); const names = plugins.map(plugin => plugin.brunchPluginName).join(', '); debug(`Loaded plugins: ${names}`); if (config.hot) { const hmrCompiler = compilers.find(compiler => { return compiler.brunchPluginName === 'auto-reload-brunch'; }); if (!hmrCompiler) throw new BrunchError('HMR_PLUGIN_MISSING'); if (!hmrCompiler.supportsHMR) throw new BrunchError('HMR_PLUGIN_UNSUPPORTED'); } /* Get paths to files that plugins include. E.g. handlebars-brunch includes * `../vendor/handlebars-runtime.js` with path relative to plugin. */ const getIncludes = () => { const includes = plugins.map(plugin => { return plugin.include.then(paths => { return paths.map(path => { if (!sysPath.isAbsolute(path)) { path = sysPath.join(npmPath, plugin.brunchPluginName, path); } return sysPath.relative(absRoot, path); }); }); }); // TODO: for-of return Promise.all(includes).then(flatten); }; return getIncludes().then(includes => { helpers.push(...includes); profile('Loaded plugins'); return { hooks: { preCompile: respondTo('preCompile'), onCompile: respondTo('onCompile'), teardown: respondTo('teardown'), }, plugins: { includes, compilers, optimizers: respondTo('optimize'), all: plugins, }, }; }); }; const helpers = plugins.helpers = []; module.exports = plugins;
module.exports = { "ahj": { "rules": { "epbbFormula": { "id": "epbbFormula", "source": { "id": "6b07a571-604b-4e5d-a545-0ac3be59de16", "name": "NV Energy", "type": "Utility" }, "statements": [ { "value": "(cecAcSystemSize * 1000) * (designFactor / 100) * 0.2" } ] }, "epbbFormula2": { "id": "epbbFormula2", "source": { "id": "6b07a571-604b-4e5d-a545-0ac3be59de16", "name": "NV Energy", "type": "Utility" }, "statements": [ { "value": "5 - (cecAcSystemSize)" } ] }, "epbbFormula3": { "id": "epbbFormula3", "source": { "id": "8cc558a4-9a97-4ef5-9e34-f535d3e0c21c", "name": "Connecticut", "type": "State" }, "statements": [ { "condition": [ { "left": "designFactor", "operator": "<", "right": 75 } ], "description": "Condition 16", "value": "((10000 * 0.547) + ((dcPtcSystemSize * 1000) - 10000) * 0.473) * (designFactor / 100) * systemAdjustmentFactor" } ] } } }, "definitions": { "rules": { "epbbFormula": { "allowableConditions": [ "systemSizeDc", "designFactor", "cecAcSystemSize" ], "description": "Calculate the expected performance based buy down rebates", "id": "epbbFormula", "name": "Epbb Formula", "rule": true, "tags": [ "utilityRequirementsRuleGroup", "default" ], "template": { "dataType": "formula", "onConflict": "standard" } }, "epbbFormula2": { "allowableConditions": [ "systemSizeDc", "designFactor", "cecAcSystemSize" ], "description": "Calculate the expected performance based buy down rebates", "id": "epbbFormula2", "name": "Epbb Formula 2", "rule": true, "tags": [ "utilityRequirementsRuleGroup", "default" ], "template": { "dataType": "formula", "onConflict": "standard" } }, "epbbFormula3": { "allowableConditions": [ "designFactor", "systemAdjustmentFactor", "dcPtcSystemSize" ], "description": "Calculate the expected performance based buy down rebates", "id": "epbbFormula3", "name": "Epbb Formula 3", "rule": true, "tags": [ "utilityRequirementsRuleGroup", "default" ], "template": { "dataType": "formula", "onConflict": "standard" } } }, "conditions": { "cecAcSystemSize": { "applyTo": [ "epbbFormula" ], "condition": true, "description": "CEC-AC System Size", "id": "cecAcSystemSize", "name": "CEC-AC System Size", "tags": [ "electrical", "design", "surveyor" ], "template": { "dataType": "number", "units": "KW" } }, "systemSizeDc": { "applyTo": [ "epbbFormula" ], "condition": true, "description": "DC System Size", "id": "systemSizeDc", "name": "DC System Size", "tags": [ "electrical", "design", "surveyor" ], "template": { "dataType": "number", "range": { "min": 0 }, "units": "KW" } }, "designFactor": { "applyTo": [ "epbbFormula" ], "condition": true, "description": "Design Factor", "id": "designFactor", "name": "Design Factor", "tags": [ "design" ], "template": { "dataType": "number" } }, "systemAdjustmentFactor": { "applyTo": [ "epbbFormula" ], "condition": true, "description": "System Adjustment Factor", "id": "systemAdjustmentFactor", "name": "System Adjustment Factor", "tags": [ "electrical", "design", "surveyor" ], "template": { "dataType": "number" } }, "dcPtcSystemSize": { "applyTo": [ "epbbFormula", "proratedPtcDcSystemSize" ], "condition": true, "description": "DC PTC System Size", "id": "dcPtcSystemSize", "name": "DC PTC System Size", "tags": [ "electrical", "design", "surveyor" ], "template": { "dataType": "number", "units": "KW" } } } } };
import { uglify } from 'rollup-plugin-uglify'; import pkg from './package.json'; export default [ { input: 'src/module.js', output: [ { name: 'wtEasyMask', file: pkg.browser, format: 'umd' }, { file: pkg.module, format: 'es' }, ] }, { input: 'src/module.js', plugins: [ uglify(), ], output: [ { file: pkg.browser.replace('.js', '.min.js'), format: 'umd', }, ] } ];
//Regular click var i = 1; var main = function() { $("#regular").click(function() { $(".user").html('You have decided to click the button <span class="counter"> 0 </span> times.'); $(".counter").text(i); i++; }); //Fibonacci var first = 0; var second = 1; var current_fib; var fib_pressed = 0; $("#fibonacci").click(function() { $(".user").html('The current fibonacci number is <span class="counter"> 0 </span>.'); fib_pressed++; if (fib_pressed === 1) { $(".counter").text(0); } else if (fib_pressed === 2) { $(".counter").text(1); } else if (fib_pressed === 3) { $(".counter").text('1 (again)'); current_fib = first + second; first = second; second = current_fib; } else { current_fib = first + second; first = second; second = current_fib; $(".counter").text(current_fib); } }); //Prime var current_prime = 2; var prime_pressed = 0; function isPrime(number) { if (number < 2) { return false } if (number != Math.round(number)) { return false } var isPrime = true; for (var i = 2; i <= Math.sqrt(number); i++) { if (number % i == 0) { isPrime = false } } return isPrime; }; $("#prime").click(function() { $(".user").html('The current prime number is <span class="counter"> 2 </span>.'); prime_pressed++; if (prime_pressed == 1) { $(".counter").text(2); } if (prime_pressed > 1) { current_prime++; while (!(isPrime(current_prime))) { current_prime++; } $(".counter").text(current_prime); } }); }; $(document).ready(main);
// CONTROLLER // ============================================================================= class EditController { /** * Fires when the controller is finished initializing. * * @method $onInit */ $onInit() { // controller name this.name = "edit"; } } // EXPORT // ============================================================================= export default EditController;
var base = require('../base') var ERROR_LEVEL = base.ERROR_LEVEL var Class = base.Class var RuleChecker = base.RuleChecker var helper = require('./helper'); module.exports = global.FEDUnknownCssNameChecker = new Class(RuleChecker, function() { this.__init__ = function(self) { self.id = 'unknown-css-prop' self.errorLevel = ERROR_LEVEL.ERROR self.errorMsg = 'unknown attribute name "${name}" found in "${selector}"' } this.check = function(self, rule, config) { return helper.isCssProp(rule.name.toLowerCase()) } this.__doc__ = { "summary":"错误的css属性", "desc":"本工具会帮您查找错误的CSS属性,如果写错了,即可收到错误提示" } })
import Debonair from "./classes/Debonair"; import { Styler, StylerObject } from "./classes/Styler"; import components from "./components"; import DebonairApp from "./components/DebonairApp"; export default { Debonair, Styler, StylerObject, components, DebonairApp };
'use strict'; angular.module('wateringApp') .controller('SensorListCtrl', ['$scope', 'SensorsFactory', '$state', function ($scope, SensorsFactory, $state) { // callback for ng-click 'editSensor': $scope.editSensor = function (sensorId) { $state.go('sensor-detail', {id: sensorId}); }; // callback for ng-click 'deleteSensor': $scope.deleteSensor = function (sensorId) { $state.go('sensor-delete', {id: sensorId}); }; // callback for ng-click 'createSensor': $scope.createNewSensor = function () { $state.go('sensor-creation'); }; $scope.sensors = SensorsFactory.query(); }]) .controller('SensorDetailCtrl', ['$scope', 'SensorFactory', 'SensorsFactory', '$state', '$stateParams', function ($scope, SensorFactory, SensorsFactory, $state, $stateParams) { // callback for ng-click 'updateSensor': $scope.updateSensor = function () { SensorFactory.update($scope.sensor); $scope.sensors = SensorsFactory.query(); $state.go('sensor-list'); }; // callback for ng-click 'cancel': $scope.cancel = function () { $state.go('sensor-list'); }; $scope.sensor = SensorFactory.show({id: $stateParams.id}); }]) .controller('SensorCreationCtrl', ['$scope', 'SensorsFactory', '$state', function ($scope, SensorsFactory, $state) { // callback for ng-click 'createNewSensor': $scope.createNewSensor = function () { SensorsFactory.create($scope.sensor); $scope.sensors = SensorsFactory.query(); $state.go('sensor-list'); } // callback for ng-click 'cancel': $scope.cancel = function () { $state.go('sensor-list'); }; }]) .controller('SensorDeleteCtrl', ['$scope', 'SensorFactory', 'SensorsFactory', '$state', '$stateParams', function ($scope, SensorFactory, SensorsFactory, $state, $stateParams) { // callback for ng-click 'deleteSensor': $scope.deleteSensor = function (sensorId) { SensorFactory.delete({ id: sensorId }); $scope.sensors = SensorsFactory.query(); $state.go('sensor-list'); }; // callback for ng-click 'cancel': $scope.cancel = function () { $state.go('sensor-list'); }; $scope.sensor = SensorFactory.show({id: $stateParams.id}); }]);
/** * @since 2017-04-18 17:58 * @author chenyiqin */ import * as server from '../src/constant/server' import fetchMock from 'fetch-mock' import getTodoListJson from './json/getTodoList.json' export const getTodosMock = fetchMock.mock(new RegExp(`/${server.GET_TODO_LIST_METHOD}`), (url, opts) => { console.log(`fetchMock url, opts = `, url, opts) // eslint-disable-line return new Promise((resolve,) => { const result = getTodoListJson resolve(JSON.stringify(result)) }) })
import bcrypt from 'bcrypt-as-promised'; import mongoose, { Schema } from 'mongoose'; const ChallengeSchema = new Schema({ deleted: { type: Boolean, default: false }, name: String, flag: String, // salt+hash flagThumb: String, // part of the original flag, for searching purpose category: { type: String, lowercase: true }, difficulty: Number, description: String, }, { timestamps: true, }); /** * Hash the flag and set the flag thumbnail */ ChallengeSchema.methods.setFlag = async function (plainFlag) { let flagThumb; if (plainFlag.length > 10) { flagThumb = plainFlag.substr(0, 6) + '...' + plainFlag.substr(-4, 4); } else { flagThumb = plainFlag.substr(0, 3) + '...'; } this.flag = await bcrypt.hash(plainFlag, 10); this.flagThumb = flagThumb; }; /** * Test whether a flag is correct */ ChallengeSchema.methods.testFlag = async function (flag) { try { await bcrypt.compare(flag, this.flag); } catch (e) { if (e instanceof bcrypt.MISMATCH_ERROR) { return false; } else { throw e; } } return true; }; ChallengeSchema.index({ deleted: 1, category: 1, name: 1 }); mongoose.model('Challenge', ChallengeSchema);
'use strict'; var test = require('tap').test; var DrSax = require('../index'); test('nested anchor tags should function correctly', function(t){ var drsax = new DrSax(); var output = drsax.write('<a href="http://test.com"><b>testing</b></a>'); t.equal(output, '[**testing**](http://test.com)', 'nesting spliced tags'); t.end(); });
export * from './StationDetailsContainer';
var Promise = require('bluebird'); module.exports = function(){} module.exports.prototype.start = function(metalogin,data){}; module.exports.prototype.invalidate = function(id,data){} module.exports.prototype.set = function(id,data){} module.exports.prototype.get = Promise.promisify(function(id,done){ return done(null,null); });
import React, { Component } from 'react'; export default class NamedContainer extends Component { render() { const { header, footer, main } = this.props; return ( <div> <div> <h1>Header fragment</h1> {header} </div> <div> <h1>Main fragment</h1> {main} </div> <div> <h1>Footer fragment</h1> {footer} </div> </div> ) } }
/* eslint-disable no-use-before-define */ import React from 'react'; import TextField from '@material-ui/core/TextField'; import Autocomplete from '@material-ui/lab/Autocomplete'; import { makeStyles } from '@material-ui/core/styles'; // ISO 3166-1 alpha-2 // ⚠️ No support for IE 11 function countryToFlag(isoCode) { return typeof String.fromCodePoint !== 'undefined' ? isoCode .toUpperCase() .replace(/./g, (char) => String.fromCodePoint(char.charCodeAt(0) + 127397)) : isoCode; } const useStyles = makeStyles({ option: { fontSize: 15, '& > span': { marginRight: 10, fontSize: 18, }, }, }); export default function CountrySelect() { const classes = useStyles(); return ( <Autocomplete id="country-select-demo" style={{ width: 300 }} options={countries} classes={{ option: classes.option, }} autoHighlight getOptionLabel={(option) => option.label} renderOption={(option) => ( <React.Fragment> <span>{countryToFlag(option.code)}</span> {option.label} ({option.code}) +{option.phone} </React.Fragment> )} renderInput={(params) => ( <TextField {...params} label="Choose a country" variant="outlined" inputProps={{ ...params.inputProps, autoComplete: 'new-password', // disable autocomplete and autofill }} /> )} /> ); } // From https://bitbucket.org/atlassian/atlaskit-mk-2/raw/4ad0e56649c3e6c973e226b7efaeb28cb240ccb0/packages/core/select/src/data/countries.js const countries = [ { code: 'AD', label: 'Andorra', phone: '376' }, { code: 'AE', label: 'United Arab Emirates', phone: '971' }, { code: 'AF', label: 'Afghanistan', phone: '93' }, { code: 'AG', label: 'Antigua and Barbuda', phone: '1-268' }, { code: 'AI', label: 'Anguilla', phone: '1-264' }, { code: 'AL', label: 'Albania', phone: '355' }, { code: 'AM', label: 'Armenia', phone: '374' }, { code: 'AO', label: 'Angola', phone: '244' }, { code: 'AQ', label: 'Antarctica', phone: '672' }, { code: 'AR', label: 'Argentina', phone: '54' }, { code: 'AS', label: 'American Samoa', phone: '1-684' }, { code: 'AT', label: 'Austria', phone: '43' }, { code: 'AU', label: 'Australia', phone: '61', suggested: true }, { code: 'AW', label: 'Aruba', phone: '297' }, { code: 'AX', label: 'Alland Islands', phone: '358' }, { code: 'AZ', label: 'Azerbaijan', phone: '994' }, { code: 'BA', label: 'Bosnia and Herzegovina', phone: '387' }, { code: 'BB', label: 'Barbados', phone: '1-246' }, { code: 'BD', label: 'Bangladesh', phone: '880' }, { code: 'BE', label: 'Belgium', phone: '32' }, { code: 'BF', label: 'Burkina Faso', phone: '226' }, { code: 'BG', label: 'Bulgaria', phone: '359' }, { code: 'BH', label: 'Bahrain', phone: '973' }, { code: 'BI', label: 'Burundi', phone: '257' }, { code: 'BJ', label: 'Benin', phone: '229' }, { code: 'BL', label: 'Saint Barthelemy', phone: '590' }, { code: 'BM', label: 'Bermuda', phone: '1-441' }, { code: 'BN', label: 'Brunei Darussalam', phone: '673' }, { code: 'BO', label: 'Bolivia', phone: '591' }, { code: 'BR', label: 'Brazil', phone: '55' }, { code: 'BS', label: 'Bahamas', phone: '1-242' }, { code: 'BT', label: 'Bhutan', phone: '975' }, { code: 'BV', label: 'Bouvet Island', phone: '47' }, { code: 'BW', label: 'Botswana', phone: '267' }, { code: 'BY', label: 'Belarus', phone: '375' }, { code: 'BZ', label: 'Belize', phone: '501' }, { code: 'CA', label: 'Canada', phone: '1', suggested: true }, { code: 'CC', label: 'Cocos (Keeling) Islands', phone: '61' }, { code: 'CD', label: 'Congo, Democratic Republic of the', phone: '243' }, { code: 'CF', label: 'Central African Republic', phone: '236' }, { code: 'CG', label: 'Congo, Republic of the', phone: '242' }, { code: 'CH', label: 'Switzerland', phone: '41' }, { code: 'CI', label: "Cote d'Ivoire", phone: '225' }, { code: 'CK', label: 'Cook Islands', phone: '682' }, { code: 'CL', label: 'Chile', phone: '56' }, { code: 'CM', label: 'Cameroon', phone: '237' }, { code: 'CN', label: 'China', phone: '86' }, { code: 'CO', label: 'Colombia', phone: '57' }, { code: 'CR', label: 'Costa Rica', phone: '506' }, { code: 'CU', label: 'Cuba', phone: '53' }, { code: 'CV', label: 'Cape Verde', phone: '238' }, { code: 'CW', label: 'Curacao', phone: '599' }, { code: 'CX', label: 'Christmas Island', phone: '61' }, { code: 'CY', label: 'Cyprus', phone: '357' }, { code: 'CZ', label: 'Czech Republic', phone: '420' }, { code: 'DE', label: 'Germany', phone: '49', suggested: true }, { code: 'DJ', label: 'Djibouti', phone: '253' }, { code: 'DK', label: 'Denmark', phone: '45' }, { code: 'DM', label: 'Dominica', phone: '1-767' }, { code: 'DO', label: 'Dominican Republic', phone: '1-809' }, { code: 'DZ', label: 'Algeria', phone: '213' }, { code: 'EC', label: 'Ecuador', phone: '593' }, { code: 'EE', label: 'Estonia', phone: '372' }, { code: 'EG', label: 'Egypt', phone: '20' }, { code: 'EH', label: 'Western Sahara', phone: '212' }, { code: 'ER', label: 'Eritrea', phone: '291' }, { code: 'ES', label: 'Spain', phone: '34' }, { code: 'ET', label: 'Ethiopia', phone: '251' }, { code: 'FI', label: 'Finland', phone: '358' }, { code: 'FJ', label: 'Fiji', phone: '679' }, { code: 'FK', label: 'Falkland Islands (Malvinas)', phone: '500' }, { code: 'FM', label: 'Micronesia, Federated States of', phone: '691' }, { code: 'FO', label: 'Faroe Islands', phone: '298' }, { code: 'FR', label: 'France', phone: '33', suggested: true }, { code: 'GA', label: 'Gabon', phone: '241' }, { code: 'GB', label: 'United Kingdom', phone: '44' }, { code: 'GD', label: 'Grenada', phone: '1-473' }, { code: 'GE', label: 'Georgia', phone: '995' }, { code: 'GF', label: 'French Guiana', phone: '594' }, { code: 'GG', label: 'Guernsey', phone: '44' }, { code: 'GH', label: 'Ghana', phone: '233' }, { code: 'GI', label: 'Gibraltar', phone: '350' }, { code: 'GL', label: 'Greenland', phone: '299' }, { code: 'GM', label: 'Gambia', phone: '220' }, { code: 'GN', label: 'Guinea', phone: '224' }, { code: 'GP', label: 'Guadeloupe', phone: '590' }, { code: 'GQ', label: 'Equatorial Guinea', phone: '240' }, { code: 'GR', label: 'Greece', phone: '30' }, { code: 'GS', label: 'South Georgia and the South Sandwich Islands', phone: '500' }, { code: 'GT', label: 'Guatemala', phone: '502' }, { code: 'GU', label: 'Guam', phone: '1-671' }, { code: 'GW', label: 'Guinea-Bissau', phone: '245' }, { code: 'GY', label: 'Guyana', phone: '592' }, { code: 'HK', label: 'Hong Kong', phone: '852' }, { code: 'HM', label: 'Heard Island and McDonald Islands', phone: '672' }, { code: 'HN', label: 'Honduras', phone: '504' }, { code: 'HR', label: 'Croatia', phone: '385' }, { code: 'HT', label: 'Haiti', phone: '509' }, { code: 'HU', label: 'Hungary', phone: '36' }, { code: 'ID', label: 'Indonesia', phone: '62' }, { code: 'IE', label: 'Ireland', phone: '353' }, { code: 'IL', label: 'Israel', phone: '972' }, { code: 'IM', label: 'Isle of Man', phone: '44' }, { code: 'IN', label: 'India', phone: '91' }, { code: 'IO', label: 'British Indian Ocean Territory', phone: '246' }, { code: 'IQ', label: 'Iraq', phone: '964' }, { code: 'IR', label: 'Iran, Islamic Republic of', phone: '98' }, { code: 'IS', label: 'Iceland', phone: '354' }, { code: 'IT', label: 'Italy', phone: '39' }, { code: 'JE', label: 'Jersey', phone: '44' }, { code: 'JM', label: 'Jamaica', phone: '1-876' }, { code: 'JO', label: 'Jordan', phone: '962' }, { code: 'JP', label: 'Japan', phone: '81', suggested: true }, { code: 'KE', label: 'Kenya', phone: '254' }, { code: 'KG', label: 'Kyrgyzstan', phone: '996' }, { code: 'KH', label: 'Cambodia', phone: '855' }, { code: 'KI', label: 'Kiribati', phone: '686' }, { code: 'KM', label: 'Comoros', phone: '269' }, { code: 'KN', label: 'Saint Kitts and Nevis', phone: '1-869' }, { code: 'KP', label: "Korea, Democratic People's Republic of", phone: '850' }, { code: 'KR', label: 'Korea, Republic of', phone: '82' }, { code: 'KW', label: 'Kuwait', phone: '965' }, { code: 'KY', label: 'Cayman Islands', phone: '1-345' }, { code: 'KZ', label: 'Kazakhstan', phone: '7' }, { code: 'LA', label: "Lao People's Democratic Republic", phone: '856' }, { code: 'LB', label: 'Lebanon', phone: '961' }, { code: 'LC', label: 'Saint Lucia', phone: '1-758' }, { code: 'LI', label: 'Liechtenstein', phone: '423' }, { code: 'LK', label: 'Sri Lanka', phone: '94' }, { code: 'LR', label: 'Liberia', phone: '231' }, { code: 'LS', label: 'Lesotho', phone: '266' }, { code: 'LT', label: 'Lithuania', phone: '370' }, { code: 'LU', label: 'Luxembourg', phone: '352' }, { code: 'LV', label: 'Latvia', phone: '371' }, { code: 'LY', label: 'Libya', phone: '218' }, { code: 'MA', label: 'Morocco', phone: '212' }, { code: 'MC', label: 'Monaco', phone: '377' }, { code: 'MD', label: 'Moldova, Republic of', phone: '373' }, { code: 'ME', label: 'Montenegro', phone: '382' }, { code: 'MF', label: 'Saint Martin (French part)', phone: '590' }, { code: 'MG', label: 'Madagascar', phone: '261' }, { code: 'MH', label: 'Marshall Islands', phone: '692' }, { code: 'MK', label: 'Macedonia, the Former Yugoslav Republic of', phone: '389' }, { code: 'ML', label: 'Mali', phone: '223' }, { code: 'MM', label: 'Myanmar', phone: '95' }, { code: 'MN', label: 'Mongolia', phone: '976' }, { code: 'MO', label: 'Macao', phone: '853' }, { code: 'MP', label: 'Northern Mariana Islands', phone: '1-670' }, { code: 'MQ', label: 'Martinique', phone: '596' }, { code: 'MR', label: 'Mauritania', phone: '222' }, { code: 'MS', label: 'Montserrat', phone: '1-664' }, { code: 'MT', label: 'Malta', phone: '356' }, { code: 'MU', label: 'Mauritius', phone: '230' }, { code: 'MV', label: 'Maldives', phone: '960' }, { code: 'MW', label: 'Malawi', phone: '265' }, { code: 'MX', label: 'Mexico', phone: '52' }, { code: 'MY', label: 'Malaysia', phone: '60' }, { code: 'MZ', label: 'Mozambique', phone: '258' }, { code: 'NA', label: 'Namibia', phone: '264' }, { code: 'NC', label: 'New Caledonia', phone: '687' }, { code: 'NE', label: 'Niger', phone: '227' }, { code: 'NF', label: 'Norfolk Island', phone: '672' }, { code: 'NG', label: 'Nigeria', phone: '234' }, { code: 'NI', label: 'Nicaragua', phone: '505' }, { code: 'NL', label: 'Netherlands', phone: '31' }, { code: 'NO', label: 'Norway', phone: '47' }, { code: 'NP', label: 'Nepal', phone: '977' }, { code: 'NR', label: 'Nauru', phone: '674' }, { code: 'NU', label: 'Niue', phone: '683' }, { code: 'NZ', label: 'New Zealand', phone: '64' }, { code: 'OM', label: 'Oman', phone: '968' }, { code: 'PA', label: 'Panama', phone: '507' }, { code: 'PE', label: 'Peru', phone: '51' }, { code: 'PF', label: 'French Polynesia', phone: '689' }, { code: 'PG', label: 'Papua New Guinea', phone: '675' }, { code: 'PH', label: 'Philippines', phone: '63' }, { code: 'PK', label: 'Pakistan', phone: '92' }, { code: 'PL', label: 'Poland', phone: '48' }, { code: 'PM', label: 'Saint Pierre and Miquelon', phone: '508' }, { code: 'PN', label: 'Pitcairn', phone: '870' }, { code: 'PR', label: 'Puerto Rico', phone: '1' }, { code: 'PS', label: 'Palestine, State of', phone: '970' }, { code: 'PT', label: 'Portugal', phone: '351' }, { code: 'PW', label: 'Palau', phone: '680' }, { code: 'PY', label: 'Paraguay', phone: '595' }, { code: 'QA', label: 'Qatar', phone: '974' }, { code: 'RE', label: 'Reunion', phone: '262' }, { code: 'RO', label: 'Romania', phone: '40' }, { code: 'RS', label: 'Serbia', phone: '381' }, { code: 'RU', label: 'Russian Federation', phone: '7' }, { code: 'RW', label: 'Rwanda', phone: '250' }, { code: 'SA', label: 'Saudi Arabia', phone: '966' }, { code: 'SB', label: 'Solomon Islands', phone: '677' }, { code: 'SC', label: 'Seychelles', phone: '248' }, { code: 'SD', label: 'Sudan', phone: '249' }, { code: 'SE', label: 'Sweden', phone: '46' }, { code: 'SG', label: 'Singapore', phone: '65' }, { code: 'SH', label: 'Saint Helena', phone: '290' }, { code: 'SI', label: 'Slovenia', phone: '386' }, { code: 'SJ', label: 'Svalbard and Jan Mayen', phone: '47' }, { code: 'SK', label: 'Slovakia', phone: '421' }, { code: 'SL', label: 'Sierra Leone', phone: '232' }, { code: 'SM', label: 'San Marino', phone: '378' }, { code: 'SN', label: 'Senegal', phone: '221' }, { code: 'SO', label: 'Somalia', phone: '252' }, { code: 'SR', label: 'Suriname', phone: '597' }, { code: 'SS', label: 'South Sudan', phone: '211' }, { code: 'ST', label: 'Sao Tome and Principe', phone: '239' }, { code: 'SV', label: 'El Salvador', phone: '503' }, { code: 'SX', label: 'Sint Maarten (Dutch part)', phone: '1-721' }, { code: 'SY', label: 'Syrian Arab Republic', phone: '963' }, { code: 'SZ', label: 'Swaziland', phone: '268' }, { code: 'TC', label: 'Turks and Caicos Islands', phone: '1-649' }, { code: 'TD', label: 'Chad', phone: '235' }, { code: 'TF', label: 'French Southern Territories', phone: '262' }, { code: 'TG', label: 'Togo', phone: '228' }, { code: 'TH', label: 'Thailand', phone: '66' }, { code: 'TJ', label: 'Tajikistan', phone: '992' }, { code: 'TK', label: 'Tokelau', phone: '690' }, { code: 'TL', label: 'Timor-Leste', phone: '670' }, { code: 'TM', label: 'Turkmenistan', phone: '993' }, { code: 'TN', label: 'Tunisia', phone: '216' }, { code: 'TO', label: 'Tonga', phone: '676' }, { code: 'TR', label: 'Turkey', phone: '90' }, { code: 'TT', label: 'Trinidad and Tobago', phone: '1-868' }, { code: 'TV', label: 'Tuvalu', phone: '688' }, { code: 'TW', label: 'Taiwan, Province of China', phone: '886' }, { code: 'TZ', label: 'United Republic of Tanzania', phone: '255' }, { code: 'UA', label: 'Ukraine', phone: '380' }, { code: 'UG', label: 'Uganda', phone: '256' }, { code: 'US', label: 'United States', phone: '1', suggested: true }, { code: 'UY', label: 'Uruguay', phone: '598' }, { code: 'UZ', label: 'Uzbekistan', phone: '998' }, { code: 'VA', label: 'Holy See (Vatican City State)', phone: '379' }, { code: 'VC', label: 'Saint Vincent and the Grenadines', phone: '1-784' }, { code: 'VE', label: 'Venezuela', phone: '58' }, { code: 'VG', label: 'British Virgin Islands', phone: '1-284' }, { code: 'VI', label: 'US Virgin Islands', phone: '1-340' }, { code: 'VN', label: 'Vietnam', phone: '84' }, { code: 'VU', label: 'Vanuatu', phone: '678' }, { code: 'WF', label: 'Wallis and Futuna', phone: '681' }, { code: 'WS', label: 'Samoa', phone: '685' }, { code: 'XK', label: 'Kosovo', phone: '383' }, { code: 'YE', label: 'Yemen', phone: '967' }, { code: 'YT', label: 'Mayotte', phone: '262' }, { code: 'ZA', label: 'South Africa', phone: '27' }, { code: 'ZM', label: 'Zambia', phone: '260' }, { code: 'ZW', label: 'Zimbabwe', phone: '263' }, ];
import React from 'react' import { Progress, Segment } from 'shengnian-ui-react' const ProgressExampleAttached = () => ( <Segment> <Progress percent={50} attached='top' /> La la la la <Progress percent={50} attached='bottom' /> </Segment> ) export default ProgressExampleAttached
(function (angular) { "use strict"; angular .module('content.core') .directive('imageLoader', ImageLoaderDirective); ImageLoaderDirective.$inject = [ '$timeout' ]; function ImageLoaderDirective( $timeout ) { return { restrict: 'A', scope: true, link: function (scope, elem, attr) { scope.imageLoad = true; $timeout(function () { var image = elem[0]; image.src = image.getAttribute('data-src'); image.onload = function () { image.removeAttribute('data-src'); scope.imageLoad = false; scope.$digest(); }; }); } }; } })(angular);
var fs = require("fs"); var arguments = process.argv.splice(2); if (arguments.length === 0) { console.log('missing directory name param'); process.exit(); } var components = arguments[0]; var appName = '<%= appname %>'.toLocaleLowerCase(); // >>>>>>>>>>>>>>>>>>>>>>>>>>>> // update style template // >>>>>>>>>>>>>>>>>>>>>>>>>>>> var styleTpl = []; styleTpl.push('.' + appName + '-components-' + components + '{'); styleTpl.push(''); styleTpl.push('}'); styleTpl = styleTpl.join('\n'); // >>>>>>>>>>>>>>>>>>>>>>>>>>>> // update js template // >>>>>>>>>>>>>>>>>>>>>>>>>>>> var jsTpl = []; jsTpl.push("import React, {Component, render} from 'react';"); jsTpl.push("require('./"+components+".less');"); jsTpl.push("export default class "+ components+" extends Component {"); jsTpl.push(" render () {"); jsTpl.push(" return ("); jsTpl.push(" );"); jsTpl.push(" }"); jsTpl.push("}"); jsTpl = jsTpl.join('\n'); function mkdirSync (dir, mode) { mode = mode || 0755; if(!fs.existsSync(dir)) { fs.mkdirSync(dir, mode) } else { console.log('Directory [' + dir + '] has existed'); process.exit(); } } function writeFile (filename, content) { fs.open(filename, 'w', '0644', function (e, fd) { if(e) throw e; fs.write(fd, content, function(e){ if(e) throw e; fs.closeSync(fd); }); }); } mkdirSync('app/components/' + components); writeFile ('app/components/'+ components + '/' + components + '.less', styleTpl); writeFile ('app/components/'+ components + '/' + components + '.js', jsTpl); console.log('Create component Success!');
/** @module ember-audio */ import EmberObject, { computed, observer } from '@ember/object'; import ProcessorMixin from 'ember-audio/mixins/processor'; import io from 'ember-audio/mixins/io'; /** ## GainObject This is a gain object. A `gain` value of `1` will produce full volume ( 0dB ) output. The output will be the same level as the input with no attenuation or gain being applied. A `gain` value of `0` will produce no output. @class GainObject @namespace Objects @uses EmberAudio.IoMixin @uses EmberAudio.ProcessorMixin */ export default EmberObject.extend( io, ProcessorMixin, { /** This is required and is not automatically injected. Pass in the audioService when creating it. ``` GainObject.create({ audioService: this.get('audioService') }); ``` @property audioService @type {Object} @private */ audioService: null, /** ## gain @property gain @type {Number} @default 1 */ gain: 1, /** ## polarity If `true` then the polarity is positive. @property polarity @type {Boolean} */ polarity: true, /** ## mute If `true` then the audio will be muted (no sound output). This is the same as setting the gain to `0`. @property mute @type {Boolean} */ mute: false, /** This is the minimum value for this gain range. It can be used for setting the minimum value of the range slider. @property min @type {Number} */ min: 0, /** This is the maximum value for this gain range. It can be used for setting the maximum value of the range slider. @property max @type {Number} */ max: 1, /** @method init @private */ init() { this._super(...arguments); this.setGain(); }, /** Computed Property. The gain/polarity. @property _gain @type {Number} @private */ _gain: computed('gain', 'polarity', function () { var {gain, polarity} = this.getProperties('gain', 'polarity'); return (polarity) ? gain : gain * -1; }), /** @method createProcessor */ createProcessor() { var gain = this.get('gain'); var audioContext = this.get('audioContext'); if ( audioContext && typeof audioContext.createGain === 'function' ) { var processor = audioContext.createGain(); processor.gain.value = gain; return processor; } }, /** Set the gain. @method setGain @param {Number} gain @private */ setGain(gain) { const { processor, _gain, mute } = this.getProperties('processor', '_gain', 'mute'); if (isNaN(gain)) { gain = parseFloat(_gain); } if (processor && processor.gain) { processor.gain.value = (mute) ? 0 : gain; } }, /** @event gainChanged */ gainChanged: observer('gain', function() { this.setGain(); }), /** @event polarityChanged */ polarityChanged: observer('polarity', function() { this.setGain(); }), /** @event muteChanged */ muteChanged: observer('mute', function() { this.setGain(); }) });
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'print', 'en-gb', { toolbar: 'Print' } );
/* * httpx.js * * @file httpx.js * @version 0.2.0 * @description The simple HTTP / RESTful requests library of JavaScript (XHR). * @license MIT License * @author Pandao * {@link https://github.com/pandao/httpx.js} * @updateTime 2015-06-17 */ (function(factory) { "use strict"; if(typeof exports === "object" && typeof module === "object") { module.exports = factory(); } else if(typeof define === "function" && (define.amd || define.cmd)) { define(factory); } else { window.httpx = factory(); } })(function() { "use strict"; var httpx = { version : "0.2.0", /** * Create XHR object * * @return {object} XMLHttpRequest */ xhr : function() { return new XMLHttpRequest(); // IE7+, XMLHttpRequest Level 1 }, /** * Get default's configs * * @param {string} name * @return {string|object} */ defaults : function(name) { name = name || ""; var $defaults = { async : true, timeout : 3000, method : "GET", url : "", data : "", dataType : "text", headers : {}, contentType : "text/plain; charset=UTF-8", jsonp : "callback", // for query string success : function() {}, error : function(method, url) { console.error("HTTP Request Error: ", method, url, this.status + " (" + ((this.statusText) ? this.statusText : "Unkown Error / Timeout") + ")"); }, ontimeout : function(method, url) { console.error("HTTP Request Timeout: ", method, url, this.status + " (" + ((this.statusText) ? this.statusText : "Timeout") + ")"); } }; return (name !== "" && typeof name === "string") ? $defaults[name] : $defaults; }, /** * XHR requestor * * @param {object} options * @return {void} */ request : function(options) { options = options || {}; var settings = this.defaults(); for (var key in options) { if (options.hasOwnProperty(key)) { settings[key] = options[key]; } } var url = settings.url; var data = settings.data; var method = settings.method; //console.log("settings =>", settings); var urlData = urlBuild(url, data); data = urlData.data; if (method === "GET") { url = urlData.url; } var xhr = this.xhr(); var readyStateChange = function(e) { if ( xhr.readyState === 4 ) { if ( xhr.status === 200 || xhr.status === 304) { var result; switch (settings.dataType) { case "json" : result = JSON.parse(xhr.responseText); break; case "xml": result = xhr.responseXML; break; default: result = xhr.responseText; break; } settings.success.bind(xhr)(result); } else { settings.error.bind(xhr)(method, url, e); } } }; xhr.addEventListener("readystatechange", readyStateChange); xhr.addEventListener("error", function(e) { settings.error.bind(xhr)(method, url, e); }); xhr.addEventListener("timeout", function(e) { settings.ontimeout.bind(xhr)(method, url, e); }); xhr.open(method, url, true); if (method !== "GET") { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); } else { xhr.setRequestHeader("Content-type", settings.contentType); } // Custom http headers, you can override default's Content-Type header. for (var key2 in settings.headers) { xhr.setRequestHeader(key2, settings.headers[key2]); } xhr.$url = url; xhr.$method = method; xhr.$dataType = settings.dataType; xhr.timeout = settings.timeout; xhr.send(data); }, /** * Execute request for short methods * * @param {string} method HTTP method * @param {string|object} url request url or options k/v object * @param {object} data request datas * @param {function} callback Success callback * @param {function} error Error callback * @return {void} */ exec : function(method, url, data, callback, error) { data = data || {}; callback = callback || function() {}; error = error || this.defaults("error"); if (typeof data === "function") { error = callback; callback = data; data = ""; } var options = { url : url, method : method, data : data, success : callback, error : error }; if (typeof url === "object") { options = url; options.method = method; } this.request(options); }, /** * GET method * * @param {string|object} url request url or options k/v object * @param {object} data request datas * @param {function} callback Success callback * @param {function} error Error callback * @return {void} */ get : function(url, data, callback, error) { this.exec("GET", url, data, callback, error); }, /** * POST method * * @param {string|object} url request url or options k/v object * @param {object} data request datas * @param {function} callback Success callback * @param {function} error Error callback * @return {void} */ post : function(url, data, callback, error) { this.exec("POST", url, data, callback, error); }, /** * PUT method * * @param {string|object} url request url or options k/v object * @param {object} data request datas * @param {function} callback Success callback * @param {function} error Error callback * @return {void} */ put : function(url, data, callback, error) { this.exec("PUT", url, data, callback, error); }, /** * PATCH method * * @param {string|object} url request url or options k/v object * @param {object} data request datas * @param {function} callback Success callback * @param {function} error Error callback * @return {void} */ patch : function(url, data, callback, error) { this.exec("PATCH", url, data, callback, error); }, /** * DELETE method * * @param {string|object} url request url or options k/v object * @param {object} data request datas * @param {function} callback Success callback * @param {function} error Error callback * @return {void} */ "delete" : function(url, data, callback, error) { this.exec("DELETE", url, data, callback, error); }, /** * Get json, link jQuery getJSON() * * @param {string|object} url request url or options k/v object * @param {object} data request datas * @param {function} callback Success callback * @param {function} error Error callback * @return {void} */ json : function(url, data, callback, error) { data = data || {}; callback = callback || function() {}; error = error || this.defaults("error"); if (typeof data === "function") { error = callback; callback = data; data = ""; } var options = { url : url, dataType : "json", method : "GET", data : data, success : callback, error : error }; if (typeof url === "object") { options = url; options.method = "GET"; options.dataType = "json"; } this.request(options); }, /** * Alias json() * * @param {string|object} url request url or options k/v object * @param {object} data request datas * @param {function} callback Success callback * @param {function} error Error callback * @return {void} */ getJSON : function(url, data, callback, error) { this.json(url, data, callback, error); }, /** * JSONP method * * @param {string|object} url request url or options k/v object * @param {object} data request datas * @param {function} callback Success callback * @param {string} callbackName for query string name * @return {void} */ jsonp : function(url, data, callback, callbackName) { callbackName = callbackName || "callback"; if (typeof data === "function") { callbackName = callback; callback = data; data = ""; } var urlData = urlBuild(url, data); url = urlData.url; data = urlData.data; var fn = "__jsonp_" + callbackName + (new Date()).getTime() + "_" + Math.floor(Math.random() * 100000) + "__"; url += ((url.indexOf("?") < 0) ? "?" : "&") + callbackName + "=" + fn; var evalJsonp = function(callback) { return function(data) { if (typeof data === "string") { try { data = JSON.parse(data); } catch (e) {} } data = data || {}; callback(data, url); window[fn] = null; document.body.removeChild(document.getElementById(fn)); }; }; window[fn] = evalJsonp(callback); var script = document.createElement("script"); script.src = url; script.async = true; script.id = fn; document.body.appendChild(script); }, /** * Get script file, like jQuery getScript() * * @param {string} src javascript file path * @param {function} callback loaded callback function * @returns {void} */ getScript : function(src, callback) { if (src === "") { alert("Error: Get script source can't be empty"); return ; } callback = callback || function() {}; var head = document.getElementsByTagName("head")[0]; var loaded = document.querySelectorAll("script[src=\""+src+"\"]"); if (loaded.length > 0) { head.removeChild(loaded[0]); } var script = document.createElement("script"); script.type = "text/javascript"; script.onload = script.onreadystatechange = function() { if (!script.readyState || /loaded|complete/.test(script.readyState) ) { script.onload = script.onreadystatechange = null; script = undefined; callback(); } }; script.src = src; script.async = true; head.appendChild(script); } }; /** * Query url & strings build * * @param {string} url request url * @param {object} data request datas * @return {object} */ function urlBuild(url, data) { if (typeof data === "object") { var temp = []; for (var i in data) { temp.push(i + "=" + encodeURIComponent(data[i])); } data = temp.join("&"); } url = url + ( (url.indexOf("?") < 0) ? ( (data === "" || !data) ? "" : "?" ) : (data === "" || !data) ? "" : "&") + data; return { url : url, data : data }; }; return httpx; });
/* eslint import/no-extraneous-dependencies: "off" */ /* eslint import/no-unresolved: "off" */ import React from 'react' // prefer stateless functions const Greeting = props => { return ( // wrapping multiline JSX in parentheses <div>Hello, {props.name}</div> // no curly space ) } export default Greeting
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * * @providesModule RelayCompilerPublic * @format */ 'use strict'; var _require = require('./GraphQLCompilerPublic'), CodegenRunner = _require.CodegenRunner, ConsoleReporter = _require.ConsoleReporter, MultiReporter = _require.MultiReporter; module.exports = { Compiler: require('./RelayCompiler'), ConsoleReporter: ConsoleReporter, /** @deprecated Use JSModuleParser. */ FileIRParser: require('./RelayJSModuleParser'), FileWriter: require('./RelayFileWriter'), IRTransforms: require('./RelayIRTransforms'), JSModuleParser: require('./RelayJSModuleParser'), MultiReporter: MultiReporter, Runner: CodegenRunner, formatGeneratedModule: require('./formatGeneratedModule') };
'use strict' var KeyPrefix = '/es/loaded:' var KeyVersion = KeyPrefix + 'version:' function createStore (localStorage) { function enumKeys () { var keys = [] for (var i = 0, len = localStorage.length; i < len; i++) { var key = localStorage.key(i) if (key.startsWith(KeyPrefix)) { keys.push(localStorage.key(i)) } } return keys } return { keys: enumKeys, getItem: localStorage.getItem.bind(localStorage), setItem: localStorage.setItem.bind(localStorage), removeItem: localStorage.removeItem.bind(localStorage), clear: function () { var keys = enumKeys() for (var i = 0, len = keys.length; i < len; i++) { localStorage.removeItem(keys[i]) } return keys } } } function useMemory () { var store = Object.create(null) return { keys: function () { return Object.getOwnPropertyNames(store) }, getItem: function (key) { return store[key] || null }, setItem: function (key, value) { store[key] = value }, removeItem: function (key) { delete store[key] }, clear: function () { store = Object.create(null) } } } function keyOf (uri) { return typeof uri === 'string' && uri ? KeyPrefix + uri : null } function versionKeyOf (uri) { return typeof uri === 'string' && uri ? KeyVersion + uri : null } function generateTimestamp (version) { return 'local:' + Math.trunc(Date.now() / 600 / 1000) } function manage (store) { var management = Object.create(null) management.list = function list (filter) { var uris = [] var keys = store.keys() for (var i = 0; i < keys.length; i++) { if (keys[i].startsWith(KeyVersion)) { if (typeof filter !== 'string' || keys[i].indexOf(filter) > 0) { uris.push([keys[i].substring(KeyVersion.length), store.getItem(keys[i])]) } } } return uris } management.read = function read (uri) { var keys = store.keys() for (var i = 0; i < keys.length; i++) { if (keys[i].startsWith(KeyVersion)) { if (typeof uri !== 'string' || keys[i].indexOf(uri) > 0) { return store.getItem(keyOf(keys[i].substring(KeyVersion.length))) } } } } management.reset = function reset (filter) { var counter = 0 var keys = store.keys() for (var i = 0; i < keys.length; i++) { if (keys[i].startsWith(KeyVersion)) { if (typeof filter !== 'string' || keys[i].indexOf(filter) > 0) { counter++ store.removeItem(keys[i]) store.removeItem(keyOf(keys[i].substring(KeyVersion.length))) } } } return counter } management.clear = function clear () { store.clear() return true } return management } module.exports = function cacheIn ($void) { var store = $void.isNativeHost ? useMemory() : createStore(window.localStorage) var cache = Object.create(null) cache.store = manage(store) cache.get = function get (uri) { var key = keyOf(uri) return key ? store.getItem(key) : null } cache.ver = function ver (uri) { var key = versionKeyOf(uri) return key ? store.getItem(key) : null } cache.isTimestamp = function isTimestamp (version) { return version.startsWith('local:') } cache.isExpired = function isExpired (version) { return version !== generateTimestamp() } cache.set = function set (uri, value, version) { if (typeof value !== 'string') { return null // invalid call. } var key = keyOf(uri) var verKey = versionKeyOf(uri) if (!key || !verKey) { return null // invalid call. } if (typeof version !== 'string' || !key) { version = generateTimestamp() } store.setItem(key, value) store.setItem(verKey, version) return version } return cache }
const expect = require('chai').expect; const chai = require("chai"); const chaiAsPromised = require("chai-as-promised"); const should = require('chai').should(); const cf = require('../index'); chai.use(chaiAsPromised); const TEST_NUMBER = 1234; const TEST_STRING_1 = 'A'; const TEST_STRING_2 = 'B'; const TEST_OBJECT = { prop: TEST_NUMBER }; describe("bind", function() { it("takes one argument and returns a function", function() { const result = cf.bind(function* () {}); return expect(result).to.be.a('function'); }); it("binds the given GeneratorFunction to the given context", function() { return cf.bind(function* () { return this.prop; }, TEST_OBJECT).should.eventually.equal(TEST_NUMBER); }); it("binds the given GeneratorFunction to the given context and passes arguments to the function", function() { const result = TEST_STRING_1 + TEST_STRING_2 + TEST_NUMBER; return cf.bind(function* (arg1, arg2) { return arg1 + arg2 + this.prop; }, TEST_OBJECT, TEST_STRING_1, TEST_STRING_2).should.eventually.equal(result); }); it("binds the given Function to the given context", function() { return cf.bind(function() { return this.prop; }, TEST_OBJECT).should.eventually.equal(TEST_NUMBER); }); it("binds the given Function to the given context and passes arguments to the function", function() { const result = TEST_STRING_1 + TEST_STRING_2 + TEST_NUMBER; return cf.bind(function(arg1, arg2) { return arg1 + arg2 + this.prop; }, TEST_OBJECT, TEST_STRING_1, TEST_STRING_2).should.eventually.equal(result); }); }); describe("lazyBind", function() { it("takes one argument and returns a function", function() { const result = cf.lazyBind(function* () {}); return expect(result).to.be.a('function'); }); it("binds the given GeneratorFunction to the given context", function() { return cf.lazyBind(function* () { return this.prop; }, TEST_OBJECT)().should.eventually.equal(TEST_NUMBER); }); it("returns a function wrapper that waits to be executed and when executed is bound to the given context", function() { const result = cf.lazyBind(function* () { return this.prop; }, TEST_OBJECT); expect(result).to.be.a('function'); return result().should.eventually.equal(TEST_NUMBER); }); it("binds the given GeneratorFunction to the given context and passes arguments to the function", function() { const result = TEST_STRING_1 + TEST_STRING_2 + TEST_NUMBER; return cf.lazyBind(function* (arg1, arg2) { return arg1 + arg2 + this.prop; }, TEST_OBJECT)(TEST_STRING_1, TEST_STRING_2).should.eventually.equal(result); }); it("binds the given Function to the given context and passes arguments to the function", function() { const result = TEST_STRING_1 + TEST_STRING_2 + TEST_NUMBER; return cf.lazyBind(function (arg1, arg2) { return arg1 + arg2 + this.prop; }, TEST_OBJECT)(TEST_STRING_1, TEST_STRING_2).should.eventually.equal(result); }); });
import {getEl,getFirstElementChild} from './../tools'; //组件初始化 function componentHandler(node) { let nodeName = node.nodeName.toLowerCase(), elHtml = getEl(this.components[nodeName]) != null ? getEl(this.components[nodeName]).innerHTML : this.components[nodeName], //复制组件节点 cloneNode = node.cloneNode(true), nodeParent = node.parentNode; //复制的组件中添加子节点 cloneNode.innerHTML = elHtml; //获取组件中的节点内容 let componentNode = getFirstElementChild(cloneNode); nodeParent.replaceChild(componentNode, node); return componentNode; } export default componentHandler;
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.UNDEFINED_INPUT_ERROR = exports.INVALID_BUFFER = exports.isEnd = exports.END = undefined; exports.emitter = emitter; exports.channel = channel; exports.eventChannel = eventChannel; var _utils = require('./utils'); var _buffers = require('./buffers'); var CHANNEL_END_TYPE = '@@redux-saga/CHANNEL_END'; var END = exports.END = { type: CHANNEL_END_TYPE }; var isEnd = exports.isEnd = function isEnd(a) { return a && a.type === CHANNEL_END_TYPE; }; function emitter() { var subscribers = []; function subscribe(sub) { subscribers.push(sub); return function () { return (0, _utils.remove)(subscribers, sub); }; } function emit(item) { var arr = subscribers.slice(); for (var i = 0, len = arr.length; i < len; i++) { arr[i](item); } } return { subscribe: subscribe, emit: emit }; } var INVALID_BUFFER = exports.INVALID_BUFFER = 'invalid buffer passed to channel factory function'; var UNDEFINED_INPUT_ERROR = exports.UNDEFINED_INPUT_ERROR = 'Saga was provided with an undefined action'; if (process.env.NODE_ENV !== 'production') { exports.UNDEFINED_INPUT_ERROR = UNDEFINED_INPUT_ERROR += '\nHints:\n - check that your Action Creator returns a non-undefined value\n - if the Saga was started using runSaga, check that your subscribe source provides the action to its listeners\n '; } function channel(buffer) { var closed = false; var takers = []; if (arguments.length > 0) { (0, _utils.check)(buffer, _utils.is.buffer, INVALID_BUFFER); } else { buffer = _buffers.buffers.fixed(); } function checkForbiddenStates() { if (closed && takers.length) { throw (0, _utils.internalErr)('Cannot have a closed channel with pending takers'); } if (takers.length && !buffer.isEmpty()) { throw (0, _utils.internalErr)('Cannot have pending takers with non empty buffer'); } } function put(input) { checkForbiddenStates(); (0, _utils.check)(input, _utils.is.notUndef, UNDEFINED_INPUT_ERROR); if (!closed) { if (takers.length) { for (var i = 0; i < takers.length; i++) { var cb = takers[i]; if (!cb[_utils.MATCH] || cb[_utils.MATCH](input)) { takers.splice(i, 1); return cb(input); } } } else { buffer.put(input); } } } function take(cb, matcher) { checkForbiddenStates(); (0, _utils.check)(cb, _utils.is.func, 'channel.take\'s callback must be a function'); if (arguments.length > 1) { (0, _utils.check)(matcher, _utils.is.func, 'channel.take\'s matcher argument must be a function'); cb[_utils.MATCH] = matcher; } if (closed && buffer.isEmpty()) { cb(END); } else if (!buffer.isEmpty()) { cb(buffer.take()); } else { takers.push(cb); cb.cancel = function () { return (0, _utils.remove)(takers, cb); }; } } function close() { checkForbiddenStates(); if (!closed) { closed = true; if (takers.length) { var arr = takers; takers = []; for (var i = 0, len = arr.length; i < len; i++) { arr[i](END); } takers = []; } } } return { take: take, put: put, close: close, get __takers__() { return takers; }, get __closed__() { return closed; } }; } function eventChannel(subscribe) { var buffer = arguments.length <= 1 || arguments[1] === undefined ? _buffers.buffers.none() : arguments[1]; var matcher = arguments[2]; /** should be if(typeof matcher !== undefined) instead? see PR #273 for a background discussion **/ if (arguments.length > 2) { (0, _utils.check)(matcher, _utils.is.func, 'Invalid match function passed to eventChannel'); } var chan = channel(buffer); var unsubscribe = subscribe(function (input) { if (isEnd(input)) { chan.close(); } else if (!matcher || matcher(input)) { chan.put(input); } }); return { take: chan.take, close: function close() { if (!chan.__closed__) { chan.close(); unsubscribe(); } } }; }
//~ name c337 alert(c337); //~ component c338.js
'use strict'; angular.module('myApp.view2', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view2', { templateUrl: 'view2/view2.html', controller: 'View2Ctrl' }); }]) .controller('View2Ctrl', [function() { }]) .directive('myHtml', function () { return{ restrict:'A', link: function (scope,element,attr) { // scope.content="aaa"; element.find("li div").bind('click', function(e){ scope.content=$(this).html(); scope.$apply(); }); } }; }) ;
describe("Protobone.Model", function() { describe("#url", function() { it("exists", function() { expect(Protobone.Model.prototype.url).toEqual(jasmine.any(Function)); }); it("returns an url for a new model", function() { var M = Class.create(Protobone.Model, { urlRoot: '/MyModel' }); var m = new M(); expect(m.url()).toEqual('/MyModel'); }); it("returns an url for an existing model", function() { var M = Class.create(Protobone.Model, { urlRoot: '/MyModel' }); var m = new M({id: 5}); expect(m.url()).toEqual('/MyModel/5'); }); it("throws an exception if urlRoot is null", function() { var m = new Protobone.Model({id: 5}); expect(m.url).toThrow(); }); }); });
const path = require('path') module.exports = { context: __dirname, entry: './js/ClientApp.jsx', devtool: 'cheap-eval-source-map', output: { path: path.join(__dirname, 'public'), filename: 'bundle.js' }, devServer: { publicPath: '/public/', historyApiFallback: true }, resolve: { extensions: ['.js', '.jsx', '.json'] }, stats: { colors: true, reasons: true, chunks: true }, module: { rules: [ { enforce: 'pre', test: /\.jsx?$/, loader: 'eslint-loader', exclude: /node_modules/ }, { test: /\.jsx?$/, loader: 'babel-loader' }, { test: /\.svg$/, use: [ { loader: 'babel-loader' }, { loader: 'react-svg-loader', options: { jsx: true // true outputs JSX tags } } ] } ] } }
/* global it, history, describe, location, expect */ var jsdom = require('../index') describe('simple', function () { jsdom() it('has document', function () { var div = document.createElement('div') expect(div.nodeName).eql('DIV') }) it('has history', function () { history.pushState({}, 'abc', '#/a/b/c') expect(location.href).match(/\/a\/b\/c$/) }) })
'use strict' // 3rd const debug = require('debug')('app:db:dice') const assert = require('better-assert') const knex = require('knex')({ client: 'pg' }) const _ = require('lodash') // 1st const { pool } = require('./util') const { sql } = require('pg-extra') // Note: The db/*.js files are an ongoing effort to // split apart the db/index.js monolith. //////////////////////////////////////////////////////////// // Generalized update function that takes an object of // field/values to be updated. exports.updateUser = async function(userId, fields) { assert(Number.isInteger(userId)) assert(_.isPlainObject(fields)) // Validate fields const WHITELIST = ['gender'] Object.keys(fields).forEach(key => { if (WHITELIST.indexOf(key) === -1) { throw new Error('FIELD_NOT_WHITELISTED') } }) // Build SQL string const str = knex('users') .where({ id: userId }) .update(fields) .toString() return pool._query(str) } //////////////////////////////////////////////////////////// exports.unapproveUser = async userId => { assert(Number.isInteger(userId)) return pool.query(sql` UPDATE users SET approved_by_id = NULL, approved_at = NULL WHERE id = ${userId} `) } //////////////////////////////////////////////////////////// exports.approveUser = async ({ approvedBy, targetUser }) => { assert(Number.isInteger(approvedBy)) assert(Number.isInteger(targetUser)) return pool.query(sql` UPDATE users SET approved_by_id = ${approvedBy}, approved_at = NOW() WHERE id = ${targetUser} `) } ////////////////////////////////////////////////////////////