code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
|---|---|---|---|---|---|
exports.hasBeenLoaded = false;
exports.load = function() {
exports.hasBeenLoaded = true;
}
|
bitgamma/plugin-loader
|
test/test_plugins/plugin1/index.js
|
JavaScript
|
mit
| 94
|
/*!
* Stickyfill -- `position: sticky` polyfill
* v. 1.1.4 | https://github.com/wilddeer/stickyfill
* Copyright Oleg Korsunsky | http://wd.dizaina.net/
*
* MIT License
*/
(function(doc, win) {
var watchArray = [],
scroll,
initialized = false,
html = doc.documentElement,
noop = function() {},
checkTimer,
//visibility API strings
hiddenPropertyName = 'hidden',
visibilityChangeEventName = 'visibilitychange';
//fallback to prefixed names in old webkit browsers
if (doc.webkitHidden !== undefined) {
hiddenPropertyName = 'webkitHidden';
visibilityChangeEventName = 'webkitvisibilitychange';
}
//test getComputedStyle
if (!win.getComputedStyle) {
seppuku();
}
//test for native support
var prefixes = ['', '-webkit-', '-moz-', '-ms-'],
block = document.createElement('div');
for (var i = prefixes.length - 1; i >= 0; i--) {
try {
block.style.position = prefixes[i] + 'sticky';
}
catch(e) {}
if (block.style.position != '') {
seppuku();
}
}
updateScrollPos();
//commit seppuku!
function seppuku() {
init = add = rebuild = pause = stop = kill = noop;
}
function mergeObjects(targetObj, sourceObject) {
for (var key in sourceObject) {
if (sourceObject.hasOwnProperty(key)) {
targetObj[key] = sourceObject[key];
}
}
}
function parseNumeric(val) {
return parseFloat(val) || 0;
}
function updateScrollPos() {
scroll = {
top: win.pageYOffset,
left: win.pageXOffset
};
}
function onScroll() {
if (win.pageXOffset != scroll.left) {
updateScrollPos();
rebuild();
return;
}
if (win.pageYOffset != scroll.top) {
updateScrollPos();
recalcAllPos();
}
}
//fixes flickering
function onWheel(event) {
setTimeout(function() {
if (win.pageYOffset != scroll.top) {
scroll.top = win.pageYOffset;
recalcAllPos();
}
}, 0);
}
function recalcAllPos() {
for (var i = watchArray.length - 1; i >= 0; i--) {
recalcElementPos(watchArray[i]);
}
}
function recalcElementPos(el) {
if (!el.inited) return;
var currentMode = (scroll.top <= el.limit.start? 0: scroll.top >= el.limit.end? 2: 1);
if (el.mode != currentMode) {
switchElementMode(el, currentMode);
}
}
//checks whether stickies start or stop positions have changed
function fastCheck() {
for (var i = watchArray.length - 1; i >= 0; i--) {
if (!watchArray[i].inited) continue;
var deltaTop = Math.abs(getDocOffsetTop(watchArray[i].clone) - watchArray[i].docOffsetTop),
deltaHeight = Math.abs(watchArray[i].parent.node.offsetHeight - watchArray[i].parent.height);
if (deltaTop >= 2 || deltaHeight >= 2) return false;
}
return true;
}
function initElement(el) {
if (isNaN(parseFloat(el.computed.top)) || el.isCell || el.computed.display == 'none') return;
el.inited = true;
if (!el.clone) clone(el);
if (el.parent.computed.position != 'absolute' &&
el.parent.computed.position != 'relative') el.parent.node.style.position = 'relative';
recalcElementPos(el);
el.parent.height = el.parent.node.offsetHeight;
el.docOffsetTop = getDocOffsetTop(el.clone);
}
function deinitElement(el) {
var deinitParent = true;
el.clone && killClone(el);
mergeObjects(el.node.style, el.css);
//check whether element's parent is used by other stickies
for (var i = watchArray.length - 1; i >= 0; i--) {
if (watchArray[i].node !== el.node && watchArray[i].parent.node === el.parent.node) {
deinitParent = false;
break;
}
};
if (deinitParent) el.parent.node.style.position = el.parent.css.position;
el.mode = -1;
}
function initAll() {
for (var i = watchArray.length - 1; i >= 0; i--) {
initElement(watchArray[i]);
}
}
function deinitAll() {
for (var i = watchArray.length - 1; i >= 0; i--) {
deinitElement(watchArray[i]);
}
}
function switchElementMode(el, mode) {
var nodeStyle = el.node.style;
switch (mode) {
case 0:
nodeStyle.position = 'absolute';
nodeStyle.left = el.offset.left + 'px';
nodeStyle.right = el.offset.right + 'px';
nodeStyle.top = el.offset.top + 'px';
nodeStyle.bottom = 'auto';
nodeStyle.width = 'auto';
nodeStyle.marginLeft = 0;
nodeStyle.marginRight = 0;
nodeStyle.marginTop = 0;
break;
case 1:
nodeStyle.position = 'fixed';
nodeStyle.left = el.box.left + 'px';
nodeStyle.right = el.box.right + 'px';
nodeStyle.top = el.css.top;
nodeStyle.bottom = 'auto';
nodeStyle.width = 'auto';
nodeStyle.marginLeft = 0;
nodeStyle.marginRight = 0;
nodeStyle.marginTop = 0;
break;
case 2:
nodeStyle.position = 'absolute';
nodeStyle.left = el.offset.left + 'px';
nodeStyle.right = el.offset.right + 'px';
nodeStyle.top = 'auto';
nodeStyle.bottom = 0;
nodeStyle.width = 'auto';
nodeStyle.marginLeft = 0;
nodeStyle.marginRight = 0;
break;
}
el.mode = mode;
}
function clone(el) {
el.clone = document.createElement('div');
var refElement = el.node.nextSibling || el.node,
cloneStyle = el.clone.style;
cloneStyle.height = el.height + 'px';
cloneStyle.width = el.width + 'px';
cloneStyle.marginTop = el.computed.marginTop;
cloneStyle.marginBottom = el.computed.marginBottom;
cloneStyle.marginLeft = el.computed.marginLeft;
cloneStyle.marginRight = el.computed.marginRight;
cloneStyle.padding = cloneStyle.border = cloneStyle.borderSpacing = 0;
cloneStyle.fontSize = '1em';
cloneStyle.position = 'static';
cloneStyle.cssFloat = el.computed.cssFloat;
el.node.parentNode.insertBefore(el.clone, refElement);
}
function killClone(el) {
el.clone.parentNode.removeChild(el.clone);
el.clone = undefined;
}
function getElementParams(node) {
var computedStyle = getComputedStyle(node),
parentNode = node.parentNode,
parentComputedStyle = getComputedStyle(parentNode),
cachedPosition = node.style.position;
node.style.position = 'relative';
var computed = {
top: computedStyle.top,
marginTop: computedStyle.marginTop,
marginBottom: computedStyle.marginBottom,
marginLeft: computedStyle.marginLeft,
marginRight: computedStyle.marginRight,
cssFloat: computedStyle.cssFloat,
display: computedStyle.display
},
numeric = {
top: parseNumeric(computedStyle.top),
marginBottom: parseNumeric(computedStyle.marginBottom),
paddingLeft: parseNumeric(computedStyle.paddingLeft),
paddingRight: parseNumeric(computedStyle.paddingRight),
borderLeftWidth: parseNumeric(computedStyle.borderLeftWidth),
borderRightWidth: parseNumeric(computedStyle.borderRightWidth)
};
node.style.position = cachedPosition;
var css = {
position: node.style.position,
top: node.style.top,
bottom: node.style.bottom,
left: node.style.left,
right: node.style.right,
width: node.style.width,
marginTop: node.style.marginTop,
marginLeft: node.style.marginLeft,
marginRight: node.style.marginRight
},
nodeOffset = getElementOffset(node),
parentOffset = getElementOffset(parentNode),
parent = {
node: parentNode,
css: {
position: parentNode.style.position
},
computed: {
position: parentComputedStyle.position
},
numeric: {
borderLeftWidth: parseNumeric(parentComputedStyle.borderLeftWidth),
borderRightWidth: parseNumeric(parentComputedStyle.borderRightWidth),
borderTopWidth: parseNumeric(parentComputedStyle.borderTopWidth),
borderBottomWidth: parseNumeric(parentComputedStyle.borderBottomWidth)
}
},
el = {
node: node,
box: {
left: nodeOffset.win.left,
right: html.clientWidth - nodeOffset.win.right
},
offset: {
top: nodeOffset.win.top - parentOffset.win.top - parent.numeric.borderTopWidth,
left: nodeOffset.win.left - parentOffset.win.left - parent.numeric.borderLeftWidth,
right: -nodeOffset.win.right + parentOffset.win.right - parent.numeric.borderRightWidth
},
css: css,
isCell: computedStyle.display == 'table-cell',
computed: computed,
numeric: numeric,
width: nodeOffset.win.right - nodeOffset.win.left,
height: nodeOffset.win.bottom - nodeOffset.win.top,
mode: -1,
inited: false,
parent: parent,
limit: {
start: nodeOffset.doc.top - numeric.top,
end: parentOffset.doc.top + parentNode.offsetHeight - parent.numeric.borderBottomWidth -
node.offsetHeight - numeric.top - numeric.marginBottom
}
};
return el;
}
function getDocOffsetTop(node) {
var docOffsetTop = 0;
while (node) {
docOffsetTop += node.offsetTop;
node = node.offsetParent;
}
return docOffsetTop;
}
function getElementOffset(node) {
var box = node.getBoundingClientRect();
return {
doc: {
top: box.top + win.pageYOffset,
left: box.left + win.pageXOffset
},
win: box
};
}
function startFastCheckTimer() {
checkTimer = setInterval(function() {
!fastCheck() && rebuild();
}, 500);
}
function stopFastCheckTimer() {
clearInterval(checkTimer);
}
function handlePageVisibilityChange() {
if (!initialized) return;
if (document[hiddenPropertyName]) {
stopFastCheckTimer();
}
else {
startFastCheckTimer();
}
}
function init() {
if (initialized) return;
updateScrollPos();
initAll();
win.addEventListener('scroll', onScroll);
win.addEventListener('wheel', onWheel);
//watch for width changes
win.addEventListener('resize', rebuild);
win.addEventListener('orientationchange', rebuild);
//watch for page visibility
doc.addEventListener(visibilityChangeEventName, handlePageVisibilityChange);
startFastCheckTimer();
initialized = true;
}
function rebuild() {
if (!initialized) return;
deinitAll();
for (var i = watchArray.length - 1; i >= 0; i--) {
watchArray[i] = getElementParams(watchArray[i].node);
}
initAll();
}
function pause() {
win.removeEventListener('scroll', onScroll);
win.removeEventListener('wheel', onWheel);
win.removeEventListener('resize', rebuild);
win.removeEventListener('orientationchange', rebuild);
doc.removeEventListener(visibilityChangeEventName, handlePageVisibilityChange);
stopFastCheckTimer();
initialized = false;
}
function stop() {
pause();
deinitAll();
}
function kill() {
stop();
//empty the array without loosing the references,
//the most performant method according to http://jsperf.com/empty-javascript-array
while (watchArray.length) {
watchArray.pop();
}
}
function add(node) {
//check if Stickyfill is already applied to the node
for (var i = watchArray.length - 1; i >= 0; i--) {
if (watchArray[i].node === node) return;
};
var el = getElementParams(node);
watchArray.push(el);
if (!initialized) {
init();
}
else {
initElement(el);
}
}
function remove(node) {
for (var i = watchArray.length - 1; i >= 0; i--) {
if (watchArray[i].node === node) {
deinitElement(watchArray[i]);
watchArray.splice(i, 1);
}
};
}
//expose Stickyfill
win.Stickyfill = {
stickies: watchArray,
add: add,
remove: remove,
init: init,
rebuild: rebuild,
pause: pause,
stop: stop,
kill: kill
};
})(document, window);
//if jQuery is available -- create a plugin
if (window.jQuery) {
(function($) {
$.fn.Stickyfill = function(options) {
this.each(function() {
Stickyfill.add(this);
});
return this;
};
})(window.jQuery);
}
|
BROCKHAUS-AG/contentmonkee
|
MAIN/Default.WebUI/App_Themes/default/js/stickyfill.js
|
JavaScript
|
mit
| 14,350
|
var copy = require('..');
copy.oneSync('fixtures/a.txt', 'actual');
|
malys/copy
|
examples/copy-one-sync.js
|
JavaScript
|
mit
| 69
|
var fs = require('fs');
module.exports = {
/**
* check if folder exists - otherwise create one
* @param rootFolder
* @param folder
* @param cb
*/
createFolder : function(rootFolder, folder, cb) {
var folders = [],
actualFolder = "";
// create array
folder.split('/').forEach(function (f) {
// remove empty strings like ''
if (f !== '') {
folders.push(f);
}
});
(function create(idx) {
if (idx < folders.length) {
actualFolder += '/' + folders[idx];
fs.exists(rootFolder + actualFolder, function (exists) {
if (exists) {
create(idx + 1);
} else {
fs.mkdir(rootFolder + actualFolder, function () {
create(idx + 1);
});
}
});
} else {
cb();
}
}(0));
},
/**
* add a / at the beginning or end
* @param folder
* @returns {*}
*/
formatFolder : function(folder) {
if (folder === undefined || folder.length === 0) {
return '/';
}
// replace all spaces with underscores
folder = folder.split(' ').join('_');
if (folder.length > 1 && folder[folder.length] !== '/') {
folder += '/';
}
if (folder[0] !== '/') {
folder = '/' + folder;
}
return folder;
}
};
|
eightyfour/drag-king
|
lib/folderUtil.js
|
JavaScript
|
mit
| 1,594
|
define([
'jquery',
'underscore',
'backbone',
'app',
'text!templates/nav.html'
], function ($, _, Backbone, App, Template) {
var Nav = Backbone.View.extend({
el: '#rightSidebarMenu',
template: _.template(Template),
initialize: function () {
this.render();
},
toggleMenu: function () {
$("#rightSidebarMenu").toggleClass('toggled');
},
render: function () {
this.$el.html(this.template());
return this;
},
events: {
'click #nav li a': 'toggleMenu',
'clock #toggle-menu': 'toggleMenu'
}
});
return Nav;
});
|
SergioRodriguezRuiz/change4city
|
www/js/views/nav.js
|
JavaScript
|
mit
| 688
|
module.exports = require('bindings')('binding');
|
emersion/mpu6050-dmp
|
index.js
|
JavaScript
|
mit
| 49
|
'use strict';
const _test = require('tap').test;
const _unhandledStatus = require('./unhandled-status');
_test('200 status ok', assert => {
assert.plan(1);
_unhandledStatus.filter({
statusCode: 200
});
assert.pass();
});
_test('299 status ok', assert => {
assert.plan(1);
_unhandledStatus.filter({
statusCode: 200
});
assert.pass();
});
_test('199 status fail', assert => {
assert.plan(1);
try{
_unhandledStatus.filter({
statusCode: 199
});
assert.fail();
} catch(e){
assert.equals(e.type, _unhandledStatus.unhandledStatusError().type);
}
});
_test('300 status fail', assert => {
assert.plan(1);
try{
_unhandledStatus.filter({
statusCode: 300
});
assert.fail();
} catch(e){
assert.equals(e.type, _unhandledStatus.unhandledStatusError().type);
}
});
|
AKBarcenas/COGS-120-Project
|
node_modules/yelp-fusion/node_modules/@tonybadguy/call-me-maybe/lib/response-filters/unhandled-status.test.js
|
JavaScript
|
mit
| 867
|
export const replaceVariables = (str, callback) => str.replace(/\{ *([^\{\} ]+)[^\{\}]*\}/gmi, callback);
|
VoiSmart/Rocket.Chat
|
app/mailer/server/utils.js
|
JavaScript
|
mit
| 106
|
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable global-require */
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
index: [
'webpack-hot-middleware/client',
'./client/index.jsx',
],
admin: [
'webpack-hot-middleware/client',
'./client/admin.jsx',
],
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.jsx$/,
loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.scss$/,
loaders: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.css$/,
loader: 'style-loader!css-loader?sourceMap',
},
{
test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff',
},
{
test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-woff',
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=application/octet-stream',
},
{
test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader',
},
{
test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
loader: 'url-loader?limit=10000&mimetype=image/svg+xml',
},
{
test: /\.(jpe?g|gif|png)$/,
loader: 'file-loader',
},
{
test: /\.js$/,
loader: 'source-map-loader',
enforce: 'pre',
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
output: {
path: path.resolve(__dirname, '..', 'dist'),
filename: '[name]/bundle.js',
publicPath: '/',
},
plugins: [
new HtmlWebpackPlugin({
template: './client/index.html',
filename: 'index.html',
inject: 'body',
chunks: ['index'],
hash: true,
}),
new HtmlWebpackPlugin({
template: './client/admin.html',
filename: 'admin.html',
inject: 'body',
chunks: ['admin'],
hash: true,
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
],
devServer: {
historyApiFallback: true,
},
};
|
rugby-board/rugby-board-node
|
config/webpack.dev.config.js
|
JavaScript
|
mit
| 2,355
|
'use strict';
var BaseModel = require('model-toolkit').BaseModel;
var uom = require('../master/uom');
module.exports = class DeliveryOrderItemFulfillment extends BaseModel {
constructor(source) {
super('delivery-order-item-fulfillment', '1.0.0');
//Define Properties
this.purchaseOrderId = {};
this.purchaseOrder = {};
this.productId = {};
this.product = {};
this.purchaseOrderQuantity = 0;
this.purchaseOrderUom = new uom();
this.deliveredQuantity = 0;
this.realizationQuantity = [];
this.remark = '';
this.copy(source);
}
};
|
danliris/dl-models
|
src/purchasing/delivery-order-item-fulfillment.js
|
JavaScript
|
mit
| 634
|
describe("toBeGreaterThan", function() {
it("passes if 2 is > 1", function() {
expect(2).toBeGreaterThan(1);
});
it("passes if 1 > 0.999", function() {
expect(1).toBeGreaterThan(0.999);
});
it("passes if 2 is not > 2", function() {
expect(2).not.toBeGreaterThan(2);
});
});
|
crysalead-js/chai-kahlan
|
spec/to-be-greater-than-spec.js
|
JavaScript
|
mit
| 308
|
var http = require("http");
var bCapServ = require("buster-capture-server");
var helper = module.exports = {
run: function (tc, args, callback) {
tc.cli.run(args, function (err, server) {
if (server && server.close) { server.close(); }
callback.call(tc, err, server);
});
},
requestHelperFor: function (host, port) {
var helper = Object.create(this);
helper.host = host;
helper.port = port;
return helper;
},
request: function (method, url, headers, callback) {
if (typeof headers == "function") {
callback = headers;
headers = {};
}
http.request({
method: method.toUpperCase(),
host: this.host || "localhost",
port: this.getPort(),
path: url,
headers: headers
}, function (res) {
var body = "";
res.on("data", function (chunk) { body += chunk; });
res.on("end", function () { callback(res, body); });
}).end();
},
getPort: function () {
return this.port || 9999;
},
get: function (url, headers, callback) {
return this.request("GET", url, headers, callback);
},
post: function (url, headers, callback) {
return this.request("POST", url, headers, callback);
},
captureSlave: function (ua, callback) {
bCapServ.testHelper.captureSlave(this.getPort(), ua).then(callback);
}
};
|
zenners/angular-contacts
|
node_modules/firebase/node_modules/faye-websocket/node_modules/websocket-driver/node_modules/websocket-extensions/node_modules/jstest/node_modules/buster/node_modules/buster-test-cli/node_modules/stream-logger/node_modules/buster/node_modules_old/buster-server-cli/test/test-helper.js
|
JavaScript
|
mit
| 1,504
|
(function() {
this.IssuableBulkActions = (function() {
function IssuableBulkActions(opts) {
var ref, ref1, ref2;
if (opts == null) {
opts = {};
}
this.container = (ref = opts.container) != null ? ref : $('.content'), this.form = (ref1 = opts.form) != null ? ref1 : this.getElement('.bulk-update'), this.issues = (ref2 = opts.issues) != null ? ref2 : this.getElement('.issues-list .issue');
this.form.data('bulkActions', this);
this.willUpdateLabels = false;
this.bindEvents();
Issuable.initChecks();
}
IssuableBulkActions.prototype.getElement = function(selector) {
return this.container.find(selector);
};
IssuableBulkActions.prototype.bindEvents = function() {
return this.form.off('submit').on('submit', this.onFormSubmit.bind(this));
};
IssuableBulkActions.prototype.onFormSubmit = function(e) {
e.preventDefault();
return this.submit();
};
IssuableBulkActions.prototype.submit = function() {
var _this, xhr;
_this = this;
xhr = $.ajax({
url: this.form.attr('action'),
method: this.form.attr('method'),
dataType: 'JSON',
data: this.getFormDataAsObject()
});
xhr.done(function(response, status, xhr) {
return location.reload();
});
xhr.fail(function() {
return new Flash("Issue update failed");
});
return xhr.always(this.onFormSubmitAlways.bind(this));
};
IssuableBulkActions.prototype.onFormSubmitAlways = function() {
return this.form.find('[type="submit"]').enable();
};
IssuableBulkActions.prototype.getSelectedIssues = function() {
return this.issues.has('.selected_issue:checked');
};
IssuableBulkActions.prototype.getLabelsFromSelection = function() {
var labels;
labels = [];
this.getSelectedIssues().map(function() {
var _labels;
_labels = $(this).data('labels');
if (_labels) {
return _labels.map(function(labelId) {
if (labels.indexOf(labelId) === -1) {
return labels.push(labelId);
}
});
}
});
return labels;
};
/**
* Will return only labels that were marked previously and the user has unmarked
* @return {Array} Label IDs
*/
IssuableBulkActions.prototype.getUnmarkedIndeterminedLabels = function() {
var el, i, id, j, labelsToKeep, len, len1, ref, ref1, result;
result = [];
labelsToKeep = [];
ref = this.getElement('.labels-filter .is-indeterminate');
for (i = 0, len = ref.length; i < len; i++) {
el = ref[i];
labelsToKeep.push($(el).data('labelId'));
}
ref1 = this.getLabelsFromSelection();
for (j = 0, len1 = ref1.length; j < len1; j++) {
id = ref1[j];
if (labelsToKeep.indexOf(id) === -1) {
result.push(id);
}
}
return result;
};
/**
* Simple form serialization, it will return just what we need
* Returns key/value pairs from form data
*/
IssuableBulkActions.prototype.getFormDataAsObject = function() {
var formData;
formData = {
update: {
state_event: this.form.find('input[name="update[state_event]"]').val(),
assignee_id: this.form.find('input[name="update[assignee_id]"]').val(),
milestone_id: this.form.find('input[name="update[milestone_id]"]').val(),
issues_ids: this.form.find('input[name="update[issues_ids]"]').val(),
subscription_event: this.form.find('input[name="update[subscription_event]"]').val(),
add_label_ids: [],
remove_label_ids: []
}
};
if (this.willUpdateLabels) {
this.getLabelsToApply().map(function(id) {
return formData.update.add_label_ids.push(id);
});
this.getLabelsToRemove().map(function(id) {
return formData.update.remove_label_ids.push(id);
});
}
return formData;
};
IssuableBulkActions.prototype.getLabelsToApply = function() {
var $labels, labelIds;
labelIds = [];
$labels = this.form.find('.labels-filter input[name="update[label_ids][]"]');
$labels.each(function(k, label) {
if (label) {
return labelIds.push(parseInt($(label).val()));
}
});
return labelIds;
};
/**
* Returns Label IDs that will be removed from issue selection
* @return {Array} Array of labels IDs
*/
IssuableBulkActions.prototype.getLabelsToRemove = function() {
var indeterminatedLabels, labelsToApply, result;
result = [];
indeterminatedLabels = this.getUnmarkedIndeterminedLabels();
labelsToApply = this.getLabelsToApply();
indeterminatedLabels.map(function(id) {
if (labelsToApply.indexOf(id) === -1) {
return result.push(id);
}
});
return result;
};
return IssuableBulkActions;
})();
}).call(this);
|
mr-dxdy/gitlabhq
|
app/assets/javascripts/issues-bulk-assignment.js
|
JavaScript
|
mit
| 5,046
|
module.exports = function (req, res, bounce) {
if (!req.connection.encrypted) {
for (var i = 0; i < this.bouncers.length; i++) {
if (!this.bouncers[i].key) continue;
var hostname = req.headers.host.split(':')[0];
var host = hostname + ':' + this.bouncers[i].address().port;
res.statusCode = 302;
res.setHeader('location', 'https://' + host + req.url);
return res.end();
}
res.statusCode = 404;
res.end('no https endpoint configured\n');
}
else bounce()
};
|
beni55/ploy
|
example/bouncer.js
|
JavaScript
|
mit
| 594
|
var Xflow = Xflow || {};
var XML3D = XML3D || {};
(function() {
var camController;
function setupCameraController()
{
camController = XML3D.Xml3dSceneController.controllers[0];
camController.detach();
camController.mode = "panning";
camController.useKeys = false;
camController.useRaycasting = true;
camController.attach();
}
XML3D.updateViewportSize = function (elem) {
camController.camera.setResolution(elem.clientWidth,elem.clientHeight);
}
window.addEventListener('load', setupCameraController, false);
})();
|
stlemme/xml3d-experimental
|
buffersize-bug/main.js
|
JavaScript
|
mit
| 528
|
return "Raw example";
|
ForbesLindesay/umd
|
examples/raw/index.js
|
JavaScript
|
mit
| 21
|
console.log("[puzzle(knalledge/storage-mongo) - /models/index.js] Building up 'global.db'");
var mkNode = require('./mkNode');
var mkEdge = require('./mkEdge');
var mkMap = require('./mkMap');
if (!global.hasOwnProperty('db')) {
global.db = {};
}
global.db.kNode = mkNode;
global.db.kEdge = mkEdge;
global.db.kMap = mkMap;
module.exports = global.db;
console.log("[puzzle(knalledge/storage-mongo) - /models/index.js] Built up 'global.db'");
console.log("[puzzle(knalledge/storage-mongo) - /models/index.js] global.db.kEdge.Schema: " + global.db.kEdge.Schema);
|
mprinc/KnAllEdge
|
src/backend/dev_puzzles/knalledge/storage-mongo_old/lib/models/index-old.js
|
JavaScript
|
mit
| 568
|
/* eslint-env browser */
/* global Webex */
/* eslint-disable camelcase */
/* eslint-disable max-nested-callbacks */
/* eslint-disable no-alert */
/* eslint-disable no-console */
/* eslint-disable require-jsdoc */
/* eslint-disable arrow-body-style */
/* eslint-disable max-len */
// Declare some globals that we'll need throughout
let activeMeeting, remoteShareStream, webex;
// First, let's wire our form fields up to localStorage so we don't have to
// retype things everytime we reload the page.
[
'access-token',
'invitee'
].forEach((id) => {
const el = document.getElementById(id);
el.value = localStorage.getItem(id);
el.addEventListener('change', (event) => {
localStorage.setItem(id, event.target.value);
});
});
// There's a few different events that'll let us know we should initialize
// Webex and start listening for incoming calls, so we'll wrap a few things
// up in a function.
function connect() {
return new Promise((resolve) => {
if (!webex) {
// eslint-disable-next-line no-multi-assign
webex = window.webex = Webex.init({
config: {
logger: {
level: 'debug'
},
meetings: {
reconnection: {
enabled: true
}
}
// Any other sdk config we need
},
credentials: {
access_token: document.getElementById('access-token').value
}
});
}
// Listen for added meetings
webex.meetings.on('meeting:added', (addedMeetingEvent) => {
if (addedMeetingEvent.type === 'INCOMING') {
const addedMeeting = addedMeetingEvent.meeting;
// Acknowledge to the server that we received the call on our device
addedMeeting.acknowledge(addedMeetingEvent.type)
.then(() => {
if (confirm('Answer incoming call')) {
joinMeeting(addedMeeting);
}
else {
addedMeeting.decline();
}
});
}
});
// Register our device with Webex cloud
if (!webex.meetings.registered) {
webex.meetings.register()
// Sync our meetings with existing meetings on the server
.then(() => webex.meetings.syncMeetings())
.then(() => {
// This is just a little helper for our selenium tests and doesn't
// really matter for the example
document.body.classList.add('listening');
document.getElementById('connection-status').innerHTML = 'connected';
// Our device is now connected
resolve();
})
// This is a terrible way to handle errors, but anything more specific is
// going to depend a lot on your app
.catch((err) => {
console.error(err);
// we'll rethrow here since we didn't really *handle* the error, we just
// reported it
throw err;
});
}
else {
// Device was already connected
resolve();
}
});
}
// Similarly, there are a few different ways we'll get a meeting Object, so let's
// put meeting handling inside its own function.
function bindMeetingEvents(meeting) {
// meeting is a meeting instance, not a promise, so to know if things break,
// we'll need to listen for the error event. Again, this is a rather naive
// handler.
meeting.on('error', (err) => {
console.error(err);
});
meeting.on('meeting:startedSharingRemote', () => {
// Set the source of the video element to the previously stored stream
document.getElementById('remote-screen').srcObject = remoteShareStream;
document.getElementById('screenshare-tracks-remote').innerHTML = 'SHARING';
});
meeting.on('meeting:stoppedSharingRemote', () => {
document.getElementById('remote-screen').srcObject = null;
document.getElementById('screenshare-tracks-remote').innerHTML = 'STOPPED';
});
// Handle media streams changes to ready state
meeting.on('media:ready', (media) => {
if (!media) {
return;
}
console.log(`MEDIA:READY type:${media.type}`);
if (media.type === 'local') {
document.getElementById('self-view').srcObject = media.stream;
}
if (media.type === 'remoteVideo') {
document.getElementById('remote-view-video').srcObject = media.stream;
}
if (media.type === 'remoteAudio') {
document.getElementById('remote-view-audio').srcObject = media.stream;
}
if (media.type === 'remoteShare') {
// Remote share streams become active immediately on join, even if nothing is being shared
remoteShareStream = media.stream;
}
if (media.type === 'localShare') {
document.getElementById('self-screen').srcObject = media.stream;
}
});
// Handle media streams stopping
meeting.on('media:stopped', (media) => {
// Remove media streams
if (media.type === 'local') {
document.getElementById('self-view').srcObject = null;
}
if (media.type === 'remoteVideo') {
document.getElementById('remote-view-video').srcObject = null;
}
if (media.type === 'remoteAudio') {
document.getElementById('remote-view-audio').srcObject = null;
}
if (media.type === 'localShare') {
document.getElementById('self-screen').srcObject = null;
}
});
// Handle share specific events
meeting.on('meeting:startedSharingLocal', () => {
document.getElementById('screenshare-tracks').innerHTML = 'SHARING';
});
meeting.on('meeting:stoppedSharingLocal', () => {
document.getElementById('screenshare-tracks').innerHTML = 'STOPPED';
});
// Update participant info
meeting.members.on('members:update', (delta) => {
const {full: membersData} = delta;
const memberIDs = Object.keys(membersData);
memberIDs.forEach((memberID) => {
const memberObject = membersData[memberID];
// Devices are listed in the memberships object.
// We are not concerned with them in this demo
if (memberObject.isUser) {
if (memberObject.isSelf) {
document.getElementById('call-status-local').innerHTML = memberObject.status;
}
else {
document.getElementById('call-status-remote').innerHTML = memberObject.status;
}
}
});
});
// Of course, we'd also like to be able to end the meeting:
const leaveMeeting = () => meeting.leave();
document.getElementById('hangup').addEventListener('click', leaveMeeting, {once: true});
meeting.on('all', (event) => {
console.log(event);
});
}
// Waits for the meeting to be media update ready
function waitForMediaReady(meeting) {
return new Promise((resolve, reject) => {
if (meeting.canUpdateMedia()) {
resolve();
}
else {
console.info('SHARE-SCREEN: Unable to update media, pausing to retry...');
let retryAttempts = 0;
const retryInterval = setInterval(() => {
retryAttempts += 1;
console.info('SHARE-SCREEN: Retry update media check');
if (meeting.canUpdateMedia()) {
console.info('SHARE-SCREEN: Able to update media, continuing');
clearInterval(retryInterval);
resolve();
}
// If we can't update our media after 15 seconds, something went wrong
else if (retryAttempts > 15) {
console.error('SHARE-SCREEN: Unable to share screen, media was not able to update.');
clearInterval(retryInterval);
reject();
}
}, 1000);
}
});
}
// Join the meeting and add media
function joinMeeting(meeting) {
// Save meeting to global object
activeMeeting = meeting;
// Call our helper function for binding events to meetings
bindMeetingEvents(meeting);
return meeting.join().then(() => {
const mediaSettings = {
receiveVideo: true,
receiveAudio: true,
receiveShare: true,
sendVideo: true,
sendAudio: true,
sendShare: false
};
return meeting.getMediaStreams(mediaSettings).then((mediaStreams) => {
const [localStream, localShare] = mediaStreams;
meeting.addMedia({
localShare,
localStream,
mediaSettings
});
});
});
}
// In order to simplify the state management needed to keep track of our button
// handlers, we'll rely on the current meeting global object and only hook up event
// handlers once.
document.getElementById('share-screen').addEventListener('click', () => {
if (activeMeeting) {
// First check if we can update
waitForMediaReady(activeMeeting).then(() => {
console.info('SHARE-SCREEN: Sharing screen via `shareScreen()`');
activeMeeting.shareScreen()
.then(() => {
console.info('SHARE-SCREEN: Screen successfully added to meeting.');
})
.catch((e) => {
console.error('SHARE-SCREEN: Unable to share screen, error:');
console.error(e);
});
});
}
else {
console.error('No active meeting available to share screen.');
}
});
document.getElementById('stop-screen-share').addEventListener('click', () => {
if (activeMeeting) {
// First check if we can update, if not, wait and retry
waitForMediaReady(activeMeeting).then(() => {
activeMeeting.stopShare();
});
}
});
// Now, let's set up connection handling
document.getElementById('credentials').addEventListener('submit', (event) => {
// let's make sure we don't reload the page when we submit the form
event.preventDefault();
// The rest of the connection setup happens in connect();
connect();
});
// And finally, let's wire up dialing
document.getElementById('dialer').addEventListener('submit', (event) => {
// again, we don't want to reload when we try to dial
event.preventDefault();
const destination = document.getElementById('invitee').value;
// we'll use `connect()` (even though we might already be connected or
// connecting) to make sure we've got a functional webex instance.
connect()
.then(() => {
// Create the meeting
return webex.meetings.create(destination).then((meeting) => {
// Pass the meeting to our join meeting helper
return joinMeeting(meeting);
});
})
.catch((error) => {
// Report the error
console.error(error);
// Implement error handling here
});
});
|
aimeex3/spark-js-sdk
|
packages/node_modules/samples/browser-call-with-screenshare/app.js
|
JavaScript
|
mit
| 10,305
|
"use strict";
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint maxlen: false */
const apirequest_1 = require("../../lib/apirequest");
/**
* Google Cloud Video Intelligence API
*
* Google Cloud Video Intelligence API.
*
* @example
* const google = require('googleapis');
* const videointelligence = google.videointelligence('v1beta1');
*
* @namespace videointelligence
* @type {Function}
* @version v1beta1
* @variation v1beta1
* @param {object=} options Options for Videointelligence
*/
function Videointelligence(options) {
const self = this;
self._options = options || {};
self.videos = {
/**
* videointelligence.videos.annotate
*
* @desc Performs asynchronous video annotation. Progress and results can be retrieved through the `google.longrunning.Operations` interface. `Operation.metadata` contains `AnnotateVideoProgress` (progress). `Operation.response` contains `AnnotateVideoResponse` (results).
*
* @alias videointelligence.videos.annotate
* @memberOf! videointelligence(v1beta1)
*
* @param {object} params Parameters for request
* @param {videointelligence(v1beta1).GoogleCloudVideointelligenceV1beta1_AnnotateVideoRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
annotate: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://videointelligence.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1beta1/videos:annotate').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return apirequest_1.default(parameters, callback);
}
};
}
module.exports = Videointelligence;
//# sourceMappingURL=v1beta1.js.map
|
ratokeshi/endo-google-cloud-platform
|
node_modules/googleapis/apis/videointelligence/v1beta1.js
|
JavaScript
|
mit
| 2,959
|
var auth = require('../helpers/auth');
var proxy = require('../helpers/proxy');
var config = {
/**
* --------- ADD YOUR UAA CONFIGURATION HERE ---------
*
* This uaa helper object simulates NGINX uaa integration using Grunt allowing secure cloudfoundry service integration in local development without deploying your application to cloudfoundry.
* Please update the following uaa configuration for your solution
* You'll need to update clientId, serverUrl, and base64ClientCredential.
*/
uaa: {
clientId: 'app_client_id',
serverUrl: 'https://f5eba58e-4799-450a-8b7e-3dc5897a30d8.predix-uaa.run.aws-usw02-pr.ice.predix.io',
defaultClientRoute: '/about',
base64ClientCredential: 'YXBwX2NsaWVudF9pZDpzZWNyZXQ='
},
/**
* --------- ADD YOUR SECURE ROUTES HERE ------------
*
* Please update the following object add your secure routes
*
* Note: Keep the /api in front of your services here to tell the proxy to add authorization headers.
* You'll need to update the url and instanceId.
*/
proxy: {
'/api/view-service': {
url: 'https://predix-views.run.aws-usw02-pr.ice.predix.io/v1$1',
instanceId: 'cc9ba4f7-fae2-4832-82cf-9146323957f1',
pathRewrite: { '^/api/view-service': '/v1'}
},
'/api/timeseries': {
url: 'https://time-series-store-predix.run.aws-usw02-pr.ice.predix.io/$1',
instanceId: '92f8b9c6-153c-47e0-9cf8-530c9d661c48',
pathRewrite: {'^/api/timeseries': '/v1/datapoints'}
}
}
};
module.exports = {
server: {
options: {
port: 9000,
base: 'public',
open: true,
hostname: 'localhost',
middleware: function (connect, options) {
var middlewares = [];
//add predix services proxy middlewares
middlewares = middlewares.concat(proxy.init(config.proxy));
//add predix uaa authentication middlewaress
middlewares = middlewares.concat(auth.init(config.uaa));
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
var directory = options.directory || options.base[options.base.length - 1];
options.base.forEach(function (base) {
// Serve static files.
middlewares.push(connect.static(base));
});
// Make directory browse-able.
middlewares.push(connect.directory(directory));
return middlewares;
}
}
}
};
|
edwinrsuarez/Thoth
|
PredixMachineDashboard-ES/tasks/options/connect.js
|
JavaScript
|
mit
| 2,424
|
/**
* GUploads
* Javascript multiples upload
*
* @filesource js/uploads.js
* @link http://www.kotchasan.com/
* @copyright 2016 Goragod.com
* @license http://www.kotchasan.com/license/
*/
(function() {
"use strict";
window.GUploads = GClass.create();
GUploads.prototype = {
initialize: function(options) {
this.options = {
form: "",
input: "",
fileprogress: "",
fileext: ["jpg", "jpeg", "gif", "png"],
iconpath: WEB_URL + "skin/ext/",
onupload: $K.emptyFunction,
oncomplete: $K.emptyFunction,
customSettings: {}
};
Object.extend(this.options, options || {});
this.form = $G(this.options.form);
this.frmContainer = document.createElement("div");
this.frmContainer.style.display = "none";
this.form.appendChild(this.frmContainer);
this.index = 0;
this.count = 0;
var input = $G(this.options.input);
this.prefix = input.get("id");
this.parent = $G(input.parentNode);
this.size = input.get("size");
this.className = input.className;
this.name = input.get("name");
this.multiple = window.FormData ? true : false;
input.multiple = this.multiple;
this.result = $E(this.options.fileprogress);
var temp = this;
var _doUploadChanged = function(e) {
var index = 0;
var doProgress = function(val) {
$E("bar_" + temp.prefix + "_" + index).style.width = val + "%";
};
var xhr = new GAjax({
onProgress: doProgress,
contentType: null
});
function _upload(files, i) {
var total = 0;
if (temp.uploading && i < files.length) {
index = i;
if ($E("p_" + temp.prefix + "_" + index)) {
var f = files[i];
var data = new FormData();
for (var name in temp.options.customSettings) {
data.append(
name,
encodeURIComponent(temp.options.customSettings[name])
);
}
data.append("file", f);
$G("close_" + temp.prefix + "_" + index).remove();
xhr.send(temp.form.action, data, function(xhr) {
var ds = xhr.responseText.toJSON();
if (ds) {
if (ds.alert) {
$G("result_" + temp.prefix + "_" + index).addClass(
"invalid"
).innerHTML =
ds.alert;
temp.error.push(ds.alert);
}
} else if (xhr.responseText != "") {
$G("result_" + temp.prefix + "_" + index).addClass(
"invalid"
).innerHTML =
xhr.responseText;
temp.error.push(xhr.responseText);
} else {
$G("p_" + temp.prefix + "_" + index).remove();
total++;
}
_upload(files, index + 1);
});
} else {
_upload(files, index + 1);
}
} else {
temp.options.oncomplete.call(temp, temp.error.join("\n"), total);
}
}
if (temp.multiple) {
forEach(this.files, function() {
var file = temp._ext(this.name);
if (temp.options.fileext.indexOf(file.ext) != -1) {
temp._display(file);
temp.count++;
temp.index++;
}
});
temp.uploading = true;
temp.options.onupload.call(temp);
_upload(this.files, 0);
} else {
var file = temp._ext(this.value);
if (temp.options.fileext.indexOf(file.ext) != -1) {
temp._display(file);
var form = document.createElement("form");
form.id = "form_" + temp.prefix + "_" + temp.index;
form.action = temp.form.action;
temp.frmContainer.appendChild(form);
this.removeEvent("change", _doUploadChanged);
form.appendChild(this);
for (var name in temp.options.customSettings) {
$G(form).create("input", {
name: name,
value: encodeURIComponent(temp.options.customSettings[name]),
type: "hidden"
});
}
temp.count++;
temp.index++;
var _input = $G(temp.parent).create("input", {
id: temp.prefix + temp.index,
name: temp.name,
class: temp.className,
type: "file"
});
_input.addEvent("change", _doUploadChanged);
} else {
alert(trans("The type of file is invalid"));
}
}
};
input.addEvent("change", _doUploadChanged);
this.uploading = false;
this.error = new Array();
var _submit = function(forms, index) {
var total = 0;
var id = forms[index].id;
var result = $E(id.replace("form_", "result_"));
$G(id.replace("form_", "close_")).remove();
result.className = "icon-loading";
var frm = new GForm(id);
frm.result = result;
frm.submit(function(xhr) {
var ds = xhr.responseText.toJSON();
if (ds) {
if (ds.alert) {
frm.result.innerHTML = ds.alert;
frm.result.className = "icon-invalid";
temp.error.push(ds.alert);
}
} else if (xhr.responseText != "") {
frm.result.innerHTML = xhr.responseText;
frm.result.className = "icon-invalid";
temp.error.push(xhr.responseText);
} else {
frm.result.className = "icon-valid";
total++;
}
index++;
if (index < forms.length && temp.uploading) {
_submit.call(temp, forms, index);
} else {
temp.options.oncomplete.call(temp, temp.error.join("\n"), total);
}
});
};
this.form.addEvent("submit", function(e) {
GEvent.stop(e);
if (!temp.uploading && temp.index > 0) {
temp.uploading = true;
$E(temp.prefix + temp.index).disabled = "disabled";
temp.options.onupload.call(temp);
total = 0;
_submit(temp.frmContainer.getElementsByTagName("form"), 0);
}
});
},
cancel: function() {
this.uploading = false;
},
_ext: function(name) {
var obj = new Object();
var files = name.replace(/\\/g, "/").split("/");
obj.name = files[files.length - 1];
var exts = obj.name.split(".");
obj.ext = exts[exts.length - 1].toLowerCase();
return obj;
},
_display: function(file) {
var p = document.createElement("p");
this.result.appendChild(p);
p.id = "p_" + this.prefix + "_" + this.index;
var img = document.createElement("img");
img.src = this._getIcon(file.ext);
p.appendChild(img);
var span = document.createElement("span");
span.innerHTML = file.name;
p.appendChild(span);
var a = document.createElement("a");
a.className = "icon-delete";
a.id = "close_" + this.prefix + "_" + this.index;
p.appendChild(a);
var temp = this;
callClick(a, function() {
temp._remove(this.id.replace("close_" + temp.prefix + "_", ""));
});
var span = document.createElement("span");
p.appendChild(span);
span.id = "result_" + this.prefix + "_" + this.index;
if (this.multiple) {
var bar = document.createElement("span");
bar.className = "bar_graphs";
p.appendChild(bar);
var span = document.createElement("span");
span.className = "value_graphs";
span.id = "bar_" + this.prefix + "_" + this.index;
bar.appendChild(span);
}
},
_getIcon: function(ext) {
var icons = new Array(
"file",
"aiff",
"avi",
"bmp",
"c",
"cpp",
"css",
"dll",
"doc",
"docx",
"exe",
"flv",
"gif",
"htm",
"html",
"iso",
"jpeg",
"jpg",
"js",
"midi",
"mov",
"mp3",
"mpg",
"ogg",
"pdf",
"php",
"png",
"ppt",
"pptx",
"psd",
"rar",
"rm",
"rtf",
"sql",
"swf",
"tar",
"tgz",
"tiff",
"txt",
"wav",
"wma",
"wmv",
"xls",
"xml",
"xvid",
"zip"
);
var i = icons.indexOf(ext);
i = i > 0 ? i : 0;
return this.options.iconpath + icons[i] + ".png";
},
_remove: function(index) {
$G("p_" + this.prefix + "_" + index).remove();
$G("form_" + this.prefix + "_" + index).remove();
this.count--;
}
};
})();
function initGUploads(form_id, id, model, module_id) {
var patt = /^(delete)_([0-9]+)(_([0-9]+))?$/,
form = $G(form_id);
if (G_Lightbox === null) {
G_Lightbox = new GLightbox();
} else {
G_Lightbox.clear();
}
var _doDelete = function() {
var cs = new Array();
forEach(form.elems("a"), function() {
if (this.className == "icon-check") {
var hs = patt.exec(this.id);
cs.push(hs[2]);
}
});
if (cs.length == 0) {
alert(trans("Please select at least one item").replace(/XXX/, this.innerHTML));
} else if (confirm(trans("You want to XXX the selected items ?").replace(/XXX/, this.innerHTML))) {
_action("action=deletep&mid=" + module_id + "&aid=" + id + "&id=" + cs.join(","));
}
};
var _doAction = function(e) {
var hs = patt.exec(this.id);
if (hs[1] == "delete") {
this.className = this.className == "icon-check" ? "icon-uncheck" : "icon-check";
}
GEvent.stop(e);
return false;
};
function _action(q) {
send("index.php/" + model, q, doFormSubmit);
}
forEach(form.elems("a"), function() {
var hs = patt.exec(this.id);
if (hs) {
G_Lightbox.add(this.parentNode);
callClick(this, _doAction);
}
});
new GDragDrop(form_id, {
endDrag: function() {
var elems = new Array();
forEach($G(form_id).elems("figure"), function() {
if (this.id) {
elems.push(this.id.replace("L_", ""));
}
});
if (elems.length > 1) {
_action("action=sort&mid=" + module_id + "&aid=" + id + "&id=" + elems.join(","));
}
}
});
var _setSel = function() {
var chk = this.id == "selectAll" ? "icon-check" : "icon-uncheck";
forEach(form.elems("a"), function() {
var hs = patt.exec(this.id);
if (hs && hs[1] == "delete") {
this.className = chk;
}
});
};
var galleryUploadResult = function(error, count) {
if (error != "") {
alert(error);
}
if (count > 0) {
alert(trans("Successfully uploaded XXX files").replace("XXX", count));
}
if (loader) {
loader.reload();
} else {
window.location.reload();
}
};
var upload = new GUploads({
form: form_id,
input: "fileupload_tmp",
fileprogress: "fsUploadProgress",
oncomplete: galleryUploadResult,
onupload: function() {
$E("btnCancel").disabled = false;
},
customSettings: { albumId: id }
});
callClick("btnCancel", function() {
upload.cancel();
});
callClick("btnDelete", _doDelete);
callClick("selectAll", _setSel);
callClick("clearSelected", _setSel);
}
|
goragod/GCMS
|
js/uploads.js
|
JavaScript
|
mit
| 11,668
|
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var app = express();
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3001, '0.0.0.0', function (err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3001');
});
|
jdsninja/mimic
|
server.js
|
JavaScript
|
mit
| 613
|
/*globals define*/
/*jshint browser: true*/
/**
* Contains helper functions for logging/downloading the state of the client.
*
* @author pmeijer / https://github.com/pmeijer
*/
define([
'js/Utils/SaveToDisk'
], function (saveToDisk) {
'use strict';
function _stateLogReplacer(key, value) {
var chainItem,
prevChain,
nextChain,
chain;
if (key === 'project') {
if (value) {
return value.name;
} else {
return null;
}
} else if (key === 'core') {
if (value) {
return 'instantiated';
} else {
return 'notInstantiated';
}
} else if (key === 'metaNodes') {
return Object.keys(value);
} else if (key === 'nodes') {
return Object.keys(value);
} else if (key === 'loadNodes') {
return Object.keys(value);
} else if (key === 'users') {
return Object.keys(value);
} else if (key === 'rootObject') {
return;
} else if (key === 'undoRedoChain') {
if (value) {
chain = {
previous: null,
next: null
};
if (value.previous) {
prevChain = {};
chain.previous = prevChain;
}
chainItem = value;
while (chainItem.previous) {
prevChain.previous = {
commitHash: chainItem.commitHash,
previous: null
};
prevChain = prevChain.previous;
chainItem = chainItem.previous;
}
if (value.next) {
nextChain = {};
chain.next = nextChain;
}
chainItem = value;
while (chainItem.next) {
nextChain.next = {
commitHash: chainItem.commitHash,
next: null
};
nextChain = nextChain.next;
chainItem = chainItem.next;
}
return chain;
}
}
return value;
}
function getStateLogString(client, state, doFullState, indent) {
indent = indent || 0;
if (doFullState === true) {
return JSON.stringify(state, _stateLogReplacer, indent);
} else {
return JSON.stringify({
connection: client.getNetworkStatus(),
projectId: client.getActiveProjectId(),
branchName: client.getActiveBranchName(),
branchStatus: client.getBranchStatus(),
commitHash: client.getActiveCommitHash(),
rootHash: client.getActiveRootHash(),
projectReadOnly: client.isProjectReadOnly(),
commitReadOnly: client.isCommitReadOnly()
}, null, indent);
}
}
function downloadStateDump(client, state) {
var blob,
fileUrl,
errData = {
timestamp: (new Date()).toISOString(),
webgme: {
NpmVersion: 'n/a',
version: 'n/a',
GitHubVersion: 'n/a'
},
branchErrors: [],
browserInfo: {
appCodeName: window.navigator.appCodeName,
appName: window.navigator.appName,
appVersion: window.navigator.appVersion,
onLine: window.navigator.onLine,
cookieEnabled: window.navigator.cookieEnabled,
platform: window.navigator.platform,
product: window.navigator.product,
userAgent: window.navigator.userAgent
},
clientState: JSON.parse(getStateLogString(client, state, true))
};
if (typeof WebGMEGlobal !== 'undefined') {
/* jshint -W117 */
errData.webgme.NpmVersion = WebGMEGlobal.NpmVersion;
errData.webgme.GitHubVersion = WebGMEGlobal.GitHubVersion;
errData.webgme.version = WebGMEGlobal.version;
/* jshint +W117 */
}
if (state.project && state.branchName && state.project.branches[state.branchName]) {
state.project.branches[state.branchName].errorList.forEach(function (err) {
errData.branchErrors.push({
message: err.message,
stack: err.stack});
});
}
blob = new Blob([JSON.stringify(errData, null, 2)], {type: 'application/json'});
fileUrl = window.URL.createObjectURL(blob);
saveToDisk.saveUrlToDisk(fileUrl, 'webgme-client-dump.json');
}
return {
downloadStateDump: downloadStateDump,
getStateLogString: getStateLogString
};
});
|
pillforge/webgme
|
src/client/js/client/stateloghelpers.js
|
JavaScript
|
mit
| 5,082
|
//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
//
// Test uncaught exception source info
//
function dummy() {
// do nothing
}
dummy();
nosuchfunc(); //9,1
dummy();
|
arunetm/ChakraCore_0114
|
test/Error/sourceInfo_00.js
|
JavaScript
|
mit
| 506
|
/**
* == scripty2 fx ==
* The scripty2 effects framework provides for time-based transformations of DOM elements
* and arbitrary JavaScript objects. This is at the core of scripty2 and presents a refinement
* of the visual effects framework of script.aculo.us 1.
*
* In practice [[S2.FX.Morph]] is most often used, which allows transitions from one
* set of CSS style rules to another.
*
* <h2>Features</h2>
*
* * <a href="scripty2%20fx/element.html#morph-class_method">CSS morphing engine</a>:
* morph from one set of style properties to another, including
* support for all CSS length types (px, em, %, cm, pt, etc.)
* * <a href="scripty2%20fx/s2/fx/transitions.html">Extensive transition system</a>
* for animation easing and special effects (e.g. bouncing)
* * On supported browsers, uses browser-native visual effects (CSS Transitions),
* fully automatically with no change to your code required
* * Auto-adjusts to differences in computing and rendering speed (drops frames as necessary)
* * Limits the number of attempted frame renders to conserve CPU in fast computers
* * Flexible OOP-based implementation allows for easy extension and hacks
* * <a href="scripty2%20fx/s2/fx/queue.html">Effect queuing</a> to run an effect after other effects have finished
* * <a href="scripty2%20fx/element.html#morph-class_method">Chaining</a> and
* <a href="scripty2%20fx/s2/fx/base.html#new-constructor">default options</a>:
* easy-to-use syntax for most use cases
* * <a href="scripty2%20fx/s2/fx/element.html#play-instance_method">Reusable effect instances</a>
* can be used with more than one DOM element
* * User-definable callback functions at any point in the effect lifecycle
* * Effects are abortable (either as-is or abort-to-end)
**/
/** section: scripty2 fx
* S2.FX
* This is the main effects namespace.
**/
S2.FX = (function(){
var queues = [], globalQueue,
heartbeat, activeEffects = 0;
function beatOnDemand(dir) {
activeEffects += dir;
if (activeEffects > 0) heartbeat.start();
else heartbeat.stop();
}
function renderQueues() {
var timestamp = heartbeat.getTimestamp();
for (var i = 0, queue; queue = queues[i]; i++) {
queue.render(timestamp);
}
}
function initialize(initialHeartbeat){
if (globalQueue) return;
queues.push(globalQueue = new S2.FX.Queue());
S2.FX.DefaultOptions.queue = globalQueue;
heartbeat = initialHeartbeat || new S2.FX.Heartbeat();
document
.observe('effect:heartbeat', renderQueues)
.observe('effect:queued', beatOnDemand.curry(1))
.observe('effect:dequeued', beatOnDemand.curry(-1));
}
function formatTimestamp(timestamp) {
if (!timestamp) timestamp = (new Date()).valueOf();
var d = new Date(timestamp);
return d.getSeconds() + '.' + d.getMilliseconds() + 's';
}
return {
initialize: initialize,
getQueues: function() { return queues; },
addQueue: function(queue) { queues.push(queue); },
getHeartbeat: function() { return heartbeat; },
setHeartbeat: function(newHeartbeat) { heartbeat = newHeartbeat; },
formatTimestamp: formatTimestamp
}
})();
Object.extend(S2.FX, {
DefaultOptions: {
transition: 'sinusoidal',
position: 'parallel',
fps: 60,
duration: .2
},
elementDoesNotExistError: {
name: 'ElementDoesNotExistError',
message: 'The specified DOM element does not exist, but is required for this effect to operate'
},
parseOptions: function(options) {
if (Object.isNumber(options))
options = { duration: options };
else if (Object.isFunction(options))
options = { after: options };
else if (Object.isString(options))
options = { duration: options == 'slow' ? 1 : options == 'fast' ? .1 : .2 };
return options || {};
},
ready: function(element) {
if (!element) return;
var table = this._ready;
var uid = element._prototypeUID;
if (!uid) return true;
bool = table[uid];
return Object.isUndefined(bool) ? true : bool;
},
setReady: function(element, bool) {
if (!element) return;
var table = this._ready, uid = element._prototypeUID;
if (!uid) {
element.getStorage();
uid = element._prototypeUID;
}
table[uid] = bool;
},
_ready: {}
});
/**
* class S2.FX.Base
**/
S2.FX.Base = Class.create({
/**
* new S2.FX.Base([options])
* - options (Number | Function | Object): options for the effect.
*
* Base calls for all effects. Subclasses need to define the `update` instance
* method for it to be useful. scripty2 currently provides one subclass implementation
* for effects based on DOM elements, [[S2.FX.Element]].
*
* <h4>Effect options</h4>
*
* There are serveral ways the options argument can be used:
*
* new S2.FX.Base({ duration: 3, transition: 'spring' });
* new S2.FX.Base(function(){}) // shortcut for { after: function(){} }
* new S2.FX.Base(3); // shortcut for { duration: 3 }
* new S2.FX.Base('slow'); // shortcut for { duration: 1 }
* new S2.FX.Base('fast'); // shortcut for { duration: .1 }
*
* The following options are recognized:
*
* * `duration`: duration in seconds, defaults to 0.2 (a fifth of a second). This
* speed is based on the value Mac OS X uses for interface effects.
* * `transition`: Function reference or String with a property name from [[S2.FX.Transitions]].
* Sets the transition method for easing and other special effects.
* * `before`: Function to be executed before the first frame of the effect is rendered.
* * `after`: Function to be executed after the effect has finished.
* * `beforeUpdate`: Function to be executed before each frame is rendered. This function
* is given two parameters: the effect instance and the current position (between 0 and 1).
* * `afterUpdate`: Function to be executed after each frame is renedred. This function
* is given two parameters: the effect instance and the current position (between 0 and 1).
* * `fps`: The maximum number of frames per second. Ensures that no more than `options.fps`
* frames per second are rendered, even if there's enough computation resources available.
* This can be used to make CPU-intensive effects use fewer resources.
* * `queue`: Specify a [[S2.FX.Queue]] to be used for the effect.
* * `position`: Position within the specified queue, `parallel` (start immediately, default) or `end`
* (queue up until the last effect in the queue is finished)
*
* The effect won't start immediately, it will merely be initialized.
* To start the effect, call [[S2.FX.Base#play]].
**/
initialize: function(options) {
S2.FX.initialize();
this.updateWithoutWrappers = this.update;
if(options && options.queue && !S2.FX.getQueues().include(options.queue))
S2.FX.addQueue(options.queue);
this.setOptions(options);
this.duration = this.options.duration*1000;
this.state = 'idle';
['after','before'].each(function(method) {
this[method] = function(method) {
method(this);
return this;
}
}, this);
},
setOptions: function(options) {
options = S2.FX.parseOptions(options);
this.options = Object.extend(this.options || Object.extend({}, S2.FX.DefaultOptions), options);
if (options.tween) this.options.transition = options.tween;
if (this.options.beforeUpdate || this.options.afterUpdate) {
this.update = this.updateWithoutWrappers.wrap( function(proceed,position){
if (this.options.beforeUpdate) this.options.beforeUpdate(this, position);
proceed(position);
if (this.options.afterUpdate) this.options.afterUpdate(this, position);
}.bind(this));
}
if (this.options.transition === false)
this.options.transition = S2.FX.Transitions.linear;
this.options.transition = Object.propertize(this.options.transition, S2.FX.Transitions);
},
/**
* S2.FX.Base#play([options]) -> S2.FX.Base
* - options: Effect options, see above.
*
* Starts playing the effect.
* Returns the effect.
**/
play: function(options) {
this.setOptions(options);
this.frameCount = 0;
this.state = 'idle';
this.options.queue.add(this);
this.maxFrames = this.options.fps * this.duration / 1000;
return this;
},
/**
* S2.FX.Base#render(timestamp) -> undefined
* - timestamp (Date): point in time, normally the current time
*
* Renders the effect, and calls the before/after functions when necessary.
* This method also switches the state of the effect from `idle` to `running` when
* the first frame is rendered, and from `running` to `finished` after the last frame
* is rendered.
**/
render: function(timestamp) {
if (this.options.debug) {
// this.debug("render called at " + S2.FX.formatTimestamp(timestamp));
}
if (timestamp >= this.startsAt) {
// Effect should be active.
if (this.state == 'idle' && (!this.element || S2.FX.ready(this.element))) {
// If there's an element, it's ready for a new effect, but this effect
// hasn't yet been started. Start it now.
this.debug('starting the effect at ' + S2.FX.formatTimestamp(timestamp));
// Reschedule the end time in case we're running behind schedule.
this.endsAt = this.startsAt + this.duration;
this.start();
this.frameCount++;
return this;
}
if (timestamp >= this.endsAt && this.state !== 'finished') {
// The effect has exceeded its scheduled time but has not yet been
// stopped yet. Stop it now.
this.debug('stopping the effect at ' + S2.FX.formatTimestamp(timestamp));
this.finish();
return this;
}
if (this.state === 'running') {
// The effect is running. Figure out its new tweening coefficient
// and update the animation.
var position = 1 - (this.endsAt - timestamp) / this.duration;
if ((this.maxFrames * position).floor() > this.frameCount) {
this.update(this.options.transition(position));
this.frameCount++;
}
}
}
return this;
},
start: function() {
if (this.options.before) this.options.before(this);
if (this.setup) this.setup();
this.state = 'running';
this.update(this.options.transition(0));
},
/**
* S2.FX.Base#cancel([after]) -> undefined
* - after (Boolean): if true, run the after method (if defined), defaults to false
*
* Calling `cancel()` immediately halts execution of the effect, and calls the `teardown`
* method if defined.
**/
cancel: function(after) {
if (this.state !== 'running') return;
if (this.teardown) this.teardown();
if (after && this.options.after) this.options.after(this);
this.state = 'finished';
},
/**
* S2.FX.Base#finish() -> undefined
*
* Immediately render the last frame and halt execution of the effect
* and call the `teardown`method if defined.
**/
finish: function() {
if (this.state !== 'running') return;
this.update(this.options.transition(1));
this.cancel(true);
},
/**
* S2.FX.Base#inspect() -> String
*
* Returns the debug-oriented string representation of an effect.
**/
inspect: function() {
return '#<S2.FX:' + [this.state, this.startsAt, this.endsAt].inspect() + '>';
},
/**
* S2.FX.Base#update() -> undefined
*
* The update method is called for each frame to be rendered. The implementation
* in `S2.FX.Base` simply does nothing, and is intended to be overwritten by
* subclasses. It is provided for cases where `S2.FX.Base` is instantiated directly
* for ad-hoc effects using the beforeUpdate and afterUpdate callbacks.
**/
update: Prototype.emptyFunction,
debug: function(message) {
if (!this.options.debug) return;
if (window.console && console.log) {
console.log(message);
}
}
});
/**
* class S2.FX.Element < S2.FX.Base
* Base class for effects that change DOM elements. This is the base class for
* the most important effects implementation [[S2.FX.Morph]], but can be used
* as a base class for non-CSS based effects too.
**/
S2.FX.Element = Class.create(S2.FX.Base, {
/**
* new S2.FX.Element(element[, options])
* - element (Object | String): DOM element or element ID
* - options (Number | Function | Object): options for the effect.
*
* See [[S2.FX.Base]] for a description of the `options` argument.
**/
initialize: function($super, element, options) {
if(!(this.element = $(element)))
throw(S2.FX.elementDoesNotExistError);
this.operators = [];
return $super(options);
},
/**
* S2.FX.Element#animate(operator[, args...]) -> undefined
* - operator (String): lowercase name of an [[S2.FX.Operator]]
*
* Starts an animation by using a [[S2.FX.Operator]] on the element
* that is associated with the effect.
*
* The rest of the arguments are passed to Operators' constructor.
* This method is intended to be called in the `setup` instance method
* of subclasses, for example:
*
* // setup method from S2.FX.Style
* setup: function() {
* this.animate('style', this.element, { style: this.options.style });
* }
**/
animate: function() {
var args = $A(arguments), operator = args.shift();
operator = operator.charAt(0).toUpperCase() + operator.substring(1);
this.operators.push(new S2.FX.Operators[operator](this, args[0], args[1] || {}));
},
/**
* S2.FX.Element#play([element[, options]]) -> S2.FX.Base
* - element (Object | String): DOM element or element ID
* - options (Number | Function | Object): options for the effect.
*
* Starts playing the element effect. The optional `element` argument can
* be used to reuse this instance on a different element than for
* which it was used originally.
**/
play: function($super, element, options) {
if (element) this.element = $(element);
this.operators = [];
return $super(options);
},
update: function(position) {
for (var i = 0, operator; operator = this.operators[i]; i++) {
operator.render(position);
}
}
});
|
abhishekbhalani/scripty2
|
src/effects/base.js
|
JavaScript
|
mit
| 14,480
|
/*
* Copyright 2016 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'find/app/page/search/suggest/suggest-view',
'find/idol/app/page/search/results/idol-results-view',
'find/idol/app/page/search/results/idol-results-view-augmentation'
], function(SuggestView, ResultsView, ResultsViewAugmentation) {
return SuggestView.extend({
ResultsView: ResultsView,
ResultsViewAugmentation: ResultsViewAugmentation,
getIndexes: function(indexesCollection) {
return indexesCollection.pluck('id')
}
});
});
|
LinkPowerHK/find
|
idol/src/main/public/static/js/find/idol/app/page/search/suggest/idol-suggest-view.js
|
JavaScript
|
mit
| 686
|
/**
* @license Highcharts JS v8.2.2 (2020-10-22)
* @module highcharts/modules/venn
* @requires highcharts
*
* (c) 2017-2019 Highsoft AS
* Authors: Jon Arild Nygard
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Series/VennSeries.js';
|
cdnjs/cdnjs
|
ajax/libs/highcharts/8.2.2/es-modules/masters/modules/venn.src.js
|
JavaScript
|
mit
| 267
|
$(document).ready(function () {
var window_height = window.innerHeight;
$('.wrapper').css("height", window_height);
$(window).resize(function () {
$('.wrapper').css("height", window.innerHeight);
});
window.bg = chrome.extension.getBackgroundPage();
show_def(location.hash.substring(1));
window.onhashchange = function () {
show_def(location.hash.substring(1));
}
$(document).on('dblclick', function () {
if (confirm("翻译该单词?")) {
var text = window.getSelection().toString().trim().match(/^[a-zA-Z\s']+$/);
window.word = text;
location.hash = "#" + text;
}
});
/* $("#addSentence .content").change(function() {
window.translation = $(this).val();
})*/
});
function show_def(word) {
if (!word) {
word = "Opps! That is not a something!"
}
window.word = word;
document.title = word;
var tmp = $.trim(word);
var re = / /;
var pos = tmp.search(re);
if (pos !== -1) {
sentence_def(tmp);
} else {
word_def(tmp);
}
}
function sentence_def(youdaoIn) {
$.ajax({
url: bg.youdao_url + youdaoIn,
dataType: "json",
success: function (data) {
if (data.errorCode == 0) {
$("#sentence_title").html(data.query);
/*有道翻译*/
var temp_translated_sentence = '';
for (var i in data.translation) {
temp_translated_sentence += "<p>" + data.translation[i] + "</p>";
}
$("#translated").html(temp_translated_sentence);
/*有道词典*/
if (data.basic) {
$("#word_title").html(youdaoIn);
$("#word_pron").html(data.basic.phonetic);
var temp_youdao_word = '';
for (var i in data.basic.explains) {
temp_youdao_word += "<li>" + data.basic.explains[i] + "</li>";
}
$("#word_cn_def").html(temp_youdao_word);
}
;
if (data.web) {
var temp_youdao_word_web = '';
for (var i in data.basic.web) {
var tmp_obj = data.basic.web[i];
for (var j in tmp_obj["value"]) {
temp_youdao_word_web += "<li>" + tmp_obj["value"][j] + "</li>";
}
}
$("#word_cn_def").html(temp_youdao_word_web);
}
;
} else {
switch (data.errorCode) {
case 20:
alert("要翻译的文本超过200字符");
break;
case 30:
alert("无法翻译");
break;
case 40:
alert("不支持的语言类型");
break;
case 50:
alert("无效的key");
break;
case 60:
alert("无词典结果,仅在获取词典结果生效");
break;
}
window.history.back();
}
},
error: function (data) {
alert("翻译句子——失败");
}
});
}
function word_def(word) {
$.ajax({
url: bg.oauth.conf.api_root + bg.ShanbayApi.search + word + '&access_token=' + bg.oauth.access_token(),
dataType: "json",
success: function (data) {
if (data.status_code === 0) {
/*获取单词例句*/
show_example(data.data.id);
/*单词标题*/
$("#word_title").html(data.data.content);
/*加音标*/
$("#word_pron").html(data.data.pron);
/*加发音*/
$(".pronounce").html("发音<audio src=" + data.data.audio + "></audio>");
$(".pronounce").click(function () {
$("audio", this)[0].play();
});
/*中文单词翻译*/
var cn_defs = $.trim(data.data.definition).split("\n");
var tmp_cn_defs_string = '';
cn_defs.forEach(function showCnDefs(val, index) {
tmp_cn_defs_string += "<li><span>" + index + "</span> " + val + "</li>";
});
$("#word_cn_def").html(tmp_cn_defs_string);
/*英文单词翻译*/
var en_defs = data.data.en_definitions;
var index_en_defs = Object.keys(en_defs);
var tmp_en_defs_string = '';
for (var i in index_en_defs) {
tmp_en_defs_string += "<li>" + index_en_defs[i] + ":</li>";
en_defs[index_en_defs[i]].forEach(function showEnDefs(val, index) {
tmp_en_defs_string += "<li><span>" + index + "</span> " + val + "</li>";
});
}
$("#word_en_def").html(tmp_en_defs_string);
} else {
console.log(data.msg);
sentence_def(word);
}
},
error: function (data) {
alert("翻译单词——失败");
}
});
}
/*function add_word() {
$.ajax({
url: ,
dataType: "json",
success: function(data) {},
error: function(data) {}
})
}
*/
function show_example(id) {
$.ajax({
url: bg.oauth.conf.api_root + bg.ShanbayApi.example + '?vocabulary_id=' + id + '&access_token=' + bg.oauth.access_token(),
dataType: "json",
success: function (data) {
if (data.status_code === 0) {
var temp_example_array = data.data.sort(sort_example);
var temp_html_string = '';
var temp_html_string2 = '';
for (var i in temp_example_array) {
if (i < 5) {
temp_html_string += "<div><p><span>" + i + "</span> likes:" + temp_example_array[i].likes + "|unlikes:" + temp_example_array[i].unlikes + "</p><p>" + temp_example_array[i].annotation + "</p><p>" + temp_example_array[i].translation + "</p></div>";
if (i == 4) {
temp_html_string += '<div id="show_left_examples"><p>...</p></div>';
}
;
} else {
temp_html_string2 += "<div><p><span>" + i + "</span> likes:" + temp_example_array[i].likes + "|unlikes:" + temp_example_array[i].unlikes + "</p><p>" + temp_example_array[i].annotation + "</p><p>" + temp_example_array[i].translation + "</p></div>";
}
}
;
$("#examples").html(temp_html_string);
$("#show_left_examples").click(function () {
$(this).remove();
$("#examples").append(temp_html_string2);
});
} else {
alert(data.msg);
}
},
error: function (data) {
alert("获取例句——失败");
}
});
}
function sort_example(object1, object2) {
var front_likes = object1.likes - object1.unlikes;
var behind_likes = object2.likes - object2.unlikes;
if (front_likes > behind_likes) {
return -1;
} else if (front_likes === behind_likes) {
return 0;
} else {
return 1;
}
;
}
|
SineLabo/WordsNoteGenerator
|
js/app.js
|
JavaScript
|
mit
| 7,676
|
/**
* jQuery plugins development demo
*
* by javascript-html5-tutorial.com
*/
(function($) {
// we extend jQ by new simple function
$.fn.myFunctionExt = function(param) {
alert("The parameter is: " + param);
};
// standard CSS modifier for elements
$.fn.myCSSModifier = function() {
return this.css({
margin: '5px',
padding: '5px',
border: 'solid 2px #f00',
});
};
// plugin code
$.mySimplePlugin = function(options) {
// define properties and methods
var str = 'abdef',
number = 128,
arr = ['One', 'Two', 'Three', '...'],
actions = {
test_alert: function() {
this.myFunctionExt('X1');
// this.myFunctionExt(str);
this.myFunctionExt(arr[1]);
},
test_css: function() {
// apply for all elements in body
// this.myCSSModifier();
// apply only for specified element
$('#d2').myCSSModifier();
},
default_action: function() {
alert('Bye bye!');
}
},
// core processing - options
body = $('body');
if (options) {
// multiple options
if (typeof options == 'object') {
for(i in options) {
if (options[i] != false && actions[i]) {
actions[i].call(body);
}
}
} else {
// string - one option
if (actions[options]) {
actions[options].call(body);
}
}
} else {
// no option specified - call default
return actions['default_action'].call(body);
}
};
})(jQuery);
|
dominik-w/js_html5_com
|
jquery_plugins_dev/jq_plugin_dev_demo2/jq_plugin_dev_demo2.js
|
JavaScript
|
mit
| 2,023
|
/**
* @name padLeft
* @category String
* @since v0.19.0
* @description
* Pads a string to a given length by prepending it with the given character
* until that length is reached.
*
* @example
* padLeft(5, 'X', 'hi') // => 'XXXhi'
*/
// TODO(zuko): how should we handle char of length > 1?
// TODO(zuko): throw error if char is empty?
export default function padLeft (length, char, str) {
while (str.length < length) {
str = char + str
}
return str
}
|
davezuko/halcyon
|
src/padLeft.js
|
JavaScript
|
mit
| 470
|
'use strict';
exports.init = function(req, res) {
if (req.isAuthenticated()) {
res.redirect(req.user.defaultReturnUrl());
} else {
res.render('login/forgot/index');
}
};
exports.send = function(req, res, next) {
var workflow = req.app.utility.workflow(req, res);
workflow.on('validate', function() {
if (!req.body.email) {
workflow.outcome.errfor.email = 'required';
return workflow.emit('response');
}
workflow.emit('generateToken');
});
workflow.on('generateToken', function() {
var crypto = require('crypto');
crypto.randomBytes(21, function(err, buf) {
if (err) {
return next(err);
}
var token = buf.toString('hex');
req.app.db.models.User.encryptPassword(token, function(err, hash) {
if (err) {
return next(err);
}
workflow.emit('patchUser', token, hash);
});
});
});
workflow.on('patchUser', function(token, hash) {
var conditions = { email: req.body.email.toLowerCase() };
var fieldsToSet = {
resetPasswordToken: hash,
resetPasswordExpires: Date.now() + 10000000
};
req.app.db.models.User.findOneAndUpdate(conditions, fieldsToSet, function(err, user) {
if (err) {
return workflow.emit('exception', err);
}
if (!user) {
return workflow.emit('response');
}
workflow.emit('sendEmail', token, user);
});
});
workflow.on('sendEmail', function(token, user) {
req.app.utility.sendmail(req, res, {
from: req.app.config.smtp.from.name + ' <' + req.app.config.smtp.from.address + '>',
to: user.email,
subject: 'Reset your ' + req.app.config.projectName + ' password',
textPath: 'login/forgot/email-text',
htmlPath: 'login/forgot/email-html',
locals: {
username: user.username,
resetLink: req.protocol + '://' + req.app.config.host + req.app.config.baseUrl + '/login/reset/' + user.email + '/' + token + '/',
projectName: req.app.config.projectName
},
success: function(message) {
workflow.emit('response');
},
error: function(err) {
workflow.outcome.errors.push('Error Sending: ' + err);
workflow.emit('response');
}
});
});
workflow.emit('validate');
};
|
akinaru/google-cross-client-node
|
app/views/login/forgot/index.js
|
JavaScript
|
mit
| 2,648
|
//>>built
define({"days-standAlone-short":"Du Lu Ma Mi Jo Vi S\u00e2".split(" "),"field-second-relative+0":"acum","field-weekday":"Zi a s\u0103pt\u0103m\u00e2nii","field-wed-relative+0":"miercurea aceasta","field-wed-relative+1":"miercurea viitoare","dateFormatItem-GyMMMEd":"E, d MMM y G","dateFormatItem-MMMEd":"E, d MMM","field-tue-relative+-1":"mar\u021bea trecut\u0103","days-format-short":"Du Lu Ma Mi Jo Vi S\u00e2".split(" "),"dateFormat-long":"d MMMM y G","field-fri-relative+-1":"vinerea trecut\u0103",
"field-wed-relative+-1":"miercurea trecut\u0103","dateFormatItem-yyyyQQQ":"QQQ y G","dateTimeFormat-medium":"{1}, {0}","dayPeriods-format-wide-pm":"p.m.","dateFormat-full":"EEEE, d MMMM y G","dateFormatItem-yyyyMEd":"E, dd.MM.y G","field-thu-relative+-1":"joia trecut\u0103","dateFormatItem-Md":"dd.MM","field-era":"Er\u0103","quarters-format-wide":["trimestrul I","trimestrul al II-lea","trimestrul al III-lea","trimestrul al IV-lea"],"field-year":"An","field-hour":"Or\u0103","field-sat-relative+0":"s\u00e2mb\u0103ta aceasta",
"field-sat-relative+1":"s\u00e2mb\u0103ta viitoare","field-day-relative+0":"azi","field-thu-relative+0":"joia aceasta","field-day-relative+1":"m\u00e2ine","field-thu-relative+1":"joia viitoare","dateFormatItem-GyMMMd":"d MMM y G","field-day-relative+2":"poim\u00e2ine","quarters-format-abbr":["trim. I","trim. II","trim. III","trim. IV"],"quarters-standAlone-wide":["Trimestrul I","Trimestrul al II-lea","Trimestrul al III-lea","Trimestrul al IV-lea"],"dateFormatItem-Gy":"y G","dateFormatItem-yyyyMMMEd":"E, d MMM y G",
"days-standAlone-wide":"Duminic\u0103 Luni Mar\u021bi Miercuri Joi Vineri S\u00e2mb\u0103t\u0103".split(" "),"dateFormatItem-yyyyMMM":"MMM y G","dateFormatItem-yyyyMMMd":"d MMM y G","field-sun-relative+0":"duminica aceasta","field-sun-relative+1":"duminica viitoare","quarters-standAlone-abbr":["Trim. I","Trim. II","Trim. III","Trim. IV"],eraAbbr:["AH"],"field-minute":"Minut","field-dayperiod":"a.m/p.m.","days-standAlone-abbr":"Dum Lun Mar Mie Joi Vin S\u00e2m".split(" "),"field-day-relative+-1":"ieri",
"dateTimeFormat-long":"{1} 'la' {0}","field-day-relative+-2":"alalt\u0103ieri","dateFormatItem-MMMd":"d MMM","dateFormatItem-MEd":"E, dd.MM","dateTimeFormat-full":"{1} 'la' {0}","field-fri-relative+0":"vinerea aceasta","field-fri-relative+1":"vinerea viitoare","field-day":"Zi","days-format-wide":"duminic\u0103 luni mar\u021bi miercuri joi vineri s\u00e2mb\u0103t\u0103".split(" "),"field-zone":"Fus orar","dateFormatItem-y":"y","field-year-relative+-1":"anul trecut","field-month-relative+-1":"luna trecut\u0103",
"days-format-abbr":"Dum Lun Mar Mie Joi Vin S\u00e2m".split(" "),"days-format-narrow":"DLMMJVS".split(""),"dateFormatItem-yyyyMd":"dd.MM.y G","field-month":"Lun\u0103","days-standAlone-narrow":"DLMMJVS".split(""),"field-tue-relative+0":"mar\u021bea aceasta","field-tue-relative+1":"mar\u021bea viitoare","dayPeriods-format-wide-am":"a.m.","field-mon-relative+0":"lunea aceasta","field-mon-relative+1":"lunea viitoare","dateFormat-short":"dd.MM.y GGGGG","field-second":"Secund\u0103","field-sat-relative+-1":"s\u00e2mb\u0103ta trecut\u0103",
"field-sun-relative+-1":"duminica trecut\u0103","field-month-relative+0":"luna aceasta","field-month-relative+1":"luna viitoare","dateFormatItem-Ed":"E d","field-week":"S\u0103pt\u0103m\u00e2n\u0103","dateFormat-medium":"dd.MM.y G","field-year-relative+0":"anul acesta","field-week-relative+-1":"s\u0103pt\u0103m\u00e2na trecut\u0103","dateFormatItem-yyyyM":"MM.y G","field-year-relative+1":"anul viitor","dateFormatItem-yyyyQQQQ":"QQQQ y G","dateTimeFormat-short":"{1}, {0}","dateFormatItem-GyMMM":"MMM y G",
"field-mon-relative+-1":"lunea trecut\u0103","dateFormatItem-yyyy":"y G","field-week-relative+0":"s\u0103pt\u0103m\u00e2na aceasta","field-week-relative+1":"s\u0103pt\u0103m\u00e2na viitoare"});
|
ycabon/presentations
|
2020-devsummit/arcgis-js-api-road-ahead/js-api/dojo/cldr/nls/ro/islamic.js
|
JavaScript
|
mit
| 3,833
|
/* global describe, it, expect */
import { shortMessage, shortCommit } from './commits';
describe('shortMessage', () => {
const BIG_MESSAGE = `✨ Somehow this is the first spec I've written for our front-end, and this seems really odd to me
- this should be a big enough message to make sure we're not running into anything silly`;
it('returns the first line of a multi-line message', () => {
expect(shortMessage(BIG_MESSAGE)).toMatchSnapshot();
});
it('returns the whole message in a one-line message', () => {
expect(shortMessage('Bump frontend')).toMatchSnapshot();
});
});
describe('shortCommit', () => {
it('returns a 7-character SHA1 for a full SHA1 commitish', () => {
expect(shortCommit('be9c03b0dbddafccb0882f62182b84924579c93b')).toMatchSnapshot();
});
it('returns the full name for a non-SHA1 commitish', () => {
expect(shortCommit('preload-pipeline-names-sperlunking')).toMatchSnapshot();
});
it('returns the full name for a 40-character non-SHA1 commitish', () => {
expect(shortCommit('so-this-is-a-forty-character-branch-name')).toMatchSnapshot();
});
});
|
fotinakis/buildkite-frontend
|
app/lib/commits.spec.js
|
JavaScript
|
mit
| 1,120
|
type TestFunction = (done: () => void) => void | Promise<mixed>;
declare var describe: {
(name: string, spec: () => void): void,
only(description: string, spec: () => void): void,
skip(description: string, spec: () => void): void,
timeout(ms: number): void,
...
};
declare var context: typeof describe;
declare var it: {
(name: string, spec?: TestFunction): void,
only(description: string, spec: TestFunction): void,
skip(description: string, spec: TestFunction): void,
timeout(ms: number): void,
...
};
declare function before(method: TestFunction): void;
declare function beforeEach(method: TestFunction): void;
declare function after(method: TestFunction): void;
declare function afterEach(method: TestFunction): void;
|
splodingsocks/FlowTyped
|
definitions/npm/mocha_v2.4.x/flow_v0.104.x-/mocha_v2.4.x.js
|
JavaScript
|
mit
| 746
|
import TopicTree from './TopicTree.js';
let raw;
if (__SERVER__) {
// TODO(jlfwong): Make this actually download data from KA instead of just
// pulling from disk.
/*
const PROJECTION = JSON.stringify({
topics:[{
id: 1,
slug: 1,
translatedTitle: 1,
translatedDescription: 1,
relativeUrl: 1,
childData: 1
}],
videos: [{
id: 1,
slug: 1,
translatedTitle: 1,
translatedDescription: 1,
translatedYoutubeId: 1
}]
});
const TOPIC_TREE_URL = `https://www.khanacademy.org/api/v2/topics/topictree?projection=${PROJECTION}`;
*/
raw = JSON.parse(require("fs").readFileSync(`${__dirname}/../static/topictree.json`));
raw.topics.forEach(t => {
t.childData = t.childData.filter(c => (c.kind === "Topic" ||
c.kind === "Video"));
})
} else {
raw = {topics: [], videos: []}
}
export default TopicTree.indexData(raw);
|
jlfwong/1rt
|
src/FullTopicTree.js
|
JavaScript
|
mit
| 1,008
|
/*
* Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
var models = require('./index');
/**
* @class
* Initializes a new instance of the UpdateApplicationUpgradeDescription class.
* @constructor
* @member {string} [name]
*
* @member {number} [upgradeKind]
*
* @member {object} [updateDescription]
*
* @member {number} [updateDescription.rollingUpgradeMode]
*
* @member {boolean} [updateDescription.forceRestart]
*
* @member {number} [updateDescription.failureAction]
*
* @member {number} [updateDescription.upgradeReplicaSetCheckTimeoutInSeconds]
*
* @member {string} [updateDescription.healthCheckWaitDurationInMilliseconds]
*
* @member {string}
* [updateDescription.healthCheckStableDurationInMilliseconds]
*
* @member {string} [updateDescription.healthCheckRetryTimeoutInMilliseconds]
*
* @member {string} [updateDescription.upgradeTimeoutInMilliseconds]
*
* @member {string} [updateDescription.upgradeDomainTimeoutInMilliseconds]
*
* @member {object} [applicationHealthPolicy]
*
* @member {boolean} [applicationHealthPolicy.considerWarningAsError]
*
* @member {number}
* [applicationHealthPolicy.maxPercentUnhealthyDeployedApplications]
*
* @member {object} [applicationHealthPolicy.defaultServiceTypeHealthPolicy]
*
* @member {number}
* [applicationHealthPolicy.defaultServiceTypeHealthPolicy.maxPercentUnhealthyServices]
*
* @member {number}
* [applicationHealthPolicy.defaultServiceTypeHealthPolicy.maxPercentUnhealthyPartitionsPerService]
*
* @member {number}
* [applicationHealthPolicy.defaultServiceTypeHealthPolicy.maxPercentUnhealthyReplicasPerPartition]
*
*/
function UpdateApplicationUpgradeDescription() {
}
/**
* Defines the metadata of UpdateApplicationUpgradeDescription
*
* @returns {object} metadata of UpdateApplicationUpgradeDescription
*
*/
UpdateApplicationUpgradeDescription.prototype.mapper = function () {
return {
required: false,
serializedName: 'UpdateApplicationUpgradeDescription',
type: {
name: 'Composite',
className: 'UpdateApplicationUpgradeDescription',
modelProperties: {
name: {
required: false,
serializedName: 'Name',
type: {
name: 'String'
}
},
upgradeKind: {
required: false,
serializedName: 'UpgradeKind',
type: {
name: 'Number'
}
},
updateDescription: {
required: false,
serializedName: 'UpdateDescription',
type: {
name: 'Composite',
className: 'UpdateApplicationUpgradeDescriptionUpdateDescription'
}
},
applicationHealthPolicy: {
required: false,
serializedName: 'ApplicationHealthPolicy',
type: {
name: 'Composite',
className: 'ApplicationHealthPolicy'
}
}
}
}
};
};
module.exports = UpdateApplicationUpgradeDescription;
|
smithab/azure-sdk-for-node
|
lib/services/serviceFabric/lib/models/updateApplicationUpgradeDescription.js
|
JavaScript
|
mit
| 3,108
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
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 extendStatics(d, b);
};
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;
};
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
import { _, AgAbstractField, AgCheckbox, AgGroupComponent, AgRadioButton, AgToggleButton, Autowired, ChartType, Component, DragAndDropService, DragSourceType, PostConstruct, VerticalDirection } from "@ag-grid-community/core";
import { ChartController } from "../../chartController";
var ChartDataPanel = /** @class */ (function (_super) {
__extends(ChartDataPanel, _super);
function ChartDataPanel(chartController) {
var _this = _super.call(this, ChartDataPanel.TEMPLATE) || this;
_this.columnComps = new Map();
_this.chartController = chartController;
return _this;
}
ChartDataPanel.prototype.init = function () {
this.updatePanels();
this.addManagedListener(this.chartController, ChartController.EVENT_CHART_UPDATED, this.updatePanels.bind(this));
};
ChartDataPanel.prototype.destroy = function () {
this.clearComponents();
_super.prototype.destroy.call(this);
};
ChartDataPanel.prototype.updatePanels = function () {
var _this = this;
var currentChartType = this.chartType;
var _a = this.chartController.getColStateForMenu(), dimensionCols = _a.dimensionCols, valueCols = _a.valueCols;
var colIds = dimensionCols.map(function (c) { return c.colId; }).concat(valueCols.map(function (c) { return c.colId; }));
this.chartType = this.chartController.getChartType();
if (_.areEqual(_.keys(this.columnComps), colIds) && this.chartType === currentChartType) {
// if possible, we just update existing components
__spreadArrays(dimensionCols, valueCols).forEach(function (col) {
_this.columnComps.get(col.colId).setValue(col.selected, true);
});
if (this.chartController.isActiveXYChart()) {
var getSeriesLabel_1 = this.generateGetSeriesLabel();
valueCols.forEach(function (col) {
_this.columnComps.get(col.colId).setLabel(getSeriesLabel_1(col));
});
}
}
else {
// otherwise we re-create everything
this.clearComponents();
this.createCategoriesGroupComponent(dimensionCols);
this.createSeriesGroupComponent(valueCols);
}
};
ChartDataPanel.prototype.addComponent = function (parent, component) {
var eDiv = document.createElement('div');
eDiv.className = 'ag-chart-data-section';
eDiv.appendChild(component.getGui());
parent.appendChild(eDiv);
};
ChartDataPanel.prototype.addChangeListener = function (component, columnState) {
var _this = this;
this.addManagedListener(component, AgAbstractField.EVENT_CHANGED, function () {
columnState.selected = component.getValue();
_this.chartController.updateForPanelChange(columnState);
});
};
ChartDataPanel.prototype.createCategoriesGroupComponent = function (columns) {
var _this = this;
this.categoriesGroupComp = this.createBean(new AgGroupComponent({
title: this.getCategoryGroupTitle(),
enabled: true,
suppressEnabledCheckbox: true,
suppressOpenCloseIcons: false,
cssIdentifier: 'charts-data'
}));
var inputName = "chartDimension" + this.getCompId();
columns.forEach(function (col) {
var comp = _this.categoriesGroupComp.createManagedBean(new AgRadioButton());
comp.setLabel(_.escapeString(col.displayName));
comp.setValue(col.selected);
comp.setInputName(inputName);
_this.addChangeListener(comp, col);
_this.categoriesGroupComp.addItem(comp);
_this.columnComps.set(col.colId, comp);
});
this.addComponent(this.getGui(), this.categoriesGroupComp);
};
ChartDataPanel.prototype.createSeriesGroupComponent = function (columns) {
var _this = this;
this.seriesGroupComp = this.createManagedBean(new AgGroupComponent({
title: this.getSeriesGroupTitle(),
enabled: true,
suppressEnabledCheckbox: true,
suppressOpenCloseIcons: false,
cssIdentifier: 'charts-data'
}));
if (this.chartController.isActiveXYChart()) {
var pairedModeToggle = this.seriesGroupComp.createManagedBean(new AgToggleButton());
var chartProxy_1 = this.chartController.getChartProxy();
pairedModeToggle
.setLabel(this.chartTranslator.translate('paired'))
.setLabelAlignment('left')
.setLabelWidth('flex')
.setInputWidth(45)
.setValue(chartProxy_1.getSeriesOption('paired') || false)
.onValueChange(function (newValue) {
chartProxy_1.setSeriesOption('paired', newValue);
_this.chartController.updateForGridChange();
});
this.seriesGroupComp.addItem(pairedModeToggle);
}
var getSeriesLabel = this.generateGetSeriesLabel();
columns.forEach(function (col) {
var comp = _this.seriesGroupComp.createManagedBean(new AgCheckbox());
comp.addCssClass('ag-data-select-checkbox');
var label = getSeriesLabel(col);
comp.setLabel(label);
comp.setValue(col.selected);
_this.addChangeListener(comp, col);
_this.seriesGroupComp.addItem(comp);
_this.columnComps.set(col.colId, comp);
_this.addDragHandle(comp, col);
});
this.addComponent(this.getGui(), this.seriesGroupComp);
var dropTarget = {
getContainer: this.getGui.bind(this),
onDragging: this.onDragging.bind(this),
isInterestedIn: this.isInterestedIn.bind(this),
};
this.dragAndDropService.addDropTarget(dropTarget);
};
ChartDataPanel.prototype.addDragHandle = function (comp, col) {
var _this = this;
var eDragHandle = _.createIconNoSpan('columnDrag', this.gridOptionsWrapper);
_.addCssClass(eDragHandle, 'ag-drag-handle');
_.addCssClass(eDragHandle, 'ag-chart-data-column-drag-handle');
comp.getGui().insertAdjacentElement('beforeend', eDragHandle);
var dragSource = {
type: DragSourceType.ChartPanel,
eElement: eDragHandle,
dragItemName: col.displayName,
defaultIconName: DragAndDropService.ICON_MOVE,
getDragItem: function () { return ({ columns: [col.column] }); },
onDragStopped: function () { _this.insertIndex = undefined; }
};
this.dragAndDropService.addDragSource(dragSource, true);
this.addDestroyFunc(function () { return _this.dragAndDropService.removeDragSource(dragSource); });
};
ChartDataPanel.prototype.generateGetSeriesLabel = function () {
if (!this.chartController.isActiveXYChart()) {
return function (col) { return _.escapeString(col.displayName); };
}
var isBubble = this.chartType === ChartType.Bubble;
var isInPairedMode = this.isInPairedMode();
var selectedValuesCount = 0;
var indexToAxisLabel = new Map();
indexToAxisLabel.set(0, 'X');
indexToAxisLabel.set(1, 'Y');
indexToAxisLabel.set(2, 'size');
return function (col) {
var escapedLabel = _.escapeString(col.displayName);
if (!col.selected) {
return escapedLabel;
}
var axisLabel;
if (isInPairedMode) {
axisLabel = indexToAxisLabel.get(selectedValuesCount % (isBubble ? 3 : 2));
}
else {
if (selectedValuesCount === 0) {
axisLabel = 'X';
}
else {
axisLabel = isBubble && selectedValuesCount % 2 === 0 ? 'size' : 'Y';
}
}
selectedValuesCount++;
return escapedLabel + " (" + axisLabel + ")";
};
};
ChartDataPanel.prototype.getCategoryGroupTitle = function () {
return this.chartTranslator.translate(this.chartController.isActiveXYChart() ? 'labels' : 'categories');
};
ChartDataPanel.prototype.getSeriesGroupTitle = function () {
return this.chartTranslator.translate(this.chartController.isActiveXYChart() ? 'xyValues' : 'series');
};
ChartDataPanel.prototype.isInPairedMode = function () {
return this.chartController.isActiveXYChart() && this.chartController.getChartProxy().getSeriesOption('paired');
};
ChartDataPanel.prototype.clearComponents = function () {
_.clearElement(this.getGui());
this.categoriesGroupComp = this.destroyBean(this.categoriesGroupComp);
this.seriesGroupComp = this.destroyBean(this.seriesGroupComp);
this.columnComps.clear();
};
ChartDataPanel.prototype.onDragging = function (draggingEvent) {
var _this = this;
if (this.checkInsertIndex(draggingEvent)) {
var column_1 = draggingEvent.dragItem.columns[0];
var _a = this.chartController.getColStateForMenu(), dimensionCols = _a.dimensionCols, valueCols = _a.valueCols;
__spreadArrays(dimensionCols, valueCols).filter(function (state) { return state.column === column_1; })
.forEach(function (state) {
state.order = _this.insertIndex;
_this.chartController.updateForPanelChange(state);
});
}
};
ChartDataPanel.prototype.checkInsertIndex = function (draggingEvent) {
if (_.missing(draggingEvent.vDirection)) {
return false;
}
var newIndex = 0;
var mouseEvent = draggingEvent.event;
this.columnComps.forEach(function (comp) {
var rect = comp.getGui().getBoundingClientRect();
var verticalFit = mouseEvent.clientY >= (draggingEvent.vDirection === VerticalDirection.Down ? rect.top : rect.bottom);
if (verticalFit) {
newIndex++;
}
});
var changed = this.insertIndex !== undefined && newIndex !== this.insertIndex;
this.insertIndex = newIndex;
return changed;
};
ChartDataPanel.prototype.isInterestedIn = function (type) {
return type === DragSourceType.ChartPanel;
};
ChartDataPanel.TEMPLATE = "<div class=\"ag-chart-data-wrapper\"></div>";
__decorate([
Autowired('dragAndDropService')
], ChartDataPanel.prototype, "dragAndDropService", void 0);
__decorate([
Autowired('chartTranslator')
], ChartDataPanel.prototype, "chartTranslator", void 0);
__decorate([
PostConstruct
], ChartDataPanel.prototype, "init", null);
return ChartDataPanel;
}(Component));
export { ChartDataPanel };
|
ceolter/angular-grid
|
enterprise-modules/charts/dist/es6/charts/chartComp/menu/data/chartDataPanel.js
|
JavaScript
|
mit
| 12,388
|
/**
* Utilities; useful scripts
*/
var utils = {
debug: false
}
/**
* Functions related to arrays
*/
utils.array = {
/**
* Is the given value present in the array
*
* @return bool
*/
inArray: function (needle, array) {
// loop values
for (var i in array) {
if (array[i] === needle) return true
}
// fallback
return false
}
}
/**
* Function related to cookies
*/
utils.cookies = {
/**
* Are cookies enabled?
*
* @return bool
*/
isEnabled: function () {
// try to grab the property
var cookiesEnabled = !!(navigator.cookieEnabled)
// unknown property?
if (typeof navigator.cookieEnabled === 'undefined' && !cookiesEnabled) {
// try to set a cookie
document.cookie = 'testcookie'
cookiesEnabled = ($.inArray('testcookie', document.cookie) !== -1)
}
// return
return cookiesEnabled
},
/**
* Read a cookie
*
* @return mixed
*/
readCookie: function (name) {
// get cookies
var cookies = document.cookie.split(';')
name = name + '='
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i]
while (cookie.charAt(0) === ' ') cookie = cookie.substring(1, cookie.length)
if (cookie.indexOf(name) === 0) return cookie.substring(name.length, cookie.length)
}
// fallback
return null
},
setCookie: function (name, value, days) {
if (typeof days === 'undefined') days = 7
var expireDate = new Date()
expireDate.setDate(expireDate.getDate() + days)
document.cookie = name + '=' + escape(value) + ';expires=' + expireDate.toUTCString() + ';path=/'
}
}
/**
* Functions related to forms
*/
utils.form = {
/**
* Is a checkbox checked?
*
* @return bool
* @param object element
*/
isChecked: function (element) {
return ($('input[name="' + element.attr('name') + '"]:checked').length >= 1)
},
/**
* Is the value inside the element a valid email address
*
* @return bool
* @param object element
*/
isEmail: function (element) {
var regexp = /^[a-z0-9!#$%&'*+-/=?^_`{|}.~]+@([a-z0-9]+([-]+[a-z0-9]+)*\.)+[a-z]{2,7}$/i
return regexp.test(element.val())
},
/**
* Is the element filled
*
* @return bool
* @param object element
*/
isFilled: function (element) {
return (utils.string.trim(element.val()) !== '')
},
/**
* Is the value inside the element a valid number
*
* @return bool
* @param object element
*/
isNumber: function (element) {
return (!isNaN(element.val()) && element.val() !== '')
},
/**
* Is the value inside the element a valid URL
*
* @return bool
* @param object element
*/
isURL: function (element) {
var regexp = /^((http|ftp|https):\/{2})?(([0-9a-zA-Z_-]+\.)+[0-9a-zA-Z]+)((:[0-9]+)?)((\/([~0-9a-zA-Z#%@./_-]+)?(\?[0-9a-zA-Z%@/&=_-]+)?)?)$/i
return regexp.test(element.val())
}
}
/**
* Functions related to strings
*/
utils.string = {
// data member
div: false,
/**
* Fix a HTML5-chunk, so IE can render it
*
* @return string
* @param string html
*/
html5: function (html) {
var html5 = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' ')
var i = 0
// create div if needed
if (utils.string.div === false) {
utils.string.div = document.createElement('div')
utils.string.div.innerHTML = '<nav></nav>'
if (utils.string.div.childNodes.length !== 1) {
var fragment = document.createDocumentFragment()
i = html5.length
while (i--) fragment.createElement(html5[i])
fragment.appendChild(utils.string.div)
}
}
html = html.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
// fix for when in a table
var inTable = html.match(/^<(tbody|tr|td|th|col|colgroup|thead|tfoot)[\s/>]/i)
if (inTable) {
utils.string.div.innerHTML = '<table>' + html + '</table>'
} else {
utils.string.div.innerHTML = html
}
var scope
if (inTable) {
scope = utils.string.div.getElementsByTagName(inTable[1])[0].parentNode
} else {
scope = utils.string.div
}
var returnedFragment = document.createDocumentFragment()
i = scope.childNodes.length
while (i--) returnedFragment.appendChild(scope.firstChild)
return returnedFragment
},
/**
* Encode the string as HTML
*
* @return string
* @param string value
*/
htmlEncode: function (value) {
return $('<div/>').text(value).html()
},
/**
* Decode the string as HTML
*
* @return string
* @param string value
*/
htmlDecode: function (value) {
return $('<div/>').html(value).text()
},
/**
* Replace all occurences of one string into a string
*
* @return string
* @param string value
* @param string needle
* @param string replacement
*/
replaceAll: function (value, needle, replacement) {
if (typeof value === 'undefined') return ''
return value.replace(new RegExp(needle, 'g'), replacement)
},
/**
* Sprintf replaces all arguments that occur in the string (%1$s, %2$s, ...)
*
* @return string
* @param string value
* @params string arguments
*/
sprintf: function (value) {
if (arguments.length < 2) {
return value
} else {
// replace $ symbol first, because our RegExp won't except this symbol
value = value.replace(/\$s/g, 'Ss')
// find all variables and replace them
for (var i = 1; i < arguments.length; i++) {
value = utils.string.replaceAll(value, '%' + i + 'Ss', arguments[i])
}
}
return value
},
/**
* Strip HTML tags
*
* @return string
*/
stripTags: function (value) {
return value.replace(/<[^>]*>/ig, '')
},
/**
* Strip whitespace from the beginning and end of a string
*
* @return string
* @param string value
* @param string[optional] charList
*/
trim: function (value, charList) {
if (typeof value === 'undefined') return ''
if (typeof charList === 'undefined') charList = ' '
var pattern = new RegExp('^[' + charList + ']*|[' + charList + ']*$', 'g')
return value.replace(pattern, '')
},
/**
* PHP-like urlencode
*
* @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/encodeURIComponent#Description
* @return string
* @param string value
*/
urlEncode: function (value) {
return encodeURIComponent(value).replace(/%20/g, '+').replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/~/g, '%7E')
},
/**
* PHP-like urlencode
*
* @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Functions/encodeURIComponent#Description
* @return string
* @param string value
*/
urlDecode: function (value) {
return decodeURIComponent(value.replace(/\+/g, '%20').replace(/%21/g, '!').replace(/%27/g, '\'').replace(/%28/g, '(').replace(/%29/g, ')').replace(/%2A/g, '*').replace(/%7E/g, '~'))
},
/**
* Urlise a string (cfr. SpoonFilter::urlise)
*
* @return string
* @param string value
*/
urlise: function (value) {
// reserved characters (RFC 3986)
var reservedCharacters = [
'/', '?', ':', '@', '#', '[', ']',
'!', '$', '&', '\'', '(', ')', '*',
'+', ',', ';', '='
]
// remove reserved characters
for (var i in reservedCharacters) value = value.replace(reservedCharacters[i], ' ')
// replace double quote, since this one might cause problems in html (e.g. <a href="double"quote">)
value = utils.string.replaceAll(value, '"', ' ')
// replace spaces by dashes
value = utils.string.replaceAll(value, ' ', '-')
// only urlencode if not yet urlencoded
if (utils.string.urlDecode(value) === value) {
// to lowercase
value = value.toLowerCase()
// urlencode
value = utils.string.urlEncode(value)
}
// convert "--" to "-"
value = value.replace(/-+/, '-')
// trim - signs
return utils.string.trim(value, '-')
},
/**
* Adds a capital letter to a string
*
* @return string
* @param string $value
*/
ucfirst: function (value) {
return value.charAt(0).toUpperCase() + value.slice(1)
},
/**
* Convert a HTML string to a XHTML string.
*
* @return string
* @param string value
*/
xhtml: function (value) {
// break tags should end with a slash
value = value.replace(/<br>/g, '<br />')
value = value.replace(/<br ?\/?>$/g, '')
value = value.replace(/^<br ?\/?>/g, '')
// image tags should end with a slash
value = value.replace(/(<img [^>]+[^/])>/gi, '$1 />')
// input tags should end with a slash
value = value.replace(/(<input [^>]+[^/])>/gi, '$1 />')
// big no-no to <b|i|u>
value = value.replace(/<b\b[^>]*>(.*?)<\/b[^>]*>/g, '<strong>$1</strong>')
value = value.replace(/<i\b[^>]*>(.*?)<\/i[^>]*>/g, '<em>$1</em>')
value = value.replace(/<u\b[^>]*>(.*?)<\/u[^>]*>/g, '<span style="text-decoration:underline">$1</span>')
// XHTML
return value
}
}
/**
* Functions related to the current url
*/
utils.url = {
extractParamFromUri: function (uri, paramName) {
if (!uri) return
uri = uri.split('#')[0]
var parts = uri.split('?')
if (parts.length === 1) return
var query = decodeURI(parts[1])
paramName += '='
var params = query.split('&')
for (var i = 0; i < params.length; ++i) {
var param = params[i]
if (param.indexOf(paramName) === 0) return decodeURIComponent(param.split('=')[1])
}
},
/**
* Get a GET parameter
*
* @return string
* @param string name
*/
getGetValue: function (name) {
// init return value
var getValue = ''
// get GET chunks from url
var hashes = window.location.search.slice(window.location.search.indexOf('?') + 1).split('&')
// find requested parameter
$.each(hashes, function (index, value) {
// split name/value up
var chunks = value.split('=')
// found the requested parameter
if (chunks[0] === name) {
// set for return
getValue = chunks[1]
// break loop
return false
}
})
// cough up value
return getValue
}
}
|
riadvice/forkcms
|
src/Frontend/Core/Js/utils.js
|
JavaScript
|
mit
| 10,489
|
suite('isObject', () => {
function isObject1(obj) {
return obj && Object.prototype.toString.call(obj) === '[object Object]'
}
function isObject2(obj) {
return obj && typeof obj === 'object' && !Array.isArray(obj)
}
const obj0 = {}
const obj1 = null
const obj2 = []
const obj3 = '123'
const obj4 = 123
function use(result) {
return result === true
}
benchmark('isObject impl 1', () => {
use(isObject1(obj0))
use(isObject1(obj1))
use(isObject1(obj2))
use(isObject1(obj3))
use(isObject1(obj4))
})
benchmark('isObject impl 2', () => {
use(isObject2(obj0))
use(isObject2(obj1))
use(isObject2(obj2))
use(isObject2(obj3))
use(isObject2(obj4))
})
})
|
cssinjs/jss
|
packages/jss/benchmark/tests/is-object.js
|
JavaScript
|
mit
| 729
|
'use strict';
describe('Test vehicle Service', function() {
var url = 'http://localhost:5002';
var vehicleService, $httpBackend, scope;
var vehicles=[{
'email': 'mary@demo.org',
'name': 'Lincon MKX'
}, {
'email': 'mary@demo.org',
'name': 'Corolla'
}];
var vehicle = {
'email': 'mary@demo.org',
'name': 'Golf'
};
beforeEach(module('appServices'));
beforeEach(inject(function(Vehicle, $rootScope, _$httpBackend_) {
vehicleService = Vehicle;
scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
}));
it('should be able to query vehicles', function() {
$httpBackend.expectGET(url + '/api/vehicles?tid=f2cb3e8d653f46008272113c6c72422843902ef8')
.respond(200, vehicles);
vehicleService.query('f2cb3e8d653f46008272113c6c72422843902ef8',
function(data, status, headers, config){
scope.vehicles = data;
});
$httpBackend.flush();
//console.log('vehicles=%j', scope.vehicles);
expect(scope.vehicles.length).toBe(2);
});
//
it('should be able to save vehicle', function() {
$httpBackend.expectPOST(url + '/api/vehicles?tid=f2cb3e8d653f46008272113c6c72422843902ef8', vehicle)
.respond(200, vehicle);
vehicleService.save('f2cb3e8d653f46008272113c6c72422843902ef8', vehicle,
function(data, status, headers, config){
scope.vehicle = data;
});
$httpBackend.flush();
//console.log('vehicle=%j', scope.vehicle);
expect(scope.vehicle.name).toBe('Golf');
});
});
|
vollov/mileagelog
|
client/test/unit/services/vehicle.test.js
|
JavaScript
|
mit
| 1,446
|
(function(JVM) {
JVM.RegisterBuiltIn("java/lang/Object", {
'$impl': {
'getClass$()Ljava/lang/Class;': function($) {
return this.$class.class; // Return the Java Class implementation from our class
},
'toString$()Ljava/lang/String;': function($) {
return $.jvm.createString(this.$class.$className + "@" + this.$id);
},
'hashCode$()I': function() {
return this.$id;
}
}
});
})(JVM);
|
NexusTools/NexusToolsWebsite
|
src/static/jvm/jvm.js/classes/java_lang_Object.js
|
JavaScript
|
mit
| 537
|
var models = require('./../app/models')
, db = require('../db').connect()
, async = require('async')
var updateUserInfo = function() {
var userSerializer = {
select: ['id', 'username', 'type', 'info'],
info: {
select: ['screenName', 'email', 'receiveEmails']
}
}
db.keys('user:*', function(err, usersIdKeys) {
async.forEach(usersIdKeys,
function(usersIdKey, callback) {
var userId;
usersIdKey = usersIdKey.replace(/user:/, '');
if (/:(\w)+/.test(usersIdKey))
return callback(null)
userId = usersIdKey;
models.User.findById(userId, function(err, user) {
if (!user)
return callback(null)
if (user.info || (user.info &&user.info.screenName))
return callback(null)
var params = {
screenName: user.username
}
user.update(params, function(err, user) {
if (err)
return callback(err)
console.log("User " + user.username + " updated.")
callback(err)
})
})
},
function(err) {
console.log('User info update completed.');
if (err)
console.log("Error occured.")
})
})
db.get('username:anonymous:uid', function(err, uid) {
db.hset('user:' + uid + ':info', 'screenName', 'anonymous', function(err, res) {
console.log("Updated anonymous user.")
})
})
}
exports.updateUserInfo = function() {
updateUserInfo();
}
|
berkus/pepyatka-server
|
services/update-user-info.js
|
JavaScript
|
mit
| 1,836
|
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
/* eslint-disable jsx-a11y/aria-role */
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { deepmerge } from '@material-ui/utils';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import KeyboardArrowLeft from '../internal/svg-icons/KeyboardArrowLeft';
import KeyboardArrowRight from '../internal/svg-icons/KeyboardArrowRight';
import ButtonBase from '../ButtonBase';
import useThemeProps from '../styles/useThemeProps';
import experimentalStyled from '../styles/experimentalStyled';
import { getTabScrollButtonUtilityClass } from './tabScrollButtonClasses';
const overridesResolver = (props, styles) => {
const {
styleProps
} = props;
return deepmerge(_extends({}, styleProps.orientation && styles[styleProps.orientation]), styles.root || {});
};
const useUtilityClasses = styleProps => {
const {
classes,
orientation,
disabled
} = styleProps;
const slots = {
root: ['root', orientation, disabled && 'disabled']
};
return composeClasses(slots, getTabScrollButtonUtilityClass, classes);
};
const TabScrollButtonRoot = experimentalStyled(ButtonBase, {}, {
name: 'MuiTabScrollButton',
slot: 'Root',
overridesResolver
})(({
styleProps
}) => _extends({
/* Styles applied to the root element. */
width: 40,
flexShrink: 0,
opacity: 0.8,
'&.Mui-disabled': {
opacity: 0
}
}, styleProps.orientation === 'vertical' && {
width: '100%',
height: 40,
'& svg': {
transform: 'rotate(90deg)'
}
}));
var _ref = /*#__PURE__*/React.createElement(KeyboardArrowLeft, {
fontSize: "small"
});
var _ref2 = /*#__PURE__*/React.createElement(KeyboardArrowRight, {
fontSize: "small"
});
const TabScrollButton = /*#__PURE__*/React.forwardRef(function TabScrollButton(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiTabScrollButton'
});
const {
className,
direction
} = props,
other = _objectWithoutPropertiesLoose(props, ["className", "direction", "orientation", "disabled"]); // TODO: convert to simple assignment after the type error in defaultPropsHandler.js:60:6 is fixed
const styleProps = _extends({}, props);
const classes = useUtilityClasses(styleProps);
return /*#__PURE__*/React.createElement(TabScrollButtonRoot, _extends({
component: "div",
className: clsx(classes.root, className),
ref: ref,
role: null,
styleProps: styleProps,
tabIndex: null
}, other), direction === 'left' ? _ref : _ref2);
});
process.env.NODE_ENV !== "production" ? TabScrollButton.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The direction the button should indicate.
*/
direction: PropTypes.oneOf(['left', 'right']).isRequired,
/**
* If `true`, the component is disabled.
*/
disabled: PropTypes.bool,
/**
* The component orientation (layout flow direction).
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']).isRequired,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object
} : void 0;
export default TabScrollButton;
|
cdnjs/cdnjs
|
ajax/libs/material-ui/5.0.0-alpha.27/modern/TabScrollButton/TabScrollButton.js
|
JavaScript
|
mit
| 3,824
|
/**
* @license Highstock JS v8.2.2 (2020-10-22)
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Paweł Fus
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/price-envelopes', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'Stock/Indicators/PriceEnvelopesIndicator.js', [_modules['Core/Series/Series.js'], _modules['Core/Utilities.js']], function (BaseSeries, U) {
/* *
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var isArray = U.isArray,
merge = U.merge;
// im port './SMAIndicator.js';
var SMA = BaseSeries.seriesTypes.sma;
/**
* The Price Envelopes series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.priceenvelopes
*
* @augments Highcharts.Series
*/
BaseSeries.seriesType('priceenvelopes', 'sma',
/**
* Price envelopes indicator based on [SMA](#plotOptions.sma) calculations.
* This series requires the `linkedTo` option to be set and should be loaded
* after the `stock/indicators/indicators.js` file.
*
* @sample stock/indicators/price-envelopes
* Price envelopes
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/price-envelopes
* @optionparent plotOptions.priceenvelopes
*/
{
marker: {
enabled: false
},
tooltip: {
pointFormat: '<span style="color:{point.color}">\u25CF</span><b> {series.name}</b><br/>Top: {point.top}<br/>Middle: {point.middle}<br/>Bottom: {point.bottom}<br/>'
},
params: {
period: 20,
/**
* Percentage above the moving average that should be displayed.
* 0.1 means 110%. Relative to the calculated value.
*/
topBand: 0.1,
/**
* Percentage below the moving average that should be displayed.
* 0.1 means 90%. Relative to the calculated value.
*/
bottomBand: 0.1
},
/**
* Bottom line options.
*/
bottomLine: {
styles: {
/**
* Pixel width of the line.
*/
lineWidth: 1,
/**
* Color of the line. If not set, it's inherited from
* [plotOptions.priceenvelopes.color](
* #plotOptions.priceenvelopes.color).
*
* @type {Highcharts.ColorString}
*/
lineColor: void 0
}
},
/**
* Top line options.
*
* @extends plotOptions.priceenvelopes.bottomLine
*/
topLine: {
styles: {
lineWidth: 1
}
},
dataGrouping: {
approximation: 'averages'
}
},
/**
* @lends Highcharts.Series#
*/
{
nameComponents: ['period', 'topBand', 'bottomBand'],
nameBase: 'Price envelopes',
pointArrayMap: ['top', 'middle', 'bottom'],
parallelArrays: ['x', 'y', 'top', 'bottom'],
pointValKey: 'middle',
init: function () {
SMA.prototype.init.apply(this, arguments);
// Set default color for lines:
this.options = merge({
topLine: {
styles: {
lineColor: this.color
}
},
bottomLine: {
styles: {
lineColor: this.color
}
}
}, this.options);
},
toYData: function (point) {
return [point.top, point.middle, point.bottom];
},
translate: function () {
var indicator = this, translatedEnvelopes = ['plotTop', 'plotMiddle', 'plotBottom'];
SMA.prototype.translate.apply(indicator);
indicator.points.forEach(function (point) {
[point.top, point.middle, point.bottom].forEach(function (value, i) {
if (value !== null) {
point[translatedEnvelopes[i]] =
indicator.yAxis.toPixels(value, true);
}
});
});
},
drawGraph: function () {
var indicator = this,
middleLinePoints = indicator.points,
pointsLength = middleLinePoints.length,
middleLineOptions = (indicator.options),
middleLinePath = indicator.graph,
gappedExtend = {
options: {
gapSize: middleLineOptions.gapSize
}
},
deviations = [[],
[]], // top and bottom point place holders
point;
// Generate points for top and bottom lines:
while (pointsLength--) {
point = middleLinePoints[pointsLength];
deviations[0].push({
plotX: point.plotX,
plotY: point.plotTop,
isNull: point.isNull
});
deviations[1].push({
plotX: point.plotX,
plotY: point.plotBottom,
isNull: point.isNull
});
}
// Modify options and generate lines:
['topLine', 'bottomLine'].forEach(function (lineName, i) {
indicator.points = deviations[i];
indicator.options = merge(middleLineOptions[lineName].styles, gappedExtend);
indicator.graph = indicator['graph' + lineName];
SMA.prototype.drawGraph.call(indicator);
// Now save lines:
indicator['graph' + lineName] = indicator.graph;
});
// Restore options and draw a middle line:
indicator.points = middleLinePoints;
indicator.options = middleLineOptions;
indicator.graph = middleLinePath;
SMA.prototype.drawGraph.call(indicator);
},
getValues: function (series, params) {
var period = params.period,
topPercent = params.topBand,
botPercent = params.bottomBand,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
// 0- date, 1-top line, 2-middle line, 3-bottom line
PE = [],
// middle line, top line and bottom line
ML,
TL,
BL,
date,
xData = [],
yData = [],
slicedX,
slicedY,
point,
i;
// Price envelopes requires close value
if (xVal.length < period ||
!isArray(yVal[0]) ||
yVal[0].length !== 4) {
return;
}
for (i = period; i <= yValLen; i++) {
slicedX = xVal.slice(i - period, i);
slicedY = yVal.slice(i - period, i);
point = SMA.prototype.getValues.call(this, {
xData: slicedX,
yData: slicedY
}, params);
date = point.xData[0];
ML = point.yData[0];
TL = ML * (1 + topPercent);
BL = ML * (1 - botPercent);
PE.push([date, TL, ML, BL]);
xData.push(date);
yData.push([TL, ML, BL]);
}
return {
values: PE,
xData: xData,
yData: yData
};
}
});
/**
* A price envelopes indicator. If the [type](#series.priceenvelopes.type)
* option is not specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.priceenvelopes
* @since 6.0.0
* @excluding dataParser, dataURL
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/price-envelopes
* @apioption series.priceenvelopes
*/
''; // to include the above in the js output
});
_registerModule(_modules, 'masters/indicators/price-envelopes.src.js', [], function () {
});
}));
|
cdnjs/cdnjs
|
ajax/libs/highcharts/8.2.2/indicators/price-envelopes.src.js
|
JavaScript
|
mit
| 10,344
|
define(['database', 'queue', 'qPopulate', 'status', 'qData'], function(database, questionQueue, populate, status, queueData) {
// ===============================================
//
// Populate
//
//
describe('Queue: Testing Queue Load and Save', function() {
var currentQuestion, currentQuestionID, nextQuestion;
var sizeOfQueueBeforeSaveAndLoad;
var arrayOfQuestionData = [{
'question': "a lss",
'answer': "un lss"
}, {
'question': "a few lss",
'answer': "quelques lss"
}, {
'question': "about lss",
'answer': "environ lss"
}, {
'question': "according to lss",
'answer': "selon lss"
}];
// Create before testing
before(function(done) {
status.rq("in Load And Save Spec questionQueue is " + JSON.stringify(questionQueue) + ".");
var step1 = function() {
questionQueue.clear();
database.createdb();
done();
};
database.deletedb(step1);
});
after(function(done) {
var nextStep = function() {
done();
};
database.deletedb(nextStep);
});
// ===============================================
//
// Run these tests
//
//
it('Queue Size: Confirm that the queue is initially of size 0', function() {
assert.equal(questionQueue.size(), 0, "questionQueue Size (" + questionQueue.size() + ")should start at 0");
});
it('Queue Size: Populate and confirm queue size is 4', function(done) {
// ===============================================
// Populate the question queue
var step2 = function() {
var localQueue = questionQueue.get();
var queueSize = localQueue.length;
status.qls("questionQueue Size (" + questionQueue.size() + ") or " + queueSize + " should equal the number of questions we added just now(" + arrayOfQuestionData.length + ")");
var lqueueSize = questionQueue.size();
// Store down the size for later
sizeOfQueueBeforeSaveAndLoad = lqueueSize;
assert.equal(lqueueSize, arrayOfQuestionData.length, "Didnt match");
status.qls("questionQueue Size (" + lqueueSize + ") should equal the number of questions we added just now(" + arrayOfQuestionData.length + ")");
done();
};
populate(arrayOfQuestionData, step2);
});
it('Save with no error', function(done) {
var step2 = function(err) {
assert.notOk(err, "There was an error:" + err + ".");
done();
};
status.qls("questionQueue Size (" + questionQueue.size() + ") should equal the number of questions we added just now(" + arrayOfQuestionData.length + ")");
questionQueue.save(step2);
});
it('Save AGAIN with no error (since the _rev seems to be picky)', function(done) {
var step2 = function(err) {
assert.notOk(err, "There was an error:" + err + ".");
done();
};
status.qls("questionQueue Size (" + questionQueue.size() + ") should equal the number of questions we added just now(" + arrayOfQuestionData.length + ")");
questionQueue.save(step2);
});
it('Clear the queue and confirm it is size 0', function() {
questionQueue.clear();
var lqueueSize = questionQueue.size();
assert.equal(lqueueSize, 0, "Wasn't properly cleared");
});
it('Confirm that Current was cleared', function() {
var currentID = questionQueue.getCurrent();
assert.equal(currentID,227, "No the current doesnt have an ID yet");
});
it('Load and confirm that its the same size', function(done) {
var step2 = function() {
var lqueueSize = questionQueue.size();
assert.equal(lqueueSize, sizeOfQueueBeforeSaveAndLoad, "Wasn't properly Loaded");
done();
};
questionQueue.load(step2);
});
it('Confirm that Current was properly loaded with functions', function() {
var currentID = questionQueue.getCurrent().getID();
assert.ok(currentID, "No the current doesnt have an ID yet");
});
it('Confirm that Next was properly loaded with functions', function() {
var nextID = questionQueue.getNext().getID();
assert.ok(nextID, "No the current doesnt have an ID yet");
});
it('Confirm that Previous was properly loaded with functions', function() {
var previousID = questionQueue.getPrevious().getMode();
assert.ok(previousID, "No the current doesnt have an ID yet");
});
//Need to do this
// Before
// DONE
// Manually load up the queue
// DONE
// Store down how many are in the queue
// DONE
// Save the queue
// Empty the queue
// Confirm 0 quantity
// Load the queue from the save
// Confirm the same quantity
});
});
|
JudgeGroovyman/new_lazacademy
|
public/javascripts/app/queue/load_save_spec.js
|
JavaScript
|
cc0-1.0
| 5,463
|
var require = { "paths" :
{
"jquery": "./lib/jquery/dist/jquery",
"underscore": "./lib/underscore/underscore",
"backbone": "./lib/backbone/backbone",
"jquery-scrollstop": "./lib/jquery.scrollstop/index",
"queryparams": "./lib/backbone.queryparams/index",
"unveil": "./lib/unveil/jquery.unveil",
"definition-view": "./views/sidebar/definition-view",
"sub-head-view": "./views/header/sub-head-view",
"sidebar-module-view": "./views/sidebar/sidebar-module-view",
"toc-view": "./views/drawer/toc-view",
"sidebar-view": "./views/sidebar/sidebar-view",
"reg-view": "./views/main/reg-view",
"diff-view": "./views/main/diff-view",
"konami": "./lib/konami/index",
"analytics-handler": "./views/analytics-handler-view",
"header-view": "./views/header/header-view",
"section-footer-view": "./views/main/section-footer-view",
"drawer-view": "./views/drawer/drawer-view",
"history-view": "./views/drawer/history-view",
"search-view": "./views/drawer/search-view",
"sxs-list-view": "./views/sidebar/sxs-list-view",
"sidebar-list-view": "./views/sidebar/sidebar-list-view",
"sxs-view": "./views/breakaway/sxs-view",
"search-results-view": "./views/main/search-results-view",
"main-view": "./views/main/main-view",
"child-view": "./views/main/child-view",
"help-view": "./views/sidebar/help-view",
"breakaway-view": "./views/breakaway/breakaway-view",
"drawer-tabs-view": "./views/drawer/drawer-tabs-view",
"super-view": "./views/super-view",
"drawer-events": "./events/drawer-events",
"sidebar-events": "./events/sidebar-events",
"header-events": "./events/header-events",
"main-events": "./events/main-events",
"breakaway-events": "./events/breakaway-events",
"ga-events": "./events/ga-events",
"search-model": "./models/search-model",
"meta-model": "./models/meta-model",
"reg-model": "./models/reg-model",
"sxs-model": "./models/sxs-model",
"diff-model": "./models/diff-model",
"regs-router": "./router",
"regs-helpers": "./helpers",
"sidebar-model": "./models/sidebar-model"
}
, "shim":
{
"underscore": {
"deps": [
"jquery"
],
"exports": "_"
},
"backbone": {
"deps": [
"underscore",
"jquery"
],
"exports": "Backbone"
},
"konami": {
"exports": "Konami"
},
"jquery-scrollstop": {
"deps": ["jquery"]
},
"unveil": {
"deps": ["jquery"]
}
}
}
|
jeremiak/regulations-site
|
regulations/static/regulations/js/built/require.config.js
|
JavaScript
|
cc0-1.0
| 2,818
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2015 Photon Storm Ltd.
* @license {@link http://choosealicense.com/licenses/no-license/|No License}
*
* @description This example requires the Phaser Virtual Joystick Plugin to run.
* For more details please see http://phaser.io/shop/plugins/virtualjoystick
*/
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example');
var PhaserGame = function () {
this.sprite;
this.pad;
this.stick;
};
PhaserGame.prototype = {
init: function () {
this.game.renderer.renderSession.roundPixels = true;
this.physics.startSystem(Phaser.Physics.ARCADE);
},
preload: function () {
this.load.atlas('arcade', 'assets/virtualjoystick/skins/arcade-joystick.png', 'assets/virtualjoystick/skins/arcade-joystick.json');
this.load.image('ball', 'assets/virtualjoystick/beball1.png');
this.load.image('bg', 'assets/virtualjoystick/sky5.png');
},
create: function () {
this.add.image(0, 0, 'bg');
this.sprite = this.add.sprite(400, 200, 'ball');
this.physics.arcade.enable(this.sprite);
this.pad = this.game.plugins.add(Phaser.VirtualJoystick);
this.stick = this.pad.addStick(0, 0, 200, 'arcade');
this.stick.showOnTouch = true;
},
update: function () {
var maxSpeed = 400;
if (this.stick.isDown)
{
this.physics.arcade.velocityFromRotation(this.stick.rotation, this.stick.force * maxSpeed, this.sprite.body.velocity);
}
else
{
this.sprite.body.velocity.set(0);
}
}
};
game.state.add('Game', PhaserGame, true);
|
boniatillo-com/PhaserEditor
|
source/phasereditor/phasereditor.resources.phaser.examples/phaser-examples-master/examples/virtualjoystick/show on touch.js
|
JavaScript
|
epl-1.0
| 1,722
|
define(["CC"],
function(CC) {
if (UNIT_TEST) {
var uexALiBaiChuanCase = {
"init": function() {
uexALiBaiChuan.init(function(error, msg) {
if (!error) {
UNIT_TEST.assert(true);
} else {
UNIT_TEST.log('[init fail]' + msg);
UNIT_TEST.assert(false);
}
});
},
"login": function() {
uexALiBaiChuan.login(function(error, msg) {
if (!error) {
UNIT_TEST.assert(true);
} else {
UNIT_TEST.log('[login fail]' + msg);
UNIT_TEST.assert(false);
}
});
},
"getUserInfo ": function() {
var info = uexALiBaiChuan.getUserInfo();
if (info) {
UNIT_TEST.log('[user info]' + JSON.stringify(info));
UNIT_TEST.assert(true);
} else {
UNIT_TEST.assert(false);
}
},
"openMyCart": function() {
UNIT_TEST.log('[打开购物车后请手动关闭]');
setTimeout(function() {
uexALiBaiChuan.openMyCart();
CC.confirm("请确认购物车刚才是否打开?", function(ret) {
UNIT_TEST.assert(ret);
});
},
2000);
},
"openMyOrdersPage": function() {
UNIT_TEST.log('[打开订单列表后请手动关闭]');
setTimeout(function() {
uexALiBaiChuan.openMyOrdersPage();
CC.confirm("请确认订单列表刚才是否打开?", function(ret) {
UNIT_TEST.assert(ret);
});
},
2000);
},
"openItemDetailPageById": function() {
UNIT_TEST.log('[打开商品详情页后请手动关闭]');
setTimeout(function() {
var params = {
isvcode: "appcan",
itemid: "45535180986",
mmpid: "mm_175878368_0_0"
};
uexALiBaiChuan.openItemDetailPageById(JSON.stringify(params));
CC.confirm("请确认商品详情页刚才是否打开, 内容是否正确", function(ret) {
UNIT_TEST.assert(ret);
});
},
2000);
},
"openItemDetailPageByURL": function() {
UNIT_TEST.log('[打开商品详情页后请手动关闭]');
setTimeout(function() {
var params = {
url: "https://detail.tmall.com/item.htm?id=528887107325",
mmpid: "mm_175878368_0_0"
};
uexALiBaiChuan.openItemDetailPageByURL(JSON.stringify(params));
CC.confirm("请确认商品详情页刚才是否打开, 内容是否正确", function(ret) {
UNIT_TEST.assert(ret);
});
},
2000);
},
"logout": function() {
uexALiBaiChuan.logout(function(error, msg) {
if (!error) {
UNIT_TEST.assert(true);
} else {
UNIT_TEST.log('[logout fail]' + msg);
UNIT_TEST.assert(false);
}
});
}
};
UNIT_TEST.addCase("uexALiBaiChuan", uexALiBaiChuanCase);
}
});
|
android-plugin/uexGaodeNavi
|
assets/widget/case/js/uexALiBaiChuan.js
|
JavaScript
|
gpl-2.0
| 3,862
|
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Placholder English language file.
*/
FCKLang.LimeReplacementFieldsBtn = 'Insert/Edit LimeReplacementField' ;
FCKLang.LimeReplacementFieldsDlgTitle = 'LimeReplacementField Properties' ;
|
healthcommcore/lung_cancer_site
|
survey/admin/scripts/fckeditor.263/editor/plugins/LimeReplacementFields/lang/en.js
|
JavaScript
|
gpl-2.0
| 822
|
jQuery(document).ready(function($) {
$(".fland-tabs").tabs({ fx: { opacity: 'show' } });
$(".fland-toggle").each( function () {
if($(this).attr('data-id') == 'closed') {
$(this).accordion({ header: '.fland-toggle-title', collapsible: true, active: false });
} else {
$(this).accordion({ header: '.fland-toggle-title', collapsible: true});
}
});
});
|
alonecuzzo/23bit
|
wp-content/themes/timeline/shortcode/js/zilla-shortcodes-lib.js
|
JavaScript
|
gpl-2.0
| 371
|
import { browserHistory } from 'react-router';
import C from './constants';
const auth = {
login: (provider) => {
let authProvider = null;
switch (provider) {
case 'facebook':
authProvider = new firebase.auth.FacebookAuthProvider();
break;
case 'google':
authProvider = new firebase.auth.GoogleAuthProvider();
break;
default:
break;
}
if (window.location.protocol === 'http') {
return C.FIREBASE.auth().signInWithPopup(authProvider);
} else {
return C.FIREBASE.auth().signInWithRedirect(authProvider);
}
},
isLoggedIn: () => {
return C.FIREBASE.auth().currentUser;
},
checkAuth: (nextState, replace, cb) => {
if (!C.FIREBASE.auth().currentUser) {
replace({
pathname: '/',
state: { nextPathname: nextState.location.pathname }
});
}
cb();
}
};
export default auth;
|
project-bobon/bobonroastprofile
|
src/auth.js
|
JavaScript
|
gpl-2.0
| 921
|
if (!window._path) {
window._path = 'admin';
}
window.sites = [];
window.groupname = null;
if (window.menuData == undefined) {
jr.xhr.get(window._path + '?module=ajax&action=appinit', function (x) {
var ip, address, md, username;
eval(x);
window.menuData = md;
jr.json.bind(document, { userName: username });
});
//window.menuData = [];
}
if (window.menuHandler == undefined) {
window.menuHandler = null;
}
function showGate() {
var els = document.getElementsByTagName("DIV");
els[0].className = 'loading-gate';
els[1].className = 'loading-bar';
if (/MSIE\s*(5|6|7)\./.test(window.navigator.userAgent)) {
els[1].style.left = (document.documentElement.clientWidth - els[1].offsetWidth) / 2 + 'px';
els[1].style.top = (document.documentElement.clientHeight - els[1].offsetHeight) / 2 + 'px';
}
}
function cancelGate() {
var els = document.getElementsByTagName("DIV");
els[0].className = 'loading-gate hidden';
els[1].className = 'loading-bar hidden';
}
var FwMenu = {
ele: null,
menuTitles: [],
getByCls: function (className) {
return this.ele.getElementsByClassName ? this.ele.getElementsByClassName(className) : document.getElementsByClassName(className, this.ele);
},
init: function (data, menuHandler) {
//获取菜单元素
this.ele = document.getElementsByClassName('page-left-menu')[0];
//第一次加载
var md = data;
//处理菜单数据
if (menuHandler && menuHandler instanceof Function) {
var hdata = menuHandler(data);
if (hdata != undefined && hdata != null) {
md = hdata;
}
}
var menuEle = this.ele;
menuEle.innerHTML = '';
var html, linkText, url;
for (var i1 = 0; i1 < md.length; i1++) {
html = '';
for (var i2 = 0; i2 < md[i1].childs.length; i2++) {
if (md[i1].childs[i2].childs.length > 0) {
html += '<div class="group hidden"><div class="group-title" group="' + md[i1].id + '" style="cursor:pointer" title="点击展开操作菜单"><span>' + md[i1].childs[i2].text + '</span></div>';
html += '<div class="panel hidden"><ul id="fns_' + i2 + '">';
for (var i3 = 0; i3 < md[i1].childs[i2].childs.length; i3++) {
linkText = md[i1].childs[i2].childs[i3].text;
url = md[i1].childs[i2].childs[i3].uri;
// html += (i3 != 0 && i3 % 4 == 0 ? '<div class="clearfix"></div>' : '') +
html += '<li' + (i2 == 0 && i3 == 0 ? ' class="current"' : '') + '><a class="fn" style="cursor:pointer;" url="' + url + '"' +
//(md[i1].childs[i2].childs.length == 1 ? ' style="margin:0 ' + ((100 - linktext.length * 14) / 2) + 'px"' : '') +
'><span class="icon icon_' + i1 + '_' + i2 + '_' + i3 + '"></span>' + linkText + '</a></li>';
}
html += '</ul></div></div>';
}
}
menuEle.innerHTML += html;
}
//获取所有的标题菜单
this.menuTitles = this.getByCls('group-title');
var t = this;
jr.each(this.menuTitles, function (i, e) {
var groupName = e.getAttribute('group');
jr.event.add(e, 'click', (function (_t, _e) {
return function () {
_t.show(_e);
};
})(t, e));
//设置打开
jr.each(e.nextSibling.getElementsByTagName('LI'), function (i2, e2) {
jr.event.add(e2, 'click', (function (_this, _t, g) {
return function () {
_t.set(groupName, _this);
var a = _this.childNodes[0];
if (a.url != '') {
FwTab.show(a.innerHTML, a.getAttribute('url'));
}
};
})(e2, t, groupName));
});
});
},
//设置第几组显示
change: function (id) {
var menuTitles = this.menuTitles;
var groupName = id;
if (!groupName) {
if (menuTitles.length == 0) {
return;
} else {
groupName = menuTitles[0].getAttribute('group');
}
}
var isFirst = true;
var selectedLi = null; //已经选择的功能菜单
var firstPanel = null;
var titleGroups = [];
var _lis;
jr.each(menuTitles, function (i, e) {
if (e.getAttribute('group') != groupName) {
e.parentNode.className = 'group hidden';
} else {
titleGroups.push(e);
e.parentNode.className = 'group';
//第一个panel
if (firstPanel == null) {
firstPanel = e.nextSibling;
}
}
});
for (var i = 0; i < titleGroups.length; i++) {
_lis = titleGroups[i].nextSibling.getElementsByTagName('LI');
for (var j = 0; j < _lis.length; j++) {
if (_lis[j].className == 'current') {
selectedLi = _lis[j];
i = titleGroups.length + 1; //使其跳出循环
break;
}
}
}
if (selectedLi != null) {
selectedLi.parentNode.parentNode.className = 'panel';
} else if (firstPanel != null) {
firstPanel.className = 'panel';
}
},
//查看菜单
show: function (titleDiv) {
var groupName = titleDiv.getAttribute('group');
jr.each(this.menuTitles, function (i, e) {
if (e.getAttribute('group') == groupName) {
if (e != titleDiv) {
e.nextSibling.className = 'panel hidden';
} else {
e.nextSibling.className = 'panel';
}
}
});
},
set: function (groupName, ele) {
jr.each(this.menuTitles, function (i, e) {
if (e.getAttribute('group') == groupName) {
jr.each(e.nextSibling.getElementsByTagName('LI'), function (i, e2) {
e2.className = ele == e2 ? 'current' : '';
});
}
});
}
};
/* Tab管理 */
var FwTab = {
//框架集
frames: null,
tabs: null,
initialize: function () {
var framebox = jr.$('pageframes');
this.tabs = jr.$('pagetabs').getElementsByTagName('UL')[0];
var getByCls = function (cls) {
return (framebox.getElementsByClassName ? framebox.getElementsByClassName(cls) : document.getElementsByClassName(cls, framebox))[0];
};
this.frames = getByCls('frames');
},
pageBeforeLoad: function () {
this.showLoadBar();
},
pageLoad: function () {
this.hiddenLoadBar();
},
showLoadBar: function () { },
hiddenLoadBar: function () { },
show: function (text, url, closeable) {
var _tabs = this.tabs.getElementsByTagName('LI');
var _indent;
var _exits = false;
var _cur_indents = url;
var _li = null;
jr.each(_tabs, function (i, obj) {
_indent = obj.getAttribute('indent');
if (_indent == _cur_indents) {
_exits = true;
obj.className = 'current';
_li = obj;
}
});
if (!_exits) {
this.pageBeforeLoad();
//添加框架
var frameDiv = document.createElement('DIV');
var frame;
try {
//解决ie8下有边框的问题
frame = document.createElement('<IFRAME frameborder="0">');
} catch (ex) {
frame = document.createElement('IFRAME');
}
frame.src = url;
frameDiv.appendChild(frame);
this.frames.appendChild(frameDiv);
var _loadCall = (function (t) {
return function () {
t.pageLoad.apply(t);
};
})(this);
frame.frameBorder = '0';
frame.setAttribute('frameBorder', '0', 0);
frame.setAttribute('indent', _cur_indents);
frame.setAttribute('id', 'ifr_' + _cur_indents);
jr.event.add(frame, 'load', _loadCall);
//添加选项卡
_li = document.createElement('LI');
_li.onmouseout = (function (t) {
return function () {
if (t.className != 'current') t.className = '';
};
})(_li);
_li.onmouseover = (function (t) {
return function () {
if (t.className != 'current') t.className = 'hover';
};
})(_li);
_li.setAttribute('indent', _cur_indents);
_li.innerHTML = '<span class="txt"><span class="tab-title" onclick="FwTab.set(this)">' + text + '</span>'
+ (closeable == false ? '' : '<span class="tab-close" title="关闭选项卡" onclick="FwTab.close(this);">x</span>')
+ '</span><span class="rgt"></span>';
this.tabs.appendChild(_li);
}
//触发事件,切换IFRAME
this.set(_li, true);
},
set: function (t, isOpen) {
//如果不是刚打开的tab,则关闭加载提示
if (!isOpen) {
this.hiddenLoadBar();
}
var li = t.nodeName != 'LI' ? t.parentNode.parentNode : t;
var _frames = this.frames.getElementsByTagName('DIV');
var _lis = this.tabs.getElementsByTagName('LI');
jr.each(_lis, function (i, obj) {
if (obj == li) {
obj.className = 'current';
_frames[i].className = 'current';
_frames[i].style.height = '100%';
} else {
obj.className = '';
_frames[i].className = '';
_frames[i].style.height = '0px';
}
});
},
//关闭tab,如果不指定关闭按钮,则关闭当前页
close: function (t) {
var closeIndex = -1;
var isActived = false;
var closeLi = null;
if (t) {
//传递指定的tab进行关闭
if (t.nodeName == 'SPAN') {
var list = jr.dom.getsByClass(this.tabs, 'tab-close');
var noCloseBtnLen = this.tabs.getElementsByTagName('LI').length - list.length;
for (var i = 0; i < list.length; i++) {
if (list[i] == t) {
closeIndex = i + noCloseBtnLen;
closeLi = list[i].parentNode.parentNode;
break;
}
}
}
//根据标题来关闭
else if (typeof (t) == 'string') {
var list = jr.dom.getsByClass(this.tabs, 'tab-title');
for (var i = 0; i < list.length; i++) {
if (t == list[i].innerHTML.replace(/<[^>]+>/g, '')) {
closeIndex = i;
closeLi = list[i].parentNode.parentNode;
break;
}
}
}
} else {
//关闭当前选中的tab
var _lis = this.tabs.getElementsByTagName('LI');
for (var i = 0; i < _lis.length; i++) {
if (_lis[i].className == 'current') {
closeIndex = i;
closeLi = _lis[i];
break;
}
}
}
//判断是否关闭当前选中的tab
if (closeLi) {
isActived = closeLi.className == 'current';
}
if (closeIndex > 0) {
var _lis = this.tabs.getElementsByTagName('LI');
var _ifrs = this.frames.getElementsByTagName('DIV');
var ifr = _ifrs[closeIndex].childNodes[0];
if (ifr.nodeName == 'IFRAME') {
ifr.src = '';
ifr = null;
}
this.tabs.removeChild(_lis[closeIndex]);
this.frames.removeChild(_ifrs[closeIndex]);
//如果关闭当前激活的tab,则显示其他的tab和iframe
if (isActived) {
this.hiddenLoadBar(); /* 避免当打开就刷新时仍然加载问题 */
if (closeIndex >= _lis.length) {
closeIndex = _lis.length - 1;
}
_lis[closeIndex].className = 'current';
if (_ifrs[closeIndex]) {
_ifrs[closeIndex].className = 'current';
_ifrs[closeIndex].style.height = '100%';
}
}
}
},
//获取Tab Iframe的框架,如果不包括则返回null
getWindow: function (t) {
if (typeof (t) == 'string') {
var frameIndex = -1;
var list = jr.dom.getsByClass(this.tabs, 'tab-title');
for (var i = 0; i < list.length; i++) {
if (t == list[i].innerHTML.replace(/<[^>]+>/g, '')) {
frameIndex = i;
break;
}
}
//没有框架或超出数量
if (frameIndex == -1) return null;
var frameDivs = this.frames.getElementsByTagName('DIV');
if (frameIndex >= frameDivs.length) return null;
//获取Iframe
var iframes = frameDivs[frameIndex].getElementsByTagName('IFRAME');
//不包含iframe
if (iframes.length == 0) return null;
return iframes[0].contentWindow;
}
return null;
}
};
//加载app
function loadApps() {
var ele;
jr.each(document.getElementsByTagName('H2'), function (i, e) {
if (e.innerHTML == 'APPS') {
ele = e.parentNode.getElementsByTagName('DIV')[0];
}
});
if (ele) {
ele.id = 'ribbon-apps';
jr.load(ele, window._path + '?module=plugin&action=miniapps&ajax=1');
}
}
window.M = {
dialog: function (id, title, url, isAjax, width, height, closeCall) {
newDialog(id, title, url, isAjax, width, height, closeCall);
},
alert: function (html, func) {
jr.tipbox.show(html, false, 100, 2000, 'up');
if (func) {
setTimeout(func, 1000);
}
},
msgtip: function (arg, func) {
jr.tipbox.show(arg.html, false, 100, arg.autoClose ? 2000 : -1, 'up');
if (func) {
setTimeout(func, 1000);
}
},
tip: function (msg, func) {
this.msgtip({ html: msg, autoClose: true }, func);
},
loadCatTree: function () {
_loadCategoryTree();
},
clearCache: function (t) {
window.M.msgtip({ html: '清除中....' });
jr.xhr.post(window._path, 'module=ajax&action=clearcache', function (x) {
window.M.msgtip({ html: '缓存清除完成!', autoClose: true });
jr.xhr.get('/');
}, function (x) { });
},
addFavorite: function () {
var url = location.href;
var title = document.title;
try {
window.external.addFavorite(url, title);
}
catch (e) {
try {
window.sidebar.addPanel(title, url, "");
}
catch (e) {
alert("浏览器不支持,请手动添加!");
}
}
},
setFullScreen: function (event) {
//var leftWidth = $(e_SD).offsetWidth;
//if (leftWidth >= window.M.epix.leftWidth) {
if (!$(e_SD).parentNode.style || $(e_SD).parentNode.style.display != 'none') {
//全屏
$(e_HD).style.height = '0px';
$(e_SD).style.width = '0px';
$(e_FT).style.height = '0px';
$(e_HD).style.overflow = 'hidden';
$(e_SD).parentNode.style.cssText += 'display:none';
} else {
//取消全屏
$(e_HD).style.overflow = '';
$(e_HD).style.height = (window.M.epix.topHeight - 5) + 'px';
$(e_SD).style.width = (window.M.epix.leftWidth - 1) + 'px';
$(e_FT).style.height = (window.M.epix.footHeight - 1) + 'px';
$(e_SD).parentNode.style.display = '';
}
window.onresize();
}
};
var mainDiv = document.getElementsByClassName('page-main')[0];
function getDivByCls(cls, ele) {
var e = ele || mainDiv;
return (e.getElementsByClassName ?
e.getElementsByClassName(cls) :
document.getElementsByClassName(cls, e))[0];
}
//左栏div
var leftDiv = getDivByCls('page-main-left');
//右栏div
var rightDiv = getDivByCls('page-main-right');
//框架div
var frameDiv = getDivByCls('page-frames');
//分割div
var splitDiv = getDivByCls('page-main-split');
//框架遮盖层
var frameShadowDiv = getDivByCls('page-frame-shadow');
//用户操作栏
var userDiv = getDivByCls('page-user', document.body);
//重置窗口尺寸
function _resizeWin() {
var height = document.documentElement.clientHeight;
var width = jr.screen.width();
mainDiv.style.height = (height - mainDiv.offsetTop) + 'px';
frameDiv.style.height = (mainDiv.offsetHeight - frameDiv.offsetTop) + 'px';
//设置右栏的宽度
rightDiv.style.width = (width - leftDiv.offsetWidth - splitDiv.offsetWidth + 1) + 'px';
}
jr.event.add(window, 'resize', _resizeWin);
//设置按键
window.onload = function () {
document.onkeydown = function (event) {
var e = window.event || event;
//按键ALT+F11,启用全屏
if (e.altKey && e.keyCode == 122) {
window.M.setFullScreen();
e.returnvalue = false;
return false;
} else if (e.ctrlKey && e.keyCode === 83) {
return jr.event.preventDefault(event);
} else if (e.keyCode === 122) {
window.M.setFullScreen();
e.returnvalue = false;
return false;
} else if (!e.ctrlKey && e.keyCode == 116) {
var ifr = null;
var ifrs = document.getElementsByTagName('IFRAME');
for (var i = 0; i < ifrs.length; i++) {
if (ifrs[i].className == 'current') {
ifr = ifrs[i];
break;
}
}
if (ifr != null) {
var src = ifr.src;
ifr.src = '';
ifr.src = src;
}
e.returnvalue = false;
return false;
}
};
//FwMenu.init(window.menuData, window.menuHandler);
//FwMenu.change();
_resizeWin();
FwTab.initialize();
//添加左右栏改变大小功能
new dragObject(splitDiv, window).custom(null, 'w-resize', (function (ld, rd, sd, minWidth, maxWidth) {
return function (event) {
//显示遮罩层以支持drag
frameShadowDiv.className = frameShadowDiv.className.replace(' hidden', '');
var e = event || window.event;
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
if (e.preventDefault) e.preventDefault(); //这两句便是解决firefox拖动问题的.
var mx = e.clientX;
if (mx > minWidth && mx < maxWidth) {
sd.style.left = mx + 'px';
ld.style.width = mx + 'px';
ld.style.marginRight = -mx + 'px';
rd.style.marginLeft = (mx + 5) + 'px';
_resizeWin();
}
};
})(leftDiv,
rightDiv,
splitDiv,
splitDiv.getAttribute('min'),
splitDiv.getAttribute('max')),
function () {
frameShadowDiv.className += ' hidden';
});
};
//=========================== 辅助方法 ===============================//
function _loadCategoryTree() {
var treeTitle = '站点栏目';
var treeGroupName = 'content';
var menuTitles = FwMenu.menuTitles;
var e = null;
for (var i = 0; i < menuTitles.length; i++) {
e = menuTitles[i];
var groupName = e.getAttribute('group');
if (groupName == treeGroupName) {
if (e.innerHTML.replace(/<[^>]+>/g, '') == treeTitle) {
jr.load(e.nextSibling, window._path + '?module=category&action=tree&for=archives&siteid=&ajax=1&rd=' + Math.random() + '#noload', function (result) { });
break;
}
}
}
}
|
jsix/cms
|
src/core/JR.Cms.Web/Resource/WebManager/resouces/images/ui.component.source.js
|
JavaScript
|
gpl-2.0
| 20,786
|
var Aether = Aether || {};
/***
* Hud Object
*/
(function(){
var Hud = function(){
var _this = this;
_this.canvas = document.createElement("canvas");
_this.canvas.width = 200;
_this.canvas.height = 200;
_this.ctx = _this.canvas.getContext("2d");
_this.ctx.font = "9px Helvetica";
_this.ctx.fillStyle = "white";
_this.refresh = function(){
_this.ctx.clearRect ( 0 , 0 , _this.canvas.width , _this.canvas.height );
_this.ctx.fillText("HP: "+Aether.hero.stats.hp+" / "+Aether.hero.stats.maxHp,10,15);
//_this.ctx.fillText("HP: "+Aether.hero.stats.mp+" / "+Aether.hero.stats.maxMp,10,15);
_this.ctx.fillText("EP: "+Aether.hero.stats.ep+" / "+Aether.hero.stats.maxEp,10,26);
var tempCanvas = Aether.utility.outlineSprite({canvas: _this.canvas, color: "rgba(0,0,0,.7)", stroke:1});
_this.ctx.drawImage(tempCanvas,0,0);
};
};
Aether.hud = new Hud();
})();
|
asyndesis/harpies
|
public/js/hud.js
|
JavaScript
|
gpl-2.0
| 930
|
/*
Copyright (c) 2004-2008, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.lang.functional.reversed"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.lang.functional.reversed"] = true;
dojo.provide("dojox.lang.functional.reversed");
dojo.require("dojox.lang.functional.lambda");
// This module adds high-level functions and related constructs:
// - reversed versions of array-processing functions similar to standard JS functions
// Notes:
// - this module provides reversed versions of standard array-processing functions:
// forEachRev, mapRev, filterRev
// Defined methods:
// - take any valid lambda argument as the functional argument
// - operate on dense arrays
// - take a string as the array argument
(function(){
var d = dojo, df = dojox.lang.functional;
d.mixin(df, {
// JS 1.6 standard array functions, which can take a lambda as a parameter.
// Consider using dojo._base.array functions, if you don't need the lambda support.
filterRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: creates a new array with all elements that pass the test
// implemented by the provided function.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var t = [], v;
for(var i = a.length - 1; i >= 0; --i){
v = a[i];
if(f.call(o, v, i, a)){ t.push(v); }
}
return t; // Array
},
forEachRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: executes a provided function once per array element.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
for(var i = a.length - 1; i >= 0; f.call(o, a[i], i, a), --i);
},
mapRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: creates a new array with the results of calling
// a provided function on every element in this array.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
var n = a.length, t = new Array(n);
for(var i = n - 1, j = 0; i >= 0; t[j++] = f.call(o, a[i], i, a), --i);
return t; // Array
},
everyRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: tests whether all elements in the array pass the test
// implemented by the provided function.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
for(var i = a.length - 1; i >= 0; --i){
if(!f.call(o, a[i], i, a)){
return false; // Boolean
}
}
return true; // Boolean
},
someRev: function(/*Array|String*/ a, /*Function|String|Array*/ f, /*Object?*/ o){
// summary: tests whether some element in the array passes the test
// implemented by the provided function.
if(typeof a == "string"){ a = a.split(""); }
o = o || d.global; f = df.lambda(f);
for(var i = a.length - 1; i >= 0; --i){
if(f.call(o, a[i], i, a)){
return true; // Boolean
}
}
return false; // Boolean
}
});
})();
}
|
fedora-infra/packagedb
|
pkgdb/static/js/dojox/lang/functional/reversed.js
|
JavaScript
|
gpl-2.0
| 3,243
|
Drupal.TBMegaMenu = Drupal.TBMegaMenu || {};
(function ($, Drupal, drupalSettings) {
"use strict";
Drupal.TBMegaMenu.oldWindowWidth = 0;
Drupal.TBMegaMenu.displayedMenuMobile = false;
Drupal.TBMegaMenu.supportedScreens = [980];
Drupal.TBMegaMenu.menuResponsive = function () {
var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
var navCollapse = $('.tb-megamenu').children('.nav-collapse');
if (windowWidth < Drupal.TBMegaMenu.supportedScreens[0]) {
navCollapse.addClass('collapse');
if (Drupal.TBMegaMenu.displayedMenuMobile) {
var left = 0-$('.tb-megamenu').children('.btn-navbar').offset().left;
navCollapse.css('left',left+'px');
navCollapse.css({height: 'auto', overflow: 'visible'});
} else {
navCollapse.css({height: 0, overflow: 'hidden'});
}
} else {
// If width of window is greater than 980 (supported screen).
navCollapse.removeClass('collapse');
if (navCollapse.height() <= 0) {
navCollapse.css({height: 'auto', overflow: 'visible'});
}
}
};
Drupal.behaviors.tbMegaMenuAction = {
attach: function (context, settings) {
var button = $(context).find('.tb-megamenu-button').once('tb-megamenu-action');
$(button).click(function () {
if (parseInt($(this).parent().children('.nav-collapse').height())) {
$(this).parent().children('.nav-collapse').css({height: 0, overflow: 'hidden'});
Drupal.TBMegaMenu.displayedMenuMobile = false;
}
else {
$(this).parent().children('.nav-collapse').css({height: 'auto', overflow: 'visible'});
Drupal.TBMegaMenu.displayedMenuMobile = true;
Drupal.TBMegaMenu.menuResponsive();
}
});
var isTouch = 'ontouchstart' in window && !(/hp-tablet/gi).test(navigator.appVersion);
if (!isTouch) {
$(document).ready(function ($) {
var mm_duration = 0;
$('.tb-megamenu').each(function () {
if ($(this).data('duration')) {
mm_duration = $(this).data('duration');
}
});
var mm_timeout = mm_duration ? 100 + mm_duration : 500;
$('.nav > li, li.mega').hover(function (event) {
var $this = $(this);
if ($this.hasClass('mega')) {
$this.addClass('animating');
clearTimeout($this.data('animatingTimeout'));
$this.data('animatingTimeout', setTimeout(function () {
$this.removeClass('animating');
}, mm_timeout));
}
clearTimeout($this.data('hoverTimeout'));
$this.data('hoverTimeout', setTimeout(function () {
$this.addClass('open');
}, 100));
},
function (event) {
var $this = $(this);
if ($this.hasClass('mega')) {
$this.addClass('animating');
clearTimeout($this.data('animatingTimeout'));
$this.data('animatingTimeout', setTimeout(function () {
$this.removeClass('animating');
}, mm_timeout));
}
clearTimeout($this.data('hoverTimeout'));
$this.data('hoverTimeout', setTimeout(function () {
$this.removeClass('open');
}, 100));
});
});
}
$(window).resize(function () {
var windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
if (windowWidth != Drupal.TBMegaMenu.oldWindowWidth) {
Drupal.TBMegaMenu.oldWindowWidth = windowWidth;
Drupal.TBMegaMenu.menuResponsive();
}
});
}
};
})(jQuery, Drupal, drupalSettings);
|
padmanabhan-developer/EstarProd
|
modules/tb_megamenu/js/tb-megamenu-frontend.js
|
JavaScript
|
gpl-2.0
| 3,768
|
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
/**
* Module: TYPO3/CMS/Backend/LayoutModule/DragDrop
* this JS code does the drag+drop logic for the Layout module (Web => Page)
* based on jQuery UI
*/
define(['jquery', 'jquery-ui/droppable'], function ($) {
'use strict';
/**
*
* @type {{contentIdentifier: string, dragIdentifier: string, dragHeaderIdentifier: string, dropZoneIdentifier: string, columnIdentifier: string, validDropZoneClass: string, dropPossibleHoverClass: string, addContentIdentifier: string, originalStyles: string}}
* @exports TYPO3/CMS/Backend/LayoutModule/DragDrop
*/
var DragDrop = {
contentIdentifier: '.t3js-page-ce',
dragIdentifier: '.t3-page-ce-dragitem',
dragHeaderIdentifier: '.t3js-page-ce-draghandle',
dropZoneIdentifier: '.t3js-page-ce-dropzone-available',
columnIdentifier: '.t3js-page-column',
validDropZoneClass: 'active',
dropPossibleHoverClass: 't3-page-ce-dropzone-possible',
addContentIdentifier: '.t3js-page-new-ce',
clone: true,
originalStyles: ''
};
/**
* initializes Drag+Drop for all content elements on the page
*/
DragDrop.initialize = function () {
$(DragDrop.contentIdentifier).draggable({
handle: this.dragHeaderIdentifier,
scope: 'tt_content',
cursor: 'move',
distance: 20,
addClasses: 'active-drag',
revert: 'invalid',
zIndex: 100,
start: function (evt, ui) {
DragDrop.onDragStart($(this));
},
stop: function (evt, ui) {
DragDrop.onDragStop($(this));
}
});
$(DragDrop.dropZoneIdentifier).droppable({
accept: this.contentIdentifier,
scope: 'tt_content',
tolerance: 'pointer',
over: function (evt, ui) {
DragDrop.onDropHoverOver($(ui.draggable), $(this));
},
out: function (evt, ui) {
DragDrop.onDropHoverOut($(ui.draggable), $(this));
},
drop: function (evt, ui) {
DragDrop.onDrop($(ui.draggable), $(this), evt);
}
});
};
/**
* called when a draggable is selected to be moved
* @param $element a jQuery object for the draggable
* @private
*/
DragDrop.onDragStart = function ($element) {
// Add css class for the drag shadow
DragDrop.originalStyles = $element.get(0).style.cssText;
$element.children(DragDrop.dragIdentifier).addClass('dragitem-shadow');
$element.append('<div class="ui-draggable-copy-message">' + TYPO3.lang['dragdrop.copy.message'] + '</div>');
// Hide create new element button
$element.children(DragDrop.dropZoneIdentifier).addClass('drag-start');
$element.closest(DragDrop.columnIdentifier).removeClass('active');
$element.parents(DragDrop.columnHolderIdentifier).find(DragDrop.addContentIdentifier).hide();
$element.find(DragDrop.dropZoneIdentifier).hide();
// make the drop zones visible
$(DragDrop.dropZoneIdentifier).each(function () {
if (
$(this).parent().find('.icon-actions-document-new').length
) {
$(this).addClass(DragDrop.validDropZoneClass);
} else {
$(this).closest(DragDrop.contentIdentifier).find('> ' + DragDrop.addContentIdentifier + ', > > ' + DragDrop.addContentIdentifier).show();
}
});
};
/**
* called when a draggable is released
* @param $element a jQuery object for the draggable
* @private
*/
DragDrop.onDragStop = function ($element) {
// Remove css class for the drag shadow
$element.children(DragDrop.dragIdentifier).removeClass('dragitem-shadow');
// Show create new element button
$element.children(DragDrop.dropZoneIdentifier).removeClass('drag-start');
$element.closest(DragDrop.columnIdentifier).addClass('active');
$element.parents(DragDrop.columnHolderIdentifier).find(DragDrop.addContentIdentifier).show();
$element.find(DragDrop.dropZoneIdentifier).show();
$element.find('.ui-draggable-copy-message').remove();
// Reset inline style
$element.get(0).style.cssText = DragDrop.originalStyles;
$(DragDrop.dropZoneIdentifier + '.' + DragDrop.validDropZoneClass).removeClass(DragDrop.validDropZoneClass);
};
/**
* adds CSS classes when hovering over a dropzone
* @param $draggableElement
* @param $droppableElement
* @private
*/
DragDrop.onDropHoverOver = function ($draggableElement, $droppableElement) {
if ($droppableElement.hasClass(DragDrop.validDropZoneClass)) {
$droppableElement.addClass(DragDrop.dropPossibleHoverClass);
}
};
/**
* removes the CSS classes after hovering out of a dropzone again
* @param $draggableElement
* @param $droppableElement
* @private
*/
DragDrop.onDropHoverOut = function ($draggableElement, $droppableElement) {
$droppableElement.removeClass(DragDrop.dropPossibleHoverClass);
};
/**
* this method does the whole logic when a draggable is dropped on to a dropzone
* sending out the request and afterwards move the HTML element in the right place.
*
* @param $draggableElement
* @param $droppableElement
* @param {Event} evt the event
* @private
*/
DragDrop.onDrop = function ($draggableElement, $droppableElement, evt) {
var newColumn = DragDrop.getColumnPositionForElement($droppableElement);
$droppableElement.removeClass(DragDrop.dropPossibleHoverClass);
var $pasteAction = typeof $draggableElement === 'number';
// send an AJAX requst via the AjaxDataHandler
var contentElementUid = $pasteAction ? $draggableElement : parseInt($draggableElement.data('uid'));
if (contentElementUid > 0) {
var parameters = {};
// add the information about a possible column position change
var targetFound = $droppableElement.closest(DragDrop.contentIdentifier).data('uid');
// the item was moved to the top of the colPos, so the page ID is used here
var targetPid = 0;
if (typeof targetFound === 'undefined') {
// the actual page is needed
targetPid = $('[data-page]').first().data('page');
} else {
// the negative value of the content element after where it should be moved
targetPid = 0 - parseInt(targetFound);
}
var language = parseInt($droppableElement.closest('[data-language-uid]').data('language-uid'));
var colPos = 0;
if (targetPid !== 0) {
colPos = newColumn;
}
parameters['cmd'] = {tt_content: {}};
parameters['data'] = {tt_content: {}};
var copyAction = (evt && evt.originalEvent.ctrlKey || $droppableElement.hasClass('t3js-paste-copy'));
if (copyAction) {
parameters['cmd']['tt_content'][contentElementUid] = {
copy: {
action: 'paste',
target: targetPid,
update: {
colPos: colPos,
sys_language_uid: language
}
}
};
DragDrop.ajaxAction($droppableElement, $draggableElement, parameters, copyAction, $pasteAction);
} else {
parameters['data']['tt_content'][contentElementUid] = {
colPos: colPos,
sys_language_uid: language
};
if ($pasteAction) {
parameters = {
CB: {
paste: 'tt_content|' + targetPid,
update: {
colPos: colPos,
sys_language_uid: language
}
}
};
} else {
parameters['cmd']['tt_content'][contentElementUid] = {move: targetPid};
}
// fire the request, and show a message if it has failed
DragDrop.ajaxAction($droppableElement, $draggableElement, parameters, copyAction, $pasteAction);
}
}
};
/**
* this method does the actual AJAX request for both, the move and the copy action.
*
* @param $droppableElement
* @param $draggableElement
* @param parameters
* @param $copyAction
* @param $pasteAction
* @private
*/
DragDrop.ajaxAction = function ($droppableElement, $draggableElement, parameters, $copyAction, $pasteAction) {
require(['TYPO3/CMS/Backend/AjaxDataHandler'], function (DataHandler) {
DataHandler.process(parameters).done(function (result) {
if (!result.hasErrors) {
// insert draggable on the new position
if (!$pasteAction) {
if (!$droppableElement.parent().hasClass(DragDrop.contentIdentifier.substring(1))) {
$draggableElement.detach().css({top: 0, left: 0})
.insertAfter($droppableElement.closest(DragDrop.dropZoneIdentifier));
} else {
$draggableElement.detach().css({top: 0, left: 0})
.insertAfter($droppableElement.closest(DragDrop.contentIdentifier));
}
}
if ($('.t3js-page-lang-column').length || $copyAction || $pasteAction) {
self.location.reload(true);
}
}
});
});
};
/**
* returns the next "upper" container colPos parameter inside the code
* @param $element
* @return int|null the colPos
*/
DragDrop.getColumnPositionForElement = function ($element) {
var $columnContainer = $element.closest('[data-colpos]');
if ($columnContainer.length && $columnContainer.data('colpos') !== 'undefined') {
return $columnContainer.data('colpos');
} else {
return false;
}
};
$(DragDrop.initialize);
return DragDrop;
});
|
ksjogo/TYPO3.CMS
|
typo3/sysext/backend/Resources/Public/JavaScript/LayoutModule/DragDrop.js
|
JavaScript
|
gpl-2.0
| 9,148
|
(function($, v) {
var timeout;
$(document).ready(function() {
$('#settings-button').click(function() {
$('#settings-form').submit();
});
function updateChart() {
clearTimeout(timeout);
timeout = setTimeout(function() {
var settings = $('#settings-form').serializeObject();
delete settings['width'];
delete settings['height'];
v.charts.canvas.settings = settings;
v.render();
}, 1000);
}
$('.control-text').change(updateChart).keyup(updateChart);
$('.control-select, .control-checkbox').change(updateChart);
$('.color-picker-hex').wpColorPicker({
change: updateChart,
clear: updateChart
});
});
})(jQuery, visualizer);
(function($) {
$.fn.serializeObject = function() {
var self = this,
json = {},
push_counters = {},
patterns = {
"validate": /^[a-zA-Z][a-zA-Z0-9_]*(?:\[(?:\d*|[a-zA-Z0-9_]+)\])*$/,
"key": /[a-zA-Z0-9_]+|(?=\[\])/g,
"push": /^$/,
"fixed": /^\d+$/,
"named": /^[a-zA-Z0-9_]+$/
};
this.build = function(base, key, value) {
base[key] = value;
return base;
};
this.push_counter = function(key) {
if (push_counters[key] === undefined) {
push_counters[key] = 0;
}
return push_counters[key]++;
};
$.each($(this).serializeArray(), function() {
// skip invalid keys
if (!patterns.validate.test(this.name)) {
return;
}
var k,
keys = this.name.match(patterns.key),
merge = this.value,
reverse_key = this.name;
while ((k = keys.pop()) !== undefined) {
// adjust reverse_key
reverse_key = reverse_key.replace(new RegExp("\\[" + k + "\\]$"), '');
if (k.match(patterns.push)) {
// push
merge = self.build([], self.push_counter(reverse_key), merge);
} else if (k.match(patterns.fixed)) {
// fixed
merge = self.build([], k, merge);
} else if (k.match(patterns.named)) {
// named
merge = self.build({}, k, merge);
}
}
json = $.extend(true, json, merge);
});
return json;
};
})(jQuery);
|
hle25-micros/aet-tankers
|
wp-content/plugins/visualizer/js/preview.js
|
JavaScript
|
gpl-2.0
| 2,020
|
var api = angular.module('api', []);
api.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('[[|').endSymbol('|]]');
})
// wikipedia controller
api.controller('WikipediaController', ['$scope', '$http',
function($scope, $http) {
$scope.wikipediaUrl = 'https://el.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=';
$scope.retrieve = function(query) {
$scope.wikipediaUrl = $scope.wikipediaUrl + query + '&callback=JSON_CALLBACK';
$http.jsonp($scope.wikipediaUrl).
success(function(data) {
// var extract = data['query']['pages'][0]['extract'];
$scope.introduction = data['query']['pages'][Object.keys(data['query']['pages'])[0]]['extract'];
});
}
}
]);
// google streetview controller
//instagram controller
api.controller('InstagramController', ['$scope', '$http',
function($scope) {
$scope.instagramURL = 'https://api.instagram.com/v1/tags/';
$scope.clientID = '6bd0d43dcbdb41f0bb635f04b781f501';
$scope.clientSecret = '762e179dc9b64fdd906bed99d872e7e3';
$scope.retrieve = function(query) {
$scope.instagramURL = $scope.instagramURL + query + '/media/recent?client_id=' + clientID;
$http.get($scope.instagramURL).
success(function(data) {
});
}
}
]);
api.controller('PhotoController', ['$scope', '$http',
function($scope, $http) {
$scope.retrieve = function(lat, lng) {
var url = 'https://api.instagram.com/v1/media/search?lat=' + lat + '&lng=' + lng + '&access_token=2227972880.6bd0d43.17e7232c04b34d2c999abd5201733e7a';
$http.jsonp(url + '&callback=JSON_CALLBACK').success(function(data) {
$scope.photos = data;
console.log(data);
});
}
}
]);
// foursquare controller
api.controller('FoursquareController', ['$scope', '$http',
function($scope, $http) {
$scope.foursquareClientId = 'SOMQPXPTYGH5D45CIKDYXOTZSHPY1TMZRLYFXPCCXMAELAOH';
$scope.foursquareClientSecret = '3H42G4VRXP5IQK1OOR5SCAKEGAQ1CEEDAAV3H4RC0O5WJHKV';
$scope.foursquareUrl = 'https://api.foursquare.com/v2/venues/search?near=';
$scope.retrieve = function(query) {
$scope.foursquareUrl = $scope.foursquareUrl + query + '&client_id=' + $scope.foursquareClientId + '&client_secret=' + $scope.foursquareClientSecret + '&v=20151710&limit=10';
$http.get($scope.foursquareUrl).
success(function(data) {
$scope.foursquareData = data;
});
}
$scope.imgWidth = 318;
$scope.imgHeight = 220;
$scope.streetviewURL = 'https://maps.googleapis.com/maps/api/streetview?';
$scope.streetviewKey = 'AIzaSyDtm7_hcQI0uEXsbrhF44Gon4TZP4LwjSM';
$scope.getStreet = function(latitude, longitude) {
var streetviewURL = $scope.streetviewURL + 'size=' + $scope.imgWidth + 'x' + $scope.imgHeight + '&location=' + latitude + ',' + longitude + '&heading=151.78&pitch=-0.76' + '&key=' + $scope.streetviewKey;
return streetviewURL;
}
}
]);
// image url construction (google streetview and foursquare combined!!!)
api.controller('StreetViewImageController', ['$scope',
function($scope) {
$scope.imgWidth = 318;
$scope.imgHeight = 220;
$scope.streetviewURL = 'https://maps.googleapis.com/maps/api/streetview?';
$scope.streetviewKey = 'AIzaSyDtm7_hcQI0uEXsbrhF44Gon4TZP4LwjSM';
$scope.retrieve = function(latitude, longitude) {
$scope.streetviewURL = $scope.streetviewURL + 'size=' + scope.imgWidth + 'x' + $scope.imgHeight + '&location=' + latitude + ',' + longitude + '&heading=151.78&pitch=-0.76' + '&key=' + $scope.streetviewKey;
return $scope.streetviewURL;
}
}
]);
// panoramio controller
api.controller('PanoramioController', ['$scope', '$http',
function($scope, $http) {
$scope.panoramioURL = 'http://www.panoramio.com/map/get_panoramas.php?order=popularity&set=full&from=0&to=30&'
$scope.retrieve = function(minLng, minLat, maxLng, maxLat) {
//minx, miny, maxx, maxy define the area to show photos from (minimum longitude, latitude, maximum longitude and latitude, respectively).
$scope.panoramioURL = $scope.panoramioURL + 'minx=' + minLng + '&miny=' + minLat + '&maxx=' + maxLng + '&maxy=' + maxLat + '&size=medium';
$scope.panoramioImageURLS = [];
$http.jsonp($scope.panoramioURL + '&callback=JSON_CALLBACK').
success(function(data) {
var photos = data['photos'];
var i = Math.floor((Math.random() * 30) + 1);
$scope.image = photos[i];
});
}
}
]);
|
crowdhackathon-tourism/holidays-on-village
|
public/assets/js/controllers/api.js
|
JavaScript
|
gpl-2.0
| 4,908
|
/***************************************************************
¶à¼¶¹ØÁª²Ëµ¥ http://wanghui.name
***************************************************************/
//²Ëµ¥ÏÂÀ¿òÃû³Æ
var arrSel = ['S1','S2','S3','S4','S5'];
//**********¶¨ÒåÊý×鿪ʼ*****************************
//²Ëµ¥Ïî¸ñʽ£ºÃû³Æ£¬Öµ£¬[×ÓÏî(ûÓÐ×ÓÏîΪnull)]
// alert(menu);
//**********¶¨ÒåÊý×é½áÊø*****************************
//**********º¯ Êý***********************************
function multiLevelMenu(level)
{
//ͨ¹ýÊý×éϱê(level)µÃµ½Ëù¶ÔÓ¦µÄÏÂÀ¿ò
var obj;
var subObj;
var currMenu;
var parentMenu;
obj=document.getElementById(arrSel[level]);
if(obj)
{
//ͨ¹ýobj.selectedIndex ÕÒµ½ÆäÓ¦¸ÃÏÔʾµÄÏîÔÚmenuÊý×éÖеÄϱêÒýÓÃλÖÃ
var currMenu_varName = "menu";
var parentMenu_value_varName = "menu";
var parentMenu_text_varName = "menu";
for(i=0;i<level;i++)
{
//Èç¹ûselectedIndex ÊÇn,¾ÍÖ¤Ã÷objÇ°ÃæÓÐ3(n-1)(µÚÒ»¸önull)¸öͬһ¼¶µÄÊý×éÔªËØ£¬
//Æä×ÓÏîÔÚmenuÖеĴËÒ»¼¶ÖеÄϱêλÖþÍÊÇ 3(n-1)+2,¼´3n-1
// level=0 currMenu_varName = "menu"
// level=1 currMenu_varName = "menu[3n-1]"
// level=2 currMenu_varName = "menu[3n-1][3n-1]" ÒÀ´ËÀàÍÆ...
currMenu_varName += "[" + (document.getElementById(arrSel[i]).selectedIndex*3 -1) + "]";
if (i==(level-1))
{
//´æ´¢µ±Ç°²Ëµ¥µÄ¸¸ÀàµÄvalueÊôÐÔµÄÊý×éÔªËØµÄÃû³Æ
parentMenu_value_varName += "[" + (document.getElementById(arrSel[i]).selectedIndex*3 -2) + "]";
//´æ´¢µ±Ç°²Ëµ¥µÄ¸¸ÀàµÄtextÊôÐÔµÄÊý×éÔªËØµÄÃû³Æ
parentMenu_text_varName += "[" + (document.getElementById(arrSel[i]).selectedIndex*3-3) + "]";
}
else
{
parentMenu_value_varName = currMenu_varName;
parentMenu_text_varName = currMenu_varName;
}
}
//alert(currMenu_varName);
//°ÑÊý×éÃû×Ö·û´®×ª»»³É¶ÔÓ¦µÄÊý×é,´ËÊý×éÖдæµÄ¾ÍÊǵ±Ç°²Ëµ¥µÄÊý¾Ý
currMenu = eval(currMenu_varName);
if (currMenu == null)
{
//ϼ¶²Ëµ¥Èç¹ûÊÇnull,°Ñϼ¶²Ëµ¥µÄÖµºÍtextÈ«²¿ÖÃΪµ±Ç°²Ëµ¥µÄÖµºÍtext
parentMenu_value = eval(parentMenu_value_varName);
parentMenu_text = eval(parentMenu_text_varName);
//alert(parentMenu_value);
maxLevel = arrSel.length;
for (i=level; i<maxLevel; i++)
{
subObj = document.getElementById(arrSel[i]);
//Çå¿ÕÔÓÐÑ¡Ïî
sel_len = subObj.length;
for(j=0; j<sel_len; j++)
{
subObj.remove(0);
}
subObj.options.add(new Option('null', ''));
}
}
else
{
//Çå¿ÕÔÓÐÑ¡Ïî
//parentMenu_value = eval(parentMenu_value_varName);
//parentMenu_text = eval(parentMenu_text_varName);
sel_len = obj.length;
for(i=0;i<sel_len;i++)
{
obj.remove(0);
}
//еIJ˵¥Ïî¸öÊý
new_sel_len = Math.floor(currMenu.length/3);
//°ÑcurrMenuÖеÄÖµºÍÎı¾¼ÓÈë²Ëµ¥(obj)
obj.options.add(new Option('null',''));
for(i=0;i<new_sel_len;i++)
{
obj.options.add(new Option(currMenu[i*3],currMenu[i*3+1]));
}
//obj.options.add(new Option('null', ''));
//Ö¸¶¨ÏÂÒ»¼¶²Ëµ¥onchangeʼþ
//obj.onchange = alert("onchange");
obj.onchange = Function("multiLevelMenu(" + (level+1) + ")");
//µÝ¹éµ÷ÓÃ
multiLevelMenu(level+1);
}
}
else
{
//Í˳öµÝ¹é
return false;
}
}
multiLevelMenu(0);
////////////////////////////////////////////////////////////////////////////////////////////
//ÏÔʾµ±Ç°µÄ·ÖÀà
selected_menu(document.getElementById('S1'),0,part_1);
selected_menu(document.getElementById('S2'),1,part_2);
selected_menu(document.getElementById('S3'),2,part_3);
selected_menu(document.getElementById('S4'),3,part_4);
selected_menu(document.getElementById('S5'),4,part_5);
function selected_menu(obj,level,sel_value)
{
len=obj.length;
for(i=0;i<len;i++)
{
if(obj.options[i].value==sel_value)
{
obj.options[i].selected=true;
multiLevelMenu(level+1);
break;
}
}
}
|
hp-yu/quicklab_yc
|
include/multiLevelMenu.js
|
JavaScript
|
gpl-2.0
| 3,754
|
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2011 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/documents/epl-v10.php
See the LICENSE file in the project's top-level directory for details.
Authors:
* Martin Wittemann (martinwittemann)
************************************************************************ */
/**
* Mixin holding the handler for the two axis mouse wheel scrolling. Please
* keep in mind that the including widget has to have the scroll bars
* implemented as child controls named <code>scrollbar-x</code> and
* <code>scrollbar-y</code> to get the handler working. Also, you have to
* attach the listener yourself.
*/
qx.Mixin.define("qx.ui.core.scroll.MWheelHandling",
{
members :
{
/**
* Mouse wheel event handler
*
* @param e {qx.event.type.Mouse} Mouse event
*/
_onMouseWheel : function(e)
{
var showX = this._isChildControlVisible("scrollbar-x");
var showY = this._isChildControlVisible("scrollbar-y");
var scrollbarY = showY ? this.getChildControl("scrollbar-y", true) : null;
var scrollbarX = showX ? this.getChildControl("scrollbar-x", true) : null;
var deltaY = e.getWheelDelta("y");
var deltaX = e.getWheelDelta("x");
var endY = !showY;
var endX = !showX;
// y case
if (scrollbarY) {
var steps = parseInt(deltaY);
if (steps !== 0) {
scrollbarY.scrollBySteps(steps);
}
var position = scrollbarY.getPosition();
var max = scrollbarY.getMaximum();
// pass the event to the parent if the scrollbar is at an edge
if (steps < 0 && position <= 0 || steps > 0 && position >= max) {
endY = true;
}
}
// x case
if (scrollbarX) {
var steps = parseInt(deltaX);
if (steps !== 0) {
scrollbarX.scrollBySteps(steps);
}
var position = scrollbarX.getPosition();
var max = scrollbarX.getMaximum();
// pass the event to the parent if the scrollbar is at an edge
if (steps < 0 && position <= 0 || steps > 0 && position >= max) {
endX = true;
}
}
// pass the event to the parent if both scrollbars are at the end
if (!endY || !endX) {
// Stop bubbling and native event only if a scrollbar is visible
e.stop();
}
}
}
});
|
09zwcbupt/undergrad_thesis
|
ext/poxdesk/qx/framework/source/class/qx/ui/core/scroll/MWheelHandling.js
|
JavaScript
|
gpl-3.0
| 2,606
|
'use strict';
var BotUtil = require('./botutil');
var PermissionLevels = require('./permissionlevels');
/**
* Creates/loads a permission object
* @constructor
* @param {PermissionsManager} manager
* @param {String} id
* @param {Integer} defaultLevel
* @returns {Permission}
*/
var Permission = function (manager, id, defaultLevel) {
/**
* The PermissionsManager in charge of the permission
* @type PermissionsManager
*/
this.manager = manager;
/**
* The id of the permission
* @type String
*/
this.id = id;
this.defaultLevel = defaultLevel || (PermissionLevels.PERMISSION_ADMIN | PermissionLevels.PERMISSION_MOD);
this.level = false;
this.whitelist = {};
this.blacklist = {};
this.load();
};
/**
* Loads permission properties from storage
* @returns {undefined}
*/
Permission.prototype.load = function () {
var store = this.manager.GetStore();
if (store.permissions[this.id] && store.permissions[this.id].level) {
this.hydrate(store.permissions[this.id]);
} else {
this.level = this.defaultLevel;
this.save(store);
}
};
/**
* Hydrates this permissions object with the given data
* @param {Object} data
* @returns {undefined}
*/
Permission.prototype.hydrate = function (data) {
if (data.id) this.id = data.id;
this.level = data.level || this.defaultLevel;
this.whitelist = data.whitelist || {};
this.blacklist = data.blacklist || {};
};
/**
* Saves this permission in storage
* @param {Object} [_store]
* @returns {undefined}
*/
Permission.prototype.save = function (_store) {
var store = _store || this.manager.GetStore();
store.permissions[this.id] = {
id: this.id,
level: this.level,
whitelist: this.whitelist,
blacklist: this.blacklist
};
this.manager.SaveStore(store);
};
/**
* Checks if a user has this permission
* @param {User} user
* @returns {Boolean}
*/
Permission.prototype.check = function (user) {
return !this.blacklist[user.id] && (((this.level & user.privilegeLevel) !== 0) || (this.whitelist[user.id] && user.registered));
};
/**
* Blacklists the given user
* @param {User} user
* @returns {undefined}
*/
Permission.prototype.blacklist = function (user) {
this.blacklist[user.id || user.toLowerCase()] = user.username || user;
this.save();
};
/**
* Unblacklists the given user
* @param {User} user
* @returns {undefined}
*/
Permission.prototype.unblacklist = function (user) {
delete this.blacklist[user.id || user.toLowerCase()];
this.save();
};
/**
* Whitelists the given user
* @param {User} user
* @returns {undefined}
*/
Permission.prototype.whitelist = function (user) {
this.whitelist[user.id || user.toLowerCase()] = user.username || user;
this.save();
};
/**
* Unwhitelists the given user
* @param {User} user
* @returns {undefined}
*/
Permission.prototype.unwhitelist = function (user) {
delete this.whitelist[user.id || user.toLowerCase()];
this.save();
};
module.exports = Permission;
|
Tschrock/PicartoChatBot
|
modules/permission.js
|
JavaScript
|
gpl-3.0
| 3,068
|
/*******************************************************************************
uBlock Origin - a browser extension to block requests.
Copyright (C) 2015-present Raymond Hill
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
Home: https://github.com/gorhill/uBlock
*/
'use strict';
/******************************************************************************/
(( ) => {
/******************************************************************************/
// This can happen
if ( typeof vAPI !== 'object' || vAPI.loadAllLargeMedia instanceof Function ) {
return;
}
/******************************************************************************/
const largeMediaElementAttribute = 'data-' + vAPI.sessionId;
const largeMediaElementSelector =
':root audio[' + largeMediaElementAttribute + '],\n' +
':root img[' + largeMediaElementAttribute + '],\n' +
':root picture[' + largeMediaElementAttribute + '],\n' +
':root video[' + largeMediaElementAttribute + ']';
/******************************************************************************/
const isMediaElement = function(elem) {
return /^(?:audio|img|picture|video)$/.test(elem.localName);
};
/******************************************************************************/
const mediaNotLoaded = function(elem) {
switch ( elem.localName ) {
case 'audio':
case 'video': {
const src = elem.src || '';
if ( src.startsWith('blob:') ) {
elem.autoplay = false;
elem.pause();
}
return elem.readyState === 0 || elem.error !== null;
}
case 'img': {
if ( elem.naturalWidth !== 0 || elem.naturalHeight !== 0 ) {
break;
}
const style = window.getComputedStyle(elem);
// For some reason, style can be null with Pale Moon.
return style !== null ?
style.getPropertyValue('display') !== 'none' :
elem.offsetHeight !== 0 && elem.offsetWidth !== 0;
}
default:
break;
}
return false;
};
/******************************************************************************/
// For all media resources which have failed to load, trigger a reload.
// <audio> and <video> elements.
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
const surveyMissingMediaElements = function() {
let largeMediaElementCount = 0;
for ( const elem of document.querySelectorAll('audio,img,video') ) {
if ( mediaNotLoaded(elem) === false ) { continue; }
elem.setAttribute(largeMediaElementAttribute, '');
largeMediaElementCount += 1;
switch ( elem.localName ) {
case 'img': {
const picture = elem.closest('picture');
if ( picture !== null ) {
picture.setAttribute(largeMediaElementAttribute, '');
}
} break;
default:
break;
}
}
return largeMediaElementCount;
};
if ( surveyMissingMediaElements() === 0 ) { return; }
// Insert CSS to highlight blocked media elements.
if ( vAPI.largeMediaElementStyleSheet === undefined ) {
vAPI.largeMediaElementStyleSheet = [
largeMediaElementSelector + ' {',
'border: 2px dotted red !important;',
'box-sizing: border-box !important;',
'cursor: zoom-in !important;',
'display: inline-block;',
'filter: none !important;',
'font-size: 1rem !important;',
'min-height: 1em !important;',
'min-width: 1em !important;',
'opacity: 1 !important;',
'outline: none !important;',
'transform: none !important;',
'visibility: visible !important;',
'z-index: 2147483647',
'}',
].join('\n');
vAPI.userStylesheet.add(vAPI.largeMediaElementStyleSheet);
vAPI.userStylesheet.apply();
}
/******************************************************************************/
const loadMedia = async function(elem) {
const src = elem.getAttribute('src') || '';
elem.removeAttribute('src');
await vAPI.messaging.send('scriptlets', {
what: 'temporarilyAllowLargeMediaElement',
});
if ( src !== '' ) {
elem.setAttribute('src', src);
}
elem.load();
};
/******************************************************************************/
const loadImage = async function(elem) {
const src = elem.getAttribute('src') || '';
elem.removeAttribute('src');
await vAPI.messaging.send('scriptlets', {
what: 'temporarilyAllowLargeMediaElement',
});
if ( src !== '' ) {
elem.setAttribute('src', src);
}
};
/******************************************************************************/
const loadMany = function(elems) {
for ( const elem of elems ) {
switch ( elem.localName ) {
case 'audio':
case 'video':
loadMedia(elem);
break;
case 'img':
loadImage(elem);
break;
default:
break;
}
}
};
/******************************************************************************/
const onMouseClick = function(ev) {
if ( ev.button !== 0 || ev.isTrusted === false ) { return; }
const toLoad = [];
const elems = document.elementsFromPoint instanceof Function
? document.elementsFromPoint(ev.clientX, ev.clientY)
: [ ev.target ];
for ( const elem of elems ) {
if ( elem.matches(largeMediaElementSelector) === false ) { continue; }
elem.removeAttribute(largeMediaElementAttribute);
if ( mediaNotLoaded(elem) ) {
toLoad.push(elem);
}
}
if ( toLoad.length === 0 ) { return; }
loadMany(toLoad);
ev.preventDefault();
ev.stopPropagation();
};
document.addEventListener('click', onMouseClick, true);
/******************************************************************************/
const onLoadedData = function(ev) {
const media = ev.target;
if ( media.localName !== 'audio' && media.localName !== 'video' ) {
return;
}
const src = media.src;
if ( typeof src === 'string' && src.startsWith('blob:') === false ) {
return;
}
media.autoplay = false;
media.pause();
};
// https://www.reddit.com/r/uBlockOrigin/comments/mxgpmc/
// Support cases where the media source is not yet set.
for ( const media of document.querySelectorAll('audio,video') ) {
const src = media.src;
if (
(typeof src === 'string') &&
(src === '' || src.startsWith('blob:'))
) {
media.autoplay = false;
media.pause();
}
}
document.addEventListener('loadeddata', onLoadedData);
/******************************************************************************/
const onLoad = function(ev) {
const elem = ev.target;
if ( isMediaElement(elem) === false ) { return; }
elem.removeAttribute(largeMediaElementAttribute);
};
document.addEventListener('load', onLoad, true);
/******************************************************************************/
const onLoadError = function(ev) {
const elem = ev.target;
if ( isMediaElement(elem) === false ) { return; }
if ( mediaNotLoaded(elem) ) {
elem.setAttribute(largeMediaElementAttribute, '');
}
};
document.addEventListener('error', onLoadError, true);
/******************************************************************************/
vAPI.loadAllLargeMedia = function() {
document.removeEventListener('click', onMouseClick, true);
document.removeEventListener('loadeddata', onLoadedData, true);
document.removeEventListener('load', onLoad, true);
document.removeEventListener('error', onLoadError, true);
const toLoad = [];
for ( const elem of document.querySelectorAll(largeMediaElementSelector) ) {
elem.removeAttribute(largeMediaElementAttribute);
if ( mediaNotLoaded(elem) ) {
toLoad.push(elem);
}
}
loadMany(toLoad);
};
/******************************************************************************/
})();
/*******************************************************************************
DO NOT:
- Remove the following code
- Add code beyond the following code
Reason:
- https://github.com/gorhill/uBlock/pull/3721
- uBO never uses the return value from injected content scripts
**/
void 0;
|
gorhill/uBlock
|
src/js/scriptlets/load-large-media-interactive.js
|
JavaScript
|
gpl-3.0
| 9,032
|
var searchData=
[
['editor',['editor',['../classeditor.html',1,'']]]
];
|
mihailikus/cengen
|
doc/html/search/classes_65.js
|
JavaScript
|
gpl-3.0
| 74
|
// @flow
import { Record, Map } from 'immutable'
import Profile from 'models/Profile'
import ShareRecipient from 'models/ShareRecipient'
import IpfsDirectory from 'models/IpfsDirectory'
import isIpfs from 'is-ipfs'
const LOCAL_DATA_VERSION = 1
const PUBLISH_DATA_VERSION = 1
export const ShareState = {
AVAILABLE : 'AVAILABLE',
DOWNLOADING : 'DOWNLOADING',
PAUSED : 'PAUSED',
SHARING : 'SHARING'
}
export type ShareStateType = $Keys<typeof ShareState>
/**
* PlantUML diagram (http://plantuml.com/state-diagram)
*
* @startuml
*
* [*] --> Available : got a notification
*
* Available --> Downloading : start()
* Downloading --> Available : abort()
*
* Downloading --> Paused : pause()
* Paused --> Downloading : start()
* Paused --> Sharing : download done
*
* Paused --> Available : abort()
*
* [*] --> Sharing : created a Share locally
*
* Downloading --> Sharing : download done
* Sharing --> Available : data lost
*
* @enduml
*/
export const writable = {
dataVersion: 'dataVersion',
id: 'id',
hash: 'hash',
authorPubkey: 'authorPubkey',
title: 'title',
description: 'description',
status: 'status',
content: 'content',
recipients: 'recipients',
favorite: 'favorite',
outputPath: 'outputPath'
}
export const ShareRecord = Record({
dataVersion: LOCAL_DATA_VERSION,
id: null,
hash: null,
authorPubkey: null,
title: null,
description: null,
status: null,
content: null,
recipients: Map(),
favorite: false,
outputPath: null
}, 'Share')
export default class Share extends ShareRecord {
dataVersion: number
// local identifier
id: number
hash: ?string
// (authorPubkey == null) mean that the user is the author
authorPubkey: ?string
title: string
description: string
status: ShareStateType
content: ?IpfsDirectory
recipients: Map<string,ShareRecipient>
favorite: boolean
outputPath: ?string
static create(title: string, description: ?string = null) {
return new this().withMutations(share => share
.set(writable.authorPubkey, null)
.set(writable.title, title)
.set(writable.description, description)
.set(writable.status, ShareState.SHARING)
)
}
static fromData(hash: string, data) {
const { dataVersion, author, title, description, content, recipients } = data
if(dataVersion !== PUBLISH_DATA_VERSION) {
throw 'Unexpected share data version'
}
if(!isIpfs.multihash(hash)) {
throw 'invalid hash'
}
// TODO: more check, author should be set...
const _recipients = Map(
recipients.map(({pubkey}) => [pubkey, ShareRecipient.create(pubkey)])
)
return new this().withMutations(share => share
.set(writable.hash, hash)
.set(writable.status, ShareState.AVAILABLE)
.set(writable.authorPubkey, author)
.set(writable.title, title)
.set(writable.description, description || '')
.set(writable.content, IpfsDirectory.create(content))
.set(writable.recipients, _recipients)
)
}
// Return the object to be published in IPFS
getPublishObject(profile: Profile): {} {
const recipients = this.recipients.valueSeq().map((recipient: ShareRecipient) => ({
pubkey: recipient.pubkey
}))
return {
dataVersion: PUBLISH_DATA_VERSION,
author: this.isAuthor ? profile.pubkey : this.authorPubkey,
title: this.title,
description: this.description,
content: this.content.hash,
recipients
}
}
get progress(): number {
return this.content.progress
}
// return the progress formated and rounded at 2 decimal (ex: '83.25%')
get progressFormatted() : string {
return `${Math.round(this.content.progress * 10000) / 100}%`
}
get sizeTotal(): number {
return this.content.sizeTotal
}
get sizeLocal(): number {
return this.content.sizeLocal
}
get metadataLocal() : boolean {
return this.content && this.content.metadataLocal
}
get metadataProgress(): [] {
return this.content && this.content.metadataProgress
}
get isLocal() : boolean {
return this.metadataLocal && this.content.isLocal
}
get isAuthor() : boolean {
return this.authorPubkey === null
}
get isAvailable() : boolean {
return this.status === ShareState.AVAILABLE
}
get isDownloading() : boolean {
return this.status === ShareState.DOWNLOADING
}
get isPaused() : boolean {
return this.status === ShareState.PAUSED
}
get isSharing() : boolean {
return this.status === ShareState.SHARING
}
hasRecipient(pubkey: string) : boolean {
return this.recipients.some((recipient: ShareRecipient) => recipient.pubkey === pubkey)
}
}
|
MichaelMure/TotallyNotArbore
|
app/models/Share.js
|
JavaScript
|
gpl-3.0
| 4,675
|
/*
* Copyright (C) 2007-2022 Crafter Software Corporation. All Rights Reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* File: in-context-edit.js
* Component ID: templateholder-incontextedit
* @author: Russ Danner
* @date: 4.26.2011
**/
(function () {
CStudioAuthoring.register('TemplateHolder.InContextEdit', {
ROOT_ROW: [''].join(''),
SUB_ROW: [''].join(''),
OVERLAY: [''].join(''),
SUCCESS: [''].join('')
});
CStudioAuthoring.Env.ModuleMap.map('templateholder-incontextedit', CStudioAuthoring.TemplateHolder.InContextEdit);
})();
|
rart/studio-ui
|
static-assets/components/cstudio-templates/in-context-edit.js
|
JavaScript
|
gpl-3.0
| 1,116
|
/*! jQuery UI - v1.10.4 - 2014-03-09
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function(t){var e=/up|down|vertical/,i=/up|left|vertical|horizontal/;t.effects.effect.blind=function(s,n){var a,o,r,l=t(this),h=["position","top","bottom","left","right","height","width"],c=t.effects.setMode(l,s.mode||"hide"),u=s.direction||"up",d=e.test(u),p=d?"height":"width",f=d?"top":"left",g=i.test(u),m={},v="show"===c;l.parent().is(".ui-effects-wrapper")?t.effects.save(l.parent(),h):t.effects.save(l,h),l.show(),a=t.effects.createWrapper(l).css({overflow:"hidden"}),o=a[p](),r=parseFloat(a.css(f))||0,m[p]=v?o:0,g||(l.css(d?"bottom":"right",0).css(d?"top":"left","auto").css({position:"absolute"}),m[f]=v?r:o+r),v&&(a.css(p,0),g||a.css(f,r+o)),a.animate(m,{duration:s.duration,easing:s.easing,queue:!1,complete:function(){"hide"===c&&l.hide(),t.effects.restore(l,h),t.effects.removeWrapper(l),n()}})}})(jQuery);
|
dwbfox/Nuke-Your-Tracks
|
js/vendor/jquery-ui-1.10.4.custom/development-bundle/ui/minified/jquery.ui.effect-blind.min.js
|
JavaScript
|
gpl-3.0
| 956
|
import countWords from "../stringProcessing/countWords.js";
import keyphraseLengthFactor from "../helpers/keyphraseLengthFactor.js";
/**
* Calculates a recommended keyword count for a text. The formula to calculate this number is based on the
* keyword density formula.
*
* @param {string} text The paper text.
* @param {number} keyphraseLength The length of the focus keyphrase in words.
* @param {number} recommendedKeywordDensity The recommended keyword density (either maximum or minimum).
* @param {string} maxOrMin Whether it's a maximum or minimum recommended keyword density.
*
* @returns {number} The recommended keyword count.
*/
export default function( text, keyphraseLength, recommendedKeywordDensity, maxOrMin ) {
const wordCount = countWords( text );
if ( wordCount === 0 ) {
return 0;
}
const lengthKeyphraseFactor = keyphraseLengthFactor( keyphraseLength );
const recommendedKeywordCount = ( recommendedKeywordDensity * wordCount ) / ( 100 * lengthKeyphraseFactor );
/*
* The recommended keyword count should always be at least 2,
* regardless of the keyword density, the word count, or the keyphrase length.
*/
if ( recommendedKeywordCount < 2 ) {
return 2;
}
switch ( maxOrMin ) {
case "min":
// Round up for the recommended minimum count.
return Math.ceil( recommendedKeywordCount );
default:
case "max":
// Round down for the recommended maximum count.
return Math.floor( recommendedKeywordCount );
}
}
|
Yoast/js-text-analysis
|
src/assessmentHelpers/recommendedKeywordCount.js
|
JavaScript
|
gpl-3.0
| 1,477
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/** @module state */ /** for typedoc */
var predicates_1 = require("../common/predicates");
var common_1 = require("../common/common");
var StateMatcher = /** @class */ (function () {
function StateMatcher(_states) {
this._states = _states;
}
StateMatcher.prototype.isRelative = function (stateName) {
stateName = stateName || "";
return stateName.indexOf(".") === 0 || stateName.indexOf("^") === 0;
};
StateMatcher.prototype.find = function (stateOrName, base, matchGlob) {
if (matchGlob === void 0) { matchGlob = true; }
if (!stateOrName && stateOrName !== "")
return undefined;
var isStr = predicates_1.isString(stateOrName);
var name = isStr ? stateOrName : stateOrName.name;
if (this.isRelative(name))
name = this.resolvePath(name, base);
var state = this._states[name];
if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {
return state;
}
else if (isStr && matchGlob) {
var _states = common_1.values(this._states);
var matches = _states.filter(function (state) {
return state.__stateObjectCache.nameGlob &&
state.__stateObjectCache.nameGlob.matches(name);
});
if (matches.length > 1) {
console.log("stateMatcher.find: Found multiple matches for " + name + " using glob: ", matches.map(function (match) { return match.name; }));
}
return matches[0];
}
return undefined;
};
StateMatcher.prototype.resolvePath = function (name, base) {
if (!base)
throw new Error("No reference point given for path '" + name + "'");
var baseState = this.find(base);
var splitName = name.split("."), i = 0, pathLength = splitName.length, current = baseState;
for (; i < pathLength; i++) {
if (splitName[i] === "" && i === 0) {
current = baseState;
continue;
}
if (splitName[i] === "^") {
if (!current.parent)
throw new Error("Path '" + name + "' not valid for state '" + baseState.name + "'");
current = current.parent;
continue;
}
break;
}
var relName = splitName.slice(i).join(".");
return current.name + (current.name && relName ? "." : "") + relName;
};
return StateMatcher;
}());
exports.StateMatcher = StateMatcher;
//# sourceMappingURL=stateMatcher.js.map
|
cycojesus/ledgerrb
|
public/app/vendor/node_modules/@uirouter/core/lib/state/stateMatcher.js
|
JavaScript
|
gpl-3.0
| 2,700
|
/**
* @file Burrow.js
* @fileOverview Factory module for the Burrow class.
* @author Dennis Mckinnon
* @module Burrow
*/
'use strict'
var Service = require('./service')
var events = require('./events.js')
var Pipe = require('./pipe')
var ContractManager = require('./contractManager')
var Namereg = require('./namereg')
/**
* Create a new instance of the Burrow class.
*
* @param {string} URL - URL of Burrow instance.
* @returns {Burrow} - A new instance of the Burrow class.
*/
exports.createInstance = function (URL, account, options) {
URL = (typeof URL === 'string' ? URL : URL.host + ':' + URL.port)
return new Burrow(URL, account, options)
}
/**
* The main class.
*
* @param {string} URL - URL of Burrow instance.
* @constructor
*/
function Burrow (URL, account, options) {
this.URL = URL
this.tag = options.tag
if (!account) {
this.readonly = true
this.account = null
} else {
this.readonly = false
this.account = account
}
this.executionEvents = Service('rpcevents.proto', 'rpcevents', 'ExecutionEvents', URL)
this.transact = Service('rpctransact.proto', 'rpctransact', 'Transact', URL)
this.query = Service('rpcquery.proto', 'rpcquery', 'Query', URL)
// This is the execution events streaming service running on top of the raw streaming function.
this.events = events(this)
// Contracts stuff running on top of grpc
this.pipe = new Pipe(this)
this.contracts = new ContractManager(this, options)
this.namereg = new Namereg(this)
}
|
silasdavis/eris-db
|
js/lib/Burrow.js
|
JavaScript
|
gpl-3.0
| 1,514
|
/**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License
* at:
*
* http://opensource.org/licenses/ecl2.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*
*/
/*jslint browser: true, nomen: true*/
/*global define*/
define(["require", "jquery", "underscore", "backbone", "engage/core"], function(require, $, _, Backbone, Engage) {
"use strict";
var insertIntoDOM = true;
var PLUGIN_NAME = "Slide text";
var PLUGIN_TYPE = "engage_tab";
var PLUGIN_VERSION = "1.0";
var PLUGIN_TEMPLATE_DESKTOP = "templates/desktop.html";
var PLUGIN_TEMPLATE_MOBILE = "templates/mobile.html";
var PLUGIN_TEMPLATE_EMBED = "templates/embed.html";
var PLUGIN_STYLES_DESKTOP = [
"styles/desktop.css"
];
var PLUGIN_STYLES_EMBED = [
"styles/embed.css"
];
var PLUGIN_STYLES_MOBILE = [
"styles/mobile.css"
];
var plugin;
var events = {
segmentMouseover: new Engage.Event("Segment:mouseOver", "the mouse is over a segment", "both"),
segmentMouseout: new Engage.Event("Segment:mouseOut", "the mouse is off a segment", "both"),
seek: new Engage.Event("Video:seek", "seek video to a given position in seconds", "trigger"),
plugin_load_done: new Engage.Event("Core:plugin_load_done", "", "handler"),
mediaPackageModelError: new Engage.Event("MhConnection:mediaPackageModelError", "", "handler")
};
var isDesktopMode = false;
var isEmbedMode = false;
var isMobileMode = false;
// desktop, embed and mobile logic
switch (Engage.model.get("mode")) {
case "embed":
plugin = {
insertIntoDOM: insertIntoDOM,
name: PLUGIN_NAME,
type: PLUGIN_TYPE,
version: PLUGIN_VERSION,
styles: PLUGIN_STYLES_EMBED,
template: PLUGIN_TEMPLATE_EMBED,
events: events
};
isEmbedMode = true;
break;
case "mobile":
plugin = {
insertIntoDOM: insertIntoDOM,
name: PLUGIN_NAME,
type: PLUGIN_TYPE,
version: PLUGIN_VERSION,
styles: PLUGIN_STYLES_MOBILE,
template: PLUGIN_TEMPLATE_MOBILE,
events: events
};
isMobileMode = true;
break;
case "desktop":
default:
plugin = {
insertIntoDOM: insertIntoDOM,
name: PLUGIN_NAME,
type: PLUGIN_TYPE,
version: PLUGIN_VERSION,
styles: PLUGIN_STYLES_DESKTOP,
template: PLUGIN_TEMPLATE_DESKTOP,
events: events
};
isDesktopMode = true;
break;
}
/* don't change these variables */
var Utils;
var TEMPLATE_TAB_CONTENT_ID = "engage_slidetext_tab_content";
var html_snippet_id = "engage_slidetext_tab_content";
var id_segmentNo = "tab_slidetext_segment_";
var mediapackageChange = "change:mediaPackage";
var initCount = 4;
var mediapackageError = false;
var translations = new Array();
var Segment;
function initTranslate(language, funcSuccess, funcError) {
var path = Engage.getPluginPath("EngagePluginTabSlidetext").replace(/(\.\.\/)/g, "");
// var jsonstr = window.location.origin + "/engage/theodul/" + path; // this solution is really bad, fix it... ILPATCH
var jsonstr = ILIAS_THEODUL_PATH + path;
Engage.log("Controls: selecting language " + language);
jsonstr += "language/" + language + ".json";
$.ajax({
url: jsonstr,
dataType: "json",
success: function(data) {
if (data) {
data.value_locale = language;
translations = data;
if (funcSuccess) {
funcSuccess(translations);
}
} else {
if (funcError) {
funcError();
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (funcError) {
funcError();
}
}
});
}
function translate(str, strIfNotFound) {
return (translations[str] != undefined) ? translations[str] : strIfNotFound;
}
var SlidetextTabView = Backbone.View.extend({
initialize: function(mediaPackageModel, template) {
this.setElement($(plugin.container));
this.model = mediaPackageModel;
this.template = template;
// bind the render function always to the view
_.bindAll(this, "render");
// listen for changes of the model and bind the render function to this
this.model.bind("change", this.render);
},
render: function() {
if (!mediapackageError) {
var segments = [];
var segmentInformation = this.model.get("segments");
if (segmentInformation !== undefined) {
for (var i = 0; i < segmentInformation.length; i++) {
if (segmentInformation[i] && segmentInformation[i].time) {
var segmentText = "No slide text available.";
if (segmentInformation[i].text)
segmentText = segmentInformation[i].text;
var segmentPreview = undefined;
if (segmentInformation[i].previews && segmentInformation[i].previews.preview
&& segmentInformation[i].previews.preview.$) {
segmentPreview = segmentInformation[i].previews.preview.$;
}
segments.push(new Segment((segmentInformation[i].time / 1000), segmentPreview, segmentText));
} else {
Engage.log("Tab:Slidetext: Detected Segment with start time " + segmentInformation[i].time / 1000 +
" that exceeds the duration of the video ");
}
};
if (segments.length > 0) {
// sort segments ascending by time
segments.sort(function(a, b) {
return a.time - b.time;
});
}
}
var tempVars = {
segments: segments,
str_segment: translate("segment", "Segment"),
str_noSlidesAvailable: translate("noSlidesAvailable", "No slides available."),
str_slide_text: translate("slide_text", "Slide text")
};
// compile template and load into the html
var template = _.template(this.template);
this.$el.html(template(tempVars));
$("#engage_tab_" + plugin.name.replace(/\s/g,"_")).text(tempVars.str_slide_text);
if (segments && (segments.length > 0)) {
Engage.log("Tab:Slidetext: " + segments.length + " segments are available.");
$.each(segments, function(i, v) {
$("#" + id_segmentNo + i).click(function(e) {
e.preventDefault();
if (!isNaN(v.time)) {
Engage.trigger(plugin.events.seek.getName(), v.time);
}
});
$("#" + id_segmentNo + i).mouseover(function(e) {
e.preventDefault();
Engage.trigger(plugin.events.segmentMouseover.getName(), i);
}).mouseout(function(e) {
e.preventDefault();
Engage.trigger(plugin.events.segmentMouseout.getName(), i);
});
});
}
Engage.on(plugin.events.segmentMouseover.getName(), function(no) {
$("#" + id_segmentNo + no).removeClass("mediaColor").addClass("mediaColor-hover");
});
Engage.on(plugin.events.segmentMouseout.getName(), function(no) {
$("#" + id_segmentNo + no).removeClass("mediaColor-hover").addClass("mediaColor");
});
}
}
});
function initPlugin() {
// only init if plugin template was inserted into the DOM
if (isDesktopMode && plugin.inserted) {
var slidetextTabView = new SlidetextTabView(Engage.model.get("mediaPackage"), plugin.template);
Engage.on(plugin.events.mediaPackageModelError.getName(), function(msg) {
mediapackageError = true;
});
}
}
if (isDesktopMode) {
// init event
Engage.log("Tab:Slidetext: Init");
var relative_plugin_path = Engage.getPluginPath("EngagePluginTabSlidetext");
// listen on a change/set of the mediaPackage model
Engage.model.on(mediapackageChange, function() {
initCount -= 1;
if (initCount <= 0) {
initPlugin();
}
});
// all plugins loaded
Engage.on(plugin.events.plugin_load_done.getName(), function() {
Engage.log("Tab:Slidetext: Plugin load done");
initCount -= 1;
if (initCount <= 0) {
initPlugin();
}
});
// load segment class
require([relative_plugin_path + "segment"], function(segment) {
Engage.log("Tab:Slidetext: Segment class loaded");
Segment = segment;
initCount -= 1;
if (initCount <= 0) {
initPlugin();
}
});
// load utils class
require([relative_plugin_path + "utils"], function(utils) {
Engage.log("Tab:Slidetext: Utils class loaded");
Utils = new utils();
plugin.timeStrToSeconds = Utils.timeStrToSeconds;
initTranslate(Engage.model.get("language"), function() {
Engage.log("Tab:Slidetext: Successfully translated.");
initCount -= 1;
if (initCount <= 0) {
initPlugin();
}
}, function() {
Engage.log("Tab:Slidetext: Error translating...");
initCount -= 1;
if (initCount <= 0) {
initPlugin();
}
});
});
}
return plugin;
});
|
TIK-NFL/ilias-oc-plugin
|
templates/theodul/plugin/4/static/main.js
|
JavaScript
|
gpl-3.0
| 11,430
|
/**
* @license
* Visual Blocks Editor
*
* Copyright 2011 Google Inc.
* https://developers.google.com/blockly/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Core JavaScript library for Blockly.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
// Top level object for Blockly.
goog.provide('Blockly');
goog.require('Blockly.BlockSvg.render');
goog.require('Blockly.Events');
goog.require('Blockly.FieldAngle');
goog.require('Blockly.FieldCheckbox');
goog.require('Blockly.FieldColour');
// Date picker commented out since it increases footprint by 60%.
// Add it only if you need it.
//goog.require('Blockly.FieldDate');
goog.require('Blockly.FieldDropdown');
goog.require('Blockly.FieldImage');
goog.require('Blockly.FieldTextInput');
goog.require('Blockly.FieldNumber');
goog.require('Blockly.FieldVariable');
goog.require('Blockly.Generator');
goog.require('Blockly.Msg');
goog.require('Blockly.Procedures');
goog.require('Blockly.Toolbox');
goog.require('Blockly.WidgetDiv');
goog.require('Blockly.WorkspaceSvg');
goog.require('Blockly.constants');
goog.require('Blockly.inject');
goog.require('Blockly.utils');
goog.require('goog.color');
goog.require('goog.userAgent');
// Turn off debugging when compiled.
var CLOSURE_DEFINES = {'goog.DEBUG': false};
/**
* The main workspace most recently used.
* Set by Blockly.WorkspaceSvg.prototype.markFocused
* @type {Blockly.Workspace}
*/
Blockly.mainWorkspace = null;
/**
* Currently selected block.
* @type {Blockly.Block}
*/
Blockly.selected = null;
/**
* Currently highlighted connection (during a drag).
* @type {Blockly.Connection}
* @private
*/
Blockly.highlightedConnection_ = null;
/**
* Connection on dragged block that matches the highlighted connection.
* @type {Blockly.Connection}
* @private
*/
Blockly.localConnection_ = null;
/**
* All of the connections on blocks that are currently being dragged.
* @type {!Array.<!Blockly.Connection>}
* @private
*/
Blockly.draggingConnections_ = [];
/**
* Contents of the local clipboard.
* @type {Element}
* @private
*/
Blockly.clipboardXml_ = null;
/**
* Source of the local clipboard.
* @type {Blockly.WorkspaceSvg}
* @private
*/
Blockly.clipboardSource_ = null;
/**
* Is the mouse dragging a block?
* DRAG_NONE - No drag operation.
* DRAG_STICKY - Still inside the sticky DRAG_RADIUS.
* DRAG_FREE - Freely draggable.
* @private
*/
Blockly.dragMode_ = Blockly.DRAG_NONE;
/**
* Wrapper function called when a touch mouseUp occurs during a drag operation.
* @type {Array.<!Array>}
* @private
*/
Blockly.onTouchUpWrapper_ = null;
/**
* Convert a hue (HSV model) into an RGB hex triplet.
* @param {number} hue Hue on a colour wheel (0-360).
* @return {string} RGB code, e.g. '#5ba65b'.
*/
Blockly.hueToRgb = function(hue) {
return goog.color.hsvToHex(hue, Blockly.HSV_SATURATION,
Blockly.HSV_VALUE * 255);
};
/**
* Returns the dimensions of the specified SVG image.
* @param {!Element} svg SVG image.
* @return {!Object} Contains width and height properties.
*/
Blockly.svgSize = function(svg) {
return {width: svg.cachedWidth_,
height: svg.cachedHeight_};
};
/**
* Size the workspace when the contents change. This also updates
* scrollbars accordingly.
* @param {!Blockly.WorkspaceSvg} workspace The workspace to resize.
*/
Blockly.resizeSvgContents = function(workspace) {
workspace.resizeContents();
};
/**
* Size the SVG image to completely fill its container. Call this when the view
* actually changes sizes (e.g. on a window resize/device orientation change).
* See Blockly.resizeSvgContents to resize the workspace when the contents
* change (e.g. when a block is added or removed).
* Record the height/width of the SVG image.
* @param {!Blockly.WorkspaceSvg} workspace Any workspace in the SVG.
*/
Blockly.svgResize = function(workspace) {
var mainWorkspace = workspace;
while (mainWorkspace.options.parentWorkspace) {
mainWorkspace = mainWorkspace.options.parentWorkspace;
}
var svg = mainWorkspace.getParentSvg();
var div = svg.parentNode;
if (!div) {
// Workspace deleted, or something.
return;
}
var width = div.offsetWidth;
var height = div.offsetHeight;
if (svg.cachedWidth_ != width) {
svg.setAttribute('width', width + 'px');
svg.cachedWidth_ = width;
}
if (svg.cachedHeight_ != height) {
svg.setAttribute('height', height + 'px');
svg.cachedHeight_ = height;
}
mainWorkspace.resize();
};
/**
* Handle a mouse-up anywhere on the page.
* @param {!Event} e Mouse up event.
* @private
*/
Blockly.onMouseUp_ = function(e) {
var workspace = Blockly.getMainWorkspace();
Blockly.Css.setCursor(Blockly.Css.Cursor.OPEN);
workspace.dragMode_ = Blockly.DRAG_NONE;
// Unbind the touch event if it exists.
if (Blockly.onTouchUpWrapper_) {
Blockly.unbindEvent_(Blockly.onTouchUpWrapper_);
Blockly.onTouchUpWrapper_ = null;
}
if (Blockly.onMouseMoveWrapper_) {
Blockly.unbindEvent_(Blockly.onMouseMoveWrapper_);
Blockly.onMouseMoveWrapper_ = null;
}
};
/**
* Handle a mouse-move on SVG drawing surface.
* @param {!Event} e Mouse move event.
* @private
*/
Blockly.onMouseMove_ = function(e) {
if (e.touches && e.touches.length >= 2) {
return; // Multi-touch gestures won't have e.clientX.
}
var workspace = Blockly.getMainWorkspace();
if (workspace.dragMode_ != Blockly.DRAG_NONE) {
var dx = e.clientX - workspace.startDragMouseX;
var dy = e.clientY - workspace.startDragMouseY;
var metrics = workspace.startDragMetrics;
var x = workspace.startScrollX + dx;
var y = workspace.startScrollY + dy;
x = Math.min(x, -metrics.contentLeft);
y = Math.min(y, -metrics.contentTop);
x = Math.max(x, metrics.viewWidth - metrics.contentLeft -
metrics.contentWidth);
y = Math.max(y, metrics.viewHeight - metrics.contentTop -
metrics.contentHeight);
// Move the scrollbars and the page will scroll automatically.
workspace.scrollbar.set(-x - metrics.contentLeft,
-y - metrics.contentTop);
// Cancel the long-press if the drag has moved too far.
if (Math.sqrt(dx * dx + dy * dy) > Blockly.DRAG_RADIUS) {
Blockly.longStop_();
workspace.dragMode_ = Blockly.DRAG_FREE;
}
e.stopPropagation();
e.preventDefault();
}
};
/**
* Handle a key-down on SVG drawing surface.
* @param {!Event} e Key down event.
* @private
*/
Blockly.onKeyDown_ = function(e) {
if (Blockly.mainWorkspace.options.readOnly || Blockly.isTargetInput_(e)) {
// No key actions on readonly workspaces.
// When focused on an HTML text input widget, don't trap any keys.
return;
}
var deleteBlock = false;
if (e.keyCode == 27) {
// Pressing esc closes the context menu.
Blockly.hideChaff();
} else if (e.keyCode == 8 || e.keyCode == 46) {
// Delete or backspace.
// Stop the browser from going back to the previous page.
// Do this first to prevent an error in the delete code from resulting in
// data loss.
e.preventDefault();
if (Blockly.selected && Blockly.selected.isDeletable()) {
deleteBlock = true;
}
} else if (e.altKey || e.ctrlKey || e.metaKey) {
if (Blockly.selected &&
Blockly.selected.isDeletable() && Blockly.selected.isMovable()) {
if (e.keyCode == 67) {
// 'c' for copy.
Blockly.hideChaff();
Blockly.copy_(Blockly.selected);
} else if (e.keyCode == 88) {
// 'x' for cut.
Blockly.copy_(Blockly.selected);
deleteBlock = true;
}
}
if (e.keyCode == 86) {
// 'v' for paste.
if (Blockly.clipboardXml_) {
Blockly.Events.setGroup(true);
Blockly.clipboardSource_.paste(Blockly.clipboardXml_);
Blockly.Events.setGroup(false);
}
} else if (e.keyCode == 90) {
// 'z' for undo 'Z' is for redo.
Blockly.hideChaff();
Blockly.mainWorkspace.undo(e.shiftKey);
}
}
if (deleteBlock) {
// Common code for delete and cut.
Blockly.Events.setGroup(true);
Blockly.hideChaff();
var heal = Blockly.dragMode_ != Blockly.DRAG_FREE;
Blockly.selected.dispose(heal, true);
if (Blockly.highlightedConnection_) {
Blockly.highlightedConnection_.unhighlight();
Blockly.highlightedConnection_ = null;
}
Blockly.Events.setGroup(false);
}
};
/**
* Stop binding to the global mouseup and mousemove events.
* @private
*/
Blockly.terminateDrag_ = function() {
Blockly.BlockSvg.terminateDrag();
Blockly.Flyout.terminateDrag_();
};
/**
* PID of queued long-press task.
* @private
*/
Blockly.longPid_ = 0;
/**
* Context menus on touch devices are activated using a long-press.
* Unfortunately the contextmenu touch event is currently (2015) only suported
* by Chrome. This function is fired on any touchstart event, queues a task,
* which after about a second opens the context menu. The tasks is killed
* if the touch event terminates early.
* @param {!Event} e Touch start event.
* @param {!Blockly.Block|!Blockly.WorkspaceSvg} uiObject The block or workspace
* under the touchstart event.
* @private
*/
Blockly.longStart_ = function(e, uiObject) {
Blockly.longStop_();
Blockly.longPid_ = setTimeout(function() {
e.button = 2; // Simulate a right button click.
uiObject.onMouseDown_(e);
}, Blockly.LONGPRESS);
};
/**
* Nope, that's not a long-press. Either touchend or touchcancel was fired,
* or a drag hath begun. Kill the queued long-press task.
* @private
*/
Blockly.longStop_ = function() {
if (Blockly.longPid_) {
clearTimeout(Blockly.longPid_);
Blockly.longPid_ = 0;
}
};
/**
* Copy a block onto the local clipboard.
* @param {!Blockly.Block} block Block to be copied.
* @private
*/
Blockly.copy_ = function(block) {
var xmlBlock = Blockly.Xml.blockToDom(block);
if (Blockly.dragMode_ != Blockly.DRAG_FREE) {
Blockly.Xml.deleteNext(xmlBlock);
}
// Encode start position in XML.
var xy = block.getRelativeToSurfaceXY();
xmlBlock.setAttribute('x', block.RTL ? -xy.x : xy.x);
xmlBlock.setAttribute('y', xy.y);
Blockly.clipboardXml_ = xmlBlock;
Blockly.clipboardSource_ = block.workspace;
};
/**
* Duplicate this block and its children.
* @param {!Blockly.Block} block Block to be copied.
* @private
*/
Blockly.duplicate_ = function(block) {
// Save the clipboard.
var clipboardXml = Blockly.clipboardXml_;
var clipboardSource = Blockly.clipboardSource_;
// Create a duplicate via a copy/paste operation.
Blockly.copy_(block);
block.workspace.paste(Blockly.clipboardXml_);
// Restore the clipboard.
Blockly.clipboardXml_ = clipboardXml;
Blockly.clipboardSource_ = clipboardSource;
};
/**
* Cancel the native context menu, unless the focus is on an HTML input widget.
* @param {!Event} e Mouse down event.
* @private
*/
Blockly.onContextMenu_ = function(e) {
if (!Blockly.isTargetInput_(e)) {
// When focused on an HTML text input widget, don't cancel the context menu.
e.preventDefault();
}
};
/**
* Close tooltips, context menus, dropdown selections, etc.
* @param {boolean=} opt_allowToolbox If true, don't close the toolbox.
*/
Blockly.hideChaff = function(opt_allowToolbox) {
Blockly.Tooltip.hide();
Blockly.WidgetDiv.hide();
if (!opt_allowToolbox) {
var workspace = Blockly.getMainWorkspace();
if (workspace.toolbox_ &&
workspace.toolbox_.flyout_ &&
workspace.toolbox_.flyout_.autoClose) {
workspace.toolbox_.clearSelection();
}
}
};
/**
* Return an object with all the metrics required to size scrollbars for the
* main workspace. The following properties are computed:
* .viewHeight: Height of the visible rectangle,
* .viewWidth: Width of the visible rectangle,
* .contentHeight: Height of the contents,
* .contentWidth: Width of the content,
* .viewTop: Offset of top edge of visible rectangle from parent,
* .viewLeft: Offset of left edge of visible rectangle from parent,
* .contentTop: Offset of the top-most content from the y=0 coordinate,
* .contentLeft: Offset of the left-most content from the x=0 coordinate.
* .absoluteTop: Top-edge of view.
* .absoluteLeft: Left-edge of view.
* .toolboxWidth: Width of toolbox, if it exists. Otherwise zero.
* .toolboxHeight: Height of toolbox, if it exists. Otherwise zero.
* .flyoutWidth: Width of the flyout if it is always open. Otherwise zero.
* .flyoutHeight: Height of flyout if it is always open. Otherwise zero.
* .toolboxPosition: Top, bottom, left or right.
* @return {Object} Contains size and position metrics of main workspace.
* @private
* @this Blockly.WorkspaceSvg
*/
Blockly.getMainWorkspaceMetrics_ = function() {
var svgSize = Blockly.svgSize(this.getParentSvg());
if (this.toolbox_) {
if (this.toolboxPosition == Blockly.TOOLBOX_AT_TOP ||
this.toolboxPosition == Blockly.TOOLBOX_AT_BOTTOM) {
svgSize.height -= this.toolbox_.getHeight();
} else if (this.toolboxPosition == Blockly.TOOLBOX_AT_LEFT ||
this.toolboxPosition == Blockly.TOOLBOX_AT_RIGHT) {
svgSize.width -= this.toolbox_.getWidth();
}
}
// Set the margin to match the flyout's margin so that the workspace does
// not jump as blocks are added.
var MARGIN = Blockly.Flyout.prototype.CORNER_RADIUS - 1;
var viewWidth = svgSize.width - MARGIN;
var viewHeight = svgSize.height - MARGIN;
var blockBox = this.getBlocksBoundingBox();
// Fix scale.
var contentWidth = blockBox.width * this.scale;
var contentHeight = blockBox.height * this.scale;
var contentX = blockBox.x * this.scale;
var contentY = blockBox.y * this.scale;
if (this.scrollbar) {
// Add a border around the content that is at least half a screenful wide.
// Ensure border is wide enough that blocks can scroll over entire screen.
var leftEdge = Math.min(contentX - viewWidth / 2,
contentX + contentWidth - viewWidth);
var rightEdge = Math.max(contentX + contentWidth + viewWidth / 2,
contentX + viewWidth);
var topEdge = Math.min(contentY - viewHeight / 2,
contentY + contentHeight - viewHeight);
var bottomEdge = Math.max(contentY + contentHeight + viewHeight / 2,
contentY + viewHeight);
} else {
var leftEdge = blockBox.x;
var rightEdge = leftEdge + blockBox.width;
var topEdge = blockBox.y;
var bottomEdge = topEdge + blockBox.height;
}
var absoluteLeft = 0;
if (this.toolbox_ && this.toolboxPosition == Blockly.TOOLBOX_AT_LEFT) {
absoluteLeft = this.toolbox_.getWidth();
}
var absoluteTop = 0;
if (this.toolbox_ && this.toolboxPosition == Blockly.TOOLBOX_AT_TOP) {
absoluteTop = this.toolbox_.getHeight();
}
var metrics = {
viewHeight: svgSize.height,
viewWidth: svgSize.width,
contentHeight: bottomEdge - topEdge,
contentWidth: rightEdge - leftEdge,
viewTop: -this.scrollY,
viewLeft: -this.scrollX,
contentTop: topEdge,
contentLeft: leftEdge,
absoluteTop: absoluteTop,
absoluteLeft: absoluteLeft,
toolboxWidth: this.toolbox_ ? this.toolbox_.getWidth() : 0,
toolboxHeight: this.toolbox_ ? this.toolbox_.getHeight() : 0,
flyoutWidth: this.flyout_ ? this.flyout_.getWidth() : 0,
flyoutHeight: this.flyout_ ? this.flyout_.getHeight() : 0,
toolboxPosition: this.toolboxPosition
};
return metrics;
};
/**
* Sets the X/Y translations of the main workspace to match the scrollbars.
* @param {!Object} xyRatio Contains an x and/or y property which is a float
* between 0 and 1 specifying the degree of scrolling.
* @private
* @this Blockly.WorkspaceSvg
*/
Blockly.setMainWorkspaceMetrics_ = function(xyRatio) {
if (!this.scrollbar) {
throw 'Attempt to set main workspace scroll without scrollbars.';
}
var metrics = this.getMetrics();
if (goog.isNumber(xyRatio.x)) {
this.scrollX = -metrics.contentWidth * xyRatio.x - metrics.contentLeft;
}
if (goog.isNumber(xyRatio.y)) {
this.scrollY = -metrics.contentHeight * xyRatio.y - metrics.contentTop;
}
var x = this.scrollX + metrics.absoluteLeft;
var y = this.scrollY + metrics.absoluteTop;
this.translate(x, y);
if (this.options.gridPattern) {
this.options.gridPattern.setAttribute('x', x);
this.options.gridPattern.setAttribute('y', y);
if (goog.userAgent.IE) {
// IE doesn't notice that the x/y offsets have changed. Force an update.
this.updateGridPattern_();
}
}
};
/**
* When something in Blockly's workspace changes, call a function.
* @param {!Function} func Function to call.
* @return {!Array.<!Array>} Opaque data that can be passed to
* removeChangeListener.
* @deprecated April 2015
*/
Blockly.addChangeListener = function(func) {
// Backwards compatability from before there could be multiple workspaces.
console.warn('Deprecated call to Blockly.addChangeListener, ' +
'use workspace.addChangeListener instead.');
return Blockly.getMainWorkspace().addChangeListener(func);
};
/**
* Returns the main workspace. Returns the last used main workspace (based on
* focus). Try not to use this function, particularly if there are multiple
* Blockly instances on a page.
* @return {!Blockly.Workspace} The main workspace.
*/
Blockly.getMainWorkspace = function() {
return Blockly.mainWorkspace;
};
// IE9 does not have a console. Create a stub to stop errors.
if (!goog.global['console']) {
goog.global['console'] = {
'log': function() {},
'warn': function() {}
};
}
// Export symbols that would otherwise be renamed by Closure compiler.
if (!goog.global['Blockly']) {
goog.global['Blockly'] = {};
}
goog.global['Blockly']['getMainWorkspace'] = Blockly.getMainWorkspace;
goog.global['Blockly']['addChangeListener'] = Blockly.addChangeListener;
|
guimotoys/guimo_app
|
www/lib/blockly/core/blockly.js
|
JavaScript
|
gpl-3.0
| 18,440
|
(function () {
'use strict';
var components = angular.module('lavagna.components');
components.component('lvgCardModal', {
bindings: {
project: '=',
board: '=',
card: '=',
user: '='
},
controller: function($mdDialog, $state, $scope) {
var ctrl = this;
var goBack = function() {
$state.go('^');
};
$mdDialog.show({
controller: DialogController,
templateUrl: 'app/components/card-modal/card-modal.html',
parent: angular.element(document.body),
clickOutsideToClose: true,
fullscreen: true,
locals: {
project: ctrl.project,
board: ctrl.board,
card: ctrl.card,
user: ctrl.user
},
bindToController: true,
controllerAs: 'modalCtrl',
onRemoving: goBack
});
function DialogController($mdDialog) {
this.close = function() {
$mdDialog.cancel();
};
}
$scope.$on('$destroy', function() {
$mdDialog.cancel();
});
}
});
})();
|
velmuruganvelayutham/lavagna
|
src/main/webapp/app/components/card-modal/card-modal.js
|
JavaScript
|
gpl-3.0
| 1,277
|
$(document).ready(function () {
$("#elm_cnh_code").focus(function (e) {
$(".cnh-hint").fadeIn("slow");
$(".cnh-arrow").removeClass("hide");
$(".cnh-arrow").addClass("cnh");
$(".cnh-arrow").removeClass("validade");
$(".cnh-arrow2").addClass("hide");
});
$("#elm_cnh_validity").focus(function (e) {
$(".cnh-hint").fadeIn("slow");
$(".cnh-arrow").removeClass("hide");
$(".cnh-arrow").removeClass("cnh");
$(".cnh-arrow").addClass("validade");
$(".cnh-arrow2").addClass("hide");
});
$("#elm_first_driver_license").focus(function (e) {
$(".cnh-hint").fadeIn("slow");
$(".cnh-arrow").addClass("hide");
$(".cnh-arrow2").removeClass("hide");
$(".cnh-arrow2").addClass("data");
});
$("#elm_cnh_code,#elm_cnh_validity,#elm_first_driver_license").blur(function (e) {
$(".cnh-hint").fadeOut("fast");
});
});
|
eokoe/De-Olho-Nas-Metas
|
web/root/static/js/cadastro.js
|
JavaScript
|
gpl-3.0
| 947
|
module.exports = {
props: ['user', 'team', 'billableType'],
/**
* Load mixins for the component.
*/
mixins: [
require('./../mixins/discounts')
],
/**
* The componetn's data.
*/
data() {
return {
currentDiscount: null,
loadingCurrentDiscount: false
};
},
/**
* The component has been created by Vue.
*/
created() {
var self = this;
this.$on('updateDiscount', function(){
self.getCurrentDiscountForBillable(self.billableType, self.billable);
return true;
})
},
/**
* Prepare the component.
*/
mounted() {
this.getCurrentDiscountForBillable(this.billableType, this.billable);
},
};
|
expoteca/expoteca.com
|
spark/resources/assets/js/settings/payment-method-stripe.js
|
JavaScript
|
gpl-3.0
| 784
|
Ext
.define(
'Bloodbank.view.searchengine.search.SearchEngineMainPanelController',
{
extend : 'Ext.app.ViewController',
alias : 'controller.solrsearchcontroller',
recognizing : false,
recognition:null,
searchCommand : [],
afterRender : function() {
debugger;
me=this;
this.searchCommand.push("search");
this.searchCommand.push("find");
this.searchCommand.push("go");
searchCommand=this.searchCommand;
currentTab = this.getView();
// txtField=this.getView().down("#searchs");
var final_span = "";
var interim_span = "";
var final_transcript = '';
var ignore_onend;
var start_timestamp;
if (!('webkitSpeechRecognition' in window)) {
upgrade();
} else {
start_button = 'inline-block';
var recognition = new webkitSpeechRecognition();
this.recognition=recognition;
recognition.continuous = true;
recognition.interimResults = true;
recognition.onstart = function() {
// currentTab = Ext.MainAppMagr.getActiveTab();
recognizing = true;
currentTab.down("#voice").setIcon(
'images/mic-animate.gif');
};
recognition.onerror = function(event) {
// currentTab = Ext.MainAppMagr.getActiveTab();
if (event.error == 'no-speech') {
currentTab.down("#voice").setIcon(
'images/mic.gif');
alert("No speech was detected. You may need to adjust your microphone");
ignore_onend = true;
}
if (event.error == 'audio-capture') {
currentTab.down("#voice").setIcon(
'images/mic.gif');
alert("No microphone was found. Ensure that a microphone is installed");
ignore_onend = true;
}
if (event.error == 'not-allowed') {
if (event.timeStamp - start_timestamp < 100) {
alert("Permission to use microphone is blocked.");
} else {
alert("Permission to use microphone was denied.");
}
ignore_onend = true;
}
};
recognition.onend = function() {
// currentTab = Ext.MainAppMagr.getActiveTab();
recognizing = false;
if (ignore_onend) {
return;
}
currentTab.down("#voice").setIcon(
'images/mic.gif');
if (!final_transcript) {
return;
}
//showInfo('');
if (window.getSelection) {
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(document
.getElementById('final_span'));
window.getSelection().addRange(range);
}
};
recognition.onresult = function(event) {
// currentTab = Ext.MainAppMagr.getActiveTab();
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript = event.results[i][0].transcript;
} else {
interim_transcript += event.results[i][0].transcript;
}
}
var isSearchCommand = false;
var inputWords = final_transcript.split(' ');
for (var k = 0; k < inputWords.length; k++) {
if (searchCommand.indexOf(inputWords[k]) != -1) {
isSearchCommand = true;
final_transcript = final_transcript
.replace(inputWords[k], '');
}
}
currentTab.down('#searchs').setValue(
final_transcript);
if (isSearchCommand) {
me.onSolrSearchClick();
}
if (recognizing) {
recognition.stop();
return;
}
if (final_transcript || interim_transcript) {
showButtons('inline-block');
}
};
}
},
onSolrSearchClick : function(me) {
debugger;
var myView = this.view;
var searchText = myView.down('#searchs').value;
var oprationType = myView.down('#Lang').value;
var statusPanel = myView.down('#stat');
Ext.MessageBox.show({
msg : 'Retrieving data...',
progressText : 'Retrieving...',
width : 300,
wait : true,
waitConfig : {
interval : 200
}
});
Ext.Ajax.setTimeout(160000);
Ext.Ajax
.request({
url : 'secure/SearchEngineController/getSearchResult?searchString='
+ encodeURIComponent(searchText)
+ "&oprationType=" + oprationType,
method : 'GET',
timeout : 1600000,
waitMsg : 'Retriving data...',
success : function(response) {
debugger;
/*
* jsonResult = myView.down("#results");
* jsonResult.update("Result tab");
*/
isHide = false;
result = Ext.JSON
.decode(response.responseText);
doUMeanPanel = myView
.down("#doUMeanPanel");
doUMeanPanel.removeAll();
doumeanarray = result.doUMean;
if (doumeanarray.length > 0) {
doUMeanPanel.show();
doUMeanPanel.add(doumeanarray);
} else {
doUMeanPanel.hide();// =true;
isHide = true;
}
graphView = myView.down("#table");
documentGrid = myView
.down("#documentView");
mainDocumentPanel = myView
.down("#mainDocumentPanel");
graphView.removeAll(true);
if (result.hasOwnProperty("graphData")
&& result.graphData.length > 0) {
debugger;
graphView.add(result.graphData);
graphView.doLayout();
}
if (result.hasOwnProperty("documents")
&& result.documents.length > 0) {
/*
* documentGrid.store
* .loadData(result.documents);
*/
documentGrid.store.getProxy()
.setData(result.documents);
documentGrid.store.read();
documentGrid.ALLDATA = result.documents;
/*
* pager=documentGrid.query('pagingtoolbar')[0];
* pager.bindStore(documentGrid.store);
* documentGrid.reconfigure(documentGrid.store);
* documentGrid.store.loadPage(1);
*/
/*
* pagging.store =
* documentGrid.store;
*
*/
mainDocumentPanel.expand();
} else {
var k = [];
documentGrid.store.loadData(k);
if (isHide)
mainDocumentPanel.collapse();
else
mainDocumentPanel.expand();
}
/*
* resultPanel=myView.down("#resultsTab");
* resultPanel.dockedItems.items[0].query("label")[0].setText(result.status);
*/
statusPanel.body
.update("<font size ='2' color='#808080'>"
+ result.status
+ "</font>");
Ext.MessageBox.hide();
},
failure : function() {
Ext.Msg.alert("Request Failed",
"Request Failed");
}
});
},
onVoiceSearch : function recognizeVoice(me) {
currentScope = me;
recognizing=this.recognizing;
recognition=this.recognition;
if (recognizing) {
recognition.stop();
return;
}
recognition.start();
ignore_onend = false;
this.getView().down("#voice").setIcon(
'images/mic-slash.gif');
showButtons('none');
start_timestamp = event.timeStamp;
function showInfo(s) {
if (s) {
for (var child = info.firstChild; child; child = child.nextSibling) {
if (child.style) {
child = child.id == s ? 'inline'
: 'none';
}
}
info = 'visible';
} else {
info = 'hidden';
}
}
var current_style;
function showButtons(style) {
if (style == current_style) {
return;
}
current_style = style;
}
},
onPanelCollapse : function(me) {
var defaultWidthToReduce = 20;
var defaultHeightToReduce = 0;
debugger;
resultPanel = me.up();
mainPanel = resultPanel.query("[title=Graph Data]")[0];
var Value = resultPanel.down("panelheaderfield").value;
newColumns = parseInt(Value);
totalWidth = (mainPanel.getWidth())
- (defaultWidthToReduce + (newColumns * 5));
calculateWidthPerChart=(totalWidth)/ newColumns;
for (var i = 0; i < mainPanel.items.length; i++) {
var currentPanel = mainPanel.items.items[i];
if(currentPanel.items.length==1 && currentPanel.items.items[0].hasOwnProperty("group") && currentPanel.items.items[0].group==true)
{
debugger
groupPanel=currentPanel.items.items[0];
lengthOfChildPanel=groupPanel.items.length;
for (var j = 0; j < lengthOfChildPanel; j++) {
var childGroupPanel = groupPanel.items.items[j];
childGroupPanel
.setWidth(calculateWidthPerChart/lengthOfChildPanel);
}
}
/*else{
currentPanel
.setWidth(calculateWidthPerChart);
}*/
groupPanel
.setWidth(calculateWidthPerChart);
currentPanel
.setWidth(calculateWidthPerChart);
}
try {
for ( var k in FusionCharts.items) {
fusionObj = FusionCharts.items[k];
var panelbodyId = fusionObj.options.containerElementId;
var curentPanel=mainPanel.down('#'+ panelbodyId.substring(0, panelbodyId.indexOf('-body')));
if (curentPanel != null) {
pPanel=curentPanel.up();
mainCalaculatedWidth=(totalWidth)/ newColumns;
if(pPanel.hasOwnProperty("group") && pPanel.group==true)
{
totalColumnsForMultiChart=pPanel.layout.columns;
groupedCalculatedWidht=mainCalaculatedWidth/totalColumnsForMultiChart;
fusionObj.resizeTo(groupedCalculatedWidht-10);
}
else{
fusionObj.resizeTo(mainCalaculatedWidth-10);
}
}
}
} catch (ex) {
}
mainPanel.setWidth(totalWidth);
googleMapPanel=mainPanel.query("mapPanel");
if(googleMapPanel!=null && googleMapPanel.length>0)
{
for(gCount=0;gCount<googleMapPanel.length;gCount++)
{
currentGoogleMapPanel=googleMapPanel[gCount];
currentGoogleMapPanel.controller.resizeMap();
}
}
debugger;
/*for (var i = 0; i < mainPanel.items.length; i++) {
var currentPanel = mainPanel.items.items[i];
currentPanel.setWidth((totalWidth / newColumns));
}
try {
for ( var k in FusionCharts.items) {
fusionObj = FusionCharts.items[k];
var panelbodyId = fusionObj.options.containerElementId;
if (mainPanel.down('#'
+ panelbodyId.substring(0, panelbodyId
.indexOf('-body'))) != null) {
fusionObj.resizeTo((totalWidth)
/ newColumns);
}
}
} catch (ex) {
}
debugger;
mainPanel.setWidth(totalWidth);*/
}
});
|
applifireAlgo/bloodbank
|
bloodbank/src/main/webapp/app/view/searchengine/search/SearchEngineMainPanelController.js
|
JavaScript
|
gpl-3.0
| 11,390
|
// Karma configuration
// Generated on Tue Aug 18 2015 09:02:09 GMT+0100 (GMT Daylight Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'lib/*.js',
'src/*.js',
'test/*.test.js'
],
// list of files to exclude
exclude: [
'src/startContentProcessor.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
|
Softwire/Workflowy2Web
|
karma.conf.js
|
JavaScript
|
gpl-3.0
| 1,659
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
import type { ThunkArgs } from "./types";
export function setExpandedState(expanded) {
return ({ dispatch, getState }: ThunkArgs) => {
dispatch({
type: "SET_EXPANDED_STATE",
expanded
});
};
}
|
amitzur/debugger.html
|
src/actions/source-tree.js
|
JavaScript
|
mpl-2.0
| 425
|
/*global self*/
/*jshint latedef: nofunc*/
/*
Distributed under both the W3C Test Suite License [1] and the W3C
3-clause BSD License [2]. To contribute to a W3C Test Suite, see the
policies and contribution forms [3].
[1] http://www.w3.org/Consortium/Legal/2008/04-testsuite-license
[2] http://www.w3.org/Consortium/Legal/2008/03-bsd-license
[3] http://www.w3.org/2004/10/27-testcases
*/
/* Documentation: http://web-platform-tests.org/writing-tests/testharness-api.html
* (../docs/_writing-tests/testharness-api.md) */
(function ()
{
var debug = false;
// default timeout is 10 seconds, test can override if needed
var settings = {
output:true,
harness_timeout:{
"normal":10000,
"long":60000
},
test_timeout:null,
message_events: ["start", "test_state", "result", "completion"]
};
var xhtml_ns = "http://www.w3.org/1999/xhtml";
/*
* TestEnvironment is an abstraction for the environment in which the test
* harness is used. Each implementation of a test environment has to provide
* the following interface:
*
* interface TestEnvironment {
* // Invoked after the global 'tests' object has been created and it's
* // safe to call add_*_callback() to register event handlers.
* void on_tests_ready();
*
* // Invoked after setup() has been called to notify the test environment
* // of changes to the test harness properties.
* void on_new_harness_properties(object properties);
*
* // Should return a new unique default test name.
* DOMString next_default_test_name();
*
* // Should return the test harness timeout duration in milliseconds.
* float test_timeout();
*
* // Should return the global scope object.
* object global_scope();
* };
*/
/*
* A test environment with a DOM. The global object is 'window'. By default
* test results are displayed in a table. Any parent windows receive
* callbacks or messages via postMessage() when test events occur. See
* apisample11.html and apisample12.html.
*/
function WindowTestEnvironment() {
this.name_counter = 0;
this.window_cache = null;
this.output_handler = null;
this.all_loaded = false;
var this_obj = this;
this.message_events = [];
this.dispatched_messages = [];
this.message_functions = {
start: [add_start_callback, remove_start_callback,
function (properties) {
this_obj._dispatch("start_callback", [properties],
{type: "start", properties: properties});
}],
test_state: [add_test_state_callback, remove_test_state_callback,
function(test) {
this_obj._dispatch("test_state_callback", [test],
{type: "test_state",
test: test.structured_clone()});
}],
result: [add_result_callback, remove_result_callback,
function (test) {
this_obj.output_handler.show_status();
this_obj._dispatch("result_callback", [test],
{type: "result",
test: test.structured_clone()});
}],
completion: [add_completion_callback, remove_completion_callback,
function (tests, harness_status) {
var cloned_tests = map(tests, function(test) {
return test.structured_clone();
});
this_obj._dispatch("completion_callback", [tests, harness_status],
{type: "complete",
tests: cloned_tests,
status: harness_status.structured_clone()});
}]
}
on_event(window, 'load', function() {
this_obj.all_loaded = true;
});
on_event(window, 'message', function(event) {
if (event.data && event.data.type === "getmessages" && event.source) {
// A window can post "getmessages" to receive a duplicate of every
// message posted by this environment so far. This allows subscribers
// from fetch_tests_from_window to 'catch up' to the current state of
// this environment.
for (var i = 0; i < this_obj.dispatched_messages.length; ++i)
{
event.source.postMessage(this_obj.dispatched_messages[i], "*");
}
}
});
}
WindowTestEnvironment.prototype._dispatch = function(selector, callback_args, message_arg) {
this.dispatched_messages.push(message_arg);
this._forEach_windows(
function(w, same_origin) {
if (same_origin) {
try {
var has_selector = selector in w;
} catch(e) {
// If document.domain was set at some point same_origin can be
// wrong and the above will fail.
has_selector = false;
}
if (has_selector) {
try {
w[selector].apply(undefined, callback_args);
} catch (e) {
if (debug) {
throw e;
}
}
}
}
if (supports_post_message(w) && w !== self) {
w.postMessage(message_arg, "*");
}
});
};
WindowTestEnvironment.prototype._forEach_windows = function(callback) {
// Iterate of the the windows [self ... top, opener]. The callback is passed
// two objects, the first one is the windows object itself, the second one
// is a boolean indicating whether or not its on the same origin as the
// current window.
var cache = this.window_cache;
if (!cache) {
cache = [[self, true]];
var w = self;
var i = 0;
var so;
while (w != w.parent) {
w = w.parent;
so = is_same_origin(w);
cache.push([w, so]);
i++;
}
w = window.opener;
if (w) {
cache.push([w, is_same_origin(w)]);
}
this.window_cache = cache;
}
forEach(cache,
function(a) {
callback.apply(null, a);
});
};
WindowTestEnvironment.prototype.on_tests_ready = function() {
var output = new Output();
this.output_handler = output;
var this_obj = this;
add_start_callback(function (properties) {
this_obj.output_handler.init(properties);
});
add_test_state_callback(function(test) {
this_obj.output_handler.show_status();
});
add_result_callback(function (test) {
this_obj.output_handler.show_status();
});
add_completion_callback(function (tests, harness_status) {
this_obj.output_handler.show_results(tests, harness_status);
});
this.setup_messages(settings.message_events);
};
WindowTestEnvironment.prototype.setup_messages = function(new_events) {
var this_obj = this;
forEach(settings.message_events, function(x) {
var current_dispatch = this_obj.message_events.indexOf(x) !== -1;
var new_dispatch = new_events.indexOf(x) !== -1;
if (!current_dispatch && new_dispatch) {
this_obj.message_functions[x][0](this_obj.message_functions[x][2]);
} else if (current_dispatch && !new_dispatch) {
this_obj.message_functions[x][1](this_obj.message_functions[x][2]);
}
});
this.message_events = new_events;
}
WindowTestEnvironment.prototype.next_default_test_name = function() {
//Don't use document.title to work around an Opera bug in XHTML documents
var title = document.getElementsByTagName("title")[0];
var prefix = (title && title.firstChild && title.firstChild.data) || "Untitled";
var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
this.name_counter++;
return prefix + suffix;
};
WindowTestEnvironment.prototype.on_new_harness_properties = function(properties) {
this.output_handler.setup(properties);
if (properties.hasOwnProperty("message_events")) {
this.setup_messages(properties.message_events);
}
};
WindowTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
on_event(window, 'load', callback);
};
WindowTestEnvironment.prototype.test_timeout = function() {
var metas = document.getElementsByTagName("meta");
for (var i = 0; i < metas.length; i++) {
if (metas[i].name == "timeout") {
if (metas[i].content == "long") {
return settings.harness_timeout.long;
}
break;
}
}
return settings.harness_timeout.normal;
};
WindowTestEnvironment.prototype.global_scope = function() {
return window;
};
/*
* Base TestEnvironment implementation for a generic web worker.
*
* Workers accumulate test results. One or more clients can connect and
* retrieve results from a worker at any time.
*
* WorkerTestEnvironment supports communicating with a client via a
* MessagePort. The mechanism for determining the appropriate MessagePort
* for communicating with a client depends on the type of worker and is
* implemented by the various specializations of WorkerTestEnvironment
* below.
*
* A client document using testharness can use fetch_tests_from_worker() to
* retrieve results from a worker. See apisample16.html.
*/
function WorkerTestEnvironment() {
this.name_counter = 0;
this.all_loaded = true;
this.message_list = [];
this.message_ports = [];
}
WorkerTestEnvironment.prototype._dispatch = function(message) {
this.message_list.push(message);
for (var i = 0; i < this.message_ports.length; ++i)
{
this.message_ports[i].postMessage(message);
}
};
// The only requirement is that port has a postMessage() method. It doesn't
// have to be an instance of a MessagePort, and often isn't.
WorkerTestEnvironment.prototype._add_message_port = function(port) {
this.message_ports.push(port);
for (var i = 0; i < this.message_list.length; ++i)
{
port.postMessage(this.message_list[i]);
}
};
WorkerTestEnvironment.prototype.next_default_test_name = function() {
var suffix = this.name_counter > 0 ? " " + this.name_counter : "";
this.name_counter++;
return "Untitled" + suffix;
};
WorkerTestEnvironment.prototype.on_new_harness_properties = function() {};
WorkerTestEnvironment.prototype.on_tests_ready = function() {
var this_obj = this;
add_start_callback(
function(properties) {
this_obj._dispatch({
type: "start",
properties: properties,
});
});
add_test_state_callback(
function(test) {
this_obj._dispatch({
type: "test_state",
test: test.structured_clone()
});
});
add_result_callback(
function(test) {
this_obj._dispatch({
type: "result",
test: test.structured_clone()
});
});
add_completion_callback(
function(tests, harness_status) {
this_obj._dispatch({
type: "complete",
tests: map(tests,
function(test) {
return test.structured_clone();
}),
status: harness_status.structured_clone()
});
});
};
WorkerTestEnvironment.prototype.add_on_loaded_callback = function() {};
WorkerTestEnvironment.prototype.test_timeout = function() {
// Tests running in a worker don't have a default timeout. I.e. all
// worker tests behave as if settings.explicit_timeout is true.
return null;
};
WorkerTestEnvironment.prototype.global_scope = function() {
return self;
};
/*
* Dedicated web workers.
* https://html.spec.whatwg.org/multipage/workers.html#dedicatedworkerglobalscope
*
* This class is used as the test_environment when testharness is running
* inside a dedicated worker.
*/
function DedicatedWorkerTestEnvironment() {
WorkerTestEnvironment.call(this);
// self is an instance of DedicatedWorkerGlobalScope which exposes
// a postMessage() method for communicating via the message channel
// established when the worker is created.
this._add_message_port(self);
}
DedicatedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
DedicatedWorkerTestEnvironment.prototype.on_tests_ready = function() {
WorkerTestEnvironment.prototype.on_tests_ready.call(this);
// In the absence of an onload notification, we a require dedicated
// workers to explicitly signal when the tests are done.
tests.wait_for_finish = true;
};
/*
* Shared web workers.
* https://html.spec.whatwg.org/multipage/workers.html#sharedworkerglobalscope
*
* This class is used as the test_environment when testharness is running
* inside a shared web worker.
*/
function SharedWorkerTestEnvironment() {
WorkerTestEnvironment.call(this);
var this_obj = this;
// Shared workers receive message ports via the 'onconnect' event for
// each connection.
self.addEventListener("connect",
function(message_event) {
this_obj._add_message_port(message_event.source);
}, false);
}
SharedWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
SharedWorkerTestEnvironment.prototype.on_tests_ready = function() {
WorkerTestEnvironment.prototype.on_tests_ready.call(this);
// In the absence of an onload notification, we a require shared
// workers to explicitly signal when the tests are done.
tests.wait_for_finish = true;
};
/*
* Service workers.
* http://www.w3.org/TR/service-workers/
*
* This class is used as the test_environment when testharness is running
* inside a service worker.
*/
function ServiceWorkerTestEnvironment() {
WorkerTestEnvironment.call(this);
this.all_loaded = false;
this.on_loaded_callback = null;
var this_obj = this;
self.addEventListener("message",
function(event) {
if (event.data && event.data.type && event.data.type === "connect") {
if (event.ports && event.ports[0]) {
// If a MessageChannel was passed, then use it to
// send results back to the main window. This
// allows the tests to work even if the browser
// does not fully support MessageEvent.source in
// ServiceWorkers yet.
this_obj._add_message_port(event.ports[0]);
event.ports[0].start();
} else {
// If there is no MessageChannel, then attempt to
// use the MessageEvent.source to send results
// back to the main window.
this_obj._add_message_port(event.source);
}
}
}, false);
// The oninstall event is received after the service worker script and
// all imported scripts have been fetched and executed. It's the
// equivalent of an onload event for a document. All tests should have
// been added by the time this event is received, thus it's not
// necessary to wait until the onactivate event.
on_event(self, "install",
function(event) {
this_obj.all_loaded = true;
if (this_obj.on_loaded_callback) {
this_obj.on_loaded_callback();
}
});
}
ServiceWorkerTestEnvironment.prototype = Object.create(WorkerTestEnvironment.prototype);
ServiceWorkerTestEnvironment.prototype.add_on_loaded_callback = function(callback) {
if (this.all_loaded) {
callback();
} else {
this.on_loaded_callback = callback;
}
};
function create_test_environment() {
if ('document' in self) {
return new WindowTestEnvironment();
}
if ('DedicatedWorkerGlobalScope' in self &&
self instanceof DedicatedWorkerGlobalScope) {
return new DedicatedWorkerTestEnvironment();
}
if ('SharedWorkerGlobalScope' in self &&
self instanceof SharedWorkerGlobalScope) {
return new SharedWorkerTestEnvironment();
}
if ('ServiceWorkerGlobalScope' in self &&
self instanceof ServiceWorkerGlobalScope) {
return new ServiceWorkerTestEnvironment();
}
if ('WorkerGlobalScope' in self &&
self instanceof WorkerGlobalScope) {
return new DedicatedWorkerTestEnvironment();
}
throw new Error("Unsupported test environment");
}
var test_environment = create_test_environment();
function is_shared_worker(worker) {
return 'SharedWorker' in self && worker instanceof SharedWorker;
}
function is_service_worker(worker) {
// The worker object may be from another execution context,
// so do not use instanceof here.
return 'ServiceWorker' in self &&
Object.prototype.toString.call(worker) == '[object ServiceWorker]';
}
/*
* API functions
*/
function test(func, name, properties)
{
var test_name = name ? name : test_environment.next_default_test_name();
properties = properties ? properties : {};
var test_obj = new Test(test_name, properties);
test_obj.step(func, test_obj, test_obj);
if (test_obj.phase === test_obj.phases.STARTED) {
test_obj.done();
}
}
function async_test(func, name, properties)
{
if (typeof func !== "function") {
properties = name;
name = func;
func = null;
}
var test_name = name ? name : test_environment.next_default_test_name();
properties = properties ? properties : {};
var test_obj = new Test(test_name, properties);
if (func) {
test_obj.step(func, test_obj, test_obj);
}
return test_obj;
}
function promise_test(func, name, properties) {
var test = async_test(name, properties);
// If there is no promise tests queue make one.
if (!tests.promise_tests) {
tests.promise_tests = Promise.resolve();
}
tests.promise_tests = tests.promise_tests.then(function() {
var donePromise = new Promise(function(resolve) {
test.add_cleanup(resolve);
});
var promise = test.step(func, test, test);
test.step(function() {
assert_not_equals(promise, undefined);
});
Promise.resolve(promise).then(
function() {
test.done();
})
.catch(test.step_func(
function(value) {
if (value instanceof AssertionError) {
throw value;
}
assert(false, "promise_test", null,
"Unhandled rejection with value: ${value}", {value:value});
}));
return donePromise;
});
}
function promise_rejects(test, expected, promise, description) {
return promise.then(test.unreached_func("Should have rejected: " + description)).catch(function(e) {
assert_throws(expected, function() { throw e }, description);
});
}
/**
* This constructor helper allows DOM events to be handled using Promises,
* which can make it a lot easier to test a very specific series of events,
* including ensuring that unexpected events are not fired at any point.
*/
function EventWatcher(test, watchedNode, eventTypes)
{
if (typeof eventTypes == 'string') {
eventTypes = [eventTypes];
}
var waitingFor = null;
var eventHandler = test.step_func(function(evt) {
assert_true(!!waitingFor,
'Not expecting event, but got ' + evt.type + ' event');
assert_equals(evt.type, waitingFor.types[0],
'Expected ' + waitingFor.types[0] + ' event, but got ' +
evt.type + ' event instead');
if (waitingFor.types.length > 1) {
// Pop first event from array
waitingFor.types.shift();
return;
}
// We need to null out waitingFor before calling the resolve function
// since the Promise's resolve handlers may call wait_for() which will
// need to set waitingFor.
var resolveFunc = waitingFor.resolve;
waitingFor = null;
resolveFunc(evt);
});
for (var i = 0; i < eventTypes.length; i++) {
watchedNode.addEventListener(eventTypes[i], eventHandler, false);
}
/**
* Returns a Promise that will resolve after the specified event or
* series of events has occured.
*/
this.wait_for = function(types) {
if (waitingFor) {
return Promise.reject('Already waiting for an event or events');
}
if (typeof types == 'string') {
types = [types];
}
return new Promise(function(resolve, reject) {
waitingFor = {
types: types,
resolve: resolve,
reject: reject
};
});
};
function stop_watching() {
for (var i = 0; i < eventTypes.length; i++) {
watchedNode.removeEventListener(eventTypes[i], eventHandler, false);
}
};
test.add_cleanup(stop_watching);
return this;
}
expose(EventWatcher, 'EventWatcher');
function setup(func_or_properties, maybe_properties)
{
var func = null;
var properties = {};
if (arguments.length === 2) {
func = func_or_properties;
properties = maybe_properties;
} else if (func_or_properties instanceof Function) {
func = func_or_properties;
} else {
properties = func_or_properties;
}
tests.setup(func, properties);
test_environment.on_new_harness_properties(properties);
}
function done() {
if (tests.tests.length === 0) {
tests.set_file_is_test();
}
if (tests.file_is_test) {
tests.tests[0].done();
}
tests.end_wait();
}
function generate_tests(func, args, properties) {
forEach(args, function(x, i)
{
var name = x[0];
test(function()
{
func.apply(this, x.slice(1));
},
name,
Array.isArray(properties) ? properties[i] : properties);
});
}
function on_event(object, event, callback)
{
object.addEventListener(event, callback, false);
}
function step_timeout(f, t) {
var outer_this = this;
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(function() {
f.apply(outer_this, args);
}, t * tests.timeout_multiplier);
}
expose(test, 'test');
expose(async_test, 'async_test');
expose(promise_test, 'promise_test');
expose(promise_rejects, 'promise_rejects');
expose(generate_tests, 'generate_tests');
expose(setup, 'setup');
expose(done, 'done');
expose(on_event, 'on_event');
expose(step_timeout, 'step_timeout');
/*
* Return a string truncated to the given length, with ... added at the end
* if it was longer.
*/
function truncate(s, len)
{
if (s.length > len) {
return s.substring(0, len - 3) + "...";
}
return s;
}
/*
* Return true if object is probably a Node object.
*/
function is_node(object)
{
// I use duck-typing instead of instanceof, because
// instanceof doesn't work if the node is from another window (like an
// iframe's contentWindow):
// http://www.w3.org/Bugs/Public/show_bug.cgi?id=12295
try {
var has_node_properties = ("nodeType" in object &&
"nodeName" in object &&
"nodeValue" in object &&
"childNodes" in object);
} catch (e) {
// We're probably cross-origin, which means we aren't a node
return false;
}
if (has_node_properties) {
try {
object.nodeType;
} catch (e) {
// The object is probably Node.prototype or another prototype
// object that inherits from it, and not a Node instance.
return false;
}
return true;
}
return false;
}
var replacements = {
"0": "0",
"1": "x01",
"2": "x02",
"3": "x03",
"4": "x04",
"5": "x05",
"6": "x06",
"7": "x07",
"8": "b",
"9": "t",
"10": "n",
"11": "v",
"12": "f",
"13": "r",
"14": "x0e",
"15": "x0f",
"16": "x10",
"17": "x11",
"18": "x12",
"19": "x13",
"20": "x14",
"21": "x15",
"22": "x16",
"23": "x17",
"24": "x18",
"25": "x19",
"26": "x1a",
"27": "x1b",
"28": "x1c",
"29": "x1d",
"30": "x1e",
"31": "x1f",
"0xfffd": "ufffd",
"0xfffe": "ufffe",
"0xffff": "uffff",
};
/*
* Convert a value to a nice, human-readable string
*/
function format_value(val, seen)
{
if (!seen) {
seen = [];
}
if (typeof val === "object" && val !== null) {
if (seen.indexOf(val) >= 0) {
return "[...]";
}
seen.push(val);
}
if (Array.isArray(val)) {
return "[" + val.map(function(x) {return format_value(x, seen);}).join(", ") + "]";
}
switch (typeof val) {
case "string":
val = val.replace("\\", "\\\\");
for (var p in replacements) {
var replace = "\\" + replacements[p];
val = val.replace(RegExp(String.fromCharCode(p), "g"), replace);
}
return '"' + val.replace(/"/g, '\\"') + '"';
case "boolean":
case "undefined":
return String(val);
case "number":
// In JavaScript, -0 === 0 and String(-0) == "0", so we have to
// special-case.
if (val === -0 && 1/val === -Infinity) {
return "-0";
}
return String(val);
case "object":
if (val === null) {
return "null";
}
// Special-case Node objects, since those come up a lot in my tests. I
// ignore namespaces.
if (is_node(val)) {
switch (val.nodeType) {
case Node.ELEMENT_NODE:
var ret = "<" + val.localName;
for (var i = 0; i < val.attributes.length; i++) {
ret += " " + val.attributes[i].name + '="' + val.attributes[i].value + '"';
}
ret += ">" + val.innerHTML + "</" + val.localName + ">";
return "Element node " + truncate(ret, 60);
case Node.TEXT_NODE:
return 'Text node "' + truncate(val.data, 60) + '"';
case Node.PROCESSING_INSTRUCTION_NODE:
return "ProcessingInstruction node with target " + format_value(truncate(val.target, 60)) + " and data " + format_value(truncate(val.data, 60));
case Node.COMMENT_NODE:
return "Comment node <!--" + truncate(val.data, 60) + "-->";
case Node.DOCUMENT_NODE:
return "Document node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
case Node.DOCUMENT_TYPE_NODE:
return "DocumentType node";
case Node.DOCUMENT_FRAGMENT_NODE:
return "DocumentFragment node with " + val.childNodes.length + (val.childNodes.length == 1 ? " child" : " children");
default:
return "Node object of unknown type";
}
}
/* falls through */
default:
try {
return typeof val + ' "' + truncate(String(val), 1000) + '"';
} catch(e) {
return ("[stringifying object threw " + String(e) +
" with type " + String(typeof e) + "]");
}
}
}
expose(format_value, "format_value");
/*
* Assertions
*/
function assert_true(actual, description)
{
assert(actual === true, "assert_true", description,
"expected true got ${actual}", {actual:actual});
}
expose(assert_true, "assert_true");
function assert_false(actual, description)
{
assert(actual === false, "assert_false", description,
"expected false got ${actual}", {actual:actual});
}
expose(assert_false, "assert_false");
function same_value(x, y) {
if (y !== y) {
//NaN case
return x !== x;
}
if (x === 0 && y === 0) {
//Distinguish +0 and -0
return 1/x === 1/y;
}
return x === y;
}
function assert_equals(actual, expected, description)
{
/*
* Test if two primitives are equal or two objects
* are the same object
*/
if (typeof actual != typeof expected) {
assert(false, "assert_equals", description,
"expected (" + typeof expected + ") ${expected} but got (" + typeof actual + ") ${actual}",
{expected:expected, actual:actual});
return;
}
assert(same_value(actual, expected), "assert_equals", description,
"expected ${expected} but got ${actual}",
{expected:expected, actual:actual});
}
expose(assert_equals, "assert_equals");
function assert_not_equals(actual, expected, description)
{
/*
* Test if two primitives are unequal or two objects
* are different objects
*/
assert(!same_value(actual, expected), "assert_not_equals", description,
"got disallowed value ${actual}",
{actual:actual});
}
expose(assert_not_equals, "assert_not_equals");
function assert_in_array(actual, expected, description)
{
assert(expected.indexOf(actual) != -1, "assert_in_array", description,
"value ${actual} not in array ${expected}",
{actual:actual, expected:expected});
}
expose(assert_in_array, "assert_in_array");
function assert_object_equals(actual, expected, description)
{
//This needs to be improved a great deal
function check_equal(actual, expected, stack)
{
stack.push(actual);
var p;
for (p in actual) {
assert(expected.hasOwnProperty(p), "assert_object_equals", description,
"unexpected property ${p}", {p:p});
if (typeof actual[p] === "object" && actual[p] !== null) {
if (stack.indexOf(actual[p]) === -1) {
check_equal(actual[p], expected[p], stack);
}
} else {
assert(same_value(actual[p], expected[p]), "assert_object_equals", description,
"property ${p} expected ${expected} got ${actual}",
{p:p, expected:expected, actual:actual});
}
}
for (p in expected) {
assert(actual.hasOwnProperty(p),
"assert_object_equals", description,
"expected property ${p} missing", {p:p});
}
stack.pop();
}
check_equal(actual, expected, []);
}
expose(assert_object_equals, "assert_object_equals");
function assert_array_equals(actual, expected, description)
{
assert(actual.length === expected.length,
"assert_array_equals", description,
"lengths differ, expected ${expected} got ${actual}",
{expected:expected.length, actual:actual.length});
for (var i = 0; i < actual.length; i++) {
assert(actual.hasOwnProperty(i) === expected.hasOwnProperty(i),
"assert_array_equals", description,
"property ${i}, property expected to be ${expected} but was ${actual}",
{i:i, expected:expected.hasOwnProperty(i) ? "present" : "missing",
actual:actual.hasOwnProperty(i) ? "present" : "missing"});
assert(same_value(expected[i], actual[i]),
"assert_array_equals", description,
"property ${i}, expected ${expected} but got ${actual}",
{i:i, expected:expected[i], actual:actual[i]});
}
}
expose(assert_array_equals, "assert_array_equals");
function assert_approx_equals(actual, expected, epsilon, description)
{
/*
* Test if two primitive numbers are equal withing +/- epsilon
*/
assert(typeof actual === "number",
"assert_approx_equals", description,
"expected a number but got a ${type_actual}",
{type_actual:typeof actual});
assert(Math.abs(actual - expected) <= epsilon,
"assert_approx_equals", description,
"expected ${expected} +/- ${epsilon} but got ${actual}",
{expected:expected, actual:actual, epsilon:epsilon});
}
expose(assert_approx_equals, "assert_approx_equals");
function assert_less_than(actual, expected, description)
{
/*
* Test if a primitive number is less than another
*/
assert(typeof actual === "number",
"assert_less_than", description,
"expected a number but got a ${type_actual}",
{type_actual:typeof actual});
assert(actual < expected,
"assert_less_than", description,
"expected a number less than ${expected} but got ${actual}",
{expected:expected, actual:actual});
}
expose(assert_less_than, "assert_less_than");
function assert_greater_than(actual, expected, description)
{
/*
* Test if a primitive number is greater than another
*/
assert(typeof actual === "number",
"assert_greater_than", description,
"expected a number but got a ${type_actual}",
{type_actual:typeof actual});
assert(actual > expected,
"assert_greater_than", description,
"expected a number greater than ${expected} but got ${actual}",
{expected:expected, actual:actual});
}
expose(assert_greater_than, "assert_greater_than");
function assert_between_exclusive(actual, lower, upper, description)
{
/*
* Test if a primitive number is between two others
*/
assert(typeof actual === "number",
"assert_between_exclusive", description,
"expected a number but got a ${type_actual}",
{type_actual:typeof actual});
assert(actual > lower && actual < upper,
"assert_between_exclusive", description,
"expected a number greater than ${lower} " +
"and less than ${upper} but got ${actual}",
{lower:lower, upper:upper, actual:actual});
}
expose(assert_between_exclusive, "assert_between_exclusive");
function assert_less_than_equal(actual, expected, description)
{
/*
* Test if a primitive number is less than or equal to another
*/
assert(typeof actual === "number",
"assert_less_than_equal", description,
"expected a number but got a ${type_actual}",
{type_actual:typeof actual});
assert(actual <= expected,
"assert_less_than_equal", description,
"expected a number less than or equal to ${expected} but got ${actual}",
{expected:expected, actual:actual});
}
expose(assert_less_than_equal, "assert_less_than_equal");
function assert_greater_than_equal(actual, expected, description)
{
/*
* Test if a primitive number is greater than or equal to another
*/
assert(typeof actual === "number",
"assert_greater_than_equal", description,
"expected a number but got a ${type_actual}",
{type_actual:typeof actual});
assert(actual >= expected,
"assert_greater_than_equal", description,
"expected a number greater than or equal to ${expected} but got ${actual}",
{expected:expected, actual:actual});
}
expose(assert_greater_than_equal, "assert_greater_than_equal");
function assert_between_inclusive(actual, lower, upper, description)
{
/*
* Test if a primitive number is between to two others or equal to either of them
*/
assert(typeof actual === "number",
"assert_between_inclusive", description,
"expected a number but got a ${type_actual}",
{type_actual:typeof actual});
assert(actual >= lower && actual <= upper,
"assert_between_inclusive", description,
"expected a number greater than or equal to ${lower} " +
"and less than or equal to ${upper} but got ${actual}",
{lower:lower, upper:upper, actual:actual});
}
expose(assert_between_inclusive, "assert_between_inclusive");
function assert_regexp_match(actual, expected, description) {
/*
* Test if a string (actual) matches a regexp (expected)
*/
assert(expected.test(actual),
"assert_regexp_match", description,
"expected ${expected} but got ${actual}",
{expected:expected, actual:actual});
}
expose(assert_regexp_match, "assert_regexp_match");
function assert_class_string(object, class_string, description) {
assert_equals({}.toString.call(object), "[object " + class_string + "]",
description);
}
expose(assert_class_string, "assert_class_string");
function _assert_own_property(name) {
return function(object, property_name, description)
{
assert(object.hasOwnProperty(property_name),
name, description,
"expected property ${p} missing", {p:property_name});
};
}
expose(_assert_own_property("assert_exists"), "assert_exists");
expose(_assert_own_property("assert_own_property"), "assert_own_property");
function assert_not_exists(object, property_name, description)
{
assert(!object.hasOwnProperty(property_name),
"assert_not_exists", description,
"unexpected property ${p} found", {p:property_name});
}
expose(assert_not_exists, "assert_not_exists");
function _assert_inherits(name) {
return function (object, property_name, description)
{
assert(typeof object === "object" || typeof object === "function",
name, description,
"provided value is not an object");
assert("hasOwnProperty" in object,
name, description,
"provided value is an object but has no hasOwnProperty method");
assert(!object.hasOwnProperty(property_name),
name, description,
"property ${p} found on object expected in prototype chain",
{p:property_name});
assert(property_name in object,
name, description,
"property ${p} not found in prototype chain",
{p:property_name});
};
}
expose(_assert_inherits("assert_inherits"), "assert_inherits");
expose(_assert_inherits("assert_idl_attribute"), "assert_idl_attribute");
function assert_readonly(object, property_name, description)
{
var initial_value = object[property_name];
try {
//Note that this can have side effects in the case where
//the property has PutForwards
object[property_name] = initial_value + "a"; //XXX use some other value here?
assert(same_value(object[property_name], initial_value),
"assert_readonly", description,
"changing property ${p} succeeded",
{p:property_name});
} finally {
object[property_name] = initial_value;
}
}
expose(assert_readonly, "assert_readonly");
function assert_throws(code, func, description)
{
try {
func.call(this);
assert(false, "assert_throws", description,
"${func} did not throw", {func:func});
} catch (e) {
if (e instanceof AssertionError) {
throw e;
}
if (code === null) {
throw new AssertionError('Test bug: need to pass exception to assert_throws()');
}
if (typeof code === "object") {
assert(typeof e == "object" && "name" in e && e.name == code.name,
"assert_throws", description,
"${func} threw ${actual} (${actual_name}) expected ${expected} (${expected_name})",
{func:func, actual:e, actual_name:e.name,
expected:code,
expected_name:code.name});
return;
}
var code_name_map = {
INDEX_SIZE_ERR: 'IndexSizeError',
HIERARCHY_REQUEST_ERR: 'HierarchyRequestError',
WRONG_DOCUMENT_ERR: 'WrongDocumentError',
INVALID_CHARACTER_ERR: 'InvalidCharacterError',
NO_MODIFICATION_ALLOWED_ERR: 'NoModificationAllowedError',
NOT_FOUND_ERR: 'NotFoundError',
NOT_SUPPORTED_ERR: 'NotSupportedError',
INUSE_ATTRIBUTE_ERR: 'InUseAttributeError',
INVALID_STATE_ERR: 'InvalidStateError',
SYNTAX_ERR: 'SyntaxError',
INVALID_MODIFICATION_ERR: 'InvalidModificationError',
NAMESPACE_ERR: 'NamespaceError',
INVALID_ACCESS_ERR: 'InvalidAccessError',
TYPE_MISMATCH_ERR: 'TypeMismatchError',
SECURITY_ERR: 'SecurityError',
NETWORK_ERR: 'NetworkError',
ABORT_ERR: 'AbortError',
URL_MISMATCH_ERR: 'URLMismatchError',
QUOTA_EXCEEDED_ERR: 'QuotaExceededError',
TIMEOUT_ERR: 'TimeoutError',
INVALID_NODE_TYPE_ERR: 'InvalidNodeTypeError',
DATA_CLONE_ERR: 'DataCloneError'
};
var name = code in code_name_map ? code_name_map[code] : code;
var name_code_map = {
IndexSizeError: 1,
HierarchyRequestError: 3,
WrongDocumentError: 4,
InvalidCharacterError: 5,
NoModificationAllowedError: 7,
NotFoundError: 8,
NotSupportedError: 9,
InUseAttributeError: 10,
InvalidStateError: 11,
SyntaxError: 12,
InvalidModificationError: 13,
NamespaceError: 14,
InvalidAccessError: 15,
TypeMismatchError: 17,
SecurityError: 18,
NetworkError: 19,
AbortError: 20,
URLMismatchError: 21,
QuotaExceededError: 22,
TimeoutError: 23,
InvalidNodeTypeError: 24,
DataCloneError: 25,
EncodingError: 0,
NotReadableError: 0,
UnknownError: 0,
ConstraintError: 0,
DataError: 0,
TransactionInactiveError: 0,
ReadOnlyError: 0,
VersionError: 0,
OperationError: 0,
NotAllowedError: 0
};
if (!(name in name_code_map)) {
throw new AssertionError('Test bug: unrecognized DOMException code "' + code + '" passed to assert_throws()');
}
var required_props = { code: name_code_map[name] };
if (required_props.code === 0 ||
(typeof e == "object" &&
"name" in e &&
e.name !== e.name.toUpperCase() &&
e.name !== "DOMException")) {
// New style exception: also test the name property.
required_props.name = name;
}
//We'd like to test that e instanceof the appropriate interface,
//but we can't, because we don't know what window it was created
//in. It might be an instanceof the appropriate interface on some
//unknown other window. TODO: Work around this somehow?
assert(typeof e == "object",
"assert_throws", description,
"${func} threw ${e} with type ${type}, not an object",
{func:func, e:e, type:typeof e});
for (var prop in required_props) {
assert(typeof e == "object" && prop in e && e[prop] == required_props[prop],
"assert_throws", description,
"${func} threw ${e} that is not a DOMException " + code + ": property ${prop} is equal to ${actual}, expected ${expected}",
{func:func, e:e, prop:prop, actual:e[prop], expected:required_props[prop]});
}
}
}
expose(assert_throws, "assert_throws");
function assert_unreached(description) {
assert(false, "assert_unreached", description,
"Reached unreachable code");
}
expose(assert_unreached, "assert_unreached");
function assert_any(assert_func, actual, expected_array)
{
var args = [].slice.call(arguments, 3);
var errors = [];
var passed = false;
forEach(expected_array,
function(expected)
{
try {
assert_func.apply(this, [actual, expected].concat(args));
passed = true;
} catch (e) {
errors.push(e.message);
}
});
if (!passed) {
throw new AssertionError(errors.join("\n\n"));
}
}
expose(assert_any, "assert_any");
function Test(name, properties)
{
if (tests.file_is_test && tests.tests.length) {
throw new Error("Tried to create a test with file_is_test");
}
this.name = name;
this.phase = tests.phase === tests.phases.ABORTED ?
this.phases.COMPLETE : this.phases.INITIAL;
this.status = this.NOTRUN;
this.timeout_id = null;
this.index = null;
this.properties = properties;
var timeout = properties.timeout ? properties.timeout : settings.test_timeout;
if (timeout !== null) {
this.timeout_length = timeout * tests.timeout_multiplier;
} else {
this.timeout_length = null;
}
this.message = null;
this.stack = null;
this.steps = [];
this.cleanup_callbacks = [];
tests.push(this);
}
Test.statuses = {
PASS:0,
FAIL:1,
TIMEOUT:2,
NOTRUN:3
};
Test.prototype = merge({}, Test.statuses);
Test.prototype.phases = {
INITIAL:0,
STARTED:1,
HAS_RESULT:2,
COMPLETE:3
};
Test.prototype.structured_clone = function()
{
if (!this._structured_clone) {
var msg = this.message;
msg = msg ? String(msg) : msg;
this._structured_clone = merge({
name:String(this.name),
properties:merge({}, this.properties),
phases:merge({}, this.phases)
}, Test.statuses);
}
this._structured_clone.status = this.status;
this._structured_clone.message = this.message;
this._structured_clone.stack = this.stack;
this._structured_clone.index = this.index;
this._structured_clone.phase = this.phase;
return this._structured_clone;
};
Test.prototype.step = function(func, this_obj)
{
if (this.phase > this.phases.STARTED) {
return;
}
this.phase = this.phases.STARTED;
//If we don't get a result before the harness times out that will be a test timout
this.set_status(this.TIMEOUT, "Test timed out");
tests.started = true;
tests.notify_test_state(this);
if (this.timeout_id === null) {
this.set_timeout();
}
this.steps.push(func);
if (arguments.length === 1) {
this_obj = this;
}
try {
return func.apply(this_obj, Array.prototype.slice.call(arguments, 2));
} catch (e) {
if (this.phase >= this.phases.HAS_RESULT) {
return;
}
var message = String((typeof e === "object" && e !== null) ? e.message : e);
var stack = e.stack ? e.stack : null;
this.set_status(this.FAIL, message, stack);
this.phase = this.phases.HAS_RESULT;
this.done();
}
};
Test.prototype.step_func = function(func, this_obj)
{
var test_this = this;
if (arguments.length === 1) {
this_obj = test_this;
}
return function()
{
return test_this.step.apply(test_this, [func, this_obj].concat(
Array.prototype.slice.call(arguments)));
};
};
Test.prototype.step_func_done = function(func, this_obj)
{
var test_this = this;
if (arguments.length === 1) {
this_obj = test_this;
}
return function()
{
if (func) {
test_this.step.apply(test_this, [func, this_obj].concat(
Array.prototype.slice.call(arguments)));
}
test_this.done();
};
};
Test.prototype.unreached_func = function(description)
{
return this.step_func(function() {
assert_unreached(description);
});
};
Test.prototype.step_timeout = function(f, timeout) {
var test_this = this;
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(this.step_func(function() {
return f.apply(test_this, args);
}), timeout * tests.timeout_multiplier);
}
Test.prototype.add_cleanup = function(callback) {
this.cleanup_callbacks.push(callback);
};
Test.prototype.force_timeout = function() {
this.set_status(this.TIMEOUT);
this.phase = this.phases.HAS_RESULT;
};
Test.prototype.set_timeout = function()
{
if (this.timeout_length !== null) {
var this_obj = this;
this.timeout_id = setTimeout(function()
{
this_obj.timeout();
}, this.timeout_length);
}
};
Test.prototype.set_status = function(status, message, stack)
{
this.status = status;
this.message = message;
this.stack = stack ? stack : null;
};
Test.prototype.timeout = function()
{
this.timeout_id = null;
this.set_status(this.TIMEOUT, "Test timed out");
this.phase = this.phases.HAS_RESULT;
this.done();
};
Test.prototype.done = function()
{
if (this.phase == this.phases.COMPLETE) {
return;
}
if (this.phase <= this.phases.STARTED) {
this.set_status(this.PASS, null);
}
this.phase = this.phases.COMPLETE;
clearTimeout(this.timeout_id);
tests.result(this);
this.cleanup();
};
/*
* Invoke all specified cleanup functions. If one or more produce an error,
* the context is in an unpredictable state, so all further testing should
* be cancelled.
*/
Test.prototype.cleanup = function() {
var error_count = 0;
var total;
forEach(this.cleanup_callbacks,
function(cleanup_callback) {
try {
cleanup_callback();
} catch (e) {
// Set test phase immediately so that tests declared
// within subsequent cleanup functions are not run.
tests.phase = tests.phases.ABORTED;
error_count += 1;
}
});
if (error_count > 0) {
total = this.cleanup_callbacks.length;
tests.status.status = tests.status.ERROR;
tests.status.message = "Test named '" + this.name +
"' specified " + total + " 'cleanup' function" +
(total > 1 ? "s" : "") + ", and " + error_count + " failed.";
tests.status.stack = null;
}
};
/*
* A RemoteTest object mirrors a Test object on a remote worker. The
* associated RemoteWorker updates the RemoteTest object in response to
* received events. In turn, the RemoteTest object replicates these events
* on the local document. This allows listeners (test result reporting
* etc..) to transparently handle local and remote events.
*/
function RemoteTest(clone) {
var this_obj = this;
Object.keys(clone).forEach(
function(key) {
this_obj[key] = clone[key];
});
this.index = null;
this.phase = this.phases.INITIAL;
this.update_state_from(clone);
tests.push(this);
}
RemoteTest.prototype.structured_clone = function() {
var clone = {};
Object.keys(this).forEach(
(function(key) {
var value = this[key];
if (typeof value === "object" && value !== null) {
clone[key] = merge({}, value);
} else {
clone[key] = value;
}
}).bind(this));
clone.phases = merge({}, this.phases);
return clone;
};
RemoteTest.prototype.cleanup = function() {};
RemoteTest.prototype.phases = Test.prototype.phases;
RemoteTest.prototype.update_state_from = function(clone) {
this.status = clone.status;
this.message = clone.message;
this.stack = clone.stack;
if (this.phase === this.phases.INITIAL) {
this.phase = this.phases.STARTED;
}
};
RemoteTest.prototype.done = function() {
this.phase = this.phases.COMPLETE;
}
/*
* A RemoteContext listens for test events from a remote test context, such
* as another window or a worker. These events are then used to construct
* and maintain RemoteTest objects that mirror the tests running in the
* remote context.
*
* An optional third parameter can be used as a predicate to filter incoming
* MessageEvents.
*/
function RemoteContext(remote, message_target, message_filter) {
this.running = true;
this.tests = new Array();
var this_obj = this;
remote.onerror = function(error) { this_obj.remote_error(error); };
// Keeping a reference to the remote object and the message handler until
// remote_done() is seen prevents the remote object and its message channel
// from going away before all the messages are dispatched.
this.remote = remote;
this.message_target = message_target;
this.message_handler = function(message) {
var passesFilter = !message_filter || message_filter(message);
if (this_obj.running && message.data && passesFilter &&
(message.data.type in this_obj.message_handlers)) {
this_obj.message_handlers[message.data.type].call(this_obj, message.data);
}
};
this.message_target.addEventListener("message", this.message_handler);
}
RemoteContext.prototype.remote_error = function(error) {
var message = error.message || String(error);
var filename = (error.filename ? " " + error.filename: "");
// FIXME: Display remote error states separately from main document
// error state.
this.remote_done({
status: {
status: tests.status.ERROR,
message: "Error in remote" + filename + ": " + message,
stack: error.stack
}
});
if (error.preventDefault) {
error.preventDefault();
}
};
RemoteContext.prototype.test_state = function(data) {
var remote_test = this.tests[data.test.index];
if (!remote_test) {
remote_test = new RemoteTest(data.test);
this.tests[data.test.index] = remote_test;
}
remote_test.update_state_from(data.test);
tests.notify_test_state(remote_test);
};
RemoteContext.prototype.test_done = function(data) {
var remote_test = this.tests[data.test.index];
remote_test.update_state_from(data.test);
remote_test.done();
tests.result(remote_test);
};
RemoteContext.prototype.remote_done = function(data) {
if (tests.status.status === null &&
data.status.status !== data.status.OK) {
tests.status.status = data.status.status;
tests.status.message = data.status.message;
tests.status.stack = data.status.stack;
}
this.message_target.removeEventListener("message", this.message_handler);
this.running = false;
this.remote = null;
this.message_target = null;
if (tests.all_done()) {
tests.complete();
}
};
RemoteContext.prototype.message_handlers = {
test_state: RemoteContext.prototype.test_state,
result: RemoteContext.prototype.test_done,
complete: RemoteContext.prototype.remote_done
};
/*
* Harness
*/
function TestsStatus()
{
this.status = null;
this.message = null;
this.stack = null;
}
TestsStatus.statuses = {
OK:0,
ERROR:1,
TIMEOUT:2
};
TestsStatus.prototype = merge({}, TestsStatus.statuses);
TestsStatus.prototype.structured_clone = function()
{
if (!this._structured_clone) {
var msg = this.message;
msg = msg ? String(msg) : msg;
this._structured_clone = merge({
status:this.status,
message:msg,
stack:this.stack
}, TestsStatus.statuses);
}
return this._structured_clone;
};
function Tests()
{
this.tests = [];
this.num_pending = 0;
this.phases = {
INITIAL:0,
SETUP:1,
HAVE_TESTS:2,
HAVE_RESULTS:3,
COMPLETE:4,
ABORTED:5
};
this.phase = this.phases.INITIAL;
this.properties = {};
this.wait_for_finish = false;
this.processing_callbacks = false;
this.allow_uncaught_exception = false;
this.file_is_test = false;
this.timeout_multiplier = 1;
this.timeout_length = test_environment.test_timeout();
this.timeout_id = null;
this.start_callbacks = [];
this.test_state_callbacks = [];
this.test_done_callbacks = [];
this.all_done_callbacks = [];
this.pending_remotes = [];
this.status = new TestsStatus();
var this_obj = this;
test_environment.add_on_loaded_callback(function() {
if (this_obj.all_done()) {
this_obj.complete();
}
});
this.set_timeout();
}
Tests.prototype.setup = function(func, properties)
{
if (this.phase >= this.phases.HAVE_RESULTS) {
return;
}
if (this.phase < this.phases.SETUP) {
this.phase = this.phases.SETUP;
}
this.properties = properties;
for (var p in properties) {
if (properties.hasOwnProperty(p)) {
var value = properties[p];
if (p == "allow_uncaught_exception") {
this.allow_uncaught_exception = value;
} else if (p == "explicit_done" && value) {
this.wait_for_finish = true;
} else if (p == "explicit_timeout" && value) {
this.timeout_length = null;
if (this.timeout_id)
{
clearTimeout(this.timeout_id);
}
} else if (p == "timeout_multiplier") {
this.timeout_multiplier = value;
}
}
}
if (func) {
try {
func();
} catch (e) {
this.status.status = this.status.ERROR;
this.status.message = String(e);
this.status.stack = e.stack ? e.stack : null;
}
}
this.set_timeout();
};
Tests.prototype.set_file_is_test = function() {
if (this.tests.length > 0) {
throw new Error("Tried to set file as test after creating a test");
}
this.wait_for_finish = true;
this.file_is_test = true;
// Create the test, which will add it to the list of tests
async_test();
};
Tests.prototype.set_timeout = function() {
var this_obj = this;
clearTimeout(this.timeout_id);
if (this.timeout_length !== null) {
this.timeout_id = setTimeout(function() {
this_obj.timeout();
}, this.timeout_length);
}
};
Tests.prototype.timeout = function() {
if (this.status.status === null) {
this.status.status = this.status.TIMEOUT;
}
this.complete();
};
Tests.prototype.end_wait = function()
{
this.wait_for_finish = false;
if (this.all_done()) {
this.complete();
}
};
Tests.prototype.push = function(test)
{
if (this.phase < this.phases.HAVE_TESTS) {
this.start();
}
this.num_pending++;
test.index = this.tests.push(test);
this.notify_test_state(test);
};
Tests.prototype.notify_test_state = function(test) {
var this_obj = this;
forEach(this.test_state_callbacks,
function(callback) {
callback(test, this_obj);
});
};
Tests.prototype.all_done = function() {
return this.phase === this.phases.ABORTED ||
(this.tests.length > 0 && test_environment.all_loaded &&
this.num_pending === 0 && !this.wait_for_finish &&
!this.processing_callbacks &&
!this.pending_remotes.some(function(w) { return w.running; }));
};
Tests.prototype.start = function() {
this.phase = this.phases.HAVE_TESTS;
this.notify_start();
};
Tests.prototype.notify_start = function() {
var this_obj = this;
forEach (this.start_callbacks,
function(callback)
{
callback(this_obj.properties);
});
};
Tests.prototype.result = function(test)
{
if (this.phase > this.phases.HAVE_RESULTS) {
return;
}
this.phase = this.phases.HAVE_RESULTS;
this.num_pending--;
this.notify_result(test);
};
Tests.prototype.notify_result = function(test) {
var this_obj = this;
this.processing_callbacks = true;
forEach(this.test_done_callbacks,
function(callback)
{
callback(test, this_obj);
});
this.processing_callbacks = false;
if (this_obj.all_done()) {
this_obj.complete();
}
};
Tests.prototype.complete = function() {
if (this.phase === this.phases.COMPLETE) {
return;
}
this.phase = this.phases.COMPLETE;
var this_obj = this;
this.tests.forEach(
function(x)
{
if (x.phase < x.phases.COMPLETE) {
this_obj.notify_result(x);
x.cleanup();
x.phase = x.phases.COMPLETE;
}
}
);
this.notify_complete();
};
/*
* Determine if any tests share the same `name` property. Return an array
* containing the names of any such duplicates.
*/
Tests.prototype.find_duplicates = function() {
var names = Object.create(null);
var duplicates = [];
forEach (this.tests,
function(test)
{
if (test.name in names && duplicates.indexOf(test.name) === -1) {
duplicates.push(test.name);
}
names[test.name] = true;
});
return duplicates;
};
Tests.prototype.notify_complete = function() {
var this_obj = this;
var duplicates;
if (this.status.status === null) {
duplicates = this.find_duplicates();
// Test names are presumed to be unique within test files--this
// allows consumers to use them for identification purposes.
// Duplicated names violate this expectation and should therefore
// be reported as an error.
if (duplicates.length) {
this.status.status = this.status.ERROR;
this.status.message =
duplicates.length + ' duplicate test name' +
(duplicates.length > 1 ? 's' : '') + ': "' +
duplicates.join('", "') + '"';
} else {
this.status.status = this.status.OK;
}
}
forEach (this.all_done_callbacks,
function(callback)
{
callback(this_obj.tests, this_obj.status);
});
};
/*
* Constructs a RemoteContext that tracks tests from a specific worker.
*/
Tests.prototype.create_remote_worker = function(worker) {
var message_port;
if (is_service_worker(worker)) {
// Microsoft Edge's implementation of ServiceWorker doesn't support MessagePort yet.
// Feature detection isn't a straightforward option here; it's only possible in the
// worker's script context.
var isMicrosoftEdgeBrowser = navigator.userAgent.includes("Edge");
if (window.MessageChannel && !isMicrosoftEdgeBrowser) {
// The ServiceWorker's implicit MessagePort is currently not
// reliably accessible from the ServiceWorkerGlobalScope due to
// Blink setting MessageEvent.source to null for messages sent
// via ServiceWorker.postMessage(). Until that's resolved,
// create an explicit MessageChannel and pass one end to the
// worker.
var message_channel = new MessageChannel();
message_port = message_channel.port1;
message_port.start();
worker.postMessage({type: "connect"}, [message_channel.port2]);
} else {
// If MessageChannel is not available, then try the
// ServiceWorker.postMessage() approach using MessageEvent.source
// on the other end.
message_port = navigator.serviceWorker;
worker.postMessage({type: "connect"});
}
} else if (is_shared_worker(worker)) {
message_port = worker.port;
message_port.start();
} else {
message_port = worker;
}
return new RemoteContext(worker, message_port);
};
/*
* Constructs a RemoteContext that tracks tests from a specific window.
*/
Tests.prototype.create_remote_window = function(remote) {
remote.postMessage({type: "getmessages"}, "*");
return new RemoteContext(
remote,
window,
function(msg) {
return msg.source === remote;
}
);
};
Tests.prototype.fetch_tests_from_worker = function(worker) {
if (this.phase >= this.phases.COMPLETE) {
return;
}
this.pending_remotes.push(this.create_remote_worker(worker));
};
function fetch_tests_from_worker(port) {
tests.fetch_tests_from_worker(port);
}
expose(fetch_tests_from_worker, 'fetch_tests_from_worker');
Tests.prototype.fetch_tests_from_window = function(remote) {
if (this.phase >= this.phases.COMPLETE) {
return;
}
this.pending_remotes.push(this.create_remote_window(remote));
};
function fetch_tests_from_window(window) {
tests.fetch_tests_from_window(window);
}
expose(fetch_tests_from_window, 'fetch_tests_from_window');
function timeout() {
if (tests.timeout_length === null) {
tests.timeout();
}
}
expose(timeout, 'timeout');
function add_start_callback(callback) {
tests.start_callbacks.push(callback);
}
function add_test_state_callback(callback) {
tests.test_state_callbacks.push(callback);
}
function add_result_callback(callback) {
tests.test_done_callbacks.push(callback);
}
function add_completion_callback(callback) {
tests.all_done_callbacks.push(callback);
}
expose(add_start_callback, 'add_start_callback');
expose(add_test_state_callback, 'add_test_state_callback');
expose(add_result_callback, 'add_result_callback');
expose(add_completion_callback, 'add_completion_callback');
function remove(array, item) {
var index = array.indexOf(item);
if (index > -1) {
array.splice(index, 1);
}
}
function remove_start_callback(callback) {
remove(tests.start_callbacks, callback);
}
function remove_test_state_callback(callback) {
remove(tests.test_state_callbacks, callback);
}
function remove_result_callback(callback) {
remove(tests.test_done_callbacks, callback);
}
function remove_completion_callback(callback) {
remove(tests.all_done_callbacks, callback);
}
/*
* Output listener
*/
function Output() {
this.output_document = document;
this.output_node = null;
this.enabled = settings.output;
this.phase = this.INITIAL;
}
Output.prototype.INITIAL = 0;
Output.prototype.STARTED = 1;
Output.prototype.HAVE_RESULTS = 2;
Output.prototype.COMPLETE = 3;
Output.prototype.setup = function(properties) {
if (this.phase > this.INITIAL) {
return;
}
//If output is disabled in testharnessreport.js the test shouldn't be
//able to override that
this.enabled = this.enabled && (properties.hasOwnProperty("output") ?
properties.output : settings.output);
};
Output.prototype.init = function(properties) {
if (this.phase >= this.STARTED) {
return;
}
if (properties.output_document) {
this.output_document = properties.output_document;
} else {
this.output_document = document;
}
this.phase = this.STARTED;
};
Output.prototype.resolve_log = function() {
var output_document;
if (typeof this.output_document === "function") {
output_document = this.output_document.apply(undefined);
} else {
output_document = this.output_document;
}
if (!output_document) {
return;
}
var node = output_document.getElementById("log");
if (!node) {
if (!document.body || document.readyState == "loading") {
return;
}
node = output_document.createElement("div");
node.id = "log";
output_document.body.appendChild(node);
}
this.output_document = output_document;
this.output_node = node;
};
Output.prototype.show_status = function() {
if (this.phase < this.STARTED) {
this.init();
}
if (!this.enabled) {
return;
}
if (this.phase < this.HAVE_RESULTS) {
this.resolve_log();
this.phase = this.HAVE_RESULTS;
}
var done_count = tests.tests.length - tests.num_pending;
if (this.output_node) {
if (done_count < 100 ||
(done_count < 1000 && done_count % 100 === 0) ||
done_count % 1000 === 0) {
this.output_node.textContent = "Running, " +
done_count + " complete, " +
tests.num_pending + " remain";
}
}
};
Output.prototype.show_results = function (tests, harness_status) {
if (this.phase >= this.COMPLETE) {
return;
}
if (!this.enabled) {
return;
}
if (!this.output_node) {
this.resolve_log();
}
this.phase = this.COMPLETE;
var log = this.output_node;
if (!log) {
return;
}
var output_document = this.output_document;
while (log.lastChild) {
log.removeChild(log.lastChild);
}
var harness_url = get_harness_url();
if (harness_url !== undefined) {
var stylesheet = output_document.createElementNS(xhtml_ns, "link");
stylesheet.setAttribute("rel", "stylesheet");
stylesheet.setAttribute("href", harness_url + "testharness.css");
var heads = output_document.getElementsByTagName("head");
if (heads.length) {
heads[0].appendChild(stylesheet);
}
}
var status_text_harness = {};
status_text_harness[harness_status.OK] = "OK";
status_text_harness[harness_status.ERROR] = "Error";
status_text_harness[harness_status.TIMEOUT] = "Timeout";
var status_text = {};
status_text[Test.prototype.PASS] = "Pass";
status_text[Test.prototype.FAIL] = "Fail";
status_text[Test.prototype.TIMEOUT] = "Timeout";
status_text[Test.prototype.NOTRUN] = "Not Run";
var status_number = {};
forEach(tests,
function(test) {
var status = status_text[test.status];
if (status_number.hasOwnProperty(status)) {
status_number[status] += 1;
} else {
status_number[status] = 1;
}
});
function status_class(status)
{
return status.replace(/\s/g, '').toLowerCase();
}
var summary_template = ["section", {"id":"summary"},
["h2", {}, "Summary"],
function()
{
var status = status_text_harness[harness_status.status];
var rv = [["section", {},
["p", {},
"Harness status: ",
["span", {"class":status_class(status)},
status
],
]
]];
if (harness_status.status === harness_status.ERROR) {
rv[0].push(["pre", {}, harness_status.message]);
if (harness_status.stack) {
rv[0].push(["pre", {}, harness_status.stack]);
}
}
return rv;
},
["p", {}, "Found ${num_tests} tests"],
function() {
var rv = [["div", {}]];
var i = 0;
while (status_text.hasOwnProperty(i)) {
if (status_number.hasOwnProperty(status_text[i])) {
var status = status_text[i];
rv[0].push(["div", {"class":status_class(status)},
["label", {},
["input", {type:"checkbox", checked:"checked"}],
status_number[status] + " " + status]]);
}
i++;
}
return rv;
},
];
log.appendChild(render(summary_template, {num_tests:tests.length}, output_document));
forEach(output_document.querySelectorAll("section#summary label"),
function(element)
{
on_event(element, "click",
function(e)
{
if (output_document.getElementById("results") === null) {
e.preventDefault();
return;
}
var result_class = element.parentNode.getAttribute("class");
var style_element = output_document.querySelector("style#hide-" + result_class);
var input_element = element.querySelector("input");
if (!style_element && !input_element.checked) {
style_element = output_document.createElementNS(xhtml_ns, "style");
style_element.id = "hide-" + result_class;
style_element.textContent = "table#results > tbody > tr."+result_class+"{display:none}";
output_document.body.appendChild(style_element);
} else if (style_element && input_element.checked) {
style_element.parentNode.removeChild(style_element);
}
});
});
// This use of innerHTML plus manual escaping is not recommended in
// general, but is necessary here for performance. Using textContent
// on each individual <td> adds tens of seconds of execution time for
// large test suites (tens of thousands of tests).
function escape_html(s)
{
return s.replace(/\&/g, "&")
.replace(/</g, "<")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function has_assertions()
{
for (var i = 0; i < tests.length; i++) {
if (tests[i].properties.hasOwnProperty("assert")) {
return true;
}
}
return false;
}
function get_assertion(test)
{
if (test.properties.hasOwnProperty("assert")) {
if (Array.isArray(test.properties.assert)) {
return test.properties.assert.join(' ');
}
return test.properties.assert;
}
return '';
}
log.appendChild(document.createElementNS(xhtml_ns, "section"));
var assertions = has_assertions();
var html = "<h2>Details</h2><table id='results' " + (assertions ? "class='assertions'" : "" ) + ">" +
"<thead><tr><th>Result</th><th>Test Name</th>" +
(assertions ? "<th>Assertion</th>" : "") +
"<th>Message</th></tr></thead>" +
"<tbody>";
for (var i = 0; i < tests.length; i++) {
html += '<tr class="' +
escape_html(status_class(status_text[tests[i].status])) +
'"><td>' +
escape_html(status_text[tests[i].status]) +
"</td><td>" +
escape_html(tests[i].name) +
"</td><td>" +
(assertions ? escape_html(get_assertion(tests[i])) + "</td><td>" : "") +
escape_html(tests[i].message ? tests[i].message : " ") +
(tests[i].stack ? "<pre>" +
escape_html(tests[i].stack) +
"</pre>": "") +
"</td></tr>";
}
html += "</tbody></table>";
try {
log.lastChild.innerHTML = html;
} catch (e) {
log.appendChild(document.createElementNS(xhtml_ns, "p"))
.textContent = "Setting innerHTML for the log threw an exception.";
log.appendChild(document.createElementNS(xhtml_ns, "pre"))
.textContent = html;
}
};
/*
* Template code
*
* A template is just a javascript structure. An element is represented as:
*
* [tag_name, {attr_name:attr_value}, child1, child2]
*
* the children can either be strings (which act like text nodes), other templates or
* functions (see below)
*
* A text node is represented as
*
* ["{text}", value]
*
* String values have a simple substitution syntax; ${foo} represents a variable foo.
*
* It is possible to embed logic in templates by using a function in a place where a
* node would usually go. The function must either return part of a template or null.
*
* In cases where a set of nodes are required as output rather than a single node
* with children it is possible to just use a list
* [node1, node2, node3]
*
* Usage:
*
* render(template, substitutions) - take a template and an object mapping
* variable names to parameters and return either a DOM node or a list of DOM nodes
*
* substitute(template, substitutions) - take a template and variable mapping object,
* make the variable substitutions and return the substituted template
*
*/
function is_single_node(template)
{
return typeof template[0] === "string";
}
function substitute(template, substitutions)
{
if (typeof template === "function") {
var replacement = template(substitutions);
if (!replacement) {
return null;
}
return substitute(replacement, substitutions);
}
if (is_single_node(template)) {
return substitute_single(template, substitutions);
}
return filter(map(template, function(x) {
return substitute(x, substitutions);
}), function(x) {return x !== null;});
}
function substitute_single(template, substitutions)
{
var substitution_re = /\$\{([^ }]*)\}/g;
function do_substitution(input) {
var components = input.split(substitution_re);
var rv = [];
for (var i = 0; i < components.length; i += 2) {
rv.push(components[i]);
if (components[i + 1]) {
rv.push(String(substitutions[components[i + 1]]));
}
}
return rv;
}
function substitute_attrs(attrs, rv)
{
rv[1] = {};
for (var name in template[1]) {
if (attrs.hasOwnProperty(name)) {
var new_name = do_substitution(name).join("");
var new_value = do_substitution(attrs[name]).join("");
rv[1][new_name] = new_value;
}
}
}
function substitute_children(children, rv)
{
for (var i = 0; i < children.length; i++) {
if (children[i] instanceof Object) {
var replacement = substitute(children[i], substitutions);
if (replacement !== null) {
if (is_single_node(replacement)) {
rv.push(replacement);
} else {
extend(rv, replacement);
}
}
} else {
extend(rv, do_substitution(String(children[i])));
}
}
return rv;
}
var rv = [];
rv.push(do_substitution(String(template[0])).join(""));
if (template[0] === "{text}") {
substitute_children(template.slice(1), rv);
} else {
substitute_attrs(template[1], rv);
substitute_children(template.slice(2), rv);
}
return rv;
}
function make_dom_single(template, doc)
{
var output_document = doc || document;
var element;
if (template[0] === "{text}") {
element = output_document.createTextNode("");
for (var i = 1; i < template.length; i++) {
element.data += template[i];
}
} else {
element = output_document.createElementNS(xhtml_ns, template[0]);
for (var name in template[1]) {
if (template[1].hasOwnProperty(name)) {
element.setAttribute(name, template[1][name]);
}
}
for (var i = 2; i < template.length; i++) {
if (template[i] instanceof Object) {
var sub_element = make_dom(template[i]);
element.appendChild(sub_element);
} else {
var text_node = output_document.createTextNode(template[i]);
element.appendChild(text_node);
}
}
}
return element;
}
function make_dom(template, substitutions, output_document)
{
if (is_single_node(template)) {
return make_dom_single(template, output_document);
}
return map(template, function(x) {
return make_dom_single(x, output_document);
});
}
function render(template, substitutions, output_document)
{
return make_dom(substitute(template, substitutions), output_document);
}
/*
* Utility funcions
*/
function assert(expected_true, function_name, description, error, substitutions)
{
if (tests.tests.length === 0) {
tests.set_file_is_test();
}
if (expected_true !== true) {
var msg = make_message(function_name, description,
error, substitutions);
throw new AssertionError(msg);
}
}
function AssertionError(message)
{
this.message = message;
this.stack = this.get_stack();
}
expose(AssertionError, "AssertionError");
AssertionError.prototype = Object.create(Error.prototype);
AssertionError.prototype.get_stack = function() {
var stack = new Error().stack;
// IE11 does not initialize 'Error.stack' until the object is thrown.
if (!stack) {
try {
throw new Error();
} catch (e) {
stack = e.stack;
}
}
// 'Error.stack' is not supported in all browsers/versions
if (!stack) {
return "(Stack trace unavailable)";
}
var lines = stack.split("\n");
// Create a pattern to match stack frames originating within testharness.js. These include the
// script URL, followed by the line/col (e.g., '/resources/testharness.js:120:21').
// Escape the URL per http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
// in case it contains RegExp characters.
var script_url = get_script_url();
var re_text = script_url ? script_url.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&') : "\\btestharness.js";
var re = new RegExp(re_text + ":\\d+:\\d+");
// Some browsers include a preamble that specifies the type of the error object. Skip this by
// advancing until we find the first stack frame originating from testharness.js.
var i = 0;
while (!re.test(lines[i]) && i < lines.length) {
i++;
}
// Then skip the top frames originating from testharness.js to begin the stack at the test code.
while (re.test(lines[i]) && i < lines.length) {
i++;
}
// Paranoid check that we didn't skip all frames. If so, return the original stack unmodified.
if (i >= lines.length) {
return stack;
}
return lines.slice(i).join("\n");
}
function make_message(function_name, description, error, substitutions)
{
for (var p in substitutions) {
if (substitutions.hasOwnProperty(p)) {
substitutions[p] = format_value(substitutions[p]);
}
}
var node_form = substitute(["{text}", "${function_name}: ${description}" + error],
merge({function_name:function_name,
description:(description?description + " ":"")},
substitutions));
return node_form.slice(1).join("");
}
function filter(array, callable, thisObj) {
var rv = [];
for (var i = 0; i < array.length; i++) {
if (array.hasOwnProperty(i)) {
var pass = callable.call(thisObj, array[i], i, array);
if (pass) {
rv.push(array[i]);
}
}
}
return rv;
}
function map(array, callable, thisObj)
{
var rv = [];
rv.length = array.length;
for (var i = 0; i < array.length; i++) {
if (array.hasOwnProperty(i)) {
rv[i] = callable.call(thisObj, array[i], i, array);
}
}
return rv;
}
function extend(array, items)
{
Array.prototype.push.apply(array, items);
}
function forEach(array, callback, thisObj)
{
for (var i = 0; i < array.length; i++) {
if (array.hasOwnProperty(i)) {
callback.call(thisObj, array[i], i, array);
}
}
}
function merge(a,b)
{
var rv = {};
var p;
for (p in a) {
rv[p] = a[p];
}
for (p in b) {
rv[p] = b[p];
}
return rv;
}
function expose(object, name)
{
var components = name.split(".");
var target = test_environment.global_scope();
for (var i = 0; i < components.length - 1; i++) {
if (!(components[i] in target)) {
target[components[i]] = {};
}
target = target[components[i]];
}
target[components[components.length - 1]] = object;
}
function is_same_origin(w) {
try {
'random_prop' in w;
return true;
} catch (e) {
return false;
}
}
/** Returns the 'src' URL of the first <script> tag in the page to include the file 'testharness.js'. */
function get_script_url()
{
if (!('document' in self)) {
return undefined;
}
var scripts = document.getElementsByTagName("script");
for (var i = 0; i < scripts.length; i++) {
var src;
if (scripts[i].src) {
src = scripts[i].src;
} else if (scripts[i].href) {
//SVG case
src = scripts[i].href.baseVal;
}
var matches = src && src.match(/^(.*\/|)testharness\.js$/);
if (matches) {
return src;
}
}
return undefined;
}
/** Returns the URL path at which the files for testharness.js are assumed to reside (e.g., '/resources/').
The path is derived from inspecting the 'src' of the <script> tag that included 'testharness.js'. */
function get_harness_url()
{
var script_url = get_script_url();
// Exclude the 'testharness.js' file from the returned path, but '+ 1' to include the trailing slash.
return script_url ? script_url.slice(0, script_url.lastIndexOf('/') + 1) : undefined;
}
function supports_post_message(w)
{
var supports;
var type;
// Given IE implements postMessage across nested iframes but not across
// windows or tabs, you can't infer cross-origin communication from the presence
// of postMessage on the current window object only.
//
// Touching the postMessage prop on a window can throw if the window is
// not from the same origin AND post message is not supported in that
// browser. So just doing an existence test here won't do, you also need
// to wrap it in a try..cacth block.
try {
type = typeof w.postMessage;
if (type === "function") {
supports = true;
}
// IE8 supports postMessage, but implements it as a host object which
// returns "object" as its `typeof`.
else if (type === "object") {
supports = true;
}
// This is the case where postMessage isn't supported AND accessing a
// window property across origins does NOT throw (e.g. old Safari browser).
else {
supports = false;
}
} catch (e) {
// This is the case where postMessage isn't supported AND accessing a
// window property across origins throws (e.g. old Firefox browser).
supports = false;
}
return supports;
}
/**
* Setup globals
*/
var tests = new Tests();
var error_handler = function(e) {
if (tests.tests.length === 0 && !tests.allow_uncaught_exception) {
tests.set_file_is_test();
}
var stack;
if (e.error && e.error.stack) {
stack = e.error.stack;
} else {
stack = e.filename + ":" + e.lineno + ":" + e.colno;
}
if (tests.file_is_test) {
var test = tests.tests[0];
if (test.phase >= test.phases.HAS_RESULT) {
return;
}
test.set_status(test.FAIL, e.message, stack);
test.phase = test.phases.HAS_RESULT;
test.done();
} else if (!tests.allow_uncaught_exception) {
tests.status.status = tests.status.ERROR;
tests.status.message = e.message;
tests.status.stack = stack;
}
done();
};
addEventListener("error", error_handler, false);
addEventListener("unhandledrejection", function(e){ error_handler(e.reason); }, false);
test_environment.on_tests_ready();
})();
// vim: set expandtab shiftwidth=4 tabstop=4:
|
bzbarsky/servo
|
tests/wpt/web-platform-tests/resources/testharness.js
|
JavaScript
|
mpl-2.0
| 100,320
|
// DO NOT EDIT! This test has been generated by tools/gentest.py.
// OffscreenCanvas test in a worker:size.attributes.parse.hex
// Description:Parsing of non-negative integers
// Note:
importScripts("/resources/testharness.js");
importScripts("/2dcontext/resources/canvas-tests.js");
var t = async_test("Parsing of non-negative integers");
t.step(function() {
var offscreenCanvas = new OffscreenCanvas(100, 50);
var ctx = offscreenCanvas.getContext('2d');
offscreenCanvas.width = '0x100';
offscreenCanvas.height = '0x100';
_assertSame(offscreenCanvas.width, 256, "offscreenCanvas.width", "256");
_assertSame(offscreenCanvas.height, 256, "offscreenCanvas.height", "256");
t.done();
});
done();
|
larsbergstrom/servo
|
tests/wpt/web-platform-tests/offscreen-canvas/the-offscreen-canvas/size.attributes.parse.hex.worker.js
|
JavaScript
|
mpl-2.0
| 699
|
const helper = require('./helper');
const _ = require('lodash');
const assume = require('assume');
const taskcluster = require('taskcluster-client');
const mocha = require('mocha');
helper.secrets.mockSuite(helper.suiteName(__filename), ['app', 'azure'], function(mock, skipping) {
helper.withPulse(mock, skipping);
helper.withEntities(mock, skipping);
helper.withRoles(mock, skipping);
helper.withServers(mock, skipping);
/**
* Customized test function, taking an object as follows:
* test('...', {
* roles: [ // roles to create (will be deleted before the test)
* {
* roleId: 'assume:thing-id:*'
* scopes: [...]
* },
* ],
* clients: [ // clients to create (will be deleted before the test)
* {
* clientId: '...'
* includes: [...], // test that client has these scopes
* excludes: [...] // test that client doesn't have these scopes
* }
* ],
* });
*
* Due to the nature of these test we can't expect them to work if two
* instances of these test cases runs at the same time.
*/
let test = (title, t) => {
mocha.test(title, async function() {
// Some of these tests can be a bit slow, especially without in-memory entities
this.timeout(10 * 60 * 1000);
// Ensure all roles and clients from the test are deleted
for (let c of t.clients) {
await helper.apiClient.deleteClient(c.clientId);
}
for (let r of t.roles) {
await helper.apiClient.deleteRole(r.roleId);
}
// Create all roles and clients
for (let c of t.clients) {
await helper.apiClient.createClient(c.clientId, {
description: 'client for test case: ' + title,
expires: taskcluster.fromNowJSON('2 hours'),
scopes: c.scopes,
});
}
for (let r of t.roles) {
await helper.apiClient.createRole(r.roleId, {
description: 'role for test case: ' + title,
scopes: r.scopes,
});
}
// Run tests for all clients
let err = '';
await Promise.all(t.clients.map(async (c) => {
let client = await helper.apiClient.client(c.clientId);
let missing = _.difference(c.includes, client.expandedScopes);
let forbidden = _.intersection(c.exludes, client.expandedScopes);
if (missing.length !== 0 || forbidden.length !== 0) {
err += 'Test failed: ' + JSON.stringify(t, null, 2) + '\n';
err += 'Client: ' + JSON.stringify(client, null, 2) + '\n';
}
if (missing.length !== 0) {
err += 'Missing: ' + JSON.stringify(missing) + '\n';
}
if (forbidden.length !== 0) {
err += 'Forbidden: ' + JSON.stringify(forbidden) + '\n';
}
if (missing.length !== 0 || forbidden.length !== 0) {
err += '\n\n';
}
}));
// delete all roles and clients from the tests
for (let c of t.clients) {
await helper.apiClient.deleteClient(c.clientId);
}
for (let r of t.roles) {
await helper.apiClient.deleteRole(r.roleId);
}
if (err !== '') {
throw new Error(err);
}
});
};
test('assume:thing-id:* works', {
roles: [
{
roleId: 'thing-id:*',
scopes: ['test-scope-1'],
},
],
clients: [
{
clientId: 'test-client',
scopes: [
'assume:thing-id:test',
],
includes: [
'assume:thing-id:test',
'test-scope-1',
],
excludes: [
'assume:thing-id:*',
'*',
],
},
],
});
test('can get assume:tree:*', {
roles: [
{
roleId: 'thing-id:test',
scopes: ['assume:tree:*'],
},
],
clients: [
{
clientId: 'test-client',
scopes: [
'assume:thing-id:test',
],
includes: [
'assume:tree:*',
],
excludes: [
'assume:thing-id:test', // should be compressed away
],
},
],
});
test('two clients don\'t get the same .. uh, look, something shiny!', {
roles: [
{
roleId: 'thing-id:test-client-1',
scopes: ['scope-1'],
}, {
roleId: 'thing-id:test-client-2',
scopes: ['scope-2'],
}, {
roleId: 'thing-id:test-client-*',
scopes: ['scope-for-both'],
}, {
roleId: 'thing-id:other-client',
scopes: ['other-scope'],
},
],
clients: [
{
clientId: 'test-client-1',
scopes: [
'assume:thing-id:test-client-1',
],
includes: [
'assume:thing-id:test-client-1',
'scope-1',
'scope-for-both',
],
excludes: [
'assume:thing-id:test-client-2',
'scope-2',
'other-scope',
'thing-id:test-client-*',
],
}, {
clientId: 'test-client-2',
scopes: [
'assume:thing-id:test-client-2',
],
includes: [
'scope-2',
'scope-for-both',
],
excludes: [
'scope-1',
'other-scope',
'thing-id:test-client-*',
],
}, {
clientId: 'other-client',
scopes: [
'assume:thing-id:other-client',
],
includes: [
'other-scope',
],
excludes: [
'scope-for-both',
'scope-1',
'scope-2',
'thing-id:test-client-*',
],
},
],
});
test('two clients with two prefix roles', {
roles: [
{
roleId: 'test-role-abc*',
scopes: ['scope-1'],
}, {
roleId: 'test-role-abc-*',
scopes: ['scope-2'],
},
],
clients: [
{
clientId: 'test-client-abc',
scopes: [
'assume:test-role-abc',
],
includes: [
'scope-1',
],
excludes: [
'scope-2',
],
}, {
clientId: 'test-client-abc-again',
scopes: [
'assume:test-role-abc-again',
],
includes: [
'scope-1',
'scope-2',
],
excludes: ['*'],
},
],
});
test('indirect roles works', {
roles: [
{
roleId: 'test-client-1',
scopes: ['assume:test-role'],
}, {
roleId: 'test-role',
scopes: ['special-scope'],
},
],
clients: [
{
clientId: 'test-client-1',
scopes: [
'assume:test-client-1',
],
includes: [
'assume:test-role',
'special-scope',
],
excludes: ['*'],
},
],
});
test('indirect roles works (with many levels of indirection)', {
roles: [
{
roleId: 'test-role-1',
scopes: ['assume:test-role-2'],
}, {
roleId: 'test-role-2',
scopes: ['assume:test-role-3'],
}, {
roleId: 'test-role-3',
scopes: ['assume:test-role-4'],
}, {
roleId: 'test-role-4',
scopes: ['assume:test-role-5'],
}, {
roleId: 'test-role-5',
scopes: ['assume:test-role-6'],
}, {
roleId: 'test-role-6',
scopes: ['assume:test-role-7'],
}, {
roleId: 'test-role-7',
scopes: ['assume:test-role-8'],
}, {
roleId: 'test-role-8',
scopes: ['assume:test-role-9'],
}, {
roleId: 'test-role-9',
scopes: ['assume:test-role'],
}, {
roleId: 'test-role',
scopes: ['special-scope'],
},
],
clients: [
{
clientId: 'test-client-1',
scopes: [
'assume:test-role-1',
],
includes: [
'assume:test-role',
'assume:test-role-1',
'assume:test-role-2',
'assume:test-role-3',
'assume:test-role-4',
'assume:test-role-5',
'assume:test-role-6',
'assume:test-role-7',
'assume:test-role-8',
'assume:test-role-9',
'special-scope',
],
excludes: ['*'],
},
],
});
test('a client using a parameterized role', {
roles: [
{
roleId: 'project-admin:*',
scopes: ['assume:admin-role:project-<..>/*', 'secrets:get:project/<..>/*'],
}, {
roleId: 'admin-role:*',
scopes: [
'auth:create-role:<..>',
'auth:update-role:<..>',
'auth:delete-role:<..>',
],
},
],
clients: [
{
clientId: 'single-admin',
scopes: [
'assume:project-admin:proj1',
],
includes: [
'auth:create-role:project-proj1/*',
],
excludes: [
'auth:create-role:project-*',
],
}, {
clientId: 'double-admin',
scopes: [
'assume:project-admin:proj1',
'assume:project-admin:proj2',
],
includes: [
'auth:create-role:project-proj1/*',
'auth:create-role:project-proj2/*',
],
excludes: [
'auth:create-role:project-*',
],
}, {
clientId: 'star-admin',
scopes: [
'assume:project-admin:proj*',
],
includes: [
'auth:create-role:project-proj*', // note no slash
],
excludes: [
'auth:create-role:project-*',
],
},
],
});
const N = 50;
test('indirect roles works (with ' + N + ' roles)', {
roles: [
{
roleId: 'big-test-client',
scopes: ['assume:test-role-0'],
}, {
roleId: 'test-role-' + N,
scopes: ['special-scope'],
},
].concat(_.range(N).map(i => {
return {
roleId: 'test-role-' + i,
scopes: ['assume:test-role-' + (i + 1)],
};
})),
clients: [
{
clientId: 'big-test-client',
scopes: [
'assume:big-test-client',
],
includes: [
'special-scope',
].concat(_.range(N + 1).map(i => 'assume:test-role-' + i)),
excludes: ['*'],
},
],
});
const M = 5; // depth
const K = 25; // multiplier
test('test with depth = ' + M + ' x ' + K, {
roles: _.flatten([
_.flatten(_.range(K).map(k => {
return _.flatten(_.range(M).map(m => {
return {
roleId: 'k-' + k + '-' + m,
scopes: ['assume:k-' + k + '-' + (m + 1)],
};
}));
})),
_.range(K).map(k => {
return {
roleId: 'k-' + k + '-' + M,
scopes: ['special-scope'],
};
}),
]),
clients: [
{
clientId: 'c',
scopes: ['assume:k-2-0'],
includes: [
'special-scope',
].concat(_.range(M + 1).map(i => 'assume:k-2-' + i)),
excludes: ['*'],
},
],
});
test('a* scope grants all roles', {
roles: [
{
roleId: '-',
scopes: ['T'],
},
],
clients: [
{
clientId: 'test-client-1',
scopes: [
'a*',
],
includes: [
'T',
],
excludes: [
'scope-1', 'scope-2',
],
},
],
});
test('assume* scope grants all roles', {
roles: [
{
roleId: '-',
scopes: ['T'],
},
],
clients: [
{
clientId: 'test-client-1',
scopes: [
'assume*',
],
includes: [
'T',
],
excludes: [
'scope-1', 'scope-2',
],
},
],
});
test('assume:* scope grants all roles', {
roles: [
{
roleId: '-',
scopes: ['T'],
},
],
clients: [
{
clientId: 'test-client-1',
scopes: [
'assume:*',
],
includes: [
'T',
],
excludes: [
'scope-1', 'scope-2',
],
},
],
});
test('assume:project:<name> expands', {
roles: [
{
roleId: 'project:*',
scopes: ['irc:<..>', 'artifacts:private/<..>/*'],
},
],
clients: [
{
clientId: 'test-client-1',
scopes: [
'assume:project:my-prj',
],
includes: [
'irc:my-prj',
'artifacts:private/my-prj/*',
],
excludes: [
'scope-1', 'scope-2',
],
},
],
});
});
|
taskcluster/taskcluster-auth
|
test/rolelogic_test.js
|
JavaScript
|
mpl-2.0
| 12,558
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
import { SET_PREFERENCE, UPDATE_OUTPUT } from '../../../constants/actions';
import { requestSetPreference } from '../../../senders';
export const setPreference = (name, value) => ({
type: SET_PREFERENCE,
name,
value,
});
export const toggleSetting = (name) => ((dispatch, getState) => {
const value = !getState().preferences[name];
requestSetPreference(name, value);
});
const runAfterLanguageChange = (language) => ((dispatch, getState) => {
const { preferences } = getState();
const { recentLanguages } = preferences;
dispatch({
type: UPDATE_OUTPUT,
output: null,
});
if (!language) return;
if (recentLanguages.indexOf(language) < 0 && language !== 'auto') {
recentLanguages.unshift(language);
}
requestSetPreference('recentLanguages', recentLanguages.slice(0, 6));
});
export const swapLanguages = () => ((dispatch, getState) => {
const state = getState();
const { inputLang, outputLang } = state.preferences;
const { output } = state.pages.home;
if (inputLang === 'auto') {
if (output && output.inputLang) {
requestSetPreference('inputLang', outputLang);
requestSetPreference('outputLang', output.inputLang);
dispatch(runAfterLanguageChange());
}
return;
}
requestSetPreference('inputLang', outputLang);
requestSetPreference('outputLang', inputLang);
dispatch(runAfterLanguageChange());
});
export const updateInputLang = (value) => ((dispatch, getState) => {
if (getState().preferences.outputLang === value) { // newInputLang === outputLang
dispatch(swapLanguages());
return;
}
requestSetPreference('inputLang', value);
dispatch(runAfterLanguageChange(value));
});
export const updateOutputLang = (value) => ((dispatch, getState) => {
if (getState().preferences.inputLang === value) { // newOutputLang === inputLang
dispatch(swapLanguages());
return;
}
requestSetPreference('outputLang', value);
dispatch(runAfterLanguageChange(value));
});
|
translatium/translatium
|
src/state/root/preferences/actions.js
|
JavaScript
|
mpl-2.0
| 2,183
|
(function(){
var a;
a=function(){
var a,b;
b=document.createElement("script");
b.src="/assets/js/vendor/zxcvbn.js";
b.type="text/javascript";
b.async=!0;
a=document.getElementsByTagName("script")[0];
return a.parentNode.insertBefore(b,a)
};
null!=window.attachEvent?window.attachEvent("onload",a):window.addEventListener("load",a,!1)
}).call(this);
|
CryptArc/txbits
|
txbits/public/js/vendor/zxcvbn-async.js
|
JavaScript
|
agpl-3.0
| 421
|
var env = 'prod';
var api_url;
var admin_url;
if (env == 'local') {
admin_url = 'http://admin.forum.dev/';
api_url = 'http://api.forum.dev/';
} else {
admin_url = 'https://admin.forum-am.fr/';
api_url = 'https://api.forum-am.fr/';
}
var app = angular.module('app', ['ngResource',
'oc.lazyLoad',
'app.config',
'ui.router',
'ngSanitize',
'angular-bind-html-compile',
'localytics.directives',
'ngTouch',
'underscore',
'ngMessages',
'angularMoment',
'vcRecaptcha',
'commons',
'accueil',
'authentification',
'biensePreparer',
'exposants',
'infosPratique'
]).constant('urls', {
API: api_url,
ADMIN: admin_url
});
app.config(
function ($stateProvider, $httpProvider, $urlRouterProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = undefined;
$httpProvider.defaults.headers.put['Content-Type'] = undefined;
$httpProvider.defaults.transformRequest = angular.identity;
$urlRouterProvider.otherwise("accueil");
$stateProvider
.state('index', {
abstract: true,
url: "/", // root route
templateUrl: 'index.html'
})
.state('accueil', {
url: "/accueil?target_area",
templateUrl: 'src/accueil/accueil.html',
controller: 'accueilController',
resolve: {
lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'accueil',
files: [
'src/accueil/accueilController.js',
'src/accueil/accueilService.js'
]
});
}]
}
})
.state('actualites', {
url: '/actualites/{id:[0-9]*}',
templateUrl: 'src/accueil/accueil.html',
controller: 'accueilController',
resolve: {
lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'actualites',
files: [
'src/accueil/accueilController.js',
'src/accueil/accueilService.js'
]
});
}]
}
})
.state('connexion', {
url: "/connexion",
templateUrl: 'src/authentification/authentification.html',
controller: 'authentificationController',
resolve: {
lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'authentification',
files: [
'src/authentification/authentificationController.js',
'src/authentification/authentificationService.js'
]
});
}]
}
})
.state('inscription', {
url: "/inscription",
templateUrl: 'src/authentification/authentification.html',
controller: 'authentificationController',
resolve: {
lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'authentification',
files: [
'src/authentification/authentificationController.js',
'src/authentification/authentificationService.js'
]
});
}]
}
})
.state('biensepreparer', {
url: "/biensepreparer",
templateUrl: 'src/bien_se_preparer/bien_se_preparer.html',
controller: 'biensePreparerController',
resolve: {
lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'biensePreparer',
files: [
'src/bien_se_preparer/biensePreparerController.js',
'src/bien_se_preparer/biensePreparerService.js'
]
});
}]
}
})
.state('listeExposants', {
url: "/exposants",
templateUrl: 'src/exposants/exposants.html',
controller: 'exposantsController',
resolve: {
lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'listeExposants',
files: [
'src/exposants/exposantsController.js',
'src/exposants/exposantsService.js'
]
});
}]
}
})
.state('exposants', {
url: "/exposants/{id:[0-9]*}",
templateUrl: 'src/exposants/exposants.html',
controller: 'exposantsController',
resolve: {
lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'exposants',
files: [
'src/exposants/exposantsController.js',
'src/exposants/exposantsService.js'
]
});
}]
}
})
.state('infospratiques', {
url: "/infospratiques",
templateUrl: 'src/infos_pratique/infos_pratique.html',
controller: 'infosPratiqueController',
resolve: {
lazy: ['$ocLazyLoad', function ($ocLazyLoad) {
return $ocLazyLoad.load({
name: 'infosPratique',
files: [
'src/infos_pratique/infosPratiqueController.js',
'src/infos_pratique/infosPratiqueService.js',
'src/exposants/exposantsService.js'
]
});
}]
}
});
$httpProvider.interceptors.push('app.httpinterceptor');
});
app.run(function ($rootScope, $location, $http) {
console.log("app run ");
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options) {
});
});
//Intercepteur HTTP
app.factory('app.httpinterceptor', function ($q, $rootScope, $location) {
return {
// optional method
'request': function (config) {
return config || $q.when(config);
},
// optional method
'requestError': function (rejection) {
return $q.reject(rejection);
},
// optional method
'response': function (response) {
return response || $q.when(response);
},
// optional method
'responseError': function (rejection) {
if (rejection.status === 403) {
$location.path('/accueil');
}
return $q.reject(rejection);
}
};
});
|
Nyan-Kat/forumam_front
|
src/app.js
|
JavaScript
|
agpl-3.0
| 7,841
|
/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2014 Canonical Ltd.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
General Public License for more details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
(function() {
describe('Web handler', function() {
var mockXhr, webHandler, webModule;
var requirements = ['juju-env-web-handler'];
before(function(done) {
// Set up the YUI instance, the test utils and the web namespace.
YUI(GlobalConfig).use(requirements, function(Y) {
webModule = Y.namespace('juju.environments.web');
done();
});
});
beforeEach(function() {
// Instantiate a web handler and set up an XMLHttpRequest mock.
webHandler = new webModule.WebHandler();
var context = XMLHttpRequest.prototype;
mockXhr = {
addEventListener: sinon.stub(context, 'addEventListener'),
open: sinon.stub(context, 'open'),
setRequestHeader: sinon.stub(context, 'setRequestHeader'),
send: sinon.stub(context, 'send'),
removeEventListener: sinon.stub(
context, 'removeEventListener')
};
});
afterEach(function() {
webHandler.destroy();
// Reset all the method mocks.
Object.keys(mockXhr).forEach(key => {
mockXhr[key].restore();
});
});
// Ensure the progress event is correctly handled.
var assertProgressHandled = function(progressCallback) {
// Retrieve the registered progress handler.
var args = mockXhr.addEventListener.args;
var progressHandler = args[0][1];
// Set up a progress event and call the progress handler.
var evt = {type: 'progress'};
progressHandler(evt);
// The progress callback has been correctly called.
assert.strictEqual(progressCallback.callCount, 1);
assert.deepEqual(progressCallback.lastCall.args, [evt]);
// The event listeners are only removed when the completed callback is
// called.
assert.strictEqual(mockXhr.removeEventListener.called, false);
};
// Ensure the completed event is correctly handled.
var assertCompletedHandled = function(completedCallback) {
// Retrieve the registered handlers.
var args = mockXhr.addEventListener.args;
var progressHandler = args[0][1];
var completedHandler = args[1][1];
// Set up a load event and call the completed handler.
var evt = {type: 'load'};
completedHandler(evt);
// The completion callback has been correctly called.
assert.strictEqual(completedCallback.callCount, 1);
assert.deepEqual(completedCallback.lastCall.args, [evt]);
// The event listeners have been removed.
assert.strictEqual(mockXhr.removeEventListener.callCount, 3);
args = mockXhr.removeEventListener.args;
assert.deepEqual(args[0], ['progress', progressHandler]);
assert.deepEqual(args[1], ['error', completedHandler]);
assert.deepEqual(args[2], ['load', completedHandler]);
};
describe('sendPostRequest', function() {
it('opens and sends an XHR request with the proper data', function() {
var path = '/juju-core/charms?series=trusty';
var headers = {'Content-Type': 'application/zip'};
var data = 'a zip file object';
// Make a POST request.
webHandler.sendPostRequest(
path, headers, data, 'user', 'passwd', false,
function() {return 'progress';}, function() {return 'completed';});
// Ensure the xhr instance has been used properly.
assert.strictEqual(mockXhr.addEventListener.callCount, 3);
// Two events listeners are added, one for request's progress and one
// for request's completion.
var args = mockXhr.addEventListener.args;
assert.strictEqual(args[0][0], 'progress');
assert.strictEqual(args[1][0], 'error');
assert.strictEqual(args[2][0], 'load');
// The xhr is then asynchronously opened.
assert.strictEqual(mockXhr.open.callCount, 1);
assert.deepEqual(mockXhr.open.lastCall.args, ['POST', path, true]);
// Headers are properly set up.
assert.strictEqual(mockXhr.setRequestHeader.callCount, 2);
args = mockXhr.setRequestHeader.args;
assert.deepEqual(args[0], ['Content-Type', 'application/zip']);
assert.deepEqual(args[1], ['Authorization', 'Basic dXNlcjpwYXNzd2Q=']);
// The zip file is then correctly sent.
assert.strictEqual(mockXhr.send.callCount, 1);
assert.deepEqual(mockXhr.send.lastCall.args, ['a zip file object']);
// The event listeners are only removed when the completed callback is
// called.
assert.strictEqual(mockXhr.removeEventListener.called, false);
});
it('handles request progress', function() {
var progressCallback = sinon.stub();
// Make a POST request.
webHandler.sendPostRequest(
'/path/', {}, 'data', 'user', 'passwd', false, progressCallback);
assertProgressHandled(progressCallback);
});
it('handles request completion', function() {
var completedCallback = sinon.stub();
// Make a POST request.
webHandler.sendPostRequest(
'/path/', {}, 'data', 'user', 'passwd', false,
function() {}, completedCallback);
assertCompletedHandled(completedCallback);
});
});
describe('sendPutRequest', function() {
it('opens and sends an XHR request with the proper data', function() {
var path = '/juju-core/charms?series=trusty';
var headers = {'Content-Type': 'application/zip'};
var data = 'a zip file object';
// Make a POST request.
webHandler.sendPutRequest(
path, headers, data, 'user', 'passwd', false,
function() {return 'progress';}, function() {return 'completed';});
// Ensure the xhr instance has been used properly.
assert.strictEqual(mockXhr.addEventListener.callCount, 3);
// Two events listeners are added, one for request's progress and one
// for request's completion.
var args = mockXhr.addEventListener.args;
assert.strictEqual(args[0][0], 'progress');
assert.strictEqual(args[1][0], 'error');
assert.strictEqual(args[2][0], 'load');
// The xhr is then asynchronously opened.
assert.strictEqual(mockXhr.open.callCount, 1);
assert.deepEqual(mockXhr.open.lastCall.args, ['PUT', path, true]);
// Headers are properly set up.
assert.strictEqual(mockXhr.setRequestHeader.callCount, 2);
args = mockXhr.setRequestHeader.args;
assert.deepEqual(args[0], ['Content-Type', 'application/zip']);
assert.deepEqual(args[1], ['Authorization', 'Basic dXNlcjpwYXNzd2Q=']);
// The zip file is then correctly sent.
assert.strictEqual(mockXhr.send.callCount, 1);
assert.deepEqual(mockXhr.send.lastCall.args, ['a zip file object']);
// The event listeners are only removed when the completed callback is
// called.
assert.strictEqual(mockXhr.removeEventListener.called, false);
});
it('handles request progress', function() {
var progressCallback = sinon.stub();
// Make a POST request.
webHandler.sendPutRequest(
'/path/', {}, 'data', 'user', 'passwd', false, progressCallback);
assertProgressHandled(progressCallback);
});
it('handles request completion', function() {
var completedCallback = sinon.stub();
// Make a POST request.
webHandler.sendPutRequest(
'/path/', {}, 'data', 'user', 'passwd', false,
function() {}, completedCallback);
assertCompletedHandled(completedCallback);
});
});
describe('sendGetRequest', function() {
it('opens and sends an XHR request with the proper data', function() {
var path = '/juju-core/charms?url=local:trusty/django-42';
// Make a GET request.
webHandler.sendGetRequest(
path, null, 'user', 'passwd', false,
function() {return 'progress';}, function() {return 'completed';});
// Ensure the xhr instance has been used properly.
assert.strictEqual(mockXhr.addEventListener.callCount, 3);
// Two events listeners are added, one for request's progress and one
// for request's completion.
var args = mockXhr.addEventListener.args;
assert.strictEqual(args[0][0], 'progress');
assert.strictEqual(args[1][0], 'error');
assert.strictEqual(args[2][0], 'load');
// The xhr is then asynchronously opened.
assert.strictEqual(mockXhr.open.callCount, 1);
assert.deepEqual(mockXhr.open.lastCall.args, ['GET', path, true]);
// Headers are properly set up.
assert.strictEqual(mockXhr.setRequestHeader.callCount, 1);
args = mockXhr.setRequestHeader.args;
assert.deepEqual(args[0], ['Authorization', 'Basic dXNlcjpwYXNzd2Q=']);
// The zip file is then correctly sent.
assert.strictEqual(mockXhr.send.callCount, 1);
assert.lengthOf(mockXhr.send.lastCall.args, 0);
// The event listeners are only removed when the completed callback is
// called.
assert.strictEqual(mockXhr.removeEventListener.called, false);
});
it('handles request progress', function() {
var progressCallback = sinon.stub();
// Make a GET request.
webHandler.sendGetRequest(
'/path/', {}, 'user', 'passwd', false, progressCallback);
assertProgressHandled(progressCallback);
});
it('handles request completion', function() {
var completedCallback = sinon.stub();
// Make a GET request.
webHandler.sendGetRequest(
'/path/', {}, 'user', 'passwd', false,
function() {}, completedCallback);
assertCompletedHandled(completedCallback);
});
});
describe('sendPatchRequest', function() {
it('opens and sends an XHR request with the proper data', function() {
var path = '/juju-core/charms?series=trusty';
var headers = {'Content-Type': 'application/zip'};
var data = 'a zip file object';
// Make a PATCH request.
webHandler.sendPatchRequest(
path, headers, data, 'user', 'passwd', false,
function() {return 'progress';}, function() {return 'completed';});
// Ensure the xhr instance has been used properly.
assert.strictEqual(mockXhr.addEventListener.callCount, 3);
// Two events listeners are added, one for request's progress and one
// for request's completion.
var args = mockXhr.addEventListener.args;
assert.strictEqual(args[0][0], 'progress');
assert.strictEqual(args[1][0], 'error');
assert.strictEqual(args[2][0], 'load');
// The xhr is then asynchronously opened.
assert.strictEqual(mockXhr.open.callCount, 1);
assert.deepEqual(mockXhr.open.lastCall.args, ['PATCH', path, true]);
// Headers are properly set up.
assert.strictEqual(mockXhr.setRequestHeader.callCount, 2);
args = mockXhr.setRequestHeader.args;
assert.deepEqual(args[0], ['Content-Type', 'application/zip']);
assert.deepEqual(args[1], ['Authorization', 'Basic dXNlcjpwYXNzd2Q=']);
// The zip file is then correctly sent.
assert.strictEqual(mockXhr.send.callCount, 1);
assert.deepEqual(mockXhr.send.lastCall.args, ['a zip file object']);
// The event listeners are only removed when the completed callback is
// called.
assert.strictEqual(mockXhr.removeEventListener.called, false);
});
it('handles request progress', function() {
var progressCallback = sinon.stub();
// Make a PATCH request.
webHandler.sendPatchRequest(
'/path/', {}, 'data', 'user', 'passwd', false, progressCallback);
assertProgressHandled(progressCallback);
});
it('handles request completion', function() {
var completedCallback = sinon.stub();
// Make a PATCH request.
webHandler.sendPatchRequest(
'/path/', {}, 'data', 'user', 'passwd', false,
function() {}, completedCallback);
assertCompletedHandled(completedCallback);
});
});
it('defines a function which helps creating auth headers', function() {
var header = webHandler._createAuthorizationHeader('myuser', 'mypasswd');
assert.strictEqual(header, 'Basic bXl1c2VyOm15cGFzc3dk');
});
describe('getUrl', function() {
it('returns a complete URL based on the given credentials', function() {
var url = webHandler.getUrl('/my/path', 'myuser', 'mypassword');
var expectedUrl = 'http://myuser:mypassword@' +
window.location.host + '/my/path';
assert.strictEqual(url, expectedUrl);
});
});
});
})();
|
bac/juju-gui
|
jujugui/static/gui/src/test/test_web_handler.js
|
JavaScript
|
agpl-3.0
| 13,636
|
import React from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
// material components
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";
import FormControl from "@material-ui/core/FormControl";
import FormHelperText from "@material-ui/core/FormHelperText";
// jarr
import editPanelStyle from "../editPanelStyle";
import { editLoadedObj } from "../slice";
const mapStateToProps = (state) => ({
link: state.edit.loadedObj.link,
links: state.edit.loadedObj.links,
});
const mapDispatchToProp = (dispatch) => ({
edit(value) {
dispatch(editLoadedObj({ key: "link", value }));
}
});
const ProposedLinks = ({ link, links, edit }) => {
const classes = editPanelStyle();
if (!links) {
return null;
}
return (
<FormControl>
<FormHelperText>Other possible feed link have been found :</FormHelperText>
<Select variant="outlined" value={link}
onChange={(e) => edit(e.target.value)}
className={classes.editPanelInput}
>
{links.map((proposedLink) => (
<MenuItem key={`l${links.indexOf(proposedLink)}`}
value={proposedLink}>{proposedLink}</MenuItem>
))}
</Select>
</FormControl>
);
};
ProposedLinks.propTypes = {
link: PropTypes.string,
links: PropTypes.array,
edit: PropTypes.func.isRequired,
};
export default connect(mapStateToProps, mapDispatchToProp)(ProposedLinks);
|
jaesivsm/JARR
|
jsclient/src/features/editpanel/Feed/ProposedLinks.js
|
JavaScript
|
agpl-3.0
| 1,467
|
$(document).ready(function () {
//do not show when upgrade is in progress or an error message
//is visible on the login page
if (jQuery('#upgrade').length === 0 && jQuery('#body-login .error').length === 0) {
showSetPassword();
}
});
// Done when "colorBox" is displayed
function showSetPasswordComplete() {
$("#userSetPassword #passwordform").on('submit', function(e){
// TODO: implement basic tests (fields must be set, fields must be same)
if (($('#pass1').val() == '') || ($('#pass2').val() == '')) {
$('#passworderror').html(t('user_set_password', 'Both password fields must be set.'));
$('#passworderror').show();
return false;
}
if ($('#pass1').val() != $('#pass2').val()) {
$('#passworderror').html(t('user_set_password', 'Passwords differs.'));
$('#passworderror').show();
return false;
}
if ($('#pass1').val() !== '') {
var password = $('#pass1').val();
$.ajax({
type: 'POST',
url: OC.generateUrl('/apps/password_policy/policy/set_password'),
data: {password: password},
async: false
}).
done(function(data) {
if (data.status == 'success') {
var post = $( "#passwordform" ).serialize();
$('#passwordchanged').hide();
$('#passworderror').hide();
// Ajax foo
$.post(OC.generateUrl('/apps/user_set_password/api/1.0/changepassword'), post, function(data){
if ( data.status === "success" ){
$('.strengthify-wrapper').tipsy('hide');
OC.Notification.showTemporary( t('user_set_password', 'Password successfully changed') );
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
$.colorbox.close();
}
else {
if (typeof(data.data) !== "undefined") {
$('#passworderror').html(data.data.msg);
} else {
$('#passworderror').html(t('user_set_password', 'Unable to change password'));
}
$('#passworderror').show();
}
});
return false;
}
else {
$('#passworderror').html(t('password_policy', 'Password does not comply with the Password Policy.'));
$('#passworderror').show();
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
return false;
}
});
}
else {
$('#passwordchanged').hide();
$('#passworderror').show();
return false;
}
return false;
});
$('#pass1').strengthify({
zxcvbn: OC.linkTo('core','vendor/zxcvbn/dist/zxcvbn.js'),
titles: [
t('core', 'Very weak password'),
t('core', 'Weak password'),
t('core', 'So-so password'),
t('core', 'Good password'),
t('core', 'Strong password')
]
});
var setShowPassword = function(input, label) {
input.showPassword().keyup();
};
setShowPassword($('#pass1'), $('label[for=personal-show]'));
setShowPassword($('#pass2'), $('label[for=personal-confirm-show]'));
}
function check_password_policy(e) {
var password = $('#pass1').val();
$.ajax({
type: 'POST',
url: OC.generateUrl('/apps/password_policy/policy/set_password'),
data: {password: password},
success: function(data){
if (data.status == 'success') {
return true;
}
else {
$('#passworderror').html(t('password_policy', 'Password does not comply with the Password Policy.'));
$('#passworderror').show();
e.stopImmediatePropagation();
e.stopPropagation();
e.preventDefault();
return false;
}
}
});
}
|
CNRS-DSI-Dev/user_set_password
|
js/activate.js
|
JavaScript
|
agpl-3.0
| 4,458
|
/* This file is part of Stereoskopix FOV2GO for Unity V3.
* URL: http://www.stereoskopix.com/ * Please direct any bugs/comments/suggestions to hoberman@usc.edu.
* Stereoskopix FOV2GO for Unity Copyright (c) 2011-12 Perry Hoberman & MxR Lab. All rights reserved.
* This script goes in the Editor folder. It provides a custom inspector for s3dDeviceManager.
*/
@CustomEditor (s3dDeviceManager)
class s3dDeviceManagerEditor extends Editor {
function OnInspectorGUI () {
EditorGUIUtility.LookLikeControls(170,30);
var allowSceneObjects : boolean = !EditorUtility.IsPersistent (target);
EditorGUILayout.BeginVertical("box");
target.phoneLayout = EditorGUILayout.EnumPopup(GUIContent("Phone Layout","Select Phone Layout"), target.phoneLayout);
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
target.use3dCursor = EditorGUILayout.Toggle(GUIContent("Use 3D Cursor","Use 3D Cursor"), target.use3dCursor);
if (target.use3dCursor) {
EditorGUI.indentLevel = 1;
target.cursor3D = EditorGUILayout.ObjectField(GUIContent("3D Cursor","Select s3dGuiTexture for Cursor"),target.cursor3D,s3dGuiCursor,allowSceneObjects);
EditorGUI.indentLevel = 0;
}
target.movePadPosition = EditorGUILayout.EnumPopup(GUIContent("Move Pad Position","Select Move Pad Position"), target.movePadPosition);
if (target.movePadPosition != 0) {
EditorGUI.indentLevel = 1;
target.moveTouchpad = EditorGUILayout.ObjectField(GUIContent("Move Touchpad","Select s3dTouchpad for Move"),target.moveTouchpad,s3dTouchpad,allowSceneObjects);
EditorGUI.indentLevel = 0;
}
target.turnPadPosition = EditorGUILayout.EnumPopup(GUIContent("Turn Pad Position","Select Turn Pad Position"), target.turnPadPosition);
if (target.turnPadPosition != 0) {
EditorGUI.indentLevel = 1;
target.turnTouchpad = EditorGUILayout.ObjectField(GUIContent("Turn Touchpad","Select s3dTouchpad for Turn"),target.turnTouchpad,s3dTouchpad,allowSceneObjects);
EditorGUI.indentLevel = 0;
}
target.pointPadPosition = EditorGUILayout.EnumPopup(GUIContent("Cursor Pad Position","Select Cursor Pad Position"), target.pointPadPosition);
if (target.pointPadPosition != 0) {
EditorGUI.indentLevel = 1;
target.pointTouchpad = EditorGUILayout.ObjectField(GUIContent("Cursor Touchpad","Select s3dTouchpad for Cursor"),target.pointTouchpad,s3dTouchpad,allowSceneObjects);
EditorGUI.indentLevel = 0;
}
target.useStereoParamsTouchpad = EditorGUILayout.Toggle(GUIContent("Show 3D Params Touchpad","Use Stereo Params Touchpad"), target.useStereoParamsTouchpad);
if (target.useStereoParamsTouchpad) {
EditorGUI.indentLevel = 1;
target.stereoParamsTouchpad = EditorGUILayout.ObjectField(GUIContent("Stereo Params Touchpad","Select s3dTouchpad for Stereo Params"),target.stereoParamsTouchpad,s3dTouchpad,allowSceneObjects);
EditorGUI.indentLevel = 2;
target.interaxialTouchpad = EditorGUILayout.ObjectField(GUIContent("Interaxial Touchpad","Select s3dTouchpad for Interaxial"),target.interaxialTouchpad,s3dTouchpad,allowSceneObjects);
target.zeroPrlxTouchpad = EditorGUILayout.ObjectField(GUIContent("Zero Prlx Touchpad","Select s3dTouchpad for Zero Prlx"),target.zeroPrlxTouchpad,s3dTouchpad,allowSceneObjects);
target.hitTouchpad = EditorGUILayout.ObjectField(GUIContent("H I T Touchpad","Select s3dTouchpad for H I T"),target.hitTouchpad,s3dTouchpad,allowSceneObjects);
EditorGUI.indentLevel = 0;
}
target.showLoadNewScenePad = EditorGUILayout.Toggle(GUIContent("Show Load Scene Touchpad","Show Load New Scene Touchpad"), target.showLoadNewScenePad);
if (target.showLoadNewScenePad) {
EditorGUI.indentLevel = 1;
target.loadNewSceneTouchpad = EditorGUILayout.ObjectField(GUIContent("Load New Scene Touchpad","Select s3dTouchpad for Load New Scene"),target.loadNewSceneTouchpad,s3dTouchpad,allowSceneObjects);
EditorGUI.indentLevel = 0;
}
target.showFpsTool01 = EditorGUILayout.Toggle(GUIContent("Show FPS Tool 01 Touchpad","Show FPS Tool 01 Touchpad"), target.showFpsTool01);
if (target.showFpsTool01) {
EditorGUI.indentLevel = 1;
target.fpsTool01 = EditorGUILayout.ObjectField(GUIContent("FPS Tool 01 Touchpad","Select s3dTouchpad for FPS Tool 01"),target.fpsTool01,s3dTouchpad,allowSceneObjects);
EditorGUI.indentLevel = 0;
}
target.showFpsTool02 = EditorGUILayout.Toggle(GUIContent("Show FPS Tool 02 Touchpad","Show FPS Tool 02 Touchpad"), target.showFpsTool02);
if (target.showFpsTool02) {
EditorGUI.indentLevel = 1;
target.fpsTool02 = EditorGUILayout.ObjectField(GUIContent("FPS Tool 02 Touchpad","Select s3dTouchpad for FPS Tool 02"),target.fpsTool02,s3dTouchpad,allowSceneObjects);
EditorGUI.indentLevel = 0;
}
EditorGUILayout.EndVertical();
if (GUI.changed) {
EditorUtility.SetDirty (target);
}
}
}
|
hcilab-um/UnityHandlers
|
UnityMultiplatform/unity_epson-200/Assets/FOV2GO/Editor/s3dDeviceManagerEditor.js
|
JavaScript
|
agpl-3.0
| 4,845
|
/*
* Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Ext.define('Traccar.view.State', {
extend: 'Ext.grid.Panel',
xtype: 'stateView',
requires: [
'Traccar.view.StateController'
],
controller: 'state',
store: 'Attributes',
title: Strings.stateTitle,
columns: [{
text: Strings.stateName,
dataIndex: 'name',
flex: 1
}, {
text: Strings.stateValue,
dataIndex: 'value',
flex: 1
}]
});
|
erlymon/erlymon
|
apps/erlymon/priv/web/app/view/State.js
|
JavaScript
|
agpl-3.0
| 1,052
|
/**
* Store data to enroll learners into the course
*/
;(function (define) {
'use strict';
define([
'backbone'
],
function( Backbone) {
return Backbone.Model.extend({
defaults: {
course_id: '',
optIn: false,
}
});
}
);
}).call(this, define || RequireJS.define);
|
waheedahmed/edx-platform
|
lms/static/js/learner_dashboard/models/course_enroll_model.js
|
JavaScript
|
agpl-3.0
| 410
|
/**
* PUI Object
*/
PUI = {
zindex : 1000,
/**
* Aligns container scrollbar to keep item in container viewport, algorithm copied from jquery-ui menu widget
*/
scrollInView: function(container, item) {
var borderTop = parseFloat(container.css('borderTopWidth')) || 0,
paddingTop = parseFloat(container.css('paddingTop')) || 0,
offset = item.offset().top - container.offset().top - borderTop - paddingTop,
scroll = container.scrollTop(),
elementHeight = container.height(),
itemHeight = item.outerHeight(true);
if(offset < 0) {
container.scrollTop(scroll + offset);
}
else if((offset + itemHeight) > elementHeight) {
container.scrollTop(scroll + offset - elementHeight + itemHeight);
}
},
isIE: function(version) {
return ($.browser.msie && parseInt($.browser.version, 10) === version);
},
escapeRegExp: function(text) {
return text.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
},
escapeHTML: function(value) {
return value.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
},
clearSelection: function() {
if(window.getSelection) {
if(window.getSelection().empty) {
window.getSelection().empty();
} else if(window.getSelection().removeAllRanges) {
window.getSelection().removeAllRanges();
}
} else if(document.selection && document.selection.empty) {
document.selection.empty();
}
},
inArray: function(arr, item) {
for(var i = 0; i < arr.length; i++) {
if(arr[i] === item) {
return true;
}
}
return false;
}
};
|
echinopsii/net.echinopsii.ariane.community.core.portal
|
wresources/src/main/webapp/ariane/test/ajs/primeui-0.9.6/development/js/core/core.js
|
JavaScript
|
agpl-3.0
| 1,852
|
/*
***** BEGIN LICENSE BLOCK *****
Copyright © 2009 Center for History and New Media
George Mason University, Fairfax, Virginia, USA
http://zotero.org
This file is part of Zotero.
Zotero is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Zotero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
Zotero.ItemFields = new function() {
// Private members
var _fields = {};
var _fieldsFormats = [];
var _fieldsLoaded;
var _fieldFormats = [];
var _itemTypeFields = [];
var _baseTypeFields = [];
var _typeFieldIDsByBase = {};
var _typeFieldNamesByBase = {};
var self = this;
// Privileged methods
this.getName = getName;
this.getID = getID;
this.getLocalizedString = getLocalizedString;
this.isValidForType = isValidForType;
this.isInteger = isInteger;
this.getItemTypeFields = getItemTypeFields;
this.isBaseField = isBaseField;
this.isFieldOfBase = isFieldOfBase;
this.getBaseMappedFields = getBaseMappedFields;
this.getFieldIDFromTypeAndBase = getFieldIDFromTypeAndBase;
this.getBaseIDFromTypeAndField = getBaseIDFromTypeAndField;
this.getTypeFieldsFromBase = getTypeFieldsFromBase;
/*
* Return the fieldID for a passed fieldID or fieldName
*/
function getID(field) {
if (!_fieldsLoaded) {
_loadFields();
}
if (typeof field == 'number') {
return field;
}
return _fields[field] ? _fields[field]['id'] : false;
}
/*
* Return the fieldName for a passed fieldID or fieldName
*/
function getName(field) {
if (!_fieldsLoaded) {
_loadFields();
}
return _fields[field] ? _fields[field]['name'] : false;
}
function getLocalizedString(itemType, field) {
// unused currently
//var typeName = Zotero.ItemTypes.getName(itemType);
var fieldName = Zotero.ItemFields.getName(field);
// Fields in the items table are special cases
switch (field) {
case 'dateAdded':
case 'dateModified':
case 'itemType':
return Zotero.getString("itemFields." + field);
}
// TODO: different labels for different item types
try {
_fieldCheck(field, 'getLocalizedString');
}
// TEMP
catch (e) {
try {
asfasfa();
}
catch (e2) {
Zotero.debug(e2);
}
Zotero.debug(e);
throw (e);
}
if (_fields[field].label) {
return _fields[field].label;
}
else {
try {
var loc = Zotero.getString("itemFields." + fieldName);
}
// If localized string not found, try base field
catch (e) {
Zotero.debug("Localized string not found for field '" + fieldName + "' -- trying base field");
var baseFieldID = this.getBaseIDFromTypeAndField(itemType, field);
fieldName = this.getName(baseFieldID);
var loc = Zotero.getString("itemFields." + fieldName);
}
return loc;
}
}
function isValidForType(fieldID, itemTypeID) {
_fieldCheck(fieldID, 'isValidForType');
if (!_fields[fieldID]['itemTypes']) {
return false;
}
return !!_fields[fieldID]['itemTypes'][itemTypeID];
}
function isInteger(fieldID) {
_fieldCheck(fieldID, 'isInteger');
var ffid = _fields[fieldID]['formatID'];
return _fieldFormats[ffid] ? _fieldFormats[ffid]['isInteger'] : false;
}
this.isMultiline = function (fieldID) {
_fieldCheck(fieldID, 'isMultiline');
// TEMP: extra and abstractNote
return 22 || 90;
}
this.isCustom = function (fieldID) {
_fieldCheck(fieldID, 'isCustom');
return _fields[fieldID].custom;
}
/*
* Returns an array of fieldIDs for a given item type
*/
function getItemTypeFields(itemTypeID) {
if (!_fieldsLoaded) {
_loadFields();
}
if (_itemTypeFields[itemTypeID]) {
return _itemTypeFields[itemTypeID];
}
if (!itemTypeID) {
throw("Invalid item type id '" + itemTypeID
+ "' provided to getItemTypeFields()");
}
var sql = 'SELECT fieldID FROM itemTypeFieldsCombined '
+ 'WHERE itemTypeID=' + itemTypeID + ' ORDER BY orderIndex';
var fields = Zotero.DB.columnQuery(sql);
_itemTypeFields[itemTypeID] = fields ? fields : [];
return _itemTypeFields[itemTypeID];
}
function isBaseField(field) {
_fieldCheck(field, arguments.callee.name);
return _fields[field]['isBaseField'];
}
function isFieldOfBase(field, baseField) {
var fieldID = _fieldCheck(field, 'isFieldOfBase');
var baseFieldID = this.getID(baseField);
if (!baseFieldID) {
throw ("Invalid field '" + baseField + '" for base field in ItemFields.getFieldIDFromTypeAndBase()');
}
if (fieldID == baseFieldID) {
return true;
}
var typeFields = this.getTypeFieldsFromBase(baseFieldID);
return typeFields.indexOf(fieldID) != -1;
}
function getBaseMappedFields() {
return Zotero.DB.columnQuery("SELECT DISTINCT fieldID FROM baseFieldMappingsCombined");
}
/*
* Returns the fieldID of a type-specific field for a given base field
* or false if none
*
* Examples:
*
* 'audioRecording' and 'publisher' returns label's fieldID
* 'book' and 'publisher' returns publisher's fieldID
* 'audioRecording' and 'number' returns false
*
* Accepts names or ids
*/
function getFieldIDFromTypeAndBase(itemType, baseField) {
var itemTypeID = Zotero.ItemTypes.getID(itemType);
if (!itemTypeID) {
throw ("Invalid item type '" + itemType + "' in ItemFields.getFieldIDFromTypeAndBase()");
}
var baseFieldID = this.getID(baseField);
if (!baseFieldID) {
throw ("Invalid field '" + baseField + '" for base field in ItemFields.getFieldIDFromTypeAndBase()');
}
return _baseTypeFields[itemTypeID][baseFieldID];
}
/*
* Returns the fieldID of the base field for a given type-specific field
* or false if none
*
* Examples:
*
* 'audioRecording' and 'label' returns publisher's fieldID
* 'book' and 'publisher' returns publisher's fieldID
* 'audioRecording' and 'runningTime' returns false
*
* Accepts names or ids
*/
function getBaseIDFromTypeAndField(itemType, typeField) {
var itemTypeID = Zotero.ItemTypes.getID(itemType);
var typeFieldID = this.getID(typeField);
if (!itemTypeID) {
throw ("Invalid item type '" + itemType + "' in ItemFields.getBaseIDFromTypeAndField()");
}
_fieldCheck(typeField, 'getBaseIDFromTypeAndField');
if (!this.isValidForType(typeFieldID, itemTypeID)) {
throw ("'" + typeField + "' is not a valid field for '" + itemType + "' in ItemFields.getBaseIDFromTypeAndField()");
}
// If typeField is already a base field, just return that
if (this.isBaseField(typeFieldID)) {
return typeFieldID;
}
return Zotero.DB.valueQuery("SELECT baseFieldID FROM baseFieldMappingsCombined "
+ "WHERE itemTypeID=? AND fieldID=?", [itemTypeID, typeFieldID]);
}
/*
* Returns an array of fieldIDs associated with a given base field
*
* e.g. 'publisher' returns fieldIDs for [university, studio, label, network]
*/
function getTypeFieldsFromBase(baseField, asNames) {
var baseFieldID = this.getID(baseField);
if (!baseFieldID) {
throw ("Invalid base field '" + baseField + '" in ItemFields.getTypeFieldsFromBase()');
}
if (asNames) {
return _typeFieldNamesByBase[baseFieldID] ?
_typeFieldNamesByBase[baseFieldID] : false;
}
return _typeFieldIDsByBase[baseFieldID] ?
_typeFieldIDsByBase[baseFieldID] : false;
}
this.isAutocompleteField = function (field) {
field = this.getName(field);
var autoCompleteFields = [
'journalAbbreviation',
'series',
'seriesTitle',
'seriesText',
'libraryCatalog',
'callNumber',
'archive',
'archiveLocation',
'language',
'programmingLanguage',
'rights',
// TEMP - NSF
'programDirector',
'institution',
'discipline'
];
// Add the type-specific versions of these base fields
var baseACFields = ['publisher', 'publicationTitle', 'type', 'medium', 'place'];
autoCompleteFields = autoCompleteFields.concat(baseACFields);
for (var i=0; i<baseACFields.length; i++) {
var add = Zotero.ItemFields.getTypeFieldsFromBase(baseACFields[i], true)
autoCompleteFields = autoCompleteFields.concat(add);
}
return autoCompleteFields.indexOf(field) != -1;
}
/**
* A long field expands into a multiline textbox while editing but displays
* as a single line in non-editing mode; newlines are not allowed
*/
this.isLong = function (field) {
field = this.getName(field);
var fields = [
'title'
];
return fields.indexOf(field) != -1;
}
/**
* A multiline field displays as a multiline text box in editing mode
* and non-editing mode; newlines are allowed
*/
this.isMultiline = function (field) {
field = this.getName(field);
var fields = [
'abstractNote',
'extra',
// TEMP - NSF
'address'
];
return fields.indexOf(field) != -1;
}
this.reload = function () {
_fieldsLoaded = false;
}
/**
* Check whether a field is valid, throwing an exception if not
* (since it should never actually happen)
**/
function _fieldCheck(field, func) {
var fieldID = self.getID(field);
if (!fieldID) {
throw ("Invalid field '" + field + (func ? "' in ItemFields." + func + "()" : "'"));
}
return fieldID;
}
/*
* Returns hash array of itemTypeIDs for which a given field is valid
*/
function _getFieldItemTypes() {
var sql = 'SELECT fieldID, itemTypeID FROM itemTypeFieldsCombined';
var results = Zotero.DB.query(sql);
if (!results) {
throw ('No fields in itemTypeFields!');
}
var fields = new Array();
for (var i=0; i<results.length; i++) {
if (!fields[results[i]['fieldID']]) {
fields[results[i]['fieldID']] = new Array();
}
fields[results[i]['fieldID']][results[i]['itemTypeID']] = true;
}
return fields;
}
/*
* Build a lookup table for base field mappings
*/
function _loadBaseTypeFields() {
_typeFieldIDsByBase = {};
_typeFieldNamesByBase = {};
// Grab all fields, base field or not
var sql = "SELECT IT.itemTypeID, F.fieldID AS baseFieldID, BFM.fieldID "
+ "FROM itemTypesCombined IT LEFT JOIN fieldsCombined F "
+ "LEFT JOIN baseFieldMappingsCombined BFM"
+ " ON (IT.itemTypeID=BFM.itemTypeID AND F.fieldID=BFM.baseFieldID)";
var rows = Zotero.DB.query(sql);
var sql = "SELECT DISTINCT baseFieldID FROM baseFieldMappingsCombined";
var baseFields = Zotero.DB.columnQuery(sql);
var fields = [];
for each(var row in rows) {
if (!fields[row.itemTypeID]) {
fields[row.itemTypeID] = [];
}
if (row.fieldID) {
fields[row.itemTypeID][row.baseFieldID] = row.fieldID;
}
// If a base field and already valid for the type, just use that
else if (isBaseField(row.baseFieldID) &&
isValidForType(row.baseFieldID, row.itemTypeID)) {
fields[row.itemTypeID][row.baseFieldID] = row.baseFieldID;
}
// Set false for other fields so that we don't need to test for
// existence
else {
fields[row.itemTypeID][row.baseFieldID] = false;
}
}
_baseTypeFields = fields;
var sql = "SELECT baseFieldID, fieldID, fieldName "
+ "FROM baseFieldMappingsCombined JOIN fieldsCombined USING (fieldID)";
var rows = Zotero.DB.query(sql);
for each(var row in rows) {
if (!_typeFieldIDsByBase[row['baseFieldID']]) {
_typeFieldIDsByBase[row['baseFieldID']] = [];
_typeFieldNamesByBase[row['baseFieldID']] = [];
}
_typeFieldIDsByBase[row['baseFieldID']].push(row['fieldID']);
_typeFieldNamesByBase[row['baseFieldID']].push(row['fieldName']);
}
}
/*
* Load all fields into an internal hash array
*/
function _loadFields() {
_fields = {};
_fieldsFormats = [];
_itemTypeFields = [];
var result = Zotero.DB.query('SELECT * FROM fieldFormats');
for (var i=0; i<result.length; i++) {
_fieldFormats[result[i]['fieldFormatID']] = {
regex: result[i]['regex'],
isInteger: result[i]['isInteger']
};
}
var fields = Zotero.DB.query('SELECT * FROM fieldsCombined');
var fieldItemTypes = _getFieldItemTypes();
var sql = "SELECT DISTINCT baseFieldID FROM baseFieldMappingsCombined";
var baseFields = Zotero.DB.columnQuery(sql);
for each(var field in fields) {
_fields[field['fieldID']] = {
id: field['fieldID'],
name: field.fieldName,
label: field.label,
custom: !!field.custom,
isBaseField: (baseFields.indexOf(field['fieldID']) != -1),
formatID: field['fieldFormatID'],
itemTypes: fieldItemTypes[field['fieldID']]
};
// Store by name as well as id
_fields[field['fieldName']] = _fields[field['fieldID']];
}
_fieldsLoaded = true;
_loadBaseTypeFields();
}
}
|
fbennett/zotero
|
chrome/content/zotero/xpcom/data/itemFields.js
|
JavaScript
|
agpl-3.0
| 13,152
|
define([
'backbone',
'./metric'
], function (Backbone, Metric) {
return Backbone.Collection.extend({
model: Metric,
url: function () {
return window.baseUrl + '/api/metrics/search';
},
parse: function (r) {
this.total = r.total;
this.p = r.p;
this.ps = r.ps;
return r.metrics;
},
fetch: function (options) {
var opts = _.defaults(options || {}, { data: {} });
this.q = opts.data.q;
opts.data.isCustom = true;
return Backbone.Collection.prototype.fetch.call(this, opts);
},
fetchMore: function () {
var p = this.p + 1;
return this.fetch({ add: true, remove: false, data: { p: p, ps: this.ps, q: this.q } });
},
refresh: function () {
return this.fetch({ reset: true, data: { q: this.q } });
},
hasMore: function () {
return this.total > this.p * this.ps;
}
});
});
|
dgageot/sonarqube
|
server/sonar-web/src/main/js/apps/metrics/metrics.js
|
JavaScript
|
lgpl-3.0
| 911
|
class DataInterface {
// Data retrieval. Going to use API in this instance, but in the event
// sockets seems more doable the functions should be easy to switch out
getUpdatedStory(){
return "Myep";
}
}
module.exports = DataInterface;
|
TheGrimJam/fictiongen
|
fictiongen_app/staticfiles/js/data.js
|
JavaScript
|
lgpl-3.0
| 269
|
import { faIcon } from '../../../helpers/fa-icon';
import { module, test } from 'qunit';
module('Unit | Helper | {{fa-icon}}');
test('it works as a function', function(assert) {
var result = faIcon('credit-card');
assert.equal(result, '<i class="fa fa-credit-card" aria-hidden="true"></i>');
});
|
limesoft/ember-cli-font-awesome
|
tests/unit/helpers/fa-icon-test.js
|
JavaScript
|
unlicense
| 302
|
import { app, Menu, prompt } from "electron";
const template = [
{
label: "Edit",
submenu: [
{
role: "undo"
},
{
role: "redo"
},
{
type: "separator"
},
{
role: "cut"
},
{
role: "copy"
},
{
role: "paste"
},
{
role: "pasteandmatchstyle"
},
{
role: "delete"
},
{
role: "selectall"
}
]
},
{
label: "View",
submenu: [
{
role: "reload"
},
{
role: "toggledevtools"
},
{
type: "separator"
},
{
role: "resetzoom"
},
{
role: "zoomin"
},
{
role: "zoomout"
},
{
type: "separator"
},
{
role: "togglefullscreen"
}
]
},
{
role: "window",
submenu: [
{
role: "minimize"
},
{
role: "close"
}
]
},
{
role: "help",
submenu: [
{
label: "Learn More",
click() {
require("electron").shell.openExternal("http://electron.atom.io");
}
}
]
}
];
if (process.platform === "darwin") {
template.unshift({
label: app.getName(),
submenu: [
{
role: "about",
label: "About Streamplace"
},
{
type: "separator"
},
{
role: "services",
submenu: []
},
{
type: "separator"
},
{
role: "hide"
},
{
role: "hideothers"
},
{
role: "unhide"
},
{
type: "separator"
},
{
role: "quit"
}
]
});
// Edit menu.
template[1].submenu.push(
{
type: "separator"
},
{
label: "Speech",
submenu: [
{
role: "startspeaking"
},
{
role: "stopspeaking"
}
]
}
);
// Window menu.
template[3].submenu = [
{
label: "Close",
accelerator: "CmdOrCtrl+W",
role: "close"
},
{
label: "Minimize",
accelerator: "CmdOrCtrl+M",
role: "minimize"
},
{
label: "Zoom",
role: "zoom"
},
{
type: "separator"
},
{
label: "Bring All to Front",
role: "front"
}
];
}
const menu = Menu.buildFromTemplate(template);
export default menu;
|
streamkitchen/streamkitchen
|
packages/sp-app/src/menu.js
|
JavaScript
|
apache-2.0
| 2,458
|
export function ba_se() {
console.log('"mod.ule"."ba.se"');
}
|
WebAssembly/binaryen
|
scripts/test/mod.ule.js
|
JavaScript
|
apache-2.0
| 65
|
// Copyright 2015 OpenWhere, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
var AWSClass = require('../AWSClass.js');
var propertyMap = {'Bucket': {'list': false, 'type': 'string'},
'IncludeCookies': {'list': false, 'type': 'boolean'},
'Prefix': {'list': false, 'type': 'string'}};
var Class = function (id) {
return AWSClass.call(this, id, 'CloudfrontLogging', {});
};
require('util').inherits(Class, AWSClass);
Class = AWSClass.registerPropertyPrototypes(Class, propertyMap);
module.exports = Class;
|
owap/scenery
|
lib/properties/CloudfrontLogging.js
|
JavaScript
|
apache-2.0
| 1,043
|
/*
* Kendo UI Web v2014.1.318 (http://kendoui.com)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-web
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["sr-Latn-CS"] = {
name: "sr-Latn-CS",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-n $","n $"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
symbol: "Din."
}
},
calendars: {
standard: {
days: {
names: ["nedelja","ponedeljak","utorak","sreda","četvrtak","petak","subota"],
namesAbbr: ["ned","pon","uto","sre","čet","pet","sub"],
namesShort: ["ne","po","ut","sr","če","pe","su"]
},
months: {
names: ["januar","februar","mart","april","maj","jun","jul","avgust","septembar","oktobar","novembar","decembar",""],
namesAbbr: ["jan","feb","mar","apr","maj","jun","jul","avg","sep","okt","nov","dec",""]
},
AM: [""],
PM: [""],
patterns: {
d: "d.M.yyyy",
D: "d. MMMM yyyy",
F: "d. MMMM yyyy H:mm:ss",
g: "d.M.yyyy H:mm",
G: "d.M.yyyy H:mm:ss",
m: "d. MMMM",
M: "d. MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm",
T: "H:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ".",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
facundolucas/eCuentas
|
src/main/webapp/resources/kendoui/src/js/cultures/kendo.culture.sr-Latn-CS.js
|
JavaScript
|
apache-2.0
| 2,717
|
return 53;
|
lucaswerkmeister/ceylon.language
|
runtime-js/runtime/integerSize.js
|
JavaScript
|
apache-2.0
| 11
|
export default function initOverrideOpen(db, SyncNode, crudMonitor) {
return function overrideOpen(origOpen) {
return function () {
//
// Make sure to subscribe to "creating", "updating" and "deleting" hooks for all observable tables that were created in the stores() method.
//
Object.keys(db._allTables).forEach(tableName => {
let table = db._allTables[tableName];
if (table.schema.observable) {
crudMonitor(table);
}
if (table.name === "_syncNodes") {
table.mapToClass(SyncNode);
}
});
return origOpen.apply(this, arguments);
}
};
}
|
chrahunt/Dexie.js
|
addons/Dexie.Observable/src/override-open.js
|
JavaScript
|
apache-2.0
| 644
|