text
stringlengths 2
6.14k
|
|---|
function solve(params) {
var number = +params[0]
switch (number) {
case 0:
return 'zero';
break;
case 1:
return 'one';
break;
case 2:
return 'two';
break;
case 3:
return 'three';
break;
case 4:
return 'four';
break;
case 5:
return 'five';
break;
case 6:
return 'six';
break;
case 7:
return 'seven';
break;
case 8:
return 'eight';
break;
case 9:
return 'nine';
break;
default:
return 'not a digit'
break;
}
}
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm4 8h-3v3h-2v-3H8V8h3V5h2v3h3v2z"
}), 'AddLocation');
|
import test from "ava";
import fs from "fs";
import path from "path";
import rimraf from "rimraf";
import webpack from "webpack";
import PnpWebpackPlugin from "pnp-webpack-plugin";
import createTestDirectory from "./helpers/createTestDirectory";
const ReactIntlPlugin = require("react-intl-webpack-plugin");
const cacheDir = path.join(__dirname, "output/cache/cachefiles");
const outputDir = path.join(__dirname, "output/metadata");
const babelLoader = path.join(__dirname, "../lib");
const globalConfig = {
mode: "development",
entry: "./test/fixtures/metadata.js",
output: {
path: outputDir,
filename: "[id].metadata.js",
},
plugins: [new ReactIntlPlugin()],
resolve: {
plugins: [PnpWebpackPlugin],
},
module: {
rules: [
{
test: /\.jsx?/,
loader: babelLoader,
options: {
metadataSubscribers: [ReactIntlPlugin.metadataContextFunctionName],
plugins: ["react-intl"],
presets: [],
},
exclude: /node_modules/,
},
],
},
};
// Create a separate directory for each test so that the tests
// can run in parallel
test.beforeEach.cb(t => {
createTestDirectory(outputDir, t.title, (err, directory) => {
if (err) return t.end(err);
t.context.directory = directory;
t.end();
});
});
test.afterEach.cb(t => rimraf(t.context.directory, t.end));
test.cb("should pass metadata code snippet", t => {
const config = Object.assign({}, globalConfig, {
output: {
path: t.context.directory,
filename: "[id].metadata.js",
},
});
webpack(config, (err, stats) => {
t.is(err, null);
t.deepEqual(stats.compilation.errors, []);
t.deepEqual(stats.compilation.warnings, []);
fs.readdir(t.context.directory, (err, files) => {
t.is(err, null);
t.true(files.length > 0);
fs.readFile(
path.resolve(t.context.directory, "reactIntlMessages.json"),
function (err, data) {
t.is(err, null);
const text = data.toString();
const jsonText = JSON.parse(text);
t.true(jsonText.length == 1);
t.true(jsonText[0].id == "greetingId");
t.true(jsonText[0].defaultMessage == "Hello World!");
t.end();
},
);
});
});
});
test.cb("should not throw error", t => {
const config = Object.assign({}, globalConfig, {
output: {
path: t.context.directory,
filename: "[id].metadata.js",
},
});
webpack(config, (err, stats) => {
t.is(err, null);
t.deepEqual(stats.compilation.errors, []);
t.deepEqual(stats.compilation.warnings, []);
t.end();
});
});
test.cb("should throw error", t => {
const config = Object.assign({}, globalConfig, {
output: {
path: t.context.directory,
filename: "[id].metadata.js",
},
entry: "./test/fixtures/metadataErr.js",
});
webpack(config, (err, stats) => {
t.is(err, null);
t.true(stats.compilation.errors.length > 0);
t.deepEqual(stats.compilation.warnings, []);
t.end();
});
});
test.cb("should pass metadata code snippet ( cache version )", t => {
const config = Object.assign({}, globalConfig, {
output: {
path: t.context.directory,
filename: "[id].metadata.js",
},
module: {
rules: [
{
test: /\.jsx?/,
loader: babelLoader,
options: {
metadataSubscribers: [ReactIntlPlugin.metadataContextFunctionName],
plugins: ["react-intl"],
cacheDirectory: cacheDir,
presets: [],
},
exclude: /node_modules/,
},
],
},
});
webpack(config, (err, stats) => {
t.is(err, null);
t.deepEqual(stats.compilation.errors, []);
t.deepEqual(stats.compilation.warnings, []);
fs.readdir(t.context.directory, (err, files) => {
t.is(err, null);
t.true(files.length > 0);
fs.readFile(
path.resolve(t.context.directory, "reactIntlMessages.json"),
function (err, data) {
t.is(err, null);
const text = data.toString();
const jsonText = JSON.parse(text);
t.true(jsonText.length == 1);
t.true(jsonText[0].id == "greetingId");
t.true(jsonText[0].defaultMessage == "Hello World!");
t.end();
},
);
});
});
});
|
var a = function() {
return 'b';
};
b = function doB(q, wer, ty) {
var c = function(n) {
return function() {
return q +
wer - ty;
}
}
return c
}
this.foo = {
bar: function() {
var r = function() {
re(); draw();
return log('foo') + 'bar';
};
},
ipsum: function(amet) {
return function() {
amet()
}
}
};
var noop = function() {};
var add = function(a, b) {
return a + b;
}
call(function(a) {
b();
});
// issue #36
var obj = {
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
}
};
// issue #134
var foo = new MyConstructor(function otherFunction() {});
// issue #143
if (!this._pollReceive) {
this._pollReceive = nn.PollReceiveSocket(this.binding, function(events) {
if (events) this._receive();
}.bind(this));
}
// issue #283
var foo = function foo() {
bar()
}
var foo = function() {
bar()
}
// default params (#285)
var defaultParams = function defaults(z, x = 1, y = 2) {
return z + x + y;
}
// issue #350
var foo = function*() {
yield '123';
yield '456';
};
var foo = function*() {
yield '123';
yield '456';
};
|
'use strict';
define([
'jquery', 'underscore', 'angular',
'angular-resource'
],
function ($, _, angular) {
var resourceApp = angular.module('resourceApp', [ 'ngResource' ]);
resourceApp.factory('NodeFactory', function ($resource) {
// $resource(url[, paramDefaults][, actions]);
return $resource('/document/node/:nid', {}, {
// save: { method: 'PUT', params: { nid: '@nid'}, transformResponse: function () {
// console.log('transformResponse', arguments);
// }, transformRequest: function () {
// console.log('transformRequest', arguments);
// } },
// get: { ... }
create: { method: 'POST' },
read: { method: 'GET', isArray: true },
update: { method: 'PUT', params: { nid: '@nid'} },
delete: { method: 'DELETE', params: { nid: '@nid'}, query: {} }
});
});
resourceApp.controller('ResourceDemoCtrl', function ($scope, NodeFactory) {
// We can retrieve a collection from the server
$scope.nodelist = NodeFactory.read(function readSuccess (value, responseHeaders) {
// console.log(nodelist);
// GET: /document/node
// server returns: [ {...}, {...}, ... ];
var node = value[0];
node.ipAddr = '211.114.0.250';
node.alive = false;
delete node.os;
node.$update();
// PUT: /document/node/160
// server returns: { ... };
});
$scope.setCurr = function (node) {
// clone
$scope.nodeData = {
nid: node.nid,
ipAddr: node.ipAddr,
port: node.port,
alive: node.alive
};
// ref
// $scope.nodeData = node;
};
$scope.requestByFactory = function (method, node) {
switch (method) {
case 'create':
var newNode = NodeFactory.create(node, function (value, responseHeaders) {
$scope.nodelist.push(newNode);
}, function (httpResponse) {
alert(httpResponse.data);
});
// POST: /document/node
// server returns: { ... };
break;
case 'update':
var updated = NodeFactory.update(node, function (value, responseHeaders) {
var selected = _.findWhere($scope.nodelist, { nid: node.nid });
if (selected) {
updated = _.extend(selected, updated);
}
}, function (httpResponse) {
alert(httpResponse.data);
});
// PUT: /document/node/:nid
// server returns: { ... };
break;
case 'getOne':
$scope.nodeData = NodeFactory.get(node);
break;
case 'delete':
var nid = NodeFactory.delete(node, function (value, responseHeaders) {
var selected = _.findWhere($scope.nodelist, { nid: node.nid });
if (selected) {
$scope.nodelist.splice(_.indexOf($scope.nodelist, selected), 1);
}
}, function (httpResponse) {
alert(httpResponse.data);
});
// DELETE: /document/node/:nid
// server returns: nid
break;
}
};
$scope.requestByInstence = function (method, node) {
switch (method) {
case 'update':
node.$update(function (value, responseHeaders) {
node = value;
}, function (httpResponse) {
alert(httpResponse.data);
});
// PUT: /document/node/:nid
// server returns: { ... };
break;
// case 'getOne':
// node = node.$get(node);
// break;
case 'delete':
node.$delete(function (value, responseHeaders) {
$scope.nodelist.splice(_.indexOf($scope.nodelist, node), 1);
}, function (httpResponse) {
alert(httpResponse.data);
});
// DELETE: /document/node/:nid
// server returns: nid
break;
}
};
});
});
|
var _curry2 = require('./internal/_curry2');
/**
* Tests if two items are equal. Equality is strict here, meaning reference equality for objects and
* non-coercing equality for primitives.
*
* @func
* @memberOf R
* @category Relation
* @sig a -> b -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @example
*
* var o = {};
* R.eq(o, o); //=> true
* R.eq(o, {}); //=> false
* R.eq(1, 1); //=> true
* R.eq(1, '1'); //=> false
*/
module.exports = _curry2(function eq(a, b) { return a === b; });
|
var searchData=
[
['wait_5ffor_5fcal_132',['wait_for_cal',['../class_a_d_c___module.html#a4fb69b5b2d07c3fc8f5f0bbbf05dfa2a',1,'ADC_Module']]],
['waituntilstable_133',['waitUntilStable',['../namespace_v_r_e_f.html#a108f7c1b5a2073bc092eafcae58575b0',1,'VREF']]],
['wrong_5fadc_134',['WRONG_ADC',['../namespace_a_d_c___error.html#ad050c44d1f3422d02e5f9726edeee8f0a52df2c8ae830ed21e0c2fc269087b3ec',1,'ADC_Error']]],
['wrong_5fpin_135',['WRONG_PIN',['../namespace_a_d_c___error.html#ad050c44d1f3422d02e5f9726edeee8f0ab578c19f4fab8e2bfeddc85fa17b5acf',1,'ADC_Error']]]
];
|
class Goblin extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 100;
this.attackStrength = 60;
this.attackSpeed = 1100;
this.speed = 0.15; // 10 px/ms
this.deploySpeed = 1000;
this.size = 10;
this.color = 'green';
super.setup();
}
}
class Skeleton extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 38;
this.attackStrength = 38;
this.attackSpeed = 1000;
this.speed = 0.1; // 10 px/ms
this.deploySpeed = 1000;
this.size = 7;
this.color = 'white';
super.setup();
}
}
class Archer extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 175;
this.attackStrength = 59;
this.attackSpeed = 1200;
this.attackAir = true;
this.speed = 0.05; // 10 px/ms
this.range = 100;
this.deploySpeed = 1000;
this.size = 10;
this.color = 'pink';
super.setup();
}
}
class BabyDragon extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 800;
this.attackStrength = 100;
this.attackSpeed = 1600;
this.attackSplash = true;
this.attackAir = true;
this.speed = 0.05; // 10 px/ms
this.range = 70;
this.targetRadius = 20;
this.deploySpeed = 1000;
this.flyingTroop = true;
this.size = 15;
this.color = 'darkgreen';
super.setup();
}
}
class Giant extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 2000;
this.attackStrength = 145;
this.attackSpeed = 1500;
this.speed = 0.01; // 10 px/ms
this.deploySpeed = 1000;
this.attackBuilding = true;
this.size = 20;
this.color = 'brown';
super.setup();
}
}
|
import db from './db';
const authenticatedOnly = (req, res, next) => {
if (req.isAuthenticated()) { return next(); }
return res.status(401).send('Authentication required');
};
const dbRoutes = (app) => {
app.post('/users', authenticatedOnly, (req, res) => {
db.update(req.body, (doc) => {
if (process.env.NODE_ENV !== 'production') {
console.log('Saved:', doc);
}
res.send(doc.data);
});
});
};
export default dbRoutes;
|
import Tipp from 'src/models/TippModel';
/**
* Save a new tipp
* @param {Object} req Request object
* @param {Object} res Response object
* @param {Function} next Callback for next middleware in route
*/
export const postTipp = (req, res, next) => new Tipp(req.body).save()
.then(data => res.json(data))
.catch(err => next(err));
/**
* Delete a tipp, needs authentication
* @param {Object} req Request object
* @param {Object} res Response object
* @param {Function} next Callback for next middleware in route
*/
export const deleteTipp = (req, res, next) => Tipp.remove({
_id: req.params.id,
})
.then(data => res.json(data))
.catch(err => next(err));
/**
* Update a tipp
* @param {Objec} req
* @param {Object} res
* @param {Function} next Callback for next middleware in route
*/
export const putTipp = (req, res, next) => Tipp.findByIdAndUpdate(req.params.id, {
$set: req.body,
}, {
new: true,
})
.then(data => res.json(data))
.catch(err => next(err));
/**
* Get a list of all tipps
* @param {Object} req
* @param {Object} res
* @param {Function} next Callback for next middleware in route
*/
export const listTipps = (req, res, next) => Tipp
.find({}, '-email')
.sort('-created')
.then(data => res.json(data))
.catch(err => next(err));
/**
* Get one tipp
* @param {Object} req
* @param {Object} res
* @param {Function} next Callback for next middleware in route
*/
export const getTipp = (req, res, next) => Tipp.findOne({
_id: req.params.id,
})
.then(data => res.json(data))
.catch(err => next(err));
|
import React from 'react';
import { combineReducers } from 'redux';
import { connect } from 'react-redux';
// Count reducer
const count = (state = 10, action) => {
switch (action.type) {
case 'increment':
return state + 1;
case 'decrement':
return state -1;
default:
return state;
}
}
// The store reducer for our Counter component.
export const reducer = combineReducers({
count,
});
// A simple React component
class Counter extends React.Component {
render() {
return React.createElement(
'div',
null,
this.props.count,
React.createElement(
'button',
{ onClick: () => this.props.dispatch({ type: 'increment' }) },
'inc'
),
React.createElement(
'button',
{ onClick: () => this.props.dispatch({ type: 'decrement' }) },
'dec'
)
);
}
}
export default connect(state => ({...state}))(Counter);
|
'use strict';
/**
* Module dependencies.
*/
var debug = require('debug')('swara:config'),
path = require('path'),
_ = require('lodash'),
glob = require('glob');
/**
* Load app configurations
*/
module.exports = _.extend(
require('./env/all'),
require('./env/' + process.env.NODE_ENV) || {}
);
/**
* Get files by glob patterns
*/
module.exports.getGlobbedFiles = function (globPatterns, removeRoot) {
// For context switching
var _this = this;
// URL paths regex
var urlRegex = new RegExp('^(?:[a-z]+:)?\/\/', 'i');
// The output array
var output = [];
// If glob pattern is array so we use each pattern in a recursive way, otherwise we use glob
if (_.isArray(globPatterns)) {
globPatterns.forEach(function (globPattern) {
output = _.union(output, _this.getGlobbedFiles(globPattern, removeRoot));
});
} else if (_.isString(globPatterns)) {
if (urlRegex.test(globPatterns)) {
output.push(globPatterns);
} else {
var publicRE = /^public\//;
if (publicRE.test(globPatterns)) {
globPatterns = __dirname + '/../' + globPatterns;
var newRoot = __dirname + '/../' + removeRoot;
removeRoot = path.normalize(newRoot);
}
var files = glob.sync(globPatterns);
if (removeRoot) {
files = files.map(function (file) {
return file.replace(removeRoot, '');
});
}
output = _.union(output, files);
}
}
debug('Returning with output: %j', output);
return output;
};
/**
* Get the modules JavaScript files
*/
module.exports.getJavaScriptAssets = function (includeTests) {
var output = this.getGlobbedFiles(this.assets.lib.js.concat(this.assets.js), 'public/');
// To include tests
if (includeTests) {
output = _.union(output, this.getGlobbedFiles(this.assets.tests));
}
debug('getJavaScriptAssets returning with: %j', output);
return output;
};
/**
* Get the modules CSS files
*/
module.exports.getCSSAssets = function () {
var output = this.getGlobbedFiles(this.assets.lib.css.concat(this.assets.css), 'public/');
debug('getCSSAssets returning with: %j', output);
return output;
};
|
export { default } from "./Paragraph";
|
'use strict';
angular.module('dashboardApp')
.controller('RentsCtrl', function ($scope, Rents, $location, $routeParams, Auth, rents) {
$scope.rents = rents;
$scope.returnBook = function(rent){
Rents.returnBook({'rentId': rent.rentId}, function(res){
console.log(res);
rent.status = res.status;
rent.rent.returnDate = res.rent.returnDate;
});
};
$scope.getStyle = function(rent){
if (rent.rent && (new Date(rent.rent.endDate) < new Date() && !rent.rent.returnDate)) {
return 'warning';
}
};
$scope.query = function(){
if (!$scope.mayQuery) {
return false;
}
var query = {page: $scope.page + 1};
query = angular.extend(query, $routeParams, {user: Auth.getUser().userId});
console.log(query);
Rents.query(query,
function(rents){
if (!rents.length) {
$scope.mayQuery = false;
}
$scope.rents = $scope.rents.concat(rents);
$scope.page += 1;
},
function(error){
});
};
$scope.page = 1;
$scope.mayQuery = 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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
import * as Rules from './validation_rules';
import { find, partial, uniqBy } from 'lodash';
/**
* Creates a validator instance
*
* @param {array} rules
* @param {object} redux
* @param {object} validations
*
* @example
* let valid = new validator([{
* label: 'email ',
* rules: [{
* rule: 'required',
* message: 'Email address required'
* }]
* }]);
*
* @example with redux binding
* let valid = new validator([{
* label: 'email ',
* rules: [{
* rule: 'required',
* message: 'Email address required'
* }, {
* rule: action1,
* message: 'Some message'
* }]
* }], {
* store: store,
* actions: {
* action1: () => { ... },
* action2: () => { ... }
* }
* });
*
* @example with custom validations
* let valid = new validator([{
* label: 'email ',
* rules: [{
* rule: 'required',
* message: 'Email address required'
* }, {
* label: 'specialString',
* rule: [{
* rule: 'containsSomeWord',
* args: 'foo',
* message: 'This value must have the word "foo"'
* }]
* }]
* }], null, {
* containsSomeWord: (val, word) => val.indexOf(word) > -1
* });
*/
var validator = function () {
function validator(rules, redux, validations, value) {
_classCallCheck(this, validator);
this._rules = rules;
this._val = value ? value : '';
this._redux = redux;
this._validations = validations || {};
this._reduxRules = [];
this._errors = [];
}
validator.prototype.checkRules = function checkRules() {
var _this = this;
var optional = false;
this._errors = this._rules.filter(function (r) {
if (r.rule === 'optional' && _this._val === '') optional = true;
return _this.isRuleValid(r.rule);
});
// only run redux async rules if all synchronous rules have passed
// currently not logging synchronous errors for redux callbacks, use store state
this._reduxRules = uniqBy(this._reduxRules, 'rule');
if (this._reduxRules.length > 0 && this._errors.length < 1) {
this._reduxRules.forEach(function (r) {
return r.promise = _this._redux.store.dispatch(_this._redux.actions[r.rule](_this._val));
});
}
// check for optional override
if (optional) this._errors = [];
};
validator.prototype.hasArgs = function hasArgs(rule) {
return find(this._rules, function (r) {
return r.rule === rule && r.args;
});
};
validator.prototype.isRuleValid = function isRuleValid(rule) {
if (rule && (this._validations[rule] || Rules[rule])) {
var ruleToEval = Rules[rule] || this._validations[rule];
var hasArgs = this.hasArgs(rule);
var method = partial(ruleToEval, this._val);
return hasArgs ? !method(hasArgs.args) : !method();
} else if (rule && this._redux.actions[rule]) {
this._reduxRules.push({ rule: rule, promise: Promise.resolve() });
}
};
validator.prototype.reset = function reset() {
this._errors = [];
};
_createClass(validator, [{
key: 'val',
set: function set(val) {
this._val = val;
},
get: function get() {
return this._val;
}
}, {
key: 'errors',
get: function get() {
return this._errors;
}
}]);
return validator;
}();
export { validator as default };
|
var casper = require('casper').create();
var utils = require('utils');
// casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36');
var x = require('casper').selectXPath;
casper.on("resource.error", function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
});
casper.start('http://www.apple.com/');
casper.wait(3000, function() {
var title = casper.getTitle();
console.log('>>> PageTitle: ' + title);
console.log('>>> PageHTML:\n' + casper.getHTML());
});
casper.run(function() {
this.exit(0);
});
|
goog.provide('ol.source.GeoJSON');
goog.require('ol.format.GeoJSON');
goog.require('ol.source.StaticVector');
/**
* @classdesc
* Static vector source in GeoJSON format
*
* @constructor
* @extends {ol.source.StaticVector}
* @fires ol.source.VectorEvent
* @param {olx.source.GeoJSONOptions=} opt_options Options.
* @api
*/
ol.source.GeoJSON = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
goog.base(this, {
attributions: options.attributions,
extent: options.extent,
format: new ol.format.GeoJSON({
defaultDataProjection: options.defaultProjection
}),
logo: options.logo,
object: options.object,
projection: options.projection,
text: options.text,
url: options.url,
urls: options.urls
});
};
goog.inherits(ol.source.GeoJSON, ol.source.StaticVector);
|
import React from 'react';
import styled from 'styled-components';
const FooterSection = styled.section`
padding: 0.4em 0em;
text-align: right;
`;
class Footer extends React.Component {
render() {
return <FooterSection>{ this.props.children }</FooterSection>;
}
}
export default Footer
|
// pages/list/index.js
Page({
/**
* 页面的初始数据
*/
data: {
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
casper.test.begin('BAS GeoMap Features site shows a home page and has 1 or more Features', 5, function suite(test) {
casper.start("https://geomap-features.web.bas.ac.uk", function() {
// Basic checks
test.assertTitle("BAS GeoMap Features", "homepage title is the one expected");
test.assertExists('.page-header h1', "there is a main header on the homepage");
// View Features button
test.assertExists('.page-header h1', "there is a main header on the homepage");
var featreButtonText = casper.fetchText('.btn.btn-primary.btn-lg.btn-bsk.btn-bsk-primary');
test.assertMatch(featreButtonText, /^View all [1-9]\d* Features/, 'the view features button has a count of one or more features');
// Click button to do next tests
casper.click('.btn.btn-primary.btn-lg.btn-bsk.btn-bsk-primary')
});
casper.then(function() {
test.assertTitle("Index of Features", "features index title is the one expected");
});
casper.run(function() {
test.done();
});
});
|
/** @jsx React.DOM */
var Footer =
React.createClass({
shouldComponentUpdate: function() {
return false;
},
render:function(){
return (
<div className="footer">
<p>© Company</p>
</div>
)
}
});
|
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./lib/create-render'));
__export(require('./lib/universal-cache'));
//# sourceMappingURL=index.js.map
|
import SubGenerator2 from "stimpak-subgenerator-2";
export default class SubGenerator {
setup(stimpak) {
stimpak
.use(SubGenerator2)
.prompt({
type: "input",
name: "promptName",
message: "You should not see this"
})
.render("**/*", `${__dirname}/templates`);
}
}
|
/*jshint unused: vars */
require.config({
paths: {
angular: '../../bower_components/angular/angular',
'angular-animate': '../../bower_components/angular-animate/angular-animate',
'angular-aria': '../../bower_components/angular-aria/angular-aria',
'angular-cookies': '../../bower_components/angular-cookies/angular-cookies',
'angular-messages': '../../bower_components/angular-messages/angular-messages',
'angular-mocks': '../../bower_components/angular-mocks/angular-mocks',
'angular-resource': '../../bower_components/angular-resource/angular-resource',
'angular-route': '../../bower_components/angular-route/angular-route',
'angular-sanitize': '../../bower_components/angular-sanitize/angular-sanitize',
'angular-touch': '../../bower_components/angular-touch/angular-touch',
bootstrap: '../../bower_components/bootstrap/dist/js/bootstrap',
'angular-bootstrap': '../../bower_components/angular-bootstrap/ui-bootstrap-tpls',
'angular-ui-grid': '../../bower_components/angular-ui-grid/ui-grid'
},
shim: {
angular: {
exports: 'angular'
},
'angular-route': [
'angular'
],
'angular-cookies': [
'angular'
],
'angular-sanitize': [
'angular'
],
'angular-resource': [
'angular'
],
'angular-animate': [
'angular'
],
'angular-touch': [
'angular'
],
'angular-bootstrap': [
'angular'
],
'angular-mocks': {
deps: [
'angular'
],
exports: 'angular.mock'
}
},
priority: [
'angular'
],
packages: [
]
});
//http://code.angularjs.org/1.2.1/docs/guide/bootstrap#overview_deferred-bootstrap
window.name = 'NG_DEFER_BOOTSTRAP!';
require([
'angular',
'angular-route',
'angular-cookies',
'angular-sanitize',
'angular-resource',
'angular-animate',
'angular-touch',
'angular-bootstrap',
'app'
], function (angular, ngRoutes, ngCookies, ngSanitize, ngResource, ngAnimate, ngTouch, ngBootstrap, app) {
'use strict';
/* jshint ignore:start */
var $html = angular.element(document.getElementsByTagName('html')[0]);
/* jshint ignore:end */
angular.element().ready(function () {
angular.resumeBootstrap([app.name]);
});
});
|
import PropTypes from 'prop-types';
import React from 'react';
import moment from 'moment';
import { withStyles } from 'material-ui/styles';
import IconButton from 'material-ui/IconButton';
import CloseIcon from 'material-ui-icons/Close';
import InfoIcon from 'material-ui-icons/Info';
import TimelineIcon from 'material-ui-icons/Timeline';
import { Users } from '/imports/api/users/user';
import {
Inner,
ZoomerImage,
ZoomerBackground,
ToolBoxSection,
ActionSection,
UserAvatar,
ImageDetail,
} from '../ZoomerHolder.style';
const ZoomerInner = (props) => {
const {
image,
imageHolderStyle,
classes,
onLogoClick,
onAvatarClick,
onInfoActionClick,
onExifActionClick,
} = props;
const user = Users.findOne({ username: image.user });
const avatar = user && user.profile.avatar;
return (
<Inner>
<ZoomerImage style={imageHolderStyle}>
<ZoomerBackground />
</ZoomerImage>
<ToolBoxSection>
<IconButton
className={classes.iconBtn}
onClick={onLogoClick}
><CloseIcon className={classes.icon__logo} />
</IconButton>
</ToolBoxSection>
<ActionSection>
<div>
<UserAvatar
src={avatar}
role="presentation"
onClick={onAvatarClick}
/>
<ImageDetail>
<span>
{image.user}
</span>
<span>
{moment(image.createdAt).format('YYYY-MM-DD HH:mm')}
</span>
</ImageDetail>
</div>
<div>
<IconButton
className={classes.iconBtn}
onClick={onInfoActionClick}
><TimelineIcon />
</IconButton>
<IconButton
className={classes.iconBtn}
onClick={onExifActionClick}
><InfoIcon />
</IconButton>
</div>
</ActionSection>
</Inner>
);
};
ZoomerInner.propTypes = {
image: PropTypes.object.isRequired,
imageHolderStyle: PropTypes.object.isRequired,
classes: PropTypes.object.isRequired,
onLogoClick: PropTypes.func.isRequired,
onAvatarClick: PropTypes.func.isRequired,
onInfoActionClick: PropTypes.func.isRequired,
onExifActionClick: PropTypes.func.isRequired,
};
const styles = {
iconBtn: {
color: '#fff',
},
icon__logo: {
width: 28,
height: 28,
},
};
export default withStyles(styles)(ZoomerInner);
|
// @flow
import React from 'react';
import { generateStreamUrl } from 'util/web';
export default function useGetThumbnail(
uri: string,
claim: ?Claim,
streamingUrl: ?string,
getFile: string => void,
shouldHide: boolean
) {
let thumbnailToUse;
// $FlowFixMe
const isImage = claim && claim.value && claim.value.stream_type === 'image';
// $FlowFixMe
const isFree = claim && claim.value && (!claim.value.fee || Number(claim.value.fee.amount) <= 0);
const thumbnailInClaim = claim && claim.value && claim.value.thumbnail && claim.value.thumbnail.url;
// @if TARGET='web'
if (thumbnailInClaim) {
thumbnailToUse = thumbnailInClaim;
} else if (claim && isImage && isFree) {
thumbnailToUse = generateStreamUrl(claim.name, claim.claim_id);
}
// @endif
// @if TARGET='app'
thumbnailToUse = thumbnailInClaim;
//
// Temporarily disabled until we can call get with "save_blobs: off"
//
// React.useEffect(() => {
// if (hasClaim && isImage && isFree) {
// if (streamingUrl) {
// setThumbnail(streamingUrl);
// } else if (!shouldHide) {
// getFile(uri);
// }
// }
// }, [hasClaim, isFree, isImage, streamingUrl, uri, shouldHide]);
// @endif
const [thumbnail, setThumbnail] = React.useState(thumbnailToUse);
React.useEffect(() => {
setThumbnail(thumbnailToUse);
}, [thumbnailToUse]);
return thumbnail;
}
|
var Core = require('cw-core');
var Exception = Core.Exception;
var ArgumentNullException = Core.ArgumentNullException;
var ArgumentException = Core.ArgumentException;
var Arr = Core.Arr;
var Enumerable = require('linq');
var _ = require('underscore');
var Field = (function () {
function Field(form, name) {
this._rules = [];
if (form == null) {
throw new ArgumentNullException('form');
}
this._form = form;
this.name = name;
}
Object.defineProperty(Field.prototype, "name", {
get: function () {
return this._name;
},
set: function (name) {
this._name = name;
},
enumerable: true,
configurable: true
});
Field.prototype.addRule = function () {
var args = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
args[_i] = arguments[_i + 0];
}
return this.insertRule.apply(this, [this._rules.length].concat(args));
};
Field.prototype.insertRule = function (idx, rule) {
var args = [];
for (var _i = 0; _i < (arguments.length - 2); _i++) {
args[_i] = arguments[_i + 2];
}
if (idx < 0) {
idx = this._rules.length + idx + 1;
}
if (_.isString(rule)) {
this._rules.splice(idx, 0, new RuleObject(rule, null, null, args));
} else if (!_.isUndefined(rule.validate)) {
var name = Arr.get(args, 0, null);
args = args.splice(0, 1);
this._rules.splice(idx, 0, new RuleObject(name, null, rule, args));
} else if (_.isFunction(rule)) {
this._rules.splice(idx, 0, new RuleObject(null, rule, null, args));
} else {
throw new ArgumentException('rule', 'rule parameter must be string or function.');
}
return this;
};
Field.prototype.removeRule = function (rule) {
var idx;
while ((idx = this.findRule(rule)) >= 0) {
delete this._rules[idx];
}
return this;
};
Field.prototype.validate = function (v, result) {
var _this = this;
var rules = Enumerable.from(this._rules);
var error = null;
var validated = true;
var validatedValue = v;
rules.forEach(function (rule) {
if (validated) {
var args = {
value: validatedValue,
result: result,
parameters: rule.arguments,
form: _this._form
};
var result = rule.validate(_this, args);
if (_.isBoolean(result)) {
validated = validated && result;
} else {
validatedValue = result;
}
if (!validated) {
error = {
field: _this,
rule: rule.name,
value: validatedValue,
arguments: rule.arguments
};
}
}
});
return {
hasError: !validated,
error: error,
validatedValue: validatedValue
};
};
Field.prototype.findRule = function (rule) {
if (_.isString(rule)) {
return Enumerable.from(this._rules).indexOf(function (v) {
return v.name == rule;
});
} else if (_.isFunction(rule)) {
return Enumerable.from(this._rules).indexOf(function (v) {
return v.validator == rule;
});
}
return -1;
};
Object.defineProperty(Field.prototype, "form", {
get: function () {
return this._form;
},
enumerable: true,
configurable: true
});
return Field;
})();
var RuleObject = (function () {
function RuleObject(name, func, validator, arguments) {
this.name = name;
this.function = func;
this.validator = validator;
this.arguments = arguments;
}
RuleObject.prototype.validate = function (field, args) {
if (this.function != null) {
return this.function.apply(field, [args.value].concat(this.arguments));
} else if (this.validator != null) {
return this.validator.validate(args);
} else {
var validator = field.form.getValidator(this.name);
if (!validator) {
throw new Exception('Rule:' + this.name + " is not found.");
}
return validator.validate(args);
}
};
return RuleObject;
})();
module.exports = Field;
//# sourceMappingURL=Field.js.map
|
define(function(require) {
var $ = require('./jquery');
var marked = require('./marked');
var prettify = require('./prettify');
var title = document.title;
function initPage() {
marked.setOptions({
highlight: function(code) {
return prettify.prettyPrintOne(escape(code));
}
});
$('.section').each(function() {
$(this).html(marked($(this).children('.markdown').val()));
});
$('.loading').remove();
initShare();
updateView();
}
function initEvent() {
$(document).bind({
WeixinJSBridgeReady: initShare
});
if ('onhashchange' in window) {
$(window).on({
hashchange: function() {
updateView();
}
});
} else {
$('body').on({
click: function() {
if (this.href.indexOf('#') >= 0) {
updateView(this.href.replace(/(?:.*(#\w+)|.*)/, '$1') || '#intro');
}
}
}, 'a');
}
$('.footer .top').on({
click: function() {
window.scrollTo(0, 0);
}
});
}
function initShare() {
if (!window.WeixinJSBridge) {
return;
}
try {
WeixinJSBridge.on('menu:share:appmessage', function(argv) {
WeixinJSBridge.invoke('sendAppMessage', getShareData());
});
WeixinJSBridge.on('menu:share:timeline', function(argv) {
WeixinJSBridge.invoke('shareTimeline', getShareData());
});
} catch (e) {}
}
function getShareData() {
return {
title: document.title,
link: document.location.href,
desc: $('#intro p').eq(0).text(),
img_url: 'http://tp3.sinaimg.cn/1562087202/180/40038430931/1'
};
}
function updateView(id) {
id = id || location.href.replace(/(?:.*(#\w+)|.*)/, '$1') || '#intro';
$('.section').hide();
document.title = title + ' - ' + $(id).show().find('h2').eq(0).text();
setTimeout(window.scrollTo, 0, 0, 0);
ga('send', 'event', 'section', 'view', id);
}
function escape(code) {
return code
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
initPage();
initEvent();
});
|
/**
@module ember-flexberry
*/
import Ember from 'ember';
const { getOwner } = Ember;
import { enumCaptions } from 'ember-flexberry-data/utils/enum-functions';
/**
Helper for get array captions of registered enum.
@class EnumCaptionHelper
@extends <a href="http://emberjs.com/api/classes/Ember.Helper.html">Ember.Helper</a>
@public
*/
export default Ember.Helper.extend({
compute([enumName]) {
let enumInstance = getOwner(this).lookup('enum:' + enumName);
return enumCaptions(enumInstance);
}
});
|
angular.module('emp').service('PeopleService', function($http) {
var service = {
getAllPeople: function() {
return $http.get('core/data/people.json', { cache: true }).then(function(resp) {
return resp.data;
});
},
getPerson: function(id) {
function personMatchesParam(person) {
return person.id === id;
}
return service.getAllPeople().then(function (people) {
return people.find(personMatchesParam)
});
}
}
return service;
})
|
var fs = require('fs');
var path = require('path');
var config = require('../config');
function snapshotFilename(snapPath) {
return snapPath.replace(/[^[a-zA-Z0-9]+/g, '_').substr(-100) + '_snapshot.json';
}
function snapshotPath(snapPath) {
return path.join(process.cwd(), config.snapshotPath, snapshotFilename(snapPath));
}
function snapshotExist(snapPath) {
return fs.existsSync(snapshotPath(snapPath));
}
module.exports = {
snapshotFilename: snapshotFilename,
snapshotPath: snapshotPath,
snapshotExist: snapshotExist
};
|
define(['config', 'folders'], function (config, folders) {
var wrikeStates = { 'active': 0, 'completed': 1, 'deferred': 2, 'cancelled': 3 };
var statusFolders = folders.getSubfolders(config.statusFolder)
, statuses = {}
, statusesById = {};
$.each(statusFolders, function (i, val) {
var wrikeState = val.data.title.match(/\d+\. .* \((.*)\)/);
// If the status has an improperly formatted name, ignore it
if (wrikeState === null || typeof (wrikeState = wrikeStates[wrikeState[1].toLowerCase()]) === 'undefined') {
debug.warn('Status has the wrong format. Should be titled "123. Your Status Name (Active|Completed|Deferred|Cancelled)"\nYou provided "' + val.data.title + '"');
return;
}
val.powerWrike.wrikeState = wrikeState;
statuses[val.powerWrike.uniquePath] = statusesById[val.id] = val;
});
return {
statuses: statuses,
statusesById: statusesById,
};
});
|
//= require assets/templates/user
|
'use strict';
require('./connectionHelper');
const expect = require('chai').expect;
const supertest = require('supertest');
const app = require('../app.js');
const Appointment = require('../models/appointment');
const agent = supertest(app);
describe('appointment', function() {
let appointment = {};
beforeEach(function(done) {
Appointment.remove({}, done);
appointment = new Appointment({
name: 'Appointment',
phoneNumber: '+5555555',
time: new Date(),
notification: 15,
timeZone: 'Africa/Algiers',
});
});
describe('GET /appointments', function() {
it('list all appointments', function(done) {
const result = appointment.save();
result
.then(function() {
agent
.get('/appointments')
.expect(function(response) {
expect(response.text).to.contain('Appointment');
expect(response.text).to.contain('+5555555');
expect(response.text).to.contain('15');
expect(response.text).to.contain('Africa/Algiers');
})
.expect(200, done);
});
});
});
describe('GET /appointments/create', function() {
it('shows create property form', function(done) {
agent
.get('/appointments/create')
.expect(function(response) {
expect(response.text).to.contain('Create');
})
.expect(200, done);
});
});
describe('POST to /appointments', function() {
it('creates a new appointment', function(done) {
agent
.post('/appointments')
.type('form')
.send({
name: 'Appointment',
phoneNumber: '+5555555',
time: '02-17-2016 12:00am',
notification: 15,
timeZone: 'Africa/Algiers',
})
.expect(function(res) {
Appointment
.find({})
.then(function(appointments) {
expect(appointments.length).to.equal(1);
});
})
.expect(302, done);
});
});
describe('GET /appointments/:id/edit', function() {
it('shows a single appointment', function(done) {
const result = appointment.save();
result
.then(function() {
agent
.get('/appointments/' + appointment.id + '/edit')
.expect(function(response) {
expect(response.text).to.contain('Appointment');
expect(response.text).to.contain('+5555555');
expect(response.text).to.contain('15');
expect(response.text).to.contain('Africa/Algiers');
})
.expect(200, done);
});
});
});
describe('POST /appointments/:id/edit', function() {
it('updates an appointment', function(done) {
const result = appointment.save();
result
.then(function() {
agent
.post('/appointments/' + appointment.id + '/edit')
.type('form')
.send({
name: 'Appointment2',
phoneNumber: '+66666666',
time: '02-17-2016 12:00am',
notification: 15,
timeZone: 'Africa/Algiers',
})
.expect(function(response) {
Appointment
.findOne()
.then(function(appointment) {
expect(appointment.name).to.contain('Appointment2');
expect(appointment.phoneNumber).to.contain('+66666666');
});
})
.expect(302, done);
});
});
});
});
|
import React from "react";
import ReactDOM from "react-dom";
import VariableInspector from "./components/VariableInspector";
ReactDOM.render(
<VariableInspector />,
document.getElementById("root")
);
|
module.exports = {
rules: {
"no-alert": [0],
"@thibaudcolas/cookbook/import/no-extraneous-dependencies": [
"error",
{
devDependencies: true,
},
],
},
};
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'removeformat', 'ka', {
toolbar: 'ფორმატირების მოხსნა'
} );
|
var _ = require('lodash');
var path = require('path');
function cucumberJUnitReporter(providedConfig, builder) {
var config = _.defaults(providedConfig || {}, {
reportDir: 'test_reports',
reportPrefix: 'TEST-',
reportSuffix: '.xml',
reportFile: 'test_results.xml',
oneReportPerFeature: true,
numberSteps: true
});
var suite = builder;
var featurePath;
var featureName;
var scenarioName;
var stepCounter = 0;
function getCurrentTestClassName() {
var testClassName = '';
if (featureName) {
testClassName += 'Feature: ' + featureName.replace(/\./g, ' ');
}
if (scenarioName) {
testClassName += '.Scenario: ' + scenarioName.replace(/\./g, ' ');
}
return testClassName;
}
function getFeatureReportPath() {
var reportName = config.reportPrefix +
featurePath.replace(/[\/]/g, '.') +
config.reportSuffix;
return path.join(config.reportDir, reportName);
}
function getGlobalReportPath() {
return path.join(config.reportDir, config.reportFile);
}
function getStepName(stepCount, step) {
var name = '';
if (config.numberSteps) {
if (stepCount < 10) {
name += '0';
}
name += stepCount + '. ';
}
name += step.getKeyword() + step.getName();
return name;
}
function formatTime(duration) {
if (typeof duration === 'number') {
return Math.round(duration / 1e6) / 1e3;
}
return null;
}
function registerHandlers() {
this.registerHandler('BeforeFeature', function (event, callback) {
var feature = event.getPayloadItem('feature');
featureName = feature.getName();
featurePath = path.relative(process.cwd(), feature.getUri());
suite = builder.testSuite().name(featureName);
callback();
});
this.registerHandler('BeforeScenario', function (event, callback) {
var scenario = event.getPayloadItem('scenario');
scenarioName = scenario.getName();
stepCounter = 0;
callback();
});
this.registerHandler('StepResult', function (event, callback) {
var stepResult = event.getPayloadItem('stepResult');
var step = stepResult.getStep();
var stepName = step.getName();
if (typeof stepName === "undefined" && stepResult.isSuccessful()) {
callback();
return;
}
stepCounter++;
var testCase = suite.testCase()
.className(getCurrentTestClassName())
.name(getStepName(stepCounter, step));
if (stepResult.isSuccessful()) {
testCase.time(formatTime(stepResult.getDuration()));
} else if (stepResult.isSkipped()) {
testCase.skipped();
} else if (!stepResult.isPending() && !stepResult.isUndefined()) {
var failureException = stepResult.getFailureException();
testCase.failure(failureException).time(formatTime(stepResult.getDuration()));
if (failureException.stack) {
testCase.stacktrace(failureException.stack);
}
}
callback();
});
this.registerHandler('AfterScenario', function (event, callback) {
scenarioName = undefined;
callback();
});
this.registerHandler('AfterFeature', function (event, callback) {
if (config.oneReportPerFeature) {
builder.writeTo(getFeatureReportPath());
builder = builder.newBuilder();
}
featureName = undefined;
featurePath = undefined;
suite = builder;
callback();
});
this.registerHandler('AfterFeatures', function (event, callback) {
if (!config.oneReportPerFeature) {
builder.writeTo(getGlobalReportPath());
}
callback();
});
}
return registerHandlers;
}
module.exports = cucumberJUnitReporter;
|
/**
* Created by shuis on 2017/5/29.
*/
import React, { Component } from 'react';
import {
View,
Image,
FlatList,
TouchableWithoutFeedback
} from 'react-native';
import {TabBarIcon, TweetSeparator} from '../component/base';
import Tweet from '../component/Tweet';
import {public_timeline} from '../api/api';
class LookAround extends Component{
static navigationOptions = ({ navigation }) => ({
title: '随便看看',
tabBarLabel: '发现',
tabBarIcon: <TabBarIcon icon={require('../img/discovery.png')}/>,
headerRight: (
<TouchableWithoutFeedback onPress={()=>{navigation.state.params.onPress()}}>
<View style={{padding:10}}>
<Image source={require('../img/refresh.png')}/>
</View>
</TouchableWithoutFeedback>
)
});
constructor(props){
super(props);
this.state = {
data: [],
showImageViewer: false,
image: [{url:''}],
}
}
componentWillMount() {
this.props.navigation.setParams({
onPress:this._fetch,
})
}
componentDidMount() {
this._fetch();
}
_fetch = async () => {
try {
let res = await public_timeline();
this.setState({
data: res,
});
} catch (e) {
}
};
_renderItem = ({item}) => {
return <Tweet item={item} navigation={this.props.navigation}/>;
};
_keyExtractor = (item, index) => index;
_renderSeparator = () => {
return <TweetSeparator/>
};
render(){
return (
<View>
<FlatList
data = {this.state.data}
renderItem = {this._renderItem}
initialNumToRender = {6}
keyExtractor={this._keyExtractor}
ItemSeparatorComponent={this._renderSeparator}
/>
</View>
)
}
}
export default LookAround;
|
var should = require('should');
var annotationRouter = require('../../index.js');
var path = './mock.js';
describe('get basic routes', function(){
describe('asynchronous', function(){
var err;
before(function(done){
routes = {};
annotationRouter(path, function(e, route){
if(e) err = e;
routes[route.method + '-' + route.url] = route;
}, done);
});
it('should have gone well', function(){
should.ifError(err);
routes.should.not.be.empty;
var nb = 0;
for(var i in routes){
routes[i].should.be.a.route;
nb++;
}
nb.should.be.equal(5);
});
it('should get the first route of getAll', checkRoute('GET', '/user', 'getAll', 'getUsers'));
it('should get the second route of getAll', checkRoute('GET', '/company{companyId}/user', 'getAll', 'getUsers'));
it('should get the route of getUser', checkRoute('GET', '/user/{id}', 'getUser', 'getUser'));
it('should get the route of postUser', checkRoute('POST', '/user', 'postUser', 'addUser'));
it('should get the route of functionToEditTheUser', checkRoute('PUT', '/user/{id}', 'functionToEditTheUser', 'updateUser'));
it('should get non supported annotations', function(){
routes['PUT-/user/{id}'].should.have.property('annotations').which.have.property('isAdmin', [[]]);
});
it('should get non supported raw annotations', function(){
routes['PUT-/user/{id}'].should.have.property('rawAnnotations').which.have.property('isAdmin', ['isAdmin()']);
});
});
describe('synchronous', function(){
var err;
before(function(){
routes = {};
try {
annotationRouter.sync(path).map(function(route){
routes[route.method + '-' + route.url] = route;
});
} catch (e) {
err = e;
}
});
it('should have gone well', function(){
should.ifError(err);
routes.should.not.be.empty;
var nb = 0;
for(var i in routes){
routes[i].should.be.a.route;
nb++;
}
nb.should.be.equal(5);
});
it('should get the first route of getAll', checkRoute('GET', '/user', 'getAll', 'getUsers'));
it('should get the second route of getAll', checkRoute('GET', '/company{companyId}/user', 'getAll', 'getUsers'));
it('should get the route of getUser', checkRoute('GET', '/user/{id}', 'getUser', 'getUser'));
it('should get the route of postUser', checkRoute('POST', '/user', 'postUser', 'addUser'));
it('should get the route of functionToEditTheUser', checkRoute('PUT', '/user/{id}', 'functionToEditTheUser', 'updateUser'));
it('should get non supported annotations', function(){
routes['PUT-/user/{id}'].should.have.property('annotations').which.have.property('isAdmin', [[]]);
});
it('should get non supported raw annotations', function(){
routes['PUT-/user/{id}'].should.have.property('rawAnnotations').which.have.property('isAdmin', ['isAdmin()']);
});
});
});
function checkRoute(method, url, actionName, functionResult, nonOfficialAnnotations, nonOfficialRawAnnotations){
return function(){
var route = routes[method + '-' + url];
should.exist(route, 'route wasn\'t found');
route.should.have.property('url', url);
route.should.have.property('method', method);
route.should.have.property('action');
route.action().should.be.equal(functionResult);
route.should.have.property('actionName', actionName);
route.should.have.property('controller');
route.controller.should.have.property('name', 'mock');
route.controller.should.have.property('ext', '.js');
route.controller.should.have.property('base', 'mock.js');
route.controller.should.have.property('dir').which.containEql('test/router');
route.controller.should.have.property('full').which.containEql('test/router/mock.js');
route.controller.should.have.property('annotations').which.containEql('IsLogIn');
route.controller.should.have.property('rawAnnotations').which.have.property('IsLogIn', ['IsLogIn()']);
};
}
|
var Drag={
obj: null,
leftTime: null,
rightTime: null,
init: function (o,minX,maxX,btnRight,btnLeft) {
o.onmousedown=Drag.start;
o.hmode=true;
if(o.hmode&&isNaN(parseInt(o.style.left))) { o.style.left="0px"; }
if(!o.hmode&&isNaN(parseInt(o.style.right))) { o.style.right="0px"; }
o.minX=typeof minX!='undefined'?minX:null;
o.maxX=typeof maxX!='undefined'?maxX:null;
o.onDragStart=new Function();
o.onDragEnd=new Function();
o.onDrag=new Function();
btnLeft.onmousedown=Drag.startLeft;
btnRight.onmousedown=Drag.startRight;
btnLeft.onmouseup=Drag.stopLeft;
btnRight.onmouseup=Drag.stopRight;
},
start: function (e) {
var o=Drag.obj=this;
e=Drag.fixE(e);
var x=parseInt(o.hmode?o.style.left:o.style.right);
o.onDragStart(x);
o.lastMouseX=e.clientX;
if(o.hmode) {
if(o.minX!=null) { o.minMouseX=e.clientX-x+o.minX; }
if(o.maxX!=null) { o.maxMouseX=o.minMouseX+o.maxX-o.minX; }
} else {
if(o.minX!=null) { o.maxMouseX= -o.minX+e.clientX+x; }
if(o.maxX!=null) { o.minMouseX= -o.maxX+e.clientX+x; }
}
document.onmousemove=Drag.drag;
document.onmouseup=Drag.end;
return false;
},
drag: function (e) {
e=Drag.fixE(e);
var o=Drag.obj;
var ex=e.clientX;
var x=parseInt(o.hmode?o.style.left:o.style.right);
var nx;
if(o.minX!=null) { ex=o.hmode?Math.max(ex,o.minMouseX):Math.min(ex,o.maxMouseX); }
if(o.maxX!=null) { ex=o.hmode?Math.min(ex,o.maxMouseX):Math.max(ex,o.minMouseX); }
nx=x+((ex-o.lastMouseX)*(o.hmode?1:-1));
$i("scrollcontent").style[o.hmode?"left":"right"]=(-nx*barUnitWidth)+"px";
Drag.obj.style[o.hmode?"left":"right"]=nx+"px";
Drag.obj.lastMouseX=ex;
Drag.obj.onDrag(nx);
return false;
},
startLeft: function () {
Drag.leftTime=setInterval("Drag.scrollLeft()",1);
},
scrollLeft: function () {
var c=$i("scrollcontent");
var o=$i("scrollbar");
if((parseInt(o.style.left.replace("px",""))<(590-162-10))&&(parseInt(o.style.left.replace("px",""))>=0)) {
o.style.left=(parseInt(o.style.left.replace("px",""))+1)+"px";
c.style.left=(-(parseInt(o.style.left.replace("px",""))+1)*barUnitWidth)+"px";
} else {
Drag.stopLeft();
}
},
stopLeft: function () {
clearInterval(Drag.leftTime);
},
startRight: function () {
Drag.rightTime=setInterval("Drag.scrollRight()",1);
},
scrollRight: function () {
var c=$i("scrollcontent");
var o=$i("scrollbar");
if((parseInt(o.style.left.replace("px",""))<=(590-162-10))&&(parseInt(o.style.left.replace("px",""))>0)) {
o.style.left=(parseInt(o.style.left.replace("px",""))-1)+"px";
c.style.left=(-(parseInt(o.style.left.replace("px",""))-1)*barUnitWidth)+"px";
} else {
Drag.stopRight();
}
},
stopRight: function () {
clearInterval(Drag.rightTime);
},
end: function () {
document.onmousemove=null;
document.onmouseup=null;
Drag.obj.onDragEnd(parseInt(Drag.obj.style[Drag.obj.hmode?"left":"right"]));
Drag.obj=null;
},
fixE: function (e) {
if(typeof e=='undefined') { e=window.event; }
if(typeof e.layerX=='undefined') { e.layerX=e.offsetX; }
return e;
}
};
var scrollbar = $i('scrollbar');
var scrollleft = $i('scrollleft');
var scrollright = $i('scrollright');
$("#scrollcontent").css({ width: '600px', left: '-0px', position:'absolute'});
var _tmp1="",_tmp2="",data=slideJSON;
$.each(data,function(i){
_tmp1+='<li><a href="'+data[i].link+'"><img title="'+data[i].title+'" src="'+data[i].img+'"></a></li>';
if(i==$CurrentPage-1){
_tmp2+='<li><a href="'+data[i].link+'"><img title="'+data[i].title+'" src="'+data[i].img+'" class="current"></a></li>';
}else{
_tmp2+='<li><a href="'+data[i].link+'"><img title="'+data[i].title+'" src="'+data[i].img+'"></a></li>';
}
});
$("#imagelist").html(_tmp1);
$("#scrollcontent").html(_tmp2);
if($TotalPage>5){
if(scrollbar&&scrollright){
Drag.init(scrollbar,0,418,scrollleft,scrollright);
}
var scrollcontentWidth = (118*$TotalPage+120)+'px';
var scrollcontentLeft = '-0px';
var scroolbarLeft = '0px';
if($CurrentPage>3){
var $$CurrentPage = ($CurrentPage+2>$TotalPage)? ($TotalPage-5): ($CurrentPage-3);
scrollcontentLeft = '-'+(118*$$CurrentPage)+'px';
scroolbarLeft = ((118*$$CurrentPage)/barUnitWidth)+'px';
}
$("#scrollcontent").css({ width: scrollcontentWidth, left: scrollcontentLeft});
$("#scrollbar").css({ left: scroolbarLeft});
}
else{
$("#scrollleft").hide();
$("#scrollright").hide();
$("#scrollbar img").hide();
}
|
'use strict';
const $ = use('chalk', 'syncy');
function task(done) {
$.syncy([
'app/fonts/**',
'app/images/**/*.{gif,jpg,png,svg}',
'app/{scripts,styles}/vendor/**',
'app/*'
], 'build', {
base: 'app',
ignoreInDest: [
'styles/*.{css,map}',
'scripts/*.{js,map}',
'*.html'
]
})
.then(() => {
done();
}).catch(function(err) {
$.helper.errorHandler(err, this, done, (err) => {
console.log($.chalk.red('>> ') + err);
});
});
}
module.exports = {
task
};
|
const ADD_TODO = 'ADD_TODO';
const TOGGLE_TODO = 'TOGGLE_TODO';
const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER';
const SHOW_ALL = 'SHOW_ALL';
const todo = (state = {}, action) => {
switch (action.type) {
case ADD_TODO:
return {
id: action.id,
text: action.text,
completed: false
};
case TOGGLE_TODO:
if (state.id !== action.id) {
return state;
}
return {
...state,
completed: !state.completed
};
default:
return state;
}
};
const initialState = {
todos: [],
filter: SHOW_ALL
};
export default function reducer(state = initialState, action) {
let todos;
switch (action.type) {
case ADD_TODO:
todos = [todo(undefined, action), ...state.todos];
return {
...state,
filter: SHOW_ALL,
todos
};
case TOGGLE_TODO:
todos = state.todos.map(td =>
todo(td, action)
);
return {
...state,
todos
};
case SET_VISIBILITY_FILTER:
return {
...state,
filter: action.filter,
todos: [...state.todos]
};
default:
return state;
}
}
export function addTodo(id, text) {
return {
type: ADD_TODO,
id,
text
};
}
export function toggleTodo(id) {
return {
type: TOGGLE_TODO,
id
};
}
export function setVisibilityFilter(filter) {
return {
type: SET_VISIBILITY_FILTER,
filter
};
}
|
import { createStore, compose, applyMiddleware } from 'redux';
import reduxImmutableStateInvariant from 'redux-immutable-state-invariant';
import thunk from 'redux-thunk';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';
import rootReducer from '../reducers';
const client = axios.create({
//all axios can be used, shown in axios documentation
baseURL: '/api/',
responseType: 'json'
});
function configureStoreProd(initialState) {
const middlewares = [
// Add other middleware on this line...
// thunk middleware can also accept an extra argument to be passed to each thunk action
// https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
thunk,
axiosMiddleware(client)
];
return createStore(
rootReducer,
initialState,
compose(applyMiddleware(...middlewares))
);
}
function configureStoreDev(initialState) {
const middlewares = [
// Add other middleware on this line...
// Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches.
reduxImmutableStateInvariant(),
// thunk middleware can also accept an extra argument to be passed to each thunk action
// https://github.com/gaearon/redux-thunk#injecting-a-custom-argument
thunk,
axiosMiddleware(client)
];
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for Redux dev tools
const store = createStore(
rootReducer,
initialState,
composeEnhancers(applyMiddleware(...middlewares))
);
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('../reducers', () => {
const nextReducer = require('../reducers').default; // eslint-disable-line global-require
store.replaceReducer(nextReducer);
});
}
return store;
}
const configureStore =
process.env.NODE_ENV === 'production'
? configureStoreProd
: configureStoreDev;
export default configureStore;
|
/* eslint-disable security/detect-object-injection */
const path = require("path").posix;
const { calculateInstability, metricsAreCalculable } = require("../module-utl");
const {
getAfferentCouplings,
getEfferentCouplings,
getParentFolders,
object2Array,
} = require("./utl");
function upsertCouplings(pAllDependents, pNewDependents) {
pNewDependents.forEach((pNewDependent) => {
pAllDependents[pNewDependent] = pAllDependents[pNewDependent] || {
count: 0,
};
pAllDependents[pNewDependent].count += 1;
});
}
function upsertFolderAttributes(pAllMetrics, pModule, pDirname) {
pAllMetrics[pDirname] = pAllMetrics[pDirname] || {
dependencies: {},
dependents: {},
moduleCount: 0,
};
upsertCouplings(
pAllMetrics[pDirname].dependents,
getAfferentCouplings(pModule, pDirname)
);
upsertCouplings(
pAllMetrics[pDirname].dependencies,
getEfferentCouplings(pModule, pDirname).map(
(pDependency) => pDependency.resolved
)
);
pAllMetrics[pDirname].moduleCount += 1;
return pAllMetrics;
}
function aggregateToFolder(pAllFolders, pModule) {
getParentFolders(path.dirname(pModule.source)).forEach((pParentDirectory) =>
upsertFolderAttributes(pAllFolders, pModule, pParentDirectory)
);
return pAllFolders;
}
function sumCounts(pAll, pCurrent) {
return pAll + pCurrent.count;
}
function getFolderLevelCouplings(pCouplingArray) {
return Array.from(
new Set(
pCouplingArray.map((pCoupling) =>
path.dirname(pCoupling.name) === "."
? pCoupling.name
: path.dirname(pCoupling.name)
)
)
).map((pCoupling) => ({ name: pCoupling }));
}
function calculateFolderMetrics(pFolder) {
const lModuleDependents = object2Array(pFolder.dependents);
const lModuleDependencies = object2Array(pFolder.dependencies);
// this calculation might look superfluous (why not just .length the dependents
// and dependencies?), but it isn't because there can be > 1 relation between
// two folders
const lAfferentCouplings = lModuleDependents.reduce(sumCounts, 0);
const lEfferentCouplings = lModuleDependencies.reduce(sumCounts, 0);
return {
...pFolder,
afferentCouplings: lAfferentCouplings,
efferentCouplings: lEfferentCouplings,
instability: calculateInstability(lEfferentCouplings, lAfferentCouplings),
dependents: getFolderLevelCouplings(lModuleDependents),
dependencies: getFolderLevelCouplings(lModuleDependencies),
};
}
function findFolderByName(pAllFolders, pName) {
return pAllFolders.find((pFolder) => pFolder.name === pName);
}
function denormalizeInstability(pFolder, _, pAllFolders) {
return {
...pFolder,
dependencies: pFolder.dependencies.map((pDependency) => {
const lFolder = findFolderByName(pAllFolders, pDependency.name) || {};
return {
...pDependency,
instability: lFolder.instability >= 0 ? lFolder.instability : 0,
};
}),
};
}
module.exports = function aggregateToFolders(pModules) {
const lFolders = object2Array(
pModules.filter(metricsAreCalculable).reduce(aggregateToFolder, {})
).map(calculateFolderMetrics);
return lFolders.map(denormalizeInstability);
};
|
/*
* grunt-tankipas
* https://github.com/Leny/grunt-tankipas
*
* Copyright (c) 2014 Leny
* Licensed under the MIT license.
*/
"use strict";
var chalk, error, spinner, tankipas;
tankipas = require("tankipas");
chalk = require("chalk");
error = chalk.bold.red;
(spinner = require("simple-spinner")).change_sequence(["◓", "◑", "◒", "◐"]);
module.exports = function(grunt) {
var tankipasTask;
tankipasTask = function() {
var fNext, oOptions;
fNext = this.async();
oOptions = this.options({
system: null,
gap: 120,
user: null,
branch: null,
commit: null,
raw: false
});
spinner.start(50);
return tankipas(process.cwd(), oOptions, function(oError, iTotal) {
var iHours, iMinutes, sUserString;
spinner.stop();
if (oError) {
grunt.log.error(oError);
fNext(false);
}
if (oOptions.raw) {
grunt.log.writeln(iTotal);
} else {
iTotal /= 1000;
iMinutes = (iMinutes = Math.floor(iTotal / 60)) > 60 ? iMinutes % 60 : iMinutes;
iHours = Math.floor(iTotal / 3600);
sUserString = oOptions.user ? " (for " + (chalk.cyan(oOptions.user)) + ")" : "";
grunt.log.writeln("Time spent on project" + sUserString + ": ±" + (chalk.yellow(iHours)) + " hours & " + (chalk.yellow(iMinutes)) + " minutes.");
}
return fNext();
});
};
if (grunt.config.data.tankipas) {
return grunt.registerMultiTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask);
} else {
return grunt.registerTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask);
}
};
|
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '../',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
files: [
'node_modules/jquery/dist/jquery.js',
'node_modules/angular/angular.js',
'node_modules/angular-sanitize/angular-sanitize.js',
'node_modules/angular-ui-bootstrap/ui-bootstrap-tpls.js',
'node_modules/angular-translate/dist/angular-translate.js',
'node_modules/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
'node_modules/angular-mocks/angular-mocks.js',
'node_modules/openlayers/build/ol-custom.js',
'src/anol/anol.js',
'src/anol/helper.js',
'src/anol/layer.js',
'src/anol/layer/basewms.js',
'src/anol/layer/feature.js',
'src/anol/layer/staticgeojson.js',
'src/anol/**/*.js',
'src/modules/module.js',
'src/modules/**/module.js',
'src/modules/**/*.js',
'test/spec/**/*.js',
'src/modules/**/*.html'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"src/modules/**/*.html": ["ng-html2js"]
},
ngHtml2JsPreprocessor: {
// the name of the Angular module to create
moduleName: "mocked-templates"
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently installed from us:
// - Chrome
// - Firefox
// - Safari (only Mac)
// - PhantomJS
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
|
// test: indent_only
const
foo
=
1
+
2
;
const foo =
[1, 2];
const foo = [
1, 2];
const foo =
{a, b};
const foo = {
a, b};
someMethod(foo, [
0, 1, 2,], bar);
someMethod(
foo,
[0, 1, 2,],
bar);
someMethod(foo, [
0, 1,
2,
], bar);
someMethod(
foo,
[
1, 2],);
someMethod(
foo,
[1, 2],
);
someMethod(foo, {
a: 1, b: 2,}, bar);
someMethod(
foo,
{a: 1, b: 2,},
bar);
someMethod(foo, {
a: 1, b: 2
}, bar);
someMethod(
foo,
{
a: 1, b: 2},);
someMethod(
foo,
{a: 1, b: 2},
);
someMethod(a =>
a*2
);
someMethod(a => {
a*2}
);
foo()
.bar(a => a*2);
foo().bar(a =>
a*2);
foo =
function() {
};
foo =
function() {
};
switch (foo) {
case 1: return b;}
switch (foo) {
case 1:
return b;}
class Foo {
}
class Foo {
bar(
) {}
}
class Foo {
bar() {
}
}
if (x) {
statement;
more;
}
|
/*
* Snapshot multiple pages using arrays.
*
* Use an array to snapshot specific urls.
* Use per-page selectors.
* Use per-page output paths.
* Remove all script tags from output.
* Use javascript arrays.
*/
var path = require("path");
var util = require("util");
var assert = require("assert");
var htmlSnapshots = require("html-snapshots");
// a data structure with snapshot input
var sites = [
{
label: "html5rocks",
url: "http://html5rocks.com",
selector: ".latest-articles"
},
{
label: "updates.html5rocks",
url: "http://updates.html5rocks.com",
selector: ".articles-list"
}
];
htmlSnapshots.run({
// input source is the array of urls to snapshot
input: "array",
source: sites.map(function(site) { return site.url; }),
// setup and manage the output
outputDir: path.join(__dirname, "./tmp"),
outputDirClean: true,
// per url output paths, { url: outputpath [, url: outputpath] }
outputPath: sites.reduce(function(prev, curr) {
prev[curr.url] = curr.label; // use the label to differentiate '/index.html' from both sites
return prev;
}, {}),
// per url selectors, { url: selector [, url: selector] }
selector: sites.reduce(function(prev, curr) {
prev[curr.url] = curr.selector;
return prev;
}, {}),
// remove all script tags from the output
snapshotScript: {
script: "removeScripts"
}
}, function(err, completed) {
console.log("completed snapshots:");
console.log(util.inspect(completed));
// throw if there was an error
assert.ifError(err);
});
|
/*!
* Office for Experience Design v1.0.0 (http://ing-experience-design.com/)
* Copyright 2016 ING, Office for Experience Design
* Licensed under MIT (https://spdx.org/licenses/MIT)
*/
|
var async = require('async'),
fs = require('graceful-fs'),
path = require('path'),
colors = require('colors'),
swig = require('swig'),
spawn = require('child_process').spawn,
util = require('../../util'),
file = util.file2,
commitMessage = require('./util').commitMessage;
// http://git-scm.com/docs/git-clone
var rRepo = /(:|\/)([^\/]+)\/([^\/]+)\.git\/?$/;
module.exports = function(args, callback){
var baseDir = hexo.base_dir,
deployDir = path.join(baseDir, '.deploy'),
publicDir = hexo.public_dir;
if (!args.repo && !args.repository){
var help = '';
help += 'You should configure deployment settings in _config.yml first!\n\n';
help += 'Example:\n';
help += ' deploy:\n';
help += ' type: github\n';
help += ' repo: <repository url>\n';
help += ' branch: [branch]\n';
help += ' message: [message]\n\n';
help += 'For more help, you can check the docs: ' + 'http://hexo.io/docs/deployment.html'.underline;
console.log(help);
return callback();
}
var url = args.repo || args.repository;
if (!rRepo.test(url)){
hexo.log.e(url + ' is not a valid repository URL!');
return callback();
}
var branch = args.branch;
if (!branch){
var match = url.match(rRepo),
username = match[2],
repo = match[3],
rGh = new RegExp('^' + username + '\\.github\\.[io|com]', 'i');
// https://help.github.com/articles/user-organization-and-project-pages
if (repo.match(rGh)){
branch = 'master';
} else {
branch = 'gh-pages';
}
}
var run = function(command, args, callback){
var cp = spawn(command, args, {cwd: deployDir});
cp.stdout.on('data', function(data){
process.stdout.write(data);
});
cp.stderr.on('data', function(data){
process.stderr.write(data);
});
cp.on('close', callback);
};
async.series([
// Set up
function(next){
fs.exists(deployDir, function(exist){
if (exist && !args.setup) return next();
hexo.log.i('Setting up GitHub deployment...');
var commands = [
['init'],
['add', '-A', '.'],
['commit', '-m', 'First commit']
];
if (branch !== 'master') commands.push(['branch', '-M', branch]);
commands.push(['remote', 'add', 'github', url]);
file.writeFile(path.join(deployDir, 'placeholder'), '', function(err){
if (err) callback(err);
async.eachSeries(commands, function(item, next){
run('git', item, function(code){
if (code === 0) next();
});
}, function(){
if (!args.setup) next();
});
});
});
},
function(next){
hexo.log.i('Clearing .deploy folder...');
file.emptyDir(deployDir, next);
},
function(next){
hexo.log.i('Copying files from public folder...');
file.copyDir(publicDir, deployDir, next);
},
function(next){
var commands = [
['add', '-A'],
['commit', '-m', commitMessage(args)],
['push', '-u', 'github', branch, '--force']
];
async.eachSeries(commands, function(item, next){
run('git', item, function(){
next();
});
}, next);
}
], callback);
};
|
// config.pro.spec.js
import config from '../../../src/constants/config.pro'
describe('Config PRO constants', function () {
test('exist', () => {
expect(config).toMatchSnapshot()
})
})
|
const DrawCard = require('../../drawcard.js');
class VaesTolorro extends DrawCard {
setupCardAbilities(ability) {
this.interrupt({
when: {
onCharacterKilled: event => event.card.getPower() >= 1
},
cost: ability.costs.kneelSelf(),
handler: context => {
let pendingCard = context.event.card;
let power = pendingCard.getPower() >= 2 && pendingCard.getStrength() === 0 ? 2 : 1;
pendingCard.modifyPower(-power);
this.modifyPower(power);
this.game.addMessage('{0} kneels {1} to move {2} power from {3} to {1}',
this.controller, this, power, pendingCard);
}
});
}
}
VaesTolorro.code = '04074';
module.exports = VaesTolorro;
|
//~ name a361
alert(a361);
//~ component a362.js
|
const fs = require("fs");
module.exports = function (config) {
var mod = require("./mod.js")(config);
config[mod.name] = mod;
function tryPatchComponent(componentName) {
if (config[componentName] && fs.existsSync(`${__dirname}/${componentName}.js`)) {
require(`./${componentName}`)(config, mod);
}
}
tryPatchComponent("engine");
tryPatchComponent("backend");
tryPatchComponent("driver");
tryPatchComponent("cli");
tryPatchComponent("cronjobs");
};
|
/*jshint quotmark: false*/
'use strict';
var Blueprint = require('../models/blueprint');
var Task = require('../models/task');
var parseOptions = require('../utilities/parse-options');
var merge = require('lodash-node/modern/objects/merge');
module.exports = Task.extend({
run: function(options) {
var blueprint = Blueprint.lookup(options.args[0], {
paths: this.project.blueprintLookupPaths()
});
var entity = {
name: options.args[1],
options: parseOptions(options.args.slice(2))
};
var installOptions = {
target: this.project.root,
entity: entity,
ui: this.ui,
analytics: this.analytics,
project: this.project
};
installOptions = merge(installOptions, options || {});
return blueprint.install(installOptions);
}
});
|
angular.module('app')
.controller('ProgressController', ['$scope', function ($scope) {
$scope.percent = 45;
$scope.setPercent = function(p) {
$scope.percent = p;
}
}])
|
containerRemoveSchemas = new SimpleSchema({
force: {
type: Boolean,
optional:true,
label: "Force"
},
link: {
type: Boolean,
optional:true,
label: "Link"
},
v: {
type: Boolean,
optional:true,
label: "Volumes"
}
,id: {
type: String,
autoform: {
type: 'hidden',
label:false
}
}
,host: {
type: String,
autoform: {
type: 'hidden',
label:false
}
}
});
if (Meteor.isClient){
AutoForm.hooks({
containerRemoveForm: {
after: {
'method': formNotifier('rm','containers')}
}});
}
|
app.controller('DashboardController',function($scope,$http,Article){
//Pagination configuration
$scope.maxSize = 5;
$scope.numPerPage = 5;
$scope.currentPage = '1';
$scope.isEdit = false;
$scope.isError= false;
$scope.newarticle = {}; // Edit/New panel model
$scope.curArticle = {}; // Currently selected article model
$scope.errors = [];
//Load all articles.
Article.query(function(data){
$scope.articles = data;
},function(error){
console.log(error);
alert('Loading data failed.');
});
//Shows validation errors
function errorHandler(error){
$scope.isError=true; //Show validator error
angular.forEach(error.data,function(key,value){
$scope.errors.push(value + ': ' + key);
});
}
//Open New panel
$scope.newArticle = function(article){
$scope.isEdit=true;
$scope.isError=false;
//Initialize with Article resource
$scope.newarticle = new Article();
};
//Open Edit panel with data on edit button click
$scope.editArticle = function(article){
$scope.isEdit=true;
$scope.isError=false;
// Store selected data for future use
$scope.curArticle = article;
//Copy data to panel
$scope.newarticle = angular.copy(article);
};
//Update and New article
$scope.addArticle = function(article){
//TODO error handling on requests
//Check if update or new
if($scope.curArticle.id){
//Send put resource request
article.$update(function(data){
// Update values to selected article
angular.extend($scope.curArticle,$scope.curArticle,data);
//Hide edit/new panel
$scope.isEdit = false;
},errorHandler);
}else{
//Send post resource request
article.$save(function(data){
//Add newly add article to articles json
$scope.articles.push(data);
//Hide edit/new panel
$scope.isEdit = false;
},errorHandler);
}
//Remove old values
//$scope.newarticle = new Article();
};
//Delete button
$scope.deleteArticle = function(article){
if(confirm('Are you sure ?')){
article.$delete(function(data){
alert(data.msg);
//Get selected article index then remove from articles json
var curIndex = $scope.articles.indexOf(article);
$scope.articles.splice(curIndex,1);
},function(error){
alert('Item not deleted');
console.log(error);
});
}
};
//Cancel panel button
$scope.cancelArticle = function(article){
$scope.isEdit=false;
$scope.isError=false;
//Remove old values
$scope.newarticle= new Article();
};
});
|
/* google-paper.js */
'use strict';
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
var RAD_2_DEG = 180/Math.PI;
function moving_average(period) {
var nums = [];
return function(num) {
nums.push(num);
if (nums.length > period)
nums.splice(0,1);
var sum = 0;
for (var i in nums)
sum += nums[i];
var n = period;
if (nums.length < period)
n = nums.length;
return(sum/n);
}
}
var GP = GP || {};
GP.PaperTracker = function(options){
this.options = options || {};
this.video;
this.canvas;
this.context;
this.camDirection = 'front'; // back
this.imageData;
this.detector;
this.posit;
this.markers;
this.init(options);
};
GP.PaperTracker.prototype.init = function(options){
this.video = document.getElementById('video');
this.canvas = document.getElementById('video-canvas');
this.context = this.canvas.getContext('2d');
this.canvas.width = parseInt(this.canvas.style.width);
this.canvas.height = parseInt(this.canvas.style.height);
this.trackingInfo = {
lastTrackTime: 0,
haveTracking: false,
neverTracked: true,
translation: [0,0,0],
orientation: [0,0,0],
rotation: [0,0,0]
};
this.detector = new AR.Detector();
this.posit = new POS.Posit(this.options.modelSize, this.canvas.width);
};
GP.PaperTracker.prototype.postInit = function(){
var vid = this.video;
navigator.getUserMedia({video:true},
function (stream){
if (window.webkitURL) {
vid.src = window.webkitURL.createObjectURL(stream);
} else if (vid.mozSrcObject !== undefined) {
vid.mozSrcObject = stream;
} else {
vid.src = stream;
}
},
function(error){
console.log('stream not found');
}
);
};
GP.PaperTracker.prototype.snapshot = function(){
this.context.drawImage(this.video, 0, 0, this.canvas.width, this.canvas.height);
this.imageData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
};
GP.PaperTracker.prototype.detect = function(){
var markers = this.detector.detect(this.imageData);
this.markers = markers;
return markers;
};
GP.PaperTracker.prototype.process = function(){
if (this.video.readyState === this.video.HAVE_ENOUGH_DATA){
this.snapshot();
this.detect();
this.drawCorners();
return true;
}
return false;
};
GP.PaperTracker.prototype.drawCorners = function(){
var corners, corner, i, j;
this.context.lineWidth = 3;
for (i = 0; i < this.markers.length; ++ i){
corners = this.markers[i].corners;
this.context.strokeStyle = "red";
this.context.beginPath();
for (j = 0; j < corners.length; ++ j){
corner = corners[j];
this.context.moveTo(corner.x, corner.y);
corner = corners[(j + 1) % corners.length];
this.context.lineTo(corner.x, corner.y);
}
this.context.stroke();
this.context.closePath();
this.context.strokeStyle = "blue";
this.context.strokeRect(corners[0].x - 2, corners[0].y - 2, 4, 4);
}
};
GP.PaperTracker.prototype.updateTracking = function(){
var corners, corner, pose, i;
if (this.markers.length == 0) {
this.trackingInfo.haveTracking = false;
return false;
}
this.trackingInfo.neverTracked = false;
this.trackingInfo.haveTracking = true;
corners = this.markers[0].corners;
for (i = 0; i < corners.length; ++ i){
corner = corners[i];
corner.x = corner.x - (this.canvas.width / 2);
corner.y = (this.canvas.height / 2) - corner.y;
}
pose = this.posit.pose(corners);
var rotation = pose.bestRotation;
var translation = pose.bestTranslation;
this.trackingInfo.translation = translation;
this.trackingInfo.rotation = rotation;
return this.trackingInfo;
};
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* eslint-disable global-require */
// The top-level (parent) route
export default {
path: '/',
// Keep in mind, routes are evaluated in order
children: [
require('./home/index').default,
require('./contact/index').default,
require('./login/index').default,
require('./register/index').default,
require('./admin/index').default,
// Wildcard routes, e.g. { path: '*', ... } (must go last)
require('./content/index').default,
require('./notFound/index').default,
],
async action({ next }) {
// Execute each child route until one of them return the result
const route = await next();
// Provide default values for title, description etc.
route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`;
route.description = route.description || '';
return route;
},
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.utils = exports.default = void 0;
var reducers = _interopRequireWildcard(require("./reducers"));
var _utils = _interopRequireWildcard(require("./utils"));
exports.utils = _utils;
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var _default = reducers;
exports.default = _default;
|
///////////////////////////////////////////////////////////////////////////////
//
// Effect
//
///////////////////////////////////////////////////////////////////////////////
//// IMPORTS //////////////////////////////////////////////////////////////////
import { toJs } from 'mori';
import diff from 'virtual-dom/diff';
import patch from 'virtual-dom/patch';
import stateStream from '../streams/state';
///////////////////////////////////////////////////////////////////////////////
// :: DOMNode node, Function stateToModel, Function modelToVDOM
// -> Effectful Eventstream that will mutate the node as state changes,
// mapping the state to a model that is rendered to a virtual DOM, and
// patched to the DOM.
// Note - the Effectful EventStream will need a subscriber to start.
export default (node, stateToModel, modelToVDOM) => {
return stateStream
.map(toJs)
.map(stateToModel)
.map(modelToVDOM)
.diff(node, diff)
.scan(node, patch);
};
///////////////////////////////////////////////////////////////////////////////
|
if (typeof global === 'undefined') {
global = window;
} else {
global.XRegExp = require('../../xregexp-all');
}
// Ensure that all opt-in features are disabled when each spec starts
global.disableOptInFeatures = function() {
XRegExp.uninstall('namespacing astral');
};
// Property name used for extended regex instance data
global.REGEX_DATA = 'xregexp';
// Check for ES6 `u` flag support
global.hasNativeU = XRegExp._hasNativeFlag('u');
// Check for ES6 `y` flag support
global.hasNativeY = XRegExp._hasNativeFlag('y');
// Check for strict mode support
global.hasStrictMode = (function() {
'use strict';
return !this;
}());
// Naive polyfill of String.prototype.repeat
if (!String.prototype.repeat) {
String.prototype.repeat = function(count) {
return count ? Array(count + 1).join(this) : '';
};
}
|
'use strict';
let datafire = require('datafire');
let openapi = require('./openapi.json');
let aws = require('aws-sdk');
const INTEGRATION_ID = 'amazonaws_data_jobs_iot';
const SDK_ID = 'IoTJobsDataPlane';
let integ = module.exports = new datafire.Integration({
id: INTEGRATION_ID,
title: openapi.info.title,
description: openapi.info.description,
logo: openapi.info['x-logo'],
});
integ.security[INTEGRATION_ID]= {
integration: INTEGRATION_ID,
fields: {
accessKeyId: "",
secretAccessKey: "",
region: "AWS region (if applicable)",
}
}
function maybeCamelCase(str) {
return str.replace(/_(\w)/g, (match, char) => char.toUpperCase())
}
// We use this instance to make sure each action is available in the SDK at startup.
let dummyInstance = new aws[SDK_ID]({version: openapi.version, endpoint: 'foo'});
for (let path in openapi.paths) {
for (let method in openapi.paths[path]) {
if (method === 'parameters') continue;
let op = openapi.paths[path][method];
let actionID = op.operationId;
actionID = actionID.replace(/\d\d\d\d_\d\d_\d\d$/, '');
if (actionID.indexOf('_') !== -1) {
actionID = actionID.split('_')[1];
}
let functionID = actionID.charAt(0).toLowerCase() + actionID.substring(1);
if (!dummyInstance[functionID]) {
console.error("AWS SDK " + SDK_ID + ": Function " + functionID + " not found");
console.log(method, path, op.operationId, actionID);
continue;
}
let inputParam = (op.parameters || []).filter(p => p.in === 'body')[0] || {};
let response = (op.responses || {})[200] || {};
let inputSchema = {
type: 'object',
properties: {},
};
if (inputParam.schema) inputSchema.allOf = [inputParam.schema];
(op.parameters || []).forEach(p => {
if (p.name !== 'Action' && p.name !== 'Version' && p.name !== 'body' && !p.name.startsWith('X-')) {
inputSchema.properties[maybeCamelCase(p.name)] = {type: p.type};
if (p.required) {
inputSchema.required = inputSchema.required || [];
inputSchema.required.push(p.name);
}
}
})
function getSchema(schema) {
if (!schema) return;
return Object.assign({definitions: openapi.definitions}, schema);
}
integ.addAction(actionID, new datafire.Action({
inputSchema: getSchema(inputSchema),
outputSchema: getSchema(response.schema),
handler: (input, context) => {
let lib = new aws[SDK_ID](Object.assign({
version: openapi.info.version,
}, context.accounts[INTEGRATION_ID]));
return lib[functionID](input).promise()
.then(data => {
return JSON.parse(JSON.stringify(data));
})
}
}));
}
}
|
'use strict';
exports.__esModule = true;
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'); } }
var _jquery = require('jquery');
var _jquery2 = _interopRequireDefault(_jquery);
require('./loading-mask.css!');
var _locale = require('../locale');
var LoadingMask = (function () {
function LoadingMask(resources) {
_classCallCheck(this, LoadingMask);
this.loadingMask = undefined;
this.dimScreen = undefined;
this.dialog = undefined;
this.loadingTitle = undefined;
this.title = undefined;
this.locale = _locale.Locale.Repository['default'];
this._createLoadingMask();
}
LoadingMask.prototype._createLoadingMask = function _createLoadingMask() {
this.title = this.locale.translate('loading');
this.dimScreen = '<div id="loadingMask" class="spinner"><div class="loadingTitle">' + this.title + '</div><div class="mask"></div></div>';
(0, _jquery2['default'])('body').append(this.dimScreen);
this.loadingMask = (0, _jquery2['default'])('#loadingMask');
this.loadingTitle = (0, _jquery2['default'])('.loadingTitle').css({
color: '#ffffff',
opacity: 1,
fontSize: '2.5em',
fontFamily: 'Roboto'
});
};
LoadingMask.prototype.show = function show() {
this.loadingMask.show();
};
LoadingMask.prototype.hide = function hide() {
this.loadingMask.hide();
};
return LoadingMask;
})();
exports.LoadingMask = LoadingMask;
|
var five = require("johnny-five"),
board = new five.Board();
board.on("ready", function() {
var led = new five.Led(12);
var rgb = new five.Led.RGB([6, 5, 3]);
var index = 0;
this.loop(10, function() {
// led.toggle();
if (index === 16777215) {
index = 0;
}
rgb.color(index.toString(16));
index++;
});
});
// var led = new five.Led(13);
// led.blink(5);
|
var mysql = require('mysql');
var bcrypt = require('bcryptjs');
var connection = mysql.createConnection({
host: process.env.FOLIO_HOST,
user: process.env.FOLIO_USER,
database: process.env.FOLIO_DATABASE,
password: process.env.FOLIO_PASSWORD
});
console.log("[*] Database connection open")
console.log("[*] Resetting username and password");
connection.query("TRUNCATE users;");
console.log("[*] Creating default user, admin (username), password (password)");
var passwordhash = bcrypt.hashSync("password", 10);
console.log("\t[>] Password hash: " + passwordhash);
connection.query("INSERT INTO users(username, passwordhash) values('admin', '" + passwordhash + "');");
connection.end();
console.log("[*] Finished!");
|
import React from 'react'
import PropTypes from 'prop-types'
import { MarkerCanvasProvider } from './MarkerCanvasContext'
import TimelineMarkersRenderer from './TimelineMarkersRenderer'
import { TimelineStateConsumer } from '../timeline/TimelineStateContext'
// expand to fill entire parent container (ScrollElement)
const staticStyles = {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0
}
/**
* Renders registered markers and exposes a mouse over listener for
* CursorMarkers to subscribe to
*/
class MarkerCanvas extends React.Component {
static propTypes = {
getDateFromLeftOffsetPosition: PropTypes.func.isRequired,
children: PropTypes.node
}
handleMouseMove = evt => {
if (this.subscription != null) {
const { pageX } = evt
// FIXME: dont use getBoundingClientRect. Use passed in scroll amount
const { left: containerLeft } = this.containerEl.getBoundingClientRect()
// number of pixels from left we are on canvas
// we do this calculation as pageX is based on x from viewport whereas
// our canvas can be scrolled left and right and is generally outside
// of the viewport. This calculation is to get how many pixels the cursor
// is from left of this element
const canvasX = pageX - containerLeft
const date = this.props.getDateFromLeftOffsetPosition(canvasX)
this.subscription({
leftOffset: canvasX,
date,
isCursorOverCanvas: true
})
}
}
handleMouseLeave = () => {
if (this.subscription != null) {
// tell subscriber that we're not on canvas
this.subscription({ leftOffset: 0, date: 0, isCursorOverCanvas: false })
}
}
handleMouseMoveSubscribe = sub => {
this.subscription = sub
return () => {
this.subscription = null
}
}
state = {
subscribeToMouseOver: this.handleMouseMoveSubscribe
}
render() {
return (
<MarkerCanvasProvider value={this.state}>
<div
style={staticStyles}
onMouseMove={this.handleMouseMove}
onMouseLeave={this.handleMouseLeave}
ref={el => (this.containerEl = el)}
>
<TimelineMarkersRenderer />
{this.props.children}
</div>
</MarkerCanvasProvider>
)
}
}
const MarkerCanvasWrapper = props => (
<TimelineStateConsumer>
{({ getDateFromLeftOffsetPosition }) => (
<MarkerCanvas
getDateFromLeftOffsetPosition={getDateFromLeftOffsetPosition}
{...props}
/>
)}
</TimelineStateConsumer>
)
export default MarkerCanvasWrapper
|
const mongoose = require('mongoose')
const Schema = mongoose.Schema
let AgencySchema = new Schema({
})
module.exports = mongoose.model('Agency', AgencySchema)
|
const mix = require('laravel-mix');
mix
.js('resources/assets/app.js', 'public/js')
.extract(['vue', 'lodash'])
;
|
window.test = 1;
|
const express = require('express'),
handler = require('../handlers/sitemap'),
requestHelper = require('../helpers/request-helper'),
router = express.Router();
router.get('/', requestHelper.cache(), (req, res, next) => {
requestHelper.initRouter({
req: req,
res: res,
handler: handler,
endPointParams: {
posts: '?system.type=blog_post&order=elements.date[desc]&elements=url_slug'
},
view: 'sitemap'
});
});
module.exports = router;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var TooltipDelay;
(function (TooltipDelay) {
TooltipDelay[TooltipDelay["zero"] = 0] = "zero";
TooltipDelay[TooltipDelay["medium"] = 1] = "medium";
})(TooltipDelay = exports.TooltipDelay || (exports.TooltipDelay = {}));
//# sourceMappingURL=Tooltip.Props.js.map
|
require("./71.js");
require("./143.js");
require("./286.js");
require("./571.js");
module.exports = 572;
|
var joi = require('joi');
var _ = require('lodash');
module.exports = function(router, db) {
// This is our "class" that accesses/modifies notes in the db
var NoteService = require('../lib/db-notes')
var noteService = new NoteService(db);
// Joi is a wonderful library that takes strings and converts them into the proper
// type while validating them. Anyone who works with query strings knows this is
// usually a painfully dull process, and this makes that 10x easier.
var querySchema = joi.object().keys({
limit: joi.number().integer().min(1).max(1000),
skip: joi.number().integer().min(0),
field: joi.string().valid(["createdBy", "note", "lastModified"]),
value: joi.string().trim(),
sort: joi.valid(["createdBy", "note"]),
order: joi.number().valid([1, -1])
}).and(['sort', 'order']).and('field','value');
// Read list
router.get('/api/notes', function(req, res, next) {
joi.validate(req.query, querySchema, function(err, queryString) {
var query = {}, options = {};
if(err) return next(err);
if(_.isEmpty(queryString)) {
options.sort = { 'lastModified': -1 };
query = {};
} else {
query = setQuery(queryString.field, queryString.value);
if(queryString.sort) options.sort[queryString.sort] = queryString.order;
options.limit = queryString.limit;
options.skip = queryString.skip;
}
noteService.list(query, options, function(err, users) {
if(err) return next(err);
res.send(users);
});
});
});
/**
* Adds a note. The lastModified date is handled automatically.
*/
router.post('/api/notes', function(req, res, next) {
var note;
note = {
createdBy: req.body.name,
note: req.body.note
};
noteService.add(note, function(err, result) {
if(err) {
if(err.message ==='Validation failed') {
return res.send(400, err);
}
return next(err);
}
if(result === null) {
return res.send(400, { error: { message: 'Note does not exist' }});
}
// Doesn't belong in the api really, but for quickly getting this working:
if(req.accepts(['html', 'json']) === 'html') return res.redirect('/notes');
res.send(200, result);
});
});
/**
* Updates a note.
* TODO: Not yet used and tested
*/
router.put('/api/notes/:id', function(req, res, next) {
var id;
try{
id = ObjectID(req.params.id);
}catch(err) {
return res.send(400, {error: err.message});
}
noteService.updateNote(id, req.body, function(err, result) {
if(err) return next(err);
if(result === 0) {
return res.send(400, { error: 'Note `' + req.params.id + '` does not exist' });
}
res.json(200, null);
});
});
/**
* Deletes a note from the db
*/
router.delete('/api/notes/:id', function(req, res, next) {
noteService.remove(req.params.id, function(err, result) {
if(err) return next(err);
if(result === 0) {
return res.send(400, { error: 'Note `' + req.params.id + '` does not exist' });
}
res.json(200, null);
});
});
};
|
'use strict';
var twoSum = require('../src/two-sum/naive');
describe('twoSum naive', function () {
it('should return undefined when called on an empty array', function () {
expect(twoSum([], 1)).toBe(undefined);
});
it('should return correct result when it exists in sorted lists', function () {
expect(twoSum([1, 2, 4, 8, 16], 3)).toEqual([0, 1]);
expect(twoSum([1, 2, 4, 8, 16], 6)).toEqual([1, 2]);
expect(twoSum([1, 2, 4, 8, 16], 17)).toEqual([0, 4]);
expect(twoSum([1, 2, 4, 8, 16], 20)).toEqual([2, 4]);
expect(twoSum([1, 2, 4, 8, 16], 24)).toEqual([3, 4]);
});
it('should return correct result when it exists in a jumbled lists', function () {
expect(twoSum([16, 1, 4, 2, 8], 3)).toEqual([1, 3]);
expect(twoSum([16, 1, 4, 2, 8], 6)).toEqual([2, 3]);
expect(twoSum([16, 1, 4, 2, 8], 17)).toEqual([0, 1]);
expect(twoSum([16, 1, 4, 2, 8], 20)).toEqual([0, 2]);
expect(twoSum([16, 1, 4, 2, 8], 24)).toEqual([0, 4]);
});
});
|
module.exports = {
description: "",
ns: "react-material-ui",
type: "ReactNode",
dependencies: {
npm: {
"material-ui/svg-icons/image/photo-size-select-actual": require('material-ui/svg-icons/image/photo-size-select-actual')
}
},
name: "ImagePhotoSizeSelectActual",
ports: {
input: {},
output: {
component: {
title: "ImagePhotoSizeSelectActual",
type: "Component"
}
}
}
}
|
import _ from 'lodash/fp'
export const TYPES = {
ADDON: 'addon',
COLLECTION: 'collection',
ELEMENT: 'element',
VIEW: 'view',
MODULE: 'module',
}
const TYPE_VALUES = _.values(TYPES)
/**
* Determine if an object qualifies as a META object.
* It must have the required keys and valid values.
* @private
* @param {Object} _meta A proposed Stardust _meta object.
* @returns {Boolean}
*/
export const isMeta = (_meta) => (
_.includes(_.get('type', _meta), TYPE_VALUES)
)
/**
* Extract the Stardust _meta object and optional key.
* Handles literal _meta objects, classes with _meta, objects with _meta
* @private
* @param {function|object} metaArg A class, a component instance, or meta object..
* @returns {object|string|undefined}
*/
const getMeta = (metaArg) => {
// literal
if (isMeta(metaArg)) return metaArg
// from prop
else if (isMeta(_.get('_meta', metaArg))) return metaArg._meta
// from class
else if (isMeta(_.get('constructor._meta', metaArg))) return metaArg.constructor._meta
}
const metaHasKeyValue = _.curry((key, val, metaArg) => _.flow(getMeta, _.get(key), _.eq(val))(metaArg))
export const isType = metaHasKeyValue('type')
// ----------------------------------------
// Export
// ----------------------------------------
// type
export const isAddon = isType(TYPES.ADDON)
export const isCollection = isType(TYPES.COLLECTION)
export const isElement = isType(TYPES.ELEMENT)
export const isView = isType(TYPES.VIEW)
export const isModule = isType(TYPES.MODULE)
// parent
export const isParent = _.flow(getMeta, _.has('parent'), _.eq(false))
export const isChild = _.flow(getMeta, _.has('parent'))
// other
export const isPrivate = _.flow(getMeta, _.get('name'), _.startsWith('_'))
|
var Backbone = require('backbone'),
_ = require('underscore');
global.App = {};
App.Task = Backbone.Model.extend({
url : 'http://localhost:9292/tasks/' + this.get('id'),
defaults : {
title: 'Untitled Task 1',
done : false
}
});
App.TaskCollection = Backbone.collection.extend({
model : Task,
urlRoot : 'http://localhost:9292/tasks'
});
App.TaskView = Backbone.View.extend({
tagName : 'li',
className : 'task',
template : _.template(require('./templates/task.html')),
initialize : function() {
this.render();
},
render : function() {
this.$el.html(this.template(this.model.attributes));
this.delegateEvents();
return this;
}
});
App.TaskCollectionView = Backbone.View.extend({
tagName : 'ul',
className : 'task-list',
initialize: function() {
this.render();
},
render : function() {
this.$el.empty();
_.each(this.collection.models, function(task) {
var view = new App.TaskView({model: task});
this.$el.append(view.render().$el);
});
this.delegateEvents();
return this;
}
});
App.Router = Backbone.Router.extend({
routes : {
'(/)' : 'showList'
},
showList: function() {
var tasks = new App.TaskCollection();
var view = new App.TaskCollectionView({collection: tasks});
$('body').html(view.render().el);
}
});
module.exports = App;
|
var model = require(__dirname + '/../models/model.js');
var controller = function() {};
//create new user
function create(id) {
var newUser = new model({
id: id,
currentCowntt: 0,
apiCallsMade: 0
});
return newUser;
}
function getUser(id, cb) {
model.findOne({ //find by unique id
id: id
}, function(err, user) {
if (err) {
console.log(err);
throw new Error('could not query db');
}
if (!user) {//user already existed in database
user = create(id);
}
cb(user);
});
}
function saveUser(user, cb) {
user.save( function(saveErr) {
if (saveErr) {
console.log('saveError saving to debugger: ' + saveErr);
}
cb(user);
});
}
controller.prototype.incrementCowntt = function(id, parentCB) {
getUser(id, function (user) {
user.currentCowntt += 1;
user.apiCallsMade += 1;
saveUser(user, function() {
parentCB(user.currentCowntt);
});
});
};
controller.prototype.decrementCowntt = function(id, parentCB) {
getUser(id, function (user) {
user.currentCowntt -= 1;
user.apiCallsMade += 1;
saveUser(user, function() {
parentCB(user.currentCowntt);
});
});
};
controller.prototype.setCowntt = function(id, setVal, parentCB) {
getUser(id, function (user) {
user.currentCowntt = setVal;
user.apiCallsMade += 1;
saveUser(user, function() {
parentCB(user.currentCowntt);
});
});
};
controller.prototype.getCowntt = function(id, parentCB) {
getUser(id, function (user) {
user.apiCallsMade += 1;
saveUser(user, function() {
});
parentCB(user.currentCowntt);
});
};
module.exports = controller;
|
import React, {PropTypes, Component} from 'react';
import moment from 'moment';
import StyleSheet from 'styles/agenda.styl';
export default class AgendaChart extends Component {
static propTypes = {
items: PropTypes.array,
currentDate: PropTypes.number,
roomName: PropTypes.string
}
render() {
const start = moment().hour(8).minutes(0);
const {currentDate, items, roomName} = this.props;
let currTime;
if (moment(currentDate).isSame(moment(), 'day')) {
currTime = moment().diff(start, 'hours', true);
}
return (
<div className={StyleSheet.container}>
<div className="room-header biggie">
<span className="room-title">
{roomName}
</span>
</div>
<div className="content-container">
{(currTime > 0) &&
<div
className="current-time"
style={{
top: `${currTime * 10}%`
}}/>
}
{items.map(item => {
const morning = moment(currentDate).hour(8).minutes(0);
const fromTop = moment(item.start.dateTime).diff(morning, 'hours', true);
const fromBottom = moment(item.end.dateTime).diff(item.start.dateTime, 'hours', true);
return (
<div
key={`agenda-${item.id}`}
className="agenda-item"
style={{
top: `${(fromTop * 10)}%`,
height: `${(fromBottom * 10)}%`
}}>
<p className="content">
{item.summary} <br/>
{moment(item.start.dateTime).format('h:mm ')}-
{moment(item.end.dateTime).format(' h:mm')}
</p>
</div>
);
})}
</div>
</div>
);
}
}
|
import { tshirtImageVersions, imageVersionProps } from './fragments'
export default `
${imageVersionProps}
${tshirtImageVersions}
{
categoryNav {
id
name
slug
level
tileImage { ...tshirtImageVersions }
}
}
`
|
/**
* Created with JetBrains WebStorm.
* User: yuzhechang
* Date: 13-9-24
* Time: 下午3:47
* To change this template use File | Settings | File Templates.
*/
(function($) {
var ngmod = angular.module("framework.controllers", ["framework.serviceService"]);
ngmod.controller("pageCtrl",function($scope,$rootScope,service_clist_FlistRES){
$scope.abc = "test-data";
$scope.flistData = null;
$scope.selFlist=null ;
//页面数据,回传数据
//modal_onLoad是父controller里的虚方法(面向对象里类的概念)。
// 在这里的实际中是父controller里调用$rootScope.modal_onLoad,在子controller里提供modal_onLoad,并写入到$rootScope中。
$rootScope.modal_onLoad = function(config){
$scope.data = config.data;
if(config.data.rowData)
{
$scope.flistData = config.data.rowData;
$scope.selFlist = config.data.rowData.fieldName;
console.log( $scope.selFlist);
}
// $scope.flistData.position = config.data.rowsNum;
//添加提交按钮的处理事件
config.onSubmitForModal(function(){
console.log("窗口内的提交事件");
// config.resultData = {id:10000,msg:"回传数据"};
config.resultData = $scope.flistData;
return true;
});
}
//获取属性数据
service_clist_FlistRES.get({
},function(structureFlist){
$scope.structureFlist=structureFlist;
console.log(structureFlist);
});
//选择属性事件
$scope.flistChange=function(flistId)
{
var flistjson =eval('('+flistId+')');
$scope.flistData = flistjson;
$scope.flistData.fieldName=flistjson.name;
$scope.flistData.desc=flistjson.description;
$scope.flistData.otherName =flistjson.name;
$scope.flistData.required=$(".J_isMust option:checked").text();
$scope.flistData.position= $scope.data.rowsNum;
}
});
})(jQuery);
|
/**
* Created by Dennis on 08/11/16.
*/
/*
* action types
*/
export const KNOWLEDGEBASE_CHANGE = 'KNOWLEDGEBASE_CHANGE'
/*
* other constants
*/
/*
* action creators
*/
export function setKnowledgebase(k){
return function (dispatch) {
dispatch({type: KNOWLEDGEBASE_CHANGE, knowledgebase: k});
}
}
|
import Component from '@ember/component';
import layout from '../templates/components/slds-dropdown-item';
export default Component.extend({
layout,
tagName: '',
clicked: null,
actions: {
clicked(handler, next) {
if (handler) {
handler(next);
}
}
}
});
|
/**
* Internationalization / Localization Settings
* (sails.config.i18n)
*
* If your app will touch people from all over the world, i18n (or internationalization)
* may be an important part of your international strategy.
*
*
* For more information, check out:
* http://links.sailsjs.org/docs/config/i18n
*/
module.exports.i18n = {
// Which locales are supported?
locales: ['en', 'es', 'fr', 'de'],
objectNotation: true
};
|
import Setting from '../models/setting';
import KhongDau from 'khong-dau';
export function getSettings(req, res) {
Setting.find({ disable: false }).exec((err, settings) => {
if(err) {
res.json({ settings: [] });
} else {
res.json({ settings });
}
})
}
|
/**
* @fileOverview first_run.js shows the necessary navigation and
* design elements to be integrated into the privly-applications
* bundle.
*/
/**
* Initialize the applications by showing and hiding the proper
* elements.
*/
function init() {
// Set the nav bar to the proper domain
privlyNetworkService.initializeNavigation();
privlyNetworkService.initPrivlyService(
privlyNetworkService.contentServerDomain(),
privlyNetworkService.showLoggedInNav,
privlyNetworkService.showLoggedOutNav
);
$("#messages").hide();
$("#form").show();
// Show a preview of the tooltip to the user
$("#tooltip").append(Privly.glyph.getGlyphDOM())
.show()
.append("<br/><br/><p>This is your Privly Glyph</p>");
}
// Initialize the application
document.addEventListener('DOMContentLoaded', init);
|
require("./46.js");
require("./93.js");
require("./186.js");
require("./372.js");
module.exports = 373;
|
var doc = require('dynamodb-doc');
var dynamodb = new doc.DynamoDB();
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, ' '));
var bname = event.name.replace(/\W/g, '');
bname = bname.charAt(0).toUpperCase() + bname.slice(1);
dynamodb.updateItem({
"TableName": "baby-names",
"Key" : {
name : bname
},
"UpdateExpression" : "SET votes = votes + :a",
"ExpressionAttributeValues" : {
":a" : 1
}
}, function(err, data) {
if (err) {
context.done('error putting item into dynamodb failed: '+err);
} else {
console.log('success: '+JSON.stringify(data, null, ' '));
context.done();
}
});
};
|
'use strict';
// Author: ThemeREX.com
// user-interface-buttons.html scripts
//
(function($) {
"use strict";
// Init Theme Core
Core.init();
// Init Demo JS
Demo.init();
// Init Ladda Plugin
Ladda.bind('.ladda-button', {
timeout: 2000
});
// Simulate loading progress on buttons with ".ladda-button" class
Ladda.bind('.progress-button', {
callback: function(instance) {
var progress = 0;
var interval = setInterval(function() {
progress = Math.min(progress + Math.random() * 0.1, 1);
instance.setProgress(progress);
if (progress === 1) {
instance.stop();
clearInterval(interval);
}
}, 200);
}
});
})(jQuery);
|
'use strict';
// Teams controller
angular.module('teams').controller('TeamsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Teams', 'Players', '$filter',
function($scope, $stateParams, $location, Authentication, Teams, Players, $filter) {
$scope.authentication = Authentication;
// Create new Team
$scope.create = function() {
// Create new Team object
var team = new Teams ({
name: this.name
});
// Redirect after save
team.$save(function(response) {
$location.path('teams/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Team
$scope.remove = function(team) {
if ( team ) {
team.$remove();
for (var i in $scope.teams) {
if ($scope.teams [i] === team) {
$scope.teams.splice(i, 1);
}
}
} else {
$scope.team.$remove(function() {
$location.path('teams');
});
}
};
// Update existing Team
$scope.update = function() {
var team = $scope.team;
team.$update(function() {
$location.path('teams/' + team._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Teams
$scope.find = function() {
$scope.teams = Teams.query();
};
// Find existing Team
$scope.findOne = function() {
$scope.team = Teams.get({
teamId: $stateParams.teamId
});
$scope.players = Players.query({
'team': $stateParams.teamId
});
};
}
]);
|
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
/* eslint no-console: ["error", { allow: ["log"] }] */
const gulp = require('gulp');
const modifyFile = require('gulp-modify-file');
const path = require('path');
const rollup = require('rollup');
const buble = require('rollup-plugin-buble');
const replace = require('rollup-plugin-replace');
const commonjs = require('rollup-plugin-commonjs');
const resolve = require('rollup-plugin-node-resolve');
const vue = require('rollup-plugin-vue');
function buildKs(cb) {
const env = process.env.NODE_ENV || 'development';
const target = process.env.TARGET || 'universal';
const buildPath = env === 'development' ? './build' : './packages';
let f7VuePath = path.resolve(__dirname, `../${buildPath}/vue/framework7-vue.esm.js`);
let f7Path = path.resolve(__dirname, `../${buildPath}/core/framework7.esm.bundle`);
if (process.platform.indexOf('win') === 0) {
f7VuePath = f7VuePath.replace(/\\/g, '/');
f7Path = f7Path.replace(/\\/g, '/');
}
gulp.src('./kitchen-sink/vue/index.html')
.pipe(modifyFile((content) => {
if (env === 'development') {
return content
.replace('../../packages/core/css/framework7.min.css', '../../build/core/css/framework7.css')
.replace('../../packages/core/js/framework7.min.js', '../../build/core/js/framework7.js');
}
return content
.replace('../../build/core/css/framework7.css', '../../packages/core/css/framework7.min.css')
.replace('../../build/core/js/framework7.js', '../../packages/core/js/framework7.min.js');
}))
.pipe(gulp.dest('./kitchen-sink/vue'));
rollup.rollup({
input: './kitchen-sink/vue/src/app.js',
plugins: [
replace({
delimiters: ['', ''],
'process.env.NODE_ENV': JSON.stringify(env),
'process.env.TARGET': JSON.stringify(target),
"'framework7-vue'": () => `'${f7VuePath}'`,
"'framework7/framework7.esm.bundle'": () => `'${f7Path}'`,
}),
resolve({ jsnext: true }),
commonjs(),
vue(),
buble({
objectAssign: 'Object.assign',
}),
],
onwarn(warning, warn) {
const ignore = ['EVAL'];
if (warning.code && ignore.indexOf(warning.code) >= 0) {
return;
}
warn(warning);
},
}).then(bundle => bundle.write({
format: 'umd',
name: 'app',
strict: true,
sourcemap: false,
file: './kitchen-sink/vue/js/app.js',
})).then(() => {
if (cb) cb();
}).catch((err) => {
console.log(err);
if (cb) cb();
});
}
module.exports = buildKs;
|
import {expect} from 'chai';
import {camel_case} from '../src';
describe('CamelCase', () => {
it('should be exists.', () => {
expect(camel_case).to.be.exists;
});
it('should convert helloThere to HelloThere.', () => {
expect(camel_case('helloThere')).to.be.equals('HelloThere');
});
it('should convert i_am_a_robot to IAmARobot.', () => {
expect(camel_case('i_am_a_robot')).to.be.equals('IAmARobot');
});
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _base = require('./base');
var _base2 = _interopRequireDefault(_base);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var config = {
appEnv: 'test' // don't remove the appEnv property here
};
exports.default = Object.freeze(Object.assign(_base2.default, config));
|
import React from 'react'
import ColorWheel from './ColorWheel.jsx'
React.render(<ColorWheel title='ColorWheel' />, document.querySelector('#color-wheel'))
|
const uAPI = require('../../index');
const config = require('../../test/testconfig');
const AirService = uAPI.createAirService(
{
auth: config,
debug: 2,
production: false,
}
);
const AirServiceQuiet = uAPI.createAirService(
{
auth: config,
production: false,
}
);
const requestPTC = 'ADT';
const shop_params = {
legs: [
{
from: 'LOS',
to: 'IST',
departureDate: '2019-06-18',
},
{
from: 'IST',
to: 'LOS',
departureDate: '2019-06-21',
},
],
passengers: {
[requestPTC]: 1,
},
cabins: ['Economy'],
requestId: 'test',
};
AirServiceQuiet.shop(shop_params)
.then((results) => {
const forwardSegments = results['0'].directions['0']['0'].segments;
const backSegments = results['0'].directions['1']['0'].segments;
const farerules_params = {
segments: forwardSegments.concat(backSegments),
passengers: shop_params.passengers,
long: true,
requestId: 'test',
};
return AirService.fareRules(farerules_params);
})
.then(
(res) => {
console.log(JSON.stringify(res));
},
err => console.error(err)
).catch((err) => {
console.error(err);
});
|
var objc = require('../')
objc.dlopen('/System/Library/Frameworks/AppKit.framework/AppKit');
NSApplication = objc.objc_getClass('NSApplication');
console.log(NSApplication);
var sharedApplication = objc.sel_registerName('sharedApplication');
var app = objc.objc_msgSend(NSApplication, sharedApplication);
console.log(app);
|
const minimatch = require( "minimatch" );
const webpack = require( "webpack" );
const _ = require( "lodash" );
module.exports = function( options ) {
function isMatchingModule( mod ) {
return mod.resource && _.some( options.paths, path => minimatch( mod.resource, path ) );
}
return new webpack.optimize.CommonsChunkPlugin( {
name: options.name,
filename: options.filename,
minChunks: isMatchingModule
} );
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.