text
stringlengths
2
6.14k
import apiClient from './apiClient'; export default { login(data) { return apiClient.post('/user/login', { data }); } };
var ligle = require('ligle-engine')(); var logger = ligle.util.logger('basic.js'); // 模型 module.exports = ligle.model.ModelBase.extend({ __className:'basic', __upDir:'basic', init:function(obj){ this._super(obj); }, coll:{name:'basic',fields:{}}, rest:{}, });
import ApplicationSerializer from 'ember-fhir-adapter/serializers/application'; var QuestionnaireGroupComponent = ApplicationSerializer.extend({ attrs:{ concept : {embedded: 'always'}, group : {embedded: 'always'}, question: {embedded: 'always'} } }); export default QuestionnaireGroupComponent;
/** * Dependencies */ var NOOT = require('../../')('namespace', 'error', 'http'); var _ = require('lodash'); var mongoose; var ValidationError; var CastError; var defineMongoose = function() { if (!mongoose) { mongoose = require('mongoose'); ValidationError = mongoose.Error.ValidationError; CastError = mongoose.Error.CastError; } }; /*********************************************************************************************************************** * @class Errors * @static * @namespace NOOT **********************************************************************************************************************/ var Errors = NOOT.Namespace.create({ /** * @property InternalServerError * @static * @type Class */ InternalServerError: NOOT.Error.extend({ name: 'InternalServerError', statusCode: NOOT.HTTP.InternalServerError }), /** * @property NotImplemented * @static * @type Class */ NotImplemented: NOOT.Error.extend({ name: 'NotImplementedError', statusCode: NOOT.HTTP.NotImplemented }), /** * @property Unavailable * @static * @type Class */ Unavailable: NOOT.Error.extend({ name: 'UnavailableError', statusCode: NOOT.HTTP.ServiceUnavailable }), /** * @property BadRequest * @static * @type Class */ BadRequest: NOOT.Error.extend({ name: 'BadRequestError', statusCode: NOOT.HTTP.BadRequest }), /** * @property Unauthorized * @static * @type Class */ Unauthorized: NOOT.Error.extend({ name: 'UnauthorizedError', statusCode: NOOT.HTTP.Unauthorized }), /** * @property Forbidden * @static * @type Class */ Forbidden: NOOT.Error.extend({ name: 'ForbiddenError', statusCode: NOOT.HTTP.Forbidden }), /** * @property NotFound * @static * @type Class */ NotFound: NOOT.Error.extend({ name: 'NotFoundError', statusCode: NOOT.HTTP.NotFound }), /** * @property Conflict * @static * @type Class */ Conflict: NOOT.Error.extend({ name: 'ConflictError', statusCode: NOOT.HTTP.Conflict }), fromMongooseError: function(err) { defineMongoose(); if (err instanceof ValidationError || err instanceof CastError) return new this.BadRequest(err.toString()); else if (err.code === 11000) return new this.Conflict(err.message); return new this.InternalServerError(err.message); }, /** * Given a status code, returns an instance of one the defined NOOT.Errors. If no defined NOOT.Errors is found, then * NOOT.Errors.InternalServerError will be used as a default. * * @method fromStatusCode * @param {Number} statusCode * @param {*...} [errorParams] NOOT.Error parameters */ fromStatusCode: function() { var args = NOOT.makeArray(arguments); var statusCode = args.shift(); var ErrorClass = _.find(Errors, function(item) { return item.prototype.statusCode === statusCode; }) || Errors.InternalServerError; return (function() { function Wrapper() { return ErrorClass.apply(this, args); } Wrapper.prototype = ErrorClass.prototype; return new Wrapper(); })(); } }); /** * @exports */ module.exports = Errors;
/** * @ignore * attribute management and event in one * @author yiminghe@gmail.com, lifesinger@gmail.com */ KISSY.add('base', function (S, Attribute, EventCustom) { /** * @class KISSY.Base * @mixins KISSY.Event.Target * @mixins KISSY.Base.Attribute * * A base class which objects requiring attributes and custom event support can * extend. attributes configured * through the static {@link KISSY.Base#static-ATTRS} property for each class * in the hierarchy will be initialized by Base. */ function Base(config) { var self = this, c = self.constructor; // save user config self.userConfig = config; // define while (c) { addAttrs(self, c['ATTRS']); c = c.superclass ? c.superclass.constructor : null; } // initial initAttrs(self, config); } /** * The default set of attributes which will be available for instances of this class, and * their configuration * * By default if the value is an object literal or an array it will be 'shallow' cloned, to * protect the default value. * * for example: * @example * { * x:{ * value: // default value * valueFn: // default function to get value * getter: // getter function * setter: // setter function * } * } * * @property ATTRS * @member KISSY.Base * @static * @type {Object} */ function addAttrs(host, attrs) { if (attrs) { for (var attr in attrs) { // 子类上的 ATTRS 配置优先 // 父类后加,父类不覆盖子类的相同设置 // 属性对象会 merge // a: {y: {getter: fn}}, b: {y: {value: 3}} // b extends a // => // b {y: {value: 3, getter: fn}} host.addAttr(attr, attrs[attr], false); } } } function initAttrs(host, config) { if (config) { for (var attr in config) { // 用户设置会调用 setter/validator 的,但不会触发属性变化事件 host.setInternal(attr, config[attr]); } } } S.augment(Base, EventCustom.Target, Attribute); Base.Attribute = Attribute; S.Base = Base; return Base; }, { requires: ['base/attribute', 'event/custom'] });
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("path", { fillOpacity: ".3", d: "M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v9.17h2L13 7v5.5h2l-1.07 2H17V5.33C17 4.6 16.4 4 15.67 4z" }), h("path", { d: "M11 20v-5.5H7v6.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V14.5h-3.07L11 20z" })), 'BatteryCharging30');
#! /usr/local/bin/node 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _minimist = require('minimist'); var _minimist2 = _interopRequireDefault(_minimist); var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); var _libLoadJs = require('./lib/load.js'); var _libLoadJs2 = _interopRequireDefault(_libLoadJs); var _libWriteJs = require('./lib/write.js'); var _libWriteJs2 = _interopRequireDefault(_libWriteJs); var _libParseJs = require('./lib/parse.js'); var _libParseJs2 = _interopRequireDefault(_libParseJs); var debug = (0, _debug2['default'])('todo:index'); var source = process.env.TODO_DB || '.todo.json'; var args = (0, _minimist2['default'])(process.argv.slice(2)); debug('Provided arguments: %o', args); var tasks = (0, _libLoadJs2['default'])(source); var result = (0, _libParseJs2['default'])(args, tasks); (0, _libWriteJs2['default'])(result);
/*global require*/ 'use strict'; require.config({ shim: { underscore: { exports: '_' }, backbone: { deps: [ 'underscore', 'jquery' ], exports: 'Backbone' }, foundation: { deps: ['jquery'], exports: 'foundation' }, downloadify: { deps: ['jquery'], exports: 'downloadify' }, swfobject: { deps: [], exports: 'swfobject' } }, paths: { jquery: '../vendor/jquery/jquery.min', backbone: '../vendor/backbone/backbone-min', underscore: '../vendor/underscore/underscore-min', foundation: '../vendor/foundation/foundation.min', text: '../vendor/requirejs-text/text', d3: '../vendor/d3/d3.v3.min', sylvester: '../vendor/sylvester/sylvester', downloadify: '../vendor/downloadify/js/downloadify.min', swfobject: '../vendor/downloadify/js/swfobject', detect: '../vendor/detect/detect.min' } }); require([ 'jquery', 'backbone', 'underscore', 'routes/app' ], function ( $, Backbone, _, App ) { window.mentalmodeler = new App(); Backbone.history.start(); }); function flashInitialized() { window.mentalmodeler.appModel.start(); }
define(['plugins/http', 'durandal/app', 'knockout', 'viewmodels/newGame'], function(http, app, ko, NewGame) { var ctor = function () { var self = this; function gameObj(eventId, name, image, rules, scoreType) { this.eventId = eventId; this.name = name; // str this.image = image; // url this.rules = rules; // str this.scoreType = scoreType; // str } self.games = ko.observableArray([]); function getGames() { // http.get(app.url+'event/78f9075c-f81c-42fe-9d50-63e666b5450d/games').then(function(response) { // for(var i = 0; i < response.items.length; i++) { // self.games.push(new gameObj("NAME", response.items[i].media.m, "HDLSFHSD", "sdfhjksdhfdjs")); // } // }); http.get('https://public.opencpu.org/ocpu/library/').then(function(response) { console.dir(response); for(var i = 0; i < response.items.length; i++) { self.games.unshift(new gameObj(app.event.id, "game name", response.items[i].media.m, "rules", "timed")); } }); } this.showHeader = true; this.title = 'Games'; this.addingGame = ko.observable(false); this.imgSrc = function() { var randomNum1 = Math.round((Math.random()*100+300)/10)*10; var randomNum2 = Math.round((Math.random()*100+200)/10)*10; return "http://placesheen.com/"+randomNum1+"/"+randomNum2; }; this.newItem = function(game) { var gaaame = new NewGame(); gaaame.game = game || new gameObj(app.event.id, "", "", "", "timed"); app.showDialog(gaaame).then(function(result) { if(result) { console.dir(result); //http.post(app.url+'event/'+app.event.id+'/games/', JSON.stringify(result)).then(function(response) { self.games.unshift(new gameObj(result.eventId, result.name, "", result.rules, result.scoreType)); //}); } }); }; getGames(); }; return ctor; });
export const uri = 'os' export const getMemory = (state, id) => state[uri].memory[id]
//// NPM const chalk = require('chalk') //// CORE const path = require('path') //// LOCAL const api = require('../api') const { format, log } = require('../log') const { dft } = require('../viewer') const config = require('../../config/config.json') module.exports = { description: chalk`File System stored T-SQL scripts\n Uses files from the configured scripts folder {italic config.cli.scripts.path}: '${config.cli.scripts.path}' Filtered for the configured script file extension {italic config.cli.scripts.filter}: '${config.cli.scripts.filter}' Scripts are archived into the 'scripts' nedb collection`, args: { action: { archive: `Save a copy of all scripts in the scripts folder to the scripts archive`, backup: `Save a copy of a selected script to the scripts archive`, browse: `Open a selected script in the browser`, develop: `Open a selected script in the configured IDE: '${config.ide}'`, edit: `Open a selected script in the configured editor: '${config.editor}'`, get: `Display a script from the 'scripts' folder (Read Only, does not touch cache)`, load: `${dft()} Load a script from the 'scripts' folder to the Batch cache`, new: `Create a new script file`, restore: `Show a script from the 'scripts' archive (no load to batch cache)`, save: `Save the current batch in cache to a script file)` }, filter: { 'default': config.cli.scripts.filter, }, option: {} }, dispatch: async args => { let scriptName let text let filter = config.cli.scripts.filter let path = config.cli.scripts.path let available = await api.listFiles(path.resolve(path), filter) // for (let name of available) { // if (!args.filter || name.startsWith(args.filter)) { // available.push(name.replace(filter, ``)) // } // } switch (args.action) { case ('archive'): for (let name of available) { text = await api.fileToJSON(path.resolve(path, name + filter)) store.scripts.put(name, text) } break case ('backup'): // !!! ??? needs to be a checked list... They are in the repo too scriptName = await api.choose(available, 'Script to save (upsert) into archive') store.scripts.upsert(scriptName, await fileToJSON(path.resolve(path, scriptName, filter))) break case ('browse'): scriptName = await api.choose(available, 'Script to open in browser') doc = await view.highlightSource(path.resolve(path, scriptName.concat('.sql'))) await api.spawnTask(`${config.browser.command} ${doc}`) break case ('develop'): if (config.ide) { scriptName = await api.choose(available, `Script to develop (opens in '${config.ide}')`) await api.spawnTask(`${config.ide} ${path.resolve(path, scriptName + filter)}`) } else log('warn', 'no IDE configured') break case ('edit'): scriptName = await api.choose(available, `Script to edit (opens in '${config.editor}'`) await api.editFile(path.resolve(path, scriptName + filter)) break case ('get'): scriptName = await api.choose(available, 'Script to display (does not touch Batch)') log('log', await api.fileToJSON(path.resolve(path, scriptName + filter))) break case ('new'): if (config.ide) { scriptName = await api.input(`New script name (opens in '${config.ide}')`) await api.spawnTask(`${config.ide} ${path.resolve(path, scriptName + filter)}`) } else log('warn', 'no IDE configured') break case ('restore'): scriptName = await api.choose(await store.scripts.listNames(), 'Select script to display without spoiling the Batch') break case ('save'): log('log', await api.jsonToFIle(path.resolve(path, scriptName + filter))) break case ('load'): default: scriptName = await api.choose(available, 'Select script to load to Batch cache') await api.fileToBatch(path.resolve(path, scriptName)) break } } }
/** * @fileOverview router * @name index.js<f/socket/router> * @author Masaki Sueda <sueda_masaki@cyberagent.co.jp> */ var fs = require('fs'); var url = require('url'); var path = require('path'); var _ = require('underscore'); var beezlib = require('beezlib'); var bootstrap = require('../../bootstrap'); var config = bootstrap.config; var store = bootstrap.store; var Router = function () { }; module.exports = new Router(); /** * Return the socket data. * * @param {String} req * @param {Function} callback */ Router.prototype.transmission = function transmission(req, namespace, format, callback) { if (!_.isString(req)) { beezlib.logger.debug("<< request should be string.") return callback(req); } if (!config.app.socket.use) { beezlib.logger.debug("<< Socket Server is not running. application/javascript error"); return callback(req); } if (!store.socket) { beezlib.logger.debug("<< Socket Data is not set. application/javascript error"); return callback(req); } /** * create regexp by format * @param {String} format - formatted string */ var formatRegexp = function formatRegexp(format) { format = format.replace(/[\-{}\[\]+?.,\\\^$|#\s]/g, '\\$&') .replace(/%.{1}/g, '(.+?)'); return new RegExp('^' + format + '$'); }; /** * format string */ var formatString = function formatString() { var args = Array.prototype.slice.call(arguments); var str = args.pop(); for (var i = 0; i < args.length; i++) { str = str.replace(/%.{1}/, args[i]); } return str; }; /** * get socket data */ var load = function load(key, noRetry) { if (store.socket.mapping.hasOwnProperty(key)) { var file = store.socket.mapping[key]; store.socket.reload(file); return store.socket.data[key]; } if (!noRetry) { store.socket.reloadAll(); return load(key, true); } return null; }; var walkAry = function walkAry(d) { for (var g = 0; g < d.length; g++) { if (_.isString(d[g])) { d[g] = _.template(d[g])(); } else if (_.isArray(d[g])) { walkAry(d[g]); } else if (_.isObject(d[g])) { walkObj(d[g]); } } }; var walkObj = function walkObj(d) { var v = _.keys(d); for (var k = 0; k < v.length; k++) { if (_.isString(d[v[k]])) { d[v[k]] = _.template(d[v[k]])(); } else if (_.isArray(d[v[k]])) { walkAry(d[v[k]]); } else if (_.isObject(d[v[k]])) { walkObj(d[v[k]]); } } }; format = format || '%s.%s:%s'; var regexp = format && formatRegexp(format); var match = req.match(regexp); if (!match) { beezlib.logger.debug('data format is illegal'); return callback && callback('data format is illegal'); } var service = match[1]; var method = match[2]; var body = match[3]; try { body = JSON.parse(body); var datas = load(namespace); var data = (datas[service] && datas[service][method]) || datas[method]; var delay = config.app.socket.delay || body.__delay__ || 0; if (!data) { beezlib.logger.error('<< res.json application/javascript error'); } if (body.__error__) { var err = new Error('Custom Response close connection'); return callback && callback(err); } // set request id data._req = body._req; if (delay) { beezlib.logger.debug('Custom Response delay time:', delay); } setTimeout(function() { callback && callback(null, formatString(service, method, JSON.stringify(data), format)); }, delay); } catch (e) { beezlib.logger.error(e); } }; Router.prototype.setup = function setup(app) { var self = this; var io = app.get('io'); var namespace = config.app.socket.namespace; var room; // set events for each namespace _.each(namespace, function (name) { var index = name.indexOf('/'); if (index === 0) { name = name.substr(1); } io.of('/' + name).on('connection', function (socket) { beezlib.logger.debug('connection start'); socket.on('disconnect', function (socket) { beezlib.logger.warn('<< disconnect namespace:', name); }); socket.on('join', function (_room) { if (_room) { beezlib.logger.debug('<< join the room :', _room); socket.join(_room); room = _room; socket.emit('joined'); } }); socket.on('message', function (req, format) { beezlib.logger.debug('<< get message :', req); self.transmission(req, name, format, function (err, res) { if (err) { socket.emit('error', err); return; } socket.emit('message', res); if (room) { beezlib.logger.debug('>> send message to room :', room, ' namespace: ', name); socket.broadcast.emit('message', res); } else { beezlib.logger.debug('>> send message to all. namespace: ', name); socket.broadcast.to(room).emit('message', res); } }); }); socket.on('error', function (err) { beezlib.logger.error(err); socket.disconnect(); }); }); }); };
const AWS = require('aws-sdk'); const __ = require('lodash'); const BaseClient = require('./baseClient'); class ApplicationAutoScalingClient extends BaseClient { get _awsApplicationAutoScalingClient() { if(!this._internalApplicationAutoScalingClient) { let params = { accessKeyId: this._accessKey, secretAccessKey: this._secretKey, apiVersion: '2016-02-06', region: this._region }; this._internalApplicationAutoScalingClient = new AWS.ApplicationAutoScaling(params); } return this._internalApplicationAutoScalingClient; } /** * Registers or updates a scalable target. A scalable target is a resource that Application Auto Scaling can scale out or scale in. After you have registered a scalable target, you can use this operation to update the minimum and maximum values for your scalable dimension. * @param {Object} params * @param {string} params.ResourceId - e.g. service * @param {string} params.ScalableDimension * @param {string} params.ServiceNamespace * @param {int} params.MaxCapacity * @param {int} params.MinCapacity * @param {string} params.RoleARN * @return {Promise.<TResult>|*} */ async registerScalableTarget(params) { return await this._awsApplicationAutoScalingClient.registerScalableTarget(params).promise(); } /** * Creates or updates a policy for an Application Auto Scaling scalable target. * @param {Object} params * @param {string} params.PolicyName * @param {string} params.ResourceId * @param {string} params.ScalableDimension * @param {string} params.ServiceNamespace * @param {string} params.PolicyType * @param {object} params.StepScalingPolicyConfiguration * @return {Promise.<TResult>|*} */ async putScalingPolicy(params) { return await this._awsApplicationAutoScalingClient.putScalingPolicy(params).promise(); } } module.exports = ApplicationAutoScalingClient;
8.0-alpha3:a5a082039926b30f9cb681c9b009146be4e6538db1040ec084cfe7c8f36469ff 8.0-alpha4:a5a082039926b30f9cb681c9b009146be4e6538db1040ec084cfe7c8f36469ff 8.0-alpha5:a5a082039926b30f9cb681c9b009146be4e6538db1040ec084cfe7c8f36469ff 8.0-alpha6:a5a082039926b30f9cb681c9b009146be4e6538db1040ec084cfe7c8f36469ff 8.0-alpha7:a5a082039926b30f9cb681c9b009146be4e6538db1040ec084cfe7c8f36469ff 8.0-alpha8:a5a082039926b30f9cb681c9b009146be4e6538db1040ec084cfe7c8f36469ff 8.0-alpha9:a5a082039926b30f9cb681c9b009146be4e6538db1040ec084cfe7c8f36469ff 8.0-alpha10:a5a082039926b30f9cb681c9b009146be4e6538db1040ec084cfe7c8f36469ff 8.0-alpha11:a5a082039926b30f9cb681c9b009146be4e6538db1040ec084cfe7c8f36469ff 8.0-alpha12:e8244cfdaeb9c2394a39b2012c82d2c444235e1393103ff6eaee96e302405ea8 8.0-alpha13:e8244cfdaeb9c2394a39b2012c82d2c444235e1393103ff6eaee96e302405ea8 8.0.0-alpha14:e8244cfdaeb9c2394a39b2012c82d2c444235e1393103ff6eaee96e302405ea8 8.0.0-alpha15:047020ff109a00bf7a02a450b0a1c323937cdc55c638ed5f0db3607da641f595 8.0.0-beta1:047020ff109a00bf7a02a450b0a1c323937cdc55c638ed5f0db3607da641f595 8.0.0-beta2:047020ff109a00bf7a02a450b0a1c323937cdc55c638ed5f0db3607da641f595 8.0.0-beta3:047020ff109a00bf7a02a450b0a1c323937cdc55c638ed5f0db3607da641f595 8.0.0-beta4:047020ff109a00bf7a02a450b0a1c323937cdc55c638ed5f0db3607da641f595 8.0.0-beta6:047020ff109a00bf7a02a450b0a1c323937cdc55c638ed5f0db3607da641f595 8.0.0-beta7:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-beta9:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-beta10:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-beta11:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-beta12:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-beta13:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-beta14:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-beta15:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-beta16:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-rc1:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-rc2:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-rc3:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.0-rc4:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.1:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.2:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.3:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.4:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.5:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.0.6:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.1.0-beta1:255298aa19fa332d84dc88ec0890ca7d4fe6eb9160db8d78fbf8c627aff3221f 8.1.0-beta2:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.1.0-rc1:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.1.1:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.1.2:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.1.3:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.1.4:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.1.5:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.1.6:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.1.7:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.1.8:ec1688127786f435a1fff41720201b0e4ba6f9e44e26247b43eae38a1af9262e 8.1.9:ec1688127786f435a1fff41720201b0e4ba6f9e44e26247b43eae38a1af9262e 8.1.10:ec1688127786f435a1fff41720201b0e4ba6f9e44e26247b43eae38a1af9262e 8.2.0-beta1:ec1688127786f435a1fff41720201b0e4ba6f9e44e26247b43eae38a1af9262e 8.2.0-beta2:ec1688127786f435a1fff41720201b0e4ba6f9e44e26247b43eae38a1af9262e 8.2.0-beta3:ec1688127786f435a1fff41720201b0e4ba6f9e44e26247b43eae38a1af9262e 8.2.0-rc1:ec1688127786f435a1fff41720201b0e4ba6f9e44e26247b43eae38a1af9262e 8.2.0-rc2:b30b08f58ed732973748475254fc5bb2dc50decccae226ef0e72e0c84eec0ac3 8.2.1:b30b08f58ed732973748475254fc5bb2dc50decccae226ef0e72e0c84eec0ac3 8.2.2:b30b08f58ed732973748475254fc5bb2dc50decccae226ef0e72e0c84eec0ac3 8.2.3:b30b08f58ed732973748475254fc5bb2dc50decccae226ef0e72e0c84eec0ac3 8.2.4:b30b08f58ed732973748475254fc5bb2dc50decccae226ef0e72e0c84eec0ac3 8.2.5:b30b08f58ed732973748475254fc5bb2dc50decccae226ef0e72e0c84eec0ac3 8.2.6:b30b08f58ed732973748475254fc5bb2dc50decccae226ef0e72e0c84eec0ac3 8.3.0-alpha1:98dd405c876486d76dab6e65c0b5aed373ffcf13f61bf3a6a8d5e2564fbcb900 8.3.0-beta1:b45949f486fda5e2222097390550a018f3d8204211d31eeb987e1e2f338748a3 8.3.0-rc1:b45949f486fda5e2222097390550a018f3d8204211d31eeb987e1e2f338748a3 8.2.7:b30b08f58ed732973748475254fc5bb2dc50decccae226ef0e72e0c84eec0ac3 8.3.0-rc2:b45949f486fda5e2222097390550a018f3d8204211d31eeb987e1e2f338748a3 8.0.0:4319d030149fa421f25646ebb3c293e8651ab8704dc058c8e2f4a43da9bf2d3a 8.1.0:f69e3fad0fe07bdd8c7afef94f527ff591d80786d325c4406f334a75942dbf66 8.2.0:b30b08f58ed732973748475254fc5bb2dc50decccae226ef0e72e0c84eec0ac3 8.3.0:b45949f486fda5e2222097390550a018f3d8204211d31eeb987e1e2f338748a3
'use strict'; var assert = require('./utils').assert; var Func = require('../lib/Func'); describe('Func', function() { describe('constructor', function() { it('should be a function', function() { assert.isFunction(Func); }); it('should accept an object and initialise properly', function() { var echo = function() {}; var func = new Func('echo', echo); assert.equal(func.name, 'echo'); assert.strictEqual(func.handler, echo); }); }); describe('#name', function() { it('should be validated', function() { new Func('test', function() {}); assert.throws( function() { new Func(); }, '"undefined" is not a valid function name' ); assert.throws( function() { new Func(undefined); }, '"undefined" is not a valid function name' ); assert.throws( function() { new Func(null); }, '"null" is not a valid function name' ); assert.throws( function() { new Func(false); }, '"false" is not a valid function name' ); assert.throws( function() { new Func(''); }, '"" is not a valid function name' ); }); }); describe('#handler', function() { it('should be validated', function() { new Func('test', function() {}); assert.throws( function() { new Func('test'); }, 'Function handlers must be functions' ); assert.throws( function() { new Func('test', {}); }, 'Function handlers must be functions' ); }); }); describe('#call()', function() { it('the handler should be provided with a this context, data, and a callback', function(done) { var context = {}; var data = {}; var func = new Func('test', function(_data, cb) { assert.strictEqual(this, context); assert.strictEqual(_data, data); assert.isFunction(cb); done(); }); func.call(context, data, function(){}); }); it('should convert all function output to strings', function(done) { var object = new Func('test', function(data, cb) { cb(null, {foo: [20]}); }); var number = new Func('test', function(data, cb) { cb(null, 10); }); object.call(null, null, function(err, output) { assert.isNull(err); assert.equal(output, JSON.stringify({foo: [20]})); number.call(null, null, function(err, output) { assert.isNull(err); assert.equal(output, '10'); done(); }); }); }); it('should produce errors if the output is falsey', function(done) { var _null = new Func('test', function(data, cb) { cb(null, null); }); var _undefined = new Func('test', function(data, cb) { cb(null, undefined); }); var _false = new Func('test', function(data, cb) { cb(null, false); }); var emptyString = new Func('test', function(data, cb) { cb(null, ''); }); _null.call(null, null, function(err, output) { assert.instanceOf(err, Error); assert.isUndefined(output); _undefined.call(null, null, function(err, output) { assert.instanceOf(err, Error); assert.isUndefined(output); _false.call(null, null, function(err, output) { assert.instanceOf(err, Error); assert.isUndefined(output); emptyString.call(null, null, function(err, output) { assert.instanceOf(err, Error); assert.isUndefined(output); done(); }); }); }); }); }); it('can complete asynchronously', function(done) { var func = new Func('test', function(data, cb) { setTimeout(function() { cb(null, 'delayed success'); }, 10); }); func.call(null, null, function(err, output) { assert.isNull(err); assert.equal(output, 'delayed success'); done(); }); }); }); });
import { combineReducers } from 'redux'; import list from './list'; import detail from './detail'; export default combineReducers({ list, detail, });
$(window).ready(function () { $('.picunit a').each(function (i, el) { var imgurl = $('.picdetailurl span:eq(' + i + ')').text(); console.log(imgurl); $(el).click(function (event) { document.documentElement.style.overflow = 'hidden'; imgtag = format('<img src="{0}" alt="" />', imgurl); console.log(imgtag); $('.picscroll').append(imgtag); $('.picdetail').css('width', $(window).width()); $('.picdetail').css('height', $(window).height()); $('.picdetail').show(500); event.preventDefault(); }); }); $('.picdetail').click(function (event) { disableDetail(event); }); $('.picarticle').click(function (event) { event.stopPropagation(); }); $('.close').click(function (event) { disableDetail(event); }); }); function disableDetail(event) { $('.picdetail').hide(500); document.documentElement.style.overflow = 'auto'; event.preventDefault(); $('.picscroll').empty(); }
// All code points in the `Meroitic_Cursive` script as per Unicode v6.1.0: [ 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6, 0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE, 0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6, 0x109B7, 0x109BE, 0x109BF ];
BR.OpacitySlider = L.Control.extend({ options: { position: 'topleft', callback: function(opacity) {} }, onAdd: function (map) { var container = L.DomUtil.create('div', 'leaflet-bar control-slider'), input = $('<input id="slider" type="text"/>'), item = localStorage.opacitySliderValue, value = item ? parseInt(item) : 100, minOpacity = (BR.conf.minOpacity || 0) * 100; if (value < minOpacity) { value = minOpacity; } var stopClickAfterSlide = function(evt) { L.DomEvent.stop(evt); removeStopClickListeners(); }; var removeStopClickListeners = function() { document.removeEventListener('click', stopClickAfterSlide, true); document.removeEventListener('mousedown', removeStopClickListeners, true); }; $(container).html(input); $(container).attr('title', 'Set transparency of route track and markers'); input.slider({ min: 0, max: 100, step: 1, value: value, orientation: 'vertical', reversed : true, selection: 'before', // inverted, serves as track style, see css tooltip: 'hide' }).on('slide slideStop', { self: this }, function (evt) { evt.data.self.options.callback(evt.value / 100); }).on('slideStop', function (evt) { localStorage.opacitySliderValue = evt.value; // When dragging outside slider and over map, click event after mouseup // adds marker when active on Chromium. So disable click (not needed) // once after sliding. document.addEventListener('click', stopClickAfterSlide, true); // Firefox does not fire click event in this case, so make sure stop listener // is always removed on next mousedown. document.addEventListener('mousedown', removeStopClickListeners, true); }); this.options.callback(value / 100); return container; } });
'use strict' var difference = require('array-differ') var extend = require('xtend') module.exports = function keyDifference (obj) { var others = [].slice.call(arguments, 1) var source = Object.keys(obj) var rest = Object.keys(extend.apply(null, others)) return difference(source, rest) }
'use strict'; angular.module('Trendicity') .factory('TrendicityInterceptor', function ($injector, $q) { var hideLoadingModalIfNecessary = function() { var $http = $http || $injector.get('$http'); if ($http.pendingRequests.length === 0) { $injector.get('$ionicLoading').hide(); } }; return { request: function(config) { $injector.get('$ionicLoading').show(); // Handle adding the access_token for instagram api requests var InstagramService = $injector.get('InstagramService'); if (InstagramService.isLoggedIn() && config.url.indexOf(InstagramService.getEndpoint()) === 0) { config.params = config.params || {}; config.params.access_token = InstagramService.getAccessToken(); // jshint ignore:line } return config; }, requestError: function(rejection) { hideLoadingModalIfNecessary(); return $q.reject(rejection); }, response: function(response) { hideLoadingModalIfNecessary(); return response; }, responseError: function(rejection) { hideLoadingModalIfNecessary(); if (rejection.status === 400 && rejection.data.meta.error_type === 'OAuthParameterException') { // jshint ignore:line console.log('detected what appears to be an Instagram auth error...'); rejection.status = 401; // Set the status to 401 so that angular-http-auth inteceptor will handle it } return $q.reject(rejection); } }; } );
import React from 'react'; import ReactDom from 'react-dom'; import { Router, Route, Link, IndexRoute } from 'react-router' import { createHistory, useBasename } from 'history' import alt from './alt' import App from './components/app'; import HomeMonClient from './api/home_mon_client'; import SceneStore from './stores/scene'; import Dashboard from './components/dashboard' const history = useBasename(createHistory)({ basename: '/' }) ReactDom.render(( <Router history={history}> <Route path="/" component={App}> <IndexRoute component={Dashboard} /> </Route> </Router> ), document.getElementById('app'))
version https://git-lfs.github.com/spec/v1 oid sha256:8ac3471e2d008b89bd66b3f52e030ff607cc25de26837e58ef415303f4582007 size 4964
'use strict'; // Classes exports.Char = require('./Char'); exports.CharSide = require('./CharSide'); // Tools, ordered chronologically by when used. exports.autoFit = require('./auto-fit'); exports.breakTextIntoLines = require('./break-text-into-lines'); exports.charWhitelist = require('./char-whitelist'); exports.charMaps = require('./char-maps.js'); exports.padLines = require('./pad-lines'); exports.embedText = require('./embed-text'); exports.connectChars = require('./connect-chars'); exports.findAdjacentChar = require('./find-adjacent-char'); exports.connectCharsHorizontally = require('./connect-chars-horizontally.js'); exports.connectCharsVertically = require('./connect-chars-vertically.js'); exports.connectSpaces = require('./connect-spaces'); exports.setEndpoints = require('./set-endpoints'); exports.flatten = require('./flatten'); exports.fillOut = require('./fill-out'); exports.solve = require('./solve'); exports.shuffleArray = require('./shuffle-array'); exports.randomInRange = require('./random-in-range');
import Ember from 'ember'; const { String: { htmlSafe } } = Ember; export function pageTransform(width) { let transform = `transform: translate3d(${width}%, 0px, 0px)`; return htmlSafe(`-webkit-${transform}; -ms-${transform}; ${transform}`); } export function pageTransformOffset(offset, columns) { let width = 1.0 / columns * 100.0; let widthStr = -(width + offset).toFixed(14); return pageTransform(widthStr); } let SLIDER_TRANSFORM_COMMON = 'transition-duration: 400ms; transition-timing-function: cubic-bezier(0.5, 0, 0.1, 0); transition-delay: 0ms;'; export function sliderTransform(width) { return htmlSafe(`transform: translate3d(${width}px, 0px, 0px); ${SLIDER_TRANSFORM_COMMON}`); } export function sliderTransformHover(width) { return htmlSafe(`transform: scale(2) translate3d(${width}px, 0px, 0px); z-index: 4; ${SLIDER_TRANSFORM_COMMON}`); }
/*! * conkitty, https://github.com/hoho/conkitty * Copyright 2013-2014 Marat Abdullin * Released under the MIT license */ 'use strict'; module.exports = { TEMPLATE_NAME: 'template name', COMMAND_NAME: 'command name', VARIABLE: 'variable', JAVASCRIPT: 'JavaScript', STRING: 'string', CSS: 'css selector', CSS_TAG: 'tag name', CSS_CLASS: 'css class name', CSS_ID: 'css id', CSS_BEM: 'css BEM name', CSS_BEM_MOD: 'css BEM modifier', CSS_ATTR: 'css attribute', CSS_ATTR_NAME: 'css attribute name', CSS_IF: 'css conditional', ATTR: 'attribute', INCLUDE: 'file include', ARGUMENT_DECL: 'argument declaration', ARGUMENT_VAL: 'argument value', NODE_APPENDER: 'node appender' };
;(function() { "use strict"; angular .module('RDash') .directive('orderFormForm', function() { return { restrict: 'E', scope: { entity: '=' }, controller: 'orderFormFormController', templateUrl: 'components/orderForm/form/orderFormFormTmpl.html' }; }); })();
export default ngModule => { ngModule // Redirect to playlist.list .config(function($urlRouterProvider) { $urlRouterProvider.otherwise('/'); }) // Use HTML5 pushstate (nice URLs) .config(function($locationProvider) { $locationProvider.hashPrefix('!'); }) // Configure Prismic .config(function(PrismicProvider) { PrismicProvider.setApiEndpoint('https://ux-glossary.prismic.io/api'); PrismicProvider.setAccessToken(''); PrismicProvider.setClientId(''); PrismicProvider.setClientSecret(''); PrismicProvider.setLinkResolver(function(ctx, doc) { let letter = doc .getText("term.term") .charAt(0) .toLowerCase(); return `/#!/${letter}/${doc.id}/`; }); }) ; }
//Loads the correct sidebar on window load, //collapses the sidebar on window resize. // Sets the min-height of #page-wrapper to window size //$(".loading").show(); $(function() { $(window).bind("load resize", function() { topOffset = 50; width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width; if (width < 768) { $('div.navbar-collapse').addClass('collapse') topOffset = 100; // 2-row-menu } else { $('div.navbar-collapse').removeClass('collapse') } height = (this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height; if (height < 1) height = 1; if (height > topOffset) { $("#page-wrapper").css("min-height", (height) + "px"); } }) }) $(document).ready(function(){ $('.loading').fadeOut('normal'); //$('.box-holder,.table').addClass('animated fadeInRight'); //$('.dashboard-title').addClass('animated fadeInUp'); })
// 函数传递 // function say(world) { // console.log('sql: ' + world + '.'); // } // function execute(someFunction, value) { // someFunction(value); // } // execute(say, 'Hello world'); // function eat(food){ // console.log('sql: ' + food + '.'); // } // execute(eat, 'apple'); function execute(someFunction, value) { someFunction(value); } // 匿名函数用法 execute(function(word){ console.log('sql: ' + word + '.'); }, 'Hello world'); execute(function(food){ console.log('sql: ' + food + '.'); }, 'apple');
#! /usr/bin/env node var main = require('./main'), program = require('commander'); program .usage('[options] [task]') .option('-r, --report', 'print an hours report') .option('-t, --time <items>', 'backdates by time specified (i.e. 1h 5m)') .parse(process.argv); if (program.args.length === 0) { program.help(); return; } main(program.args.join(" "), { report: program.report, time: program.time });
import React from 'react'; import * as snapshot from '../utils/snapshot'; import { TouchableOpacity, ActionSheetIOS, StyleSheet } from 'react-native'; /** * Simple developer menu, which allows e.g. to clear the app state. * It can be accessed through a tiny button in the bottom right corner of the screen. * ONLY FOR DEVELOPMENT MODE! */ const DeveloperMenu = React.createClass({ displayName: 'DeveloperMenu', showDeveloperMenu() { const options = { clearState: 0, showLogin: 1, cancel: 2 }; const callback = async index => { if (index === options.clearState) { await snapshot.clearSnapshot(); console.warn('(╯°□°)╯︵ ┻━┻ \nState cleared, Cmd+R to reload the application now'); } }; ActionSheetIOS.showActionSheetWithOptions({ options: [ 'Clear state', 'Cancel' ], cancelButtonIndex: options.cancel }, callback); }, render() { if (!__DEV__) { return null; } return ( <TouchableOpacity style={styles.circle} onPress={this.showDeveloperMenu} /> ); } }); const styles = StyleSheet.create({ circle: { position: 'absolute', bottom: 5, right: 5, width: 10, height: 10, borderRadius: 5, backgroundColor: '#000' } }); export default DeveloperMenu;
import expect from "expect.js"; import sinon from "sinon"; import Action from "../../../main/javascript/flux/Action"; describe("Action", () => { it("should call listeners when triggered.", () => { var action = new Action("test1"); var listener = sinon.spy(); action.onDispatch(listener); action("test"); expect(listener.calledOnce).to.be.ok(); }); it("should not call listeners that have been removed.", () => { var action = new Action("test2"); var listener = sinon.spy(); var remove = action.onDispatch(listener); remove(); action(); expect(listener.called).not.to.be.ok(); }); it("should share dispatching across different instances with the same name.", () => { var action1 = new Action("test3"); var action2 = new Action("test3"); var listener = sinon.spy(); action1.onDispatch(listener); action2("test"); expect(listener.calledWith("test")).to.be.ok(); }); });
define([ 'utils/Config', 'utils/Debug', 'utils/String', 'backbone', 'views/PageView', 'views/ToDoView', 'text!../../templates/PageView.container.html', 'text!../../templates/PageView.controls.html' ], function( Config, Debug, StringUtil, Backbone, PageView, ToDoView, pageViewContainerTmpl, pageViewControlsTmpl ) { 'use strict'; /** * */ return Backbone.View.extend({ /** * */ initialize : function() { var self = this; this.collection.bind('add', function() { new ToDoView({ model : self.collection.at(self.collection.length-1), parent : self }).render(); }); this.on(Config.event.ADD_RANDOM_TASK, function() { var id = StringUtil.generateId(), title = StringUtil.generateRandomTitle( id ), now = (new Date()).getTime(), key = Config.modelKey, item = {}; item[key.ID] = id; item[key.START_DATE] = now; item[key.TITLE] = title; item[key.DESCRIPTION] = title; self.collection.add([item]); self.render(); // ? setTimeout(function() { window.document.body.scrollTop = window.document.documentElement.scrollHeight; }, 0); }); return Backbone.View.prototype.initialize.apply(this, arguments); }, /** * */ // TODO: This method depends on selectors too much, refactor it. render : function() { var kDebugTimerId = 'TodoCollectionView.render', self = this; Debug.time(kDebugTimerId); this.parent.$el.find('#container').empty(); //window.document.getElementById('container').innerHTML = ''; this.parent.$el.find('#container').append(pageViewContainerTmpl); //window.pageView.$el.find('#container').append(page...ntainerTmpl); this.collection.each(function(todo) { window.pageView.$el.find('#container').append( (new ToDoView({ model : todo, parent : self })).render().el ); }); this.parent.$el.find('#controls').html(pageViewControlsTmpl); //window.pageView.$el.find('#controls').html(pageViewControlsTmpl); Debug.timeEnd(kDebugTimerId); return Backbone.View.prototype.render.apply(this, arguments); } }); });
app.directive('modelanythingPluginsCourselist', [ "settings", "$location", "SessionService", "User", "Course", function( settings, $location, SessionService, User, Course ) { return { templateUrl: settings.widgets + 'modelanything/plugins/courselist.html', link: function(scope, element, attrs) { var session_user; var getCourse = function(course) { Course.get({_id: course._id}, function(course) { return course[0]; }); } var refresh = function(){ SessionService.getSession().success(function(response) { User.get({_id: response.user._id, _populate:"courses"}, function(user) { session_user = user; if(session_user[0].role == "admin") { scope.heading = "All courses"; } else if((session_user[0].role == "student") || (session_user[0].role == "teacher")) { scope.heading = "My courses"; } scope.pinnedCourses = []; if(user[0].courses_pinned.length > 0) { var allPinnedCourses = []; for (i = 0; i < user[0].courses_pinned.length; i++) { currentObj = session_user[0].courses_pinned[i]; if(currentObj.pinned) { Course.get({_id: currentObj.course}, function(course) { scope.pinnedCourses.push(course[0]); }); } } } }); }); } //Runs on page update refresh(); function findWithAttr(array, attr, value) { for(var i = 0; i < array.length; i += 1) { if(array[i][attr] === value) { return i; } } } scope.class = "assignClass" scope.courseLocation = function(obj) { $location.path("courses/" + obj.currentTarget.attributes.dataLocation.value); }; scope.$root.$on('addedCourse', function() { refresh(); }); } } } ]);
//!*script var MAX_COUNT = 9; // 履歴最大数
const autoplay = { props: { /** * Flag to enable autoplay */ autoplay: { type: Boolean, default: false }, /** * Time elapsed before next slide */ autoplayTimeout: { type: Number, default: 2000 }, /** * Flag to pause autoplay on hover */ autoplayHoverPause: { type: Boolean, default: true } }, data () { return { autoplayInterval: null } }, destroyed () { if (!process.server) { this.pauseAutoplay() this.$el.removeEventListener('mouseenter', this.pauseAutoplay) this.$el.removeEventListener('mouseleave', this.startAutoplay) } }, methods: { pauseAutoplay () { if (this.autoplayInterval) { this.autoplayInterval = clearInterval(this.autoplayInterval) } }, startAutoplay () { if (this.autoplay) { this.autoplayInterval = setInterval(() => { this.dir === 'ltr' ? this.goPrev() : this.goNext() }, this.autoplayTimeout) } } }, mounted () { if (!process.server && this.autoplayHoverPause) { this.$el.addEventListener('mouseenter', this.pauseAutoplay) this.$el.addEventListener('mouseleave', this.startAutoplay) this.startAutoplay() } } } export default autoplay
Tinytest.addAsync('Job - create job', function(test, done){ var jobId = Random.id(); var originalCreateJob = Jobs.createOrUpdate; Jobs.createOrUpdate = function(_id, jobInfo){ var expected = { "data.key": "test", 'data.name': 'jobname', 'type': "new-job", 'appId': 'app-id', 'state': 'created' } test.equal(_id, jobId); test.equal(jobInfo, expected); Jobs.createOrUpdate = originalCreateJob; done(); } var job = new Job('new-job','app-id', jobId); job.setData({ 'key': 'test', 'name': 'jobname' }); }); Tinytest.addAsync('Job - set state', function(test, done){ var jobId = Random.id(); var originalCreateJob = Jobs.createOrUpdate; Jobs.createOrUpdate = function(_id, jobInfo){ var expected = { 'type': "new-job2", 'data.name': 'jobname', 'appId': 'app-id', 'state': "running", 'state': 'created', 'data.duration': 1000 }; test.equal(_id, jobId); test.equal(jobInfo, expected); Jobs.createOrUpdate = originalCreateJob; }; var job = new Job('new-job2', 'app-id', jobId); job.setData({ 'name': 'jobname', 'duration': 1000 }); Jobs.createOrUpdate = function(_id, jobInfo){ var expected = { 'type': "new-job2", 'data.name': 'jobname', 'appId': 'app-id', 'state': "running", 'data.duration': 1000 } test.equal(_id, jobId); test.equal(jobInfo, expected); Jobs.createOrUpdate = originalCreateJob; done(); }; job.setState('running'); });
const curry = require('ramda').curry module.exports = curry((arg, fn) => fn(arg) )
exports.BattleScripts = { init: function() { for (var i in this.data.Pokedex) { var hp = this.modData('Pokedex', i).baseStats.hp; var spd = this.modData('Pokedex', i).baseStats.atk; var def = this.modData('Pokedex', i).baseStats.def; var spa = this.modData('Pokedex', i).baseStats.spa; var spd = this.modData('Pokedex', i).baseStats.spd; var spe = this.modData('Pokedex', i).baseStats.spe; this.modData('Pokedex', i).baseStats.hp = spe; this.modData('Pokedex', i).baseStats.atk = spa; this.modData('Pokedex', i).baseStats.def = spd; this.modData('Pokedex', i).baseStats.spa = atk; this.modData('Pokedex', i).baseStats.spd = def; this.modData('Pokedex', i).baseStats.spe = hp; } };
export function mapUrl (availableActions = {}, url = []) { const notFound = {action: null, params: []} // test for empty input if (url.length === 0 || Object.keys(availableActions).length === 0) { return notFound } /*eslint-disable */ const reducer = (prev, current) => { if (prev.action && prev.action[current]) { return {action: prev.action[current], params: []} // go deeper } else { if (typeof prev.action === 'function') { return {action: prev.action, params: prev.params.concat(current)} // params are found } else { return notFound } } } /*eslint-enable */ const actionAndParams = url.reduce(reducer, {action: availableActions, params: []}) return (typeof actionAndParams.action === 'function') ? actionAndParams : notFound }
// @flow import React from 'react' import { Table } from 'antd' import m from 'moment' type Props = { fetchRepos: () => void, repos: Object } const columns = [{ title: 'Name', dataIndex: 'name' }, { title: 'Language', dataIndex: 'language' }, { title: 'Fork', dataIndex: 'fork', render: (text) => { return String(text) } }, { title: 'Description', dataIndex: 'description' }, { title: 'CreatedAt', dataIndex: 'created_at', render: (text) => { return m(new Date(text)).format('YYYY-MM-DD HH:mm') } }, { title: 'UpdatedAt', dataIndex: 'updated_at', render: (text) => { return String(text) } }] export class GithubReposView extends React.Component { props: Props componentDidMount () { this.props.fetchRepos() } render () { const { isFetching, data } = this.props.repos || {} return ( <div> <Table columns={columns} dataSource={data} size='middle' loading={isFetching} rowKey={(record) => record.id} /> </div> ) } } export default GithubReposView
0o1
'use strict'; /* global alertify */ angular.module('septWebRadioApp', [ 'ngRoute', 'ngAnimate', 'ngCookies', 'ngResource', 'ui.bootstrap', 'septWebRadioControllers', 'septWebRadioDirectives', 'septWebRadioFactories', 'septWebRadioFilters' ]); angular.module('septWebRadioApp') .config(['$routeProvider', '$locationProvider', '$httpProvider', function ($routeProvider, $locationProvider, $httpProvider) { $routeProvider .when('/index', { templateUrl: 'partials/index/index.html', controller: 'IndexCtrl' }) .when('/stage', { templateUrl: 'partials/stage/stage.html', controller: 'StageCtrl' }) .when('/replay', { templateUrl: 'partials/replay/replay.html', controller: 'ReplayCtrl' }) .when('/topical', { templateUrl: 'partials/topical/topical.html', controller: 'TopicalCtrl' }) .when('/door', { templateUrl: 'partials/door/door.html', controller: 'DoorCtrl' }) .when('/backstage', { templateUrl: 'partials/backstage/backstage.html', controller: 'BackstageCtrl' }) .when('/login', { templateUrl: 'partials/sign/in.html', controller: 'SignCtrl' }) .when('/signup', { templateUrl: 'partials/sign/up.html', controller: 'SignCtrl' }) .when('/:userId/playlists', { templateUrl: 'partials/playlists/all.html', controller: 'PlaylistsCtrl' }) .when('/:userId/playlists/:playlistId', { templateUrl: 'partials/playlists/all.html', controller: 'PlaylistsCtrl' }) .otherwise({ redirectTo: '/index' }); $locationProvider.html5Mode(true); // Catch the 401 error var interceptor = ['$rootScope', '$q', function (scope, $q) { function success(response) { return response; } function error(response) { var status = response.status; if (status === 401) { var deferred = $q.defer(); scope.$broadcast('event:loginRequired'); return deferred.promise; } alertify.error('An error occurred. Please check your connexion or contact an admin!'); // otherwise return $q.reject(response); } return function (promise) { return promise.then(success, error); }; }]; $httpProvider.responseInterceptors.push(interceptor); }] );
var log4js = require('../lib/log4js'); log4js.configure({ appenders: [ { type: "file", filename: "madeup/path/to/file.log" } ], replaceConsole: true }); logger = log4js.getLogger(); logger.info("Does this work?");
/*! * (C) Ionic http://ionicframework.com - MIT License * Built with http://stenciljs.com */ Ionic.defineComponents("mvy6pg4yo2jt",function(n,t,I,o,u){var O=function(){return function(){}}(),i=function(){return function(){}}(),c=function(){return function(){}}();n["ION-COL"]=O,n["ION-GRID"]=i,n["ION-ROW"]=c},["ION-COL",{}],["ION-GRID",{}],["ION-ROW",{}]);
/** * 1. Building application menu. * 2. Adding separator between submenu. * 3. Build application menu with template. */ 'use strict'; const remote = require('electron').remote; const Menu = remote.Menu; /** * Create menu instance. */ var menu = new Menu(); /** * Create menu template. */ var template = [{ label: 'File', submenu: [{ label: 'New' }, { label: 'Open' }, { type: 'separator' }, { label: 'Save' }, { label: 'Save As' }, { type: 'separator' }, { label: 'Print' }, { label: 'Quit' }] }, { label: 'Help', submenu: [{ label: 'Documentation' }, { label: 'About' }] }]; /** * Provide template to buildFromTemplate method. */ menu = Menu.buildFromTemplate(template); /** * Provide menu to setApplicationMenu method. */ Menu.setApplicationMenu(menu);
var path = require('path'); var paths = require('./paths'); module.exports = function(modules) { return { filename: '', filenameRelative: '', sourceMap: true, sourceRoot: '', moduleRoot: path.resolve('src').replace(/\\/g, '/'), moduleIds: false, comments: false, compact: false, code: true, presets: [ ['es2015', { loose: true, modules: modules }], 'stage-1'], plugins: [ 'syntax-flow', 'transform-decorators-legacy', 'transform-flow-strip-types' ] }; };
import React from 'react' import { shallow } from 'enzyme'; import TodoList from '../../src/components/TodoList' const setup = propOverrides => { const props = Object.assign({ todos: [], }, propOverrides) const wrapper = shallow(<TodoList {...props} />) return { props, wrapper } } describe('TodoList', () => { it('renders as li', () => { const { wrapper } = setup() expect(wrapper.type()).toBe('div') }) })
module.exports = function(config) { var settings = { basePath: '', frameworks: ['mocha', 'browserify', 'es5-shim', 'sinon'], files: [{ pattern: 'dist/js/gardr/**/*.js', watched: false, included: false, served: true }, { pattern: 'dist/js/gardr/**/iframe.htm', watched: false, included: false, served: true }, { pattern: 'test/integration/fixtures/*.js', watched: true, included: false, served: true }, 'test/**/*.test.js' ], reporters: ['progress'], browserify: { watch: true, debug: true }, preprocessors: { 'test/**/*.test.js': 'browserify' }, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], captureTimeout: 30000, singleRun: false, plugins: [ 'karma-chrome-launcher', 'karma-sauce-launcher', 'karma-sinon', 'karma-es5-shim', 'karma-browserify', 'karma-mocha' ] }; if (process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY) { settings.browserDisconnectTimeout = 60000; settings.browserNoActivityTimeout = 60000; settings.captureTimeout = 60000 * 3; settings.autoWatch = false; settings.sauceLabs = { testName: 'Gardr FINN', tags: ['gardr', 'finn'] }; settings.reporters = ['dots', 'saucelabs']; settings.customLaunchers = {}; var key = process.env.BROWSER_TYPE; var target = require('./ci-browsers.js')[key]; if (!target) { console.error('Missing / Unknown BROWSER_TYPE ' + process.env.BROWSER_TYPE); process.exit(1); } Object.keys(target).forEach(function(key){ settings.customLaunchers[key] = target[key]; }); console.log('Running CI tests on', Object.keys(settings.customLaunchers).join(', ')); settings.browsers = Object.keys(settings.customLaunchers); } config.set(settings); };
var bckArray = ["bck_1", "bck_2", "bck_3", "bck_4", "bck_5", "bck_6", "bck_1"]; var currentLVL = 1; var currentBck; var backgroundVelocity = 5; export function update(level){ if(level > currentLVL) { currentBck.loadTexture(bckArray[level - 1], 0); backgroundVelocity += 4; } } export function create(game){ currentBck = game.add.tileSprite(0, 0, 800, 600, bckArray[0]); } export function get() { return currentBck; } export function velocity() { return backgroundVelocity; } export function reset() { backgroundVelocity = 5; currentLVL = 1; }
var abstractService = require("./abstractService") var HomeScreenService = (function () { function HomeScreenService(packageRepository, launchWithPersistentConsole) { this.packageRepository = packageRepository; this.launchWithPersistentConsole = launchWithPersistentConsole; } HomeScreenService.prototype.index = function (aRequest, aResponse) { aResponse.render('index', { title: 'Intel Tizen IVI Proof of Concept', services: abstractService.AttachedServices, applications: this.packageRepository.getInstalledApps(), launchWithPersistentConsole: this.launchWithPersistentConsole }); }; return HomeScreenService; })(); exports.HomeScreenService = HomeScreenService;
var ExtractTextPlugin = require("extract-text-webpack-plugin"); var Webpack = require('webpack'); var path = require('path'); var nodeModulesPath = path.resolve(__dirname, 'node_modules'); var buildPath = path.resolve(__dirname, 'build'); var mainPath = path.resolve(__dirname, 'js', 'app.js'); var config = { node: { __filename: true, fs: 'empty' }, // Makes sure errors in console map to the correct file // and line number devtool: 'eval', entry: [ // For hot style updates 'webpack/hot/dev-server', // The script refreshing the browser on none hot updates 'webpack-dev-server/client?http://localhost:8080', // Our application mainPath ], output: { // We need to give Webpack a path. It does not actually need it, // because files are kept in memory in webpack-dev-server, but an // error will occur if nothing is specified. We use the buildPath // as that points to where the files will eventually be bundled // in production path: buildPath, filename: 'bundle.js', // Everything related to Webpack should go through a build path, // localhost:3000/build. That makes proxying easier to handle publicPath: '/build/' }, module: { loaders: [{ test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.scss$/, exclude: /node_modules/, loader: ExtractTextPlugin.extract("style-loader", "css-loader!autoprefixer-loader!sass-loader") }, { test: /\.hbs$/, exclude: /node_modules/, loader: "handlebars-loader" }] }, plugins: [ new ExtractTextPlugin("style.css"), new Webpack.HotModuleReplacementPlugin() // we have to manually add the Hot Replacement plugin when running from Node ], externals: { 'TweenLite': 'TweenLite' }, resolve: { alias: { "eventEmitter/EventEmitter": "wolfy87-eventemitter" } } }; module.exports = config;
/** * Created by raunak on 20/6/17. */ import {combineReducers} from 'redux' import ReducerFetchCityData from './reducer_fetch_city_data' import ReducerAddToCart from './reducer_Add_To_Cart' const rootReducers=combineReducers({ CityData:ReducerFetchCityData, AddToCart:ReducerAddToCart }); export default rootReducers;
var searchData= [ ['yesbutton',['yesButton',['../class_modal_panel.html#ad03ef3b69d09cf3c4b6a9d309bb7401d',1,'ModalPanel']]] ];
/** * Created by USER: tarso. * On DATE: 29/08/16. * By NAME: app01.js. */ /** * black-scholes * * Source: https://www.npmjs.com/package/black-scholes */ 'use strict' var bs = require("black-scholes"); var nCall; var nPut; var nS; // Current price of the underlying var nK; // Strike price var nTime; // Time to expiration in years var nVolatility; // Volatility as a decimal var nRisk; // Annual risk-free interest rate as a decimal var strType; // The type of option to be priced - "call" or "put" var nCall; // Value of Call stock option var nPut; // Value of Put stock option console.log('Calc 01'); nCall = bs.blackScholes(30, 34, .25, .2, .08, "call"); // 0.23834902311961947 nPut = bs.blackScholes(30, 34, .25, .2, .08, "put"); // 3.5651039155492974 console.log('call (0.23834902311961947) :', nCall); console.log('put (3.5651039155492974) :', nPut); console.log('Calc 02'); nCall = bs.blackScholes(12.81, 13, (21/365), 0.4141, .1425, "call"); // 0.23834902311961947 nPut = bs.blackScholes(12.81, 13, (21/365), 0.4141, .1425, "put"); // 3.5651039155492974 console.log('call (0.46822936305387586) :', nCall); console.log('put (0.5520828936691498) :', nPut); console.log('Calc 03'); nCall = bs.blackScholes(12.87, 13, (20/365), 0.4141, .1425, "call"); // 0.23834902311961947 nPut = bs.blackScholes(12.87, 13, (20/365), 0.4141, .1425, "put"); // 3.5651039155492974 console.log('call (0.4837464921878265) :', nCall); console.log('put (0.5126349072970466) :', nPut);
var url = require('url'); var util = require('util'); var http = require('http'); var events = require('events'); var endpoint = require('endpoint'); var modulebox = require('../lib/dispatch.js'); function Test(settings) { if (!(this instanceof Test)) return new Test(settings); var self = this; this.box = modulebox(settings); this.box.on('error', this.emit.bind(this, 'error')); this.box.on('warning', this.emit.bind(this, 'warning')); this.server = http.createServer(); this.server.on('request', function (req, res) { self.box.dispatch(req, res); }); this.remote = null; } module.exports = Test; util.inherits(Test, events.EventEmitter); Test.prototype.open = function (callback) { var self = this; this.server.listen(0, '127.0.0.1', function () { var addr = self.server.address(); self.remote = 'http://' + addr.address + ':' + addr.port; callback(); }); }; Test.prototype.query = function (query, callback) { var href = url.parse(this.remote); delete href.search; href.query = query; http.get(url.format(href), function (res) { var mtime = null; var hash = null; if (res.headers['last-modified']) mtime = new Date(res.headers['last-modified']); if (res.headers.etag) hash = res.headers.etag.slice(3, -1); res.pipe(endpoint(function (err, content) { callback(err, { 'mtime': mtime, 'hash': hash }, content); })); }); }; Test.prototype.request = function(what, callback) { this.query({ 'normal': JSON.stringify(what.normal ? what.normal : []), 'special': JSON.stringify(what.special ? what.special : []), 'from': JSON.stringify(what.from ? what.from : '/'), 'request': JSON.stringify(what.request ? what.request : []) }, callback); }; Test.prototype.close = function (callback) { this.server.close(callback); };
var mddf = require('../'); var fdstore = require('fd-chunk-store'); var sparse = require('sparse-chunk-store'); var df = mddf({ size: 4096, dim: 3, store: sparse(fdstore(4096, 'data.mddf')) }); var near = df.near(process.argv.slice(2)); (function next () { near(function (err, pt, data) { if (!pt) return; console.log(pt) process.nextTick(next); }); })();
const express = require('express'); const find = require('array-find'); const Archive = require('./archive'); const ServerConfig = require('../utils/server-config'); const BLP = require('blizzardry/lib/blp'); const {DecodeStream} = require('blizzardry/lib/restructure'); const DBC = require('blizzardry/lib/dbc/entities'); const {PNG} = require('pngjs'); module.exports = class Pipeline { static get DATA_DIR() { return ServerConfig.db.get('clientData'); } constructor() { this.router = express(); this.router.param('resource', this.resource.bind(this)); this.router.get('/:resource(*.blp).png', this.blp.bind(this)); this.router.get('/:resource(*.dbc)/:id(*)?.json', this.dbc.bind(this)); this.router.get('/find/:query', this.find.bind(this)); this.router.get('/:resource', this.serve.bind(this)); } get archive() { this._archive = this._archive || Archive.build(this.constructor.DATA_DIR); return this._archive; } resource(req, res, next, path) { req.resourcePath = path; if (req.resource = this.archive.files.get(path)) { next(); } else { const err = new Error('resource not found'); err.status = 404; throw err; } } blp(req, res) { BLP.from(req.resource.data, function(blp) { const mipmap = blp.largest; const png = new PNG({ width: mipmap.width, height: mipmap.height }); png.data = mipmap.rgba; res.set('Content-Type', 'image/png'); png.pack().pipe(res); }); } dbc(req, res) { const name = req.resourcePath.match(/(\w+)\.dbc/)[1]; if (definition = DBC[name]) { dbc = definition.dbc.decode(new DecodeStream(req.resource.data)); if (id = req.params[0]) { entity = find(dbc.records, function(entity) { return String(entity.id) === id; }); if (entity) { res.send(entity); } else { err = new Error('entity not found'); err.status = 404; throw err; } } else { res.send(dbc.records); } } else { err = new Error('entity definition not found'); err.status = 404; throw err; } } find(req, res) { res.send(this.archive.files.find(req.params.query)); } serve(req, res) { res.send(req.resource.data); } };
import React from 'react'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import axios from 'axios'; class Struktur extends React.Component{ constructor(){ super(); this.state = { value: '', list: [], data: [], } } loadData(data){ var _this = this; var tahun = data; console.log("Load data "+tahun);; axios.get('data/'+tahun+'.json') .then(function (response) { _this.setState({ value: tahun, data: response.data, }); }) .catch(function (error) { console.log(error.response); }); } componentWillMount(){ var _this = this; axios.get('data/list.json') .then(function (response) { _this.setState({ list: response.data, }); if(response.data.length>0) _this.loadData(response.data[response.data.length-1].tahun); }) .catch(function (error) { console.log(error); _this.setState({ value: '', }); }); } handleChange = (event, index, value) => { this.setState({value}); this.loadData(value); } render(){ return ( (this.state.value!=='' && this.state.value!==0)? <div> <SelectField floatingLabelText="Struktur Pengurus" value={this.state.value} fullWidth={true} onChange={this.handleChange} > { this.state.list.map(item => ( <MenuItem value={item.tahun} primaryText={item.tahun+"-"+(item.tahun+1)} key={item.tahun} /> )) } </SelectField> <div> <table> <tbody> { this.state.data.map((row, index) => ( <tr key={index}> <td><b>{row.jabatan}</b></td> <td>:</td> { Object.prototype.toString.call(row.nama) !== '[object Array]' ? <td>{row.nama}</td> : <td> { row.nama.map((row2, index2) => ( <span key={index2}>{index2+1}. {row2.nama}<br/></span> )) } </td> } </tr> )) } </tbody> </table> </div> </div> : <div> <h1>Cannot load data</h1> </div> ); } } export default Struktur;
const http = require('http'); const metrics = require('./metrics'); const profiling = require('./profiling'); const DEFAULT_HOSTNAME = '0.0.0.0'; const DEFAULT_PORT = 9142; const DEFAULT_PATH = '/metrics'; function slash_metrics_handler(req, res) { res.statusCode = 200; res.end(metrics.getMetrics()); }; function slash_handler(req, res) { res.writeHead(301, { 'Location': '/metrics' }); res.end(`<html> <head><title>Node profiling exporter</title></head> <body> <h1>Node profiling exporter</h1> <p><a href="/metrics">Metrics</a></p> </body> </html>`); } function startServer(opts) { if (!opts) opts = {}; const hostname = !!opts.hostname ? opts.hostname : DEFAULT_HOSTNAME; const port = !!opts.port ? parseInt(opts.port) : DEFAULT_PORT; const path = !!opts.path ? opts.path : DEFAULT_PATH; return new Promise( (resolve, reject) => { const server = http.createServer((req, res) => { const { method, url } = req; if (method === "GET" && url === path) return slash_metrics_handler(req, res); else if (method === "GET" && url === "/") return slash_handler(req, res); res.statusCode = 404; res.end(); return; }); server.on('clientError', (err, socket) => { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); }); server.listen(port, hostname, () => { resolve('http://' + hostname + ':' + port + path); }); }); } module.exports = { startServer };
var fs = require('fs'); var exec = require('child_process').execSync; exports.convert = function(doc, format, outDir) { try{ fs.statSync(doc); }catch(err){ if(err.code == 'ENOENT') return false; } if(typeof outDir === 'undefined' || outDir === null){ outDirProperty = '' }else{ console.log("fck"); console.log(outDir); outDirProperty = '--outdir ' + outDir } exec('libreoffice --headless --convert-to ' + format + ' ' + doc + ' ' + outDirProperty + ' >/dev/null'); return true; }
import * as React from 'react'; import { experimentalStyled as styled } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardHeader from '@material-ui/core/CardHeader'; import CardMedia from '@material-ui/core/CardMedia'; import CardContent from '@material-ui/core/CardContent'; import CardActions from '@material-ui/core/CardActions'; import Collapse from '@material-ui/core/Collapse'; import Avatar from '@material-ui/core/Avatar'; import IconButton from '@material-ui/core/IconButton'; import Typography from '@material-ui/core/Typography'; import { red } from '@material-ui/core/colors'; import FavoriteIcon from '@material-ui/icons/Favorite'; import ShareIcon from '@material-ui/icons/Share'; import ExpandMoreIcon from '@material-ui/icons/ExpandMore'; import MoreVertIcon from '@material-ui/icons/MoreVert'; const ExpandMore = styled((props) => { const { expand, ...other } = props; return <IconButton {...other} />; })(({ theme, expand }) => ({ transform: !expand ? 'rotate(0deg)' : 'rotate(180deg)', marginLeft: 'auto', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shortest, }), })); export default function RecipeReviewCard() { const [expanded, setExpanded] = React.useState(false); const handleExpandClick = () => { setExpanded(!expanded); }; return ( <Card sx={{ maxWidth: 345 }}> <CardHeader avatar={ <Avatar sx={{ bgcolor: red[500] }} aria-label="recipe"> R </Avatar> } action={ <IconButton aria-label="settings"> <MoreVertIcon /> </IconButton> } title="Shrimp and Chorizo Paella" subheader="September 14, 2016" /> <CardMedia sx={{ height: 0, paddingTop: '56.25%', // 16:9 }} image="/static/images/cards/paella.jpg" title="Paella dish" /> <CardContent> <Typography variant="body2" color="text.secondary"> This impressive paella is a perfect party dish and a fun meal to cook together with your guests. Add 1 cup of frozen peas along with the mussels, if you like. </Typography> </CardContent> <CardActions disableSpacing> <IconButton aria-label="add to favorites"> <FavoriteIcon /> </IconButton> <IconButton aria-label="share"> <ShareIcon /> </IconButton> <ExpandMore expand={expanded} onClick={handleExpandClick} aria-expanded={expanded} aria-label="show more" > <ExpandMoreIcon /> </ExpandMore> </CardActions> <Collapse in={expanded} timeout="auto" unmountOnExit> <CardContent> <Typography paragraph>Method:</Typography> <Typography paragraph> Heat 1/2 cup of the broth in a pot until simmering, add saffron and set aside for 10 minutes. </Typography> <Typography paragraph> Heat oil in a (14- to 16-inch) paella pan or a large, deep skillet over medium-high heat. Add chicken, shrimp and chorizo, and cook, stirring occasionally until lightly browned, 6 to 8 minutes. Transfer shrimp to a large plate and set aside, leaving chicken and chorizo in the pan. Add pimentón, bay leaves, garlic, tomatoes, onion, salt and pepper, and cook, stirring often until thickened and fragrant, about 10 minutes. Add saffron broth and remaining 4 1/2 cups chicken broth; bring to a boil. </Typography> <Typography paragraph> Add rice and stir very gently to distribute. Top with artichokes and peppers, and cook without stirring, until most of the liquid is absorbed, 15 to 18 minutes. Reduce heat to medium-low, add reserved shrimp and mussels, tucking them down into the rice, and cook again without stirring, until mussels have opened and rice is just tender, 5 to 7 minutes more. (Discard any mussels that don’t open.) </Typography> <Typography> Set aside off of the heat to let rest for 10 minutes, and then serve. </Typography> </CardContent> </Collapse> </Card> ); }
exports.lte = function () { /** * Tests if the first argument is less than or equal to the second argument. * May be used inline or as a conditional block. * @category comparisons * * @signature {{lte value test}} * @param {string|integer} value Smaller value * @param {string|integer} test Greater value * @return {boolean} * * @signature {{#lte value test}}<TEMPLATE>[{{else}}<TEMPLATE>]{{/lte}} */ return function lte (value, test, options) { if (arguments.length !== 3) { throw new Error('Handlebars Helper "lte" needs 2 parameters'); } if (!options.fn) return value <= test || ''; if (value <= test) { return options.fn(this); } else { return options.inverse(this); } }; /***/ };
var convert = require("./convert"); var globalToSlim = require("../lib/global/slim"); describe("global -> slim", function() { it("works", function() { return convert({ converter: globalToSlim, sourceFileName: "global", expectedFileName: "global_slim" }); }); it("turns `meta.deps` into `stealRequire` calls", function() { return convert({ converter: globalToSlim, sourceFileName: "global", expectedFileName: "global_deps_slim", load: { metadata: { format: "global", deps: ["foo", "bar"] } }, options: { normalize: function(name) { return { foo: 1, bar: 2 }[name]; } } }); }); it("turns `meta.exports` into `stealModule.exports`", function() { return convert({ converter: globalToSlim, sourceFileName: "global", expectedFileName: "global_exports_slim", load: { metadata: { format: "global", exports: "GLOBAL" } } }); }); it("works when both `meta.deps` and `meta.exports` set", function() { return convert({ converter: globalToSlim, sourceFileName: "global", expectedFileName: "global_deps_exports_slim", load: { metadata: { format: "global", deps: ["foo", "bar"], exports: "GLOBAL" } } }); }); });
exports.BattleScripts = { inherit: 'gen5', gen: 3, init: function() { for (var i in this.data.Learnsets) { this.modData('Learnsets', i); var learnset = this.data.Learnsets[i].learnset; for (var moveid in learnset) { if (typeof learnset[moveid] === 'string') learnset[moveid] = [learnset[moveid]]; learnset[moveid] = learnset[moveid].filter(function(source) { return source[0] === '3'; }); if (!learnset[moveid].length) delete learnset[moveid]; } } for (var i in this.data.Pokedex) { delete this.data.Pokedex[i].abilities['DW']; } }, getCategory: function(move) { move = this.getMove(move); if (!(move.category in {'Special':1,'Physical':1})) return move.category; // overwrite categories var specialTypes = {Fire:1, Water:1, Grass:1, Ice:1, Electric:1, Dark:1, Psychic:1, Dragon:1}; return specialTypes[move.type]? 'Special' : 'Physical'; } };
var app = app || {}; //var Codemirror = require('../../node_modules/react-codemirror/dist/react-codemirror.min.js') (function() { app.APP_TEST = 1; app.STANDARD_TEST = 0; app.SERVER_TEST = 2; var TestButton = app.TestButton; var CodeEditor = app.CodeEditor; var UrlEditor = app.UrlEditor; var ResultDisplay = app.ResultDisplay; var TokenEditor = app.TokenEditor; app.type2str = function(test_type){ var typeStr = ''; switch (test_type) { case app.APP_TEST: typeStr = 'App Test'; break; case app.STANDARD_TEST: typeStr = 'Standard Test'; break; case app.SERVER_TEST: typeStr = 'Server Test'; break; } return typeStr; } function onChange(newCode) { console.log(newCode) } function updateCode(newCode){ console.log(newCode); } var options = { lineNumbers: true, mode:'java' }; var TesterApp = React.createClass({displayName: "TesterApp", getInitialState: function() { return {code:"",url:"", isResultReady:true, isLoading:false, isTestPass:true, isTestFail:false, testResult:{}, access_token:''}; }, updateCode:function(newCode){ this.setState({code:newCode}); }, updateUrl:function(newUrl){ this.setState({url:newUrl}); }, updateAccessToken:function(newToken){ this.setState({access_token:newToken}); }, handleTaskSubmit:function(submitType){ //this.state.isLoading = !this.state.isLoading; //this.setState({isLoading:!this.state.isLoading}); var post_data = {code:this.state.code,language:'python',type:submitType,url:this.state.url,access_token :this.state.access_token}; console.log(post_data); $.ajax({ url:'http://localhost:8000/home/submit', type:'POST', data:JSON.stringify(post_data), dataType:'json', cache:false, success:function(data){ console.log(data) } }); //connect with websocket app.close_socket(); }, componentDidMount:function(){ window.comp = this; }, updateTestResult:function(res){ this.setState({isResultReady:true, testResult:res}); }, render:function(){ return ( React.createElement("div", {className: "box"}, React.createElement("div", {className: "test-input"}, React.createElement("div", {className: "btnArea"}, React.createElement(TestButton, {btn_name: "App Test", submitTestTask: this.handleTaskSubmit, btnType: app.APP_TEST}), React.createElement(TestButton, {btn_name: "Server Test", submitTestTask: this.handleTaskSubmit, btnType: app.SERVER_TEST}), React.createElement(TestButton, {btn_name: "Standard Test", submitTestTask: this.handleTaskSubmit, btnType: app.STANDARD_TEST}) ), React.createElement(UrlEditor, {updateUrl: this.updateUrl}), React.createElement(TokenEditor, {updateToken: this.updateAccessToken}), React.createElement(CodeEditor, {updateCode: this.updateCode, language: "python"}) ), React.createElement("div", {className: "result-area"}, React.createElement("div", {className: "loading", hidden: !this.state.isLoading}, React.createElement("img", {src: "../img/5.png", alt: "loading", class: "img-responsive loading-img"}) ), !this.state.isLoading && this.state.isResultReady ? React.createElement(ResultDisplay, React.__spread({}, this.state.testResult)) : null ) ) ); } }); function render() { ReactDOM.render( React.createElement(TesterApp, null), document.getElementById('main') ); } render(); })();
'use strict'; const Code = require('code'); const Hapi = require('hapi'); const Hoek = require('hoek'); const Inert = require('inert'); const Lab = require('lab'); const Vision = require('vision'); const HapiSwagger = require('../../lib/index.js'); const Helper = require('../helper.js'); const expect = Code.expect; const lab = (exports.lab = Lab.script()); lab.experiment('connections', () => { const server = new Hapi.Server(); lab.before(function(done) { server.connection({ host: 'localhost', port: 3000, labels: 'a' }); server.connection({ host: 'localhost', port: 3001, labels: 'b' }); server.connection({ host: 'localhost', port: 3002, labels: 'c' }); let plugin1 = function(plugin, options, next) { plugin.route({ method: 'GET', path: '/plugin1', config: { handler: function(request, reply) { reply('Hi from plugin 1'); }, description: 'plugin1', tags: ['api'] } }); next(); }; plugin1.attributes = { name: 'plugin1' }; let plugin2 = function(plugin, options, next) { plugin.route({ method: 'GET', path: '/plugin2', config: { handler: function(request, reply) { reply('Hi from plugin 2'); }, description: 'plugin2', tags: ['api'] } }); next(); }; plugin2.attributes = { name: 'plugin2' }; let swaggerOptions = { schemes: ['http'], info: { title: 'Test API Documentation', description: 'This is a sample example of API documentation.', version: '1.0.0', termsOfService: 'https://github.com/glennjones/hapi-swagger/', contact: { email: 'glennjonesnet@gmail.com' }, license: { name: 'MIT', url: 'https://raw.githubusercontent.com/glennjones/hapi-swagger/master/license.txt' } } }; let swaggerOptionsA = Hoek.clone(swaggerOptions); let swaggerOptionsB = Hoek.clone(swaggerOptions); swaggerOptionsA.host = 'localhost:3000'; swaggerOptionsB.host = 'localhost:3001'; server.register([Inert, Vision], function(err) { expect(err).to.equal(undefined); // interface a - add swagger UI server.register( [ plugin1, { register: HapiSwagger, options: swaggerOptionsA } ], { select: ['a'] }, function(err) { expect(err).to.equal(undefined); // interface b - add swagger UI server.register( [ plugin2, { register: HapiSwagger, options: swaggerOptionsB } ], { select: ['b'] }, function(err) { expect(err).to.equal(undefined); server.start(function() { done(); }); } ); } ); }); }); lab.test('server connection a', done => { const a = server.select('a'); a.inject({ method: 'GET', url: '/swagger.json' }, function(response) { expect(response.statusCode).to.equal(200); Helper.validate(response, done, expect); }); }); lab.test('server connection b', done => { const b = server.select('b'); b.inject({ method: 'GET', url: '/swagger.json' }, function(response) { expect(response.statusCode).to.equal(200); Helper.validate(response, done, expect); }); }); lab.test('server connection c', done => { const c = server.select('c'); c.inject({ method: 'GET', url: '/swagger.json' }, function(response) { expect(response.statusCode).to.equal(404); done(); }); }); });
import React from 'react'; import PrimaryCallToAction from '../../../shared/js/components/gironde.fr/PrimaryCallToAction'; import Markdown from '../../../shared/js/components/Markdown'; import MoneyAmount from '../../../shared/js/components/MoneyAmount'; /* interface FocusDetailProps{ className: string title: string, illustrationUrl: url, amount: number proportion: number [0, 1], text, highlights, moreUrl } */ export default function ({className, title, illustrationUrl, amount, proportion, text, highlights = [], moreUrl}) { return React.createElement('div', { className: ['focus-detail', className].filter(e => e).join(' ') }, React.createElement('div', {className: 'illustration'}, React.createElement('img', {src: illustrationUrl}) ), React.createElement('div', {className: 'explanation'}, React.createElement('h3', {}, title), React.createElement('div', {className: 'proportion-container'}, React.createElement('div', {className: 'proportion', style: {width: proportion*100+'%'}}, amount ? React.createElement(MoneyAmount, {amount}) : undefined ) ), React.createElement(Markdown, {}, text), highlights && highlights.length >= 1 ? React.createElement('div', {className: 'highlights'}, highlights.map(h => { return React.createElement('div', {}, React.createElement('strong', {}, h.strong), React.createElement('span', {}, h.span) ) }) ) : undefined, React.createElement(PrimaryCallToAction, {href: moreUrl, text: 'En savoir plus'}) ) ); }
// shared config (dev and prod) const {resolve} = require('path'); const {CheckerPlugin} = require('awesome-typescript-loader'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], }, context: resolve(__dirname, '../../src'), module: { rules: [ { test: /\.js$/, use: ['babel-loader', 'source-map-loader'], exclude: /node_modules/, }, { test: /\.tsx?$/, use: ['babel-loader', 'awesome-typescript-loader'], }, { test: /\.css$/, use: ['style-loader', { loader: 'css-loader', options: { importLoaders: 1 } }], }, { test: /\.scss$/, loaders: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 1 } }, 'sass-loader', ], }, { test: /\.(jpe?g|png|gif|svg)$/i, loaders: [ 'file-loader?hash=sha512&digest=hex&name=img/[hash].[ext]', 'image-webpack-loader?bypassOnDebug&optipng.optimizationLevel=7&gifsicle.interlaced=false', ], }, ], }, plugins: [ new CheckerPlugin(), new HtmlWebpackPlugin({template: 'index.html.ejs',}), ], externals: { 'react': 'React', 'react-dom': 'ReactDOM', }, performance: { hints: false, }, };
/* */ module.exports = function(hljs) { return { aliases: ['cmake.in'], case_insensitive: true, keywords: { keyword: 'add_custom_command add_custom_target add_definitions add_dependencies ' + 'add_executable add_library add_subdirectory add_test aux_source_directory ' + 'break build_command cmake_minimum_required cmake_policy configure_file ' + 'create_test_sourcelist define_property else elseif enable_language enable_testing ' + 'endforeach endfunction endif endmacro endwhile execute_process export find_file ' + 'find_library find_package find_path find_program fltk_wrap_ui foreach function ' + 'get_cmake_property get_directory_property get_filename_component get_property ' + 'get_source_file_property get_target_property get_test_property if include ' + 'include_directories include_external_msproject include_regular_expression install ' + 'link_directories load_cache load_command macro mark_as_advanced message option ' + 'output_required_files project qt_wrap_cpp qt_wrap_ui remove_definitions return ' + 'separate_arguments set set_directory_properties set_property ' + 'set_source_files_properties set_target_properties set_tests_properties site_name ' + 'source_group string target_link_libraries try_compile try_run unset variable_watch ' + 'while build_name exec_program export_library_dependencies install_files ' + 'install_programs install_targets link_libraries make_directory remove subdir_depends ' + 'subdirs use_mangled_mesa utility_source variable_requires write_file ' + 'qt5_use_modules qt5_use_package qt5_wrap_cpp on off true false and or', operator: 'equal less greater strless strgreater strequal matches' }, contains: [ { className: 'envvar', begin: '\\${', end: '}' }, hljs.HASH_COMMENT_MODE, hljs.QUOTE_STRING_MODE, hljs.NUMBER_MODE ] }; };
var gulp = require('gulp'); var gutil = require("gulp-util"); var webpack = require("webpack"); var WebpackDevServer = require("webpack-dev-server"); var path = require('path'); var Server = require('karma').Server; var config = { entry: path.resolve(__dirname, 'app/main.js'), output: { path: path.resolve(__dirname, 'build'), filename: 'main.js' }, module: { loaders: [{ test: /\.jsx?$/, // A regexp to test the require path. accepts either js or jsx loader: 'babel' // The module to load. "babel" is short for "babel-loader" }] } } gulp.task("webpack", function(callback) { // run webpack webpack(config, function(err, stats) { if(err) throw new gutil.PluginError("webpack", err); gutil.log("[webpack]", stats.toString({ // output options })); callback(); }); }); gulp.task("tests", function(callback) { // console.log(path.resolve(__dirname + 'test/karma.conf.js')) new Server({ configFile: path.resolve(__dirname, 'test/karma.config.js'), singleRun: false }, callback).start(); }); gulp.task("webpack-dev-server", function(callback) { // Start a webpack-dev-server var compiler = webpack(config); new WebpackDevServer(compiler, { // server and middleware options }).listen(8080, "localhost", function(err) { if(err) throw new gutil.PluginError("webpack-dev-server", err); // Server listening gutil.log("[webpack-dev-server]", "http://localhost:8080/webpack-dev-server/index.html"); // keep the server alive or continue? callback(); }); });
/* * THIS FILE IS AUTO GENERATED FROM 'lib/stages/ecma_peep.kep' * DO NOT EDIT */ define(["require", "exports", "akh/error", "bes/object", "neith/tree", "../ecma_peep"], (function(require, exports, Error, __o, __o0, ecma_peep) { "use strict"; var optimize, setProperty = __o["setProperty"], node = __o0["node"]; (optimize = (function(options, data) { var tree = data["tree"]; return Error.of(setProperty(data, "tree", node(ecma_peep.optimize(tree)))); })); return optimize; }));
/* eslint no-undef: 0, fp/no-unused-expression: 0, fp/no-nil: 0, fp/no-mutation:0 , react/jsx-filename-extension:0 */ import React from 'react'; import {mount} from 'enzyme'; import {root} from 'utils'; import {HeaderPure} from './index'; jest.mock('react-router-dom/Link'); jest.mock('components/Container'); jest.mock('components/Column'); jest.mock('components/Hidden'); jest.mock('components/Row'); jest.mock('../Logotype'); jest.mock('../MenuButton'); jest.mock('../NavigationLinkList'); describe('Header Pure Mount', () => { const map = {}; window.addEventListener = jest.genMockFn().mockImplementation((event, cb) => { map[event] = cb; }); const classes = { '.default-Header-header.shrinkedHeader': 'default-Header-header.shrinkedHeader', '.default-Header-headerLogoContainer.shrinkedHeader': 'default-Header-headerLogoContainer.shrinkedHeader', '.default-Header-navigationLinksContainer.closed': 'default-Header-navigationLinksContainer.closed', fixedOnTheTop: 'default-Header-fixedOnTheTop', header: 'default-Header-header', headerColumn: 'default-Header-headerColumn', headerLogoContainer: 'default-Header-headerLogoContainer', headerMenuButtonContainer: 'default-Header-headerMenuButtonContainer', headerPadding: 'default-Header-headerPadding', navigationLinks: 'default-Header-navigationLinks', navigationLinksContainer: 'default-Header-navigationLinksContainer' }; it('component with scrolled down document since to "scrollTop: 100" match expected snapshot', () => { const wrapper = mount(<HeaderPure classes={classes} navigationLinkArray={[]} />); map.scroll({target: {scrollingElement: {scrollTop: 100} } }); expect(wrapper).toMatchSnapshot(); }); it('component with scrolled down document since to "scrollTop: 24" match expected snapshot', () => { const wrapper = mount(<HeaderPure classes={classes} navigationLinkArray={[]} />); map.scroll({target: {scrollingElement: {scrollTop: 24} } }); expect(wrapper).toMatchSnapshot(); }); it('component should removeEventListener on unmount', () => { root.removeEventListener = jest.fn(); const wrapper = mount(<HeaderPure classes={classes} navigationLinkArray={[]} />); wrapper.unmount(); expect(root.removeEventListener.mock.calls.length).toBeGreaterThan(0); }); });
/* * * mads - version 2.00.01 * Copyright (c) 2015, Ninjoe * Dual licensed under the MIT or GPL Version 2 licenses. * https://en.wikipedia.org/wiki/MIT_License * https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html * */ var mads = function () { /* Get Tracker */ if (typeof custTracker == 'undefined' && typeof rma != 'undefined') { this.custTracker = rma.customize.custTracker; } else if (typeof custTracker != 'undefined') { this.custTracker = custTracker; } else { this.custTracker = []; } /* Unique ID on each initialise */ this.id = this.uniqId(); /* Tracked tracker */ this.tracked = []; /* Body Tag */ this.bodyTag = document.getElementsByTagName('body')[0]; /* Head Tag */ this.headTag = document.getElementsByTagName('head')[0]; /* RMA Widget - Content Area */ this.contentTag = document.getElementById('rma-widget'); /* URL Path */ this.path = typeof rma != 'undefined' ? rma.customize.src : ''; }; /* Generate unique ID */ mads.prototype.uniqId = function () { return new Date().getTime(); } /* Link Opner */ mads.prototype.linkOpener = function (url) { if(typeof url != "undefined" && url !=""){ if (typeof mraid !== 'undefined') { mraid.open(url); }else{ window.open(url); } } } /* tracker */ mads.prototype.tracker = function (tt, type, name, value) { /* * name is used to make sure that particular tracker is tracked for only once * there might have the same type in different location, so it will need the name to differentiate them */ name = name || type; if ( typeof this.custTracker != 'undefined' && this.custTracker != '' && this.tracked.indexOf(name) == -1 ) { for (var i = 0; i < this.custTracker.length; i++) { var img = document.createElement('img'); if (typeof value == 'undefined') { value = ''; } /* Insert Macro */ var src = this.custTracker[i].replace('{{type}}', type); src = src.replace('{{tt}}', tt); src = src.replace('{{value}}', value); /* */ img.src = src + '&' + this.id; img.style.display = 'none'; this.bodyTag.appendChild(img); this.tracked.push(name); } } }; /* Load JS File */ mads.prototype.loadJs = function (js, callback) { var script = document.createElement('script'); script.src = js; if (typeof callback != 'undefined') { script.onload = callback; } this.headTag.appendChild(script); } /* Load CSS File */ mads.prototype.loadCss = function (href) { var link = document.createElement('link'); link.href = href; link.setAttribute('type', 'text/css'); link.setAttribute('rel', 'stylesheet'); this.headTag.appendChild(link); } /* * * Unit Testing for mads * */ var testunit = function () { var app = new mads(); console.log(typeof app.bodyTag != 'undefined'); console.log(typeof app.headTag != 'undefined'); console.log(typeof app.custTracker != 'undefined'); console.log(typeof app.path != 'undefined'); console.log(typeof app.contentTag != 'undefined'); app.loadJs('https://code.jquery.com/jquery-1.11.3.min.js',function () { console.log(typeof window.jQuery != 'undefined'); }); app.loadCss('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'); app.contentTag.innerHTML = '<div class="container"><div class="jumbotron"> \ <h1>Hello, world!</h1> \ <p>...</p> \ <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p> \ </div></div>'; app.custTracker = ['http://www.tracker.com?type={{type}}&tt={{tt}}','http://www.tracker2.com?type={{type}}']; app.tracker('CTR', 'test'); app.tracker('E','test','name'); app.linkOpener('http://www.google.com'); } var bisnis = function () { this.app = new mads(); this.app.loadCss(this.app.path + 'css/style.css'); this.app.loadJs('https://code.jquery.com/jquery-1.11.3.min.js', this.curry(this.render, this)); } bisnis.prototype.curry = function(fn, scope /*, arguments */) { scope = scope || window; var actualArgs = arguments; return function() { var args = []; for(var j = 0; j < arguments.length; j++) { args.push(arguments[j]); } for(var i = 2; i < actualArgs.length; i++) { args.push(actualArgs[i]); } return fn.apply(scope, args); }; }; bisnis.prototype.render = function () { var _this = this; this.app.contentTag.innerHTML = '<div id="bisnis"><img src="'+this.app.path+'img/ERatePendidikan728x90.png"/><div id="bisnis-usd-rate">13625.00</div></div>'; $.get('https://api.mobileads.com/scrapper/bca/index.php', function (node) { console.log(node) document.getElementById('bisnis-usd-rate').innerHTML = node; }) document.getElementById('bisnis').addEventListener('click', function () { _this.app.tracker('CTR', 'site'); _this.app.linkOpener('http://bca.co.id/id/kurs-sukubunga/kurs_counter_bca/kurs_counter_bca_landing.jsp'); }); } new bisnis();
const { expect } = require('chai') const path = require('path') const ldnode = require('../../index') const supertest = require('supertest') const serverOptions = { root: path.join(__dirname, '../resources/headers'), multiuser: false, webid: true, sslKey: path.join(__dirname, '../keys/key.pem'), sslCert: path.join(__dirname, '../keys/cert.pem'), forceUser: 'https://ruben.verborgh.org/profile/#me' } describe('Header handler', () => { let request before(() => { const server = ldnode.createServer(serverOptions) request = supertest(server) }) describe('WAC-Allow', () => { describeHeaderTest('read/append for the public', { resource: '/public-ra', headers: { 'WAC-Allow': 'user="read append",public="read append"', 'Access-Control-Expose-Headers': /(^|,\s*)WAC-Allow(,|$)/ } }) describeHeaderTest('read/write for the user, read for the public', { resource: '/user-rw-public-r', headers: { 'WAC-Allow': 'user="read write append",public="read"', 'Access-Control-Expose-Headers': /(^|,\s*)WAC-Allow(,|$)/ } }) describeHeaderTest('read/write/append/control for the user, nothing for the public', { resource: '/user-rwac-public-0', headers: { 'WAC-Allow': 'user="read write append control",public=""', 'Access-Control-Expose-Headers': /(^|,\s*)WAC-Allow(,|$)/ } }) }) function describeHeaderTest (label, { resource, headers }) { describe(`a resource that is ${label}`, () => { let response before(() => request.get(resource).then(res => { response = res })) for (const header in headers) { const value = headers[header] const name = header.toLowerCase() if (value instanceof RegExp) { it(`has a ${header} header matching ${value}`, () => { expect(response.headers).to.have.property(name) expect(response.headers[name]).to.match(value) }) } else { it(`has a ${header} header of ${value}`, () => { expect(response.headers).to.have.property(name, value) }) } } }) } })
const fetch = require("node-fetch"); let get = (uri, resolve, reject) => { return new Promise((resolve, reject) => { fetch(uri) .then((resource) => { if (resource.ok) { return resource.json(); } else throw(resource); }) .then((result) => { resolve(result); }) .catch((err) => { if (reject) reject(err); console.error(err) }); }); }; exports.legacy = (resolve, reject) => { return get("http://api.bluelytics.com.ar/json/last_price",resolve,reject); }; exports.latest = (resolve, reject) => { return get("http://api.bluelytics.com.ar/v2/latest",resolve,reject); };
CKEDITOR.plugins.add( 'cia_inlinesave', { init: function( editor ) { editor.addCommand( 'cia_inlinesave', { exec : function( editor ) { SaveData(); } }); editor.ui.addButton( 'Inlinesave', { label: 'Save', command: 'cia_inlinesave', icon: this.path + 'images/inlinesave.png' } ); } } );
// Generated by CoffeeScript 1.4.0 (function() { $('document').ready(function() { var init, pendulumswing, rotation, swingtime; rotation = 3; swingtime = 700; init = function() { return $('#get_in_touch_pivot').stop().animate({ rotate: rotation }, 0, function() { $('#get_in_touch_pivot').css("display", "block"); return pendulumswing(); }); }; pendulumswing = function() { return $('#get_in_touch_pivot').animate({ rotate: rotation }, swingtime, "swing", function() { if (rotation === 0) { return; } if (rotation > 0) { rotation -= 0.5; } else { rotation += 0.5; } rotation *= -1; return pendulumswing(); }); }; return $('#contact').waypoint(function(direction) { if (direction === 'down') { rotation = 3; swingtime = 700; return init(); } }, { offset: 500 }); }); }).call(this);
"use strict"; module.exports = function(){ var dao = new app.dao.project() , resolve = new app.views.json().promise; return { list: function (req, res, next) { var input = app.utils.mongoose.query(req.query); resolve( dao.list(input.query, input.fields, input.projection), res, next ); }, find: function(req, res, next){ resolve(dao.find(req.params.id), res, next); }, create: function(req, res, next){ resolve(dao.create(req.body), res, next); }, update: function(req, res, next){ var q = req.query , id = req.params.id; resolve(( q.proposal !== undefined && dao.addProposal(id, q.proposal) || q.question !== undefined && dao.addQuestion(id, q.question) || ( q.experience !== undefined && dao.addExperience(id, q.experience) ) || dao.update(id, req.body) ), res, next); }, delete: function(req, res, next){ resolve(dao.delete(req.params.id), res, next); } }; };
/** * Action types. */ export const FETCH_REPOSITORIES = 'home/FETCH_REPOSITORIES'; export const UPDATE_REPOSITORIES = 'home/UPDATE_REPOSITORIES'; /** * Returns an action of type FETCH_REPOSITORIES, that tells * the app to fetch repositories from the given organization. * * @param {string} organization - Organisation name. * @return {object} - Action. */ export const fetchRepositories = (organization) => ({ type: FETCH_REPOSITORIES, payload: { organization } }); /** * Returns an action of type UPDATE_REPOSITORIES, that tells * the app to update repositories in the store. * * @param {array} repositories - Repositories. * @return {object} - Action. */ export const updateRepositories = (repositories) => ({ type: UPDATE_REPOSITORIES, payload: { repositories } });
/** * array_merge for phpjs */ function array_merge () { // eslint-disable-line camelcase // discuss at: http://locutus.io/php/array_merge/ // original by: Brett Zamir (http://brett-zamir.me) // bugfixed by: Nate // bugfixed by: Brett Zamir (http://brett-zamir.me) // input by: josh // example 1: var $arr1 = {"color": "red", 0: 2, 1: 4} // example 1: var $arr2 = {0: "a", 1: "b", "color": "green", "shape": "trapezoid", 2: 4} // example 1: array_merge($arr1, $arr2) // returns 1: {"color": "green", 0: 2, 1: 4, 2: "a", 3: "b", "shape": "trapezoid", 4: 4} // example 2: var $arr1 = [] // example 2: var $arr2 = {1: "data"} // example 2: array_merge($arr1, $arr2) // returns 2: {0: "data"} var args = Array.prototype.slice.call(arguments) var argl = args.length var arg var retObj = {} var k = '' var argil = 0 var j = 0 var i = 0 var ct = 0 var toStr = Object.prototype.toString var retArr = true for (i = 0; i < argl; i++) { if (toStr.call(args[i]) !== '[object Array]') { retArr = false break } } if (retArr) { retArr = [] for (i = 0; i < argl; i++) { retArr = retArr.concat(args[i]) } return retArr } for (i = 0, ct = 0; i < argl; i++) { arg = args[i] if (toStr.call(arg) === '[object Array]') { for (j = 0, argil = arg.length; j < argil; j++) { retObj[ct++] = arg[j] } } else { for (k in arg) { if (arg.hasOwnProperty(k)) { if (parseInt(k, 10) + '' === k) { retObj[ct++] = arg[k] } else { retObj[k] = arg[k] } } } } } return retObj }
"use strict"; var log_1 = require("../log/log"); var production = process.env["NODE_ENV"] === "production" ? "production" : "development"; function getEnvironmentalVariable(variable, defaultValue, printToConsole) { defaultValue = defaultValue ? defaultValue : ""; printToConsole = printToConsole !== undefined ? printToConsole : true; if (!process.env[variable]) { log_1["default"].error("Could not find environmental variable '" + variable + "', using value '" + defaultValue + "'."); return defaultValue; } var message = "Found environmental variable: '" + variable + "'"; if (printToConsole === true) { message += ", value '" + process.env[variable] + "'."; } else { message += "."; } log_1["default"].trace(message); return process.env[variable]; } exports.getEnvironmentalVariable = getEnvironmentalVariable; ; function printProductionStatus() { log_1["default"].info("Application running in '" + production + "' mode."); } exports.printProductionStatus = printProductionStatus; ; function isInProduction() { return production === "production"; } exports.isInProduction = isInProduction; function getDatabaseConnectionString() { var user = getEnvironmentalVariable("DB_USER", "", false); var password = getEnvironmentalVariable("DB_PASSWORD", "", false); var url = getEnvironmentalVariable("DB_URL", "", false); var application = getEnvironmentalVariable("DB_APPLICATION", "", false); if (user === "" || password === "" || url === "") { throw "Application cannot run without defined DB_USER, DB_PASSWORD and DB_URL environment variables."; } return "mongodb://" + user + ":" + password + "@" + url + "/" + application; } exports.getDatabaseConnectionString = getDatabaseConnectionString;
version https://git-lfs.github.com/spec/v1 oid sha256:c8b4fcb018b12f9e11099f7a8ad08808bfa3f4a6012357390ac1182b36657227 size 12227
/* * grunt-fontface * https://github.com/nsmith7989/grunt-fontface * * Copyright (c) 2014 Nathanael Smith * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('fontface', 'Generate CSS/SCSS from all font files within a font directory', function () { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ fontDir: 'fonts', outputFile: 'sass/_fonts.scss', removeFromFile: '-webfont' }), fontFiles = []; var _ = require('underscore'), path = require('path'), fs = require('fs'), fontFiles = [], uniqFontFiles = [], contents = ''; //rewrite file names fs.readdirSync(process.cwd() + '/' + options.fontDir, function(err, files) { files.forEach(function(file) { if (file.indexOf('-webfont') !== -1) { var workiingFile = path.resolve(file); grunt.log.write(workiingFile); fs.rename(workiingFile, workiingFile.replace('-webfont', '', function(err) { if (err) throw err; })); } }); }); grunt.file.recurse(process.cwd() + '/' + options.fontDir, function(abspath, rootdir, subdir, filename) { if (filename.indexOf(options.removeFromFile) !== -1) { grunt.log.writeln('>>Renaming ' + filename); var workiingFile = path.resolve(process.cwd() + '/' + options.fontDir + '/' + filename); fs.renameSync(workiingFile, workiingFile.replace('-webfont', ''), function(err) { if (err) throw err; }); filename = filename.replace(options.removeFromFile, ''); } var processFile = filename.substring(0, filename.lastIndexOf('.')); fontFiles.push(processFile); }); //reduce the array uniqFontFiles = _.uniq(fontFiles).filter(function(elem) { if (elem) { return elem; } }); //build contents uniqFontFiles.forEach(function(elem) { _.templateSettings = { interpolate: /\{\{(.+?)\}\}/g }; var template = _.template(options.template); contents += template({font: elem}) + grunt.util.linefeed; }); grunt.file.write(options.outputFile, contents); }); };
var _; //globals describe("About Applying What We Have Learnt", function() { var products; beforeEach(function () { products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false }, { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true }, { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true } ]; }); /*********************************************************************************/ it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () { var i,j,hasMushrooms, productsICanEat = []; for (i = 0; i < products.length; i+=1) { if (products[i].containsNuts === false) { hasMushrooms = false; for (j = 0; j < products[i].ingredients.length; j+=1) { if (products[i].ingredients[j] === "mushrooms") { hasMushrooms = true; } } if (!hasMushrooms) productsICanEat.push(products[i]); } } expect(productsICanEat.length).toBe(1); }); it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { var productsICanEat = []; var noNuts = _(products).filter(function(x) { return x.containsNuts == false }); var noNutsOrShrooms = _(noNuts).filter(function(x) { return x.ingredients.indexOf("mushrooms") == -1 }); productsICanEat = noNutsOrShrooms; /* solve using filter() & all() / any() */ expect(productsICanEat.length).toBe(1); }); /*********************************************************************************/ it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { var sum = 0; for(var i=1; i<1000; i+=1) { if (i % 3 === 0 || i % 5 === 0) { sum += i; } } var range = _.range(1, 1000); var ansArr = _(range).filter(function (x) { return x % 3 === 0 || x % 5 === 0 }); var ans = _(ansArr).reduce(function (sum, x) { return sum + x }); expect(sum).toBe(ans); }); it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { var sum = _.range(1,1000).filter(function(x) { return x % 3 === 0 || x % 5 === 0}).reduce(function (sum, x) { return sum + x }); /* try chaining range() and reduce() */ expect(233168).toBe(sum); }); /*********************************************************************************/ it("should count the ingredient occurrence (imperative)", function () { var ingredientCount = { "{ingredient name}": 0 }; for (i = 0; i < products.length; i+=1) { for (j = 0; j < products[i].ingredients.length; j+=1) { ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1; } } expect(ingredientCount['mushrooms']).toBe(2); }); it("should count the ingredient occurrence (functional)", function () { // var ingredientCount = { "{ingredient name}": 0 }; var ingredientCount = _(products).chain() .pluck("ingredients") .flatten() .reduce(function(memo, item) { memo[item] = (memo[item] || 0) + 1; return memo; }, {}) .value(); /* chain() together map(), flatten() and reduce() */ expect(ingredientCount['mushrooms']).toBe(2); }); /*********************************************************************************/ /* UNCOMMENT FOR EXTRA CREDIT */ /* it("should find the largest prime factor of a composite number", function () { }); it("should find the largest palindrome made from the product of two 3 digit numbers", function () { }); it("should find the smallest number divisible by each of the numbers 1 to 20", function () { }); it("should find the difference between the sum of the squares and the square of the sums", function () { }); it("should find the 10001st prime", function () { }); */ });
/** * Module dependencies */ var program = require('commander'); var messages = require('./messages'); var notify = require('./notify'); program.parse(process.argv); module.exports = function(mssg) { console.log(program.args); notify.debug(mssg); }; /** * Export the whole thing */ // module.exports = { // debug: debug // };
(function () { console.log("Start"); var hub = $.connection.testHub; //hub.client.tell does not work, beware hub.client.answer = function (message, messageId) { console.log("Message received, id: " + messageId); console.log(message); }; $.connection.hub.start().done(function () { console.log("Hup opened"); var path = "/echo"; var msg = { "Message": "Ping" }; var msgType = "SignalRMeetsAkka.Echo"; console.log("Send(" + path + ", " + JSON.stringify(msg) + ", " + msgType); hub.server.send(path, msg, msgType); var uuid = "t45t8u34r8h3u984ur9384r"; console.log("Ask(" + path + ", " + JSON.stringify(msg) + ", " + msgType + ", " + uuid); hub.server.ask(path, msg, msgType, uuid); }); })();
// +---------------------------------------------------------------------- // | CmsWing [ 网站内容管理框架 ] // +---------------------------------------------------------------------- // | Copyright (c) 2015 http://www.cmswing.com All rights reserved. // +---------------------------------------------------------------------- // | Author: arterli <arterli@qq.com> // +---------------------------------------------------------------------- const DEFULT_AUTO_REPLY = '功能正在开发中~'; module.exports = class extends think.Controller { indexAction() { const echostr = this.get('echostr'); return this.body = echostr; } // 关键词消息回复 async textAction() { // console.log(this.http); const message = this.post(); // console.log(message); const key = message.Content.trim(); const kmodel = this.model('wx_keywords'); const isKey = await kmodel.field('rule_id').where({keyword_name: key}).find(); if (!think.isEmpty(isKey)) { // 是关键字 const rulemodel = this.model('wx_keywords_rule'); const replyliststr = await rulemodel.where({id: isKey.rule_id}).getField('reply_id', true); const replylisttmp = replyliststr.split(','); const replylist = []; for (const i in replylisttmp) { if (replylisttmp[i] != '') { replylist.push(replylisttmp[i]); } } if (!think.isEmpty(replylist)) { const randomi = parseInt(Math.random() * replylist.length); const replymodel = this.model('wx_replylist'); const data = await replymodel.where({id: replylist[randomi]}).getField('content', true); return this.success(data); } } // 普通消息回复 const replymodel = this.model('wx_replylist'); const datas = await replymodel.where({reply_type: 2}).order('create_time DESC').select(); const data = datas[0]; let content; switch (data.type) { case 'text': content = data.content; break; case 'news': content = JSON.parse(data.content); break; } return this.success(content); } // 事件关注 async eventAction() { const message = this.post(); switch (message.Event) { case 'subscribe': // 首次关注 const datas = await this.model('wx_replylist').where({reply_type: 1}).order('create_time DESC').select(); const data = datas[0]; let content; switch (data.type) { case 'text': content = data.content; break; case 'news': content = JSON.parse(data.content); break; } this.success(content); break; case 'unsubscribe':// 取消关注 // todo break; case 'CLICK':// click事件坚挺 const res = await this.model('wx_material').find(message.EventKey); const news_item = JSON.parse(res.material_wx_content); const list = news_item.news_item; for (const v of list) { v.picurl = v.thumb_url; } this.success(list); // todo break; case 'SCAN':// 扫码事件监听 // todo console.log(message); break; default: console.log(message); break; } // this.reply(JSON.stringify(message)); } __call() { return this.success(DEFULT_AUTO_REPLY); } };
var gulp = require('gulp'); gulp.task('phpmd', function(callback) { var spawn = require('child_process').spawn; spawn( 'phpmd', [ 'src', 'text', 'app/Resources/phpmd.xml' ], {stdio: 'inherit'} ).on('close', function(code, signal) { callback(); }); });
let fileInfoOptions = { name: 'file.info', filename: 'out.log', colorize: true, level : 'info', levels : {debug: 0, info : 1, warn: 2, error: 3}, colors : {debug: 'blue', info : 'green', warn: 'orange', error: 'red'}, json: true, handleExeptions: true, humanReadableUnhandledException: true, }; let fileErrorOptions = { name: 'file.error', filename: 'err.log', colorize: true, level : 'error', levels : {debug: 0, info : 1, warn: 2, error: 3}, colors : {debug: 'blue', info : 'green', warn: 'orange', error: 'red'}, json: true, handleExeptions: true, humanReadableUnhandledException: true, }; // Share the same transport(=File) between 2 different files... // one for debug & the other file for errors only. logger.addTransport('file', fileInfoOptions); logger.addTransport('file', fileErrorOptions); let consoleOptions = { colorize: true, level : 'info', }; logger.addTransport('console', consoleOptions); let papertrailOptions = { host: 'logs5.papertrailapp.com', // Replace with your papertrail app URL port: 44279, // Replace with your papertrail app's port number logFormat: function(level, message) { return '[' + level + '] ' + message; }, inlineMeta: true, json: true, colorize: true, handleExeptions: true }; // Simply add the papertrail transport logger.addTransport('papertrail', papertrailOptions);
define(['angular', './card.controller', './card.service', 'requestApi'], function (angular, cardsCtrl, CardDataService) { 'use strict'; angular.module('boardGame.card', ['boardGame.requestApi']) .service('CardDataService', CardDataService) .controller('cardsCtrl', cardsCtrl); });
const Koa = require('koa') const app = new Koa() const views = require('koa-views') const json = require('koa-json') const onerror = require('koa-onerror') const bodyparser = require('koa-bodyparser') const logger = require('koa-logger') const index = require('./routes/index') const users = require('./routes/users') const config = require('./config.js') // api代理 const proxy = require('koa-proxies') const httpsProxyAgent = require('https-proxy-agent') app.use(proxy('/api', { target: 'http://172.16.8.197:8081', changeOrigin: true, logs: true, rewrite: path => path.replace(/^\/api/g, '') // agent: new httpsProxyAgent('http://172.16.8.197:8081'), // rewrite: path => path.replace(/^\/api(\/|\/\w+)?$/, '') })) // 链接数据库 const db = require('mysql'); // var connection = db.createConnection({ // host: '172.16.8.191:3306', // // host: '172.16.8.191:3306/pudong', // user: 'root', // password: 'ipudong', // database: 'ceshi' // }) var connection = db.createConnection(config.mysql) connection.connect(function(err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); }); global.connection = connection; global.sf = require('./boot.js'); // error handler onerror(app) // middlewares app.use(bodyparser({ enableTypes:['json', 'form', 'text'] })) app.use(json()) app.use(logger()) // 使用端路由渲染页面 // app.use(require('koa-static')(__dirname + '/public')) // app.use(views(__dirname + '/views', { // extension: 'pug' // })) // 使用前端路由分离渲染页面 // app.use(require('koa-static')(__dirname + '/dist')) // app.use(views(__dirname + '/dist')) // 使用前端路由,前后端,node端做后端,代理访问其他数据员后台api app.use(require('koa-static')(__dirname + '/fronts')) app.use(views(__dirname + '/fronts')) // logger app.use(async (ctx, next) => { const start = new Date() await next() const ms = new Date() - start console.log(`${ctx.method} ${ctx.url} - ${ms}ms`) }) // routes app.use(index.routes(), index.allowedMethods()) app.use(users.routes(), users.allowedMethods()) module.exports = app
//= require spec_helper //= require models/dot //= require collections/dots //= require templates/dot_view //= require views/dot_view //= require views/dots_view describe('DotsView', function() { var subject, dot; beforeEach(function() { dots = new Dots(); dots.add([{ id: 1, name: 'Breakfast', priority: 3 }, { id: 2, name: 'Lunch', priority: 2 }, { id: 3, name: 'Dinner', priority: 1 }]); subject = new DotsView({ collection: dots }); SANDBOX.append(subject.render().el); }); describe("when an item is prioritized", function() { it("re-renders with the prioritized item at the top", function() { subject.$('.dot-prioritize[data-dot-id=' + dots.at(2).id + ']').trigger('click'); expect(subject.children.findByIndex(0).$el.hasClass('js-top')).to.be.true; }); }); });
import React from 'react' import Button from './Button' import { removeToken } from '../storages/SessionStorage' export default (props) => { const handleLogInClick = () => { chrome.runtime.sendMessage({ action: 'vk_notification_auth' }, (response) => { if (response.content == 'OK') { if (props.afterLogInClick) { props.afterLogInClick() } } }) } const handleLogOutClick = async () => { try { await removeToken() if (props.afterLogOutClick) { props.afterLogOutClick() } } catch (e) { /* handle error */ console.log(e); } } let button if (props.accessToken) { button = <Button onClick={ handleLogOutClick }>Выйти</Button> } else { button = <Button onClick={ handleLogInClick }>Войти</Button> } return props.hidden ? null : button }
/** * Services for connecting to Player's real-time API * @module realtime */
var mappingDefaults = { styles: ['css', 'less', 'scss', 'sass', 'styl'], templates: ['jade', 'pug', 'json', 'html', 'htm', 'yml', 'yaml'], images: ['jpg', 'jpeg', 'png', 'svg'], sprites: ['svg'] } module.exports = function(gulp, config, watch) { var mapping = require('lodash').merge({}, mappingDefaults, config.mapping || {}) var fileExtensions = [] var mappingRegEx = {} Object.keys(mapping).forEach(function(key) { mappingRegEx[key] = [] mappingRegEx[key] = mapping[key].map(function(i) { var ext = '.' + i.replace(/^\./, '') // remove . from the beginning of the string if(fileExtensions.indexOf(key) == -1) { fileExtensions.push(ext.substring(1)) } return new RegExp(ext + '$') }) }) return function(done) { var c = require('better-console') c.info('Watching sources for change and recompilation...') var log = require('better-console') var minimatch = require('minimatch') var path = require('path') var runcmd = require('../helpers/runcmd') var glob = '**/*.{' + fileExtensions.join() + '}' var subtractPaths = require('../helpers/subtractPaths') var distFolderRelative = subtractPaths(config.dist_folder, config.dir) var globDist = distFolderRelative + '/**/*.*' var completeHandler = function(e) { if(config.hooks && config.hooks.watch) { log.info('~ watch hook: ' + config.hooks.watch) runcmd(config.hooks.watch, config.dir, function() { log.info('/>') }) } } var changeHandler = function(filepath) { // Filter dist sources if (minimatch(filepath, globDist)) { return } config._lastChanged = filepath var handlers = [] Object.keys(mappingRegEx).forEach(function (key) { mappingRegEx[key].forEach(function(regexp) { if(filepath.match(regexp)) { handlers.push(key) } }) }) if (!handlers.length) { c.warn('! unknown extension', path.extname(filepath), filepath) return } handlers.forEach(function(handler) { try { gulp.task(handler)(completeHandler) } catch(e) { // task is not defined, we can silently ignore it } }) } watch(glob, changeHandler) done() } }
'use strict'; //TODO: // Use distinct routes per passenger [stopOver: true] // Create controls for numbers of cars, frequency of passenger requests, tick speed, pause // Track passenger wait times // Track car transit times per route; aggregate interesting stats // Export stats as .json; make downloadable // Show infowindow on car click for car-specific details // Animate marker events // Reshuffle optimize passengers that are not part of a car's immediate route RideshareSimApp.controller('OptionsCtrl', function($scope, app) { $scope.togglePause = function(){ app.togglePause(); } $scope.paused = function(){ return app.paused(); } $scope.togglePauseText = function(){ return ($scope.paused() ? 'Resume' : 'Pause'); } });
import Employee from '../../components/EmployeePage'; import { graphql } from 'gatsby'; /** TODO: make this work dynamically */ export const query = graphql` query { EmployeeImages: allFile( sort: { order: ASC, fields: [absolutePath] } filter: { relativePath: { regex: "/mugshots/hallvard.jpg/" } } ) { edges { node { relativePath name childImageSharp { fluid(maxWidth: 1000) { ...GatsbyImageSharpFluid } } } } } } `; export default Employee;
const chalk = require('chalk'); const settings = require('../settings.json'); exports.run = function(client, message, args) { if (message.author == settings.adminid){ // If anyone else was to host a version of this bot, you may wish to change this to your ID. console.log(chalk.bgRed('Send command used!')); let result = args.join(' '); // Stores the server id into a serperate string var server = result.split(" "); // So the message is neat. var messagePrep = server.toString(); var message = messagePrep.replace(/,/g , " "); // As it is an array converted to a string I must replace the commas with spaces! message = message.substr(message.indexOf(" ") + 1); // Removes the server ID. // Actually sends the message, yay. client.channels.get(server[0]).sendMessage(message); } };