code
stringlengths 2
1.05M
|
---|
'use strict';
/**
* Module dependencies.
*/
var init = require('./config/init')(),
config = require('./config/config'),
mongoose = require('mongoose'),
chalk = require('chalk');
/**
* Main application entry file.
* Please note that the order of loading is important.
*/
// Bootstrap db connection
var db = mongoose.connect(config.db, function(err) {
if (err) {
console.error(chalk.red('Could not connect to MongoDB!'));
console.log(chalk.red(err));
}
});
// Init the express application
var app = require('./config/express')(db);
// Bootstrap passport config
require('./config/passport')();
// Start the app by listening on <port>
app.listen(config.port);
// Expose app
exports = module.exports = app;
// Logging initialization
console.log('MEAN.JS application started on port ' + config.port);
// Twilio SMS Notification
/*
var accountSid = 'AC35bcc6b076419c037a465463ea23f942',
authToken = '1dcfaa7d4151e6774dbf6ea6fb2faba4',
client = require('twilio')(accountSid, authToken);
function checkReminders () {
var promise = client.messages.create({
to: '+19194413402', // a number to call
from: '+19196705363', // a Twilio number you own
body: 'test click'
});
promise.then(function (call) {
console.log('Call success! Call SID: ' + call.sid);
}, function (error) {
console.error('Call failed! Reasons: ' + error.message);
});
}
*/
|
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, ltsvlogger = require('../index.js')
, http = require('http')
, fs = require('fs')
, path = require('path');
// select tokens
var ltsv = [];
ltsv.push("time");
ltsv.push("host");
ltsv.push("X-Forwarded-For");
ltsv.push("user");
ltsv.push("ident");
ltsv.push("req");
ltsv.push("method");
ltsv.push("uri");
ltsv.push("protocol");
ltsv.push("status");
ltsv.push("size");
ltsv.push("reqsize");
ltsv.push("referer");
ltsv.push("ua");
ltsv.push("vhost");
ltsv.push("reqtime");
ltsv.push("X-Cache");
ltsv.push("X-Runtime");
ltsv.push("hoge"); //will be ignored
var out = fs.createWriteStream("./example/log/access.log",{flags: 'a+'});
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(ltsvlogger({format:ltsv,stream:out}));
// app.use(ltsvlogger()); //use default format
// app.use(ltsvlogger("default")); //use default format
// app.use(ltsvlogger("tiny")); //use tiny format
// app.use(ltsvlogger("short")); //use short format
// app.use(ltsvlogger({format:"short"})); //use short format
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
|
var gulp = require('gulp'),
merge = require('merge-stream'),
htmlreplace = require('gulp-html-replace'),
minifyHTML = require('gulp-minify-html')
;
var conf = require('../conf').conf;
var js_all = require('../conf').js_all;
var js_vendor = require('../conf').js_vendor;
var css_file_min = require('../conf').css_file_min;
gulp.task('copy', function () {
var opts = {
conditionals: true,
spare:true
};
var html = gulp.src('*.html', { cwd: conf.app_cwd })
.pipe(htmlreplace({
js: {
src: [['js/'+js_all, 'lib/'+js_vendor]],
tpl: '<script data-main="%s" src="%s"></script>'
},
css: ['css/'+css_file_min]
}))
.pipe(minifyHTML(opts))
.pipe(gulp.dest(conf.dest));
var fonts = gulp.src('css/fonts/*', { cwd: conf.app_cwd })
.pipe(gulp.dest(conf.dest+'css/fonts'));
var favicon = gulp.src('favicon.ico', { cwd: conf.app_cwd })
.pipe(gulp.dest(conf.dest));
var img = gulp.src('img/*', { cwd: conf.app_cwd })
.pipe(gulp.dest(conf.dest+'img'));
var css_img = gulp.src(['css/images/*'], { cwd: conf.app_cwd })
.pipe(gulp.dest(conf.dest+'css/images'));
var data = gulp.src('data/*', { cwd: conf.app_cwd })
.pipe(gulp.dest(conf.dest+'data'));
return merge(html, fonts, favicon, img, css_img, data);
});
|
/*eslint-disable no-var*/
/**
* Generates a template when compiled with HtmlWebpackPlugin.
*
* The template will include:
* - The title
* - An optional meta description
* - An optional meta keywords
* - Any links to css files
* - An optional react root id
* - An optional isomorphic template in the react root id to use server side rendering
* - Any javascript file chunks
* - An optional google analytics script
*/
module.exports = function(templateParams) {
var htmlWebpackPlugin = templateParams.htmlWebpackPlugin;
var options = htmlWebpackPlugin.options;
var meta = '<meta charset="utf-8">'
+ '<meta http-equiv="X-UA-Compatible" content="IE=edge">'
+ '<meta name="viewport" content="width=device-width, initial-scale=1">';
if(options.description) {
meta += '<meta name="description" content="' + options.description + '">';
}
if(options.keywords) {
meta += '<meta name="keywords" content="' + options.keywords + '">';
}
var css = htmlWebpackPlugin.files.css.map(function(href) {
return '<link href="' + href + '" rel="stylesheet">';
}).join('');
var title = '<title>' + options.title + '</title>';
var head = '<head>' + meta + title + css + '</head>';
var entry = '';
if(options.appMountId) {
entry = '<div id="' + options.appMountId + '">';
if(options.isomorphic) {
entry += '<div><%- ' + options.isomorphic + ' %></div>';
}
entry += '</div>';
}
var js = htmlWebpackPlugin.files.js.map(function(chunk) {
return '<script src="' + chunk + '"></script>';
}).join('');
if(options.googleAnalytics) {
js = js
+ "<script>"
+ "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){"
+ "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),"
+ "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)"
+ "})(window,document,'script','//www.google-analytics.com/analytics.js','ga');"
+ "ga('create', '" + options.googleAnalytics + "', 'auto');"
+ "ga('send', 'pageview');"
+ "</script>";
}
var body = '<body>' + entry + js + '</body>';
return '<!DOCTYPE html><html>' + head + body + '</html>';
};
|
// declare namespace object
var content = {};
// declare and initialize text prototype object
content.text = {
// how many text instances have been created
count: 0,
// index number
index: null,
// text content
string: null,
// jquery reference to page element
element: null,
// define new text instance (content and index)
define: function() {
},
// place text instance in document
place: function() {
},
// change content of text instance
change: function() {
}
}
|
// In-Class Group assignment
// there are a couple of assignments listed in comments below
var app = {};
app.TodoModel = Backbone.Model.extend({});
app.TodosCollection = Backbone.Collection.extend({
model: app.TodoModel,
comparator: 'cid'
});
app.todosCollection = new app.TodosCollection();
app.todosCollection.add([
{ title: 'mow the lawn',
description: 'fill the gasoline tank, start the engine, cut all the grass, bag grass'},
{ title: 'paint the house',
description: 'paint all the things'},
{ title: 'fix the leaky bathtub faucet',
description: 'get the seat wrench, turn off water main, unscrew things, get new parts'}
]);
app.TodoMainView = Backbone.View.extend({
el: '#my-app',
template: '<h1><i class="fa fa-check-square-o"></i> Todos</h1>' +
'<form class="pure-form pure-form-stacked" id="todo-form">' +
'<fieldset>' +
'<div class="pure-control-group">' +
'<label for="todo-input">Todo Title</label>' +
'<input id="todo-input" class="form-control" type="text">' +
'</div>' +
'<div class="pure-control-group">' +
'<label for="description-input">Todo Description</label>' +
'<input id="description-input" class="form-control" type="text">' +
'</div>' +
'<div class="pure-controls">' +
'<button id="add-todo" class="pure-button">Add todo</button>' +
'</div>' +
'</fieldset>' +
'</form>' +
'<br><br>' +
'<h3>My Todos</h3>' +
'<ol id="todo-list">' +
'</ol>',
render: function () {
console.log('main view render function started');
// ASSIGNMENT: look in Backbone docs and find out what $el is.
// describe this in your own words. have a representative from your group share
// what this is.
// ANSWER: this.$el is a cached, jQuery wrapped version of the el property
// from your Backbone view
// FOLLOW-UP-QUESTION: What is the advantage of $el
// ANSWER: it is already cached, so we don't have to query the dom for
// that element
this.$el.html(this.template);
// QUESTION: Why are we able to usee this.collection to reference
// the collection we need? Where is this made possible?
// Have a representative from your group write down and share this answer
// with the class.
// ANSWER: from this line at the bottom of this file:
// app.todoMainView = new app.TodoMainView({collection: app.todosCollection});
app.todoInputView = new app.TodoInputView({collection: this.collection});
app.todoListView = new app.TodoListView({collection: this.collection});
app.todoListView.render();
}
});
app.TodoInputView = Backbone.View.extend({
el: '#todo-form',
events: {
'click #add-todo': 'addTodo'
},
addTodo: function (event) {
event.preventDefault();
var $todoInput = $(this.el).find('#todo-input');
var $description = $(this.el).find('#description-input');
console.log('button was clicked');
var todoInput = $todoInput.val();
var descriptionInput = $description.val();
this.collection.add({title: todoInput, description: descriptionInput});
$description.val('');
$todoInput.val('');
}
});
app.TodoListView = Backbone.View.extend({
el: '#todo-list',
initialize: function () {
this.collection.on('add', this.render, this);
},
render: function () {
var outputHtml = '';
this.collection.models.forEach(function (item) {
outputHtml += '<li><strong>' + item.get('title') + ': </strong>' +
item.get('description') + '</li>';
});
$(this.el).html(outputHtml);
}
});
$(function () {
app.todoMainView = new app.TodoMainView({collection: app.todosCollection});
app.todoMainView.render();
});
|
export function clamp(num, min, max) {
return Math.max(min, Math.min(max, num));
}
export function maybe(cond, value) {
if (!cond) return '';
return (typeof value === 'function') ? value() : value;
}
export function range(start, stop, step) {
let count = 0, old = start;
let initial = n => (n > 0 && n < 1) ? .1 : 1;
let length = arguments.length;
if (length == 1) [start, stop] = [initial(start), start];
if (length < 3) step = initial(start);
let range = [];
while ((step >= 0 && start <= stop)
|| (step < 0 && start > stop)) {
range.push(start);
start += step;
if (count++ >= 1000) break;
}
if (!range.length) range.push(old);
return range;
}
export function alias_for(obj, names) {
Object.keys(names).forEach(n => {
obj[n] = obj[names[n]];
});
return obj;
}
export function is_letter(c) {
return /^[a-zA-Z]$/.test(c);
}
export function is_nil(s) {
return s === undefined || s === null;
}
export function is_empty(value) {
return is_nil(value) || value === '';
}
export function lazy(fn) {
let wrap = () => fn;
wrap.lazy = true;
return wrap;
}
export function sequence(count, fn) {
let [x, y = 1] = String(count).split('x');
x = clamp(parseInt(x) || 1, 1, 65536);
y = clamp(parseInt(y) || 1, 1, 65536);
let max = x * y;
let ret = [];
let index = 1;
for (let i = 1; i <= y; ++i) {
for (let j = 1; j <= x; ++j) {
ret.push(fn(index++, j, i, max));
}
}
return ret;
}
export function cell_id(x, y, z) {
return 'c-' + x + '-' + y + '-' + z;
}
export function get_value(input) {
while (input && input.value) {
return get_value(input.value);
}
return is_nil(input) ? '' : input;
}
export function normalize_png_name(name) {
let prefix = is_nil(name)
? Date.now()
: String(name).replace(/\/.png$/g, '');
return prefix + '.png';
}
export function cache_image(src, fn, delay = 0) {
let img = new Image();
img.crossOrigin = 'anonymous';
img.src = src;
img.onload = function() {
setTimeout(fn, delay);
}
}
export function is_safari() {
return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
}
export function un_entity(code) {
let textarea = document.createElement('textarea');
textarea.innerHTML = code;
return textarea.value;
}
export function hash(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
let code = str.charCodeAt(i);
hash = ((hash << 5) - hash) + code;
hash &= hash;
}
return hash;
}
export function make_tag_function(fn) {
let get_value = v => is_nil(v) ? '' : v;
return (input, ...vars) => {
let string = input.reduce((s, c, i) => s + c + get_value(vars[i]), '');
return fn(string);
};
}
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
info: >
Step 4 of defineProperty calls the [[DefineOwnProperty]] internal method
of O to define the property. For configurable properties, step 9c of
[[DefineOwnProperty]] permits changing the kind of a property.
es5id: 15.2.3.6-4-15
description: >
Object.defineProperty permits changing accessor property to data
property for configurable properties
includes: [runTestCase.js]
---*/
function testcase() {
var o = {};
// define an accessor property
// dummy getter
var getter = function () { return 1; }
var d1 = { get: getter, configurable: true };
Object.defineProperty(o, "foo", d1);
// changing "foo" to be a data valued property should succeed, since
// [[Configurable]] on the original property will be true. Existing
// values of [[Configurable]] and [[Enumerable]] need to be preserved
// and the rest need to be set to their default values.
var desc = { value: 101 };
Object.defineProperty(o, "foo", desc);
var d2 = Object.getOwnPropertyDescriptor(o, "foo");
if (d2.value === 101 &&
d2.writable === false &&
d2.enumerable === false &&
d2.configurable === true) {
return true;
}
}
runTestCase(testcase);
|
import serifPreview from './class/serif_preview_class.js';
export default option => {
// セリフフォームを取得
const $serifList = document.querySelectorAll("tr.LG");
$serifList.forEach($tr => {
const $parent = $tr.querySelector('td');
const preview = new serifPreview($parent, option);
let $table = document.createElement('table');
$table.appendChild(preview.$previewToggle);
$table.appendChild(preview.$previewBlock);
$parent.appendChild($table);
});
}
|
/**
* Created by lonso on 14-11-13.
* liusc@polyvi.com
*/
'use strict';
var Promise = require('bluebird');
var crypto = require('crypto');
var util = require('../utils/util.js');
var md5 = function (val) {
return new Promise(function (resolve, reject) {
resolve(crypto.createHash('md5').update((val).toString(), 'UTF-8').digest('hex'))
})
};
var type = ['unicast', 'broadcast', 'groupcast', 'customizedcast', 'filecast'];
module.exports = Umeng;
var options = {
uri: 'http://msg.umeng.com/api/send',
method: 'POST'
};
function Umeng(appInfo) {
if (!(this instanceof Umeng)) return new Umeng(appInfo);
if (!appInfo.appKey || !appInfo.app_master_secret || !appInfo.ios_appKey || !appInfo.ios_app_master_secret)
return new Error('appKey and masterSecret need');
this.appKey = appInfo.appKey;
this.app_master_secret = appInfo.app_master_secret;
this.ios_appKey = appInfo.ios_appKey;
this.ios_app_master_secret = appInfo.ios_app_master_secret;
return this;
}
Umeng.prototype.init = function (args) {
var that = this;
var message = {};
that.message = message;
return new Promise(function (resolve, reject) {
if (!~type.indexOf(args.type)) return reject(new Error('type error'));
var masterSecret = args.app_master_secret || that.app_master_secret;
args.after_open = args.after_open || "go_app";
message.appKey = args.appKey || that.appKey;
message.timestamp = new Date().getTime();
message.type = args.type || 'broadcast';
message.device_tokens = args.device_tokens || '';
message.alias = args.alias || '';
message.alias_type = args.alias_type || '';
message.file_id = args.file_id || '';
message.filter = args.filter || '';
that.message.policy = args.policy || {};
args.production_mode && (that.message.production_mode = args.production_mode);
that.message.description = args.description || '';
args.thirdparty_id && (that.message.thirdparty_id = args.thirdparty_id);
md5(message.appKey.toLowerCase() + masterSecret.toLowerCase() + message.timestamp).then(function (md5V) {
message.validation_token = md5V;
resolve(message);
}).catch(function (e) {
reject(e)
})
})
};
/**
* body 格式
* {
ticker: args.ticker,
title: args.title,
text: args.content,
builder_id: args.builder_id || 0,
icon: args.icon || '',
largeIcon: args.largeIcon || '',
img: args.img || '',
play_vibrate: args.play_vibrate || true,
play_lights: args.play_lights|| true,
play_sound: args.play_sound || true,
sound: args.sound || '',
after_open: args.after_open || 'go_app',
url: args.url || '',
activity: args.activity || '',
custom: args.custom
}
* @param args
* @param cb
* @returns {Promise}
*/
Umeng.prototype.androidPush = function (args) {
var that = this;
return new Promise(function (resolve, reject) {
if (!args.body.title || !args.body.text || !args.body.ticker)
return reject(new Error('title, content, ticker must need'));
that.init(args).then(function (message) {
message.payload = {
display_type: args.display_type || "notification",
body: args.body,
extra: args.extra || ''
};
options.json = message;
return util.requestHelper(options);
}).then(function (data) {
resolve(data)
}).catch(function (e) {
reject(e);
});
})
};
/**
* ios push
* payload 格式:
* payload: {
body: {
aps: {
alert: 'test alert notification'
},
custom: {
type: 1
}
}
}
* @param args
* @returns {Promise}
*/
Umeng.prototype.iosPush = function (args) {
var that = this;
args.appKey = that.ios_appKey;
args.app_master_secret =that.ios_app_master_secret;
return new Promise(function (resolve, reject) {
if (!args.payload.body.aps.alert)
return reject(new Error('alert must need'));
that.init(args).then(function (message) {
message.payload = args.payload.body;
options.json = message;
return util.requestHelper(options);
}).then(function (data) {
resolve(data)
}).catch(function (e) {
reject(e);
});
})
};
Umeng.prototype.getStatus = function (args) {
var statusOptions = {
uri: 'http://msg.umeng.com/api/status',
method: 'POST'
};
statusOptions.json = args;
statusOptions.json.appKey = this.appKey;
return util.requestHelper(statusOptions)
};
Umeng.prototype.cancel = function (args) {
var cancelOptions = {
uri: 'http://msg.umeng.com/api/cancel',
method: 'POST'
};
cancelOptions.json = args;
cancelOptions.json.appKey = this.appKey;
return util.requestHelper(cancelOptions)
};
Umeng.prototype.upload = function (args) {
var uploadOptions = {
uri: 'http://msg.umeng.com/upload',
method: 'POST'
};
uploadOptions.json = args;
uploadOptions.json.appKey = this.appKey;
return util.requestHelper(uploadOptions)
};
|
import {Inferno, Component} from './../infernowrapper';
import {Link} from './../components/link';
const NestedStateless = (props) => (<section class={props.class}>{props.children}</section>);
export class InputViewConainer extends Component {
constructor(props) {
super(props);
this.state = {
value: 0
};
this.addStuff = this.addStuff.bind(this);
}
addStuff() {
this.setState({
value: 10
});
}
render() {
return (
<div>
<h2>IGearInput</h2>
<button onClick={this.addStuff}>Add</button>
<NestedStateless>
<NestedStateless key={1}><h1>1</h1></NestedStateless>
<NestedStateless class={''+this.state.value}><h2>{this.state.value}</h2></NestedStateless>
</NestedStateless>
</div>
)
}
}
|
var Pattern = require('hexo-util').Pattern;
var moment = require('moment');
function isTmpFile(path){
var last = path[path.length - 1];
return last === '%' || last === '~';
}
function isHiddenFile(path){
if (path[0] === '_') return true;
return /\/_/.test(path);
}
exports.ignoreTmpAndHiddenFile = new Pattern(function(path){
if (isTmpFile(path) || isHiddenFile(path)) return false;
return true;
});
exports.isTmpFile = isTmpFile;
exports.isHiddenFile = isHiddenFile;
exports.toDate = function(date){
if (!date || moment.isMoment(date)) return date;
if (!(date instanceof Date)){
date = new Date(date);
}
if (isNaN(date.getTime())) return;
return date;
};
|
var infinityListView = new infinity.ListView($('#poly-ed-scroll'));
var theFilters = {};
$(".filterBtn").on("click", function(event){
theFilters.metadata.startYear = $(".poly-ed-startYear");
theFilters.metadata.startYear = $(".poly-ed-endYear");
/////need to break up strings into arrays to search properly
theFilters.transcription.languages = $(".poly-ed-languages-filter");
theFilters.transcription.difficulty = $("#poly-ed-TranscriptionDifficulty");
theFilters.translation.languages = $(".poly-ed-languages-filter");
theFilters.translation.difficulty = $("#poly-ed-TranslationDifficulty");
theFilters.searchTerms = $(".poly-ed-languages-filter");
});
var theScrollHeight = $( window ).height() - $(".ed-poly-header").height() - $(".poly-ed-filters-row").height();
$("#poly-ed-scroll").height(theScrollHeight);
var polyEdFilters = null;
generateQueue(12, true, true, 0);
|
var dragSrcEl = null;
var svg = null;
var x = null;
var y = null;
function handleDragStart(e) {
this.style.opacity = '0.4'; // this / e.target is the source node.
dragSrcEl = this;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', this.innerHTML);
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'move';
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
this.classList.add('over');
}
function handleDragLeave(e) {
// this / e.target is previous target element.
this.classList.remove('over');
}
function handleDrop(e) {
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
svg_origin = document.querySelector('#canvas svg').getBoundingClientRect();
console.log(svg_origin)
origin_x = svg_origin.x;
origin_y = svg_origin.y;
x = e.clientX - origin_x;
y = e.clientY - origin_y;
var g = dragSrcEl.querySelector("g");
console.log("Dropping "+g+" on "+x+" , "+y+".");
svg.append('g')
.html(g.innerHTML)
.attr('class', 'node')
.attr("transform", function(d) {
return "translate(" + x + "," + y + ")";
});
return false;
}
function handleDragEnd(e) {
// this/e.target is the source node.
this.style.opacity = '1';
var types = document.querySelectorAll('#palette .draggablebox');
[].forEach.call(types, function (typ) {
typ.classList.remove('over');
});
}
function activateShapes(){
var types = document.querySelectorAll('#palette .draggablebox');
[].forEach.call(types, function(typ) {
typ.addEventListener('dragstart', handleDragStart, false);
typ.addEventListener('dragenter', handleDragEnter, false);
typ.addEventListener('dragleave', handleDragLeave, false);
typ.addEventListener('dragend', handleDragEnd, false);
});
}
function activateCanvas(){
document.querySelector('#canvas').addEventListener('dragover', handleDragOver, false);
document.querySelector('#canvas').addEventListener('drop', handleDrop, false);
}
function loadShapesIntoPalette(){
d3.json("types.json", function(error, treeData) {
if (error != null){
alert(error);
}
var shapes = treeData.shapes;
// Normalize for fixed-depth.
shapes.forEach(function(d) { d.x = 10; d.y = 10 });
var palette = d3.select("#palette")
svg = d3.select('#canvas')
.append('svg')
.on('mouseup', function(d){
coordinates = d3.mouse(this);
x = coordinates[0];
y = coordinates[1];
console.log(x + ", " + y)
})
// Declare the shapes
var node = palette.selectAll("div.shapecontainer")
.data(shapes, function(d) { return d });
// Enter the shapes.
var nodeEnter = node.enter().append("div")
.attr("class", "shapecontainer")
.append('span')
.attr('class', 'draggablebox')
.attr('draggable', 'true')
.append("svg")
.attr("class", "palettesvg")
.append('g')
.attr('class', 'type')
.attr('shape', function(d){return d.shape})
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")"; })
.append("path")
.style("stroke", function(d) { return 'black'; })
.style("fill", function(d) { return d.colour; })
.attr("d", d3.symbol()
.size(function(d) { return d.height * d.width; } )
.type(function(d) { if
(d.shape == "circle") { return d3.symbolCircle; } else if
(d.shape == "diamond") { return d3.symbolDiamond;} else if
(d.shape == "cross") { return d3.symbolCross;} else if
(d.shape == "triangle") { return d3.symbolTriangle;} else if
(d.shape == "square") { return d3.symbolSquare;} else if
(d.shape == "star") { return d3.symbolStar;} else if
(d.shape == "wye") { return d3.symbolWye;}
}));
//Make the shapes in the palette draggable.
activateShapes();
activateCanvas();
});
}
|
/* jshint -W069 */
var assert = require('assert')
, path = require('path')
, fs = require('fs')
, data = require(path.join(__dirname, 'server/observerData.json'))
var attributeCheck = function (data) {
it('should copy <html> attributes', function () {
assert.equal(data.cdvLoaderReady.html['data-ex-1'], 'null')
assert.equal(data.cdvLoaderReady.html['data-ex-2'], 'text value 1')
})
it('should copy <head> attributes', function () {
assert.equal(data.cdvLoaderReady.head['data-ex-1'], 'null')
assert.equal(data.cdvLoaderReady.head['data-ex-2'], 'text value 2')
})
it('should copy <body> attributes', function () {
assert.equal(data.cdvLoaderReady.body['data-ex-1'], 'null')
assert.equal(data.cdvLoaderReady.body['data-ex-2'], 'text value')
assert.equal(data.cdvLoaderReady.body.id, 'the-body')
assert.equal(data.cdvLoaderReady.body.class, 'the-class')
})
}
describe('Server conditions', function () {
it('should be 7 in all', function () {
assert.strictEqual(data.length, 7)
})
})
describe('When the server is down before install, cdvLoader:', function () {
it('should dispatch the cdvLoaderCheckingForUpdate event', function () {
assert('cdvLoaderCheckingForUpdate' in data[0])
})
it('should display the update view', function () {
assert(data[0].cdvLoaderCheckingForUpdate['#cdv-loader-update-view'].isVisible)
})
it('should dispatch cdvLoaderUpdateAborted event', function () {
assert('cdvLoaderUpdateAborted' in data[0])
})
it('should advise the user that it could not install', function () {
var text = data[0].cdvLoaderUpdateAborted['#cdv-loader-update-msg'].innerHTML
assert.equal(text, 'Failed to retrieve app files from the server. The app could not be installed.')
})
it('should not trigger any uncaught exceptions', function () {
assert.equal(data[0].errors, undefined)
})
})
describe('When the server returns errors before install, cdvLoader:', function () {
it('should dispatch the cdvLoaderCheckingForUpdate event', function () {
assert('cdvLoaderCheckingForUpdate' in data[1])
})
it('should display the update view', function () {
assert(data[1].cdvLoaderCheckingForUpdate['#cdv-loader-update-view'].isVisible)
})
it('should dispatch cdvLoaderUpdateAborted event', function () {
assert('cdvLoaderUpdateAborted' in data[1])
})
it('should advise the user that it could not get the manifest', function () {
var text = data[1].cdvLoaderUpdateAborted['#cdv-loader-update-msg'].innerHTML
assert.equal(text, 'Failed to retrieve app files from the server. The app could not be installed.')
})
it('should not trigger any uncaught exceptions', function () {
assert.equal(data[1].errors, undefined)
})
})
describe('When the server is up for initial install, cdvLoader:', function () {
it('should dispatch the cdvLoaderCheckingForUpdate event', function () {
assert('cdvLoaderCheckingForUpdate' in data[2])
})
it('should display the update view', function () {
assert(data[2].cdvLoaderCheckingForUpdate['#cdv-loader-update-view'].isVisible)
})
it('should dispatch the cdvLoaderManifestDownloaded event', function () {
assert('cdvLoaderManifestDownloaded' in data[2])
})
it('should dispatch the cdvLoaderUpdating event', function () {
assert('cdvLoaderUpdating' in data[2])
})
it('should dispatch the cdvLoaderReady event', function () {
assert('cdvLoaderReady' in data[2])
})
it('should execute main.js first', function () {
assert.equal(data[2].cdvLoaderReady.execSequence[0], 'main.js')
})
it('should execute second.js second', function () {
assert.equal(data[2].cdvLoaderReady.execSequence[1], 'second.js')
})
it('should inject style.css', function () {
assert(data[2].cdvLoaderReady['style[data-uri="style.css"]'].exists)
})
it('should replace the document title', function () {
assert.equal(data[2].cdvLoaderReady.documentTitle, 'v1')
})
it('should inject <head> material', function () {
assert(data[2].cdvLoaderReady['#head-node'].exists)
})
it('should inject <body> material', function () {
assert(data[2].cdvLoaderReady['#body-node'].exists)
})
attributeCheck(data[2])
it('should not trigger any uncaught exceptions', function () {
assert.equal(data[2].errors, undefined)
})
})
describe('When the server is down after install, cdvLoader:', function () {
it('should dispatch the cdvLoaderCheckingForUpdate event', function () {
assert('cdvLoaderCheckingForUpdate' in data[3])
})
it('should display the update view', function () {
assert(data[3].cdvLoaderCheckingForUpdate['#cdv-loader-update-view'].isVisible)
})
it('should dispatch cdvLoaderUpdateAborted event', function () {
assert('cdvLoaderUpdateAborted' in data[3])
})
it('should advise the user that it could not get the manifest', function () {
var text = data[3].cdvLoaderUpdateAborted['#cdv-loader-update-msg'].innerHTML
assert.equal(text, 'The update server failed to return the update list.')
})
it('should dispatch the cdvLoaderReady event', function () {
assert('cdvLoaderReady' in data[3])
})
it('should execute main.js first', function () {
assert.equal(data[3].cdvLoaderReady.execSequence[0], 'main.js')
})
it('should execute second.js second', function () {
assert.equal(data[3].cdvLoaderReady.execSequence[1], 'second.js')
})
it('should inject style.css', function () {
assert(data[3].cdvLoaderReady['style[data-uri="style.css"]'].exists)
})
it('should replace the document title', function () {
assert.equal(data[3].cdvLoaderReady.documentTitle, 'v1')
})
it('should inject <head> material', function () {
assert(data[3].cdvLoaderReady['#head-node'].exists)
})
it('should inject <body> material', function () {
assert(data[3].cdvLoaderReady['#body-node'].exists)
})
attributeCheck(data[3])
it('should not trigger any uncaught exceptions', function () {
assert.equal(data[3].errors, undefined)
})
})
describe('When the server returns errors after install, cdvLoader:', function () {
it('should dispatch the cdvLoaderCheckingForUpdate event', function () {
assert('cdvLoaderCheckingForUpdate' in data[4])
})
it('should display the update view', function () {
assert(data[4].cdvLoaderCheckingForUpdate['#cdv-loader-update-view'].isVisible)
})
it('should dispatch cdvLoaderUpdateAborted event', function () {
assert('cdvLoaderUpdateAborted' in data[4])
})
it('should advise the user that it could not get the manifest', function () {
var text = data[4].cdvLoaderUpdateAborted['#cdv-loader-update-msg'].innerHTML
assert.equal(text, 'The update server failed to return the update list.')
})
it('should dispatch the cdvLoaderReady event', function () {
assert('cdvLoaderReady' in data[4])
})
it('should execute main.js first', function () {
assert.equal(data[4].cdvLoaderReady.execSequence[0], 'main.js')
})
it('should execute second.js second', function () {
assert.equal(data[4].cdvLoaderReady.execSequence[1], 'second.js')
})
it('should inject style.css', function () {
assert(data[4].cdvLoaderReady['style[data-uri="style.css"]'].exists)
})
it('should replace the document title', function () {
assert.equal(data[4].cdvLoaderReady.documentTitle, 'v1')
})
it('should inject <head> material', function () {
assert(data[4].cdvLoaderReady['#head-node'].exists)
})
it('should inject <body> material', function () {
assert(data[4].cdvLoaderReady['#body-node'].exists)
})
attributeCheck(data[4])
it('should not trigger any uncaught exceptions', function () {
assert.equal(data[4].errors, undefined)
})
})
describe('When the server provides no update after install, cdvLoader:', function () {
it('should dispatch the cdvLoaderCheckingForUpdate event', function () {
assert('cdvLoaderCheckingForUpdate' in data[5])
})
it('should display the update view', function () {
assert(data[5].cdvLoaderCheckingForUpdate['#cdv-loader-update-view'].isVisible)
})
it('should dispatch the cdvLoaderReady event', function () {
assert('cdvLoaderReady' in data[5])
})
it('should execute main.js first', function () {
assert.equal(data[5].cdvLoaderReady.execSequence[0], 'main.js')
})
it('should execute second.js second', function () {
assert.equal(data[5].cdvLoaderReady.execSequence[1], 'second.js')
})
it('should inject style.css', function () {
assert(data[5].cdvLoaderReady['style[data-uri="style.css"]'].exists)
})
it('should replace the document title', function () {
assert.equal(data[5].cdvLoaderReady.documentTitle, 'v1')
})
it('should inject <head> material', function () {
assert(data[5].cdvLoaderReady['#head-node'].exists)
})
it('should inject <body> material', function () {
assert(data[5].cdvLoaderReady['#body-node'].exists)
})
attributeCheck(data[5])
it('should not trigger any uncaught exceptions', function () {
assert.equal(data[5].errors, undefined)
})
})
describe('When the server provides an update, cdvLoader:', function () {
it('should dispatch the cdvLoaderCheckingForUpdate event', function () {
assert('cdvLoaderCheckingForUpdate' in data[6])
})
it('should display the update view', function () {
assert(data[6].cdvLoaderCheckingForUpdate['#cdv-loader-update-view'].isVisible)
})
it('should dispatch the cdvLoaderManifestDownloaded event', function () {
assert('cdvLoaderManifestDownloaded' in data[6])
})
it('should dispatch the cdvLoaderUpdating event', function () {
assert('cdvLoaderUpdating' in data[6])
})
it('should dispatch the cdvLoaderReady event', function () {
assert('cdvLoaderReady' in data[6])
})
it('should execute main.js first', function () {
assert.equal(data[6].cdvLoaderReady.execSequence[0], 'main.js')
})
it('should execute second.js second', function () {
assert.equal(data[6].cdvLoaderReady.execSequence[1], 'second.js')
})
it('should execute third.js third', function () {
assert.equal(data[6].cdvLoaderReady.execSequence[2], 'third.js')
})
it('should inject style.css', function () {
assert(data[6].cdvLoaderReady['style[data-uri="style.css"]'].exists)
})
it('should inject style2.css', function () {
assert(data[6].cdvLoaderReady['style[data-uri="style2.css"]'].exists)
})
it('should inject style2.css after style.css', function () {
var els = data[6].cdvLoaderReady.styleElements
assert(els.indexOf('style.css') < els.indexOf('style2.css'))
})
it('should replace the document title', function () {
assert.equal(data[6].cdvLoaderReady.documentTitle, 'v2')
})
it('should inject <head> material', function () {
assert(data[6].cdvLoaderReady['#head-node'].exists)
})
it('should inject <body> material', function () {
assert(data[6].cdvLoaderReady['#body-node'].exists)
})
attributeCheck(data[6])
it('should not trigger any uncaught exceptions', function () {
assert.equal(data[6].errors, undefined)
})
})
|
(function(){
"use strict";
var app = angular.module("pynative");
app.directive("radiogroupview", function() {
return {
controller: "ViewController",
templateUrl: "/static/angular-templates/radiogroup.html",
restrict: "E",
scope: {
viewdata: "=viewdata"
}
};
});
})();
|
'use strict';
/* eslint-disable global-require */
require('../dist/pixi');
PIXI.utils.skipHello(); // hide banner
describe('PIXI', function ()
{
it('should exist as a global object', function ()
{
expect(PIXI).to.be.an('object');
});
require('./core');
require('./interaction');
require('./renders');
require('./prepare');
});
|
module.exports = function (grunt) {
grunt.initConfig({
sass: {
dist: {
options: {
style: 'compressed',
sourcemap: 'none'
},
files: {
'css/styles.min.css': 'scss/styles.scss',
}
}
},
watch: {
src: {
files: ['scss/**/*.scss'],
tasks: ['sass']
}
}
});
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['sass','watch']);
};
|
(function () {
'use strict';
angular
.module('loopbackAdmin.login.authentication')
.config(config);
/** @ngInject */
function config($httpProvider) {
// This functionality was taken from https://github.com/beeman/loopback-angular-admin/issues and modified
// Thanks to http://stackoverflow.com/questions/14681654/i-need-two-instances-of-angularjs-http-service-or-what/19954545#19954545
$httpProvider.interceptors.push(function ($q, $injector) {
return {
responseError: function (rejection) {
//Intercept 401 responses and redirect to login screen
$injector.invoke(function ($q, $location, $log, CoreService) {
// $http is already constructed at the time and you may
// use it, just as any other service registered in your
// app module and modules on which app depends on.
if (rejection.status === 401) {
// save the current location so that login can redirect back
$location.nextAfterLogin = $location.path();
if ($location.path() === '/router' || $location.path() === '/login') {
$log.warn('401 while on router on login path');
} else {
if ($location.path() !== '/register') {
$location.path('/login');
}
CoreService.toastError('Error 401 received', 'We received a 401 error from the API! Redirecting to login');
}
} else if (rejection.status === 404) {
$log.error('Error 404 received: ' + rejection);
CoreService.toastError('Error 404 received', 'We received a 404 error from the API! Redirecting to login');
} else if (rejection.status === 422) {
$log.error('Error 422 received: ' + rejection);
CoreService.toastError('Error 442 received', rejection.data.error.message);
} else if (rejection.status === 0) {
$location.path('/');
CoreService.toastError('Connection Refused', 'The connection to the API is refused. Please verify that the API is running!');
}
return $q.reject(rejection);
});
}
};
});
}
})();
|
/**
* Given an array of numbers (`arr`), find the item in the array closest
* to a given number (`num`).
*
* @param {Array.<number>} arr An array of numbers.
* @param {number} num Close number to search from.
* @return {?number} The closest number in the array.
*/
export default function closest(arr, num) {
let closest = null;
arr.reduce((closestDiff, value) => {
const diff = Math.abs(value - num);
if (diff < closestDiff) {
closest = value;
return diff;
}
return closestDiff;
}, Infinity);
return closest;
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import {
createStore,
applyMiddleware
} from 'redux';
import {
Provider
} from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import R from 'ramda';
import App from './App';
import reducers from './reducers';
import {
fetchRandomSongs,
fetchArtists
} from './actionTypes.js';
require('../index.html');
let store = createStore(reducers, window.devToolsExtension && window.devToolsExtension(),
applyMiddleware(thunkMiddleware));
ReactDOM.render(
<MuiThemeProvider>
<Provider store={store}>
<App />
</Provider>
</MuiThemeProvider>,
document.getElementById('root')
);
store.dispatch(fetchArtists(store.getState().library));
|
var should = require('chai').should()
|
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { colors } from 'global-colors';
import FormFieldHeading from 'components/FormFieldHeading';
import FormFieldWrapper from 'components/FormFieldWrapper';
const StyledTextInputContainer = styled.div`
width: ${(props) => props.widthpct}%;
height: 40px;
position: relative;
font-weight: normal;
font-style: normal;
display: -webkit-inline-box;
display: -ms-inline-flexbox;
display: inline-flex;
`;
const StyledTextInput = styled.input`
background-color: #fff;
color: rgb(${colors.secondaryblue});
width: 100%;
border-radius: 6px;
border: 2px solid rgb(${colors.secondarygrey});
color: rgb(${colors.secondaryblue});
padding-left: 8px;
display: inline-block;
margin: 0em;
max-width: 100%;
-webkit-box-flex: 1;
-ms-flex: 1 0 auto;
flex: 1 0 auto;
outline: none;
`;
const StyledFieldButton = styled.div`
display: inline-block;
position: relative;
left: -44px;
top: 2px;
line-height: 1;
vertical-align: baseline;
margin: 0em 0.14285714em;
background-color: ${(props) => (props.active) ? '#C8C8C8' : '#E8E8E8'};
color: rgba(0, 0, 0, 0.6);
padding: 0.5833em 0.833em;
font-weight: bold;
height: 36px;
border: 2px solid transparent;
cursor: ${(props) => (props.active) ? 'default' : 'pointer'};
-webkit-transition: background-color 0.25s ease, background 0.25s ease;
transition: background-color 0.25s ease, background 0.25s ease;
&:hover {
background-color: #CCCCCC;
}
`;
const StyledFieldButtonOne = styled(StyledFieldButton)`
left:-86px;
`;
const StyledFieldButtonTwo = styled(StyledFieldButton)`
left:-91px;
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
`;
export default function FormOptionButtonField({ input, type, fieldheading, activeoptionindex, optionclickhandler, buttonlabels, meta: { touched, error }, widthpct = 92, leftpadding = 4 }) {
const fieldButtonOneActive = (activeoptionindex === 0);
const fieldButtonTwoActive = (activeoptionindex === 1);
let fieldValue = (activeoptionindex === 0) ? input.value.get('amount') : input.value.get('pct');
if (isNaN(fieldValue.replace(/,/g, '').replace('$', ''))) { fieldValue = ''; }
return (
<FormFieldWrapper leftpadding={leftpadding}>
<FormFieldHeading>{fieldheading}</FormFieldHeading>
<div>
<StyledTextInputContainer widthpct={widthpct}>
<StyledTextInput {...input} value={fieldValue} type={type} />
<StyledFieldButtonOne name={`${input.name}_dollarmask`} active={fieldButtonOneActive} onClick={(e, data) => { input.onChange(); optionclickhandler(e, data, `${input.name}_dollarmask`); }}>{ buttonlabels[0] }</StyledFieldButtonOne>
<StyledFieldButtonTwo name={`${input.name}_pctmask`} active={fieldButtonTwoActive} onClick={(e, data) => { input.onChange(); optionclickhandler(e, data, `${input.name}_pctmask`); }}>{ buttonlabels[1] }</StyledFieldButtonTwo>
</StyledTextInputContainer>
{touched && error && <span>{error}</span>}
</div>
</FormFieldWrapper>
);
}
FormOptionButtonField.propTypes = {
input: PropTypes.any,
type: PropTypes.string,
activeoptionindex: PropTypes.number,
fieldheading: PropTypes.string,
optionclickhandler: PropTypes.func,
buttonlabels: PropTypes.array,
meta: PropTypes.any,
widthpct: PropTypes.number,
leftpadding: PropTypes.number,
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:76e69fba44e96859b3bc4a0c5b8b0c3a5baf15633892c13e802aff0baa92ea58
size 122298
|
version https://git-lfs.github.com/spec/v1
oid sha256:f7c48c8b07ed19fd26ce685209569de468d586c127bd87c6f8354506055bf1e3
size 15495
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
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;
};
Object.defineProperty(exports, "__esModule", { value: true });
var Radium = require("radium");
var React = require("react");
var css_eb_button_1 = require("./css_eb_button");
var Button = (function (_super) {
__extends(Button, _super);
function Button(props) {
var _this = _super.call(this, props) || this;
_this.state = {
buttonText: props.text || "Button",
isDisabled: !!props.disabled,
};
_this.onClickHandler = _this.onClickHandler.bind(_this);
return _this;
}
Button.prototype.render = function () {
var onClick = this.state.isDisabled ? null : this.onClickHandler;
var stylesArr = (this.props.UIType === "AE") ?
this.state.isDisabled ? [css_eb_button_1.AEButton, css_eb_button_1.AECssDisabled] : [css_eb_button_1.AEButton, css_eb_button_1.AECssActive]
:
this.state.isDisabled ? [css_eb_button_1.CssBase, css_eb_button_1.CssDisabled] : [css_eb_button_1.CssBase, css_eb_button_1.CssActive];
return (React.createElement("div", null,
React.createElement(Radium.StyleRoot, null,
React.createElement("div", { className: "extraui-kit__button-main", style: [stylesArr], onClick: onClick },
React.createElement("p", { style: [css_eb_button_1.CssPBase] }, this.state.buttonText)))));
};
Button.prototype.onClickHandler = function (e, obj) {
this.props.onClickHandler(e, obj);
};
Button = __decorate([
Radium
], Button);
return Button;
}(React.Component));
exports.default = Button;
//# sourceMappingURL=Button.js.map
|
function numbers() {
for ( var arg of arguments ) {
console.log(arg);
}
}
numbers();
numbers(1);
numbers(1, 2, 3);
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes, Component } from 'react';
import Location from '../../core/Location';
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
class Link extends Component {
static propTypes = {
to: PropTypes.string.isRequired,
children: PropTypes.element.isRequired,
state: PropTypes.object,
onClick: PropTypes.func,
};
static handleClick = event => {
let allowTransition = true;
let clickResult;
if (this.props && this.props.onClick) {
clickResult = this.props.onClick(event);
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
if (clickResult === false || event.defaultPrevented === true) {
allowTransition = false;
}
event.preventDefault();
if (allowTransition) {
window.location = event.currentTarget;
}
};
render() {
const { to, children, ...props } = this.props;
return <a onClick={Link.handleClick.bind(this)} {...props}>{children}</a>;
}
}
export default Link;
|
const fa_hourglass_end = 'M1536 128q0 261-106.5 461.5t-266.5 306.5q160 106 266.5 306.5t106.5 461.5h96q14 0 23 9t9 23v64q0 14-9 23t-23 9h-1472q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h96q0-261 106.5-461.5t266.5-306.5q-160-106-266.5-306.5t-106.5-461.5h-96q-14 0-23-9t-9-23v-64q0-14 9-23t23-9h1472q14 0 23 9t9 23v64q0 14-9 23t-23 9h-96zm-534 708q77-29 149-92.5t129.5-152.5 92.5-210 35-253h-1024q0 132 35 253t92.5 210 129.5 152.5 149 92.5q19 7 30.5 23.5t11.5 36.5-11.5 36.5-30.5 23.5q-137 51-244 196h700q-107-145-244-196-19-7-30.5-23.5t-11.5-36.5 11.5-36.5 30.5-23.5z'
export default fa_hourglass_end
|
function extractQueryParams() {
var params = {};
location.search.substr(1).split('&').forEach(function(item) {
params[item.split('=')[0]] = decodeURIComponent(item.split('=')[1]);
});
return params;
};
function clearQueryString() {
var uri = window.location.toString();
if (uri.indexOf('?') > 0) {
var cleanUri = uri.substring(0, uri.indexOf('?'));
window.history.replaceState({}, document.title, cleanUri);
}
};
function getDocumentIdFromLocation() {
return location.href.split('/d/')[1].split('/')[0];
}
export { extractQueryParams, clearQueryString, getDocumentIdFromLocation };
|
require('dotenv').config()
const db = require('../models')
module.exports = db
|
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var eslint = require('gulp-eslint');
var staticTransform = require('connect-static-transform');
var buildDirectory = 'dist';
var pkg = require('./package.json');
gulp.task('build', function() {
gulp.src('jquery.tkDropdown.js')
.pipe(gulp.dest(buildDirectory));
return gulp.src('jquery.tkDropdown.js')
.pipe(uglify({ output: { max_line_len: 500 } }))
.pipe(rename({ suffix: '-min' }))
.pipe(gulp.dest(buildDirectory));
});
gulp.task('lint', function() {
return gulp.src(pkg.main)
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
var emulateIEMiddlewareFactory = function(version) {
return staticTransform({
root: __dirname,
match: /(.+)\.html/,
transform: function (path, text, send) {
send(text.replace('content="IE=edge,chrome=1"', 'content="IE=' + version + '"'));
}
});
};
var emulateIEMiddleware = {
'ie8': emulateIEMiddlewareFactory(8),
'ie9': emulateIEMiddlewareFactory(9),
'ie10': emulateIEMiddlewareFactory(10)
};
var shell = function(command, callback) {
var args = process.argv.slice(3).join(' '),
proc = exec(command + ' ' + args, function(err) {
callback(err);
});
proc.stdout.on('data', function(data) {
process.stdout.write(data);
});
proc.stderr.on('data', function(data) {
process.stderr.write(data);
});
};
|
/*
Copyright (c) 2016 Joseph B. Hall [@groundh0g]
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 Console = new (function() {
"use strict";
// constants
this.LOG_DEBUG = "DEBUG";
this.LOG_ERROR = "ERROR";
this.LOG_INFO = "INFO";
this.LOG_WARN = "WARN";
// ** DEBUG MODE **
this.isDebug = false; // true;
var self = this;
var logEntries = [];
var logCounts = { };
var _entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
var escapeHtml = function(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return _entityMap[s];
});
};
var log = function(type, msg, ex) {
logCounts[type] = (logCounts[type] || 0) + 1;
logEntries.push({
type: type,
message: msg,
exception: ex
});
var icon = undefined;
switch(type) {
case self.LOG_DEBUG: icon = "fa fa-angle-double-right"; break;
case self.LOG_ERROR: icon = "fa fa-bug"; break;
case self.LOG_INFO: icon = "fa fa-info-circle"; break;
case self.LOG_WARN: icon = "fa fa-exclamation-triangle"; break;
}
var html =
(icon ? "<i class='" + icon + "'></i> " : "") +
(type ? "<b>" + type + ":</b> " : "") +
msg;
if(ex) {
html = "<span title='" + escapeHtml(ex) + "' style='cursor:default;'>" + html + "</span>";
} else {
html = "<span style='cursor:default;'>" + html + "</span>";
}
$("#divConsole").append(html).append("<br/>");
$("#tabConsole span").hide();
var $lbl = undefined;
switch(type) {
case self.LOG_ERROR: $lbl = $("#lblLogCountERROR"); break;
case self.LOG_DEBUG: $lbl = $("#lblLogCountDEBUG"); break;
case self.LOG_WARN: $lbl = $("#lblLogCountWARNING"); break;
case self.LOG_INFO: $lbl = $("#lblLogCountINFO"); break;
default: $lbl = $("#lblLogCountSUCCESS"); break;
}
$lbl.text(self.count()).show();
};
this.debug = function(msg, ex) {}; // { if(this.isDebug) log(this.LOG_DEBUG, msg, ex); };
this.error = function(msg, ex) { log(this.LOG_ERROR, msg, ex); };
this.info = function(msg, ex) { log(this.LOG_INFO, msg, ex); };
this.warn = function(msg, ex) { log(this.LOG_WARN, msg, ex); };
this.clear = function() {
logEntries = [];
logCounts = { };
$("#divConsole").html("");
};
this.count = function(type) {
return type ? (logCounts[type] || 0) : (
(logCounts[this.LOG_DEBUG] || 0) +
(logCounts[this.LOG_ERROR] || 0) +
(logCounts[this.LOG_INFO] || 0) +
(logCounts[this.LOG_WARN] || 0)
);
};
this.clear();
return this;
})();
|
function saveapplication(){
var instcode = document.getElementById("instcode").value;
var datereceived = document.getElementById("datereceived").value;
var programname = document.getElementById("programname").value;
var yearlevel = document.getElementById("yearlevel").value;
var schoolyear = document.getElementById("schoolyear").value;
var assigned_to_uid = document.getElementById("assigned_to_uid").value;
var application_status = document.getElementById("application_status").value;
$.ajax({
url: 'programapplication/saveapplication/',
type: 'post',
data: {instcode:instcode,datereceived:datereceived,programname:programname,yearlevel:yearlevel,assigned_to_uid:assigned_to_uid,application_status:application_status,schoolyear:schoolyear},
success: function(response) {
//console.log(response);
//var data = JSON.parse(response);
window.location.reload();
}
});
}
function updateapplication(){
var progappid = document.getElementById("progappid").value;
var instcode = document.getElementById("instcode").value;
var datereceived = document.getElementById("datereceived").value;
var programname = document.getElementById("programname").value;
var yearlevel = document.getElementById("yearlevel").value;
var schoolyear = document.getElementById("schoolyear").value;
var assigned_to_uid = document.getElementById("assigned_to_uid").value;
var application_status = document.getElementById("application_status").value;
$.ajax({
url: '../updateapplication',
type: 'post',
data: {instcode:instcode,datereceived:datereceived,programname:programname,yearlevel:yearlevel,assigned_to_uid:assigned_to_uid,application_status:application_status,progappid:progappid,schoolyear:schoolyear},
success: function(response) {
//console.log(response);
//var data = JSON.parse(response);
window.location.reload();
}
});
}
function saveremarks(progappid){
var remarks_reply = document.getElementById("remarks_reply").value;
var application_status = document.getElementById("application_status").value;
$.ajax({
url: '../saveremarks',
type: 'post',
data: {progappid:progappid,remarks_reply:remarks_reply,application_status:application_status},
success: function(response) {
//console.log(response);
//var data = JSON.parse(response);
//window.location.reload();
$('#remarks_list').load(document.URL + ' #remarks_list');
}
});
}
function deleteapplication(id){
var baseurl = document.getElementById("baseurl").value;
var r = confirm("Are your sure you want to delete this Application?");
if (r == true) {
//alert ("You pressed OK!");
//var person = prompt("Please enter Administrator Password");
//if (person =='superadmin') {
$.ajax({
url: baseurl+'programapplication/deleteapplication',
type: 'post',
data: {progappid: id},
success: function(response) {
$.bootstrapGrowl('<h4><strong>Program Deleted!</strong></h4> <p>Program has been deleted!</p>', {
type: 'success',
delay: 3000,
allow_dismiss: true,
offset: {from: 'top', amount: 20}
});
setTimeout(function(){location.reload();},1000);
}
});
//}else{
//alert("Invalid Password");
//}
} if(r == false) {
//txt = "You pressed Cancel!";
}
}
function deleteremarks(id){
//var baseurl = document.getElementById("baseurl").value;
var r = confirm("Are your sure you want to delete this Remarks?");
if (r == true) {
//alert ("You pressed OK!");
var person = prompt("Please enter Administrator Password");
if (person =='superadmin') {
$.ajax({
url: '../deleteremarks',
type: 'post',
data: {remarksid: id},
success: function(response) {
//console.log(response);
$('#remarks_list').load(document.URL + ' #remarks_list');
}
});
}else{
alert("Invalid Password");
}
} if(r == false) {
//txt = "You pressed Cancel!";
}
}
$(document).ready(function() {
$('#program-application-list-table').DataTable( {
"order": [[ 0, "desc" ]]
} );
} );
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><circle cx="19.5" cy="19.5" r="1.5" /><path d="M11 18.03V8.98l4.22-2.15c.73-.37.73-1.43-.01-1.79l-4.76-2.33C9.78 2.38 9 2.86 9 3.6V19c0 .55-.45 1-1 1s-1-.45-1-1v-.73c-1.79.35-3 .99-3 1.73 0 1.1 2.69 2 6 2s6-.9 6-2c0-.99-2.16-1.81-5-1.97z" /></React.Fragment>
, 'GolfCourseRounded');
|
/* eslint-disable no-console */
'use strict'
const Libp2p = require('../../')
const TCP = require('libp2p-tcp')
const Mplex = require('libp2p-mplex')
const SECIO = require('libp2p-secio')
const { NOISE } = require('libp2p-noise')
const CID = require('cids')
const KadDHT = require('libp2p-kad-dht')
const all = require('it-all')
const delay = require('delay')
const createNode = async () => {
const node = await Libp2p.create({
addresses: {
listen: ['/ip4/0.0.0.0/tcp/0']
},
modules: {
transport: [TCP],
streamMuxer: [Mplex],
connEncryption: [NOISE, SECIO],
dht: KadDHT
},
config: {
dht: {
enabled: true
}
}
})
await node.start()
return node
}
;(async () => {
const [node1, node2, node3] = await Promise.all([
createNode(),
createNode(),
createNode()
])
node1.peerStore.addressBook.set(node2.peerId, node2.multiaddrs)
node2.peerStore.addressBook.set(node3.peerId, node3.multiaddrs)
await Promise.all([
node1.dial(node2.peerId),
node2.dial(node3.peerId)
])
// Wait for onConnect handlers in the DHT
await delay(100)
const cid = new CID('QmTp9VkYvnHyrqKQuFPiuZkiX9gPcqj6x5LJ1rmWuSySnL')
await node1.contentRouting.provide(cid)
console.log('Node %s is providing %s', node1.peerId.toB58String(), cid.toBaseEncodedString())
// wait for propagation
await delay(300)
const providers = await all(node3.contentRouting.findProviders(cid, { timeout: 3000 }))
console.log('Found provider:', providers[0].id.toB58String())
})();
|
'use Strict';
var WhoAmI = function() {
this.getMe = function(ipaddress, lang, os) {
return {
"ipaddress" : ipaddress || 'null',
"language" : lang || 'null',
"software" : os || 'null'
}
}
}
function Controller() {
this.process = function(req) {
var ip,lang,os;
//get ip
ip = req.header('x-forwarded-for') || req.connection.remoteAddress;
//get lang
if (/(.*),.*/.test(req.header('accept-language'))) {
lang = /(.*),.*/.exec(req.header('accept-language'))[1];
}
//get os
if ((/.*?\((.*?)\)/g).test(req.header('user-agent'))) {
var os = (/.*?\((.*?)\)/g).exec(req.header('user-agent'))[1] ;
}
var whoAmI = new WhoAmI();
return whoAmI.getMe(ip,lang,os);
}
}
module.exports = Controller;
|
/** the Last Crusade - Ep. 1 (medium) https://www.codingame.com/training/medium/the-last-crusade-episode-1
* This puzzle makes you use an associative array that make a link between
* arbitrary types and directions. You also need to store some values in a
* 2D array.
*
* Statement:
* The goal of this puzzle is to predict the path that a character will take
* in a labyrinth according to the topology of the rooms. The resolution
* of this exercise intensively focus on the correct usage of associative
* arrays. If you can manage them correctly and creates the right
* associations, your final code could be quite short.
*
* Story:
* Indiana is trapped in a tunnel, help him escape!
* In this first level, you just have to get familiar with how the tunnel
* works: your goal is simply to predict Indiana movements within this
* tunnel.
**/
// W - Number of columns.
// H - Number of rows.
let [W, H] = readline().split` `.map(Number);
const maze = []; // Maze
while (H--) {
// Represents a line in the grid and contains W integers.
// Each integer represents one room of a given type.
maze.push(readline());
}
// The coordinate along the X axis of the exit
// (not useful for this first mission, but must be read).
const EX = +readline();
// game loop
while (true) {
inputs = readline().split` `;
const [XI, YI, POS] = [+inputs[0], +inputs[1], inputs[2]];
const currentLevel = maze[YI].split` `;
let [XT, YT] = [XI, YI];
switch(currentLevel[XI]) {
case '1':
case '3':
case '7':
case '8':
case '9':
case '12':
case '13':
YT += 1;
break;
case '2':
XT += POS === 'LEFT' ? 1 : -1;
break;
case '4':
(POS === 'TOP') ? XT -= 1 : YT +=1;
break;
case '5':
(POS === 'TOP') ? XT += 1 : YT +=1;
break;
case '6':
XT += (POS === 'TOP' && EX > XI) || POS === 'LEFT' ? 1 : -1;
break;
case '10':
XT -= 1;
break;
case '11':
XT += 1;
break;
default:
break;
}
// One line containing the X Y coordinates of the room
// in which you believe Indy will be on the next turn.
print(`${XT} ${YT}`);
}
|
$(function () {
'use strict';
/* start ready */
$('#cardNumber').inputmask('9999 - 9999 - 9999 - 9999');
$('#expiryDate').inputmask('99 / 9999');
$('#cvv2').inputmask('999');
$('button[data-action="modal"][data-type="complete"]').animatedModal({
modalTarget: 'completeModal',
animatedIn: 'fadeIn',
animatedOut: 'fadeOut',
animationDuration: '.4s',
useBackground: false,
afterOpen: function() {
setTimeout(function() {
$('#completeModal .close-completeModal').click();
}, 650);
}
});
$('button[data-action="modal"][data-type="cancel"]').animatedModal({
modalTarget: 'cancelModal',
animatedIn: 'fadeIn',
animatedOut: 'fadeOut',
animationDuration: '.4s',
useBackground: false,
afterOpen: function() {
setTimeout(function() {
$('#cancelModal .close-cancelModal').click();
}, 650);
}
});
/* end ready */
});
|
/**
* Created by mars on 2015/10/11.
*/
import React, {
Component,
ToolbarAndroid,
StyleSheet
}
from 'react-native';
export default class Toolbar extends Component {
constructor(props) {
super(props);
}
render() {
const {dispatch, navIconClicked, title, type} = this.props;
const icon = !type || type === 'home' ? require('./img/ic_menu_white_24dp.png') : require('./img/ic_arrow_back_white_24dp.png')
return (
<ToolbarAndroid
titleColor="#ffffff"
title={title || "The Verge"}
navIcon={icon}
style={styles.toolbar}
onIconClicked={()=>navIconClicked()}
>
</ToolbarAndroid>
)
}
}
var styles = StyleSheet.create({
toolbar: {
backgroundColor: '#F62459',
height: 56
},
});
|
(function() {
'use strict';
angular
.module('save-a-selfie.common')
.service('updateEula', updateEula);
updateEula.$inject = ['$http', '$cordovaDevice', 'apiUrl'];
function updateEula($http, $cordovaDevice, apiUrl) {
var service = {
post: post
};
return service;
function post(eula) {
var type, uuid = $cordovaDevice.getDevice()
.uuid;
if (eula === 'photo') {
type = 'EULA';
} else if (eula === 'map') {
type = 'map';
}
var data = {
deviceID: uuid,
EULAType: type
};
return $http({
method: 'POST',
url: apiUrl +
'/wp/wp-content/themes/magazine-child/updateEULA.php',
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" +
encodeURIComponent(obj[p]));
return str.join("&");
},
})
.catch(function() {
console.log('Error submitting EULA!');
});
}
}
})();
|
!function(e){function r(n){if(t[n])return t[n].exports;var o=t[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}var t={};return r.m=e,r.c=t,r.p="",r(0)}([function(e,r){var t=document.getElementById("app");t.innerHTML="Hi"}]);
|
module.exports = function ({ $incremental, $lookup }) {
return {
object: function () {
return function (object) {
return function ($buffer, $start, $end) {
let $_, $i = []
if ($end - $start < 10) {
return $incremental.object(object, 0, $i)($buffer, $start, $end)
}
$buffer[$start++] = object.nudge & 0xff
$_ = 0
object.array.copy($buffer, $start)
$start += object.array.length
$_ += object.array.length
$_ = 8 - $_
$buffer.fill(0x0, $start, $start + $_)
$start += $_
$buffer[$start++] = object.sentry & 0xff
return { start: $start, serialize: null }
}
}
} ()
}
}
|
var _ = require("lodash");
var rx_1 = require("rx");
var fetch = require('node-fetch');
var filter = require('fuzzaldrin').filter;
//https://skimdb.npmjs.com/registry/_design/app/_view/browseAll?group_level=1
function search(text) {
return rx_1.Observable.fromPromise(fetch("https://skimdb.npmjs.com/registry/_design/app/_view/browseAll?group_level=1&limit=100&start_key=%5B%22" + encodeURIComponent(text) + "%22,%7B%7D%5D&end_key=%5B%22" + encodeURIComponent(text) + "z%22,%7B%7D%5D")
.then(function (res) { return res.json(); }))
.flatMap(function (z) {
return rx_1.Observable.from(z.rows);
});
}
//http://registry.npmjs.org/gulp/latest
function searchPackage(text, name) {
return rx_1.Observable.fromPromise(fetch("http://registry.npmjs.org/" + name + "/latest")
.then(function (res) { return res.json(); }));
}
function makeSuggestion(item) {
var type = 'package';
return {
_search: item.key,
text: item.key,
snippet: item.key,
type: type,
displayText: item.key,
className: 'autocomplete-json-schema'
};
}
var packageName = {
getSuggestions: function (options) {
if (!options.replacementPrefix)
return Promise.resolve([]);
return search(options.replacementPrefix)
.map(makeSuggestion)
.toArray()
.toPromise();
},
fileMatchs: ['package.json'],
pathMatch: function (path) {
return path === "dependencies" || path === "devDependencies";
},
dispose: function () { }
};
var packageVersion = {
getSuggestions: function (options) {
var name = options.path.split('/');
return searchPackage(options.replacementPrefix, name[name.length - 1])
.map(function (z) { return ({ key: "^" + z.version }); })
.map(makeSuggestion)
.toArray()
.toPromise();
},
fileMatchs: ['package.json'],
pathMatch: function (path) {
return _.startsWith(path, "dependencies/") || _.startsWith(path, "devDependencies/");
},
dispose: function () { }
};
var providers = [packageName, packageVersion];
module.exports = providers;
|
const webpack = require('webpack');
const Merge = require('webpack-merge');
const WebpackShellPlugin = require('webpack-shell-plugin');
const CommonConfig = require('../common/webpack.server.common.js');
module.exports = Merge(CommonConfig, {
devtool: 'inline-source-map',
plugins: [
new WebpackShellPlugin({onBuildEnd: ['nodemon dist/server/server.js --watch dist/server']}),
]
});
|
"use strict"
class MSCP{
async init(apiPath){
this.apiPath = apiPath ? apiPath : typeof MSCP_API_PATH === "string" ? MSCP_API_PATH : '/api'
this.def = await this.apireq("")
this.mscp_request_include_always_parms = {}
if(this._isLocalStorageAvailable() === true && this.def.error !== undefined && localStorage.MSCPDefinition !== undefined){
this.def = JSON.parse(localStorage.MSCPDefinition)
console.log("Could not fetch MSCP definition, so the one from localStorage is used")
}
if(this.def.error === undefined){
for(let s of this.def.serve){
this._addDependency(s)
}
if(this._isLocalStorageAvailable() === true){
localStorage.MSCPDefinition = JSON.stringify(this.def);
}
return true;
}
console.log("Could not get any MSCP definition. Client calls will fail!")
return false;
}
_addDependency(s){
let obj = this;
let objKey = s.name;
if(s.namespace){
if(this[s.namespace] === undefined){
this[s.namespace] = {}
}
objKey = `${s.namespace}.${s.name}`
this[s.namespace][s.name] = (...args) => this[objKey].apply(this, args);
}
this[objKey] = async function(...args){
let data = {}
let i = 0
for(let i = 0; i < s.args.length && i < args.length; i++){
let a = s.args[i]
if(typeof a === "string"){
data[a] = args[i] !== undefined ? args[i] : null
} else if (typeof a === "object" && typeof a.name === "string" && a.name != ""){
data[a.name] = args[i] !== undefined ? args[i] : null
}
}
let command = (s.namespace ? s.namespace + "/" : "") + s.name;
if(s.returntype == "download"){
let args = []
for(let a in data){
args.push(`${a}=${data[a]}`)
}
window.location = `${this.apiPath}/${command}?${args.join("&")}`
return;
}
var response = await this.apireq(command, data);
if(response.success === true)
return response.result;
else {
console.log("Error on calling function " + s.name + ": " + response.error)
throw response.error;
}
}
}
async apireq(command, data = {}){
return this.req(`${this.apiPath}/${command}`, data);
}
async req(url, data = {}){
let reqData = jQuery.extend({}, data, this.mscp_request_include_always_parms);
try{
let response = await fetch(url, {
method: 'post',
body: JSON.stringify(reqData),
credentials: 'include',
headers: new Headers({
'Content-Type': 'application/json'
})
});
if(response.status == 403){
let accessKey = prompt("You do not have access to this functionality. Enter an access key to continue.")
if(accessKey){
reqData.accessKey = accessKey;
return await this.req(url, reqData)
} else {
throw "No AccessKey entered"
}
}
return await response.json();
} catch(err){
console.log(err)
return {success: false, error: "Could not connect to server or received invalid response"};
}
}
_isLocalStorageAvailable(){
var test = 'test';
try {
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch(e) {
return false;
}
}
}
var mscp = new MSCP();
mscp.ready = new Promise((resolve, reject)=>{mscp.readyResolve = resolve})
$(function() {
(async () => {
await mscp.init();
mscp.readyResolve();
})()
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:daebf9ab467cf02d6a37c6eef3f9e173f25b03529e3b616a6e5f2bd4e9c666fb
size 3952
|
/** @flow */
export type PositionInfo = {
x: number,
y: number
};
export type ScrollPosition = {
scrollLeft: number,
scrollTop: number
};
export type SizeAndPositionInfo = {
height: number,
width: number,
x: number,
y: number
};
export type SizeInfo = {
height: number,
width: number
};
|
var path = require('path');
var fs = require('fs');
var taskRunner = require('task-nibbler').nibbler;
var glob = require('glob');
var ROOT_DIR = path.resolve(__dirname, '../');
var TERRAFORM_FILE = ROOT_DIR + '/snippets/terraform.json';
function snippetsProcessor(pathToNewJsonSnippetsFile) {
return new Promise(function(resolve, reject) {
try {
var newSnippetsContent = fs.readFileSync(pathToNewJsonSnippetsFile, {encoding: 'utf8'});
newSnippetsContent = newSnippetsContent.substring(newSnippetsContent.indexOf('\n') + 1);
newSnippetsContent = newSnippetsContent.substring(0, newSnippetsContent.lastIndexOf('\n')) + ',';
fs.appendFile(TERRAFORM_FILE, newSnippetsContent, function(error) {
resolve();
});
} catch (e) {
console.log(pathToNewJsonSnippetsFile, e);
reject(e);
}
});
}
function doBuild() {
// @FIXME: temp. solution
var messageFiller = '\n"copyright": { "year": "2017" } \n}';
glob(ROOT_DIR + '/src/**/*.json', function(error, files) {
fs.truncateSync(TERRAFORM_FILE, 0);
fs.appendFileSync(TERRAFORM_FILE, '{\n');
taskRunner(files, snippetsProcessor)
.then(function() {
fs.appendFile(TERRAFORM_FILE, messageFiller);
})
.catch(function(error) {
console.log('[ERROR]', error);
});
});
}
// run json builder
doBuild();
|
import Immutable from 'seamless-immutable';
const initialState = Immutable({
counter: 0,
});
export default (state = initialState, action) => {
switch (action.type) {
case 'INCREASE_COUNTER': {
return state.set('counter', state.counter + 1);
}
default: {
return state;
}
}
};
|
let aToCSV = require('array-to-csv'),
format = require('../lib/format');
module.exports = function formatCSV(data){
let d = format.dataFlatten(data, ' ');
return aToCSV(d);
}
|
/*! DexterJS - v0.5.4 - * https://github.com/leobalter/DexterJS
* Copyright (c) 2014 Leonardo Balter; Licensed MIT, GPL */
(function() {
var Dexter = {
stored: []
},
timerArray = [],
restore, actions,
originalTimeout = setTimeout,
originalInterval = setInterval,
originalClearTimeout = clearTimeout,
originalClearInterval = clearInterval;
restore = function() {
this._seenObj[ this._seenMethod ] = this._oldCall;
this.isActive = false;
};
function setDexterObjs( scope, obj, method ) {
scope._oldCall = obj[ method ];
scope._seenObj = obj;
scope._seenMethod = method;
}
actions = {
'spy': function( that, args ) {
// call order issues
var returned = that._oldCall.apply( this, args );
if ( typeof ( that.callback ) === 'function' ) {
that.callback.apply( this, args );
}
// calls the original method
return returned;
},
'fake': function( that, args ) {
if ( typeof ( that.callback ) === 'function' ) {
return that.callback.apply( this, args );
}
}
};
function DexterObj( action, obj, method, callback ) {
var that = this;
this.called = 0;
this.isActive = true;
if ( typeof ( method ) !== 'string' ) {
throw 'Dexter should receive method name as a String';
}
if ( !obj || typeof ( obj[ method ] ) !== 'function' ) {
throw 'Dexter should receive a valid object and method combination in arguments. Ex.: window & "alert".';
}
if ( typeof ( callback ) === 'function' ) {
this.callback = callback;
}
setDexterObjs( this, obj, method );
obj[ method ] = function() {
var args = [].slice.apply( arguments );
that.called = that.called + 1;
return actions[ action ].call( this, that, args );
};
}
function createDexterObj( name ) {
return function( obj, method, callback ) {
var newObj = new DexterObj( name, obj, method, callback );
Dexter.stored.push( newObj );
return newObj;
};
}
function restoreAll() {
while ( Dexter.stored.length ) {
Dexter.stored.pop().restore();
}
return Dexter.stored.length === 0;
}
DexterObj.prototype = {
restore: restore
};
/* Timer */
function Timer() {
if ( this instanceof Timer ) {
/* jshint -W020 */
setTimeout = fakeSetTimeout;
setInterval = fakeSetInterval;
clearTimeout = fakeClearTimer;
clearInterval = fakeClearTimer;
} else {
return new Timer();
}
}
function fakeSetTimeout( callback, timer ) {
timerArray.push({
cb: callback,
time: timer,
type: 'timeout'
});
return timerArray.length;
}
function fakeSetInterval( callback, timer ) {
timerArray.push({
cb: callback,
time: timer,
type: 'interval',
originalTime: timer
});
return timerArray.length;
}
function fakeClearTimer( timeoutIndex ) {
timerArray.splice( timeoutIndex - 1, 1 );
}
Timer.prototype = {
tick: function( n ) {
var index = 0,
thisTimer;
for (; index < timerArray.length; index++ ) {
thisTimer = timerArray[ index ];
timerArray[ index ].time = thisTimer.time - n;
if ( thisTimer.type === 'timeout' ) {
Timer.prototype.tickTimeout( index );
}
if ( thisTimer.type === 'interval' ) {
Timer.prototype.tickInterval( n, index );
}
}
},
tickTimeout: function( index ) {
var thisTimer = timerArray[ index ];
if ( thisTimer.time <= 0 ) {
Timer.prototype.executeCallback( index );
timerArray.splice( index - 1, 1 );
}
},
tickInterval: function( n, index ) {
var thisTimer = timerArray[ index ],
howManyTimesWillRun = Math.floor(( n / thisTimer.originalTime )) / 1;
if ( thisTimer.time <= 0 ) {
timerArray[ index ].time = ( thisTimer.originalTime - thisTimer.time );
}
while ( howManyTimesWillRun ) {
Timer.prototype.executeCallback( index );
howManyTimesWillRun--;
}
},
executeCallback: function( index ) {
var thisTimer = timerArray[ index ];
if ( typeof thisTimer.cb === 'string' ) {
/* jshint evil:true */
eval( thisTimer.cb );
} else {
thisTimer.cb();
}
},
restore: function() {
/* jshint -W020 */
setTimeout = originalTimeout;
setInterval = originalInterval;
clearInterval = originalClearInterval;
clearTimeout = originalClearTimeout;
this.resetTimers();
},
resetTimers: function() {
timerArray = [];
}
};
Dexter.spy = createDexterObj( 'spy' );
Dexter.fake = createDexterObj( 'fake' );
Dexter.restore = restoreAll;
Dexter.timer = Timer;
if ( typeof module !== 'undefined' && module.exports ) {
// For CommonJS environments, export everything
module.exports = Dexter;
} else if ( typeof define === 'function' && define.amd ) {
// amd Enviroments, client and server side
define( 'dexter', [], function() {
return Dexter;
});
} else if ( typeof window !== 'undefined' ) {
// Old school
window.Dexter = Dexter;
}
})();
(function( globalObj ) {
var Dexter,
statusCodes, unsafeHeaders, fakeXHRObj, CreateFakeXHR,
ajaxObjs = {};
/***
* checks for XHR existence
* returns => XHR fn name || false
***/
ajaxObjs.xhr = (function() {
var xhr;
try {
xhr = new XMLHttpRequest();
return XMLHttpRequest;
} catch ( e ) {
return false;
}
}());
if ( typeof module !== 'undefined' && module.exports ) {
// For CommonJS environments, export everything
module.exports = function() {
return {};
};
return false;
} else if ( ajaxObjs.xhr ) {
if ( typeof define === 'function' && define.amd ) {
// amd Enviroments, client and server side
define( 'fakeXHR', [], function() {
return new CreateFakeXHR();
});
} else {
Dexter = window.Dexter;
Dexter.fakeXHR = function() {
return new CreateFakeXHR();
};
}
}
// Status code and their respective texts
statusCodes = {
100: 'Continue',
101: 'Switching Protocols',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
300: 'Multiple Choice',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
422: 'Unprocessable Entity',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported'
};
// Some headers should be avoided
unsafeHeaders = [
'Accept-Charset',
'Accept-Encoding',
'Connection',
'Content-Length',
'Cookie',
'Cookie2',
'Content-Transfer-Encoding',
'Date',
'Expect',
'Host',
'Keep-Alive',
'Referer',
'TE',
'Trailer',
'Transfer-Encoding',
'Upgrade',
'User-Agent',
'Via'
];
/***
* verifyState helps verifying XHR readyState in cases when that should be
* 1 (Opened) and sendFlag can´t be true. (not yet sent request)
***/
function verifyState( state, sendFlag ) {
if ( state !== 1 || sendFlag ) {
throw new Error( 'INVALID_STATE_ERR' );
}
}
/***
* string to XML parser. Got this from SinonJS that got the same from JSpec
***/
function parseXML( text ) {
var xmlDoc,
parser;
if ( typeof globalObj.DOMParser !== 'undefined' ) {
parser = new globalObj.DOMParser();
xmlDoc = parser.parseFromString( text, 'text/xml' );
} else {
xmlDoc = new ActiveXObject( 'Microsoft.XMLDOM' );
xmlDoc.async = 'false';
xmlDoc.loadXML( text );
}
return xmlDoc;
}
fakeXHRObj = {
// Status constants
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4,
// event handlers
onabort: null,
onerror: null,
onload: null,
onloadend: null,
onloadstart: null,
onprogress: null,
onreadystatechange: null,
ontimeout: null,
// readyState always start by 0
readyState: 0,
// other properties
response: '',
responseText: '',
responseType: '',
responseXML: null,
withCredentials: false,
// status code
status: 0,
// status text relative to the status code
statusText: '',
// timeout to be set, starts by 0
timeout: 0,
/***
* fake .abort
***/
abort: function() {
// reseting properties
this.aborted = true;
this.errorFlag = true;
this.method = null;
this.url = null;
this.async = undefined;
this.username = null;
this.password = null;
this.responseText = null;
this.responseXML = null;
this.requestHeaders = {};
this.sendFlag = false;
// triggering readystatechange
if ( this.readyState > this.UNSENT && this.sendFlag ) {
this.__DexterStateChange( this.DONE );
} else {
this.__DexterStateChange( this.UNSENT );
}
},
/***
* fake .getResponseHeader
***/
getResponseHeader: function( key ) {
var headerName,
responseHeaders = this.responseHeaders;
// no return before receiving headers
if ( this.readyState < this.HEADERS_RECEIVED ) {
return null;
}
// no return for Set-Cookie2
if ( /^Set-Cookie2?$/i.test( key ) ) {
return null;
}
// we manage key finding to different letter cases
key = key.toLowerCase();
for ( headerName in responseHeaders ) {
if ( responseHeaders.hasOwnProperty( headerName ) ) {
// do we have that key?
if ( headerName.toLowerCase() === key ) {
// se we return its value
return responseHeaders[ headerName ];
}
}
}
// no success, return null
return null;
},
/***
* fake .open
***/
open: function( method, url, async, username, password ) {
// method and url aren´t optional
if ( typeof ( method ) === 'undefined' || typeof ( url ) === 'undefined' ) {
throw new Error( 'Not enough arguments' );
}
// setting properties
this.method = method;
this.url = url;
// async default is true, so if async is undefined it is set to true,
// otherwise async get its boolean value
this.async = ( typeof ( async ) === 'undefined' ? true : !!async );
this.username = username;
this.password = password;
// cleaning these properties
this.responseText = null;
this.responseXML = null;
this.requestHeaders = {};
this.sendFlag = false;
// triggering readystatechange with Opened status
this.__DexterStateChange( this.OPENED );
},
/***
* fake .send
***/
send: function( data ) {
var reqHeaders;
// readyState verification (xhr should be already opened)
verifyState( this.readyState, this.sendFlag );
if ( !/^(get|head)$/i.test( this.method ) ) {
if ( this.requestHeaders[ 'Content-Type' ] ) {
reqHeaders = this.requestHeaders[ 'Content-Type' ].split( ';' );
this.requestHeaders[ 'Content-Type' ] = reqHeaders[ 0 ] + ';charset=utf-8';
} else {
this.requestHeaders[ 'Content-Type' ] = 'text/plain;charset=utf-8';
}
this.requestBody = data;
}
// setting properties
this.errorFlag = false;
this.sendFlag = true; // this.async;
// trigger readystatechange with Opened status
this.__DexterStateChange( this.OPENED );
// hummm if think I won´t need this, omg, where´s the specification
if ( typeof ( this.onSend ) === 'function' ) {
this.onSend( this );
}
},
/***
* fake .setRequestHeader
***/
setRequestHeader: function( key, value ) {
// readyState verification (xhr should be already opened)
verifyState( this.readyState, this.sendFlag );
// key shouldn´t be one of the unsafeHeaders neither start with Sec- or
// Proxy-
if ( ( unsafeHeaders.indexOf( key ) >= 0 ) || /^(Sec-|Proxy-)/.test( key ) ) {
throw new Error( 'Refused to set unsafe header "' + key + '"' );
}
if ( this.requestHeaders[ key ] ) {
// if we already have this key set, we concatenate values
this.requestHeaders[ key ] += ',' + value;
} else {
// or we just set key and value
this.requestHeaders[ key ] = value;
}
},
/***
* fake getAllResponseHeaders
***/
getAllResponseHeaders: function() {
var headers = '',
header;
if ( this.readyState < this.HEADERS_RECEIVED ) {
return '';
}
for ( header in this.responseHeaders ) {
if ( this.responseHeaders.hasOwnProperty( header ) && !/^Set-Cookie2?$/i.test( header ) ) {
headers += header + ': ' + this.responseHeaders[ header ] + '\r\n';
}
}
return headers;
},
/***
* __DexterSetResponseHeaders set xhr response headers to make arrangements
* before completing the fake ajax request
***/
__DexterSetResponseHeaders: function( headers ) {
var header;
// reseting response headers
this.responseHeaders = {};
for ( header in headers ) {
if ( headers.hasOwnProperty( header ) ) {
this.responseHeaders[ header ] = headers[ header ];
}
}
// async requests should trigger readystatechange event
if ( this.async ) {
this.__DexterStateChange( this.HEADERS_RECEIVED );
}
},
/***
* __DexterXHR indicates this is a Dexter faked XHR
***/
__DexterXHR: true,
/***
* __DexterStateChange handles events on readyState changes
***/
__DexterStateChange: function( state ) {
var ev;
this.readyState = state;
if ( typeof this.onreadystatechange === 'function' ) {
try {
// dumb event creation. "new Event" just fire errors in webkit engines
ev = document.createEvent( 'Event' );
ev.initEvent( 'readystatechange', false, false );
} catch (e) {
// dammit, IE7!
// TODO: this would break anyone´s code?
ev = {
type: 'readystatechange'
};
}
// the event goes inside an Array
this.onreadystatechange.call( this, [ ev ]);
}
},
/***
* __DexterSetResponseBody builds the response text.
***/
__DexterSetResponseBody: function( body ) {
var chunkSize = this.chunkSize || 10,
index = 0,
type;
this.responseText = '';
if ( this.async ) {
while ( index <= body.length ) {
this.__DexterStateChange( this.LOADING );
this.responseText += body.substring( index, ( index += chunkSize ) );
}
} else {
this.responseText = body;
}
type = this.getResponseHeader( 'Content-Type' ) || '';
if ( body && ( /(text\/xml)|(application\/xml)|(\+xml)/.test( type )) ) {
try {
this.responseXML = parseXML( body );
} catch ( e ) {}
}
},
/***
* __DexterRespond is the call to complete a ajax request
* @params {
* body : string with responseText (Default: '')
* headers : responseHeaders (Default: {})
* status : Number status code (Default: 200)
* }
***/
__DexterRespond: function( params ) {
var body = params.body || '',
headers = params.headers || {},
DONE = this.DONE;
// this should be verified to prevent recalling method
if ( this.readyState === DONE ) {
throw new Error( 'Request already done' );
}
this.__DexterSetResponseHeaders( headers );
this.status = params.status || 200;
this.statusText = statusCodes[ this.status ];
this.__DexterSetResponseBody( body );
// triggers the readystatechange if is an async request
if ( this.async ) {
this.__DexterStateChange( DONE );
} else {
// not being async, just set readyState value
this.readyState = DONE;
}
} /***
* not implemented yet XHR functions
* upload: function() {},
* getInterface: function() {},
* overrideMimeType: function() {},
* sendAsBinary: function() {}
***/
};
/***
* CreateFakeXHR builds the fakeXHR object
* this is a constructor and should be called with 'new'
***/
CreateFakeXHR = function() {
var FakeRequest, fakeObj,
DexterXHR = this;
/***
* requests will contain all requests made on the fakeXHR object´s lifecycle
* doing so, they can be monitored via Dexter.fakeXHR´s instance
***/
this.requests = [];
this.doneRequests = [];
/***
* this is the fake request function to be applied to XMLHttpRequest
***/
FakeRequest = function() {
// creating a reference of xhr object in Dexter.fakeXHR() object
DexterXHR.requests.push( this );
// we set a timeStamp on __DexterRef to identify requests
this.__DexterRef = Date.now();
return this;
};
fakeObj = function() {
FakeRequest.call( this );
};
// we import the fake XHR prototype to both methods
fakeObj.prototype = fakeXHRObj;
globalObj.XMLHttpRequest = fakeObj;
};
/***
* this is the Dexter.fakeXHR prototype, those method will be seen directly on
* its returned object. Not on the XHR itself.
***/
CreateFakeXHR.prototype = {
/***
* interface to export xhr.__DexterRespond and set this.doneRequests
***/
respond: function( params, index ) {
var xhr;
params = params || {};
if ( index ) {
// if index number is set return that indexed element
xhr = this.requests.splice( index, 1 )[ 0 ];
} else {
// else it gets the first request in line
xhr = this.requests.shift();
}
xhr.__DexterRespond( params );
// selected xhr will be seen on doneRequests collection
this.doneRequests.push( xhr );
},
/***
* uses a Dexter.spy on xhr send requests
***/
spy: function( callback ) {
var spy = Dexter.spy( fakeXHRObj, 'send', callback );
// this.__spy will be used on .restore();
this.__spy = spy;
return spy;
},
/***
* restore the XHR objects to their original states, defaking them
* this won´t affect already created fake ajax requests.
***/
restore: function() {
if ( this.__spy ) {
this.__spy.restore();
}
globalObj.XMLHttpRequest = ajaxObjs.xhr;
}
};
// Get a reference to the global object, like window in browsers
}( (function() {
return this;
})() ));
|
var searchData=
[
['zerocalibrate',['zeroCalibrate',['../class_i_t_g3200.html#a184c12df0419953cbeaea27313a35947',1,'ITG3200']]]
];
|
(function () {
'use strict';
angular.module('OpenSlidesApp.openslides_proxyvoting.site', [
'OpenSlidesApp.openslides_proxyvoting'
])
.config([
'mainMenuProvider',
'gettext',
function (mainMenuProvider, gettext) {
mainMenuProvider.register({
'ui_sref': 'openslides_proxyvoting.delegate.list',
'img_class': 'thumbs-o-up',
'title': 'Stimmrechte',
'weight': 510,
'perm': 'openslides_proxyvoting.can_manage'
});
}
])
.config([
'$stateProvider',
function ($stateProvider) {
$stateProvider
.state('openslides_proxyvoting', {
url: '/proxyvoting',
abstract: true,
template: "<ui-view/>"
})
.state('openslides_proxyvoting.delegate', {
abstract: true,
template: "<ui-view/>"
})
.state('openslides_proxyvoting.delegate.list', {
resolve: {
delegates: function (Delegate) {
return Delegate.findAll();
},
users: function (User) {
return User.findAll();
},
categories: function (Category) {
return Category.findAll();
},
keypads: function (Keypad) {
return Keypad.findAll();
},
seats: function (Seat) {
return Seat.findAll();
},
votingProxies: function (VotingProxy) {
return VotingProxy.findAll();
},
votingShares: function (VotingShare) {
return VotingShare.findAll();
}
}
})
.state('openslides_proxyvoting.delegate.import', {
url: '/import',
controller: 'VotingShareImportCtrl',
resolve: {
users: function (User) {
return User.findAll(); // User.find({ groups_id: 2}); // TODO: limit to Delegate group?
},
categories: function (Category) {
return Category.findAll();
},
votingShares: function (VotingShare) {
return VotingShare.findAll();
}
}
})
.state('openslides_proxyvoting.delegate.attendance', {
url: '/attendance',
controller: 'DelegateAttendanceCtrl',
resolve: {
categories: function (Category) {
return Category.findAll();
}
}
})
.state('openslides_proxyvoting.absenteevote', {
url: '/absenteevote',
abstract: true,
template: "<ui-view/>"
})
.state('openslides_proxyvoting.absenteevote.list', {
resolve: {
absenteeVotes: function (AbsenteeVote) {
AbsenteeVote.findAll();
},
users: function (User) {
return User.findAll();
},
motions: function (Motion) {
return Motion.findAll();
}
}
})
.state('openslides_proxyvoting.absenteevote.import', {
url: '/import',
controller: 'AbsenteevoteImportCtrl',
resolve: {
users: function (User) {
return User.findAll();
},
motions: function (Motion) {
return Motion.findAll();
},
absenteeVotes: function (AbsenteeVote) {
return AbsenteeVote.findAll();
}
}
})
// TODO: Add, edit absentee vote.
}
])
// Service for generic delegate form (update only)
.factory('DelegateForm', [
'gettextCatalog',
'User',
'Seat',
function (gettextCatalog, User, Seat) {
return {
getDialog: function (delegate) {
return {
template: 'static/templates/openslides_proxyvoting/delegate-form.html',
controller: 'DelegateUpdateCtrl',
className: 'ngdialog-theme-default',
closeByEscape: false,
closeByDocument: false,
resolve: {
delegate: function () {
return delegate;
}
}
}
},
getFormFields: function (id) {
var otherDelegates = User.filter({
where: {
id: {
'!=': id
},
groups_id : 2
},
orderBy: ['last_name', 'first_name']
});
return [
{
key: 'keypad_id',
type: 'input',
templateOptions: {
label: gettextCatalog.getString('Keypad ID'),
type: 'number',
}
},
{
key: 'seat_id',
type: 'select-single',
templateOptions: {
label: gettextCatalog.getString('Sitznummer'),
options: Seat.filter({ orderBy: 'id' }),
ngOptions: 'option.id as option.number for option in to.options',
placeholder: gettextCatalog.getString('--- Select seat ---')
}
},
{
key: 'is_present',
type: 'checkbox',
templateOptions: {
label: gettextCatalog.getString('Present')
}
},
{
key: 'proxy_id',
type: 'select-single',
templateOptions: {
label: gettextCatalog.getString('Vertreten durch'),
options: otherDelegates,
ngOptions: 'option.id as option.full_name for option in to.options',
placeholder: '(' + gettextCatalog.getString('Keine Vertretung') + ')'
}
},
{
key: 'mandates_id',
type: 'select-multiple',
templateOptions: {
label: gettextCatalog.getString('Vollmachten für'),
options: otherDelegates,
ngOptions: 'option.id as option.full_name for option in to.options',
placeholder: '(' + gettextCatalog.getString('Keine Vollmachten') + ')'
}
}
];
}
}
}
])
.controller('DelegateListCtrl', [
'$scope',
'ngDialog',
'DelegateForm',
'Delegate',
'User',
'Keypad',
'VotingProxy',
'Category',
function ($scope, ngDialog, DelegateForm, Delegate, User, Keypad, VotingProxy, Category) {
Delegate.bindAll({}, $scope, 'delegates');
Category.bindAll({}, $scope, 'categories');
$scope.alert = {};
// Handle table column sorting.
$scope.sortColumn = 'last_name';
$scope.reverse = false;
$scope.toggleSort = function (column) {
if ( $scope.sortColumn === column ) {
$scope.reverse = !$scope.reverse;
}
$scope.sortColumn = column;
};
// Set up pagination.
$scope.currentPage = 1;
$scope.itemsPerPage = 50;
$scope.limitBegin = 0;
$scope.pageChanged = function () {
$scope.limitBegin = ($scope.currentPage - 1) * $scope.itemsPerPage;
};
// Define custom search filter string.
$scope.getFilterString = function (delegate) {
var rep = '', keypad = '', vp = delegate.getProxy();
if (vp) {
rep = vp.rep.full_name;
}
if (delegate.keypad) {
keypad = delegate.keypad.keypad_id;
}
return [
delegate.user.full_name,
rep,
keypad
].join(' ');
};
// Open edit dialog.
$scope.openDialog = function (delegate) {
ngDialog.open(DelegateForm.getDialog(delegate));
};
// Count attending, represented and absent delegates.
$scope.$watch(function () {
return User.lastModified() + Keypad.lastModified() + VotingProxy.lastModified();
}, function () {
$scope.attendingCount = Keypad.filter({ 'user.is_present': true }).length;
$scope.representedCount = VotingProxy.getAll().length;
$scope.absentCount = Math.max(0,
$scope.delegates.length - $scope.attendingCount - $scope.representedCount);
});
}
])
.controller('DelegateUpdateCtrl', [
'$scope',
'$q',
'Delegate',
'User',
'DelegateForm',
'delegate',
function ($scope, $q, Delegate, User, DelegateForm, delegate) {
var kp = delegate.getKeypad(),
vp = delegate.getProxy(),
message,
onFailed = function (error) {
for (var e in error.data) {
message += e + ': ' + error.data[e] + ' ';
}
};
delegate.keypad_id = kp ? kp.keypad_id : null;
delegate.seat_id = kp ? kp.seat_id : null;
delegate.is_present = delegate.user.is_present;
delegate.proxy_id = vp ? vp.proxy_id : null;
delegate.mandates_id = delegate.getMandates().map(function (vp) { return vp.delegate_id });
$scope.alert = {};
$scope.model = delegate;
// Get all form fields.
$scope.formFields = DelegateForm.getFormFields(delegate.id);
$scope.save = function (delegate) {
message = '';
$scope.alert = {};
// Check for circular proxy reference.
if (delegate.mandates_id.indexOf(delegate.proxy_id) >= 0) {
message = User.get(delegate.proxy_id).full_name +
' kann nicht gleichzeitig Vertreter und Vollmachtgeber sein.'
$scope.alert = {type: 'danger', msg: message, show: true};
return;
}
// Update keypad, proxy, mandates, user and collect their promises.
var promises = [];
delegate.updateKeypad(promises, onFailed);
delegate.updateProxy(promises);
delegate.updateMandates(promises);
delegate.user.is_present = delegate.is_present;
promises.push(User.save(delegate.id));
// Wait until all promises have been resolved before closing dialog.
$q.all(promises).then(function () {
if (message) {
$scope.alert = {type: 'danger', msg: message, show: true};
}
else {
$scope.closeThisDialog();
}
});
};
}
])
.controller('DelegateAttendanceCtrl', [
'$scope',
'$http',
'Category',
function ($scope, $http, Category) {
Category.bindAll({}, $scope, 'categories');
$http.get('/proxyvoting/attendance/shares/').then(function (success) {
$scope.attendance = success.data;
});
}
])
.controller('VotingShareImportCtrl', [
'$scope',
'gettext',
'VotingShare',
'User',
'Category',
function ($scope, gettext, VotingShare, User, Category) {
$scope.delegateShares = [];
// Initialize csv settings.
$scope.separator = ',';
$scope.encoding = 'UTF-8';
$scope.encodingOptions = ['UTF-8', 'ISO-8859-1'];
$scope.csv = {
content: null,
header: true,
headerVisible: false,
separator: $scope.separator,
separatorVisible: false,
encoding: $scope.encoding,
encodingVisible: false,
accept: '.csv, .txt',
result: null
};
// Set csv file encoding.
$scope.setEncoding = function () {
$scope.csv.encoding = $scope.encoding;
};
// Set csv separator.
$scope.setSeparator = function () {
$scope.csv.separator = $scope.separator;
};
// Process csv file once it's loaded.
// csv format: number, first_name, last_name, category, shares
$scope.$watch('csv.result', function () {
$scope.delegateShares = [];
var rePattern = /^"(.*)"$/;
angular.forEach($scope.csv.result, function (record) {
var delegateShare = {};
// Get user data removing text separator (double quotes).
if (record.number) {
delegateShare.number = record.number.replace(rePattern, '$1');
}
if (record.first_name) {
delegateShare.first_name = record.first_name.replace(rePattern, '$1');
delegateShare.last_name = '';
}
if (record.last_name) {
delegateShare.last_name = record.last_name.replace(rePattern, '$1');
if (delegateShare.first_name === undefined) {
delegateShare.first_name = '';
}
}
// Validate user: Does user exist in store?
var users = User.filter(delegateShare);
if (users.length == 1) {
delegateShare.delegate_id = users[0].id;
delegateShare.first_name = users[0].first_name;
delegateShare.last_name = users[0].last_name;
}
else {
delegateShare.importerror = true;
delegateShare.user_error = gettext('Error: Delegate not found.');
}
// Get and validate category.
if (record.category) {
delegateShare.category = record.category.replace(rePattern, '$1');
var cats = Category.filter({name: delegateShare.category});
if (cats.length == 1) {
delegateShare.category_id = cats[0].id;
}
else {
delegateShare.importerror = true;
delegateShare.category_error = gettext('Error: Category not found.');
}
}
else {
delegateShare.importerror = true;
delegateShare.category_error = gettext('Error: No category provided.');
}
// Get and validate shares.
if (record.shares) {
delegateShare.shares = record.shares.replace(rePattern, '$1');
if (isNaN(parseFloat(delegateShare.shares))) {
delegateShare.importerror = true;
delegateShare.shares_error = gettext('Error: Not a valid number.');
}
}
else {
delegateShare.importerror = true;
delegateShare.shares_error = gettext('Error: No number provided.');
}
$scope.delegateShares.push(delegateShare);
});
});
// Import validated voting shares.
$scope.import = function () {
$scope.csvImporting = true;
angular.forEach($scope.delegateShares, function (delegateShare) {
if (!delegateShare.importerror) {
var vss = VotingShare.filter({
delegate_id: delegateShare.delegate_id,
category_id: delegateShare.category_id
});
if (vss.length == 1) {
vss[0].shares = delegateShare.shares;
VotingShare.save(vss[0]).then(function (success) {
delegateShare.imported = true;
});
}
else {
VotingShare.create({
delegate_id: delegateShare.delegate_id,
category_id: delegateShare.category_id,
shares: delegateShare.shares
}).then(function (success) {
delegateShare.imported = true;
});
}
}
});
// TODO: only display rows that have not yet been imported
$scope.csvImported = true;
};
// Clear csv import preview.
$scope.clear = function () {
$scope.csv.result = null;
};
}
])
.controller('AbsenteevoteListCtrl', [
'$scope',
'ngDialog',
'AbsenteeVote',
function ($scope, ngDialog, AbsenteeVote) {
AbsenteeVote.bindAll({}, $scope, 'absenteeVotes');
$scope.alert = {};
// Handle table column sorting.
$scope.sortColumn = 'last_name';
$scope.reverse = false;
$scope.toggleSort = function (column) {
if ( $scope.sortColumn === column ) {
$scope.reverse = !$scope.reverse;
}
$scope.sortColumn = column;
};
// Define custom search filter string.
$scope.getFilterString = function (absenteeVote) {
return [
absenteeVote.user.full_name,
absenteeVote.motion_title,
absenteeVote.vote
].join(' ');
};
// Set up pagination.
$scope.currentPage = 1;
$scope.itemsPerPage = 20;
$scope.limitBegin = 0;
$scope.pageChanged = function () {
$scope.limitBegin = ($scope.currentPage - 1) * $scope.itemsPerPage;
};
// *** Delete mode functions. ***
$scope.isDeleteMode = false;
// Update all checkboxes.
$scope.checkAll = function () {
angular.forEach($scope.absenteeVotes, function (absenteeVote) {
absenteeVote.selected = $scope.selectedAll;
});
};
// Uncheck all checkboxes if delete mode is closed.
$scope.uncheckAll = function () {
if (!$scope.isDeleteMode) {
$scope.selectedAll = false;
angular.forEach($scope.absenteeVotes, function (absenteeVote) {
absenteeVote.selected = false;
});
}
};
// Delete selected absentee votes.
$scope.deleteMultiple = function () {
angular.forEach($scope.absenteeVotes, function (absenteeVote) {
if (absenteeVote.selected)
AbsenteeVote.destroy(absenteeVote.id);
});
$scope.isDeleteMode = false;
$scope.uncheckAll();
};
// Delete single absentee vote.
$scope.delete = function (absenteeVote) {
AbsenteeVote.destroy(absenteeVote.id);
};
}
])
.controller('AbsenteevoteImportCtrl', [
'$scope',
'gettext',
'AbsenteeVote',
'User',
'Motion',
function ($scope, gettext, AbsenteeVote, User, Motion) {
$scope.delegateVotes = [];
// Initialize csv settings.
$scope.separator = ',';
$scope.encoding = 'UTF-8';
$scope.encodingOptions = ['UTF-8', 'ISO-8859-1'];
$scope.csv = {
content: null,
header: true,
headerVisible: false,
separator: $scope.separator,
separatorVisible: false,
encoding: $scope.encoding,
encodingVisible: false,
accept: '.csv, .txt',
result: null
};
// Set csv file encoding.
$scope.setEncoding = function () {
$scope.csv.encoding = $scope.encoding;
};
// Set csv separator.
$scope.setSeparator = function () {
$scope.csv.separator = $scope.separator;
};
// Process csv file once it's loaded.
// csv format: number, first_name, last_name, motion, vote
// TODO: Add column motion_identifier.
$scope.$watch('csv.result', function () {
$scope.delegateVotes = [];
var rePattern = /^"(.*)"$/;
angular.forEach($scope.csv.result, function (record) {
var delegateVote = {};
// Get user data removing text separator (double quotes).
if (record.number) {
delegateVote.number = record.number.replace(rePattern, '$1');
}
if (record.first_name) {
delegateVote.first_name = record.first_name.replace(rePattern, '$1');
delegateVote.last_name = '';
}
if (record.last_name) {
delegateVote.last_name = record.last_name.replace(rePattern, '$1');
if (delegateVote.first_name === undefined) {
delegateVote.first_name = '';
}
}
// Validate user: Does user exist in store?
var users = User.filter(delegateVote);
if (users.length == 1) {
delegateVote.delegate_id = users[0].id;
delegateVote.first_name = users[0].first_name;
delegateVote.last_name = users[0].last_name;
}
else {
delegateVote.importerror = true;
delegateVote.user_error = gettext('Error: Delegate not found.');
}
// Get and validate motion.
if (record.motion) {
delegateVote.motion_title = record.motion.replace(rePattern, '$1');
angular.forEach(Motion.getAll(), function (motion) {
if (motion.getTitle() == this.motion_title) {
this.motion_id = motion.id;
}
}, delegateVote);
if (delegateVote.motion_id === undefined) {
delegateVote.importerror = true;
delegateVote.motion_error = gettext('Error: Motion not found.');
}
}
else {
delegateVote.importerror = true;
delegateVote.motion_error = gettext('Error: No motion provided.');
}
// Get and validate vote.
if (record.vote) {
delegateVote.vote = record.vote.replace(rePattern, '$1');
if (['Y', 'N', 'A'].indexOf(delegateVote.vote) == -1) {
delegateVote.importerror = true;
delegateVote.vote_error = gettext('Error: Invalid vote.');
}
}
else {
delegateVote.importerror = true;
delegateVote.vote_error = gettext('Error: No vote provided.');
}
$scope.delegateVotes.push(delegateVote);
});
});
// Import validated absentee votes.
$scope.import = function () {
$scope.csvImporting = true;
angular.forEach($scope.delegateVotes, function (delegateVote) {
if (!delegateVote.importerror) {
var avs = AbsenteeVote.filter({
delegate_id: delegateVote.delegate_id,
motion_id: delegateVote.motion_id
});
if (avs.length == 1) {
avs[0].vote = delegateVote.vote;
AbsenteeVote.save(avs[0]).then(function (success) {
delegateVote.imported = true;
});
}
else {
AbsenteeVote.create({
delegate_id: delegateVote.delegate_id,
motion_id: delegateVote.motion_id,
vote: delegateVote.vote
}).then(function (success) {
delegateVote.imported = true;
});
}
}
});
$scope.csvImported = true;
};
// Clear csv import preview.
$scope.clear = function () {
$scope.csv.result = null;
};
}
])
}());
|
require('dotenv').config();
const http = require('http');
const Bundle = require('bono/bundle');
const AccountingBundle = require('./bundle');
const config = require('./config')();
const PORT = process.env.PORT || 3000;
const app = new Bundle();
app.use(require('bono/middlewares/logger')());
app.bundle('/accounting', new AccountingBundle(config));
app.get('/', ctx => {
ctx.body = { see: '/accounting' };
});
const server = http.Server(app.callback());
server.listen(PORT, () => console.log(`Listening on ${PORT}`));
|
import React, { Component } from 'react';
export default class HowItWorks extends Component {
render() {
return (
<div className="text-slide">
<p>React = (state) => View</p>
<ul>
<li>On every change of state and props re-renders the entire view </li>
<ul>
<li>Doesn't that just kill performance?</li>
<li>Doesn't mess up scrolling?</li>
<li>Doesn't that mean needlessly tearing down and rebuilding DOM?</li>
</ul>
<li>Diffs the current dom to find the minimal change set (Isn't tree-diffing O(n^3)?)</li>
<li>Mutates the DOM using this change set.</li>
</ul>
</div>
);
}
}
|
(function() {
'use strict';
angular
.module('app')
.service('mainService', mainService);
mainService.$inject = ['$q', 'apiUrl', 'wsUrl', '$mdDialog'];
/* @ngInject */
function mainService($q, apiUrl, wsUrl, $mdDialog) {
// Promise-based API
var DEVICE_URL = apiUrl + "device";
var NEW_DEVICE_URL = apiUrl + "newDeviceId";
var ACCESS_RIGHTS_URL = apiUrl + 'accessRight';
var SENSOR_URL = apiUrl + "sensor";
var stompClient = null;
var addMapToDevice = function getMap(device, $scope, show) {
device.map = {
show: show,
control: {},
version: "unknown",
showTraffic: true,
showBicycling: false,
showWeather: false,
showHeat: false,
center: {
latitude: device.location.latitude,
longitude: device.location.longitude
},
options: {
streetViewControl: false,
panControl: false,
maxZoom: 20,
minZoom: 3
},
zoom: 18,
dragging: true,
bounds: {},
clickedMarker: {
id: device.id,
latitude: device.location.latitude,
longitude: device.location.longitude,
options: {
animation: 1,
labelContent: device.name,
labelAnchor: "22 0",
labelClass: "marker-labels"
}
},
events: {
click: function(mapModel, eventName, originalEventArgs) {
var e = originalEventArgs[0];
var latitude = e.latLng.lat(),
longitude = e.latLng.lng();
console.log(latitude);
device.location.latitude = latitude;
device.location.longitude = longitude;
device.map.clickedMarker = {
id: 0,
options: {
labelClass: "marker-labels"
},
latitude: latitude,
longitude: longitude
};
$scope.$evalAsync();
}
}
};
};
function showDialog(text, description) {
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title(text)
.textContent(description)
.ok('Ok')
);
}
function subscribeToSensorTopic(stompClient, $scope, devices) {
stompClient.subscribe('/receiver/accSensor', function(serverResponse) {
var response = JSON.parse(serverResponse.body).content;
var messageFromDispatcher;
try {
messageFromDispatcher = JSON.parse(response);
} catch (e){
console.log("Cannot parse dispatcher JSON: " + response);
return;
}
var dispatcherId = messageFromDispatcher.deviceId;
var deviceIndex = -1;
for (var i = 0; i < devices.length; i++) {
var device = devices[i];
var deviceId = device.id;
if(deviceId == dispatcherId){
deviceIndex = i;
}
}
if(deviceIndex != -1) {
addInfo(messageFromDispatcher.message, $scope, devices[deviceIndex]);
}
});
}
function addInfo(response, $scope, device) {
var d = {
content: 'No data received!'
};
var c = {
content: response
};
if (device.messages.length > 2) {
device.messages.splice(0, 1);
}
if (!response) {
device.messages.push(d);
} else {
device.messages.push(c);
}
$scope.$apply();
}
return {
loadAllDevices: function($http, $scope) {
var getData = function() {
return $http.get(DEVICE_URL).then(function(result) {
var devices = result.data;
if (devices) {
for (var i = 0; i < devices.length; i++) {
var device = devices[i];
device.messages = [];
addMapToDevice(device, $scope, false);
}
}
return devices;
});
};
return {getData: getData};
},
generateNewDeviceId: function($http, type) {
var getData = function() {
var typePrefix = '';
if (type) {
typePrefix = '?type=' + type;
}
return $http.get(NEW_DEVICE_URL + typePrefix).then(function(result) {
var newDeviceId = result.data.content;
return newDeviceId;
});
};
return {getData: getData};
},
loadAccessRights: function($http) {
var getData = function() {
return $http.get(ACCESS_RIGHTS_URL).then(function(result) {
var data = result.data;
return data;
});
};
return {getData: getData};
},
addNewDevice: function($http, device) {
var location;
if (device.location) {
location = {
latitude: device.location.latitude,
longitude: device.location.longitude
};
}
var tags = [];
if (device.tags) {
for (var i = 0; i < device.tags.length; i++) {
var tag = {
name: device.tags[i]
};
tags.push(tag);
}
}
var accessRights = [];
if (device.accessRights) {
for (i = 0; i < device.accessRights.length; i++) {
var accessRight = {
name: device.accessRights[i].name
};
accessRights.push(accessRight);
}
}
var jsonDevice = JSON.stringify({
id: device.id,
type: device.type,
name: device.name,
location: location,
tags: tags,
accessRights: accessRights
});
var getData = function() {
console.log(jsonDevice);
return $http.post(DEVICE_URL, jsonDevice).then(function(result) {
return result.data;
});
};
return {getData: getData};
},
addNewSensor: function($http, sensor, device) {
var metadataArray = [];
if (sensor.metadata) {
for (var i = 0; i < sensor.metadata.length; i++) {
var metadata = {
name: sensor.metadata[i]
};
metadataArray.push(metadata);
}
}
var jsonSensor = JSON.stringify({
type: sensor.type,
name: sensor.name,
metadata: metadataArray,
deviceId: device.id
});
var getData = function() {
console.log(jsonSensor);
return $http.post(SENSOR_URL, jsonSensor).then(function(result) {
return result.data;
});
};
return {getData: getData};
},
deleteDevice: function($http, device) {
var getData = function() {
return $http.delete(DEVICE_URL + '?id=' + device.id).then(function(result) {
return result.data;
});
};
return {getData: getData};
},
addMapToDevice: addMapToDevice,
showDialog: showDialog,
disconnectToDevicesDispatcher: function disconnectToDevicesDispatcher() {
if (stompClient != null) {
stompClient.disconnect();
console.log("Disconnected");
showDialog("Disconnected!");
} else {
showDialog("No need for disconnecting!");
}
},
connectToDevicesDispatcher: function connectToDevicesDispatcher($scope, devices) {
var target = '/iot-dispatcher-websocket';
var socket = new SockJS(wsUrl + target);
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
stompClient.subscribe('/receiver/initDispatcherConnection', function(serverResponse) {
var response = JSON.parse(serverResponse.body).content;
showDialog(response);
});
stompClient.send("/destination/initDispatcherConnection");
subscribeToSensorTopic(stompClient, $scope, devices);
console.log('Connected: ' + frame);
if (!stompClient) {
showDialog("Could not connect to device dispatcher!");
}
});
}
};
}
})();
|
/*
JSPrime v0.1 beta
=================
The MIT License (MIT)
Copyright (c) 2013 Nishant Das Patnaik (nishant.dp@gmail.com)
Copyright (c) 2013 Sarathi Sabyasachi Sahoo (sarathisahoo@gmail.com)
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 source = ["URL","documentURI","URLUnencoded","baseURI","cookie","referrer","location", "localStorage.getItem","sessionStorage.getItem","sessionStorage.key","responseText", "window.name", "websockets.onMessage","load","ajax","url.parse", "get", "val","data","value"];
var sink = ["eval","setTimeout","setInterval","execScript","document.write","document.writeln","innerHTML","href","src","html","after","append","appendTo","before","insertAfter","insertBefore","prepend","prependTo","replaceWith","parseHTML","jQuery","globalEval","appendChild"];
var sinkWithConstantParam = ["eval","globalEval"];
var conditionalSink = [".setAttribute(href|src"];
var positiveSource = ["decodeURIComponent"];
var negativeSource = ["encodeURIComponent", "Y.Escape.html","text"];
var blackList = [];
var blackListObj = [];
var semiBlackList = [];
var semiSource = [];
var redLine = [];
var isXSS = false;
var sourceData = [];
var resultData = [];
var resultColor = [];
var sourceDataOld = [];
var sourceDataToExecute = [];
var isSource = true;
var sinkResultArguments = [];
var sinkResultArgumentsObj = [];
var sourceList = [];
var sourceListObj = [];
var sourceListNames = [];
var convertedFunction = [];
var aOrange = [];
var aOrangeData = "";
var aRedData = "";
var aOtherData = "";
var win;
function analyzeArrays(editorValue) {
//console.log(JSON.stringify(sink));
var sData = editorValue;
sourceDataToExecute = sData.split(/\n\r?/g);
sData = htmlEncode(sData);
sourceData = sData.split(/\n\r?/g);
sourceDataOld = sData.split(/\n\r?/g);
parseJavascriptNativeFunction();
for (var i = 0; i < source.length; i++) {
blackList = [];
blackListObj = [];
isXSS = false;
isSource = true;
checkFunctionsWithDirectSource(source[i]);
checkAsignValue(real_variable_const, source[i], source[i], null);
checkAsignValue(real_variable_var, source[i], source[i], null);
//checkAsignValue(real_variable_obj,source[i],source[i],null);
if (blackList.length > 0) {
checkSink();
}
checkSinkWithDirectSource(source[i]);
}
traverseHighLightsVariable();
//traverseHighLightsObject();
traverseHighLightsFunction();
traverseHighLightsFunctionReturn();
traverseHighLightsVariable();
traverseHighLightsFunction();
traverseHighLightsFunctionReturn();
//traverseHighLightsObject();
removeUnusedSource();
console.log(JSON.stringify(blackList));
writeResult();
}
function htmlEncode(string) {
var HTML_CHARS = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`'
};
return (string + '').replace(/[&<>"'\/`]/g, function (match) {
return HTML_CHARS[match];
});
};
function writeResult() {
var hiddenValues = "<input type='hidden' id='aOrangeData' value='" + aOrangeData + "' />";
hiddenValues += "<input type='hidden' id='aRedData' value='" + aRedData + "' />";
hiddenValues += "<input type='hidden' id='aOtherData' value='" + aOtherData + "' />";
hiddenValues += "<input type='hidden' id='aSink' value='" + sink + "' />";
hiddenValues += "<input type='hidden' id='aSource' value='" + source + "' />";
var resultDiv = document.getElementById('jsprime-output');
resultDiv.innerHTML = resultDiv.innerHTML + hiddenValues;
var resultRow = "";
for (var i = 0; i < resultData.length; i++) {
var redIndex = resultColor.indexOf('red');
if (resultColor[i] == '#FF00FF' && redIndex < i && redIndex != -1) {
var temp = resultColor[i];
resultColor[i] = resultColor[redIndex];
resultColor[redIndex] = temp;
var temp = resultData[i];
resultData[i] = resultData[redIndex];
resultData[redIndex] = temp;
}
}
for (var i = 0; i < resultData.length; i++) {
var aResultData = resultData[i].split('#LINE#');
resultRow = resultRow + '<div class="msg msg-warning" id="">';
resultRow = resultRow + '<h5 style="color:' + resultColor[i] + '">' + getColorTextHeader(resultColor[i]) + '</h5>';
resultRow = resultRow + '<p>' + getColorTextDesc(resultColor[i]) + '</p>';
resultRow += '<div class="context">';
resultRow += '<div class="code">';
resultRow += '<div class="lines">';
resultRow += '<div>' + aResultData[1] + '</div>';
resultRow += '</div><div class="inner-code"><div>';
resultRow += aResultData[0];
resultRow += '</div></div></div></div></div>';
}
document.getElementById('resultRows').innerHTML = resultRow;
}
function doHighlight(color, line) {
if (color == "orange")
aOrangeData += line + ",";
else if (color == "red")
aRedData += line + ",";
else if (color == "#FF00FF" || color == "yellow")
aOtherData += line + ",";
if (resultData.indexOf(sourceDataOld[line - 1] + "#LINE#" + (line)) == -1) {
resultData.push(sourceDataOld[line - 1] + "#LINE#" + (line));
resultColor.push(color);
} else {
resultColor[resultData.indexOf(sourceDataOld[line - 1] + "#LINE#" + (line))] = color;
}
}
function getColorTextHeader(color) {
if (color == "orange")
return 'Active Source';
if (color == "yellow")
return 'Active Variable';
if (color == "grey")
return 'Non-Active Variable';
if (color == "BurlyWood")
return 'Non-Active Source';
if (color == "#FF00FF")
return 'Active Function';
if (color == "red")
return 'Active Sink';
else
return '';
}
function getColorTextDesc(color) {
if (color == "orange")
return 'Active Source is passed which is reached to the sink later';
if (color == "yellow")
return 'Active Source is passed through the variable';
if (color == "grey")
return 'Source is passed through the variable which could not reach to the sink';
if (color == "BurlyWood")
return 'Source that could not reach to the sink';
if (color == "#FF00FF")
return 'Source is passed through the function';
if (color == "red")
return 'XSS Found - Source reached to the sink';
else
return '';
}
function traverseHighLightsVariable() {
for (var i = 0; i < real_variable_var.length; i++) {
for (var j = 0; j < sinkResultArguments.length; j++) {
if (sinkResultArguments[j] == real_variable_var[i].name && sourceListNames.indexOf(sinkResultArguments[j]) == -1) {
if (aOrange.indexOf(real_variable_var[i].line) == -1) {
doHighlight("yellow", real_variable_var[i].line);
}
var args = real_variable_var[i].value.split("+");
var isSink = false;
for (var k = 0; k < args.length; k++) {
if (sinkResultArguments.indexOf(args[k]) == -1) {
isSink = true;
sinkResultArguments.push(args[k]);
sinkResultArgumentsObj.push(real_variable_var[i]);
}
}
if (isSink == true)
traverseHighLightsVariable();
}
}
}
}
function traverseHighLightsFunction() {
for (var i = 0; i < real_func_names.length; i++) {
for (var j = 0; j < sinkResultArguments.length; j++) {
for (var k = 0; k < real_func_names[i].arguments.variables.length; k++) {
if (sinkResultArguments[j] == real_func_names[i].arguments.variables[k]) {
//sinkResultArguments.push(real_func_names[i].name);
//doHighlight("blue",real_func_names[i].line);
traverseHighLightsFunctionCall(real_func_names[i].name, real_func_names[i].arguments.variables[k], k);
}
}
}
}
for (var i = 0; i < real_func_call.length; i++) {
for (var j = 0; j < sinkResultArguments.length; j++) {
for (var k = 0; k < sinkResultArgumentsObj[j].arguments.variables.length; k++) {
if (real_func_call[i].name == sinkResultArgumentsObj[j].arguments.variables[k]) {
if (sinkResultArgumentsObj.indexOf(real_func_call[i]) == -1) {
sinkResultArguments.push(real_func_call[i].name);
sinkResultArgumentsObj.push(real_func_call[i]);
traverseHighLightsFunction();
}
}
}
}
}
}
function traverseHighLightsFunctionCall(funcName, varName, pos) {
for (var i = 0; i < real_func_call.length; i++) {
if (real_func_call[i].name == funcName) {
if (redLine.indexOf(real_func_call[i].line) == -1) {
if (aOrange.indexOf(real_func_call[i].line) == -1) {
doHighlight("#FF00FF", real_func_call[i].line);
}
for (var j = 0; j < convertedFunction.length; j++) {
if (convertedFunction[j].name == real_func_call[i].name && convertedFunction[j].startScope == real_func_call[i].startScope && convertedFunction[j].endScope == real_func_call[i].endScope) {
doHighlight("#FF00FF", convertedFunction[j].line);
traverseConvertedFunction(convertedFunction[j]);
}
}
}
if (sinkResultArguments.indexOf(real_func_call[i].arguments.variables[pos]) == -1) {
sinkResultArguments.push(real_func_call[i].arguments.variables[pos]);
sinkResultArgumentsObj.push(real_func_call[i]);
traverseHighLightsFunction();
}
}
}
}
function traverseConvertedFunction(obj) {
for (var i = 0; i < convertedFunction.length; i++) {
if (obj.value == convertedFunction[i].name && obj.startScope == convertedFunction[i].startScope && obj.endScope == convertedFunction[i].endScope) {
doHighlight("#FF00FF", convertedFunction[i].line);
traverseConvertedFunction(convertedFunction[i]);
}
}
}
function traverseHighLightsFunctionReturn() {
for (var i = 0; i < real_func_names.length; i++) {
for (var k = 0; k < real_func_names[i].returns.variables.length; k++) {
if (real_func_names[i].returns.variables[k] != undefined) {
var returnValue = real_func_names[i].returns.variables[k];
for (var j = 0; j < sinkResultArguments.length; j++) {
if (sinkResultArguments[j] == real_func_names[i].name && sinkResultArguments.indexOf(returnValue) == -1) {
sinkResultArguments.push(returnValue);
sinkResultArgumentsObj.push(real_func_names[i]);
}
}
}
}
}
}
function removeUnusedSource() {
var orangeLine = [];
for (var i = 0; i < sourceList.length; i++) {
var isSink = false;
var line;
var sinkObj = sourceList[i].split("#line#");
line = sinkObj[1];
line = parseInt(line);
for (var j = 0; j < sinkResultArguments.length; j++) {
if (sinkResultArguments[j] == null)
continue;
var aVal = sinkResultArguments[j].split(".");
var sinkVal = "";
for (var k = 0; k < aVal.length; k++) {
if (semiSource.indexOf(aVal[k]) != -1) {
sinkVal = aVal[k];
}
}
if ((sinkResultArguments[j] == sinkObj[0] || sinkVal == sinkObj[0]) && (sinkResultArgumentsObj[j].startScope >= sourceListObj[i].startScope && sinkResultArgumentsObj[j].endScope <= sourceListObj[i].endScope)) {
isSink = true;
} else {
for (var k = 0; k < real_func_names.length; k++) {
if (real_func_names[k].line == sinkResultArgumentsObj[j].startScope) {
for (var t = 0; t < real_func_call.length; t++) {
if (real_func_names[k].name == real_func_call[t].name) {
for (var m = 0; m < sinkResultArgumentsObj.length; m++) {
if (sinkResultArgumentsObj[m].value == real_func_call[t].name && sinkResultArgumentsObj[m].startScope == real_func_call[t].startScope && sinkResultArgumentsObj[m].endScope == real_func_call[t].endScope) {
isSink = true;
break;
}
if (real_func_call[t].arguments.variables.indexOf(sinkResultArgumentsObj[m].name) != -1 && sinkResultArgumentsObj[m].startScope == real_func_call[t].startScope && sinkResultArgumentsObj[m].endScope == real_func_call[t].endScope) {
isSink = true;
break;
}
}
}
if (isSink == true) {
break;
}
}
}
if (isSink == true) {
break;
}
}
}
}
if (isSink == false && redLine.indexOf(line) == -1) {
doHighlight("BurlyWood", line);
} else {
orangeLine.push(line);
}
if (orangeLine.indexOf(line) != -1 && redLine.indexOf(line) == -1) {
doHighlight("orange", line);
}
}
}
function checkAsignValue(obj, source, actualSource, sourceObj) {
for (var i = 0; i < obj.length; i++) {
if (obj[i].value != undefined) {
if (negativeSource.indexOf(obj[i].value) != -1) {
obj[i].negativeSource = 1;
}
if (sourceObj) {
if (sourceObj.negativeSource2 == 1 && positiveSource.indexOf(sourceObj.name) == -1) {
obj[i].negativeSource = 1;
}
}
var multipleValue = obj[i].value.split("+");
var isPass = false;
for (var j = 0; j < multipleValue.length; j++) {
var aVal = multipleValue[j].split(".");
for (var k = 0; k < aVal.length; k++) {
if ((semiSource.indexOf(aVal[k]) != -1 || blackList.indexOf(aVal[k]) != -1) && sourceObj != null) {
semiSource.push(obj[i].name);
isPass = true;
break;
}
}
}
if (obj[i].value.indexOf(actualSource) != -1 || multipleValue.indexOf(source) != -1 || isPass == true) {
var isScope = true;
for (var j = 0; j < multipleValue.length; j++) {
if (multipleValue[j] == source && sourceObj != null) {
if (sourceObj.startScope && obj[i].line) {
if (obj[i].line >= sourceObj.startScope && obj[i].line <= sourceObj.endScope) {
for (var k = i - 1; k >= 0; k--) {
if (obj[k].name == multipleValue[j]) {
if (obj[k] != sourceObj) {
isScope = false;
}
}
}
} else {
isScope = false;
}
if (isScope == true) {
for (var k = 0; k < real_func_names.length; k++) {
if (real_func_names[k].line == obj[i].startScope) {
for (var p = 0; p < real_func_names[k].arguments.variables.length; p++) {
if (real_func_names[k].arguments.variables[p] == multipleValue[j]) {
isScope = false;
for (var m = 0; m < real_func_call.length; m++) {
if (real_func_call[m].name == real_func_names[k].name) {
for (var n = 0; n < real_func_call[m].arguments.variables.length; n++) {
if (blackList.indexOf(real_func_call[m].arguments.variables[n]) != -1) {
isScope = true;
break;
}
}
}
}
}
}
}
}
}
}
}
}
if (isScope == false) {
continue;
}
if (obj[i].value.indexOf(actualSource) != -1) {
isSource = true;
}
if (blackList.indexOf(obj[i].name) == -1) {
blackList.push(obj[i].name);
blackListObj.push(obj[i]);
if (isSource == true) {
doHighlight("orange", obj[i].line);
sourceList.push(obj[i].name + "#line#" + obj[i].line);
sourceListNames.push(obj[i].name);
sourceListObj.push(obj[i]);
semiSource.push(obj[i].name);
} else {
if (aOrange.indexOf(obj[i].line) == -1) {
doHighlight("grey", obj[i].line);
}
}
isSource = false;
checkAsignValue(real_variable_const, obj[i].name, actualSource, obj[i]);
checkAsignValue(real_variable_var, obj[i].name, actualSource, obj[i]);
//checkAsignValue(real_variable_obj,obj[i].name,actualSource,obj[i]);
checkFunctionCallee(obj[i].name, actualSource, obj[i]);
checkFunctionReturnValue(obj[i].name, actualSource, obj[i]);
}
isSource = false;
}
}
}
}
function checkFunctionCallee(val, actualSource, sourceObj) {
for (var i = 0; i < real_func_call.length; i++) {
for (var j = 0; j < real_func_call[i].arguments.variables.length; j++) {
var args = (real_func_call[i].arguments.variables[j] || "").split("+");
for (var k = 0; k < args.length; k++) {
if (args[k] == val) {
checkPassValueToFunction(real_func_call[i].name, args[k], j, actualSource, sourceObj);
if (real_func_call[i - 1]) {
sourceObj.value = real_func_call[i - 1].name;
checkRecursiveFunctionCallee(real_func_call[i - 1], real_func_call[i], actualSource, sourceObj, real_func_call, i);
}
}
}
}
}
}
function checkRecursiveFunctionCallee(func, func2, actualSource, sourceObj, realFunc, pos) {
var doRepeat = false;
for (var j1 = 0; j1 < func.arguments.variables.length; j1++) {
if (func.arguments.variables[j1] != undefined) {
var args2 = func.arguments.variables[j1].split("+");
for (var k1 = 0; k1 < args2.length; k1++) {
var aVal = args2[k1].split(".");
if (aVal[0] == func2.name) {
doRepeat = true;
checkPassValueToFunction(func.name, aVal[0], j1, actualSource, sourceObj);
break;
}
}
}
}
if (doRepeat == true) {
pos--;
if (realFunc[pos - 1]) {
checkRecursiveFunctionCallee(realFunc[pos - 1], realFunc[pos], actualSource, sourceObj, realFunc, pos);
}
}
}
function checkPassValueToFunction(name, val, pos, actualSource, sourceObj) {
for (var i = 0; i < real_func_names.length; i++) {
if (name == real_func_names[i].name) {
if (sourceObj.negativeSource == 1 && positiveSource.indexOf(real_func_names[i].name) == -1) {
real_func_names[i].negativeSource2 = 1;
}
blackList.push(real_func_names[i].arguments.variables[pos]);
blackListObj.push(real_func_names[i]);
//checkAsignValue(real_variable_obj,real_func_names[i].arguments.variables[pos],actualSource,sourceObj);
checkAsignValue(real_variable_var, real_func_names[i].arguments.variables[pos], actualSource, sourceObj);
}
}
}
function checkFunctionReturnValue(val, actualSource, sourceObj) {
for (var i = 0; i < real_func_names.length; i++) {
for (var k = 0; k < real_func_names[i].returns.variables.length; k++) {
var returnValue = "";
if (real_func_names[i].returns.variables[k] != undefined) {
returnValue = real_func_names[i].returns.variables[k];
}
if (returnValue != "") {
aVal = returnValue.split(".");
if (blackList.indexOf(aVal[0]) != -1 && blackList.indexOf(real_func_names[i].name) == -1) {
blackList.push(real_func_names[i].name);
blackListObj.push(real_func_names[i]);
//checkAsignValue(real_variable_obj,real_func_names[i].name,actualSource,real_func_names[i]);
checkAsignValue(real_variable_var, real_func_names[i].name, actualSource, real_func_names[i]);
}
}
}
}
}
function checkSinkWithDirectSource(source) {
for (var i = 0; i < sink.length; i++) {
for (var j = 0; j < real_func_call.length; j++) {
if (real_func_call[j].name.indexOf(sink[i]) != -1) {
for (var k = 0; k < real_func_call[j].arguments.variables.length; k++) {
var args = real_func_call[j].arguments.variables[k].split("+");
for (var l = 0; l < args.length; l++) {
if (args[l].indexOf(source) != -1) {
if (real_func_call[j].startLine) {
for (var lineCount = parseInt(real_func_call[j].startLine); lineCount <= parseInt(real_func_call[j].endLine); lineCount++) {
doHighlight("red", lineCount);
redLine.push(lineCount);
}
} else {
doHighlight("red", real_func_call[j].line);
redLine.push(real_func_call[j].line);
}
isXSS = true;
}
}
}
if (sinkWithConstantParam && (sinkWithConstantParam.indexOf(sink[i]) != -1)) {
for (var k = 0; k < real_func_call[j].arguments.literals.length; k++) {
var args = real_func_call[j].arguments.literals[k].split("+");
for (var l = 0; l < args.length; l++) {
if (args[l].indexOf(source) != -1) {
doHighlight("red", real_func_call[j].line);
redLine.push(real_func_call[j].line);
isXSS = true;
}
}
}
}
}
}
for (var j = 0; j < real_variable_var.length; j++) {
if (real_variable_var[j].name.indexOf(sink[i]) != -1) {
var multipleValue = real_variable_var[j].value.split("+");
for (var k = 0; k < multipleValue.length; k++) {
if (multipleValue[k].indexOf(source) != -1) {
doHighlight("red", real_variable_var[j].line);
redLine.push(real_variable_var[j].line);
sinkResultArguments.push(real_variable_var[j].name);
sinkResultArgumentsObj.push(real_variable_var[j]);
isXSS = true;
}
}
}
}
}
}
function checkFunctionsWithDirectSource(source) {
for (var j = 0; j < real_func_call.length; j++) {
for (var k = 0; k < real_func_call[j].arguments.variables.length; k++) {
var args = (real_func_call[j].arguments.variables[k] || "").split("+");
for (var l = 0; l < args.length; l++) {
if (args[l].indexOf(source) != -1) {
for (var l2 = 0; l2 < real_variable_var.length; l2++) {
if (real_variable_var[l2].line == real_func_call[j].line) {
doHighlight("orange", real_variable_var[l2].line);
aOrange.push(real_variable_var[l2].line);
var newFunction = clone(real_variable_var[l2]);
newFunction.name = args[l];
real_variable_var.push(newFunction);
blackList.push(newFunction.name);
blackListObj.push(newFunction);
sourceList.push(real_variable_var[l2].name + "#line#" + newFunction.line);
sourceListNames.push(newFunction.name);
sourceListObj.push(newFunction);
semiSource.push(newFunction.name);
checkFunctionCallee(newFunction.name, newFunction.name, newFunction);
checkFunctionReturnValue(newFunction.name, newFunction.name, newFunction);
break;
}
}
for (var j1 = 0; j1 < real_func_names.length; j1++) {
if (real_func_names[j1].name == real_func_call[j].name && real_func_names[j1].arguments.variables[l]) {
doHighlight("orange", real_func_call[j].line);
aOrange.push(real_func_call[j].line);
blackList.push(args[l]);
blackListObj.push(real_func_call[j]);
blackList.push(real_func_names[j1].arguments.variables[l]);
blackListObj.push(real_func_call[j]);
break;
}
}
}
checkSourceRecursionInFunction(args[l], real_func_call[j]);
}
}
}
}
function checkSourceRecursionInFunction(funcName, funcCall) {
for (var m = 0; m < real_func_names.length; m++) {
if (funcName == real_func_names[m].name) {
for (var m2 = 0; m2 < real_func_names[m].returns.variables.length; m2++) {
funcCall.arguments.variables.push(real_func_names[m].returns.variables[m2]);
}
for (var m4 = 0; m4 < real_func_call.length; m4++) {
if (funcName == real_func_call[m4].name) {
funcName = real_func_call[m4].arguments.variables[0];
checkSourceRecursionInFunction(funcName, funcCall);
}
}
}
}
}
function checkSink() {
for (var i = 0; i < sink.length; i++) {
for (var j = 0; j < blackList.length; j++) {
checkInFunctionCall(sink[i], blackList[j], blackListObj[j]);
checkInAssignToSink(sink[i], blackList[j], blackListObj[j]);
}
}
for (var i = 0; i < conditionalSink.length; i++) {
for (var j = 0; j < blackList.length; j++) {
checkInFunctionCall(conditionalSink[i], blackList[j], blackListObj[j]);
}
}
}
function checkInFunctionCall(sink, val, sinkObj) {
if (sinkObj.negativeSource == 1 || sinkObj.negativeSource2 == 1) {
return;
}
var conditionalSinkObj = sink.split("(");
sink = conditionalSinkObj[0];
for (var i = 0; i < real_func_call.length; i++) {
if (real_func_call[i].name) {
if (real_func_call[i].name.indexOf(sink) != -1) {
for (var j = 0; j < real_func_call[i].arguments.variables.length; j++) {
var args = real_func_call[i].arguments.variables[j].split("+");
for (var k = 0; k < args.length; k++) {
for (var j1 = 0; j1 < real_func_call.length; j1++) {
if (real_func_call[j1].name == args[k] && real_func_call[j1].line == real_func_call[i].line) {
for (var t = 0; t < real_func_call[j1].returns.variables.length; t++) {
var returnValue = real_func_call[j1].returns.variables[t];
if (blackList.indexOf(returnValue) != -1) {
doHighlight("red", real_func_call[i].line);
redLine.push(real_func_call[i].line);
sinkResultArguments.push(returnValue);
sinkResultArgumentsObj.push(real_func_call[i]);
isXSS = true;
break;
}
}
}
}
if (args[k] == val) {
var isScope = true;
for (var p = 0; p < real_variable_var.length; p++) {
if (real_variable_var[p].line <= real_func_call[i].line && real_variable_var[p].line > sinkObj.line) {
if (real_variable_var[p].name == args[k]) {
var obj = real_variable_var[p].value.split(".");
if (obj[0] != real_variable_var[p].name && blackList.indexOf(obj[0]) == -1) {
isScope = false;
break;
}
}
}
if (sinkObj.name == real_variable_var[p].name) {
if (sinkObj != real_variable_var[p] && !(sinkObj.startScope == real_variable_var[p].startScope && sinkObj.endScope == real_variable_var[p].endScope)) {
isScope = false;
} else {
isScope = true;
}
}
if (real_variable_var[p].line == real_func_call[i].line) {
break;
}
}
if (isScope == true) {
if (real_func_call[i].line > sinkObj.endScope || real_func_call[i].line < sinkObj.startScope) {
isScope = false;
}
}
//if(isScope==true)
//{
for (var t = 0; t < real_func_names.length; t++) {
if (real_func_names[t].line == real_func_call[i].startScope || real_func_names[t].line == (real_func_call[i].startScope - 1)) {
for (var p = 0; p < real_func_names[t].arguments.variables.length; p++) {
if (real_func_names[t].arguments.variables[p] == args[k]) {
isScope = false;
}
}
if (isScope == false) {
for (var p = 0; p < real_func_call.length; p++) {
if (real_func_call[p].name == real_func_names[t].name) {
for (var x = 0; x < real_func_call[p].arguments.variables.length; x++) {
if (blackList.indexOf(real_func_call[p].arguments.variables[x]) != -1) {
isScope = true;
sinkResultArguments.push(real_func_call[p].arguments.variables[x]);
sinkResultArgumentsObj.push(real_func_call[p]);
}
}
}
}
}
if (isScope == true) {
break;
}
}
}
//}
if (isScope == true) {
if (conditionalSinkObj[1]) {
isScope = false;
var expectedValue = conditionalSinkObj[1].split("|");
var params = real_func_call[i].arguments.literals;
for (var e1 = 0; e1 < expectedValue.length; e1++) {
if (params.indexOf(expectedValue[e1]) != -1) {
isScope = true;
break;
}
}
}
}
if (isScope == true) {
doHighlight("red", real_func_call[i].line);
redLine.push(real_func_call[i].line);
sinkResultArguments.push(args[k]);
sinkResultArgumentsObj.push(real_func_call[i]);
isXSS = true;
}
}
}
}
if (sinkWithConstantParam && (sinkWithConstantParam.indexOf(sink) != -1)) {
for (var j = 0; j < real_func_call[i].arguments.literals.length; j++) {
var args = real_func_call[i].arguments.literals[j].split("+");
for (var k = 0; k < args.length; k++) {
if (args[k] == val) {
doHighlight("red", real_func_call[i].line);
redLine.push(real_func_call[i].line);
sinkResultArguments.push(args[k]);
sinkResultArgumentsObj.push(real_func_call[i]);
isXSS = true;
}
}
}
}
}
}
}
}
function checkInAssignToSink(sink, val, sinkObj) {
if (sinkObj.negativeSource == 1 || sinkObj.negativeSource2 == 1) {
return;
}
for (var i = 0; i < real_variable_var.length; i++) {
if (real_variable_var[i].name.indexOf(sink) != -1) {
var multipleValue = real_variable_var[i].value.split("+");
for (var j = 0; j < multipleValue.length; j++) {
if (multipleValue[j] == val) {
var isScope = true;
for (var p = 0; p < real_variable_var.length; p++) {
if (sinkObj.name == real_variable_var[p].name) {
if (real_variable_var[p].line <= real_variable_var[i].line && real_variable_var[p].line > sinkObj.line) {
var obj = real_variable_var[p].value.split(".")
if (obj[0] != real_variable_var[p].name && blackList.indexOf(obj[0]) == -1) {
isScope = false;
break;
}
}
if (sinkObj == real_variable_var[p] && !(sinkObj.startScope == real_variable_var[p].startScope && sinkObj.endScope == real_variable_var[p].endScope)) {
isScope = false;
} else {
sinkResultArguments.push(real_variable_var[p].name);
sinkResultArgumentsObj.push(real_variable_var[p]);
isScope = true;
}
}
if (real_variable_var[p].line == real_variable_var[i].line) {
break;
}
}
if (isScope == true) {
var isScope2 = false;
for (var k = 0; k < real_func_names.length; k++) {
if (real_func_names[k].line == real_variable_var[i].startScope || real_func_names[k].line == (real_variable_var[i].startScope - 1)) {
for (var p = 0; p < real_func_names[k].arguments.variables.length; p++) {
if (real_func_names[k].arguments.variables[p] == multipleValue[j]) {
isScope = false;
}
}
if (isScope == false) {
for (var p = 0; p < real_func_call.length; p++) {
if (real_func_call[p].name == real_func_names[k].name) {
for (var x = 0; x < real_func_call[p].arguments.variables.length; x++) {
if (blackList.indexOf(real_func_call[p].arguments.variables[x]) != -1) {
isScope = true;
isScope2 = true;
sinkResultArguments.push(real_func_call[p].arguments.variables[x]);
sinkResultArgumentsObj.push(real_func_call[p]);
}
}
}
}
}
}
if (isScope2 == true) {
break;
}
}
}
if (isScope == true) {
if (real_variable_var[i].line > sinkObj.endScope || real_variable_var[i].line < sinkObj.startScope) {
isScope = false;
}
}
if (isScope == true) {
doHighlight("red", real_variable_var[i].line);
redLine.push(real_variable_var[i].line);
sinkResultArguments.push(val);
sinkResultArgumentsObj.push(real_variable_var[i]);
isXSS = true;
}
break;
}
}
}
}
}
function parseJavascriptNativeFunction() {
for (var i = 0; i < real_variable_var.length; i++) {
var val = real_variable_var[i].value;
var aVal = val.split(".")
for (var j = 0; j < aVal.length; j++) {
if (aVal[j] == "reverse") {
parseJavascriptNativeFunctionReverse(aVal[0]);
}
}
}
}
function parseJavascriptNativeFunctionReverse(name) {
for (var i = 0; i < real_variable_const.length; i++) {
if (real_variable_const[i].name == name) {
var data = real_variable_const[i].value.split("").reverse().join("");
real_variable_const[i].value = data;
}
}
}
|
var searchData=
[
['ramcost',['RamCost',['../interface_pathfinder_1_1_executable_1_1_i_interface.html#aa68a2b955d6ff745afc3448778ac2c55',1,'Pathfinder::Executable::IInterface']]],
['reader',['Reader',['../class_pathfinder_1_1_event_1_1_load_computer_xml_read_event.html#a4fdbd3e2d8b775425b1f698a568258f9',1,'Pathfinder.Event.LoadComputerXmlReadEvent.Reader()'],['../class_pathfinder_1_1_event_1_1_o_s_load_save_file_event.html#adcae2048c7aa633ad34e57e1f7c6e7ef',1,'Pathfinder.Event.OSLoadSaveFileEvent.Reader()']]],
['rectangle',['Rectangle',['../class_pathfinder_1_1_event_1_1_extension_menu_event.html#a3940943c918e371746a4b45fc4ddaf93',1,'Pathfinder.Event.ExtensionMenuEvent.Rectangle()'],['../class_pathfinder_1_1_g_u_i_1_1_base_interaction.html#a9f9f5bffc48a54c44062d0e13d9a6942',1,'Pathfinder.GUI.BaseInteraction.Rectangle()']]],
['result',['Result',['../class_pathfinder_1_1_event_1_1_executable_execute_event.html#aa93d64b15191fe49c8d2a455ab7d08bb',1,'Pathfinder::Event::ExecutableExecuteEvent']]],
['root',['Root',['../class_pathfinder_1_1_game_filesystem_1_1_file_object.html#a93b08d279b3c7ed1eb7093de98c5c9bf',1,'Pathfinder.GameFilesystem.FileObject.Root()'],['../interface_pathfinder_1_1_game_filesystem_1_1_i_file_object.html#a7c57a2c473d56bc9064da1a1633abee0',1,'Pathfinder.GameFilesystem.IFileObject.Root()']]]
];
|
var redis = require('redis');
var meld = require('meld');
var when = require('when');
var nodefn = require('when/node/function');
var bind = require('lodash.bind');
var uniqueId = require('lodash.uniqueid');
function createCacher(client, query, name, period){
var cacher = meld.around(query, function(methodCall){
// keep these locally since altering than can mess with chaining
var cacheName = name;
var cachePeriod = period;
if(typeof cacheName === 'function'){
cacheName = cacheName.apply(cacheName, methodCall.args);
}
if(typeof cachePeriod === 'function'){
cachePeriod = cachePeriod.apply(cachePeriod, [cacheName].concat(methodCall.args));
}
return client.get(cacheName)
.then(function(data){
/* jshint eqnull: true */
data = JSON.parse(data);
if(data != null){
return data;
}
return methodCall.proceed()
.then(function(data){
client.setEx(cacheName, cachePeriod, JSON.stringify(data));
return data;
});
});
});
cacher.cacheAs = function(name){
return createCacher(client, query, name, period);
};
cacher.cacheFor = function(period){
return createCacher(client, query, name, period);
};
cacher.noCache = function(){
return query;
};
cacher.guarantee = function(resultsLength){
return meld.around(query, function(methodCall){
return methodCall.proceed()
.then(function(result){
if(result.length !== resultsLength){
return when.reject(new Error('Result length not ' + resultsLength));
}
return result;
});
});
};
return cacher;
}
module.exports = cache;
function cache(query, config){
var redisClient = redis.createClient(config.host, config.port, config);
var client = {
get: nodefn.lift(bind(redisClient.get, redisClient)),
setEx: nodefn.lift(bind(redisClient.setex, redisClient))
};
return createCacher(client, query, 'quiche' + uniqueId(), 10);
}
|
"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);
};
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@angular/core");
const allServices_service_1 = require("../../services/allServices.service");
let DataComponent = class DataComponent {
constructor(allServicesService) {
this.allServicesService = allServicesService;
this.output = "";
this.title = "Data";
this.loading = true;
}
ngOnInit() {
this.getAllData();
}
getAllData() {
this.allServicesService.getAllData().subscribe(allData => {
this.data = allData;
this.t = this.data[0].title;
var div = document.getElementById('data-list');
var len = 0;
var con = "";
for (let e of this.data) {
console.log(e.content);
if (e.content.length > 500) {
con = e.content.substring(0, 500) + "...";
}
else {
con = e.content;
}
var date = e.date;
div.innerHTML = div.innerHTML + "<li class='data-entry'><a href='/data/" + e.id + "' class='data-entry-link'><div class='data-entry-container'><h3 class='data-entry-title data-entry-element'>" + e.title + "</h3><h4 class='data-entry-category data-entry-element'>" + date.substring(4, 6) + "/" + date.substring(6, 8) + "/" + date.substring(0, 4) + "</h4><h4 class='data-entry-category data-entry-element'>" + e.category + "</h4><p class='data-entry-content data-entry-element'>" + con + "</p></div></a><hr/></li>";
}
console.log(this.t);
this.loading = false;
}, error => this.errorMessage = error);
}
};
DataComponent = __decorate([
core_1.Component({
selector: 'data',
templateUrl: '../app/components/data/data.html',
styleUrls: ['../app/components/data/data.css'],
encapsulation: core_1.ViewEncapsulation.None,
providers: [
allServices_service_1.AllServicesService
]
}),
__metadata("design:paramtypes", [allServices_service_1.AllServicesService])
], DataComponent);
exports.DataComponent = DataComponent;
//# sourceMappingURL=data.component.js.map
|
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var baseConfig = require('./webpack.config');
var NODE_ENV = process.env.NODE_ENV === 'production' ? 'production' : 'development'
module.exports = Object.assign(baseConfig, {
mode: NODE_ENV,
context: __dirname + '/examples',
devtool: NODE_ENV === 'production' ? false : 'inline-source-map',
devServer: {
port: 3001,
contentBase: './examples',
hot: true,
liveReload: false,
},
entry: ['./index'],
output: {
path: path.join(__dirname, 'dist', 'examples'),
filename: 'bundle.js',
publicPath: '/'
},
plugins: [
...baseConfig.plugins,
new HtmlWebpackPlugin({
template: 'index.html',
inject: false
})
],
externals: [],
resolve: {
alias: {
'react-sticky-el': path.join(__dirname, 'src')
},
modules: [
'node_modules',
path.resolve('./app')
],
extensions: ['.js']
}
});
|
/** @module test-export-20190914020335 */
class _NotExported {
}
/**
*
*/
function _foo() {
}
/**
* Default export with 'module.exports ='.
*/
module.exports = _foo;
/**
* Wrong 'exports.name =' export.
* @type {number}
* @constant
*/
exports.bar = 0;
exports = module.exports
/**
* Good 'exports.name =' export.
* @type {string}
* @constant
*/
exports.baz = "hello";
|
import { Future, resolve, reject } from './Promise'
import CancelToken from './CancelToken'
import Action from './Action'
// -------------------------------------------------------------
// ## Coroutine
// -------------------------------------------------------------
// coroutine :: Generator e a -> (...* -> Promise e a)
// Make a coroutine from a promise-yielding generator
export default function coroutine (generatorFunction) {
return function coroutinified () {
return runGenerator(generatorFunction.apply(this, arguments))
}
}
const stack = []
Object.defineProperty(coroutine, 'cancel', {
get () {
if (!stack.length) throw new SyntaxError('coroutine.cancel is only available inside a coroutine')
return stack[stack.length - 1].getToken()
},
set (token) {
if (!stack.length) throw new SyntaxError('coroutine.cancel is only available inside a coroutine')
token = CancelToken.from(token)
stack[stack.length - 1].setToken(token)
},
configurable: true
})
function runGenerator (generator) {
const swappable = CancelToken.reference(null)
const promise = new Future(swappable.get())
promise._whenToken(new Coroutine(generator, promise, swappable)).run()
// taskQueue.add(new Coroutine(generator, promise, swappable))
return promise
}
class Coroutine extends Action {
constructor (generator, promise, ref) {
super(promise)
// the generator that is driven. Empty after cancellation
this.generator = generator
// a CancelTokenReference
this.tokenref = ref
}
run () {
this.step(this.generator.next, void 0)
}
fulfilled (ref) {
if (this.generator == null) return
this.step(this.generator.next, ref.value)
}
rejected (ref) {
if (this.generator == null) return false
this.step(this.generator.throw, ref.value)
return true
}
cancel (results) {
/* istanbul ignore else */
if (this.promise._isResolved()) { // promise checks for cancellation itself
const res = new Future()
this.promise = new Coroutine(this.generator, res, null) // not cancellable
this.generator = null
this.tokenref = null
if (results) results.push(res)
}
}
cancelled (p) {
const cancelRoutine = this.promise
this.promise = null
const reason = p.near().value
cancelRoutine.step(cancelRoutine.generator.return, reason)
}
step (f, x) {
/* eslint complexity:[2,5] */
let result
stack.push(this)
try {
result = f.call(this.generator, x)
} catch (e) {
result = {value: reject(e), done: true}
} finally {
stack.pop() // assert: === this
}
if (this.generator) { // not cancelled during execution
const res = resolve(result.value, this.promise.token) // TODO optimise token?
if (result.done) {
this.put(res)
} else {
res._runAction(this)
}
}
}
setToken (t) {
if (this.tokenref == null) throw new ReferenceError('coroutine.cancel is only available until cancellation')
this.tokenref.set(t)
}
getToken () {
if (this.tokenref == null) throw new ReferenceError('coroutine.cancel is only available until cancellation')
return this.tokenref.get()
}
}
|
import React from 'react'
import { IndexLink, Link } from 'react-router'
import './HomeView.scss'
const styles = {};
let data = require('../assets/data.json');
class Results3 extends React.Component {
constructor (props) {
super(props);
this.state = {
heroImage: require(`../../../img/${data.results[0].hero}`),
}
}
componentDidMount() {}
componentWillReceiveProps(nextProps) {}
render() {
return(
<div className={'results'}>
<div className="row subheaderbar" >
<em>{data.quizName}</em>
</div>
<div className="r1">
<img src={this.state.heroImage} className="img-responsive img-circle results" />
</div>
<div className="row2">
<h2>Your Car Should be <b>{data.results[2].title}</b></h2>
<Link className="whystate">email my results></Link>
<p className="resultLegend">{data.results[2].text}
<a href="http://www.libertymutual.com/carbuying" >Click here for guaranteed savings</a>
through the Liberty Mutual Car Buying Program.
</p>
</div>
<div className="clearfix"></div>
<div className="col-sm-6">
<p className="text-center lm-blue">
<em>Which Is Right for you:<br />
New or Used?</em>
</p>
<nav aria-label="...">
<ul className="pager">
<li><a href="#"><em>Take this quiz <span className="yellow">></span></em></a></li>
</ul>
</nav>
</div>
<div className="col-sm-6">
<p className="text-center lm-blue">
<em>Which Is Right for You:<br />
Buy or Lease?</em>
</p>
<nav aria-label="...">
<ul className="pager">
<li><a href="#"><em>Take this quiz <span className="yellow">></span></em></a></li>
</ul>
</nav>
</div>
</div>
)
}
}
Results3.contextTypes = {
router: React.PropTypes.object.isRequired
};
export default Results3
|
ElementStore.ZeptoAdapter = {
prototype: {
parseHTML: function parseHTML(html) {
return $(html);
},
querySelector: function querySelector(selector, element) {
return this.returnNative
? $(element || this._root).find(selector)[0]
: $(element || this._root).find(selector).eq(0);
},
querySelectorAll: function querySelectorAll(selector, element) {
return $(element || this._root).find(selector);
}
}
};
ElementStore.include(ElementStore.ZeptoAdapter);
|
import React from 'react'
import BrandGallery from '../components/BrandGallery'
export default () => (
<BrandGallery brand='Pa Concept' />
)
|
var foo=123;
|
/*!
* Retina.js v1.3.0
*
* Copyright 2014 Imulus, LLC
* Released under the MIT license
*
* Retina.js is an open source script that makes it easy to serve
* high-resolution images to devices with retina displays.
*/
(function() {
var root = (typeof exports === 'undefined' ? window : exports);
var config = {
// An option to choose a suffix for 2x images
retinaImageSuffix : '@2x',
// Ensure Content-Type is an image before trying to load @2x image
// https://github.com/imulus/retinajs/pull/45)
check_mime_type: true,
// Resize high-resolution images to original image's pixel dimensions
// https://github.com/imulus/retinajs/issues/8
force_original_dimensions: true
};
function Retina() {}
root.Retina = Retina;
Retina.configure = function(options) {
if (options === null) {
options = {};
}
for (var prop in options) {
if (options.hasOwnProperty(prop)) {
config[prop] = options[prop];
}
}
};
Retina.init = function(context) {
if (context === null) {
context = root;
}
var existing_onload = context.onload || function(){};
context.onload = function() {
var images = document.getElementsByTagName('img'), retinaImages = [], i, image;
for (i = 0; i < images.length; i += 1) {
image = images[i];
var imageSource = image.src,
imageExt = imageSource.substr(imageSource.lastIndexOf('.') + 1);
if (!!!image.getAttributeNode('data-no-retina') && imageExt !== 'svg') {
retinaImages.push(new RetinaImage(image));
}
}
existing_onload();
};
};
Retina.isRetina = function(){
var mediaQuery = '(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)';
if (root.devicePixelRatio > 1) {
return true;
}
if (root.matchMedia && root.matchMedia(mediaQuery).matches) {
return true;
}
return false;
};
var regexMatch = /\.\w+$/;
function suffixReplace (match) {
return config.retinaImageSuffix + match;
}
function RetinaImagePath(path, at_2x_path) {
this.path = path || '';
if (typeof at_2x_path !== 'undefined' && at_2x_path !== null) {
this.at_2x_path = at_2x_path;
this.perform_check = false;
} else {
if (undefined !== document.createElement) {
var locationObject = document.createElement('a');
locationObject.href = this.path;
locationObject.pathname = locationObject.pathname.replace(regexMatch, suffixReplace);
this.at_2x_path = locationObject.href;
} else {
var parts = this.path.split('?');
parts[0] = parts[0].replace(regexMatch, suffixReplace);
this.at_2x_path = parts.join('?');
}
this.perform_check = true;
}
}
root.RetinaImagePath = RetinaImagePath;
RetinaImagePath.confirmed_paths = [];
RetinaImagePath.prototype.is_external = function() {
return !!(this.path.match(/^https?\:/i) && !this.path.match('//' + document.domain) );
};
RetinaImagePath.prototype.check_2x_variant = function(callback) {
var http, that = this;
if (this.is_external()) {
return callback(false);
} else if (!this.perform_check && typeof this.at_2x_path !== 'undefined' && this.at_2x_path !== null) {
return callback(true);
} else if (this.at_2x_path in RetinaImagePath.confirmed_paths) {
return callback(true);
} else {
http = new XMLHttpRequest();
http.open('HEAD', this.at_2x_path);
http.onreadystatechange = function() {
if (http.readyState !== 4) {
return callback(false);
}
if (http.status >= 200 && http.status <= 399) {
if (config.check_mime_type) {
var type = http.getResponseHeader('Content-Type');
if (type === null || !type.match(/^image/i)) {
return callback(false);
}
}
RetinaImagePath.confirmed_paths.push(that.at_2x_path);
return callback(true);
} else {
return callback(false);
}
};
http.send();
}
};
function RetinaImage(el) {
this.el = el;
this.path = new RetinaImagePath(this.el.getAttribute('src'), this.el.getAttribute('data-at2x'));
var that = this;
this.path.check_2x_variant(function(hasVariant) {
if (hasVariant) {
that.swap();
}
});
}
root.RetinaImage = RetinaImage;
RetinaImage.prototype.swap = function(path) {
if (typeof path === 'undefined') {
path = this.path.at_2x_path;
}
var that = this;
function load() {
if (! that.el.complete) {
setTimeout(load, 5);
} else {
if (config.force_original_dimensions) {
if (that.el.offsetWidth && that.el.offsetHeight) {
that.el.setAttribute('width', that.el.offsetWidth);
that.el.setAttribute('height', that.el.offsetHeight);
}
else {
that.el.setAttribute('width', that.el.naturalWidth);
that.el.setAttribute('height', that.el.naturalHeight);
}
}
that.el.setAttribute('src', path);
}
}
load();
};
if (Retina.isRetina()) {
Retina.init(root);
}
})();
|
'use strict';
angular.module('bucleApp.core')
.service('Cc', [
'CC',
function (CC) {
return {
get: function (type) {
var license = CC.filter( function(obkLicense) {
return obkLicense.type == type;
});
return license[0];
}
}
}
]);
|
// bgmusic.js
bgmusic = {
setup: function(){
this.songStack = [];
this.playing = '';
},
play: function(song, volume, currentTime) {
volume = (typeof volume === "undefined") ? 0.7 : volume;
currentTime = (typeof currentTime === "undefined") ? 0 : currentTime;
if(!(song in resources.music))
return
var playSong = (function(that,song, volume, currentTime){
return function() {
that.playing = song;
resources.music[song].volume = volume;
resources.music[song].currentTime = currentTime;
resources.music[song].play();
}
})(this,song, volume, currentTime);
if(this.playing != song){
if(this.playing in resources.music){
resources.music[this.playing].pause();
//setTimeout will help with race conditions
//needed for Firefox Mobile
setTimeout(playSong,150)
} else {
setTimeout(playSong,150)
}
}
},
changeVolume: function(volume){
if(this.playing in resources.music){
resources.music[this.playing].setVolume(volume);
}
},
pushSong: function(){
var song = this.playing;
this.songStack.push({ song: song,
volume: resources.music[song].volume,
currentTime: resources.music[song].currentTime,
});
},
popSong: function(){
var sp = this.songStack.pop();
this.play(sp.song, sp.volume, sp.currentTime)
}
}
|
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import OrganizationExplorer from './organization-explorer';
import OrganizationDetails from './organization-details';
import NotFound from '../not-found'
import { connector as organizationListConnector } from './organization-explorer'
export const organizationLink = organizationURI => {
const orgId = organizationURI.split('/').pop()
return `/organisations/${orgId}`
}
const OrganizationDetailsSmart = organizationListConnector(function (props) {
const { organizations, match: { params: { organization: orgId } } } = props
const candidate = organizations.find(({ organization }) => organization.endsWith(orgId))
if (candidate) {
return <OrganizationDetails organization={candidate.organization} />
}
return <UnknownOrganization orgId={orgId} />
})
function UnknownOrganization({ orgId }) {
const message = `No organization matching the provided id \`${orgId}\``
return <NotFound message={message} />
}
export default (
<Route path="/organisations">
<Switch>
<Route exact path="/organisations" component={OrganizationExplorer} />
<Route
path="/organisations/:organization"
component={OrganizationDetailsSmart}
/>
</Switch>
</Route>
);
|
var path = require('path');
var fs = require('fs');
var os = require('os');
var hrobj = require('../build/Release/hcaptha.node');
var dir = require('./dir.js');
var timer = require('./timer.js');
var gen_func = require('./gen.js');
//ccap.create("abcdef","/usr/local/nodejs/hcaptha/test.jpeg",6,256,40,40,50);
/*
CAP类支持3种实例化
1、CAP(),完全使用默认
2、CAP(width,height,offset)
3、CAP({
width:256,
height:40,
offset:40,
generate:function(){//自定义生成随机数
this.width;
this.height;
return "abcdefg";
}
})
*/
var ins_count = 0;//记录实例化次数
var img_path = path.join(__dirname,'../../../','/public/cap_img');
var pid = process.pid;
var isjpeg = (os.platform() == 'linux')? 1 : 0;//判断是否启用jpeg,如果是为win32则只能使用bmp
var fname = isjpeg ? '.jpeg':'.bmp'
var CAP = function(args){
if(!(this instanceof arguments.callee)) return new arguments.callee(args);
//this.filename = img_path+'/captcha_'+ins_count+'_'+pid+'_{$number}'+fname;
this.filename = img_path+'/captcha_'+fname;
this.width = 256;//默认验证码宽度
this.height = 60;//默认验证码高度
this.offset = 40;//默认验证码字符间隔
this.quality = 50;//默认图片质量
this._text_len = 6;//默认验证码字数
this.generate = null;//自定义生成随机字符串方法
this.fontsize = 57; //默认字体大小
this.is_first = true;
this._cache_num = 1;//默认缓存5个验证码
this.buf = [];//缓存数组
this.text_buf = [];//定义字符串内容数组
this._init(args);//构造函数
this._create = this.generate ? this._custom_create : this._default_create;
this._create();
this.is_first = false;
}
CAP.prototype._init = function(args){
if(arguments.length<1) return;//如果不传参数,则全部使用默认值
if(typeof arguments[0] === 'object'){//如果传递了对象,则替换默认值
var obj = arguments[0];
this.width = obj.width || this.width;
this.height = obj.height || this.height;
this.offset = obj.offset || this.offset;
this.quality = obj.quality || this.quality;
this.generate = obj.generate || null;
this.fontsize = obj.fontsize || this.fontsize;
return;
}
//如果只传递了宽,高,间隔则替换默认值
this.width = arguments[0] || this.width;
this.height = arguments[1] || this.height;
this.offset = arguments[2] || this.offset;
this._get_count = 0;
return this;
}
CAP.prototype._default_generate = gen_func; //设置默认验证码生成函数
CAP.prototype._call_create = function(text,len,j){//调用C++的CIMG库的create函数生成验证码文件
var that = this;
var filepath = that.filename.replace('{$number}',j);
hrobj.create(text, filepath, len, that.width, that.height, that.offset, that.quality,isjpeg,that.fontsize);
if(this.is_first){
try{
var buffer = fs.readFileSync(filepath);
}catch(e){
console.log('readsync file error');
}
that.buf[j] = buffer;
that.text_buf[j] = text;
return this;
}
fs.readFile(filepath, function(err,data){
if(err) return console.log('read file error');
that.buf[j] = data;
that.text_buf[j] = text;
});
return this;
}
CAP.prototype._default_create = function(){//默认方式创建
for(var i=0;i<this._cache_num;i++){
this._call_create(this._default_generate(), this._text_len, i)
}
return this;
}
CAP.prototype._custom_create = function(){//自定义创建
for(var i=0;i<this._cache_num;i++){
var str = this.generate();
this._call_create(str, str.length,i);
}
return this;
}
CAP.prototype._timer = function(){//存入计数器的函数
this._get_count++;//记录timer调用次数
this._create();
}
CAP.prototype.get = function(){//对外接口,返回验证码和字母
var num = Math.floor(Math.random()*this._cache_num);//生成随机数
return [this.text_buf[num], this.buf[num]];//返回字母和buffer给用户
}
module.exports = function(args){
var cap = CAP(args);
ins_count++;
timer.reg_ary.push(cap);//将实例化之后的对象注册到timer定时器中
return cap;
};
dir();//设置路径权限,清空历史文件夹
timer.loop();//启动计时器
|
// Compiled by ClojureScript 1.9.293 {}
goog.provide('cljs.reader');
goog.require('cljs.core');
goog.require('goog.string');
goog.require('goog.string.StringBuffer');
/**
* @interface
*/
cljs.reader.PushbackReader = function(){};
/**
* Returns the next char from the Reader,
* nil if the end of stream has been reached
*/
cljs.reader.read_char = (function cljs$reader$read_char(reader){
if((!((reader == null))) && (!((reader.cljs$reader$PushbackReader$read_char$arity$1 == null)))){
return reader.cljs$reader$PushbackReader$read_char$arity$1(reader);
} else {
var x__54434__auto__ = (((reader == null))?null:reader);
var m__54435__auto__ = (cljs.reader.read_char[goog.typeOf(x__54434__auto__)]);
if(!((m__54435__auto__ == null))){
return m__54435__auto__.call(null,reader);
} else {
var m__54435__auto____$1 = (cljs.reader.read_char["_"]);
if(!((m__54435__auto____$1 == null))){
return m__54435__auto____$1.call(null,reader);
} else {
throw cljs.core.missing_protocol.call(null,"PushbackReader.read-char",reader);
}
}
}
});
/**
* Push back a single character on to the stream
*/
cljs.reader.unread = (function cljs$reader$unread(reader,ch){
if((!((reader == null))) && (!((reader.cljs$reader$PushbackReader$unread$arity$2 == null)))){
return reader.cljs$reader$PushbackReader$unread$arity$2(reader,ch);
} else {
var x__54434__auto__ = (((reader == null))?null:reader);
var m__54435__auto__ = (cljs.reader.unread[goog.typeOf(x__54434__auto__)]);
if(!((m__54435__auto__ == null))){
return m__54435__auto__.call(null,reader,ch);
} else {
var m__54435__auto____$1 = (cljs.reader.unread["_"]);
if(!((m__54435__auto____$1 == null))){
return m__54435__auto____$1.call(null,reader,ch);
} else {
throw cljs.core.missing_protocol.call(null,"PushbackReader.unread",reader);
}
}
}
});
/**
* @constructor
* @implements {cljs.reader.PushbackReader}
*/
cljs.reader.StringPushbackReader = (function (s,buffer,idx){
this.s = s;
this.buffer = buffer;
this.idx = idx;
})
cljs.reader.StringPushbackReader.prototype.cljs$reader$PushbackReader$ = cljs.core.PROTOCOL_SENTINEL;
cljs.reader.StringPushbackReader.prototype.cljs$reader$PushbackReader$read_char$arity$1 = (function (reader){
var self__ = this;
var reader__$1 = this;
if((self__.buffer.length === (0))){
self__.idx = (self__.idx + (1));
return (self__.s[self__.idx]);
} else {
return self__.buffer.pop();
}
});
cljs.reader.StringPushbackReader.prototype.cljs$reader$PushbackReader$unread$arity$2 = (function (reader,ch){
var self__ = this;
var reader__$1 = this;
return self__.buffer.push(ch);
});
cljs.reader.StringPushbackReader.getBasis = (function (){
return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Symbol(null,"s","s",-948495851,null),new cljs.core.Symbol(null,"buffer","buffer",-2037140571,null),cljs.core.with_meta(new cljs.core.Symbol(null,"idx","idx",-1600747296,null),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"mutable","mutable",875778266),true], null))], null);
});
cljs.reader.StringPushbackReader.cljs$lang$type = true;
cljs.reader.StringPushbackReader.cljs$lang$ctorStr = "cljs.reader/StringPushbackReader";
cljs.reader.StringPushbackReader.cljs$lang$ctorPrWriter = (function (this__54377__auto__,writer__54378__auto__,opt__54379__auto__){
return cljs.core._write.call(null,writer__54378__auto__,"cljs.reader/StringPushbackReader");
});
cljs.reader.__GT_StringPushbackReader = (function cljs$reader$__GT_StringPushbackReader(s,buffer,idx){
return (new cljs.reader.StringPushbackReader(s,buffer,idx));
});
cljs.reader.push_back_reader = (function cljs$reader$push_back_reader(s){
return (new cljs.reader.StringPushbackReader(s,[],(-1)));
});
/**
* Checks whether a given character is whitespace
*/
cljs.reader.whitespace_QMARK_ = (function cljs$reader$whitespace_QMARK_(ch){
var or__53771__auto__ = goog.string.isBreakingWhitespace(ch);
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return ("," === ch);
}
});
/**
* Checks whether a given character is numeric
*/
cljs.reader.numeric_QMARK_ = (function cljs$reader$numeric_QMARK_(ch){
return goog.string.isNumeric(ch);
});
/**
* Checks whether the character begins a comment.
*/
cljs.reader.comment_prefix_QMARK_ = (function cljs$reader$comment_prefix_QMARK_(ch){
return (";" === ch);
});
/**
* Checks whether the reader is at the start of a number literal
*/
cljs.reader.number_literal_QMARK_ = (function cljs$reader$number_literal_QMARK_(reader,initch){
return (cljs.reader.numeric_QMARK_.call(null,initch)) || (((("+" === initch)) || (("-" === initch))) && (cljs.reader.numeric_QMARK_.call(null,(function (){var next_ch = cljs.reader.read_char.call(null,reader);
cljs.reader.unread.call(null,reader,next_ch);
return next_ch;
})())));
});
cljs.reader.reader_error = (function cljs$reader$reader_error(var_args){
var args__54886__auto__ = [];
var len__54879__auto___60085 = arguments.length;
var i__54880__auto___60086 = (0);
while(true){
if((i__54880__auto___60086 < len__54879__auto___60085)){
args__54886__auto__.push((arguments[i__54880__auto___60086]));
var G__60087 = (i__54880__auto___60086 + (1));
i__54880__auto___60086 = G__60087;
continue;
} else {
}
break;
}
var argseq__54887__auto__ = ((((1) < args__54886__auto__.length))?(new cljs.core.IndexedSeq(args__54886__auto__.slice((1)),(0),null)):null);
return cljs.reader.reader_error.cljs$core$IFn$_invoke$arity$variadic((arguments[(0)]),argseq__54887__auto__);
});
cljs.reader.reader_error.cljs$core$IFn$_invoke$arity$variadic = (function (rdr,msg){
throw (new Error(cljs.core.apply.call(null,cljs.core.str,msg)));
});
cljs.reader.reader_error.cljs$lang$maxFixedArity = (1);
cljs.reader.reader_error.cljs$lang$applyTo = (function (seq60083){
var G__60084 = cljs.core.first.call(null,seq60083);
var seq60083__$1 = cljs.core.next.call(null,seq60083);
return cljs.reader.reader_error.cljs$core$IFn$_invoke$arity$variadic(G__60084,seq60083__$1);
});
cljs.reader.macro_terminating_QMARK_ = (function cljs$reader$macro_terminating_QMARK_(ch){
var and__53759__auto__ = !((ch === "#"));
if(and__53759__auto__){
var and__53759__auto____$1 = !((ch === "'"));
if(and__53759__auto____$1){
var and__53759__auto____$2 = !((ch === ":"));
if(and__53759__auto____$2){
return cljs.reader.macros.call(null,ch);
} else {
return and__53759__auto____$2;
}
} else {
return and__53759__auto____$1;
}
} else {
return and__53759__auto__;
}
});
cljs.reader.read_token = (function cljs$reader$read_token(rdr,initch){
var sb = (new goog.string.StringBuffer(initch));
var ch = cljs.reader.read_char.call(null,rdr);
while(true){
if(((ch == null)) || (cljs.reader.whitespace_QMARK_.call(null,ch)) || (cljs.reader.macro_terminating_QMARK_.call(null,ch))){
cljs.reader.unread.call(null,rdr,ch);
return sb.toString();
} else {
var G__60088 = (function (){
sb.append(ch);
return sb;
})()
;
var G__60089 = cljs.reader.read_char.call(null,rdr);
sb = G__60088;
ch = G__60089;
continue;
}
break;
}
});
/**
* Advances the reader to the end of a line. Returns the reader
*/
cljs.reader.skip_line = (function cljs$reader$skip_line(reader,_){
while(true){
var ch = cljs.reader.read_char.call(null,reader);
if(((ch === "\n")) || ((ch === "\r")) || ((ch == null))){
return reader;
} else {
continue;
}
break;
}
});
cljs.reader.int_pattern = cljs.core.re_pattern.call(null,"^([-+]?)(?:(0)|([1-9][0-9]*)|0[xX]([0-9A-Fa-f]+)|0([0-7]+)|([1-9][0-9]?)[rR]([0-9A-Za-z]+))(N)?$");
cljs.reader.ratio_pattern = cljs.core.re_pattern.call(null,"^([-+]?[0-9]+)/([0-9]+)$");
cljs.reader.float_pattern = cljs.core.re_pattern.call(null,"^([-+]?[0-9]+(\\.[0-9]*)?([eE][-+]?[0-9]+)?)(M)?$");
cljs.reader.symbol_pattern = cljs.core.re_pattern.call(null,"^[:]?([^0-9/].*/)?([^0-9/][^/]*)$");
cljs.reader.re_matches_STAR_ = (function cljs$reader$re_matches_STAR_(re,s){
var matches = re.exec(s);
if((!((matches == null))) && (((matches[(0)]) === s))){
if((matches.length === (1))){
return (matches[(0)]);
} else {
return matches;
}
} else {
return null;
}
});
cljs.reader.match_int = (function cljs$reader$match_int(s){
var groups = cljs.reader.re_matches_STAR_.call(null,cljs.reader.int_pattern,s);
var ie8_fix = (groups[(2)]);
var zero = ((cljs.core._EQ_.call(null,ie8_fix,""))?null:ie8_fix);
if(!((zero == null))){
return (0);
} else {
var a = (cljs.core.truth_((groups[(3)]))?[(groups[(3)]),(10)]:(cljs.core.truth_((groups[(4)]))?[(groups[(4)]),(16)]:(cljs.core.truth_((groups[(5)]))?[(groups[(5)]),(8)]:(cljs.core.truth_((groups[(6)]))?[(groups[(7)]),parseInt((groups[(6)]),(10))]:[null,null]
))));
var n = (a[(0)]);
var radix = (a[(1)]);
if((n == null)){
return null;
} else {
var parsed = parseInt(n,radix);
if(("-" === (groups[(1)]))){
return (- parsed);
} else {
return parsed;
}
}
}
});
cljs.reader.match_ratio = (function cljs$reader$match_ratio(s){
var groups = cljs.reader.re_matches_STAR_.call(null,cljs.reader.ratio_pattern,s);
var numinator = (groups[(1)]);
var denominator = (groups[(2)]);
return (parseInt(numinator,(10)) / parseInt(denominator,(10)));
});
cljs.reader.match_float = (function cljs$reader$match_float(s){
return parseFloat(s);
});
cljs.reader.match_number = (function cljs$reader$match_number(s){
if(cljs.core.truth_(cljs.reader.re_matches_STAR_.call(null,cljs.reader.int_pattern,s))){
return cljs.reader.match_int.call(null,s);
} else {
if(cljs.core.truth_(cljs.reader.re_matches_STAR_.call(null,cljs.reader.ratio_pattern,s))){
return cljs.reader.match_ratio.call(null,s);
} else {
if(cljs.core.truth_(cljs.reader.re_matches_STAR_.call(null,cljs.reader.float_pattern,s))){
return cljs.reader.match_float.call(null,s);
} else {
return null;
}
}
}
});
cljs.reader.escape_char_map = (function cljs$reader$escape_char_map(c){
if((c === "t")){
return "\t";
} else {
if((c === "r")){
return "\r";
} else {
if((c === "n")){
return "\n";
} else {
if((c === "\\")){
return "\\";
} else {
if((c === "\"")){
return "\"";
} else {
if((c === "b")){
return "\b";
} else {
if((c === "f")){
return "\f";
} else {
return null;
}
}
}
}
}
}
}
});
cljs.reader.read_2_chars = (function cljs$reader$read_2_chars(reader){
return (new goog.string.StringBuffer(cljs.reader.read_char.call(null,reader),cljs.reader.read_char.call(null,reader))).toString();
});
cljs.reader.read_4_chars = (function cljs$reader$read_4_chars(reader){
return (new goog.string.StringBuffer(cljs.reader.read_char.call(null,reader),cljs.reader.read_char.call(null,reader),cljs.reader.read_char.call(null,reader),cljs.reader.read_char.call(null,reader))).toString();
});
cljs.reader.unicode_2_pattern = cljs.core.re_pattern.call(null,"^[0-9A-Fa-f]{2}$");
cljs.reader.unicode_4_pattern = cljs.core.re_pattern.call(null,"^[0-9A-Fa-f]{4}$");
cljs.reader.validate_unicode_escape = (function cljs$reader$validate_unicode_escape(unicode_pattern,reader,escape_char,unicode_str){
if(cljs.core.truth_(cljs.core.re_matches.call(null,unicode_pattern,unicode_str))){
return unicode_str;
} else {
return cljs.reader.reader_error.call(null,reader,"Unexpected unicode escape \\",escape_char,unicode_str);
}
});
cljs.reader.make_unicode_char = (function cljs$reader$make_unicode_char(code_str){
var code = parseInt(code_str,(16));
return String.fromCharCode(code);
});
cljs.reader.escape_char = (function cljs$reader$escape_char(buffer,reader){
var ch = cljs.reader.read_char.call(null,reader);
var mapresult = cljs.reader.escape_char_map.call(null,ch);
if(cljs.core.truth_(mapresult)){
return mapresult;
} else {
if((ch === "x")){
return cljs.reader.make_unicode_char.call(null,cljs.reader.validate_unicode_escape.call(null,cljs.reader.unicode_2_pattern,reader,ch,cljs.reader.read_2_chars.call(null,reader)));
} else {
if((ch === "u")){
return cljs.reader.make_unicode_char.call(null,cljs.reader.validate_unicode_escape.call(null,cljs.reader.unicode_4_pattern,reader,ch,cljs.reader.read_4_chars.call(null,reader)));
} else {
if(cljs.reader.numeric_QMARK_.call(null,ch)){
return String.fromCharCode(ch);
} else {
return cljs.reader.reader_error.call(null,reader,"Unexpected unicode escape \\",ch);
}
}
}
}
});
/**
* Read until first character that doesn't match pred, returning
* char.
*/
cljs.reader.read_past = (function cljs$reader$read_past(pred,rdr){
var ch = cljs.reader.read_char.call(null,rdr);
while(true){
if(cljs.core.truth_(pred.call(null,ch))){
var G__60090 = cljs.reader.read_char.call(null,rdr);
ch = G__60090;
continue;
} else {
return ch;
}
break;
}
});
cljs.reader.read_delimited_list = (function cljs$reader$read_delimited_list(delim,rdr,recursive_QMARK_){
var a = [];
while(true){
var ch = cljs.reader.read_past.call(null,cljs.reader.whitespace_QMARK_,rdr);
if(cljs.core.truth_(ch)){
} else {
cljs.reader.reader_error.call(null,rdr,"EOF while reading");
}
if((delim === ch)){
return a;
} else {
var temp__4655__auto__ = cljs.reader.macros.call(null,ch);
if(cljs.core.truth_(temp__4655__auto__)){
var macrofn = temp__4655__auto__;
var mret = macrofn.call(null,rdr,ch);
var G__60091 = (((mret === rdr))?a:(function (){
a.push(mret);
return a;
})()
);
a = G__60091;
continue;
} else {
cljs.reader.unread.call(null,rdr,ch);
var o = cljs.reader.read.call(null,rdr,true,null,recursive_QMARK_);
var G__60092 = (((o === rdr))?a:(function (){
a.push(o);
return a;
})()
);
a = G__60092;
continue;
}
}
break;
}
});
cljs.reader.not_implemented = (function cljs$reader$not_implemented(rdr,ch){
return cljs.reader.reader_error.call(null,rdr,"Reader for ",ch," not implemented yet");
});
cljs.reader.read_dispatch = (function cljs$reader$read_dispatch(rdr,_){
var ch = cljs.reader.read_char.call(null,rdr);
var dm = cljs.reader.dispatch_macros.call(null,ch);
if(cljs.core.truth_(dm)){
return dm.call(null,rdr,_);
} else {
var temp__4655__auto__ = cljs.reader.maybe_read_tagged_type.call(null,rdr,ch);
if(cljs.core.truth_(temp__4655__auto__)){
var obj = temp__4655__auto__;
return obj;
} else {
return cljs.reader.reader_error.call(null,rdr,"No dispatch macro for ",ch);
}
}
});
cljs.reader.read_unmatched_delimiter = (function cljs$reader$read_unmatched_delimiter(rdr,ch){
return cljs.reader.reader_error.call(null,rdr,"Unmatched delimiter ",ch);
});
cljs.reader.read_list = (function cljs$reader$read_list(rdr,_){
var arr = cljs.reader.read_delimited_list.call(null,")",rdr,true);
var i = arr.length;
var r = cljs.core.List.EMPTY;
while(true){
if((i > (0))){
var G__60093 = (i - (1));
var G__60094 = cljs.core._conj.call(null,r,(arr[(i - (1))]));
i = G__60093;
r = G__60094;
continue;
} else {
return r;
}
break;
}
});
cljs.reader.read_comment = cljs.reader.skip_line;
cljs.reader.read_vector = (function cljs$reader$read_vector(rdr,_){
return cljs.core.vec.call(null,cljs.reader.read_delimited_list.call(null,"]",rdr,true));
});
cljs.reader.read_map = (function cljs$reader$read_map(rdr,_){
var l = cljs.reader.read_delimited_list.call(null,"}",rdr,true);
var c = l.length;
if(cljs.core.odd_QMARK_.call(null,c)){
cljs.reader.reader_error.call(null,rdr,"Map literal must contain an even number of forms");
} else {
}
if((c <= ((2) * cljs.core.PersistentArrayMap.HASHMAP_THRESHOLD))){
return cljs.core.PersistentArrayMap.fromArray(l,true,true);
} else {
return cljs.core.PersistentHashMap.fromArray(l,true);
}
});
cljs.reader.read_number = (function cljs$reader$read_number(reader,initch){
var buffer = (new goog.string.StringBuffer(initch));
var ch = cljs.reader.read_char.call(null,reader);
while(true){
if(cljs.core.truth_((function (){var or__53771__auto__ = (ch == null);
if(or__53771__auto__){
return or__53771__auto__;
} else {
var or__53771__auto____$1 = cljs.reader.whitespace_QMARK_.call(null,ch);
if(or__53771__auto____$1){
return or__53771__auto____$1;
} else {
return cljs.reader.macros.call(null,ch);
}
}
})())){
cljs.reader.unread.call(null,reader,ch);
var s = buffer.toString();
var or__53771__auto__ = cljs.reader.match_number.call(null,s);
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return cljs.reader.reader_error.call(null,reader,"Invalid number format [",s,"]");
}
} else {
var G__60095 = (function (){
buffer.append(ch);
return buffer;
})()
;
var G__60096 = cljs.reader.read_char.call(null,reader);
buffer = G__60095;
ch = G__60096;
continue;
}
break;
}
});
cljs.reader.read_string_STAR_ = (function cljs$reader$read_string_STAR_(reader,_){
var buffer = (new goog.string.StringBuffer());
var ch = cljs.reader.read_char.call(null,reader);
while(true){
if((ch == null)){
return cljs.reader.reader_error.call(null,reader,"EOF while reading");
} else {
if(("\\" === ch)){
var G__60097 = (function (){
buffer.append(cljs.reader.escape_char.call(null,buffer,reader));
return buffer;
})()
;
var G__60098 = cljs.reader.read_char.call(null,reader);
buffer = G__60097;
ch = G__60098;
continue;
} else {
if(("\"" === ch)){
return buffer.toString();
} else {
var G__60099 = (function (){
buffer.append(ch);
return buffer;
})()
;
var G__60100 = cljs.reader.read_char.call(null,reader);
buffer = G__60099;
ch = G__60100;
continue;
}
}
}
break;
}
});
cljs.reader.read_raw_string_STAR_ = (function cljs$reader$read_raw_string_STAR_(reader,_){
var buffer = (new goog.string.StringBuffer());
var ch = cljs.reader.read_char.call(null,reader);
while(true){
if((ch == null)){
return cljs.reader.reader_error.call(null,reader,"EOF while reading");
} else {
if(("\\" === ch)){
buffer.append(ch);
var nch = cljs.reader.read_char.call(null,reader);
if((nch == null)){
return cljs.reader.reader_error.call(null,reader,"EOF while reading");
} else {
var G__60105 = (function (){var G__60103 = buffer;
G__60103.append(nch);
return G__60103;
})();
var G__60106 = cljs.reader.read_char.call(null,reader);
buffer = G__60105;
ch = G__60106;
continue;
}
} else {
if(("\"" === ch)){
return buffer.toString();
} else {
var G__60107 = (function (){var G__60104 = buffer;
G__60104.append(ch);
return G__60104;
})();
var G__60108 = cljs.reader.read_char.call(null,reader);
buffer = G__60107;
ch = G__60108;
continue;
}
}
}
break;
}
});
cljs.reader.special_symbols = (function cljs$reader$special_symbols(t,not_found){
if((t === "nil")){
return null;
} else {
if((t === "true")){
return true;
} else {
if((t === "false")){
return false;
} else {
if((t === "/")){
return new cljs.core.Symbol(null,"/","/",-1371932971,null);
} else {
return not_found;
}
}
}
}
});
cljs.reader.read_symbol = (function cljs$reader$read_symbol(reader,initch){
var token = cljs.reader.read_token.call(null,reader,initch);
if(cljs.core.truth_((function (){var and__53759__auto__ = goog.string.contains(token,"/");
if(cljs.core.truth_(and__53759__auto__)){
return !((token.length === (1)));
} else {
return and__53759__auto__;
}
})())){
return cljs.core.symbol.call(null,cljs.core.subs.call(null,token,(0),token.indexOf("/")),cljs.core.subs.call(null,token,(token.indexOf("/") + (1)),token.length));
} else {
return cljs.reader.special_symbols.call(null,token,cljs.core.symbol.call(null,token));
}
});
cljs.reader.read_literal = (function cljs$reader$read_literal(rdr,ch){
var token = cljs.reader.read_token.call(null,rdr,ch);
var chars = cljs.core.subs.call(null,token,(1));
if((chars.length === (1))){
return chars;
} else {
if((chars === "tab")){
return "\t";
} else {
if((chars === "return")){
return "\r";
} else {
if((chars === "newline")){
return "\n";
} else {
if((chars === "space")){
return " ";
} else {
if((chars === "backspace")){
return "\b";
} else {
if((chars === "formfeed")){
return "\f";
} else {
if((chars.charAt((0)) === "u")){
return cljs.reader.make_unicode_char.call(null,cljs.core.subs.call(null,chars,(1)));
} else {
if((chars.charAt((0)) === "o")){
return cljs.reader.not_implemented.call(null,rdr,token);
} else {
return cljs.reader.reader_error.call(null,rdr,"Unknown character literal: ",token);
}
}
}
}
}
}
}
}
}
});
cljs.reader.read_keyword = (function cljs$reader$read_keyword(reader,initch){
var token = cljs.reader.read_token.call(null,reader,cljs.reader.read_char.call(null,reader));
var a = cljs.reader.re_matches_STAR_.call(null,cljs.reader.symbol_pattern,token);
var token__$1 = (a[(0)]);
var ns = (a[(1)]);
var name = (a[(2)]);
if(((!((void 0 === ns))) && ((ns.substring((ns.length - (2)),ns.length) === ":/"))) || (((name[(name.length - (1))]) === ":")) || (!((token__$1.indexOf("::",(1)) === (-1))))){
return cljs.reader.reader_error.call(null,reader,"Invalid token: ",token__$1);
} else {
if((!((ns == null))) && ((ns.length > (0)))){
return cljs.core.keyword.call(null,ns.substring((0),ns.indexOf("/")),name);
} else {
return cljs.core.keyword.call(null,token__$1);
}
}
});
cljs.reader.desugar_meta = (function cljs$reader$desugar_meta(f){
if((f instanceof cljs.core.Symbol)){
return new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"tag","tag",-1290361223),f], null);
} else {
if(typeof f === 'string'){
return new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"tag","tag",-1290361223),f], null);
} else {
if((f instanceof cljs.core.Keyword)){
return cljs.core.PersistentArrayMap.fromArray([f,true], true, false);
} else {
return f;
}
}
}
});
cljs.reader.wrapping_reader = (function cljs$reader$wrapping_reader(sym){
return (function (rdr,_){
var x__54608__auto__ = sym;
return cljs.core._conj.call(null,(function (){var x__54608__auto____$1 = cljs.reader.read.call(null,rdr,true,null,true);
return cljs.core._conj.call(null,cljs.core.List.EMPTY,x__54608__auto____$1);
})(),x__54608__auto__);
});
});
cljs.reader.throwing_reader = (function cljs$reader$throwing_reader(msg){
return (function (rdr,_){
return cljs.reader.reader_error.call(null,rdr,msg);
});
});
cljs.reader.read_meta = (function cljs$reader$read_meta(rdr,_){
var m = cljs.reader.desugar_meta.call(null,cljs.reader.read.call(null,rdr,true,null,true));
if(cljs.core.map_QMARK_.call(null,m)){
} else {
cljs.reader.reader_error.call(null,rdr,"Metadata must be Symbol,Keyword,String or Map");
}
var o = cljs.reader.read.call(null,rdr,true,null,true);
if(((!((o == null)))?((((o.cljs$lang$protocol_mask$partition0$ & (262144))) || ((cljs.core.PROTOCOL_SENTINEL === o.cljs$core$IWithMeta$)))?true:(((!o.cljs$lang$protocol_mask$partition0$))?cljs.core.native_satisfies_QMARK_.call(null,cljs.core.IWithMeta,o):false)):cljs.core.native_satisfies_QMARK_.call(null,cljs.core.IWithMeta,o))){
return cljs.core.with_meta.call(null,o,cljs.core.merge.call(null,cljs.core.meta.call(null,o),m));
} else {
return cljs.reader.reader_error.call(null,rdr,"Metadata can only be applied to IWithMetas");
}
});
cljs.reader.read_set = (function cljs$reader$read_set(rdr,_){
return cljs.core.PersistentHashSet.fromArray(cljs.reader.read_delimited_list.call(null,"}",rdr,true),true);
});
cljs.reader.read_regex = (function cljs$reader$read_regex(rdr,ch){
return cljs.core.re_pattern.call(null,cljs.reader.read_raw_string_STAR_.call(null,rdr,ch));
});
cljs.reader.read_discard = (function cljs$reader$read_discard(rdr,_){
cljs.reader.read.call(null,rdr,true,null,true);
return rdr;
});
cljs.reader.macros = (function cljs$reader$macros(c){
if((c === "\"")){
return cljs.reader.read_string_STAR_;
} else {
if((c === ":")){
return cljs.reader.read_keyword;
} else {
if((c === ";")){
return cljs.reader.read_comment;
} else {
if((c === "'")){
return cljs.reader.wrapping_reader.call(null,new cljs.core.Symbol(null,"quote","quote",1377916282,null));
} else {
if((c === "@")){
return cljs.reader.wrapping_reader.call(null,new cljs.core.Symbol(null,"deref","deref",1494944732,null));
} else {
if((c === "^")){
return cljs.reader.read_meta;
} else {
if((c === "`")){
return cljs.reader.not_implemented;
} else {
if((c === "~")){
return cljs.reader.not_implemented;
} else {
if((c === "(")){
return cljs.reader.read_list;
} else {
if((c === ")")){
return cljs.reader.read_unmatched_delimiter;
} else {
if((c === "[")){
return cljs.reader.read_vector;
} else {
if((c === "]")){
return cljs.reader.read_unmatched_delimiter;
} else {
if((c === "{")){
return cljs.reader.read_map;
} else {
if((c === "}")){
return cljs.reader.read_unmatched_delimiter;
} else {
if((c === "\\")){
return cljs.reader.read_literal;
} else {
if((c === "#")){
return cljs.reader.read_dispatch;
} else {
return null;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
});
cljs.reader.dispatch_macros = (function cljs$reader$dispatch_macros(s){
if((s === "{")){
return cljs.reader.read_set;
} else {
if((s === "<")){
return cljs.reader.throwing_reader.call(null,"Unreadable form");
} else {
if((s === "\"")){
return cljs.reader.read_regex;
} else {
if((s === "!")){
return cljs.reader.read_comment;
} else {
if((s === "_")){
return cljs.reader.read_discard;
} else {
return null;
}
}
}
}
}
});
/**
* Reads the first object from a PushbackReader. Returns the object read.
* If EOF, throws if eof-is-error is true. Otherwise returns sentinel.
*
* Only supports edn (similar to clojure.edn/read)
*/
cljs.reader.read = (function cljs$reader$read(reader,eof_is_error,sentinel,is_recursive){
while(true){
var ch = cljs.reader.read_char.call(null,reader);
if((ch == null)){
if(cljs.core.truth_(eof_is_error)){
return cljs.reader.reader_error.call(null,reader,"EOF while reading");
} else {
return sentinel;
}
} else {
if(cljs.reader.whitespace_QMARK_.call(null,ch)){
var G__60111 = reader;
var G__60112 = eof_is_error;
var G__60113 = sentinel;
var G__60114 = is_recursive;
reader = G__60111;
eof_is_error = G__60112;
sentinel = G__60113;
is_recursive = G__60114;
continue;
} else {
if(cljs.reader.comment_prefix_QMARK_.call(null,ch)){
var G__60115 = cljs.reader.read_comment.call(null,reader,ch);
var G__60116 = eof_is_error;
var G__60117 = sentinel;
var G__60118 = is_recursive;
reader = G__60115;
eof_is_error = G__60116;
sentinel = G__60117;
is_recursive = G__60118;
continue;
} else {
var f = cljs.reader.macros.call(null,ch);
var res = (cljs.core.truth_(f)?f.call(null,reader,ch):((cljs.reader.number_literal_QMARK_.call(null,reader,ch))?cljs.reader.read_number.call(null,reader,ch):cljs.reader.read_symbol.call(null,reader,ch)
));
if((res === reader)){
var G__60119 = reader;
var G__60120 = eof_is_error;
var G__60121 = sentinel;
var G__60122 = is_recursive;
reader = G__60119;
eof_is_error = G__60120;
sentinel = G__60121;
is_recursive = G__60122;
continue;
} else {
return res;
}
}
}
}
break;
}
});
/**
* Reads one object from the string s
*/
cljs.reader.read_string = (function cljs$reader$read_string(s){
if(typeof s === 'string'){
} else {
throw (new Error("Cannot read from non-string object."));
}
var r = cljs.reader.push_back_reader.call(null,s);
return cljs.reader.read.call(null,r,false,null,false);
});
cljs.reader.zero_fill_right_and_truncate = (function cljs$reader$zero_fill_right_and_truncate(s,width){
if(cljs.core._EQ_.call(null,width,cljs.core.count.call(null,s))){
return s;
} else {
if((width < cljs.core.count.call(null,s))){
return cljs.core.subs.call(null,s,(0),width);
} else {
var b = (new goog.string.StringBuffer(s));
while(true){
if((b.getLength() < width)){
var G__60123 = b.append("0");
b = G__60123;
continue;
} else {
return b.toString();
}
break;
}
}
}
});
cljs.reader.divisible_QMARK_ = (function cljs$reader$divisible_QMARK_(num,div){
return (cljs.core.mod.call(null,num,div) === (0));
});
cljs.reader.indivisible_QMARK_ = (function cljs$reader$indivisible_QMARK_(num,div){
return cljs.core.not.call(null,cljs.reader.divisible_QMARK_.call(null,num,div));
});
cljs.reader.leap_year_QMARK_ = (function cljs$reader$leap_year_QMARK_(year){
var and__53759__auto__ = cljs.reader.divisible_QMARK_.call(null,year,(4));
if(cljs.core.truth_(and__53759__auto__)){
var or__53771__auto__ = cljs.reader.indivisible_QMARK_.call(null,year,(100));
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return cljs.reader.divisible_QMARK_.call(null,year,(400));
}
} else {
return and__53759__auto__;
}
});
cljs.reader.days_in_month = (function (){var dim_norm = new cljs.core.PersistentVector(null, 13, 5, cljs.core.PersistentVector.EMPTY_NODE, [null,(31),(28),(31),(30),(31),(30),(31),(31),(30),(31),(30),(31)], null);
var dim_leap = new cljs.core.PersistentVector(null, 13, 5, cljs.core.PersistentVector.EMPTY_NODE, [null,(31),(29),(31),(30),(31),(30),(31),(31),(30),(31),(30),(31)], null);
return ((function (dim_norm,dim_leap){
return (function (month,leap_year_QMARK_){
return cljs.core.get.call(null,(cljs.core.truth_(leap_year_QMARK_)?dim_leap:dim_norm),month);
});
;})(dim_norm,dim_leap))
})();
cljs.reader.timestamp_regex = /(\d\d\d\d)(?:-(\d\d)(?:-(\d\d)(?:[T](\d\d)(?::(\d\d)(?::(\d\d)(?:[.](\d+))?)?)?)?)?)?(?:[Z]|([-+])(\d\d):(\d\d))?/;
cljs.reader.parse_int = (function cljs$reader$parse_int(s){
var n = parseInt(s,(10));
if(cljs.core.not.call(null,isNaN(n))){
return n;
} else {
return null;
}
});
cljs.reader.check = (function cljs$reader$check(low,n,high,msg){
if(((low <= n)) && ((n <= high))){
} else {
cljs.reader.reader_error.call(null,null,[cljs.core.str(msg),cljs.core.str(" Failed: "),cljs.core.str(low),cljs.core.str("<="),cljs.core.str(n),cljs.core.str("<="),cljs.core.str(high)].join(''));
}
return n;
});
cljs.reader.parse_and_validate_timestamp = (function cljs$reader$parse_and_validate_timestamp(s){
var vec__60127 = cljs.core.re_matches.call(null,cljs.reader.timestamp_regex,s);
var _ = cljs.core.nth.call(null,vec__60127,(0),null);
var years = cljs.core.nth.call(null,vec__60127,(1),null);
var months = cljs.core.nth.call(null,vec__60127,(2),null);
var days = cljs.core.nth.call(null,vec__60127,(3),null);
var hours = cljs.core.nth.call(null,vec__60127,(4),null);
var minutes = cljs.core.nth.call(null,vec__60127,(5),null);
var seconds = cljs.core.nth.call(null,vec__60127,(6),null);
var fraction = cljs.core.nth.call(null,vec__60127,(7),null);
var offset_sign = cljs.core.nth.call(null,vec__60127,(8),null);
var offset_hours = cljs.core.nth.call(null,vec__60127,(9),null);
var offset_minutes = cljs.core.nth.call(null,vec__60127,(10),null);
var v = vec__60127;
if(cljs.core.not.call(null,v)){
return cljs.reader.reader_error.call(null,null,[cljs.core.str("Unrecognized date/time syntax: "),cljs.core.str(s)].join(''));
} else {
var years__$1 = cljs.reader.parse_int.call(null,years);
var months__$1 = (function (){var or__53771__auto__ = cljs.reader.parse_int.call(null,months);
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return (1);
}
})();
var days__$1 = (function (){var or__53771__auto__ = cljs.reader.parse_int.call(null,days);
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return (1);
}
})();
var hours__$1 = (function (){var or__53771__auto__ = cljs.reader.parse_int.call(null,hours);
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return (0);
}
})();
var minutes__$1 = (function (){var or__53771__auto__ = cljs.reader.parse_int.call(null,minutes);
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return (0);
}
})();
var seconds__$1 = (function (){var or__53771__auto__ = cljs.reader.parse_int.call(null,seconds);
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return (0);
}
})();
var fraction__$1 = (function (){var or__53771__auto__ = cljs.reader.parse_int.call(null,cljs.reader.zero_fill_right_and_truncate.call(null,fraction,(3)));
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return (0);
}
})();
var offset_sign__$1 = ((cljs.core._EQ_.call(null,offset_sign,"-"))?(-1):(1));
var offset_hours__$1 = (function (){var or__53771__auto__ = cljs.reader.parse_int.call(null,offset_hours);
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return (0);
}
})();
var offset_minutes__$1 = (function (){var or__53771__auto__ = cljs.reader.parse_int.call(null,offset_minutes);
if(cljs.core.truth_(or__53771__auto__)){
return or__53771__auto__;
} else {
return (0);
}
})();
var offset = (offset_sign__$1 * ((offset_hours__$1 * (60)) + offset_minutes__$1));
return new cljs.core.PersistentVector(null, 8, 5, cljs.core.PersistentVector.EMPTY_NODE, [years__$1,cljs.reader.check.call(null,(1),months__$1,(12),"timestamp month field must be in range 1..12"),cljs.reader.check.call(null,(1),days__$1,cljs.reader.days_in_month.call(null,months__$1,cljs.reader.leap_year_QMARK_.call(null,years__$1)),"timestamp day field must be in range 1..last day in month"),cljs.reader.check.call(null,(0),hours__$1,(23),"timestamp hour field must be in range 0..23"),cljs.reader.check.call(null,(0),minutes__$1,(59),"timestamp minute field must be in range 0..59"),cljs.reader.check.call(null,(0),seconds__$1,((cljs.core._EQ_.call(null,minutes__$1,(59)))?(60):(59)),"timestamp second field must be in range 0..60"),cljs.reader.check.call(null,(0),fraction__$1,(999),"timestamp millisecond field must be in range 0..999"),offset], null);
}
});
cljs.reader.parse_timestamp = (function cljs$reader$parse_timestamp(ts){
var temp__4655__auto__ = cljs.reader.parse_and_validate_timestamp.call(null,ts);
if(cljs.core.truth_(temp__4655__auto__)){
var vec__60133 = temp__4655__auto__;
var years = cljs.core.nth.call(null,vec__60133,(0),null);
var months = cljs.core.nth.call(null,vec__60133,(1),null);
var days = cljs.core.nth.call(null,vec__60133,(2),null);
var hours = cljs.core.nth.call(null,vec__60133,(3),null);
var minutes = cljs.core.nth.call(null,vec__60133,(4),null);
var seconds = cljs.core.nth.call(null,vec__60133,(5),null);
var ms = cljs.core.nth.call(null,vec__60133,(6),null);
var offset = cljs.core.nth.call(null,vec__60133,(7),null);
return (new Date((Date.UTC(years,(months - (1)),days,hours,minutes,seconds,ms) - ((offset * (60)) * (1000)))));
} else {
return cljs.reader.reader_error.call(null,null,[cljs.core.str("Unrecognized date/time syntax: "),cljs.core.str(ts)].join(''));
}
});
cljs.reader.read_date = (function cljs$reader$read_date(s){
if(typeof s === 'string'){
return cljs.reader.parse_timestamp.call(null,s);
} else {
return cljs.reader.reader_error.call(null,null,"Instance literal expects a string for its timestamp.");
}
});
cljs.reader.read_queue = (function cljs$reader$read_queue(elems){
if(cljs.core.vector_QMARK_.call(null,elems)){
return cljs.core.into.call(null,cljs.core.PersistentQueue.EMPTY,elems);
} else {
return cljs.reader.reader_error.call(null,null,"Queue literal expects a vector for its elements.");
}
});
cljs.reader.read_js = (function cljs$reader$read_js(form){
if(cljs.core.vector_QMARK_.call(null,form)){
var arr = [];
var seq__60152_60168 = cljs.core.seq.call(null,form);
var chunk__60153_60169 = null;
var count__60154_60170 = (0);
var i__60155_60171 = (0);
while(true){
if((i__60155_60171 < count__60154_60170)){
var x_60172 = cljs.core._nth.call(null,chunk__60153_60169,i__60155_60171);
arr.push(x_60172);
var G__60173 = seq__60152_60168;
var G__60174 = chunk__60153_60169;
var G__60175 = count__60154_60170;
var G__60176 = (i__60155_60171 + (1));
seq__60152_60168 = G__60173;
chunk__60153_60169 = G__60174;
count__60154_60170 = G__60175;
i__60155_60171 = G__60176;
continue;
} else {
var temp__4657__auto___60177 = cljs.core.seq.call(null,seq__60152_60168);
if(temp__4657__auto___60177){
var seq__60152_60178__$1 = temp__4657__auto___60177;
if(cljs.core.chunked_seq_QMARK_.call(null,seq__60152_60178__$1)){
var c__54585__auto___60179 = cljs.core.chunk_first.call(null,seq__60152_60178__$1);
var G__60180 = cljs.core.chunk_rest.call(null,seq__60152_60178__$1);
var G__60181 = c__54585__auto___60179;
var G__60182 = cljs.core.count.call(null,c__54585__auto___60179);
var G__60183 = (0);
seq__60152_60168 = G__60180;
chunk__60153_60169 = G__60181;
count__60154_60170 = G__60182;
i__60155_60171 = G__60183;
continue;
} else {
var x_60184 = cljs.core.first.call(null,seq__60152_60178__$1);
arr.push(x_60184);
var G__60185 = cljs.core.next.call(null,seq__60152_60178__$1);
var G__60186 = null;
var G__60187 = (0);
var G__60188 = (0);
seq__60152_60168 = G__60185;
chunk__60153_60169 = G__60186;
count__60154_60170 = G__60187;
i__60155_60171 = G__60188;
continue;
}
} else {
}
}
break;
}
return arr;
} else {
if(cljs.core.map_QMARK_.call(null,form)){
var obj = {};
var seq__60158_60189 = cljs.core.seq.call(null,form);
var chunk__60159_60190 = null;
var count__60160_60191 = (0);
var i__60161_60192 = (0);
while(true){
if((i__60161_60192 < count__60160_60191)){
var vec__60162_60193 = cljs.core._nth.call(null,chunk__60159_60190,i__60161_60192);
var k_60194 = cljs.core.nth.call(null,vec__60162_60193,(0),null);
var v_60195 = cljs.core.nth.call(null,vec__60162_60193,(1),null);
(obj[cljs.core.name.call(null,k_60194)] = v_60195);
var G__60196 = seq__60158_60189;
var G__60197 = chunk__60159_60190;
var G__60198 = count__60160_60191;
var G__60199 = (i__60161_60192 + (1));
seq__60158_60189 = G__60196;
chunk__60159_60190 = G__60197;
count__60160_60191 = G__60198;
i__60161_60192 = G__60199;
continue;
} else {
var temp__4657__auto___60200 = cljs.core.seq.call(null,seq__60158_60189);
if(temp__4657__auto___60200){
var seq__60158_60201__$1 = temp__4657__auto___60200;
if(cljs.core.chunked_seq_QMARK_.call(null,seq__60158_60201__$1)){
var c__54585__auto___60202 = cljs.core.chunk_first.call(null,seq__60158_60201__$1);
var G__60203 = cljs.core.chunk_rest.call(null,seq__60158_60201__$1);
var G__60204 = c__54585__auto___60202;
var G__60205 = cljs.core.count.call(null,c__54585__auto___60202);
var G__60206 = (0);
seq__60158_60189 = G__60203;
chunk__60159_60190 = G__60204;
count__60160_60191 = G__60205;
i__60161_60192 = G__60206;
continue;
} else {
var vec__60165_60207 = cljs.core.first.call(null,seq__60158_60201__$1);
var k_60208 = cljs.core.nth.call(null,vec__60165_60207,(0),null);
var v_60209 = cljs.core.nth.call(null,vec__60165_60207,(1),null);
(obj[cljs.core.name.call(null,k_60208)] = v_60209);
var G__60210 = cljs.core.next.call(null,seq__60158_60201__$1);
var G__60211 = null;
var G__60212 = (0);
var G__60213 = (0);
seq__60158_60189 = G__60210;
chunk__60159_60190 = G__60211;
count__60160_60191 = G__60212;
i__60161_60192 = G__60213;
continue;
}
} else {
}
}
break;
}
return obj;
} else {
return cljs.reader.reader_error.call(null,null,[cljs.core.str("JS literal expects a vector or map containing "),cljs.core.str("only string or unqualified keyword keys")].join(''));
}
}
});
cljs.reader.read_uuid = (function cljs$reader$read_uuid(uuid){
if(typeof uuid === 'string'){
return cljs.core.uuid.call(null,uuid);
} else {
return cljs.reader.reader_error.call(null,null,"UUID literal expects a string as its representation.");
}
});
cljs.reader._STAR_tag_table_STAR_ = cljs.core.atom.call(null,new cljs.core.PersistentArrayMap(null, 4, ["inst",cljs.reader.read_date,"uuid",cljs.reader.read_uuid,"queue",cljs.reader.read_queue,"js",cljs.reader.read_js], null));
cljs.reader._STAR_default_data_reader_fn_STAR_ = cljs.core.atom.call(null,null);
cljs.reader.maybe_read_tagged_type = (function cljs$reader$maybe_read_tagged_type(rdr,initch){
var tag = cljs.reader.read_symbol.call(null,rdr,initch);
var pfn = cljs.core.get.call(null,cljs.core.deref.call(null,cljs.reader._STAR_tag_table_STAR_),[cljs.core.str(tag)].join(''));
var dfn = cljs.core.deref.call(null,cljs.reader._STAR_default_data_reader_fn_STAR_);
if(cljs.core.truth_(pfn)){
return pfn.call(null,cljs.reader.read.call(null,rdr,true,null,false));
} else {
if(cljs.core.truth_(dfn)){
return dfn.call(null,tag,cljs.reader.read.call(null,rdr,true,null,false));
} else {
return cljs.reader.reader_error.call(null,rdr,"Could not find tag parser for ",[cljs.core.str(tag)].join('')," in ",cljs.core.pr_str.call(null,cljs.core.keys.call(null,cljs.core.deref.call(null,cljs.reader._STAR_tag_table_STAR_))));
}
}
});
cljs.reader.register_tag_parser_BANG_ = (function cljs$reader$register_tag_parser_BANG_(tag,f){
var tag__$1 = [cljs.core.str(tag)].join('');
var old_parser = cljs.core.get.call(null,cljs.core.deref.call(null,cljs.reader._STAR_tag_table_STAR_),tag__$1);
cljs.core.swap_BANG_.call(null,cljs.reader._STAR_tag_table_STAR_,cljs.core.assoc,tag__$1,f);
return old_parser;
});
cljs.reader.deregister_tag_parser_BANG_ = (function cljs$reader$deregister_tag_parser_BANG_(tag){
var tag__$1 = [cljs.core.str(tag)].join('');
var old_parser = cljs.core.get.call(null,cljs.core.deref.call(null,cljs.reader._STAR_tag_table_STAR_),tag__$1);
cljs.core.swap_BANG_.call(null,cljs.reader._STAR_tag_table_STAR_,cljs.core.dissoc,tag__$1);
return old_parser;
});
cljs.reader.register_default_tag_parser_BANG_ = (function cljs$reader$register_default_tag_parser_BANG_(f){
var old_parser = cljs.core.deref.call(null,cljs.reader._STAR_default_data_reader_fn_STAR_);
cljs.core.swap_BANG_.call(null,cljs.reader._STAR_default_data_reader_fn_STAR_,((function (old_parser){
return (function (_){
return f;
});})(old_parser))
);
return old_parser;
});
cljs.reader.deregister_default_tag_parser_BANG_ = (function cljs$reader$deregister_default_tag_parser_BANG_(){
var old_parser = cljs.core.deref.call(null,cljs.reader._STAR_default_data_reader_fn_STAR_);
cljs.core.swap_BANG_.call(null,cljs.reader._STAR_default_data_reader_fn_STAR_,((function (old_parser){
return (function (_){
return null;
});})(old_parser))
);
return old_parser;
});
//# sourceMappingURL=reader.js.map
|
const path = require('path');
const { paths, rootResolution } = require('../../context');
const internalRegex = `^(${paths.src
.map((srcPath) => path.basename(srcPath))
.join('|')})/`;
const rootResolutionConfig = {
settings: {
'import/internal-regex': internalRegex,
},
};
module.exports = {
...(rootResolution ? rootResolutionConfig : undefined),
rules: {
'import/order': [
'error',
{
'newlines-between': 'always',
alphabetize: { order: 'asc' },
groups: [
'builtin',
'external',
'internal',
'parent',
'sibling',
'index',
],
pathGroups: [
{
pattern: '*.+(treat|less|css)',
group: 'index',
position: 'after',
patternOptions: { matchBase: true },
},
],
},
],
},
};
|
var AnsTypeView = Backbone.View.extend({
initialize: function(args){
_.bindAll(this, 'render');
this.template_begin = _.template(args.template_begin);
this.template_finish = _.template(args.template_finish);
this.generate_choice = args.generate_choice;
if (args.render)
this.render = args.render;
},
render: function(answers, choice, end){
var template = end?this.template_finish:this.template_begin;
var str = '<ul class="list-group">';
_.each(answers, function(obj, hash, list){
str += template({
text: obj.text,
is_correct: obj.is_correct,
hash: hash,
choice: choice
});
});
str += '</ul>';
return str;
}
})
var AnsTypeViews = {
radio: new AnsTypeView({
template_begin: "<li class='list-group-item <%-choice==hash?'active':''%>'>\
<input type='radio' name='ans' <%-choice==hash?'checked':''%> value='<%=hash%>' /> <%-text%>\
</li>",
template_finish: "<li class='list-group-item'>\
<input type='radio' name='ans' disabled='disabled' <%-choice==hash?'checked':''%> value='<%=hash%>' /> <%-text%>\
<% if(is_correct){ %>\
<span class='label label-default label-success'>OK</span>\
<% }else if(choice==hash){ %>\
<span class='label label-default label-danger'>WRONG</span>\
<% } %>\
</li>",
generate_choice: function(form){
return form.find("input:checked").val();
}
}),
checkbox: new AnsTypeView({
template_begin: "<li class='list-group-item <%-choice.indexOf(hash)>=0?'active':''%>'>\
<input type='checkbox' <%-choice.indexOf(hash)>=0?'checked':''%> name='ans' value='<%=hash%>' /> <%-text%>\
</li>",
template_finish: "<li class='list-group-item'>\
<input type='checkbox' disabled='disabled' <%-choice.indexOf(hash)>=0?'checked':''%> value='<%=hash%>' /> <%-text%>\
<% if(is_correct){ %>\
<span class='label label-default label-success'>OK</span>\
<% }else if(choice.indexOf(hash)>=0){ %>\
<span class='label label-default label-danger'>WRONG</span>\
<% } %>\
</li>",
generate_choice: function(form){
var choice = [];
form.find("input:checked").each(function(index, el){
choice.push(el.value);
})
return choice;
}
}),
text: new AnsTypeView({
template_begin: "Answer: <input type='text' class='form-control' value='<%-choice%>' />",
template_finish: "Answer: <input type='text' class='form-control' value='<%-choice%>' disabled />\
<% if(is_correct){ %>\
<span class='label label-default label-success'>OK</span>\
<% }else{ %>\
<span class='label label-default label-danger'>WRONG</span>\
Good answers: \
<% _.each(good_answers,function(ans,key,list){ %>\
<span class='label label-info'><%-ans%></span>\
<% }) %>\
<% } %>",
generate_choice: function(form){
return form.find("input[type=\"text\"]").val()
},
render: function(answers, choice, end){
if (!end){
return this.template_begin({choice: choice})
}else{
var is_correct = false;
var good_answers = [];
var trim_choice = choice.trim();
_.each(answers, function(obj, hash, list){
if (obj.is_correct){
var txt = obj.text.trim();
if (trim_choice == txt)
is_correct = true;
good_answers.push(txt);
}
})
return this.template_finish({
is_correct: is_correct,
good_answers: good_answers,
choice: choice
})
}
}
})
};
|
function saveOptions(e) {
e.preventDefault();
var openInTabs = document.getElementsByName("openInTab");
var selected = "";
for (var i = 0; openInTabs.length; i++) {
if (openInTabs[i].checked === true) {
selected = openInTabs[i].value;
break;
}
}
browser.storage.local.set({
openInTabs: selected
});
}
function restoreOptions() {
function setOpenInTab(result) {
var openInTabs = document.getElementsByName("openInTab");
for (var i = 0; openInTabs.length; i++) {
if (openInTabs[i].value === result.openInTabs) {
openInTabs[i].checked = true;
break;
}
}
}
var getting1 = browser.storage.local.get("openInTabs");
getting1.then(setOpenInTab, onError);
}
function onError(error) {
console.log(`Error: ${error}`);
}
document.addEventListener("DOMContentLoaded", restoreOptions);
document.querySelector("form").addEventListener("submit", saveOptions);
|
$(function(){ // on dom ready
var cy = cytoscape({
container: document.getElementById('cy'),
boxSelectionEnabled: false,
autounselectify: true,
style: [
{
selector: 'node',
css: {
'content': 'data(id)',
'text-valign': 'center',
'text-halign': 'center'
}
},
{
selector: '$node > node',
css: {
'padding-top': '10px',
'padding-left': '10px',
'padding-bottom': '10px',
'padding-right': '10px',
'text-valign': 'top',
'text-halign': 'center',
'background-color': '#bbb'
}
},
{
selector: 'edge',
css: {
'target-arrow-shape': 'triangle',
'curve-style': 'bezier'
}
},
{
selector: ':selected',
css: {
'background-color': 'black',
'line-color': 'black',
'target-arrow-color': 'black',
'source-arrow-color': 'black'
}
}
],
elements: {
nodes: [
{ data: { id: 'a', parent: 'b' }, position: { x: 215, y: 85 } },
{ data: { id: 'b' } },
{ data: { id: 'c', parent: 'b' }, position: { x: 300, y: 85 } },
{ data: { id: 'd' }, position: { x: 215, y: 175 } },
{ data: { id: 'e' } },
{ data: { id: 'f', parent: 'e' }, position: { x: 300, y: 175 } }
],
edges: [
{ data: { id: 'ad', source: 'a', target: 'd' } },
{ data: { id: 'eb', source: 'e', target: 'b' } }
]
},
layout: {
name: 'preset',
padding: 5
}
});
}); // on dom ready
|
/**
* Created by DELL on 8/21/2016.
*/
angular.module('myApp')
.controller('ProductController', function ($scope, $stateParams, $filter, ProductService, $rootScope, HomeService) {
$scope.format = {
brand: 'Độ thoáng:', product_code: 'Thoải mái:',
reward_point: 'Chất liệu:', guarantee: 'Bảo hành:', detail_a: 'Giá:'
};
HomeService.fetchAllItems()
.then(function (response) {
$scope.products = response.data.data;
$scope.product = $filter('filter')($scope.products, {_id: $stateParams.id})[0];
$scope.temp = [];
$scope.tempRandom = [];
$scope.services = [];
for (var j = 0; j < $scope.products.length; j++) {
if ($scope.products[j].code != 'VC')
$scope.temp.push($scope.products[j])
}
var randoms = $rootScope.randomNumbers($scope.temp.length),
rand = randoms();
$scope.Nice = $scope.temp[rand];
while (rand != null) {
$scope.tempRandom.push($scope.temp[rand]);
rand = randoms();
}
for (var i = 0; i < 3; i++) {
$scope.services.push($scope.tempRandom[i]);
}
$scope.smallitems = [];
for (var i = 0; i < 3; i++) {
$scope.smallitems.push($scope.tempRandom[i + 3]);
}
})
.catch(function () {
$scope.products = [];
});
HomeService.fetchAllCategory()
.then(function (response) {
$scope.categorys = response.data.data;
})
.catch(function () {
});
$scope.read = 'Read more >>';
});
|
'use strict';
import React, {
Component,
Picker,
} from 'react-native';
class PickerButton extends Component {
render(){
return (
<Picker
onValueChange={(lang)=> this.setState({language:lang})}>
<Picker.Item label="Java" value="java" />
<Picker.Item label="JavaScript" value="js" />
</Picker>)
}
}
export default PickerButton;
|
import * as React from 'react';
import Button from '@mui/material-next/Button';
export default function MultilineButtonNext() {
return (
<Button variant="contained" style={{ width: 400 }}>
{[
'Contained buttons are rectangular-shaped buttons.',
'They may be used inline.',
'They lift and display ink reactions on press.',
].join(' ')}
</Button>
);
}
|
const assert = require("assert")
describe("black algo", function () {
const black = require("./black")
it("", function () {
const result = black([
[false, true, false],//0 1
[true, true, false],//1 0 //1 1
[false, true, true]//2 1 // 2 2
])
assert.deepEqual(result, [
{command: "PAINT_SQUARE", args: [0, 1, 0]},
{command: "PAINT_SQUARE", args: [1, 0, 0]},
{command: "PAINT_SQUARE", args: [1, 1, 0]},
{command: "PAINT_SQUARE", args: [2, 1, 0]},
{command: "PAINT_SQUARE", args: [2, 2, 0]},
])
})
})
|
'use strict';
const KeyboardCharacters = require('./keyboard-characters');
const split = require('split');
const KeyboardBase = require('./keyboard-base');
class KeyboardLines extends KeyboardBase {
constructor(options) {
super(KeyboardCharacters, options);
this.device.pipe(split()).on('data', data => this.emit('data', data));
}
}
module.exports = KeyboardLines;
|
version https://git-lfs.github.com/spec/v1
oid sha256:2f070953c9114c1610f420fda1c3556e49a9da7b99ec24ffec5a0501e531a4ee
size 3963
|
/**
* THIS FILE IS AUTO-GENERATED
* DON'T MAKE CHANGES HERE
*/
import { addScalarDependencies } from './dependenciesAddScalar.generated';
import { isIntegerDependencies } from './dependenciesIsInteger.generated';
import { isNegativeDependencies } from './dependenciesIsNegative.generated';
import { stirlingS2Dependencies } from './dependenciesStirlingS2.generated';
import { typedDependencies } from './dependenciesTyped.generated';
import { createBellNumbers } from '../../factoriesAny.js';
export var bellNumbersDependencies = {
addScalarDependencies: addScalarDependencies,
isIntegerDependencies: isIntegerDependencies,
isNegativeDependencies: isNegativeDependencies,
stirlingS2Dependencies: stirlingS2Dependencies,
typedDependencies: typedDependencies,
createBellNumbers: createBellNumbers
};
|
var SlackNotifierAdmin = {
validate : function(){
try{
var teamName = document.forms["slackNotifierAdminForm"]["teamName"].value;
var token = document.forms["slackNotifierAdminForm"]["token"].value;
var iconUrl = document.forms["slackNotifierAdminForm"]["iconUrl"].value;
var botName = document.forms["slackNotifierAdminForm"]["botName"].value;
var maxCommitsToDisplay = document.forms["slackNotifierAdminForm"]["maxCommitsToDisplay"].value;
var showCommits = document.forms["slackNotifierAdminForm"]["showCommits"].checked;
var proxyHost = document.forms["slackNotifierAdminForm"]["proxyHost"].value;
var proxyPort = document.forms["slackNotifierAdminForm"]["proxyPort"].value;
var proxyUser = document.forms["slackNotifierAdminForm"]["proxyUser"].value;
var proxyPassword = document.forms["slackNotifierAdminForm"]["proxyPassword"].value;
var errors = [];
if(!teamName){
errors.push("Team name is required.");
}
if(!token){
errors.push("Api token is required.");
}
if(!iconUrl){
errors.push("Icon url is required.");
}
if(!botName){
errors.push("Bot name is required.");
}
if(proxyHost && !proxyPort){
errors.push("Proxy port is required if a host is specified.");
}
if(proxyUser && !proxyPassword){
errors.push("Proxy password is required if a user is specified.");
}
if(!showCommits){
if(!maxCommitsToDisplay){
errors.push("Max commits to display is required.");
}
else if(parseInt(maxCommitsToDisplay) == Number.NaN){
errors.push("Max commits to display must be a valid integer");
}
}
$('slackNotificationErrors').innerHTML = '';
if(errors.length > 0) {
var errorList = jQuery('<ul></ul>');
jQuery.each(errors, function(index, error) {
var li = jQuery('<li/>')
.addClass('slack-config-error')
.text(error)
.appendTo(errorList);
});
errorList.appendTo($('slackNotificationErrors'));
return false;
}
else {
return true;
}
}
catch(err){
$('slackNotificationErrors').innerHTML = 'Oops! Something went wrong!';
return false;
}
},
sendTestNotification : function() {
if(!SlackNotifierAdmin.validate()) {
return false;
}
jQuery.ajax(
{
url: $("slackNotifierAdminForm").action,
data: {
test: 1,
teamName: $("teamName").value,
defaultChannel: $("defaultChannel").value,
token: $("token").value,
botName: $("botName").value,
iconUrl: $("iconUrl").value,
maxCommitsToDisplay: $("maxCommitsToDisplay").value,
showCommits: $("showCommits").checked,
showCommitters: $("showCommitters").checked,
showTriggeredBy: $("showTriggeredBy").checked,
showElapsedBuildTime: $("showElapsedBuildTime").checked,
showBuildAgent: $("showBuildAgent").checked,
showFailureReason: $("showFailureReason").checked,
proxyHost: $("proxyHost").value,
proxyPort: $("proxyPort").value,
proxyUser: $("proxyUser").value,
proxyPassword: $("proxyPassword").getEncryptedPassword($("publicKey").value)
},
type: "GET"
}).done(function() {
alert("Notification sent\r\n\r\nNote: Any changes have not yet been saved.");
}).fail(function() {
alert("Failed to send notification!")
});
return false;
},
save : function() {
if(!SlackNotifierAdmin.validate()) {
return false;
}
jQuery.ajax(
{
url: $("slackNotifierAdminForm").action,
data: {
edit: 1,
teamName: $("teamName").value,
defaultChannel: $("defaultChannel").value,
token: $("token").value,
botName: $("botName").value,
iconUrl: $("iconUrl").value,
maxCommitsToDisplay: $("maxCommitsToDisplay").value,
showCommits: $("showCommits").checked,
showCommitters: $("showCommitters").checked,
showTriggeredBy: $("showTriggeredBy").checked,
showElapsedBuildTime: $("showElapsedBuildTime").checked,
showBuildAgent: $("showBuildAgent").checked,
showFailureReason: $("showFailureReason").checked,
proxyHost: $("proxyHost").value,
proxyPort: $("proxyPort").value,
proxyUser: $("proxyUser").value,
proxyPassword: $("proxyPassword").getEncryptedPassword($("publicKey").value)
},
type: "POST"
}).done(function() {
BS.reload();
}).fail(function() {
alert("Failed to save configuration!")
});
return false;
}
}
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define("require exports ../../../../core/tsSupport/assignHelper ../../../../Color ../../../../core/compilerUtils ../../../../core/maybe ../../../../core/screenUtils ../../../../core/libs/gl-matrix-2/vec4f64".split(" "),function(r,b,d,m,n,f,g,e){function c(a,b){if(f.isNone(a))return null;var c=f.isSome(a.color)?e.vec4f64.fromArray(m.toUnitRGBA(a.color)):e.vec4f64.fromValues(0,0,0,0),h=g.pt2px(a.size),k=g.pt2px(a.extensionLength);switch(a.type){case "solid":return l(d({color:c,size:h,extensionLength:k},
b));case "sketch":return d({},p,d({color:c,size:h,extensionLength:k},b),{type:"sketch"});default:n.neverReached(a)}}function l(a){return d({},q,a,{type:"solid"})}Object.defineProperty(b,"__esModule",{value:!0});b.createMaterial=function(a,b){return c(a&&a.enabled&&a.edges||null,b)};b.createMaterialFromEdges=c;b.createSolidEdgeMaterial=l;var q={color:e.vec4f64.fromValues(0,0,0,.2),size:1,extensionLength:0,opacity:1,objectTransparency:2},p={color:e.vec4f64.fromValues(0,0,0,.2),size:1,extensionLength:0,
opacity:1,objectTransparency:2}});
|
/*
* Fingerpointer jQuery plugin
* version 1.1
* author: Damien Antipa
* http://github.com/dantipa/jquery.fingerpointer
*/
(function ($, window, undefined) {
var isTouch = 'ontouchstart' in window;
$.fn.finger = function () {
if (isTouch) {
this.on.apply(this, arguments);
}
return this;
};
$.fn.pointer = function () {
if (!isTouch) {
this.on.apply(this, arguments);
}
return this;
};
$.fn.fipo = function () {
var args = Array.prototype.slice.call(arguments, 1, arguments.length);
this.pointer.apply(this, args);
args[0] = arguments[0];
this.finger.apply(this, args);
return this;
};
}(jQuery, this));
|
'use strict';
var keystone = require('keystone');
var Types = keystone.Field.Types;
//schema
var User = new keystone.List('User');
User.add({
name: { type: Types.Name, required: true, index: true },
email: { type: Types.Email, initial: true, required: true, index: true },
password: { type: Types.Password, initial: true },
canAccessKeystone: { type: Boolean, initial: true }
});
User.register();
|
/*jshint laxcomma: true, smarttabs: true, node:true, unused:true, esnext:true */
'use strict';
/**
* Mixin class providing functionality for detail endpoints
* @module tastypie/lib/resource/detail
* @author Eric Satterwhite
* @since 1.0.1
* @requires boom
* @requires mout/collection/forEach
* @requires tastypie/lib/class
* @requires tastypie/lib/http
**/
var Boom = require('boom')
, each = require('mout/collection/forEach')
, Class = require('../class')
, http = require('../http')
, Detail
;
function annotate( err, bundle ){
if(!err){
return err;
}
err.req = bundle.req;
err.res = bundle.res;
return err;
}
function delete_db( bundle, err, data ){
if( err ){
err = annotate( err );
return this.emit( 'error', err );
}
if(!this.options.returnData){
return this.respond( bundle, http.noContent );
}
this.full_dehydrate(bundle.object, bundle, ( err, data ) => {
if( err ){
err = annotate( err, bundle );
return this.emit( 'error', err );
}
bundle.data = data;
this.options.cache.set(bundle.toKey( 'detail' ) , null );
return this.respond( bundle );
});
}
/**
* @mixin
* @alias module:tastypie/lib/resource/detail
*/
Detail = new Class({
delete_detail: function delete_detail( bundle ){
return this.get_object( bundle, ( err, obj ) => {
bundle.object = obj;
if( !obj ){
bundle.data = {
message: `No object found at ${bundle.req.path}`
,statusCode: 404
,error:'Not Found'
};
return this.respond(bundle, http.notFound);
}
this.remove_object( bundle, delete_db.bind( this, bundle ) );
});
}
/**
* Dispatches detail requests which operated on a sigular, specific object
* @method module:tastypie/lib/resource/detail#dispatch_detail
* @param {Request} req An express request object
* @param {Response} rep An express response object
* @param {Function} next An express next callback
**/
, dispatch_detail: function dispatch_detail( req, res ){
return this.dispatch( 'detail', this.bundle( req, res ) );
}
/**
* Top level method used to retreive indiidual objects by id.
* This method handles caching results as well as reading from the cache
* @where applicable
* @method module:tastypie/lib/resource/detail#get_detail
* @param {Bundle} bundle A bundle representing the current request.
**/
, get_detail: function get_detail( bundle ){
var that = this;
this.from_cache( 'detail', bundle, function( err, data ){
if( err ) return that.emit( 'error', annotate( err, bundle ) );
if( !data ){
let err = Boom.notFound(`No object found at ${bundle.req.path}`);
return that.emit( 'error', annotate( err, bundle ) );
}
that.full_dehydrate( data, bundle, function( err, data ){
bundle.data = data;
return that.respond( bundle );
});
});
}
/**
* Method used to retrieve a specific object
* **NOTE** This method *must* be implement for specific use cases. The default does not implement this method
* @method module:tastypie/lib/resource/detail#get_object
* @param {module:tastypie/lib/resource~Bundle} bundle
* @param {module:tastypie/lib/resource~Nodeback} callback
* @example
var MyResource = Resource.extend({
get_object: function( bundle, callback ){
Model.get( bundle.req.params.pk, callback )
}
})
* @example
var MyResource = new Class({
inherits: Resource
, get_object: function( bundle, callback ){
this.get_objects(bundle,function(e, objects){
var obj = JSON.parse( objects ).filter(function( obj ){
return obj._id = bundle.req.params.pk
})[0]
callback( null, obj )
})
}
})
**/
, get_object: function get_object( bundle, callback ){
var e = Boom.notImplemented("method get_object not implemented");
e = annotate( e, bundle );
e.next = bundle.next;
setImmediate(callback, e );
}
/**
* High level function called in response to an OPTIONS request. Returns with an Allow header and empty body
* @method module:tastypie/lib/resource/detail#options_detail
* @param {module:tastypie/lib/resource~Bundle} bundle An object represneting the current `OPTIONS` request
**/
, options_detail: function options_detail( bundle ){
bundle.data = null;
this.respond( bundle, null, null, ( err, reply ) => {
let methods = [];
each( this.options.allowed.detail,function( value, key ){
if( value ){
methods.push( key.toUpperCase() );
}
});
reply.header('Allow',methods.join(','));
});
}
/**
* high level function called to handle PATCH requests
* @method module:tastypie/lib/resource/detail#patch_detail
* @param {module:tastypie/lib/resource~Bundle} bundle An object represneting the current `PATCH` request
**/
, patch_detail: function patch_detail( bundle ){
var response = http.ok
, that = this
, format
;
format = this.format( bundle, this.options.serializer.types );
this.deserialize( bundle.req.payload, format, function( err, data ){
bundle = that.bundle(bundle.req, bundle.res, data );
// update_object must save the object
that.update_object( bundle, function( err, bndl ){
if( err ){
return that.emit( 'error', annotate(err, bundle) );
}
if( !that.options.returnData ){
bundle.data = null;
response = http.noContent;
} else {
that.full_dehydrate( bndl.object, bndl, function( err, data ){
if( err ){
return that.emit( 'error', annotate(err, bundle) );
}
bndl.data = data;
return that.respond( bndl, response );
});
}
});
});
}
/**
* Top level method used to handle post request to listing endpoints. Used to update instances with supplied data
* @method module:tastypie/lib/resource/detail#put_detail
* @param {module:tastypie/lib/resource~Bundle} bundle An object represneting the current `PUT` request
**/
, put_detail: function put_detail( bundle ){
var response = http.ok
, that = this
, format
;
format = this.format( bundle, this.options.serializer.types );
this.deserialize( bundle.req.payload, format, function( err, data ){
bundle = that.bundle(bundle.req, bundle.res, data );
// replace_object must save the object
that.replace_object( bundle, function( err, bndl ){
if( err ){
err = annotate(err, bundle);
return that.emit( 'error', err );
}
if( !that.options.returnData ){
bundle.data = null;
response = http.noContent;
}
that.full_dehydrate( bndl.object, bndl, function( err, data ){
if( err ){
err = annotate(err, bundle);
return that.emit( 'error', err );
}
bndl.data = data;
return that.respond( bndl, response );
});
});
});
}
/**
* Low level function called to delete existing objects
* @method module:tastypie/lib/resource/detail#remove_object
* @param {module:tastypie/lib/resource~Bundle} bundle An object represneting the current `DELETE` request
* @param {module:tastypie/lib/resource~NodeBack} callback a callback to be caled when finished
**/
, remove_object: function( bundle, callback ){
var e = Boom.notImplemented('method remove_object not implemented');
e = annotate( e, bundle );
setImmediate( callback, e, null );
}
/**
* Low level function called to replace existing objects
* @method module:tastypie/lib/resource/detail#replace_object
* @param {module:tastypie/lib/resource~Bundle} bundle An object represneting the current `PUT` request
* @param {module:tastypie/lib/resource~NodeBack} callback a callback to be caled when finished
**/
, replace_object: function replace_object( bundle, callback ){
var e = Boom.notImplemented("method replace_object not implemented");
e = annotate(e, bundle);
setImmediate( callback, e, null );
}
/**
* Method that is responsibe for updating a specific object during a *PUT* request
* @method module:tastypie/lib/resource/detail#update_object
* @param {module:tastypie/lib/resource~Bundle} bundle The data bundle representing the current request
* @param {module:tastypie/lib/resource~Nodeback} callback callback to be called when the operation finishes.
**/
, update_object: function update_object( bundle, callback ){
var e = Boom.notImplemented("method update_object not implemented");
e = annotate(e, bundle);
setImmediate(callback, e, null );
}
});
module.exports = Detail;
|
/*record the operation of admin on users*/
const Sequelize = require('sequelize');
module.exports = (db) => {
return db.define('admin_log',{
content:{
type: Sequelize.TEXT, allowNull: false
}
});
};
|
const { format } = require('prettier');
const Analyser = require('../analyser');
const { parseAssign, parseFunc, getCompletionItemsAtScope, getSignatureItemsAtScope } = require('../tableItemHelper');
const luaCode = `CS.LuaBehaviour = {}
function CS.LuaBehaviour(abc, cbd) end
CS.LuaBehaviour.luaScript = nil`;
function formatJson(j) {
return format(JSON.stringify(j), { parser: 'json', printWidth: 120 });
}
test('analyse', () => {
const analyse = new Analyser(luaCode);
// console.log(formatJson(analyse.globalScope.tableCompItems));
});
const tableNode = {
type: 'AssignmentStatement',
variables: [
{
type: 'MemberExpression',
indexer: '.',
identifier: { type: 'Identifier', name: 'LuaBehaviour' },
base: { type: 'Identifier', name: 'CS' },
},
],
init: [
{
type: 'TableConstructorExpression',
fields: [
{
type: 'TableKeyString',
key: { type: 'Identifier', name: 'ab' },
value: { type: 'NumericLiteral', value: 1, raw: '1' },
},
{
type: 'TableKeyString',
key: { type: 'Identifier', name: 'cd' },
value: {
type: 'TableConstructorExpression',
fields: [
{
type: 'TableValue',
value: {
type: 'NumericLiteral',
value: 1,
raw: '1',
},
},
{
type: 'TableValue',
value: {
type: 'NumericLiteral',
value: 2,
raw: '2',
},
},
],
},
},
{
type: 'TableKeyString',
key: { type: 'Identifier', name: 'ef' },
value: {
type: 'TableConstructorExpression',
fields: [
{
type: 'TableKeyString',
key: { type: 'Identifier', name: 'qg' },
value: {
type: 'BooleanLiteral',
value: false,
raw: 'false',
},
},
],
},
},
],
},
],
};
const funcNode = {
type: 'FunctionDeclaration',
identifier: {
type: 'MemberExpression',
indexer: '.',
identifier: { type: 'Identifier', name: 'LuaBehaviour' },
base: { type: 'Identifier', name: 'CS' },
},
isLocal: false,
parameters: [{ type: 'Identifier', name: 'abc' }, { type: 'Identifier', name: 'cbd' }],
body: [],
};
const assignNode = {
type: 'AssignmentStatement',
variables: [
{
type: 'MemberExpression',
indexer: '.',
identifier: { type: 'Identifier', name: 'luaScript' },
base: {
type: 'MemberExpression',
indexer: '.',
identifier: { type: 'Identifier', name: 'LuaBehaviour' },
base: { type: 'Identifier', name: 'CS' },
},
},
],
init: [{ type: 'NilLiteral', value: null, raw: 'nil' }],
};
test('parse Table', () => {
const compItems = [];
parseAssign(compItems, tableNode);
parseAssign(compItems, assignNode);
parseFunc(compItems, funcNode);
expect(compItems).toEqual([
{
propName: 'CS',
propType: 'Object',
children: [
{
propName: 'LuaBehaviour',
propType: 'Object',
children: [
{ propName: 'ab', propType: 'number' },
{ propName: 'cd', propType: 'Object', children: [] },
{ propName: 'ef', propType: 'Object', children: [{ propName: 'qg', propType: 'bool' }] },
{ propName: 'luaScript', propType: 'any' },
],
},
{
propName: 'LuaBehaviour',
propType: 'Function',
params: [{ name: 'abc', paramType: 'any' }, { name: 'cbd', paramType: 'any' }],
},
],
},
]);
});
test('getCompletionItemsAtScope', () => {
const scope = {
tableCompItems: [],
parentScope: null,
};
parseAssign(scope.tableCompItems, tableNode);
parseAssign(scope.tableCompItems, assignNode);
parseFunc(scope.tableCompItems, funcNode);
const rst = getCompletionItemsAtScope(scope, ['CS']);
expect(rst).toEqual([
{
label: 'LuaBehaviour',
kind: 8,
detail: '(property) LuaBehaviour: table',
},
{
label: 'LuaBehaviour',
kind: 2,
detail: 'function LuaBehaviour(abc: any, cbd: any)',
},
]);
const rst2 = getCompletionItemsAtScope(scope, ['LuaBehaviour', 'CS']);
expect(rst2).toEqual([
{ label: 'ab', kind: 9, detail: '(property) ab: number' },
{ label: 'cd', kind: 8, detail: '(property) cd: table' },
{ label: 'ef', kind: 8, detail: '(property) ef: table' },
{
label: 'luaScript',
kind: 9,
detail: '(property) luaScript: any',
},
]);
});
test('getSignatureItemsAtScope', () => {
const scope = {
tableCompItems: [],
parentScope: null,
};
parseAssign(scope.tableCompItems, tableNode);
parseFunc(scope.tableCompItems, funcNode);
const rst = getSignatureItemsAtScope(scope, ['LuaBehaviour', 'CS']);
expect(rst).toEqual([
{
label: 'LuaBehaviour(abc: any, cbd: any)',
parameters: [{ label: 'abc' }, { label: 'cbd' }],
},
]);
});
|
'use strict';
var nopt = require('nopt');
var chalk = require('chalk');
var path = require('path');
var camelize = require('../utilities/string').camelize;
var getCallerFile = require('../utilities/get-caller-file');
var isGitRepo = require('../utilities/git-repo');
var Promise = require('../ext/promise');
var defaults = require('lodash-node/modern/objects/defaults');
var assign = require('lodash-node/modern/objects/assign');
var keys = require('lodash-node/modern/objects/keys');
var pluck = require('lodash-node/modern/collections/pluck');
var union = require('lodash-node/modern/arrays/union');
var uniq = require('lodash-node/modern/arrays/uniq');
var where = require('lodash-node/modern/collections/where');
var reject = require('lodash-node/modern/collections/reject');
var EOL = require('os').EOL;
var CoreObject = require('core-object');
var debug = require('debug')('ember-cli:command');
var Watcher = require('../models/watcher');
var SilentError = require('../errors/silent');
var allowedWorkOptions = {
insideProject: true,
outsideProject: true,
everywhere: true
};
path.name = 'Path';
// extend nopt to recognize 'gitUrl' as a type
nopt.typeDefs.gitUrl = {
type: 'gitUrl',
validate: function(data, k, val) {
if (isGitRepo(val)) {
data[k] = val;
return true;
} else {
return false;
}
}
};
module.exports = Command;
function Command() {
CoreObject.apply(this, arguments);
this.isWithinProject = this.project.isEmberCLIProject();
this.name = this.name || path.basename(getCallerFile(), '.js');
debug('initialize: name: %s, name: %s', this.name);
this.aliases = this.aliases || [];
// Works Property
if (!allowedWorkOptions[this.works]) {
throw new Error('The "' + this.name + '" command\'s works field has to ' +
'be either "everywhere", "insideProject" or "outsideProject".');
}
// Options properties
this.availableOptions = this.availableOptions || [];
this.anonymousOptions = this.anonymousOptions || [];
this.registerOptions();
}
/*
Registers options with command. This method provides the ability to extend or override command options.
Expects an object containing anonymousOptions or availableOptions, which it will then merge with
existing availableOptions before building the optionsAliases which are used to define shorthands.
*/
Command.prototype.registerOptions = function(options) {
var extendedAvailableOptions = options && options.availableOptions || [];
var extendedAnonymousOptions = options && options.anonymousOptions || [];
this.anonymousOptions = union(this.anonymousOptions.slice(0), extendedAnonymousOptions);
// merge any availableOptions
this.availableOptions = union(this.availableOptions.slice(0), extendedAvailableOptions);
var optionKeys = uniq(pluck(this.availableOptions, 'name'));
optionKeys.map(this.mergeDuplicateOption.bind(this));
this.optionsAliases = this.optionsAliases || {};
this.availableOptions.map(this.validateOption.bind(this));
};
Command.__proto__ = CoreObject;
Command.prototype.description = null;
Command.prototype.works = 'insideProject';
Command.prototype.constructor = Command;
/*
Hook for extending a command before it is run in the cli.run command.
Most common use case would be to extend availableOptions.
@method beforeRun
@return {Promise|null}
*/
Command.prototype.beforeRun = function() {};
/*
@method validateAndRun
@return {Promise}
*/
Command.prototype.validateAndRun = function(args) {
var commandOptions = this.parseArgs(args);
// if the help option was passed, resolve with 'callHelp' to call help command
if (commandOptions && (commandOptions.options.help || commandOptions.options.h)) {
debug(this.name + ' called with help option');
return Promise.resolve('callHelp');
}
this.analytics.track({
name: 'ember ',
message: this.name
});
if (commandOptions === null) {
return Promise.resolve();
}
if (this.works === 'insideProject' && !this.isWithinProject) {
this.ui.writeLine('You have to be inside an ember-cli project in order to use ' +
'the ' + chalk.green(this.name) + ' command.');
return Promise.resolve();
}
if (this.works === 'outsideProject' && this.isWithinProject) {
this.ui.writeLine('You cannot use the '+ chalk.green(this.name) +
' command inside an ember-cli project.');
return Promise.resolve();
}
return Watcher.detectWatcher(this.ui, commandOptions.options).then(function(options) {
return this.run(options, commandOptions.args);
}.bind(this));
};
/*
Merges any options with duplicate keys in the availableOptions array.
Used primarily by registerOptions.
@method mergeDuplicateOption
@param {String} key
@return {Object}
*/
Command.prototype.mergeDuplicateOption = function(key) {
var duplicateOptions, mergedOption, mergedAliases;
// get duplicates to merge
duplicateOptions = where(this.availableOptions, {'name': key});
if (duplicateOptions.length > 1) {
// TODO: warn on duplicates and overwriting
mergedAliases = [];
pluck(duplicateOptions, 'aliases').map(function(alias) {
alias.map(function(a) {
mergedAliases.push(a);
});
});
// merge duplicate options
mergedOption = assign.apply(null,duplicateOptions);
// replace aliases with unique aliases
mergedOption.aliases = uniq(mergedAliases, function(alias) {
if(typeof alias === 'object') {
return alias[Object.keys(alias)[0]];
}
return alias;
});
// remove duplicates from options
this.availableOptions = reject(this.availableOptions, {'name': key});
this.availableOptions.push(mergedOption);
}
return this.availableOptions;
};
/*
Normalizes option, filling in implicit values
@method normalizeOption
@param {Object} option
@return {Object}
*/
Command.prototype.normalizeOption = function(option) {
option.key = camelize(option.name);
option.required = option.required || false;
return option;
};
/*
Assigns option
@method assignOption
@param {Object} option
@param {Object} parsedOptions
@param {Object} commandOptions
@return {Boolean}
*/
Command.prototype.assignOption = function(option, parsedOptions, commandOptions) {
var isValid = isValidParsedOption(option, parsedOptions[option.name]);
if (isValid) {
if (parsedOptions[option.name] === undefined) {
if (option.default !== undefined) {
commandOptions[option.key] = option.default;
}
if (this.settings[option.name] !== undefined) {
commandOptions[option.key] = this.settings[option.name];
} else if (this.settings[option.key] !== undefined) {
commandOptions[option.key] = this.settings[option.key];
}
} else {
commandOptions[option.key] = parsedOptions[option.name];
delete parsedOptions[option.name];
}
} else {
this.ui.writeLine('The specified command ' + chalk.green(this.name) +
' requires the option ' + chalk.green(option.name) + '.');
}
return isValid;
};
/*
Validates option
@method validateOption
@param {Object} option
@return {Boolean}
*/
Command.prototype.validateOption = function(option) {
var parsedAliases;
if (!option.name || !option.type) {
throw new Error('The command "' + this.name + '" has an option ' +
'without the required type and name fields.');
}
if (option.name !== option.name.toLowerCase()) {
throw new Error('The "' + option.name + '" option\'s name of the "' +
this.name + '" command contains a capital letter.');
}
this.normalizeOption(option);
if (option.aliases) {
parsedAliases = option.aliases.map(this.parseAlias.bind(this, option));
return parsedAliases.map(this.assignAlias.bind(this, option)).indexOf(false) === -1;
}
return false;
};
/*
Parses alias for an option and adds it to optionsAliases
@method parseAlias
@param {Object} option
@param {Object|String} alias
@return {Object}
*/
Command.prototype.parseAlias = function(option, alias) {
var aliasType = typeof alias;
var key, value, aliasValue;
if (isValidAlias(alias, option.type)) {
if (aliasType === 'string') {
key = alias;
value = ['--' + option.name];
} else if (aliasType === 'object') {
key = Object.keys(alias)[0];
value = ['--' + option.name, alias[key]];
}
} else {
if (Array.isArray(alias)) {
aliasType = 'array';
aliasValue = alias.join(',');
} else {
aliasValue = alias;
try {
aliasValue = JSON.parse(alias);
}
catch(e) {
var debug = require('debug')('ember-cli/models/command');
debug(e);
}
}
throw new Error('The "' + aliasValue + '" [type:' + aliasType +
'] alias is not an acceptable value. It must be a string or single key' +
' object with a string value (for example, "value" or { "key" : "value" }).');
}
return {
key: key,
value: value,
original: alias
};
};
Command.prototype.assignAlias = function(option, alias) {
var isValid = this.validateAlias(option, alias);
if (isValid) {
this.optionsAliases[alias.key] = alias.value;
}
return isValid;
};
/*
Validates alias value
@method validateAlias
@params {Object} alias
@return {Boolean}
*/
Command.prototype.validateAlias = function(option, alias) {
var key = alias.key;
var value = alias.value;
if (!this.optionsAliases[key]) {
return true;
} else {
if (value[0] !== this.optionsAliases[key][0]) {
throw new SilentError('The "' + key + '" alias is already in use by the "' + this.optionsAliases[key][0] +
'" option and cannot be used by the "' + value[0] + '" option. Please use a different alias.');
} else {
if (value[1] !== this.optionsAliases[key][1]) {
this.ui.writeLine(chalk.yellow('The "' + key + '" alias cannot be overridden. Please use a different alias.'));
// delete offending alias from options
var index = this.availableOptions.indexOf(option);
var aliasIndex = this.availableOptions[index].aliases.indexOf(alias.original);
if (this.availableOptions[index].aliases[aliasIndex]) {
delete this.availableOptions[index].aliases[aliasIndex];
}
}
}
return false;
}
};
/*
Parses command arguments and processes
@method parseArgs
@param {Object} commandArgs
@return {Object|null}
*/
Command.prototype.parseArgs = function(commandArgs) {
var knownOpts = {}; // Parse options
var commandOptions = {};
var parsedOptions;
var assembleAndValidateOption = function(option) {
return this.assignOption(option, parsedOptions, commandOptions);
};
var validateParsed = function(key) {
// ignore 'argv', 'h', and 'help'
if (!commandOptions.hasOwnProperty(key) && key !== 'argv' && key !== 'h' && key !== 'help') {
this.ui.writeLine(chalk.yellow('The option \'--' + key + '\' is not registered with the ' + this.name + ' command. ' +
'Run `ember ' + this.name + ' --help` for a list of supported options.'));
}
if (typeof parsedOptions[key] !== 'object') {
commandOptions[camelize(key)] = parsedOptions[key];
}
};
this.availableOptions.forEach(function(option) {
knownOpts[option.name] = option.type;
});
parsedOptions = nopt(knownOpts, this.optionsAliases, commandArgs, 0);
if (!this.availableOptions.every(assembleAndValidateOption.bind(this))) {
return null;
}
keys(parsedOptions).map(validateParsed.bind(this));
return {
options: defaults(commandOptions, this.settings),
args: parsedOptions.argv.remain
};
};
/*
*/
Command.prototype.run = function(commandArgs) {
throw new Error('command must implement run' + commandArgs.toString());
};
/*
Prints basic help for the command.
Basic help looks like this:
ember generate <blueprint> <options...>
Generates new code from blueprints
aliases: g
--dry-run (Default: false)
--verbose (Default: false)
The default implementation is designed to cover all bases
but may be overriden if necessary.
@method printBasicHelp
*/
Command.prototype.printBasicHelp = function() {
// ember command-name
var output;
if (this.isRoot) {
output = 'Usage: ' + this.name;
} else {
output = 'ember ' + this.name;
}
// <anonymous-option-1> ...
if (this.anonymousOptions.length > 0) {
var anonymousOptions = this.anonymousOptions;
if (anonymousOptions.join) {
anonymousOptions = anonymousOptions.join(' ');
}
output += ' ' + chalk.yellow(anonymousOptions);
}
// <options...>
if (this.availableOptions.length > 0) {
output += chalk.cyan(' <options...>');
}
output += EOL;
// Description
if (this.description) {
output += ' ' + this.description + EOL;
}
// aliases: a b c
if (this.aliases.length) {
output += chalk.grey(' aliases: ' + this.aliases.filter(function(a) { return a; }).join(', ') + EOL);
}
// --available-option (Required) (Default: value)
// ...
if (this.availableOptions.length > 0) {
this.availableOptions.forEach(function(option) {
output += chalk.cyan(' --' + option.name);
if (option.type) {
output += chalk.cyan(' (' + (Array.isArray(option.type) ? option.type.map(function(a) {
return typeof a === 'string' ? a : a.name;
}).join(', ') : option.type.name) + ')');
}
if (option.required) {
output += chalk.cyan(' (Required)');
}
if (option.default !== undefined) {
output += chalk.cyan(' (Default: ' + option.default + ')');
}
if (option.description) {
output += ' ' + option.description;
}
if (option.aliases) {
output += chalk.grey(EOL + ' aliases: ' + option.aliases.map(function(a) {
var key;
if (typeof a === 'string') {
return '-' + a + (option.type === Boolean ? '' : ' <value>');
} else {
key = Object.keys(a)[0];
return '-' + key + ' (--' + option.name + '=' + a[key] + ')';
}
}).join(', '));
}
output += EOL;
});
}
this.ui.writeLine(output);
};
/*
Prints detailed help for the command.
The default implementation is no-op and should be overridden
for each command where further help text is required.
@method printDetailedHelp
*/
Command.prototype.printDetailedHelp = function() {};
/*
Validates options parsed by nopt
*/
function isValidParsedOption(option, parsedOption) {
// option.name didn't parse
if (parsedOption === undefined) {
// no default
if (option.default === undefined) {
if (option.required) {
return false;
}
}
}
return true;
}
/*
Validates alias. Must be a string or single key object
*/
function isValidAlias(alias, expectedType) {
var type = typeof alias;
if (type === 'string') {
return true;
} else if (type === 'object') {
// no arrays, no multi-key objects
if (!Array.isArray(alias) && Object.keys(alias).length === 1) {
var valueType = typeof alias[Object.keys(alias)[0]];
if (valueType === expectedType.name.toLowerCase()) {
return true;
}
}
}
return false;
}
|
/* eslint-disable no-implicit-coercion, no-shadow */
var Promise = require('lie');
var loader = require('little-loader');
var cache = global.__requireAsyncCache = global.__requireAsyncCache || {};
function createBundlePromise ( opts, _require, urlRoot ) {
return Promise.resolve()
.then(function () {
return _require('' + opts.name);
})
.catch(function () {
return new Promise(function ( resolve, reject ) {
loader(urlRoot + opts.url, function ( err ) {
if ( err ) {
return reject(err);
}
try {
resolve(_require('' + opts.name));
} catch ( err1 ) {
if ( /require.async/.test(err1) ) {
return reject(Error(err1));
}
try {
resolve(_require('' + opts.hash));
} catch ( err2 ) {
reject(Error(err1));
}
}
});
});
});
}
module.exports = function ( _require, options ) {
return function ( el, cb, errCb ) {
var bundles = [].concat(el);
var promises = [];
var bundle, i, bundlesLength;
for ( i = 0, bundlesLength = bundles.length; i < bundlesLength; i++ ) {
bundle = bundles[i];
if ( !cache[bundle.hash] ) {
cache[bundle.hash] = createBundlePromise(bundle, _require, options.urlRoot);
}
promises.push(cache[bundle.hash]);
}
return Promise.all(promises)
.then(function ( reqs ) {
return cb && cb.apply(null, reqs);
})
.catch(function ( err ) {
if ( options.rethrowError ) {
return setTimeout(function () {
throw err;
}, 0);
}
return errCb && errCb(err);
});
};
};
|
'use strict';
/**
* Module dependencies
*/
const fs = require('fs');
const path = require('path');
const util = require('util');
const File = require('vinyl');
const ansi = require('ansi');
const Emitter = require('component-emitter');
const Benchmark = require('benchmark');
const define = require('define-property');
const reader = require('file-reader');
const isGlob = require('is-glob');
const typeOf = require('kind-of');
const merge = require('mixin-deep');
const glob = require('resolve-glob');
const log = require('log-utils');
const mm = require('micromatch');
/**
* Local variables
*/
const utils = require('./lib/utils');
const cursor = ansi(process.stdout);
const colors = log.colors;
/**
* Create an instance of Benchmarked with the given `options`.
*
* ```js
* const suite = new Suite();
* ```
* @param {Object} `options`
* @api public
*/
function Benchmarked(options) {
if (!(this instanceof Benchmarked)) {
return new Benchmarked(options);
}
Emitter.call(this);
this.options = Object.assign({}, options);
this.results = [];
this.defaults(this);
}
/**
* Inherit Emitter
*/
util.inherits(Benchmarked, Emitter);
/**
* Default settings
*/
Benchmarked.prototype.defaults = function(benchmarked) {
this.fixtures = {
files: [],
cache: {},
toFile: function(file) {
const str = fs.readFileSync(file.path, 'utf8');
file.content = reader.file(file);
file.bytes = util.format('(%d bytes)', str.length);
}
};
this.code = {
files: [],
cache: {},
toFile: function(file) {
file.run = require(file.path);
}
};
if (typeof this.options.format === 'function') {
this.format = this.options.format;
}
if (this.options.fixtures) {
this.addFixtures(this.options.fixtures);
}
if (this.options.code) {
this.addCode(this.options.code);
}
};
/**
* Default formatter for benchmark.
*
* @param {Benchmark} `benchmark` The Benchmark to produce a string from.
*/
Benchmarked.prototype.format = function(benchmark) {
return ' ' + benchmark;
};
/**
* Create a vinyl file object.
*
* @param {String} `type` The type of file to create (`code` or `fixture`)
* @param {String} `filepath`
*/
Benchmarked.prototype.toFile = function(type, filepath, options) {
const opts = merge({cwd: this.cwd}, this.options, options);
let file = new File({path: path.resolve(opts.cwd, filepath)});
file.key = utils.setKey(file, opts);
file.inspect = function() {
return '<' + utils.toTitle(type) + ' ' + this.key + '"' + this.relative + '">';
};
const fn = opts.toFile || this[type].toFile;
const res = fn.call(this, file);
if (utils.isFile(res)) {
file = res;
}
return file;
};
/**
* Add fixtures to run benchmarks against.
*
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
*/
Benchmarked.prototype.filter = function(type, patterns, options) {
if (typeof patterns === 'undefined') {
patterns = '*';
}
const isMatch = mm.matcher(patterns, options);
const results = [];
for (let file of this.fixtures.files) {
if (isMatch(file.basename)) {
file.suite = this.addSuite(file, options);
results.push(file);
}
}
return results;
};
/**
* Add fixtures to run benchmarks against.
*
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
*/
Benchmarked.prototype.match = function(type, patterns, options) {
return mm.matchKeys(this[type].files, patterns, options);
};
/**
* Add fixtures to run benchmarks against.
*
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
*/
Benchmarked.prototype.addFile = function(type, file, options) {
if (isGlob(file) || Array.isArray(file)) {
return this.addFiles.apply(this, arguments);
}
if (typeof file === 'string') {
file = this.toFile(type, file, options);
}
if (!utils.isFile(file)) {
throw new Error('expected "file" to be a vinyl file object');
}
this[type].cache[file.path] = file;
this[type].files.push(file);
return this;
};
/**
* Add fixtures to run benchmarks against.
*
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
*/
Benchmarked.prototype.addFiles = function(type, files, options) {
const opts = merge({cwd: this.cwd}, this.options, options);
switch (typeOf(files)) {
case 'string':
if (isGlob(files)) {
this.addFiles(type, glob.sync(files, opts), options);
} else {
this.addFile(type, files, options);
}
break;
case 'array':
this.addFilesArray(type, files, options);
break;
case 'object':
this.addFilesObject(type, files, options);
break;
default: {
throw new TypeError('cannot load files: ', util.inspect(arguments));
}
}
return this;
};
/**
* Add an array of `files` to the files array and cache for the given `type`.
*
* @param {String} `type` Either `code` or `fixtures`
* @param {Array} Files to add
* @param {Object}
*/
Benchmarked.prototype.addFilesArray = function(type, files, options) {
for (let file of files) {
this.addFile(type, file, options);
}
return this;
};
/**
* Add a fixture to run benchmarks against.
*
* @param {String|Function} `fixture` Filepath or function
*/
Benchmarked.prototype.addFilesObject = function(type, files, options) {
for (let key in Object.keys(files)) {
this.addFile(type, files[key], options);
}
return this;
};
/**
* Add a fixture to run benchmarks against.
*
* @param {String|Function} `fixture` Filepath or function
*/
Benchmarked.prototype.addFixture = function(file, options) {
this.addFile('fixtures', file, options);
return this;
};
/**
* Add fixtures to run benchmarks against.
*
* ```js
* benchmarks.addFixtures('fixtures/*.txt');
* ```
* @param {String|Array} `patterns` Filepaths or glob patterns.
* @param {Options} `options`
* @api public
*/
Benchmarked.prototype.addFixtures = function(files, options) {
this.addFiles('fixtures', files, options);
return this;
};
/**
* Specify the functions to be benchmarked.
*
* ```js
* benchmarks.addCode('fixtures/*.txt');
* ```
* @param {String|Array} `patterns` Filepath(s) or glob patterns.
* @param {Options} `options`
* @api public
*/
Benchmarked.prototype.addCode = function(file, options) {
this.addFiles('code', file, options);
return this;
};
/**
* Add benchmark suite to the given `fixture` file.
*
* @param {Object} `fixture` vinyl file object
* @api public
*/
Benchmarked.prototype.addSuite = function(fixture, options) {
var files = this.code.files;
var opts = this.options;
var format = this.format;
// capture results for this suite
var res = {name: fixture.key, file: fixture, results: []};
define(res, 'fixture', fixture);
this.results.push(res);
if (opts.dryRun === true) {
files.forEach(function(file) {
console.log(file.run(fixture.content));
});
return;
}
var suite = new Benchmark.Suite(fixture.bytes, {
name: fixture.key,
onStart: function onStart() {
console.log(colors.cyan('\n# %s %s'), fixture.relative, fixture.bytes);
},
onComplete: function() {
cursor.write('\n');
}
});
files.forEach((file) => {
suite.add(file.key, Object.assign({
onCycle: function onCycle(event) {
cursor.horizontalAbsolute();
cursor.eraseLine();
cursor.write(format(event.target));
},
fn: function() {
return file.run.apply(null, utils.arrayify(fixture.content));
},
onComplete: function(event) {
cursor.horizontalAbsolute();
cursor.eraseLine();
cursor.write(format(event.target));
cursor.write('\n');
res.results.push(utils.captureBench(event, file));
},
onAbort: this.emit.bind(this, 'error'),
onError: this.emit.bind(this, 'error')
}, options));
});
if (files.length <= 1) {
this.emit('complete', res);
return suite;
}
suite.on('complete', () => {
var fastest = suite.filter('fastest').map('name');
res.fastest = fastest;
this.emit('complete', res);
console.log(' fastest is', colors.green(fastest));
});
return suite;
};
/**
* Run the benchmarks.
*
* ```js
* benchmarks.run();
* ```
* @param {Object} `options`
* @param {Function} `cb`
* @param {Object} `thisArg`
* @api public
*/
Benchmarked.prototype.run = function(patterns, options, cb) {
if (typeof options === 'function') {
cb = options;
options = { async: true };
}
var fixtures = this.filter('fixtures', patterns, options);
if (fixtures.length > 0) {
console.log('Benchmarking: (%d of %d)', fixtures.length, this.fixtures.files.length);
fixtures.forEach(function(file) {
console.log(' · %s', file.key);
});
} else {
console.log('No matches for patterns: %s', util.inspect(patterns));
}
fixtures.forEach(function(file) {
file.suite.run(options);
});
this.emit('end', this.results);
};
Benchmarked.prototype.dryRun = function(pattern, options, fn) {
if (typeof options === 'function') {
fn = options;
options = null;
}
if (typeof pattern === 'function') {
fn = pattern;
options = {};
pattern = '**/*';
}
if (typeof fn !== 'function') {
throw new TypeError('Expected fn to be a function');
}
var opts = Object.assign({ async: true }, options);
var fixtures = this.filter('fixtures', pattern, opts);
var len = this.fixtures.files.length;
var code = this.code;
if (fixtures.length > 0) {
console.log('Dry run for (%d of %d) fixtures:', fixtures.length, len);
fixtures.forEach(function(file) {
console.log(' · %s', file.key);
});
} else {
console.log('No matches for pattern: %s', util.inspect(pattern));
}
console.log();
code.files.forEach(function(file) {
fixtures.forEach(function(fixture) {
fn(file, fixture);
});
});
};
Benchmarked.run = function(options) {
const opts = Object.assign({cwd: process.cwd()}, options);
if (fs.existsSync(path.join(opts.cwd, 'benchmark'))) {
opts.cwd = path.join(opts.cwd, 'benchmark');
}
return new Promise(function(resolve, reject) {
const suite = new Benchmarked({
cwd: __dirname,
fixtures: path.join(opts.cwd, opts.fixtures),
code: path.join(opts.cwd, opts.code)
});
suite.on('error', reject);
if (opts.dry) {
suite.dryRun(function(code, fixture) {
console.log(colors.cyan('%s > %s'), code.key, fixture.key);
const args = require(fixture.path).slice();
const expected = args.pop();
const actual = code.invoke.apply(null, args);
console.log(expected, actual);
console.log();
resolve();
});
} else {
suite.on('end', resolve);
suite.run();
}
});
};
Benchmarked.render = function(benchmarks) {
const res = [];
for (let i = 0; i < benchmarks.length; i++) {
const target = benchmarks[i];
let b = `# ${target.name} ${target.file.bytes}\n`;
for (let i = 0; i < target.results.length; i++) {
const stats = target.results[i];
b += ` ${stats.name} x ${stats.ops} ops/sec ±${stats.rme}%`;
b += ` (${stats.runs} runs sampled)\n`;
}
b += `\n fastest is ${target.fastest.join(', ')}`;
b += ` (by ${diff(target)} avg)\n`;
res.push(b);
}
return res.join('\n');
};
function diff(target) {
let len = target.results.length;
let fastest = 0;
let rest = 0;
for (let i = 0; i < len; i++) {
let stats = target.results[i];
if (target.fastest.indexOf(stats.name) !== -1) {
fastest = +stats.hz;
} else {
rest += +stats.hz;
}
}
var avg = (fastest / (+rest / (len - 1)) * 100);
return avg.toFixed() + '%';
}
/**
* Expose `Benchmarked`
*/
module.exports = Benchmarked;
|
import Ember from "ember-metal/core";
import { get } from "ember-metal/property_get";
import EmberError from "ember-metal/error";
import run from "ember-metal/run_loop";
import jQuery from "ember-views/system/jquery";
import Test from "ember-testing/test";
/**
* @module ember
* @submodule ember-testing
*/
var helper = Test.registerHelper;
var asyncHelper = Test.registerAsyncHelper;
var countAsync = 0;
function currentRouteName(app) {
var appController = app.__container__.lookup('controller:application');
return get(appController, 'currentRouteName');
}
function currentPath(app) {
var appController = app.__container__.lookup('controller:application');
return get(appController, 'currentPath');
}
function currentURL(app) {
var router = app.__container__.lookup('router:main');
return get(router, 'location').getURL();
}
function pauseTest() {
Test.adapter.asyncStart();
return new Ember.RSVP.Promise(function() { }, 'TestAdapter paused promise');
}
function focus(el) {
if (el && el.is(':input, [contenteditable=true]')) {
var type = el.prop('type');
if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') {
run(el, function() {
// Firefox does not trigger the `focusin` event if the window
// does not have focus. If the document doesn't have focus just
// use trigger('focusin') instead.
if (!document.hasFocus || document.hasFocus()) {
this.focus();
} else {
this.trigger('focusin');
}
});
}
}
}
function visit(app, url) {
var router = app.__container__.lookup('router:main');
if (app._readinessDeferrals > 0) {
router['initialURL'] = url;
run(app, 'advanceReadiness');
delete router['initialURL'];
} else {
router.location.setURL(url);
run(app.__deprecatedInstance__, 'handleURL', url);
}
return app.testHelpers.wait();
}
function click(app, selector, context) {
var $el = app.testHelpers.findWithAssert(selector, context);
run($el, 'mousedown');
focus($el);
run($el, 'mouseup');
run($el, 'click');
return app.testHelpers.wait();
}
function check(app, selector, context) {
var $el = app.testHelpers.findWithAssert(selector, context);
var type = $el.prop('type');
Ember.assert('To check \'' + selector +
'\', the input must be a checkbox', type === 'checkbox');
if (!$el.prop('checked')) {
app.testHelpers.click(selector, context);
}
return app.testHelpers.wait();
}
function uncheck(app, selector, context) {
var $el = app.testHelpers.findWithAssert(selector, context);
var type = $el.prop('type');
Ember.assert('To uncheck \'' + selector +
'\', the input must be a checkbox', type === 'checkbox');
if ($el.prop('checked')) {
app.testHelpers.click(selector, context);
}
return app.testHelpers.wait();
}
function triggerEvent(app, selector, contextOrType, typeOrOptions, possibleOptions) {
var arity = arguments.length;
var context, type, options;
if (arity === 3) {
// context and options are optional, so this is
// app, selector, type
context = null;
type = contextOrType;
options = {};
} else if (arity === 4) {
// context and options are optional, so this is
if (typeof typeOrOptions === "object") { // either
// app, selector, type, options
context = null;
type = contextOrType;
options = typeOrOptions;
} else { // or
// app, selector, context, type
context = contextOrType;
type = typeOrOptions;
options = {};
}
} else {
context = contextOrType;
type = typeOrOptions;
options = possibleOptions;
}
var $el = app.testHelpers.findWithAssert(selector, context);
var event = jQuery.Event(type, options);
run($el, 'trigger', event);
return app.testHelpers.wait();
}
function keyEvent(app, selector, contextOrType, typeOrKeyCode, keyCode) {
var context, type;
if (typeof keyCode === 'undefined') {
context = null;
keyCode = typeOrKeyCode;
type = contextOrType;
} else {
context = contextOrType;
type = typeOrKeyCode;
}
return app.testHelpers.triggerEvent(selector, context, type, { keyCode: keyCode, which: keyCode });
}
function fillIn(app, selector, contextOrText, text) {
var $el, context;
if (typeof text === 'undefined') {
text = contextOrText;
} else {
context = contextOrText;
}
$el = app.testHelpers.findWithAssert(selector, context);
focus($el);
run(function() {
$el.val(text).change();
});
return app.testHelpers.wait();
}
function findWithAssert(app, selector, context) {
var $el = app.testHelpers.find(selector, context);
if ($el.length === 0) {
throw new EmberError("Element " + selector + " not found.");
}
return $el;
}
function find(app, selector, context) {
var $el;
context = context || get(app, 'rootElement');
$el = app.$(selector, context);
return $el;
}
function andThen(app, callback) {
return app.testHelpers.wait(callback(app));
}
function wait(app, value) {
return Test.promise(function(resolve) {
// If this is the first async promise, kick off the async test
if (++countAsync === 1) {
Test.adapter.asyncStart();
}
// Every 10ms, poll for the async thing to have finished
var watcher = setInterval(function() {
var router = app.__container__.lookup('router:main');
// 1. If the router is loading, keep polling
var routerIsLoading = router.router && !!router.router.activeTransition;
if (routerIsLoading) { return; }
// 2. If there are pending Ajax requests, keep polling
if (Test.pendingAjaxRequests) { return; }
// 3. If there are scheduled timers or we are inside of a run loop, keep polling
if (run.hasScheduledTimers() || run.currentRunLoop) { return; }
if (Test.waiters && Test.waiters.any(function(waiter) {
var context = waiter[0];
var callback = waiter[1];
return !callback.call(context);
})) {
return;
}
// Stop polling
clearInterval(watcher);
// If this is the last async promise, end the async test
if (--countAsync === 0) {
Test.adapter.asyncEnd();
}
// Synchronously resolve the promise
run(null, resolve, value);
}, 10);
});
}
/**
* Loads a route, sets up any controllers, and renders any templates associated
* with the route as though a real user had triggered the route change while
* using your app.
*
* Example:
*
* ```javascript
* visit('posts/index').then(function() {
* // assert something
* });
* ```
*
* @method visit
* @param {String} url the name of the route
* @return {RSVP.Promise}
*/
asyncHelper('visit', visit);
/**
* Clicks an element and triggers any actions triggered by the element's `click`
* event.
*
* Example:
*
* ```javascript
* click('.some-jQuery-selector').then(function() {
* // assert something
* });
* ```
*
* @method click
* @param {String} selector jQuery selector for finding element on the DOM
* @return {RSVP.Promise}
*/
asyncHelper('click', click);
if (Ember.FEATURES.isEnabled('ember-testing-checkbox-helpers')) {
/**
* Checks a checkbox. Ensures the presence of the `checked` attribute
*
* Example:
*
* ```javascript
* check('#remember-me').then(function() {
* // assert something
* });
* ```
*
* @method check
* @param {String} selector jQuery selector finding an `input[type="checkbox"]`
* element on the DOM to check
* @return {RSVP.Promise}
*/
asyncHelper('check', check);
/**
* Unchecks a checkbox. Ensures the absence of the `checked` attribute
*
* Example:
*
* ```javascript
* uncheck('#remember-me').then(function() {
* // assert something
* });
* ```
*
* @method check
* @param {String} selector jQuery selector finding an `input[type="checkbox"]`
* element on the DOM to uncheck
* @return {RSVP.Promise}
*/
asyncHelper('uncheck', uncheck);
}
/**
* Simulates a key event, e.g. `keypress`, `keydown`, `keyup` with the desired keyCode
*
* Example:
*
* ```javascript
* keyEvent('.some-jQuery-selector', 'keypress', 13).then(function() {
* // assert something
* });
* ```
*
* @method keyEvent
* @param {String} selector jQuery selector for finding element on the DOM
* @param {String} type the type of key event, e.g. `keypress`, `keydown`, `keyup`
* @param {Number} keyCode the keyCode of the simulated key event
* @return {RSVP.Promise}
* @since 1.5.0
*/
asyncHelper('keyEvent', keyEvent);
/**
* Fills in an input element with some text.
*
* Example:
*
* ```javascript
* fillIn('#email', 'you@example.com').then(function() {
* // assert something
* });
* ```
*
* @method fillIn
* @param {String} selector jQuery selector finding an input element on the DOM
* to fill text with
* @param {String} text text to place inside the input element
* @return {RSVP.Promise}
*/
asyncHelper('fillIn', fillIn);
/**
* Finds an element in the context of the app's container element. A simple alias
* for `app.$(selector)`.
*
* Example:
*
* ```javascript
* var $el = find('.my-selector');
* ```
*
* @method find
* @param {String} selector jQuery string selector for element lookup
* @return {Object} jQuery object representing the results of the query
*/
helper('find', find);
/**
* Like `find`, but throws an error if the element selector returns no results.
*
* Example:
*
* ```javascript
* var $el = findWithAssert('.doesnt-exist'); // throws error
* ```
*
* @method findWithAssert
* @param {String} selector jQuery selector string for finding an element within
* the DOM
* @return {Object} jQuery object representing the results of the query
* @throws {Error} throws error if jQuery object returned has a length of 0
*/
helper('findWithAssert', findWithAssert);
/**
Causes the run loop to process any pending events. This is used to ensure that
any async operations from other helpers (or your assertions) have been processed.
This is most often used as the return value for the helper functions (see 'click',
'fillIn','visit',etc).
Example:
```javascript
Ember.Test.registerAsyncHelper('loginUser', function(app, username, password) {
visit('secured/path/here')
.fillIn('#username', username)
.fillIn('#password', password)
.click('.submit')
return app.testHelpers.wait();
});
@method wait
@param {Object} value The value to be returned.
@return {RSVP.Promise}
*/
asyncHelper('wait', wait);
asyncHelper('andThen', andThen);
/**
Returns the currently active route name.
Example:
```javascript
function validateRouteName() {
equal(currentRouteName(), 'some.path', "correct route was transitioned into.");
}
visit('/some/path').then(validateRouteName)
```
@method currentRouteName
@return {Object} The name of the currently active route.
@since 1.5.0
*/
helper('currentRouteName', currentRouteName);
/**
Returns the current path.
Example:
```javascript
function validateURL() {
equal(currentPath(), 'some.path.index', "correct path was transitioned into.");
}
click('#some-link-id').then(validateURL);
```
@method currentPath
@return {Object} The currently active path.
@since 1.5.0
*/
helper('currentPath', currentPath);
/**
Returns the current URL.
Example:
```javascript
function validateURL() {
equal(currentURL(), '/some/path', "correct URL was transitioned into.");
}
click('#some-link-id').then(validateURL);
```
@method currentURL
@return {Object} The currently active URL.
@since 1.5.0
*/
helper('currentURL', currentURL);
/**
Pauses the current test - this is useful for debugging while testing or for test-driving.
It allows you to inspect the state of your application at any point.
Example (The test will pause before clicking the button):
```javascript
visit('/')
return pauseTest();
click('.btn');
```
@since 1.9.0
@method pauseTest
@return {Object} A promise that will never resolve
*/
helper('pauseTest', pauseTest);
/**
Triggers the given DOM event on the element identified by the provided selector.
Example:
```javascript
triggerEvent('#some-elem-id', 'blur');
```
This is actually used internally by the `keyEvent` helper like so:
```javascript
triggerEvent('#some-elem-id', 'keypress', { keyCode: 13 });
```
@method triggerEvent
@param {String} selector jQuery selector for finding element on the DOM
@param {String} [context] jQuery selector that will limit the selector
argument to find only within the context's children
@param {String} type The event type to be triggered.
@param {Object} [options] The options to be passed to jQuery.Event.
@return {RSVP.Promise}
@since 1.5.0
*/
asyncHelper('triggerEvent', triggerEvent);
|
/**
* DepositoryVersion Manager module.
* @module resource-managers/depository-version-manager
* @see module:resource-managers/resource-manager
*/
'use strict';
var console = require('../utils/console');
var ResourceManager = require('./resource-manager');
/**
* DepositoryVersion Manager Object
*
* Class representing an API Depository Versions manager.
* Depositories and datasets may be updated periodically.
* Depository versions are a mechanism to keep track of changes within a depository.
* Depository versions are named according to the Semantic Versioning guidelines.
* Example version names include: 1.0.0 and 0.0.1-2014-01-01.
*
* @constructor
* @augments ResourceManager
* @requires module:resource-managers/resource-manager
*/
var DepositoryVersionManager = function(solveBio, id) {
var path = '/v1/depository_versions';
// Call the parent constructor, making sure (using Function#call)
// that "this" is set correctly during the call
ResourceManager.call(this, solveBio, path, id);
};
DepositoryVersionManager.prototype = Object.create(ResourceManager.prototype);
/**
* List datasets in a depository version.
*
* @returns {Promise} API response.
*/
DepositoryVersionManager.prototype.datasets = function() {
if(this._id) {
return this._solveBio.get(this._path + '/' + this._id + '/datasets', {});
}
else {
console.error('You need to specify a version id.');
}
};
/**
* Retrieves the changelog of a specific depository_version by its full name or ID.
* The response will show which attributes were removed, added or changed.
*
* @returns {Promise} API response.
*/
DepositoryVersionManager.prototype.changelog = function() {
if(this._id) {
return this._solveBio.get(this._path + '/' + this._id + '/changelog', {});
}
else {
console.error('You need to specify a version id.');
}
};
module.exports = DepositoryVersionManager;
|
version https://git-lfs.github.com/spec/v1
oid sha256:8d212c4923076ea6312c861f6baba6066b830dcacc2a3fcc1e6a21731667c813
size 8096
|
/**
* Created by Pillar on 2015/6/4.
*/
console.log('I am storage.js');
sb = 123;
|
export { default } from 'ember-flexberry-designer/serializers/fd-dev-uml-dpd';
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.