code stringlengths 2 1.05M |
|---|
const Inventory = require('../objects/Inventory');
class Settlement {
constructor(name) {
/**
* @type {string}
*/
this.name = name;
/**
* @type {Inventory}
*/
this.inventory = new Inventory();
/**
* @type {number}
*/
this.members = 1;
}
addMember() {
this.members += 1;
}
removeMember() {
this.members -= 1;
}
/**
* @param {string} name
* @param {string} dataString
*/
set(name, dataString) {
const data = JSON.parse(dataString);
this.name = name;
this.members = data.members;
this.inventory = new Inventory();
this.inventory.set(data.inventory);
}
/**
* @returns {Object}
*/
get() {
return {
$name: this.name,
$data: JSON.stringify({
members: this.members,
inventory: this.inventory.get()
})
}
}
}
module.exports = Settlement; |
const warpjsPlugins = require('@warp-works/warpjs-plugins');
const warpCore = require('./../lib/core');
module.exports = () => {
const plugin = warpjsPlugins.getPlugin('session');
if (plugin) {
return plugin.module.middlewares(plugin.config, warpCore, plugin.Persistence);
} else {
return null;
}
};
|
var express = require('express');
var app = express();
app.use('/node_modules', express.static(__dirname + '/node_modules'));
app.use(express.static(__dirname + '/public'));
// redirect all others to the index (HTML5 history)
app.all('/*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.listen(3000, function() {
console.log('Express listening on port 3000.');
}); |
var test = require('tape');
var fs = require('fs');
// Load utils and constants in the global scope of this file to run tests on:
/* jshint ignore:start */
eval(fs.readFileSync(__dirname + '/../src/constants.js') + '');
eval(fs.readFileSync(__dirname + '/../src/utils.js') + '');
/* jshint ignore:end */
test('test unixSeconds', function(t) {
t.equal(utils.unixSeconds(), Math.round(Date.now() / 1000));
t.end();
});
test('test getDefaultConfig', function(t) {
var config = utils.getDefaultConfig();
t.equal(config.seconds, 0);
t.equal(config.duration, null);
t.equal(config.editable, false);
t.equal(config.repeat, false);
t.equal(config.countdown, false);
t.equal(config.updateFrequency, 500);
t.end();
});
test('test secondsToFormattedTime', function(t) {
t.equal(utils.secondsToFormattedTime(100, '%m:%s'), '1:40');
t.equal(utils.secondsToFormattedTime(3, '%m:%s'), '0:3');
t.equal(utils.secondsToFormattedTime(1000, '%M minutes'), '16 minutes');
t.equal(utils.secondsToFormattedTime(1000, '%T seconds'), '1000 seconds');
t.equal(utils.secondsToFormattedTime(1000, '%H:%M:%S'), '00:16:40');
t.equal(utils.secondsToFormattedTime(1000, '%h:%M:%S'), '0:16:40');
t.equal(utils.secondsToFormattedTime(5, '%h:%m:%s'), '0:0:5');
t.equal(utils.secondsToFormattedTime(365, '%h:%m:%s'), '0:6:5');
t.equal(utils.secondsToFormattedTime(365, '%d:%h:%m:%s'), '0:0:6:5');
t.equal(utils.secondsToFormattedTime(451810, '%d:%h:%m:%s'), '5:5:30:10');
t.equal(utils.secondsToFormattedTime(280929, '%D:%H:%m:%s'), '03:06:2:9');
t.end();
});
test('test durationTimeToSeconds', function(t) {
t.equal(utils.durationTimeToSeconds(330), 330);
t.equal(utils.durationTimeToSeconds('5m30s'), 330);
t.equal(utils.durationTimeToSeconds('30s'), 30);
t.equal(utils.durationTimeToSeconds('5m'), 300);
t.equal(utils.durationTimeToSeconds('5h'), 18000);
t.equal(utils.durationTimeToSeconds('5h30m10s'), 19810);
t.equal(utils.durationTimeToSeconds('5d5h30m10s'), 451810);
t.equal(utils.durationTimeToSeconds('05d05h30m10s'), 451810);
t.throws(function() {
utils.durationTimeToSeconds();
});
t.throws(function() {
utils.durationTimeToSeconds('invalid-format');
});
t.end();
});
test('test secondsToPrettyTime', function(t) {
t.equal(utils.secondsToPrettyTime(100), '1:40 min');
t.equal(utils.secondsToPrettyTime(1000), '16:40 min');
t.equal(utils.secondsToPrettyTime(1234), '20:34 min');
t.equal(utils.secondsToPrettyTime(19810), '5:30:10');
t.equal(utils.secondsToPrettyTime(451810), '5:05:30:10');
t.end();
});
test('test prettyTimeToSeconds', function(t) {
t.equal(utils.prettyTimeToSeconds('1:40 min'), 100);
t.equal(utils.prettyTimeToSeconds('16:40 min'), 1000);
t.equal(utils.prettyTimeToSeconds('20:34 min'), 1234);
t.equal(utils.prettyTimeToSeconds('5:30:10'), 19810);
t.equal(utils.prettyTimeToSeconds('03:06:02:09'), 280929);
t.equal(utils.prettyTimeToSeconds('3:06:02:09'), 280929);
t.end();
});
|
import React, { Component } from "react";
import { Redirect, Route, Switch } from "react-router-dom";
import componentQueries from "react-component-queries";
import { Sidebar } from "./sidebar";
import { Me } from "./me";
import { Task } from "./task";
import { User } from "./user";
class Authenticated extends Component {
constructor(props) {
super(props);
this.state = {
showSideBar: !props.temporaryDock,
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.temporaryDock !== this.props.temporaryDock) {
this.setState({ showSideBar: !nextProps.temporaryDock });
}
}
toggleSideBar = evt => {
const { showSideBar } = this.state;
this.setState({ showSideBar: !showSideBar });
};
render() {
const { signOut, temporaryDock } = this.props;
const { showSideBar } = this.state;
return (
<div style={{ display: "flex", height: "100%" }}>
<Sidebar
temporaryDock={temporaryDock}
signOut={signOut}
showSideBar={showSideBar}
toggleSideBar={this.toggleSideBar}
{...this.props}
/>
<Switch>
<Route
path="/me"
render={props => (
<Me
{...props}
{...this.props}
toggleSideBar={this.toggleSideBar}
/>
)}
/>
<Route
path="/tasks"
render={props => (
<Task
{...props}
{...this.props}
toggleSideBar={this.toggleSideBar}
/>
)}
/>
<Route
path="/users"
render={props => (
<User
{...props}
{...this.props}
toggleSideBar={this.toggleSideBar}
/>
)}
/>
<Route exactly path="/" render={() => <Redirect to="/me" />} />
</Switch>
</div>
);
}
}
Authenticated = componentQueries({
queries: [
({ width }) => ({
temporaryDock: width < 800,
}),
],
config: { pure: false },
})(Authenticated);
export { Authenticated };
|
function Spawner() {
this.frame = 0
this.threshold = 220
this.toughness = 1
this.bossMode = false
this.speed = 1
}
Spawner.prototype.physics = function() {
if (!this.bossMode && this.frame % 90 === 0) {
this.spawn()
}
this.frame++
if(this.frame % 800 === 0) {
this.toughness++
this.speed += 0.4
if (debug) console.log('updated toughness', this.toughness)
}
}
Spawner.prototype.spawn = function(size, speed, toughness) {
size = size || 20
speed = speed || this.speed
toughness = toughness || this.toughness
var x, y
if(Math.random() > .5) {
// top or bottom side
y = Math.random() > .5 ? GAME.h + size * 2 : -size*2
x = Math.floor(Math.random() * GAME.w)
} else {
// left or right size
x = Math.random() > .5 ? GAME.w + size * 2: -size*2
y = Math.floor(Math.random() * GAME.h)
}
var enemy = new Enemy({
x:x, y:y, size:size, speed:speed, target: GAME.player, toughness: toughness
})
GAME.enemies.push(enemy)
return enemy
}
Spawner.prototype.draw = function(ctx) {
// This is no logner used, as the processing is done on the GPU via fragment shader
return
// metabolize ctx
var data = ctx.getImageData(0, 0, GAME.w, GAME.h)
var pix = data.data
for(var i=0, l=pix.length; i<l; i+=4) {
if(pix[i+3] < this.threshold) {
pix[i+3] /= 6
if(pix[i+3] > this.threshold/4) {
pix[i+3] = 0
}
}
}
ctx.putImageData(data, 0, 0)
}
Spawner.prototype.enableBossMode = function() {
this.bossMode = true
var boss = this.spawn(100, 1.7, 15)
setInterval(function(){
boss.speed += 0.025
if(debug) console.log('speed up', boss.speed)
}, 5000)
}
|
import { expect } from 'chai'
import { clean, runMocha } from '../helper'
describe('Test Id', () => {
beforeEach(clean)
it('should add testId to test cases', () => {
return runMocha(['testId']).then(results => {
expect(results).to.have.lengthOf(1)
const result = results[0]
expect(result('ns2\\:test-suite > name').text()).to.be.equal(
'Suite with testIds'
)
expect(
result('test-case > name')
.eq(0)
.text()
).to.be.equal('Test #1')
expect(
result('test-case > name')
.eq(1)
.text()
).to.be.equal('Test #2')
expect(
result('test-case label[name="testId"]')
.eq(0)
.attr('value')
).to.be.equal('3')
expect(
result('test-case label[name="testId"]')
.eq(1)
.attr('value')
).to.be.equal('4')
})
})
})
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var component = __webpack_require__(1);
var app = document.createElement('div');
document.body.appendChild(app);
app.appendChild(component());
/***/ },
/* 1 */
/***/ function(module, exports) {
module.exports = function () {
var element = document.createElement('h1');
element.innerHTML = 'Hello';
return element;
};
/***/ }
/******/ ]); |
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("node_modules/codemirror/lib/codemirror.js"), require("node_modules/codemirror/mode/htmlmixed/htmlmixed.js"), require("node_modules/codemirror/mode/ruby/ruby.js"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../ruby/ruby"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
// full haml mode. This handled embeded ruby and html fragments too
CodeMirror.defineMode("haml", function(config) {
var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"});
var rubyMode = CodeMirror.getMode(config, "ruby");
function rubyInQuote(endQuote) {
return function(stream, state) {
var ch = stream.peek();
if (ch == endQuote && state.rubyState.tokenize.length == 1) {
// step out of ruby context as it seems to complete processing all the braces
stream.next();
state.tokenize = html;
return "closeAttributeTag";
} else {
return ruby(stream, state);
}
};
}
function ruby(stream, state) {
if (stream.match("-#")) {
stream.skipToEnd();
return "comment";
}
return rubyMode.token(stream, state.rubyState);
}
function html(stream, state) {
var ch = stream.peek();
// handle haml declarations. All declarations that cant be handled here
// will be passed to html mode
if (state.previousToken.style == "comment" ) {
if (state.indented > state.previousToken.indented) {
stream.skipToEnd();
return "commentLine";
}
}
if (state.startOfLine) {
if (ch == "!" && stream.match("!!")) {
stream.skipToEnd();
return "tag";
} else if (stream.match(/^%[\w:#\.]+=/)) {
state.tokenize = ruby;
return "hamlTag";
} else if (stream.match(/^%[\w:]+/)) {
return "hamlTag";
} else if (ch == "/" ) {
stream.skipToEnd();
return "comment";
}
}
if (state.startOfLine || state.previousToken.style == "hamlTag") {
if ( ch == "#" || ch == ".") {
stream.match(/[\w-#\.]*/);
return "hamlAttribute";
}
}
// donot handle --> as valid ruby, make it HTML close comment instead
if (state.startOfLine && !stream.match("-->", false) && (ch == "=" || ch == "-" )) {
state.tokenize = ruby;
return state.tokenize(stream, state);
}
if (state.previousToken.style == "hamlTag" ||
state.previousToken.style == "closeAttributeTag" ||
state.previousToken.style == "hamlAttribute") {
if (ch == "(") {
state.tokenize = rubyInQuote(")");
return state.tokenize(stream, state);
} else if (ch == "{") {
if (!stream.match(/^\{%.*/)) {
state.tokenize = rubyInQuote("}");
return state.tokenize(stream, state);
}
}
}
return htmlMode.token(stream, state.htmlState);
}
return {
// default to html mode
startState: function() {
var htmlState = htmlMode.startState();
var rubyState = rubyMode.startState();
return {
htmlState: htmlState,
rubyState: rubyState,
indented: 0,
previousToken: { style: null, indented: 0},
tokenize: html
};
},
copyState: function(state) {
return {
htmlState : CodeMirror.copyState(htmlMode, state.htmlState),
rubyState: CodeMirror.copyState(rubyMode, state.rubyState),
indented: state.indented,
previousToken: state.previousToken,
tokenize: state.tokenize
};
},
token: function(stream, state) {
if (stream.sol()) {
state.indented = stream.indentation();
state.startOfLine = true;
}
if (stream.eatSpace()) return null;
var style = state.tokenize(stream, state);
state.startOfLine = false;
// dont record comment line as we only want to measure comment line with
// the opening comment block
if (style && style != "commentLine") {
state.previousToken = { style: style, indented: state.indented };
}
// if current state is ruby and the previous token is not `,` reset the
// tokenize to html
if (stream.eol() && state.tokenize == ruby) {
stream.backUp(1);
var ch = stream.peek();
stream.next();
if (ch && ch != ",") {
state.tokenize = html;
}
}
// reprocess some of the specific style tag when finish setting previousToken
if (style == "hamlTag") {
style = "tag";
} else if (style == "commentLine") {
style = "comment";
} else if (style == "hamlAttribute") {
style = "attribute";
} else if (style == "closeAttributeTag") {
style = null;
}
return style;
}
};
}, "htmlmixed", "ruby");
CodeMirror.defineMIME("text/x-haml", "haml");
});
|
var http = require('http');
var sys = require('sys');
var fs = require('fs');
http.createServer(function(req, res) {
debugHeaders(req);
if (req.headers.accept && req.headers.accept === 'text/event-stream') {
if (req.url === 'https://api.spark.io/v1/events/motion-detected?access_token=5a4501e8e5d6ab780731274e000a5894657f9d10') {
sendSSE(req, res);
} else {
res.writeHead(404);
res.end();
}
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(fs.readFileSync(__dirname + '/index.html'));
res.end();
}
}).listen(8000);
function sendSSE(req, res) {
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
var id = (new Date()).toLocaleTimeString();
// Sends a SSE every 5 seconds on a single connection.
setInterval(function() {
constructSSE(res, id, (new Date()).toLocaleTimeString());
}, 5000);
constructSSE(res, id, (new Date()).toLocaleTimeString());
}
function constructSSE(res, id, data) {
res.write('id: ' + id + '\n');
res.write("data: " + data + '\n\n');
}
function debugHeaders(req) {
sys.puts('URL: ' + req.url);
for (var key in req.headers) {
sys.puts(key + ': ' + req.headers[key]);
}
sys.puts('\n\n');
} |
'use strict';
var gulp = require('gulp'),
karma = require('karma').server,
open = require('open'),
plugins = require('gulp-load-plugins')();
plugins.connect = require('gulp-connect');
plugins.useref = require('gulp-useref');
gulp.task('build', ['html', 'images']);
gulp.task('clean', function () {
return gulp.src(['dist'], { read: false }).pipe(plugins.clean());
});
gulp.task('connect', plugins.connect.server());
gulp.task('default', ['clean', 'test'], function () {
gulp.start('build');
});
gulp.task('html', ['stylesheets', 'javascripts'], function () {
var cssFilter = plugins.filter('**/*.css'),
jsFilter = plugins.filter('**/*.js'),
htmlFilter = plugins.filter('**/*.html');
return gulp.src('app/*.html')
.pipe(plugins.useref.assets())
.pipe(jsFilter)
.pipe(plugins.uglify({
preserveComments: 'some'
}))
.pipe(jsFilter.restore())
.pipe(cssFilter)
.pipe(plugins.csso())
.pipe(cssFilter.restore())
.pipe(plugins.useref.restore())
.pipe(plugins.useref())
.pipe(htmlFilter)
.pipe(plugins.htmlmin({
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true
}))
.pipe(htmlFilter.restore())
.pipe(gulp.dest('dist'))
.pipe(plugins.size());
});
gulp.task('images', ['resize'], function () {
return gulp.src('app/assets/images/**/*')
.pipe(plugins.imagemin())
.pipe(gulp.dest('dist/assets/images'))
.pipe(plugins.size());
});
gulp.task('javascripts', function () {
return gulp.src('app/assets/javascripts/**/*.js')
.pipe(plugins.jshint('.jshintrc'))
.pipe(plugins.jshint.reporter('default'))
.pipe(plugins.size());
});
gulp.task('resize', function () {
return gulp.src('app/assets/images/**@2x.png')
.pipe(plugins.imageResize({
imageMagick: true,
width: '50%'
}))
.pipe(plugins.rename(function (path) { path.basename = path.basename.replace('@2x', ''); }))
.pipe(gulp.dest('app/assets/images'));
});
gulp.task('serve', ['connect', 'stylesheets', 'resize'], function () {
open('http://localhost:3000');
});
gulp.task('stylesheets', function () {
return gulp.src('app/assets/stylesheets/app.scss')
.pipe(plugins.rubySass({
loadPath: ['app/assets/bower_components'],
style: 'expanded'
}))
.pipe(plugins.autoprefixer('last 1 version'))
.pipe(gulp.dest('app/assets/stylesheets'))
.pipe(plugins.size());
});
gulp.task('test', function () {
karma.start({
configFile: '../../../karma.conf.js'
}, function (exitCode) {
process.exit(exitCode);
});
});
gulp.task('watch', ['connect', 'serve'], function () {
gulp.watch([
'app/*.html',
'app/assets/images/**/*',
'app/assets/javascripts/**/*.js',
'app/assets/stylesheets/**/*.css',
'app/assets/stylesheets/**/*.scss',
'spec/javascripts/**/*.js'
], function (event) {
gulp.src(event.path)
.pipe(plugins.connect.reload());
});
gulp.watch('app/assets/images/**/*', ['images']);
gulp.watch('app/assets/javascripts/**/*.js', ['javascripts']);
gulp.watch('app/assets/stylesheets/**/*.scss', ['stylesheets']);
});
|
var lastOpenedInfo = null;
// Processing
var runProcess = function() {
var now = new Date();
$.ajax({
url: "https://docs.google.com/spreadsheet/pub",
data: {
key: localStorage["spreadsheet-key"],
output: "txt"
},
method: "GET",
dataType: "text",
timeout: 10000,
error: function(jq, status, err) {
localStorage["last-fetch-success"] = false;
},
success: function(data, status) {
localStorage["last-fetch-success"] = true;
processData(now, data);
}
});
};
var timeToInt = function(timestamp) {
var pieces = timestamp.split(":");
if (pieces.length < 2) {
return -1;
}
var hours = parseInt(pieces[0], "10");
var minutes = parseInt(pieces[1], "10");
if (isNaN(hours) || isNaN(minutes)) {
return -1;
}
return hours * 60 + minutes;
};
var isActiveDay = function(time, usertime) {
if (usertime == "Everyday") {
return true;
}
if (usertime == "Weekdays" && time.getDay() >= 1 && time.getDay() <= 5) {
return true;
}
if (usertime == "Weekends" && (time.getDay() == 0 || time.getDay() == 6)) {
return true;
}
return false;
};
var isActiveTime = function(time, startTime, endTime) {
var current = time.getHours() * 60 + time.getMinutes();
var start = timeToInt(startTime);
if (start == -1) {
start = 0;
}
var end = timeToInt(endTime);
if (end == -1) {
end = Infinity;
}
return current >= start && current < end;
};
var openWebsite = function(url, index) {
if (lastOpenedInfo != null && lastOpenedInfo.index == index &&
lastOpenedInfo.url == url) {
return;
}
if (lastOpenedInfo != null) {
chrome.tabs.get(lastOpenedInfo.tabId, function(tab) {
chrome.tabs.remove(tab.id);
});
}
chrome.tabs.create({
url: url,
active: true
}, function(tab) {
lastOpenedInfo = {
tabId: tab.id,
index: index,
url: url
};
if (localStorage["hide-cursor"] == "true") {
chrome.tabs.insertCSS(tab.id, {
file: "hide_cursor.css"
});
}
});
};
var processData = function(timestamp, data) {
var rows = data.split("\n");
var completed = false;
for (var i = 0; i < rows.length; i++) {
// Header
if (i == 0) {
continue;
}
// Columns
var columns = rows[i].split("\t");
if (columns.length < 4) {
continue;
}
if (!isActiveDay(timestamp, columns[0])) {
continue;
}
if (!isActiveTime(timestamp, columns[1], columns[2])) {
continue;
}
var url = columns[3];
completed = true;
openWebsite(url, i);
break;
}
if (!completed) {
var url = chrome.extension.getURL("idle.html");
openWebsite(url, -1);
}
};
// Tab listener
chrome.tabs.onRemoved.addListener(function(tabId) {
if (lastOpenedInfo != null && lastOpenedInfo.tabId == tabId) {
lastOpenedInfo = null;
if (localStorage["reopen"] == "true") {
runProcess();
}
}
});
// Initialize alarm
chrome.alarms.create("fetch", {delayInMinutes: 1, periodInMinutes: 1});
chrome.alarms.onAlarm.addListener(function(alarm) {
runProcess();
});
// Startup
runProcess();
// Installation hook
chrome.runtime.onInstalled.addListener(function(obj) {
if (obj.reason == "install") {
localStorage["reopen"] = "true";
chrome.tabs.create({
url: chrome.runtime.getURL("options.html"),
active: true
});
}
});
|
(function (angular, noty) {
"use strict";
angular.module('ClassStyleModule', ['myApp', 'ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/classStyle', {
templateUrl: 'classStyle/show.html',
controller: 'ClassStyleController',
resolve: {
studios: ['consts', '$http', 'ApiService', function (consts, $http) {
return $http.get(consts.apiUrl + '/Studios').then(function (response) {
return response.data;
}, function (err) {
return false;
});
}],
classStyles: ['consts', '$http', 'ApiService', function (consts, $http) {
return $http.get(consts.apiUrl + '/ClassStyles').then(function (response) {
return response.data;
}, function (err) {
return false;
});
}]
}
});
}])
.controller('ClassStyleController', ['$scope', 'classStyles', 'studios', 'ngDialog', '$http', 'consts', '$route',
function ($scope, classStyles, studios, ngDialog, $http, consts, $route) {
$scope.edit = function (classStyle) {
ngDialog.open({
template: 'classStyle/edit.html',
className: 'ngdialog-theme-default',
width: '70%',
controller: 'ClassStyleEditController',
resolve: {
classStyle: [function () {
return classStyle;
}],
studios: [function () {
return studios;
}]
}
});
};
$scope.remove = function (studio) {
ngDialog.openConfirm({
template: '\
<p>Do you really want to remove this Class Style?</p>\
<div class="ngdialog-buttons">\
<button type="button" class="ngdialog-button ngdialog-button-secondary" ng-click="closeThisDialog(0)">No</button>\
<button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="confirm(1)">Yes</button>\
</div>',
plain: true
}).then(function (confirm) {
$http.delete(consts.apiUrl + '/ClassStyles/' + studio.id)
.then(function (response) {
noty({type: 'warning', text: 'Class Style removed'});
$route.reload();
}, function (err) {
if (err.data.error && err.data.error.message) {
noty({type: 'error', text: err.data.error.message});
} else {
console.error(err);
noty({
type: 'error',
text: 'An unknown error has ocurred, check browser\'s console for more info'
});
}
});
});
}
$scope.new = function () {
ngDialog.open({
template: 'classStyle/new.html',
className: 'ngdialog-theme-default',
width: '70%',
controller: 'ClassStyleNewController',
resolve: {
studios: [function () {
return studios;
}]
}
});
};
_.forEach(classStyles, function (classStyle) {
classStyle.studio = _.find(studios, {id: classStyle.studioId});
});
$scope.classStyles = classStyles;
$scope.studios = studios;
}])
.controller('ClassStyleEditController', ['$scope', 'classStyle', 'studios', 'ngDialog', '$http', '$route', 'consts', 'Upload',
function ($scope, classStyle, studios, ngDialog, $http, $route, consts, Upload) {
$scope.dsThumbnail = {};
$scope.upload = function (file, model, formModel, formModelVar) {
Upload.upload({
url: consts.apiUrl + '/AWSS3s/' + consts.s3bucket + '/upload',
data: {file: file}
}).then(function (resp) {
model.location = formModel[formModelVar] = consts.apiUrl + '/AWSS3s/' + consts.s3bucket + '/download/' + resp.data.result.files.file[0].name;
}, function (resp) {
noty({
type: 'error',
text: 'An error has ocurred while uploading the image to the server.'
});
console.error(resp);
}, function (evt) {
model.progress = parseInt(100.0 * evt.loaded / evt.total);
});
};
$scope.submit = function (classStyle) {
$http.post(consts.apiUrl + '/ClassStyles/update', classStyle, {params: {where: {id: classStyle.id}}})
.then(function (response) {
noty({type: 'success', text: 'Changes saved '});
$scope.closeThisDialog();
$route.reload();
}, function (err) {
if (err.data.error && err.data.error.message) {
noty({type: 'error', text: err.data.error.message});
} else {
console.error(err);
noty({
type: 'error',
text: 'An unknown error has ocurred, check browser\'s console for more info'
});
}
});
};
$scope.classStyle = angular.copy(classStyle);
$scope.studios = studios;
}])
.controller('ClassStyleNewController', ['$scope', 'studios', 'ngDialog', '$http', '$route', 'consts', 'Upload',
function ($scope, studios, ngDialog, $http, $route, consts, Upload) {
$scope.dsThumbnail = {};
$scope.upload = function (file, model, formModel, formModelVar) {
Upload.upload({
url: consts.apiUrl + '/AWSS3s/' + consts.s3bucket + '/upload',
data: {file: file}
}).then(function (resp) {
model.location = formModel[formModelVar] = consts.apiUrl + '/AWSS3s/' + consts.s3bucket + '/download/' + resp.data.result.files.file[0].name;
}, function (resp) {
noty({
type: 'error',
text: 'An error has ocurred while uploading the image to the server.'
});
console.error(resp);
}, function (evt) {
model.progress = parseInt(100.0 * evt.loaded / evt.total);
});
};
$scope.submit = function (classStyle) {
$http.post(consts.apiUrl + '/ClassStyles', classStyle)
.then(function (response) {
noty({type: 'success', text: 'Class style saved'});
$scope.closeThisDialog();
$route.reload();
}, function (err) {
if (err.data.error && err.data.error.message) {
noty({type: 'error', text: err.data.error.message});
} else {
console.error(err);
noty({
type: 'error',
text: 'An unknown error has ocurred, check browser\'s console for more info'
});
}
});
};
$scope.classStyle = {};
$scope.studios = studios;
}])
;
})(angular, noty); |
/*
Copyright (c) 2010 Till Theis, http://www.tilltheis.de
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var EventManager = function() {
var events = {}; // { eventName: { callbacks: [f], context: object }, .. }
this.connect = function(event, callback) {
assertEvent('connect', event);
assertCallback('connect', callback);
var callbacks = events[event].callbacks;
if (callbacks.indexOf(callback) !== -1) {
throw "EventManager::connect: Specified callback is already connected with event '" + event + "'";
}
events[event].callbacks.push(callback);
};
this.disconnect = function(event, callback) {
assertEvent('disconnect', event);
assertCallback('disconnect', callback);
var e = events[event];
var callbacks = e.callbacks;
var idx = callbacks.indexOf(callback);
if (idx === -1) {
throw "EventManager::disconnect: Specified callback '" + callback + "' not connected with event '" + event + "'";
}
callbacks.splice(idx, 1);
};
this.emit = function(event) {
assertEvent('emit', event);
var args = Array.prototype.slice.call(arguments, 1, arguments.length);
var e = events[event];
var callbacks = e.callbacks;
for (var i = 0; i < callbacks.length; ++i) {
callbacks[i].apply(e.context, args);
}
};
this.registerEvent = function(event, optionalContext) {
if (event in events) {
throw "EventManager::registerEvent: Event '" + event + "' is already registered";
}
events[event] = {
callbacks: [],
context: optionalContext || window
};
};
this.unregisterEvent = function(event) {
assertEvent('unregisterEvent', event);
delete events[event];
};
var assertEvent = function(method, event) {
if (!(event in events)) {
throw "EventManager::" + method + ": Unknown event '" + event + "'";
}
};
var assertCallback = function(method, callback) {
if (typeof callback !== 'function') {
throw "EventManager::" + method + ": Callback must be a function";
}
};
};
|
'use strict';
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _createReactClass = require('create-react-class');
var _createReactClass2 = _interopRequireDefault(_createReactClass);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _year_dropdown_options = require('./year_dropdown_options');
var _year_dropdown_options2 = _interopRequireDefault(_year_dropdown_options);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var YearDropdown = (0, _createReactClass2.default)({
displayName: 'YearDropdown',
propTypes: {
onChange: _propTypes2.default.func.isRequired,
year: _propTypes2.default.number.isRequired
},
getInitialState: function getInitialState() {
return {
dropdownVisible: false
};
},
renderReadView: function renderReadView() {
return _react2.default.createElement(
'div',
{ className: 'react-datepicker__year-read-view', onClick: this.toggleDropdown },
_react2.default.createElement(
'span',
{ className: 'react-datepicker__year-read-view--selected-year' },
this.props.year
),
_react2.default.createElement('span', { className: 'react-datepicker__year-read-view--down-arrow' })
);
},
renderDropdown: function renderDropdown() {
return _react2.default.createElement(_year_dropdown_options2.default, {
ref: 'options',
year: this.props.year,
onChange: this.onChange,
onCancel: this.toggleDropdown });
},
onChange: function onChange(year) {
this.toggleDropdown();
if (year === this.props.year) return;
this.props.onChange(year);
},
toggleDropdown: function toggleDropdown() {
this.setState({
dropdownVisible: !this.state.dropdownVisible
});
},
render: function render() {
return _react2.default.createElement(
'div',
null,
this.state.dropdownVisible ? this.renderDropdown() : this.renderReadView()
);
}
});
module.exports = YearDropdown;
|
wm.Event = (function () {
'use strict';
let Event = function (name) {
this.name = name;
this.callbacks = [];
}
Event.prototype.registerCallback = function (callback) {
this.callbacks.push(callback);
}
return Event;
})();
|
var Greeter = (function () {
function Greeter(element) {
this.element = element;
}
Greeter.prototype.greet = function (msg) {
this.element.innerHTML = msg.greeting;
};
return Greeter;
}());
|
// @flow
import {createSelector} from 'reselect'
import type {Middleware} from 'redux'
import type {Features, ComposeMiddleware} from './index'
import {defaultComposeMiddleware} from './defaults'
export default function featureMiddlewaresMiddleware<S, A: {type: $Subtype<string>}>(
config?: {
getFeatures?: (state: S) => ?Features<S, A>,
composeMiddleware?: ComposeMiddleware<S, A>,
} = {}
): Middleware<S, A> {
const getFeatures = config.getFeatures || ((state: any) => state && state.features)
const composeMiddleware = config.composeMiddleware || defaultComposeMiddleware
const selectFeatureMiddleware: (state: S) => Middleware<S, A> = createSelector(
getFeatures,
(features: ?Features<S, A>): Middleware<S, A> => {
if (!features) return store => next => next
const middlewares: Array<Middleware<S, A>> = []
for (let id in features) {
const {middleware} = features[id]
if (middleware instanceof Function) middlewares.push(middleware)
}
if (!middlewares.length) return store => next => next
return composeMiddleware(...middlewares)
}
)
return store => next => action => selectFeatureMiddleware(store.getState())(store)(next)(action)
}
|
var _; //globals
/* This section uses a functional extension known as Underscore.js - http://documentcloud.github.com/underscore/
"Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support
that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.
It's the tie to go along with jQuery's tux."
*/
describe("About Higher Order Functions", function () {
/// The filter() method creates a new array with all elements that pass the test implemented by the provided function. ////
it("should use filter to return array items that meet a criteria", function () {
var numbers = [1,2,3];
var odd = _(numbers).filter(function (x) { return x % 2 !== 0 });
expect(odd).toEqual([1,3]); //////// the filter equation means that the number is odd /////
expect(odd.length).toBe(2); //////// there are 2 odd numbers ///////
expect(numbers.length).toBe(3); ///////// there are 3 total numbers in the array, even and odd /////
});
////// The map() method creates a new array with the results of calling a provided function on every element in this array.
it("should use 'map' to transform each element", function () {
var numbers = [1, 2, 3];
var numbersPlus1 = _(numbers).map(function(x) { return x + 1 });
expect(numbersPlus1).toEqual([2, 3, 4]); //// you are just adding 1 to each number based on the function above ////
expect(numbers).toEqual([1, 2, 3]); ///// they are just asking for the numbers from the above variable //////
});
///// The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value.
it("should use 'reduce' to update the same result on each iteration", function () {
var numbers = [1, 2, 3];
var reduction = _(numbers).reduce(
function(/* result from last call */ memo, /* current */ x) { return memo + x }, /* initial */ 0);
expect(reduction).toBe(6); ////// add 1 plus 2 plus 3 and you get 6 ///////
expect(numbers).toEqual([1, 2, 3]); ///// they are just asking for the numbers from the variable above ////
});
/////// The forEach() method executes a provided function once per array element. //////
it("should use 'forEach' for simple iteration", function () {
var numbers = [1,2,3];
var msg = "";
var isEven = function (item) {
msg += (item % 2) === 0;
};
_(numbers).forEach(isEven);
expect(msg).toEqual("falsetruefalse"); ////// 2 is even so it is true. 1 and 3 are odd so they are false. But why is this so? //////
expect(numbers).toEqual([1, 2, 3]); ////// this is from the variable numbers above /////
});
it("should use 'all' to test whether all items pass condition", function () {
var onlyEven = [2,4,6];
var mixedBag = [2,4,5,6];
var isEven = function(x) { return x % 2 === 0 };
expect(_(onlyEven).all(isEven)).toBe(true); //// ran this in the console and came out true. all that are in the onlyeven variable are even ///
expect(_(mixedBag).all(isEven)).toBe(false); //// ran this in the console and came out false. all that are in the mixedBag are not even //////
});
it("should use 'any' to test if any items passes condition" , function () {
var onlyEven = [2,4,6];
var mixedBag = [2,4,5,6];
var isEven = function(x) { return x % 2 === 0 };
expect(_(onlyEven).any(isEven)).toBe(true);
expect(_(mixedBag).any(isEven)).toBe(true); //// they are asking if any of the numbers are even this time //////
});
it("should use range to generate an array", function() { ////// I DONT UNDERSTAND RANGE??? //////
expect(_.range(3)).toEqual([0, 1, 2]);
expect(_.range(1, 4)).toEqual([1, 2, 3]);
expect(_.range(0, -4, -1)).toEqual([0, -1, -2, -3]);
});
it("should use flatten to make nested arrays easy to work with", function() {
expect(_([ [1, 2], [3, 4] ]).flatten()).toEqual([1, 2, 3, 4]); //// flatten merges the arrays together /////
});
it("should use chain() ... .value() to use multiple higher order functions", function() {
var result = _([ [0, 1], 2 ]).chain()
.flatten()
.map(function(x) { return x+1 } )
.reduce(function (sum, x) { return sum + x })
.value();
expect(result).toEqual(6); //// 6 because the flatten merges the numbers together, map adds 1 to each number and reduce adds all the numbers together ////
});
});
|
/*
* ORE - Online Roguelike Engine
*
* Copyright (C) 2016 Mark Purser
* Released under the MIT license
* http://github.com/markpurser/ORE/LICENSE
*
* Tile rendering based on
* https://github.com/jice-nospam/yendor.ts
* Copyright (c) 2014 Jice
*/
/**
* @module ORE
*/
this.ORE = this.ORE || {};
(function () {
ORE.init = function (oreOptions)
{
this._renderingCanvas = oreOptions.renderCanvas;
this._debugCanvas = oreOptions.debugCanvas;
this._keyboard = new Keyboard();
var tileWidthPx = oreOptions.tileWidthPx;
var tileHeightPx = oreOptions.tileHeightPx;
var spriteGridWidth = oreOptions.viewWidth;
var spriteGridHeight = oreOptions.viewHeight;
var bufferSize = 6;
var viewPos = { x:2060, y:2070 };
this._buffer = new ORE.Buffer(viewPos, spriteGridWidth, spriteGridHeight, bufferSize);
var loader = PIXI.loader;
loader.add('tilesheet', oreOptions.tilesheetImage);
loader.load( function( loader, resources )
{
var stats = {
fpsText: new PIXI.Text('', {font: '24px Arial', fill: 0xff1010}),
fpsTimer: 0,
currentFrameCount: 0
};
var numTilesX = resources.tilesheet.texture.width / tileWidthPx;
var numTilesY = resources.tilesheet.texture.height / tileHeightPx;
var bufferWidth = spriteGridWidth * bufferSize;
var bufferHeight = spriteGridHeight * bufferSize;
// init tile textures
var tileTextures = [];
_.range(numTilesX).forEach(function(x)
{
_.range(numTilesY).forEach(function(y)
{
var rect = new PIXI.Rectangle(x * tileWidthPx, y * tileHeightPx, tileWidthPx, tileHeightPx);
tileTextures[x + y * numTilesX] = new PIXI.Texture(resources.tilesheet.texture, rect);
});
});
// create a new instance of a pixi container
var parentContainer = new PIXI.Container();
var worldSprites = [];
var worldSpriteContainer = ORE.SpriteGrid(
spriteGridWidth, spriteGridHeight, tileWidthPx, tileHeightPx, tileTextures[0], worldSprites);
var debugSprites = [];
var debugSpriteContainer = ORE.SpriteGrid(
bufferSize, bufferSize, tileWidthPx, tileHeightPx, tileTextures[0], debugSprites);
parentContainer.addChild(worldSpriteContainer);
parentContainer.addChild(stats.fpsText);
var playerX = viewPos.x * tileWidthPx;
var playerY = viewPos.y * tileHeightPx;
// create a renderer instance
var pixiOptions = {
clearBeforeRender: true,
preserveDrawingBuffer: false,
resolution: 1,
view: ORE._renderingCanvas
};
ORE._renderer = PIXI.autoDetectRenderer(
oreOptions.renderCanvasSize.width, oreOptions.renderCanvasSize.height, pixiOptions);
ORE._renderer.backgroundColor = 0x66ff99;
// create a renderer instance
var pixiDebugOptions = {
clearBeforeRender: true,
preserveDrawingBuffer: false,
resolution: 2,
view: ORE._debugCanvas
};
ORE._debugRenderer = PIXI.autoDetectRenderer(
oreOptions.debugCanvasSize.width, oreOptions.debugCanvasSize.height, pixiDebugOptions);
ORE._debugRenderer.backgroundColor = 0xaa4444;
// add the renderer view element to the DOM
//document.body.appendChild(ORE._renderer.view);
requestAnimationFrame(animate);
function animate()
{
if(oreOptions.displayStats)
{
ORE.updateStats(stats);
}
if(ORE._keyboard.isKeyPressed(Keyboard.KEYS.UP))
{
playerY--;
}
if(ORE._keyboard.isKeyPressed(Keyboard.KEYS.DOWN))
{
playerY++;
}
if(ORE._keyboard.isKeyPressed(Keyboard.KEYS.LEFT))
{
playerX--;
}
if(ORE._keyboard.isKeyPressed(Keyboard.KEYS.RIGHT))
{
playerX++;
}
viewPos.x = playerX >> 4;
viewPos.y = playerY >> 4;
var scrollX = playerX & 15;
var scrollY = playerY & 15;
worldSpriteContainer.position.x = -scrollX;
worldSpriteContainer.position.y = -scrollY;
ORE._buffer.fastTileCode(viewPos, worldSprites, tileTextures);
ORE._buffer.updateDebugDisplay(viewPos, debugSprites, tileTextures);
requestAnimationFrame(animate);
// render
ORE._renderer.render(parentContainer);
ORE._debugRenderer.render(debugSpriteContainer);
}
});
};
ORE.updateStats = function (stats)
{
stats.currentFrameCount++;
if( stats.fpsTimer === 0 )
{
stats.fpsTimer = new Date().getTime();
}
else if( new Date().getTime() - stats.fpsTimer > 1000 )
{
var rendererTypeStr = 'Canvas';
if(ORE._renderer instanceof PIXI.WebGLRenderer)
{
rendererTypeStr = 'WebGL';
}
stats.fpsText.text = 'fps: ' + stats.currentFrameCount + '\npixi: ' + PIXI.VERSION + '\nRenderer: ' + rendererTypeStr;
stats.fpsTimer = new Date().getTime();
stats.currentFrameCount = 0;
}
};
})();
|
four51.app.directive('navigation', function() {
var obj = {
restrict: 'E',
templateUrl: 'partials/controls/nav.html',
controller: 'NavCtrl'
}
return obj;
});
four51.app.directive('accountnavigation', function() {
var obj = {
restrict: 'E',
templateUrl: 'partials/controls/accountnav.html',
controller: 'NavCtrl'
}
return obj;
});
//[back] button to help continue shopping without needing to force user to use [products] button http://stackoverflow.com/questions/14070285/how-to-implement-history-back-in-angular-js
four51.app.directive('backStep', function(){
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function () {
history.back();
scope.$apply();
})
}
}
});
// equal height directive, maybe we want bootstrap wells to all be same height- this works
//four51.app.directive('sizeColumn', function() {
// return function(scope, element) {
// scope.$watch('obj', function(){
// var biggestHeight = -1;
// $('.well').each(function(){
// if($(this).height() > biggestHeight){
// biggestHeight = $(this).height();
// }
// });
// element.css('height', element.height(biggestHeight));
// });
// };
//});
|
/*
* Kendo UI v2015.1.408 (http://www.telerik.com/kendo-ui)
* Copyright 2015 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([ "./kendo.autocomplete", "./kendo.datepicker", "./kendo.numerictextbox", "./kendo.combobox", "./kendo.dropdownlist" ], f);
})(function(){
(function($, undefined) {
var kendo = window.kendo,
ui = kendo.ui,
DataSource = kendo.data.DataSource,
Widget = ui.Widget,
CHANGE = "change",
BOOL = "boolean",
ENUM = "enums",
STRING = "string",
NS = ".kendoFilterCell",
EQ = "Is equal to",
NEQ = "Is not equal to",
proxy = $.proxy;
function findFilterForField(filter, field) {
var filters = [];
if ($.isPlainObject(filter)) {
if (filter.hasOwnProperty("filters")) {
filters = filter.filters;
} else if(filter.field == field) {
return filter;
}
}
if (($.isArray(filter))) {
filters = filter;
}
for (var i = 0; i < filters.length; i++) {
var result = findFilterForField(filters[i], field);
if (result) {
return result;
}
}
}
function removeFiltersForField(expression, field) {
if (expression.filters) {
expression.filters = $.grep(expression.filters, function(filter) {
removeFiltersForField(filter, field);
if (filter.filters) {
return filter.filters.length;
} else {
return filter.field != field;
}
});
}
}
function removeDuplicates (dataSelector, dataTextField) {
var getter = kendo.getter(dataTextField, true);
return function(e) {
var items = dataSelector(e),
result = [],
index = 0,
seen = {};
while (index < items.length) {
var item = items[index++],
text = getter(item);
if(!seen.hasOwnProperty(text)){
result.push(item);
seen[text] = true;
}
}
return result;
};
}
var FilterCell = Widget.extend( {
init: function(element, options) {
element = $(element).addClass("k-filtercell");
var wrapper = this.wrapper = $("<span/>").appendTo(element);
var that = this,
dataSource,
viewModel,
passedOptions = options,
first,
type,
operators = that.operators = options.operators || {},
input = that.input = $("<input/>")
.attr(kendo.attr("bind"), "value: value")
.appendTo(wrapper);
Widget.fn.init.call(that, element[0], options);
options = that.options;
dataSource = that.dataSource = options.dataSource;
//gets the type from the dataSource or sets default to string
that.model = dataSource.reader.model;
type = options.type = STRING;
var fields = kendo.getter("reader.model.fields", true)(dataSource) || {};
var target = fields[options.field];
if (target && target.type) {
type = options.type = target.type;
}
if (options.values) {
options.type = type = ENUM;
}
operators = operators[type] || options.operators[type];
if (!passedOptions.operator) {
for (first in operators) { // get the first operator
options.operator = first;
break;
}
}
that._parse = function(value) {
return value + "";
};
if (that.model && that.model.fields) {
var field = that.model.fields[options.field];
if (field) {
if (field.parse) {
that._parse = proxy(field.parse, field);
}
}
}
that.viewModel = viewModel = kendo.observable({
operator: options.operator,
value: null,
operatorVisible: function() {
var val = this.get("value");
return val !== null && val !== undefined && val != "undefined";
}
});
viewModel.bind(CHANGE, proxy(that.updateDsFilter, that));
if (type == STRING) {
that.initSuggestDataSource(options);
}
if (options.inputWidth !== null) {
input.width(options.inputWidth);
}
that._setInputType(options, type);
if (type != BOOL && options.showOperators !== false) {
that._createOperatorDropDown(operators);
} else {
wrapper.addClass("k-operator-hidden");
}
that._createClearIcon();
kendo.bind(this.wrapper, viewModel);
if (type == STRING) {
if (!options.template) {
that.setAutoCompleteSource();
}
}
if (type == ENUM) {
that.setComboBoxSource(that.options.values);
}
that._refreshUI();
that._refreshHandler = proxy(that._refreshUI, that);
that.dataSource.bind(CHANGE, that._refreshHandler);
},
_setInputType: function(options, type) {
var that = this,
input = that.input;
if (typeof (options.template) == "function") {
options.template.call(that.viewModel, {
element: that.input,
dataSource: that.suggestDataSource
});
} else if (type == STRING) {
input.attr(kendo.attr("role"), "autocomplete")
.attr(kendo.attr("text-field"), options.dataTextField || options.field)
.attr(kendo.attr("filter"), options.suggestionOperator)
.attr(kendo.attr("delay"), options.delay)
.attr(kendo.attr("min-length"), options.minLength)
.attr(kendo.attr("value-primitive"), true);
} else if (type == "date") {
input.attr(kendo.attr("role"), "datepicker");
} else if (type == BOOL) {
input.remove();
var radioInput = $("<input type='radio'/>");
var wrapper = that.wrapper;
var inputName = kendo.guid();
var labelTrue = $("<label/>").text(options.messages.isTrue).append(radioInput);
radioInput.attr(kendo.attr("bind"), "checked:value")
.attr("name", inputName)
.val("true");
var labelFalse = labelTrue.clone().text(options.messages.isFalse);
radioInput.clone().val("false").appendTo(labelFalse);
wrapper.append([labelTrue, labelFalse]);
} else if (type == "number") {
input.attr(kendo.attr("role"), "numerictextbox");
} else if (type == ENUM) {
input.attr(kendo.attr("role"), "combobox")
.attr(kendo.attr("text-field"), "text")
.attr(kendo.attr("suggest"), true)
.attr(kendo.attr("filter"), "contains")
.attr(kendo.attr("value-field"), "value")
.attr(kendo.attr("value-primitive"), true);
}
},
_createOperatorDropDown: function(operators) {
var items = [];
for (var prop in operators) {
items.push({
text: operators[prop],
value: prop
});
}
var dropdown = $('<input class="k-dropdown-operator" ' + kendo.attr("bind") + '="value: operator"/>').appendTo(this.wrapper);
this.operatorDropDown = dropdown.kendoDropDownList({
dataSource: items,
dataTextField: "text",
dataValueField: "value",
open: function() {
//TODO calc this
this.popup.element.width(150);
},
valuePrimitive: true
}).data("kendoDropDownList");
this.operatorDropDown.wrapper.find(".k-i-arrow-s").removeClass("k-i-arrow-s").addClass("k-filter");
},
initSuggestDataSource: function(options) {
var suggestDataSource = options.suggestDataSource;
if (!(suggestDataSource instanceof DataSource)) {
if (!options.customDataSource && suggestDataSource) {
suggestDataSource.group = undefined;
}
suggestDataSource =
this.suggestDataSource =
DataSource.create(suggestDataSource);
}
if (!options.customDataSource) {
suggestDataSource._pageSize = undefined;
suggestDataSource.reader.data = removeDuplicates(suggestDataSource.reader.data, this.options.field);
}
this.suggestDataSource = suggestDataSource;
},
setAutoCompleteSource: function() {
var autoComplete = this.input.data("kendoAutoComplete");
if (autoComplete) {
autoComplete.setDataSource(this.suggestDataSource);
}
},
setComboBoxSource: function(values) {
var dataSource = DataSource.create({
data: values
});
var comboBox = this.input.data("kendoComboBox");
if (comboBox) {
comboBox.setDataSource(dataSource);
}
},
_refreshUI: function(e) {
var that = this,
filter = findFilterForField(that.dataSource.filter(), this.options.field) || {},
viewModel = that.viewModel;
that.manuallyUpdatingVM = true;
filter = $.extend(true, {}, filter);
//MVVM check binding does not update the UI when changing the value to null/undefined
if (that.options.type == BOOL) {
if (viewModel.value !== filter.value) {
that.wrapper.find(":radio").prop("checked", false);
}
}
if (filter.operator) {
viewModel.set("operator", filter.operator);
}
viewModel.set("value", filter.value);
that.manuallyUpdatingVM = false;
},
updateDsFilter: function(e) {
var that = this,
model = that.viewModel;
if (that.manuallyUpdatingVM || (e.field == "operator" && model.value === undefined)) {
return;
}
var currentFilter = $.extend({}, that.viewModel.toJSON(), { field: that.options.field });
var expression = {
logic: "and",
filters: []
};
if (currentFilter.value !== undefined && currentFilter.value !== null) {
expression.filters.push(currentFilter);
}
var mergeResult = that._merge(expression);
if (mergeResult.filters.length) {
that.dataSource.filter(mergeResult);
} else {
that.dataSource.filter({});
}
},
_merge: function(expression) {
var that = this,
logic = expression.logic || "and",
filters = expression.filters,
filter,
result = that.dataSource.filter() || { filters:[], logic: "and" },
idx,
length;
removeFiltersForField(result, that.options.field);
for (idx = 0, length = filters.length; idx < length; idx++) {
filter = filters[idx];
filter.value = that._parse(filter.value);
}
filters = $.grep(filters, function(filter) {
return filter.value !== "" && filter.value !== null;
});
if (filters.length) {
if (result.filters.length) {
expression.filters = filters;
if (result.logic !== "and") {
result.filters = [ { logic: result.logic, filters: result.filters }];
result.logic = "and";
}
if (filters.length > 1) {
result.filters.push(expression);
} else {
result.filters.push(filters[0]);
}
} else {
result.filters = filters;
result.logic = logic;
}
}
return result;
},
_createClearIcon: function() {
var that = this;
$("<button type='button' class='k-button k-button-icon'/>")
.attr(kendo.attr("bind"), "visible:operatorVisible")
.html("<span class='k-icon k-i-close'/>")
.click(proxy(that.clearFilter, that))
.appendTo(that.wrapper);
},
clearFilter: function() {
this.viewModel.set("value", null);
},
destroy: function() {
var that = this;
that.filterModel = null;
Widget.fn.destroy.call(that);
kendo.destroy(that.element);
},
events: [
CHANGE
],
options: {
name: "FilterCell",
delay: 200,
minLength: 1,
inputWidth: null,
values: undefined,
customDataSource: false,
field: "",
dataTextField: "",
type: "string",
suggestDataSource: null,
suggestionOperator: "startswith",
operator: "eq",
showOperators: true,
template: null,
messages: {
isTrue: "is true",
isFalse: "is false",
filter: "Filter",
clear: "Clear",
operator: "Operator"
},
operators: {
string: {
eq: EQ,
neq: NEQ,
startswith: "Starts with",
contains: "Contains",
doesnotcontain: "Does not contain",
endswith: "Ends with"
},
number: {
eq: EQ,
neq: NEQ,
gte: "Is greater than or equal to",
gt: "Is greater than",
lte: "Is less than or equal to",
lt: "Is less than"
},
date: {
eq: EQ,
neq: NEQ,
gte: "Is after or equal to",
gt: "Is after",
lte: "Is before or equal to",
lt: "Is before"
},
enums: {
eq: EQ,
neq: NEQ
}
}
}
});
ui.plugin(FilterCell);
})(window.kendo.jQuery);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
// Generated by CoffeeScript 1.9.1
exports.MSGBYPAGE = 30;
exports.LIMIT_DESTROY = 200;
exports.LIMIT_UPDATE = 30;
exports.CONCURRENT_DESTROY = 1;
exports.FETCH_AT_ONCE = 10000;
exports.LIMIT_BY_BOX = 1000;
exports.REFRESH_INTERVAL = 300000;
|
/* */
"format cjs";
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-master-0d7fbad
*/
!function(n,e,i){"use strict";function t(n,e){return["$mdUtil","$window",function(i,t){return{restrict:"A",multiElement:!0,link:function(o,r,a){var d=o.$on("$md-resize-enable",function(){d();var c=r[0],u=c.nodeType===t.Node.ELEMENT_NODE?t.getComputedStyle(c):{};o.$watch(a[n],function(n){if(!!n===e){i.nextTick(function(){o.$broadcast("$md-resize")});var t={cachedTransitionStyles:u};i.dom.animator.waitTransitionEnd(r,t).then(function(){o.$broadcast("$md-resize")})}})})}}}]}e.module("material.components.showHide",["material.core"]).directive("ngShow",t("ngShow",!0)).directive("ngHide",t("ngHide",!1))}(window,window.angular); |
import Ember from 'ember';
export default Ember.Controller.extend({
/**
Text for 'flexberry-togggler' component 'caption' property.
@property caption
@type String
*/
caption: '',
/**
Text for inner 'flexberry-togggler' component 'caption' property.
@property innerCaption
@type String
*/
innerCaption: '',
/**
Text for 'flexberry-togggler' component 'expandedCaption' property.
@property expandedCaption
@type String
*/
expandedCaption: null,
/**
Text for inner 'flexberry-togggler' component 'expandedCaption' property.
@property expandedInnerCaption
@type String
*/
expandedInnerCaption: null,
/**
Text for 'flexberry-togggler' component 'collapsedCaption' property.
@property collapsedCaption
@type String
*/
collapsedCaption: null,
/**
Text for inner 'flexberry-togggler' component 'collapsedCaption' property.
@property collapsedInnerCaption
@type String
*/
collapsedInnerCaption: null,
/**
CSS clasess for i tag.
@property iconClass
@type String
*/
iconClass: '',
/**
Is accordion expanded?
@property expanded
@type Boolean
@default true
*/
expanded: true,
/**
Is inner accordion expanded?
@property innerExpanded
@type Boolean
@default true
*/
innerExpanded: false,
/**
Template text for 'flexberry-textbox' component.
@property componentTemplateText
@type String
*/
componentTemplateText: new Ember.Handlebars.SafeString(
'{{#flexberry-toggler<br>' +
' caption=caption<br>' +
' expandedCaption=expandedCaption<br>' +
' collapsedCaption=collapsedCaption<br>' +
' expanded=expanded<br>' +
' iconClass=iconClass<br>' +
' componentName="myToggler"<br>' +
'}}<br>' +
' {{t "forms.components-examples.flexberry-toggler.settings-example-inner.togglerContent"}}<br>' +
' {{#flexberry-toggler<br>' +
' caption=innerCaption<br>' +
' expandedCaption=expandedInnerCaption<br>' +
' collapsedCaption=collapsedInnerCaption<br>' +
' expanded=innerExpanded<br>' +
' iconClass=iconClass<br>' +
' componentName="myInnerToggler"<br>' +
' }}<br>' +
' {{t "forms.components-examples.flexberry-toggler.settings-example-inner.innerTogglerContent"}}<br>' +
' {{/flexberry-toggler}}<br>' +
'{{/flexberry-toggler}}'
),
/**
Component settings metadata.
@property componentSettingsMetadata
@type Object[]
*/
componentSettingsMetadata: Ember.computed(function() {
let componentSettingsMetadata = Ember.A();
componentSettingsMetadata.pushObject({
settingName: 'caption',
settingType: 'string',
settingDefaultValue: '',
bindedControllerPropertieName: 'caption'
});
componentSettingsMetadata.pushObject({
settingName: 'expandedCaption',
settingType: 'string',
settingDefaultValue: null,
bindedControllerPropertieName: 'expandedCaption'
});
componentSettingsMetadata.pushObject({
settingName: 'collapsedCaption',
settingType: 'string',
settingDefaultValue: null,
bindedControllerPropertieName: 'collapsedCaption'
});
componentSettingsMetadata.pushObject({
settingName: 'expanded',
settingType: 'boolean',
settingDefaultValue: false,
bindedControllerPropertieName: 'expanded'
});
componentSettingsMetadata.pushObject({
settingName: 'innerCaption',
settingType: 'string',
settingDefaultValue: '',
bindedControllerPropertieName: 'innerCaption'
});
componentSettingsMetadata.pushObject({
settingName: 'expandedInnerCaption',
settingType: 'string',
settingDefaultValue: null,
bindedControllerPropertieName: 'expandedInnerCaption'
});
componentSettingsMetadata.pushObject({
settingName: 'collapsedInnerCaption',
settingType: 'string',
settingDefaultValue: null,
bindedControllerPropertieName: 'collapsedInnerCaption'
});
componentSettingsMetadata.pushObject({
settingName: 'innerExpanded',
settingType: 'boolean',
settingDefaultValue: false,
bindedControllerPropertieName: 'innerExpanded'
});
componentSettingsMetadata.pushObject({
settingName: 'iconClass',
settingType: 'string',
settingDefaultValue: undefined,
bindedControllerPropertieName: 'iconClass'
});
return componentSettingsMetadata;
})
});
|
'use strict';
// user-model.js - A mongoose model
//
// See http://mongoosejs.com/docs/models.html
// for more of what you can do here.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
facebookId: { type: String },
facebook: { type: Schema.Types.Mixed },
githubId: { type: String },
github: { type: Schema.Types.Mixed },
googleId: { type: String },
google: { type: Schema.Types.Mixed },
email: {type: String, required: true, unique: true},
password: { type: String, required: true },
createdAt: { type: Date, 'default': Date.now },
updatedAt: { type: Date, 'default': Date.now },
});
const userModel = mongoose.model('user', userSchema);
module.exports = userModel;
|
angular.module('F1FeederApp.controllers', []).
controller('driversController', function($scope, ergastAPIservice) {
$scope.nameFilter = null;
$scope.driversList = [];
$scope.searchFilter = function (driver) {
var keyword = new RegExp($scope.nameFilter, 'i');
return !$scope.nameFilter || keyword.test(driver.Driver.givenName) || keyword.test(driver.Driver.familyName);
};
ergastAPIservice.getDrivers().success(function (response) {
$scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;
});
}).
/* Driver controller */
controller('driverController', function($scope, $routeParams, ergastAPIservice) {
$scope.id = $routeParams.id;
$scope.races = [];
$scope.driver = null;
ergastAPIservice.getDriverDetails($scope.id).success(function (response) {
$scope.driver = response.MRData.StandingsTable.StandingsLists[0].DriverStandings[0];
});
ergastAPIservice.getDriverRaces($scope.id).success(function (response) {
$scope.races = response.MRData.RaceTable.Races;
});
}); |
([
function(module, exports, __webpack_require__) {
__webpack_require__(2);
__webpack_require__(1);
(function(angular) {
(module.exports['myModule'] = angular.module('myModule', ['component', 'component.two']));
}.call(exports, __webpack_require__(3)))
},
function(module, exports, __webpack_require__) {
(function(angular) {
(module.exports['component'] = angular.module('component', []));
}.call(exports, __webpack_require__(3)))
},
function(module, exports, __webpack_require__) {
(function(angular) {
(module.exports['component.two'] = angular.module('component.two', []));
}.call(exports, __webpack_require__(3)))
},
function(module, exports, __webpack_require__) {
(function(angular) {
module.exports = window.angular
}.call(exports, __webpack_require__(3)))
}
])
|
var searchData=
[
['rightchild',['RightChild',['../struct_tree_1_1_node.html#ab9ca9f558858f48a2f6890f5024936f0',1,'Tree::Node']]],
['root',['Root',['../struct_tree.html#ac67db90bca69fd1b4275fafa11ea23ed',1,'Tree']]]
];
|
'use strict';
Connector.playerSelector = '#player-core';
Connector.artistSelector = '#artist';
Connector.trackSelector = '#title';
Connector.getTrackArt = () => $('#player-current-song').attr('rel');
|
import CoverageBar from './components/coverage-bar.js';
import DashboardController from './controllers/controller.js';
import PieChart from './directives/pie-chart.js';
import Project from './factory/project.js';
import ProjectStore from './services/project-status.js';
import StatusBar from './components/status-bar.js';
describe('Classes', () => {
it('should be defined', () => {
expect(CoverageBar).toBeDefined();
expect(DashboardController).toBeDefined();
expect(PieChart).toBeDefined();
expect(Project).toBeDefined();
expect(ProjectStore).toBeDefined();
expect(Project).toBeDefined();
expect(StatusBar).toBeDefined();
});
});
|
module.exports = function (req, res) {
var keystone = req.keystone;
if (!keystone.security.csrf.validate(req)) {
return res.apiError(403, 'invalid csrf');
}
req.list.model.findById(req.params.id, function (err, item) {
if (err) return res.status(500).json({ error: 'database error', detail: err });
if (!item) return res.status(404).json({ error: 'not found', id: req.params.id });
req.list.updateItem(item, req.body, { files: req.files, user: req.user }, function (err) {
if (err) {
var status = err.error === 'validation errors' ? 400 : 500;
var error = err.error === 'database error' ? err.detail : err;
return res.apiError(status, error);
}
res.json(req.list.getData(item));
});
});
};
|
'use strict';
// const webpack = require('webpack');
const NgAnnotatePlugin = require('ng-annotate-webpack-plugin');
module.exports = function(grunt) {
grunt.config('express.dist', {
options: {
script : '<%= paths.dist.server %>/bin/web.js',
debug : true
}
});
grunt.config('webpack.dist', {
output: {
path: '<%= paths.dist.assets %>'
},
plugins: [
// new webpack.optimize.UglifyJsPlugin(),
// new webpack.optimize.OccurenceOrderPlugin(),
// new webpack.optimize.DedupePlugin(),
new NgAnnotatePlugin()
]
});
grunt.config('clean.dist', {
files: [{
dot: true,
src: [ '<%= paths.dist.root %>' ]
}]
});
grunt.config('copy.dist', {
files: [{
expand : true,
dest : '<%= paths.dist.root %>',
src : [
'Procfile',
'package.json',
'server/**/*',
'!<%= paths.dev.server %>/config/ssl/**/*'
]
}]
});
grunt.registerTask('build:dist', [
'clean:dist',
'copy:dist',
'webpack:dist'
]);
grunt.registerTask('serve:dist', [ 'env:prod', 'build:dist', 'express:dist', 'wait' ]);
};
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var http_1 = require('@angular/http');
var core_1 = require('@angular/core');
require('rxjs/add/operator/map'); // add map function to observable
var PizzaService = (function () {
function PizzaService(http) {
this.http = http;
}
PizzaService.prototype.getPizza = function () {
return this.http
.get('assets/pizza.json')
.map(function (res) { return res.json(); });
};
PizzaService = __decorate([
core_1.Injectable(),
__metadata('design:paramtypes', [http_1.Http])
], PizzaService);
return PizzaService;
}());
exports.PizzaService = PizzaService;
//# sourceMappingURL=pizza.service.js.map |
SyncedCron.options = {
log: false,
collectionName: 'cronHistory',
utc: false,
collectionTTL: 172800
}
defaultFrequency = 7; // once a week
defaultTime = '00:00';
var getSchedule = function (parser) {
var frequency = getSetting('newsletterFrequency', defaultFrequency);
var recur = parser.recur();
var schedule;
switch (frequency) {
case 1: // every day
// sched = {schedules: [{dw: [1,2,3,4,5,6,0]}]};
schedule = recur.on(1,2,3,4,5,6,0).dayOfWeek();
case 2: // Mondays, Wednesdays, Fridays
// sched = {schedules: [{dw: [2,4,6]}]};
schedule = recur.on(2,4,6).dayOfWeek();
case 3: // Mondays, Thursdays
// sched = {schedules: [{dw: [2,5]}]};
schedule = recur.on(2,5).dayOfWeek();
case 7: // Once a week (Mondays)
// sched = {schedules: [{dw: [2]}]};
schedule = recur.on(6).dayOfWeek();
default: // Once a week (Mondays)
schedule = recur.on(6).dayOfWeek();
}
return schedule.on(getSetting('newsletterTime', defaultTime)).time();
}
Meteor.methods({
getNextJob: function () {
var nextJob = SyncedCron.nextScheduledAtDate('scheduleNewsletter');
console.log(nextJob);
return nextJob;
}
});
var addJob = function () {
SyncedCron.add({
name: 'scheduleNewsletter',
schedule: function(parser) {
// parser is a later.parse object
return getSchedule(parser);
},
job: function() {
scheduleNextCampaign();
}
});
}
Meteor.startup(function () {
if (getSetting('enableNewsletter', false)) {
addJob();
}
});
|
var afterLogout = null;
Accounts.afterLogout = function(func) {
if (afterLogout) {
throw new Error("Can only call afterLogout once");
} else {
return afterLogout = func;
}
};
var oldLogoutMethod = Meteor.server.method_handlers.logout;
delete Meteor.server.method_handlers.logout;
Meteor.methods({
logout: function() {
var userId = this.userId;
oldLogoutMethod.call(this);
if (afterLogout) {
afterLogout(userId);
}
}
});
|
angular.module('playlytics')
.factory('playlistFactory', ['$localStorage', '$state', function ($localStorage, $state){
var storage = $localStorage.$default({myPlaylists: {}})
var createPlaylist = function(playlist) {
if (storage.myPlaylists[playlist]) {
alert("this playlist already exists")
} else {
storage.myPlaylists[playlist] = [];
}
}
var deleteSong = function(playlist, index) {
storage.myPlaylists[playlist].splice(index,1);
}
function swapIndexes(array, index1, index2) {
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
var moveUp = function(playlist,index) {
swapIndexes(storage.myPlaylists[playlist], index, index-1)
}
var moveDown = function(playlist,index) {
swapIndexes(storage.myPlaylists[playlist], index, index+1)
}
return {
createPlaylist: createPlaylist,
myPlaylists: storage.myPlaylists,
deleteSong: deleteSong,
moveUp: moveUp,
moveDown: moveDown
}
}]);
|
export const containsString = (substring, stringArray = []) => {
let matches = false;
stringArray.forEach((_string) => {
if (substring.includes(_string)) matches = true;
});
return matches;
};
export default { containsString };
|
let webpack = require('webpack');
let path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
output: {
path: path.resolve(__dirname, '../dist'),
filename: 'js/[name].js',
publicPath: '/'
},
resolve: {
modules: [
path.join(__dirname, '../src'),
'node_modules'
],
alias: {
// models: path.join(__dirname, '../src/assets/javascripts/models')
},
extensions: ['.js', '.jsx', '.json', '.less']
},
plugins: [
// Shared code
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
filename: 'js/vendor.bundle.js',
minChunks: Infinity
}),
new HtmlWebpackPlugin({
title: 'React Redux Starter',
filename: 'index.html',
template: 'src/index.html'
})
],
module: {
loaders: [
{
test: /\.(js|jsx)$/,
include: path.resolve(__dirname, '../src'),
loaders: ['babel-loader']
},
// fonts
{
test: /\.(woff|woff2|ttf|eot)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader',
query: {
limit: 8192,
name: 'fonts/[name].[ext]?[hash]'
}
},
// Images
// Inline base64 URLs for <=8k images, direct URLs for the rest
{
test: /\.(png|jpg|jpeg|gif|svg)$/,
loader: 'url-loader',
query: {
limit: 8192,
name: 'images/[name].[ext]?[hash]'
}
}
]
}
};
|
'use strict';
var net = require('net');
var EventEmitter = require('eventemitter3');
exports.run = function () {
var run = require('../../run');
return {
ready: run.ready,
stop: function (test) {
run.stop(function (stopped) {
test.ok(stopped);
});
}
};
}
exports.sleep = function sleep(ms) {
return new Promise(function (resolve) {
setTimeout(resolve.bind(null, true), ms);
});
};
exports.connect = function connect(opts) {
return new Promise(function (resolve, reject) {
var socket = net.connect(opts, function () {
socket.ee = new EventEmitter();
var bufs = [];
socket.on('data', function (data) {
var index, buf, obj;
while ((index = data.indexOf(10)) > -1) {
buf = Buffer.concat(bufs.concat([data.slice(0,
index)]));
data = data.slice(index + 1);
try {
obj = JSON.parse(buf.toString('utf-8'));
} finally {
if (obj) {
socket.ee.emit('record', obj);
}
}
}
if (data.length) {
bufs.push(data);
}
});
resolve(socket);
});
socket.on('error', reject);
});
};
exports.respond = function (socket) {
return new Promise(function (resolve, reject) {
var bufs = [];
socket.on('data', function (data) {
bufs.push(data);
});
socket.on('end', function () {
var data = Buffer.concat(bufs);
var obj;
try {
obj = JSON.parse(data.toString('utf-8'));
} catch (e) {
reject(e);
return;
}
resolve(obj);
});
});
}
|
/**
* This unit test file was auto generated via a gulp task.
* Any formatting issues can be ignored
*/
'use strict';
var _ = require('lodash'),
expect = require('must'),
lodashCollectionHelpers = require('./lodash-collection-helpers-es5.min'),
bankUserInfoData = require('../test/bankUserInfo'),
userInfoData = require('../test/userInfo'),
fullNameInfoData = require('../test/fullNameInfo'),
workInfoData = require('../test/workInfo');
describe("Testing ES5 minified", function() {
describe('Testing Lodash Collection Helpers in release 1.0.0', function() {
describe('Testing isCollection', function() {
it('with undefined value', function() {
expect(lodashCollectionHelpers.isCollection()).to.be(false);
});
it('with null value', function() {
expect(lodashCollectionHelpers.isCollection(null)).to.be(false);
});
it('with string value', function() {
expect(lodashCollectionHelpers.isCollection('should return false')).to.be(false);
});
it('with number value', function() {
expect(lodashCollectionHelpers.isCollection(111)).to.be(false);
});
it('with plain object value', function() {
expect(lodashCollectionHelpers.isCollection({
shouldReturnFalse: true
})).to.be(false);
});
it('with with empty array value', function() {
expect(lodashCollectionHelpers.isCollection([])).to.be(true);
});
it('with array of strings value', function() {
expect(lodashCollectionHelpers.isCollection(['should return false'])).to.be(false);
});
it('with array of numbers value', function() {
expect(lodashCollectionHelpers.isCollection([111])).to.be(false);
});
it('with array of plain objects value', function() {
expect(lodashCollectionHelpers.isCollection([{
shouldReturnTrue: true
}])).to.be(true);
});
});
describe('Testing pickAs', function() {
var workInfo;
beforeEach(function() {
workInfo = workInfoData;
});
it('With plain object and undefined source map returns empty object', function() {
var data = workInfo[0];
var selectedData = lodashCollectionHelpers.pickAs(data);
expect(_.isPlainObject(selectedData)).to.be(true);
expect(_.isEmpty(selectedData)).to.be(true);
});
it('With plain object and array source map to return what _.pick would return', function() {
var data = workInfo[0];
var sourceMap = ['name', 'company'];
var selectedData = lodashCollectionHelpers.pickAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(2);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
});
it('With String source and object source map to return String source', function() {
var data = "Invalid";
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = lodashCollectionHelpers.pickAs(data, sourceMap);
expect(_.isString(data)).to.be(true);
expect(selectedData).to.equal(data);
});
it('With plain object and object source map to return modified object', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = lodashCollectionHelpers.pickAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(2);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
});
it('With plain object and object source map to return modified object nested values', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer',
'details.greeting': 'personalGreeting',
'details.other': 'otherInfo.other'
};
var selectedData = lodashCollectionHelpers.pickAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(4);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.personalGreeting).to.equal(data.details.greeting);
expect(selectedData.otherInfo.other).to.equal(data.details.other);
});
it('With collection and object source map to return modified object', function() {
var sourceMap = {
'employeeId': 'employeeId',
'name': 'employeeName',
'company': 'employer'
};
var selectedData = lodashCollectionHelpers.pickAs(workInfo, sourceMap);
expect(selectedData.length).to.equal(20);
_.each(selectedData, function(item) {
var original = _.find(workInfo, {
employeeId: item.employeeId
});
expect(_.keys(item).length).to.equal(3);
expect(item.employeeId).to.equal(original.employeeId);
expect(item.employeeName).to.equal(original.name);
expect(item.employer).to.equal(original.company);
});
});
});
describe('Testing pickAllAs', function() {
var bankUserInfo,
userInfo,
fullNameInfo,
workInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = fullNameInfoData;
workInfo = workInfoData;
});
it('With plain object and undefined source map returns original object', function() {
var data = workInfo[0];
var selectedData = lodashCollectionHelpers.pickAllAs(data);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and array source map returns original object', function() {
var data = workInfo[0];
var sourceMap = ['name', 'company'];
var selectedData = lodashCollectionHelpers.pickAllAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and object source map to return modified object', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = lodashCollectionHelpers.pickAllAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and object source map to return modified object nested values', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer',
'details.greeting': 'personalGreeting',
'details.other': 'otherInfo.other'
};
var selectedData = lodashCollectionHelpers.pickAllAs(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(8);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.personalGreeting).to.equal(data.details.greeting);
expect(selectedData.otherInfo.other).to.equal(data.details.other);
});
it('With collection and object source map to return modified object', function() {
var sourceMap = {
'employeeId': 'employeeId',
'name': 'employeeName',
'company': 'employer'
};
var selectedData = lodashCollectionHelpers.pickAllAs(workInfo, sourceMap);
expect(selectedData.length).to.equal(20);
_.each(selectedData, function(item) {
var original = _.find(workInfo, {
employeeId: item.employeeId
});
expect(_.keys(item).length).to.equal(6);
expect(item.employeeId).to.equal(original.employeeId);
expect(item.employeeName).to.equal(original.name);
expect(item.employer).to.equal(original.company);
expect(item.email).to.equal(original.email);
expect(item.phone).to.equal(original.phone);
expect(item.details.greeting).to.equal(original.details.greeting);
expect(item.details.other).to.equal(original.details.other);
});
});
});
describe('Testing select', function() {
var workInfo;
beforeEach(function() {
workInfo = workInfoData;
});
it('With plain object and undefined source map returns empty object', function() {
var data = workInfo[0];
var selectedData = lodashCollectionHelpers.select(data);
expect(_.isPlainObject(selectedData)).to.be(true);
expect(_.isEmpty(selectedData)).to.be(true);
});
it('With plain object and array source map to return what _.pick would return', function() {
var data = workInfo[0];
var sourceMap = ['name', 'company'];
var selectedData = lodashCollectionHelpers.select(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(2);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
});
it('With plain object and object source map to return modified object', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = lodashCollectionHelpers.select(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(2);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
});
it('With plain object and object source map to return modified object nested values', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer',
'details.greeting': 'personalGreeting',
'details.other': 'otherInfo.other'
};
var selectedData = lodashCollectionHelpers.select(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(4);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.personalGreeting).to.equal(data.details.greeting);
expect(selectedData.otherInfo.other).to.equal(data.details.other);
});
it('With collection and object source map to return modified object', function() {
var sourceMap = {
'employeeId': 'employeeId',
'name': 'employeeName',
'company': 'employer'
};
var selectedData = lodashCollectionHelpers.select(workInfo, sourceMap);
expect(selectedData.length).to.equal(20);
_.each(selectedData, function(item) {
var original = _.find(workInfo, {
employeeId: item.employeeId
});
expect(_.keys(item).length).to.equal(3);
expect(item.employeeId).to.equal(original.employeeId);
expect(item.employeeName).to.equal(original.name);
expect(item.employer).to.equal(original.company);
});
});
});
describe('Testing selectAll', function() {
var workInfo;
beforeEach(function() {
workInfo = workInfoData;
});
it('With plain object and undefined source map returns original object', function() {
var data = workInfo[0];
var selectedData = lodashCollectionHelpers.selectAll(data);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and array source map returns original object', function() {
var data = workInfo[0];
var sourceMap = ['name', 'company'];
var selectedData = lodashCollectionHelpers.selectAll(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.name).to.equal(data.name);
expect(selectedData.company).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and object source map to return modified object', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer'
};
var selectedData = lodashCollectionHelpers.selectAll(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(6);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.details.greeting).to.equal(data.details.greeting);
expect(selectedData.details.other).to.equal(data.details.other);
});
it('With plain object and object source map to return modified object nested values', function() {
var data = workInfo[0];
var sourceMap = {
'name': 'employeeName',
'company': 'employer',
'details.greeting': 'personalGreeting',
'details.other': 'otherInfo.other'
};
var selectedData = lodashCollectionHelpers.selectAll(data, sourceMap);
expect(_.keys(selectedData).length).to.equal(8);
expect(selectedData.employeeId).to.equal(data.employeeId);
expect(selectedData.employeeName).to.equal(data.name);
expect(selectedData.employer).to.equal(data.company);
expect(selectedData.email).to.equal(data.email);
expect(selectedData.phone).to.equal(data.phone);
expect(selectedData.personalGreeting).to.equal(data.details.greeting);
expect(selectedData.otherInfo.other).to.equal(data.details.other);
});
it('With collection and object source map to return modified object', function() {
var sourceMap = {
'employeeId': 'employeeId',
'name': 'employeeName',
'company': 'employer'
};
var selectedData = lodashCollectionHelpers.selectAll(workInfo, sourceMap);
expect(selectedData.length).to.equal(20);
_.each(selectedData, function(item) {
var original = _.find(workInfo, {
employeeId: item.employeeId
});
expect(_.keys(item).length).to.equal(6);
expect(item.employeeId).to.equal(original.employeeId);
expect(item.employeeName).to.equal(original.name);
expect(item.employer).to.equal(original.company);
expect(item.email).to.equal(original.email);
expect(item.phone).to.equal(original.phone);
expect(item.details.greeting).to.equal(original.details.greeting);
expect(item.details.other).to.equal(original.details.other);
});
});
});
describe('Testing joinOn', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = lodashCollectionHelpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have nested Id attributes', function() {
var joinedCollection = lodashCollectionHelpers.leftJoin([{
ids: {
id: 1
},
value: 'Value One'
}], [{
uids: {
uid: 1
},
value: 'Value One other'
}], 'ids.id', 'uids.uid');
expect(joinedCollection[0].ids.id).to.equal(1);
expect(joinedCollection[0].uids.uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('When both collections have matching attribute names default value is from left side collection', function() {
var joinedCollection = lodashCollectionHelpers.leftJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('With invalid collections returns empty array', function() {
var joinedCollection = lodashCollectionHelpers.joinOn("userInfo", "fullNameInfo", 'uid');
expect(_.isArray(joinedCollection)).to.be(true);
expect(_.isEmpty(joinedCollection)).to.be(true);
});
it('With same named match key', function() {
var joinedCollection = lodashCollectionHelpers.joinOn(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = lodashCollectionHelpers.joinOn(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
it('With differently named keys', function() {
var joinedCollection = lodashCollectionHelpers.joinOn(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
var joinedCollection = lodashCollectionHelpers.joinOn(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
if (_.isPlainObject(originalBankUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else {
expect(_.keys(item).length).to.equal(6);
}
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
});
describe('Testing leftJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = lodashCollectionHelpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have matching attribute names default value is from left side collection', function() {
var joinedCollection = lodashCollectionHelpers.leftJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('With same named match key', function() {
var joinedCollection = lodashCollectionHelpers.leftJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = lodashCollectionHelpers.leftJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
it('With differently named keys', function() {
var joinedCollection = lodashCollectionHelpers.leftJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
var joinedCollection = lodashCollectionHelpers.leftJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
if (_.isPlainObject(originalBankUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else {
expect(_.keys(item).length).to.equal(6);
}
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
});
describe('Testing rightJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = lodashCollectionHelpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have matching attribute names default value is from right side collection', function() {
var joinedCollection = lodashCollectionHelpers.rightJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One other');
});
it('With same named match key', function() {
var joinedCollection = lodashCollectionHelpers.rightJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = lodashCollectionHelpers.rightJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
expect(_.keys(item).length).to.equal(4);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.name).to.equal(originalBankUserInfo.name);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently named keys', function() {
var joinedCollection = lodashCollectionHelpers.rightJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
var joinedCollection = lodashCollectionHelpers.rightJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(10);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
var originalUserInfo = _.find(userInfo, {
uid: item.customerId
});
if (_.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
} else {
expect(_.keys(item).length).to.equal(4);
}
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
});
describe('Testing innerJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = lodashCollectionHelpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have matching attribute names default value is from left side collection', function() {
var joinedCollection = lodashCollectionHelpers.leftJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('With same named match key', function() {
var joinedCollection = lodashCollectionHelpers.innerJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = lodashCollectionHelpers.innerJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(0);
});
it('With differently named keys', function() {
var joinedCollection = lodashCollectionHelpers.innerJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
userInfo = _.takeRight(userInfo, 15);
var joinedCollection = lodashCollectionHelpers.innerJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(5);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.uid
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
});
describe('Testing fullJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = lodashCollectionHelpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('When both collections have matching attribute names default value is from left side collection', function() {
var joinedCollection = lodashCollectionHelpers.leftJoin([{
id: 1,
value: 'Value One'
}], [{
uid: 1,
value: 'Value One other'
}], 'id', 'uid');
expect(joinedCollection[0].id).to.equal(1);
expect(joinedCollection[0].uid).to.equal(1);
expect(joinedCollection[0].value).to.equal('Value One');
});
it('With invalid collections returns empty array', function() {
var joinedCollection = lodashCollectionHelpers.fullJoin('userInfo', 'fullNameInfo', 'uid');
expect(_.isArray(joinedCollection)).to.be(true);
expect(_.isEmpty(joinedCollection)).to.be(true);
});
it('With invalid dest collection returns empty array', function() {
var joinedCollection = lodashCollectionHelpers.fullJoin('userInfo', fullNameInfo, 'uid');
expect(_.isArray(joinedCollection)).to.be(true);
expect(_.isEmpty(joinedCollection)).to.be(true);
});
it('With invalid source collection returns empty array', function() {
var joinedCollection = lodashCollectionHelpers.fullJoin(userInfo, 'fullNameInfo', 'uid');
expect(_.isArray(joinedCollection)).to.be(true);
expect(_.isEmpty(joinedCollection)).to.be(true);
});
it('With same named match key', function() {
var joinedCollection = lodashCollectionHelpers.fullJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(7);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to join', function() {
var joinedCollection = lodashCollectionHelpers.fullJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(40);
_.each(joinedCollection, function(item) {
if (_.keys(item).length === 4) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else if (_.keys(item).length === 6) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
}
});
});
it('With differently named keys', function() {
var joinedCollection = lodashCollectionHelpers.fullJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
if (_.isPlainObject(originalBankUserInfo) && _.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else {
if (_.isPlainObject(originalBankUserInfo)) {
expect(_.keys(item).length).to.equal(4);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else if (_.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
}
}
});
});
it('With differently lengthed Collections', function() {
bankUserInfo = _.take(bankUserInfo, 10);
userInfo = _.takeRight(userInfo, 15);
var joinedCollection = lodashCollectionHelpers.fullJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
if (_.isPlainObject(originalBankUserInfo) && _.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(9);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else {
if (_.isPlainObject(originalBankUserInfo)) {
expect(_.keys(item).length).to.equal(4);
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
} else if (_.isPlainObject(originalUserInfo)) {
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
}
}
});
});
});
describe('Testing leftAntiJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = lodashCollectionHelpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('With same named match key', function() {
fullNameInfo = _.takeRight(fullNameInfo, 5);
var joinedCollection = lodashCollectionHelpers.leftAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(15);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
it('With same named match key & should not have any data to anti join', function() {
var joinedCollection = lodashCollectionHelpers.leftAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(0);
});
it('With same named match key & all data to anti join', function() {
var joinedCollection = lodashCollectionHelpers.leftAntiJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
it('With differently named keys', function() {
bankUserInfo = _.takeRight(bankUserInfo, 5);
var joinedCollection = lodashCollectionHelpers.leftAntiJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(15);
_.each(joinedCollection, function(item) {
var originalUserInfo = _.find(userInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(6);
expect(item.uid).to.equal(originalUserInfo.uid);
expect(item.name).to.equal(originalUserInfo.name);
expect(item.age).to.equal(originalUserInfo.age);
expect(item.eyeColor).to.equal(originalUserInfo.eyeColor);
expect(item.gender).to.equal(originalUserInfo.gender);
expect(item.isActive).to.equal(originalUserInfo.isActive);
});
});
});
describe('Testing rightAntiJoin', function() {
var bankUserInfo,
userInfo,
fullNameInfo;
beforeEach(function() {
bankUserInfo = bankUserInfoData;
userInfo = userInfoData;
fullNameInfo = lodashCollectionHelpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('With same named match key', function() {
userInfo = _.takeRight(userInfo, 5);
var joinedCollection = lodashCollectionHelpers.rightAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(15);
_.each(joinedCollection, function(item) {
var originalFullNameInfo = _.find(fullNameInfo, {
uid: item.uid
});
expect(_.keys(item).length).to.equal(2);
expect(item.uid).to.equal(originalFullNameInfo.uid);
expect(item.fullName).to.equal(originalFullNameInfo.fullName);
});
});
it('With same named match key & should not have any data to anti join', function() {
var joinedCollection = lodashCollectionHelpers.rightAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(0);
});
it('With same named match key & all data to anti join', function() {
var joinedCollection = lodashCollectionHelpers.rightAntiJoin(userInfo, bankUserInfo, 'uid');
expect(joinedCollection.length).to.equal(20);
_.each(joinedCollection, function(item) {
expect(_.keys(item).length).to.equal(4);
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.name).to.equal(originalBankUserInfo.name);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
it('With differently named keys', function() {
userInfo = _.takeRight(userInfo, 5);
var joinedCollection = lodashCollectionHelpers.rightAntiJoin(userInfo, bankUserInfo, 'uid', 'customerId');
expect(joinedCollection.length).to.equal(15);
_.each(joinedCollection, function(item) {
expect(_.keys(item).length).to.equal(4);
var originalBankUserInfo = _.find(bankUserInfo, {
customerId: item.customerId
});
expect(item.customerId).to.equal(originalBankUserInfo.customerId);
expect(item.name).to.equal(originalBankUserInfo.name);
expect(item.bank).to.equal(originalBankUserInfo.bank);
expect(item.balance).to.equal(originalBankUserInfo.balance);
});
});
});
describe('Testing fullAntiJoin', function() {
var leftCollection,
rightCollection1,
rightCollection2,
rightCollection3,
userInfo,
fullNameInfo;
beforeEach(function() {
leftCollection = [{
uid: 1,
value: 'only on left'
}, {
uid: 2,
value: 'sharedLeft'
}];
rightCollection1 = [{
uid: 3,
value: 'only on right'
}, {
uid: 2,
value: 'sharedRight'
}];
rightCollection2 = [{
id: 3,
value: 'only on right'
}, {
id: 2,
value: 'sharedRight'
}];
rightCollection3 = [{
uid: 3,
value: 'only on right1'
}, {
uid: 4,
value: 'sharedRight2'
}];
userInfo = userInfoData;
fullNameInfo = lodashCollectionHelpers.selectAll(fullNameInfoData, {
name: 'fullName'
});
});
it('With same named match key', function() {
var joinedCollection = lodashCollectionHelpers.fullAntiJoin(leftCollection, rightCollection1, 'uid');
expect(joinedCollection.length).to.equal(2);
_.each(joinedCollection, function(item) {
expect(_.keys(item).length).to.equal(2);
if (item.uid === 1) {
expect(item.uid).to.equal(leftCollection[0].uid);
expect(item.value).to.equal(leftCollection[0].value);
} else {
expect(item.uid).to.equal(rightCollection1[0].uid);
expect(item.value).to.equal(rightCollection1[0].value);
}
});
});
it('With same named match key & should not have any data to anti join', function() {
var joinedCollection = lodashCollectionHelpers.fullAntiJoin(userInfo, fullNameInfo, 'uid');
expect(joinedCollection.length).to.equal(0);
});
it('With same named match key & all data to anti join', function() {
var joinedCollection = lodashCollectionHelpers.fullAntiJoin(leftCollection, rightCollection3, 'uid');
expect(joinedCollection.length).to.equal(4);
_.each(joinedCollection, function(item, index) {
expect(_.keys(item).length).to.equal(2);
if (item.uid === 1 || item.uid === 2) {
expect(item.uid).to.equal(leftCollection[index].uid);
expect(item.value).to.equal(leftCollection[index].value);
} else {
expect(item.uid).to.equal(rightCollection3[index - 2].uid);
expect(item.value).to.equal(rightCollection3[index - 2].value);
}
});
});
it('With differently named keys', function() {
var joinedCollection = lodashCollectionHelpers.fullAntiJoin(leftCollection, rightCollection2, 'uid', 'id');
expect(joinedCollection.length).to.equal(2);
_.each(joinedCollection, function(item) {
expect(_.keys(item).length).to.equal(2);
if (item.uid === 1) {
expect(item.uid).to.equal(leftCollection[0].uid);
expect(item.value).to.equal(leftCollection[0].value);
} else {
expect(item.uid).to.equal(rightCollection2[0].uid);
expect(item.value).to.equal(rightCollection2[0].value);
}
});
});
});
});
describe('Testing Lodash Collection Helpers in release 1.1.0', function() {
describe('Testing indexBy', function() {
var collection;
beforeEach(function() {
collection = _.map(_.range(4), function(value) {
return {
uid: value,
test: 'test ' + value,
static: 'static-value',
data: {
list: _.range(value * 2)
}
};
});
});
it('Call with non-collection returns an empty plain Object', function() {
var indexedCollection = lodashCollectionHelpers.indexBy('non collection', 'uid');
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(true);
});
it('Call with missing iteree returns indexed on collection index number', function() {
var indexedCollection = lodashCollectionHelpers.indexBy(collection);
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, uidKey) {
var originalItem = collection[_.parseInt(uidKey)];
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem);
})).to.be(true);
});
it('Non-String Index value returns indexed on collection index number', function() {
var indexedCollection = lodashCollectionHelpers.indexBy(collection, 'data.list');
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, uidKey) {
var originalItem = collection[_.parseInt(uidKey)];
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem);
})).to.be(true);
});
it('Index by uid string key', function() {
var indexedCollection = lodashCollectionHelpers.indexBy(collection, 'uid');
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, uidKey) {
var originalItem = _.find(collection, {
uid: _.parseInt(uidKey)
});
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem);
})).to.be(true);
});
it('Index by function', function() {
var indexedCollection = lodashCollectionHelpers.indexBy(collection, function(item) {
return _.get(item, 'uid');
});
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, uidKey) {
var originalItem = _.find(collection, {
uid: _.parseInt(uidKey)
});
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem);
})).to.be(true);
});
it('Index by static value', function() {
var indexedCollection = lodashCollectionHelpers.indexBy(collection, 'static');
expect(_.isPlainObject(indexedCollection)).to.be(true);
expect(_.isEmpty(indexedCollection)).to.be(false);
expect(_.every(indexedCollection, function(item, key) {
var originalItem = _.find(collection, {
uid: _.parseInt(item.uid)
});
var expectedKey = 'static-value';
if (item.uid > 0) {
expectedKey = expectedKey + '(' + item.uid + ')';
}
return _.isPlainObject(item) && _.isPlainObject(originalItem) && _.isEqual(item, originalItem) && expectedKey === key;
})).to.be(true);
});
});
describe('Testing uniqify', function() {
var collection;
beforeEach(function() {
collection = _.map(_.range(4), function(value) {
return {
test: 'test ' + value,
static: 'static-value',
data: {
list: _.range(value * 2)
}
};
});
});
it('Call with non-collection returns original input value', function() {
var uniqifiedCollection = lodashCollectionHelpers.uniqify('non collection');
expect(_.isString(uniqifiedCollection)).to.be(true);
expect(uniqifiedCollection).to.equal('non collection');
});
it('Base uniqification', function() {
var idKey = 'uuid';
var uniqifiedCollection = lodashCollectionHelpers.uniqify(collection);
expect(lodashCollectionHelpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with "" id key', function() {
var idKey = 'uuid';
var uniqifiedCollection = lodashCollectionHelpers.uniqify(collection, "");
expect(lodashCollectionHelpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with null id key', function() {
var idKey = 'uuid';
var uniqifiedCollection = lodashCollectionHelpers.uniqify(collection, null);
expect(lodashCollectionHelpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with non-string id key', function() {
var idKey = 'uuid';
var uniqifiedCollection = lodashCollectionHelpers.uniqify(collection, {
test: 'test'
});
expect(lodashCollectionHelpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with user defined id key', function() {
var idKey = 'uid';
var uniqifiedCollection = lodashCollectionHelpers.uniqify(collection, idKey);
expect(lodashCollectionHelpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with user defined function', function() {
var idKey = 'uid';
var uniqifiedCollection = lodashCollectionHelpers.uniqify(collection, idKey, function(item) {
return _.get(item, 'test');
});
expect(lodashCollectionHelpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with user defined function that returns static value', function() {
var idKey = 'uid';
var uniqifiedCollection = lodashCollectionHelpers.uniqify(collection, idKey, function(item) {
return _.get(item, 'static');
});
expect(lodashCollectionHelpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
it('Uniqify with user defined function that returns non-string value', function() {
var idKey = 'uid';
var uniqifiedCollection = lodashCollectionHelpers.uniqify(collection, idKey, function(item) {
return _.get(item, 'data.list');
});
expect(lodashCollectionHelpers.isCollection(uniqifiedCollection)).to.be(true);
expect(_.every(uniqifiedCollection, function(item, index) {
var originalItem = collection[index];
var unUniqifiedItem = _.omit(_.cloneDeep(item), [idKey]);
var isUnique = _.filter(uniqifiedCollection, _.set({}, idKey, _.get(item, idKey))).length === 1;
return _.isString(_.get(item, idKey)) && isUnique && _.isPlainObject(originalItem) && _.isEqual(unUniqifiedItem, originalItem);
})).to.be(true);
});
});
});
});
|
/**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import GitRepo from 'git-repository';
import task from './lib/task';
// TODO: Update deployment URL
const remote = {
name: 'github',
url: 'https://github.com/patmood/svg-jsx-online.git',
branch: 'gh-pages',
};
/**
* Deploy the contents of the `/build` folder to GitHub Pages.
*/
export default task(async function deploy() {
// Initialize a new Git repository inside the `/build` folder
// if it doesn't exist yet
const repo = await GitRepo.open('build', { init: true });
await repo.setRemote(remote.name, remote.url);
// Fetch the remote repository if it exists
if ((await repo.hasRef(remote.url, remote.branch))) {
await repo.fetch(remote.name);
await repo.reset(`${remote.name}/${remote.branch}`, { hard: true });
await repo.clean({ force: true });
}
// Build the project in RELEASE mode which
// generates optimized and minimized bundles
process.argv.push('release');
await require('./build')();
// Push the contents of the build folder to the remote server via Git
await repo.add('--all .');
await repo.commit('Update ' + new Date().toISOString());
await repo.push(remote.name, 'master:' + remote.branch);
});
|
$(document).on('click', '.dropdown-menu li a', function () {
document.getElementById("selected_album").innerHTML = $(this).text();
});
function selectAlbum() {
var album_id = event.target.value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("selected_album").innerHTML = xhttp.responseText;
}
};
if(album_id != "new_album") {
//window.location.assign("gallery/albumDetails/" + album_id);
xhttp.open("GET", "gallery/albumDetails/" + album_id, true);
xhttp.send();
}
else {
window.location.assign("gallery/create_album");
}
} |
'use strict';
angular.module('myApp.view3', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view3', {
templateUrl: 'view3/view3.html',
controller: 'View3Ctrl'
});
}])
.controller('View3Ctrl', function ($http, $scope) {
$scope.countries = [{
value: 'dk',
label: 'dk'
}, {
value: 'nor',
label: 'nor'
}];
$scope.options = [{
value: 'search',
label: 'normal search'
}, {
value: 'vat',
label: 'vat'
}, {
value: 'name',
label: 'name'
}, {
value: 'produ',
label: 'production unit'
}, {
value: 'phone',
label: 'phone number'
}];
$scope.find = function () {
var dataObj = {
search: $scope.search,
option: $scope.optionList.label,
country: $scope.countryList.label
};
$http.post('api/company', dataObj)
.success(function (data, status, headers, config) {
$scope.data = data;
})
.error(function (data, status, headers, config) {
});
};
}); |
var gulp = require('gulp'),
pug = require('gulp-pug'),
sass = require('gulp-sass'),
ts = require('gulp-typescript'),
shell = require('gulp-shell'),
webpack = require('webpack-stream')
var tsProject = ts.createProject('tsconfig.json')
var path = {
assets: ['app/assets/**/*'],
views: ['app/views/**/*.pug', '!app/views/**/_*.pug'],
scss: ['app/scss/launcher.scss'],
scripts: ['app/src/**/*.ts']
}
gulp.task('assets', function() {
return gulp.src(path.assets)
.pipe(gulp.dest('./dist/assets'))
})
gulp.task('views', function () {
return gulp.src(path.views)
.pipe(pug())
.pipe(gulp.dest('./dist'))
})
gulp.task('scss', function () {
return gulp.src(path.scss)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./dist/assets/css'))
})
gulp.task('compile:ts', function() {
return tsProject.src()
.pipe(tsProject())
.js.pipe(gulp.dest('./dist/assets/js'))
})
gulp.task('compile', ['compile:ts'], function () {
return gulp.src('./dist/assets/js/application.js')
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./dist/assets/js'));
})
gulp.task('build', ['assets', 'views', 'scss', 'compile'])
gulp.task('watch', ['build'], function() {
gulp.watch(path.assets, ['assets'])
gulp.watch(path.views, ['views'])
gulp.watch('app/scss/**/*.scss', ['scss'])
gulp.watch(path.scripts, ['compile'])
})
gulp.task('run', ['watch'], shell.task([
'electron .'
]))
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Transfer Schema
*/
var TransferSchema = new Schema({
destination: {
type: Schema.ObjectId,
ref: 'Station'
},
source: {
type: Schema.ObjectId,
ref: 'Station'
},
amount: {
type: Number,
default: 0,
required: 'Please fill Bloodtransfer amount',
trim: true
},
bloodType: {
type: String,
default: "empty",
required: 'Please fill blood type',
trim: true
},
state: {
type: String,
default: "pending",
required: 'Please state',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Transfer', TransferSchema);
|
/*global define:true */
if (typeof define !== 'function') {
var define = require('amdefine')(module);
}
define(['./sprintf'], function (sprintf) {
'use strict';
function splitTrimFilterArgs(commaSepArgs) { //parse 'one, two' into ['one', 'two']
if (!commaSepArgs) return [];
return commaSepArgs.split(',') //split on commas
.map(function (s) { return s.trim(); }) //trim
.filter(function (s) { return (s); }); //filter out empty strings
}
/**
@param patternFn regex + fn or splitStr + fn
*/
function parseReduce(accum, patternFn) {
if (typeof(accum) !== 'string') return accum; // already matched
var m = (patternFn.regex) ? patternFn.regex.exec(accum) : accum.split(patternFn.splitStr);
if (m) return patternFn.fn(m, accum); // pass in matches and origStr, return result obj
return accum; // no match, return str, will try next matcher
}
function parseStr(str, parseMatchers, errStr) {
var result = parseMatchers.reduce(parseReduce, str);
if (typeof(result) !== 'string') { // matched
return result;
} else { // no match
throw new Error(sprintf(errStr, str));
}
}
return {
splitTrimFilterArgs: splitTrimFilterArgs,
parseStr: parseStr
};
});
|
function OnRun($rootScope, AppSettings, xdLocalStorage) {
'ngInject';
xdLocalStorage.init({
iframeUrl:'http://www.agenciadigitala.local:80/cross-domain-storage/magical-frame.html'
}).then(function () {
console.log('Got iframe ready to site');
xdLocalStorage.getItem('privateToken').then(function (response) {
console.log('TOKEN PRIVADO:', response.value);
});
});
// change page title based on state
$rootScope.$on('$stateChangeSuccess', (event, toState) => {
$rootScope.pageTitle = '';
if (toState.title) {
$rootScope.pageTitle += toState.title;
$rootScope.pageTitle += ' \u2014 '; //
}
$rootScope.pageTitle += AppSettings.appTitle;
});
}
export default OnRun;
|
define([
"../_base/config", "../_base/json", "../_base/kernel", /*===== "../_base/declare", =====*/ "../_base/lang",
"../_base/xhr", "../sniff", "../_base/window",
"../dom", "../dom-construct", "../query", "require", "../aspect", "../request/iframe"
], function(config, json, kernel, /*===== declare, =====*/ lang, xhr, has, win, dom, domConstruct, query, require, aspect, _iframe){
// module:
// dojo/io/iframe
dojo.deprecated("dojo/io/iframe", "Use dojo/request/iframe.", "2.0");
/*=====
var __ioArgs = declare(kernel.__IoArgs, {
// method: String?
// The HTTP method to use. "GET" or "POST" are the only supported
// values. It will try to read the value from the form node's
// method, then try this argument. If neither one exists, then it
// defaults to POST.
// handleAs: String?
// Specifies what format the result data should be given to the
// load/handle callback. Valid values are: text, html, xml, json,
// javascript. IMPORTANT: For all values EXCEPT html and xml, The
// server response should be an HTML file with a textarea element.
// The response data should be inside the textarea element. Using an
// HTML document the only reliable, cross-browser way this
// transport can know when the response has loaded. For the html
// handleAs value, just return a normal HTML document. NOTE: xml
// is now supported with this transport (as of 1.1+); a known issue
// is if the XML document in question is malformed, Internet Explorer
// will throw an uncatchable error.
// content: Object?
// If "form" is one of the other args properties, then the content
// object properties become hidden form form elements. For
// instance, a content object of {name1 : "value1"} is converted
// to a hidden form element with a name of "name1" and a value of
// "value1". If there is not a "form" property, then the content
// object is converted into a name=value&name=value string, by
// using xhr.objectToQuery().
});
=====*/
/*=====
return kernel.io.iframe = {
// summary:
// Deprecated, use dojo/request/iframe instead.
// Sends an Ajax I/O call using and Iframe (for instance, to upload files)
create: function(fname, onloadstr, uri){
// summary:
// Creates a hidden iframe in the page. Used mostly for IO
// transports. You do not need to call this to start a
// dojo/io/iframe request. Just call send().
// fname: String
// The name of the iframe. Used for the name attribute on the
// iframe.
// onloadstr: String
// A string of JavaScript that will be executed when the content
// in the iframe loads.
// uri: String
// The value of the src attribute on the iframe element. If a
// value is not given, then dojo/resources/blank.html will be
// used.
},
setSrc: function(iframe, src, replace){
// summary:
// Sets the URL that is loaded in an IFrame. The replace parameter
// indicates whether location.replace() should be used when
// changing the location of the iframe.
},
doc: function(iframeNode){
// summary:
// Returns the document object associated with the iframe DOM Node argument.
}
};
=====*/
var mid = _iframe._iframeName;
mid = mid.substring(0, mid.lastIndexOf('_'));
var iframe = lang.delegate(_iframe, {
// summary:
// Deprecated, use dojo/request/iframe instead.
// Sends an Ajax I/O call using and Iframe (for instance, to upload files)
create: function(){
return iframe._frame = _iframe.create.apply(_iframe, arguments);
},
// cover up delegated methods
get: null,
post: null,
send: function(/*__ioArgs*/args){
// summary:
// Function that sends the request to the server.
// This transport can only process one send() request at a time, so if send() is called
// multiple times, it will queue up the calls and only process one at a time.
var rDfd;
//Set up the deferred.
var dfd = xhr._ioSetArgs(args,
function(/*Deferred*/dfd){
// summary:
// canceller function for xhr._ioSetArgs call.
rDfd && rDfd.cancel();
},
function(/*Deferred*/dfd){
// summary:
// okHandler function for xhr._ioSetArgs call.
var value = null,
ioArgs = dfd.ioArgs;
try{
var handleAs = ioArgs.handleAs;
//Assign correct value based on handleAs value.
if(handleAs === "xml" || handleAs === "html"){
value = rDfd.response.data;
}else{
value = rDfd.response.text;
if(handleAs === "json"){
value = json.fromJson(value);
}else if(handleAs === "javascript"){
value = kernel.eval(value);
}
}
}catch(e){
value = e;
}
return value;
},
function(/*Error*/error, /*Deferred*/dfd){
// summary:
// errHandler function for xhr._ioSetArgs call.
dfd.ioArgs._hasError = true;
return error;
}
);
var ioArgs = dfd.ioArgs;
var method = "GET",
form = dojo.byId(args.form);
if(args.method && args.method.toUpperCase() === "POST" && form){
method = "POST";
}
var options = {
method: method,
handleAs: args.handleAs === "json" || args.handleAs === "javascript" ? "text" : args.handleAs,
form: args.form,
query: form ? null : args.content,
data: form ? args.content : null,
timeout: args.timeout,
ioArgs: ioArgs
};
if(options.method){
options.method = options.method.toUpperCase();
}
if(config.ioPublish && kernel.publish && ioArgs.args.ioPublish !== false){
var start = aspect.after(_iframe, "_notifyStart", function(data){
if(data.options.ioArgs === ioArgs){
start.remove();
xhr._ioNotifyStart(dfd);
}
}, true);
}
rDfd = _iframe(ioArgs.url, options, true);
ioArgs._callNext = rDfd._callNext;
rDfd.then(function(){
dfd.resolve(dfd);
}).otherwise(function(error){
dfd.ioArgs.error = error;
dfd.reject(error);
});
return dfd;
},
_iframeOnload: win.global[mid + '_onload']
});
lang.setObject("dojo.io.iframe", iframe);
return iframe;
});
|
/*
=========================================================
Name: ImportHS6e
GitHub: https://github.com/eepjr24/ImportHS6e
Roll20 Contact: eepjr24
Version: 1.03
Last Update: 02/21/2022
=========================================================
Updates:
Removed Rolls section from parsing (caused JSON bugs and was not used)
Added support for Charges
Updated END calcs for many powers
Handled Limitations that change END cost
Added support for END Reserves
Added support for powers with END and Charges
Added more abbreviation for complications
*/
var API_Meta = API_Meta || {};
API_Meta.ImportHS6e = { offset: Number.MAX_SAFE_INTEGER, lineCount: -1 };
{
try { throw new Error(''); } catch (e) { API_Meta.ImportHS6e.offset = (parseInt(e.stack.split(/\n/)[1].replace(/^.*:(\d+):.*$/, '$1'), 10) - (21)); }
}
const ImportHS6e = (() => {
let version = '1.xx',
lastUpdate = 1645461785103,
debug_log = 0, // Debug settings, all debug values 1=on
logObjs = 1, // Output character object to api log
comp_log = 0, // Debug complications
cskl_log = 0, // Debug combat skill Levels
move_log = 0, // Debug movement debug
perk_log = 0, // Debug perks
pnsk_log = 0, // Debug penalty skill levels
powr_log = 1, // Debug powers
remv_log = 0, // Debug attribute removal
resv_log = 0, // Debug reserves
skil_log = 0, // Debug skills
sklv_log = 0, // Debug skill levels
stat_log = 0, // Debug characteristics
taln_log = 0, // Debug talents
comp_rem = 1, // Complications removal flag, all removal flags 1=remove
cskl_rem = 1, // Combat skill levels removal flag
powr_rem = 1, // Powers removal flag
perk_rem = 1, // Debug removal flag
pskl_rem = 1, // Penalty skill level removal flag
resv_rem = 1, // Reserves removal flag
skil_rem = 1, // Skills removal flag
sklv_rem = 1, // Skill levels removal flag
stat_rem = 1, // Characteristics removal flag
taln_rem = 1, // Talents removal flag
move_rem = 1; // Movement removal flag
const checkInstall= () => { // Display version information on startup.
var updated = new Date(lastUpdate);
log('\u0EC2\u2118 [ImportHS6e v'+version+', ' + updated.getFullYear() + "/" + (updated.getMonth()+1) + "/" + updated.getDate() + "]");
};
const showImportHelp = (who) => { // Show the help for the tool. Needs work.
if (who){ who = "/w " + who.split(" ", 1)[0] + " "; }
sendChat('Hero System 6e Character Importer', who + ' ' );
};
const logDebug = (logval) => { // Conditional log function, logs if debug flag is found
if(debug_log!=0) {log(logval);}
};
const removeExistingAttributes = (alst) => { // Remove existing attributes from roll20 character sheet
for (var c=0; c < alst.length; c++) // Loop character sheet atribute list
{
let attr = alst[c].get("name"), // Get attribute name
attrtype = attr.split("_");
if (!(/^repeating_/.test(attr))){continue;} // Only remove repeating elements
switch (attrtype[1]) // Create the complication description based on the type
{
case "complications":
if(!comp_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
case "combatskills":
if(!cskl_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
case "penaltyskills":
if(!pskl_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
case "perks":
if(!perk_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
case "powers":
if(!powr_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
case "skilllevels":
if(!sklv_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
case "skills":
if(!skil_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
case "talents":
if(!taln_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
case "reserves":
if(!resv_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
case "moves":
if(!move_rem){break;}
alst[c].remove(); // Remove them
if (remv_log){logDebug(attr);} // Debug removal
break;
default:
sendChat("i6e_API", "Unhandled repeating element removal: (" + attrtype[1] + ") " + attr);
break;
}
}
};
const createOrSetAttr = (atnm, val, mval, cid) => { // Set an individual attribute if it exists, otherwise create it.
var objToSet = findObjs({type: 'attribute', characterid: cid, name: atnm})[0]
if(val===undefined)
{
sendChat("i6e_API", "Undefined value in set attribute: " + atnm);
return;
}
if(typeof objToSet === "number" && IsNaN(val))
{
sendChat("i6e_API", "Type mismatch (numeric expected) in set attribute: " + atnm);
return;
}
if(objToSet===undefined) // If attribute does not exist, create otherwise set current value.
{
return createObj('attribute', {name: atnm, current: val, max: mval, characterid: cid});
} else
{
objToSet.set('current', val);
objToSet.set('max', mval);
return objToSet;
}
};
const createCharacteristics = (stlst, chid) => {
for (const [key, value] of Object.entries(stlst)) { // Set the characteristics
let chnm = key + '_base';
createOrSetAttr(chnm, value.value, "", chid);
if(/^(end|body|stun)/.test(chnm)) // Handle display values for body, end and stun.
{
chnm = key.toUpperCase();
createOrSetAttr(chnm, value.value, "", chid);
}
if(!!stat_log){logDebug("Set " + chnm + " to " + value.value);} // Log characteristic assignment
}
};
const createFeatures = (hdj, chid) => {
//createOrSetAttr("alternate_ids", hdj., chid); // Future Placeholder
createOrSetAttr("player_name", hdj.playername, "", chid);
createOrSetAttr("height", hdj.height, "", chid);
createOrSetAttr("weight", hdj.weight, "", chid);
createOrSetAttr("hair", hdj.hair, "", chid);
createOrSetAttr("eyes", hdj.eye, "", chid);
createOrSetAttr("appearance", hdj.appearance, "", chid);
createOrSetAttr("background", hdj.background, "", chid);
createOrSetAttr("personality", hdj.personality,"", chid);
createOrSetAttr("quotes", hdj.quote, "", chid);
createOrSetAttr("tactics", hdj.tactics, "",chid);
createOrSetAttr("campaign", hdj.campUse, "",chid);
};
const createSkills = (sklst, cid) => { // Create all skills
for (var h=0; h < sklst.length; h++) // Loop through HD sheet skills.
{
if(sklst[h].type==="Skill Levels"){continue;} // Skill Levels are handled in their own routine
let uuid = generateUUID().replace(/_/g, "Z"), // Generate a UUID for skill grouping
rspre = "repeating_skills_" + uuid + "_skill_", // Build the string prefix for skill names
rsnm = rspre + "name", // Build the skill name value
rshi = rspre + "has_increase", // Build the has increase name value
rshr = rspre + "has_roll", // Build the has roll name value
rsrs = rspre + "roll_show", // Build the roll show name value
rsrt = rspre + "roll_target", // Build the roll target name value
rsch = rspre + "char", // Build the skill characteristic name value
rsin = rspre + "increase", // Build the skill increase name value
rsrf = rspre + "roll_formula", // Build the roll formula name value
hs = sklst[h],
targ = hs.roll,
roll = Number(targ.substring(0, Math.min(targ.length-1,2))), // Convert the roll to integer
sknm = "",
incr = hs.level,
noch = (hs.char == "None" ? "" : hs.char);
switch (hs.type)
{
case "Defense Maneuver":
sknm = hs.name + hs.input;
break;
case "Perception":
noch = "INT"
default:
sknm = hs.text.trim();
break;
}
// Create the skill entries.
createOrSetAttr(rsnm, sknm, "", cid);
createOrSetAttr(rshr, !!roll, "", cid);
createOrSetAttr(rshi, !!incr, "", cid);
createOrSetAttr(rsin, incr, "", cid);
if(!!roll)
{
createOrSetAttr(rsrs, targ, "", cid);
createOrSetAttr(rsrf, "&{template:hero6template} {{charname=@{character_name}}} {{action=@{skill_name}}} {{roll=[[3d6]]}} {{target=" + roll + "}} {{base=9}} {{stat= " + roll-9 + "}} {{lvls=" + incr + "}}", "", cid);
createOrSetAttr(rsrt, roll, "", cid);
}
if(!(/^(GENERAL)/.test(noch) || noch === undefined))
{
createOrSetAttr(rsch, noch, "", cid);
}
}
};
// TODO Check with Roll20 users to see if I need to duplicate records where level >1 in HD
const createSkillLevels = (sllst, cid) => {
for (var h=0; h < sllst.length; h++) // Loop through HD sheet skills.
{
if(sllst[h].type!=="Skill Levels"){continue;} // Other skill levels are handled in their own routine
let uuid = generateUUID().replace(/_/g, "Z"), // Generate a UUID for skill grouping
rspre = "repeating_skilllevels_" + uuid, // Build the string prefix for skill names
rsnm = rspre + "_skill_level", // Build the skill name value
rshi = rspre + "_radio_skill_level"; // Build the level name value
createOrSetAttr(rsnm, sllst[h].name.trim(), "", cid);
createOrSetAttr(rshi, 0, "", cid);
if(!!sklv_log){logDebug("Set " + sllst[h].name.trim());} // Log skill level assignment
}
};
const createMovement = (mlst, cid) => {
if(!mlst){return;} // If movement list is not undefined
let uuid = ""; // UUID for complication grouping
for (const [key, value] of Object.entries(mlst)) { // Set the movement values
cmnm = key + '_combat';
ncnm = key + '_noncombat';
if(/^(leap)/.test(cmnm)) // Handle split for leap
{
createOrSetAttr('h' + cmnm, value.combat, "", cid);
createOrSetAttr('h' + ncnm, value.noncombat, "", cid);
createOrSetAttr('v' + cmnm, value.primary.combat.value/2 + "m", "", cid);
createOrSetAttr('v' + ncnm, value.combat, "", cid);
if (move_log){logDebug(cmnm);} // Debug movement
} else if (/^(run|swim)/.test(cmnm)) // Handle run, swim (always appear)
{
createOrSetAttr(cmnm, value.combat, "", cid);
createOrSetAttr(ncnm, value.noncombat, "", cid);
if (move_log){logDebug(cmnm);} // Debug movement
} else // Handle all other cases
{
switch (key) // Create the movement description based on the type
{
case "fly":
cmnm = "Flight";
if (move_log){logDebug(cmnm);} // Debug movement
break;
case "swing":
cmnm = "Swinging";
if (move_log){logDebug(cmnm);} // Debug movement
break;
case "teleport":
cmnm = "Teleportation";
if (move_log){logDebug(cmnm);} // Debug movement
break;
case "tunnel":
cmnm = "Tunneling";
if (move_log){logDebug(cmnm);} // Debug movement
break;
default:
sendChat("i6e_API", "Unhandled repeating element movement: (" + key + ") " + value.combat);
break;
}
uuid = generateUUID().replace(/_/g, "Z"); // Generate a UUID for complication grouping
mvnm = "repeating_moves_" + uuid + "_spec_move_name"; // Build the movement repeating name
mvcb = "repeating_moves_" + uuid + "_spec_move_combat"; // Build the combat repeating name
mvnc = "repeating_moves_" + uuid + "_spec_move_noncombat"; // Build the noncombat repeating name
createOrSetAttr(mvnm, cmnm, "", cid);
createOrSetAttr(mvcb, value.combat, "", cid);
createOrSetAttr(mvnc, value.noncombat, "", cid);
}
}
};
const createCombatLevels = (cllst, cid) => {
let ccb = "",
rocv = "",
romv = "",
rdcv = "",
rdmv = "",
rdc = "",
clnm = "";
// Create all combat skill levels
for (var cl=0; cl < cllst.length; cl++) // Loop through combat skill levels
{
let hcs = cllst[cl]; // Get combat skill level JSON attribute
if(!(/^(Combat Skill Levels)/.test(hcs.name))){continue;} // Only process Combat Skill Levels
uuid = generateUUID().replace(/_/g, "Z"); // Generate a UUID for complication grouping
clnm = "repeating_combatskills_" + uuid + "_csl_name"; // Build the combat level repeating name
ccb = "repeating_combatskills_" + uuid + "_csl_checkbox";
rocv = "repeating_combatskills_" + uuid + "_radio_csl_ocv";
romv = "repeating_combatskills_" + uuid + "_radio_csl_omcv";
rdcv = "repeating_combatskills_" + uuid + "_radio_csl_dcv";
rdmv = "repeating_combatskills_" + uuid + "_radio_csl_dmcv";
rdc = "repeating_combatskills_" + uuid + "_radio_csl_dc";
createOrSetAttr(clnm, hcs.text, "", cid);
createOrSetAttr(ccb, 0, "", cid);
createOrSetAttr(rocv, 0, "", cid);
createOrSetAttr(romv, 0, "", cid);
createOrSetAttr(rdcv, 0, "", cid);
createOrSetAttr(rdmv, 0, "", cid);
createOrSetAttr(rdc, 0, "", cid);
if(!!cskl_log){logDebug("Set " + hcs.name );} // Log skill level assignment
}
};
const createPenaltyLevels = (plst, cid) => {
let pcb = "",
rocv = "",
rmod = "",
rdcv = "",
psnm = "";
for (var p=0; p < plst.length; p++) // Loop through Skills
{
let hps = plst[p]; // Get skill JSON attribute
if(!(/^(Penalty Skill Levels)/.test(hps.name))){continue;} // Only process Penalty Skill Levels
logDebug(hps.text);
uuid = generateUUID().replace(/_/g, "Z"); // Generate a UUID for penalty skill grouping
psnm = "repeating_penaltyskills_" + uuid + "_psl_name"; // Build the penalty skill repeating name
pcb = "repeating_penaltyskills_" + uuid + "_psl_checkbox";
rocv = "repeating_penaltyskills_" + uuid + "_radio_psl_";
rdcv = "repeating_penaltyskills_" + uuid + "_radio_psl_";
rmod = "repeating_penaltyskills_" + uuid + "_radio_psl_";
createOrSetAttr(psnm, hps.text, "", cid);
createOrSetAttr(pcb, 0, "", cid);
// TODO Use OptionID to set appropriate flags for ocv, dcv, rmod Example:SINGLEDCV
createOrSetAttr(rocv, 0, "", cid);
createOrSetAttr(rmod, 0, "", cid);
createOrSetAttr(rdcv, (/^(SINGLEDCV)/.test(hps.optionID)), "", cid);
if(!!pnsk_log){logDebug("Set " + hps.text);} // Log penalty skill level assignment
}
};
const createComplications = (clst, cid) => {
let rcap = "", // Complication cost name
rcnm = "", // Complication name
compnm = "", // Complication description
ad1 = "", // Complication adder 1
ad2 = "", // Complication adder 2
ad3 = "", // Complication adder 3
ad4 = "", // Complication adder 4
ad5 = "", // Complication adder 5
md1 = "", // Complication modifier 1
md2 = "", // Complication modifier 2
md3 = "", // Complication modifier 3
uuid = "";
// Create all complications
for (var c=0; c < clst.length; c++) // Loop through complications
{
var hc = clst[c]; // Get complication JSON attribute
uuid = generateUUID().replace(/_/g, "Z"); // Generate a UUID for complication grouping
rcnm = "repeating_complications_" + uuid + "_complication"; // Build the complication repeating name
rcap = rcnm + "_cost";
if (hc.adders[4])
{ // Populate 5 adders
ad5 = hc.adders[4].input;
ad4 = hc.adders[3].input;
ad3 = hc.adders[2].input;
ad2 = hc.adders[1].input;
ad1 = hc.adders[0].input;
} else if (hc.adders[3])
{ // Populate first 4 adders
ad4 = hc.adders[3].input;
ad3 = hc.adders[2].input;
ad2 = hc.adders[1].input;
ad1 = hc.adders[0].input;
} else if (hc.adders[2])
{ // Populate first 3 adders
ad3 = hc.adders[2].input;
ad2 = hc.adders[1].input;
ad1 = hc.adders[0].input;
} else if (hc.adders[1])
{ // Populate first 2 adders
ad2 = hc.adders[1].input;
ad1 = hc.adders[0].input;
} else if (hc.adders[0])
{ // Populate 1st adder
ad1 = hc.adders[0].input;
}
if (hc.modifiers[2]!==undefined)
{ // Populate 3 modifiers
md3 = hc.modifiers[2].input;
md2 = hc.modifiers[1].input;
md1 = hc.modifiers[0].input;
} else if (hc.modifiers[1]!==undefined)
{ // Populate 2 modifiers
md2 = hc.modifiers[1].input;
md1 = hc.modifiers[0].input;
} else if (hc.modifiers[0]!==undefined)
{ // Populate 1 modifier
md1 = hc.modifiers[0].input;
}
switch (hc.XMLID) // Create the complication description based on the type
{
case "ACCIDENTALCHANGE": // Accidental Change
compnm = "Acc Chg: " + hc.input + ", " + ad1 + ", " + ad2;
break;
case "DEPENDENCE": // Dependence
compnm = "Dep: " + hc.input + ", " + ad1 + " / " + ad3 + ", " + ad2;
break;
case "DEPENDENTNPC": // Dependent NPC
compnm = "DNPC: " + hc.input + ", " + ad1 + ", " + ad2 + ", " + ad3;
break;
case "DISTINCTIVEFEATURES": // Distinctive Features
compnm = "DF: " + hc.input + ", " + ad1 + ", " + ad2 + ", " + ad3;
break;
case "ENRAGED": // Enraged
compnm = "Enraged: " + hc.input + ", " + ad2 + ", " + ad3 + ", " + ad1 ;
break;
case "GENERICDISADVANTAGE": // Custom - manually fill in
compnm = "Populate Custom Complication Here";
break;
case "HUNTED": // Hunted
compnm = "Hunted: " + hc.input + " (" + ad1 + ", " + ad2 + ", " + ad3 + ")";
break;
case "PHYSICALLIMITATION": // Physical Complication
compnm = "Phys Comp: " + hc.input + ", " + ad1 + ", " + ad2 + ", " + ad3;
break;
case "PSYCHOLOGICALLIMITATION": // Psychological Complication
compnm = "Psy Comp: " + hc.input + ", " + ad1 + ", " + ad2 + ", " + ad3;
break;
case "RIVALRY": // Negative Reputation
compnm = "Rival: " + ad2 + " (" + ad1 + ", " + ad3 + ", " + ad4 + ", " + ad5;
break;
case "REPUTATION": // Negative Reputation
compnm = "Neg Rep: " + hc.input + ", " + ad1 + ", " + ad2 + ", " + ad3;
break;
case "SOCIALLIMITATION": // Social Complication
compnm = "Soc Comp: " + hc.input + ", " + ad1 + ", " + ad2 + ", " + ad3;
break;
case "SUSCEPTIBILITY": // Susceptiblity
compnm = "Susc: " + hc.input + "(" + ad1 + " " + ad2 + ")";
break;
// TODO Check the various combinations and combine cases if possible.
case "UNLUCK": // Unluck
compnm = name;
break;
case "VULNERABILITY": // Vulnerability
compnm = "Vuln: " + hc.input + " - " + md1 + " (" + ad1 + ")";
break;
default:
sendChat("i6e_API", "Unhandled complication type: " + hc.XMLID);
break;
}
// TODO make abbreviations optional
compnm = compnm.replace(/[,\s]+$/g, '') // Trim trailing comma and space as needed
.replace('As Powerful', 'AsPow') // Abbreviate As Powerful
.replace('Common', 'Com') // Abbreviate Common
.replace('Frequently', 'Freq') // Abbreviate Frequent
.replace('Infrequently', 'Infreq') // Abbreviate Infrequent
.replace('Less Powerful', 'LessPow') // Abbreviate Less Powerful
.replace('Major', 'Maj') // Abbreviate Major
.replace('Moderate', 'Mod') // Abbreviate Moderate
.replace('More Powerful', 'MoPow') // Abbreviate More Powerful
.replace('Professional', 'Prof.') // Abbreviate Professional
.replace('Rival Aware of Rivalry', 'Aware') // Abbreviate Rival wording
.replace('Rival is', '') // Remove Rival wording (redundant)
.replace('Rival Unaware of Rivalry', 'Unaware') // Abbreviate Rival wording
.replace('Romantic', 'Rom.') // Abbreviate Romantic
.replace('Seek to Harm or Kill Rival', 'Harm/Kill') // Shorten Seek to Harm or Kill
.replace('Seek to Outdo, Embarrass or Humiliate Rival', 'Outdo/Emb.') // Shorten Seek Outdo
.replace('Slightly', 'Slight') // Abbreviate Slightly
.replace('Strong', 'Str') // Abbreviate Strong
.replace('Total', 'Tot') // Abbreviate Total
.replace('Uncommon', 'Unc') // Abbreviate Uncommon
.replace('Very Common', 'VC') // Abbreviate Very Common
createOrSetAttr(rcap, hc.active, "", cid); // Assign the complication cost
createOrSetAttr(rcnm, compnm, "", cid); // Assign the complication name
}
};
const createReserve = (resnm, amt, cid) => {
let rrnm = "",
rre = "";
logDebug(resnm);
uuid = generateUUID().replace(/_/g, "Z"); // Generate a UUID for penalty skill grouping
rrnm = "repeating_reserves_" + uuid + "_reserve_name"; // Build the penalty skill repeating name
rre = "repeating_reserves_" + uuid + "_reserve_end";
createOrSetAttr(rrnm, resnm, "", cid);
createOrSetAttr(rre, amt, amt, cid);
if(!!resv_log){logDebug("Set " + resnm + " to " + amt);} // Log penalty skill level assignment
};
// Calculate the power modifiers (Advantages / Limitations) and endurance modifiers for a power
const figurePowerMod = (modf, calc, endf) => {
let lval = 0,
aval = 0,
rend = 1.0, // Set return end to 1 by default
rsrr = 0,
mset = 0, // Flag to determine if a modifier set the rend
chgs = 0,
val = "";
if(endf === 0){ // If the power does not cost END by default
rend = 0; // Set return to 0 to start
if(!modf.length){ // If there are no modifiers
rend = "no cost";
mset = 1;
}
}
modf.forEach(m => { // Loop all modifiers
val = m.value;
val = val.replace('¾', '.75') // Substitue decimals for fractions
.replace('½', '.5')
.replace('¼', '.25')
.replace(/[^\x00-\xBF]+/g, '')
if(val.substring(0,1) === "-"){lval=lval+parseFloat(val);} // Add to limitations
if(val.substring(0,1) === "+"){aval=aval+parseFloat(val);} // Add to advantages
if(m.type === "Reduced Endurance")
{
if(m.input === "Half END") // Set to half endurance cost
{
rend = .5;
mset = 1;
} else if (m.input === "0 END") // Set to zero endurance cost
{
rend = 0;
mset = 1;
}
} else if(m.type === "Increased Endurance Cost")
{
rend = parseInt(m.input.substring(1,3).trim()); // Set to increased endurance cost
mset = 1;
} else if(m.type === "Costs Endurance") // Handle limitations that add endurance cost
{
if(m.input === "Costs Half Endurance")
{
rend = .5;
mset = 1;
} else // Set to normal endurance cost
{
rend = 1.0;
mset = 1;
}
} else if (m.type === "Charges")
{
chgs = m.input;
}
// TODO handle rsr figures, need HD examples
})
// If the power costs no end naturally and was not set by a modifier,
// set to no cost
if(mset === 0 && rend === 0){
rend = "no cost";
}
switch (calc)
{
case "lim": // Figure limitation value
return lval*-1;
case "adv": // Figure advantage value
return aval;
case "end": // Figure endurance multiplier
return rend;
case "rsr": // Figure skill roll
return rsrr;
case "chg": // Figure charges
return chgs;
default: // Unknown calculation
return sendChat("i6e_API", "Unknown calculation value: " + calc);
}
};
const createSimplePower = (pwjson, uuid, cid) => {
let pwnm = '',
pwdesc = '',
end = 0, // Store endurance as a number
ap = 0, // Store active points as a number
bp = 0, // Store base points as a number
rp = 0, // Store real points as a number
hclas = pwjson.class,
rppre = "repeating_powers_" + uuid, // Build the string prefix for power labels
rppow = rppre + "_power",
rpnm = rppre + "_power_name", // Build the power name label
rppf = rppre + "_use_power_formula", // Build the power formula label
rppf2 = rppre + "_use_power2_formula", // Build the 2nd power formula label
rpec = rppre + "_power_end_cost", // Build the power end cost label
rpea = rppre + "_power_end_ap_cost", // Build the power ap end cost label
rpes = rppre + "_power_end_str_cost", // Build the power str end cost label
rprc = rppre + "_power_remaining_charges", // Build the power remaining charges / end label
rppe = rppre + "_power_expand",
rppat = rppre + "_pow_attack", // Is this power a pre-selected attack option?
rpbp = rppre + "_pow_base_points",
rpap = rppre + "_pow_active_points",
rpan = rppre + "_pow_active_points_no_reduced_end",
rprp = rppre + "_pow_real_points",
rprl = rppre + "_power_real_cost",
rpbd = rppre + "_attack_base_dice",
rpbs = rppre + "_attack_base_dice_show",
rpsd = rppre + "_attack_str_dice",
rpss = rppre + "_attack_str_dice_show",
rpse = rppre + "_attack_str_for_end",
rpmd = rppre + "_attack_maneuver_dice_show",
rpcd = rppre + "_attack_csl_dice_show",
rpac = rppre + "_attack_cv",
rped = rppre + "_attack_extra_dice",
rpds = rppre + "_attack_extra_dice_show",
rpad = rppre + "_attack_dice",
rpas = rppre + "_attack_dice_show",
rppn = rppre + "_pow_advantages_no_reduced_end",
rppa = rppre + "_pow_advantages",
rppl = rppre + "_pow_limitations",
rpem = rppre + "_end_multiplier",
rpps = rppre + "_power_end_source",
rpaus = rppre + "_attack_uses_str",
rpaw = rppre + "_attack_wizard",
rpadc = rppre + "_attack_die_cost",
rpatt = rppre + "_attack_type",
rpatk = rppre + "_attack_killing",
rpahl = rppre + "_attack_hit_location",
rppft = rppre + "_pow_frame_type", // Power Framework type
rppfn = rppre + "_pow_framework_name", // Power framework name
rppef = rppre + "_power_end_fixed", // Fixed END value for Charges and Reserves
rpper = rppre + "_power_end_reserve_name", // Name of Reserve for Charges and Reserves
pwtype = pwjson.type.trim(), // Power type
xmlid = pwjson.XMLID,
pwlvl = pwjson.level,
pwsn = "", // Power short name (no prefix)
lim = 0.0, // Base power limitation value (without list of framework lims)
adv = 0.0, // Base power advantage value (without list of framework lims)
endm = 1, // Endurance multiplier
ocv = getAttrByName(cid, 'ocv'),
mocv = getAttrByName(cid, 'omcv'),
zero = 0,
ka = 0, // Killing attack flag (1 for RKA, HKA)
wiz = 0, // Does this power use the wiard for die calculation
cvtyp = "", // Combat Value Type (OCV or OMCV)
coste = 0, // Whether the power costs end or not
adc = 0, // Attack die cost (CP per die of power)
att = "",
wizc = "",
hl = 0, // Power uses hit locations
chg = 0, // Number of charges for the power
strbs = 0; // Power uses strength as a basis
if (isNaN(pwjson.end) || pwjson.end==="") {end = 0;} else {end = parseInt(pwjson.end)}
if (isNaN(pwjson.active)) {ap = 0;} else {ap = parseInt(pwjson.active)}
if (isNaN(pwjson.base)) {bp = 0;} else {bp = parseInt(pwjson.base)}
if(pwjson.desc===undefined){
sendChat("i6e_API", "Power has undefined description, JSON template version is incorrect: " + pwnm);
} else
{
pwdesc = pwjson.desc.replace(/[^\x00-\xBF]+/g, '');
}
if (pwjson.name.trim() === "No Name Supplied")
{
pwnm = pwjson.prefix + pwtype;
pwsn = pwtype;
} else
{
pwnm = pwjson.prefix + pwjson.name.trim();
pwsn = pwjson.name.trim();
}
if(pwjson.prefix === "" && pwjson.framework === ""){
pft = "";
}
logDebug(xmlid + " 1 CostE: " + coste);
// Create the power entries. Reordered to correct order for sheet macro to read.
createOrSetAttr(rpnm, pwnm, "", cid); // Assign the power name
switch (xmlid)
{
// Handle Effect powers
case "AID":
adc = 6;
case "DISPEL":
adc = 3;
case "DRAIN":
adc = 10;
case "HEALING":
adc = 10;
case "TRANSFORM":
// TODO Figure out a way to determine Transform Severity to set Active Die Cost
coste = 1;
adc = bp/pwlvl;
logDebug(adc);
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=Effect}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=Effect}} {{description=" + pwdesc + "}}", "", cid);
att = "Effect";
wiz = 1;
hl = 0;
cvtyp = "OCV";
break;
// Handle Body Die Roll powers
case "ENTANGLE":
adc = 10;
case "FLASH":
// TODO Figure out a way to determine targetting or non to set Active Die Cost
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=Die Rolls}} {{count=BODY}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=Die Rolls}} {{count=BODY}}{{description=" + pwdesc + "}}", "", cid);
att = "BODY only";
adc = 5;
wiz = 1;
hl = 0;
coste = 1;
cvtyp = "OCV";
break;
// Handle attack roll only powers
case "DARKNESS":
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{hitlocation=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=STUN}} {{count=BODY}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{hitlocation=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=STUN}} {{count=BODY}}{{description=" + pwdesc + "}}", "", cid);
wiz = 0;
hl = 0;
coste = 1;
cvtyp = "OCV";
break;
// Handle Standard Attack powers
case "ENERGYBLAST":
adc = 5;
case "HANDTOHANDATTACK":
strbs = 1;
adc = 5;
case "TELEKINESIS":
// TODO Look up ADC cost in character sheet
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{hitlocation=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=STUN}} {{count=BODY}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{hitlocation=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=STUN}} {{count=BODY}}{{description=" + pwdesc + "}}", "", cid);
wiz = 0;
hl = 0;
att = "STUN & BODY";
coste = 1;
cvtyp = "OCV";
break;
// Handle Killing Attack powers
case "HKA":
strbs = 1;
case "RKA":
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{hitlocation=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{killing=1}} {{type=BODY}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{base=" + ocv + "}} {{ocv=" + ocv + "}} {{attack=[[3d6]]}} {{hitlocation=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{killing=1}} {{type=BODY}}{{description=" + pwdesc + "}}", "", cid);
adc = 15;
ka = 1;
hl = 1;
wiz = 1;
coste = 1;
att = "BODY";
cvtyp = "OCV";
break;
// Handle Luck powers
case "LUCK":
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{damage=[[" + pwjson.damage + "]]}} {{type=Die Rolls}} {{count=Luck}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{damage=[[" + pwjson.damage + "]]}} {{type=Die Rolls}} {{count=Luck}}{{description=" + pwdesc + "}}", "", cid);
att = "Luck";
adc = 5;
hl = 0;
wiz = 1;
break;
// Handle Ego Attack powers
case "EGOATTACK":
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{ocv=" + mocv + "}} {{attack=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=STUN}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{ocv=" + mocv + "}} {{attack=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=STUN}}{{description=" + pwdesc + "}}", "", cid);
adc = 10;
wiz = 1;
hl = 0;
att = "STUN";
coste = 1;
cvtyp = "OMCV";
break;
// Handle Mental Effect powers
case "MENTALILLUSIONS":
case "MINDCONTROL":
case "MINDSCAN":
case "TELEPATHY":
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{ocv=" + mocv + "}} {{attack=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=Effect}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{ocv=" + mocv + "}} {{attack=[[3d6]]}} {{damage=[[" + pwjson.damage + "]]}} {{type=Effect}}{{description=" + pwdesc + "}}", "", cid);
att = "Effect";
coste = 1;
cvtyp = "OMCV";
hl = 0;
adc = 5;
wiz = 1;
break;
// Handle Misc powers (cost 0 END default)
// case "ABSORPTION": check spelling
case "ARMOR":
// Figure out how to add armor to resistant Defenses on sheet.
case "DAMAGENEGATION":
case "DCV":
case "LIFESUPPORT":
case "MENTALDEFENSE":
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{description=" + pwdesc + "}}", "", cid); // Assign the power name
hl = 0;
wiz = 0;
break;
// Handle Misc powers (cost END default)
case "FLIGHT":
case "FORCEFIELD":
// Figure out how to add FF to resistant Defenses on sheet.
case "FORCEWALL":
case "IMAGES":
case "INVISIBILITY":
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{description=" + pwdesc + "}}", "", cid); // Assign the power name
coste = 1;
hl = 0;
wiz = 0;
break;
// Handle Senses
case "HRRP":
case "NIGHTVISION":
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{description=" + pwdesc + "}}", "", cid); // Assign the power name
hl = 0;
wiz = 0;
break;
// Handle END Reserves
case "ENDURANCERESERVE":
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{description=" + pwdesc + "}}", "", cid); // Assign the power name
sendChat("i6e_API", "END Reserves in BETA, check reserve: " + pwnm);
// Parse END and REC from description
//chg = pwjson.end.replace(/\[*\]*/g, ''); // Calculate max charges
createReserve("R_" + pwnm, chg, cid); // Create the charge Pool
// createOrSetAttr(rpper, "R_" + pwnm, "", cid); // Set the charge pool name
// createOrSetAttr(rppef, "1", "", cid); // Set charges per use to 1
endm = "no cost";
logDebug("Charges: " + chg);
hl = 0;
wiz = 0;
break;
// Handle Frameworks
case "GENERIC_OBJECT":
if(pwjson.framework !== ""){
hl = 0;
wiz = 0;
endm = "no cost";
pfn = pwnm;
pft = pwjson.framework;
// Frameworks can have advantages and limitations that carry to all entries. Store them for later use.
lav = adv;
llv = lim;
}
break;
// Handle everything that falls through
default:
createOrSetAttr(rppf, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}}", "", cid);
createOrSetAttr(rppf2, "&{template:hero6template} {{charname=@{character_name}}} {{power=" + pwnm + "}} {{description=" + pwdesc + "}}", "", cid); // Assign the power name
sendChat("i6e_API", "Defaulted Power Type: " + xmlid);
hl = 0;
wiz = 0;
break;
}
// Calculate limitation, advantages and endurance multipliers
if(pwjson.modifiers.length)
{
lim = figurePowerMod(pwjson.modifiers, "lim", coste);
adv = figurePowerMod(pwjson.modifiers, "adv", coste);
chg = figurePowerMod(pwjson.modifiers, "chg", coste);
}
endm = figurePowerMod(pwjson.modifiers, "end", coste);
if(!!powr_log){logDebug(xmlid + " Lim,Adv,Chg,Endm: " + lim + ", " + adv + ", " + chg + ", " + endm);}
createOrSetAttr(rppow, pwdesc, "", cid); // Assign the power description
createOrSetAttr(rpbp, pwjson.base, "", cid); // Assign base points (string)
createOrSetAttr(rppa, adv, "", cid); // Power advantage total
createOrSetAttr(rpap, ap, "", cid); // Assign active points (number)
createOrSetAttr(rpan, parseInt(pwjson.base)*adv, "", cid); // Active Points without reduced end
createOrSetAttr(rppl, lim, "", cid); // Power limitation total
if(pft!=="") // Set up framework attributes
{
if(pft==="MP"){
createOrSetAttr(rppft, "Multipower Pool", "", cid);
} else if (pft==="VPP"){
createOrSetAttr(rppft, "Variable Power Pool", "", cid);
}
createOrSetAttr(rppfn, pwnm, "", cid);
}
if (endm === 0){
createOrSetAttr(rppn, adv-(.5), "", cid); // Power advantage total without Reduced End
} else if (endm === .5){
createOrSetAttr(rppn, adv-(.25), "", cid); // Power advantage total without Reduced End
} else {
createOrSetAttr(rppn, adv, "", cid); // Power advantage total
}
// Use case: Absorption, Cannot be stunned, Clinging, etc.
// Also Lim: Costs 1/2 END
if(endm === 1){ // Set Endurance Multiplier
coste = 1;
createOrSetAttr(rpem, "1x END", "", cid);
} else if (endm === 0){
coste = 0;
createOrSetAttr(rpem, "0 END", "", cid);
} else if (endm === .5){
coste = 1;
createOrSetAttr(rpem, "½ END", "", cid);
} else if (endm === "no cost"){
coste = 0;
createOrSetAttr(rpem, "no cost", "", cid);
} else if (endm > 1){
coste = 1;
createOrSetAttr(rpem, "Costs " + endm + "x", "", cid);
}
if (chg !== 0){
sendChat("i6e_API", "Charges in BETA, check power: " + pwnm);
createReserve("C_" + pwsn, chg, cid); // Create the charge Pool
createOrSetAttr(rpper, "C_" + pwsn, "", cid); // Set the charge pool name
createOrSetAttr(rppef, "1", "", cid); // Set charges per use to 1
createOrSetAttr(rprc, chg, "", cid); // Endurance Cost - Remaining Charges (string)
logDebug(pwsn + " Charges: " + chg);
}
// Assign Endurance Source
if(chg !== 0 && coste !== 0){
createOrSetAttr(rpps, "Both", "", cid); // Set Endurance Source to Both
} else if (chg !== 0 && coste === 0){
createOrSetAttr(rpps, "Reserve", "", cid); // Set Endurance Source to Reserve
} else if ((chg === 0 && coste === 0) || (pwjson.framework!=="")){
createOrSetAttr(rpps, "none", "", cid); // Set Endurance Source to none
} else {
createOrSetAttr(rpps, "END", "", cid); // Set Endurance Source to END
}
// Set the slot types for MP and VPP
if(pwjson.prefix!=="" && pft!=="")
{
adv = adv + lav; // Add list advantage to list items
lim = lim + llv; // Add list limitation to list items
if(pft==="MP")
{
createOrSetAttr(rppfn, pfn, "", cid);
if(/^\d*f/.test(pwjson.real)) // Test to see if the cost ends in f.
{
createOrSetAttr(rppft, "MP Slot, fixed", "", cid);
} else
{
createOrSetAttr(rppft, "MP Slot, variable", "", cid);
}
}
if(pft==="VPP")
{
createOrSetAttr(rppfn, pfn, "", cid);
createOrSetAttr(rppft, "VPP Slot", "", cid);
}
}
// TODO: Check if this is needed? Does the sheet calculate it?
// Calculate real points from AP and Limitations.
if(ap !== 0){
rp = ap/(1+lim);
dec = rp - Math.floor(rp);
if(dec > .5){rp = Math.ceil(rp)}else{rp = Math.floor(rp)}; // Round the real points
}
// createOrSetAttr(rpec, pwjson.end, "", cid); // Endurance Cost (string)
// createOrSetAttr(rpea, end, "", cid); // Endurance Cost - AP (number)
// createOrSetAttr(rpes, zero, "", cid); // Endurance Cost - STR (number)
createOrSetAttr(rppe, zero, "", cid); // FLAG: Is power wizard expanded?
wizc = wiz.toString();
createOrSetAttr(rppat, wizc, "", cid); // FLAG: Is power preselected attack option
createOrSetAttr(rpbd, pwjson.damage, "", cid); // Base dice
createOrSetAttr(rpbs, pwjson.damage, "", cid); // Base dice show
createOrSetAttr(rprp, rp, "", cid); // Real Points
// Calculated by sheet?
//createOrSetAttr(rprl, pwjson.real, "", cid); // Real Cost
createOrSetAttr(rpsd, " ", "", cid); // Strength dice
createOrSetAttr(rpss, " ", "", cid); // Strength dice show
createOrSetAttr(rpse, zero, "", cid); // STR for END
createOrSetAttr(rpmd, " ", "", cid); // Attack Maneuver dice show
createOrSetAttr(rpcd, " ", "", cid); // CSL dice show
createOrSetAttr(rped, " ", "", cid); // Extra dice
createOrSetAttr(rpds, " ", "", cid); // Extra dice show
createOrSetAttr(rpad, pwjson.damage, "", cid); // Attack dice
createOrSetAttr(rpas, pwjson.damage, "", cid); // Attack dice show
if(!!wiz)
{
createOrSetAttr(rpaus, strbs, "", cid);
createOrSetAttr(rpaw, "", "", cid);
// TODO: Figure out how to set.
// createOrSetAttr(rpatt, , "", cid);
createOrSetAttr(rpatk, ka, "", cid);
createOrSetAttr(rpac, cvtyp, "", cid);
createOrSetAttr(rpadc, adc, "", cid);
if(strbs)
{
createOrSetAttr(rpac, cvtyp, "", cid);
} else
{
createOrSetAttr(rpac, cvtyp, "", cid);
}
createOrSetAttr(rpahl, hl, "", cid);
}
};
const createPerks = (plst, cid) => {
let pknm = '';
// Create all perks
for (var p=0; p < plst.length; p++) // Loop through HD sheet powers
{
UUID = generateUUID().replace(/_/g, "Z"); // Generate a UUID for perk grouping
pknm = "repeating_perks_" + UUID + "_perk_name";
createOrSetAttr(pknm, plst[p].desc.trim(), "", cid);
}
};
const createTalents = (tlst, cid) => {
let objToSet = [],
tlnm = '';
// Create all talents
for (var t=0; t < tlst.length; t++) // Loop through HD sheet powers
{
if(tlst[t].desc===undefined){continue;}
UUID = generateUUID().replace(/_/g, "Z"); // Generate a UUID for perk grouping
tlnm = "repeating_perks_" + UUID + "_perk_name";
createOrSetAttr(tlnm, tlst[t].desc.trim(), "", cid);
}
};
const generateUUID = () => { // Generate a UUID (original code by The Aaron)
let a = 0;
let b = [];
let c = (new Date()).getTime() + 0;
let f = 7;
let e = new Array(8);
let d = c === a;
a = c;
for (; 0 <= f; f--) {
e[f] = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".charAt(c % 64);
c = Math.floor(c / 64);
}
c = e.join("");
if (d) {
for (f = 11; 0 <= f && 63 === b[f]; f--) {
b[f] = 0;
}
b[f]++;
} else {
for (f = 0; 12 > f; f++) {
b[f] = Math.floor(64 * Math.random());
}
}
for (f = 0; 12 > f; f++){
c += "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".charAt(b[f]);
}
return c;
};
const decodeEditorText = (t, o) =>{ // Clean up notes and decode (code by The Aaron)
let w = t;
o = Object.assign({ separator: '\r\n', asArray: false },o);
// Token GM Notes
if(/^%3Cp%3E/.test(w)){
w = unescape(w);
}
if(/^<p>/.test(w)){
let lines = w.match(/<p>.*?<\/p>/g)
.map( l => l.replace(/^<p>(.*?)<\/p>$/,'$1'));
return o.asArray ? lines : lines.join(o.separator);
}
// neither
return t;
};
const handleInput = (msg) => { // Monitor the chat for commands, process sheet if import called
if (!(msg.type === "api" &&
/^!(importHS6e|i6e)(\s|$)/.test(msg.content))) { // Ignore messages not intended for this script
return;
}
///////////////////////////////////////////////////////////////////////////////// Begin processing API message
let args = msg.content.split(/\s+--/).slice(1);
args.forEach(a => { // Loop all attributes
switch (a)
{
case "help": // Show help in Chat
//return showImportHelp(who);
break;
case "debug": // Log debug info to API Console
debug_log = 1;
break;
case "statdebug": // Log debug info to API Console
stat_log = 1;
break;
case "movedebug": // Log debug info to API Console
move_log = 1;
break;
case "powrdebug": // Log debug info to API Console
powr_log = 1;
break;
case "compdebug": // Log debug info to API Console
comp_log = 1;
break;
case "perkdebug": // Log debug info to API Console
perk_log = 1;
break;
case "talndebug": // Log debug info to API Console
taln_log = 1;
break;
case "skildebug": // Log debug info to API Console
skil_log = 1;
break;
case "showobj": // Show current objects on API Console
logObjs = 1;
break;
default:
//return sendChat("Unknown argument value", who, "", "ImportHS6e" );
break;
}
})
if (debug_log===1){log("Debug is ON");}else{log("Debug is OFF");} // Display current Debug status.
var selected = msg.selected;
if (selected===undefined) // Must have a token selected
{
sendChat("i6e_API", "Please select a token.");
return;
}
let token = getObj("graphic",selected[0]._id); // Get selected token
let character = getObj("character",token.get("represents")); // Get character linked to token
if (character===undefined) // Token must have valid character assigned.
{
sendChat("i6e_API", "Token has no character assigned, please assign and retry.");
return;
}
///////////////////////////////////////////////////////////////////////////////// Begin parsing character sheet
let chid = character.id; // Get character identifier
let herodesignerData = [];
let characterName = findObjs({type: 'attribute', characterid: chid, name: 'name'})[0];
character.get("gmnotes", function(gmnotes) { // Begin processing the GM Notes section
let dec_gmnotes = decodeEditorText(gmnotes);
// Clean JSON of extra junk the HTML adds.
dec_gmnotes = dec_gmnotes.replace(/<[^>]*>/g, '') // Remove <tags>
.replace(/&[^;]*;/g, '') // Remove
.replace(/[^\x0A-\xBF]/g, '') // Remove nonstandard letters;
.replace(/\},\s{1,}\]/g, '\}\]') // Remove extra comma
.replace(/"rolls":[^]*?(?=],\r)/g, '"rolls":['); // Remove Rolls section
logDebug(dec_gmnotes);
if(gmnotes.length <= 5000)
{
sendChat("i6e_API", "JSON too short to contain valid character data. Update character (not token) GM Notes.");
return;
}
let hdJSON = JSON.parse(dec_gmnotes), // Parse the decoded JSON from GM Notes field.
hdchlist = hdJSON.stats, // Create array of all HD Characteristics.
hdmvlist = hdJSON.movement, // Create array of all HD Characteristics.
hdsklist = hdJSON.skills, // Create array of all HD Skills.
hdsllist = hdJSON.skills, // Create array of all HD Skill Levels.
hdcmlist = hdJSON.disads, // Create array of all HD Complications.
hdpwlist = hdJSON.powers, // Create array of all HD Powers.
hdpklist = hdJSON.perks, // Create array of all HD Perks.
hdtllist = hdJSON.talents; // Create array of all HD Talents.
character.set("name", hdJSON.name); // Set the name
// Create array of all attributes
var attrlist = findObjs({type: 'attribute', characterid: chid});
// TODO make adds conditional based on input flags per attribute type (stats, powers etc)
removeExistingAttributes(attrlist);
logDebug("*** Existing skills and complications removed");
createCharacteristics(hdJSON.stats, chid);
logDebug("*** Stats Assigned");
createFeatures(hdJSON, chid);
logDebug("*** Features Assigned");
createSkills(hdsklist, chid);
logDebug("*** Skills Assigned");
createMovement(hdmvlist, chid);
logDebug("*** Movement Assigned");
createSkillLevels(hdsllist, chid);
logDebug("*** Skill Levels Assigned");
createCombatLevels(hdsklist, chid);
logDebug("*** Combat Levels Assigned");
createPenaltyLevels(hdsklist, chid);
logDebug("*** Penalty Levels Assigned");
createComplications(hdcmlist, chid);
logDebug("*** Complications Assigned");
createPerks(hdpklist, chid);
logDebug("*** Perks Assigned");
createTalents(hdtllist, chid);
logDebug("*** Talents Assigned");
// Create all powers
for (var h=0; h < hdpwlist.length; h++) // Loop through HD sheet powers
{
UUID = generateUUID().replace(/_/g, "Z"); // Generate a UUID for power grouping
createSimplePower(hdpwlist[h], UUID, chid);
}
logDebug("*** Powers Assigned");
// TODO
// logDebug("Equipment Assigned");
// logDebug("Rolls Assigned");
// logDebug("Lightning Reflexes Assigned");
if (logObjs != 0){ // Output character for debug purposes
let allobjs = getAllObjs();
log(allobjs);
}
});
};
const registerEventHandlers = () => {
on('chat:message', handleInput);
return;
};
on('ready',function() {
checkInstall();
registerEventHandlers();
});
return;
})();
{ try { throw new Error(''); } catch (e) { API_Meta.ImportHS6e.lineCount = (parseInt(e.stack.split(/\n/)[1].replace(/^.*:(\d+):.*$/, '$1'), 10) - API_Meta.ImportHS6e.offset); } }
|
/*
|--------------------------------------------------------------------------
| Browser-sync config file
|--------------------------------------------------------------------------
|
| For up-to-date information about the options:
| http://www.browsersync.io/docs/options/
|
| There are more options than you see here, these are just the ones that are
| set internally. See the website for more info.
|
|
*/
module.exports = {
"ui": {
"port": 3005,
"weinre": {
"port": 8080
}
},
"files": [
"./src/assets/**/*",
"./src/*.**"
],
"watchOptions": {},
"server": {
"baseDir": "./src"
},
"proxy": false,
"port": 3007,
"middleware": false,
"serveStatic": [],
"ghostMode": {
"clicks": true,
"scroll": true,
"forms": {
"submit": true,
"inputs": true,
"toggles": true
}
},
"logLevel": "info",
"logPrefix": "BS",
"logConnections": false,
"logFileChanges": true,
"logSnippet": true,
"rewriteRules": false,
"open": "local",
"browser": ["google chrome"],
"cors": false,
"xip": false,
"hostnameSuffix": false,
"reloadOnRestart": false,
"notify": true,
"scrollProportionally": true,
"scrollThrottle": 0,
"scrollRestoreTechnique": "window.name",
"scrollElements": [],
"scrollElementMapping": [],
"reloadDelay": 0,
"reloadDebounce": 0,
"reloadThrottle": 0,
"plugins": [],
"injectChanges": true,
"startPath": null,
"minify": true,
"host": null,
"localOnly": false,
"codeSync": true,
"timestamps": true,
"clientEvents": [
"scroll",
"scroll:element",
"input:text",
"input:toggles",
"form:submit",
"form:reset",
"click"
],
"socket": {
"socketIoOptions": {
"log": false
},
"socketIoClientConfig": {
"reconnectionAttempts": 50
},
"path": "/browser-sync/socket.io",
"clientPath": "/browser-sync",
"namespace": "/browser-sync",
"clients": {
"heartbeatTimeout": 5000
}
},
"tagNames": {
"less": "link",
"scss": "link",
"css": "link",
"jpg": "img",
"jpeg": "img",
"png": "img",
"svg": "img",
"gif": "img",
"js": "script"
}
};
|
const package = require('../../package.json')
module.exports = function(command) {
console.log('Translator version: ' + package.version)
}; |
$(document).ready(function () {
});
|
let num = 10;
console.log(num.toString()); // "10"
console.log(num.toString(2)); // "1010"
console.log(num.toString(8)); // "12"
console.log(num.toString(10)); // "10"
console.log(num.toString(16)); // "a"
|
import {combineReducers} from 'redux'
import {reducerCreator} from 'redux-amrc'
import counter from './counter'
const rootReducer = combineReducers({
async: reducerCreator(),
counter
})
export default rootReducer |
/**
* Autoplay Plugin
* @version 2.0.0-beta.3
* @author Bartosz Wojciechowski
* @author Artus Kolanowski
* @license The MIT License (MIT)
*/
;(function($, window, document, undefined) {
/**
* Creates the autoplay plugin.
* @class The Autoplay Plugin
* @param {Owl} scope - The Owl Carousel
*/
var Autoplay = function(carousel) {
/**
* Reference to the core.
* @protected
* @type {Owl}
*/
this._core = carousel;
/**
* The autoplay interval.
* @type {Number}
*/
this._interval = null;
/**
* Indicates whenever the autoplay is paused.
* @type {Boolean}
*/
this._paused = false;
/**
* All event handlers.
* @protected
* @type {Object}
*/
this._handlers = {
'changed.owl.carousel': $.proxy(function(e) {
if (e.namespace && e.property.name === 'settings') {
if (this._core.settings.autoplay) {
this.play();
} else {
this.stop();
}
}
}, this),
'initialized.owl.carousel': $.proxy(function(e) {
if (e.namespace && this._core.settings.autoplay) {
this.play();
}
}, this),
'play.owl.autoplay': $.proxy(function(e, t, s) {
if (e.namespace) {
this.play(t, s);
}
}, this),
'stop.owl.autoplay': $.proxy(function(e) {
if (e.namespace) {
this.stop();
}
}, this),
'mouseover.owl.autoplay': $.proxy(function() {
if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
this.pause();
}
}, this),
'mouseleave.owl.autoplay': $.proxy(function() {
if (this._core.settings.autoplayHoverPause && this._core.is('rotating')) {
this.play();
}
}, this)
};
// register event handlers
this._core.$element.on(this._handlers);
// set default options
this._core.options = $.extend({}, Autoplay.Defaults, this._core.options);
if (this._core.options.autoplay) {
this._core.$element
.on('focus', $.proxy(function() {
this.pause();
}, this))
.on('blur', $.proxy(function() {
this.play();
}, this));
}
};
/**
* Default options.
* @public
*/
Autoplay.Defaults = {
autoplay: false,
autoplayTimeout: 5000,
autoplayHoverPause: true, // false
autoplaySpeed: false
};
/**
* Starts the autoplay.
* @public
* @param {Number} [timeout] - The interval before the next animation starts.
* @param {Number} [speed] - The animation speed for the animations.
*/
Autoplay.prototype.play = function(timeout, speed) {
this._paused = false;
if (this._core.is('rotating')) {
return;
}
this._core.enter('rotating');
this._interval = window.setInterval($.proxy(function() {
if (this._paused || this._core.is('busy') || this._core.is('interacting') || document.hidden) {
return;
}
this._core.next(speed || this._core.settings.autoplaySpeed);
}, this), timeout || this._core.settings.autoplayTimeout);
};
/**
* Stops the autoplay.
* @public
*/
Autoplay.prototype.stop = function() {
if (!this._core.is('rotating')) {
return;
}
window.clearInterval(this._interval);
this._core.leave('rotating');
};
/**
* Stops the autoplay.
* @public
*/
Autoplay.prototype.pause = function() {
if (!this._core.is('rotating')) {
return;
}
this._paused = true;
};
/**
* Destroys the plugin.
*/
Autoplay.prototype.destroy = function() {
var handler, property;
this.stop();
for (handler in this._handlers) {
this._core.$element.off(handler, this._handlers[handler]);
}
for (property in Object.getOwnPropertyNames(this)) {
typeof this[property] != 'function' && (this[property] = null);
}
};
$.fn.<%= pluginName %>.Constructor.Plugins.autoplay = Autoplay;
})(window.Zepto || window.jQuery, window, document);
|
var React = require('react');
var immstruct = require('immstruct');
var Component = require('./component');
var data = immstruct({
name: 'root',
value: 1,
children: [
{
name: 'c-1',
value: 1
}, {
name: 'c-2',
value: 1,
children: [
{
name: 'c-2-1',
value: 1
}, {
name: 'c-2-2',
value: 1
}, {
name: 'c-2-3',
value: 1
}
]
}
]
});
data.on('swap', render);
function render() {
React.render(
<Component cursor={data.cursor()} />,
document.body
);
}
render();
|
var examples = [{
title: 'Data list',
code: function() {
var table = new jsTable(data);
return table;
}
}, {
title: 'name ~ *l* or age > 20',
code: function() {
var table = new jsTable(data);
return table
.find(jsTable.or().regexp('name', /l/).greaterThan('age', 20));
}
}, {
title: 'name ~ *l* and age > 20',
code: function() {
var table = new jsTable(data);
return table
.find(jsTable.and().regexp('name', /l/).greaterThan('age', 20));
}
}, {
title: '(name ~ *l* or name ~ *o*) and age > 20',
code: function() {
var table = new jsTable(data);
return table
.find(
jsTable.and()
.add(
jsTable.or()
.regexp('name', /l/)
.regexp('name', /o/)
)
.greaterThan('age', 20)
);
}
}]; |
'use strict';
const createRouter = require('@arangodb/foxx/router');
const router = createRouter();
module.context.use(router);
router.get('/hello-world', function (req, res) {
res.send('Hello from volpe 0.1, a simple shortest-path implementation');
})
.response(['text/plain'], 'A generic greeting')
.summary('Generic greeting')
.description('Prints a generic greeting and simple usage');
const joi = require('joi');
const db = require('@arangodb').db;
const errors = require('@arangodb').errors;
const DOC_NOT_FOUND = errors.ERROR_ARANGO_DOCUMENT_NOT_FOUND.code;
const aql = require('@arangodb').aql;
router.get('/run_aql', function (req, res) {
const keys = db._query(aql`
FOR i IN [ 1, 2, 3, 4 ]
RETURN i * 2
`);
res.send(keys);
})
.response(joi.array().items(
joi.string().required()
).required(), '.')
.summary('List entry keys')
.description('Runs a simple test query');
const collection = db._collection('fullnodes');
router.get('/node/:key', function (req, res) {
try {
const data = collection.document(req.pathParams.key);
res.send(data["id"])
} catch (e) {
if (!e.isArangoError || e.errorNum !== DOC_NOT_FOUND) {
throw e;
}
res.throw(404, 'The entry does not exist', e);
}
})
.pathParam('key', joi.string().required(), 'Key of the entry')
.response(joi.object().required(), 'Node ID stored in the collection')
.summary('Retrieve a node entry')
.description('Retrieves the ID for an entry from the "fullnodes" collection by key');
router.get('/shortestpath/', function (req, res) {
const keys = db._query(aql`for i in any shortest_path "fullnodes/20913296" to "fullnodes/2512646997" fulledges
return merge({node: i.id, lat: i.lat, lon: i.lon}, (i.tags ? {tags: i.tags} : {}))`);
res.json(keys.toArray());
})
.response(joi.array().items(
joi.string().required()
).required(), 'API shortest path between York and Scarborough')
.summary('Shortest path between York and Scarborough')
.description('All nodes in the shortest path between nodes York and Scarborough. Equivalent to shortestpath/20913296/2512646997');
router.get('/shortestpath/:start/:end/', function (req, res) {
res.set("Content-Type", "text/plain; charset=utf-8");
const keys = db._query(aql`for i in any shortest_path
concat("fullnodes/",${req.pathParams.start}) to
concat("fullnodes/",${req.pathParams.end}) fulledges
return merge({node: i.id, lat: i.lat, lon: i.lon}, (i.tags ? {tags: i.tags} : {}))`);
res.send(keys);
})
.response(joi.array().items(
joi.string().required()
).required(), 'API shortestpath/start node/end node/')
.summary('Shortest path all nodes')
.description('Assembles all nodes in the shortest path between nodes in url /shortestpath/start/finish');
|
//**************************************************************************** */
// Node.js 代码
// Promise life cycle
// pending
// Fulfilled
// Rejected
const fs = require('fs');
function readFile(filename) {
return new Promise((resolve, reject) => {
// 触发异步任务
fs.readFile(filename, { encoding: 'utf-8' }, (err, contens) => {
if (err) {
reject(err);
return;
}
resolve(contens);
});
});
}
let rfPromise = readFile('SetMapa.js');
rfPromise.then(
contents => {
console.log(contents);
},
err => {
console.log(err.message);
}
);
//**************************************************************************** */
// ES6中,在Promise对象rejected后,如果没有在then中
// 显式地捕捉,那么此rejected就会无声无息地消失。
// 因此在Node中,通过 process 提供了两个事件:
// unhandledRejection: 在一次事件轮询中,当一个 promise 处于 rejected 状态却没有 rejection 处理它,该事件会被触发。
// rejectionHandled: 在一次事件轮询之后,如果存在 rejected 状态的 promise 并已被 rejection 处理过,该事件会被触发。
// 设计这些事件的目的是为了帮助辨识未处理的 rejected 状态的 promise 。
let rejected;
process.on('unhandledRejection', (reason, promise) => {
console.log(reason.message);
console.log(rejected == promise);
});
rejected = Promise.reject(new Error('Explosion!'));
//**************************************************************************** */
// Promise 链
// 错误捕获
let p1 = new Promise(function(resolve, reject) {
resolve(42);
});
p1.then(function(value) {
console.log(value);
return value + 1
}).then(function(value) {
console.log(value);
console.log("Finished");
throw new Error("Boom!");
}).catch(function(error) {
console.log(error.message); // "Boom!"
});
//**************************************************************************** */
// 多个Promise
// Promise.all Promise.race
let p1 = new Promise(function(resolve, reject) {
resolve(42);
});
let p2 = new Promise(function(resolve, reject) {
resolve(43);
});
let p3 = new Promise(function(resolve, reject) {
resolve(44);
});
let p4 = Promise.all([p1, p2, p3]);
p4.then(function(value) {
console.log(Array.isArray(value)); // true
console.log(value[0]); // 42
console.log(value[1]); // 43
console.log(value[2]); // 44
});
// reject发生
let p1 = new Promise(function(resolve, reject) {
resolve(42);
});
let p2 = new Promise(function(resolve, reject) {
reject(43);
});
let p3 = new Promise(function(resolve, reject) {
resolve(44);
});
let p4 = Promise.all([p1, p2, p3]);
p4.catch(function(value) {
console.log(Array.isArray(value)) // false
console.log(value); // 43
});
//**************************************************************************** */
// 继承
class MyPromise extends Promise {
// 使用默认的构造函数
success(resolve, reject) {
return this.then(resolve, reject);
}
failure(reject) {
return this.catch(reject);
}
} |
/**
* Created by jms on 07-16-16.
*/
$(function () {
var processURL = function () {
var long_url = $('.ui.form').form('get value', 'long_url');
console.info('validation passed, %s', long_url);
$.ajax({
url: '/process_url',
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
long_url: long_url
}),
success: function (data) {
console.info(data);
var site_url = window.top.location.href;
$('#short_url').html(site_url + data.code);
$('#msg').removeClass('hidden');
},
error: function () {
console.error(this.props.url, status, err.toString());
}
});
};
var focusFirstInvalidField = function () {
$('.ui.form').find('div.field.error').first().find('input').focus();
};
$('.ui.form').form({
on: 'blur',
fields: {
long_url: {
identifier: 'long_url',
rules: [
{
type: 'empty',
prompt: 'url cannot be empty'
},
{
type: 'url',
prompt: 'you must enter a valid url '
}
]
}
},
onSuccess: processURL,
onFailure: focusFirstInvalidField
}
);
$('div.ui.clear').on('click', function () {
$('#msg').addClass('hidden');
$('form').form('clear')
});
});
|
(function() {
'use strict';
angular.module('mobile-bazaar.about')
.service('SettingsService', SettingsService);
SettingsService.$inject = ['$http'];
function SettingsService($http) {
var APIURL = 'http://localhost:28469/api/settings';
return {
getSettings: getSettings
};
function getSettings() {
return $http.get(APIURL)
.then(function(res) {
console.log(res.data);
return res.data;
})
.catch(function(err){
console.log(err);
});
}
}
}()); |
'use strict';
var should = require('should'),
request = require('supertest'),
app = require('../../server'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Callback = mongoose.model('Callback'),
agent = request.agent(app);
/**
* Globals
*/
var credentials, user, callback;
/**
* Callback routes tests
*/
describe('Callback CRUD tests', function() {
beforeEach(function(done) {
// Create user credentials
credentials = {
username: 'username',
password: 'password'
};
// Create a new user
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: credentials.username,
password: credentials.password,
provider: 'local'
});
// Save a user to the test db and create new Callback
user.save(function() {
callback = {
name: 'Callback Name'
};
done();
});
});
it('should be able to save Callback instance if logged in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Callback
agent.post('/callbacks')
.send(callback)
.expect(200)
.end(function(callbackSaveErr, callbackSaveRes) {
// Handle Callback save error
if (callbackSaveErr) done(callbackSaveErr);
// Get a list of Callbacks
agent.get('/callbacks')
.end(function(callbacksGetErr, callbacksGetRes) {
// Handle Callback save error
if (callbacksGetErr) done(callbacksGetErr);
// Get Callbacks list
var callbacks = callbacksGetRes.body;
// Set assertions
(callbacks[0].user._id).should.equal(userId);
(callbacks[0].name).should.match('Callback Name');
// Call the assertion callback
done();
});
});
});
});
it('should not be able to save Callback instance if not logged in', function(done) {
agent.post('/callbacks')
.send(callback)
.expect(401)
.end(function(callbackSaveErr, callbackSaveRes) {
// Call the assertion callback
done(callbackSaveErr);
});
});
it('should not be able to save Callback instance if no name is provided', function(done) {
// Invalidate name field
callback.name = '';
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Callback
agent.post('/callbacks')
.send(callback)
.expect(400)
.end(function(callbackSaveErr, callbackSaveRes) {
// Set message assertion
(callbackSaveRes.body.message).should.match('Please fill Callback name');
// Handle Callback save error
done(callbackSaveErr);
});
});
});
it('should be able to update Callback instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Callback
agent.post('/callbacks')
.send(callback)
.expect(200)
.end(function(callbackSaveErr, callbackSaveRes) {
// Handle Callback save error
if (callbackSaveErr) done(callbackSaveErr);
// Update Callback name
callback.name = 'WHY YOU GOTTA BE SO MEAN?';
// Update existing Callback
agent.put('/callbacks/' + callbackSaveRes.body._id)
.send(callback)
.expect(200)
.end(function(callbackUpdateErr, callbackUpdateRes) {
// Handle Callback update error
if (callbackUpdateErr) done(callbackUpdateErr);
// Set assertions
(callbackUpdateRes.body._id).should.equal(callbackSaveRes.body._id);
(callbackUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback
done();
});
});
});
});
it('should be able to get a list of Callbacks if not signed in', function(done) {
// Create new Callback model instance
var callbackObj = new Callback(callback);
// Save the Callback
callbackObj.save(function() {
// Request Callbacks
request(app).get('/callbacks')
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Array.with.lengthOf(1);
// Call the assertion callback
done();
});
});
});
it('should be able to get a single Callback if not signed in', function(done) {
// Create new Callback model instance
var callbackObj = new Callback(callback);
// Save the Callback
callbackObj.save(function() {
request(app).get('/callbacks/' + callbackObj._id)
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Object.with.property('name', callback.name);
// Call the assertion callback
done();
});
});
});
it('should be able to delete Callback instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Callback
agent.post('/callbacks')
.send(callback)
.expect(200)
.end(function(callbackSaveErr, callbackSaveRes) {
// Handle Callback save error
if (callbackSaveErr) done(callbackSaveErr);
// Delete existing Callback
agent.delete('/callbacks/' + callbackSaveRes.body._id)
.send(callback)
.expect(200)
.end(function(callbackDeleteErr, callbackDeleteRes) {
// Handle Callback error error
if (callbackDeleteErr) done(callbackDeleteErr);
// Set assertions
(callbackDeleteRes.body._id).should.equal(callbackSaveRes.body._id);
// Call the assertion callback
done();
});
});
});
});
it('should not be able to delete Callback instance if not signed in', function(done) {
// Set Callback user
callback.user = user;
// Create new Callback model instance
var callbackObj = new Callback(callback);
// Save the Callback
callbackObj.save(function() {
// Try deleting Callback
request(app).delete('/callbacks/' + callbackObj._id)
.expect(401)
.end(function(callbackDeleteErr, callbackDeleteRes) {
// Set message assertion
(callbackDeleteRes.body.message).should.match('User is not logged in');
// Handle Callback error error
done(callbackDeleteErr);
});
});
});
afterEach(function(done) {
User.remove().exec();
Callback.remove().exec();
done();
});
}); |
var Sprite = require('../spritesheet/Sprite');
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
function NineSlice(asset, w, h) {
// 9-slice sprites
//
// 0 w w+1 asset.width
// 0 ┌───┬─────────┬───┐
// │ A │ B | C │
// h ├───┼─────────┼───┤
// │ │ | │
// │ D │ E | F │
// │ │ | │
// h+1 ├───┼─────────┼───┤
// │ G │ H | I │
// asset.height └───┴─────────┴───┘
//
//
// 3-slices optimizations:
// ┌───┬───────┬───┐ ┌───┐
// │ J │ K | L │ │ M │
// └───┴───────┴───┘ ├───┤
// │ N │
// ├───┤
// │ O │
// └───┘
if (asset._isNineSlice) {
asset = asset.asset;
}
this.asset = asset;
var path = asset.path;
var x = 0;
var y = 0;
if (asset._isTileMap) {
throw new Error('TileMap cannot be used as NineSlice');
}
var width = asset.width;
var height = asset.height;
if (asset._isSprite) {
x = asset.x;
y = asset.y;
asset = asset.img;
} else if (asset._isTexture) {
asset = asset.canvas;
path = '';
}
this.w0 = w;
this.w1 = width - 1;
this.w2 = width - w - 1;
this.h0 = h;
this.h1 = height - 1;
this.h2 = height - h - 1;
// 9-slices
this._a = new Sprite(asset, path, x, y, w, h);
this._b = new Sprite(asset, path, x + w, y, 1, h);
this._c = new Sprite(asset, path, x + w + 1, y, this.w2, h);
this._d = new Sprite(asset, path, x, y + h, w, 1);
this._e = new Sprite(asset, path, x + w, y + h, 1, 1);
this._f = new Sprite(asset, path, x + w + 1, y + h, this.w2, 1);
this._g = new Sprite(asset, path, x, y + h + 1, w, this.h2);
this._h = new Sprite(asset, path, x + w, y + h + 1, 1, this.h2);
this._i = new Sprite(asset, path, x + w + 1, y + h + 1, this.w2, this.h2);
// horizontal 3-slices
this._j = new Sprite(asset, path, x, y, w, height);
this._k = new Sprite(asset, path, x + w, y, 1, height);
this._l = new Sprite(asset, path, x + w + 1, y, this.w2, height);
// vertical 3-slices
this._m = new Sprite(asset, path, x, y, width, h);
this._n = new Sprite(asset, path, x, y + h, width, 1);
this._o = new Sprite(asset, path, x, y + h + 1, width, this.h2);
}
module.exports = NineSlice;
NineSlice.prototype._isNineSlice = true;
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
NineSlice.prototype._draw = function (texture, x, y, w, h) {
w = Math.round(w);
h = Math.round(h);
if (w < 0) { x += w; w = -w; }
if (h < 0) { y += h; h = -h; }
var mw = this.w1 + 1;
var mh = this.h1 + 1;
if (w <= mw && h <= mh) {
texture.draw(this.asset, x, y);
return;
}
var x1 = x + this.w0;
var x2 = x + w - this.w2
var y1 = y + this.h0;
var y2 = y + h - this.h2;
if (h <= mh) {
texture.draw (this._j, x, y);
texture.stretchDraw(this._k, x1, y, w - this.w1, mh);
texture.draw (this._l, x2, y);
return;
}
if (w <= mw) {
texture.draw (this._m, x, y);
texture.stretchDraw(this._n, x, y1, mw, h - this.h1);
texture.draw (this._o, x, y2);
return;
}
texture.draw (this._a, x, y);
texture.stretchDraw(this._b, x1, y, w - this.w1, this.h0);
texture.draw (this._c, x2, y);
texture.stretchDraw(this._d, x, y1, this.w0, h - this.h1);
texture.stretchDraw(this._e, x1, y1, w - this.w1, h - this.h1);
texture.stretchDraw(this._f, x2, y1, this.w2, h - this.h1);
texture.draw (this._g, x, y2);
texture.stretchDraw(this._h, x1, y2, w - this.w1, this.h2);
texture.draw (this._i, x2, y2);
};
//▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
NineSlice.prototype.draw = function (x, y, w, h) {
this._draw($screen, x, y, w, h);
};
|
import koa from 'koa'
import mount from 'koa-mount'
import helmet from 'koa-helmet'
import logger from 'koa-logger'
import responseTime from 'koa-response-time'
import session from 'koa-generic-session'
import level from 'levelup'
import store from 'koa-level'
import staticCache from 'koa-static-cache'
import cors from 'koa-cors'
import basicAuth from './passport/basic'
import jwtAuth from './passport/local-jwt'
import facebookAuth from './passport/facebook'
import googleAuth from './passport/google'
import localAuth from './passport/local'
import router from './routes'
import path from 'path'
import co from 'co'
import favicon from 'koa-favicon'
import services from 'src/server/services'
import adminServices from 'src/server/services/admin'
import models from 'src/server/db/models'
import locale from 'koa-locale'
import bodyParser from 'koa-bodyparser'
import noCache from 'koa-no-cache'
const debug = require('debug')
const leveldb = level('./storage/leveldb')
const app = koa()
// ES7 async
// app.experimental = true
const env = process.env.NODE_ENV || 'development'
co(function *() {
if (env === 'development') {
const webpack = require('webpack')
const config = require('config/webpack/'+ env +'.config')
const compiler = webpack(config.webpack)
app.use(require('koa-webpack-dev-middleware')(compiler, config.server.options))
app.use(require('koa-webpack-hot-middleware')(compiler))
}
})
locale(app, 'lang')
app.use(responseTime())
app.use(logger())
app.use(helmet())
if (env === 'production') {
app.use(require('koa-conditional-get')())
app.use(require('koa-etag')())
app.use(require('koa-compressor')())
// Cache pages
const cache = require('lru-cache')({ maxAge: 3000 })
app.use(require('koa-cash')({
get: function* (key) {
return cache.get(key)
},
set: function* (key, value) {
cache.set(key, value)
}
}))
}
if (env === 'development') {
debug.enable('dev,koa')
require('blocked')((ms) => debug('koa')(`blocked for ${ms}ms`))
}
const cacheOpts = { maxAge: 86400000, gzip: true }
if (env === 'development') {
app.use(
mount(
'/assets',
require('koa-proxy')({ host: 'http://0.0.0.0:3000' })
)
)
} else {
app.use(
mount('/assets',
staticCache(
path.join(__dirname, '../../public/assets'),
cacheOpts
)
)
)
}
app.use(mount('/images',
staticCache(
path.join(__dirname, '../../images'),
cacheOpts
)
))
app.use(mount('/uploads',
staticCache(
path.join(__dirname, '../../uploads'),
cacheOpts
)
))
app.use(favicon(path.join(__dirname, '../../images/app/v2.3-t/favicon.ico')))
app.use(function*(next) {
this.cookies.secure = true
yield* next
})
app.keys = require('config').app.SESSION_KEYS
app.use(
session(
{
proxy : true,
cookie: {
path: '/',
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000,
overwrite: true,
signed: true,
secure: true,
sameSite: 'lax'
}, store: store({ db: leveldb }) }
)
)
app.use(noCache({
paths: ['/api/v1/(.*)'],
types: ['application/json']
}))
app.use(mount('/api/v1', cors()))
app.use(mount('/api/v1', services.v1))
app.use(mount('/api/v1', basicAuth.initialize()))
app.use(mount('/api/v1', jwtAuth.initialize()))
app.use(bodyParser())
app.use(localAuth.initialize())
app.use(facebookAuth.initialize())
app.use(googleAuth.initialize())
app.use(router.routes())
app.use(mount('/api/admin/v1', adminServices.v1))
import adminView from './adminView'
adminView(app)
import appView from './appView'
appView(app)
const port = process.env.PORT || 3000
co(function *() {
const connection = yield models.sequelize.sync()
if (connection) {
app.listen(port)
debug('koa')(`App started listening on port ${port}`)
}
})
module.exports = app
|
const chai = require('chai');
const sinon = require('sinon');
const lab = require('lab').script();
const fn = require('../../../web/lib/plugins/good');
const expect = chai.expect;
exports.lab = lab;
lab.describe('good', () => {
lab.test('should set up local logging', done => {
process.env.HAPI_DEBUG = 'true';
const serverMock = {
register: sinon.spy(),
app: {
hostUid: '',
},
log: sinon.stub(),
};
const cbSpy = sinon.spy();
fn.register(serverMock, null, cbSpy);
serverMock.register.callArg(1);
expect(
serverMock.register.getCall(0).args[0].options.reporters.length
).to.equal(1);
// This test won't pass when not in Docker.
expect(
serverMock.register.getCall(0).args[0].options.reporters[0].config
).to.equal('/tmp/hapi-zen-platform.log');
done();
});
lab.test('should setup remote logging', done => {
process.env.HAPI_DEBUG = 'false';
process.env.LOGENTRIES_ENABLED = 'true';
process.env.LOGENTRIES_TOKEN = 'gloubiboulga';
const serverMock = {
register: sinon.spy(),
app: {
hostUid: '',
},
log: sinon.stub(),
};
const cbSpy = sinon.spy();
fn.register(serverMock, null, cbSpy);
serverMock.register.callArg(1);
expect(
serverMock.register.getCall(0).args[0].options.reporters.length
).to.equal(1);
// This test won't pass when not in Docker.
expect(
serverMock.register.getCall(0).args[0].options.reporters[0].config
.endpoint
).to.equal('https://webhook.logentries.com/noformat/logs/gloubiboulga');
done();
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var ic_publish = exports.ic_publish = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M5 4v2h14V4H5zm0 10h4v6h6v-6h4l-7-7-7 7z" } }] }; |
/**
* Created using Slot Framework
* Object model that represents the main Slot
*/
function main() {
this.userName = "";
this.userNumber = "";
}
main.create = function() { return new main(); }
main.prototype.layout = function() { return page.layouts["main"]; }
main.prototype.bind = function(json) {
return this;
}
main.prototype.onPreRender = function() {
return this;
} |
var expect = require('chai').expect // assertion library
, superagent = require('superagent') // small progressive client-side HTTP request library
, sinon = require('sinon') // stubs and mocks
//, mongoose = require('mongoose') // mongodb abstaction
, cheerio = require('cheerio') // to parse fetched DOM data
, config = require('../../config')
, Provider = require('../../controllers/provider')
, ProviderModel = require('../../models/provider')
;
var mockProviders = {
'SGI': {
contents: '\
<a OnClick="get_position();" href="annuncio/1">\
<a OnClick="get_position();" href="annuncio/2">\
<a OnClick="get_position();" href="annuncio/3">\
',
count: 3,
},
'TOE': {
contents: '\
<div id="row-viewmode">\
<div class="esclist-item other-class">\
<div>\
<a href="annuncio?id=1">A</a>\
<a href="annuncio?id=2">B</a>\
<a href="annuncio?id=3">C</a>\
<a href="annuncio?id=4">D</a>\
</div>\
</div>\
</div>\
',
count: 4,
},
'FORBES': {
contents: '\
<h2>\
<span id="2015"></span>\
</h2>\
<div>\
<ol>\
<li><a href="1" title="Person A"></a></li>\
<li><a href="1bis" title="Person 1bis" class="ignore me"></a></li>\
<li><a href="2" title="Person B"></a></li>\
<li><a href="3" title="Person C"></a></li>\
<li><a href="4" title="Person D"></a></li>\
<li><a href="5" title="Person E"></a></li>\
</ol>\
</div>\
',
count: 5,
},
};
describe('controllers - provider', function() {
// test model methods /////////////////////////////////////
describe('getAll', function() {
it('error must be null, result must be object, its length 5', function() {
// mocking MongoDB
sinon.stub(ProviderModel, 'getAll').yields(null, mockProviders); // TODO: this is wrong...
Provider.getAll({}, function(err, result) {
expect(err).to.be.null;
expect(typeof result).to.eql('object');
expect(result).to.have.keys([ 'SGI', 'TOE', 'FORBES' ]);
});
});
});
}); |
/**
* @ignore
* Component.Extension.Align
* @author yiminghe@gmail.com, qiaohua@taobao.com
*/
KISSY.add(function (S, require) {
var Node = require('node');
var win = S.Env.host,
$ = Node.all,
UA = S.UA;
// http://yiminghe.iteye.com/blog/1124720
/**
* @ignore
* 得到会导致元素显示不全的祖先元素
*/
function getOffsetParent(element) {
// ie 这个也不是完全可行
/*
<div style="width: 50px;height: 100px;overflow: hidden">
<div style="width: 50px;height: 100px;position: relative;" id="d6">
元素 6 高 100px 宽 50px<br/>
</div>
</div>
*/
// element.offsetParent does the right thing in ie7 and below. Return parent with layout!
// In other browsers it only includes elements with position absolute, relative or
// fixed, not elements with overflow set to auto or scroll.
// if (UA.ie && ieMode < 8) {
// return element.offsetParent;
// }
// 统一的 offsetParent 方法
var doc = element.ownerDocument,
body = doc.body,
parent,
positionStyle = $(element).css('position'),
skipStatic = positionStyle === 'fixed' || positionStyle === 'absolute';
if (!skipStatic) {
return element.nodeName.toLowerCase() === 'html' ? null : element.parentNode;
}
for (parent = element.parentNode; parent && parent !== body; parent = parent.parentNode) {
positionStyle = $(parent).css('position');
if (positionStyle !== 'static') {
return parent;
}
}
return null;
}
/**
* @ignore
* 获得元素的显示部分的区域
*/
function getVisibleRectForElement(element) {
var visibleRect = {
left: 0,
right: Infinity,
top: 0,
bottom: Infinity
},
el,
scrollX,
scrollY,
winSize,
doc = element.ownerDocument,
$win = $(doc).getWindow(),
body = doc.body,
documentElement = doc.documentElement;
// Determine the size of the visible rect by climbing the dom accounting for
// all scrollable containers.
for (el = element; (el = getOffsetParent(el));) {
// clientWidth is zero for inline block elements in ie.
if ((!UA.ie || el.clientWidth !== 0) &&
// body may have overflow set on it, yet we still get the entire
// viewport. In some browsers, el.offsetParent may be
// document.documentElement, so check for that too.
(el !== body &&
el !== documentElement &&
$(el).css('overflow') !== 'visible')) {
var pos = $(el).offset();
// add border
pos.left += el.clientLeft;
pos.top += el.clientTop;
visibleRect.top = Math.max(visibleRect.top, pos.top);
visibleRect.right = Math.min(visibleRect.right,
// consider area without scrollBar
pos.left + el.clientWidth);
visibleRect.bottom = Math.min(visibleRect.bottom,
pos.top + el.clientHeight);
visibleRect.left = Math.max(visibleRect.left, pos.left);
}
}
// Clip by window's viewport.
scrollX = $win.scrollLeft();
scrollY = $win.scrollTop();
visibleRect.left = Math.max(visibleRect.left, scrollX);
visibleRect.top = Math.max(visibleRect.top, scrollY);
winSize = {
width: $win.width(),
height: $win.height()
};
visibleRect.right = Math.min(visibleRect.right, scrollX + winSize.width);
visibleRect.bottom = Math.min(visibleRect.bottom, scrollY + winSize.height);
return visibleRect.top >= 0 && visibleRect.left >= 0 &&
visibleRect.bottom > visibleRect.top &&
visibleRect.right > visibleRect.left ?
visibleRect : null;
}
function getElFuturePos(elRegion, refNodeRegion, points, offset) {
var xy,
diff,
p1,
p2;
xy = {
left: elRegion.left,
top: elRegion.top
};
p1 = getAlignOffset(refNodeRegion, points[0]);
p2 = getAlignOffset(elRegion, points[1]);
diff = [p2.left - p1.left, p2.top - p1.top];
return {
left: xy.left - diff[0] + (+offset[0]),
top: xy.top - diff[1] + (+offset[1])
};
}
function isFailX(elFuturePos, elRegion, visibleRect) {
return elFuturePos.left < visibleRect.left ||
elFuturePos.left + elRegion.width > visibleRect.right;
}
function isFailY(elFuturePos, elRegion, visibleRect) {
return elFuturePos.top < visibleRect.top ||
elFuturePos.top + elRegion.height > visibleRect.bottom;
}
function adjustForViewport(elFuturePos, elRegion, visibleRect, overflow) {
var pos = S.clone(elFuturePos),
size = {
width: elRegion.width,
height: elRegion.height
};
if (overflow.adjustX && pos.left < visibleRect.left) {
pos.left = visibleRect.left;
}
// Left edge inside and right edge outside viewport, try to resize it.
if (overflow.resizeWidth &&
pos.left >= visibleRect.left &&
pos.left + size.width > visibleRect.right) {
size.width -= (pos.left + size.width) - visibleRect.right;
}
// Right edge outside viewport, try to move it.
if (overflow.adjustX && pos.left + size.width > visibleRect.right) {
// 保证左边界和可视区域左边界对齐
pos.left = Math.max(visibleRect.right - size.width, visibleRect.left);
}
// Top edge outside viewport, try to move it.
if (overflow.adjustY && pos.top < visibleRect.top) {
pos.top = visibleRect.top;
}
// Top edge inside and bottom edge outside viewport, try to resize it.
if (overflow.resizeHeight &&
pos.top >= visibleRect.top &&
pos.top + size.height > visibleRect.bottom) {
size.height -= (pos.top + size.height) - visibleRect.bottom;
}
// Bottom edge outside viewport, try to move it.
if (overflow.adjustY && pos.top + size.height > visibleRect.bottom) {
// 保证上边界和可视区域上边界对齐
pos.top = Math.max(visibleRect.bottom - size.height, visibleRect.top);
}
return S.mix(pos, size);
}
function flip(points, reg, map) {
var ret = [];
S.each(points, function (p) {
ret.push(p.replace(reg, function (m) {
return map[m];
}));
});
return ret;
}
function flipOffset(offset, index) {
offset[index] = -offset[index];
return offset;
}
/**
* @class KISSY.Component.Extension.Align
* Align extension class.Align component with specified element.
*/
function Align() {
}
Align.__getOffsetParent = getOffsetParent;
Align.__getVisibleRectForElement = getVisibleRectForElement;
Align.ATTRS =
{
/**
* alignment config.
* @type {Object}
* @property align
*
* for example:
* @example
* {
* node: null, // 参考元素, falsy 或 window 为可视区域, 'trigger' 为触发元素, 其他为指定元素
* points: ['cc','cc'], // ['tr', 'tl'] 表示 overlay 的 tl 与参考节点的 tr 对齐
* offset: [0, 0] // 有效值为 [n, m]
* }
*/
/**
* alignment config.
* @cfg {Object} align
*
* for example:
* @example
* {
* node: null, // 参考元素, falsy 或 window 为可视区域, 'trigger' 为触发元素, 其他为指定元素
* points: ['cc','cc'], // ['tr', 'tl'] 表示 overlay 的 tl 与参考节点的 tr 对齐
* offset: [0, 0] // 有效值为 [n, m]
* }
*/
/**
* @ignore
*/
align: {
value: {}
}
};
function getRegion(node) {
var offset, w, h,
domNode = node[0];
if (!S.isWindow(domNode)) {
offset = node.offset();
w = node.outerWidth();
h = node.outerHeight();
} else {
var $win = $(domNode).getWindow();
offset = {
left: $win.scrollLeft(),
top: $win.scrollTop()
};
w = $win.width();
h = $win.height();
}
offset.width = w;
offset.height = h;
return offset;
}
/**
* 获取 node 上的 align 对齐点 相对于页面的坐标
* @param region
* @param align
* @ignore
*/
function getAlignOffset(region, align) {
var V = align.charAt(0),
H = align.charAt(1),
w = region.width,
h = region.height,
x, y;
x = region.left;
y = region.top;
if (V === 'c') {
y += h / 2;
} else if (V === 'b') {
y += h;
}
if (H === 'c') {
x += w / 2;
} else if (H === 'r') {
x += w;
}
return { left: x, top: y };
}
function beforeVisibleChange(e) {
if (e.target === this && e.newVal) {
realign.call(this);
}
}
function onResize() {
if (this.get('visible')) {
realign.call(this);
}
}
function realign() {
this._onSetAlign(this.get('align'));
}
Align.prototype = {
__bindUI: function () {
// auto align on window resize or before el show
var self = this;
self.on('beforeVisibleChange', beforeVisibleChange, self);
self.$el.getWindow().on('resize', onResize, self);
},
'_onSetAlign': function (v) {
if (v && v.points) {
this.align(v.node, v.points, v.offset, v.overflow);
}
},
/*
* 对齐 Overlay 到 node 的 points 点, 偏移 offset 处
* @ignore
* @param {Element} node 参照元素, 可取配置选项中的设置, 也可是一元素
* @param {String[]} points 对齐方式
* @param {Number[]} [offset] 偏移
* @chainable
*/
align: function (refNode, points, offset, overflow) {
refNode = Node.one(refNode || win);
offset = offset && [].concat(offset) || [0, 0];
overflow = overflow || {};
var self = this,
el = self.$el,
fail = 0;
// 当前节点可以被放置的显示区域
var visibleRect = getVisibleRectForElement(el[0]);
// 当前节点所占的区域, left/top/width/height
var elRegion = getRegion(el);
// 参照节点所占的区域, left/top/width/height
var refNodeRegion = getRegion(refNode);
// 当前节点将要被放置的位置
var elFuturePos = getElFuturePos(elRegion,
refNodeRegion, points, offset);
// 当前节点将要所处的区域
var newElRegion = S.merge(elRegion, elFuturePos);
// 如果可视区域不能完全放置当前节点时允许调整
if (visibleRect && (overflow.adjustX || overflow.adjustY)) {
// 如果横向不能放下
if (isFailX(elFuturePos, elRegion, visibleRect)) {
fail = 1;
// 对齐位置反下
points = flip(points, /[lr]/ig, {
l: 'r',
r: 'l'
});
// 偏移量也反下
offset = flipOffset(offset, 0);
}
// 如果纵向不能放下
if (isFailY(elFuturePos, elRegion, visibleRect)) {
fail = 1;
// 对齐位置反下
points = flip(points, /[tb]/ig, {
t: 'b',
b: 't'
});
// 偏移量也反下
offset = flipOffset(offset, 1);
}
// 如果失败,重新计算当前节点将要被放置的位置
if (fail) {
elFuturePos = getElFuturePos(elRegion, refNodeRegion, points, offset);
S.mix(newElRegion, elFuturePos);
}
var newOverflowCfg = {};
// 检查反下后的位置是否可以放下了
// 如果仍然放不下只有指定了可以调整当前方向才调整
newOverflowCfg.adjustX = overflow.adjustX &&
isFailX(elFuturePos, elRegion, visibleRect);
newOverflowCfg.adjustY = overflow.adjustY &&
isFailY(elFuturePos, elRegion, visibleRect);
// 确实要调整,甚至可能会调整高度宽度
if (newOverflowCfg.adjustX || newOverflowCfg.adjustY) {
newElRegion = adjustForViewport(elFuturePos, elRegion,
visibleRect, newOverflowCfg);
}
}
// https://github.com/kissyteam/kissy/issues/190
// http://localhost:8888/kissy/src/overlay/demo/other/relative_align/align.html
// 相对于屏幕位置没变,而 left/top 变了
// 例如 <div 'relative'><el absolute></div>
self.set({
'x': newElRegion.left,
'y': newElRegion.top
}, {
force: 1
});
// need judge to in case set fixed with in css on height auto element
if (newElRegion.width !== elRegion.width) {
self.set('width', el.width() + newElRegion.width - elRegion.width);
}
if (newElRegion.height !== elRegion.height) {
self.set('height', el.height() + newElRegion.height - elRegion.height);
}
return self;
},
/**
* Make current element center within node.
* @param {undefined|String|HTMLElement|KISSY.NodeList} node
* Same as node config of {@link KISSY.Component.Extension.Align#cfg-align}
* @chainable
*/
center: function (node) {
var self = this;
self.set('align', {
node: node,
points: ['cc', 'cc'],
offset: [0, 0]
});
return self;
},
__destructor: function () {
var self = this;
if (self.$el) {
self.$el.getWindow().detach('resize', onResize, self);
}
}
};
return Align;
});
/**
* @ignore
*
* 2012-04-26 yiminghe@gmail.com
* - 优化智能对齐算法
* - 慎用 resizeXX
*
* 2011-07-13 yiminghe@gmail.com note:
* - 增加智能对齐,以及大小调整选项
**/ |
import Vue from 'vue';
import iView from 'iview';
import VueRouter from 'vue-router';
import router from './router';
import store from './store';
import Vuex from 'vuex';
import { docTitle } from './plugins/utils/assist';
import SissTab from './components/tabs';
import SissCombo from './components/combo';
import SissContextMenu from './components/contextmenu';
import './styles/index.less';
import 'font-awesome-webpack';
Vue.use(VueRouter);
Vue.use(Vuex);
Vue.use(iView);
Vue.use(SissTab);
Vue.use(SissCombo);
Vue.use(SissContextMenu);
Vue.prototype.$marking = "si";
router.beforeEach((to, from, next) => {
iView.LoadingBar.start();
docTitle(to.name);
next();
});
router.afterEach(() => {
iView.LoadingBar.finish();
window.scrollTo(0, 0);
});
new Vue({
router,
store
}).$mount('#app'); |
import React from 'react'
const Search = () => {
return (
<div id="search" className="pure-u-2-3 center">
<input name="search" type="text" placeholder="suchen ..." required />
</div>
)
};
export default Search;
|
'use strict';
(function() {
// Needs Controller Spec
describe('Needs Controller Tests', function() {
// Initialize global variables
var NeedsController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Needs controller.
NeedsController = $controller('NeedsController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one Need object fetched from XHR', inject(function(Needs) {
// Create sample Need using the Needs service
var sampleNeed = new Needs({
title: 'Need Title',
description: 'Need Description'
});
// Create a sample Needs array that includes the new Need
var sampleNeeds = [sampleNeed];
// Set GET response
$httpBackend.expectGET('needs').respond(sampleNeeds);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.needs).toEqualData(sampleNeeds);
}));
it('$scope.findOne() should create an array with one Need object fetched from XHR using a needId URL parameter', inject(function(Needs) {
// Define a sample Need object
var sampleNeed = new Needs({
title: 'Need Title',
description: 'Need Description'
});
// Set the URL parameter
$stateParams.needId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/needs\/([0-9a-fA-F]{24})$/).respond(sampleNeed);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.need).toEqualData(sampleNeed);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Needs) {
// Create a sample Need object
var sampleNeedPostData = new Needs({
title: 'Need Title',
description: 'Need Description'
});
// Create a sample Need response
var sampleNeedResponse = new Needs({
_id: '525cf20451979dea2c000001',
title: 'Need Title',
description: 'Need Description'
});
// Fixture mock form input values
scope.title = 'Need Title';
scope.description = 'Need Description';
// Set POST response
$httpBackend.expectPOST('needs', sampleNeedPostData).respond(sampleNeedResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.title).toEqual('');
// Test URL redirection after the Need was created
expect($location.path()).toBe('/needs/' + sampleNeedResponse._id);
}));
it('$scope.update() should update a valid Need', inject(function(Needs) {
// Define a sample Need put data
var sampleNeedPutData = new Needs({
_id: '525cf20451979dea2c000001',
title: 'Need Title',
description: 'Need Description'
});
// Mock Need in scope
scope.need = sampleNeedPutData;
// Set PUT response
$httpBackend.expectPUT(/needs\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/needs/' + sampleNeedPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid needId and remove the Need from the scope', inject(function(Needs) {
// Create new Need object
var sampleNeed = new Needs({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new Needs array and include the Need
scope.needs = [sampleNeed];
// Set expected DELETE response
$httpBackend.expectDELETE(/needs\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleNeed);
$httpBackend.flush();
// Test array after successful delete
expect(scope.needs.length).toBe(0);
}));
});
}());
|
(function(window, document, undefined) {
// Capitalises a string
// Accepts:
// str: string
// Returns:
// string
var majusculeFirst = function(str) {
return str.charAt(0).toUpperCase() + str.substring(1);
};
// Usage:
// var data = { 'first name': 'George', 'last name': 'Jetson', 'age': 110 };
// var querystring = EncodeQueryData(data);
var encodeQueryData = function (data) {
var ret = [];
for (var d in data)
ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return ret.join("&");
};
// Replaces ERB-style tags with Liquid ones as we can't escape them in posts
// Accepts:
// elements: jQuery elements in which to replace tags
// Returns:
// undefined
var replaceERBTags = function(elements) {
elements.each(function() {
// Only for text blocks at the moment as we'll strip highlighting otherwise
var $this = $(this);
var txt = $this.html();
// Replace <%= %>with {{ }}
txt = txt.replace(new RegExp('<%=(.+?)%>', 'g'), '{{$1}}');
// Replace <% %> with {% %}
txt = txt.replace(new RegExp('<%(.+?)%>', 'g'), '{%$1%}');
$this.html(txt);
});
};
// Gets a map with all key and values from the URL
// Returns:
// map { key: value }
var urlParams = function() {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
};
// Retrieves the value of a GET parameter with a given key
// Accepts:
// param: string
// Returns:
// string or null
var getParam = function(param) {
var queryString = window.location.search.substring(1); //decodeURI(window.location.search);
var queries = queryString.split('&');
for (var i in queries) {
var pair = queries[i].split('=');
if (pair[0] === param) {
// Decode the parameter value, replacing %20 with a space etc.
return decodeURIComponent(pair[1]);
}
}
return null;
};
// Filters posts with the condition `post['property'] == value`
// Accepts:
// posts - array of post objects and a string
// property - string of post object property to compare
// value - filter value of property
// Returns:
// array of post objects
var filterPostsByPropertyValue = function(posts, property, value) {
var filteredPosts = [];
for (var i in posts) {
var post = posts[i];
var prop = post[property];
// The property could be a string, such as a post's category,
// or an array, such as a post's tags
if (prop.constructor === String) {
if (prop.toLowerCase() === value.toLowerCase()) {
filteredPosts.push(post);
}
} else if (prop.constructor === Array) {
for (var j in prop) {
if (prop[j].toLowerCase() === value.toLowerCase()) {
filteredPosts.push(post);
}
}
}
}
return filteredPosts;
};
// Formats search results and appends them to the DOM
// Accepts:
// property: string of object type we're displaying
// value: string of name of object we're displaying
// posts: array of post objects
// Returns:
// undefined
var layoutResultsPage = function(containername, templatename, propertyid, property, posts, fail) {
var $container = $(containername);
var data = {};
if ($container.length === 0) return;
$(propertyid).append(property);
if (posts.length === 0) {
$container.html('<p>' + fail + '</p>');
} else {
data['posts'] = posts;
$container.html(tmpl(templatename, data));
}
}
// Get the bootstrap environment
var findBootstrapEnvironment = function () {
var envs = ['xs', 'sm', 'md', 'lg'];
$el = $('<div>');
$el.appendTo($('body'));
for (var i = envs.length - 1; i >= 0; i--) {
var env = envs[i];
$el.addClass('hidden-'+env);
if ($el.is(':hidden')) {
$el.remove();
return env;
}
};
}
// Define the app object and expose it in the global scope
window.Jekyll = {
majusculeFirst: majusculeFirst,
urlParams: urlParams,
getParam: getParam,
filterPostsByPropertyValue: filterPostsByPropertyValue,
layoutResultsPage: layoutResultsPage,
encodeQueryData: encodeQueryData,
replaceERBTags: replaceERBTags,
findBootstrapEnvironment: findBootstrapEnvironment
};
})(window, window.document);
$(function() {
// var responsiveHeader = function() {
// var size = Jekyll.findBootstrapEnvironment();
// if (size == 'xs') {
// if ($('#header-button-mobile').hasClass('hidden')) {
// $('#header-tabs-items').removeClass('nav');
// $('#header-tabs-items').removeClass('nav-tabs');
// $('#header-button-mobile').removeClass('hidden');
// $('#header-tabs-items').addClass('dropdown-menu');
// }
// } else {
// if (! $('#header-button-mobile').hasClass('hidden')) {
// $('#header-button-mobile').addClass('hidden');
// $('#header-tabs-items').addClass('nav');
// $('#header-tabs-items').addClass('nav-tabs');
// $('#header-tabs-items').removeClass('dropdown-menu');
// }
// }
// };
// responsiveHeader();
// $(window).bind('resize', responsiveHeader);
});
|
import React, { Component } from 'react';
import { Link } from 'react-router';
export class Login extends Component{
render(){
return(<div className="login-container">
<div className="login-form">
<div className="form-title">Login</div>
<div className="line"></div>
<div className="form-elements">
<div className="form-group">
<div className="label">E-mail</div>
<input className="form-input" type="text"/>
</div>
<div className="form-group">
<div className="label">Password</div>
<input className="form-input" type="password"/>
<div className="form-options">
<div className = "remember">
<input type="checkbox" />
Remember Me
</div>
<div className= "forget">
Forgot password
</div>
</div>
</div>
<div className="form-group">
<button type="submit" className="submit-button">Login</button>
</div>
<div className="social-login">
<div className="social-label">or Login using</div>
<div className="social-options">
<div className="facebook">
<img src="../../img/facebook.png" />Facebook</div>
<div className="google">
<img src="../../img/google.png" />Google</div>
</div>
</div>
<div className="login-switch">
<Link className="link" to="/register">Haven't created an account yet? Register.</Link>
</div>
</div>
</div>
</div>)
}
}
export default class LoginPage extends Component {
constructor() {
super();
this.state = {
}
}
render() {
return (<div className="mycontainer center">
<Login />
</div>)
}
}
|
angular.module('todoService', [])
.factory('Todos', ['$http',function($http) {
return {
get : function() {
return $http.get('/api/todos');
},
create : function(todoData) {
return $http.post('/api/todos', todoData);
},
delete : function(id) {
return $http.delete('/api/todos/' + id);
}
}
}]); |
function shadeBlend(p, c0, c1) {
var n = p < 0 ? p * -1 : p, u = Math.round, w = parseInt;
if (c0.length > 7) {
var f = c0.split(","), t = (c1 ? c1 : p < 0 ? "rgb(0,0,0)" : "rgb(255,255,255)").split(","), R = w(f[0].slice(4)), G = w(f[1]), B = w(f[2]);
return "rgb(" + (u((w(t[0].slice(4)) - R) * n) + R) + "," + (u((w(t[1]) - G) * n) + G) + "," + (u((w(t[2]) - B) * n) + B) + ")"
} else {
var f = w(c0.slice(1), 16), t = w((c1 ? c1 : p < 0 ? "#000000" : "#FFFFFF").slice(1), 16), R1 = f >> 16, G1 = f >> 8 & 0x00FF, B1 = f & 0x0000FF;
return "#" + (0x1000000 + (u(((t >> 16) - R1) * n) + R1) * 0x10000 + (u(((t >> 8 & 0x00FF) - G1) * n) + G1) * 0x100 + (u(((t & 0x0000FF) - B1) * n) + B1)).toString(16).slice(1)
}
}
var colors = [
"#d35400",
"#c0392b",
"#2980b9",
"#7f8c8d"
];
angular.module('starter.controllers', [])
.controller('homeCtrl', function ($scope, $state) {
console.log('in home');
$scope.start = function () {
console.log('clicked');
$state.go('tab.persona');
};
})
.controller('personaCtrl', function ($scope, $state) {
var student = {
parent: null,
name: 'root',
wallet: {
address: 'mrp4coJDchLcMqyo3KKV4HFPmY5UT2qKRT',
key: 'cRppGzhJzdEgM5vfNn9e72bKpLDWxTD8gXDKbpE3JLBKLiMzfNEQ',
balance: 0
},
pockets: {
Savings: {
parent: 'root',
name: 'Savings',
hard_ratio: 0.70,
color: '#8e44ad',
pockets: {
House: {
name: 'House',
parent: 'savings',
hard_ratio: 0.7,
savings: true,
wallet: {
address: 'mrp4coJDchLcMqyo3KKV4HFPmY5UT2qKRT',
key: 'cRppGzhJzdEgM5vfNn9e72bKpLDWxTD8gXDKbpE3JLBKLiMzfNEQ',
balance: 147
}
},
Pension: {
name: 'Pension',
parent: 'savings',
hard_ratio: 0.3,
wallet: {
address: 'mrp4coJDchLcMqyo3KKV4HFPmY5UT2qKRT',
key: 'cRppGzhJzdEgM5vfNn9e72bKpLDWxTD8gXDKbpE3JLBKLiMzfNEQ',
balance: 63
}
}
}
},
Spending: {
parent: 'root',
name: 'Spending',
hard_ratio: 0.30,
color: '#2c3e50',
pockets: {
'shopping': {
parent: 'spending',
name: 'shopping',
hard_ratio: 0.25,
wallet: {
address: 'mrp4coJDchLcMqyo3KKV4HFPmY5UT2qKRT',
key: 'cRppGzhJzdEgM5vfNn9e72bKpLDWxTD8gXDKbpE3JLBKLiMzfNEQ',
balance: 22.5
}
},
'cigarettes': {
parent: 'spending',
name: 'cigarettes',
hard_ratio: 0.25,
wallet: {
address: 'mrp4coJDchLcMqyo3KKV4HFPmY5UT2qKRT',
key: 'cRppGzhJzdEgM5vfNn9e72bKpLDWxTD8gXDKbpE3JLBKLiMzfNEQ',
balance: 22.5
}
},
Rent: {
parent: 'spending',
name: 'Rent',
hard_ratio: 0.25,
wallet: {
address: 'mrp4coJDchLcMqyo3KKV4HFPmY5UT2qKRT',
key: 'cRppGzhJzdEgM5vfNn9e72bKpLDWxTD8gXDKbpE3JLBKLiMzfNEQ',
balance: 22.5
}
},
gadgets: {
parent: 'spending',
name: 'gadgets',
hard_ratio: 0.25,
wallet: {
address: 'mrp4coJDchLcMqyo3KKV4HFPmY5UT2qKRT',
key: 'cRppGzhJzdEgM5vfNn9e72bKpLDWxTD8gXDKbpE3JLBKLiMzfNEQ',
balance: 22.5
}
}
}
}
}
};
$scope.choosePersona = function (persona) {
if (persona === 'student') {
engine.pockets.create(student).then(function () {
$state.go('tab.pockets');
}).error(function (err) {
if (err) throw err;
});
}
};
})
.controller('settingsCtrl', function ($scope) {
$scope.fee = 0.0001;
$scope.save = function () {
engine.config.set({fee: $scope.fee});
};
})
.controller('pocketsCtrl', function ($scope, $state, $stateParams, $ionicPopup) {
$scope.pocketName = $stateParams.pocketName;
if ($stateParams.pocketName === '')
$scope.pocketName = 'root';
engine.pockets.get({name: $scope.pocketName}).then(function (result) {
var currentColor = result.color;
var i = 1;
for (var k in result.pockets) {
if (result.pockets.hasOwnProperty(k)) {
if (!result.pockets[k].color && result.pockets[k] != 'root')
result.pockets[k].color = shadeBlend(i / 10, currentColor);
}
i++;
}
$scope.pockets = result;
$scope.$digest();
}).error(function (err) {
if (err)
throw err;
});
$scope.selectPocket = function (pocketName, hasChildren) {
if (hasChildren)
$state.go('tab.pockets', {pocketName: pocketName});
else
$state.go('tab.pocket-details', {pocketName: pocketName});
};
$scope.spend = function () {
$scope.data = {};
var myPopup = $ionicPopup.show({
template: '<div class="list">' +
'<label class="item item-input item-select">' +
'<span class="input-label">Spend from</span>' +
'<select ng-model="data.pocket">' +
'<option ng-repeat="(key, pocket) in pockets.pockets" value="{{pocket.name}}">{{pocket.name}}</option>' +
'</select>' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">Amount</span>' +
'<input ng-model="data.amount" type="number" placeholder="0.01">' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">To address</span>' +
'<input ng-model="data.toAddress" type="text" placeholder="BTC Address">' +
'</label>' +
'<br><div style="text-align:center"><button class="btn btn-primary" ng-click="scanQR()">Scan</button></div>' +
'</div>',
title: 'Send money',
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Send</b>',
type: 'button-positive',
onTap: function (e) {
if (!$scope.data) {
//don't allow the user to close unless he enters wifi password
e.preventDefault();
} else {
return $scope.result;
}
}
}
]
});
myPopup.then(function (res) {
console.log($scope.data);
});
};
$scope.editPocket = function (pocketName) {
engine.pockets.get({name: pocketName}).then(function (result) {
$scope.result = result;
var myPopup = $ionicPopup.show({
template: '<div class="list">' +
'<label class="item item-input item-select">' +
'<span class="input-label">Parent</span>' +
'<select ng-model="result.parent">' +
'<option value="root">root</option>' +
'<option ng-repeat="(key, pocket) in result.pockets" value="{{result.name}}">{{pocket.name}}</option>' +
'</select>' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">Pocket name</span>' +
'<input ng-model="result.name" type="text" placeholder="My new pocket">' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">Ratio</span>' +
'<input ng-model="result.hard_ratio" type="number" placeholder="20">' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">Color</span>' +
'<input ng-model="result.color" type="text" placeholder="#cccccc">' +
'</label>' +
'<label class="item item-input item-select">' +
'<span class="input-label">Importance</span>' +
'<select>' +
'<option value="low">Low</option>' +
'<option value="high">High</option>' +
'</select>' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">Limit</span>' +
'<input ng-model="result.limit" type="number" placeholder="1">' +
'</label>' +
'</div>',
title: 'Edit pocket',
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Save</b>',
type: 'button-positive',
onTap: function (e) {
if (!$scope.result) {
//don't allow the user to close unless he enters wifi password
e.preventDefault();
} else {
return $scope.result;
}
}
}
]
});
myPopup.then(function (res) {
engine.pockets.update(res).then(function () {
}).error(function (err) {
if (err) throw err;
});
});
}).error(function (err) {
if (err)
throw err;
});
};
$scope.pocketHold = function (pocketName) {
var myPopup = $ionicPopup.alert({
template: "<div>Delete?</div>",
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Delete</b>',
type: 'button-positive',
onTap: function () {
return true
}
}
]
});
myPopup.then(function (res) {
if (res) {
engine.pockets.delete({name: pocketName}).then(function () {
}).error(function (err) {
if (err)
throw err;
});
}
});
};
$scope.addPocket = function () {
$scope.newpocket = {};
var myPopup = $ionicPopup.show({
template: '<div class="list">' +
'<label class="item item-input item-select">' +
'<span class="input-label">Parent</span>' +
'<select ng-model="newpocket.parent">' +
'<option value="root">root</option>' +
'<option ng-repeat="(key, pocket) in pockets.pockets" value="{{pocket.name}}">{{pocket.name}}</option>' +
'</select>' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">Pocket name</span>' +
'<input ng-model="newpocket.name" type="text" placeholder="My new pocket">' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">Ratio</span>' +
'<input ng-model="newpocket.hard_ratio" type="number" placeholder="20">' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">Color</span>' +
'<input ng-model="newpocket.color" type="text" placeholder="#cccccc">' +
'</label>' +
'<label class="item item-input item-select">' +
'<span class="input-label">Importance</span>' +
'<select>' +
'<option value="low">Low</option>' +
'<option value="high">High</option>' +
'</select>' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">Limit</span>' +
'<input ng-model="newpocket.limit" type="number" placeholder="1">' +
'</label>' +
'</div>',
title: 'Add a new pocket',
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Add</b>',
type: 'button-positive',
onTap: function (e) {
if (!$scope.newpocket) {
//don't allow the user to close unless he enters wifi password
e.preventDefault();
} else {
return $scope.newpocket;
}
}
}
]
});
myPopup.then(function (res) {
if (res) {
$scope.newpocket.hard_ratio = $scope.newpocket.hard_ratio / 100;
engine.pockets.create($scope.newpocket).then(function () {
//$state.go('')
}).error(function (err) {
if (err)
throw err;
});
}
});
};
$scope.rootInfo = function () {
$state.go('tab.rootinfo');
}
})
.controller('rootinfoCtrl', function ($scope, $ionicPopup) {
engine.pockets.get({name: 'root'}).then(function (pockets) {
$scope.pockets = pockets;
}).error(function (err) {
if (err)
throw err;
});
$scope.spendDialog = function () {
$scope.data = {};
var myPopup = $ionicPopup.show({
template: '<label class="item item-input">' +
'<span class="input-label">Amount</span>' +
'<input ng-model="data.amount" type="number" placeholder="0.01">' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">To address</span>' +
'<input ng-model="data.toAddress" type="text" placeholder="BTC Address">' +
'</label>' +
'<br><div style="text-align:center"><button class="btn btn-primary" ng-click="scanQR()">Scan</button></div>',
title: 'Spend from parent wallet',
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Send!</b>',
type: 'button-positive'
}
]
});
myPopup.then(function (res) {
if (res) {
engine.bitcoin.sendMoney({
from: {
name: 'root',
wallet: {
address: $scope.pockets.wallet.address,
key: $scope.pockets.wallet.key
}
},
to: {
name: 'test',
wallet: {
address: $scope.data.toAddress
}
},
amount: $scope.data.amount
}).then(function (result) {
console.log(result);
}).error(function (err) {
console.log(err);
});
console.log($scope.pockets.name, $scope.data.toAddress, $scope.data.amount);
}
});
};
console.log('in root');
})
.controller('pocketDetailsCtrl', function ($scope, $state, $ionicPopup, $stateParams, $cordovaBarcodeScanner) {
engine.pockets.get({name: $stateParams.pocketName}).then(function (result) {
$scope.pockets = result;
$scope.$digest();
});
$scope.scanQR = function () {
$cordovaBarcodeScanner.scan().then(function (imageData) {
$scope.data.toAddress = imageData.text;
}, function (error) {
console.log("An error happened -> " + error);
});
};
$scope.spendDialog = function () {
$scope.data = {};
var myPopup = $ionicPopup.show({
template: '<label class="item item-input">' +
'<span class="input-label">Amount</span>' +
'<input ng-model="data.amount" type="number" placeholder="0.01">' +
'</label>' +
'<label class="item item-input">' +
'<span class="input-label">To address</span>' +
'<input ng-model="data.toAddress" type="text" placeholder="0.01">' +
'</label>' +
'<br><div style="text-align:center"><button class="btn btn-primary" ng-click="scanQR()">Scan</button></div>',
title: 'Spend from ' + $scope.pockets.name,
scope: $scope,
buttons: [
{text: 'Cancel'},
{
text: '<b>Send!</b>',
type: 'button-positive'
}
]
});
myPopup.then(function (res) {
if (res) {
engine.bitcoin.sendMoney({
from: {
name: $scope.pockets.name,
wallet: {
address: $scope.pockets.wallet.address,
key: $scope.pockets.wallet.key
}
},
to: {
name: 'test',
wallet: {
address: $scope.data.toAddress
}
},
amount: $scope.data.amount
}).then(function (result) {
console.log(result);
}).error(function (err) {
console.log(err);
});
console.log($scope.pockets.name, $scope.data.toAddress, $scope.data.amount);
}
});
};
})
.controller('DashCtrl', function ($scope) {
})
.controller('ChatsCtrl', function ($scope, Chats) {
$scope.chats = Chats.all();
$scope.remove = function (chat) {
Chats.remove(chat);
}
})
.controller('ChatDetailCtrl', function ($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('AccountCtrl', function ($scope) {
$scope.settings = {
enableFriends: true
};
});
|
/**
* Created by khuongdt on 11/12/2015.
*/
goog.provide('bigfox.example.ChatHandler');
goog.require('goog.log');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('bigfox.core.base.BaseMessage');
goog.require('bigfox.core.base.MessageIn');
goog.require('bigfox.core.base.MessageOut');
goog.require('bigfox.core.crypt.CryptManager');
goog.require('bigfox.core.util.BFCompressUtil');
goog.require('bigfox.core.websocket.BFConnectionHandler');
/**
*
* @param {!bigfox.core.websocket.BFConnection} connection
* @constructor
*/
bigfox.example.ChatHandler= function(connection){
bigfox.example.ChatHandler.base(this,'constructor', connection)
}
goog.inherits(bigfox.example.ChatHandler,bigfox.core.websocket.BFConnectionHandler);
bigfox.example.ChatHandler.prototype.onOpen = function(e){
}
bigfox.example.ChatHandler.prototype.onMessage = function(e){
console.log('On Message in Chat handler: ', e.message);
if(e.message instanceof bigfox.example.SCChatMessage){
$('.chat').append(e.message.getMessage());
$('.chat').append('<br>');
}
}
bigfox.example.ChatHandler.prototype.onError = function(e){
}
bigfox.example.ChatHandler.prototype.onClose = function(e){
if(goog.DEBUG){
console.log('Connection closed!');
}
} |
/*!
Bootstrap integration for DataTables' SearchPanes
©2016 SpryMedia Ltd - datatables.net/license
*/
(function(b){"function"===typeof define&&define.amd?define(["jquery","datatables.net-bs4","datatables.net-searchpanes"],function(a){return b(a,window,document)}):"object"===typeof exports?module.exports=function(a,c){a||(a=window);if(!c||!c.fn.dataTable)c=require("datatables.net-bs4")(a,c).$;c.fn.dataTable.SearchPanes||require("datatables.net-searchpanes")(a,c);return b(c,a,a.document)}:b(jQuery,window,document)})(function(b){var a=b.fn.dataTable;b.extend(!0,a.SearchPane.classes,{buttonGroup:"btn-group",
disabledButton:"disabled",narrow:"col",pane:{container:"table"},paneButton:"btn btn-light",pill:"pill badge badge-pill badge-secondary",search:"form-control search",searchCont:"input-group",searchLabelCont:"input-group-append",subRow1:"dtsp-subRow1",subRow2:"dtsp-subRow2",table:"table table-sm table-borderless",topRow:"dtsp-topRow"});b.extend(!0,a.SearchPanes.classes,{clearAll:"dtsp-clearAll btn btn-light",container:"dtsp-searchPanes",disabledButton:"disabled",panes:"dtsp-panes dtsp-panesContainer",
title:"dtsp-title",titleRow:"dtsp-titleRow"});return a.searchPanes});
|
var _ = require('lodash');
var Store = require('./Store');
var DebugStore = require('./debug/DebugStore');
var DebugActions = require('./debug/DebugActions');
var RegisteredStore = _.assign({}, Store, {
name: '',
/**
* Fetch an object of data to display on the debug output
*/
getDebugData: function() {
return {};
},
/**
* Assign additional functionality to this store
* @param data
* @returns {*|void}
*/
assign: function(data) {
return _.assign(this, data);
}
});
module.exports = {
create: function(name) {
var store = _.assign({}, RegisteredStore, {
name: name
});
// If the debug store is alive this will be dispatched, if not (production) then these actions will go ignored.
DebugActions.registerStore(name, store);
return store;
}
};
|
// Copyright 2008 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Check for regression of bug 1011505 (out of memory when flattening strings).
var i;
var s = "";
for (i = 0; i < 1024; i++) {
s = s + (i + (i+1));
s = s.substring(1);
}
// Flatten the string.
assertEquals(57, s.charCodeAt(0));
|
var mlcl_forms = angular.module('mlcl_forms')
.directive('selectObjectids', ['$http', 'configService', function($http, configService) {
return {
scope: {
model: '=widgetmodel',
fieldinfo: '=',
selected: "="
},
restrict: 'E',
templateUrl: 'widgetDirectives/selectObjectids/selectObjectid.tpl.html',
link: function(scope) {
if(scope.selected) {
scope.selected = {};
}
scope.foundObjects = [];
scope.refreshObjects = function(searchString) {
var searchParam = {q: searchString};
return $http.get(
configService.apiHost+'/api/search/'+scope.fieldinfo.ref,
{params: searchParam}
).then(function(response) {
scope.foundObjects = response.data.results;
});
};
}
};
}]);
|
import _ from 'lodash';
import Component from '../_classes/component/Component';
import ComponentModal from '../_classes/componentModal/ComponentModal';
import EventEmitter from 'eventemitter3';
import NativePromise from 'native-promise-only';
import {
isMongoId,
eachComponent,
getStringFromComponentPath,
getArrayFromComponentPath
} from '../../utils/utils';
import { GlobalFormio as Formio } from '../../Formio';
import Form from '../../Form';
export default class FormComponent extends Component {
static schema(...extend) {
return Component.schema({
label: 'Form',
type: 'form',
key: 'form',
src: '',
reference: true,
form: '',
path: '',
tableView: true,
}, ...extend);
}
static get builderInfo() {
return {
title: 'Nested Form',
icon: 'wpforms',
group: 'premium',
documentation: '/userguide/#form',
weight: 110,
schema: FormComponent.schema()
};
}
init() {
super.init();
this.formObj = {
display: this.component.display,
settings: this.component.settings,
components: this.component.components
};
this.valueChanged = false;
this.subForm = null;
this.formSrc = '';
if (this.component.src) {
this.formSrc = this.component.src;
}
if (
!this.component.src &&
!this.options.formio &&
(this.component.form || this.component.path)
) {
if (this.component.project) {
this.formSrc = Formio.getBaseUrl();
// Check to see if it is a MongoID.
if (isMongoId(this.component.project)) {
this.formSrc += '/project';
}
this.formSrc += `/${this.component.project}`;
this.options.project = this.formSrc;
}
else {
this.formSrc = Formio.getProjectUrl();
this.options.project = this.formSrc;
}
if (this.component.form) {
if (isMongoId(this.component.form)) {
this.formSrc += `/form/${this.component.form}`;
}
else {
this.formSrc += `/${this.component.form}`;
}
}
else if (this.component.path) {
this.formSrc += `/${this.component.path}`;
}
}
// Build the source based on the root src path.
if (!this.formSrc && this.options.formio) {
const rootSrc = this.options.formio.formsUrl;
if (this.component.form && isMongoId(this.component.form)) {
this.formSrc = `${rootSrc}/${this.component.form}`;
}
else {
const formPath = this.component.path || this.component.form;
this.formSrc = `${rootSrc.replace(/\/form$/, '')}/${formPath}`;
}
}
if (this.builderMode && this.component.hasOwnProperty('formRevision')) {
this.component.revision = this.component.formRevision;
delete this.component.formRevision;
}
// Add revision version if set.
if (this.component.revision || this.component.revision === 0 ||
this.component.formRevision || this.component.formRevision === 0
|| this.component.revisionId
) {
this.setFormRevision(this.component.revisionId || this.component.revision || this.component.formRevision);
}
return this.createSubForm();
}
get dataReady() {
return this.subFormReady || NativePromise.resolve();
}
get defaultValue() {
// Not not provide a default value unless the subform is ready so that it will initialize correctly.
return this.subForm ? super.defaultValue : null;
}
get defaultSchema() {
return FormComponent.schema();
}
get emptyValue() {
return { data: {} };
}
get ready() {
return this.subFormReady || NativePromise.resolve();
}
get useOriginalRevision() {
return this.component?.useOriginalRevision && !!this.formObj?.revisions;
}
setFormRevision(rev) {
// Remove current revisions from src if it is
this.formSrc = this.formSrc.replace(/\/v\/[0-9a-z]+/, '');
const revNumber = Number.parseInt(rev);
if (!isNaN(revNumber)) {
this.subFormRevision = rev;
this.formSrc += `/v/${rev}`;
}
else {
this.subFormRevision = undefined;
}
}
getComponent(path, fn) {
path = getArrayFromComponentPath(path);
if (path[0] === 'data') {
path.shift();
}
const originalPathStr = `${this.path}.data.${getStringFromComponentPath(path)}`;
if (this.subForm) {
return this.subForm.getComponent(path, fn, originalPathStr);
}
}
getSubOptions(options = {}) {
options.parentPath = `${this.path}.data.`;
options.events = this.createEmitter();
// Make sure to not show the submit button in wizards in the nested forms.
_.set(options, 'buttonSettings.showSubmit', false);
if (!this.options) {
return options;
}
if (this.options.base) {
options.base = this.options.base;
}
if (this.options.project) {
options.project = this.options.project;
}
if (this.options.readOnly || this.component.disabled) {
options.readOnly = this.options.readOnly || this.component.disabled;
}
if (this.options.breadcrumbSettings) {
options.breadcrumbSettings = this.options.breadcrumbSettings;
}
if (this.options.buttonSettings) {
options.buttonSettings = _.clone(this.options.buttonSettings);
}
if (this.options.viewAsHtml) {
options.viewAsHtml = this.options.viewAsHtml;
}
if (this.options.language) {
options.language = this.options.language;
}
if (this.options.template) {
options.template = this.options.template;
}
if (this.options.templates) {
options.templates = this.options.templates;
}
if (this.options.renderMode) {
options.renderMode = this.options.renderMode;
}
if (this.options.attachMode) {
options.attachMode = this.options.attachMode;
}
if (this.options.iconset) {
options.iconset = this.options.iconset;
}
if (this.options.fileService) {
options.fileService = this.options.fileService;
}
if (this.options.onChange) {
options.onChange = this.options.onChange;
}
return options;
}
render() {
if (this.builderMode) {
return super.render(this.component.label || 'Nested form');
}
const subform = this.subForm ? this.subForm.render() : this.renderTemplate('loading');
return super.render(subform);
}
asString(value) {
return this.getValueAsString(value);
}
/**
* Prints out the value of form components as a datagrid value.
*/
getValueAsString(value) {
if (!value) {
return 'No data provided';
}
if (!value.data && value._id) {
return value._id;
}
if (!value.data || !Object.keys(value.data).length) {
return 'No data provided';
}
return '[Complex Data]';
}
attach(element) {
// Don't attach in builder.
if (this.builderMode) {
return super.attach(element);
}
return super.attach(element)
.then(() => {
if (this.isSubFormLazyLoad() && !this.hasLoadedForm && !this.subFormLoading) {
this.createSubForm(true);
}
return this.subFormReady.then(() => {
this.empty(element);
if (this.options.builder) {
this.setContent(element, this.ce('div', {
class: 'text-muted text-center p-2'
}, this.text(this.formObj.title)));
return;
}
this.setContent(element, this.render());
if (this.subForm) {
if (this.isNestedWizard) {
element = this.root.element;
}
this.subForm.attach(element);
this.valueChanged = this.hasSetValue;
if (!this.valueChanged && this.dataValue.state !== 'submitted') {
this.setDefaultValue();
}
else {
this.restoreValue();
}
}
if (!this.builderMode && this.component.modalEdit) {
const modalShouldBeOpened = this.componentModal ? this.componentModal.isOpened : false;
const currentValue = modalShouldBeOpened ? this.componentModal.currentValue : this.dataValue;
this.componentModal = new ComponentModal(this, element, modalShouldBeOpened, currentValue);
this.setOpenModalElement();
}
});
});
}
detach() {
if (this.subForm) {
this.subForm.detach();
}
super.detach();
}
get currentForm() {
return this._currentForm;
}
get hasLoadedForm() {
return this.formObj
&& this.formObj.components
&& Array.isArray(this.formObj.components)
&& this.formObj.components.length;
}
set currentForm(instance) {
this._currentForm = instance;
if (!this.subForm) {
return;
}
this.subForm.getComponents().forEach(component => {
component.currentForm = this;
});
}
get isRevisionChanged() {
return _.isNumber(this.subFormRevision)
&& _.isNumber(this.formObj._vid)
&& this.formObj._vid !== this.subFormRevision;
}
destroy() {
if (this.subForm) {
this.subForm.destroy();
this.subForm = null;
this.subFormReady = null;
}
super.destroy();
}
redraw() {
if (this.subForm) {
this.subForm.form = this.formObj;
this.setSubFormDisabled(this.subForm);
}
return super.redraw();
}
/**
* Pass everyComponent to subform.
* @param args
* @returns {*|void}
*/
everyComponent(...args) {
if (this.subForm) {
this.subForm.everyComponent(...args);
}
}
setSubFormDisabled(subForm) {
subForm.disabled = this.disabled; // When the Nested Form is disabled make the subForm disabled
}
updateSubWizards(subForm) {
if (this.isNestedWizard && this.root?.subWizards && subForm?._form?.display === 'wizard') {
const existedForm = this.root.subWizards.findIndex(form => form.component.form === this.component.form);
if (existedForm !== -1) {
this.root.subWizards[existedForm] = this;
}
else {
this.root.subWizards.push(this);
}
this.emit('subWizardsUpdated', subForm);
}
}
/**
* Create a subform instance.
*
* @return {*}
*/
createSubForm(fromAttach) {
this.subFormReady = this.loadSubForm(fromAttach).then((form) => {
if (!form) {
return;
}
// Iterate through every component and hide the submit button.
eachComponent(form.components, (component) => {
this.hideSubmitButton(component);
});
// If the subform is already created then destroy the old one.
if (this.subForm) {
this.subForm.destroy();
}
// Render the form.
return (new Form(form, this.getSubOptions())).ready.then((instance) => {
this.subForm = instance;
this.subForm.currentForm = this;
this.subForm.parent = this;
this.subForm.parentVisible = this.visible;
this.subForm.on('change', () => {
if (this.subForm) {
this.dataValue = this.subForm.getValue();
this.triggerChange({
noEmit: true
});
}
});
this.subForm.url = this.formSrc;
this.subForm.nosubmit = true;
this.subForm.root = this.root;
this.subForm.localRoot = this.isNestedWizard ? this.localRoot : this.subForm;
this.restoreValue();
this.valueChanged = this.hasSetValue;
this.onChange();
return this.subForm;
});
}).then((subForm) => {
this.updateSubWizards(subForm);
return subForm;
});
return this.subFormReady;
}
hideSubmitButton(component) {
const isSubmitButton = (component.type === 'button') &&
((component.action === 'submit') || !component.action);
if (isSubmitButton) {
component.hidden = true;
}
}
/**
* Load the subform.
*/
loadSubForm(fromAttach) {
if (this.builderMode || this.isHidden() || (this.isSubFormLazyLoad() && !fromAttach)) {
return NativePromise.resolve();
}
if (this.hasLoadedForm && !this.isRevisionChanged) {
// Pass config down to sub forms.
if (this.root && this.root.form && this.root.form.config && !this.formObj.config) {
this.formObj.config = this.root.form.config;
}
return NativePromise.resolve(this.formObj);
}
else if (this.formSrc) {
this.subFormLoading = true;
return (new Formio(this.formSrc)).loadForm({ params: { live: 1 } })
.then((formObj) => {
this.formObj = formObj;
this.subFormLoading = false;
return formObj;
})
.catch((err) => {
console.log(err);
return null;
});
}
return NativePromise.resolve();
}
get subFormData() {
return this.dataValue?.data || {};
}
checkComponentValidity(data, dirty, row, options) {
options = options || {};
const silentCheck = options.silentCheck || false;
if (this.subForm) {
return this.subForm.checkValidity(this.subFormData, dirty, null, silentCheck);
}
return super.checkComponentValidity(data, dirty, row, options);
}
checkComponentConditions(data, flags, row) {
const visible = super.checkComponentConditions(data, flags, row);
// Return if already hidden
if (!visible) {
return visible;
}
if (this.subForm) {
return this.subForm.checkConditions(this.subFormData);
}
// There are few cases when subForm is not loaded when a change is triggered,
// so we need to perform checkConditions after it is ready, or some conditional fields might be hidden in View mode
else if (this.subFormReady) {
this.subFormReady.then(() => {
if (this.subForm) {
return this.subForm.checkConditions(this.subFormData);
}
});
}
return visible;
}
calculateValue(data, flags, row) {
if (this.subForm) {
return this.subForm.calculateValue(this.subFormData, flags);
}
return super.calculateValue(data, flags, row);
}
setPristine(pristine) {
super.setPristine(pristine);
if (this.subForm) {
this.subForm.setPristine(pristine);
}
}
/**
* Determine if the subform should be submitted.
* @return {*|boolean}
*/
get shouldSubmit() {
return this.subFormReady && (!this.component.hasOwnProperty('reference') || this.component.reference) && !this.isHidden();
}
/**
* Returns the data for the subform.
*
* @return {*}
*/
getSubFormData() {
if (_.get(this.subForm, 'form.display') === 'pdf') {
return this.subForm.getSubmission();
}
else {
return NativePromise.resolve(this.dataValue);
}
}
/**
* Submit the subform if configured to do so.
*
* @return {*}
*/
submitSubForm(rejectOnError) {
// If we wish to submit the form on next page, then do that here.
if (this.shouldSubmit) {
return this.subFormReady.then(() => {
if (!this.subForm) {
return this.dataValue;
}
this.subForm.nosubmit = false;
return this.subForm.submitForm().then(result => {
this.subForm.loading = false;
this.subForm.showAllErrors = false;
this.dataValue = result.submission;
return this.dataValue;
}).catch(err => {
this.subForm.showAllErrors = true;
if (rejectOnError) {
this.subForm.onSubmissionError(err);
return NativePromise.reject(err);
}
else {
return {};
}
});
});
}
return this.getSubFormData();
}
/**
* Submit the form before the next page is triggered.
*/
beforePage(next) {
// Should not submit child forms if we are going to the previous page
if (!next) {
return super.beforePage(next);
}
return this.submitSubForm(true).then(() => super.beforePage(next));
}
/**
* Submit the form before the whole form is triggered.
*/
beforeSubmit() {
const submission = this.dataValue;
const isAlreadySubmitted = submission && submission._id && submission.form;
// This submission has already been submitted, so just return the reference data.
if (isAlreadySubmitted && !this.subForm?.wizard) {
this.dataValue = submission;
return NativePromise.resolve(this.dataValue);
}
return this.submitSubForm(false)
.then(() => {
return this.dataValue;
})
.then(() => super.beforeSubmit());
}
isSubFormLazyLoad() {
return this.root?._form?.display === 'wizard' && this.component.lazyLoad;
}
isHidden() {
if (!this.visible) {
return true;
}
return !super.checkConditions(this.rootValue);
}
setValue(submission, flags = {}) {
const changed = super.setValue(submission, flags);
this.valueChanged = true;
if (this.subForm) {
const revisionPath = submission._frid ? '_frid' : '_vid';
const shouldLoadOriginalRevision = this.useOriginalRevision
&& _.isNumber(submission[revisionPath])
&& _.isNumber(this.subForm.form?.[revisionPath])
&& submission._fvid !== this.subForm.form[revisionPath];
if (shouldLoadOriginalRevision) {
this.setFormRevision( submission._frid || submission._fvid);
this.createSubForm().then(() => {
this.attach(this.element);
});
}
else {
this.setSubFormValue(submission, flags);
}
}
return changed;
}
setSubFormValue(submission, flags) {
const shouldLoadSubmissionById = submission
&& submission._id
&& this.subForm.formio
&& _.isEmpty(submission.data);
if (shouldLoadSubmissionById) {
const formId = submission.form || this.formObj.form || this.component.form;
const submissionUrl = `${this.subForm.formio.formsUrl}/${formId}/submission/${submission._id}`;
this.subForm.setUrl(submissionUrl, this.options);
this.subForm.loadSubmission();
}
else {
this.subForm.setValue(submission, flags);
}
}
isEmpty(value = this.dataValue) {
return value === null || _.isEqual(value, this.emptyValue) || (this.areAllComponentsEmpty(value.data) && !value._id);
}
areAllComponentsEmpty(data) {
let res = true;
if (this.subForm) {
this.subForm.everyComponent((comp) => {
const componentValue = _.get(data, comp.key);
res &= comp.isEmpty(componentValue);
});
}
else {
res = false;
}
return res;
}
getValue() {
if (this.subForm) {
return this.subForm.getValue();
}
return this.dataValue;
}
get errors() {
let errors = super.errors;
if (this.subForm) {
errors = errors.concat(this.subForm.errors);
}
return errors;
}
updateSubFormVisibility() {
if (this.subForm) {
this.subForm.parentVisible = this.visible;
}
}
/**
* Determines if this form is a Nested Wizard
* which means it should be a Wizard itself and should be a direct child of a Wizard's page
* @returns {boolean}
*/
get isNestedWizard() {
return this.subForm?._form?.display === 'wizard' && this.parent?.parent?._form?.display === 'wizard';
}
get visible() {
return super.visible;
}
set visible(value) {
const isNestedWizard = this.isNestedWizard;
if (this._visible !== value) {
this._visible = value;
// Form doesn't load if hidden. If it becomes visible, create the form.
if (!this.subForm && value) {
this.createSubForm();
this.subFormReady.then(() => {
this.updateSubFormVisibility();
this.clearOnHide();
});
this.redraw();
return;
}
this.updateSubFormVisibility();
this.clearOnHide();
isNestedWizard ? this.rebuild() : this.redraw();
}
if (!value && isNestedWizard) {
this.root.redraw();
}
}
get parentVisible() {
return super.parentVisible;
}
set parentVisible(value) {
if (this._parentVisible !== value) {
this._parentVisible = value;
this.clearOnHide();
// Form doesn't load if hidden. If it becomes visible, create the form.
if (!this.subForm && value) {
this.createSubForm();
this.subFormReady.then(() => {
this.updateSubFormVisibility();
});
this.redraw();
return;
}
this.updateSubFormVisibility();
this.redraw();
}
}
isInternalEvent(event) {
switch (event) {
case 'focus':
case 'blur':
case 'componentChange':
case 'componentError':
case 'error':
case 'formLoad':
case 'languageChanged':
case 'render':
case 'checkValidity':
case 'initialized':
case 'submit':
case 'submitButton':
case 'nosubmit':
case 'updateComponent':
case 'submitDone':
case 'submissionDeleted':
case 'requestDone':
case 'nextPage':
case 'prevPage':
case 'wizardNavigationClicked':
case 'updateWizardNav':
case 'restoreDraft':
case 'saveDraft':
case 'saveComponent':
case 'pdfUploaded':
return true;
default:
return false;
}
}
createEmitter() {
const emitter = new EventEmitter();
const nativeEmit = emitter.emit;
const that = this;
emitter.emit = function(event, ...args) {
const eventType = event.replace(`${that.options.namespace}.`, '');
nativeEmit.call(this, event, ...args);
if (!that.isInternalEvent(eventType)) {
that.emit(eventType, ...args);
}
};
return emitter;
}
deleteValue() {
super.setValue(null, {
noUpdateEvent: true,
noDefault: true
});
this.unset();
}
}
|
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/*!
* Next JS
* Copyright (c)2011 Xenophy.CO.,LTD All rights Reserved.
* http://www.xenophy.com
*/
// {{{ NX.smtp.Response.close
module.exports = function() {
};
// }}}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/
|
// local imports
import calculateResponsiveState from 'actions/creators/calculateResponsiveState'
import CALCULATE_RESPONSIVE_STATE from 'actions/types/CALCULATE_RESPONSIVE_STATE'
describe('calculateResponsiveState', function () {
it('returns action object with correct type when no arg passed', function () {
const action = calculateResponsiveState()
// action should be an object
expect(action).to.be.an('object')
// action should have correct type
expect(action.type).to.equal(CALCULATE_RESPONSIVE_STATE)
})
it('returns action object with correct type when empty arg passed', function () {
const action = calculateResponsiveState({})
// action should be an object
expect(action).to.be.an('object')
// action should have correct type
expect(action.type).to.equal(CALCULATE_RESPONSIVE_STATE)
})
it('returns action object with correct type when window-like arg passed', function () {
const innerWidth = 100
const innerHeight = 200
const matchMedia = function () {}
const action = calculateResponsiveState({innerWidth, innerHeight, matchMedia})
// action should be an object
expect(action).to.be.an('object')
// action should have correct type
expect(action.type).to.equal(CALCULATE_RESPONSIVE_STATE)
})
it('puts the argument properties onto the returned action', function () {
const innerWidth = Math.ceil(100 * Math.random())
const innerHeight = Math.ceil(100 * Math.random())
const matchMedia = function () {
return Math.random() * Math.random()
}
const action = calculateResponsiveState({innerWidth, innerHeight, matchMedia})
// action should have same properties as passed to creator
expect(action.innerWidth).to.equal(innerWidth)
expect(action.innerHeight).to.equal(innerHeight)
expect(action.matchMedia).to.equal(matchMedia)
})
it('properly defaults when no arg passed', function () {
const action = calculateResponsiveState()
expect(action.innerWidth).to.be.undefined
expect(action.innerHeight).to.be.undefined
expect(action.matchMedia).to.be.undefined
})
it('properly defaults when empty arg passed', function () {
const action = calculateResponsiveState({})
expect(action.innerWidth).to.be.undefined
expect(action.innerHeight).to.be.undefined
expect(action.matchMedia).to.be.undefined
})
})
|
module.exports = {
assetPrefix: process.env.NODE_ENV === 'production' ? '/react-dat-gui' : ''
};
|
// python Template for the preamble
var preamble = (basis,classname)=>
`"""3D Projective Geometric Algebra.
Written by a generator written by enki.
"""
__author__ = \'Enki\'
import math
class ${classname}:
def __init__(self, value=0, index=0):
"""Initiate a new ${classname}.
Optional, the component index can be set with value.
"""
self.mvec = [0] * ${basis.length}
self._base = [${basis.map(x=>'"'+x+'"').join(', ')}]
if (value != 0):
self.mvec[index] = value
@classmethod
def fromarray(cls, array):
"""Initiate a new ${classname} from an array-like object.
The first axis of the array is assumed to correspond to the elements
of the algebra, and needs to have the same length. Any other dimensions
are left unchanged, and should have simple operations such as addition
and multiplication defined. NumPy arrays are therefore a perfect
candidate.
:param array: array-like object whose length is the dimension of the algebra.
:return: new instance of ${classname}.
"""
self = cls()
if len(array) != len(self):
raise TypeError('length of array must be identical to the dimension '
'of the algebra.')
self.mvec = array
return self
def __str__(self):
if isinstance(self.mvec, list):
res = ' + '.join(filter(None, [("%.7f" % x).rstrip("0").rstrip(".")+(["",self._base[i]][i>0]) if abs(x) > 0.000001 else None for i,x in enumerate(self)]))
else: # Assume array-like, redirect str conversion
res = str(self.mvec)
if (res == ''):
return "0"
return res
def __getitem__(self, key):
return self.mvec[key]
def __setitem__(self, key, value):
self.mvec[key] = value
def __len__(self):
return len(self.mvec)`
// python Template for our binary operators
var binary = (classname, symbol, name, name_a, name_b, name_ret, code, classname_a=classname, classname_b=classname, desc)=>
` def ${(name.match(/^s[^u]/) || name.match(/s$/))?name:({"+":"__add__","-":"__sub__","*":"__mul__","^":"__xor__","&":"__and__","|":"__or__"}[symbol]||name)}(${name_a},${name_b}):${(name in {Mul:1,Add:1,Sub:1})?`
"""${classname}.${name}
${desc}
"""
if type(${name_b}) in (int, float):
return ${name_a}.${name.toLowerCase()}s(${name_b})`:``}
${name_ret} = ${name_a}.mvec.copy()
${code.replace(/;/g,'').replace(/^ */g,'').replace(/\n */g,'\n ')}
return ${classname}.fromarray(${name_ret})
${(name in {Mul:1,Add:1})?` __r${name.toLowerCase()}__=__${name.toLowerCase()}__`:((name in {Sub:1})?`
def __r${name.toLowerCase()}__(${name_a},${name_b}):
"""${classname}.${name}
${desc}
"""
return ${name_b} + -1 * ${name_a}
`:``)}`;
// python Template for our unary operators
var unary = (classname, symbol, name, name_a, name_ret, code, classname_a=classname,desc)=>
` def ${({"~":"__invert__"}[symbol]||name)}(${name_a}):
"""${classname}.${name}
${desc}
"""
${name_ret} = ${name_a}.mvec.copy()
${code.replace(/;/g,'').replace(/^ */g,'').replace(/\n */g,'\n ')}
return ${classname}.fromarray(${name_ret})`;
// python template for CGA example
var CGA = (basis,classname)=>({
preamble:
``,
amble:
`
if __name__ == '__main__':
# CGA is point based. Vectors are points.
E1 = ${classname}(1.0, 1)
E2 = ${classname}(1.0, 2)
E3 = ${classname}(1.0, 3)
E4 = ${classname}(1.0, 4)
E5 = ${classname}(1.0, 5)
EO = E4 + E5
EI = (E5 - E4) * 0.5
def up(x, y, z):
return x * E1 + y * E2 + z * E3 + 0.5 * (x * x + y * y + z * z) * EI + EO
PX = up(1, 2, 3)
LINE = PX ^ EO ^ EI
SPHERE = (EO - EI).Dual()
# output some numbers.
print("a point :", str(PX))
print("a line :", str(LINE))
print("a sphere :", str(SPHERE))
`
});
// python template for algebras without example
var GENERIC = (basis,classname)=>({
preamble:`
`,
amble:`
${basis.slice(1).map((x,i)=>`${x} = ${classname}(1.0, ${i+1})`).join('\n')}
if __name__ == '__main__':
print("${basis[1]}*${basis[1]} :", str(${basis[1]}*${basis[1]}))
print("pss :", str(${basis[basis.length-1]}))
print("pss*pss :", str(${basis[basis.length-1]}*${basis[basis.length-1]}))
`
})
// python template for PGA example
var PGA3D = (basis,classname)=>({
preamble:
``,
amble:
`
if __name__ == '__main__':
# A rotor (Euclidean line) and translator (Ideal line)
def rotor(angle, line):
return math.cos(angle / 2.0) + math.sin(angle / 2.0) * line.normalized()
def translator(dist, line):
return 1.0 + dist / 2.0 * line
# PGA is plane based. Vectors are planes. (think linear functionals)
E0 = ${classname}(1.0, 1) # ideal plane
E1 = ${classname}(1.0, 2) # x=0 plane
E2 = ${classname}(1.0, 3) # y=0 plane
E3 = ${classname}(1.0, 4) # z=0 plane
# A plane is defined using its homogenous equation ax + by + cz + d = 0
def PLANE(a, b, c, d):
return a * E1 + b * E2 + c * E3 + d * E0
# PGA points are trivectors.
E123 = E1 ^ E2 ^ E3
E032 = E0 ^ E3 ^ E2
E013 = E0 ^ E1 ^ E3
E021 = E0 ^ E2 ^ E1
# A point is just a homogeneous point, euclidean coordinates plus the origin
def POINT(x, y, z):
return E123 + x * E032 + y * E013 + z * E021
# for our toy problem (generate points on the surface of a torus)
# we start with a function that generates motors.
# circle(t) with t going from 0 to 1.
def CIRCLE(t, radius, line):
return rotor(t * math.pi * 2.0, line) * translator(radius, E1 * E0)
# a torus is now the product of two circles.
def TORUS(s, t, r1, l1, r2, l2):
return CIRCLE(s, r2, l2)*CIRCLE(t, r1, l1)
# sample the torus points by sandwich with the origin
def POINT_ON_TORUS(s, t):
to = TORUS(s, t, 0.25, E1 * E2, 0.6, E1 * E3)
return to * E123 * ~to
# Elements of the even subalgebra (scalar + bivector + pss) of unit length are motors
ROT = rotor(math.pi / 2.0, E1 * E2)
# The outer product ^ is the MEET. Here we intersect the yz (x=0) and xz (y=0) planes.
AXZ = E1 ^ E2 # x=0, y=0 -> z-axis line
# line and plane meet in point. We intersect the line along the z-axis (x=0,y=0) with the xy (z=0) plane.
ORIG = AXZ ^ E3 # x=0, y=0, z=0 -> origin
# We can also easily create points and join them into a line using the regressive (vee, &) product.
PX = POINT(1, 0, 0)
LINE = ORIG & PX # & = regressive product, JOIN, here, x-axis line.
# Lets also create the plane with equation 2x + z - 3 = 0
P = PLANE(2, 0, 1, -3)
# rotations work on all elements ..
ROTATED_LINE = ROT * LINE * ~ROT
ROTATED_POINT = ROT * PX * ~ROT
ROTATED_PLANE = ROT * P * ~ROT
# See the 3D PGA Cheat sheet for a huge collection of useful formulas
POINT_ON_PLANE = (P | PX) * P
# output some numbers.
print("a point :", str(PX))
print("a line :", str(LINE))
print("a plane :", str(P))
print("a rotor :", str(ROT))
print("rotated line :", str(ROTATED_LINE))
print("rotated point :", str(ROTATED_POINT))
print("rotated plane :", str(ROTATED_PLANE))
print("point on plane:", str(POINT_ON_PLANE.normalized()))
print("point on torus:", str(POINT_ON_TORUS(0.0, 0.0)))
print(E0 - 1)
print(1 - E0)
`
})
// python Template for the postamble
var postamble = (basis,classname,example)=>
` def norm(a):
return abs((a * a.Conjugate())[0])**0.5
def inorm(a):
return a.Dual().norm()
def normalized(a):
return a * (1 / a.norm())
${example.amble}
`;
Object.assign(exports,{preamble,postamble,unary,binary,desc:"python",PGA3D,CGA,GENERIC});
|
const path = require('path');
const rootDir = path.resolve('./');
module.exports = {
entry: {
bundle: rootDir + '/js/main.js',
},
output: {
filename: '[name].js',
path: rootDir + '/public'
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
"presets": [
["env", {
"targets": {
"browsers": ["last 2 versions", "> 5%"]
}
}]
]
}
}
},
{
test: /\.hbs/,
loader: "handlebars-loader",
query: {
partialDirs: [
path.join(rootDir, 'views', 'partials')
]
}
},
]
},
};
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* [description]
*
* @function Phaser.Geom.Polygon.Reverse
* @since 3.0.0
*
* @generic {Phaser.Geom.Polygon} O - [polygon,$return]
*
* @param {Phaser.Geom.Polygon} polygon - [description]
*
* @return {Phaser.Geom.Polygon} [description]
*/
var Reverse = function (polygon)
{
polygon.points.reverse();
return polygon;
};
module.exports = Reverse;
|
define("cool/controls/numberSlider",
[
"dojo/_base/declare",
"dojo/_base/lang",
"dojo/_base/array",
"cool/controls/_control",
"dijit/form/HorizontalSlider",
'dijit/_TemplatedMixin',
'dijit/_WidgetsInTemplateMixin',
"dojo/text!./templates/numberSlider.html"
], function(declare, lang, array, _control, Slider, _TemplatedMixin, _WidgetsInTemplateMixin, widgetTpl) {
return declare("cool.controls.numberSlider", [_control, _TemplatedMixin, _WidgetsInTemplateMixin], {
templateString: widgetTpl,
coolInit : function() {
this.inherited(arguments);
var self=this;
var min = this.getParameter('from') || 0;
var max = this.getParameter('to');
var field = new Slider({
minimum: min,
maximum: max,
intermediateChanges: true,
discreteValues: 1+max-min,
//style: "width:300px;",
onChange: function(value){
self.labeldiv.innerHTML = value;
self.emit("change", {});
}
}, this.sliderdiv);
this.own(field);
this.field = field;
if(this.isReadOnly()) {
field.set('readOnly', true);
this.disable();
}
if(this.definition.hasOwnProperty('value')) {
this.set('value', this.definition.value);
this.emit("valueInit", {});
}
},
_setValueAttr: function(value) {
if(isNaN(value)) {
this.field.set('value', null );
}
else this.field.set('value', value );
},
_getValueAttr: function() {
var ret = this.field.get('value');
return isNaN( ret ) ? null : ret;
}
});
}); |
define([
'jquery',
'underscore',
'global',
'backbone'
], function(
$,
_,
global,
Backbone
){
"use strict";
var SingleModel = Backbone.Model.extend({
MODEL_READY: 'model:ready',
initialize:function(){
_.bindAll(this,
'onFetchSuccess'
);
},
fetch : function() {
$.ajax({
type : "get",
dataType : "json",
url: window.location+'?json=get_single',
success: this.onFetchSuccess
});
},
onFetchSuccess: function(response){
this.setAttributes(response);
this.trigger(this.MODEL_READY);
},
setAttributes:function(response){
var result = response.post;
var slides = this.getSlides(result.acf);
var excerpt = this.getExcerpt(result.acf.copy);
var date = this.getDate(result.date);
this.set('id',result.id);
this.set('slug',result.slug);
this.set('url',result.url);
this.set('title',result.title);
this.set('slides',slides);
this.set('content',result.acf.copy);
this.set('excerpt',excerpt);
this.set('acf',result.acf);
this.set('attachments',result.attachments);
this.set('date',date);
this.set('categories',result.categories);
},
getSlides:function(results){
var embed = results.video;
var slides = _.map(results.gallery,this.getSlide,this);
if(embed !== ""){
var obj = {
'type':'video',
'embed':embed
};
slides.unshift(obj);
}
return slides;
},
getSlide:function(item){
var slide = {};
if(global.smart.tablet){
slide.url = item.gallery_image.sizes.large;
slide.height = item.gallery_image.sizes['large-height'];
slide.width = item.gallery_image.sizes['large-width'];
} else if(global.smart.phone){
slide.url = item.gallery_image.sizes.medium;
slide.height = item.gallery_image.sizes['medium-height'];
slide.width = item.gallery_image.sizes['medium-width'];
} else {
slide.url = item.gallery_image.url;
slide.height = item.gallery_image.height;
slide.width = item.gallery_image.width;
}
slide.type = 'image';
slide.caption = item.caption;
slide.description = item.description;
return slide;
},
getExcerpt:function(content){
var excerptLength = 240;
if(content.length > excerptLength){
content = content.substring(0,excerptLength) + "...";
}
return content;
},
getDate:function(results){
var date = results.split(' ');
date = date[0];
date = date.split('-');
date = [ parseInt(date[2], 10) , parseInt(date[1], 10) , date[0] ];
date = date.join('.');
return date;
}
});
return SingleModel;
}); |
import extend from 'tui-code-snippet/object/extend';
import forEach from 'tui-code-snippet/collection/forEach';
import style from '@/ui/template/style';
import standardTheme from '@/ui/theme/standard';
import { styleLoad } from '@/util';
import icon from '@svg/default.svg';
/**
* Theme manager
* @class
* @param {Object} customTheme - custom theme
* @ignore
*/
class Theme {
constructor(customTheme) {
this.styles = this._changeToObject(extend({}, standardTheme, customTheme));
styleLoad(this._styleMaker());
this._loadDefaultSvgIcon();
}
/**
* Get a Style cssText or StyleObject
* @param {string} type - style type
* @returns {string|object} - cssText or StyleObject
*/
// eslint-disable-next-line complexity
getStyle(type) {
let result = null;
const firstProperty = type.replace(/\..+$/, '');
const option = this.styles[type];
switch (type) {
case 'common.bi':
result = this.styles[type].image;
break;
case 'menu.icon':
result = {
active: this.styles[`${firstProperty}.activeIcon`],
normal: this.styles[`${firstProperty}.normalIcon`],
hover: this.styles[`${firstProperty}.hoverIcon`],
disabled: this.styles[`${firstProperty}.disabledIcon`],
};
break;
case 'submenu.icon':
result = {
active: this.styles[`${firstProperty}.activeIcon`],
normal: this.styles[`${firstProperty}.normalIcon`],
};
break;
case 'submenu.label':
result = {
active: this._makeCssText(this.styles[`${firstProperty}.activeLabel`]),
normal: this._makeCssText(this.styles[`${firstProperty}.normalLabel`]),
};
break;
case 'submenu.partition':
result = {
vertical: this._makeCssText(
extend({}, option, { borderLeft: `1px solid ${option.color}` })
),
horizontal: this._makeCssText(
extend({}, option, { borderBottom: `1px solid ${option.color}` })
),
};
break;
case 'range.disabledPointer':
case 'range.disabledBar':
case 'range.disabledSubbar':
case 'range.pointer':
case 'range.bar':
case 'range.subbar':
option.backgroundColor = option.color;
result = this._makeCssText(option);
break;
default:
result = this._makeCssText(option);
break;
}
return result;
}
/**
* Make css resource
* @returns {string} - serialized css text
* @private
*/
_styleMaker() {
const submenuLabelStyle = this.getStyle('submenu.label');
const submenuPartitionStyle = this.getStyle('submenu.partition');
return style({
subMenuLabelActive: submenuLabelStyle.active,
subMenuLabelNormal: submenuLabelStyle.normal,
submenuPartitionVertical: submenuPartitionStyle.vertical,
submenuPartitionHorizontal: submenuPartitionStyle.horizontal,
biSize: this.getStyle('common.bisize'),
subMenuRangeTitle: this.getStyle('range.title'),
submenuRangePointer: this.getStyle('range.pointer'),
submenuRangeBar: this.getStyle('range.bar'),
submenuRangeSubbar: this.getStyle('range.subbar'),
submenuDisabledRangePointer: this.getStyle('range.disabledPointer'),
submenuDisabledRangeBar: this.getStyle('range.disabledBar'),
submenuDisabledRangeSubbar: this.getStyle('range.disabledSubbar'),
submenuRangeValue: this.getStyle('range.value'),
submenuColorpickerTitle: this.getStyle('colorpicker.title'),
submenuColorpickerButton: this.getStyle('colorpicker.button'),
submenuCheckbox: this.getStyle('checkbox'),
menuIconSize: this.getStyle('menu.iconSize'),
submenuIconSize: this.getStyle('submenu.iconSize'),
menuIconStyle: this.getStyle('menu.icon'),
submenuIconStyle: this.getStyle('submenu.icon'),
});
}
/**
* Change to low dimensional object.
* @param {object} styleOptions - style object of user interface
* @returns {object} low level object for style apply
* @private
*/
_changeToObject(styleOptions) {
const styleObject = {};
forEach(styleOptions, (value, key) => {
const keyExplode = key.match(/^(.+)\.([a-z]+)$/i);
const [, property, subProperty] = keyExplode;
if (!styleObject[property]) {
styleObject[property] = {};
}
styleObject[property][subProperty] = value;
});
return styleObject;
}
/**
* Style object to Csstext serialize
* @param {object} styleObject - style object
* @returns {string} - css text string
* @private
*/
_makeCssText(styleObject) {
const converterStack = [];
forEach(styleObject, (value, key) => {
if (['backgroundImage'].indexOf(key) > -1 && value !== 'none') {
value = `url(${value})`;
}
converterStack.push(`${this._toUnderScore(key)}: ${value}`);
});
return converterStack.join(';');
}
/**
* Camel key string to Underscore string
* @param {string} targetString - change target
* @returns {string}
* @private
*/
_toUnderScore(targetString) {
return targetString.replace(/([A-Z])/g, ($0, $1) => `-${$1.toLowerCase()}`);
}
/**
* Load default svg icon
* @private
*/
_loadDefaultSvgIcon() {
if (!document.getElementById('tui-image-editor-svg-default-icons')) {
const parser = new DOMParser();
const encodedURI = icon.replace(/data:image\/svg\+xml;base64,/, '');
const dom = parser.parseFromString(atob(encodedURI), 'text/xml');
document.body.appendChild(dom.documentElement);
}
}
/**
* Make className for svg icon
* @param {string} iconType - normal' or 'active' or 'hover' or 'disabled
* @param {boolean} isSubmenu - submenu icon or not.
* @returns {string}
* @private
*/
_makeIconClassName(iconType, isSubmenu) {
const iconStyleInfo = isSubmenu ? this.getStyle('submenu.icon') : this.getStyle('menu.icon');
const { path, name } = iconStyleInfo[iconType];
return path && name ? iconType : `${iconType} use-default`;
}
/**
* Make svg use link path name
* @param {string} iconType - normal' or 'active' or 'hover' or 'disabled
* @param {boolean} isSubmenu - submenu icon or not.
* @returns {string}
* @private
*/
_makeSvgIconPrefix(iconType, isSubmenu) {
const iconStyleInfo = isSubmenu ? this.getStyle('submenu.icon') : this.getStyle('menu.icon');
const { path, name } = iconStyleInfo[iconType];
return path && name ? `${path}#${name}-` : '#';
}
/**
* Make svg use link path name
* @param {Array.<string>} useIconTypes - normal' or 'active' or 'hover' or 'disabled
* @param {string} menuName - menu name
* @param {boolean} isSubmenu - submenu icon or not.
* @returns {string}
* @private
*/
_makeSvgItem(useIconTypes, menuName, isSubmenu) {
return useIconTypes
.map((iconType) => {
const svgIconPrefix = this._makeSvgIconPrefix(iconType, isSubmenu);
const iconName = this._toUnderScore(menuName);
const svgIconClassName = this._makeIconClassName(iconType, isSubmenu);
return `<use xlink:href="${svgIconPrefix}ic-${iconName}" class="${svgIconClassName}"/>`;
})
.join('');
}
/**
* Make svg icon set
* @param {Array.<string>} useIconTypes - normal' or 'active' or 'hover' or 'disabled
* @param {string} menuName - menu name
* @param {boolean} isSubmenu - submenu icon or not.
* @returns {string}
*/
makeMenSvgIconSet(useIconTypes, menuName, isSubmenu = false) {
return `<svg class="svg_ic-${isSubmenu ? 'submenu' : 'menu'}">${this._makeSvgItem(
useIconTypes,
menuName,
isSubmenu
)}</svg>`;
}
}
export default Theme;
|
var zom = require('./zomato-data');
exports.webhookRoutes = function(router){
router.get('/get-zomato-data', zom.getData);
}; |
import { combineReducers } from 'redux';
import { titleReducer } from 'redux-title'
import todos from './todos';
import visibilityFilter from './visibilityFilter';
import counter from './counter';
import intl from './intl';
import navigation from './navigation';
import filterNav from './filterNav';
import appStyle from './appStyle';
import dashboard from './dashboard';
import auth from './auth';
import user from './user';
import signIn from './signIn';
import todoDialog from './todoDialog';
import {usersByPage, selectedUsersPage, usersQuery } from './gitUsers';
import {selectedReposPage, reposByPage, reposQuery } from './repos';
import { routerReducer } from 'react-router-redux';
import {responsiveStateReducer} from 'redux-responsive';
const reducers = combineReducers({
todos,
title: titleReducer,
visibilityFilter,
counter,
browser: responsiveStateReducer,
intl,
navigation,
filterNav,
appStyle,
todoDialog,
dashboard,
usersByPage,
selectedUsersPage,
usersQuery,
selectedReposPage,
reposByPage,
reposQuery,
auth,
user,
signIn,
routing: routerReducer,
})
export default reducers;
|
/**
* Module dependencies.
*/
var request = require('superagent');
var jquery = require('cheerio').load;
/**
* Expose `parse`.
*/
module.exports = parse;
/**
* Parse wiki `url` and invoke `fn(err, pkgs)`.
*
* @param {String} url
* @param {Function} fn
* @api public
*/
function parse(url, fn) {
request
.get(url)
.end(function(err, res){
if (err) return fn(err);
if (res.error) return fn(res.error);
var $ = jquery(res.text);
var data = {};
var cat;
$('#wiki-body h2, #wiki-body h2 + ul li').each(function(){
var name = this[0].name;
// heading
if ('h' == name[0]) {
var text = $(this).text().trim();
cat = data[text] = [];
return;
}
// package
var tuple = $(this).text().split(':');
var name = tuple[0].trim();
var abbrs = tuple[1].split(',').map(function(abbr){return abbr.trim();});
cat.push({
name: name,
abbrs: abbrs
});
});
fn(null, data);
});
}
|
/**
* @license Highstock JS v8.1.2 (2020-06-16)
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Sebastian Bochan
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/ema', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'indicators/ema.src.js', [_modules['parts/Utilities.js']], function (U) {
/* *
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var correctFloat = U.correctFloat,
isArray = U.isArray,
seriesType = U.seriesType;
/**
* The EMA series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.ema
*
* @augments Highcharts.Series
*/
seriesType('ema', 'sma',
/**
* Exponential moving average indicator (EMA). This series requires the
* `linkedTo` option to be set.
*
* @sample stock/indicators/ema
* Exponential moving average indicator
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/ema
* @optionparent plotOptions.ema
*/
{
params: {
/**
* The point index which indicator calculations will base. For
* example using OHLC data, index=2 means the indicator will be
* calculated using Low values.
*
* By default index value used to be set to 0. Since Highstock 7
* by default index is set to 3 which means that the ema
* indicator will be calculated using Close values.
*/
index: 3,
period: 9 // @merge 14 in v6.2
}
},
/**
* @lends Highcharts.Series#
*/
{
accumulatePeriodPoints: function (period, index, yVal) {
var sum = 0,
i = 0,
y = 0;
while (i < period) {
y = index < 0 ? yVal[i] : yVal[i][index];
sum = sum + y;
i++;
}
return sum;
},
calculateEma: function (xVal, yVal, i, EMApercent, calEMA, index, SMA) {
var x = xVal[i - 1],
yValue = index < 0 ?
yVal[i - 1] :
yVal[i - 1][index],
y;
y = typeof calEMA === 'undefined' ?
SMA : correctFloat((yValue * EMApercent) +
(calEMA * (1 - EMApercent)));
return [x, y];
},
getValues: function (series, params) {
var period = params.period,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
EMApercent = 2 / (period + 1),
sum = 0,
EMA = [],
xData = [],
yData = [],
index = -1,
SMA = 0,
calEMA,
EMAPoint,
i;
// Check period, if bigger than points length, skip
if (yValLen < period) {
return;
}
// Switch index for OHLC / Candlestick / Arearange
if (isArray(yVal[0])) {
index = params.index ? params.index : 0;
}
// Accumulate first N-points
sum = this.accumulatePeriodPoints(period, index, yVal);
// first point
SMA = sum / period;
// Calculate value one-by-one for each period in visible data
for (i = period; i < yValLen + 1; i++) {
EMAPoint = this.calculateEma(xVal, yVal, i, EMApercent, calEMA, index, SMA);
EMA.push(EMAPoint);
xData.push(EMAPoint[0]);
yData.push(EMAPoint[1]);
calEMA = EMAPoint[1];
}
return {
values: EMA,
xData: xData,
yData: yData
};
}
});
/**
* A `EMA` series. If the [type](#series.ema.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.ema
* @since 6.0.0
* @product highstock
* @excluding dataParser, dataURL
* @requires stock/indicators/indicators
* @requires stock/indicators/ema
* @apioption series.ema
*/
''; // adds doclet above to the transpiled file
});
_registerModule(_modules, 'masters/indicators/ema.src.js', [], function () {
});
})); |
var
http = require('http'),
fs = require('fs');
http.createServer(function(req, res){
fs.readFile(__dirname + '/public/hello.txt', 'utf-8', function (err, data){
if(err){
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end(fileContents);
return;
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data);
});
}).listen(3000);
console.log('Server running at localhost:3000');
|
'use strict';
// @ngInject
let MapImageService = function($http) {
let self = this;
this.archive = 'https://api.npolar.no/map/archive';
this.base = 'https://api.npolar.no/map/archive-jpeg';
this.basename = function(filename) {
return filename.split(/\..*$/)[0];
};
this.filename = function(uri) {
let p = uri.split('/');
return p[p.length-1];
};
this.all_files_uri = (map, quality='high') => {
if (!map) {
return;
}
let file_endpoint = self.archive;
if (quality === 'web' || quality == 'preview') {
file_endpoint = self.base;
}
return `${file_endpoint}/${ map.id }/_file/_all?filename=${ encodeURIComponent(map.title.split(' ').join('_'))+'_'+map.publication.year||'' }&format=zip`;
}
this.mm = function(pixels, ppi) {
if (!pixels || !ppi) {
return;
}
return Math.round(25.4*pixels/ppi, 0);
};
// $scope.images = map.files.filter(f => (/^image\//).test(f.type));
this._image = function(image, map, suffix='-512px', format='jpeg', base=self.base) {
if (image && image.filename && map && map.id) {
let filename = image.filename.split(' ').join('_');
return `${base}/${map.id}/_file/${self.basename(filename)}${suffix}.${format}`;
}
};
this._imageInLink = function(uri, size='medium', extension='jpg') {
//console.log(uri, size, extension);
let path;
if (/https?:\/\/api\.npolar\.no/.test(uri)) {
let parts = uri.split("//")[1].split('/');
// ["api.npolar.no", "map", "archive", "14fb353a-5828-51cd-980e-5859343ff124", "_file", "11344", "Gronland_foreign_65.TIF"]
let filename = parts.pop().split(".")[0]; // "Gronland_foreign_65"
let ident = parts[parts.length-1]; // "11344"
path = "https://data.npolar.no/_file/map/archive/open/legacy/"+ident+"/"+size+"/"+filename+"."+extension;
} else if (/(open|restricted)/.test(uri)) {
let p;
p = uri.split(/(open|restricted)/).slice(-2); // ["open", "/2015/2015-05-21/Bouvetøya_1986.tif"]
extension = (extension === 'jpg') ? 'jpeg' : extension;
p[1] = p[1].replace(/\.tif(f)?$/i, `-${size}.${extension}`);
path = `${this.base}/${p[0]}/${this.previewFormat}${p[1]}`;
}
//console.log('path', path);
return path;
};
this.jpeg = function(image, map, suffix='') {
//console.log(image);
//console.debug(map);
if (image && map && map.files && map.files.length > 0) {
return self._image(image, map, suffix, 'jpeg');
} else if (map && map.links && map.links.length > 0) {
let link = map.links[0];
return self._imageInLink(link.href);
}
};
this.icon = function(image, map) {
if (image || map) {
return self.jpeg(image,map,'-512px');
}
};
//this.ikon = function(map) {
// let image = map.files.find(f => f.type === 'image/png');
// console.log(image);
//};
this.medium = function(image, map) {
return self.jpeg(image,map,'-3000px');
};
this.large = function(image, map) {
return self.jpeg(image,map,'-3000px');
};
this.title = function(map) {
if (map && map.title) {
let title = map.title;
if (map.preamble) {
title = `(${map.preamble}) ${title}`;
}
/*if (map.subtitle) {
title += ': '+map.subtitle;
}*/
if (map.publication && map.publication.year) {
title += ` (${map.publication.year})`;
} else {
title += ` (unkown year)`;
}
return title;
}
};
// image metadata <- fileFunnel file metadata
this.imageFromFile = function(file) {
//console.log(file);
return {
uri: file.url,
filename: file.filename,
length: file.file_size,
type: file.content_type
};
};
//
//File should be object with keys filename, url, [file_size, icon, extras].
this.fileFromImage = function(image) {
//console.log(image);
let f = {
url: image.uri,
filename: image.filename,
//icon: self.icon({id: "x"}, image),
file_size: image.length,
//md5sum: (image.hash||'md5:').split('md5:')[1],
content_type: image.type
};
console.log(f);
return f;
};
return this;
};
module.exports = MapImageService;
|
var pkg = require('../package'),
schema = require('../settings-schema'),
properties = schema.properties,
markdown = [],
fs = require('fs');
function setDefault(setting) {
let settingDefault = '**default:** ';
if (setting.default === undefined && !setting.defaultObject) {
settingDefault = settingDefault + 'none';
} else if (setting.type === 'string') {
settingDefault = settingDefault + '`"' + setting.default + '"`';
} else if (['number', 'boolean'].indexOf(setting.type) > -1) {
settingDefault = settingDefault + '`' + setting.default + '`';
} else {
settingDefault = settingDefault +
'\n\`\`\`\n' +
JSON.stringify(setting.defaultObject, null, 2) +
`\n\`\`\``;
}
if (setting.type !== 'object')
return settingDefault;
}
/*------------------------------------------------------------------------------------------------\
Overview
\------------------------------------------------------------------------------------------------*/
if (schema.overview)
schema.overview
.split('\n')
.forEach(paragraph => {
markdown.push(paragraph);
markdown.push('');
});
/*------------------------------------------------------------------------------------------------\
Renderer-specific settings
\------------------------------------------------------------------------------------------------*/
markdown.push(`# Renderer-specific settings`);
markdown.push(`The sections below describe each ${pkg.name} setting as of version ${schema.version}.`);
markdown.push(``);
var keys = Object.keys(properties);
keys.forEach((property,i) => {
var setting = properties[property];
markdown.push(`## settings.${property}`);
markdown.push(`\`${setting.type}\``);
markdown.push(``);
markdown.push(`${setting.description}`);
if (setting.type !== 'object') {
markdown.push(``);
markdown.push(setDefault(setting));
} else {
var subKeys = Object.keys(setting.properties);
subKeys.forEach((subProperty,i) => {
var subSetting = setting.properties[subProperty];
markdown.push(``);
markdown.push(`### settings.${property}.${subProperty}`);
markdown.push(`\`${subSetting.type}\``);
markdown.push(``);
markdown.push(`${subSetting.title}`);
markdown.push(``);
markdown.push(setDefault(subSetting));
});
}
if (setting.type === 'array' && setting.items.type === 'object') {
var subKeys = Object.keys(setting.items.properties);
subKeys.forEach((subProperty,i) => {
var subSetting = setting.items.properties[subProperty];
markdown.push(``);
markdown.push(`### settings.${property}[].${subProperty}`);
markdown.push(`\`${subSetting.type}\``);
markdown.push(``);
markdown.push(`${subSetting.title}`);
markdown.push(``);
markdown.push(setDefault(subSetting));
});
}
if (i < keys.length - 1) {
markdown.push(``);
markdown.push(``);
markdown.push(``);
}
});
/*------------------------------------------------------------------------------------------------\
Configuration markdown
\------------------------------------------------------------------------------------------------*/
fs.writeFile(
'./scripts/configuration.md',
markdown.join('\n'),
(err) => {
if (err)
console.log(err);
console.log('The configuration markdown file was built!');
});
|
'use strict';
function Customers (stripe) {
this.addSources = (identity, customer) => {
const cards = stripe.store.findCards(identity, {
customer: customer.id,
id: customer.default_source,
}).sort((a, b) => {
if (a.id === customer.default_source) {
return -1;
} else if (b.id === customer.default_source) {
return 1;
}
return 0;
});
customer.sources = stripe.model.list({
items: cards,
url: `/v1/customers/${ customer.id }/sources`,
});
return customer;
};
this.addSubscriptions = (identity, customer) => {
let subscriptions = stripe.store.findSubscriptions(identity, { customer: customer.id });
subscriptions = subscriptions.map((subscription) => {
subscription = stripe.subscriptions.populateSubscription(identity, subscription);
return subscription;
});
customer.subscriptions = stripe.model.list({
items: subscriptions,
url: `/v1/customers/${ customer.id }/subscriptions`,
});
return customer;
};
this.addDiscount = (identity, customer) => {
let discount = stripe.store.getDiscount(identity, customer.id);
if (discount) {
discount = stripe.util.clone(discount);
discount.coupon = stripe.store.getCoupon(identity, discount.coupon);
customer.discount = discount;
}
return customer;
};
this.createCustomer = (req, res, next) => {
const context = stripe.model.context(req, res, next);
const tokenId = req.body.source || req.body.card;
let token;
let card;
if (tokenId) {
token = stripe.store.getToken(context.identity, tokenId);
if (!token) {
return stripe.errors.invalidRequestError({
statusCode: 404,
message: `Error: token ${ tokenId } not found`,
param: 'card',
context,
});
}
card = stripe.store.getCard(context.identity, token.card);
if (!card) {
return stripe.errors.invalidRequestError({
statusCode: 404,
message: `Error: card ${ token.card } not found`,
param: 'card',
context,
});
}
}
const customer = stripe.model.customer({
context,
token,
card,
description: req.body.description,
email: req.body.email,
metadata: req.body.metadata,
shipping: req.body.shipping,
});
stripe.model.event({
context,
type: 'customer.created',
object: customer,
});
if (card) {
token.used = true;
stripe.store.updateToken(context.identity, token.id, token);
card.customer = customer.id;
stripe.store.updateCard(context.identity, card.id, card);
stripe.model.event({
context,
type: 'customer.source.created',
object: card,
});
}
const response = stripe.util.clone(customer);
this.addSources(context.identity, response);
this.addSubscriptions(context.identity, response);
this.addDiscount(context.identity, response);
context.send(200, response);
return next();
};
this.retrieveCustomer = (req, res, next) => {
const context = stripe.model.context(req, res, next);
const customer = stripe.store.getCustomer(context.identity, req.params.customer);
if (!customer) {
return stripe.errors.invalidRequestError({
statusCode: 400,
message: `Error: no such customer ${ req.params.customer }`,
param: 'customer',
context,
});
}
const response = stripe.util.clone(customer);
this.addSources(context.identity, response);
this.addSubscriptions(context.identity, response);
this.addDiscount(context.identity, response);
context.send(200, response);
return next();
};
this.updateCustomer = (req, res, next) => {
const context = stripe.model.context(req, res, next);
const tokenId = req.body.source || req.body.card;
let token;
let card;
if (tokenId) {
delete req.body.source;
delete req.body.card;
token = stripe.store.getToken(context.identity, tokenId);
if (!token) {
return stripe.errors.invalidRequestError({
statusCode: 404,
message: `Error: token ${ tokenId } not found`,
param: 'card',
context,
});
}
card = stripe.store.getCard(context.identity, token.card);
if (!card) {
return stripe.errors.invalidRequestError({
statusCode: 404,
message: `Error: card ${ token.card } not found`,
param: 'card',
context,
});
}
}
let customer = stripe.store.getCustomer(context.identity, req.params.customer);
if (!customer) {
return stripe.errors.invalidRequestError({
statusCode: 400,
message: `Error: no such customer ${ req.params.customer }`,
param: 'customer',
context,
});
}
if (card) {
token.used = true;
stripe.store.updateToken(context.identity, token.id, token);
card.customer = customer.id;
stripe.store.updateCard(context.identity, card.id, card);
stripe.model.event({
context,
type: 'customer.source.created',
object: card,
});
req.body.default_source = card.id;
}
const fields = [
'account_balance', 'business_vat_id', 'default_source',
'description', 'email', 'metadata', 'shipping',
];
const [ update, previous ] = stripe.util.createUpdateObject(fields, customer, req.body);
customer = stripe.store.updateCustomer(context.identity, req.params.customer, update);
stripe.model.event({
context,
type: 'customer.updated',
object: customer,
previous,
});
const response = stripe.util.clone(customer);
this.addSources(context.identity, response);
this.addSubscriptions(context.identity, response);
this.addDiscount(context.identity, response);
context.send(200, response);
return next();
};
this.deleteCustomer = (req, res, next) => {
const context = stripe.model.context(req, res, next);
let customer = stripe.store.getCustomer(context.identity, req.params.customer);
if (!customer) {
return stripe.errors.invalidRequestError({
statusCode: 400,
message: `Error: no such customer ${ req.params.customer }`,
param: 'customer',
context,
});
}
customer = stripe.store.deleteCustomer(context.identity, req.params.customer);
stripe.model.event({
context,
type: 'customer.deleted',
object: customer,
});
const response = {
deleted: true,
id: req.params.customer,
};
context.send(200, response);
return next();
};
this.listAllCustomers = (req, res, next) => {
const context = stripe.model.context(req, res, next);
const customers = stripe.store.getCustomers(context.identity);
const results = stripe.model.list({
items: customers,
url: '/v1/customers',
paginate: true,
query: req.query,
});
context.send(200, results);
return next();
};
////////////////////
stripe.server.post('/v1/customers', stripe.auth.requireAdmin, this.createCustomer);
stripe.server.get('/v1/customers/:customer', this.retrieveCustomer);
stripe.server.post('/v1/customers/:customer', stripe.auth.requireAdmin, this.updateCustomer);
stripe.server.del('/v1/customers/:customer', stripe.auth.requireAdmin, this.deleteCustomer);
stripe.server.get('/v1/customers', this.listAllCustomers);
////////////////////
}
module.exports = (stripe) => new Customers(stripe);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.