text
stringlengths
2
6.14k
'use strict'; export default function routes($routeProvider) { 'ngInject'; $routeProvider.when('/new_component', { template: '<about></about>' }); $routeProvider.when('/new_component/:somethingToPrint', { template: '<about></about>' }); }
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'firehon', environment: environment, contentSecurityPolicy: { 'connect-src': "'self' wss://*.firebaseio.com" }, firebase: 'https://firehon.firebaseio.com/', baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { // Here you can pass flags/options to your application instance // when it is created } }; if (environment === 'development') { // ENV.APP.LOG_RESOLVER = true; // ENV.APP.LOG_ACTIVE_GENERATION = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; // ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'test') { // Testem prefers this... ENV.baseURL = '/'; ENV.locationType = 'none'; // keep test console output quieter ENV.APP.LOG_ACTIVE_GENERATION = false; ENV.APP.LOG_VIEW_LOOKUPS = false; ENV.APP.rootElement = '#ember-testing'; } if (environment === 'production') { } return ENV; };
'use strict'; angular.module('springangularwayApp') .config(function ($stateProvider) { $stateProvider .state('configuration', { parent: 'admin', url: '/configuration', data: { roles: ['ROLE_ADMIN'], pageTitle: 'configuration.title' }, views: { 'content@': { templateUrl: 'scripts/app/admin/configuration/configuration.html', controller: 'ConfigurationController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('configuration'); return $translate.refresh(); }] } }); });
var path = require('path') var webpack = require('webpack') // Phaser webpack config var phaserModule = path.join(__dirname, '/node_modules/phaser-ce/') var phaser = path.join(phaserModule, 'build/custom/phaser-split.js') var pixi = path.join(phaserModule, 'build/custom/pixi.js') var p2 = path.join(phaserModule, 'build/custom/p2.js') var definePlugin = new webpack.DefinePlugin({ __DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'false')) }) module.exports = { entry: { app: [ 'babel-polyfill', path.resolve(__dirname, 'src/main.js') ], vendor: ['pixi', 'p2', 'phaser', 'webfontloader', 'react'] }, output: { path: path.resolve(__dirname, 'dist'), publicPath: './dist/', filename: 'bundle.js' }, plugins: [ definePlugin, new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new webpack.optimize.UglifyJsPlugin({ drop_console: true, minimize: true, output: { comments: false } }), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor'/* chunkName= */, filename: 'vendor.bundle.js'/* filename= */}) ], module: { rules: [ { test: /\.js$/, use: ['babel-loader'], include: path.join(__dirname, 'src') }, { test: /pixi\.js/, use: ['expose-loader?PIXI'] }, { test: /phaser-split\.js$/, use: ['expose-loader?Phaser'] }, { test: /p2\.js/, use: ['expose-loader?p2'] }, { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['react', 'es2015']} } ] }, node: { fs: 'empty', net: 'empty', tls: 'empty' }, resolve: { alias: { 'phaser': phaser, 'pixi': pixi, 'p2': p2 } } }
define([ 'base/Module', './show/Controller' ],function(Module, ShowController){ var mod = Module('HeaderModule', {autoStart: false}); var API = { showHeader: function() { var controller = new ShowController({ region: mod.kernel.headerRegion }); controller.showHeader(); } }; mod.on('start', function(){ API.showHeader(); }); });
export function pluralize(count, word) { return count === 1 ? word : word + 's'; } export function classNames(...args) { // based on https://github.com/JedWatson/classnames let classes = ''; args.forEach(arg => { if (arg) { const argType = typeof arg; if (argType === 'string' || argType === 'number') { classes += ' ' + arg; } else if (Array.isArray(arg)) { classes += ' ' + classNames(...arg); } else if (argType === 'object') { Object.keys(arg).forEach(key => { if (arg[key]) { classes += ' ' + key; } }); } } }); return classes.substr(1); } export function uuid() { let i, random; let uuid = ''; for (i = 0; i < 32; i++) { random = Math.random() * 16 | 0; if (i === 8 || i === 12 || i === 16 || i === 20) { uuid += '-'; } uuid += (i === 12 ? 4 : (i === 16 ? (random & 3 | 8) : random)) .toString(16); } return uuid; }
Marker = function({ settings, rad }) { const long = settings.longMarker ? 'protractor-extension-marker-long' : ""; this.theta = rad - Math.PI / 2; this.phi = settings.phi; this.settings = settings; this.node = document.createElement('div'); this.node.className = `protractor-extension-marker ${long}`; this.node.style.borderBottom = `20px solid ${settings.markerFill}`; PubSub.subscribe(Channels.MOVE_CONTAINER, this); PubSub.subscribe(Channels.MOVE_HANDLE_ROTATE, this); return this.node; }; Marker.prototype = { onRotate: function(msg) { this.rotation += msg.phi; }, onUpdate: function(chan, msg) { switch(chan) { case Channels.MOVE_CONTAINER: this.onMoveContainer(msg); break; case Channels.MOVE_HANDLE_ROTATE: this.onMoveHandleRotate(msg); break; } }, onMoveContainer: function(msg) { this.node.style.height = `${msg.radius + 10}px`; if (this.settings.longMarker) { const rgba = this.settings.markerFill.replace('1)', '0.4)'); this.node.style.borderTop = `${msg.radius - 10}px solid ${rgba}`; } this.transform(); }, onMoveHandleRotate: function(msg) { this.phi = msg.phi; this.transform(); }, transform: function() { this.node.style.transform = `rotate(${this.theta + this.phi}rad)`; }, setMode: function() { this.node.className = (msg.mode === "lock" ? 'protractor-extension-marker protractor-extension-marker-locked' : 'protractor-extension-marker'); }, };
import Vue from 'vue' import Kanban from './components/kanban-app.vue' import store from './store.js' new Vue({ el: '#app', store, render: h => h(Kanban) })
import {observable, runInAction, computed, action, reaction, autorun} from "mobx"; import LynlpApi from "../common/lynlp-api" import _ from "lodash"; class EntityExtractStore { @observable isFetching = false; @observable currentItem = '图形展示'; @observable entity = {}; @action fetchData(content) { this.isFetching = true; LynlpApi.entity(content).then((result)=>{ this.entity = result; this.isFetching = false; }) } } const entityExtractStore = new EntityExtractStore(); export default entityExtractStore
'use strict'; const async = require('async'); const getApp = require('../utils/utils.js').getApp; module.exports = function(Worker) { //Worker.validatesPresenceOf('title'); Worker.upsertItem = (data, cb) => { let res = {}; getApp(Worker) .then((app) => { if (!!!data.person) cb({errCode: 'ERR_WORKER_NO_PERSON'}); if (!!!data.cargos || data.cargos.length === 0 ) cb({errCode: 'ERR_WORKER_NO_CARGO'}); console.log(data); return (!!!data.person.id ? app.models.person.create(data.person) : Promise.resolve(data.person) ) .then((result) => { res.person = result; return app.models.worker.upsert({ personId: res.person.id }); }) .then(results => { res.worker = results; res.cargoMapping = []; return new Promise((resolve, reject) => async.each(data.cargos, (cargoId, cbInner) => app.models.cargoMapping.create({ cargoId: cargoId, workerId: res.worker.id }) .then(r => cbInner(null, res.cargoMapping.push(r))) .catch(err => async.each(res.cargoMapping, (itemInner, cbInner2) => cbInner2(null, itemInner.destroy()), err => cbInner({ errCode: 'ERR_WORKER_FAIL_CARGOS', message: 'problem to save cargo in worker' }) )), err => !!err ? reject(err) : resolve(res) )); }) .then(res => { cb(null, res); }) .catch(err => { if (!!res.person) res.person.destroy(); if (!!res.worker) res.worker.destroy(); cb({errCode: 'ERR_WORKER_NO_SAVE'}); }); }); }; Worker.remoteMethod('upsertItem', { description: 'upsert client ', http: {verb: 'post'}, accepts: { arg: 'data', type: 'object', description: 'data from form to upsert client', http: {source: 'body'}, required: true }, returns: { arg: 'res', type: 'object', root: true } }); };
import { combineReducers } from 'redux' import auth from './auth' import watt from './watt' import locations from './locations' export default combineReducers({ auth, watt, locations })
'use strict'; require('./components/dropdown'); require('./components/active-link');
/* eslint-env mocha */ 'use strict' const chai = require('chai') chai.use(require('dirty-chai')) const expect = chai.expect const parallel = require('async/parallel') const createNode = require('./utils/create-node.js') const echo = require('./utils/echo') describe('ping', () => { let nodeA let nodeB before((done) => { parallel([ (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist() nodeA = node node.handle('/echo/1.0.0', echo) node.start(cb) }), (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => { expect(err).to.not.exist() nodeB = node node.handle('/echo/1.0.0', echo) node.start(cb) }) ], done) }) after((done) => { parallel([ (cb) => nodeA.stop(cb), (cb) => nodeB.stop(cb) ], done) }) it('should be able to ping another node', (done) => { nodeA.ping(nodeB.peerInfo, (err, ping) => { expect(err).to.not.exist() ping.once('ping', (time) => { expect(time).to.exist() ping.stop() done() }) ping.start() }) }) it('should be not be able to ping when stopped', (done) => { nodeA.stop(() => { nodeA.ping(nodeB.peerInfo, (err) => { expect(err).to.exist() done() }) }) }) })
'use strict'; angular.module('articles').controller('ArticlesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Articles', function($scope, $stateParams, $location, Authentication, Articles) { $scope.authentication = Authentication; $scope.create = function() { var article = new Articles({ title: this.title, content: this.content }); article.$save(function(response) { $location.path('articles/' + response._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); this.title = ''; this.content = ''; }; $scope.remove = function(article) { if (article) { article.$remove(); for (var i in $scope.articles) { if ($scope.articles[i] === article) { $scope.articles.splice(i, 1); } } } else { $scope.article.$remove(function() { $location.path('articles'); }); } }; $scope.update = function() { var article = $scope.article; article.$update(function() { $location.path('articles/' + article._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.find = function() { $scope.articles = Articles.query(); }; $scope.findOne = function () { $scope.article = Articles.get({ articleId: $stateParams.articleId }); }; } ]);
require('..').config({namespace:'NVM'}) .read({}) .on('read', function(ENV){ console.log(JSON.stringify(ENV, null, 4)); });
const express = require("express"); const app = express(); app.set('port', (process.env.PORT || 3000)); const getData = require('./src/server/api/getData'); const setup = require('./src/server/api/setupApi'); app.engine('html', require('ejs').renderFile); app.set('view engine', 'html'); app.use('/assets', express.static('build')); app.use('/', require('./src/server/routers/index')); app.get('/api/:chrom', getData); const server = app.listen(app.get('port')); setup(server);
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Category Schema */ var CategorySchema = new Schema({ name: { type: String, default: '', required: 'Please fill Category name', trim: true }, created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Category', CategorySchema);
var searchData= [ ['index',['index',['../d8/d33/structsvm__sample.html#a008f6b24c7c76af103e84245fb271506',1,'svm_sample']]], ['initlibirwls',['initLIBIRWLS',['../d4/d54/pythonmodule_8c.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void):&#160;pythonmodule.c'],['../d0/da7/pythonmodule_8h.html#abe9b02ef8b3dff171684f855d6819d13',1,'initLIBIRWLS(void):&#160;pythonmodule.c']]], ['initmemory',['initMemory',['../d0/d98/ParallelAlgorithms_8h.html#aa6df8c3f4f455d5692b3cb220fc205c7',1,'ParallelAlgorithms.h']]], ['iostructures_2ec',['IOStructures.c',['../dc/dfc/IOStructures_8c.html',1,'']]], ['iostructures_2eh',['IOStructures.h',['../de/d79/IOStructures_8h.html',1,'']]], ['irwlspar',['IRWLSpar',['../d4/d49/budgeted-train_8h.html#ad51d9a46645ad0b0bedb1113a3807d24',1,'budgeted-train.h']]] ];
module.exports = { options: { templateCompilerPath: 'bower_components/ember/ember-template-compiler.js', handlebarsPath: 'bower_components/handlebars/handlebars.js', preprocess: function (source) { return source.replace(/\s+/g, ' '); }, templateName: function (sourceFile) { /* These are how templates will be named based on their folder structure. components/[name].hbs ==> components/[name] partials/[name].hbs ==> _[name] modules/application/templates/[name].hbs ==> [name] modules/application/partials/[name].hbs ==> _[name] modules/[moduleName]/templates/[moduleName].hbs ==> [moduleName] modules/[moduleName]/templates/[name].hbs ==> [moduleName]/[name] modules/[moduleName]/partials/[name].hbs ==> [moduleName]/_[name] Additionally any template that is nested deeper will have that structure added as well. modules/[moduleName]/templates/[folder1]/[folder2]/[name] ==> [moduleName]/[folder1]/[folder2]/[name] */ var matches = sourceFile.match(new RegExp('(?:app/modules/(.*?)/|app/)(templates|partials)?/?(.*)')), moduleName = matches[1], isAppModule = (moduleName === 'application'), isPartial = (matches[2] === 'partials'), fileName = matches[3], prefix = (isPartial ? '_' : ''), templateName = ''; if (moduleName && !isAppModule) { if (fileName === moduleName) { templateName = moduleName; } else { templateName = moduleName + '/' + prefix + fileName; } } else { templateName = prefix + fileName; } console.log('Compiling ' + sourceFile.blue + ' to ' + templateName.green); return templateName; } }, compile: { files: { 'tmp/compiled-templates.js': ['templates/**/*.{hbs,handlebars}', 'app/**/*.{hbs,handlebars}'] } } };
module.exports = api => { api.cache(true); return { presets: [ [ '@babel/preset-env', { targets: { node: '12' } } ] ] }; };
'use strict'; function UserListController(userList) { var vm = this; console.log('UserListController'); vm.userList = userList; } module.exports = UserListController;
import log from 'log'; import Ember from 'ember'; import {registerComponent} from 'ember-utils'; import layout from './confirm-toolbar.hbs!'; export var RheaConfirmToolbar = Ember.Component.extend({ layout, tagName: '', actions: { confirm: function(opID) { this.sendAction('confirm'); }, cancel: function(opID) { this.sendAction('cancel'); } } }); registerComponent('rhea-confirm-toolbar', RheaConfirmToolbar);
/** * 乘法操作符 */ define( function ( require, exports, modules ) { var kity = require( "kity" ); return kity.createClass( 'MultiplicationOperator', { base: require( "operator/binary-opr/left-right" ), constructor: function () { var ltr = new kity.Rect( 0, 20, 43, 3, 3 ).fill( "black"), rtl = new kity.Rect( 20, 0, 3, 43, 3 ).fill( "black" ); this.callBase( "Multiplication" ); this.addOperatorShape( ltr.setAnchor( 22, 22 ).rotate( 45 ) ); this.addOperatorShape( rtl.setAnchor( 22, 22 ).rotate( 45 ) ); } } ); } );
'use strict'; var _ = require('underscore'); module.exports = _.extend( require('./env/all'), require('./env/' + process.env.NODE_ENV) || {} );
<canvas id="drawing" width="200" height="200">A drawing of something.</canvas>
// instanciando módulos var gulp = require('gulp'); var watch = require('gulp-watch'); var del = require('del'); var shell = require('gulp-shell'); var connect = require('gulp-connect'); gulp.task('run:pelican', shell.task([ 'pelican content -s pelicanconf.py' ])); gulp.task('clean:pelican', function () { return del([ 'output/*' ]); }); gulp.task('connect', function(){ connect.server({ root: ['output'], port: 1337, livereload: true }); }); gulp.task('reload:output', function () { connect.reload(); }); gulp.task('watch', function(){ // watch('content/*', gulp.series('run:pelican', 'reload:output')); // watch('*', gulp.series('run:pelican', 'reload:output')); // watch('theme/*', gulp.series('run:pelican', 'reload:output')); // watch('theme/templates/*', gulp.series('run:pelican', 'reload:output')); // watch('theme/static/css/*', gulp.series('run:pelican', 'reload:output')); // watch('theme/static/js/*', gulp.series('run:pelican', 'reload:output')); }) gulp.task('serve', gulp.parallel('connect','run:pelican', 'watch'));
var smidig = smidig || {}; smidig.voter = (function($) { var talk_id, $form, $notice, $loader; function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } function save_vote($form, talk_id) { var votes = JSON.parse(localStorage.getItem("votes")) || {}; votes[talk_id] = true; localStorage.setItem("votes", JSON.stringify(votes)); finished($form); } function bind($form, talk_id) { $form.find("input[name='commit']").click(function() { var data = $form.serializeObject(); if(!data["feedback_vote[vote]"]) { alert("Du må gi minst 1 stjerne!"); return; } $form.find(".inputs").hide(); $form.find(".ajaxloader").show(); $form.find(".ajaxloader").css("visibility", "visible") $.ajax({ type: "POST", url: $form.attr("action"), dataType: 'json', data: data, complete: function(xhr) { if (xhr.readyState == 4) { if (xhr.status == 201) { smidig.voter.save_vote($form, talk_id); } } else { alert("Det skjedde noe galt ved lagring. Prøv igjen"); $form.find(".ajaxloader").hide(); $form.find(".inputs").show(); } } }); //cancel submit event.. return false; }); } function init($form, talk_id) { if(!supports_html5_storage()) { $notice.text("Din enhet støttes ikke"); finished($form); } var votes = JSON.parse(localStorage.getItem("votes")) || {}; if(votes[talk_id]) { finished($form); } else { bind($form, talk_id); } } function finished($form) { $form.empty(); $form.append("<em>(Du har stemt)</em>"); $form.show(); } return { init: init, save_vote: save_vote }; })(jQuery); //Document on load! $(function() { $(".talk").each(function() { var talk_id = $(this).data("talkid"); if(talk_id) { var voteTmpl = $("#tmplVote").tmpl({talk_id: talk_id}); voteTmpl.find("input.star").rating(); $(this).find(".description").append(voteTmpl); smidig.voter.init(voteTmpl, talk_id); } }); }); //Extensions to serialize a form to a js-object. $.fn.serializeObject = function(){ var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; };
import express from 'express'; import LessonController from '../controllers/LessonController'; const router = express.Router(); /* eslint-disable no-unused-vars */ const LessonsPath = '/api/lessonplans'; const teacherName = 'yonderWay'; const subjectName = 'theatre1'; const lessonNumber = '/:id'; // the data access should look something like this: // '/api/teachers/{name}/{class}/{lesson#}' router.post(LessonsPath, LessonController.create); router.get(LessonsPath, LessonController.list); router.get(LessonsPath + '/:id', LessonController.listOne); router.put(LessonsPath + '/:id', LessonController.update); router.delete(LessonsPath + '/:id', LessonController.delete); export default router;
export { default, email } from '@abcum/ember-helpers/helpers/email';
module.exports = (function () { 'use strict'; var strings = require('../../strings').dead, style = require('../../style'); return { create: function(){ this.game.world.width = this.game.canvas.width; this.game.world.height = this.game.canvas.height; this.game.camera.reset(); this.game.stage.backgroundColor = style.color.three; var deadText = this.game.add.text( this.game.world.centerX, 200, strings.gregory, { font: 'bold 60px ' + style.font.regular, fill: style.color.white, align: 'center' } ); deadText.anchor.setTo(0.5); this.game.stage.backgroundColor = style.color.three; var face = this.game.add.text( this.game.world.centerX, 320, strings.face, { font: 'bold 85px ' + style.font.regular, fill: style.color.white, align: 'center' } ); face.anchor.setTo(0.5); this.game.stage.backgroundColor = style.color.three; var instructions = this.game.add.text( this.game.world.centerX, 430, strings.instructions, { font: 'bold 20px ' + style.font.regular, fill: style.color.white, align: 'center' } ); instructions.anchor.setTo(0.5); }, capabilities: { 'revive': function(){this.game.state.start('map');} } }; })();
// We only need to import the modules necessary for initial render import CoreLayout from '../layouts/CoreLayout'; import Home from './Home'; import CounterRoute from './Counter'; /* Note: Instead of using JSX, we recommend using react-router PlainRoute objects to build route definitions. */ export const createRoutes = () => ({ path : '/', component : CoreLayout, indexRoute : Home, childRoutes : [ CounterRoute ] }); /* Note: childRoutes can be chunked or otherwise loaded programmatically using getChildRoutes with the following signature: getChildRoutes (location, cb) { require.ensure([], (require) => { cb(null, [ // Remove imports! require('./Counter').default(store) ]) }) } However, this is not necessary for code-splitting! It simply provides an API for async route definitions. Your code splitting should occur inside the route `getComponent` function, since it is only invoked when the route exists and matches. */ export default createRoutes;
import Colors from './Colors'; import Fonts from './Fonts'; import Metrics from './Metrics'; import Images from './Images'; import ApplicationStyles from './ApplicationStyles'; export { Colors, Fonts, Images, Metrics, ApplicationStyles };
import React from 'react'; import PropTypes from 'prop-types'; import Tooltip from '../Tooltip'; import SvgExclamation from '../svg/Exclamation.js'; import styles from './Input.scss'; class InputErrorSuffix extends React.Component { render() { return ( <Tooltip dataHook="input-tooltip" disabled={this.props.errorMessage.length === 0} placement="top" alignment="center" textAlign="left" content={this.props.errorMessage} overlay="" theme="dark" maxWidth="230px" hideDelay={150} > <div className={styles.exclamation}><SvgExclamation width={2} height={11}/></div> </Tooltip> ); } } InputErrorSuffix.propTypes = { theme: PropTypes.oneOf(['normal', 'paneltitle', 'material', 'amaterial']), errorMessage: PropTypes.string.isRequired, focused: PropTypes.bool }; export default InputErrorSuffix;
const fs = require("fs"); const path = require("path"); const {template} = require("lodash"); const minimist = require("minimist"); const yaml = require("js-yaml"); const argv = minimist(process.argv.slice(2)); const conf = {}; try { const src = fs.readFileSync(path.resolve(__dirname, "../deploy-config.yml")); const yml = yaml.safeLoad(src); Object.assign(conf, yml); if (argv.env && yml[argv.env]) Object.assign(conf, yml[argv.env]); else if (yml.env && yml[yml.env]) Object.assign(conf, yml[yml.env]); } catch(e) { if (e.code !== "ENOENT") console.error(e); } Object.assign(conf, argv); function walkfs(file, exts, fn) { const stat = fs.statSync(file); if (stat.isDirectory()) { fs.readdirSync(file).forEach(name => { walkfs(path.join(file, name), exts, fn); }); } else if (exts.includes(path.extname(file))) { const src = fs.readFileSync(file, "utf-8"); fn(src, file); } } function build(dir, out, exts, join="", mode) { const result = []; walkfs(dir, exts, (src, file) => { const data = Object.assign({}, conf, { __filename: file, __dirname: path.dirname(file) }); const opts = { variable: "$", imports: {} }; result.push(template(src, opts)(data).trim() + "\n"); }); if (result) { fs.writeFileSync(out, result.join(join + "\n"), { mode }); } } build( path.join(__dirname, "kube-conf"), path.resolve(__dirname, "../kubernetes.yml"), [ ".yml" ], "---" );
export default function createRegistry(repositories) { const storage = { ...repositories }; const registry = { register(repositoryName, repository) { storage[repositoryName] = repository; return registry; }, has(repositoryName) { return !!storage[repositoryName]; }, get(repositoryName) { return storage[repositoryName]; }, reduce(reducer, initialValue) { return Object .keys(storage) .reduce((previous, repositoryName) => reducer( previous, storage[repositoryName], repositoryName, ), initialValue); }, }; return registry; }
/** * Created by cc on 15-8-1. */ angular.module('app.services').factory('loginWithCode', ['app.api.http', '$ionicPopup','Storage','ENV','$state', function (http, $ionicPopup,Storage,ENV,$state) { var dataJSON = {} function login(){ if(ENV.code){ http.get('loginWithCode', {code:ENV.code}).success(function (data, status, headers, config) { console.log("loginWithCode:回调返回数据:"+JSON.stringify(data)) if(data.status == 200){ openIdLogin(data) } }) } } function openIdLogin(data){ if(data.user){ Storage.setUserInfo(data.user); } if(data.authInfo){ Storage.setAccessToken(data.authInfo); } if(data.openId){ Storage.set("openId",{openId:data.openId}) dataJSON['openId'] = data.openId } //自动登陆后,如果在登陆,注册,或忘记密码页面则跳到个人中心 if(data.user && data.authInfo && ($state.$current.name == 'forgetPass' || $state.$current.name == 'login' || $state.$current.name == 'signup')){ $state.go('tabs.usercenterMine') } } return { login:function(){ login() }, addOpenId:function(params){ console.log("addOpenId:"+JSON.stringify(params)) return angular.extend({openId:dataJSON.openId},params) } } }]);
version https://git-lfs.github.com/spec/v1 oid sha256:07f4bf13ba69118ebd88b07b6c66f211f610acc3cdf0a9322352a6b8100ba3ce size 682
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Product = mongoose.model('Product'), multiparty = require('multiparty'), uuid = require('node-uuid'), fs = require('fs'), _ = require('lodash'); /** * Create a Product */ exports.create = function(req, res, next) { var form = new multiparty.Form(); form.parse(req, function(err, fields, files) { var file = files.file[0]; var contentType = file.headers['content-type']; var tmpPath = file.path; var extIndex = tmpPath.lastIndexOf('.'); var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex); // uuid is for generating unique filenames. var fileName = uuid.v4() + extension; var destPath = '/home/blaze/Sites/github/yaltashop/uploads/' + fileName; //fs.rename(tmpPath, destPath, function(err) { if (err) { console.log('there was an error during saving file'); next(err); } var product = new Product(fields); file.name = file.originalFilename; product.photo.file = file; product.user = req.user; product.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(product); } }); //}); }); }; /** * Show the current Product */ exports.read = function(req, res) { res.jsonp(req.product); }; /** * Update a Product */ exports.update = function(req, res) { var product = req.product ; product = _.extend(product , req.body); product.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(product); } }); }; /** * Delete an Product */ exports.delete = function(req, res) { var product = req.product ; product.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(product); } }); }; /** * List of Products */ exports.list = function(req, res) { Product.find().sort('-created').populate('user', 'displayName').exec(function(err, products) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(products); } }); }; /** * Product middleware */ exports.productByID = function(req, res, next, id) { Product.findById(id).populate('user', 'displayName').exec(function(err, product) { if (err) return next(err); if (! product) return next(new Error('Failed to load Product ' + id)); req.product = product ; next(); }); }; /** * Product authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.product.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
var mongoose = require('mongoose'); var BaseModel = require("./base_model"); var Schema = mongoose.Schema; var ObjectId = Schema.ObjectId; var UserFollowSchema = new Schema({ user_id: { type: ObjectId }, kind: { type: String }, object_id: { type: ObjectId }, create_at: { type: Date, default: Date.now } }); UserFollowSchema.plugin(BaseModel); UserFollowSchema.index({user_id: 1, object_id: 1}, {unique: true}); mongoose.model('UserFollow', UserFollowSchema);
"use strict" const messages = require("..").messages const ruleName = require("..").ruleName const rules = require("../../../rules") const rule = rules[ruleName] testRule(rule, { ruleName, config: ["always"], accept: [ { code: "a { color :pink }", description: "space only before", }, { code: "a { color : pink }", description: "space before and after", }, { code: "a { color :\npink }", description: "space before and newline after", }, { code: "a { color :\r\npink }", description: "space before and CRLF after", }, { code: "$map:(key:value)", description: "SCSS map with no newlines", }, { code: "$list:('value1', 'value2')", description: "SCSS list with no newlines", }, { code: "a { background : url(data:application/font-woff;...); }", description: "data URI", } ], reject: [ { code: "a { color: pink; }", description: "no space before", message: messages.expectedBefore(), line: 1, column: 11, }, { code: "a { color : pink; }", description: "two spaces before", message: messages.expectedBefore(), line: 1, column: 11, }, { code: "a { color\t: pink; }", description: "tab before", message: messages.expectedBefore(), line: 1, column: 11, }, { code: "a { color\n: pink; }", description: "newline before", message: messages.expectedBefore(), line: 2, column: 1, }, { code: "a { color\r\n: pink; }", description: "CRLF before", message: messages.expectedBefore(), line: 1, column: 11, } ], }) testRule(rule, { ruleName, config: ["never"], accept: [ { code: "a { color:pink }", description: "no space before and after", }, { code: "a { color: pink }", description: "no space before and space after", }, { code: "a { color:\npink }", description: "no space before and newline after", }, { code: "a { color:\r\npink }", description: "no space before and CRLF after", }, { code: "$map :(key :value)", description: "SCSS map with no newlines", } ], reject: [ { code: "a { color : pink; }", description: "space before", message: messages.rejectedBefore(), line: 1, column: 11, }, { code: "a { color : pink; }", description: "two spaces before", message: messages.rejectedBefore(), line: 1, column: 11, }, { code: "a { color\t: pink; }", description: "tab before", message: messages.rejectedBefore(), line: 1, column: 11, }, { code: "a { color\n: pink; }", description: "newline before", message: messages.rejectedBefore(), line: 2, column: 1, }, { code: "a { color\r\n: pink; }", description: "CRLF before", message: messages.rejectedBefore(), line: 1, column: 11, } ], })
version https://git-lfs.github.com/spec/v1 oid sha256:012c0c10efb1958941ed2fd9f393df39f1ae6f76369bf56e500e39ade0496295 size 8392
/** * Инициализация модуля. */ /*global define*/ define(['./poke-control', './poke-history', 'jquery'], function (pokeControl, pokeHistory, $) { 'use strict'; var pokeSettings = { pokeControl: { selector: '.poke-control-container', template: '<form class="form"><div class="form-group"><label for="bdoChannel">Канал:</label><select class="form-control" name="bdoChannel" id="bdoChannel"></select></div><div class="form-group"><label for="bdoQuest">Квест:</label><select class="form-control" name="bdoQuest" id="bdoQuest"></select></div><button class="btn btn-success">Отправить</button></form>' }, pokeHistory: { selector: '.poke-history-container', template: '<table id="eventsHistory" class="table table-condensed table-hover table-striped"><thead><tr><th data-column-id="startDate">Начало</th><th data-column-id="channel" data-type="numeric">Канал</th><th data-column-id="event">Событие</th></tr></thead></table>', tableSelector: '#eventsHistory' } }, create; create = function (options) { pokeSettings = $.extend(pokeSettings, options); pokeControl.initialize(pokeSettings.pokeControl); pokeHistory.initialize(pokeSettings.pokeHistory); }; return { create: create }; });
db.groups.update( {lname: "marrasputki"}, {$set:{users: ["Jörö"], description: "Marrasputki 2018"}})
document.body.onkeydown = function( e ) { var keys = { 37: 'left', 39: 'right', 40: 'down', 38: 'rotate', 80: 'pause' }; if ( typeof keys[ e.keyCode ] != 'undefined' ) { keyPress( keys[ e.keyCode ] ); render(); } };
module.exports = { 'plugins': { 'local': { 'browsers': [ 'chrome', 'firefox' ] } } }
// JScript File var borderstyle function editorOn(divid){ $('#'+divid).parent().parent().find(' >*:last-child img').css('visibility','hidden'); borderstyle = $('#'+divid).parent().parent().css('border'); $('#'+divid).parent().parent().css('border','') } function editorOff(divid){ $('#'+divid).parent().parent().find(' >*:last-child img').css('visibility',''); $('#'+divid).parent().parent().css('border',borderstyle); }
(function () { 'use strict'; // var matcher = require('../../lib/matchUsers'); angular .module('chat.routes') .config(routeConfig); routeConfig.$inject = ['$stateProvider']; var c = "/room";// need to make this somehow return the correct room function routeConfig($stateProvider) { $stateProvider .state('chat', { url: c, templateUrl: '/modules/chat/client/views/chat.client.view.html', controller: 'ChatController', controllerAs: 'vm', data: { roles: ['user', 'admin'], pageTitle: 'Chat' } }); } }());
import React from 'react'; import { shallow } from 'enzyme'; import { expect } from 'chai'; import sinon from 'sinon'; import RadioInput from './'; describe('RadioInput', () => { let wrapper; let value; let style; let onChange; beforeEach(() => { value = 'test'; style = { backgroundColor: 'blue' }; onChange = sinon.spy(); wrapper = shallow( <RadioInput style={style} value={value} onChange={onChange} /> ); }); it('should render a radio tag', () => { expect(wrapper.find('radio')).to.have.length(1); }); it('should have a style value set via the style prop', () => { expect(wrapper.find('radio')).to.have.style('background-color', 'blue'); }); it('should have a value set via the value prop', () => { expect(wrapper.find('radio').text()).to.equal(value); }); it('should call onChange on change', () => { wrapper.find('radio').simulate('change'); expect(onChange.calledOnce).to.equal(true); }); });
/*global describe, beforeEach, it*/ 'use strict'; var assert = require('assert'); describe('ttwebapp generator', function () { it('can be imported without blowing up', function () { var app = require('../app'); assert(app !== undefined); }); });
/** * Created by Tivie on 12-11-2014. */ module.exports = function (grunt) { // Project configuration. var config = { pkg: grunt.file.readJSON('package.json'), concat: { options: { sourceMap: true, banner: ';/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n(function(){\n', footer: '}).call(this);' }, dist: { src: [ 'src/showdown.js', 'src/helpers.js', 'src/converter.js', 'src/subParsers/*.js', 'src/loader.js' ], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { options: { sourceMap: true, banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n' }, dist: { files: { 'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>'] } } }, jshint: { options: { jshintrc: '.jshintrc' }, files: [ 'Gruntfile.js', 'src/**/*.js', 'test/**/*.js' ] }, jscs: { options: { config: '.jscs.json' }, files: { src: [ 'Gruntfile.js', 'src/**/*.js', 'test/**/*.js' ] } }, changelog: { options: { repository: 'http://github.com/showdownjs/showdown', dest: 'CHANGELOG.md' } }, bump: { options: { files: ['package.json'], updateConfigs: [], commit: true, commitMessage: 'Release version %VERSION%', commitFiles: ['package.json'], createTag: true, tagName: '%VERSION%', tagMessage: 'Version %VERSION%', push: true, pushTo: 'upstream', gitDescribeOptions: '--tags --always --abbrev=1 --dirty=-d', globalReplace: false, prereleaseName: 'alpha', regExp: false } }, simplemocha: { node: { src: 'test/node/**/*.js', options: { globals: ['should'], timeout: 3000, ignoreLeaks: false, reporter: 'spec' } }, karlcow: { src: 'test/node/testsuite.karlcow.js', options: { globals: ['should'], timeout: 3000, ignoreLeaks: false, reporter: 'spec' } }, browser: { src: 'test/browser/**/*.js', options: { reporter: 'spec' } } } }; grunt.initConfig(config); require('load-grunt-tasks')(grunt); grunt.registerTask('concatenate', ['concat']); grunt.registerTask('lint', ['jshint', 'jscs']); grunt.registerTask('test', ['lint', 'concat', 'simplemocha:node']); grunt.registerTask('test-without-building', ['simplemocha:node']); grunt.registerTask('build', ['test', 'uglify']); grunt.registerTask('prep-release', ['build', 'changelog']); // Default task(s). grunt.registerTask('default', ['test']); };
// Export modules to global scope as necessary (only for testing) if (typeof process !== 'undefined' && process.title === 'node') { // We are in node. Require modules. expect = require('chai').expect; sinon = require('sinon'); num = require('..'); isBrowser = false; } else { // We are in the browser. Set up variables like above using served js files. expect = chai.expect; // num and sinon already exported globally in the browser. isBrowser = true; }
export var lusolveDocs = { name: 'lusolve', category: 'Algebra', syntax: ['x=lusolve(A, b)', 'x=lusolve(lu, b)'], description: 'Solves the linear system A * x = b where A is an [n x n] matrix and b is a [n] column vector.', examples: ['a = [-2, 3; 2, 1]', 'b = [11, 9]', 'x = lusolve(a, b)'], seealso: ['lup', 'slu', 'lsolve', 'usolve', 'matrix', 'sparse'] };
/* Copyright (c) 2017, Dogan Yazar Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Remove commonly used diacritic marks from a string as these * are not used in a consistent manner. Leave only ä, ö, å. */ var remove_diacritics = function(text) { text = text.replace('à', 'a'); text = text.replace('À', 'A'); text = text.replace('á', 'a'); text = text.replace('Á', 'A'); text = text.replace('è', 'e'); text = text.replace('È', 'E'); text = text.replace('é', 'e'); text = text.replace('É', 'E'); return text; }; // export the relevant stuff. exports.remove_diacritics = remove_diacritics;
import { StyleSheet } from "react-native"; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "flex-start", alignItems: "center", backgroundColor: "#669999" }, buttons: { // flex: 0.15, flexDirection: "row", alignItems: "center", marginVertical: 20 }, button: { marginHorizontal: 20, padding: 20, backgroundColor: "#0D4D4D", color: "white", textAlign: "center" }, selectedButton: { backgroundColor: "#006699" }, body: { // flex: 0.8, justifyContent: "flex-start", alignItems: "center" }, subTitle: { marginVertical: 10 }, viewport: { // flex: 1, alignSelf: "center", backgroundColor: "white" } }); export default styles;
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'Express' }); }); //test canvas router.get('/canvas', function (req, res, next) { res.render('canvas'); }); module.exports = router;
'use strict'; module.exports = { "definitions": { "validation-error": { "type": "object", "description": "Validation error", "properties": { "param": { "type": "string", "description": "The parameter in error" }, "msg": { "type": "string", "enum": ["invalid","required"], "description": "The error code" } } }, "validation-errors": { "type": "array", "description": "Validation errors", "items": { "$ref": "#/definitions/validation-error" } }, "system-error": { "type": "object", "description": "System error", "properties": { "error": { "type": "string", "description": "The error message" } } } } };
version https://git-lfs.github.com/spec/v1 oid sha256:2e65db5b56d276f8bcf293bede932b782ec29e72a25125d3412f81315301ecc4 size 14066
import { subtract } from '../subtract'; describe('Core.subtract', () => { test('Subtracts the second argument from the first', () => { expect(subtract(10, 8)).toBe(2); }); });
/*jslint node: true */ 'use strict'; var _ = require('underscore.string'), inquirer = require('inquirer'), path = require('path'), chalk = require('chalk-log'); module.exports = function() { return function (done) { var prompts = [{ name: 'taglibName', message: 'What is the name of your taglib or taglibs (, separated) ?', }, { name: 'appName', message: 'For which app (empty: global) ?' }, { type: 'confirm', name: 'moveon', message: 'Continue?' }]; //Ask inquirer.prompt(prompts, function (answers) { if (!answers.moveon) { return done(); } if (_.isBlank(answers.taglibName)) { chalk.error('Taglib name can NOT be empty'); done(); } answers.taglibName = _.clean(answers.taglibName); var appPath = path.join('./apps', answers.appName); var targetDir = _.isBlank(answers.appName) ? './apps/_global' : appPath; var createTagLib = require('./create-taglib'); if (answers.taglibName.match(/,/)) { var taglibs = answers.taglibName.split(',').map(function(taglib) { return _.clean(taglib); }); for (let taglib of taglibs) { answers = {taglibName: taglib, appName: answers.appName}; createTagLib(answers, targetDir); } } else { createTagLib(answers, targetDir); } } ); }; };
'use strict'; var _ = require('lodash'); var Q = require('q'); var util = require('util'); var should = require('./utils/should'); var descriptors = require('./utils/descriptors'); var Attribute = require('./attribute'); var AssertionResult = require('./assertion-result'); var PropertyAssertion = require('./assertions/property-assertion'); var StateAssertion = require('./assertions/state-assertion'); var tinto = {}; tinto.Entity = function Entity() { this._properties = {}; this._states = {}; /** * @name tinto.Entity#should * @type {tinto.Assertion} */ /** * @name tinto.Entity#should * @function * @param {...tinto.Assertion} assertions */ Object.defineProperty(this, 'should', { get: should }); }; /** * @param {string} state * @returns {function() : Promise.<tinto.AssertionResult>} */ tinto.Entity.prototype.is = function(state) { var self = this; if (!this._states[state]) { throw new Error(util.format('Unsupported state "%s"', state)); } return function() { return self._states[state].call(self).then(function(result) { return new AssertionResult(result); }); }; }; /** * @param {string} property * @param {*} expected * @returns {function() : Promise.<tinto.AssertionResult>} */ tinto.Entity.prototype.has = function(property, expected) { if (typeof property === 'number') { return hasCount.call(this, expected, property); } else { return hasValue.call(this, property, expected); } }; /** * @param {string} name * @param {function} [matcher] * @param {Array.<*>} [args] */ tinto.Entity.prototype.state = function(name, matcher, args) { this._states[name] = wrap(matcher, args); StateAssertion.register(name); }; /** * @param {Object.<string, function>} mappings */ tinto.Entity.prototype.states = function() { processMappings.call(this, 'state', arguments); }; /** * @param {string} name * @param {function} [matcher] * @param {Array.<*>} [args] */ tinto.Entity.prototype.property = function(name, matcher, args) { this._properties[name] = wrap(matcher, args); PropertyAssertion.register(name); this.getter(name, function() { return new Attribute(this, name, matcher.call(this)); }); }; /** * @param {Object.<string, function>} mappings */ tinto.Entity.prototype.properties = function() { processMappings.call(this, 'property', arguments); }; /** * @param {string} prop * @param {function()} func */ tinto.Entity.prototype.getter = function(prop, func) { Object.defineProperty(this, prop, { get: func, enumerable: true, configurable: true }); }; /** * @param {Object} props */ tinto.Entity.prototype.getters = function(props) { _.forIn(descriptors(props), function(descriptor, prop) { if (descriptor.enumerable) { if (descriptor.get) { this.getter(prop, descriptor.get); } else if (descriptor.value && typeof descriptor.value === 'function') { this.getter(prop, descriptor.value); } } }, this); }; /** * @private * @param {function()} matcher * @param {Array.<*>} args * @returns {Function} */ function wrap(matcher, args) { return function() { return Q.when(args ? matcher.apply(this, args) : matcher.call(this)); }; } /** * @private * @param {string} property * @param {*} value * @returns {function() : Promise.<tinto.AssertionResult>} */ function hasValue(property, value) { var self = this; if (!this._properties[property]) { throw new Error(util.format('Unsupported property "%s"', property)); } return function() { return self._properties[property].call(self).then(function(actual) { return new AssertionResult(_.isEqual(value, actual), value, actual); }); }; } /** * @private * @param {string} property * @param {Number} count * @returns {function() : Promise.<tinto.AssertionResult>} */ function hasCount(property, count) { var collection = this[property]; if (collection.count === undefined || typeof collection.count !== 'function') { throw new Error('Count assertions can only be applied to collections'); } return function() { return Q.resolve(collection.count()).then(function(length) { return new AssertionResult(count === length, count, length); }); }; } /** * @private * @param {string} type * @param {Array.<string|Object>} mappings */ function processMappings(type, mappings) { var self = this; mappings = Array.prototype.slice.call(mappings, 0); mappings.forEach(function(mapping) { if (typeof mapping === 'string') { self[type](mapping); } else { _.forEach(mapping, function(matcher, name) { self[type](name, matcher); }, self); } }); } module.exports = tinto.Entity;
import React from 'react' import MediaSummary from './MediaSummary' import { Button } from 'semantic-ui-react' import './mediaverticallist.css' export default class MediaVerticalList extends React.Component { render () { var arr = this.props.data if (arr === undefined) { arr = [] } var mediaNodes = arr.map((media, idx) => { return ( <MediaSummary key={media.id + '-' + idx} logo_url={media.logo_url} /> ) }) return ( <div> <h3 className='text-centered'>{this.props.title}</h3> {mediaNodes} <Button fluid size='huge'>3 Media Lainnya</Button> </div> ) } }
/* global window beforeEach jasmine it xit fit */ if (typeof global === 'undefined') { global = window; // eslint-disable-line } const customMatchers = { toAlmostEqual: (util, customEqualityTesters) => ({ compare: (actual, expected) => { const cleanActual = actual .trim() .replace(/\n/g, '') .replace(/\s+/g, ' '); // remove extra whitespace const cleanExpected = expected .trim() .replace(/\n/g, '') .replace(/\s+/g, ' '); // remove extra whitespace return { pass: util.equals(cleanActual, cleanExpected, customEqualityTesters), }; }, }), }; beforeEach(() => { jasmine.addMatchers(customMatchers); }); function addDataTableSupport() { function executeTest(name, fn, entries, override) { entries.forEach((entry) => { const itName = `${name} ${entry.name}`; const itFn = () => fn(...entry.params); (override || entry.proxy)(itName, itFn); }); } global.entry = (name, ...params) => { const result = { name, params, proxy: it, }; return result; }; global.fentry = (name, ...params) => { const result = { name, params, proxy: fit, }; return result; }; global.xentry = (name, ...params) => { const result = { name, params, proxy: xit, }; return result; }; global.describeTable = (name, fn, ...entries) => { executeTest(name, fn, entries); }; global.fdescribeTable = (name, fn, ...entries) => { executeTest(name, fn, entries, fit); }; global.xdescribeTable = (name, fn, ...entries) => { executeTest(name, fn, entries, xit); }; } addDataTableSupport();
/** * Created by Wayne on 16/3/16. */ 'use strict'; var tender = require('../controllers/tender'), cardContr = require('../controllers/card'), cardFilter = require('../../../libraries/filters/card'), truckFileter = require('../../../libraries/filters/truck'), driverFilter = require('../../../libraries/filters/driver'); module.exports = function (app) { // app.route('/tender/wechat2/details').get(driverFilter.requi, cardContr.create); // app.route('/tender/driver/card/bindTruck').post(driverFilter.requireDriver, cardFilter.requireById, truckFileter.requireById, cardContr.bindTruck); };
/** * The main purpose of this in my mind is for navigation * this way when this route is entered either via direct url * or by a link-to etc you send a ping so that nav can be updated * in the hierarchy. * * curious about feedback. I have used something similar in practice * but it's mainly for keeping the ui correct and things like that * without tightly coupling things together or at least that is my * hope. */ export default Ember.Route.extend({ beforeModel: function(trans) { trans.send('ping', this.routeName); } });
import React, { PropTypes } from 'react'; import { Provider } from 'react-redux'; import Routers from './Routers'; /** * Component is exported for conditional usage in Root.js */ const Root = ({ store }) => ( /** * Provider is a component provided to us by the 'react-redux' bindings that * wraps our app - thus making the Redux store/state available to our 'connect()' * calls in component hierarchy below. */ <Provider store={store}> <div> {Routers} </div> </Provider> ); Root.propTypes = { store: PropTypes.object.isRequired // eslint-disable-line react/forbid-prop-types }; module.exports = Root;
import actions from './shortcuts'; class MockClientStore { update(cb) { this.updateCallback = cb; } } describe('manager.shortcuts.actions.shortcuts', () => { describe('setOptions', () => { test('should update options', () => { const clientStore = new MockClientStore(); actions.setOptions({ clientStore }, { abc: 10 }); const state = { shortcutOptions: { bbc: 50, abc: 40 }, }; const stateUpdates = clientStore.updateCallback(state); expect(stateUpdates).toEqual({ shortcutOptions: { bbc: 50, abc: 10 }, }); }); test('should only update options for the key already defined', () => { const clientStore = new MockClientStore(); actions.setOptions({ clientStore }, { abc: 10, kki: 50 }); const state = { shortcutOptions: { bbc: 50, abc: 40 }, }; const stateUpdates = clientStore.updateCallback(state); expect(stateUpdates).toEqual({ shortcutOptions: { bbc: 50, abc: 10 }, }); }); test('should warn about deprecated option names', () => { const clientStore = new MockClientStore(); const spy = jest.spyOn(console, 'warn').mockImplementation(() => {}); actions.setOptions( { clientStore }, { showLeftPanel: 1, showDownPanel: 2, downPanelInRight: 3, } ); const state = { shortcutOptions: {}, }; const stateUpdates = clientStore.updateCallback(state); expect(spy).toHaveBeenCalledTimes(3); expect(stateUpdates).toEqual({ shortcutOptions: { showStoriesPanel: 1, showAddonPanel: 2, addonPanelInRight: 3, }, }); spy.mockReset(); spy.mockRestore(); }); }); });
ScalaJS.impls.scala_PartialFunction$class__orElse__Lscala_PartialFunction__Lscala_PartialFunction__Lscala_PartialFunction = (function($$this, that) { return new ScalaJS.c.scala_PartialFunction$OrElse().init___Lscala_PartialFunction__Lscala_PartialFunction($$this, that) }); ScalaJS.impls.scala_PartialFunction$class__andThen__Lscala_PartialFunction__Lscala_Function1__Lscala_PartialFunction = (function($$this, k) { return new ScalaJS.c.scala_PartialFunction$AndThen().init___Lscala_PartialFunction__Lscala_Function1($$this, k) }); ScalaJS.impls.scala_PartialFunction$class__lift__Lscala_PartialFunction__Lscala_Function1 = (function($$this) { return new ScalaJS.c.scala_PartialFunction$Lifted().init___Lscala_PartialFunction($$this) }); ScalaJS.impls.scala_PartialFunction$class__applyOrElse__Lscala_PartialFunction__O__Lscala_Function1__O = (function($$this, x, default$2) { if ($$this.isDefinedAt__O__Z(x)) { return $$this.apply__O__O(x) } else { return default$2.apply__O__O(x) } }); ScalaJS.impls.scala_PartialFunction$class__runWith__Lscala_PartialFunction__Lscala_Function1__Lscala_Function1 = (function($$this, action) { return new ScalaJS.c.scala_scalajs_runtime_AnonFunction1().init___Lscala_scalajs_js_Function1((function(arg$outer, action$1) { return (function(x) { var z = arg$outer.applyOrElse__O__Lscala_Function1__O(x, ScalaJS.modules.scala_PartialFunction().scala$PartialFunction$$checkFallback__Lscala_PartialFunction()); if ((!ScalaJS.modules.scala_PartialFunction().scala$PartialFunction$$fallbackOccurred__O__Z(z))) { action$1.apply__O__O(z); var jsx$1 = true } else { var jsx$1 = false }; return ScalaJS.bZ(jsx$1) }) })($$this, action)) }); ScalaJS.impls.scala_PartialFunction$class__$init$__Lscala_PartialFunction__V = (function($$this) { /*<skip>*/ }); //@ sourceMappingURL=PartialFunction$class.js.map
function autonomous_start() { autonomousStartTime = gameVideo.currentTime; initializeEvents(); }
(function () { 'use strict'; angular .module("myApp.presents") .factory("dataGiftService", dataGiftService); function dataGiftService($mdToast, $mdDialog) { var dataGiftService = { notification: notification, pleaseWaitDialog: pleaseWaitDialog }; function notification(status, msg, time) { if (angular.isUndefined(time)) time = 3000; $mdToast.show( $mdToast.simple() .textContent(msg) .position("top right") .hideDelay(time) .theme(status) ); } function pleaseWaitDialog(msg, parentEl) { if (angular.isUndefined(parentEl)) { parentEl = angular.element(document.body); } $mdDialog.show({ parent: parentEl, template: '<md-dialog class="wait-dialog" aria-label="Please wait">' + ' <md-dialog-content layout="column" layour-align="center center">' + '<h1 class="text-center">Proszę czekać</h1>' + '<md-content class="text-center">' + msg + '</md-content>'+ ' </md-dialog-content>' + '</md-dialog>' }); } return dataGiftService; } })();
module.exports = ` type SimpleBudgetDetail { account_type: String, account_name: String, fund_name: String, department_name: String, division_name: String, costcenter_name: String, function_name: String, charcode_name: String, organization_name: String, category_name: String, budget_section_name: String, object_name: String, year: Int, budget: Float, actual: Float, full_account_id: String, org_id: String, obj_id: String, fund_id: String, dept_id: String, div_id: String, cost_id: String, func_id: String, charcode: String, category_id: String, budget_section_id: String, proj_id: String, is_proposed: String use_actual: String } type SimpleBudgetSummary { account_type: String, category_name: String, year: Int, total_budget: Float, total_actual: Float use_actual: String } type BudgetCashFlow { account_type: String, category_name: String, category_id: String, dept_id: String, department_name: String, fund_id: String, fund_name: String, budget: Float, year: Int } type BudgetParameters { start_year: Int end_year: Int in_budget_season: Boolean } `;
module.exports = client => { console.log(`Reconnecting... [at ${new Date()}]`); };
ig.module( 'game.entities.abstract.friendly-unit' ).requires( 'game.entities.abstract.unit' ).defines(function () { FriendlyUnit = Unit.extend({ // Nothing yet! }); });
/** * Ajax函数 */ // 创建一个XMLHttpRequest对象 var createXHR; if (window.XMLHttpRequest) { createXHR = function() { return new XMLHttpRequest(); }; } else if (window.ActiveXObject) { createXHR = function() { return new ActiveXObject('Microsoft.XMLHTTP'); }; } // 发起异步请求,默认为GET请求 function ajax(url, opts) { var type = opts.type || 'get', async = opts.async || true, data = opts.data || null, headers = opts.headers || {}; var xhr = createXHR(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { opts.onsuccess && opts.onsuccess(xhr.responseText); } else { opts.onerror && opts.onerror(); } }; xhr.open(url, type, async); for (var p in headers) { xhr.setRequestHeader(p, headers[p]); } xhr.send(data); }
import { addTimer } from './timer/timer'; import { showProfile } from './profile/profile'; import { showHelp } from './help/help'; import { getAllUsers } from './timer/listUtil/getAllUsers'; import { isWorking } from './timer/listUtil/isWorking'; import { timerTimeout } from './timer/listUtil/timerTimeout'; import { refreshPoints } from './timer/listUtil/refreshPoints'; import { minusStackCalculate } from './timer/listUtil/minusStackCalculate'; import { updUsrList } from './timer/listUtil/updUsrList'; const emojiMap = { '⏺': addTimer, '👤': showProfile, '❓': showHelp }; async function menuGUI(res, bot) { const channel = bot.channel; const timerList = {}; let userList = await getAllUsers(); // eslint-disable-line const menuMsg = await channel.send('', { embed: { description: '`⏺ Start Recording! | 👤 Your Profile | ❓ Need help?`' }, }); // add reactions to message for (const emoji in emojiMap) { await menuMsg.react(emoji); } await channel.send('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬'); await menuMsg.createReactionCollector(async (reaction, user) => { if (user.bot) return false; // run the emoji command logic and remove the reaction if (emojiMap[reaction.emoji.name]) { emojiMap[reaction.emoji.name](bot, user, timerList); } await reaction.remove(user); return false; }); res(); setInterval(() => { timerTimeout(bot, timerList); }, 60000); setInterval(async () => { refreshPoints(timerList); isWorking(userList, timerList); minusStackCalculate(); updUsrList(userList); }, 60000); } module.exports = { init: (bot) => { return new Promise((res) => { menuGUI(res, bot); }); }, };
/** * Created by:homelan * User: pijiu3302@outlook.com * Date: 2017/7/31 * Time: 17:38 * */ import React from 'react'; import icons from '../utils/parseIcon'; import {connect} from 'react-redux'; import {lockPlayer} from '../store/action/actionindex'; class LockBar extends React.Component { render() { const {handleClick}=this.props; let styleObj1={}; styleObj1.background='url('+icons.playbar+')'; return ( <div className="updn" > <div className='lock-bg' style={styleObj1}> <a className={this.props.locked?'btn':'btn-unlock'} style={styleObj1} onClick={e=>handleClick(e)}></a> </div> <div className="lock-bg2" style={styleObj1} ></div> </div> ) } } const mapStateToProps=(state)=>{ return {locked:state.locked} } const mapDispatchToProps=(dispatch)=> { return { handleClick: (e) => { dispatch(lockPlayer()) e.preventDefault(); e.stopPropagation() } } }; export default connect(mapStateToProps,mapDispatchToProps)(LockBar);//important /*function mapDispatchToProps(dispatch) { return { handleClick: () => dispatch(lockPlayer()) }; } connect( mapDispatchToProps )(LockBar); */
var express = require('express'); var app = module.exports = express(); var api = require('lib/db-api'); var config = require('lib/config'); var path = require('path'); var url = require('url'); var resolve = path.resolve; var strip = require('strip'); var log = require('debug')('democracyos:facebook-card'); app.get('/topic/:id', function(req, res, next){ log('Facebook Request /topic/%s', req.params.id); api.topic.get(req.params.id, function (err, topicDoc) { if (err) return _handleError(err, req, res); log('Serving Facebook topic %s', topicDoc.id); var baseUrl = url.format({ protocol: config.protocol , hostname: config.host , port: config.publicPort }); res.render(resolve(__dirname, 'topic.jade'), { topic: topicDoc, baseUrl : baseUrl, config : config, strip: strip }); }); }) app.get('*', function(req, res, next){ log('Facebook Request generic page'); var baseUrl = url.format({ protocol: config.protocol , hostname: config.host , port: config.publicPort }); res.render(resolve(__dirname, 'generic.jade'), { baseUrl : baseUrl, config : config}); })
import Html from "./Html"; import { YatinSelectMin, YatinSelectMax } from "../parts/YatinSelect"; export default class YatinSection extends Html { constructor(min="", max="") { super(); var $yatinSection = $(` <section class="yatin-section"> <h2>¥家賃</h2> <div class="center"></div> </section> `); var selectMin = new YatinSelectMin(min); var selectMax = new YatinSelectMax(max); $yatinSection.find(".center").append( selectMin.getHtml() ); $yatinSection.find(".center").append( $(`<div class="kara">〜</div>`) ); $yatinSection.find(".center").append( selectMax.getHtml() ); this.$html = $yatinSection } }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsShallowCompare = require('react-addons-shallow-compare'); var _reactAddonsShallowCompare2 = _interopRequireDefault(_reactAddonsShallowCompare); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _NodeCaret = require('./NodeCaret'); var _NodeCaret2 = _interopRequireDefault(_NodeCaret); var _styles = require('./styles'); var _styles2 = _interopRequireDefault(_styles); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var isDirectory = function isDirectory(type) { return type === 'directory'; }; var Node = function (_Component) { _inherits(Node, _Component); function Node() { _classCallCheck(this, Node); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Node).call(this)); _this.state = {}; return _this; } // shouldComponentUpdate(nextProps, nextState, nextContext) { // const shouldUpdate = shallowCompare(this, nextProps, nextState) // // // console.log('update', shouldUpdate, nextProps.node.path) // // return shouldUpdate // } _createClass(Node, [{ key: 'render', value: function render() { var _this2 = this; var _props = this.props; var node = _props.node; var metadata = _props.metadata; var depth = _props.depth; var type = node.type; var name = node.name; var path = node.path; var expanded = metadata.expanded; var selected = metadata.selected; var hover = this.state.hover; return _react2.default.createElement( 'div', { style: (0, _styles.getPaddedStyle)(depth, selected, hover), onMouseEnter: function onMouseEnter() { return _this2.setState({ hover: true }); }, onMouseLeave: function onMouseLeave() { return _this2.setState({ hover: false }); } }, isDirectory(type) && _react2.default.createElement(_NodeCaret2.default, { expanded: expanded }), _react2.default.createElement( 'div', { style: _styles2.default.nodeText }, name ) ); } }]); return Node; }(_react.Component); exports.default = Node;
var game = new Phaser.Game(375, 667, Phaser.AUTO, 'gameDiv'); // var game = new Phaser.Game(720, 1280, Phaser.AUTO, 'gameDiv'); game.global = { taps: 0, enemyHP: 0, enemyHPTotal: 0, level: 1, enemyNumber: 1, coins: 0, player: { name: 'mr. hero', level: 1, skillLevel: [0, 0, 0, 0, 0, 0] } }; game.state.add('boot', bootState); game.state.add('load', loadState); game.state.add('menu', menuState); game.state.add('play', playState); game.state.start('boot');
/** * Default model configuration * (sails.config.models) * * Unless you override them, the following properties will be included * in each of your models. * * For more info on Sails models, see: * http://sailsjs.org/#!/documentation/concepts/ORM */ module.exports.models = { /*************************************************************************** * * * Your app's default connection. i.e. the name of one of your app's * * connections (see `config/connections.js`) * * * ***************************************************************************/ // connection: 'localDiskDb', /*************************************************************************** * * * How and whether Sails will attempt to automatically rebuild the * * tables/collections/etc. in your schema. * * * * See http://sailsjs.org/#!/documentation/concepts/ORM/model-settings.html * * * ***************************************************************************/ migrate: 'safe', schema: true, /** * This method adds records to the database * * To use add a variable 'seedData' in your model and call the * method in the bootstrap.js file */ seed: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); if (!self.seedData) { sails.log.debug('No data avaliable to seed ' + modelName); callback(); return; } self.count().exec(function (err, count) { if (!err && count === 0) { sails.log.debug('Seeding ' + modelName + '...'); if (self.seedData instanceof Array) { self.seedArray(callback); }else{ self.seedObject(callback); } } else { sails.log.debug(modelName + ' had models, so no seed needed'); callback(); } }); }, seedArray: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.createEach(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); }, seedObject: function (callback) { var self = this; var modelName = self.adapter.identity.charAt(0).toUpperCase() + self.adapter.identity.slice(1); self.create(self.seedData).exec(function (err, results) { if (err) { sails.log.debug(err); callback(); } else { sails.log.debug(modelName + ' seed planted'); callback(); } }); } };
'use strict'; const mongoose = require('mongoose-q')(require('mongoose')); const League = mongoose.model('League'); function LeagueHandler (leagueService) { this.service = leagueService; } LeagueHandler.prototype.getLeaguesByCountry = function(req, res, next) { return this.service.getByCountry(req.params.country) .then(function(countryLeagues) { return res.status(200).send(countryLeagues) }) .catch(function(err) { next(err) }) }; module.exports = LeagueHandler;
app.controller('JoinGameController', function ($scope, $location, authorization, identity, ticTacToeData, notifier) { 'use strict'; $scope.joinGame = function (gameId) { if (identity.isAuthenticated() === true) { ticTacToeData.joinGame(authorization.getAuthorizationHeader(), gameId) .then(function () { notifier.success('Game joined!'); }, function () { notifier.error('Invalid data!'); }); } else { notifier.error('Please login!'); } }; $scope.joinRandomGame = function () { if (identity.isAuthenticated() === true) { ticTacToeData.joinRandomGame(authorization.getAuthorizationHeader()) .then(function () { notifier.success('Game joined!'); }); } else { notifier.error('Please login!'); } } });
'use strict'; function Level(args) { if(!(this instanceof Level)) return new Level(args); this.context = args.context; this.player = args.player; this.gameplayObjects = args.gameplayObjects; this.outcomeListeners = []; this.finalMessageListeners = []; this.respawnInfoListeners = []; this.victoryMessages = args.victoryMessages; this.failureMessages = args.failureMessages; this.isPaused = true; this.isFinished = false; this.handleRespawnInfo(args.respawnInfo); this.player.setParentLevel(this); this.gameplayObjects.forEach(o => o.beginObservingPlayer(this.player)); } Level.prototype.draw = function() { this.context.clearRect(0, 0, this.context.canvas.width, this.context.canvas.height); this.gameplayObjects.forEach(o => o.draw(this.context)); this.player.draw(this.context); } Level.prototype.update = function(dt) { this.player.update(dt); } Level.prototype.frame = function(dt) { this.update(dt); this.draw(); } Level.prototype.startGameLoop = function() { const gameLoopFrame = now => { if(!this.isPaused) { const dt = now - this.lastFrameTime; this.frame(dt); window.requestAnimationFrame(gameLoopFrame); } this.lastFrameTime = now; } this.isPaused = false; this.lastFrameTime = performance.now(); window.requestAnimationFrame(gameLoopFrame); } Level.prototype.pauseGameLoop = function() { this.isPaused = true; } Level.prototype.addOutcomeListener = function(listener) { this.outcomeListeners.push(listener); } Level.prototype.addFinalMessageListener = function(listener) { this.finalMessageListeners.push(listener); } Level.prototype.addRespawnInfoListener = function(listener) { this.respawnInfoListeners.push(listener); } Level.prototype.generateRespawnInfo = function() { return this.player.generateRespawnInfo(); } Level.prototype.handleRespawnInfo = function(respawnInfo) { this.player.handleRespawnInfo(respawnInfo); } Level.prototype.win = function() { this.finishWithOutcome(true); } Level.prototype.lose = function() { this.finishWithOutcome(false); } Level.prototype.finishWithOutcome = function(outcome) { if(this.isFinished) return; this.isFinished = true; this.pauseGameLoop(); this.player.stop(); this.outcomeListeners.forEach(listener => listener(outcome)); const finalMessage = this.getMessageForOutcome(outcome); this.finalMessageListeners.forEach(listener => listener(finalMessage)); if(!outcome) { const respawnInfo = this.generateRespawnInfo(); Object.freeze(respawnInfo); this.respawnInfoListeners.forEach(listener => listener(respawnInfo)); } } Level.prototype.getMessageForOutcome = function(outcome) { if(outcome) return mathUtils.randomArrayElement(this.victoryMessages); else return mathUtils.randomArrayElement(this.failureMessages); }
require("./18.js"); require("./37.js"); require("./74.js"); require("./147.js"); module.exports = 148;
var Leap = require("leapjs"); var keyboard = require('node_keyboard'); //Each var individually declared below so they refence different objects in memory. I.e work independantly. //These vars log when a particular action / gesture last ran. var last_fav = new Date().getTime(); var last_swipe = new Date().getTime(); var last_up = new Date().getTime(); var last_down = new Date().getTime(); var current_time; var delay = 1000; //Number of milliseconds forced between each gesture. var controller = Leap.loop({enableGestures: true}, function(frame){ if(frame.valid && frame.gestures.length > 0){ frame.gestures.forEach(function(gesture){ switch (gesture.type){ case "circle": current_time = new Date().getTime(); if(last_fav+delay < current_time){ keyboard.press(keyboard.Key_Numpad0); keyboard.release(keyboard.Key_Numpad0); console.log("Circle Gesture"); last_fav = new Date().getTime(); } break; case "swipe": current_time = new Date().getTime(); if(last_swipe+delay < current_time){ //Classify swipe as either horizontal or vertical var isHorizontal = Math.abs(gesture.direction[0]) > Math.abs(gesture.direction[1]); //Classify as right-left or up-down if(isHorizontal){ if(gesture.direction[0] > 0){ swipeDirection = "Swipe Right"; keyboard.press(keyboard.Key_Up); //Key_Up keycode and Key_Right keycode are swapped in node_keyboard dependancy keyboard.release(keyboard.Key_Up);//Key_Up keycode and Key_Right keycode are swapped in node_keyboard dependancy } else { swipeDirection = "Swipe Left"; keyboard.press(keyboard.Key_Left); keyboard.release(keyboard.Key_Left); } } else { //vertical if(gesture.direction[1] > 0){ swipeDirection = "Swipe Up"; } else { swipeDirection = "Swipe Down"; } } console.log(swipeDirection); last_swipe = new Date().getTime(); } break; } }); } if(frame.pointables.length == 5){ var pointable = frame.pointables; current_time = new Date().getTime(); if(last_up+delay < current_time){ if(pointable[0].direction[1] > 0.78 && pointable[1].direction[1] > 0.78 && pointable[2].direction[1] > 0.78 && pointable[3].direction[1] > 0.78 && pointable[4].direction[1] > 0.78 ){ console.log("Up Vote"); keyboard.press(keyboard.Key_NumpadAdd); keyboard.release(keyboard.Key_NumpadAdd); last_up = new Date().getTime(); } } if(last_down+delay < current_time){ if(pointable[0].direction[1] < -0.78 && pointable[1].direction[1] < -0.78 && pointable[2].direction[1] < -0.78 && pointable[3].direction[1] < -0.78 && pointable[4].direction[1] < -0.78 ){ console.log("Down Vote"); keyboard.press(keyboard.Key_NumpadSubtract); keyboard.release(keyboard.Key_NumpadSubtract); last_down = new Date().getTime(); } } } }); console.log('Leap Imgur Controller Running');
// eslint-disable-next-line function getCookie(cname) { const name = `${cname}=`; const ca = document.cookie.split(';'); for (let i = 0; i < ca.length; i += 1) { let c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1); if (c.indexOf(name) !== -1) return c.substring(name.length, c.length); } return ''; }
/* * Kendo UI v2015.1.408 (http://www.telerik.com/kendo-ui) * Copyright 2015 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial license terms. */ (function(f, define){ define([], f); })(function(){ (function( window, undefined ) { var kendo = window.kendo || (window.kendo = { cultures: {} }); kendo.cultures["kok"] = { name: "kok", numberFormat: { pattern: ["-n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], percent: { pattern: ["-n %","n %"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], symbol: "%" }, currency: { pattern: ["$ -n","$ n"], decimals: 2, ",": ",", ".": ".", groupSize: [3,2], symbol: "₹" } }, calendars: { standard: { days: { names: ["आयतार","सोमार","मंगळार","बुधवार","बिरेस्तार","सुक्रार","शेनवार"], namesAbbr: ["आय.","सोम.","मंगळ.","बुध.","बिरे.","सुक्र.","शेन."], namesShort: ["आ","स","म","ब","ब","स","श"] }, months: { names: ["जानेवारी","फेब्रुवारी","मार्च","एप्रिल","मे","जून","जुलै","ऑगस्ट","सप्टेंबर","ऑक्टोबर","नोवेम्बर","डिसेंबर"], namesAbbr: ["जाने","फेब्रु","मार्च","एप्रिल","मे","जून","जुलै","ऑग.","सप्टें.","ऑक्टो.","नोवे.","डिसें"] }, AM: ["म.पू.","म.पू.","म.पू."], PM: ["म.नं.","म.नं.","म.नं."], patterns: { d: "dd-MM-yyyy", D: "dd MMMM yyyy", F: "dd MMMM yyyy HH:mm:ss", g: "dd-MM-yyyy HH:mm", G: "dd-MM-yyyy HH:mm:ss", m: "dd MMMM", M: "dd MMMM", s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss", t: "HH:mm", T: "HH:mm:ss", u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", y: "MMMM, yyyy", Y: "MMMM, yyyy" }, "/": "-", ":": ":", firstDay: 1 } } } })(this); return window.kendo; }, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
function solve(args) { const module = 1024; let numbers = args.slice(1).map(Number), current, result = 0, i = 0; while (true) { if (i === 0) { current = numbers[i]; if (numbers.length === 1) { result = current; break; } i++; } if (numbers[i] % 2 === 0 || numbers[i] === 0) { current += numbers[i]; current = current % module; i += 2; if (i > numbers.length - 1) { result = current; break; } } else if (numbers[i] % 2 !== 0 || numbers[i] === 1) { current *= numbers[i]; current = current % module; i++; if (i > numbers.length - 1) { result = current; break; } } } console.log(result); } // tests solve([ '10', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' ]); console.log('------------'); solve([ '9', '9', '9', '9', '9', '9', '9', '9', '9', '9' ]); solve(['2', '2', '2', '2', '2', '2', '2', '2', '2']);
/** * Created by chenqx on 8/5/15. * @hack 添加三角形绘制提交方式 */ /** * 以四边形填充 * @constant * @type {number} */ qc.BATCH_QUAD = 0; /** * 以三角形填充 * @constant * @type {number} */ qc.BATCH_TRIANGLES = 1; var oldWebGLSpriteBatchSetContext = PIXI.WebGLSpriteBatch.prototype.setContext; PIXI.WebGLSpriteBatch.prototype.setContext = function(gl) { oldWebGLSpriteBatchSetContext.call(this, gl); this.quadSize = this.size; this.triangleSize = 300; this.batchIndexNumber = 6; var triangleIndicesNum = this.triangleSize * 3; this.triangleIndices = new PIXI.Uint16Array(triangleIndicesNum); for (var i = 0; i < triangleIndicesNum; ++i) { this.triangleIndices[i] = i; } this._batchType = qc.BATCH_QUAD; this.quadIndexBuffer = this.indexBuffer; this.triangleIndexBuffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.triangleIndexBuffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.triangleIndices, gl.STATIC_DRAW); }; var oldWebGLSpriteBatchDestroy = PIXI.WebGLSpriteBatch.prototype.destroy; PIXI.WebGLSpriteBatch.prototype.destroy = function() { this.triangleIndices = null; this.gl.deleteBuffer(this.triangleIndexBuffer); oldWebGLSpriteBatchDestroy.call(this); } Object.defineProperties(PIXI.WebGLSpriteBatch.prototype,{ batchType : { get : function() { return this._batchType; }, set : function(v) { if (v === this._batchType) { return; } this.stop(); // 切换IndexBuffer,Size if (v === qc.BATCH_TRIANGLES) { this.size = this.triangleSize; this.indexBuffer = this.triangleIndexBuffer; this._batchType = v; this.batchIndexNumber = 3; } else { this.size = this.quadSize; this.indexBuffer = this.quadIndexBuffer; this._batchType = v; this.batchIndexNumber = 6; } this.start(); } } }); /** * @method renderBatch * @param texture {Texture} * @param size {Number} * @param startIndex {Number} */ PIXI.WebGLSpriteBatch.prototype.renderBatch = function(texture, size, startIndex) { if(size === 0)return; var gl = this.gl; // check if a texture is dirty.. if(texture._dirty[gl.id]) { this.renderSession.renderer.updateTexture(texture); } else { // bind the current texture gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]); } //gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.batchIndexNumber === 3 ? this.triangleIndexBuffer : this.indexBuffer); // now draw those suckas! gl.drawElements(gl.TRIANGLES, size * this.batchIndexNumber, gl.UNSIGNED_SHORT, startIndex * this.batchIndexNumber * 2); // increment the draw count this.renderSession.drawCount++; };
#!/usr/bin/env node // Fires up a console with Valid loaded. // Allows you to quickly play with Valid on the console. Valid = require('./lib/valid'); require('repl').start();
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M4 18h11c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zm0-5h8c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zM3 7c0 .55.45 1 1 1h11c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1zm17.3 7.88L17.42 12l2.88-2.88c.39-.39.39-1.02 0-1.41a.9959.9959 0 00-1.41 0L15.3 11.3c-.39.39-.39 1.02 0 1.41l3.59 3.59c.39.39 1.02.39 1.41 0 .38-.39.39-1.03 0-1.42z" /> , 'MenuOpenRounded');
'use strict'; describe('Service: awesomeThings', function() { // load the service's module beforeEach(module('initApp')); // instantiate service var awesomeThings; beforeEach(inject(function(_awesomeThings_) { awesomeThings = _awesomeThings_; })); it('should return all the awesomeThings at the static list', function() { expect(awesomeThings.getAll().length).toBe(4); }); it('should return an specific awesome thing', function() { // We can test the object itself here. Not doing for simplicity expect(awesomeThings.get('2').name).toBe('AngularJS'); }); });
'use strict'; var matrix = require( 'dstructs-matrix' ), ekurtosis = require( './../lib' ); var k, mat, out, tmp, i; // ---- // Plain arrays... k = new Array( 10 ); for ( i = 0; i < k.length; i++ ) { k[ i ] = i; } out = ekurtosis( k ); console.log( 'Arrays: %s\n', out ); // ---- // Object arrays (accessors)... function getValue( d ) { return d.x; } for ( i = 0; i < k.length; i++ ) { k[ i ] = { 'x': k[ i ] }; } out = ekurtosis( k, { 'accessor': getValue }); console.log( 'Accessors: %s\n', out ); // ---- // Deep set arrays... for ( i = 0; i < k.length; i++ ) { k[ i ] = { 'x': [ i, k[ i ].x ] }; } out = ekurtosis( k, { 'path': 'x/1', 'sep': '/' }); console.log( 'Deepset:'); console.dir( out ); console.log( '\n' ); // ---- // Typed arrays... k = new Float64Array( 10 ); for ( i = 0; i < k.length; i++ ) { k[ i ] = i; } tmp = ekurtosis( k ); out = ''; for ( i = 0; i < k.length; i++ ) { out += tmp[ i ]; if ( i < k.length-1 ) { out += ','; } } console.log( 'Typed arrays: %s\n', out ); // ---- // Matrices... mat = matrix( k, [5,2], 'float64' ); out = ekurtosis( mat ); console.log( 'Matrix: %s\n', out.toString() ); // ---- // Matrices (custom output data type)... out = ekurtosis( mat, { 'dtype': 'uint8' }); console.log( 'Matrix (%s): %s\n', out.dtype, out.toString() );
/* public/core.js */ var angTodo = angular.module('angTodo', []); function mainController($scope, $http) { $scope.formData = {}; /* when landing on the page, get all todos and show them */ $http.get('/api/todos') .success(function(data) { $scope.todos = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); /* when submitting the add form, send the text to the node API */ $scope.createTodo = function() { $http.post('/api/todos', $scope.formData) .success(function(data) { $scope.formData = {}; // clear the form so another todo can be entered $scope.todos = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); }; /* delete a todo after checking it */ $scope.deleteTodo = function(id) { $http.delete('/api/todos/' + id) .success(function(data) { $scope.todos = data; console.log(data); }) .error(function(data) { console.log('Error: ' + data); }); }; } /* function mainController */
define([], function() { return function($translateProvider) { $translateProvider.translations('en', { WELCOME_TO_PIO: 'Welcome to PIO', SIGN_IN: 'Sign in', SIGN_UP: 'Sign up', SIGN_OUT: 'Sign out', FORGOT_PASSWORD: 'Forgot password?', DO_NOT_HAVE_AN_ACCOUNT: 'Do not have an account?', CREATE_AN_ACCOUNT: 'Create an account', POLLS: 'Polls', ADMINISTRATION: 'Administration', TITLE: 'Title', USERS: 'Users', CREATE: 'Create', DASHBOARD: 'Dashboard', DETAILS: 'Details', DETAIL: 'Detail', CREATE_POLL: 'Create poll', CREATE_USER: 'Create user', POLL_DETAILS: 'Poll details', USER_DETAILS: 'User details', TAGS: 'Tags', SUMMARY: 'Summary', STATUS: 'Status', NAME: 'Name', AVATAR: 'Avatar', POLLINGS: 'Pollings', NOTES: 'Notes', EMAIL: 'Email', DATE: 'Date', SAVE: 'Save', CANCEL: 'Cancel' }); $translateProvider.translations('es', { WELCOME_TO_PIO: 'Bienvenido a PIO', SIGN_IN: 'Acceder', SIGN_UP: 'Registro', SIGN_OUT: 'Salir', FORGOT_PASSWORD: '¿Olvidó la contraseña?', DO_NOT_HAVE_AN_ACCOUNT: '¿No tiene una cuenta?', CREATE_AN_ACCOUNT: 'Crear un acuenta', POLLS: 'Encuestas', ADMINISTRATION: 'Administración', TITLE: 'Título', USERS: 'Usuarios', CREATE: 'Crear', DASHBOARD: 'Panel', DETAILS: 'Detalles', DETAIL: 'Detalle', CREATE_POLL: 'Crear encuesta', CREATE_USER: 'Crear usuario', POLL_DETAILS: 'Detalles de encuesta', USER_DETAILS: 'Detalles de usuario', TAGS: 'Etiquetas', SUMMARY: 'Resumen', STATUS: 'Estado', NAME: 'Nombre', AVATAR: 'Avatar', POLLINGS: 'Votaciones', NOTES: 'Notas', EMAIL: 'Correo', DATE: 'Fecha', SAVE: 'Guardar', CANCEL: 'Cancelar' }); $translateProvider.useSanitizeValueStrategy('escapeParameters'); $translateProvider.preferredLanguage('es'); }; });
{ document.getElementsByClassName('close')[0].addEventListener('click', function() { window.close(); }); }
'use strict'; angular.module('com.module.sandbox') .controller('DatepickerDemoCtrl', function ($scope) { $scope.today = function () { $scope.dt = new Date(); }; $scope.today(); $scope.clear = function () { $scope.dt = null; }; $scope.disabled = function (date, mode) { return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6)); }; $scope.toggleMin = function () { $scope.minDate = $scope.minDate ? null : new Date(); }; $scope.toggleMin(); $scope.open = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.formats = [ 'dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate' ]; $scope.format = $scope.formats[0]; });
import Ember from 'ember'; const { computed } = Ember; let IronSelector = Ember.Component.extend({ attributeBindings: [ 'selected', 'role', 'attrForSelected', 'multi' ], selectedItem: computed({ get() {}, set(key, value) { let items = this.get('items'); let idx = -1; if (items) { idx = this.get('items').indexOf(value); } if (this.getSelectedIndex() !== idx && idx !== -1) { this.set('selected', idx); } return value; } }), getSelectedIndex() { let el = this.element; if (el) { return typeof el.selected === 'number' ? el.selected : el.indexOf(el.selectedItem); } else { return -1; } }, didInsertElement() { this._super(...arguments); this.$().on('iron-select', () => { let el = this.element; let items = this.get('items'); if (items) { this.set('selectedItem', items[this.getSelectedIndex()]); } else { this.set('selectedItem', el.selected); } }); // initial selection let selectedItem = this.get('selectedItem'); if (selectedItem) { let items = this.get('items'); if (items) { this.element.select(selectedItem === 'number' ? selectedItem : items.indexOf(selectedItem)); } else { this.element.select(selectedItem === 'number' ? selectedItem : this.element.items.indexOf(selectedItem)); } } } }); IronSelector.reopenClass({ positionalParams: [ 'items' ] }); export default IronSelector;
var Component = new Brick.Component(); Component.requires = { mod: [ {name: '{C#MODNAME}', files: ['mail.js']} ] }; Component.entryPoint = function(NS){ var Y = Brick.YUI, COMPONENT = this, SYS = Brick.mod.sys; NS.MailTestWidget = Y.Base.create('MailTestWidget', SYS.AppWidget, [], { onInitAppWidget: function(err, appInstance, options){ }, destructor: function(){ this.hideResult(); }, sendTestMail: function(){ var tp = this.template, email = tp.getValue('email'); this.set('waiting', true); this.get('appInstance').mailTestSend(email, function(err, result){ this.set('waiting', false); if (!err){ this.showResult(result.mailTestSend); } }, this); }, showResult: function(mail){ var tp = this.template; tp.show('resultPanel'); this._resultMailWidget = new NS.MailViewWidget({ srcNode: tp.append('resultMail', '<div></div>'), mail: mail }); }, hideResult: function(){ var widget = this._resultMailWidget; if (!widget){ return; } widget.destroy(); this._resultMailWidget = null; this.template.hide('resultPanel'); } }, { ATTRS: { component: {value: COMPONENT}, templateBlockName: {value: 'widget'}, }, CLICKS: { send: 'sendTestMail' }, }); };
export default function reducer (state = {}, action) { return state; };