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 |
|---|---|---|---|---|---|
var User = require('../config/Sequelize.js').import('../models/User.js');
module.exports = function(app) {
function indexController(request, response) {
User.findOne({
where: {
'username': 'admin'
}
}).then(function(userObj) {
if(userObj === null) {
var salt = User.generateSalt();
User.create({
name: "Administrator",
username: "admin",
password: User.generateHash("admin", salt),
salt: salt,
cellphone: '99999999999999',
email: 'admin@admin',
administrator: true
}).then(function() {
if(request.isAuthenticated() && request.user.dataValues.administrator) {
return response.redirect("/configuration/projects");
} else if(request.isAuthenticated()) {
return response.redirect("/configuration/projects");
} else {
app.locals.activeProject = {};
return response.redirect("/login");
}
}).catch(function(err) {
console.log(err);
});
} else {
if(request.isAuthenticated() && request.user.dataValues.administrator) {
return response.redirect("/configuration/projects");
} else if(request.isAuthenticated()) {
return response.redirect("/configuration/projects");
} else {
app.locals.activeProject = {};
return response.redirect("/login");
}
}
});
}
return indexController;
};
| edelatin/terrama2 | webapp/controllers/index.js | JavaScript | lgpl-3.0 | 1,508 |
if(typeof define !== 'function')
var define = require('amdefine')(module);
define(["require","deep/deep", "./ajax"],function (require, deep, Ajax)
{
deep.store.jqueryajax = deep.store.jqueryajax || {};
deep.store.jqueryajax.HTML = deep.compose.Classes(Ajax, {
headers:{
"Accept" : "text/html; charset=utf-8"
},
dataType:"html",
bodyParser : function(data){
if(typeof data === 'string')
return data;
if(data.toString())
return data.toString();
return String(data);
},
responseParser : function(data, msg, jqXHR){
return data.toString();
}
});
//__________________________________________________
deep.extensions.push({
extensions:[
/(\.(html|htm|xhtm|xhtml)(\?.*)?)$/gi
],
store:deep.store.jqueryajax.HTML
});
deep.store.jqueryajax.HTML.createDefault = function(){
new deep.store.jqueryajax.HTML("html");
};
return deep.store.jqueryajax.HTML;
}); | philid/deep-jquery-ajax | lib/html.js | JavaScript | lgpl-3.0 | 1,000 |
import {ModelAttributeMetaData} from 'administration/model-management/meta/model-attribute-meta';
/**
* Represents a specific field meta data extending from {@link ModelAttributeMetaData}
*
* @author Svetlozar Iliev
*/
export class ModelFieldMetaData extends ModelAttributeMetaData {
constructor(id) {
super(id);
}
} | SirmaITT/conservation-space-1.7.0 | docker/sep-ui/src/administration/model-management/meta/model-field-meta.js | JavaScript | lgpl-3.0 | 330 |
var yhr = require('./main.js');
module.exports = function(uri,opt){
return yhr('DELETE',uri,null,opt);
};
| manvalls/yhr | delete.js | JavaScript | lgpl-3.0 | 110 |
import _cloneRegExp from './internal/_cloneRegExp';
import _curry2 from './internal/_curry2';
import _isRegExp from './internal/_isRegExp';
import toString from './toString';
/**
* Determines whether a given string matches a given regular expression.
*
* @func
* @memberOf R
* @since v0.12.0
* @category String
* @sig RegExp -> String -> Boolean
* @param {RegExp} pattern
* @param {String} str
* @return {Boolean}
* @see R.match
* @example
*
* R.test(/^x/, 'xyz'); //=> true
* R.test(/^y/, 'xyz'); //=> false
*/
var test = /*#__PURE__*/_curry2(function test(pattern, str) {
if (!_isRegExp(pattern)) {
throw new TypeError('‘test’ requires a value of type RegExp as its first argument; received ' + toString(pattern));
}
return _cloneRegExp(pattern).test(str);
});
export default test; | edwinspire/open-ams | node_modules/ramda/es/test.js | JavaScript | lgpl-3.0 | 824 |
module.exports = {
'Auth': {
'Token': process.env['NODE_AUTH'] || ''
}
} | BlakeRandall/balakehbotjs | config/auth.js | JavaScript | unlicense | 88 |
import firebase from 'firebase'
export default function ({ isServer, store, req, redirect }) {
// Don't run this middleware on the server
if (isServer) {
// TODO: check cookie
return
} else {
console.log('firebase.auth().currentUser =', firebase.auth().currentUser)
if (firebase.auth().currentUser === null) return redirect('/login')
}
}
| webglue/webglue.now.sh | nuxt/middleware/must-auth.js | JavaScript | unlicense | 362 |
(function() {
var app = angular.module('hebergement', []);
app.controller('TabController', function(){
this.tab = 1;
this.setTab = function(newValue){
this.tab = newValue;
};
this.isSet = function(tabName){
return this.tab === tabName;
};
});
app.controller('HostingController', function(){
var host = {};
this.addHost = function(){
// Ajout d'un hébergement
}
});
app.directive('formLogin', function(){
return {
restrict: 'E',
templateUrl : 'snips/form-login.html'
};
});
app.directive('formCreateAccount', function(){
return {
restrict: 'E',
templateUrl : 'snips/form-create-account.html'
};
});
})(); | Rambobafet/trouve_ton_hote | js/app.js | JavaScript | unlicense | 663 |
const { environment } = require('@rails/webpacker')
const webpack = require('webpack');
environment.toWebpackConfig().merge({
resolve: {
alias: {
'jquery': 'jquery/src/jquery'
}
}
});
module.exports = environment
| Hiroyuki-Adachi/farm2 | config/webpack/environment.js | JavaScript | unlicense | 233 |
JabberApp.module('DashboardApp.Show', function(Show, App, Backbone, Marionette, $, _) {
Show.Layout = App.Views.Layout.extend({
template: require('./tpl/layout.hbs')
, regions: {
upcomingRegion: '#upcoming-region'
, theatreRegion: '#theatre-region'
}
});
}); | amelon/bbrails-express | assets/javascripts/backbone/apps/dashboard/show/view.js | JavaScript | unlicense | 283 |
({
// for an explanation of these fields, you should go through
// https://github.com/jrburke/r.js/blob/master/build/example.build.js
baseUrl: '${basedir}/src/main/webapp/js',
inlineText: true,
useStrict: false,
name: '../../scripts/almond',
include: ['main'],
insertRequire: ['main'],
out: '${project.build.directory}/${project.build.finalName}/build/app.js',
wrap: false,
mainConfigFile: '${basedir}/src/main/webapp/js/main.js',
preserveLicenseComments: true,
logLevel: 0,
stubModules: ['text', 'hgn', 'hb'],
optimize: 'closure',
pragmasOnSave: {
// exclude compiler logic from Hogan.js and customHandlebars.js
excludeHogan: true,
excludeHandlebars: true
}
})
| kjbekkelund/js-java-setup | src/main/config/buildconfig.js | JavaScript | unlicense | 755 |
import inspectISOBMFF from "isobmff-inspector";
import render from "./renderer.js";
// -- Feature switching based on the various API support --
if (window.File && window.FileReader && window.Uint8Array) {
/**
* @param {Event} evt
* @returns {Boolean}
*/
function onFileSelection(evt) {
const files = evt.target.files; // FileList object
if (!files.length) {
return;
}
const file = files[0];
const reader = new FileReader();
// TODO read progressively to skip mdat and whatnot
reader.onload = (evt) => {
const arr = new Uint8Array(evt.target.result);
const res = inspectISOBMFF(arr);
render(res);
};
reader.readAsArrayBuffer(file);
return false;
}
document.getElementById("file-input")
.addEventListener("change", onFileSelection, false);
} else {
const localSegmentInput = document.getElementById("choices-local-segment");
localSegmentInput.style.display = "none";
const choiceSeparator = document.getElementById("choices-separator");
choiceSeparator.style.display = "none";
}
if (window.fetch && window.Uint8Array) {
/**
* @param {Event} evt
*/
function onUrlValidation(url) {
fetch(url)
.then(response => response.arrayBuffer())
.then((arrayBuffer) => {
const parsed = inspectISOBMFF(new Uint8Array(arrayBuffer));
render(parsed);
});
}
/**
* @returns {Boolean}
*/
function onButtonClicking() {
const url = document.getElementById("url-input").value;
if (url) {
onUrlValidation(url);
return false;
}
}
/**
* @param {Event} evt
* @returns {Boolean}
*/
function onInputKeyPress(evt) {
const keyCode = evt.keyCode || evt.which;
if (keyCode == 13) {
const url = evt.target.value;
if (url) {
onUrlValidation(url);
}
return false;
}
}
document.getElementById("url-input")
.addEventListener("keypress", onInputKeyPress, false);
document.getElementById("url-button")
.addEventListener("click", onButtonClicking, false);
} else {
const choiceSeparator = document.getElementById("choices-separator");
choiceSeparator.style.display = "none";
const urlSegmentInput = document.getElementById("choices-url-segment");
urlSegmentInput.style.display = "none";
}
| peaBerberian/AISOBMFFWVDFBUTFAII | src/index.js | JavaScript | unlicense | 2,321 |
// Particle
var position = new Vector(0, 0);
var velocity = new Vector(0, 0);
var size = 42;
var mass = 42;
var color = [0, 0, 0];
var particle = new Particle(position, velocity, size, mass, color);
console.log('p', particle); | blackpuma/chaos | js/test/particle.js | JavaScript | unlicense | 229 |
var baseURL = window.location.pathname;
var webRoot = "/"+baseURL.split("/")[1];
$(function(){
$('#logo_top').click(function() {
window.location = webRoot;
});
$('.link_formate').click(function() {
$('.selected_menu').removeClass('selected_menu');
$(this).addClass('selected_menu');
window.location = webRoot+"/Formate";
});
$('.link_iniciativas').click(function() {
$('.selected_menu').removeClass('selected_menu');
$(this).addClass('selected_menu');
window.location = webRoot+"/Iniciativas";
});
$('.link_perfil').click(function() {
$('.selected_menu').removeClass('selected_menu');
$(this).addClass('selected_menu');
window.location = webRoot+"/usuarios/perfil";
});
$('.btn_usuario').click(function() {
let id = $(this).attr('id').split('_')[2];
window.location = webRoot+"/usuarios/perfil/"+id;
});
$('#btn_abrirSideMenu').click(function() {
$('#sideMenu').show();
$(this).hide();
$('#btn_cerrarSideMenu').show();
});
$('#btn_cerrarSideMenu').click(function() {
$('#sideMenu').hide();
$(this).hide();
$('#btn_abrirSideMenu').show();
});
});
function mainMenu() {
console.log('click');
if($('#mainMenu').is(':visible')){
$('#mainMenu').hide();
}
else
$('#mainMenu').show();
}
//Funcion CSS
function ajustarMarginTop(elementoId,newMarginTop){
var elemento = document.getElementById(elementoId);
var cssMarginTop = $('#'+elementoId).css("margin-top");
//var cssMargin = $('#'+elementoId).css("margin").split(" ");
//elemento.style.margin = newMarginTop+"px "+cssMargin[1]+" "+cssMargin[2]+" "+cssMargin[3] ;
//elemento.style.margin = $('#'+elementoId).css("margin").replace(cssMarginTop,newMarginTop+"px");;
}
| Osced/Ciudadan-a | ciudadaniaconsentido/tests/TestCase/Model/Table/default.js | JavaScript | unlicense | 1,714 |
'use strict';
angular.module('athenaApp')
.config(function ($stateProvider) {
$stateProvider
.state('login', {
parent: 'account',
url: '/login',
data: {
roles: [],
pageTitle: 'Authentication'
},
views: {
'content@': {
templateUrl: 'scripts/app/account/login/login.html',
controller: 'LoginController'
}
},
resolve: {
}
});
});
| StarTrackDevKL/athena | src/main/webapp/scripts/app/account/login/login.js | JavaScript | unlicense | 646 |
var searchData=
[
['d_5fbackground',['D_BACKGROUND',['../auditd-config_8h.html#a21f280a48d918cafb9cc0a509a8892c1a3dc146342135edb841af2220e96f6373',1,'auditd-config.h']]],
['d_5fdetailed',['D_DETAILED',['../aureport-options_8h.html#ae8e4ebc0e893793afb43373bc2201f9aa7b9b4c5a8415c578f056e8b03efbf049',1,'aureport-options.h']]],
['d_5fforeground',['D_FOREGROUND',['../auditd-config_8h.html#a21f280a48d918cafb9cc0a509a8892c1acdad7922a43e3f3268cd8e5778d1b634',1,'auditd-config.h']]],
['d_5fin',['D_IN',['../audispd-pconfig_8h.html#ae9ae980041e438eed7a3af43ce4e9f6bafd0f02fc8ea8c6a076d8c90732d314bb',1,'audispd-pconfig.h']]],
['d_5fout',['D_OUT',['../audispd-pconfig_8h.html#ae9ae980041e438eed7a3af43ce4e9f6ba4e45ce2cfacd42b9aed73d990cc0e796',1,'audispd-pconfig.h']]],
['d_5fspecific',['D_SPECIFIC',['../aureport-options_8h.html#ae8e4ebc0e893793afb43373bc2201f9aa9e9a2ba01f00d303c986bae18b89cd3d',1,'aureport-options.h']]],
['d_5fsum',['D_SUM',['../aureport-options_8h.html#ae8e4ebc0e893793afb43373bc2201f9aaade401f77cfadbc2adbeeed3ae01eb25',1,'aureport-options.h']]],
['d_5funset',['D_UNSET',['../audispd-pconfig_8h.html#ae9ae980041e438eed7a3af43ce4e9f6ba37abda4c5495879435fcd83e79ba6b15',1,'D_UNSET(): audispd-pconfig.h'],['../aureport-options_8h.html#ae8e4ebc0e893793afb43373bc2201f9aa37abda4c5495879435fcd83e79ba6b15',1,'D_UNSET(): aureport-options.h']]],
['dbg_5fno',['DBG_NO',['../libaudit_8h.html#a280e2bc767a2e76de2a3b9b1eeb8ec09a7a9a6b0033804e09d661906434f757d2',1,'libaudit.h']]],
['dbg_5fyes',['DBG_YES',['../libaudit_8h.html#a280e2bc767a2e76de2a3b9b1eeb8ec09a065f682fca49b754e7b3f6a0d82a963f',1,'libaudit.h']]],
['down',['DOWN',['../aulast-llist_8h.html#af9bff8ff1154a04a899276af806b8586a9b0b4a95b99523966e0e34ffdadac9da',1,'aulast-llist.h']]]
];
| onosfw/apis | audit/apis/search/enumvalues_64.js | JavaScript | apache-2.0 | 1,785 |
({
failOnWarning : true,
/**
* Check to make sure that when the user puts in invalid options (i.e. an option missing the value element)
*/
testInputSelect_WarningForInvalidOption : {
auraWarningsExpectedDuringInit: ["Option at index 1 in select component"],
attributes : { "case" : "badsel"},
test : function(cmp) {
this.dummyFunc();
}
},
/**
* Verify that correct usage of InputSelect does not throw warnings
*/
testInputSelect_WarningDoesNotShowUp : {
test : function(cmp) {
this.dummyFunc();
}
},
/**
* Dummy function that will return true in all cases
*/
dummyFunc : function(){
return true;
}
})
| igor-sfdc/aura | aura-components/src/test/components/uitest/inputSelect_CheckWarnings/inputSelect_CheckWarningsTest.js | JavaScript | apache-2.0 | 648 |
'use strict';
const utils = require("./utils");
const logger = utils.createLogger({sourceFilePath : __filename});
const path = require("path");
const fs = require("fs");
class NamedPathsConfig{
/**
*
* @param {CachedTextFile} configReader
*/
constructor(configReader){
this.configReader = configReader;
if(!this.configReader) throw new Error("missing config reader");
this.namedPathsConfig = {};
this.namedPathsArray = [];
this.namedPathsPathMap = {};
this.namedPathsUrlMap = {};
}
/**
* @return {boolean}
*/
isNamedPathsEnabled() {
let cfg = this.readConfig();
//this.projectConfig;
return cfg.hasOwnProperty('project') && cfg.project.hasOwnProperty('namedPaths') && typeof cfg.project["namedPaths"] === 'object';
}
readConfig(){
var cfgt = this.configReader.read();
let cfg;
if(cfgt){
cfg = JSON.parse(cfgt);
}else{
cfg = {};
}
return cfg;
}
/**
*
* @return {Object.<String, {path: String, url: String}>}
*/
getNamedPathsConfigObject() {
if(this.isNamedPathsEnabled()){
return this.readConfig().project["namedPaths"];
} else {
logger.info("There are no named paths. config=", this.readConfig());
return {};
}
}
/**
*
* @param {{path:String,url:String}} namedPath
* @param {String} name
* @return {{name:String, path:String,url:String}}
*/
initNamedPath(namedPath, name) {
namedPath.name = name;
if(!utils.hasPropertyOfType(namedPath, "url", "String") || !utils.hasPropertyOfType(namedPath, "path", "String")){
logger.error("Invalid named path:", namedPath);
throw new Error("Named path " + name + " is missing url and/or path fields");
}
const thePath = namedPath.path.split('/').join(path.sep);
if (thePath.indexOf(path.sep) !== 0 && thePath.indexOf(':\\') !== 1) {
namedPath.path = path.normalize(this.projectDirPath + path.sep + thePath);
}
console.log("inited named path = ", namedPath);
return namedPath;
}
getNamedPathConfigsArray() {
const paths = [];
for (let nm in this.namedPathsConfig) {
if (utils.hasPropertyOfType(this.namedPathsConfig, nm, "Object")) {
const namedPath = this.namedPathsConfig[nm];
paths.push(this.initNamedPath(namedPath, nm));
}
}
this.validateNamedPaths(paths);
return paths;
}
/**
*
* @param {String} name
* @return {String}
*/
resolveNamedPathUrl(name) {
return this.getNamedPath(name).url;
}
/**
*
* @param {String} name
* @return {{path: String, url: String}}
*/
getNamedPath(name ) {
const cfg = this.readConfig();
if (utils.nestedPathExists(cfg, "project", "namedPaths", name)) {
if (cfg.project["namedPaths"].hasOwnProperty(name)) {
return this.initNamedPath(cfg.project["namedPaths"][name], name);
} else {
logger.info("There is no such named path : " + name + " config=", cfg);
throw new Error("Not a named path: " + name);
}
} else {
logger.info("Not a named path : " + name + " config=", cfg);
throw new Error("Not a named path: " + name);
}
}
validateNamedPaths(namedPaths) {
namedPaths.forEach(function(namedPath){
if(!fs.existsSync(namedPath.path)){
logger.error("Named path doesn't exist : ", namedPath.path);
throw new Error("Named path " + namedPath.name + " doesn't exist, check prototype.json ");
}
});
}
isNamedPathName(name) {
return this.namedPathsConfig.hasOwnProperty(name);
}
extractNamedPathUrlChild(url) {
const paths = this.namedPathsArray;
let found = false;
paths.forEach(function (np) {
if (url === np.url || url.indexOf(np.url) === 0) {
found = np;
}
});
return found;
}
/**
*
* @param {String} fullPath
* @return {boolean}
*/
isNamedPathChild(fullPath) {
const paths = this.namedPathsArray;
let found = false;
if(paths){
paths.forEach(function (np) {
if (fullPath.indexOf(np.path) === 0) {
found = true;
}
});
}
return found;
}
/**
*
* @param {String} urlPathname
* @return {boolean}
*/
isNamedPathUrlPathname(urlPathname) {
let found = false;
if(urlPathname.length >= 2){
const secSlash = urlPathname.indexOf("/", 1);
const npUrlPotential = urlPathname.substring(0, secSlash);
if(this.namedPathsUrlMap && this.namedPathsUrlMap.hasOwnProperty(npUrlPotential)){
found = true;
}else{
logger.debug("No entry in named paths url map for "+ npUrlPotential);
}
}
return found;
}
extractNamedPath(fullPath) {
const paths = this.namedPathsArray;
let namedPath = false;
paths.forEach(function (np) {
if (fullPath.indexOf(np.path) === 0) {
namedPath = np;
}
});
return namedPath;
}
/**
*
* @return {Object.<String,String>}
*/
createNamedPathsUrlMap() {
const map = {};
if(this.isNamedPathsEnabled()){
this.namedPathsArray.forEach(function(np){
map[np.url] = np.name;
});
}
return map;
}
/**
*
* @param {String} urlPathname
* @return {String}
*/
resolveUrlPathnameToNamedPathName(urlPathname) {
let name = false;
if(urlPathname.length >= 2){
const secSlash = urlPathname.indexOf("/", 1);
if(secSlash > 0){
const namedPathUrl = urlPathname.substring(0, secSlash);
if(this.namedPathsUrlMap.hasOwnProperty(namedPathUrl)){
const namedPathName = this.namedPathsUrlMap[namedPathUrl];
name = namedPathName;
}
}
}
if(name === false){
throw new Error("Could not construct named path filepath for urlpathname " + urlPathname);
}
return name;
}
/**
*
* @param {String} urlPathname
* @return {String|boolean}
*/
resolveUrlPathnameToNamedPathFile(urlPathname) {
let filePath = false;
if(urlPathname.length >= 2){
const secSlash = urlPathname.indexOf("/", 1);
if(secSlash > 0){
const namedPathUrl = urlPathname.substring(0, secSlash);
if(this.namedPathsUrlMap.hasOwnProperty(namedPathUrl)){
const namedPathName = this.namedPathsUrlMap[namedPathUrl];
const np = this.getNamedPath(namedPathName).path;
filePath = np + urlPathname.substring(namedPathUrl.length);
}
}
}
if(filePath.indexOf('c:',1)>0){
throw new Error("Illegal path: " + filePath);
}
return filePath;
}
/**
*
* @return {Object.<String, String>}
*/
createNamedPathsPathMap() {
const map = {};
if(this.isNamedPathsEnabled()){
this.namedPathsArray.forEach(function(np){
map[np.path] = np.name;
});
}
return map;
}
}
module.exports = NamedPathsConfig; | OpenNTF/Web-UI-Prototyping-Toolkit | lib/NamedPathsConfig.js | JavaScript | apache-2.0 | 7,845 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
'use strict';
exports.EntitySearchAPI = require('./entitySearch/entitySearchAPI');
exports = module.exports; | AutorestCI/azure-sdk-for-node | lib/services/cognitiveServices.Search/lib/cognitiveServicesSearch.js | JavaScript | apache-2.0 | 276 |
var DATA = {"a" : "b", "c" : "d"};
var RESPONSE = {"vendor":"OpenPolicy","name":"alex","locations":[{"continent":"Europe","country":"Germany","price":5,"latitude":"48.105964","name":"Slot_ger_4","longitude":"11.612549"},{"continent":"Europe","country":"Germany","price":6,"latitude":"52.473412","name":"Slot_ger_1","longitude":"13.390961"},{"continent":"Europe","country":"Germany","price":5,"latitude":"48.105964","name":"Slot_ger_2","longitude":"11.612549"},{"continent":"Europe","country":"Germany","price":4,"latitude":"52.473412","name":"Slot_ger_3","longitude":"13.390961"}],"version":"0.1"}
var REQUEST = {
"name":"alex",
"vendor":"OpenPolicy",
"version":"0.1",
"preferences":["germany"],
"attributes":[
{
"#http://www.q-team.org/Ontology#Einwilligung_Zur_Datensammlung":true
},
{
"#http://www.q-team.org/Ontology#minAge":12
},
{
"#http://www.q-team.org/Ontology#Recht_auf_Vergessen":false
},
{
"#http://www.q-team.org/Ontology#Meldepflicht_bei_Verletzung":true
}
]
} | iiot-stud/qteam2016 | GUI/data.js | JavaScript | apache-2.0 | 999 |
'use strict'
var gulp = require('gulp')
var $ = require('gulp-load-plugins')()
gulp.task('default', function() {
gulp.src('./src/**/*.js')
.pipe($.wrap('!function(a,b){"function"==typeof define&&define.amd?define(b):"object"==typeof exports?module.exports=b(require,exports,module):a.audioWave=b()}(this,function(){<%= contents %>});'))
.pipe($.jsbeautifier({
config: '.jsbeautifyrc'
}))
.pipe(gulp.dest('./dist'))
.pipe($.uglify({
"mangle": true
}))
.pipe($.rename({
suffix: ".min"
}))
.pipe(gulp.dest('./dist'))
.pipe(gulp.dest('./demo/js'))
})
gulp.task('demo', $.serve('demo'))
| big-data-visualization/audio-waveform | gulpfile.js | JavaScript | apache-2.0 | 645 |
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard', ['ui.bootstrap', 'ui.sortable']);
angular.module('ui.dashboard')
.directive('dashboard', ['WidgetModel', 'WidgetDefCollection', '$modal', 'DashboardState', '$log', function (WidgetModel, WidgetDefCollection, $modal, DashboardState, $log) {
return {
restrict: 'A',
templateUrl: function(element, attr) {
return attr.templateUrl ? attr.templateUrl : 'template/dashboard.html';
},
scope: true,
controller: ['$scope', '$attrs', function (scope, attrs) {
// default options
var defaults = {
stringifyStorage: true,
hideWidgetSettings: false,
hideWidgetClose: false,
settingsModalOptions: {
templateUrl: 'template/widget-settings-template.html',
controller: 'WidgetSettingsCtrl'
},
onSettingsClose: function(result, widget) { // NOTE: dashboard scope is also passed as 3rd argument
jQuery.extend(true, widget, result);
},
onSettingsDismiss: function(reason) { // NOTE: dashboard scope is also passed as 2nd argument
$log.info('widget settings were dismissed. Reason: ', reason);
}
};
// from dashboard="options"
// scope.options = scope.$eval(attrs.dashboard);
// extend default settingsModalOptions
// scope.options.settingsModalOptions = scope.options.settingsModalOptions || {};
// extend options with defaults
// angular.extend(defaults.settingsModalOptions, scope.options.settingsModalOptions);
// angular.extend(scope.options.settingsModalOptions, defaults.settingsModalOptions);
// angular.extend(defaults, scope.options);
// angular.extend(scope.options, defaults);
// from dashboard="options"
scope.options = scope.$eval(attrs.dashboard);
// Deep options
scope.options.settingsModalOptions = scope.options.settingsModalOptions || {};
_.each(['settingsModalOptions'], function(key) {
// Ensure it exists on scope.options
scope.options[key] = scope.options[key] || {};
// Set defaults
_.defaults(scope.options[key], defaults[key]);
});
// Shallow options
_.defaults(scope.options, defaults);
// jQuery.extend(true, defaults, scope.options);
// jQuery.extend(scope.options, defaults);
var sortableDefaults = {
stop: function () {
scope.saveDashboard();
},
handle: '.widget-header'
};
scope.sortableOptions = angular.extend({}, sortableDefaults, scope.options.sortableOptions || {});
}],
link: function (scope) {
// Save default widget config for reset
scope.defaultWidgets = scope.options.defaultWidgets;
//scope.widgetDefs = scope.options.widgetDefinitions;
scope.widgetDefs = new WidgetDefCollection(scope.options.widgetDefinitions);
var count = 1;
// Instantiate new instance of dashboard state
scope.dashboardState = new DashboardState(
scope.options.storage,
scope.options.storageId,
scope.options.storageHash,
scope.widgetDefs,
scope.options.stringifyStorage
);
/**
* Instantiates a new widget on the dashboard
* @param {Object} widgetToInstantiate The definition object of the widget to be instantiated
*/
scope.addWidget = function (widgetToInstantiate, doNotSave) {
var defaultWidgetDefinition = scope.widgetDefs.getByName(widgetToInstantiate.name);
if (!defaultWidgetDefinition) {
throw 'Widget ' + widgetToInstantiate.name + ' is not found.';
}
// Determine the title for the new widget
var title;
if (widgetToInstantiate.title) {
title = widgetToInstantiate.title;
} else if (defaultWidgetDefinition.title) {
title = defaultWidgetDefinition.title;
} else {
title = 'Widget ' + count++;
}
// Deep extend a new object for instantiation
widgetToInstantiate = jQuery.extend(true, {}, defaultWidgetDefinition, widgetToInstantiate);
// Instantiation
var widget = new WidgetModel(widgetToInstantiate, {
title: title
});
scope.widgets.push(widget);
if (!doNotSave) {
scope.saveDashboard();
}
};
/**
* Removes a widget instance from the dashboard
* @param {Object} widget The widget instance object (not a definition object)
*/
scope.removeWidget = function (widget) {
scope.widgets.splice(_.indexOf(scope.widgets, widget), 1);
scope.saveDashboard();
};
/**
* Opens a dialog for setting and changing widget properties
* @param {Object} widget The widget instance object
*/
scope.openWidgetSettings = function (widget) {
// Set up $modal options
var options = _.defaults(
{ scope: scope },
widget.settingsModalOptions,
scope.options.settingsModalOptions);
// Ensure widget is resolved
options.resolve = {
widget: function () {
return widget;
}
};
// Create the modal
var modalInstance = $modal.open(options);
var onClose = widget.onSettingsClose || scope.options.onSettingsClose;
var onDismiss = widget.onSettingsDismiss || scope.options.onSettingsDismiss;
// Set resolve and reject callbacks for the result promise
modalInstance.result.then(
function (result) {
// Call the close callback
onClose(result, widget, scope);
//AW Persist title change from options editor
scope.$emit('widgetChanged', widget);
},
function (reason) {
// Call the dismiss callback
onDismiss(reason, scope);
}
);
};
/**
* Remove all widget instances from dashboard
*/
scope.clear = function (doNotSave) {
scope.widgets = [];
if (doNotSave === true) {
return;
}
scope.saveDashboard();
};
/**
* Used for preventing default on click event
* @param {Object} event A click event
* @param {Object} widgetDef A widget definition object
*/
scope.addWidgetInternal = function (event, widgetDef) {
event.preventDefault();
scope.addWidget(widgetDef);
};
/**
* Uses dashboardState service to save state
*/
scope.saveDashboard = function (force) {
if (!scope.options.explicitSave) {
scope.dashboardState.save(scope.widgets);
} else {
if (!angular.isNumber(scope.options.unsavedChangeCount)) {
scope.options.unsavedChangeCount = 0;
}
if (force) {
scope.options.unsavedChangeCount = 0;
scope.dashboardState.save(scope.widgets);
} else {
++scope.options.unsavedChangeCount;
}
}
};
/**
* Wraps saveDashboard for external use.
*/
scope.externalSaveDashboard = function() {
scope.saveDashboard(true);
};
/**
* Clears current dash and instantiates widget definitions
* @param {Array} widgets Array of definition objects
*/
scope.loadWidgets = function (widgets) {
// AW dashboards are continuously saved today (no "save" button).
//scope.defaultWidgets = widgets;
scope.savedWidgetDefs = widgets;
scope.clear(true);
_.each(widgets, function (widgetDef) {
scope.addWidget(widgetDef, true);
});
};
/**
* Resets widget instances to default config
* @return {[type]} [description]
*/
scope.resetWidgetsToDefault = function () {
scope.loadWidgets(scope.defaultWidgets);
scope.saveDashboard();
};
// Set default widgets array
var savedWidgetDefs = scope.dashboardState.load();
// Success handler
function handleStateLoad(saved) {
scope.options.unsavedChangeCount = 0;
if (saved && saved.length) {
scope.loadWidgets(saved);
} else if (scope.defaultWidgets) {
scope.loadWidgets(scope.defaultWidgets);
} else {
scope.clear(true);
}
}
if (angular.isArray(savedWidgetDefs)) {
handleStateLoad(savedWidgetDefs);
} else if (savedWidgetDefs && angular.isObject(savedWidgetDefs) && angular.isFunction(savedWidgetDefs.then)) {
savedWidgetDefs.then(handleStateLoad, handleStateLoad);
} else {
handleStateLoad();
}
// expose functionality externally
// functions are appended to the provided dashboard options
scope.options.addWidget = scope.addWidget;
scope.options.loadWidgets = scope.loadWidgets;
scope.options.saveDashboard = scope.externalSaveDashboard;
// save state
scope.$on('widgetChanged', function (event) {
event.stopPropagation();
scope.saveDashboard();
});
}
};
}]);
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.directive('dashboardLayouts', ['LayoutStorage', '$timeout', '$modal',
function(LayoutStorage, $timeout, $modal) {
return {
scope: true,
templateUrl: function(element, attr) {
return attr.templateUrl ? attr.templateUrl : 'template/dashboard-layouts.html';
},
link: function(scope, element, attrs) {
scope.options = scope.$eval(attrs.dashboardLayouts);
var layoutStorage = new LayoutStorage(scope.options);
scope.layouts = layoutStorage.layouts;
scope.createNewLayout = function() {
var newLayout = {
title: 'Custom',
defaultWidgets: scope.options.defaultWidgets || []
};
layoutStorage.add(newLayout);
scope.makeLayoutActive(newLayout);
layoutStorage.save();
return newLayout;
};
scope.removeLayout = function(layout) {
layoutStorage.remove(layout);
layoutStorage.save();
};
scope.makeLayoutActive = function(layout) {
var current = layoutStorage.getActiveLayout();
if (current && current.dashboard.unsavedChangeCount) {
var modalInstance = $modal.open({
templateUrl: 'template/save-changes-modal.html',
resolve: {
layout: function() {
return layout;
}
},
controller: 'SaveChangesModalCtrl'
});
// Set resolve and reject callbacks for the result promise
modalInstance.result.then(
function() {
current.dashboard.saveDashboard();
scope._makeLayoutActive(layout);
},
function() {
scope._makeLayoutActive(layout);
}
);
} else {
scope._makeLayoutActive(layout);
}
};
scope._makeLayoutActive = function(layout) {
angular.forEach(scope.layouts, function(l) {
if (l !== layout) {
l.active = false;
} else {
l.active = true;
}
});
layoutStorage.save();
};
scope.isActive = function(layout) {
return !!layout.active;
};
scope.editTitle = function(layout) {
var input = element.find('input[data-layout="' + layout.id + '"]');
layout.editingTitle = true;
$timeout(function() {
input.focus()[0].setSelectionRange(0, 9999);
});
};
// saves whatever is in the title input as the new title
scope.saveTitleEdit = function(layout) {
layout.editingTitle = false;
layoutStorage.save();
};
scope.options.saveLayouts = function() {
layoutStorage.save(true);
};
scope.options.addWidget = function() {
var layout = layoutStorage.getActiveLayout();
if (layout) {
layout.dashboard.addWidget.apply(layout.dashboard, arguments);
}
};
scope.options.loadWidgets = function() {
var layout = layoutStorage.getActiveLayout();
if (layout) {
layout.dashboard.loadWidgets.apply(layout.dashboard, arguments);
}
};
scope.options.saveDashboard = function() {
var layout = layoutStorage.getActiveLayout();
if (layout) {
layout.dashboard.saveDashboard.apply(layout.dashboard, arguments);
}
};
var sortableDefaults = {
stop: function() {
scope.options.saveLayouts();
},
};
scope.sortableOptions = angular.extend({}, sortableDefaults, scope.options.sortableOptions || {});
}
};
}
]);
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.directive('widget', ['$injector', function ($injector) {
return {
controller: 'DashboardWidgetCtrl',
link: function (scope) {
var widget = scope.widget;
var dataModelType = widget.dataModelType;
// set up data source
if (dataModelType) {
var DataModelConstructor; // data model constructor function
if (angular.isFunction(dataModelType)) {
DataModelConstructor = dataModelType;
} else if (angular.isString(dataModelType)) {
$injector.invoke([dataModelType, function (DataModelType) {
DataModelConstructor = DataModelType;
}]);
} else {
throw new Error('widget dataModelType should be function or string');
}
var ds;
if (widget.dataModelArgs) {
ds = new DataModelConstructor(widget.dataModelArgs);
} else {
ds = new DataModelConstructor();
}
widget.dataModel = ds;
ds.setup(widget, scope);
ds.init();
scope.$on('$destroy', _.bind(ds.destroy,ds));
}
// Compile the widget template, emit add event
scope.compileTemplate();
scope.$emit('widgetAdded', widget);
}
};
}]);
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.factory('LayoutStorage', function() {
var noopStorage = {
setItem: function() {
},
getItem: function() {
},
removeItem: function() {
}
};
function LayoutStorage(options) {
var defaults = {
storage: noopStorage,
storageHash: '',
stringifyStorage: true
};
angular.extend(defaults, options);
angular.extend(options, defaults);
this.id = options.storageId;
this.storage = options.storage;
this.storageHash = options.storageHash;
this.stringifyStorage = options.stringifyStorage;
this.widgetDefinitions = options.widgetDefinitions;
this.defaultLayouts = options.defaultLayouts;
this.widgetButtons = options.widgetButtons;
this.explicitSave = options.explicitSave;
this.defaultWidgets = options.defaultWidgets;
this.settingsModalOptions = options.settingsModalOptions;
this.onSettingsClose = options.onSettingsClose;
this.onSettingsDismiss = options.onSettingsDismiss;
this.options = options;
this.options.unsavedChangeCount = 0;
this.layouts = [];
this.states = {};
this.load();
this._ensureActiveLayout();
}
LayoutStorage.prototype = {
add: function(layouts) {
if (!angular.isArray(layouts)) {
layouts = [layouts];
}
var self = this;
angular.forEach(layouts, function(layout) {
layout.dashboard = layout.dashboard || {};
layout.dashboard.storage = self;
layout.dashboard.storageId = layout.id = self._getLayoutId.call(self,layout);
layout.dashboard.widgetDefinitions = self.widgetDefinitions;
layout.dashboard.stringifyStorage = false;
layout.dashboard.defaultWidgets = layout.defaultWidgets || self.defaultWidgets;
layout.dashboard.widgetButtons = self.widgetButtons;
layout.dashboard.explicitSave = self.explicitSave;
layout.dashboard.settingsModalOptions = self.settingsModalOptions;
layout.dashboard.onSettingsClose = self.onSettingsClose;
layout.dashboard.onSettingsDismiss = self.onSettingsDismiss;
self.layouts.push(layout);
});
},
remove: function(layout) {
var index = this.layouts.indexOf(layout);
if (index >= 0) {
this.layouts.splice(index, 1);
delete this.states[layout.id];
// check for active
if (layout.active && this.layouts.length) {
var nextActive = index > 0 ? index - 1 : 0;
this.layouts[nextActive].active = true;
}
}
},
save: function() {
var state = {
layouts: this._serializeLayouts(),
states: this.states,
storageHash: this.storageHash
};
if (this.stringifyStorage) {
state = JSON.stringify(state);
}
this.storage.setItem(this.id, state);
this.options.unsavedChangeCount = 0;
},
load: function() {
var serialized = this.storage.getItem(this.id);
this.clear();
if (serialized) {
// check for promise
if (angular.isObject(serialized) && angular.isFunction(serialized.then)) {
this._handleAsyncLoad(serialized);
} else {
this._handleSyncLoad(serialized);
}
} else {
this._addDefaultLayouts();
}
},
clear: function() {
this.layouts = [];
this.states = {};
},
setItem: function(id, value) {
this.states[id] = value;
this.save();
},
getItem: function(id) {
return this.states[id];
},
removeItem: function(id) {
delete this.states[id];
this.save();
},
getActiveLayout: function() {
var len = this.layouts.length;
for (var i = 0; i < len; i++) {
var layout = this.layouts[i];
if (layout.active) {
return layout;
}
}
return false;
},
_addDefaultLayouts: function() {
var self = this;
angular.forEach(this.defaultLayouts, function(layout) {
self.add(angular.extend({}, layout));
});
},
_serializeLayouts: function() {
var result = [];
angular.forEach(this.layouts, function(l) {
result.push({
title: l.title,
id: l.id,
active: l.active,
defaultWidgets: l.dashboard.defaultWidgets
});
});
return result;
},
_handleSyncLoad: function(serialized) {
var deserialized;
if (this.stringifyStorage) {
try {
deserialized = JSON.parse(serialized);
} catch (e) {
this._addDefaultLayouts();
return;
}
} else {
deserialized = serialized;
}
if (this.storageHash !== deserialized.storageHash) {
this._addDefaultLayouts();
return;
}
this.states = deserialized.states;
this.add(deserialized.layouts);
},
_handleAsyncLoad: function(promise) {
var self = this;
promise.then(
angular.bind(self, this._handleSyncLoad),
angular.bind(self, this._addDefaultLayouts)
);
},
_ensureActiveLayout: function() {
for (var i = 0; i < this.layouts.length; i++) {
var layout = this.layouts[i];
if (layout.active) {
return;
}
}
if (this.layouts[0]) {
this.layouts[0].active = true;
}
},
_getLayoutId: function(layout) {
if (layout.id) {
return layout.id;
}
var max = 0;
for (var i = 0; i < this.layouts.length; i++) {
var id = this.layouts[i].id;
max = Math.max(max, id * 1);
}
return max + 1;
}
};
return LayoutStorage;
});
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.factory('DashboardState', ['$log', '$q', function ($log, $q) {
function DashboardState(storage, id, hash, widgetDefinitions, stringify) {
this.storage = storage;
this.id = id;
this.hash = hash;
this.widgetDefinitions = widgetDefinitions;
this.stringify = stringify;
}
DashboardState.prototype = {
/**
* Takes array of widget instance objects, serializes,
* and saves state.
*
* @param {Array} widgets scope.widgets from dashboard directive
* @return {Boolean} true on success, false on failure
*/
save: function (widgets) {
if (!this.storage) {
return true;
}
var serialized = _.map(widgets, function (widget) {
var widgetObject = {
title: widget.title,
name: widget.name,
style: widget.style,
size: widget.size,
dataModelOptions: widget.dataModelOptions,
storageHash: widget.storageHash,
attrs: widget.attrs
};
return widgetObject;
});
var item = { widgets: serialized, hash: this.hash };
if (this.stringify) {
item = JSON.stringify(item);
}
this.storage.setItem(this.id, item);
return true;
},
/**
* Loads dashboard state from the storage object.
* Can handle a synchronous response or a promise.
*
* @return {Array|Promise} Array of widget definitions or a promise
*/
load: function () {
if (!this.storage) {
return null;
}
var serialized;
// try loading storage item
serialized = this.storage.getItem( this.id );
if (serialized) {
// check for promise
if (angular.isObject(serialized) && angular.isFunction(serialized.then)) {
return this._handleAsyncLoad(serialized);
}
// otherwise handle synchronous load
return this._handleSyncLoad(serialized);
} else {
return null;
}
},
_handleSyncLoad: function(serialized) {
var deserialized, result = [];
if (!serialized) {
return null;
}
if (this.stringify) {
try { // to deserialize the string
deserialized = JSON.parse(serialized);
} catch (e) {
// bad JSON, log a warning and return
$log.warn('Serialized dashboard state was malformed and could not be parsed: ', serialized);
return null;
}
}
else {
deserialized = serialized;
}
// check hash against current hash
if (deserialized.hash !== this.hash) {
$log.info('Serialized dashboard from storage was stale (old hash: ' + deserialized.hash + ', new hash: ' + this.hash + ')');
this.storage.removeItem(this.id);
return null;
}
// Cache widgets
var savedWidgetDefs = deserialized.widgets;
// instantiate widgets from stored data
for (var i = 0; i < savedWidgetDefs.length; i++) {
// deserialized object
var savedWidgetDef = savedWidgetDefs[i];
// widget definition to use
var widgetDefinition = this.widgetDefinitions.getByName(savedWidgetDef.name);
// check for no widget
if (!widgetDefinition) {
// no widget definition found, remove and return false
$log.warn('Widget with name "' + savedWidgetDef.name + '" was not found in given widget definition objects');
continue;
}
// check widget-specific storageHash
if (widgetDefinition.hasOwnProperty('storageHash') && widgetDefinition.storageHash !== savedWidgetDef.storageHash) {
// widget definition was found, but storageHash was stale, removing storage
$log.info('Widget Definition Object with name "' + savedWidgetDef.name + '" was found ' +
'but the storageHash property on the widget definition is different from that on the ' +
'serialized widget loaded from storage. hash from storage: "' + savedWidgetDef.storageHash + '"' +
', hash from WDO: "' + widgetDefinition.storageHash + '"');
continue;
}
// push instantiated widget to result array
result.push(savedWidgetDef);
}
return result;
},
_handleAsyncLoad: function(promise) {
var self = this;
var deferred = $q.defer();
promise.then(
// success
function(res) {
var result = self._handleSyncLoad(res);
if (result) {
deferred.resolve(result);
} else {
deferred.reject(result);
}
},
// failure
function(res) {
deferred.reject(res);
}
);
return deferred.promise;
}
};
return DashboardState;
}]);
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.factory('WidgetDataModel', function () {
function WidgetDataModel() {
}
WidgetDataModel.prototype = {
setup: function (widget, scope) {
this.dataAttrName = widget.dataAttrName;
this.dataModelOptions = widget.dataModelOptions;
this.widgetScope = scope;
},
updateScope: function (data) {
this.widgetScope.widgetData = data;
},
init: function () {
// to be overridden by subclasses
},
destroy: function () {
// to be overridden by subclasses
}
};
return WidgetDataModel;
});
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.factory('WidgetDefCollection', function () {
function WidgetDefCollection(widgetDefs) {
this.push.apply(this, widgetDefs);
// build (name -> widget definition) map for widget lookup by name
var map = {};
_.each(widgetDefs, function (widgetDef) {
map[widgetDef.name] = widgetDef;
});
this.map = map;
}
WidgetDefCollection.prototype = Object.create(Array.prototype);
WidgetDefCollection.prototype.getByName = function (name) {
return this.map[name];
};
return WidgetDefCollection;
});
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.factory('WidgetModel', function () {
// constructor for widget model instances
function WidgetModel(Class, overrides) {
var defaults = {
title: 'Widget',
name: Class.name,
attrs: Class.attrs,
dataAttrName: Class.dataAttrName,
dataModelType: Class.dataModelType,
dataModelArgs: Class.dataModelArgs, // used in data model constructor, not serialized
//AW Need deep copy of options to support widget options editing
dataModelOptions: Class.dataModelOptions,
settingsModalOptions: Class.settingsModalOptions,
onSettingsClose: Class.onSettingsClose,
onSettingsDismiss: Class.onSettingsDismiss,
style: Class.style || {},
size: Class.size || {},
enableVerticalResize: (Class.enableVerticalResize === false) ? false : true
};
overrides = overrides || {};
angular.extend(this, angular.copy(defaults), overrides);
this.containerStyle = { width: '33%' }; // default width
this.contentStyle = {};
this.updateContainerStyle(this.style);
if (Class.templateUrl) {
this.templateUrl = Class.templateUrl;
} else if (Class.template) {
this.template = Class.template;
} else {
var directive = Class.directive || Class.name;
this.directive = directive;
}
if (this.size && _.has(this.size, 'height')) {
this.setHeight(this.size.height);
}
if (this.style && _.has(this.style, 'width')) { //TODO deprecate style attribute
this.setWidth(this.style.width);
}
if (this.size && _.has(this.size, 'width')) {
this.setWidth(this.size.width);
}
}
WidgetModel.prototype = {
// sets the width (and widthUnits)
setWidth: function (width, units) {
width = width.toString();
units = units || width.replace(/^[-\.\d]+/, '') || '%';
this.widthUnits = units;
width = parseFloat(width);
if (width < 0) {
return false;
}
if (units === '%') {
width = Math.min(100, width);
width = Math.max(0, width);
}
this.containerStyle.width = width + '' + units;
this.updateSize(this.containerStyle);
return true;
},
setHeight: function (height) {
this.contentStyle.height = height;
this.updateSize(this.contentStyle);
},
setStyle: function (style) {
this.style = style;
this.updateContainerStyle(style);
},
updateSize: function (size) {
angular.extend(this.size, size);
},
updateContainerStyle: function (style) {
angular.extend(this.containerStyle, style);
}
};
return WidgetModel;
});
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.controller('SaveChangesModalCtrl', ['$scope', '$modalInstance', 'layout', function ($scope, $modalInstance, layout) {
// add layout to scope
$scope.layout = layout;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss();
};
}]);
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.controller('DashboardWidgetCtrl', ['$scope', '$element', '$compile', '$window', '$timeout',
function($scope, $element, $compile, $window, $timeout) {
$scope.status = {
isopen: false
};
// Fills "container" with compiled view
$scope.makeTemplateString = function() {
var widget = $scope.widget;
// First, build template string
var templateString = '';
if (widget.templateUrl) {
// Use ng-include for templateUrl
templateString = '<div ng-include="\'' + widget.templateUrl + '\'"></div>';
} else if (widget.template) {
// Direct string template
templateString = widget.template;
} else {
// Assume attribute directive
templateString = '<div ' + widget.directive;
// Check if data attribute was specified
if (widget.dataAttrName) {
widget.attrs = widget.attrs || {};
widget.attrs[widget.dataAttrName] = 'widgetData';
}
// Check for specified attributes
if (widget.attrs) {
// First check directive name attr
if (widget.attrs[widget.directive]) {
templateString += '="' + widget.attrs[widget.directive] + '"';
}
// Add attributes
_.each(widget.attrs, function(value, attr) {
// make sure we aren't reusing directive attr
if (attr !== widget.directive) {
templateString += ' ' + attr + '="' + value + '"';
}
});
}
templateString += '></div>';
}
return templateString;
};
$scope.grabResizer = function(e) {
var widget = $scope.widget;
var widgetElm = $element.find('.widget');
// ignore middle- and right-click
if (e.which !== 1) {
return;
}
e.stopPropagation();
e.originalEvent.preventDefault();
// get the starting horizontal position
var initX = e.clientX;
// console.log('initX', initX);
// Get the current width of the widget and dashboard
var pixelWidth = widgetElm.width();
var pixelHeight = widgetElm.height();
var widgetStyleWidth = widget.containerStyle.width;
var widthUnits = widget.widthUnits;
var unitWidth = parseFloat(widgetStyleWidth);
// create marquee element for resize action
var $marquee = angular.element('<div class="widget-resizer-marquee" style="height: ' + pixelHeight + 'px; width: ' + pixelWidth + 'px;"></div>');
widgetElm.append($marquee);
// determine the unit/pixel ratio
var transformMultiplier = unitWidth / pixelWidth;
// updates marquee with preview of new width
var mousemove = function(e) {
var curX = e.clientX;
var pixelChange = curX - initX;
var newWidth = pixelWidth + pixelChange;
$marquee.css('width', newWidth + 'px');
};
// sets new widget width on mouseup
var mouseup = function(e) {
// remove listener and marquee
jQuery($window).off('mousemove', mousemove);
$marquee.remove();
// calculate change in units
var curX = e.clientX;
var pixelChange = curX - initX;
var unitChange = Math.round(pixelChange * transformMultiplier * 100) / 100;
// add to initial unit width
var newWidth = unitWidth * 1 + unitChange;
widget.setWidth(newWidth + widthUnits);
$scope.$emit('widgetChanged', widget);
$scope.$apply();
$scope.$broadcast('widgetResized', {
width: newWidth
});
};
jQuery($window).on('mousemove', mousemove).one('mouseup', mouseup);
};
//TODO refactor
$scope.grabSouthResizer = function(e) {
var widgetElm = $element.find('.widget');
// ignore middle- and right-click
if (e.which !== 1) {
return;
}
e.stopPropagation();
e.originalEvent.preventDefault();
// get the starting horizontal position
var initY = e.clientY;
// console.log('initX', initX);
// Get the current width of the widget and dashboard
var pixelWidth = widgetElm.width();
var pixelHeight = widgetElm.height();
// create marquee element for resize action
var $marquee = angular.element('<div class="widget-resizer-marquee" style="height: ' + pixelHeight + 'px; width: ' + pixelWidth + 'px;"></div>');
widgetElm.append($marquee);
// updates marquee with preview of new height
var mousemove = function(e) {
var curY = e.clientY;
var pixelChange = curY - initY;
var newHeight = pixelHeight + pixelChange;
$marquee.css('height', newHeight + 'px');
};
// sets new widget width on mouseup
var mouseup = function(e) {
// remove listener and marquee
jQuery($window).off('mousemove', mousemove);
$marquee.remove();
// calculate height change
var curY = e.clientY;
var pixelChange = curY - initY;
//var widgetContainer = widgetElm.parent(); // widget container responsible for holding widget width and height
var widgetContainer = widgetElm.find('.widget-content');
var diff = pixelChange;
var height = parseInt(widgetContainer.css('height'), 10);
var newHeight = (height + diff);
//$scope.widget.style.height = newHeight + 'px';
$scope.widget.setHeight(newHeight + 'px');
$scope.$emit('widgetChanged', $scope.widget);
$scope.$apply(); // make AngularJS to apply style changes
$scope.$broadcast('widgetResized', {
height: newHeight
});
};
jQuery($window).on('mousemove', mousemove).one('mouseup', mouseup);
};
// replaces widget title with input
$scope.editTitle = function(widget) {
var widgetElm = $element.find('.widget');
widget.editingTitle = true;
// HACK: get the input to focus after being displayed.
$timeout(function() {
widgetElm.find('form.widget-title input:eq(0)').focus()[0].setSelectionRange(0, 9999);
});
};
// saves whatever is in the title input as the new title
$scope.saveTitleEdit = function(widget) {
widget.editingTitle = false;
$scope.$emit('widgetChanged', widget);
};
$scope.compileTemplate = function() {
var container = $scope.findWidgetContainer($element);
var templateString = $scope.makeTemplateString();
var widgetElement = angular.element(templateString);
container.empty();
container.append(widgetElement);
$compile(widgetElement)($scope);
};
$scope.findWidgetContainer = function(element) {
// widget placeholder is the first (and only) child of .widget-content
return element.find('.widget-content');
};
}
]);
/*
* Copyright (c) 2014 DataTorrent, 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.
*/
'use strict';
angular.module('ui.dashboard')
.controller('WidgetSettingsCtrl', ['$scope', '$modalInstance', 'widget', function ($scope, $modalInstance, widget) {
// add widget to scope
$scope.widget = widget;
// set up result object
$scope.result = jQuery.extend(true, {}, widget);
$scope.ok = function () {
$modalInstance.close($scope.result);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
angular.module("ui.dashboard").run(["$templateCache", function($templateCache) {
$templateCache.put("template/alt-dashboard.html",
"<div>\n" +
" <div class=\"btn-toolbar\" ng-if=\"!options.hideToolbar\">\n" +
" <div class=\"btn-group\" ng-if=\"!options.widgetButtons\">\n" +
" <span class=\"dropdown\" on-toggle=\"toggled(open)\">\n" +
" <button type=\"button\" class=\"btn btn-primary dropdown-toggle\" ng-disabled=\"disabled\">\n" +
" Button dropdown <span class=\"caret\"></span>\n" +
" </button>\n" +
" <ul class=\"dropdown-menu\" role=\"menu\">\n" +
" <li ng-repeat=\"widget in widgetDefs\">\n" +
" <a href=\"#\" ng-click=\"addWidgetInternal($event, widget);\" class=\"dropdown-toggle\">{{widget.name}}</a>\n" +
" </li>\n" +
" </ul>\n" +
" </span>\n" +
" </div>\n" +
"\n" +
" <div class=\"btn-group\" ng-if=\"options.widgetButtons\">\n" +
" <button ng-repeat=\"widget in widgetDefs\"\n" +
" ng-click=\"addWidgetInternal($event, widget);\" type=\"button\" class=\"btn btn-primary\">\n" +
" {{widget.name}}\n" +
" </button>\n" +
" </div>\n" +
"\n" +
" <button class=\"btn btn-warning\" ng-click=\"resetWidgetsToDefault()\">Default Widgets</button>\n" +
"\n" +
" <button ng-if=\"options.storage && options.explicitSave\" ng-click=\"options.saveDashboard()\" class=\"btn btn-success\" ng-hide=\"!options.unsavedChangeCount\">{{ !options.unsavedChangeCount ? \"Alternative - No Changes\" : \"Save\" }}</button>\n" +
"\n" +
" <button ng-click=\"clear();\" ng-hide=\"!widgets.length\" type=\"button\" class=\"btn btn-info\">Clear</button>\n" +
" </div>\n" +
"\n" +
" <div ui-sortable=\"sortableOptions\" ng-model=\"widgets\" class=\"dashboard-widget-area\">\n" +
" <div ng-repeat=\"widget in widgets\" ng-style=\"widget.style\" class=\"widget-container\" widget>\n" +
" <div class=\"widget panel panel-default\">\n" +
" <div class=\"widget-header panel-heading\">\n" +
" <h3 class=\"panel-title\">\n" +
" <span class=\"widget-title\" ng-dblclick=\"editTitle(widget)\" ng-hide=\"widget.editingTitle\">{{widget.title}}</span>\n" +
" <form action=\"\" class=\"widget-title\" ng-show=\"widget.editingTitle\" ng-submit=\"saveTitleEdit(widget)\">\n" +
" <input type=\"text\" ng-model=\"widget.title\" class=\"form-control\">\n" +
" </form>\n" +
" <span class=\"label label-primary\" ng-if=\"!options.hideWidgetName\">{{widget.name}}</span>\n" +
" <span ng-click=\"removeWidget(widget);\" class=\"glyphicon glyphicon-remove\" ng-if=\"!options.hideWidgetClose\"></span>\n" +
" <span ng-click=\"openWidgetSettings(widget);\" class=\"glyphicon glyphicon-cog\" ng-if=\"!options.hideWidgetSettings\"></span>\n" +
" </h3>\n" +
" </div>\n" +
" <div class=\"panel-body widget-content\"></div>\n" +
" <div class=\"widget-ew-resizer\" ng-mousedown=\"grabResizer($event)\"></div>\n" +
" </div>\n" +
" </div>\n" +
" </div>\n" +
"</div>\n"
);
$templateCache.put("template/dashboard-layouts.html",
"<ul ui-sortable=\"sortableOptions\" ng-model=\"layouts\" class=\"nav nav-tabs layout-tabs\">\n" +
" <li ng-repeat=\"layout in layouts\" ng-class=\"{ active: layout.active }\">\n" +
" <a ng-click=\"makeLayoutActive(layout)\">\n" +
" <span ng-dblclick=\"editTitle(layout)\" ng-show=\"!layout.editingTitle\">{{layout.title}}</span>\n" +
" <form action=\"\" class=\"layout-title\" ng-show=\"layout.editingTitle\" ng-submit=\"saveTitleEdit(layout)\">\n" +
" <input type=\"text\" ng-model=\"layout.title\" class=\"form-control\" data-layout=\"{{layout.id}}\">\n" +
" </form>\n" +
" <span ng-click=\"removeLayout(layout)\" class=\"glyphicon glyphicon-remove remove-layout-icon\"></span>\n" +
" <!-- <span class=\"glyphicon glyphicon-pencil\"></span> -->\n" +
" <!-- <span class=\"glyphicon glyphicon-remove\"></span> -->\n" +
" </a>\n" +
" </li>\n" +
" <li>\n" +
" <a ng-click=\"createNewLayout()\">\n" +
" <span class=\"glyphicon glyphicon-plus\"></span>\n" +
" </a>\n" +
" </li>\n" +
"</ul>\n" +
"<div ng-repeat=\"layout in layouts | filter:isActive\" dashboard=\"layout.dashboard\" template-url=\"template/dashboard.html\"></div>"
);
$templateCache.put("template/dashboard.html",
"<div>\n" +
" <div class=\"btn-toolbar\" ng-if=\"!options.hideToolbar\">\n" +
" <div class=\"btn-group\" ng-if=\"!options.widgetButtons\">\n" +
" <span class=\"dropdown\" on-toggle=\"toggled(open)\">\n" +
" <button type=\"button\" class=\"btn btn-primary dropdown-toggle\" ng-disabled=\"disabled\">\n" +
" Button dropdown <span class=\"caret\"></span>\n" +
" </button>\n" +
" <ul class=\"dropdown-menu\" role=\"menu\">\n" +
" <li ng-repeat=\"widget in widgetDefs\">\n" +
" <a href=\"#\" ng-click=\"addWidgetInternal($event, widget);\" class=\"dropdown-toggle\"><span class=\"label label-primary\">{{widget.name}}</span></a>\n" +
" </li>\n" +
" </ul>\n" +
" </span>\n" +
" </div>\n" +
" <div class=\"btn-group\" ng-if=\"options.widgetButtons\">\n" +
" <button ng-repeat=\"widget in widgetDefs\"\n" +
" ng-click=\"addWidgetInternal($event, widget);\" type=\"button\" class=\"btn btn-primary\">\n" +
" {{widget.name}}\n" +
" </button>\n" +
" </div>\n" +
"\n" +
" <button class=\"btn btn-warning\" ng-click=\"resetWidgetsToDefault()\">Default Widgets</button>\n" +
"\n" +
" <button ng-if=\"options.storage && options.explicitSave\" ng-click=\"options.saveDashboard()\" class=\"btn btn-success\" ng-disabled=\"!options.unsavedChangeCount\">{{ !options.unsavedChangeCount ? \"all saved\" : \"save changes (\" + options.unsavedChangeCount + \")\" }}</button>\n" +
"\n" +
" <button ng-click=\"clear();\" type=\"button\" class=\"btn btn-info\">Clear</button>\n" +
" </div>\n" +
"\n" +
" <div ui-sortable=\"sortableOptions\" ng-model=\"widgets\" class=\"dashboard-widget-area\">\n" +
" <div ng-repeat=\"widget in widgets\" ng-style=\"widget.containerStyle\" class=\"widget-container\" widget>\n" +
" <div class=\"widget panel panel-default\">\n" +
" <div class=\"widget-header panel-heading\">\n" +
" <h3 class=\"panel-title\">\n" +
" <span class=\"widget-title\" ng-dblclick=\"editTitle(widget)\" ng-hide=\"widget.editingTitle\">{{widget.title}}</span>\n" +
" <form action=\"\" class=\"widget-title\" ng-show=\"widget.editingTitle\" ng-submit=\"saveTitleEdit(widget)\">\n" +
" <input type=\"text\" ng-model=\"widget.title\" class=\"form-control\">\n" +
" </form>\n" +
" <span class=\"label label-primary\" ng-if=\"!options.hideWidgetName\">{{widget.name}}</span>\n" +
" <span ng-click=\"removeWidget(widget);\" class=\"glyphicon glyphicon-remove\" ng-if=\"!options.hideWidgetClose\"></span>\n" +
" <span ng-click=\"openWidgetSettings(widget);\" class=\"glyphicon glyphicon-cog\" ng-if=\"!options.hideWidgetSettings\"></span>\n" +
" </h3>\n" +
" </div>\n" +
" <div class=\"panel-body widget-content\" ng-style=\"widget.contentStyle\"></div>\n" +
" <div class=\"widget-ew-resizer\" ng-mousedown=\"grabResizer($event)\"></div>\n" +
" <div ng-if=\"widget.enableVerticalResize\" class=\"widget-s-resizer\" ng-mousedown=\"grabSouthResizer($event)\"></div>\n" +
" </div>\n" +
" </div>\n" +
" </div>\n" +
"</div>"
);
$templateCache.put("template/save-changes-modal.html",
"<div class=\"modal-header\">\n" +
" <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\" ng-click=\"cancel()\">×</button>\n" +
" <h3>Unsaved Changes to \"{{layout.title}}\"</h3>\n" +
"</div>\n" +
"\n" +
"<div class=\"modal-body\">\n" +
" <p>You have {{layout.dashboard.unsavedChangeCount}} unsaved changes on this dashboard. Would you like to save them?</p>\n" +
"</div>\n" +
"\n" +
"<div class=\"modal-footer\">\n" +
" <button type=\"button\" class=\"btn btn-default\" ng-click=\"cancel()\">Don't Save</button>\n" +
" <button type=\"button\" class=\"btn btn-primary\" ng-click=\"ok()\">Save</button>\n" +
"</div>"
);
$templateCache.put("template/widget-default-content.html",
""
);
$templateCache.put("template/widget-settings-template.html",
"<div class=\"modal-header\">\n" +
" <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\" ng-click=\"cancel()\">×</button>\n" +
" <h3>Widget Options <small>{{widget.title}}</small></h3>\n" +
"</div>\n" +
"\n" +
"<div class=\"modal-body\">\n" +
" <form name=\"form\" novalidate class=\"form-horizontal\">\n" +
" <div class=\"form-group\">\n" +
" <label for=\"widgetTitle\" class=\"col-sm-2 control-label\">Title</label>\n" +
" <div class=\"col-sm-10\">\n" +
" <input type=\"text\" class=\"form-control\" name=\"widgetTitle\" ng-model=\"result.title\">\n" +
" </div>\n" +
" </div>\n" +
" <div ng-if=\"widget.settingsModalOptions.partialTemplateUrl\"\n" +
" ng-include=\"widget.settingsModalOptions.partialTemplateUrl\"></div>\n" +
" </form>\n" +
"</div>\n" +
"\n" +
"<div class=\"modal-footer\">\n" +
" <button type=\"button\" class=\"btn btn-default\" ng-click=\"cancel()\">Cancel</button>\n" +
" <button type=\"button\" class=\"btn btn-primary\" ng-click=\"ok()\">OK</button>\n" +
"</div>"
);
}]);
| ninjasun/malhar-angular-dashboard | dist/angular-ui-dashboard.js | JavaScript | apache-2.0 | 56,177 |
/*
AngularJS v1.2.14-build.2267+sha.cceb455
(c) 2010-2014 Google, Inc. http://angularjs.org
License: MIT
*/
(function(p,f,n){'use strict';f.module("ngCookies",["ng"]).factory("$cookies",["$rootScope","$browser",function(d,b){var c={},g={},h,k=!1,l=f.copy,m=f.isUndefined;b.addPollFn(function(){var a=b.cookies();h!=a&&(h=a,l(a,g),l(a,c),k&&d.$apply())})();k=!0;d.$watch(function(){var a,e,d;for(a in g)m(c[a])&&b.cookies(a,n);for(a in c)(e=c[a],f.isString(e))?e!==g[a]&&(b.cookies(a,e),d=!0):f.isDefined(g[a])?c[a]=g[a]:delete c[a];if(d)for(a in e=b.cookies(),c)c[a]!==e[a]&&(m(e[a])?delete c[a]:c[a]=e[a])});
return c}]).factory("$cookieStore",["$cookies",function(d){return{get:function(b){return(b=d[b])?f.fromJson(b):b},put:function(b,c){d[b]=f.toJson(c)},remove:function(b){delete d[b]}}}])})(window,window.angular);
//# sourceMappingURL=angular-cookies.min.js.map
| ravikiran438/cevent-app | src/main/webapp/bower_components/angular-cookies/angular-cookies.min.js | JavaScript | apache-2.0 | 873 |
Clazz.declarePackage ("J.util");
Clazz.load (null, "J.util.SimpleUnitCell", ["java.lang.Float", "J.util.ArrayUtil", "$.Matrix4f", "$.V3"], function () {
c$ = Clazz.decorateAsClass (function () {
this.notionalUnitcell = null;
this.matrixCartesianToFractional = null;
this.matrixFractionalToCartesian = null;
this.na = 0;
this.nb = 0;
this.nc = 0;
this.a = 0;
this.b = 0;
this.c = 0;
this.alpha = 0;
this.beta = 0;
this.gamma = 0;
this.cosAlpha = 0;
this.sinAlpha = 0;
this.cosBeta = 0;
this.sinBeta = 0;
this.cosGamma = 0;
this.sinGamma = 0;
this.volume = 0;
this.cA_ = 0;
this.cB_ = 0;
this.a_ = 0;
this.b_ = 0;
this.c_ = 0;
this.dimension = 0;
this.matrixCtoFAbsolute = null;
this.matrixFtoCAbsolute = null;
Clazz.instantialize (this, arguments);
}, J.util, "SimpleUnitCell");
$_M(c$, "isSupercell",
function () {
return (this.na > 1 || this.nb > 1 || this.nc > 1);
});
c$.isValid = $_M(c$, "isValid",
function (parameters) {
return (parameters != null && (parameters[0] > 0 || parameters.length > 14 && !Float.isNaN (parameters[14])));
}, "~A");
Clazz.makeConstructor (c$,
function () {
});
c$.newA = $_M(c$, "newA",
function (parameters) {
var c = new J.util.SimpleUnitCell ();
c.set (parameters);
return c;
}, "~A");
$_M(c$, "set",
function (parameters) {
if (!J.util.SimpleUnitCell.isValid (parameters)) return;
this.notionalUnitcell = J.util.ArrayUtil.arrayCopyF (parameters, parameters.length);
this.a = parameters[0];
this.b = parameters[1];
this.c = parameters[2];
this.alpha = parameters[3];
this.beta = parameters[4];
this.gamma = parameters[5];
this.na = Math.max (1, parameters.length >= 25 && !Float.isNaN (parameters[22]) ? Clazz.floatToInt (parameters[22]) : 1);
this.nb = Math.max (1, parameters.length >= 25 && !Float.isNaN (parameters[23]) ? Clazz.floatToInt (parameters[23]) : 1);
this.nc = Math.max (1, parameters.length >= 25 && !Float.isNaN (parameters[24]) ? Clazz.floatToInt (parameters[24]) : 1);
if (this.a <= 0) {
var va = J.util.V3.new3 (parameters[6], parameters[7], parameters[8]);
var vb = J.util.V3.new3 (parameters[9], parameters[10], parameters[11]);
var vc = J.util.V3.new3 (parameters[12], parameters[13], parameters[14]);
this.a = va.length ();
this.b = vb.length ();
this.c = vc.length ();
if (this.a == 0) return;
if (this.b == 0) this.b = this.c = -1;
else if (this.c == 0) this.c = -1;
this.alpha = (this.b < 0 || this.c < 0 ? 90 : vb.angle (vc) / 0.017453292);
this.beta = (this.c < 0 ? 90 : va.angle (vc) / 0.017453292);
this.gamma = (this.b < 0 ? 90 : va.angle (vb) / 0.017453292);
if (this.c < 0) {
var n = J.util.ArrayUtil.arrayCopyF (parameters, -1);
if (this.b < 0) {
vb.set (0, 0, 1);
vb.cross (vb, va);
if (vb.length () < 0.001) vb.set (0, 1, 0);
vb.normalize ();
n[9] = vb.x;
n[10] = vb.y;
n[11] = vb.z;
}if (this.c < 0) {
vc.cross (va, vb);
vc.normalize ();
n[12] = vc.x;
n[13] = vc.y;
n[14] = vc.z;
}parameters = n;
}}this.a *= this.na;
if (this.b <= 0) {
this.b = this.c = 1;
this.dimension = 1;
} else if (this.c <= 0) {
this.c = 1;
this.b *= this.nb;
this.dimension = 2;
} else {
this.b *= this.nb;
this.c *= this.nc;
this.dimension = 3;
}this.cosAlpha = Math.cos (0.017453292 * this.alpha);
this.sinAlpha = Math.sin (0.017453292 * this.alpha);
this.cosBeta = Math.cos (0.017453292 * this.beta);
this.sinBeta = Math.sin (0.017453292 * this.beta);
this.cosGamma = Math.cos (0.017453292 * this.gamma);
this.sinGamma = Math.sin (0.017453292 * this.gamma);
var unitVolume = Math.sqrt (this.sinAlpha * this.sinAlpha + this.sinBeta * this.sinBeta + this.sinGamma * this.sinGamma + 2.0 * this.cosAlpha * this.cosBeta * this.cosGamma - 2);
this.volume = this.a * this.b * this.c * unitVolume;
this.cA_ = (this.cosAlpha - this.cosBeta * this.cosGamma) / this.sinGamma;
this.cB_ = unitVolume / this.sinGamma;
this.a_ = this.b * this.c * this.sinAlpha / this.volume;
this.b_ = this.a * this.c * this.sinBeta / this.volume;
this.c_ = this.a * this.b * this.sinGamma / this.volume;
if (parameters.length > 21 && !Float.isNaN (parameters[21])) {
var scaleMatrix = Clazz.newFloatArray (16, 0);
for (var i = 0; i < 16; i++) {
var f;
switch (i % 4) {
case 0:
f = this.na;
break;
case 1:
f = this.nb;
break;
case 2:
f = this.nc;
break;
default:
f = 1;
break;
}
scaleMatrix[i] = parameters[6 + i] * f;
}
this.matrixCartesianToFractional = J.util.Matrix4f.newA (scaleMatrix);
this.matrixFractionalToCartesian = new J.util.Matrix4f ();
this.matrixFractionalToCartesian.invertM (this.matrixCartesianToFractional);
} else if (parameters.length > 14 && !Float.isNaN (parameters[14])) {
var m = this.matrixFractionalToCartesian = new J.util.Matrix4f ();
m.setColumn4 (0, parameters[6] * this.na, parameters[7] * this.na, parameters[8] * this.na, 0);
m.setColumn4 (1, parameters[9] * this.nb, parameters[10] * this.nb, parameters[11] * this.nb, 0);
m.setColumn4 (2, parameters[12] * this.nc, parameters[13] * this.nc, parameters[14] * this.nc, 0);
m.setColumn4 (3, 0, 0, 0, 1);
this.matrixCartesianToFractional = new J.util.Matrix4f ();
this.matrixCartesianToFractional.invertM (this.matrixFractionalToCartesian);
} else {
var m = this.matrixFractionalToCartesian = new J.util.Matrix4f ();
m.setColumn4 (0, this.a, 0, 0, 0);
m.setColumn4 (1, (this.b * this.cosGamma), (this.b * this.sinGamma), 0, 0);
m.setColumn4 (2, (this.c * this.cosBeta), (this.c * (this.cosAlpha - this.cosBeta * this.cosGamma) / this.sinGamma), (this.volume / (this.a * this.b * this.sinGamma)), 0);
m.setColumn4 (3, 0, 0, 0, 1);
this.matrixCartesianToFractional = new J.util.Matrix4f ();
this.matrixCartesianToFractional.invertM (this.matrixFractionalToCartesian);
}this.matrixCtoFAbsolute = this.matrixCartesianToFractional;
this.matrixFtoCAbsolute = this.matrixFractionalToCartesian;
}, "~A");
$_M(c$, "toSupercell",
function (fpt) {
fpt.x /= this.na;
fpt.y /= this.nb;
fpt.z /= this.nc;
return fpt;
}, "J.util.P3");
$_M(c$, "toCartesian",
function (pt, isAbsolute) {
if (this.matrixFractionalToCartesian != null) (isAbsolute ? this.matrixFtoCAbsolute : this.matrixFractionalToCartesian).transform (pt);
}, "J.util.Tuple3f,~B");
$_M(c$, "toFractional",
function (pt, isAbsolute) {
if (this.matrixCartesianToFractional == null) return;
(isAbsolute ? this.matrixCtoFAbsolute : this.matrixCartesianToFractional).transform (pt);
}, "J.util.Tuple3f,~B");
$_M(c$, "isPolymer",
function () {
return (this.dimension == 1);
});
$_M(c$, "isSlab",
function () {
return (this.dimension == 2);
});
$_M(c$, "getNotionalUnitCell",
function () {
return this.notionalUnitcell;
});
$_M(c$, "getUnitCellAsArray",
function (vectorsOnly) {
var m = this.matrixFractionalToCartesian;
return (vectorsOnly ? [m.m00, m.m10, m.m20, m.m01, m.m11, m.m21, m.m02, m.m12, m.m22] : [this.a, this.b, this.c, this.alpha, this.beta, this.gamma, m.m00, m.m10, m.m20, m.m01, m.m11, m.m21, m.m02, m.m12, m.m22, this.dimension, this.volume]);
}, "~B");
$_M(c$, "getInfo",
function (infoType) {
switch (infoType) {
case 0:
return this.a;
case 1:
return this.b;
case 2:
return this.c;
case 3:
return this.alpha;
case 4:
return this.beta;
case 5:
return this.gamma;
case 6:
return this.dimension;
}
return NaN;
}, "~N");
c$.ijkToPoint3f = $_M(c$, "ijkToPoint3f",
function (nnn, cell, c) {
c -= 5;
cell.x = Clazz.doubleToInt (nnn / 100) + c;
cell.y = Clazz.doubleToInt ((nnn % 100) / 10) + c;
cell.z = (nnn % 10) + c;
}, "~N,J.util.P3,~N");
Clazz.defineStatics (c$,
"toRadians", 0.017453292,
"INFO_DIMENSIONS", 6,
"INFO_GAMMA", 5,
"INFO_BETA", 4,
"INFO_ALPHA", 3,
"INFO_C", 2,
"INFO_B", 1,
"INFO_A", 0);
});
| DeepLit/WHG | root/static/js/jsmol/j2s/J/util/SimpleUnitCell.js | JavaScript | apache-2.0 | 7,722 |
//engine: JScript
//uname: diff_1C
//dname: Backend к diff, типовое сравнение от 1С (mxl,txt,js,vbs)
//addin: global
global.connectGlobals(SelfScript)
function СравнениеФайлов1С(Path1, Path2) {
var file1 = v8New("File", Path1);
var file2 = v8New("File", Path2);
if ((!file1.isFile()) & (!file2.isFile())) return null
var ext1 = file1.Extension.substr(1).toLowerCase(); //Уберем первый символ, да в нижний регистр, этоже windows
var ext2 = file2.Extension.substr(1).toLowerCase(); //Уберем первый символ, да в нижний регистр, этоже windows
var fc = v8New("СравнениеФайлов")
fc.ПервыйФайл = Path1;
fc.ВторойФайл = Path2;
fc.СпособСравнения = СпособСравненияФайлов.Двоичное;
if ((ext1.indexOf("mxl") >= 0) & (ext2.indexOf("mxl") >= 0)) fc.СпособСравнения = СпособСравненияФайлов.ТабличныйДокумент;
if ((ext1.indexOf("txt") >= 0) & (ext2.indexOf("txt") >= 0)) fc.СпособСравнения = СпособСравненияФайлов.ТекстовыйДокумент;
if ((ext1.indexOf("js") >= 0) & (ext2.indexOf("js") >= 0)) fc.СпособСравнения = СпособСравненияФайлов.ТекстовыйДокумент;
if ((ext1.indexOf("vbs") >= 0) & (ext2.indexOf("vbs") >= 0)) fc.СпособСравнения = СпособСравненияФайлов.ТекстовыйДокумент;
fc.ПоказатьРазличия();
} //СравнениеФайлов1С
function GetExtension () {
return "mxl|txt|js|vbs";
} //GetExtension
function GetBackend() {
return СравнениеФайлов1С
} //GetBackend
| artbear/snegopat-reborn-scripts | core/addins/dvcs/diff_1C.js | JavaScript | apache-2.0 | 1,902 |
/**
* Plus : Checkbox Tree
* Author : zhaoyang
*/
(function ($) {
$.fn.treeview = function(settings) {
var chkname = "pri",
dfop = {
method: "POST",
datatype: "json",
url: false,
cbiconpath: contextPath + "/rc/sc/jq/themes/treeview/img/tree/",
oncheckboxclick: false, // 当checkstate状态变化时所触发的事件,但是不会触发因级联选择而引起的变化
onnodeclick: false,
cascadecheck: true,
data: null,
clicktoggle: true, // 点击节点展开和收缩子节点
theme: "bbit-tree-arrows" // bbit-tree-lines,bbit-tree-no-lines,bbit-tree-arrows
};
$.extend(dfop, settings);
var treenodes = dfop.data, me = $(this), id = me.attr("id");
if (id == null || id == "") {
id = "bbtree" + new Date().getTime();
me.attr("id", id);
}
var html = [];
buildtree(dfop.data, html);
me.addClass("bbit-tree").html(html.join(""));
InitEvent(me);
html = null;
// region
function buildtree(data, ht) {
ht.push("<div class='bbit-tree-bwrap'>"); // Wrap ;
ht.push("<div class='bbit-tree-body'>"); // body ;
ht.push("<ul class='bbit-tree-root ", dfop.theme, "'>"); // root
var l = data.length;
for (var i = 0; i < l; i++) {
buildnode(data[i], ht, 0, i, i == l - 1);
}
ht.push("</ul>"); // root and;
ht.push("</div>"); // body end;
ht.push("</div>"); // Wrap end;
}
// endregion
function buildnode(nd, ht, deep, path, isend) {
ht.push("<li class='bbit-tree-node'>");
ht.push("<div id='", id, "_", nd.id, "' tpath='", path, "' unselectable='on'");
var cs = [];
cs.push("bbit-tree-node-el");
if (!nd.hasChildren) {
cs.push("bbit-tree-node-leaf");
}
if (nd.classes) { cs.push(nd.classes); }
ht.push(" class='", cs.join(" "), "'>");
// span indent
ht.push("<span class='bbit-tree-node-indent'>");
if (deep == 1) {
ht.push("<img class='bbit-tree-icon' src='"+contextPath+"/rc/sc/jq/themes/treeview/img/s.gif'/>");
} else if (deep > 1) {
ht.push("<img class='bbit-tree-icon' src='"+contextPath+"/rc/sc/jq/themes/treeview/img/s.gif'/>");
for (var j = 1; j < deep; j++) {
ht.push("<img class='bbit-tree-elbow-line' src='"+contextPath+"/rc/sc/jq/themes/treeview/img/s.gif'/>");
}
}
ht.push("</span>");
// checkbox
ht.push("<input type='checkbox' id='", id, "_", nd.id, "_cb' value='",nd.value,"' ",nd.checkstate?'checked=checked':''," ",nd.ChildNodes?'haschildren=true':'haschildren=false'," name=",chkname," paths='",path,"' />");
// a
ht.push("<a hideFocus class='bbit-tree-node-anchor' tabIndex=1 href='javascript:void(0);'>");
ht.push("<span unselectable='on'>", nd.text, "</span>");
ht.push("</a>");
ht.push("</div>");
// Child
if (nd.hasChildren) {
ht.push("<ul class='bbit-tree-node-ct' style='z-index: 0; position: static; visibility: visible; top: auto; left: auto;'>");
if (nd.ChildNodes) {
var l = nd.ChildNodes.length;
for (var k = 0; k < l; k++) {
nd.ChildNodes[k].parent = nd;
buildnode(nd.ChildNodes[k], ht, deep + 1, path + "." + k, k == l - 1);
}
}
ht.push("</ul>");
} else {
ht.push("<ul style='display:none;'></ul>");
}
ht.push("</li>");
nd.render = true;
}
function getItem(path) {
var ap = path.split(".");
var t = treenodes;
for (var i = 0; i < ap.length; i++) {
if (i == 0) {
t = t[ap[i]];
} else {
t = t.ChildNodes[ap[i]];
}
}
return t;
}
function check(item, state, type) {
var pstate = item.checkstate;
if (type == 1) {
item.checkstate = state;
} else {// 上溯
var cs = item.ChildNodes;
var l = cs.length;
var ch = true;
for (var i = 0; i < l; i++) {
if ((state == true && cs[i].checkstate != true) || state == false && cs[i].checkstate != false) {
ch = false;
break;
}
}
if (ch) {
item.checkstate = state;
} else {
item.checkstate = 2;
}
}
// change show **************重点*************
if (item.render && pstate != item.checkstate) {
var et = $("#" + id + "_" + item.id + "_cb");
if (et.length == 1) {
et.attr("checked", item.checkstate);
}
}
}
function cascadeCheck(ulNode) {
if (ulNode && ulNode.previousSibling && ulNode.previousSibling.childNodes[1]) {
if (ulNode.previousSibling.childNodes[1].nodeName == "INPUT") {
var posArr = "", pos = "";
if ($(ulNode.previousSibling.childNodes[1]).attr("paths").indexOf(".")) {
posArr = $(ulNode.previousSibling.childNodes[1]).attr("paths").split(".");
for (var i in posArr) {
if (i == 0) {
pos += "["+ posArr[i] + "]";
} else {
pos += "['ChildNodes']["+ posArr[i] + "]";
}
}
} else {
posArr = $(ulNode.previousSibling.childNodes[1]).attr("paths");
pos += "["+ posArr + "]";
}
eval("dfop.data"+pos).checkstate = true;
ulNode.previousSibling.childNodes[1].checked = true;
pos = null;
cascadeCheck(ulNode.parentNode.parentNode);
}
}
}
// 遍历子节点
function cascade(fn, item, args) {
if (fn(item, args, 1) != false) {
if (item.ChildNodes != null && item.ChildNodes.length > 0) {
var cs = item.ChildNodes;
for (var i = 0, len = cs.length; i < len; i++) {
cascade(fn, cs[i], args);
}
}
}
}
// 冒泡的祖先
function bubble(fn, item, args) {
var p = item.parent;
while (p) {
if (fn(p, args, 0) === false) {
break;
}
p = p.parent;
}
}
function nodeclick(e) {
var path = $(this).attr("tpath");
var et = e.target || e.srcElement;
var item = getItem(path);
var s = item.checkstate ? false : true;
var r = true;
if (dfop.oncheckboxclick) {
r = dfop.oncheckboxclick.call(et, item, s);
}
if (r != false) {
if (dfop.cascadecheck) {
// 遍历
cascade(check, item, s);
// 上溯
bubble(check, item, s);
} else {
check(item, s, 1);
}
}
}
function asnybuild(nodes, deep, path, ul, pnode) {
var l = nodes.length;
if (l > 0) {
var ht = [];
for (var i = 0; i < l; i++) {
nodes[i].parent = pnode;
buildnode(nodes[i], ht, deep, path + "." + i, i == l - 1);
}
ul.html(ht.join(""));
ht = null;
InitEvent(ul);
}
ul.addClass("bbit-tree-node-ct").css({ "z-index": 0, position: "static", visibility: "visible", top: "auto", left: "auto", display: "" });
ul.prev().removeClass("bbit-tree-node-loading");
}
function asnyloadc(pul, pnode, callback) {
if (dfop.url) {
var param = builparam(pnode);
$.ajax({
type: dfop.method,
url: dfop.url,
data: param,
dataType: dfop.datatype,
success: callback,
error: function(e) { alert("error occur!"); }
});
}
}
function builparam(node) {
var p = [{ name: "id", value: encodeURIComponent(node.id) }
, { name: "text", value: encodeURIComponent(node.text) }
, { name: "value", value: encodeURIComponent(node.value) }
, { name: "checkstate", value: node.checkstate}];
return p;
}
function InitEvent(parent) {
var nodes = $("li.bbit-tree-node>div", parent);
nodes.each(function(e) {
$(this).hover(function() {
$(this).addClass("bbit-tree-node-over");
}, function() {
$(this).removeClass("bbit-tree-node-over");
})
.click(nodeclick);
});
$(":checkbox[checked][haschildren=false]").each(function () {
cascadeCheck(this.parentNode.parentNode.parentNode);
});
}
function getck(items, c, fn) {
for (var i = 0, l = items.length; i < l; i++) {
items[i].checkstate == 1 && c.push(fn(items[i]));
if (items[i].ChildNodes != null && items[i].ChildNodes.length > 0) {
getck(items[i].ChildNodes, c, fn);
}
}
}
me[0].t = {
getSelectedNodes: function() {
var s = [];
getck(treenodes, s, function(item) { return item });
return s;
},
getSelectedValues: function() {
var s = [];
getck(treenodes, s, function(item) { return item.value });
return s;
},
getCurrentItem: function() {
return dfop.citem;
}
};
return me;
};
$.fn.swapClass = function(c1, c2) {
return this.removeClass(c1).addClass(c2);
};
// 获取所有选中的节点的Value数组
$.fn.getTSVs = function() {
if (this[0].t) {
return this[0].t.getSelectedValues();
}
return null;
};
// 获取所有选中的节点的Item数组
$.fn.getTSNs = function() {
if (this[0].t) {
return this[0].t.getSelectedNodes();
}
return null;
};
$.fn.getTCT = function() {
if (this[0].t) {
return this[0].t.getCurrentItem();
}
return null;
};
})(jQuery) | TTroia/CommunityManager | WebRoot/rc/sc/jq/plus/checkboxTree.js | JavaScript | apache-2.0 | 9,133 |
/*
* Copyright IBM Corp. 2017
*
* 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.
*/
var fs = require('fs');
var path = require('path');
module.exports = {
fileExists: function (filePath) {
try {
return fs.statSync(filePath).isFile();
} catch (err) {
return false;
}
},
size: function (filePath) {
try {
var units = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
var size = fs.statSync(filePath).size;
var exponent = Math.floor(Math.log(size) / Math.log(1024));
return (size / Math.pow(1024, exponent)).toFixed(2) + ' ' + units[exponent];
}
catch (err) {
throw err;
}
},
read: function (filePath) {
try {
return fs.readFileSync(filePath, 'utf8');
} catch (err) {
throw err;
}
},
write: function (filePath, content) {
try {
return fs.writeFileSync(filePath, content, 'utf8');
} catch (err) {
throw err;
}
},
stream: function (filePath) {
try {
return fs.createReadStream(filePath);
} catch(err) {
throw err;
}
},
name: function (filePath) {
return path.parse(filePath).name;
},
ext: function (filePath) {
return path.parse(filePath).ext;
}
}; | steveatkin/Subtitler | lib/files.js | JavaScript | apache-2.0 | 1,903 |
/*
* Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["ms"] = {
name: "ms",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["($n)","$n"],
decimals: 0,
",": ",",
".": ".",
groupSize: [3],
symbol: "RM"
}
},
calendars: {
standard: {
days: {
names: ["Ahad","Isnin","Selasa","Rabu","Khamis","Jumaat","Sabtu"],
namesAbbr: ["Ahad","Isnin","Sel","Rabu","Khamis","Jumaat","Sabtu"],
namesShort: ["A","I","S","R","K","J","S"]
},
months: {
names: ["Januari","Februari","Mac","April","Mei","Jun","Julai","Ogos","September","Oktober","November","Disember",""],
namesAbbr: ["Jan","Feb","Mac","Apr","Mei","Jun","Jul","Ogos","Sept","Okt","Nov","Dis",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy H:mm:ss",
g: "dd/MM/yyyy H:mm",
G: "dd/MM/yyyy H:mm:ss",
m: "dd MMMM",
M: "dd 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(); }); | y-todorov/Inventory | Inventory.MVC/Scripts/Kendo/cultures/kendo.culture.ms.js | JavaScript | apache-2.0 | 2,610 |
/* Copyright 2016-2017 University of Pittsburgh
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. */
/* description
load NER in json to elasticsearch for dbmi-annotator pre-annotate drug mentions */
// IMPORT=================================================================
var config = require('./../config/config.js');
var HOSTNAME = config.elastico.host;
var ES_CONN = config.elastico.host + ":" + config.elastico.port;
var q = require('q');
var uuid = require('uuid');
var fs = require('fs');
// ELASTICO=================================================================
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: ES_CONN
//log: 'trace'
});
//MAIN=================================================================
var args = process.argv.slice(2);
if (args.length == 3) {
var email = args[2];
if (args[1] == "dailymed" || args[1] == "pubmed"){
if (args[1] == "dailymed")
var NER_RESULTS = "ner-dailymed-json";
else if (args[1] == "pubmed") {
var NER_RESULTS = "ner-pubmed-json";
}
var nerResults = fs.readFileSync(NER_RESULTS,"utf-8");
var nersets = JSON.parse(nerResults).nersets;
loadNERs(nersets, args[1], email);
}
else {
console.log("RUN: node load-ner.js <ner-results (ex. ner-pubmed-json)> <options: pubmed or dailymed> <user email (ex. yin2@gmail.com)>");
process.exit(1);
}
} else {
console.log("RUN: node load-ner.js <ner-results (ex. ner-pubmed-json)> <options: pubmed or dailymed> <user email (ex. yin2@gmail.com)>");
process.exit(1);
}
function loadNERs(nersets, sourceType, email){
for (i = 0; i < nersets.length; i++){
//for (i = 0; i < 1; i++){
subL = nersets[i];
for (j = 0; j < subL.length; j++){
//for (j = 0; j < 10; j++){
annotation = subL[j];
if (annotation){
uriStr = "";
if (sourceType == "pubmed")
// load for alive PMC articles
// uriStr = "http://www.ncbi.nlm.nih.gov/pmc/articles/" + annotation.setid;
// load for local pmc html articles
uriStr = "http://localhost/dbmiannotator/" + annotation.setid + ".html";
else if (sourceType == "dailymed")
uriStr = "http://" + HOSTNAME + "/DDI-labels/" + annotation.setid + ".html";
else {
console.log("[ERROR] sourceType wrong: " + sourceType);
process.exit(1);
}
loadNewAnnotation(annotation, uriStr, email);
}
}
}
}
function loadNewAnnotation(annotation, uriStr, email){
console.log("[INFO]: begin check for " + annotation.exact + " | " + email);
uriPost = uriStr.replace(/[\/\\\-\:\.]/g, "");
q.nfcall(
client.search(
{
index: 'annotator',
type: 'annotation',
body:{
query : {
bool : {
must : [
{
match: {
"email": email
}
},
{
match: {
"uri": uriPost
}
},
{
match: {
"prefix": annotation.prefix
}
},
{
match: {
"exact": annotation.exact
}
},
{
match: {
"suffix": annotation.suffix
}
}
]
}
}
}
}).then(function (resp){
var hits = resp.hits.hits;
if (hits.length > 0){
console.log("[EXITS] " + annotation.exact);
//console.log(hits);
return true;
} else {
console.log("[NOT EXITS] " + annotation.exact);
return false;
}
}).then(function (isExists){
if (!isExists){
loadAnnotation(annotation, uriStr, email);
}
})
);
}
function loadAnnotation(annotation, uriStr, email){
if (annotation == null){
console.log("[ERROR] annotation is null!");
if (annotation.setid == null || annotation.drugname == null || annotation.startOffset == null || annotation.endOffset == null || start == null || end == null)
console.log("[ERROR] annot attributes incompelete!");
return null;
} else {
uriPost = uriStr.replace(/[\/\\\-\:\.]/g, "");
path = annotation.start.replace("/html[1]/body[1]","");
console.log("[INFO]: begin load for " + annotation.exact);
var datetime = new Date();
client.index(
{
index: 'annotator',
type: 'annotation',
id: uuid.v4(),
body: { // annotatorJs fields for drug Mention
"email": email,
"created": datetime,
"updated": datetime,
"annotationType": "DrugMention",
"permissions": {
"read": ["group:__consumer__"]
},
"argues": {
"hasTarget": {
"hasSelector": {
"@type": "TextQuoteSelector",
"exact": annotation.exact,
"prefix": annotation.prefix,
"suffix": annotation.suffix
}
},
"ranges": [
// {
// "start": path,
// "end": path,
// "startOffset": parseInt(annotation.startOffset),
// "endOffset": parseInt(annotation.endOffset),
// }
],
"supportsBy": []
},
"consumer": "mockconsumer",
"uri": uriPost,
"rawurl": uriStr,
"user": "alice"
}
}, function (err, resp) {
if (err)
console.log("[ERROR] " + err);
else
console.log("[INFO] load successfully");
});
}
}
| dbmi-pitt/dbmi-annotator | pre-annot-tool/load-ner.js | JavaScript | apache-2.0 | 7,843 |
import React from 'react';
import PageTemplate from '../../components/PageTemplate';
import BannerMain from '../../components/BannerMain';
import Carousel from '../../components/Carousel';
import dadosIniciais from '../../data/dados_iniciais.json';
function Home() {
return (
<PageTemplate>
<BannerMain
videoTitle={dadosIniciais.categorias[0].videos[0].titulo}
url={dadosIniciais.categorias[0].videos[0].url}
videoDescription={'O que é front end?'}
/>
<Carousel
ignoreFirstVideo
category={dadosIniciais.categorias[0]}
/>
<Carousel
category={dadosIniciais.categorias[1]}
/>
<Carousel
category={dadosIniciais.categorias[2]}
/>
<Carousel
category={dadosIniciais.categorias[3]}
/>
<Carousel
category={dadosIniciais.categorias[4]}
/>
<Carousel
category={dadosIniciais.categorias[5]}
/>
</PageTemplate>
);
}
export default Home;
| wesleyegberto/courses-projects | frontend/react-stack/react/aluraflix/src/pages/Home/index.js | JavaScript | apache-2.0 | 1,010 |
'use strict'
const utils = require('../../utils')
const debug = require('debug')
const log = debug('cli:object')
log.error = debug('cli:object:error')
module.exports = {
command: 'stat <key>',
describe: 'Get stats for the DAG node named by <key>',
builder: {},
handler (argv) {
utils.getIPFS((err, ipfs) => {
if (err) {
throw err
}
ipfs.object.stat(argv.key, {enc: 'base58'}, (err, stats) => {
if (err) {
throw err
}
delete stats.Hash // only for js-ipfs-api output
Object.keys(stats).forEach((key) => {
console.log(`${key}: ${stats[key]}`)
})
})
})
}
}
| Project-Oaken/water-meter-acorn | demo-for-video/water-meter-1-liter-demo/node/node_modules/ipfs/src/cli/commands/object/stat.js | JavaScript | apache-2.0 | 672 |
'use strict';
const _ = require('lodash');
const utils = require('../common/utils');
const bosh = require('../data-access-layer/bosh');
const Agent = require('../data-access-layer/service-agent');
const logger = require('../common/logger');
const errors = require('../common/errors');
const ServiceInstanceNotFound = errors.ServiceInstanceNotFound;
const BoshDirectorClient = bosh.BoshDirectorClient;
const Networks = bosh.manifest.Networks;
const BaseService = require('./BaseService');
class BaseDirectorService extends BaseService {
constructor(plan) {
super(plan);
this.plan = plan;
this.director = bosh.director;
this.agent = new Agent(this.settings.agent);
}
static parseDeploymentName(deploymentName, subnet) {
return _
.chain(utils.deploymentNameRegExp(subnet).exec(deploymentName))
.slice(1)
.tap(parts => parts[1] = parts.length ? parseInt(parts[1]) : undefined)
.value();
}
getDeploymentIps(deploymentName) {
return this.director.getDeploymentIps(deploymentName);
}
get template() {
return new Buffer(this.settings.template, 'base64').toString('utf8');
}
findDeploymentNameByInstanceId(guid) {
logger.info(`Finding deployment name with instance id : '${guid}'`);
return this.getDeploymentNames(false)
.then(deploymentNames => {
const deploymentName = _.find(deploymentNames, name => _.endsWith(name, guid));
if (!deploymentName) {
logger.warn(`+-> Could not find a matching deployment for guid: ${guid}`);
throw new ServiceInstanceNotFound(guid);
}
return deploymentName;
})
.tap(deploymentName => logger.info(`+-> Found deployment '${deploymentName}' for '${guid}'`));
}
getDeploymentNames(queued) {
return this.director.getDeploymentNames(queued);
}
get stemcell() {
return _(this.settings)
.chain()
.get('stemcell', {})
.defaults(BoshDirectorClient.getInfrastructure().stemcell)
.update('version', version => '' + version)
.value();
}
get releases() {
return _(this.settings)
.chain()
.get('releases')
.map(release => _.pick(release, 'name', 'version'))
.sortBy(release => `${release.name}/${release.version}`)
.value();
}
get networkName() {
return this.subnet || BoshDirectorClient.getInfrastructure().segmentation.network_name || 'default';
}
getNetworks(index) {
return new Networks(BoshDirectorClient.getInfrastructure().networks, index, BoshDirectorClient.getInfrastructure().segmentation);
}
getNetwork(index) {
return this.getNetworks(index)[this.networkName];
}
}
module.exports = BaseDirectorService; | sauravmndl/service-fabrik-broker | operators/BaseDirectorService.js | JavaScript | apache-2.0 | 2,696 |
(function () {
/* Imports */
var Meteor = Package.meteor.Meteor;
var _ = Package.underscore._;
var Iron = Package['iron:core'].Iron;
/* Package-scope variables */
var compilePath, Url;
(function () {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/iron:url/lib/compiler.js //
// //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
/* // 1
From https://github.com/pillarjs/path-to-regexp // 2
// 3
The MIT License (MIT) // 4
// 5
Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com) // 6
// 7
Permission is hereby granted, free of charge, to any person obtaining a copy // 8
of this software and associated documentation files (the "Software"), to deal // 9
in the Software without restriction, including without limitation the rights // 10
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // 11
copies of the Software, and to permit persons to whom the Software is // 12
furnished to do so, subject to the following conditions: // 13
// 14
The above copyright notice and this permission notice shall be included in // 15
all copies or substantial portions of the Software. // 16
// 17
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // 18
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // 19
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // 20
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // 21
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // 22
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // 23
THE SOFTWARE. // 24
*/ // 25
// 26
/** // 27
* The main path matching regexp utility. // 28
* // 29
* @type {RegExp} // 30
*/ // 31
var PATH_REGEXP = new RegExp([ // 32
// Match already escaped characters that would otherwise incorrectly appear // 33
// in future matches. This allows the user to escape special characters that // 34
// shouldn't be transformed. // 35
'(\\\\.)', // 36
// Match Express-style parameters and un-named parameters with a prefix // 37
// and optional suffixes. Matches appear as: // 38
// // 39
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?"] // 40
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined] // 41
'([\\/.])?(?:\\:(\\w+)(?:\\(((?:\\\\.|[^)])*)\\))?|\\(((?:\\\\.|[^)])*)\\))([+*?])?', // 42
// Match regexp special characters that should always be escaped. // 43
'([.+*?=^!:${}()[\\]|\\/])' // 44
].join('|'), 'g'); // 45
// 46
/** // 47
* Escape the capturing group by escaping special characters and meaning. // 48
* // 49
* @param {String} group // 50
* @return {String} // 51
*/ // 52
function escapeGroup (group) { // 53
return group.replace(/([=!:$\/()])/g, '\\$1'); // 54
} // 55
// 56
/** // 57
* Attach the keys as a property of the regexp. // 58
* // 59
* @param {RegExp} re // 60
* @param {Array} keys // 61
* @return {RegExp} // 62
*/ // 63
var attachKeys = function (re, keys) { // 64
re.keys = keys; // 65
// 66
return re; // 67
}; // 68
// 69
/** // 70
* Normalize the given path string, returning a regular expression. // 71
* // 72
* An empty array should be passed in, which will contain the placeholder key // 73
* names. For example `/user/:id` will then contain `["id"]`. // 74
* // 75
* @param {(String|RegExp|Array)} path // 76
* @param {Array} keys // 77
* @param {Object} options // 78
* @return {RegExp} // 79
*/ // 80
function pathtoRegexp (path, keys, options) { // 81
if (keys && !Array.isArray(keys)) { // 82
options = keys; // 83
keys = null; // 84
} // 85
// 86
keys = keys || []; // 87
options = options || {}; // 88
// 89
var strict = options.strict; // 90
var end = options.end !== false; // 91
var flags = options.sensitive ? '' : 'i'; // 92
var index = 0; // 93
// 94
if (path instanceof RegExp) { // 95
// Match all capturing groups of a regexp. // 96
var groups = path.source.match(/\((?!\?)/g) || []; // 97
// 98
// Map all the matches to their numeric keys and push into the keys. // 99
keys.push.apply(keys, groups.map(function (match, index) { // 100
return { // 101
name: index, // 102
delimiter: null, // 103
optional: false, // 104
repeat: false // 105
}; // 106
})); // 107
// 108
// Return the source back to the user. // 109
return attachKeys(path, keys); // 110
} // 111
// 112
if (Array.isArray(path)) { // 113
// Map array parts into regexps and return their source. We also pass // 114
// the same keys and options instance into every generation to get // 115
// consistent matching groups before we join the sources together. // 116
path = path.map(function (value) { // 117
return pathtoRegexp(value, keys, options).source; // 118
}); // 119
// 120
// Generate a new regexp instance by joining all the parts together. // 121
return attachKeys(new RegExp('(?:' + path.join('|') + ')', flags), keys); // 122
} // 123
// 124
// Alter the path string into a usable regexp. // 125
path = path.replace(PATH_REGEXP, function (match, escaped, prefix, key, capture, group, suffix, escape) { // 126
// Avoiding re-escaping escaped characters. // 127
if (escaped) { // 128
return escaped; // 129
} // 130
// 131
// Escape regexp special characters. // 132
if (escape) { // 133
return '\\' + escape; // 134
} // 135
// 136
var repeat = suffix === '+' || suffix === '*'; // 137
var optional = suffix === '?' || suffix === '*'; // 138
// 139
keys.push({ // 140
name: key || index++, // 141
delimiter: prefix || '/', // 142
optional: optional, // 143
repeat: repeat // 144
}); // 145
// 146
// Escape the prefix character. // 147
prefix = prefix ? '\\' + prefix : ''; // 148
// 149
// Match using the custom capturing group, or fallback to capturing // 150
// everything up to the next slash (or next period if the param was // 151
// prefixed with a period). // 152
capture = escapeGroup(capture || group || '[^' + (prefix || '\\/') + ']+?'); // 153
// 154
// Allow parameters to be repeated more than once. // 155
if (repeat) { // 156
capture = capture + '(?:' + prefix + capture + ')*'; // 157
} // 158
// 159
// Allow a parameter to be optional. // 160
if (optional) { // 161
return '(?:' + prefix + '(' + capture + '))?'; // 162
} // 163
// 164
// Basic parameter support. // 165
return prefix + '(' + capture + ')'; // 166
}); // 167
// 168
// Check whether the path ends in a slash as it alters some match behaviour. // 169
var endsWithSlash = path[path.length - 1] === '/'; // 170
// 171
// In non-strict mode we allow an optional trailing slash in the match. If // 172
// the path to match already ended with a slash, we need to remove it for // 173
// consistency. The slash is only valid at the very end of a path match, not // 174
// anywhere in the middle. This is important for non-ending mode, otherwise // 175
// "/test/" will match "/test//route". // 176
if (!strict) { // 177
path = (endsWithSlash ? path.slice(0, -2) : path) + '(?:\\/(?=$))?'; // 178
} // 179
// 180
// In non-ending mode, we need prompt the capturing groups to match as much // 181
// as possible by using a positive lookahead for the end or next path segment. // 182
if (!end) { // 183
path += strict && endsWithSlash ? '' : '(?=\\/|$)'; // 184
} // 185
// 186
return attachKeys(new RegExp('^' + path + (end ? '$' : ''), flags), keys); // 187
}; // 188
// 189
compilePath = pathtoRegexp; // 190
// 191
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
}).call(this);
(function () {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// packages/iron:url/lib/url.js //
// //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
/*****************************************************************************/ // 1
/* Url */ // 2
/*****************************************************************************/ // 3
/** // 4
* Url utilities and the ability to compile a url into a regular expression. // 5
*/ // 6
Url = function (url, options) { // 7
options = options || {}; // 8
this.options = options; // 9
this.keys = []; // 10
this.regexp = compilePath(url, this.keys, options); // 11
this._originalPath = url; // 12
_.extend(this, Url.parse(url)); // 13
}; // 14
// 15
/** // 16
* Given a relative or absolute path return // 17
* a relative path with a leading forward slash and // 18
* no search string or hash fragment // 19
* // 20
* @param {String} path // 21
* @return {String} // 22
*/ // 23
Url.normalize = function (url) { // 24
if (url instanceof RegExp) // 25
return url; // 26
else if (typeof url !== 'string') // 27
return '/'; // 28
// 29
var parts = Url.parse(url); // 30
var pathname = parts.pathname; // 31
// 32
if (pathname.charAt(0) !== '/') // 33
pathname = '/' + pathname; // 34
// 35
if (pathname.length > 1 && pathname.charAt(pathname.length - 1) === '/') { // 36
pathname = pathname.slice(0, pathname.length - 1); // 37
} // 38
// 39
return pathname; // 40
}; // 41
// 42
/** // 43
* Returns true if both a and b are of the same origin. // 44
*/ // 45
Url.isSameOrigin = function (a, b) { // 46
var aParts = Url.parse(a); // 47
var bParts = Url.parse(b); // 48
var result = aParts.origin === bParts.origin; // 49
return result; // 50
}; // 51
// 52
/** // 53
* Given a query string return an object of key value pairs. // 54
* // 55
* "?p1=value1&p2=value2 => {p1: value1, p2: value2} // 56
*/ // 57
Url.fromQueryString = function (query) { // 58
if (!query) // 59
return {}; // 60
// 61
if (typeof query !== 'string') // 62
throw new Error("expected string"); // 63
// 64
// get rid of the leading question mark // 65
if (query.charAt(0) === '?') // 66
query = query.slice(1); // 67
// 68
var keyValuePairs = query.split('&'); // 69
var result = {}; // 70
var parts; // 71
// 72
_.each(keyValuePairs, function (pair) { // 73
var parts = pair.split('='); // 74
var key = parts[0]; // 75
var value = decodeURIComponent(parts[1]); // 76
// 77
if (key.slice(-2) === '[]') { // 78
key = key.slice(0, -2); // 79
result[key] = result[key] || []; // 80
result[key].push(value); // 81
} else { // 82
result[key] = value; // 83
} // 84
}); // 85
// 86
return result; // 87
}; // 88
// 89
/** // 90
* Given a query object return a query string. // 91
*/ // 92
Url.toQueryString = function (queryObject) { // 93
var result = []; // 94
// 95
if (typeof queryObject === 'string') { // 96
if (queryObject.charAt(0) !== '?') // 97
return '?' + queryObject; // 98
else // 99
return queryObject; // 100
} // 101
// 102
_.each(queryObject, function (value, key) { // 103
if (_.isArray(value)) { // 104
_.each(value, function(valuePart) { // 105
result.push(encodeURIComponent(key + '[]') + '=' + encodeURIComponent(valuePart)); // 106
}); // 107
} else { // 108
result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value)); // 109
} // 110
}); // 111
// 112
// no sense in adding a pointless question mark // 113
if (result.length > 0) // 114
return '?' + result.join('&'); // 115
else // 116
return ''; // 117
}; // 118
// 119
/** // 120
* Given a string url return an object with all of the url parts. // 121
*/ // 122
Url.parse = function (url) { // 123
if (typeof url !== 'string') // 124
return {}; // 125
// 126
//http://tools.ietf.org/html/rfc3986#page-50 // 127
//http://www.rfc-editor.org/errata_search.php?rfc=3986 // 128
var re = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/; // 129
// 130
var match = url.match(re); // 131
// 132
var protocol = match[1] ? match[1].toLowerCase() : undefined; // 133
var hostWithSlashes = match[3]; // 134
var slashes = !!hostWithSlashes; // 135
var hostWithAuth= match[4] ? match[4].toLowerCase() : undefined; // 136
var hostWithAuthParts = hostWithAuth ? hostWithAuth.split('@') : []; // 137
// 138
var host, auth; // 139
// 140
if (hostWithAuthParts.length == 2) { // 141
auth = hostWithAuthParts[0]; // 142
host = hostWithAuthParts[1]; // 143
} else if (hostWithAuthParts.length == 1) { // 144
host = hostWithAuthParts[0]; // 145
auth = undefined; // 146
} else { // 147
host = undefined; // 148
auth = undefined; // 149
} // 150
// 151
var hostWithPortParts = (host && host.split(':')) || []; // 152
var hostname = hostWithPortParts[0]; // 153
var port = hostWithPortParts[1]; // 154
var origin = (protocol && host) ? protocol + '//' + host : undefined; // 155
var pathname = match[5]; // 156
var hash = match[8]; // 157
var originalUrl = url; // 158
// 159
var search = match[6]; // 160
// 161
var query; // 162
var indexOfSearch = (hash && hash.indexOf('?')) || -1; // 163
// 164
// if we found a search string in the hash and there is no explicit search // 165
// string // 166
if (~indexOfSearch && !search) { // 167
search = hash.slice(indexOfSearch); // 168
hash = hash.substr(0, indexOfSearch); // 169
// get rid of the ? character // 170
query = search.slice(1); // 171
} else { // 172
query = match[7]; // 173
} // 174
// 175
var path = pathname + (search || ''); // 176
var queryObject = Url.fromQueryString(query); // 177
// 178
var rootUrl = [ // 179
protocol || '', // 180
slashes ? '//' : '', // 181
hostWithAuth || '' // 182
].join(''); // 183
// 184
var href = [ // 185
protocol || '', // 186
slashes ? '//' : '', // 187
hostWithAuth || '', // 188
pathname || '', // 189
search || '', // 190
hash || '' // 191
].join(''); // 192
// 193
return { // 194
rootUrl: rootUrl || '', // 195
originalUrl: url || '', // 196
href: href || '', // 197
protocol: protocol || '', // 198
auth: auth || '', // 199
host: host || '', // 200
hostname: hostname || '', // 201
port: port || '', // 202
origin: origin || '', // 203
path: path || '', // 204
pathname: pathname || '', // 205
search: search || '', // 206
query: query || '', // 207
queryObject: queryObject || '', // 208
hash: hash || '', // 209
slashes: slashes // 210
}; // 211
}; // 212
// 213
/** // 214
* Returns true if the path matches and false otherwise. // 215
*/ // 216
Url.prototype.test = function (path) { // 217
return this.regexp.test(Url.normalize(path)); // 218
}; // 219
// 220
/** // 221
* Returns the result of calling exec on the compiled path with // 222
* the given path. // 223
*/ // 224
Url.prototype.exec = function (path) { // 225
return this.regexp.exec(Url.normalize(path)); // 226
}; // 227
// 228
/** // 229
* Returns an array of parameters given a path. The array may have named // 230
* properties in addition to indexed values. // 231
*/ // 232
Url.prototype.params = function (path) { // 233
if (!path) // 234
return []; // 235
// 236
var params = []; // 237
var m = this.exec(path); // 238
var queryString; // 239
var keys = this.keys; // 240
var key; // 241
var value; // 242
// 243
if (!m) // 244
throw new Error('The route named "' + this.name + '" does not match the path "' + path + '"'); // 245
// 246
for (var i = 1, len = m.length; i < len; ++i) { // 247
key = keys[i - 1]; // 248
value = typeof m[i] == 'string' ? decodeURIComponent(m[i]) : m[i]; // 249
if (key) { // 250
params[key.name] = params[key.name] !== undefined ? // 251
params[key.name] : value; // 252
} else // 253
params.push(value); // 254
} // 255
// 256
path = decodeURI(path); // 257
// 258
queryString = path.split('?')[1]; // 259
if (queryString) // 260
queryString = queryString.split('#')[0]; // 261
// 262
params.hash = path.split('#')[1] || null; // 263
params.query = Url.fromQueryString(queryString); // 264
// 265
return params; // 266
}; // 267
// 268
Url.prototype.resolve = function (params, options) { // 269
var value; // 270
var isValueDefined; // 271
var result; // 272
var wildCardCount = 0; // 273
var path = this._originalPath; // 274
var hash; // 275
var query; // 276
var missingParams = []; // 277
var originalParams = params; // 278
// 279
options = options || {}; // 280
params = params || []; // 281
query = options.query; // 282
hash = options.hash && options.hash.toString(); // 283
// 284
if (path instanceof RegExp) { // 285
throw new Error('Cannot currently resolve a regular expression path'); // 286
} else { // 287
path = path // 288
.replace( // 289
/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?/g, // 290
function (match, slash, format, key, capture, optional, offset) { // 291
slash = slash || ''; // 292
value = params[key]; // 293
isValueDefined = typeof value !== 'undefined'; // 294
// 295
if (optional && !isValueDefined) { // 296
value = ''; // 297
} else if (!isValueDefined) { // 298
missingParams.push(key); // 299
return; // 300
} // 301
// 302
value = _.isFunction(value) ? value.call(params) : value; // 303
var escapedValue = _.map(String(value).split('/'), function (segment) { // 304
return encodeURIComponent(segment); // 305
}).join('/'); // 306
return slash + escapedValue // 307
} // 308
) // 309
.replace( // 310
/\*/g, // 311
function (match) { // 312
if (typeof params[wildCardCount] === 'undefined') { // 313
throw new Error( // 314
'You are trying to access a wild card parameter at index ' + // 315
wildCardCount + // 316
' but the value of params at that index is undefined'); // 317
} // 318
// 319
var paramValue = String(params[wildCardCount++]); // 320
return _.map(paramValue.split('/'), function (segment) { // 321
return encodeURIComponent(segment); // 322
}).join('/'); // 323
} // 324
); // 325
// 326
query = Url.toQueryString(query); // 327
// 328
path = path + query; // 329
// 330
if (hash) { // 331
hash = encodeURI(hash.replace('#', '')); // 332
path = query ? // 333
path + '#' + hash : path + '/#' + hash; // 334
} // 335
} // 336
// 337
// Because of optional possibly empty segments we normalize path here // 338
path = path.replace(/\/+/g, '/'); // Multiple / -> one / // 339
path = path.replace(/^(.+)\/$/g, '$1'); // Removal of trailing / // 340
// 341
if (missingParams.length == 0) // 342
return path; // 343
else if (options.throwOnMissingParams === true) // 344
throw new Error("Missing required parameters on path " + JSON.stringify(this._originalPath) + ". The missing params are: " + JSON.stringify(missingParams) + ". The params object passed in was: " + JSON.stringify(originalParams) + ".");
else // 346
return null; // 347
}; // 348
// 349
/*****************************************************************************/ // 350
/* Namespacing */ // 351
/*****************************************************************************/ // 352
Iron.Url = Url; // 353
// 354
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
}).call(this);
/* Exports */
if (typeof Package === 'undefined') Package = {};
Package['iron:url'] = {};
})();
//# sourceMappingURL=iron_url.js.map
| durwasa-chakraborty/navigus | .demeteorized/bundle/programs/server/packages/iron_url.js | JavaScript | apache-2.0 | 64,533 |
/** @name dimensions */
var width = 12 | rodrigoramos/shaka-player | third_party/jsdoc/test/fixtures/virtual.js | JavaScript | apache-2.0 | 41 |
/**
* 首页
*/
pageData = window.pageData?window.pageData:[];
var vm = avalon.define({
$id : "sidebar",
test: "tst",
//domainBuyList1 : [{title:"test"},{title:"test2"}],
//domainSoldList1 : [{title:"test"},{title:"test2"}],//买标信息一览(最新11条,首页只表示最新的)
datas : {
domainArticleList : [],//sidebar信息一览(最新5条)12.31
timeStamp: 0,
tmp : {
currentClientId : null,
newDate : new Date()
},
userinfo : {
id : ""
}
},
});
// 初始化动作
$(function(){
avalon.scan();
//TODO
});
//sidebar信息一览(最新5条)12.31
var interval_GbjArticle_status_check = function() {
//var v = window.location.href.split("?")[1].substring(3,35);
//alert(u);
var count = 5;//首页最多显示11条
//var id= v;
$.post(
"polling/GbjArticle.json",
{
count : count //参数1,检索的limit条数
// id:id
},
function(res) {
if (res.type == "success") {
//vm.datas.domainArticleList.clear();
vm.datas.domainArticleList.pushArray(res.data.GbjArticle);
timeout_GbjArticle = setTimeout(interval_GbjArticle_status_check, 30000); //30秒自动刷新一次
}
}
);
}
interval_GbjArticle_status_check();
| GSSBuse/GSSB | src/main/webapp/static/front/js/sidebar.js | JavaScript | apache-2.0 | 1,321 |
/*global jQuery */
/*jshint browser:true */
/*!
* FitVids 1.1
*
* Copyright 2013, Chris Coyier - https://css-tricks.com + Dave Rupert - https://daverupert.com
* Credit to Thierry Koblentz - https://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
* Released under the WTFPL license - https://sam.zoy.org/wtfpl/
*
*/
(function($) {
"use strict";
$.fn.fitVids = function(options) {
var settings = {
customSelector: null,
ignore: null
};
if (!document.getElementById('fit-vids-style')) {
// appendStyles: https://github.com/toddmotto/fluidvids/blob/master/dist/fluidvids.js
var head = document.head || document.getElementsByTagName('head')[0];
var css = '.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}';
var div = document.createElement('div');
div.innerHTML = '<p>x</p><style id="fit-vids-style">' + css + '</style>';
head.appendChild(div.childNodes[1]);
}
if (options) {
$.extend(settings, options);
}
return this.each(function() {
var selectors = [
"iframe[src*='player.vimeo.com']",
"iframe[src*='youtube.com']",
"iframe[src*='youtube-nocookie.com']",
"iframe[src*='kickstarter.com'][src*='video.html']",
"object",
"embed"
];
if (settings.customSelector) {
selectors.push(settings.customSelector);
}
var ignoreList = '.fitvidsignore';
if (settings.ignore) {
ignoreList = ignoreList + ', ' + settings.ignore;
}
var $allVideos = $(this).find(selectors.join(','));
$allVideos = $allVideos.not("object object"); // SwfObj conflict patch
$allVideos = $allVideos.not(ignoreList); // Disable FitVids on this video.
$allVideos.each(function() {
var $this = $(this);
if ($this.parents(ignoreList).length > 0) {
return; // Disable FitVids on this video.
}
if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) {
return;
}
if ((!$this.css('height') && !$this.css('width')) && (isNaN($this.attr('height')) || isNaN($this.attr('width')))) {
$this.attr('height', 9);
$this.attr('width', 16);
}
var height = (this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10)))) ? parseInt($this.attr('height'), 10) : $this.height(),
width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
aspectRatio = height / width;
if (!$this.attr('id')) {
var videoID = 'fitvid' + Math.floor(Math.random() * 999999);
$this.attr('id', videoID);
}
$this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100) + "%");
$this.removeAttr('height').removeAttr('width');
});
});
};
// Works with either jQuery or Zepto
})(window.jQuery || window.Zepto); | kinasmith/kinasmith.com | js/jquery.fitvids.js | JavaScript | apache-2.0 | 3,685 |
/**
* Escapes a string for SQL insertion
*/
exports.escapeString = function(_string) {
if(typeof _string !== "string") {
return "\"" + _string + "\"";
}
return "\"" + _string.replace(/"/g, "'") + "\"";
};
/**
* Removes HTML entities, replaces breaks/paragraphs with newline, strips HTML, trims
*/
exports.cleanString = function(_string) {
if(typeof _string !== "string") {
return _string;
}
_string = _string.replace(/&*/ig, "&");
_string = exports.htmlDecode(_string);
_string = _string.replace(/\s*<br[^>]*>\s*/ig, "\n");
_string = _string.replace(/\s*<\/p>*\s*/ig, "\n\n");
_string = _string.replace(/<[^>]*>/g, "");
_string = _string.replace(/\s*\n{3,}\s*/g, "\n\n");
_string = _string.replace(/[^\S\n]{2,}/g, " ");
_string = _string.replace(/\n[^\S\n]*/g, "\n");
_string = _string.replace(/^\s+|\s+$/g, "");
return _string;
};
/**
* Combination of clean and escape string
*/
exports.cleanEscapeString = function(_string) {
_string = exports.cleanString(_string);
return exports.escapeString(_string);
};
/**
* Cleans up nasty XML
*/
exports.xmlNormalize = function(_string) {
_string = _string.replace(/ */ig, " ");
_string = _string.replace(/&(?!amp;)\s*/g, "&");
_string = _string.replace(/^\s+|\s+$/g, "");
_string = _string.replace(/<title>(?!<!\[CDATA\[)/ig, "<title><![CDATA[");
_string = _string.replace(/<description>(?!<!\[CDATA\[)/ig, "<description><![CDATA[");
_string = _string.replace(/(\]\]>)?<\/title>/ig, "]]></title>");
_string = _string.replace(/(\]\]>)?<\/description>/ig, "]]></description>");
return _string;
};
/**
* Decodes HTML entities
*/
exports.htmlDecode = function(_string) {
var tmp_str = _string.toString();
var hash_map = exports.htmlTranslationTable();
var results = tmp_str.match(/&#\d*;/ig);
if(results) {
for(var i = 0, x = results.length; i < x; i++) {
var code = parseInt(results[i].replace("&#", "").replace(";", ""), 10);
hash_map[results[i]] = code;
}
}
for(var entity in hash_map) {
var symbol = String.fromCharCode(hash_map[entity]);
tmp_str = tmp_str.split(entity).join(symbol);
}
return tmp_str;
};
exports.htmlTranslationTable = function() {
var entities = {
"–": "8211",
"—": "8212",
"‘": "8216",
"’": "8217",
"&": "38",
"„": "8222",
"•": "8226",
"ˆ": "710",
"†": "8224",
"‡": "8225",
"ƒ": "402",
"…": "8230",
"“": "8220",
"‹": "8249",
"‘": "8216",
"—": "8212",
"–": "8211",
"Œ": "338",
"œ": "339",
"‰": "8240",
"”": "8221",
"›": "8250",
"’": "8217",
"‚": "8218",
"š": "353",
"Š": "352",
"˜": "152",
"™": "8482",
"Ÿ": "376",
"Ì": "204",
"ì": "236",
"Ι": "921",
"ι": "953",
"Ï": "207",
"ï": "239",
"←": "8592",
"⇐": "8656",
"Á": "193",
"á": "225",
"Â": "194",
"â": "226",
"´": "180",
"Æ": "198",
"æ": "230",
"À": "192",
"à": "224",
"ℵ": "8501",
"Α": "913",
"α": "945",
"∧": "8743",
"∠": "8736",
"Å": "197",
"å": "229",
"≈": "8776",
"Ã": "195",
"ã": "227",
"Ä": "196",
"ä": "228",
"Β": "914",
"β": "946",
"¦": "166",
"∩": "8745",
"Ç": "199",
"ç": "231",
"¸": "184",
"¢": "162",
"Χ": "935",
"χ": "967",
"♣": "9827",
"≅": "8773",
"©": "169",
"↵": "8629",
"∪": "8746",
"¤": "164",
"↓": "8595",
"⇓": "8659",
"°": "176",
"Δ": "916",
"δ": "948",
"♦": "9830",
"÷": "247",
"É": "201",
"é": "233",
"Ê": "202",
"ê": "234",
"È": "200",
"è": "232",
"∅": "8709",
" ": "8195",
" ": "8194",
"Ε": "917",
"ε": "949",
"≡": "8801",
"Η": "919",
"η": "951",
"Ð": "208",
"ð": "240",
"Ë": "203",
"ë": "235",
"€": "8364",
"∃": "8707",
"∀": "8704",
"½": "189",
"¼": "188",
"¾": "190",
"⁄": "8260",
"Γ": "915",
"γ": "947",
"≥": "8805",
"↔": "8596",
"⇔": "8660",
"♥": "9829",
"Í": "205",
"í": "237",
"Î": "206",
"î": "238",
"¡": "161",
"ℑ": "8465",
"∞": "8734",
"∫": "8747",
"¿": "191",
"∈": "8712",
"Κ": "922",
"κ": "954",
"Λ": "923",
"λ": "955",
"⟨": "9001",
"«": "171",
"⌈": "8968",
"≤": "8804",
"⌊": "8970",
"∗": "8727",
"◊": "9674",
"‎": "8206",
"¯": "175",
"µ": "181",
"·": "183",
"−": "8722",
"Μ": "924",
"μ": "956",
"∇": "8711",
" ": "160",
"≠": "8800",
"∋": "8715",
"¬": "172",
"∉": "8713",
"⊄": "8836",
"Ñ": "209",
"ñ": "241",
"Ν": "925",
"ν": "957",
"Ó": "211",
"ó": "243",
"Ô": "212",
"ô": "244",
"Ò": "210",
"ò": "242",
"‾": "8254",
"Ω": "937",
"ω": "969",
"Ο": "927",
"ο": "959",
"⊕": "8853",
"∨": "8744",
"ª": "170",
"º": "186",
"Ø": "216",
"ø": "248",
"Õ": "213",
"õ": "245",
"⊗": "8855",
"Ö": "214",
"ö": "246",
"¶": "182",
"∂": "8706",
"⊥": "8869",
"Φ": "934",
"φ": "966",
"Π": "928",
"π": "960",
"ϖ": "982",
"±": "177",
"£": "163",
"′": "8242",
"″": "8243",
"∏": "8719",
"∝": "8733",
"Ψ": "936",
"ψ": "968",
"√": "8730",
"⟩": "9002",
"»": "187",
"→": "8594",
"⇒": "8658",
"⌉": "8969",
"ℜ": "8476",
"®": "174",
"⌋": "8971",
"Ρ": "929",
"ρ": "961",
"‏": "8207",
"⋅": "8901",
"§": "167",
"­": "173",
"Σ": "931",
"σ": "963",
"ς": "962",
"∼": "8764",
"♠": "9824",
"⊂": "8834",
"⊆": "8838",
"∑": "8721",
"⊃": "8835",
"¹": "185",
"²": "178",
"³": "179",
"⊇": "8839",
"ß": "223",
"Τ": "932",
"τ": "964",
"∴": "8756",
"Θ": "920",
"θ": "952",
"ϑ": "977",
" ": "8201",
"Þ": "222",
"þ": "254",
"˜": "732",
"×": "215",
"Ú": "218",
"ú": "250",
"↑": "8593",
"⇑": "8657",
"Û": "219",
"û": "251",
"Ù": "217",
"ù": "249",
"¨": "168",
"ϒ": "978",
"Υ": "933",
"υ": "965",
"Ü": "220",
"ü": "252",
"℘": "8472",
"
": "10",
"
": "13",
"Ξ": "926",
"ξ": "958",
"Ý": "221",
"ý": "253",
"¥": "165",
"ÿ": "255",
"Ζ": "918",
"ζ": "950",
"‍": "8205",
"‌": "8204",
""": "34",
"<": "60",
">": "62"
};
return entities;
};
/**
* Adds thousands separators to a number
*/
exports.formatNumber = function(_number) {
_number = _number + "";
x = _number.split(".");
x1 = x[0];
x2 = x.length > 1 ? "." + x[1] : "";
var expression = /(\d+)(\d{3})/;
while (expression.test(x1)) {
x1 = x1.replace(expression, "$1" + "," + "$2");
}
return x1 + x2;
};
/**
* Converts a date to absolute time (e.g. "May 2, 2011 12:00PM")
*/
exports.toDateAbsolute = function(_date) {
var date = new Date();
date.setTime(_date);
var dateHour = date.getHours() > 11 ? date.getHours() - 12 : date.getHours();
dateHour = dateHour == 0 ? 12 : dateHour;
var dateMinutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var datePeriod = date.getHours() > 12 ? "PM" : "AM";
var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
return months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear() + " " + dateHour + ":" + dateMinutes + datePeriod;
};
/**
* Converts a date to relative time (e.g. "Yesterday 12:01PM")
*/
exports.toDateRelative = function(_date) {
var date = new Date();
date.setTime(_date);
var now = new Date();
var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
var dateMonth = date.getMonth();
var dateDate = date.getDate();
var dateDay = days[date.getDay()];
var dateYear = date.getFullYear();
var dateHour = date.getHours() > 11 ? date.getHours() - 12 : date.getHours();
dateHour = dateHour == 0 ? 12 : dateHour;
var dateMinutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var datePeriod = date.getHours() > 12 ? "PM" : "AM";
var nowMonth = now.getMonth();
var nowDate = now.getDate();
var nowYear = now.getFullYear();
if(dateYear == nowYear && dateMonth == nowMonth) {
if(dateDate == nowDate) {
return "Today " + dateHour + ":" + dateMinutes + datePeriod;
} else if(dateDate >= nowDate - 1) {
return "Yesterday " + dateHour + ":" + dateMinutes + datePeriod;
} else if(dateDate >= nowDate - 6) {
return dateDay + " " + dateHour + ":" + dateMinutes + datePeriod;
} else {
return exports.toDateAbsolute(_date);
}
} else {
return exports.toDateAbsolute(_date);
}
};
/**
* Universal error callback function
*
*/
exports.onErrorCallback = function(e) {
Ti.API.info('error: '+e.data.error);
Ti.UI.createAlertDialog({
message: "Can't load data. Check network connection? Error message: "+e.error,
ok: 'OK',
title: 'Error'
}).show();
}
/*
* Attempt to extract 1st image URL, height, width properties from an HTML string
*
*/
exports.parseImageProperties = function(html){
// extract imageURL
var imageURL = exports.htmlDecode(html).match(/src=(.+?")/)[1] || '';
if (imageURL) {
imageURL = imageURL.replace(/\"/g,"");
var width = exports.htmlDecode(html).match(/width=(.+?")/)[1] || '';
width = width.replace(/\"/g, "") || '';
var height = exports.htmlDecode(html).match(/height=(.+?")/)[1] || '';
height = height.replace(/\"/g, "") || '';
//Ti.API.info('image url:' + imageURL);
//Ti.API.info('thumb: '+"http://events.jftc.nato.int/sites/default/files/imagecache/thumbnail/"+parseImageName(imageURL))
return {
"url": imageURL,
"width": width,
"height": height,
// "thumbnail":"http://events.jftc.nato.int/sites/default/files/imagecache/thumbnail/"+parseImageName(imageURL),
};
}
else {
return false;
}
}
/**
* Strip HTML tags
* Note: regex is not prefered method, I know.
*/
exports.stripTags = function(str, allowed_tags) {
// http://kevin.vanzonneveld.net
// + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Luke Godfrey
// + input by: Pul
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + input by: Alex
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Marc Palau
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Eric Nagel
// + input by: Bobby Drake
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Tomasz Wesolowski
// fixed Titanium warning by: Kosso
// * example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
// * returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
// * example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
// * returns 2: '<p>Kevin van Zonneveld</p>'
// * example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
// * returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
// * example 4: strip_tags('1 < 5 5 > 1');
// * returns 4: '1 < 5 5 > 1'
var key = '', allowed = false;
var matches = [];
var allowed_array = [];
var allowed_tag = '';
var i = 0;
var k = '';
var html = '';
var replacer = function (search, replace, str) {
return str.split(search).join(replace);
};
// Build allowes tags associative array
if (allowed_tags) {
allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
}
str += '';
// Match tags
matches = str.match(/(<\/?[\S][^>]*>)/gi);
// Go through all HTML tags
for (key in matches) {
if(key){
// Save HTML tag
html = matches[key].toString();
// Is tag not in allowed list? Remove from str!
allowed = false;
// Go through all allowed tags
for (k in allowed_array) {
if(k){
// Init
allowed_tag = allowed_array[k];
i = -1;
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag) ;}
// Determine
if (i == 0) {
allowed = true;
break;
}
}
}
if (!allowed) {
str = replacer(html, "", str); // Custom replace. No regexing
}
}
}
return str;
}
/**
* Just a helper app to fire up /lib/MiniBrowser...
*/
exports.miniBrowser = function(e){
//console.info(JSON.stringify(e));
var TiMiniBrowser = require("MiniBrowser/TiMiniBrowser");
var browser = new TiMiniBrowser({
url: e.link,
barColor: "#178cce"
});
browser.open();
}
| bob-sims/quickJFTC | app/lib/utilities.js | JavaScript | apache-2.0 | 14,150 |
/**
* Copyright 2016, Optimizely
*
* 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.
*/
var bluebird = require('bluebird');
var chai = require('chai');
var assert = chai.assert;
var math = require('mathjs');
var Optimizely = require('../index');
module.exports = {
/**
* Instantiates the optimizely object with JSON schema validation and returns the time it took
* @param {Object} datafile
* @return {Number} ms to instantiate
*/
measureInstantiation: function(datafile) {
var start = module.exports.getTimestamp();
var optlyInstance = Optimizely.createInstance({
datafile: datafile,
eventDispatcher: {dispatchEvent: function() { return bluebird.resolve(null); }},
});
var end = module.exports.getTimestamp();
var time = end - start;
assert.isNotNull(optlyInstance);
return time;
},
/**
* Instantiates the optimizely object with logger and returns the time it took
* @param {Object} datafile
* @return {Number} ms to instantiate
*/
measureInstantiationWithLogger: function(datafile) {
var start = module.exports.getTimestamp();
var optlyInstance = Optimizely.createInstance({
datafile: datafile,
eventDispatcher: {dispatchEvent: function() { return bluebird.resolve(null); }},
logger: {log: function() {}},
});
var end = module.exports.getTimestamp();
var time = end - start;
assert.isNotNull(optlyInstance);
return time;
},
/**
* Instantiates the optimizely object with error handler and returns the time it took
* @param {Object} datafile
* @return {Number} ms to instantiate
*/
measureInstantiationWithErrorHandler: function(datafile) {
var start = module.exports.getTimestamp();
var optlyInstance = Optimizely.createInstance({
datafile: datafile,
eventDispatcher: {dispatchEvent: function() { return bluebird.resolve(null); }},
errorHandler: {handleError: function() {}},
});
var end = module.exports.getTimestamp();
var time = end - start;
assert.isNotNull(optlyInstance);
return time;
},
/**
* Instantiates the optimizely object with logger & error handler and returns the time it took
* @param {Object} datafile
* @return {Number} ms to instantiate
*/
measureInstantiationWithLoggerAndErrorHandler: function(datafile) {
var start = module.exports.getTimestamp();
var optlyInstance = Optimizely.createInstance({
datafile: datafile,
eventDispatcher: {dispatchEvent: function() { return bluebird.resolve(null); }},
logger: {log: function() {}},
errorHandler: {handleError: function() {}},
});
var end = module.exports.getTimestamp();
var time = end - start;
assert.isNotNull(optlyInstance);
return time;
},
/**
* Instantiates the optimizely object without JSON schema validation and returns the time it took
* @param {Object} datafile
* @return {Number} ms to instantiate
*/
measureInstantiationWithoutJSONValidation: function(datafile) {
var start = module.exports.getTimestamp();
var optlyInstance = Optimizely.createInstance({
datafile: datafile,
skipJSONValidation: true,
eventDispatcher: {dispatchEvent: function() { return bluebird.resolve(null); }},
});
var end = module.exports.getTimestamp();
var time = end - start;
assert.isNotNull(optlyInstance);
return time;
},
/**
* Instantiates the optimizely object without JSON schema validation & with logger and returns the time it took
* @param {Object} datafile
* @return {Number} ms to instantiate
*/
measureInstantiationWithoutJSONValidationAndWithLogger: function(datafile) {
var start = module.exports.getTimestamp();
var optlyInstance = Optimizely.createInstance({
datafile: datafile,
skipJSONValidation: true,
eventDispatcher: {dispatchEvent: function() { return bluebird.resolve(null); }},
logger: {log: function() {}},
});
var end = module.exports.getTimestamp();
var time = end - start;
assert.isNotNull(optlyInstance);
return time;
},
/**
* Instantiates the optimizely object without JSON schema validation & with error handler and returns the time it took
* @param {Object} datafile
* @return {Number} ms to instantiate
*/
measureInstantiationWithoutJSONValidationAndWithErrorHandler: function(datafile) {
var start = module.exports.getTimestamp();
var optlyInstance = Optimizely.createInstance({
datafile: datafile,
skipJSONValidation: true,
eventDispatcher: {dispatchEvent: function() { return bluebird.resolve(null); }},
errorHandler: {handleError: function() {}},
});
var end = module.exports.getTimestamp();
var time = end - start;
assert.isNotNull(optlyInstance);
return time;
},
/**
* Instantiates the optimizely object without JSON schema validation & with logger & error handler and returns the time it took
* @param {Object} datafile
* @return {Number} ms to instantiate
*/
measureInstantiationWithoutJSONValidationAndWithLoggerAndErrorHandler: function(datafile) {
var start = module.exports.getTimestamp();
var optlyInstance = Optimizely.createInstance({
datafile: datafile,
skipJSONValidation: true,
eventDispatcher: {dispatchEvent: function() { return bluebird.resolve(null); }},
logger: {log: function() {}},
errorHandler: {handleError: function() {}},
});
var end = module.exports.getTimestamp();
var time = end - start;
assert.isNotNull(optlyInstance);
return time;
},
/**
* Calls the activate method on the Optimizely object and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number}
*/
measureActivate: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.activate('testExperiment2', userId);
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'control');
return time;
},
/**
* Calls the activate method on the Optimizely object with attributes and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number}
*/
measureActivateWithAttributes: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.activate('testExperimentWithFirefoxAudience', userId, {'browser_type': 'firefox'});
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'variation');
return time;
},
/**
* Calls the activate method on the Optimizely object with a forced variation and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number}
*/
measureActivateWithForcedVariation: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.activate('testExperiment2', userId);
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'variation');
return time;
},
/**
* Calls the activate method on the Optimizely object with a mutually exclusive grouped experiment and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number}
*/
measureActivateWithGroupedExperiment: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.activate('mutex_exp2', userId);
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'b');
return time;
},
/**
* Calls the activate method on the Optimizely object with a mutually exclusive grouped experiment & attributes and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number}
*/
measureActivateWithGroupedExperimentAndAttributes: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.activate('mutex_exp1', userId, {'browser_type': 'chrome'});
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'a');
return time;
},
/**
* Calls the get variation method on the Optimizely object and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureGetVariation: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.getVariation('testExperiment2', userId);
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'control');
return time;
},
/**
* Calls the get variation method on the Optimizely object with attributes and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureGetVariationWithAttributes: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.getVariation('testExperimentWithFirefoxAudience', userId, {'browser_type': 'firefox'});
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'variation');
return time;
},
/**
* Calls the get variation method on the Optimizely object with a forced variation and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureGetVariationWithForcedVariation: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.getVariation('testExperiment2', userId);
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'variation');
return time;
},
/**
* Calls the get variation method on the Optimizely object with a mutually exclusive grouped experiment and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureGetVariationWithGroupedExperiment: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.getVariation('mutex_exp2', userId);
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'b');
return time;
},
/**
* Calls the get variation method on the Optimizely object with a mutually exclusive grouped experiment & attributes and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureGetVariationWithGroupedExperimentAndAttributes: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
var variationKey = optlyInstance.getVariation('mutex_exp1', userId, {'browser_type': 'chrome'});
var end = module.exports.getTimestamp();
var time = end - start;
assert.strictEqual(variationKey, 'a');
return time;
},
/**
* Calls the track method on the Optimizely object and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureTrack: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
optlyInstance.track('testEvent', userId);
var end = module.exports.getTimestamp();
var time = end - start;
return time;
},
/**
* Calls the track method on the Optimizely object with attributes and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureTrackWithAttributes: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
optlyInstance.track('testEventWithAudiences', userId, {'browser_type': 'firefox'});
var end = module.exports.getTimestamp();
var time = end - start;
return time;
},
/**
* Calls the track method on the Optimizely object with revenue and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureTrackWithRevenue: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
optlyInstance.track('testEvent', userId, null, 666);
var end = module.exports.getTimestamp();
var time = end - start;
return time;
},
/**
* Calls the track method on the Optimizely object with attributes & revenue and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureTrackWithAttributesAndRevenue: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
optlyInstance.track('testEventWithAudiences', userId, {'browser_type': 'firefox'}, 666);
var end = module.exports.getTimestamp();
var time = end - start;
return time;
},
/**
* Calls the track method on the Optimizely object with a mutually exclusive grouped experiment and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureTrackWithGroupedExperiment: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
optlyInstance.track('testEventWithMultipleGroupedExperiments', userId);
var end = module.exports.getTimestamp();
var time = end - start;
return time;
},
/**
* Calls the track method on the Optimizely object with a mutually exclusive group & attributes and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureTrackWithGroupedExperimentAndAttributes: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
optlyInstance.track('testEventWithMultipleExperiments', userId, {'browser_type': 'chrome'});
var end = module.exports.getTimestamp();
var time = end - start;
return time;
},
/**
* Calls the track method on the Optimizely object with mutually exclusive group & revenue and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureTrackWithGroupedExperimentAndRevenue: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
optlyInstance.track('testEventWithMultipleGroupedExperiments', userId, null, 666);
var end = module.exports.getTimestamp();
var time = end - start;
return time;
},
/**
* Calls the track method on the Optimizely object with mutually exclusive group, attributes, & revenue and measures how long it takes
* @param {Object} datafile
* @param {string} userId
* @return {Number} ms to execute
*/
measureTrackWithGroupedExperimentAndAttributesAndRevenue: function(datafile, userId) {
var optlyInstance = module.exports.createOptimizelyInstance(datafile);
var start = module.exports.getTimestamp();
optlyInstance.track('testEventWithMultipleExperiments', userId, {'browser_type': 'chrome'}, 666);
var end = module.exports.getTimestamp();
var time = end - start;
return time;
},
/**
* Creates an Optimizely instance for all API method profiling
* @param {Object} datafile
* @return {Object} Optimizely instance
*/
createOptimizelyInstance: function(datafile) {
return Optimizely.createInstance({
datafile: datafile,
eventDispatcher: {dispatchEvent: function() { return bluebird.resolve(null); }},
logger: {log: function() {}},
errorHandler: {handleError: function() {}},
skipJSONValidation: true,
});
},
/**
* Returns Date.now(), how fun is that?
* @return {number} time
*/
getTimestamp: function() {
return Date.now();
},
/**
* Finds and logs medians, asserts if medians hit SLAs
* @param times
* @param slaTime
* @param numOfExperiments
*/
validateMedian: function(times, slaTime, numOfExperiments) {
var median = math.median(times);
console.log('Median time for ' + numOfExperiments + ' experiments is: ' + median);
assert.isBelow(median, slaTime);
},
/**
* Finds and logs averages, asserts if averages hit SLAs
* @param times
* @param slaTime
* @param numOfExperiments
*/
validateAverage: function(times, slaTime, numOfExperiments) {
var average = math.mean(times);
console.log('80% average time for ' + numOfExperiments + ' experiments is: ' + average);
assert.isBelow(average, slaTime);
},
/**
* Removes max and min times of 10-iteration sets for finding 80% average
* @param times
*/
removeMaxAndMin: function(times) {
times.splice(times.indexOf(Math.max.apply(null, times)), 1);
times.splice(times.indexOf(Math.min.apply(null, times)), 1);
},
};
| optimizely/node-sdk | tests/measure_methods.js | JavaScript | apache-2.0 | 18,876 |
goog.provide('recoil.structs.table.ColumnKey');
goog.provide('recoil.structs.table.MutableTable');
goog.provide('recoil.structs.table.MutableTableRow');
goog.provide('recoil.structs.table.Table');
goog.provide('recoil.structs.table.TableCell');
goog.provide('recoil.structs.table.TableInterface');
goog.provide('recoil.structs.table.TableRow');
goog.provide('recoil.structs.table.TableRowInterface');
// TODO mutable/immutable versions of table and rows
// a heirachy of rows
// changes function
// also in table widget factory produces widget, but we need a changed function
// have a primary key, but what happens if that can change?
goog.require('goog.array');
goog.require('goog.math.Long');
goog.require('goog.structs.AvlTree');
goog.require('goog.structs.Collection');
goog.require('recoil.util.Sequence');
goog.require('recoil.util.object');
/**
* @interface
*/
recoil.structs.table.TableInterface = function() {};
/**
* this ensures the sort order, the parameters to the function are columnkey and column meta data
*
* @param {function(!recoil.structs.table.ColumnKey,!Object) : *} func
*/
recoil.structs.table.TableInterface.prototype.forEachPlacedColumn = function(func) {};
/**
* @interface
*/
recoil.structs.table.TableRowInterface = function() {};
/**
* Gets only the value from the cell
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @return {CT}
*/
recoil.structs.table.TableRowInterface.prototype.get = function(column) {};
/**
* @param {function(string,!recoil.structs.table.TableCell)} func
*/
recoil.structs.table.TableRowInterface.prototype.forEachColumn = function(func) {};
/**
* Get the value and meta data from the cell
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @return {recoil.structs.table.TableCell<CT>}
*/
recoil.structs.table.TableRowInterface.prototype.getCell = function(column) {};
/**
* @template T
* @constructor
* @param {string} name
* @param {function(T,T) : number=} opt_comparator used for key values only needed if > < = do not work and it is a primary key
* @param {function(*) : T=} opt_castTo
* @param {T=} opt_default
* @param {function():T=} opt_defaultFunc
*/
recoil.structs.table.ColumnKey = function(name, opt_comparator, opt_castTo, opt_default, opt_defaultFunc) {
this.name_ = name;
this.comparator_ = opt_comparator || recoil.structs.table.ColumnKey.defaultComparator_;
this.castTo_ = opt_castTo || function(x) {return x;};
this.hasDefault_ = arguments.length > 3;
this.default_ = opt_default;
this.defaultFunc_ = opt_defaultFunc;
this.id_ = recoil.structs.table.ColumnKey.nextId_.next();
};
/**
* @param {string} name
* @return {!recoil.structs.table.ColumnKey<string>}
*/
recoil.structs.table.ColumnKey.createUnique = function(name) {
var seq = new recoil.util.Sequence();
return new recoil.structs.table.ColumnKey(name, undefined, undefined, '', function() {
return seq.next();
});
};
/**
* this function can be used to make 2 primary keys have
* the same default function, this can be useful if you want
* to have primary keys to be unique between accross to keys
*
* note this should really be called only once and before the column is
* used to generate any primary keys
*
* @param {!recoil.structs.table.ColumnKey} otherKey
*/
recoil.structs.table.ColumnKey.prototype.setSameDefaultFunc = function(otherKey) {
if (goog.isFunction(this.defaultFunc_)) {
otherKey.defaultFunc_ = this.defaultFunc_;
otherKey.hasDefault_ = true;
return;
}
throw new Error(this + ' does not have a default function');
};
/**
* @return {T}
*/
recoil.structs.table.ColumnKey.prototype.getDefault = function() {
if (goog.isFunction(this.defaultFunc_)) {
return this.defaultFunc_();
}
return this.default_;
};
/**
* @return {!recoil.structs.table.ColumnKey}
*/
recoil.structs.table.ColumnKey.prototype.clone = function() {
return this;
};
/**
* @return {boolean}
*/
recoil.structs.table.ColumnKey.prototype.hasDefault = function() {
return this.hasDefault_;
};
/**
* @type {!recoil.util.Sequence}
* @private
*/
recoil.structs.table.ColumnKey.nextId_ = new recoil.util.Sequence();
/**
* given the primary keys converts keys into a table, if there is more than
* 1 primary key this requires keys to be an array
* @param {!Array<!recoil.structs.table.ColumnKey>} primaryKeys
* @param {!Array<?>} keys
* @param {number=} opt_order
* @return {recoil.structs.table.TableRow}
*/
recoil.structs.table.ColumnKey.normalizeColumns = function(primaryKeys, keys, opt_order) {
var res = new recoil.structs.table.MutableTableRow(opt_order);
if (primaryKeys.length !== keys.length) {
throw 'incorrect number of primary keys';
}
else {
for (var i = 0; i < primaryKeys.length; i++) {
res.set(primaryKeys[i], primaryKeys[i].castTo(keys[i]));
}
}
return res.freeze();
};
/**
* @private
* @param {*} a
* @param {*} b
* @return {number}
*/
recoil.structs.table.ColumnKey.defaultComparator_ = function(a, b) {
if (a === b) {
return 0;
}
if (a === null) {
return -1;
}
if (b === null) {
return 1;
}
if (a === undefined) {
return -1;
}
if (b === undefined) {
return 1;
}
if (typeof(a) !== typeof(b)) {
return typeof(a) < typeof(b) ? -1 : 1;
}
if (a < b) {
return -1;
}
if (b < a) {
return 1;
}
return 0;
};
/**
* A default column key if none is provided they will be added sequentially
* @type {!recoil.structs.table.ColumnKey<!goog.math.Long>}
*/
recoil.structs.table.ColumnKey.INDEX =
new recoil.structs.table.ColumnKey(
'index', undefined,
function(x) {
if (x instanceof goog.math.Long) {
return x;
}
return goog.math.Long.fromNumber(parseInt(x, 10));
});
/**
* A default column that is used to store meta information for the row
* @type {!recoil.structs.table.ColumnKey<*>}
*/
recoil.structs.table.ColumnKey.ROW_META = new recoil.structs.table. ColumnKey('meta', undefined, undefined);
/**
* compares to values for column
* @param {T} a
* @param {T} b
* @return {number}
*/
recoil.structs.table.ColumnKey.prototype.valCompare = function(a, b) {
return this.comparator_(a, b);
};
/**
* compares to values for column
* @param {T} a
* @return {number|undefined}
*/
recoil.structs.table.ColumnKey.prototype.compare = function(a) {
if (a instanceof recoil.structs.table.CombinedColumnKey) {
return -a.compare(this);
}
if (a instanceof recoil.structs.table.ColumnKey) {
return this.id_ - a.id_;
}
return undefined;
};
/**
* @return {string}
*/
recoil.structs.table.ColumnKey.prototype.getId = function() {
return this.toString();
};
/**
* @return {string}
*/
recoil.structs.table.ColumnKey.prototype.toString = function() {
return this.name_ === undefined ? this.id_ : this.name_ + ':' + this.id_;
};
/**
* @param {*} a
* @return {T}
*/
recoil.structs.table.ColumnKey.prototype.castTo = function(a) {
return this.castTo_(a);
};
/**
* @return {string}
*/
recoil.structs.table.ColumnKey.prototype.getName = function() {
return this.name_ === undefined ? ('ID(' + this.id_ + ')') : this.name_;
};
/**
*
* @param {recoil.structs.table.ColumnKey} a
* @param {recoil.structs.table.ColumnKey} b
* @return {number}
*/
recoil.structs.table.ColumnKey.comparator = function(a , b) {
if (a.id_ < b.id_) {
return -1;
}
if (a.id_ > b.id_) {
return 1;
}
return 0;
};
/**
* @template T
* @extends {recoil.structs.table.ColumnKey}
* @param {!Array<recoil.structs.table.ColumnKey>} columnKeys
* @constructor
**/
recoil.structs.table.CombinedColumnKey = function(columnKeys) {
this.name_ = columnKeys.map(function(c) {return c.getName();}).join(',');
this.subKeys_ = columnKeys;
};
/**
* not implemented for combined keys set the column keys to be the same
* @param {!recoil.structs.table.ColumnKey} otherKey
*/
recoil.structs.table.CombinedColumnKey.prototype.setSameDefaultFunc = function(otherKey) {
throw new Error('not supported fro combined keys');
};
/**
* @return {T}
*/
recoil.structs.table.CombinedColumnKey.prototype.getDefault = function() {
return this.subKeys_.map(function(c) {return c.getDefault();});
};
/**
* @return {!recoil.structs.table.ColumnKey}
*/
recoil.structs.table.CombinedColumnKey.prototype.clone = function() {
return this;
};
/**
* @return {boolean}
*/
recoil.structs.table.CombinedColumnKey.prototype.hasDefault = function() {
return this.subKeys_.reduce(function(acc, v) {return acc && v;},true);
};
/**
* compares to values for column
* @param {T} a
* @param {T} b
* @return {number}
*/
recoil.structs.table.CombinedColumnKey.prototype.valCompare = function(a, b) {
if (a instanceof Array && b instanceof Array) {
if (a.length === this.subKeys_.length && b.length === this.subKeys_.length) {
for (var i = 0; i < this.subKeys_.length; i++) {
var res = this.subKeys_[i].valCompare(a[i], b[i]);
if (res !== 0) {
return res;
}
}
return 0;
}
}
return recoil.util.object.compare(a, b);
};
/**
* compares to values for column
* @param {T} a
* @return {number|undefined}
*/
recoil.structs.table.CombinedColumnKey.prototype.compare = function(a) {
if (a instanceof recoil.structs.table.CombinedColumnKey) {
var res = this.subKeys_.length - a.subKeys_.length;
if (res !== 0) {
return res;
}
for (var i = 0; i < this.subKeys_.length; i++) {
res = this.subKeys_[i].compare(a.subKeys_[i]);
if (res !== 0) {
return res;
}
}
return 0;
}
if (a instanceof recoil.structs.table.ColumnKey) {
return -1;
}
return undefined;
};
/**
* @return {string}
*/
recoil.structs.table.CombinedColumnKey.prototype.equals = function() {
return this.toString();
};
/**
* @return {string}
*/
recoil.structs.table.CombinedColumnKey.prototype.getId = function() {
return this.toString();
};
/**
* @return {string}
*/
recoil.structs.table.CombinedColumnKey.prototype.toString = function() {
return '[' + this.subKeys_.map(function(c) {return c.toString();}).join(',') + ']';
};
/**
* @param {*} a
* @return {T}
*/
recoil.structs.table.CombinedColumnKey.prototype.castTo = function(a) {
var res = [];
for (var i = 0; i < this.subKeys_.length; i++) {
res.push(this.subKeys_[i].castTo(a[i]));
}
return res;
};
/**
* @return {string}
*/
recoil.structs.table.CombinedColumnKey.prototype.getName = function() {
return this.name_;
};
/**
* construct a table which cannot change, provide a mutable table to get the value
* @param {recoil.structs.table.MutableTable} table
* @constructor
* @implements {recoil.structs.table.TableInterface}
*/
recoil.structs.table.Table = function(table) {
this.meta_ = {};
goog.object.extend(this.meta_, table.meta_);
this.columnMeta_ = {};
goog.object.extend(this.columnMeta_, table.columnMeta_);
this.primaryColumns_ = table.primaryColumns_;
this.otherColumns_ = table.otherColumns_;
this.rows_ = new goog.structs.AvlTree(table.rows_.comparator_);
this.ordered_ = new goog.structs.AvlTree(recoil.structs.table.TableRow.positionComparator_(table.rows_.comparator_));
var me = this;
table.rows_.inOrderTraverse(function(x) {
me.rows_.add(x);
me.ordered_.add(x);
});
};
/**
* very efficent way of setting the meta on a table
* it doesn't change this table but returns an new table
* with new meta
* @param {!Object} meta
* @return {!recoil.structs.table.Table}
*/
recoil.structs.table.Table.prototype.addMeta = function(meta) {
var res = new recoil.structs.table.Table(new recoil.structs.table.MutableTable(this.primaryColumns_, this.otherColumns_));
res.meta_ = goog.object.clone(this.meta_);
recoil.util.object.addProps(res.meta_, meta);
res.columnMeta_ = this.columnMeta_;
res.rows_ = this.rows_;
res.ordered_ = this.ordered_;
return res;
};
/**
* @param {?} b
* @return {number}
*/
recoil.structs.table.Table.prototype.compare = function(b) {
if (b instanceof recoil.structs.table.Table) {
var res = this.size() - b.size();
if (res !== 0) {
return res;
}
res = recoil.util.object.compareAll([
{x: this.getMeta(), y: b.getMeta()},
{x: this.primaryColumns_, y: b.primaryColumns_},
{x: this.otherColumns_, y: b.otherColumns_},
{x: this.ordered_, y: b.ordered_}]
);
if (res !== 0) {
return res;
}
//ok we don't compare lengths since we already compared the primary and other columns
//however it might be good if we ignore order of other columns
var cols = this.getColumns();
for (var i = 0; i < cols.length; i++) {
var col = cols[i];
res = recoil.util.object.compare(this.getColumnMeta(col), b.getColumnMeta(col));
if (res !== 0) {
return res;
}
}
return 0;
}
return -1;
};
/**
* @param {?} a
* @return {boolean}
*/
recoil.structs.table.Table.prototype.equals = function(a) {
return this.compare(a) === 0;
};
/**
* @return {!Array<!recoil.structs.table.ColumnKey>}
*/
recoil.structs.table.Table.prototype.getPrimaryColumns = function() {
return this.primaryColumns_;
};
/**
* @return {!Array<!recoil.structs.table.ColumnKey>}
*/
recoil.structs.table.Table.prototype.getOtherColumns = function() {
return this.otherColumns_;
};
/**
* convert to a mutable table
* @return {!recoil.structs.table.MutableTable}
*/
recoil.structs.table.Table.prototype.unfreeze = function() {
var res = new recoil.structs.table.MutableTable(this.primaryColumns_, this.otherColumns_);
recoil.util.object.addProps(res.meta_, this.meta_);
res.columnMeta_ = {};
recoil.util.object.addProps(res.columnMeta_, this.columnMeta_);
this.rows_.inOrderTraverse(function(row) {
res.addRow(row);
});
return res;
};
/**
* creates an empty mutable table with the same columns
* @param {IArrayLike<!recoil.structs.table.ColumnKey>} cols
* @return {!recoil.structs.table.MutableTable}
*/
recoil.structs.table.Table.prototype.createEmptyKeep = function(cols) {
var remove = [];
var seen = {};
cols.forEach(function(col) {
seen[col.getId()] = true;
});
this.otherColumns_.forEach(function(c) {
if (!seen[c.getId()]) {
remove.push(c);
}
});
return this.createEmpty([], [], remove);
};
/**
* creates an empty mutable table with the same columns
* @param {IArrayLike<!recoil.structs.table.ColumnKey>=} opt_extPrimaryCols
* @param {IArrayLike<!recoil.structs.table.ColumnKey>=} opt_extOtherCols
* @param {IArrayLike<!recoil.structs.table.ColumnKey>=} opt_removeCols
* @return {!recoil.structs.table.MutableTable}
*/
recoil.structs.table.Table.prototype.createEmpty = function(opt_extPrimaryCols, opt_extOtherCols, opt_removeCols) {
var newPrimary = this.primaryColumns_.concat(opt_extPrimaryCols || []);
var seen = {};
var newOther = [];
// don't add already existing columns
this.otherColumns_.forEach(function(c) {
seen[c.getId()] = true;
newOther.push(c);
});
if (opt_extOtherCols) {
opt_extOtherCols.forEach(function(c) {
if (!seen[c.getId()]) {
newOther.push(c);
}
});
}
var removeMap = {};
if (opt_removeCols) {
opt_removeCols.forEach(function(c) {
removeMap[c] = true;
});
}
var doRemove = function(arr) {
for (var i = arr.length - 1; i >= 0; i--) {
if (removeMap[arr[i]]) {
arr.splice(i, 1);
}
}
};
if (opt_removeCols) {
doRemove(newPrimary);
doRemove(newOther);
}
var res = new recoil.structs.table.MutableTable(newPrimary,
newOther);
recoil.util.object.addProps(res.meta_, this.meta_);
res.columnMeta_ = {};
recoil.util.object.addProps(res.columnMeta_, this.columnMeta_);
if (opt_removeCols) {
opt_removeCols.forEach(function(col) {
delete res.columnMeta_[col];
});
}
return res;
};
/**
* creates an empty mutable table based on a table, that will a have all original columns
* but the primary keys will be the ones specified
* @param {!Array<!recoil.structs.table.ColumnKey>} primaryCols the new primary keys these can be new or existing
* @param {!Array<!recoil.structs.table.ColumnKey>} extOtherCols any extra columns that need to be added that are
* not primary keys
* @return {!recoil.structs.table.MutableTable}
*/
recoil.structs.table.Table.prototype.createEmptyAddCols = function(primaryCols, extOtherCols) {
var otherColumns = [];
var me = this;
this.primaryColumns_.forEach(function(val) {
if (!goog.array.contains(primaryCols, val)) {
otherColumns.push(val);
}
});
this.otherColumns_.forEach(function(val) {
if (!goog.array.contains(primaryCols, val)) {
otherColumns.push(val);
}
});
extOtherCols.forEach(function(val) {
if (!goog.array.contains(otherColumns, val)) {
otherColumns.push(val);
}
});
var res = new recoil.structs.table.MutableTable(primaryCols, otherColumns);
recoil.util.object.addProps(res.meta_, this.meta_);
res.columnMeta_ = {};
recoil.util.object.addProps(res.columnMeta_, this.columnMeta_);
return res;
};
/**
* given that this table has primary key that is a number
* it will generate a mutable table row with a primary key not aready in the table
* also if all the existing rows have an position then the position of the new row will
* be the last row
*
* @param {!recoil.structs.table.MutableTable|!recoil.structs.table.MutableTable} table
*
* @return {!recoil.structs.table.MutableTableRow}
*/
recoil.structs.table.Table.createUniqueIntPkRow = function(table) {
var primaryCols = table.getPrimaryColumns();
if (primaryCols.length !== 1) {
throw 'to generate pk you must have exactly 1 primary key';
}
var res = new recoil.structs.table.MutableTableRow();
var pos = 0;
var usedPks = new goog.structs.AvlTree();
table.forEach(function(row, key) {
if (pos !== undefined) {
var rowPos = row.pos();
if (rowPos === undefined) {
pos = undefined;
}
else if (pos < rowPos) {
pos = rowPos + 1;
}
}
if (typeof(key[0]) !== 'number') {
throw 'cannot generate primary key on non number field';
}
usedPks.add(key[0]);
});
var curPk = 0;
usedPks.inOrderTraverse(function(val) {
if (curPk < val) {
return true;
}
if (curPk === val) {
curPk++;
}
return false;
});
res.set(primaryCols[0], curPk);
res.setPos(pos);
return res;
};
/**
*
* @param {!Array<!recoil.structs.table.ColumnKey>} primaryKeys
* @param {!Array<!recoil.structs.table.ColumnKey>} otherColumns
* @constructor
* @implements {recoil.structs.table.TableInterface}
* @template T
*
*/
recoil.structs.table.MutableTable = function(primaryKeys, otherColumns) {
this.meta_ = {}; // table meta data
this.columnMeta_ = {}; // column meta data
if (primaryKeys.length === 0) {
this.primaryColumns_ = [recoil.structs.table.ColumnKey.INDEX];
}
else {
this.primaryColumns_ = goog.array.clone(primaryKeys);
}
this.otherColumns_ = goog.array.clone(otherColumns);
var me = this;
var comparator = function(rowA, rowB) {
for (var key = 0; key < me.primaryColumns_.length; key++) {
var col = me.primaryColumns_[key];
var res = col.valCompare(rowA.get(col), rowB.get(col));
if (res !== 0) {
return res;
}
}
return 0;
};
this.rows_ = new goog.structs.AvlTree(comparator);
//recoil.structs.table.TableRow.positionComparator_ = function (comparator) {
this.ordered_ = new goog.structs.AvlTree(recoil.structs.table.TableRow.positionComparator_(comparator));
};
/**
* @return {recoil.structs.table.TableRow}
*/
recoil.structs.table.MutableTable.prototype.getFirstRow = function() {
var res = null;
this.forEach(function(row) {
if (!res) {
res = row;
}
});
return res;
};
/**
* @return {!Array<!recoil.structs.table.ColumnKey<*>>}
*/
recoil.structs.table.MutableTable.prototype.getColumns = function() {
return goog.array.concat(this.primaryColumns_, this.otherColumns_);
};
/**
* @return {?} a more readable version of the table
*/
recoil.structs.table.MutableTable.prototype.toDebugObj = function() {
var tableOut = [];
var behaviour = this;
this.forEach(function(row) {
tableOut.push(row);
});
return {meta: this.meta_, colMeta: this.columnMeta_, tbl: tableOut};
};
/**
* @return {!Array<!recoil.structs.table.ColumnKey<*>>}
*/
recoil.structs.table.MutableTable.prototype.getPrimaryColumns = function() {
return this.primaryColumns_;
};
/**
* @return {!Array<!recoil.structs.table.ColumnKey>}
*/
recoil.structs.table.MutableTable.prototype.getOtherColumns = function() {
return this.otherColumns_;
};
/**
* this ensures the sort order, the parameters to the function are columnkey and column meta data
*
* @param {function(!recoil.structs.table.ColumnKey,!Object) : *} func
*/
recoil.structs.table.MutableTable.prototype.forEachPlacedColumn = function(func) {
var cols = [];
var me = this;
var addCol = function(key) {
var col = me.columnMeta_[key.getId()];
if (col && col.position !== undefined) {
cols.push({meta: col, key: key});
}
};
this.primaryColumns_.forEach(addCol);
this.otherColumns_.forEach(addCol);
goog.array.sort(cols, function(x, y) {
return x.meta.position - y.meta.position;
});
cols.forEach(function(col) {
func(col.key, col.meta);
});
};
/**
* @param {function(!recoil.structs.table.ColumnKey,!Object) : *} func
*/
recoil.structs.table.MutableTable.prototype.forEachColumn = function(func) {
var cols = [];
var me = this;
var addCol = function(key) {
var col = me.columnMeta_[key.getId()];
cols.push({meta: col, key: key});
};
this.primaryColumns_.forEach(addCol);
this.otherColumns_.forEach(addCol);
cols.forEach(function(col) {
if (col.key !== recoil.structs.table.ColumnKey.ROW_META) {
func(col.key, col.meta || {});
}
func(col.key, col.meta);
});
};
/**
* @param {!recoil.structs.table.MutableTableRow|recoil.structs.table.TableRow} row
* @return {!Array<?>}
*/
recoil.structs.table.MutableTable.prototype.getRowKey = function(row) {
var res = [];
for (var i = 0; i < this.primaryColumns_.length; i++) {
res.push(row.get(this.primaryColumns_[i]));
}
return res;
};
/**
* gets the number of rows in the table
* @return {number}
*/
recoil.structs.table.MutableTable.prototype.size = function() {
return this.rows_.getCount();
};
/**
* @param {Object} a
* @param {Object} b
* @return {number}
*/
recoil.structs.table.Table.comparator = function(a, b) {
return recoil.structs.table.ColumnKey.comparator(a.key, b.key);
};
/**
* set meta data to already existing meta data, this will replace all existing meta
* data
* @param {!Object} meta
*/
recoil.structs.table.MutableTable.prototype.setMeta = function(meta) {
this.meta_ = goog.object.clone(meta);
};
/**
* get table meta data
* @return {!Object}
*/
recoil.structs.table.MutableTable.prototype.getMeta = function() {
return this.meta_;
};
/**
* add meta data to already existing meta data, this may override existing meta
* data
* @param {!Object} meta
*/
recoil.structs.table.MutableTable.prototype.addMeta = function(meta) {
var newMeta = goog.object.clone(this.meta_);
recoil.util.object.addProps(newMeta, this.meta_, meta);
this.meta_ = goog.object.clone(newMeta);
};
/**
* get column meta data
* @param {recoil.structs.table.ColumnKey} key
* @return {!Object}
*/
recoil.structs.table.MutableTable.prototype.getColumnMeta = function(key) {
var res = this.columnMeta_[key];
if (res === undefined) {
return {};
}
return res;
};
/**
* set new column meta data replacing already existing meta data there
* if it is not overriden by the new meta data
* @param {!recoil.structs.table.ColumnKey} key
* @param {!Object} meta
*/
recoil.structs.table.MutableTable.prototype.setColumnMeta = function(key, meta) {
this.columnMeta_[key] = goog.object.clone(meta);
};
/**
* add new column meta data leaving already existing meta data there
* if it is not overriden by the new meta data
* @param {!recoil.structs.table.ColumnKey} key
* @param {!Object|{position:number}} meta
*/
recoil.structs.table.MutableTable.prototype.addColumnMeta = function(key, meta) {
var newMeta = goog.object.clone(this.getColumnMeta(key));
for (var field in meta) {
newMeta[field] = meta[field];
}
this.setColumnMeta(key, newMeta);
};
/**
* get row meta data
* @param {!Array<?>} keys
* @return {!Object}
*/
recoil.structs.table.MutableTable.prototype.getRowMeta = function(keys) {
var row = this.getRow(keys);
if (row === null) {
return {};
}
return row.getMeta();
};
/**
* set new column meta data replacing already existing meta data there
* if it is not overriden by the new meta data
* @param {!Array<?>} keys
* @param {!Object} meta
*/
recoil.structs.table.MutableTable.prototype.setRowMeta = function(keys, meta) {
this.setCell(
keys,
recoil.structs.table.ColumnKey.ROW_META,
new recoil.structs.table.TableCell(undefined, meta));
};
/**
* add new column meta data leaving already existing meta data there
* if it is not overriden by the new meta data
* @param {!Array<*>} keys
* @param {!Object} meta
*/
recoil.structs.table.MutableTable.prototype.addRowMeta = function(keys, meta) {
var newMeta = {};
recoil.util.object.addProps(newMeta, this.getRowMeta(keys), meta);
this.setRowMeta(keys, newMeta);
};
/**
* this uses the primary key of the row to insert the table
*
* @param {recoil.structs.table.TableRow<T> | recoil.structs.table.MutableTableRow<T>} row
*/
recoil.structs.table.MutableTable.prototype.addRow = function(row) {
var missingKeys = [];
if (row instanceof recoil.structs.table.MutableTableRow) {
row = row.freeze();
}
this.primaryColumns_.forEach(function(col) {
if (!row.hasColumn(col)) {
if (col.hasDefault()) {
row = row.set(col, col.getDefault());
}
else {
missingKeys.push(col);
}
}
});
this.otherColumns_.forEach(function(col) {
if (!row.hasColumn(col)) {
if (col.hasDefault()) {
row = row.set(col, col.getDefault());
}
else {
throw new Error('missing column: ' + col.getName());
}
}
});
if (missingKeys.length === 1
&& this.primaryColumns_.length === 1
&& this.primaryColumns_[0] === recoil.structs.table.ColumnKey.INDEX) {
var nextId;
if (this.rows_.getCount() === 0) {
nextId = goog.math.Long.getZero();
}
else {
nextId = this.rows_.getMaximum().get(recoil.structs.table.ColumnKey.INDEX).add(goog.math.Long.getOne());
}
row = row.set(recoil.structs.table.ColumnKey.INDEX, nextId);
}
else if (missingKeys.length > 0) {
throw 'Must specify All primary keys';
}
var tblRow = row.keepColumns(goog.array.concat(this.primaryColumns_, this.otherColumns_));
if (this.rows_.findFirst(tblRow) !== null) {
throw new Error('row already exists ');
}
this.rows_.add(tblRow);
this.ordered_.add(tblRow);
};
/**
* @private
* @param {Array<*>} keys
* @return {recoil.structs.table.TableRow} the key as a row so it can be used to lookup the value in the map
*/
recoil.structs.table.MutableTable.prototype.makeKeys_ = function(keys) {
if (keys.length !== this.primaryColumns_.length) {
throw 'Incorrect number of primary keys';
}
var row = new recoil.structs.table.MutableTableRow();
for (var i = 0; i < keys.length; i++) {
row.set(this.primaryColumns_[i], keys[i]);
}
return row.freeze();
};
/**
* returns an array of keys for the row
* @param {!recoil.structs.table.TableRow} row
* @return {!Array<?>}
*/
recoil.structs.table.MutableTable.prototype.getRowKeys = function(row) {
var keys = [];
for (var i = 0; i < this.primaryColumns_.length; i++) {
keys.push(row.get(this.primaryColumns_[i]));
}
return keys;
};
/**
*
* @param {function(!recoil.structs.table.TableRow,!Array<?>,Object) : *} func the first parametr is the row the, second is \
* the primary key, and the third is the rowMeta data
*/
recoil.structs.table.MutableTable.prototype.forEach = function(func) {
var me = this;
var list = [];
//construct a list first just incase we modify the
//table while iterating over it
this.ordered_.inOrderTraverse(function(row) {
list.push(row);
});
list.forEach(function(row) {
return func(row, me.getRowKeys(row), row.getMeta());
});
//var table = this.freeze();
//table.forEach(func);
};
/**
* like foreach but makes the row mutable, this is done often
* @param {function(!recoil.structs.table.MutableTableRow,!Array<?>,Object) : *} func the first parametr is the row the, second is \
* the primary key, and the third is the rowMeta data
*/
recoil.structs.table.MutableTable.prototype.forEachModify = function(func) {
var me = this;
var list = [];
//construct a list first just incase we modify the
//table while iterating over it
this.ordered_.inOrderTraverse(function(row) {
list.push(row.unfreeze());
});
list.forEach(function(row) {
return func(row, me.getRowKeys(row), row.getMeta());
});
};
/**
* this uses the primary key of the row to insert the table
*
* @param {Array<*>} keys
*
*/
recoil.structs.table.MutableTable.prototype.removeRow = function(keys) {
var oldRow = this.rows_.remove(this.makeKeys_(keys));
if (oldRow === null) {
throw 'Row does not exist';
}
else {
this.ordered_.remove(oldRow);
}
};
/**
* gets the row from a table, pass the primary keys as an array of values
* @param {!Array<?>} keys
* @return {recoil.structs.table.TableRow}
*/
recoil.structs.table.MutableTable.prototype.getRow = function(keys) {
var keyRow = recoil.structs.table.ColumnKey.normalizeColumns(this.primaryColumns_, keys);
return this.rows_.findFirst(keyRow);
};
/**
* gets the row from a table, pass the primary keys as an array of values
* @param {function(!recoil.structs.table.TableRow):boolean} compare
* @return {recoil.structs.table.TableRow}
*/
recoil.structs.table.MutableTable.prototype.findRow = function(compare) {
let res = null;
this.forEach(function(row) {
if (compare(row)) {
res = row;
}
});
return res;
};
/**
* Sets the value for the cell
* @template CT
* @param {!Array<?>} keys
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @param {CT} value
* @param {Object=} opt_meta
*/
recoil.structs.table.MutableTable.prototype.set = function(keys, column, value, opt_meta) {
var old = this.getCell(keys, column);
if (old === null) {
throw 'Cell Does not exist';
}
if (opt_meta) {
this.setCell(keys, column, new recoil.structs.table.TableCell(value, opt_meta));
}
else {
this.setCell(keys, column, old.setValue(value));
}
};
/**
* Sets the value and meta data for the cell
* @template CT
* @param {!Array<?>} keys
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @param {CT} value
*/
recoil.structs.table.MutableTable.prototype.setCell = function(keys, column, value) {
var row = this.getRow(keys);
if (row === null) {
throw 'row not found';
}
this.removeRow(keys);
this.addRow(row.setCell(column, value));
};
/**
* sets only the cell meta data, leave the value unchanged
* @template CT
* @param {!Array<?>} keys
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @param {!Object} meta
*/
recoil.structs.table.MutableTable.prototype.setCellMeta = function(keys, column, meta) {
var cell = this.getCell(keys, column);
if (cell === null) {
console.log('settin null');
}
this.setCell(keys, column, cell.setMeta(meta));
};
/**
* adds meta data to the cell
* @template CT
* @param {!Array<?>} keys
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @param {!Object} meta
*/
recoil.structs.table.MutableTable.prototype.addCellMeta = function(keys, column, meta) {
var cell = this.getCell(keys, column);
var newMeta = cell.getMeta();
recoil.util.object.addProps(newMeta, meta);
this.setCell(keys, column, cell.setMeta(meta));
};
/**
* Sets the value and meta data for the cell
* @param {!Array<?>} keys
* @param {!recoil.structs.table.TableRow|!recoil.structs.table.MutableTableRow} row
*/
recoil.structs.table.MutableTable.prototype.setRow = function(keys, row) {
var oldRow = this.getRow(keys);
if (oldRow === null) {
throw 'row not found';
}
this.removeRow(keys);
this.addRow(row);
};
/**
* @template CT
* @param {!Array<?>} keys
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @return {recoil.structs.table.TableCell<CT>}
*/
recoil.structs.table.MutableTable.prototype.getCell = function(keys, column) {
var row = this.getRow(keys);
if (row === null) {
return null;
}
return row.getCell(column);
};
/**
* @template CT
* @param {!Array<?>} keys
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @return {CT}
*/
recoil.structs.table.MutableTable.prototype.get = function(keys, column) {
var row = this.getRow(keys);
if (row === null) {
return null;
}
return row.get(column);
};
/**
* convert into immutable table
* @return {!recoil.structs.table.Table}
*/
recoil.structs.table.MutableTable.prototype.freeze = function() {
return new recoil.structs.table.Table(this);
};
/**
* gets the value of a cell in the table, without the meta information
* @template CT
* @param {!Array<?>} keys primary key of the row
* @param {recoil.structs.table.ColumnKey<CT>} columnKey
* @return {CT}
*/
recoil.structs.table.Table.prototype.get = function(keys, columnKey) {
var r = this.getRow(keys);
if (r == null) {
return null;
}
return r.get(columnKey);
};
/**
* @return {!Object}
*/
recoil.structs.table.Table.prototype.getMeta = function() {
return recoil.util.object.clone(this.meta_);
};
/**
* @template CT
* @param {recoil.structs.table.ColumnKey<CT>} column
* @return {!Object} +
*/
recoil.structs.table.Table.prototype.getColumnMeta = function(column) {
var res = this.columnMeta_[column];
if (res === undefined) {
return {};
}
return res;
};
/**
* @template CT
* @param {!Array<?>} keys
* @param {recoil.structs.table.ColumnKey<CT>} column
* @return {!Object}
*/
recoil.structs.table.Table.prototype.getRowMeta = function(keys, column) {
var row = this.getRow(keys);
if (row === null) {
return {};
}
return row.getMeta();
};
/**
* returns an array of keys for the row
* @param {!recoil.structs.table.TableRow|!recoil.structs.table.MutableTableRow} row
* @return {!Array<?>}
*/
recoil.structs.table.Table.prototype.getRowKeys = function(row) {
var keys = [];
for (var i = 0; i < this.primaryColumns_.length; i++) {
keys.push(row.get(this.primaryColumns_[i]));
}
return keys;
};
/**
*
* @param {function(!recoil.structs.table.TableRow, !Array<?>, Object) : *} func
*/
recoil.structs.table.Table.prototype.forEach = function(func) {
var me = this;
this.ordered_.inOrderTraverse(function(row) {
return func(row, me.getRowKeys(row), row.getMeta());
});
};
/**
*
* @param {function(!recoil.structs.table.MutableTableRow, !Array<?>, Object) : *} func
*/
recoil.structs.table.Table.prototype.forEachModify = function(func) {
var me = this;
this.ordered_.inOrderTraverse(function(row) {
return func(row.unfreeze(), me.getRowKeys(row), row.getMeta());
});
};
/**
* @return {!Array<!recoil.structs.table.ColumnKey<*>>}
*/
recoil.structs.table.Table.prototype.getKeyColumns = function() {
return this.primaryColumns_;
};
/**
* @return {!Array<!recoil.structs.table.ColumnKey<*>>}
*/
recoil.structs.table.Table.prototype.getColumns = function() {
return goog.array.concat(this.primaryColumns_, this.otherColumns_);
};
/**
* this ensures the sort order, the parameters to the function are columnkey and column meta data
*
* @param {function(!recoil.structs.table.ColumnKey,!Object) : *} func
*/
recoil.structs.table.Table.prototype.forEachPlacedColumn = function(func) {
var cols = [];
var me = this;
var addCol = function(key) {
var col = me.columnMeta_[key.getId()];
if (col && col.position !== undefined) {
cols.push({meta: col, key: key});
}
};
this.primaryColumns_.forEach(addCol);
this.otherColumns_.forEach(addCol);
goog.array.sort(cols, function(x, y) {
return x.meta.position - y.meta.position;
});
cols.forEach(function(col) {
func(col.key, col.meta);
});
};
/**
* @return {?} a more readable version
*/
recoil.structs.table.Table.prototype.toDebugObj = function() {
var tableOut = [];
var behaviour = this;
this.forEach(function(row) {
tableOut.push(row);
});
return {meta: this.meta_, colMeta: this.columnMeta_, tbl: tableOut};
};
/**
* @param {function(!recoil.structs.table.ColumnKey,!Object) : *} func
*/
recoil.structs.table.Table.prototype.forEachColumn = function(func) {
var cols = [];
var me = this;
var addCol = function(key) {
var col = me.columnMeta_[key.getId()];
cols.push({meta: col, key: key});
};
this.primaryColumns_.forEach(addCol);
this.otherColumns_.forEach(addCol);
cols.forEach(function(col) {
func(col.key, col.meta || {});
});
};
/**
* gets the number of rows in the table
* @return {number}
*/
recoil.structs.table.Table.prototype.size = function() {
return this.rows_.getCount();
};
/**
* gets the row from a table, pass the primary keys as an array of values
* @param {!Array<?>} keys
* @return {recoil.structs.table.TableRow}
*/
recoil.structs.table.Table.prototype.getRow = function(keys) {
var keyRow = recoil.structs.table.ColumnKey.normalizeColumns(this.primaryColumns_, keys);
return this.rows_.findFirst(keyRow);
};
/**
* gets the row from a table, pass the primary keys as an array of values
* @param {function(!recoil.structs.table.TableRow):boolean} compare
* @return {recoil.structs.table.TableRow}
*/
recoil.structs.table.Table.prototype.findRow = function(compare) {
let res = null;
this.forEach(function(row) {
if (compare(row)) {
res = row;
}
});
return res;
};
/**
* get cell value with its associated meta information
*
* @template CT
* @param {!Array<?>} keys
* @param {!recoil.structs.table.ColumnKey<CT>} columnKey
* @return {recoil.structs.table.TableCell<CT>} an object containing the meta data and a value
*/
recoil.structs.table.Table.prototype.getCell = function(keys, columnKey) {
var rowInfo = this.getRow(keys);
if (rowInfo) {
return rowInfo.getCell(columnKey);
}
return null;
};
/**
* gets the cell meta including the column, table and row values
* @template CT
* @param {!Array<?>} keys
* @param {!recoil.structs.table.ColumnKey<CT>} col
* @return {!Object}
*/
recoil.structs.table.Table.prototype.getFullCellMeta = function(keys, col) {
var row = this.getRow(keys);
if (row) {
var meta = {};
goog.object.extend(meta, this.getMeta(),
row.getRowMeta(),
this.getColumnMeta(col), row.getCellMeta(col));
return meta;
}
return this.getMeta();
};
/**
* @return {recoil.structs.table.TableRow}
*/
recoil.structs.table.Table.prototype.getFirstRow = function() {
var res = null;
this.forEach(function(row) {
if (!res) {
res = row;
}
});
return res;
};
/**
*
* @param {Object} typeFactories
* @param {Object} tableMeta
* @param {Array<Object>} rawTable
* @param {boolean=} opt_ordered if true then it will enforce the order it rawtable came in
* @return {recoil.structs.table.Table}
*/
recoil.structs.table.Table.create = function(typeFactories, tableMeta, rawTable, opt_ordered) {
var keys = recoil.structs.table.Table.extractKeys_(tableMeta);
var tbl = new recoil.structs.table.MutableTable(keys.primaryKeys, keys.otherKeys);
tbl.setMeta({'typeFactories': typeFactories});
for (var tMeta in tableMeta) {
var colKey = tableMeta[tMeta].key;
tbl.setColumnMeta(colKey, tableMeta[tMeta]);
}
var i = 0;
rawTable.forEach(function(item) {
var row = new recoil.structs.table.MutableTableRow(opt_ordered === true ? i : undefined);
for (var tMeta in tableMeta) {
var colKey = tableMeta[tMeta].key;
row.set(colKey, item[tMeta]);
}
tbl.addRow(row);
i++;
});
return tbl.freeze();
};
/**
*
* @param {Object} tableMeta
* @return {Object}
* @private
*/
recoil.structs.table.Table.extractKeys_ = function(tableMeta) {
var primaryKeys = [];
var otherKeys = [];
for (var obj in tableMeta) {
if (tableMeta.hasOwnProperty(obj)) {
var val = tableMeta[obj];
if (val.hasOwnProperty('primary')) {
primaryKeys.push(val);
}
else {
otherKeys.push(val.key);
}
}
}
/**
* @suppress {missingProperties}
* @param {?} a
* @param {?} b
* @return {number}
*/
var comp = function(a, b) {
return a.primary - b.primary;
};
primaryKeys.sort(comp);
return {primaryKeys: recoil.structs.table.Table.getColumnKeys_(primaryKeys),
otherKeys: otherKeys};
};
/**
* @private
* @param {Array<Object>} array
* @return {!Array<!recoil.structs.table.ColumnKey>}
*/
recoil.structs.table.Table.getColumnKeys_ = function(array) {
var res = [];
for (var i = 0; i < array.length; i++) {
res.push(array[i].key);
}
return res;
};
/**
* @param {!recoil.structs.table.MutableTableRow=} opt_tableRow
* @constructor
* @implements {recoil.structs.table.TableRowInterface}
*/
recoil.structs.table.TableRow = function(opt_tableRow) {
this.cells_ = {};
this.cells_[recoil.structs.table.ColumnKey.ROW_META] = new recoil.structs.table.TableCell(undefined, {});
this.pos_ = undefined;
if (opt_tableRow !== undefined) {
for (var key in opt_tableRow.orig_) {
this.cells_[key] = opt_tableRow.orig_[key];
}
for (key in opt_tableRow.changed_) {
this.cells_[key] = opt_tableRow.changed_[key];
}
this.pos_ = opt_tableRow.pos();
}
};
/**
* @private
* @param {function (!recoil.structs.table.TableRow, !recoil.structs.table.TableRow):number} comparator
* @return {function (!recoil.structs.table.TableRow, !recoil.structs.table.TableRow):number}
*/
recoil.structs.table.TableRow.positionComparator_ = function(comparator) {
return function(x, y) {
if (x.pos() === undefined && y.pos() === undefined) {
return comparator(x, y);
}
if (x.pos() === undefined || y.pos() === undefined) {
return x.pos() === undefined ? -1 : 1;
}
var res = x.pos() - y.pos();
if (res === 0) {
return comparator(x, y);
}
return res;
};
};
/**
* checks to see if the values are equal ignoring meta data
* @param {?} that
* @return {boolean}
*/
recoil.structs.table.TableRow.prototype.valuesEqual = function(that) {
if (!(that instanceof recoil.structs.table.TableRow)) {
return false;
}
var equal = true;
var me = this;
this.forEachColumn(function(col, cell) {
if (!that.cells_.hasOwnProperty(col) || !that.cells_[col]) {
equal = false;
return true;
}
if (!recoil.util.object.isEqual(cell.getValue(), that.cells_[col].getValue())) {
equal = false;
return true;
}
return false;
});
that.forEachColumn(function(col, cell) {
if (!me.cells_.hasOwnProperty(col)) {
equal = false;
return true;
}
return false;
});
return equal;
};
/**
* @return {number|undefined}
*/
recoil.structs.table.TableRow.prototype.pos = function() {
return this.pos_;
};
/**
* Get the value and meta data from the cell
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @return {recoil.structs.table.TableCell<CT>}
*/
recoil.structs.table.TableRow.prototype.getCell = function(column) {
var res = this.cells_[column];
return res === undefined ? null : res;
};
/**
* Get the value and meta data from the cell
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @return {!Object}
*/
recoil.structs.table.TableRow.prototype.getCellMeta = function(column) {
var res = this.getCell(column);
return res ? res.getMeta() : {};
};
/**
* Get the value and meta data from the cell
* @template CT
* @return {!Object}
*/
recoil.structs.table.TableRow.prototype.getMeta = function() {
var res = this.cells_[recoil.structs.table.ColumnKey.ROW_META];
return res === undefined ? {} : res.getMeta();
};
/**
* @param {function(string,!recoil.structs.table.TableCell)} func
*/
recoil.structs.table.TableRow.prototype.forEachColumn = function(func) {
var metaCol = recoil.structs.table.ColumnKey.ROW_META.toString();
for (var col in this.cells_) {
if (metaCol !== col) {
if (func(col, this.cells_[col])) {
return;
}
}
}
};
/**
* Gets only the value from the cell
* @template CT
* @param {recoil.structs.table.ColumnKey<CT>} column
* @return {CT}
*/
recoil.structs.table.TableRow.prototype.get = function(column) {
var val = this.cells_[column];
return val === undefined ? null : val.getValue();
};
/**
* sets the cell and returns a new row, this row is unmodified
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @param {CT} value
* @return {!recoil.structs.table.TableRow}
*/
recoil.structs.table.TableRow.prototype.set = function(column, value) {
var mutable = new recoil.structs.table.MutableTableRow(this.pos(), this);
mutable.set(column, value);
return mutable.freeze();
};
/**
* sets the cell and returns a new row, this row is unmodified
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @param {!recoil.structs.table.TableCell<CT>} value
* @return {recoil.structs.table.TableRow}
*/
recoil.structs.table.TableRow.prototype.setCell = function(column, value) {
var mutable = new recoil.structs.table.MutableTableRow(this.pos(), this);
mutable.setCell(column, value);
return mutable.freeze();
};
/**
* @param {...*} var_args
* @return {recoil.structs.table.MutableTableRow}
*/
recoil.structs.table.TableRow.create = function(var_args) {
var mutableRow = new recoil.structs.table.MutableTableRow();
for (var i = 0; i < arguments.length; i += 2) {
mutableRow.set(arguments[i], arguments[i + 1]);
}
return mutableRow;
};
/**
* @param {number} pos the position of the row
* @param {...*} var_args
* @return {recoil.structs.table.MutableTableRow}
*/
recoil.structs.table.TableRow.createOrdered = function(pos, var_args) {
var mutableRow = new recoil.structs.table.MutableTableRow(pos);
for (var i = 0; i < arguments.length; i += 2) {
mutableRow.set(arguments[i], arguments[i + 1]);
}
return mutableRow;
};
/**
* @return {!Object}
*/
recoil.structs.table.TableRow.prototype.getRowMeta = function() {
var cell = this.getCell(recoil.structs.table.ColumnKey.ROW_META);
return cell ? cell.getMeta() : {};
};
/**
* removes all columsn not in the columns parameter
* @param {Array<!recoil.structs.table.ColumnKey>} columns
* @return {!recoil.structs.table.TableRow}
*/
recoil.structs.table.TableRow.prototype.keepColumns = function(columns) {
var mutable = new recoil.structs.table.MutableTableRow(this.pos_);
var me = this;
columns.forEach(function(col) {
if (me.hasColumn(col)) {
var val = me.getCell(col);
if (val !== null) {
mutable.setCell(col, val);
}
}
});
if (me.hasColumn(recoil.structs.table.ColumnKey.ROW_META)) {
mutable.setRowMeta(me.getRowMeta());
}
return mutable.freeze();
};
/**
* @template CT
* @param {recoil.structs.table.ColumnKey<CT>} column
* @return {CT}
*/
recoil.structs.table.TableRow.prototype.hasColumn = function(column) {
return this.cells_[column] !== undefined;
};
/**
* @return {!recoil.structs.table.MutableTableRow}
*/
recoil.structs.table.TableRow.prototype.unfreeze = function() {
return new recoil.structs.table.MutableTableRow(undefined, this);
};
/**
* A table row that can be changed. Use this to make a row then
* change it to a normal row
* @constructor
* @implements {recoil.structs.table.TableRowInterface}
* @param {number=} opt_position if the row is order specify this
* @param {recoil.structs.table.TableRow=} opt_immutable
*/
recoil.structs.table.MutableTableRow = function(opt_position, opt_immutable) {
if (opt_immutable) {
this.orig_ = opt_immutable.cells_;
this.pos_ = opt_position === undefined ? opt_immutable.pos() : opt_position;
}
else {
this.orig_ = {};
this.pos_ = opt_position === undefined ? undefined : opt_position;
}
this.changed_ = {};
};
/**
* Get the value and meta data from the cell
* @template CT
* @return {!Object}
*/
recoil.structs.table.MutableTableRow.prototype.getMeta = function() {
return this.getRowMeta();
};
/**
* @param {function(string,!recoil.structs.table.TableCell)} func
* if the function returns true the loop exist
*/
recoil.structs.table.MutableTableRow.prototype.forEachColumn = function(func) {
var metaCol = recoil.structs.table.ColumnKey.ROW_META.toString();
for (var col in this.changed_) {
if (metaCol !== col) {
if (func(col, this.changed_[col])) {
return;
}
}
}
for (col in this.orig_) {
if (metaCol !== col && !this.changed_[col]) {
if (func(col, this.orig_[col])) {
return;
}
}
}
};
/**
* @param {!recoil.structs.table.TableRowInterface} row
*/
recoil.structs.table.MutableTableRow.prototype.addColumns = function(row) {
var me = this;
row.forEachColumn(function(col, cell) {
me.changed_[col] = cell;
});
};
/**
* @param {?} that
* @return {boolean}
*/
recoil.structs.table.MutableTableRow.prototype.equals = function(that) {
if (!(that instanceof recoil.structs.table.MutableTableRow)) {
return false;
}
return recoil.util.object.isEqual(this.freeze(), that.freeze());
};
/**
* checks to see if the values are equal ignoring meta data
* @param {?} that
* @return {boolean}
*/
recoil.structs.table.MutableTableRow.prototype.valuesEqual = function(that) {
if (!(that instanceof recoil.structs.table.MutableTableRow)) {
return false;
}
return this.freeze().valuesEqual(that.freeze());
};
/**
* @return {number|undefined}
*/
recoil.structs.table.MutableTableRow.prototype.pos = function() {
return this.pos_;
};
/**
* @param {number|undefined} pos
*/
recoil.structs.table.MutableTableRow.prototype.setPos = function(pos) {
this.pos_ = pos;
};
/**
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @return {recoil.structs.table.TableCell<CT>}
*/
recoil.structs.table.MutableTableRow.prototype.getCell = function(column) {
if (this.changed_.hasOwnProperty(column)) {
return this.changed_[column];
}
var res = this.orig_[column];
if (res === undefined) {
return null;
}
return this.orig_[column];
};
/**
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @return {!Object}
*/
recoil.structs.table.MutableTableRow.prototype.getCellMeta = function(column) {
var res = this.getCell(column);
return res ? res.getMeta() : {};
};
/**
* @param {!Object} meta
*/
recoil.structs.table.MutableTableRow.prototype.setRowMeta = function(meta) {
var cell = this.getCell(recoil.structs.table.ColumnKey.ROW_META);
if (cell == null) {
cell = new recoil.structs.table.TableCell(undefined, {});
}
this.setCell(recoil.structs.table.ColumnKey.ROW_META, cell.setMeta(meta));
};
/**
* @param {!Object} meta
*/
recoil.structs.table.MutableTableRow.prototype.addRowMeta = function(meta) {
var newMeta = {};
recoil.util.object.addProps(newMeta, this.getRowMeta(), meta);
this.setRowMeta(newMeta);
};
/**
* @return {!Object}
*/
recoil.structs.table.MutableTableRow.prototype.getRowMeta = function() {
var cell = this.getCell(recoil.structs.table.ColumnKey.ROW_META);
return cell ? cell.getMeta() : {};
};
/**
* converts a mutable table row to immutable table row
* @return {!recoil.structs.table.TableRow}
*/
recoil.structs.table.MutableTableRow.prototype.freeze = function() {
return new recoil.structs.table.TableRow(this);
};
/**
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} column
* @return {CT}
*/
recoil.structs.table.MutableTableRow.prototype.get = function(column) {
var res = this.getCell(column);
return res === null ? null : res.getValue();
};
/**
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} columnKey
* @param {!recoil.structs.table.TableCell<CT>} val the data and meta data of the cell
*/
recoil.structs.table.MutableTableRow.prototype.setCell = function(columnKey, val) {
this.changed_[columnKey] = val;
};
/**
* a helper that just transfers the columns from the source rows
* into this row
* @param {!Array<!recoil.structs.table.ColumnKey>} columnKeys
* @param {!recoil.structs.table.TableRowInterface} src
*/
recoil.structs.table.MutableTableRow.prototype.transfer = function(columnKeys, src) {
for (var i = 0; i < columnKeys.length; i++) {
var col = columnKeys[i];
this.set(col, src.get(col));
}
};
/**
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} columnKey
* @param {CT} val the data of the cell
* @param {Object=} opt_meta
*/
recoil.structs.table.MutableTableRow.prototype.set = function(columnKey, val, opt_meta) {
var old = this.getCell(columnKey);
if (old === null) {
old = new recoil.structs.table.TableCell(undefined);
}
if (opt_meta) {
this.setCell(columnKey, new recoil.structs.table.TableCell(
columnKey.castTo(val), opt_meta));
}
else {
this.setCell(columnKey, old.setValue(columnKey.castTo(val)));
}
};
/**
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} columnKey
* @param {!Object} val the data of the cell
*/
recoil.structs.table.MutableTableRow.prototype.setCellMeta = function(columnKey, val) {
var old = this.getCell(columnKey);
if (old === null) {
old = new recoil.structs.table.TableCell(undefined);
}
this.setCell(columnKey, old.setMeta(val));
};
/**
* @template CT
* @param {!recoil.structs.table.ColumnKey<CT>} columnKey
* @param {!Object} val the data of the cell
*/
recoil.structs.table.MutableTableRow.prototype.addCellMeta = function(columnKey, val) {
var old = this.getCell(columnKey);
if (old === null) {
old = new recoil.structs.table.TableCell(undefined);
}
this.setCell(columnKey, old.addMeta(val));
};
/**
*
* @template T
* @param {T} value
* @param {Object=} opt_meta
* @constructor
*/
recoil.structs.table.TableCell = function(value, opt_meta) {
this.value_ = value;
this.meta_ = opt_meta;
};
/**
* @return {!Object}
*/
recoil.structs.table.TableCell.prototype.getMeta = function() {
return !this.meta_ ? {} : goog.object.clone(this.meta_);
};
/**
* @return {T}
*/
recoil.structs.table.TableCell.prototype.getValue = function() {
return this.value_;
};
/**
* returns a new cell with the meta data set
* @param {!Object} meta
* @return {!recoil.structs.table.TableCell<T>}
*/
recoil.structs.table.TableCell.prototype.setMeta = function(meta) {
return new recoil.structs.table.TableCell(this.value_, meta);
};
/**
* returns a new cell with the meta data set
* @param {!Object} meta
* @return {!recoil.structs.table.TableCell<T>}
*/
recoil.structs.table.TableCell.prototype.addMeta = function(meta) {
var newMeta = goog.object.clone(this.getMeta());
recoil.util.object.addProps(newMeta, meta);
return new recoil.structs.table.TableCell(this.value_, newMeta);
};
/**
* returns a new cell with the data set, keeps the metadata
* @param {T} value
* @return {!recoil.structs.table.TableCell<T>}
*/
recoil.structs.table.TableCell.prototype.setValue = function(value) {
return new recoil.structs.table.TableCell(value, this.meta_);
};
| evaks/recoil | src/structs/table/table.js | JavaScript | apache-2.0 | 58,760 |
/*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. 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.
*/
/*
* D E F A U L T A P P L I C A T I O N
*
* Simple http response server to display default.html
*
*/
console.log("STARTING DEFAULT APPLICATION");
var fs = require('fs');
var path = require('path');
var server = io.nodekit.electro.protocol.createServer('node:', function (request, response) {
console.log("EXECUTING DEFAULT APPLICATION");
var file = path.resolve(__dirname, 'default.html');
fs.readFile(file, function read(err, content) {
if (err) {
console.log(err);
response.writeHead(500, { 'Content-Type': 'text/html' });
response.end('<html><body>An internal server error occurred</body>', 'utf-8');
} else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
}
});
});
server.listen();
console.log("Server running"); | nodekit-io/nodekit-darwin | src/nodekit/NKElectro/NK_ElectroHost/www/default/index.js | JavaScript | apache-2.0 | 2,049 |
define({
root:({
mode: "Mode",
saveToPortal: "Save to Portal",
saveToDisk: "Save To Disk",
title: "Title",
description: "Description",
tags: "Tags",
defineExtent: "Define Extent",
submit: "Submit",
pixelSize: "Pixel Size",
outputSpatialReference: "Output Spatial Reference",
currentRenderer: "Current Renderer",
note: "Note",
currentRendererChecked: "If Current Renderer is checked, the rendering",
originalDataValues: "is exported, else the original data values",
exported: "will be exported.",
export: "Export",
exportImage: "Export Image",
layerSaved: "Layer saved.",
error: "Error! ",
errorNotification: "Error! No Imagery Layer visible on the map.",
utmZone: "WGS84 UTM Zone ",
WKID: "WKID : ",
webMercatorAs: "WebMercatorAS",
default: "Default",
pixelSizeRestricted: "PixelSize of export is restricted to ",
thisExtent: " for this extent.",
errorPixelSize: "Error! No Imagery Layer visible on the map.",
layer: "Layer",
exportLayerMsg: "No visible imagery layers on the map."
}),
"ar": 1,
"fr": 1
}); | Esri/WAB-Image-Services-Widgets | imagery_widgets/ISExport/nls/strings.js | JavaScript | apache-2.0 | 1,084 |
var express= require('express'),
path= require('path'),
bodyParser = require('body-parser'),
routes = require('./server/config/routes'),
app= express();
app.use(bodyParser.json());
routes(app);
app.use('/', express.static(path.join(__dirname, 'client')));
app.listen(8080);
console.log('listening on 8080');
| aaaristo/angular-on-fire | app.js | JavaScript | apache-2.0 | 329 |
/* global describe, beforeEach, it */
const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const fse = require('fs-extra');
const expectedFiles = {
eurekaregistry: [
'./k8s/registry/jhipster-registry.yml',
'./k8s/registry/application-configmap.yml'
],
consulregistry: [
'./k8s/registry/consul.yml',
'./k8s/registry/consul-config-loader.yml',
'./k8s/registry/application-configmap.yml'
],
jhgate: [
'./k8s/jhgate/jhgate-deployment.yml',
'./k8s/jhgate/jhgate-mysql.yml',
'./k8s/jhgate/jhgate-service.yml'
],
jhgateingress: [
'./k8s/jhgate/jhgate-deployment.yml',
'./k8s/jhgate/jhgate-mysql.yml',
'./k8s/jhgate/jhgate-service.yml',
'./k8s/jhgate/jhgate-ingress.yml'
],
customnamespace: [
'./k8s/namespace.yml'
],
jhconsole: [
'./k8s/console/jhipster-console.yml',
'./k8s/console/jhipster-elasticsearch.yml',
'./k8s/console/jhipster-logstash.yml',
'./k8s/console/jhipster-dashboard-console.yml',
'./k8s/console/jhipster-zipkin.yml'
],
msmysql: [
'./k8s/msmysql/msmysql-deployment.yml',
'./k8s/msmysql/msmysql-mysql.yml',
'./k8s/msmysql/msmysql-service.yml'
],
mspsql: [
'./k8s/mspsql/mspsql-deployment.yml',
'./k8s/mspsql/mspsql-postgresql.yml',
'./k8s/mspsql/mspsql-service.yml',
'./k8s/mspsql/mspsql-elasticsearch.yml'
],
msmongodb: [
'./k8s/msmongodb/msmongodb-deployment.yml',
'./k8s/msmongodb/msmongodb-mongodb.yml',
'./k8s/msmongodb/msmongodb-service.yml'
],
msmariadb: [
'./k8s/msmariadb/msmariadb-deployment.yml',
'./k8s/msmariadb/msmariadb-mariadb.yml',
'./k8s/msmariadb/msmariadb-service.yml'
],
monolith: [
'./k8s/samplemysql/samplemysql-deployment.yml',
'./k8s/samplemysql/samplemysql-mysql.yml',
'./k8s/samplemysql/samplemysql-service.yml',
'./k8s/samplemysql/samplemysql-elasticsearch.yml'
],
kafka: [
'./k8s/samplekafka/samplekafka-deployment.yml',
'./k8s/samplekafka/samplekafka-mysql.yml',
'./k8s/samplekafka/samplekafka-service.yml',
'./k8s/messagebroker/kafka.yml'
],
prometheusmonit: [
'./k8s/monitoring/jhipster-prometheus-crd.yml',
'./k8s/monitoring/jhipster-prometheus-cr.yml',
'./k8s/monitoring/jhipster-grafana.yml',
'./k8s/monitoring/jhipster-grafana-dashboard.yml'
]
};
describe('JHipster Kubernetes Sub Generator', () => {
describe('only gateway', () => {
beforeEach((done) => {
helpers
.run(require.resolve('../generators/kubernetes'))
.inTmpDir((dir) => {
fse.copySync(path.join(__dirname, './templates/compose/'), dir);
})
.withOptions({ skipChecks: true })
.withPrompts({
composeApplicationType: 'microservice',
directoryPath: './',
chosenApps: [
'01-gateway'
],
adminPassword: 'meetup',
dockerRepositoryName: 'jhipsterrepository',
dockerPushCommand: 'docker push',
kubernetesNamespace: 'jhipsternamespace',
jhipsterConsole: false,
kubernetesServiceType: 'LoadBalancer',
clusteredDbApps: []
})
.on('end', done);
});
it('creates expected registry files and content', () => {
assert.file(expectedFiles.eurekaregistry);
assert.fileContent('./k8s/registry/jhipster-registry.yml', /# base64 encoded "meetup"/);
});
it('creates expected gateway files and content', () => {
assert.file(expectedFiles.jhgate);
assert.fileContent('./k8s/jhgate/jhgate-deployment.yml', /image: jhipsterrepository\/jhgate/);
assert.fileContent('./k8s/jhgate/jhgate-deployment.yml', /jhipsternamespace.svc.cluster/);
});
});
describe('gateway and mysql microservice', () => {
beforeEach((done) => {
helpers
.run(require.resolve('../generators/kubernetes'))
.inTmpDir((dir) => {
fse.copySync(path.join(__dirname, './templates/compose/'), dir);
})
.withOptions({ skipChecks: true })
.withPrompts({
composeApplicationType: 'microservice',
directoryPath: './',
chosenApps: [
'01-gateway',
'02-mysql'
],
dockerRepositoryName: 'jhipster',
dockerPushCommand: 'docker push',
kubernetesNamespace: 'default',
jhipsterConsole: false,
kubernetesServiceType: 'LoadBalancer',
clusteredDbApps: []
})
.on('end', done);
});
it('creates expected registry files', () => {
assert.file(expectedFiles.eurekaregistry);
});
it('creates expected gateway files', () => {
assert.file(expectedFiles.jhgate);
});
it('creates expected mysql files', () => {
assert.file(expectedFiles.msmysql);
});
});
describe('mysql microservice with custom namespace and jhipster-console (with zipkin)', () => {
beforeEach((done) => {
helpers
.run(require.resolve('../generators/kubernetes'))
.inTmpDir((dir) => {
fse.copySync(path.join(__dirname, './templates/compose/'), dir);
})
.withOptions({ skipChecks: true })
.withPrompts({
composeApplicationType: 'microservice',
directoryPath: './',
chosenApps: [
'02-mysql'
],
dockerRepositoryName: 'jhipster',
dockerPushCommand: 'docker push',
kubernetesNamespace: 'mynamespace',
monitoring: 'elk',
jhipsterConsole: true,
kubernetesServiceType: 'LoadBalancer',
clusteredDbApps: []
})
.on('end', done);
});
it('creates expected registry files', () => {
assert.file(expectedFiles.eurekaregistry);
});
it('creates expected mysql files', () => {
assert.file(expectedFiles.msmysql);
});
it('creates expected jhipster-console files', () => {
assert.file(expectedFiles.jhconsole);
});
it('creates expected namespace file', () => {
assert.file(expectedFiles.customnamespace);
});
});
describe('gateway and ingress', () => {
beforeEach((done) => {
helpers
.run(require.resolve('../generators/kubernetes'))
.inTmpDir((dir) => {
fse.copySync(path.join(__dirname, './templates/compose/'), dir);
})
.withOptions({ skipChecks: true })
.withPrompts({
composeApplicationType: 'microservice',
directoryPath: './',
chosenApps: [
'01-gateway'
],
dockerRepositoryName: 'jhipster',
dockerPushCommand: 'docker push',
kubernetesNamespace: 'default',
kubernetesServiceType: 'Ingress',
ingressDomain: 'example.com',
clusteredDbApps: []
})
.on('end', done);
});
it('creates expected registry files', () => {
assert.file(expectedFiles.eurekaregistry);
});
it('creates expected gateway files', () => {
assert.file(expectedFiles.jhgate);
});
it('creates expected ingress files', () => {
assert.file(expectedFiles.jhgateingress);
});
});
describe('MySQL and PostgreSQL microservices without gateway', () => {
beforeEach((done) => {
helpers
.run(require.resolve('../generators/kubernetes'))
.inTmpDir((dir) => {
fse.copySync(path.join(__dirname, './templates/compose/'), dir);
})
.withOptions({ skipChecks: true })
.withPrompts({
composeApplicationType: 'microservice',
directoryPath: './',
chosenApps: [
'02-mysql',
'03-psql'
],
dockerRepositoryName: 'jhipster',
dockerPushCommand: 'docker push',
kubernetesNamespace: 'default',
jhipsterConsole: false,
kubernetesServiceType: 'LoadBalancer',
clusteredDbApps: []
})
.on('end', done);
});
it('creates expected registry files', () => {
assert.file(expectedFiles.eurekaregistry);
});
it('doesn\'t creates gateway files', () => {
assert.noFile(expectedFiles.jhgate);
});
it('creates expected mysql files', () => {
assert.file(expectedFiles.msmysql);
});
it('creates expected psql files', () => {
assert.file(expectedFiles.mspsql);
});
});
describe('gateway, mysql, psql, mongodb, mariadb microservices', () => {
beforeEach((done) => {
helpers
.run(require.resolve('../generators/kubernetes'))
.inTmpDir((dir) => {
fse.copySync(path.join(__dirname, './templates/compose/'), dir);
})
.withOptions({ skipChecks: true })
.withPrompts({
composeApplicationType: 'microservice',
directoryPath: './',
chosenApps: [
'01-gateway',
'02-mysql',
'03-psql',
'04-mongo',
'07-mariadb'
],
dockerRepositoryName: 'jhipster',
dockerPushCommand: 'docker push',
kubernetesNamespace: 'default',
jhipsterConsole: false,
kubernetesServiceType: 'LoadBalancer',
clusteredDbApps: []
})
.on('end', done);
});
it('creates expected registry files', () => {
assert.file(expectedFiles.eurekaregistry);
});
it('creates expected gateway files', () => {
assert.file(expectedFiles.jhgate);
});
it('creates expected mysql files', () => {
assert.file(expectedFiles.msmysql);
});
it('creates expected psql files', () => {
assert.file(expectedFiles.mspsql);
});
it('creates expected mongodb files', () => {
assert.file(expectedFiles.msmongodb);
});
it('creates expected mariadb files', () => {
assert.file(expectedFiles.msmariadb);
});
});
describe('monolith application', () => {
beforeEach((done) => {
helpers
.run(require.resolve('../generators/kubernetes'))
.inTmpDir((dir) => {
fse.copySync(path.join(__dirname, './templates/compose/'), dir);
})
.withOptions({ skipChecks: true })
.withPrompts({
composeApplicationType: 'monolith',
directoryPath: './',
chosenApps: [
'08-monolith'
],
dockerRepositoryName: 'jhipster',
dockerPushCommand: 'docker push',
kubernetesNamespace: 'default',
jhipsterConsole: false,
kubernetesServiceType: 'LoadBalancer',
clusteredDbApps: []
})
.on('end', done);
});
it('doesn\'t creates registry files', () => {
assert.noFile(expectedFiles.eurekaregistry);
});
it('creates expected default files', () => {
assert.file(expectedFiles.monolith);
});
});
describe('Kafka application', () => {
beforeEach((done) => {
helpers
.run(require.resolve('../generators/kubernetes'))
.inTmpDir((dir) => {
fse.copySync(path.join(__dirname, './templates/compose/'), dir);
})
.withOptions({ skipChecks: true })
.withPrompts({
composeApplicationType: 'monolith',
directoryPath: './',
chosenApps: [
'09-kafka'
],
dockerRepositoryName: 'jhipster',
dockerPushCommand: 'docker push',
kubernetesNamespace: 'default',
jhipsterConsole: false,
kubernetesServiceType: 'LoadBalancer',
clusteredDbApps: []
})
.on('end', done);
});
it('doesn\'t creates registry files', () => {
assert.noFile(expectedFiles.eurekaregistry);
});
it('creates expected default files', () => {
assert.file(expectedFiles.kafka);
});
});
describe('mysql microservice with custom namespace and jhipster prometheus monitoring', () => {
beforeEach((done) => {
helpers
.run(require.resolve('../generators/kubernetes'))
.inTmpDir((dir) => {
fse.copySync(path.join(__dirname, './templates/compose/'), dir);
})
.withOptions({ skipChecks: true })
.withPrompts({
composeApplicationType: 'microservice',
directoryPath: './',
chosenApps: [
'02-mysql'
],
dockerRepositoryName: 'jhipster',
dockerPushCommand: 'docker push',
kubernetesNamespace: 'mynamespace',
monitoring: 'prometheus',
kubernetesServiceType: 'LoadBalancer'
})
.on('end', done);
});
it('creates expected registry files', () => {
assert.file(expectedFiles.eurekaregistry);
});
it('creates expected mysql files', () => {
assert.file(expectedFiles.msmysql);
});
it('creates expected prometheus files', () => {
assert.file(expectedFiles.prometheusmonit);
});
it('creates expected namespace file', () => {
assert.file(expectedFiles.customnamespace);
});
});
});
| Tcharl/generator-jhipster | test/kubernetes.spec.js | JavaScript | apache-2.0 | 15,547 |
/**
*
* Online store PWA sample.
* Copyright 2017 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
*
* https://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
*
*/
import initApp from './app.js';
import {instance as router} from './router';
initApp();
router.loadCurrentRoute();
| GoogleChromeLabs/sample-pie-shop | src/client/js/app-main.js | JavaScript | apache-2.0 | 779 |
exports.definition = {
config: {
columns: {
title: "text",
attachments: "text"
},
adapter: {
type: "sql",
collection_name: "works",
idAttribute: "_id"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
initialize: function(data) {
data && data.cover && data.cover.thumbs && data.cover.thumbs.m && this.set("cover_m", data.cover.thumbs.m);
return this;
}
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {});
return Collection;
}
};
var Alloy = require("alloy"), _ = require("alloy/underscore")._, model, collection;
model = Alloy.M("works", exports.definition, []);
collection = Alloy.C("works", exports.definition, model);
exports.Model = model;
exports.Collection = collection; | chrisjbaik/seelio-uploader-titanium | Resources/android/alloy/models/Works.js | JavaScript | apache-2.0 | 953 |
/**
* @license Copyright 2018 The Lighthouse Authors. 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.
*/
'use strict';
module.exports = {
collectCoverage: false,
coverageReporters: ['none'],
collectCoverageFrom: [
'**/lighthouse-core/**/*.js',
'**/lighthouse-cli/**/*.js',
'**/lighthouse-viewer/**/*.js',
],
coveragePathIgnorePatterns: [
'/test/',
'/scripts/',
],
setupFilesAfterEnv: ['./lighthouse-core/test/test-utils.js'],
testEnvironment: 'node',
testMatch: [
'**/lighthouse-core/**/*-test.js',
'**/lighthouse-cli/**/*-test.js',
'**/lighthouse-viewer/**/*-test.js',
'**/lighthouse-viewer/**/*-test-pptr.js',
'**/clients/test/**/*-test.js',
'**/docs/**/*.test.js',
],
};
| umaar/lighthouse | jest.config.js | JavaScript | apache-2.0 | 1,238 |
/**
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
*/
define(['require', 'elementUtils'],
function (require, ElementUtils) {
/**
* @class Trigger
* @constructor
* @class Trigger Creates a Trigger
* @param {Object} options Rendering options for the view
*/
var Trigger = function (options) {
/*
Data storing structure as follows
id*: '',
previousCommentSegment:'',
name*: '',
at*: ‘’,
atEvery*: '',
annotationList: [annotation1, annotation2, ...]
*/
if (options !== undefined) {
this.id = options.id;
this.previousCommentSegment = options.previousCommentSegment;
this.name = options.name;
this.criteria = options.criteria;
this.criteriaType = options.criteriaType;
}
this.annotationList = [];
};
Trigger.prototype.addAnnotation = function (annotation) {
this.annotationList.push(annotation);
};
Trigger.prototype.clearAnnotationList = function () {
ElementUtils.prototype.removeAllElements(this.annotationList);
};
Trigger.prototype.getId = function () {
return this.id;
};
Trigger.prototype.getName = function () {
return this.name;
};
Trigger.prototype.getCriteria = function () {
return this.criteria;
};
Trigger.prototype.getCriteriaType = function () {
return this.criteriaType;
};
Trigger.prototype.getAnnotationList = function () {
return this.annotationList;
};
Trigger.prototype.setId = function (id) {
this.id = id;
};
Trigger.prototype.setName = function (name) {
this.name = name;
};
Trigger.prototype.setCriteria = function (criteria) {
this.criteria = criteria;
};
Trigger.prototype.setCriteriaType = function (criteriaType) {
this.criteriaType = criteriaType;
};
Trigger.prototype.setAnnotationList = function (annotationList) {
this.annotationList = annotationList;
};
return Trigger;
});
| wso2/carbon-analytics | components/org.wso2.carbon.siddhi.editor.core/src/main/resources/web/editor/js/design-view/elements/definitions/trigger.js | JavaScript | apache-2.0 | 2,459 |
var express = require('express');
var app = express();
var request = require("request");
var bodyParser = require('body-parser');
app.use(express.static(__dirname+"/public"));
app.use(express.static(__dirname+"/bower_components"));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/getNames', function(req, res) {
request({
url: 'http://localhost:8080/names.min.json',
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200)
res.send(body);
});
});
app.use(function(req, res) {
// Use res.sendfile, as it streams instead of reading the file into memory.
res.sendFile(__dirname + '/public/index.html');
});
app.listen(666);
console.log(__dirname);
console.log('running server at 666');
| deadkff01/fbeventgender | server.js | JavaScript | apache-2.0 | 953 |
/*! UIkit 2.27.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
(function (UI) {
"use strict";
UI.component('cover', {
defaults: {
automute: true
},
boot: function () {
// auto init
UI.ready(function (context) {
UI.$('[data-uk-cover]', context).each(function () {
var ele = UI.$(this);
if (!ele.data('cover')) {
var plugin = UI.cover(ele, UI.Utils.options(ele.attr('data-uk-cover')));
}
});
});
},
init: function () {
this.parent = this.element.parent();
UI.$win.on('load resize orientationchange', UI.Utils.debounce(function () {
this.check();
}.bind(this), 100));
this.on('display.uk.check', function (e) {
if (this.element.is(':visible')) this.check();
}.bind(this));
this.check();
if (this.element.is('iframe') && this.options.automute) {
var src = this.element.attr('src');
this.element.attr('src', '').on('load', function () {
this.contentWindow.postMessage('{ "event": "command", "func": "mute", "method":"setVolume", "value":0}', '*');
}).attr('src', [src, (src.indexOf('?') > -1 ? '&' : '?'), 'enablejsapi=1&api=1'].join(''));
}
},
check: function () {
this.element.css({width: '', height: ''});
this.dimension = {w: this.element.width(), h: this.element.height()};
if (this.element.attr('width') && !isNaN(this.element.attr('width'))) {
this.dimension.w = this.element.attr('width');
}
if (this.element.attr('height') && !isNaN(this.element.attr('height'))) {
this.dimension.h = this.element.attr('height');
}
this.ratio = this.dimension.w / this.dimension.h;
var w = this.parent.width(), h = this.parent.height(), width, height;
// if element height < parent height (gap underneath)
if ((w / this.ratio) < h) {
width = Math.ceil(h * this.ratio);
height = h;
// element width < parent width (gap to right)
} else {
width = w;
height = Math.ceil(w / this.ratio);
}
this.element.css({width: width, height: height});
}
});
})(UIkit);
| zuocaijian/HiPythonWeb | www/static/js/core/cover.js | JavaScript | apache-2.0 | 2,590 |
import svelte from 'rollup-plugin-svelte';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import copy from 'rollup-plugin-cpy'
const production = !process.env.ROLLUP_WATCH;
// 1. If in production, we build the App.svelte component that would be injected into the parent application host
// 2. If in development, we build the stand alone main.js entry which would be used inside stand alone index.html
const inputFile = production ? 'src/App.svelte' : 'src/main.js';
// 1. If in production, we build an EcmaScript bundle.mjs module
// 2. If in development, we build a standard Javascript bundle.js
const outputFile = production ? 'public/bundle.mjs' : 'public/bundle.js';
export default {
input: inputFile,
output: {
sourcemap: true,
// In production, we build an EcmaScript module (ESM)
// In development, we build an Immediately Invoked Function Expression (IIFE)
format: production ? 'esm' : 'iife',
name: 'app',
file: outputFile
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file — better for performance
css: css => {
css.write('public/bundle.css');
}
}),
// If you have external dependencies installed from
// npm, you'll most likely need these plugins. In
// some cases you'll need additional configuration —
// consult the documentation for details:
// https://github.com/rollup/rollup-plugin-commonjs
resolve(),
commonjs(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser(),
// TODO! Only copy at build time
production && copy({
// Copy EcmaScript modules and dependent resources from public folder
files: ['public/*.mjs', 'public/*.mjs.map', 'public/bundle.css', 'public/*.css.map'],
// To external folder static-apps from where the parent application host can load it
dest: '../../static-apps/hello-world',
options: {
verbose: true
}
})
]
};
| rzvdaniel/eCameleon | eCameleon.Web/apps/hello-world/rollup.config.js | JavaScript | apache-2.0 | 2,305 |
const Long = require('long');
const User = require('./User');
const Role = require('./Role');
const Emoji = require('./Emoji');
const Invite = require('./Invite');
const GuildAuditLogs = require('./GuildAuditLogs');
const Webhook = require('./Webhook');
const { Presence } = require('./Presence');
const GuildChannel = require('./GuildChannel');
const GuildMember = require('./GuildMember');
const VoiceRegion = require('./VoiceRegion');
const Constants = require('../util/Constants');
const Collection = require('../util/Collection');
const Util = require('../util/Util');
const Snowflake = require('../util/Snowflake');
const Permissions = require('../util/Permissions');
const Shared = require('./shared');
const { Error, TypeError } = require('../errors');
/**
* Represents a guild (or a server) on Discord.
* <info>It's recommended to see if a guild is available before performing operations or reading data from it. You can
* check this with `guild.available`.</info>
*/
class Guild {
constructor(client, data) {
/**
* The client that created the instance of the guild
* @name Guild#client
* @type {Client}
* @readonly
*/
Object.defineProperty(this, 'client', { value: client });
/**
* A collection of members that are in this guild. The key is the member's ID, the value is the member
* @type {Collection<Snowflake, GuildMember>}
*/
this.members = new Collection();
/**
* A collection of channels that are in this guild. The key is the channel's ID, the value is the channel
* @type {Collection<Snowflake, GuildChannel>}
*/
this.channels = new Collection();
/**
* A collection of roles that are in this guild. The key is the role's ID, the value is the role
* @type {Collection<Snowflake, Role>}
*/
this.roles = new Collection();
/**
* A collection of presences in this guild
* @type {Collection<Snowflake, Presence>}
*/
this.presences = new Collection();
if (!data) return;
if (data.unavailable) {
/**
* Whether the guild is available to access. If it is not available, it indicates a server outage
* @type {boolean}
*/
this.available = false;
/**
* The Unique ID of the guild, useful for comparisons
* @type {Snowflake}
*/
this.id = data.id;
} else {
this.setup(data);
if (!data.channels) this.available = false;
}
}
/**
* Sets up the guild.
* @param {*} data The raw data of the guild
* @private
*/
setup(data) {
/**
* The name of the guild
* @type {string}
*/
this.name = data.name;
/**
* The hash of the guild icon
* @type {?string}
*/
this.icon = data.icon;
/**
* The hash of the guild splash image (VIP only)
* @type {?string}
*/
this.splash = data.splash;
/**
* The region the guild is located in
* @type {string}
*/
this.region = data.region;
/**
* The full amount of members in this guild as of `READY`
* @type {number}
*/
this.memberCount = data.member_count || this.memberCount;
/**
* Whether the guild is "large" (has more than 250 members)
* @type {boolean}
*/
this.large = Boolean('large' in data ? data.large : this.large);
/**
* An array of guild features
* @type {Object[]}
*/
this.features = data.features;
/**
* The ID of the application that created this guild (if applicable)
* @type {?Snowflake}
*/
this.applicationID = data.application_id;
/**
* The time in seconds before a user is counted as "away from keyboard"
* @type {?number}
*/
this.afkTimeout = data.afk_timeout;
/**
* The ID of the voice channel where AFK members are moved
* @type {?Snowflake}
*/
this.afkChannelID = data.afk_channel_id;
/**
* Whether embedded images are enabled on this guild
* @type {boolean}
*/
this.embedEnabled = data.embed_enabled;
/**
* The verification level of the guild
* @type {number}
*/
this.verificationLevel = data.verification_level;
/**
* The explicit content filter level of the guild
* @type {number}
*/
this.explicitContentFilter = data.explicit_content_filter;
/**
* The timestamp the client user joined the guild at
* @type {number}
*/
this.joinedTimestamp = data.joined_at ? new Date(data.joined_at).getTime() : this.joinedTimestamp;
this.id = data.id;
this.available = !data.unavailable;
this.features = data.features || this.features || [];
if (data.members) {
this.members.clear();
for (const guildUser of data.members) this._addMember(guildUser, false);
}
if (data.owner_id) {
/**
* The user ID of this guild's owner
* @type {Snowflake}
*/
this.ownerID = data.owner_id;
}
if (data.channels) {
this.channels.clear();
for (const channel of data.channels) this.client.dataManager.newChannel(channel, this);
}
if (data.roles) {
this.roles.clear();
for (const role of data.roles) {
const newRole = new Role(this, role);
this.roles.set(newRole.id, newRole);
}
}
if (data.presences) {
for (const presence of data.presences) {
this._setPresence(presence.user.id, presence);
}
}
this._rawVoiceStates = new Collection();
if (data.voice_states) {
for (const voiceState of data.voice_states) {
this._rawVoiceStates.set(voiceState.user_id, voiceState);
const member = this.members.get(voiceState.user_id);
if (member) {
member.serverMute = voiceState.mute;
member.serverDeaf = voiceState.deaf;
member.selfMute = voiceState.self_mute;
member.selfDeaf = voiceState.self_deaf;
member.voiceSessionID = voiceState.session_id;
member.voiceChannelID = voiceState.channel_id;
this.channels.get(voiceState.channel_id).members.set(member.user.id, member);
}
}
}
if (!this.emojis) {
/**
* A collection of emojis that are in this guild. The key is the emoji's ID, the value is the emoji.
* @type {Collection<Snowflake, Emoji>}
*/
this.emojis = new Collection();
for (const emoji of data.emojis) this.emojis.set(emoji.id, new Emoji(this, emoji));
} else {
this.client.actions.GuildEmojisUpdate.handle({
guild_id: this.id,
emojis: data.emojis,
});
}
}
/**
* The timestamp the guild was created at
* @type {number}
* @readonly
*/
get createdTimestamp() {
return Snowflake.deconstruct(this.id).timestamp;
}
/**
* The time the guild was created
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* The time the client user joined the guild
* @type {Date}
* @readonly
*/
get joinedAt() {
return new Date(this.joinedTimestamp);
}
/**
* Gets the URL to this guild's icon
* @param {Object} [options={}] Options for the icon url
* @param {string} [options.format='webp'] One of `webp`, `png`, `jpg`
* @param {number} [options.size=128] One of `128`, '256', `512`, `1024`, `2048`
* @returns {?string}
*/
iconURL({ format, size } = {}) {
if (!this.icon) return null;
return Constants.Endpoints.CDN(this.client.options.http.cdn).Icon(this.id, this.icon, format, size);
}
/**
* Gets the acronym that shows up in place of a guild icon
* @type {string}
* @readonly
*/
get nameAcronym() {
return this.name.replace(/\w+/g, name => name[0]).replace(/\s/g, '');
}
/**
* The URL to this guild's splash
* @param {Object} [options={}] Options for the splash url
* @param {string} [options.format='webp'] One of `webp`, `png`, `jpg`
* @param {number} [options.size=128] One of `128`, '256', `512`, `1024`, `2048`
* @returns {?string}
*/
splashURL({ format, size } = {}) {
if (!this.splash) return null;
return Constants.Endpoints.CDN(this.client.options.http.cdn).Splash(this.id, this.splash, format, size);
}
/**
* The owner of the guild
* @type {GuildMember}
* @readonly
*/
get owner() {
return this.members.get(this.ownerID);
}
/**
* If the client is connected to any voice channel in this guild, this will be the relevant VoiceConnection
* @type {?VoiceConnection}
* @readonly
*/
get voiceConnection() {
if (this.client.browser) return null;
return this.client.voice.connections.get(this.id) || null;
}
/**
* The position of this guild
* <warn>This is only available when using a user account.</warn>
* @type {?number}
* @readonly
*/
get position() {
if (this.client.user.bot) return null;
if (!this.client.user.settings.guildPositions) return null;
return this.client.user.settings.guildPositions.indexOf(this.id);
}
/**
* Whether the guild is muted
* <warn>This is only available when using a user account.</warn>
* @type {?boolean}
* @readonly
*/
get muted() {
if (this.client.user.bot) return null;
try {
return this.client.user.guildSettings.get(this.id).muted;
} catch (err) {
return false;
}
}
/**
* The type of message that should notify you
* one of `EVERYTHING`, `MENTIONS`, `NOTHING`
* <warn>This is only available when using a user account.</warn>
* @type {?string}
* @readonly
*/
get messageNotifications() {
if (this.client.user.bot) return null;
try {
return this.client.user.guildSettings.get(this.id).messageNotifications;
} catch (err) {
return null;
}
}
/**
* Whether to receive mobile push notifications
* <warn>This is only available when using a user account.</warn>
* @type {?boolean}
* @readonly
*/
get mobilePush() {
if (this.client.user.bot) return null;
try {
return this.client.user.guildSettings.get(this.id).mobilePush;
} catch (err) {
return false;
}
}
/**
* Whether to suppress everyone messages
* <warn>This is only available when using a user account.</warn>
* @type {?boolean}
* @readonly
*/
get suppressEveryone() {
if (this.client.user.bot) return null;
try {
return this.client.user.guildSettings.get(this.id).suppressEveryone;
} catch (err) {
return null;
}
}
/*
* The `@everyone` role of the guild
* @type {Role}
* @readonly
*/
get defaultRole() {
return this.roles.get(this.id);
}
/**
* The client user as a GuildMember of this guild
* @type {?GuildMember}
* @readonly
*/
get me() {
return this.members.get(this.client.user.id);
}
/**
* Fetches a collection of roles in the current guild sorted by position
* @type {Collection<Snowflake, Role>}
* @readonly
* @private
*/
get _sortedRoles() {
return this._sortPositionWithID(this.roles);
}
/**
* Returns the GuildMember form of a User object, if the user is present in the guild.
* @param {UserResolvable} user The user that you want to obtain the GuildMember of
* @returns {?GuildMember}
* @example
* // Get the guild member of a user
* const member = guild.member(message.author);
*/
member(user) {
return this.client.resolver.resolveGuildMember(this, user);
}
/**
* Fetch a collection of banned users in this guild.
* The returned collection contains user objects keyed under `user` and reasons keyed under `reason`.
* @returns {Promise<Collection<Snowflake, Object>>}
*/
fetchBans() {
return this.client.api.guilds(this.id).bans.get().then(bans =>
bans.reduce((collection, ban) => {
collection.set(ban.user.id, {
reason: ban.reason,
user: this.client.dataManager.newUser(ban.user),
});
return collection;
}, new Collection())
);
}
/**
* Fetch a collection of invites to this guild. Resolves with a collection mapping invites by their codes.
* @returns {Promise<Collection<string, Invite>>}
*/
fetchInvites() {
return this.client.api.guilds(this.id).invites.get()
.then(inviteItems => {
const invites = new Collection();
for (const inviteItem of inviteItems) {
const invite = new Invite(this.client, inviteItem);
invites.set(invite.code, invite);
}
return invites;
});
}
/**
* Fetch all webhooks for the guild.
* @returns {Promise<Collection<Snowflake, Webhook>>}
*/
fetchWebhooks() {
return this.client.api.guilds(this.id).webhooks.get().then(data => {
const hooks = new Collection();
for (const hook of data) hooks.set(hook.id, new Webhook(this.client, hook));
return hooks;
});
}
/**
* Fetch available voice regions.
* @returns {Promise<Collection<string, VoiceRegion>>}
*/
fetchVoiceRegions() {
return this.client.api.guilds(this.id).regions.get().then(res => {
const regions = new Collection();
for (const region of res) regions.set(region.id, new VoiceRegion(region));
return regions;
});
}
/**
* Fetch audit logs for this guild.
* @param {Object} [options={}] Options for fetching audit logs
* @param {Snowflake|GuildAuditLogsEntry} [options.before] Limit to entries from before specified entry
* @param {Snowflake|GuildAuditLogsEntry} [options.after] Limit to entries from after specified entry
* @param {number} [options.limit] Limit number of entries
* @param {UserResolvable} [options.user] Only show entries involving this user
* @param {string|number} [options.type] Only show entries involving this action type
* @returns {Promise<GuildAuditLogs>}
*/
fetchAuditLogs(options = {}) {
if (options.before && options.before instanceof GuildAuditLogs.Entry) options.before = options.before.id;
if (options.after && options.after instanceof GuildAuditLogs.Entry) options.after = options.after.id;
if (typeof options.type === 'string') options.type = GuildAuditLogs.Actions[options.type];
return this.client.api.guilds(this.id)['audit-logs'].get({ query: {
before: options.before,
after: options.after,
limit: options.limit,
user_id: this.client.resolver.resolveUserID(options.user),
action_type: options.type,
} })
.then(data => GuildAuditLogs.build(this, data));
}
/**
* Adds a user to the guild using OAuth2. Requires the `CREATE_INSTANT_INVITE` permission.
* @param {UserResolvable} user User to add to the guild
* @param {Object} options Options for the addition
* @param {string} options.accessToken An OAuth2 access token for the user with the `guilds.join` scope granted to the
* bot's application
* @param {string} [options.nick] Nickname to give the member (requires `MANAGE_NICKNAMES`)
* @param {Collection<Snowflake, Role>|RoleResolvable[]} [options.roles] Roles to add to the member
* (requires `MANAGE_ROLES`)
* @param {boolean} [options.mute] Whether the member should be muted (requires `MUTE_MEMBERS`)
* @param {boolean} [options.deaf] Whether the member should be deafened (requires `DEAFEN_MEMBERS`)
* @returns {Promise<GuildMember>}
*/
addMember(user, options) {
if (this.members.has(user.id)) return Promise.resolve(this.members.get(user.id));
options.access_token = options.accessToken;
if (options.roles) {
const roles = [];
for (let role of options.roles instanceof Collection ? options.roles.values() : options.roles) {
role = this.client.resolver.resolveRole(this, role);
if (!role) {
return Promise.reject(new TypeError('INVALID_TYPE', 'options.roles',
'Array or Collection of Roles or Snowflakes', true));
}
roles.push(role.id);
}
}
return this.client.api.guilds(this.id).members(user.id).put({ data: options })
.then(data => this.client.actions.GuildMemberGet.handle(this, data).member);
}
/**
* Fetch a single guild member from a user.
* @param {UserResolvable} user The user to fetch the member for
* @param {boolean} [cache=true] Insert the user into the users cache
* @returns {Promise<GuildMember>}
*/
fetchMember(user, cache = true) {
user = this.client.resolver.resolveUser(user);
if (!user) return Promise.reject(new Error('USER_NOT_CACHED'));
if (this.members.has(user.id)) return Promise.resolve(this.members.get(user.id));
return this.client.api.guilds(this.id).members(user.id).get()
.then(data => {
if (cache) return this.client.actions.GuildMemberGet.handle(this, data).member;
else return new GuildMember(this, data);
});
}
/**
* Fetches all the members in the guild, even if they are offline. If the guild has less than 250 members,
* this should not be necessary.
* @param {Object} [options] Options for the fetch operation
* @param {string} [options.query=''] Limit fetch to members with similar usernames
* @param {number} [options.limit=0] Maximum number of members to request
* @returns {Promise<Collection<Snowflake, GuildMember>>}
*/
fetchMembers({ query = '', limit = 0 } = {}) {
return new Promise((resolve, reject) => {
if (this.memberCount === this.members.size) {
resolve((query || limit) ? new Collection() : this.members);
return;
}
this.client.ws.send({
op: Constants.OPCodes.REQUEST_GUILD_MEMBERS,
d: {
guild_id: this.id,
query,
limit,
},
});
const fetchedMembers = new Collection();
const handler = (members, guild) => {
if (guild.id !== this.id) return;
for (const member of members.values()) {
if (query || limit) fetchedMembers.set(member.user.id, member);
}
if (this.memberCount === this.members.size || ((query || limit) && members.size < 1000)) {
this.client.removeListener(Constants.Events.GUILD_MEMBERS_CHUNK, handler);
resolve((query || limit) ? fetchedMembers : this.members);
}
};
this.client.on(Constants.Events.GUILD_MEMBERS_CHUNK, handler);
this.client.setTimeout(() => {
this.client.removeListener(Constants.Events.GUILD_MEMBERS_CHUNK, handler);
reject(new Error('GUILD_MEMBERS_TIMEOUT'));
}, 120e3);
});
}
/**
* Performs a search within the entire guild.
* <warn>This is only available when using a user account.</warn>
* @param {MessageSearchOptions} [options={}] Options to pass to the search
* @returns {Promise<MessageSearchResult>}
* @example
* guild.search({
* content: 'discord.js',
* before: '2016-11-17'
* }).then(res => {
* const hit = res.results[0].find(m => m.hit).content;
* console.log(`I found: **${hit}**, total results: ${res.total}`);
* }).catch(console.error);
*/
search(options = {}) {
return Shared.search(this, options);
}
/**
* The data for editing a guild.
* @typedef {Object} GuildEditData
* @property {string} [name] The name of the guild
* @property {string} [region] The region of the guild
* @property {number} [verificationLevel] The verification level of the guild
* @property {number} [explicitContentFilter] The level of the explicit content filter
* @property {ChannelResolvable} [afkChannel] The AFK channel of the guild
* @property {number} [afkTimeout] The AFK timeout of the guild
* @property {Base64Resolvable} [icon] The icon of the guild
* @property {GuildMemberResolvable} [owner] The owner of the guild
* @property {Base64Resolvable} [splash] The splash screen of the guild
*/
/**
* Updates the guild with new information - e.g. a new name.
* @param {GuildEditData} data The data to update the guild with
* @param {string} [reason] Reason for editing this guild
* @returns {Promise<Guild>}
* @example
* // Set the guild name and region
* guild.edit({
* name: 'Discord Guild',
* region: 'london',
* })
* .then(updated => console.log(`New guild name ${updated.name} in region ${updated.region}`))
* .catch(console.error);
*/
edit(data, reason) {
const _data = {};
if (data.name) _data.name = data.name;
if (data.region) _data.region = data.region;
if (typeof data.verificationLevel !== 'undefined') _data.verification_level = Number(data.verificationLevel);
if (data.afkChannel) _data.afk_channel_id = this.client.resolver.resolveChannel(data.afkChannel).id;
if (data.afkTimeout) _data.afk_timeout = Number(data.afkTimeout);
if (data.icon) _data.icon = this.client.resolver.resolveBase64(data.icon);
if (data.owner) _data.owner_id = this.client.resolver.resolveUser(data.owner).id;
if (data.splash) _data.splash = this.client.resolver.resolveBase64(data.splash);
if (typeof data.explicitContentFilter !== 'undefined') {
_data.explicit_content_filter = Number(data.explicitContentFilter);
}
return this.client.api.guilds(this.id).patch({ data: _data, reason })
.then(newData => this.client.actions.GuildUpdate.handle(newData).updated);
}
/**
* Edit the level of the explicit content filter.
* @param {number} explicitContentFilter The new level of the explicit content filter
* @param {string} [reason] Reason for changing the level of the guild's explicit content filter
* @returns {Promise<Guild>}
*/
setExplicitContentFilter(explicitContentFilter, reason) {
return this.edit({ explicitContentFilter }, reason);
}
/**
* Edit the name of the guild.
* @param {string} name The new name of the guild
* @param {string} [reason] Reason for changing the guild's name
* @returns {Promise<Guild>}
* @example
* // Edit the guild name
* guild.setName('Discord Guild')
* .then(updated => console.log(`Updated guild name to ${guild.name}`))
* .catch(console.error);
*/
setName(name, reason) {
return this.edit({ name }, reason);
}
/**
* Edit the region of the guild.
* @param {string} region The new region of the guild
* @param {string} [reason] Reason for changing the guild's region
* @returns {Promise<Guild>}
* @example
* // Edit the guild region
* guild.setRegion('london')
* .then(updated => console.log(`Updated guild region to ${guild.region}`))
* .catch(console.error);
*/
setRegion(region, reason) {
return this.edit({ region }, reason);
}
/**
* Edit the verification level of the guild.
* @param {number} verificationLevel The new verification level of the guild
* @param {string} [reason] Reason for changing the guild's verification level
* @returns {Promise<Guild>}
* @example
* // Edit the guild verification level
* guild.setVerificationLevel(1)
* .then(updated => console.log(`Updated guild verification level to ${guild.verificationLevel}`))
* .catch(console.error);
*/
setVerificationLevel(verificationLevel, reason) {
return this.edit({ verificationLevel }, reason);
}
/**
* Edit the AFK channel of the guild.
* @param {ChannelResolvable} afkChannel The new AFK channel
* @param {string} [reason] Reason for changing the guild's AFK channel
* @returns {Promise<Guild>}
* @example
* // Edit the guild AFK channel
* guild.setAFKChannel(channel)
* .then(updated => console.log(`Updated guild AFK channel to ${guild.afkChannel}`))
* .catch(console.error);
*/
setAFKChannel(afkChannel, reason) {
return this.edit({ afkChannel }, reason);
}
/**
* Edit the AFK timeout of the guild.
* @param {number} afkTimeout The time in seconds that a user must be idle to be considered AFK
* @param {string} [reason] Reason for changing the guild's AFK timeout
* @returns {Promise<Guild>}
* @example
* // Edit the guild AFK channel
* guild.setAFKTimeout(60)
* .then(updated => console.log(`Updated guild AFK timeout to ${guild.afkTimeout}`))
* .catch(console.error);
*/
setAFKTimeout(afkTimeout, reason) {
return this.edit({ afkTimeout }, reason);
}
/**
* Set a new guild icon.
* @param {Base64Resolvable} icon The new icon of the guild
* @param {string} [reason] Reason for changing the guild's icon
* @returns {Promise<Guild>}
* @example
* // Edit the guild icon
* guild.setIcon(fs.readFileSync('./icon.png'))
* .then(updated => console.log('Updated the guild icon'))
* .catch(console.error);
*/
setIcon(icon, reason) {
return this.edit({ icon }, reason);
}
/**
* Sets a new owner of the guild.
* @param {GuildMemberResolvable} owner The new owner of the guild
* @param {string} [reason] Reason for setting the new owner
* @returns {Promise<Guild>}
* @example
* // Edit the guild owner
* guild.setOwner(guild.members.first())
* .then(updated => console.log(`Updated the guild owner to ${updated.owner.username}`))
* .catch(console.error);
*/
setOwner(owner, reason) {
return this.edit({ owner }, reason);
}
/**
* Set a new guild splash screen.
* @param {Base64Resolvable} splash The new splash screen of the guild
* @param {string} [reason] Reason for changing the guild's splash screen
* @returns {Promise<Guild>}
* @example
* // Edit the guild splash
* guild.setIcon(fs.readFileSync('./splash.png'))
* .then(updated => console.log('Updated the guild splash'))
* .catch(console.error);
*/
setSplash(splash, reason) {
return this.edit({ splash }, reason);
}
/**
* Sets the position of the guild in the guild listing.
* <warn>This is only available when using a user account.</warn>
* @param {number} position Absolute or relative position
* @param {boolean} [relative=false] Whether to position relatively or absolutely
* @returns {Promise<Guild>}
*/
setPosition(position, relative) {
if (this.client.user.bot) {
return Promise.reject(new Error('FEATURE_USER_ONLY'));
}
return this.client.user.settings.setGuildPosition(this, position, relative);
}
/**
* Marks all messages in this guild as read.
* <warn>This is only available when using a user account.</warn>
* @returns {Promise<Guild>}
*/
acknowledge() {
return this.client.api.guilds(this.id).ack
.post({ data: { token: this.client.rest._ackToken } })
.then(res => {
if (res.token) this.client.rest._ackToken = res.token;
return this;
});
}
/**
* Allow direct messages from guild members.
* @param {boolean} allow Whether to allow direct messages
* @returns {Promise<Guild>}
*/
allowDMs(allow) {
const settings = this.client.user.settings;
if (allow) return settings.removeRestrictedGuild(this);
else return settings.addRestrictedGuild(this);
}
/**
* Bans a user from the guild.
* @param {UserResolvable} user The user to ban
* @param {Object|number|string} [options] Ban options. If a number, the number of days to delete messages for, if a
* string, the ban reason. Supplying an object allows you to do both.
* @param {number} [options.days=0] Number of days of messages to delete
* @param {string} [options.reason] Reason for banning
* @returns {Promise<GuildMember|User|string>} Result object will be resolved as specifically as possible.
* If the GuildMember cannot be resolved, the User will instead be attempted to be resolved. If that also cannot
* be resolved, the user ID will be the result.
* @example
* // Ban a user by ID (or with a user/guild member object)
* guild.ban('some user ID')
* .then(user => console.log(`Banned ${user.username || user.id || user} from ${guild.name}`))
* .catch(console.error);
*/
ban(user, options = { days: 0 }) {
if (options.days) options['delete-message-days'] = options.days;
const id = this.client.resolver.resolveUserID(user);
if (!id) return Promise.reject(new Error('BAN_RESOLVE_ID', true));
return this.client.api.guilds(this.id).bans[id].put({ query: options })
.then(() => {
if (user instanceof GuildMember) return user;
const _user = this.client.resolver.resolveUser(id);
if (_user) {
const member = this.client.resolver.resolveGuildMember(this, _user);
return member || _user;
}
return id;
});
}
/**
* Unbans a user from the guild.
* @param {UserResolvable} user The user to unban
* @param {string} [reason] Reason for unbanning user
* @returns {Promise<User>}
* @example
* // Unban a user by ID (or with a user/guild member object)
* guild.unban('some user ID')
* .then(user => console.log(`Unbanned ${user.username} from ${guild.name}`))
* .catch(console.error);
*/
unban(user, reason) {
const id = this.client.resolver.resolveUserID(user);
if (!id) throw new Error('BAN_RESOLVE_ID');
return this.client.api.guilds(this.id).bans[id].delete({ reason })
.then(() => user);
}
/**
* Prunes members from the guild based on how long they have been inactive.
* @param {number} [options.days=7] Number of days of inactivity required to kick
* @param {boolean} [options.dry=false] Get number of users that will be kicked, without actually kicking them
* @param {string} [options.reason] Reason for this prune
* @returns {Promise<number>} The number of members that were/will be kicked
* @example
* // See how many members will be pruned
* guild.pruneMembers({ dry: true })
* .then(pruned => console.log(`This will prune ${pruned} people!`))
* .catch(console.error);
* @example
* // Actually prune the members
* guild.pruneMembers({ days: 1, reason: 'too many people!' })
* .then(pruned => console.log(`I just pruned ${pruned} people!`))
* .catch(console.error);
*/
pruneMembers({ days = 7, dry = false, reason } = {}) {
if (typeof days !== 'number') throw new TypeError('PRUNE_DAYS_TYPE');
return this.client.api.guilds(this.id).prune[dry ? 'get' : 'post']({ query: { days }, reason })
.then(data => data.pruned);
}
/**
* Syncs this guild (already done automatically every 30 seconds).
* <warn>This is only available when using a user account.</warn>
*/
sync() {
if (!this.client.user.bot) this.client.syncGuilds([this]);
}
/**
* Can be used to overwrite permissions when creating a channel.
* @typedef {Object} ChannelCreationOverwrites
* @property {PermissionResolvable[]|number} [allow] The permissions to allow
* @property {PermissionResolvable[]|number} [deny] The permissions to deny
* @property {RoleResolvable|UserResolvable} id ID of the group or member this overwrite is for
*/
/**
* Creates a new channel in the guild.
* @param {string} name The name of the new channel
* @param {string} type The type of the new channel, either `text` or `voice`
* @param {Object} [options={}] Options
* @param {Array<PermissionOverwrites|ChannelCreationOverwrites>} [options.overwrites] Permission overwrites
* to apply to the new channel
* @param {string} [options.reason] Reason for creating this channel
* @returns {Promise<TextChannel|VoiceChannel>}
* @example
* // Create a new text channel
* guild.createChannel('new-general', 'text')
* .then(channel => console.log(`Created new channel ${channel}`))
* .catch(console.error);
*/
createChannel(name, type, { overwrites, reason } = {}) {
if (overwrites instanceof Collection || overwrites instanceof Array) {
overwrites = overwrites.map(overwrite => {
let allow = overwrite.allow || overwrite._allowed;
let deny = overwrite.deny || overwrite._denied;
if (allow instanceof Array) allow = Permissions.resolve(allow);
if (deny instanceof Array) deny = Permissions.resolve(deny);
const role = this.client.resolver.resolveRole(this, overwrite.id);
if (role) {
overwrite.id = role.id;
overwrite.type = 'role';
} else {
overwrite.id = this.client.resolver.resolveUserID(overwrite.id);
overwrite.type = 'member';
}
return {
allow,
deny,
type: overwrite.type,
id: overwrite.id,
};
});
}
return this.client.api.guilds(this.id).channels.post({
data: {
name, type, permission_overwrites: overwrites,
},
reason,
}).then(data => this.client.actions.ChannelCreate.handle(data).channel);
}
/**
* The data needed for updating a channel's position.
* @typedef {Object} ChannelPosition
* @property {ChannelResolvable} channel Channel to update
* @property {number} position New position for the channel
*/
/**
* Batch-updates the guild's channels' positions.
* @param {ChannelPosition[]} channelPositions Channel positions to update
* @returns {Promise<Guild>}
* @example
* guild.updateChannels([{ channel: channelID, position: newChannelIndex }])
* .then(guild => console.log(`Updated channel positions for ${guild.id}`))
* .catch(console.error);
*/
setChannelPositions(channelPositions) {
const data = new Array(channelPositions.length);
for (let i = 0; i < channelPositions.length; i++) {
data[i] = {
id: this.client.resolver.resolveChannelID(channelPositions[i].channel),
position: channelPositions[i].position,
};
}
return this.client.api.guilds(this.id).channels.patch({ data: {
guild_id: this.id,
channels: channelPositions,
} }).then(() =>
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.id,
channels: channelPositions,
}).guild
);
}
/**
* Creates a new role in the guild with given information
* @param {Object} [options] Options
* @param {RoleData} [options.data] The data to update the role with
* @param {string} [options.reason] Reason for creating this role
* @returns {Promise<Role>}
* @example
* // Create a new role
* guild.createRole()
* .then(role => console.log(`Created role ${role}`))
* .catch(console.error);
* @example
* // Create a new role with data and a reason
* guild.createRole({
* data: {
* name: 'Super Cool People',
* color: 'BLUE',
* },
* reason: 'we needed a role for Super Cool People',
* })
* .then(role => console.log(`Created role ${role}`))
* .catch(console.error)
*/
createRole({ data = {}, reason } = {}) {
if (data.color) data.color = Util.resolveColor(data.color);
if (data.permissions) data.permissions = Permissions.resolve(data.permissions);
return this.client.api.guilds(this.id).roles.post({ data, reason }).then(role =>
this.client.actions.GuildRoleCreate.handle({
guild_id: this.id,
role,
}).role
);
}
/**
* Creates a new custom emoji in the guild.
* @param {BufferResolvable|Base64Resolvable} attachment The image for the emoji
* @param {string} name The name for the emoji
* @param {Object} [options] Options
* @param {Collection<Snowflake, Role>|RoleResolvable[]} [options.roles] Roles to limit the emoji to
* @param {string} [options.reason] Reason for creating the emoji
* @returns {Promise<Emoji>} The created emoji
* @example
* // Create a new emoji from a url
* guild.createEmoji('https://i.imgur.com/w3duR07.png', 'rip')
* .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`))
* .catch(console.error);
* @example
* // Create a new emoji from a file on your computer
* guild.createEmoji('./memes/banana.png', 'banana')
* .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`))
* .catch(console.error);
*/
createEmoji(attachment, name, { roles, reason } = {}) {
if (typeof attachment === 'string' && attachment.startsWith('data:')) {
const data = { image: attachment, name };
if (roles) {
data.roles = [];
for (let role of roles instanceof Collection ? roles.values() : roles) {
role = this.client.resolver.resolveRole(this, role);
if (!role) {
return Promise.reject(new TypeError('INVALID_TYPE', 'options.roles',
'Array or Collection of Roles or Snowflakes', true));
}
data.roles.push(role.id);
}
}
return this.client.api.guilds(this.id).emojis.post({ data, reason })
.then(emoji => this.client.actions.GuildEmojiCreate.handle(this, emoji).emoji);
}
return this.client.resolver.resolveBuffer(attachment)
.then(data => {
const dataURI = this.client.resolver.resolveBase64(data);
return this.createEmoji(dataURI, name, { roles, reason });
});
}
/**
* Delete an emoji.
* @param {Emoji|string} emoji The emoji to delete
* @param {string} [reason] Reason for deleting the emoji
* @returns {Promise}
*/
deleteEmoji(emoji, reason) {
if (!(emoji instanceof Emoji)) emoji = this.emojis.get(emoji);
return this.client.api.guilds(this.id).emojis(emoji.id).delete({ reason })
.then(() => this.client.actions.GuildEmojiDelete.handle(emoji).data);
}
/**
* Causes the client to leave the guild.
* @returns {Promise<Guild>}
* @example
* // Leave a guild
* guild.leave()
* .then(g => console.log(`Left the guild ${g}`))
* .catch(console.error);
*/
leave() {
if (this.ownerID === this.client.user.id) return Promise.reject(new Error('GUILD_OWNED'));
return this.client.api.users('@me').guilds(this.id).delete()
.then(() => this.client.actions.GuildDelete.handle({ id: this.id }).guild);
}
/**
* Causes the client to delete the guild.
* @returns {Promise<Guild>}
* @example
* // Delete a guild
* guild.delete()
* .then(g => console.log(`Deleted the guild ${g}`))
* .catch(console.error);
*/
delete() {
return this.client.api.guilds(this.id).delete()
.then(() => this.client.actions.GuildDelete.handle({ id: this.id }).guild);
}
/**
* Whether this guild equals another guild. It compares all properties, so for most operations
* it is advisable to just compare `guild.id === guild2.id` as it is much faster and is often
* what most users need.
* @param {Guild} guild The guild to compare with
* @returns {boolean}
*/
equals(guild) {
let equal =
guild &&
guild instanceof this.constructor &&
this.id === guild.id &&
this.available === guild.available &&
this.splash === guild.splash &&
this.region === guild.region &&
this.name === guild.name &&
this.memberCount === guild.memberCount &&
this.large === guild.large &&
this.icon === guild.icon &&
Util.arraysEqual(this.features, guild.features) &&
this.ownerID === guild.ownerID &&
this.verificationLevel === guild.verificationLevel &&
this.embedEnabled === guild.embedEnabled;
if (equal) {
if (this.embedChannel) {
if (!guild.embedChannel || this.embedChannel.id !== guild.embedChannel.id) equal = false;
} else if (guild.embedChannel) {
equal = false;
}
}
return equal;
}
/**
* When concatenated with a string, this automatically concatenates the guild's name instead of the guild object.
* @returns {string}
* @example
* // Logs: Hello from My Guild!
* console.log(`Hello from ${guild}!`);
* @example
* // Logs: Hello from My Guild!
* console.log('Hello from ' + guild + '!');
*/
toString() {
return this.name;
}
_addMember(guildUser, emitEvent = true) {
const existing = this.members.has(guildUser.user.id);
if (!(guildUser.user instanceof User)) guildUser.user = this.client.dataManager.newUser(guildUser.user);
guildUser.joined_at = guildUser.joined_at || 0;
const member = new GuildMember(this, guildUser);
this.members.set(member.id, member);
if (this._rawVoiceStates && this._rawVoiceStates.has(member.user.id)) {
const voiceState = this._rawVoiceStates.get(member.user.id);
member.serverMute = voiceState.mute;
member.serverDeaf = voiceState.deaf;
member.selfMute = voiceState.self_mute;
member.selfDeaf = voiceState.self_deaf;
member.voiceSessionID = voiceState.session_id;
member.voiceChannelID = voiceState.channel_id;
if (this.client.channels.has(voiceState.channel_id)) {
this.client.channels.get(voiceState.channel_id).members.set(member.user.id, member);
} else {
this.client.emit('warn', `Member ${member.id} added in guild ${this.id} with an uncached voice channel`);
}
}
/**
* Emitted whenever a user joins a guild.
* @event Client#guildMemberAdd
* @param {GuildMember} member The member that has joined a guild
*/
if (this.client.ws.connection.status === Constants.Status.READY && emitEvent && !existing) {
this.client.emit(Constants.Events.GUILD_MEMBER_ADD, member);
}
return member;
}
_updateMember(member, data) {
const oldMember = Util.cloneObject(member);
if (data.roles) member._roles = data.roles;
if (typeof data.nick !== 'undefined') member.nickname = data.nick;
const notSame = member.nickname !== oldMember.nickname || !Util.arraysEqual(member._roles, oldMember._roles);
if (this.client.ws.connection.status === Constants.Status.READY && notSame) {
/**
* Emitted whenever a guild member changes - i.e. new role, removed role, nickname.
* @event Client#guildMemberUpdate
* @param {GuildMember} oldMember The member before the update
* @param {GuildMember} newMember The member after the update
*/
this.client.emit(Constants.Events.GUILD_MEMBER_UPDATE, oldMember, member);
}
return {
old: oldMember,
mem: member,
};
}
_removeMember(guildMember) {
this.members.delete(guildMember.id);
}
_memberSpeakUpdate(user, speaking) {
const member = this.members.get(user);
if (member && member.speaking !== speaking) {
member.speaking = speaking;
/**
* Emitted once a guild member starts/stops speaking.
* @event Client#guildMemberSpeaking
* @param {GuildMember} member The member that started/stopped speaking
* @param {boolean} speaking Whether or not the member is speaking
*/
this.client.emit(Constants.Events.GUILD_MEMBER_SPEAKING, member, speaking);
}
}
_setPresence(id, presence) {
if (this.presences.get(id)) {
this.presences.get(id).update(presence);
return;
}
this.presences.set(id, new Presence(presence));
}
/**
* Set the position of a role in this guild.
* @param {string|Role} role The role to edit, can be a role object or a role ID
* @param {number} position The new position of the role
* @param {boolean} [relative=false] Position Moves the role relative to its current position
* @returns {Promise<Guild>}
*/
setRolePosition(role, position, relative = false) {
if (typeof role === 'string') {
role = this.roles.get(role);
}
if (!(role instanceof Role)) return Promise.reject(new TypeError('INVALID_TYPE', 'role', 'Role nor a Snowflake'));
position = Number(position);
if (isNaN(position)) return Promise.reject(new TypeError('INVALID_TYPE', 'position', 'number'));
let updatedRoles = this._sortedRoles.array();
Util.moveElementInArray(updatedRoles, role, position, relative);
updatedRoles = updatedRoles.map((r, i) => ({ id: r.id, position: i }));
return this.client.api.guilds(this.id).roles.patch({ data: updatedRoles })
.then(() =>
this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.id,
roles: updatedRoles,
}).guild
);
}
/**
* Set the position of a channel in this guild.
* @param {string|GuildChannel} channel The channel to edit, can be a channel object or a channel ID
* @param {number} position The new position of the channel
* @param {boolean} [relative=false] Position Moves the channel relative to its current position
* @returns {Promise<Guild>}
*/
setChannelPosition(channel, position, relative = false) {
if (typeof channel === 'string') {
channel = this.channels.get(channel);
}
if (!(channel instanceof GuildChannel)) {
return Promise.reject(new TypeError('INVALID_TYPE', 'channel', 'GuildChannel nor a Snowflake'));
}
position = Number(position);
if (isNaN(position)) return Promise.reject(new TypeError('INVALID_TYPE', 'position', 'number'));
let updatedChannels = this._sortedChannels(channel.type).array();
Util.moveElementInArray(updatedChannels, channel, position, relative);
updatedChannels = updatedChannels.map((r, i) => ({ id: r.id, position: i }));
return this.client.api.guilds(this.id).channels.patch({ data: updatedChannels })
.then(() =>
this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.id,
channels: updatedChannels,
}).guild
);
}
/**
* Fetches a collection of channels in the current guild sorted by position.
* @param {string} type The channel type
* @returns {Collection<Snowflake, GuildChannel>}
* @private
*/
_sortedChannels(type) {
return this._sortPositionWithID(this.channels.filter(c => {
if (type === 'voice' && c.type === 'voice') return true;
else if (type !== 'voice' && c.type !== 'voice') return true;
else return type === c.type;
}));
}
/**
* Sorts a collection by object position or ID if the positions are equivalent.
* Intended to be identical to Discord's sorting method.
* @param {Collection} collection The collection to sort
* @returns {Collection}
* @private
*/
_sortPositionWithID(collection) {
return collection.sort((a, b) =>
a.position !== b.position ?
a.position - b.position :
Long.fromString(a.id).sub(Long.fromString(b.id)).toNumber()
);
}
}
module.exports = Guild;
| zajrik/discord.js | src/structures/Guild.js | JavaScript | apache-2.0 | 46,291 |
var debug = false;
var isStatsOn = false;
var authWindow;
var app;
var runLoop = function() {
app.update();
app.draw();
}
var initApp = function() {
if (app!=null) { return; }
app = new App({}, document.getElementById('canvas'));
window.addEventListener('resize', app.resize, false);
document.addEventListener('mousemove', app.mousemove, false);
document.addEventListener('mousedown', app.mousedown, false);
document.addEventListener('mouseup', app.mouseup, false);
document.addEventListener('touchstart', app.touchstart, false);
document.addEventListener('touchend', app.touchend, false);
document.addEventListener('touchcancel', app.touchend, false);
document.addEventListener('touchmove', app.touchmove, false);
document.addEventListener('keydown', app.keydown, false);
document.addEventListener('keyup', app.keyup, false);
/**
document.getElementById('authorize-user-button').addEventListener('click', function(e) {
app.authorize(null,null);
authWindow = window.open("auth.html","","width=950,height=460,menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes')")
return false;
},false);
*/
setInterval(runLoop,30);
}
var forceInit = function() {
initApp()
document.getElementById('unsupported-browser').style.display = "none";
return false;
}
if(Modernizr.canvas && Modernizr.websockets) {
initApp();
} else {
document.getElementById('unsupported-browser').style.display = "block";
document.getElementById('force-init-button').addEventListener('click', forceInit, false);
}
var addStats = function() {
if (isStatsOn) { return; }
// Draw fps
var stats = new Stats();
document.getElementById('fps').appendChild(stats.domElement);
setInterval(function () {
stats.update();
}, 1000/60);
// Array Remove - By John Resig (MIT Licensed)
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
isStatsOn = true;
}
//document.addEventListener('keydown',function(e) {
// if(e.which == 27) {
// addStats();
// }
//})
if(debug) { addStats(); }
$(function() {
$('a[rel=external]').click(function(e) {
e.preventDefault();
window.open($(this).attr('href'));
});
});
document.body.onselectstart = function() { return false; }
| generallycloud/baseio | firenio-sample/sample-http/src/main/resources/app/html/web-socket/rumpetroll/js/main.js | JavaScript | apache-2.0 | 2,392 |
$(document).ready(function(){
$('#bx1').bxSlider();
$('#bx2').bxSlider({
hideControlOnEnd: true,
captions: true,
pager: false
})
$('#bx3').bxSlider({
hideControlOnEnd: true,
minSlides: 3,
maxSlides: 3,
slideWidth: 360,
slideMargin: 10,
pager: false,
nextSelector: '#bx-next',
prevSelector: '#bx-prev',
nextText: '>',
prevText: '<'
})
$('#bx4').bxSlider({
hideControlOnEnd: true,
minSlides: 4,
maxSlides: 4,
slideWidth: 360,
slideMargin: 10,
pager: false,
nextSelector: '#bx-next4',
prevSelector: '#bx-prev4',
nextText: '>',
prevText: '<',
})
$('#bx5').bxSlider({
minSlides: 2,
maxSlides: 3,
slideWidth: 360,
slideMargin: 10,
pager: false,
ticker: true,
speed: 12000,
tickerHover: true,
useCSS: false
})
});
| livinglegends/llf-site | js/carousels.js | JavaScript | apache-2.0 | 1,052 |
var searchData=
[
['utils',['utils',['../classsrc_1_1tests_1_1utils_1_1utils_1_1utils.html',1,'src::tests::utils::utils']]]
];
| gpierre42/optraj | Doxydoc/html/search/classes_75.js | JavaScript | apache-2.0 | 129 |
const readdirp = require('readdirp'),
path = require('path'),
fs = require('graceful-fs'),
_ = require('lodash'),
frontMatterParser = require('./parsers/front_matter_parser'),
markdownParser = require('./parsers/markdown_parser'),
fileParser = require('./parsers/file_parser'),
linkParser = require('./parsers/link_parser'),
linkAttributeParser = require('./parsers/link_attribute_parser'),
parsers = [
frontMatterParser,
markdownParser,
fileParser,
linkAttributeParser
],
directoryFilters = ['!node_modules', '!lib', '!Archive'],
fileFilters = '*.md',
F = {
failed: null
},
Ignored = {
files: []
};
function loadIgnored() {
let err, files;
try {
files = fs.readFileSync('../commit_analyzer_ignore.txt', 'utf-8');
files = files.split('\n');
console.log("\n\nIgnoring " + (files.join(', ')));
return _.each(files, function(file) {
return Ignored.files.push(file);
});
} catch (error) {
err = error;
return console.log("\n\nunable to find commit_analyzer_ignore.txt file; not ignoring any files...\n\n");
}
}
function readOpts() {
return {
root: path.join(__dirname, '..'),
fileFilter: fileFilters,
directoryFilter: directoryFilters
};
}
function fileIsIgnored(file) {
return _.indexOf(Ignored.files, file) >= 0;
}
function analyze() {
loadIgnored();
return readdirp(
readOpts(),
function(file) {
if (fileIsIgnored(file.name)) {
return;
}
return _.each(parsers, function(parser) {
const failed = F.failed;
return F.failed = parser.parse(file, failed);
});
},
function(err, res) {
if (F.failed) {
return process.exit(1);
} else {
return process.exit(0);
}
}
);
}
analyze();
| CenturyLinkCloud/KB-Commit-Analyzer | index.js | JavaScript | apache-2.0 | 1,800 |
const PERM_NOT_FOUND = "Permission '_perm_' not found on '_role_' for '_res_'.";
const Types = {
ALL: 'ALL',
CREATE: 'CREATE',
READ: 'READ',
UPDATE: 'UPDATE',
DELETE: 'DELETE'
};
/**
* The map of role-resource tuple to permissions.
* The first level key is the tuple, the second level key is the action.
* Available actions are "ALL", "CREATE", "READ", "UPDATE", "DELETE".
* @name Permission
* @constructor
*/
function Permission() {
//map of string to map of string-bool
this.perms = {};
this.makeDefaultDeny();
}
Permission.DEFAULT_KEY = '*::*';
/**
* Visualization of the permissions in tuples.
* @memberof Permission
*/
Permission.prototype.toString = function () {
var action, entry, tuple,
out = ['Size: '];
out.push(this.size());
out.push('\n-------\n');
for (tuple in this.perms) {
if (this.perms.hasOwnProperty(tuple)) {
out.push('- ');
out.push(tuple);
out.push('\n');
entry = this.perms[tuple];
for (action in entry) {
if (entry.hasOwnProperty(action)) {
out.push('\t');
out.push(action);
out.push('\t');
out.push(entry[action]);
out.push('\n');
}
}
}
}
return out.join('');
};
/**
* Grants action permission on resource to role.
* Adds the action permission to any existing actions. Overrides the
* existing action permission if any.
*
* @param {string} role - The ID of the access request object.
* @param {string} resource - The ID of the access control object.
* @param {string} [action=ALL] - The access action.
* @memberof Permission
*/
Permission.prototype.allow = function (role, resource, action) {
var perm, key = this.makeKey(role, resource);
if (!action) {
action = Types.ALL;
}
if (this.has(key)) {
perm = this.perms[key];
perm[action] = true;
} else {
this.perms[key] = this.makePermission(action, true);
}
};
/**
* Removes all permissions.
* @memberof Permission
*/
Permission.prototype.clear = function () {
this.perms = {};
};
/**
* Denies action permission on resource to role.
* Adds the action permission to any existing actions. Overrides the
* existing action permission if any.
*
* @param {string} role - The ID of the access request object.
* @param {string} resource - The ID of the access control object.
* @param {string} [action=ALL] - The access action.
* @memberof Permission
*/
Permission.prototype.deny = function (role, resource, action) {
var perm, key = this.makeKey(role, resource);
if (!action) {
action = Types.ALL;
}
if (this.has(key)) {
perm = this.perms[key];
perm[action] = false;
} else {
this.perms[key] = this.makePermission(action, false);
}
};
/**
* Exports a snapshot of the permissions map.
*
* @return {Object} A map with string keys and map values where
* the values are maps of string to boolean entries. Typically
* meant for persistent storage.
* @memberof Permission
*/
Permission.prototype.export = function () {
var i, j, clone = {};
for (i in this.perms) {
if (this.perms.hasOwnProperty(i)) {
clone[i] = {};
for (j in this.perms[i]) {
if (this.perms[i].hasOwnProperty(j)) {
clone[i][j] = this.perms[i][j];
}
}
}
}
return clone;
};
/**
* Determines if the role-resource tuple is available.
*
* @param {string} key - The tuple of role and resource.
* @return {Boolean} Returns true if the permission is available for this tuple.
* @memberof Permission
*/
Permission.prototype.has = function (key) {
return this.perms.hasOwnProperty(key);
};
/**
* Re-creates the permission map with a new of permissions.
*
* @param {Object} map - The map of string-string-boolean
* tuples. The first-level string is a permission key
* (<aco>::<aro>); the second-level string is the set of
* actions; the boolean value indicates whether the permission
* is explicitly granted/denied.
* @memberof Permission
*/
Permission.prototype.importMap = function (map) {
var i, j;
this.perms = {};
for (i in map) {
if (map.hasOwnProperty(i)) {
this.perms[i] = {};
for (j in map[i]) {
if (map[i].hasOwnProperty(j)) {
this.perms[i][j] = map[i][j];
}
}
}
}
};
/**
* Determines if the role has access on the resource.
*
* @param {string} role - The ID of the access request object.
* @param {string} resource - The ID of the access control object.
* @return {Boolean} Returns true only if the role has been
* explicitly given access to all actions on the resource.
* Returns false if the role has been explicitly denied access.
* Returns null otherwise.
* @memberof Permission
*/
Permission.prototype.isAllowedAll = function (role, resource) {
var k, perm,
allSet = 0,
key = this.makeKey(role, resource);
if (!this.has(key)) {
return null;
}
perm = this.perms[key];
for (k in perm) {
if (perm.hasOwnProperty(k)) {
if (perm[k] === false) {
return false;
}
if (k !== Types.ALL) {
allSet++;
}
}
}
if (perm.hasOwnProperty(Types.ALL)) {
return true; //true because ALL=false would be caught in the loop
}
if (allSet === 4) {
return true;
}
return null;
};
/**
* Determines if the role has access on the resource for the specific action.
* The permission on the specific action is evaluated to see if it has been
* specified. If not specified, the permission on the <code>ALL</code>
* permission is evaluated. If both are not specified, <code>null</code> is
* returned.
*
* @param {string} role - The ID of the access request object.
* @param {string} resource - The ID of the access control object.
* @param {string} action - The access action.
* @return {Boolean} Returns true if the role has access to the specified
* action on the resource. Returns false if the role is denied
* access. Returns null if no permission is specified.
* @memberof Permission
*/
Permission.prototype.isAllowed = function (role, resource, action) {
var perm, key = this.makeKey(role, resource);
if (!this.has(key)) {
return null;
}
perm = this.perms[key];
if (perm[action] === undefined) {
//if specific action is not present, check for ALL
if (perm[Types.ALL] === undefined) {
return null;
}
return perm[Types.ALL];
} //else specific action is present
return perm[action];
};
/**
* Determines if the role is denied access on the resource.
*
* @param {string} role - The ID of the access request object.
* @param {string} resource - The ID of the access control object.
* @return {Boolean} Returns true only if the role has been
* explicitly denied access to all actions on the resource.
* Returns false if the role has been explicitly granted access.
* Returns null otherwise.
* @memberof Permission
*/
Permission.prototype.isDeniedAll = function (role, resource) {
var k, perm,
allSet = 0,
key = this.makeKey(role, resource);
if (!this.has(key)) {
return null;
}
perm = this.perms[key];
for (k in perm) {
if (perm.hasOwnProperty(k)) {
//if any entry is true, resource is NOT denied
if (perm[k]) {
return false;
}
if (k !== Types.ALL) {
allSet++;
}
}
}
if (perm.hasOwnProperty(Types.ALL)) {
return true; //true because ALL=true would be caught in the loop
}
if (allSet === 4) {
return true;
}
return null;
};
/**
* Determines if the role is denied access on the resource for the specific
* action.
* The permission on the specific action is evaluated to see if it has been
* specified. If not specified, the permission on the <code>ALL</code>
* permission is evaluated. If both are not specified, <code>null</code> is
* returned.
*
* @param {string} role - The ID of the access request object.
* @param {string} resource - The ID of the access control object.
* @param {string} action - The access action.
* @return {Boolean} Returns true if the role is denied access
* to the specified action on the resource. Returns false if the
* role has access. Returns null if no permission is specified.
* @memberof Permission
*/
Permission.prototype.isDenied = function (role, resource, action) {
var perm, key = this.makeKey(role, resource);
if (!this.has(key)) {
return null;
}
perm = this.perms[key];
if (perm[action] === undefined) {
//if specific action is not present, check for ALL
if (perm[Types.ALL] === undefined) {
return null;
}
return !perm[Types.ALL];
} //else specific action is present
return !perm[action];
};
/**
* Makes the default permission allow.
* @memberof Permission
*/
Permission.prototype.makeDefaultAllow = function () {
this.perms[Permission.DEFAULT_KEY] = this.makePermission(Types.ALL, true);
};
/**
* Makes the default permission deny.
* @memberof Permission
*/
Permission.prototype.makeDefaultDeny = function () {
this.perms[Permission.DEFAULT_KEY] = this.makePermission(Types.ALL, false);
};
/**
* Removes the specified permission on resource from role.
*
* @param {string} role - The ID of the access request object.
* @param {string} resource - The ID of the access control object.
* @param {string} [action=ALL] - The access action.
* @throws Will throw an error if the permission is not available.
* @memberof Permission
*/
Permission.prototype.remove = function (role, resource, action) {
var orig, perm, type,
key = this.makeKey(role, resource),
resId = resource ? resource : '*',
roleId = role ? role : '*';
if (!action) {
action = Types.ALL;
}
if (!this.has(key)) {
throw new Error(PERM_NOT_FOUND.replace(/_perm_/g, key)
.replace(/_res_/g, resId)
.replace(/_role_/g, roleId));
}
perm = this.perms[key];
if (perm[action] !== undefined) { //i.e. if action is defined
if (action === Types.ALL) {
delete this.perms[key];
return;
} else { //remove specific action
delete perm[action];
}
} else if (perm[Types.ALL] !== undefined) {
//has ALL - remove and put in the others
orig = perm[Types.ALL];
delete perm[Types.ALL];
for (type in Types) {
if (Types.hasOwnProperty(type)) {
if (type !== action && type !== Types.ALL) {
perm[type] = orig;
}
}
}
} else if (action === Types.ALL) {
delete this.perms[key];
return;
} else { //i.e. action is not defined
throw new Error(PERM_NOT_FOUND.replace(/_perm_/g, action)
.replace(/_res_/g, resId)
.replace(/_role_/g, roleId));
}
if (Object.keys(perm).length === 0) {
delete this.perms[key];
} else {
this.perms[key] = perm;
}
};
/**
* Removes all permissions related to the resource.
*
* @param {string} resourceId - The ID of the resource to remove.
* @return {Number} The number of removed permissions.
* @memberof Permission
*/
Permission.prototype.removeByResource = function (resourceId) {
var key,
toRemove = [],
resId = '::' + resourceId;
for (key in this.perms) {
if (this.perms.hasOwnProperty(key)) {
if (key.endsWith(resId)) {
toRemove.push(key);
}
}
}
return remove(this.perms, toRemove);
};
/**
* Removes all permissions related to the role.
*
* @param {string} roleId - The ID of the role to remove.
* @return {Number} The number of removed permissions.
* @memberof Permission
*/
Permission.prototype.removeByRole = function (roleId) {
var key,
toRemove = [],
rolId = roleId + '::';
for (key in this.perms) {
if (this.perms.hasOwnProperty(key)) {
if (key.startsWith(rolId)) {
toRemove.push(key);
}
}
}
return remove(this.perms, toRemove);
};
/**
* The number of specified permissions.
*
* @return {Number} The number of permissions in the registry.
* @memberof Permission
*/
Permission.prototype.size = function () {
return Object.keys(this.perms).length;
};
/**
* Creates the key in the form "<aro>::<aco>" where "<aro>" is
* the ID of the role, and "<aco>" is the ID of the resource.
*
* @param {string} role The ID of the role.
* @param {string} resource The ID of the resource.
* @return {string} The key of the permission.
* @memberof Permission
*/
Permission.prototype.makeKey = function (role, resource) {
var aco = resource ? resource : '*',
aro = role ? role : '*';
return aro + '::' + aco;
};
/**
* Creates a permissions map.
*
* @param {string} action The action to set. Accepted values are
* "ALL", "CREATE", "READ", "UPDATE", "DELETE".
* @param {Boolean} allow Either true or false to grant or deny access.
* @return {Object} The map of string-boolean values.
* @memberof Permission
*/
Permission.prototype.makePermission = function (action, allow) {
var perm = {};
perm[action] = allow;
return perm;
};
/**
* Helper function called by remove functions to remove permissions.
* @param {Object} perms - The map of permissions - Permission.perms.
* @param {string[]} keys - The array of keys to remove from the permission.
* @return {Number} Returns the number of removed permissions.
*/
function remove(perms, keys) {
var i,
removed = 0;
for (i = 0; i < keys.length; i++) {
if (perms.hasOwnProperty(keys[i])) {
delete perms[keys[i]];
removed++;
}
}
return removed;
}
module.exports = {
Permission,
Types,
}; | rojakcoder/archly | npm/src/permission.js | JavaScript | apache-2.0 | 13,491 |
import React from "react";
import { TRANSACTION_STATUSES } from "../enums/transactions";
const { AWAITING_PROCESS, PROCESSING, PROCESSED } = TRANSACTION_STATUSES;
const STATUS_MAP = {
"Awaiting Process": AWAITING_PROCESS,
Processing: PROCESSING,
Processed: PROCESSED
};
export default class TransactionStatusDropdown extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.props.onChange(event.target.value);
}
render() {
return (
<div className="bp3-select bp3-fill">
<select
disabled={this.props.disabled}
value={this.props.status}
onChange={this.handleChange}>
<option value="">Select a status</option>
{Object.entries(STATUS_MAP).map(([key, value]) => {
return (
<option key={value} value={value}>
{key}
</option>
);
})}
</select>
</div>
);
}
}
| umnretirees/membership-platform | assets/js/batch-transaction-form/transaction-status-dropdown.js | JavaScript | apache-2.0 | 1,033 |
// Generated by CoffeeScript 1.12.4
(function() {
var BaseButtonTask, ButtonTask,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
BaseButtonTask = require('zooniverse-decision-tree/lib/button-task');
ButtonTask = (function(superClass) {
extend(ButtonTask, superClass);
function ButtonTask() {
return ButtonTask.__super__.constructor.apply(this, arguments);
}
ButtonTask.prototype.choiceTemplate = require('../templates/choice');
return ButtonTask;
})(BaseButtonTask);
module.exports = ButtonTask;
}).call(this);
| zooniverse/zooniverse-readymade | lib/tasks/button.js | JavaScript | apache-2.0 | 829 |
// Copyright 2014 Traceur Authors.
//
// 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.
import {assert} from '../util/assert.js';
import {LoaderCompiler} from '../runtime/LoaderCompiler.js';
import {ExportsList} from '../codegeneration/module/ModuleSymbol.js';
import {Map} from './polyfills/Map.js';
import {isAbsolute, resolveUrl} from '../util/url.js';
import {Options} from '../Options.js';
var NOT_STARTED = 0;
var LOADING = 1;
var LOADED = 2;
var PARSED = 3;
var TRANSFORMING = 4
var TRANSFORMED = 5;
var COMPLETE = 6;
var ERROR = 7;
function mapToValues(map) {
// We are having issues with cross frame/context symbols so we cannot use
// iterators here.
// https://github.com/google/traceur-compiler/issues/1152
var array = [];
map.forEach((v) => {
array.push(v);
});
return array;
}
class LoaderError extends Error {
constructor(msg, tree) {
super();
this.message = msg;
this.tree = tree;
this.name = 'LoaderError';
}
}
/**
* Base class representing a piece of code that is to be loaded or evaluated.
* Similar to js-loader Load object
*/
class CodeUnit {
/**
* @param {LoaderCompiler} loaderCompiler Callbacks for parsing/transforming.
* @param {string} normalizedName The normalized name of this dependency.
* @param {string} type Either 'script' or 'module'. This determinse how to
* parse the code.
* @param {number} state
*/
constructor(loaderCompiler, normalizedName, type, state,
name, referrerName, address) {
this.promise = new Promise((res, rej) => {
this.loaderCompiler = loaderCompiler;
this.normalizedName = normalizedName;
this.type = type;
this.name_ = name;
this.referrerName_ = referrerName;
this.address = address;
this.state_ = state || NOT_STARTED;
this.error = null;
this.result = null;
this.metadata_ = {};
this.dependencies = [];
this.resolve = res;
this.reject = rej;
});
}
get state() {
return this.state_;
}
set state(value) {
if (value < this.state_) {
throw new Error('Invalid state change');
}
this.state_ = value;
}
/**
* @return opaque value set and used by loaderCompiler
*/
get metadata() {
return this.metadata_;
}
set metadata(value) {
assert(value);
this.metadata_ = value;
}
nameTrace() {
var trace = this.specifiedAs();
if (isAbsolute(this.name_)) {
return trace + 'An absolute name.\n';
}
if (this.referrerName_) {
return trace + this.importedBy() + this.normalizesTo();
}
return trace + this.normalizesTo();
}
specifiedAs() {
return `Specified as ${this.name_}.\n`;
}
importedBy() {
return `Imported by ${this.referrerName_}.\n`;
}
normalizesTo() {
return 'Normalizes to ' + this.normalizedName + '\n';
}
}
/**
* CodeUnit coming from {@code Loader.set}.
*/
class PreCompiledCodeUnit extends CodeUnit {
constructor(loaderCompiler, normalizedName, name, referrerName, address,
module) {
super(loaderCompiler, normalizedName, 'module', COMPLETE,
name, referrerName, address);
this.result = module;
this.resolve(this.result);
}
}
/**
* CodeUnit coming from {@code Loader.register}.
*/
class BundledCodeUnit extends CodeUnit {
constructor(loaderCompiler, normalizedName, name, referrerName, address,
deps, execute) {
super(loaderCompiler, normalizedName, 'module', TRANSFORMED,
name, referrerName, address);
this.deps = deps;
this.execute = execute;
}
getModuleSpecifiers() {
return this.deps;
}
evaluate() {
var normalizedNames =
this.deps.map((name) => this.loader_.normalize(name));
var module = this.execute.apply(Reflect.global, normalizedNames);
System.set(this.normalizedName, module);
return module;
}
}
/**
* CodeUnit for sharing methods that just call back to loaderCompiler
*/
class HookedCodeUnit extends CodeUnit {
getModuleSpecifiers() {
return this.loaderCompiler.getModuleSpecifiers(this);
}
evaluate() {
return this.loaderCompiler.evaluateCodeUnit(this);
}
}
/**
* CodeUnit used for {@code Loader.load}.
*/
class LoadCodeUnit extends HookedCodeUnit {
/**
* @param {InternalLoader} loader
* @param {string} normalizedName
*/
constructor(loaderCompiler, normalizedName, name, referrerName, address) {
super(loaderCompiler, normalizedName, 'module', NOT_STARTED,
name, referrerName, address);
}
}
/**
* CodeUnit used for {@code Loader.eval} and {@code Loader.module}.
*/
class EvalCodeUnit extends HookedCodeUnit {
/**
* @param {LoaderCompiler} loaderCompiler
* @param {string} code
* @param {string} caller script or module name
*/
constructor(loaderCompiler, code, type = 'script',
normalizedName, referrerName, address) {
super(loaderCompiler, normalizedName, type,
LOADED, null, referrerName, address);
this.source = code;
}
}
var uniqueNameCount = 0;
/**
* The internal implementation of the code loader.
*/
export class InternalLoader {
/**
* @param {loaderCompiler} loaderCompiler
*/
constructor(loader, loaderCompiler) {
assert(loaderCompiler);
this.loader_ = loader;
this.loaderCompiler = loaderCompiler;
this.cache = new Map();
this.urlToKey = Object.create(null);
this.sync_ = false;
this.sourceMapsByURL_ = Object.create(null);
this.sourceMapsByOutputName_ = Object.create(null);
}
defaultMetadata_(metadata = {}) {
let incoming = metadata.traceurOptions;
if (incoming && !(incoming instanceof Options)) {
var unknown = Options.listUnknownOptions(incoming);
if (unknown.length) {
console.warn('Unknown metadata.traceurOptions ignored: ' +
unknown.join(','));
}
}
metadata.traceurOptions = incoming || new Options();
return metadata;
}
defaultModuleMetadata_(metadata = {}) {
var metadata = this.defaultMetadata_(metadata);
metadata.traceurOptions.script = false;
return metadata;
}
getSourceMap(url) {
// The caller may want the sourcemap from input to output or vice versa.
return this.sourceMapsByURL_[url] || this.sourceMapsByOutputName_[url];
}
load(name, referrerName = this.loader_.baseURL,
address, metadata = {}) {
metadata = this.defaultMetadata_(metadata);
var codeUnit = this.getOrCreateCodeUnit_(name, referrerName, address, metadata);
this.load_(codeUnit);
return codeUnit.promise.then(() => codeUnit);
}
load_(codeUnit) {
if (codeUnit.state === ERROR) {
return codeUnit;
}
if (codeUnit.state === TRANSFORMED) {
this.handleCodeUnitLoaded(codeUnit)
} else {
if (codeUnit.state !== NOT_STARTED)
return codeUnit;
codeUnit.state = LOADING;
codeUnit.address = this.loader_.locate(codeUnit);
this.loader_.fetch(codeUnit).then((text) => {
codeUnit.source = text;
return codeUnit;
}).
then((load) => {
return this.loader_.translate(load)
}).
then((source) => {
codeUnit.source = source;
codeUnit.state = LOADED;
this.handleCodeUnitLoaded(codeUnit);
return codeUnit;
}).
catch((err) => {
try {
codeUnit.state = ERROR;
codeUnit.error = err;
this.handleCodeUnitLoadError(codeUnit);
} catch (ex) {
console.error('Internal Error ' + (ex.stack || ex));
}
});
}
return codeUnit;
}
module(code, referrerName, address, metadata) {
var codeUnit = new EvalCodeUnit(this.loaderCompiler, code, 'module',
null, referrerName, address);
codeUnit.metadata = this.defaultMetadata_(metadata);
this.cache.set({}, codeUnit);
this.handleCodeUnitLoaded(codeUnit);
return codeUnit.promise;
}
define(normalizedName, code, address, metadata) {
var codeUnit = new EvalCodeUnit(this.loaderCompiler, code, 'module',
normalizedName, null, address);
var key = this.getKey(normalizedName, 'module');
codeUnit.metadata = this.defaultMetadata_(metadata);
this.cache.set(key, codeUnit);
this.handleCodeUnitLoaded(codeUnit);
return codeUnit.promise;
}
/**
* @param {string} code, source to be compiled as 'Script'
* @param {string=} name, ModuleSpecifier-like name, not normalized.
* @param {string=} referrerName, normalized name of container
* @param {string=} address, URL
*/
script(code, name, referrerName, address, metadata) {
var normalizedName = System.normalize(name || '', referrerName, address);
var codeUnit = new EvalCodeUnit(this.loaderCompiler, code, 'script',
normalizedName, referrerName, address);
var key = {};
if (name)
key = this.getKey(normalizedName, 'script');
codeUnit.metadata = this.defaultMetadata_(metadata);
this.cache.set(key, codeUnit);
this.handleCodeUnitLoaded(codeUnit);
return codeUnit.promise;
}
getKey(url, type) {
var combined = type + ':' + url;
if (combined in this.urlToKey) {
return this.urlToKey[combined];
}
return this.urlToKey[combined] = {};
}
getCodeUnit_(normalizedName, type) {
var key = this.getKey(normalizedName, type);
var codeUnit = this.cache.get(key);
return {key, codeUnit};
}
getOrCreateCodeUnit_(name, referrerName, address, metadata) {
var normalizedName = System.normalize(name, referrerName, address);
// TODO(jjb): embed type in name per es-discuss Yehuda Katz,
// eg import 'name,script';
var type = 'module';
if (metadata && metadata.traceurOptions && metadata.traceurOptions.script)
type = 'script';
var {key, codeUnit} = this.getCodeUnit_(normalizedName, type);
if (!codeUnit) {
// All new code units need metadata set.
assert(metadata && metadata.traceurOptions);
var module = this.loader_.get(normalizedName);
if (module) {
codeUnit = new PreCompiledCodeUnit(this.loaderCompiler, normalizedName,
name, referrerName, address, module);
codeUnit.type = 'module';
} else {
var bundledModule = this.loader_.bundledModule(name);
if (bundledModule) {
codeUnit = new BundledCodeUnit(this.loaderCompiler, normalizedName,
name, referrerName, address,
bundledModule.deps, bundledModule.execute);
} else {
codeUnit = new LoadCodeUnit(this.loaderCompiler, normalizedName,
name, referrerName, address);
codeUnit.type = type;
}
}
// We copy the incoming metadata to pass values from the API and to
// inherit value from the API call into modules imported by the root.
// But we don't want to inherit tree etc.
// TODO(jjb): move this into the CodeUnit constructors.
codeUnit.metadata = {
traceurOptions: metadata.traceurOptions,
outputName: metadata.outputName,
};
this.cache.set(key, codeUnit);
}
return codeUnit;
}
areAll(state) {
return mapToValues(this.cache).every((codeUnit) => codeUnit.state >= state);
}
getCodeUnitForModuleSpecifier(name, referrerName) {
var normalizedName = this.loader_.normalize(name, referrerName);
return this.getCodeUnit_(normalizedName, 'module').codeUnit;
}
getExportsListForModuleSpecifier(name, referrer) {
var codeUnit = this.getCodeUnitForModuleSpecifier(name, referrer);
var exportsList = codeUnit.metadata.moduleSymbol;
if (!exportsList) {
if (codeUnit.result) {
exportsList =
new ExportsList(codeUnit.normalizedName);
exportsList.addExportsFromModule(codeUnit.result);
} else {
throw new Error(
`InternalError: ${name} is not a module, required by ${referrer}`);
}
}
return exportsList;
}
/**
* This is called when a codeUnit is loaded.
* @param {CodeUnit} codeUnit
*/
handleCodeUnitLoaded(codeUnit) {
var referrerName = codeUnit.normalizedName;
try {
var moduleSpecifiers = codeUnit.getModuleSpecifiers();
if (!moduleSpecifiers) {
this.abortAll(`No module specifiers in ${referrerName}`);
return;
}
codeUnit.dependencies = moduleSpecifiers.sort().map((name) => {
return this.getOrCreateCodeUnit_(name, referrerName, null,
this.defaultModuleMetadata_(codeUnit.metadata));
});
} catch (error) {
this.rejectOneAndAll(codeUnit, error);
return;
}
codeUnit.dependencies.forEach((dependency) => {
this.load_(dependency);
});
if (this.areAll(PARSED)) {
try {
// Currently analyze is only needed for module dependencies.
if (codeUnit.type === 'module')
this.analyze();
this.transform();
this.evaluate();
} catch (error) {
this.rejectOneAndAll(codeUnit, error);
}
}
}
rejectOneAndAll(codeUnit, error) {
codeUnit.state.ERROR;
codeUnit.error = error;
codeUnit.reject(error);
// TODO(jjb): reject the other codeUnits with a distinct error.
this.abortAll(error);
}
/**
* This is called when a code unit failed to load.
* @param {CodeUnit} codeUnit
*/
handleCodeUnitLoadError(codeUnit) {
var message = codeUnit.error ? String(codeUnit.error) + '\n' :
`Failed to load '${codeUnit.address}'.\n`;
message += codeUnit.nameTrace() + this.loader_.nameTrace(codeUnit);
this.rejectOneAndAll(codeUnit, new Error(message));
}
/**
* Aborts all loading code units.
*/
abortAll(errorMessage) {
// Notify all codeUnit listeners (else tests hang til timeout).
this.cache.forEach((codeUnit) => {
if (codeUnit.state !== ERROR)
codeUnit.reject(errorMessage);
});
}
analyze() {
this.loaderCompiler.analyzeDependencies(mapToValues(this.cache), this);
}
transform() {
this.transformDependencies_(mapToValues(this.cache));
}
transformDependencies_(dependencies, dependentName) {
for (var i = 0; i < dependencies.length; i++) {
var codeUnit = dependencies[i];
if (codeUnit.state >= TRANSFORMED) {
continue;
}
if (codeUnit.state === TRANSFORMING) {
var cir = codeUnit.normalizedName;
var cle = dependentName;
this.rejectOneAndAll(codeUnit, new Error(
`Unsupported circular dependency between ${cir} and ${cle}`));
return;
}
codeUnit.state = TRANSFORMING;
try {
this.transformCodeUnit_(codeUnit);
} catch(error) {
this.rejectOneAndAll(codeUnit, error);
return;
}
}
}
transformCodeUnit_(codeUnit) {
this.transformDependencies_(codeUnit.dependencies, codeUnit.normalizedName);
if (codeUnit.state === ERROR)
return;
this.loaderCompiler.transform(codeUnit);
codeUnit.state = TRANSFORMED;
this.loaderCompiler.write(codeUnit);
var info = codeUnit.metadata.compiler.sourceMapInfo;
if (info) {
this.sourceMapsByURL_[info.url] = info.map;
this.sourceMapsByOutputName_[info.outputName] = info.map;
}
this.loader_.instantiate(codeUnit);
}
orderDependencies() {
// Order the dependencies.
var visited = new Map();
var ordered = [];
function orderCodeUnits(codeUnit) {
// Cyclic dependency.
if (visited.has(codeUnit)) {
return;
}
visited.set(codeUnit, true);
codeUnit.dependencies.forEach(orderCodeUnits);
ordered.push(codeUnit);
}
this.cache.forEach(orderCodeUnits);
return ordered;
}
evaluate() {
var dependencies = this.orderDependencies();
for (var i = 0; i < dependencies.length; i++) {
var codeUnit = dependencies[i];
if (codeUnit.state >= COMPLETE) {
continue;
}
var result;
try {
result = codeUnit.evaluate();
} catch (ex) {
this.rejectOneAndAll(codeUnit, ex);
return;
}
codeUnit.result = result;
codeUnit.source = null;
}
for (var i = 0; i < dependencies.length; i++) {
var codeUnit = dependencies[i];
if (codeUnit.state >= COMPLETE) {
continue;
}
codeUnit.state = COMPLETE;
codeUnit.resolve(codeUnit.result);
}
}
}
export var internals = {
CodeUnit,
EvalCodeUnit,
LoadCodeUnit,
LoaderCompiler
};
| vicb/traceur-compiler | src/runtime/InternalLoader.js | JavaScript | apache-2.0 | 17,018 |
// *****************************************************************************
// Copyright 2013-2019 Aerospike, 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'
/* eslint-env mocha */
/* global expect */
const Aerospike = require('../lib/aerospike')
const helper = require('./test_helper')
const AerospikeError = Aerospike.AerospikeError
const lists = Aerospike.lists
const ops = Aerospike.operations
const Context = Aerospike.cdt.Context
const status = Aerospike.status
const eql = require('deep-eql')
const {
assertError,
assertRecordEql,
assertResultEql,
assertResultSatisfy,
cleanup,
createRecord,
expectError,
initState,
operate
} = require('./util/statefulAsyncTest')
const orderList = (bin, ctx) => {
const setListOrder = lists.setOrder(bin, lists.order.ORDERED)
if (ctx) setListOrder.withContext(ctx)
return operate(setListOrder)
}
describe('client.operate() - CDT List operations', function () {
helper.skipUnlessSupportsFeature(Aerospike.features.CDT_LIST, this)
let ListOutOfBoundsError
before(() => {
ListOutOfBoundsError = helper.cluster.isVersionInRange('>=4.6.0')
? status.ERR_OP_NOT_APPLICABLE
: status.ERR_REQUEST_INVALID
})
describe('lists.setOrder', function () {
it('changes the list order', function () {
return initState()
.then(createRecord({ list: [3, 1, 2] }))
.then(operate([
lists.setOrder('list', lists.order.ORDERED),
ops.read('list')
]))
.then(assertResultEql({ list: [1, 2, 3] }))
.then(cleanup())
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('changes the order of a nested list', function () {
return initState()
.then(createRecord({ list: [[3, 1, 2], [6, 5, 4]] }))
.then(operate([
lists.setOrder('list', lists.order.ORDERED).withContext(ctx => ctx.addListIndex(0)),
lists.setOrder('list', lists.order.ORDERED).withContext(ctx => ctx.addListIndex(1)),
ops.read('list')
]))
.then(assertResultEql({ list: [[1, 2, 3], [4, 5, 6]] }))
.then(cleanup())
})
})
})
describe('lists.sort', function () {
it('sorts the list', function () {
return initState()
.then(createRecord({ list: [3, 1, 2, 1] }))
.then(operate([
lists.sort('list', lists.sortFlags.DEFAULT),
ops.read('list')
]))
.then(assertResultEql({ list: [1, 1, 2, 3] }))
.then(cleanup())
})
context('with DROP_DUPLICATES flag', function () {
it('sorts the list and drops duplicates', function () {
return initState()
.then(createRecord({ list: [3, 1, 2, 1] }))
.then(operate([
lists.sort('list', lists.sortFlags.DROP_DUPLICATES),
ops.read('list')
]))
.then(assertResultEql({ list: [1, 2, 3] }))
.then(cleanup())
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('sorts a nested list', function () {
return initState()
.then(createRecord({ list: [['a', 'b', 'c'], [3, 1, 2, 1]] }))
.then(operate([
lists.sort('list', lists.sortFlags.DEFAULT).withContext(ctx => ctx.addListIndex(-1)),
ops.read('list')
]))
.then(assertResultEql({ list: [['a', 'b', 'c'], [1, 1, 2, 3]] }))
.then(cleanup())
})
})
})
describe('lists.append', function () {
it('appends an item to the list and returns the list size', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.append('list', 99)))
.then(assertResultEql({ list: 6 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5, 99] }))
.then(cleanup)
})
context('with add-unique flag', function () {
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE
}
it('returns an error when trying to append a non-unique element', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.append('list', 3, policy)))
.then(assertError(status.ERR_FAIL_ELEMENT_EXISTS))
.then(cleanup)
})
context('with no-fail flag', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE | lists.writeFlags.NO_FAIL
}
it('returns an error when trying to append a non-unique element', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.append('list', 3, policy)))
.then(assertResultEql({ list: 5 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5] }))
.then(cleanup)
})
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('appends a value to a nested list', function () {
return initState()
.then(createRecord({ list: [1, 2, ['a', 'b', 'c'], 4, 5] }))
.then(operate(lists.append('list', 'd').withContext(ctx => ctx.addListIndex(2))))
.then(assertResultEql({ list: 4 }))
.then(assertRecordEql({ list: [1, 2, ['a', 'b', 'c', 'd'], 4, 5] }))
.then(cleanup)
})
})
})
describe('lists.appendItems', function () {
it('appends the items to the list and returns the list size', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.appendItems('list', [99, 100])))
.then(assertResultEql({ list: 7 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5, 99, 100] }))
.then(cleanup)
})
it('returns an error if the value to append is not an array', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.appendItems('list', 99)))
.then(assertError(status.ERR_PARAM))
.then(cleanup)
})
context('with add-unique flag', function () {
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE
}
it('returns an error when appending duplicate items', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.appendItems('list', [3, 6], policy)))
.then(assertError(status.ERR_FAIL_ELEMENT_EXISTS))
.then(cleanup)
})
context('with no-fail flag', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE | lists.writeFlags.NO_FAIL
}
it('does not append any items but returns ok', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.appendItems('list', [3, 6], policy)))
.then(assertResultEql({ list: 5 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5] }))
.then(cleanup)
})
context('with partial flag', function () {
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE | lists.writeFlags.NO_FAIL | lists.writeFlags.PARTIAL
}
it('appends only the unique items', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.appendItems('list', [3, 6], policy)))
.then(assertResultEql({ list: 6 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5, 6] }))
.then(cleanup)
})
})
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('appends the items to a nested list', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(lists.appendItems('map', [99, 100]).withContext(ctx => ctx.addMapKey('list'))))
.then(assertResultEql({ map: 7 }))
.then(assertRecordEql({ map: { list: [1, 2, 3, 4, 5, 99, 100] } }))
.then(cleanup)
})
})
})
describe('lists.insert', function () {
it('inserts the item at the specified index and returns the list size', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.insert('list', 2, 99)))
.then(assertResultEql({ list: 6 }))
.then(assertRecordEql({ list: [1, 2, 99, 3, 4, 5] }))
.then(cleanup)
})
context('with add-unique flag', function () {
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE
}
it('returns an error when trying to insert a non-unique element', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.insert('list', 2, 3, policy)))
.then(assertError(status.ERR_FAIL_ELEMENT_EXISTS))
.then(cleanup)
})
context('with no-fail flag', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE | lists.writeFlags.NO_FAIL
}
it('does not insert the item but returns ok', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.insert('list', 2, 3, policy)))
.then(assertResultEql({ list: 5 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5] }))
.then(cleanup)
})
})
})
context('with insert-bounded flag', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
const policy = new Aerospike.ListPolicy({
writeFlags: lists.writeFlags.INSERT_BOUNDED
})
it('returns an error when trying to insert an item outside the current bounds of the list', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.insert('list', 10, 99, policy)))
.then(assertError(ListOutOfBoundsError))
.then(cleanup)
})
context('with no-fail flag', function () {
const policy = new Aerospike.ListPolicy({
writeFlags: lists.writeFlags.INSERT_BOUNDED | lists.writeFlags.NO_FAIL
})
it('does not insert an item outside bounds, but returns ok', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.insert('list', 10, 99, policy)))
.then(assertResultEql({ list: 5 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5] }))
.then(cleanup)
})
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('inserts the item at the specified index of a nested list', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(lists.insert('map', 2, 99).withContext(ctx => ctx.addMapKey('list'))))
.then(assertResultEql({ map: 6 }))
.then(assertRecordEql({ map: { list: [1, 2, 99, 3, 4, 5] } }))
.then(cleanup)
})
})
})
describe('lists.insertItems', function () {
it('inserts the items at the specified index and returns the list size', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.insertItems('list', 2, [99, 100])))
.then(assertResultEql({ list: 7 }))
.then(assertRecordEql({ list: [1, 2, 99, 100, 3, 4, 5] }))
.then(cleanup)
})
it('returns an error if the value to insert is not an array', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.insertItems('list', 2, 99)))
.then(assertError(status.ERR_PARAM))
.then(cleanup)
})
context('with add-unique flag', function () {
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE
}
it('returns an error when trying to insert items that already exist in the list', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.insertItems('list', 2, [3, 99], policy)))
.then(assertError(status.ERR_FAIL_ELEMENT_EXISTS))
.then(cleanup)
})
context('with no-fail flag', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE | lists.writeFlags.NO_FAIL
}
it('does not insert any items but returns ok', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.insertItems('list', 2, [3, 99], policy)))
.then(assertResultEql({ list: 5 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5] }))
.then(cleanup)
})
context('with partial flag', function () {
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE | lists.writeFlags.NO_FAIL | lists.writeFlags.PARTIAL
}
it('inserts only the unique items', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.insertItems('list', 2, [3, 99], policy)))
.then(assertResultEql({ list: 6 }))
.then(assertRecordEql({ list: [1, 2, 99, 3, 4, 5] }))
.then(cleanup)
})
})
})
})
context('with insert-bounded flag', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
const policy = new Aerospike.ListPolicy({
writeFlags: lists.writeFlags.INSERT_BOUNDED
})
it('returns an error when trying to insert items outside the current bounds of the list', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.insertItems('list', 10, [99, 100], policy)))
.then(assertError(ListOutOfBoundsError))
.then(cleanup)
})
context('with no-fail flag', function () {
const policy = new Aerospike.ListPolicy({
writeFlags: lists.writeFlags.INSERT_BOUNDED | lists.writeFlags.NO_FAIL
})
it('does not insert the items outside bounds, but returns ok', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.insertItems('list', 10, [99, 100], policy)))
.then(assertResultEql({ list: 5 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5] }))
.then(cleanup)
})
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('inserts the items at the specified index of a nested list', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(lists.insertItems('map', 2, [99, 100]).withContext(ctx => ctx.addMapKey('list'))))
.then(assertResultEql({ map: 7 }))
.then(assertRecordEql({ map: { list: [1, 2, 99, 100, 3, 4, 5] } }))
.then(cleanup)
})
})
})
describe('lists.pop', function () {
it('removes the item at the specified index and returns it', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.pop('list', 2)))
.then(assertResultEql({ list: 3 }))
.then(assertRecordEql({ list: [1, 2, 4, 5] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes the item at the specified index and returns it', function () {
return initState()
.then(createRecord({ list: [[1, 2, 3, 4, 5], [6, 7, 8]] }))
.then(operate(lists.pop('list', 2).withContext(ctx => ctx.addListIndex(0))))
.then(assertResultEql({ list: 3 }))
.then(assertRecordEql({ list: [[1, 2, 4, 5], [6, 7, 8]] }))
.then(cleanup)
})
})
})
describe('lists.popRange', function () {
it('removes the items at the specified range and returns them', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.popRange('list', 2, 2)))
.then(assertResultEql({ list: [3, 4] }))
.then(assertRecordEql({ list: [1, 2, 5] }))
.then(cleanup)
})
it('removes and returns all items starting from the specified index if count is not specified', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.popRange('list', 2)))
.then(assertResultEql({ list: [3, 4, 5] }))
.then(assertRecordEql({ list: [1, 2] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes the items in the specified range and returns them', function () {
return initState()
.then(createRecord({ list: [[1, 2, 3, 4, 5], [6, 7, 8]] }))
.then(operate(lists.popRange('list', 2).withContext(ctx => ctx.addListIndex(1))))
.then(assertResultEql({ list: [8] }))
.then(assertRecordEql({ list: [[1, 2, 3, 4, 5], [6, 7]] }))
.then(cleanup)
})
})
})
describe('lists.remove', function () {
it('removes the item at the specified index and returns the number of items removed', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.remove('list', 2)))
.then(assertResultEql({ list: 1 }))
.then(assertRecordEql({ list: [1, 2, 4, 5] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes the item at the specified index', function () {
return initState()
.then(createRecord({ list: [[1, 2, 3, 4, 5], [6, 7, 8]] }))
.then(operate(lists.remove('list', 2).withContext(ctx => ctx.addListIndex(1))))
.then(assertResultEql({ list: 1 }))
.then(assertRecordEql({ list: [[1, 2, 3, 4, 5], [6, 7]] }))
.then(cleanup)
})
})
})
describe('lists.removeRange', function () {
it('removes the items in the specified range and returns the number of items removed', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.removeRange('list', 2, 2)))
.then(assertResultEql({ list: 2 }))
.then(assertRecordEql({ list: [1, 2, 5] }))
.then(cleanup)
})
it('removes all items starting from the specified index and returns the number of items removed if count is not specified', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.removeRange('list', 2)))
.then(assertResultEql({ list: 3 }))
.then(assertRecordEql({ list: [1, 2] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes the item at the specified range', function () {
return initState()
.then(createRecord({ list: [[1, 2, 3, 4, 5], [6, 7, 8]] }))
.then(operate(lists.removeRange('list', 1, 3).withContext(ctx => ctx.addListIndex(0))))
.then(assertResultEql({ list: 3 }))
.then(assertRecordEql({ list: [[1, 5], [6, 7, 8]] }))
.then(cleanup)
})
})
})
describe('lists.removeByIndex', function () {
context('returnType=VALUE', function () {
it('removes the item at the specified index and returns the value', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.removeByIndex('list', 2).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: 3 }))
.then(assertRecordEql({ list: [1, 2, 4, 5] }))
.then(cleanup)
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes the item at the specified index', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(lists.removeByIndex('map', 2).withContext(ctx => ctx.addMapKey('list'))))
.then(assertRecordEql({ map: { list: [1, 2, 4, 5] } }))
.then(cleanup)
})
})
})
describe('lists.removeByIndexRange', function () {
context('returnType=VALUE', function () {
it('removes the items in the specified range and returns the values', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.removeByIndexRange('list', 2, 2).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: [3, 4] }))
.then(assertRecordEql({ list: [1, 2, 5] }))
.then(cleanup)
})
it('removes the items starting from the specified index and returns the values', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.removeByIndexRange('list', 2).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: [3, 4, 5] }))
.then(assertRecordEql({ list: [1, 2] }))
.then(cleanup)
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes the item int the specified range', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(lists.removeByIndexRange('map', 1, 3).withContext(ctx => ctx.addMapKey('list'))))
.then(assertRecordEql({ map: { list: [1, 5] } }))
.then(cleanup)
})
})
})
describe('lists.removeByValue', function () {
context('returnType=INDEX', function () {
it('removes all items with the specified value and returns the indexes', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 1, 2, 3] }))
.then(operate(lists.removeByValue('list', 3).andReturn(lists.returnType.INDEX)))
.then(assertResultEql({ list: [2, 5] }))
.then(assertRecordEql({ list: [1, 2, 1, 2] }))
.then(cleanup)
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes all items with the specified value', function () {
return initState()
.then(createRecord({ list: [[3, 2, 1], [1, 2, 3, 1, 2, 3]] }))
.then(operate(lists.removeByValue('list', 3).withContext(ctx => ctx.addListValue([3, 2, 1]))))
.then(assertRecordEql({ list: [[2, 1], [1, 2, 3, 1, 2, 3]] }))
.then(cleanup)
})
})
})
describe('lists.removeByValueList', function () {
context('returnType=INDEX', function () {
it('removes all items with the specified values and returns the indexes', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 1, 2, 3] }))
.then(operate(lists.removeByValueList('list', [1, 3]).andReturn(lists.returnType.INDEX)))
.then(assertResultEql({ list: [0, 2, 3, 5] }))
.then(assertRecordEql({ list: [2, 2] }))
.then(cleanup)
})
})
context('invert results', function () {
it('removes all items except with the specified values', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 1, 2, 3] }))
.then(operate(lists.removeByValueList('list', [1, 3]).invertSelection()))
.then(assertRecordEql({ list: [1, 3, 1, 3] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes all items except with the specified values', function () {
return initState()
.then(createRecord({ list: [[3, 2, 1], [1, 2, 3, 1, 2, 3]] }))
.then(operate(
lists
.removeByValueList('list', [1, 4])
.withContext(ctx => ctx.addListIndex(-1))
.invertSelection()
))
.then(assertRecordEql({ list: [[3, 2, 1], [1, 1]] }))
.then(cleanup)
})
})
})
})
describe('lists.removeByValueRange', function () {
context('returnType=INDEX', function () {
it('removes all items in the specified range of values and returns the indexes', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.removeByValueRange('list', 2, 5).andReturn(lists.returnType.INDEX)))
.then(assertResultEql({ list: [1, 2, 3] }))
.then(assertRecordEql({ list: [1, 5] }))
.then(cleanup)
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes all items in the specified range of values', function () {
return initState()
.then(createRecord({ list: [[1, 2, 3, 4, 5], [6, 7, 8]] }))
.then(operate(lists.removeByValueRange('list', 2, 5).withContext(ctx => ctx.addListIndex(0))))
.then(assertRecordEql({ list: [[1, 5], [6, 7, 8]] }))
.then(cleanup)
})
})
})
describe('lists.removeByValueRelRankRange', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
context('with count', function () {
it('removes all items nearest to value and greater, by relative rank', function () {
return initState()
.then(createRecord({ list: [0, 4, 5, 9, 11, 15] }))
.then(orderList('list'))
.then(operate(lists.removeByValueRelRankRange('list', 5, 0, 2).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: [5, 9] }))
.then(assertRecordEql({ list: [0, 4, 11, 15] }))
.then(cleanup)
})
})
context('without count', function () {
it('removes all items nearest to value and greater, by relative rank', function () {
return initState()
.then(createRecord({ list: [0, 4, 5, 9, 11, 15] }))
.then(orderList('list'))
.then(operate(lists.removeByValueRelRankRange('list', 5, 0).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: [5, 9, 11, 15] }))
.then(assertRecordEql({ list: [0, 4] }))
.then(cleanup)
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes all items nearest to value and greater, by relative rank', function () {
const listContext = new Context().addMapKey('list')
return initState()
.then(createRecord({ map: { list: [0, 4, 5, 9, 11, 15] } }))
.then(orderList('map', listContext))
.then(operate(lists.removeByValueRelRankRange('map', 5, 0, 2).withContext(listContext)))
.then(assertRecordEql({ map: { list: [0, 4, 11, 15] } }))
.then(cleanup)
})
})
})
describe('lists.removeByRank', function () {
context('returnType=VALUE', function () {
it('removes the item with the specified list rank and returns the value', function () {
return initState()
.then(createRecord({ list: [3, 1, 2, 4] }))
.then(operate(lists.removeByRank('list', 1).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: 2 }))
.then(assertRecordEql({ list: [3, 1, 4] }))
.then(cleanup)
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes the item with the specified list rank', function () {
return initState()
.then(createRecord({ list: [[2, 3, 1, 4], [3, 1, 2, 4]] }))
.then(operate(lists.removeByRank('list', 1).withContext(ctx => ctx.addListIndex(1))))
.then(assertRecordEql({ list: [[2, 3, 1, 4], [3, 1, 4]] }))
.then(cleanup)
})
})
})
describe('lists.removeByRankRange', function () {
context('returnType=VALUE', function () {
it('removes the item with the specified list rank and returns the value', function () {
return initState()
.then(createRecord({ list: [3, 1, 2, 5, 4] }))
.then(operate(lists.removeByRankRange('list', 1, 3).andReturn(lists.returnType.VALUE)))
.then(assertResultSatisfy(result => eql(result.list.sort(), [2, 3, 4])))
.then(assertRecordEql({ list: [1, 5] }))
.then(cleanup)
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes the item with the specified list rank', function () {
return initState()
.then(createRecord({ list: [[3, 1, 2, 5, 4], [1, 2, 3]] }))
.then(operate(lists.removeByRankRange('list', 1, 3).withContext(ctx => ctx.addListIndex(0))))
.then(assertRecordEql({ list: [[1, 5], [1, 2, 3]] }))
.then(cleanup)
})
})
})
describe('lists.clear', function () {
it('removes all elements from the list', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.clear('list')))
.then(assertRecordEql({ list: [] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes all elements from the list', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(lists.clear('map').withContext(ctx => ctx.addMapKey('list'))))
.then(assertRecordEql({ map: { list: [] } }))
.then(cleanup)
})
})
})
describe('lists.set', function () {
it('sets the item at the specified index', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.set('list', 2, 99)))
.then(assertRecordEql({ list: [1, 2, 99, 4, 5] }))
.then(cleanup)
})
context('with add-unique flag', function () {
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE
}
it('fails with an error if the value already exists in the list', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.set('list', 2, 5, policy)))
.then(assertError(status.ERR_FAIL_ELEMENT_EXISTS))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5] }))
.then(cleanup)
})
context('with no-fail flag', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE | lists.writeFlags.NO_FAIL
}
it('does not set the value but returns ok', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.set('list', 2, 5, policy)))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5] }))
.then(cleanup)
})
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('sets the item at the specified index', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(lists.set('map', 2, 99).withContext(ctx => ctx.addMapKey('list'))))
.then(assertRecordEql({ map: { list: [1, 2, 99, 4, 5] } }))
.then(cleanup)
})
})
})
describe('lists.trim', function () {
it('removes all elements not within the specified range and returns the number of elements removed', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.trim('list', 1, 3)))
.then(assertResultEql({ list: 2 }))
.then(assertRecordEql({ list: [2, 3, 4] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('removes all elements not within the specified range', function () {
return initState()
.then(createRecord({ list: [['a', 'b', 'c'], [1, 2, 3, 4, 5]] }))
.then(operate(lists.trim('list', 1, 3).withContext(ctx => ctx.addListValue([1, 2, 3, 4, 5]))))
.then(assertResultEql({ list: 2 }))
.then(assertRecordEql({ list: [['a', 'b', 'c'], [2, 3, 4]] }))
.then(cleanup)
})
})
})
describe('lists.get', function () {
it('returns the item at the specified index', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.get('list', 2)))
.then(assertResultEql({ list: 3 }))
.then(cleanup)
})
it('should return an error if the index is out of bounds', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.get('list', 99)))
.then(assertError(ListOutOfBoundsError))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('returns the item at the specified index', function () {
return initState()
.then(createRecord({ list: [['a', 'b', 'c'], [1, 2, 3, 4, 5]] }))
.then(operate(lists.get('list', 2).withContext(ctx => ctx.addListIndex(1))))
.then(assertResultEql({ list: 3 }))
.then(cleanup)
})
})
})
describe('lists.getRange', function () {
it('returns the items in the specified range', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.getRange('list', 1, 3)))
.then(assertResultEql({ list: [2, 3, 4] }))
.then(cleanup)
})
it('returns all items starting at the specified index if count is not specified', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.getRange('list', 1)))
.then(assertResultEql({ list: [2, 3, 4, 5] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('returns the items in the specified range', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(lists.getRange('map', 1, 3).withContext(ctx => ctx.addMapKey('list'))))
.then(assertResultEql({ map: [2, 3, 4] }))
.then(cleanup)
})
})
})
describe('lists.getByIndex', function () {
context('returnType=VALUE', function () {
it('fetches the item at the specified index and returns its value', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.getByIndex('list', 2).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: 3 }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('fetches the item at the specified index and returns its value', function () {
return initState()
.then(createRecord({ list: [['a', 'b', 'c'], [1, 2, 3, 4, 5]] }))
.then(operate(
lists
.getByIndex('list', 2)
.withContext(ctx => ctx.addListIndex(1))
.andReturn(lists.returnType.VALUE)
))
.then(assertResultEql({ list: 3 }))
.then(cleanup)
})
})
})
})
describe('lists.getByIndexRange', function () {
context('returnType=VALUE', function () {
it('fetches the items in the specified range and returns the values', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.getByIndexRange('list', 2, 2).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: [3, 4] }))
.then(cleanup)
})
it('fetches the items starting from the specified index and returns the values', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.getByIndexRange('list', 2).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: [3, 4, 5] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('fetches the items in the specified range and returns the values', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(
lists
.getByIndexRange('map', 2, 2)
.withContext(ctx => ctx.addMapKey('list'))
.andReturn(lists.returnType.VALUE)
))
.then(assertResultEql({ map: [3, 4] }))
.then(cleanup)
})
})
})
})
describe('lists.getByValue', function () {
context('returnType=INDEX', function () {
it('fetches all items with the specified value and returns the indexes', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 1, 2, 3] }))
.then(operate(lists.getByValue('list', 3).andReturn(lists.returnType.INDEX)))
.then(assertResultEql({ list: [2, 5] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('fetches all items with the specified value and returns the indexes', function () {
return initState()
.then(createRecord({ list: [['a', 'b', 'c'], [1, 2, 3, 1, 2, 3]] }))
.then(operate(
lists
.getByValue('list', 3)
.withContext(ctx => ctx.addListIndex(1))
.andReturn(lists.returnType.INDEX)
))
.then(assertResultEql({ list: [2, 5] }))
.then(cleanup)
})
})
})
})
describe('lists.getByValueList', function () {
context('returnType=INDEX', function () {
it('fetches all items with the specified values and returns the indexes', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 1, 2, 3] }))
.then(operate(lists.getByValueList('list', [1, 3]).andReturn(lists.returnType.INDEX)))
.then(assertResultEql({ list: [0, 2, 3, 5] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('fetches all items with the specified values and returns the indexes', function () {
return initState()
.then(createRecord({ list: [['a', 'b', 'c'], [1, 2, 3, 1, 2, 3]] }))
.then(operate(
lists
.getByValueList('list', [1, 3])
.withContext(ctx => ctx.addListIndex(1))
.andReturn(lists.returnType.INDEX)
))
.then(assertResultEql({ list: [0, 2, 3, 5] }))
.then(cleanup)
})
})
})
context('invert results', function () {
it('fetches all items except with the specified values', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 1, 2, 3] }))
.then(operate(lists.getByValueList('list', [1, 3]).invertSelection().andReturn(lists.returnType.INDEX)))
.then(assertResultEql({ list: [1, 4] }))
.then(cleanup)
})
})
})
describe('lists.getByValueRange', function () {
context('returnType=INDEX', function () {
it('fetches all items in the specified range of values and returns the indexes', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.getByValueRange('list', 2, 5).andReturn(lists.returnType.INDEX)))
.then(assertResultEql({ list: [1, 2, 3] }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('fetches all items in the specified range of values and returns the indexes', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(
lists
.getByValueRange('map', 2, 5)
.withContext(ctx => ctx.addMapKey('list'))
.andReturn(lists.returnType.INDEX)
))
.then(assertResultEql({ map: [1, 2, 3] }))
.then(cleanup)
})
})
})
})
describe('lists.getByValueRelRankRange', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
context('with count', function () {
it('fetches all items nearest to value and greater, by relative rank', function () {
return initState()
.then(createRecord({ list: [0, 4, 5, 9, 11, 15] }))
.then(orderList('list'))
.then(operate(lists.getByValueRelRankRange('list', 5, 0, 2).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: [5, 9] }))
.then(cleanup)
})
})
context('without count', function () {
it('fetches all items nearest to value and greater, by relative rank', function () {
return initState()
.then(createRecord({ list: [0, 4, 5, 9, 11, 15] }))
.then(orderList('list'))
.then(operate(lists.getByValueRelRankRange('list', 5, 0).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: [5, 9, 11, 15] }))
.then(cleanup)
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('fetches all items nearest to value and greater, by relative rank', function () {
const listContext = new Context().addMapKey('list')
return initState()
.then(createRecord({ map: { list: [0, 4, 5, 9, 11, 15] } }))
.then(orderList('map', listContext))
.then(operate(
lists
.getByValueRelRankRange('map', 5, 0, 2)
.withContext(listContext)
.andReturn(lists.returnType.VALUE)
))
.then(assertResultEql({ map: [5, 9] }))
.then(cleanup)
})
})
})
describe('lists.getByRank', function () {
context('returnType=VALUE', function () {
it('fetches the item with the specified list rank and returns the value', function () {
return initState()
.then(createRecord({ list: [3, 1, 2, 4] }))
.then(operate(lists.getByRank('list', 1).andReturn(lists.returnType.VALUE)))
.then(assertResultEql({ list: 2 }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('fetches the item with the specified list rank and returns the value', function () {
return initState()
.then(createRecord({ list: [[3, 1, 2, 4], ['a', 'b', 'c']] }))
.then(operate(
lists
.getByRank('list', 1)
.withContext(ctx => ctx.addListIndex(0))
.andReturn(lists.returnType.VALUE)
))
.then(assertResultEql({ list: 2 }))
.then(cleanup)
})
})
})
})
describe('lists.getByRankRange', function () {
context('returnType=VALUE', function () {
it('fetches the item with the specified list rank and returns the value', function () {
return initState()
.then(createRecord({ list: [3, 1, 2, 5, 4] }))
.then(operate(lists.getByRankRange('list', 1, 3).andReturn(lists.returnType.VALUE)))
.then(assertResultSatisfy(result => eql(result.list.sort(), [2, 3, 4])))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('fetches the item with the specified list rank and returns the value', function () {
return initState()
.then(createRecord({ list: [[3, 1, 2, 5, 4], ['a', 'b', 'c']] }))
.then(operate(
lists
.getByRankRange('list', 1, 3)
.withContext(ctx => ctx.addListIndex(0))
.andReturn(lists.returnType.VALUE)
))
.then(assertResultSatisfy(result => eql(result.list.sort(), [2, 3, 4])))
.then(cleanup)
})
})
})
})
describe('lists.increment', function () {
helper.skipUnlessVersion('>= 3.15.0', this)
it('increments the element at the specified index and returns the final value', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.increment('list', 1, 3)))
.then(assertResultEql({ list: 5 }))
.then(assertRecordEql({ list: [1, 5, 3, 4, 5] }))
.then(cleanup)
})
it('increments the element at the specified index by one and returns the final value', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.increment('list', 2)))
.then(assertResultEql({ list: 4 }))
.then(assertRecordEql({ list: [1, 2, 4, 4, 5] }))
.then(cleanup)
})
context('ordered lists', function () {
it('reorders the list with the incremented value', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(orderList('list'))
.then(operate(lists.increment('list', 2, 10)))
.then(assertResultEql({ list: 13 }))
.then(assertRecordEql({ list: [1, 2, 4, 5, 13] }))
.then(cleanup)
})
})
context('with add-unique flag', function () {
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE
}
it('fails with an error if the incremented number already exists in the list', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(expectError())
.then(operate(lists.increment('list', 2, 1, policy)))
.then(assertError(status.ERR_FAIL_ELEMENT_EXISTS))
.then(cleanup)
})
context('with no-fail flag', function () {
helper.skipUnlessVersion('>= 4.3.0', this)
const policy = {
writeFlags: lists.writeFlags.ADD_UNIQUE | lists.writeFlags.NO_FAIL
}
it('does not increment the item but returns ok', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.increment('list', 2, 1, policy)))
// Note: Operation returns post-increment value even though
// operation was not executed due to add-unique constraint!
.then(assertResultEql({ list: 4 }))
.then(assertRecordEql({ list: [1, 2, 3, 4, 5] }))
.then(cleanup)
})
})
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('increments the element at the specified index and returns the final value', function () {
return initState()
.then(createRecord({ map: { list: [1, 2, 3, 4, 5] } }))
.then(operate(lists.increment('map', 1, 3).withContext(ctx => ctx.addMapKey('list'))))
.then(assertResultEql({ map: 5 }))
.then(assertRecordEql({ map: { list: [1, 5, 3, 4, 5] } }))
.then(cleanup)
})
})
})
describe('lists.size', function () {
it('returns the element count', function () {
return initState()
.then(createRecord({ list: [1, 2, 3, 4, 5] }))
.then(operate(lists.size('list')))
.then(assertResultEql({ list: 5 }))
.then(cleanup)
})
context('with nested list context', function () {
helper.skipUnlessVersion('>= 4.6.0', this)
it('returns the element count', function () {
return initState()
.then(createRecord({ list: [[], [1, 2, 3, 4, 5]] }))
.then(operate(lists.size('list').withContext(ctx => ctx.addListIndex(-1))))
.then(assertResultEql({ list: 5 }))
.then(cleanup)
})
})
})
describe('ListOperation', function () {
describe('#invertSelection', function () {
it('throws an error if the operation is not invertible', function () {
const op = lists.size('lists')
expect(() => op.invertSelection()).to.throw(AerospikeError, 'List operation cannot be inverted')
})
})
})
})
| aerospike/aerospike-client-nodejs | test/lists.js | JavaScript | apache-2.0 | 50,782 |
const Mentions = require('./MessageMentions');
const Attachment = require('./MessageAttachment');
const Embed = require('./MessageEmbed');
const MessageReaction = require('./MessageReaction');
const ReactionCollector = require('./ReactionCollector');
const ClientApplication = require('./ClientApplication');
const Util = require('../util/Util');
const Collection = require('../util/Collection');
const Constants = require('../util/Constants');
const Permissions = require('../util/Permissions');
const { Error, TypeError } = require('../errors');
let GuildMember;
/**
* Represents a message on Discord.
*/
class Message {
constructor(channel, data, client) {
/**
* The client that instantiated the Message
* @name Message#client
* @type {Client}
* @readonly
*/
Object.defineProperty(this, 'client', { value: client });
/**
* The channel that the message was sent in
* @type {TextChannel|DMChannel|GroupDMChannel}
*/
this.channel = channel;
if (data) this.setup(data);
}
setup(data) { // eslint-disable-line complexity
/**
* The ID of the message
* @type {Snowflake}
*/
this.id = data.id;
/**
* The type of the message
* @type {MessageType}
*/
this.type = Constants.MessageTypes[data.type];
/**
* The content of the message
* @type {string}
*/
this.content = data.content;
/**
* The author of the message
* @type {User}
*/
this.author = this.client.dataManager.newUser(data.author);
/**
* Represents the author of the message as a guild member
* Only available if the message comes from a guild where the author is still a member
* @type {?GuildMember}
*/
this.member = this.guild ? this.guild.member(this.author) || null : null;
/**
* Whether or not this message is pinned
* @type {boolean}
*/
this.pinned = data.pinned;
/**
* Whether or not the message was Text-To-Speech
* @type {boolean}
*/
this.tts = data.tts;
/**
* A random number or string used for checking message delivery
* @type {string}
*/
this.nonce = data.nonce;
/**
* Whether or not this message was sent by Discord, not actually a user (e.g. pin notifications)
* @type {boolean}
*/
this.system = data.type === 6;
/**
* A list of embeds in the message - e.g. YouTube Player
* @type {MessageEmbed[]}
*/
this.embeds = data.embeds.map(e => new Embed(e));
/**
* A collection of attachments in the message - e.g. Pictures - mapped by their ID
* @type {Collection<Snowflake, MessageAttachment>}
*/
this.attachments = new Collection();
for (const attachment of data.attachments) this.attachments.set(attachment.id, new Attachment(this, attachment));
/**
* The timestamp the message was sent at
* @type {number}
*/
this.createdTimestamp = new Date(data.timestamp).getTime();
/**
* The timestamp the message was last edited at (if applicable)
* @type {?number}
*/
this.editedTimestamp = data.edited_timestamp ? new Date(data.edited_timestamp).getTime() : null;
/**
* A collection of reactions to this message, mapped by the reaction ID
* @type {Collection<Snowflake, MessageReaction>}
*/
this.reactions = new Collection();
if (data.reactions && data.reactions.length > 0) {
for (const reaction of data.reactions) {
const id = reaction.emoji.id ? `${reaction.emoji.name}:${reaction.emoji.id}` : reaction.emoji.name;
this.reactions.set(id, new MessageReaction(this, reaction.emoji, reaction.count, reaction.me));
}
}
/**
* All valid mentions that the message contains
* @type {MessageMentions}
*/
this.mentions = new Mentions(this, data.mentions, data.mention_roles, data.mention_everyone);
/**
* ID of the webhook that sent the message, if applicable
* @type {?Snowflake}
*/
this.webhookID = data.webhook_id || null;
/**
* Supplimental application information for group activities
* @type {?ClientApplication}
*/
this.application = data.application ? new ClientApplication(this.client, data.application) : null;
/**
* Group activity
* @type {?Object}
*/
this.activity = data.activity ? {
partyID: data.activity.party_id,
type: data.activity.type,
} : null;
/**
* Whether this message is a hit in a search
* @type {?boolean}
*/
this.hit = typeof data.hit === 'boolean' ? data.hit : null;
/**
* The previous versions of the message, sorted with the most recent first
* @type {Message[]}
* @private
*/
this._edits = [];
}
/**
* Updates the message.
* @param {Object} data Raw Discord message update data
* @private
*/
patch(data) {
const clone = Util.cloneObject(this);
this._edits.unshift(clone);
this.editedTimestamp = new Date(data.edited_timestamp).getTime();
if ('content' in data) this.content = data.content;
if ('pinned' in data) this.pinned = data.pinned;
if ('tts' in data) this.tts = data.tts;
if ('embeds' in data) this.embeds = data.embeds.map(e => new Embed(e));
else this.embeds = this.embeds.slice();
if ('attachments' in data) {
this.attachments = new Collection();
for (const attachment of data.attachments) this.attachments.set(attachment.id, new Attachment(this, attachment));
} else {
this.attachments = new Collection(this.attachments);
}
this.mentions = new Mentions(
this,
'mentions' in data ? data.mentions : this.mentions.users,
'mentions_roles' in data ? data.mentions_roles : this.mentions.roles,
'mention_everyone' in data ? data.mention_everyone : this.mentions.everyone
);
}
/**
* The time the message was sent
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* The time the message was last edited at (if applicable)
* @type {?Date}
* @readonly
*/
get editedAt() {
return this.editedTimestamp ? new Date(this.editedTimestamp) : null;
}
/**
* The guild the message was sent in (if in a guild channel)
* @type {?Guild}
* @readonly
*/
get guild() {
return this.channel.guild || null;
}
/**
* The message contents with all mentions replaced by the equivalent text.
* If mentions cannot be resolved to a name, the relevant mention in the message content will not be converted.
* @type {string}
* @readonly
*/
get cleanContent() {
return this.content
.replace(/@(everyone|here)/g, '@\u200b$1')
.replace(/<@!?[0-9]+>/g, input => {
const id = input.replace(/<|!|>|@/g, '');
if (this.channel.type === 'dm' || this.channel.type === 'group') {
return this.client.users.has(id) ? `@${this.client.users.get(id).username}` : input;
}
const member = this.channel.guild.members.get(id);
if (member) {
if (member.nickname) return `@${member.nickname}`;
return `@${member.user.username}`;
} else {
const user = this.client.users.get(id);
if (user) return `@${user.username}`;
return input;
}
})
.replace(/<#[0-9]+>/g, input => {
const channel = this.client.channels.get(input.replace(/<|#|>/g, ''));
if (channel) return `#${channel.name}`;
return input;
})
.replace(/<@&[0-9]+>/g, input => {
if (this.channel.type === 'dm' || this.channel.type === 'group') return input;
const role = this.guild.roles.get(input.replace(/<|@|>|&/g, ''));
if (role) return `@${role.name}`;
return input;
});
}
/**
* Creates a reaction collector.
* @param {CollectorFilter} filter The filter to apply
* @param {ReactionCollectorOptions} [options={}] Options to send to the collector
* @returns {ReactionCollector}
* @example
* // Create a reaction collector
* const collector = message.createReactionCollector(
* (reaction, user) => reaction.emoji.name === '👌' && user.id === 'someID',
* { time: 15000 }
* );
* collector.on('collect', r => console.log(`Collected ${r.emoji.name}`));
* collector.on('end', collected => console.log(`Collected ${collected.size} items`));
*/
createReactionCollector(filter, options = {}) {
return new ReactionCollector(this, filter, options);
}
/**
* An object containing the same properties as CollectorOptions, but a few more:
* @typedef {ReactionCollectorOptions} AwaitReactionsOptions
* @property {string[]} [errors] Stop/end reasons that cause the promise to reject
*/
/**
* Similar to createCollector but in promise form.
* Resolves with a collection of reactions that pass the specified filter.
* @param {CollectorFilter} filter The filter function to use
* @param {AwaitReactionsOptions} [options={}] Optional options to pass to the internal collector
* @returns {Promise<Collection<string, MessageReaction>>}
*/
awaitReactions(filter, options = {}) {
return new Promise((resolve, reject) => {
const collector = this.createReactionCollector(filter, options);
collector.once('end', (reactions, reason) => {
if (options.errors && options.errors.includes(reason)) reject(reactions);
else resolve(reactions);
});
});
}
/**
* An array of cached versions of the message, including the current version
* Sorted from latest (first) to oldest (last)
* @type {Message[]}
* @readonly
*/
get edits() {
const copy = this._edits.slice();
copy.unshift(this);
return copy;
}
/**
* Whether the message is editable by the client user
* @type {boolean}
* @readonly
*/
get editable() {
return this.author.id === this.client.user.id;
}
/**
* Whether the message is deletable by the client user
* @type {boolean}
* @readonly
*/
get deletable() {
return this.author.id === this.client.user.id || (this.guild &&
this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_MESSAGES)
);
}
/**
* Whether the message is pinnable by the client user
* @type {boolean}
* @readonly
*/
get pinnable() {
return !this.guild ||
this.channel.permissionsFor(this.client.user).has(Permissions.FLAGS.MANAGE_MESSAGES);
}
/**
* Options that can be passed into editMessage.
* @typedef {Object} MessageEditOptions
* @property {string} [content] Content to be edited
* @property {Object} [embed] An embed to be added/edited
* @property {string|boolean} [code] Language for optional codeblock formatting to apply
*/
/**
* Edit the content of the message.
* @param {StringResolvable} [content] The new content for the message
* @param {MessageEditOptions} [options] The options to provide
* @returns {Promise<Message>}
* @example
* // Update the content of a message
* message.edit('This is my new content!')
* .then(msg => console.log(`Updated the content of a message from ${msg.author}`))
* .catch(console.error);
*/
edit(content, options) {
if (!options && typeof content === 'object' && !(content instanceof Array)) {
options = content;
content = '';
} else if (!options) {
options = {};
}
if (typeof options.content !== 'undefined') content = options.content;
if (typeof content !== 'undefined') content = Util.resolveString(content);
let { embed, code, reply } = options;
if (embed) embed = new Embed(embed)._apiTransform();
// Wrap everything in a code block
if (typeof code !== 'undefined' && (typeof code !== 'boolean' || code === true)) {
content = Util.escapeMarkdown(Util.resolveString(content), true);
content = `\`\`\`${typeof code !== 'boolean' ? code || '' : ''}\n${content}\n\`\`\``;
}
// Add the reply prefix
if (reply && this.channel.type !== 'dm') {
const id = this.client.resolver.resolveUserID(reply);
const mention = `<@${reply instanceof GuildMember && reply.nickname ? '!' : ''}${id}>`;
content = `${mention}${content ? `, ${content}` : ''}`;
}
return this.client.api.channels[this.channel.id].messages[this.id]
.patch({ data: { content, embed } })
.then(data => this.client.actions.MessageUpdate.handle(data).updated);
}
/**
* Pins this message to the channel's pinned messages.
* @returns {Promise<Message>}
*/
pin() {
return this.client.api.channels(this.channel.id).pins(this.id).put()
.then(() => this);
}
/**
* Unpins this message from the channel's pinned messages.
* @returns {Promise<Message>}
*/
unpin() {
return this.client.api.channels(this.channel.id).pins(this.id).delete()
.then(() => this);
}
/**
* Add a reaction to the message.
* @param {string|Emoji|ReactionEmoji} emoji The emoji to react with
* @returns {Promise<MessageReaction>}
*/
react(emoji) {
emoji = this.client.resolver.resolveEmojiIdentifier(emoji);
if (!emoji) throw new TypeError('EMOJI_TYPE');
return this.client.api.channels(this.channel.id).messages(this.id).reactions(emoji, '@me')
.put()
.then(() => this._addReaction(Util.parseEmoji(emoji), this.client.user));
}
/**
* Remove all reactions from a message.
* @returns {Promise<Message>}
*/
clearReactions() {
return this.client.api.channels(this.channel.id).messages(this.id).reactions.delete()
.then(() => this);
}
/**
* Deletes the message.
* @param {Object} [options] Options
* @param {number} [options.timeout=0] How long to wait to delete the message in milliseconds
* @param {string} [options.reason] Reason for deleting this message, if it does not belong to the client user
* @returns {Promise<Message>}
* @example
* // Delete a message
* message.delete()
* .then(msg => console.log(`Deleted message from ${msg.author}`))
* .catch(console.error);
*/
delete({ timeout = 0, reason } = {}) {
if (timeout <= 0) {
return this.client.api.channels(this.channel.id).messages(this.id)
.delete({ reason })
.then(() =>
this.client.actions.MessageDelete.handle({
id: this.id,
channel_id: this.channel.id,
}).message);
} else {
return new Promise(resolve => {
this.client.setTimeout(() => {
resolve(this.delete({ reason }));
}, timeout);
});
}
}
/**
* Reply to the message.
* @param {StringResolvable} [content] The content for the message
* @param {MessageOptions} [options] The options to provide
* @returns {Promise<Message|Message[]>}
* @example
* // Reply to a message
* message.reply('Hey, I\'m a reply!')
* .then(msg => console.log(`Sent a reply to ${msg.author}`))
* .catch(console.error);
*/
reply(content, options) {
if (!options && typeof content === 'object' && !(content instanceof Array)) {
options = content;
content = '';
} else if (!options) {
options = {};
}
return this.channel.send(content, Object.assign(options, { reply: this.member || this.author }));
}
/**
* Marks the message as read.
* <warn>This is only available when using a user account.</warn>
* @returns {Promise<Message>}
*/
acknowledge() {
return this.client.api.channels(this.channel.id).messages(this.id).ack
.post({ data: { token: this.client.rest._ackToken } })
.then(res => {
if (res.token) this.client.rest._ackToken = res.token;
return this;
});
}
/**
* Fetches the webhook used to create this message.
* @returns {Promise<?Webhook>}
*/
fetchWebhook() {
if (!this.webhookID) return Promise.reject(new Error('WEBHOOK_MESSAGE'));
return this.client.fetchWebhook(this.webhookID);
}
/**
* Used mainly internally. Whether two messages are identical in properties. If you want to compare messages
* without checking all the properties, use `message.id === message2.id`, which is much more efficient. This
* method allows you to see if there are differences in content, embeds, attachments, nonce and tts properties.
* @param {Message} message The message to compare it to
* @param {Object} rawData Raw data passed through the WebSocket about this message
* @returns {boolean}
*/
equals(message, rawData) {
if (!message) return false;
const embedUpdate = !message.author && !message.attachments;
if (embedUpdate) return this.id === message.id && this.embeds.length === message.embeds.length;
let equal = this.id === message.id &&
this.author.id === message.author.id &&
this.content === message.content &&
this.tts === message.tts &&
this.nonce === message.nonce &&
this.embeds.length === message.embeds.length &&
this.attachments.length === message.attachments.length;
if (equal && rawData) {
equal = this.mentions.everyone === message.mentions.everyone &&
this.createdTimestamp === new Date(rawData.timestamp).getTime() &&
this.editedTimestamp === new Date(rawData.edited_timestamp).getTime();
}
return equal;
}
/**
* When concatenated with a string, this automatically concatenates the message's content instead of the object.
* @returns {string}
* @example
* // Logs: Message: This is a message!
* console.log(`Message: ${message}`);
*/
toString() {
return this.content;
}
_addReaction(emoji, user) {
const emojiID = emoji.id ? `${emoji.name}:${emoji.id}` : encodeURIComponent(emoji.name);
let reaction;
if (this.reactions.has(emojiID)) {
reaction = this.reactions.get(emojiID);
if (!reaction.me) reaction.me = user.id === this.client.user.id;
} else {
reaction = new MessageReaction(this, emoji, 0, user.id === this.client.user.id);
this.reactions.set(emojiID, reaction);
}
if (!reaction.users.has(user.id)) {
reaction.users.set(user.id, user);
reaction.count++;
}
return reaction;
}
_removeReaction(emoji, user) {
const emojiID = emoji.id ? `${emoji.name}:${emoji.id}` : encodeURIComponent(emoji.name);
if (this.reactions.has(emojiID)) {
const reaction = this.reactions.get(emojiID);
if (reaction.users.has(user.id)) {
reaction.users.delete(user.id);
reaction.count--;
if (user.id === this.client.user.id) reaction.me = false;
if (reaction.count <= 0) this.reactions.delete(emojiID);
return reaction;
}
}
return null;
}
_clearReactions() {
this.reactions.clear();
}
}
module.exports = Message;
| devsnek/discord.js | src/structures/Message.js | JavaScript | apache-2.0 | 18,885 |
var buf = new Buffer(39);
var len = buf.write("www.baidu.com");
console.log("写入字节数为 : "+len);
for(var i=13;i < 39;i++){
buf[i] = i+84;
}
var json = buf.toJSON();
console.log(json);
| garyhu1/node | buffer.js | JavaScript | apache-2.0 | 202 |
export const FLAT_TABLE_THEMES = [
"light",
"dark",
"transparent-base",
"transparent-white",
];
export const FLAT_TABLE_SIZES = ["compact", "small", "medium", "large"];
| Sage/carbon | src/components/flat-table/flat-table.config.js | JavaScript | apache-2.0 | 177 |
module.exports = {
'name': 'largereq',
'category': 'Operators',
'syntax': [
'x >= y',
'largereq(x, y)'
],
'description':
'Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.',
'examples': [
'2 > 1+1',
'2 >= 1+1',
'a = 3.2',
'b = 6-2.8',
'(a > b)'
],
'seealso': [
'equal', 'unequal', 'smallereq', 'smaller', 'largereq', 'compare'
]
};
| npmcomponent/josdejong-mathjs | lib/expression/docs/function/arithmetic/largereq.js | JavaScript | apache-2.0 | 441 |
/*
Copyright 2016 ElasticBox 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.
*/
import './ek-instances.less';
import Directive from 'directive';
import Controller from './ek-instances.controller';
import constants from '../constants';
import template from './ek-instances.html';
class InstancesDirective extends Directive {
constructor() {
super({ Controller, template });
}
compile(tElement) {
tElement
.addClass('ek-instances layout-column');
return ($scope) => _.extend($scope, constants);
}
}
export default InstancesDirective;
| ElasticBox/elastickube | src/ui/app/instances/ek-instances/ek-instances.directive.js | JavaScript | apache-2.0 | 1,087 |
import { Template } from 'meteor/templating';
import { Meteor } from 'meteor/meteor';
import { Roles } from 'meteor/alanning:roles';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { $ } from 'meteor/jquery';
import { getStudentProfileMethod } from '../../../api/user/StudentProfileCollection.methods';
/* global alert */
Template.RadGrad_Login_Buttons.events({
/**
* Handle the .cas-login click event.
* @param event The click event.
* @returns {boolean} False.
* @memberOf ui/components/landing
*/
'click .cas-login': function casLogin(event, instance) {
event.preventDefault();
const callback = function loginCallback(error) {
if (error) {
console.log('Error during CAS Login: ', error);
instance.$('div .ui.error.message.hidden').text('You are not yet registered. Go see your Advisor.');
instance.$('div .ui.error.message.hidden').removeClass('hidden');
} else {
const { username } = Meteor.user('username');
if (!username) {
alert('You must use only lower case letters in your username.');
Meteor.logout();
}
const id = Meteor.userId();
let role = Roles.getRolesForUser(id)[0];
const studentp = role.toLowerCase() === 'student';
if (studentp) {
getStudentProfileMethod.call(username, (err, result) => {
if (err) {
console.error('Failed to get profile', error);
} else {
if (result.isAlumni) {
role = 'Alumni';
}
FlowRouter.go(`/${role.toLowerCase()}/${username}/home`);
}
});
}
FlowRouter.go(`/${role.toLowerCase()}/${username}/home`);
}
};
Meteor.loginWithCas(callback);
return false;
},
/**
* Handle the .meteor-login click event,
* @param event The click event.
* @returns {boolean} False.
* @memberOf ui/components/landing
*/
'click .meteor-login': function clickOpenModal(event) {
event.preventDefault();
$('.ui.modal').modal('show');
},
});
// Here's how to do the required initialization for Semantic UI dropdown menus.
Template.RadGrad_Login_Buttons.onRendered(function enableDropDown() {
this.$('.dropdown').dropdown({
action: 'select',
});
this.$('.modal').modal({
onApprove: function foo(event) {
console.log('approved', event, event.target);
},
});
});
| radgrad/radgrad | app/imports/ui/components/landing/radgrad-login-buttons.js | JavaScript | apache-2.0 | 2,450 |
/*
* Copyright 2013 pingworks - Alexander Birk und Christoph Lukas
* Copyright 2014 //SEIBERT/MEDIA - Lars-Erik Kimmel
*
* 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("Dash.view.BundleGrid", {
extend: 'Ext.grid.Panel',
alias: 'widget.bundlegrid',
requires: ['Ext.String', 'Ext.grid.column.Action', 'Ext.window.MessageBox'],
store: 'Bundles',
width: '100%',
id: 'BundleGrid',
stageColumnOffset: 6,
visibleColumnIndex: function (colIndex) {
// work around extjs bug: colIndex is wrong when some cols are hidden
var hiddenCols = 0;
for (var i = 0; i < colIndex; i++) {
if (!this.columns[i].isVisible())
hiddenCols++;
}
return colIndex + hiddenCols;
},
getStageNrFromColIndex: function(colIndex) {
return this.visibleColumnIndex(colIndex) - this.stageColumnOffset;
},
stageStatusIconRenderer: function(value, metadata, record, rowIndex, colIndex, store, view) {
var stageStatus = Dash.app.getController('Bundle').getStageStatus(record, this.getStageNrFromColIndex(colIndex));
var iconUrl = Ext.BLANK_IMAGE_URL;
var iconCls = '';
if (stageStatus) {
iconUrl = Ext.String.format(Dash.config.stagestatus.iconpath, stageStatus.get('icon'));
iconCls = stageStatus.get('cls');
}
this.columns[this.visibleColumnIndex(colIndex)].items[0].icon = iconUrl;
this.columns[this.visibleColumnIndex(colIndex)].items[0].iconCls = iconCls;
},
deploymentActionRenderer: function(value, metadata, record, rowIndex, colIndex, store, view) {
var ctrl = Dash.app.getController('Deployment');
this.columns[this.colIndexDeployment].items[0].iconCls =
ctrl.deploymentAllowed(record) ? '' : this.disabledCls;
},
triggerJenkinsJobActionRenderer: function(value, metadata, record, rowIndex, colIndex, store, view) {
var ctrl = Dash.app.getController('TriggerJenkinsJob');
this.columns[this.colIndexTriggerJenkinsJob].items[0].iconCls =
ctrl.triggerJenkinsJobAllowed(record) ? '' : this.disabledCls;
},
createChangeTooltip: function(target, bundle) {
return Ext.create('Dash.view.ChangeToolTip', {
id: 'TTC-' + bundle.get('id').replace(/\./g, '-'),
target: target
});
},
createJobResultTooltip: function(target, bundle, stage) {
return Ext.create('Dash.view.JobResultToolTip', {
id: 'TTJR-' + bundle.get('id').replace(/\./g, '-') + '-' + stage,
target: target
});
},
initComponent: function() {
var that = this;
this.columns = [
{
text: Dash.config.bundlegrid.label.timestamp,
dataIndex: 'timestamp',
type: 'date',
renderer: Ext.util.Format.dateRenderer(Dash.config.bundlegrid.dateformat),
width: Dash.config.bundlegrid.colwidth.timestamp,
hidden: Dash.config.bundlegrid.hidden.timestamp
},
{
text: Dash.config.bundlegrid.label.committer,
dataIndex: 'committer',
width: Dash.config.bundlegrid.colwidth.committer,
hidden: Dash.config.bundlegrid.hidden.committer
},
{
text: Dash.config.bundlegrid.label.pname,
dataIndex: 'pname',
width: Dash.config.bundlegrid.colwidth.pname,
hidden: Dash.config.bundlegrid.hidden.pname
},
{
text: Dash.config.bundlegrid.label.branch,
dataIndex: 'branch_name',
width: Dash.config.bundlegrid.colwidth.branch,
hidden: Dash.config.bundlegrid.hidden.branch
},
{
text: Dash.config.bundlegrid.label.revision,
dataIndex: 'revision',
renderer: function(value, metadata, record, rowIndex, colIndex, store, view) {
return ( Dash.config.bundlegrid.vcslink && Dash.config.bundlegrid.vcslink != '' && record.get('revision') != 'Unavailable')
? Ext.String.format(Dash.config.bundlegrid.vcslink, record.get('repository'), record.get('revision'), record.get('branch'))
: record.get('revision');
},
width: Dash.config.bundlegrid.colwidth.revision,
hidden: Dash.config.bundlegrid.hidden.revision
},
{
text: Dash.config.bundlegrid.label.repository,
dataIndex: 'repository',
renderer: function(value, metadata, record, rowIndex, colIndex, store, view) {
return ( Dash.config.bundlegrid.vcsrepolink && Dash.config.bundlegrid.vcsrepolink != '' && record.get('repository') != 'Unavailable')
? Ext.String.format(Dash.config.bundlegrid.vcsrepolink, record.get('repository'), record.get('revision'))
: record.get('repository');
},
width: Dash.config.bundlegrid.colwidth.repository,
hidden: Dash.config.bundlegrid.hidden.repository
},
{
text: Dash.config.bundlegrid.label.bundle,
menuText: 'Bundle',
dataIndex: 'id',
renderer: function(value, metadata, record, rowIndex, colIndex, store, view) {
return ( Dash.config.bundlegrid.repolink && Dash.config.bundlegrid.repolink != '' )
? Ext.String.format(Dash.config.bundlegrid.repolink, record.get('branch'), record.get('id'))
: record.get('id');
},
width: Dash.config.bundlegrid.colwidth.bundle,
hidden: Dash.config.bundlegrid.hidden.bundle
}
];
for (var i = 1; i <= Dash.config.pipelineStages; i++) {
this.columns.push({
text: Dash.config.bundlegrid.label['stage' + i],
menuText: i,
dataIndex: 'stage' + i,
align: 'center',
xtype: 'actioncolumn',
items: [
{
handler: function(gridview, rowIndex, colIndex, item, event, record) {
var stage = this.getStageNrFromColIndex(colIndex);
that.fireEvent('hideAllTooltips');
that.fireEvent(
'loadJobResult',
record,
stage,
that.createJobResultTooltip(event.target, record, stage)
);
}
}
],
renderer: this.stageStatusIconRenderer,
scope: this,
width: Dash.config.bundlegrid.colwidth['stage' + i],
hidden: Dash.config.bundlegrid.hidden['stage' + i]
});
}
var cols = [
{
text: Dash.config.bundlegrid.label.build,
menuText: 'Build',
align: 'center',
xtype: 'actioncolumn',
width: Dash.config.bundlegrid.colwidth.build,
hidden: Dash.config.bundlegrid.hidden.build,
items: [
{
margin: 10,
tooltip: "Build neustarten",
icon: Dash.config.bundlegrid.icon.restartBuild,
isDisabled: function(gridview, rowIndex, colIndex, item, record) {
return record.isBuildRunning();
},
handler: function(gridview, rowIndex, colIndex, item, event, record) {
Ext.MessageBox.confirm(
'Build neustarten',
Ext.String.format("Wollen Sie den Build für Revision '{0}' im Branch '{1}' wirklich neustarten?\nDer Build wird eventuell später gestartet und erscheint erst dann auf dem Dashboard.", record.get('revision'), record.get('branch')),
function(btn) {
if (btn == 'yes') {
that.fireEvent('restartBuild', record);
}
}
);
}
},
{
margin: 10,
tooltip: "Build stoppen",
icon: Dash.config.bundlegrid.icon.stopBuild,
isDisabled: function(gridview, rowIndex, colIndex, item, record) {
return !record.isBuildRunning();
},
handler: function(gridview, rowIndex, colIndex, item, event, record) {
Ext.MessageBox.confirm(
'Build stoppen',
Ext.String.format("Wollen Sie den Build für Revision '{0}' im Branch '{1}' wirklich stoppen?", record.get('revision'), record.get('branch')),
function(btn) {
if (btn == 'yes') {
that.fireEvent('stopBuild', record);
}
}
);
}
},
{
margin: 10,
tooltip: "Build anzeigen",
icon: Dash.config.bundlegrid.icon.showBuild,
isDisabled: function(gridview, rowIndex, colIndex, item, record) {
return !Ext.isDefined(record.getLatestBuildUrl());
},
handler: function(gridview, rowIndex, colIndex, item, event, record) {
that.fireEvent('showBuild', record);
}
}
],
scope: this
},
{
text: Dash.config.bundlegrid.label.changes,
menuText: 'Änderungen',
align: 'center',
xtype: 'actioncolumn',
width: Dash.config.bundlegrid.colwidth.changes,
hidden: Dash.config.bundlegrid.hidden.changes,
items: [
{
icon: Dash.config.bundlegrid.icon.change,
handler: function(gridview, rowIndex, colIndex, item, event, record) {
that.fireEvent('hideAllTooltips');
that.fireEvent(
'loadChanges',
record,
that.createChangeTooltip(event.target, record)
);
}
}
]
},
{
id: 'ColumnDeployment',
text: Dash.config.bundlegrid.label.deployment,
xtype: 'actioncolumn',
width: Dash.config.bundlegrid.colwidth.deployment,
hidden: Dash.config.bundlegrid.hidden.deployment,
flex: Dash.config.bundlegrid.flex.deployment,
items: [
{
disabled: !Dash.config.bundlegrid.deployment.enabled,
icon: Dash.config.bundlegrid.icon.deploy,
handler: function(gridview, rowIndex, colIndex, item, event, record) {
that.fireEvent('hideEnvironmentsWindow');
that.fireEvent('hideTriggerJenkinsJobWindow');
that.fireEvent('showDeployWindow', record);
}
}
],
renderer: this.deploymentActionRenderer,
scope: this
},
{
id: 'ColumnTriggerJenkinsJob',
text: Dash.config.bundlegrid.label.triggerJenkinsJob,
xtype: 'actioncolumn',
width: Dash.config.bundlegrid.colwidth.triggerJenkinsJob,
hidden: Dash.config.bundlegrid.hidden.triggerJenkinsJob,
flex: Dash.config.bundlegrid.flex.triggerJenkinsJob,
items: [
{
disabled: !Dash.config.bundlegrid.triggerJenkinsJob.enabled,
icon: Dash.config.bundlegrid.icon.deploy,
handler: function(gridview, rowIndex, colIndex, item, event, record) {
that.fireEvent('hideEnvironmentsWindow');
that.fireEvent('hideDeployWindow');
that.fireEvent('showTriggerJenkinsJobWindow', record);
}
}
],
renderer: this.triggerJenkinsJobActionRenderer,
scope: this
},
{
id: 'ColumnEditComment',
text: Dash.config.bundlegrid.label.editComment,
menuText: Dash.config.bundlegrid.label.editComment,
align: 'center',
xtype: 'actioncolumn',
hidden: Dash.config.bundlegrid.hidden.editComment,
width: Dash.config.bundlegrid.colwidth.editComment,
items: [
{
icon: Dash.config.bundlegrid.icon.comment,
handler: function(gridview, rowIndex, colIndex, item, event, record) {
that.fireEvent('showCommentWindow', record);
}
}
]
},
{
id: 'ColumnComment',
text: Dash.config.bundlegrid.label.comment,
menuText: Dash.config.bundlegrid.label.comment,
dataIndex: 'comment',
hidden: Dash.config.bundlegrid.hidden.comment,
width: Dash.config.bundlegrid.colwidth.comment,
flex: Dash.config.bundlegrid.flex.comment,
renderer: function(text) {
return Ext.util.Format.htmlEncode(text);
}
}
];
Ext.Array.each(cols, function (el) {
that.columns.push(el);
});
Ext.Array.forEach(this.columns, function(column, index) {
if (column.id == 'ColumnDeployment')
this.colIndexDeployment = index;
}, this);
Ext.Array.forEach(this.columns, function(column, index) {
if (column.id == 'ColumnTriggerJenkinsJob')
this.colIndexTriggerJenkinsJob = index;
}, this);
this.callParent(arguments);
}
});
| pingworks/dash | frontend/app/view/BundleGrid.js | JavaScript | apache-2.0 | 15,694 |
export function getCorrectFontSizeForScreen(PixelRatio, screenWidth, screenHeight, currentFont){
let devRatio = PixelRatio.get();
let factor = (((screenWidth*devRatio)/320)+((screenHeight*devRatio)/640))/2.0;
let maxFontDifferFactor = 5; //the maximum pixels of font size we can go up or down
if(factor<=1){
return currentFont-float2int(maxFontDifferFactor*0.3);
}else if((factor>=1) && (factor<=1.6)){
return currentFont-float2int(maxFontDifferFactor*0.1);
}else if((factor>=1.6) && (factor<=2)){
return currentFont;
}else if((factor>=2) && (factor<=3)){
return currentFont+float2int(maxFontDifferFactor*0.65);
}else if (factor>=3){
return currentFont+float2int(maxFontDifferFactor);
}
}
function float2int (value) {
return value | 0;
}
| GoldenOwlAsia/cooking-app | js/utils/multiResolution.js | JavaScript | apache-2.0 | 780 |
'use strict'
/* globals describe, test, expect, jest */
const path = require('path')
// This is the module we are testing
const { crawlForMovies } = require('../crawlForMovies')
const crawlParams = {
rootDirectory: __dirname,
searchDirCb: jest.fn(),
movieFileCb: jest.fn()
}
describe('crawlForMovies', () => {
test('discovers test movies without crashing', () => {
return expect(crawlForMovies(crawlParams)).resolves.toBeUndefined()
})
test('calls search directory callback during crawl', () => {
const testDirs = crawlParams.searchDirCb.mock.calls.map(dir => {
const { name } = path.parse(dir[0])
return name
})
expect(testDirs).toMatchSnapshot()
})
test('calls movie file callback during crawl', () => {
const movies = crawlParams.movieFileCb.mock.calls.map(file => {
const { name, ext } = path.parse(file[0])
return `${name}${ext}`
})
expect(movies).toMatchSnapshot()
})
})
| blenoski/movie-night | app/background/__tests__/crawlForMovies.test.js | JavaScript | apache-2.0 | 954 |
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import List from '../../components/List';
import UserIcon from '../../icons/User';
const Item = (props) => {
const { className, item: user } = props;
const classNames = ['item__container'];
if (className) {
classNames.push(className);
}
let avatar;
if (user.image) {
avatar = <img className="avatar" alt="avatar" src={user.image.data} />;
} else {
avatar = <UserIcon className="avatar" />;
}
return (
<Link className={classNames.join(' ')} to={`/users/${user._id}`}>
<div className="item">
<span className="box--row box--static">
{avatar}
<span className="item__name">{user.name}</span>
</span>
<span>{user.email}</span>
</div>
</Link>
);
};
Item.propTypes = {
className: PropTypes.string,
item: PropTypes.shape({
administrator: PropTypes.bool,
domainIds: PropTypes.arrayOf(PropTypes.string),
email: PropTypes.string,
}).isRequired,
};
Item.defaultProps = {
className: undefined,
};
export default class Users extends List {}
Users.defaultProps = {
...List.defaultProps,
category: 'users',
adminable: false,
Item,
path: '/users',
sort: '-modified name email',
title: 'People',
};
| ericsoderberg/pbc-web | ui/js/pages/user/Users.js | JavaScript | apache-2.0 | 1,319 |
/*
* Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["pa-IN"] = {
name: "pa-IN",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
symbol: "%"
},
currency: {
pattern: ["$ -n","$ n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
symbol: "ਰੁ"
}
},
calendars: {
standard: {
days: {
names: ["ਐਤਵਾਰ","ਸੋਮਵਾਰ","ਮੰਗਲਵਾਰ","ਬੁੱਧਵਾਰ","ਵੀਰਵਾਰ","ਸ਼ੁੱਕਰਵਾਰ","ਸ਼ਨਿੱਚਰਵਾਰ"],
namesAbbr: ["ਐਤ.","ਸੋਮ.","ਮੰਗਲ.","ਬੁੱਧ.","ਵੀਰ.","ਸ਼ੁਕਰ.","ਸ਼ਨਿੱਚਰ."],
namesShort: ["ਐ","ਸ","ਮ","ਬ","ਵ","ਸ਼","ਸ਼"]
},
months: {
names: ["ਜਨਵਰੀ","ਫ਼ਰਵਰੀ","ਮਾਰਚ","ਅਪ੍ਰੈਲ","ਮਈ","ਜੂਨ","ਜੁਲਾਈ","ਅਗਸਤ","ਸਤੰਬਰ","ਅਕਤੂਬਰ","ਨਵੰਬਰ","ਦਸੰਬਰ",""],
namesAbbr: ["ਜਨਵਰੀ","ਫ਼ਰਵਰੀ","ਮਾਰਚ","ਅਪ੍ਰੈਲ","ਮਈ","ਜੂਨ","ਜੁਲਾਈ","ਅਗਸਤ","ਸਤੰਬਰ","ਅਕਤੂਬਰ","ਨਵੰਬਰ","ਦਸੰਬਰ",""]
},
AM: ["ਸਵੇਰ","ਸਵੇਰ","ਸਵੇਰ"],
PM: ["ਸ਼ਾਮ","ਸ਼ਾਮ","ਸ਼ਾਮ"],
patterns: {
d: "dd-MM-yy",
D: "dd MMMM yyyy dddd",
F: "dd MMMM yyyy dddd tt hh:mm:ss",
g: "dd-MM-yy tt hh:mm",
G: "dd-MM-yy tt hh:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "tt hh:mm",
T: "tt hh:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM, yyyy",
Y: "MMMM, yyyy"
},
"/": "-",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); | y-todorov/Inventory | Inventory.MVC/Scripts/Kendo/cultures/kendo.culture.pa-IN.js | JavaScript | apache-2.0 | 3,124 |
/*
* Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
*/
define([ 'lodash',
'controlnode-widgetcfg', 'vrouter-widgetcfg','databasenode-widgetcfg',
'analyticsnode-widgetcfg','confignode-widgetcfg','monitor-infra-widgetcfg',
'security-dashboard-widgetcfg',
'confignode-modelcfg','controlnode-modelcfg','vrouter-modelcfg',
'databasenode-modelcfg','analyticsnode-modelcfg','monitor-infra-modelcfg',
'security-dashboard-modelcfg',
'monitor-infra-viewcfg','confignode-viewcfg', 'databasenode-viewcfg',
'vrouter-viewcfg', 'security-dashboard-viewcfg', 'alarms-viewconfig'
], function(
_,ControlNodeWidgetCfg, VRouterWidgetCfg, DBNodeWidgetCfg,
AnalyticsNodeWidgetCfg, CfgNodeWidgetCfg,MonitorInfraWidgetCfg,
SecurityDashboardWidgetCfg,
CfgNodeModelCfg,ControlNodeModelCfg,VRouterModelCfg,DatabaseNodeModelCfg,
AnaltyicsNodeModelCfg,MonitorInfraModelCfg,SecurityDashboardModelCfg,
MonitorInfraViewCfg,CfgNodeViewCfg, DBNodeViewCfg, VRouterViewCfg,
SecurityDashboardViewConfig, AlarmsViewConfig, SecurityDashboardViewCfg ) {
var widgetCfgManager = function() {
var self = this;
var widgetCfgMap = {},
widgetViewCfgMap = {},
widgetModelCfgMap = {};
//Populate the available widget config maps
$.extend(widgetCfgMap, ControlNodeWidgetCfg, VRouterWidgetCfg,
DBNodeWidgetCfg, AnalyticsNodeWidgetCfg,
CfgNodeWidgetCfg,MonitorInfraWidgetCfg, SecurityDashboardWidgetCfg);
//Populate the available model config maps
$.extend(widgetModelCfgMap, CfgNodeModelCfg,ControlNodeModelCfg,VRouterModelCfg,
DatabaseNodeModelCfg,AnaltyicsNodeModelCfg,MonitorInfraModelCfg,
SecurityDashboardModelCfg);
$.extend(widgetViewCfgMap, MonitorInfraViewCfg, CfgNodeViewCfg,
DBNodeViewCfg, VRouterViewCfg, SecurityDashboardViewConfig, AlarmsViewConfig,
SecurityDashboardViewCfg);
//,ControlNodeViewCfg,VRouterViewCfg,DatabaseNodeViewCfg,AnaltyicsNodeViewCfg,);
self.get = function(widgetId,overrideCfg,i) {
var widgetCfg = _.isFunction(widgetCfgMap[widgetId]) ? widgetCfgMap[widgetId](overrideCfg,i) : widgetCfgMap[widgetId];
if (widgetCfg == null) {
widgetCfg = _.isFunction(widgetViewCfgMap[widgetId]) ? widgetViewCfgMap[widgetId](overrideCfg) : widgetViewCfgMap[widgetId];
}
var modelCfg = {},viewCfg = {},baseModelCfg;
if(widgetCfg['baseModel'] != null) {
baseModelCfg = widgetModelCfgMap[widgetCfg['baseModel']];
if(widgetCfg['modelCfg'] != null) {
$.extend(true,modelCfg,baseModelCfg,widgetCfg['modelCfg'])
} else {
modelCfg = baseModelCfg;
}
if(_.result(baseModelCfg,'type','')) {
widgetCfg['tag'] = baseModelCfg['type'];
}
widgetCfg['modelCfg'] = modelCfg;
}
if(_.result(widgetCfg,'modelCfg.type','')) {
widgetCfg['tag'] = _.result(widgetCfg,'modelCfg.type');
}
if(widgetCfg['baseView'] != null) {
baseViewCfg = widgetViewCfgMap[widgetCfg['baseView']];
if(widgetCfg['viewCfg'] != null) {
$.extend(true,viewCfg,baseViewCfg,widgetCfg['viewCfg'])
} else {
viewCfg= baseViewCfg;
}
widgetCfg['viewCfg'] = viewCfg;
}
return widgetCfg;
}
//Returns list of available widgets
self.getWidgetList = function() {
// return _.keys(widgetCfgMap);
var widgetMap = _.map(_.keys(widgetCfgMap),function(widgetId) {
return {
key: widgetId,
value: self.get(widgetId),
tag: self.get(widgetId)['tag']
}
});
widgetMap = _.groupBy(widgetMap,function(d) {
return d.tag;
});
//Pick yAxisLabel if exists else return widgetId
return _.map(widgetMap,function(value,key) {
return {
text: key,
children: _.map(value, function(widgetCfg) {
return {
id:widgetCfg['key'],
text:_.result(widgetCfg['value'],'viewCfg.viewConfig.chartOptions.yAxisLabel',widgetCfg['key'])
}
})
// val:_.result(widgetCfg['value'],'viewCfg.viewConfig.chartOptions.yAxisLabel',widgetCfg['key'])
}
});
}
self.modelInstMap = {};
}
return new widgetCfgManager();
});
| biswajit-mandal/contrail-web-core | webroot/js/widget.configmanager.js | JavaScript | apache-2.0 | 4,969 |
// xiNET interaction viewer
// Copyright 2013 Rappsilber Laboratory
//
// This product includes software developed at
// the Rappsilber Laboratory (http://www.rappsilberlab.org/).
"use strict";
var Config = require('../../controller/Config');
var Link = require('./Link');
var SequenceLink = require('./SequenceLink');
//josh - following are libraries and should be in 'vendor'?
// but I don't know how to set up the dependency if its there
var Intersection = require('../../controller/Intersection');
var Point2D = require('../../controller/Point2D');
// BinaryLink.js
// the class representing a binary interaction
BinaryLink.prototype = new Link();
function BinaryLink(id, xlvController, fromI, toI) {
this.id = id;
this.evidences = d3.map();
this.interactors = [fromI, toI];
this.sequenceLinks = d3.map();
this.ctrl = xlvController;
this.ambig = false;
//used to avoid some unnecessary manipulation of DOM
this.shown = false;
}
BinaryLink.prototype.initSVG = function() {
this.line = document.createElementNS(Config.svgns, "line");
this.highlightLine = document.createElementNS(Config.svgns, "line");
this.thickLine = document.createElementNS(Config.svgns, "line");
this.line.setAttribute("class", "link");
this.line.setAttribute("fill", "none");
this.line.setAttribute("stroke", "black");
this.line.setAttribute("stroke-width", "1");
this.line.setAttribute("stroke-linecap", "round");
this.highlightLine.setAttribute("class", "link");
this.highlightLine.setAttribute("fill", "none");
this.highlightLine.setAttribute("stroke", Config.highlightColour);
this.highlightLine.setAttribute("stroke-width", "10");
this.highlightLine.setAttribute("stroke-linecap", "round");
this.highlightLine.setAttribute("stroke-opacity", "0");
this.thickLine.setAttribute("class", "link");
this.thickLine.setAttribute("fill", "none");
this.thickLine.setAttribute("stroke", "lightgray");
this.thickLine.setAttribute("stroke-linecap", "round");
this.thickLine.setAttribute("stroke-linejoin", "round");
//set the events for it
var self = this;
this.line.onmousedown = function(evt) {
self.mouseDown(evt);
};
this.line.onmouseover = function(evt) {
self.mouseOver(evt);
};
this.line.onmouseout = function(evt) {
self.mouseOut(evt);
};
this.line.ontouchstart = function(evt) {
self.touchStart(evt);
};
this.highlightLine.onmousedown = function(evt) {
self.mouseDown(evt);
};
this.highlightLine.onmouseover = function(evt) {
self.mouseOver(evt);
};
this.highlightLine.onmouseout = function(evt) {
self.mouseOut(evt);
};
this.highlightLine.ontouchstart = function(evt) {
self.touchStart(evt);
};
this.thickLine.onmousedown = function(evt) {
self.mouseDown(evt);
};
this.thickLine.onmouseover = function(evt) {
self.mouseOver(evt);
};
this.thickLine.onmouseout = function(evt) {
self.mouseOut(evt);
};
this.thickLine.ontouchstart = function(evt) {
self.touchStart(evt);
};
this.isSelected = false;
}
;
BinaryLink.prototype.showHighlight = function(show) {
if (this.shown) {
if (this.notSubLink === true){
this.highlightInteractors(show);
}
if (show) {
//~ this.highlightLine.setAttribute("stroke", xiNET.highlightColour.toRGB());
this.highlightLine.setAttribute("stroke-opacity", "1");
} else {
//~ this.highlightLine.setAttribute("stroke", xiNET.selectedColour.toRGB());
//~ if (this.isSelected === false) {
this.highlightLine.setAttribute("stroke-opacity", "0");
//~ }
}
}
};
BinaryLink.prototype.check = function() {
//~ if (!this.fromInteractor) {//TEMP HACK
//~ return false;
//~ }
if (this.interactors[0].form === 0 && this.interactors[1].form === 0) {
//~ this.ambig = true;
//~ var filteredEvids = this.getFilteredEvidences();
//~ var evidCount = filteredEvids.length;
//~ for (var i = 0; i < evidCount; i++) {
//~ var evid = filteredEvids[i];
//~ if (typeof evid.expansion === 'undefined') {
//~ this.ambig = false;
//~ }
//~ }
//~ if (evidCount > 0) {
//~ //tooltip
//~ this.tooltip = /*this.id + ', ' +*/ evidCount + ' experiment';
//~ if (evidCount > 1) {
//~ this.tooltip += 's';
//~ }
//~ this.tooltip += ' (';
//~ var nested_data = d3.nest()
//~ .key(function(d) {
//~ return d.experiment.detmethod.name;
//~ })
//~ .rollup(function(leaves) {
//~ return leaves.length;
//~ })
//~ .entries(filteredEvids);
//~
//~ nested_data.sort(function(a, b) {
//~ return b.values - a.values
//~ });
//~ var countDetMethods = nested_data.length
//~ for (var i = 0; i < countDetMethods; i++) {
//~ if (i > 0) {
//~ this.tooltip += ', ';
//~ }
//~ this.tooltip += nested_data[i].values + ' ' + nested_data[i].key;
//~ }
//~ this.tooltip += ' )';
//~ //thickLine
//~ if (evidCount > 1) {
//~ this.thickLineShown = true
//~ this.w = evidCount * (45 / BinaryLink.maxNoEvidences);
//~ }
//~ else {
//~ // this.thickLineShown = false;//hack
//~ this.w = evidCount * (45 / BinaryLink.maxNoEvidences);//hack
//~ }
//~ //ambig?
//~ this.dashedLine(this.ambig);
//sequence links will have been hidden previously
this.show();
return true;
}
else {//at least one end was in stick form
this.hide();
return false;
}
};
BinaryLink.prototype.show = function() {
if (this.ctrl.initComplete) {
if (!this.shown) {
this.shown = true;
if (typeof this.line === 'undefined') {
this.initSVG();
}
this.line.setAttribute("stroke-width", this.ctrl.z * 1);
this.highlightLine.setAttribute("stroke-width", this.ctrl.z * 10);
this.setLinkCoordinates(this.interactors[0]);
this.setLinkCoordinates(this.interactors[1]);
if (this.thickLineShown) {
this.ctrl.p_pLinksWide.appendChild(this.thickLine);
}
this.ctrl.highlights.appendChild(this.highlightLine);
this.ctrl.p_pLinks.appendChild(this.line);
if (this.thickLineShown) {
this.thickLine.setAttribute("stroke-width", this.w);
}
}
}
};
BinaryLink.prototype.hide = function() {
if (this.shown) {
this.shown = false;
if (this.thickLineShown) {
this.ctrl.p_pLinksWide.removeChild(this.thickLine);
}
this.ctrl.highlights.removeChild(this.highlightLine);
this.ctrl.p_pLinks.removeChild(this.line);
}
};
BinaryLink.prototype.setLinkCoordinates = function(interactor) {
if (this.shown) {//don't waste time changing DOM if link not visible
var pos = interactor.getPosition();
if (interactor.type !== 'complex'){
if (this.interactors[0] === interactor) {
this.line.setAttribute("x1", pos[0]);
this.line.setAttribute("y1", pos[1]);
this.highlightLine.setAttribute("x1", pos[0]);
this.highlightLine.setAttribute("y1", pos[1]);
if (this.thickLineShown) {
this.thickLine.setAttribute("x1", pos[0]);
this.thickLine.setAttribute("y1", pos[1]);
}
}
else {
this.line.setAttribute("x2", pos[0]);
this.line.setAttribute("y2", pos[1]);
this.highlightLine.setAttribute("x2", pos[0]);
this.highlightLine.setAttribute("y2", pos[1]);
if (this.thickLineShown) {
this.thickLine.setAttribute("x2", pos[0]);
this.thickLine.setAttribute("y2", pos[1]);
}
}
}else {//interactor is a complex
var otherEndPos = this.getOtherEnd(interactor).getPosition();
var naryPath = interactor.naryLink.hull;
var iPath = new Array();
for (var pi = 0; pi < naryPath.length; pi++) {
var p = naryPath[pi];
iPath.push(new Point2D(p[0],p[1]));
}
var a1 = new Point2D(pos[0], pos[1]);
var a2 = new Point2D(otherEndPos[0], otherEndPos[1]);
var intersect = Intersection.intersectLinePolygon(a1, a2, iPath);
var newPos;
if (intersect.points[0]){
newPos = [intersect.points[0].x,intersect.points[0].y];
} else {
newPos = pos;
}
if (this.interactors[0] === interactor) {
this.line.setAttribute("x1", newPos[0]);
this.line.setAttribute("y1", newPos[1]);
this.highlightLine.setAttribute("x1", newPos[0]);
this.highlightLine.setAttribute("y1", newPos[1]);
if (this.thickLineShown) {
this.thickLine.setAttribute("x1", newPos[0]);
this.thickLine.setAttribute("y1", newPos[1]);
}
}
else {
this.line.setAttribute("x2", newPos[0]);
this.line.setAttribute("y2", newPos[1]);
this.highlightLine.setAttribute("x2", newPos[0]);
this.highlightLine.setAttribute("y2", newPos[1]);
if (this.thickLineShown) {
this.thickLine.setAttribute("x2", newPos[0]);
this.thickLine.setAttribute("y2", newPos[1]);
}
}
}
}
};
BinaryLink.prototype.getOtherEnd = function(interactor) {
return ((this.interactors[0] === interactor) ? this.interactors[1] : this.interactors[0]);
};
module.exports = BinaryLink;
| joshkh/joshkh.github.io | src/model/link/BinaryLink.js | JavaScript | apache-2.0 | 9,868 |
import React from 'react'
import { connect } from 'react-redux'
import { Timeline, Alert } from 'antd'
const Item = Timeline.Item
@connect(state => ({
stage: state.config.stage,
news: state.config.news,
timeline: state.config.timeline
}))
class Events extends React.Component {
render (
{ news, timeline, endorsements } = this.props
) {
let past = Array.isArray(timeline) ? timeline.slice() : []
let future = past.pop()
return (
<div>
<Alert type='info' showIcon banner
message='Weekly Meetings'
description={<ul>
<li>Every Monday</li>
<li>3:30-5:30PM</li>
<li>HUB 303</li>
</ul>}
/>
<h2>Announcements</h2>
<p>{news || 'No news for now.'}</p>
{past && future
? <Timeline pending={future}>
{past.map((e, i) => (
<Item key={i} color='green'>{e}</Item>
))}
</Timeline>
: <em>We are currently developing our schedule.</em>
}
</div>
)
}
}
export default Events
| RcKeller/STF-Refresh | app/views/FrontPage/Events/Events.js | JavaScript | apache-2.0 | 1,128 |
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import { useCallback } from '@googleforcreators/react';
import { __ } from '@googleforcreators/i18n';
import { trackEvent } from '@googleforcreators/tracking';
import { Icons } from '@googleforcreators/design-system';
import { STORY_ANIMATION_STATE } from '@googleforcreators/animation';
/**
* Internal dependencies
*/
import { useStory } from '../../../app';
import PageMenuButton from './pageMenuButton';
function AnimationToggle() {
const { animationState, updateAnimationState } = useStory(
({ state: { animationState }, actions: { updateAnimationState } }) => {
return {
animationState,
updateAnimationState,
};
}
);
const isPlaying = [
STORY_ANIMATION_STATE.PLAYING,
STORY_ANIMATION_STATE.PLAYING_SELECTED,
].includes(animationState);
const tooltip = isPlaying
? __('Stop', 'web-stories')
: __('Play', 'web-stories');
const label = isPlaying
? __('Stop Page Animations', 'web-stories')
: __('Play Page Animations', 'web-stories');
const shortcut = 'mod+k';
const Icon = isPlaying ? Icons.StopOutline : Icons.PlayOutline;
const toggleAnimationState = useCallback(() => {
updateAnimationState({
animationState: isPlaying
? STORY_ANIMATION_STATE.RESET
: STORY_ANIMATION_STATE.PLAYING,
});
trackEvent('canvas_play_animations', {
status: isPlaying ? 'stop' : 'play',
});
}, [isPlaying, updateAnimationState]);
return (
<PageMenuButton
title={tooltip}
shortcut={shortcut}
onClick={toggleAnimationState}
aria-label={label}
>
<Icon />
</PageMenuButton>
);
}
export default AnimationToggle;
| GoogleForCreators/web-stories-wp | packages/story-editor/src/components/canvas/pagemenu/animationToggle.js | JavaScript | apache-2.0 | 2,294 |
/**
* @description CoatCheck SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M12,11 L22.1551134,17.4623449 C22.6217314,17.7592836 23,18.4433532 23,19.0093689 L23,20.9906311 C23,21.5480902 22.5605417,22 21.9975383,22 L2.00246167,22 C1.44881738,22 1,21.5566468 1,20.9906311 L1,19.0093689 C1,18.4519098 1.3786449,17.7590442 1.84488659,17.4623449 L12,11 Z M15,5 C15,3.34314575 13.6568542,2 12,2 C10.3431458,2 9,3.34314575 9,5 C9,5.93157601 9.41137234,6.80169553 10.0908534,7.31422922 C11,8 12,8 12,9.5 L12,11"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-coat-check`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'coat-check');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12,11 L22.1551134,17.4623449 C22.6217314,17.7592836 23,18.4433532 23,19.0093689 L23,20.9906311 C23,21.5480902 22.5605417,22 21.9975383,22 L2.00246167,22 C1.44881738,22 1,21.5566468 1,20.9906311 L1,19.0093689 C1,18.4519098 1.3786449,17.7590442 1.84488659,17.4623449 L12,11 Z M15,5 C15,3.34314575 13.6568542,2 12,2 C10.3431458,2 9,3.34314575 9,5 C9,5.93157601 9.41137234,6.80169553 10.0908534,7.31422922 C11,8 12,8 12,9.5 L12,11"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'CoatCheck';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
| odedre/grommet-final | src/js/components/icons/base/CoatCheck.js | JavaScript | apache-2.0 | 3,055 |
var appLocale = {lc:{"ar":function(n){
if (n === 0) {
return 'zero';
}
if (n == 1) {
return 'one';
}
if (n == 2) {
return 'two';
}
if ((n % 100) >= 3 && (n % 100) <= 10 && n == Math.floor(n)) {
return 'few';
}
if ((n % 100) >= 11 && (n % 100) <= 99 && n == Math.floor(n)) {
return 'many';
}
return 'other';
},"en":function(n){return n===1?"one":"other"},"bg":function(n){return n===1?"one":"other"},"bn":function(n){return n===1?"one":"other"},"ca":function(n){return n===1?"one":"other"},"cs":function(n){
if (n == 1) {
return 'one';
}
if (n == 2 || n == 3 || n == 4) {
return 'few';
}
return 'other';
},"da":function(n){return n===1?"one":"other"},"de":function(n){return n===1?"one":"other"},"el":function(n){return n===1?"one":"other"},"es":function(n){return n===1?"one":"other"},"et":function(n){return n===1?"one":"other"},"eu":function(n){return n===1?"one":"other"},"fa":function(n){return "other"},"fi":function(n){return n===1?"one":"other"},"fil":function(n){return n===0||n==1?"one":"other"},"fr":function(n){return Math.floor(n)===0||Math.floor(n)==1?"one":"other"},"gl":function(n){return n===1?"one":"other"},"he":function(n){return n===1?"one":"other"},"hi":function(n){return n===0||n==1?"one":"other"},"hr":function(n){
if ((n % 10) == 1 && (n % 100) != 11) {
return 'one';
}
if ((n % 10) >= 2 && (n % 10) <= 4 &&
((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
return 'few';
}
if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
return 'many';
}
return 'other';
},"hu":function(n){return "other"},"id":function(n){return "other"},"is":function(n){
return ((n%10) === 1 && (n%100) !== 11) ? 'one' : 'other';
},"it":function(n){return n===1?"one":"other"},"ja":function(n){return "other"},"ko":function(n){return "other"},"lt":function(n){
if ((n % 10) == 1 && ((n % 100) < 11 || (n % 100) > 19)) {
return 'one';
}
if ((n % 10) >= 2 && (n % 10) <= 9 &&
((n % 100) < 11 || (n % 100) > 19) && n == Math.floor(n)) {
return 'few';
}
return 'other';
},"lv":function(n){
if (n === 0) {
return 'zero';
}
if ((n % 10) == 1 && (n % 100) != 11) {
return 'one';
}
return 'other';
},"mk":function(n){return (n%10)==1&&n!=11?"one":"other"},"ms":function(n){return "other"},"mt":function(n){
if (n == 1) {
return 'one';
}
if (n === 0 || ((n % 100) >= 2 && (n % 100) <= 4 && n == Math.floor(n))) {
return 'few';
}
if ((n % 100) >= 11 && (n % 100) <= 19 && n == Math.floor(n)) {
return 'many';
}
return 'other';
},"nl":function(n){return n===1?"one":"other"},"no":function(n){return n===1?"one":"other"},"pl":function(n){
if (n == 1) {
return 'one';
}
if ((n % 10) >= 2 && (n % 10) <= 4 &&
((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
return 'few';
}
if ((n % 10) === 0 || n != 1 && (n % 10) == 1 ||
((n % 10) >= 5 && (n % 10) <= 9 || (n % 100) >= 12 && (n % 100) <= 14) &&
n == Math.floor(n)) {
return 'many';
}
return 'other';
},"pt":function(n){return n===1?"one":"other"},"ro":function(n){
if (n == 1) {
return 'one';
}
if (n === 0 || n != 1 && (n % 100) >= 1 &&
(n % 100) <= 19 && n == Math.floor(n)) {
return 'few';
}
return 'other';
},"ru":function(n){
if ((n % 10) == 1 && (n % 100) != 11) {
return 'one';
}
if ((n % 10) >= 2 && (n % 10) <= 4 &&
((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
return 'few';
}
if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
return 'many';
}
return 'other';
},"sk":function(n){
if (n == 1) {
return 'one';
}
if (n == 2 || n == 3 || n == 4) {
return 'few';
}
return 'other';
},"sl":function(n){
if ((n % 100) == 1) {
return 'one';
}
if ((n % 100) == 2) {
return 'two';
}
if ((n % 100) == 3 || (n % 100) == 4) {
return 'few';
}
return 'other';
},"sq":function(n){return n===1?"one":"other"},"sr":function(n){
if ((n % 10) == 1 && (n % 100) != 11) {
return 'one';
}
if ((n % 10) >= 2 && (n % 10) <= 4 &&
((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
return 'few';
}
if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
return 'many';
}
return 'other';
},"sv":function(n){return n===1?"one":"other"},"ta":function(n){return n===1?"one":"other"},"th":function(n){return "other"},"tr":function(n){return n===1?"one":"other"},"uk":function(n){
if ((n % 10) == 1 && (n % 100) != 11) {
return 'one';
}
if ((n % 10) >= 2 && (n % 10) <= 4 &&
((n % 100) < 12 || (n % 100) > 14) && n == Math.floor(n)) {
return 'few';
}
if ((n % 10) === 0 || ((n % 10) >= 5 && (n % 10) <= 9) ||
((n % 100) >= 11 && (n % 100) <= 14) && n == Math.floor(n)) {
return 'many';
}
return 'other';
},"ur":function(n){return n===1?"one":"other"},"vi":function(n){return "other"},"zh":function(n){return "other"}},
c:function(d,k){if(!d)throw new Error("MessageFormat: Data required for '"+k+"'.")},
n:function(d,k,o){if(isNaN(d[k]))throw new Error("MessageFormat: '"+k+"' isn't a number.");return d[k]-(o||0)},
v:function(d,k){appLocale.c(d,k);return d[k]},
p:function(d,k,o,l,p){appLocale.c(d,k);return d[k] in p?p[d[k]]:(k=appLocale.lc[l](d[k]-o),k in p?p[k]:p.other)},
s:function(d,k,p){appLocale.c(d,k);return d[k] in p?p[d[k]]:p.other}};
(window.blockly = window.blockly || {}).appLocale = {
"actor":function(d){return "actor"},
"alienInvasion":function(d){return "Alien Invasion!"},
"backgroundBlack":function(d){return "black"},
"backgroundCave":function(d){return "cave"},
"backgroundCloudy":function(d){return "cloudy"},
"backgroundHardcourt":function(d){return "hardcourt"},
"backgroundNight":function(d){return "night"},
"backgroundUnderwater":function(d){return "underwater"},
"backgroundCity":function(d){return "city"},
"backgroundDesert":function(d){return "desert"},
"backgroundRainbow":function(d){return "rainbow"},
"backgroundSoccer":function(d){return "soccer"},
"backgroundSpace":function(d){return "space"},
"backgroundTennis":function(d){return "tennis"},
"backgroundWinter":function(d){return "winter"},
"catActions":function(d){return "Actions"},
"catControl":function(d){return "Loops"},
"catEvents":function(d){return "Events"},
"catLogic":function(d){return "Logic"},
"catMath":function(d){return "Math"},
"catProcedures":function(d){return "Functions"},
"catText":function(d){return "Text"},
"catVariables":function(d){return "Variables"},
"changeScoreTooltip":function(d){return "Add or remove a point to the score."},
"changeScoreTooltipK1":function(d){return "Add a point to the score."},
"continue":function(d){return "Continue"},
"decrementPlayerScore":function(d){return "remove point"},
"defaultSayText":function(d){return "type here"},
"emotion":function(d){return "mood"},
"finalLevel":function(d){return "Congratulations! You have solved the final puzzle."},
"for":function(d){return "for"},
"hello":function(d){return "hello"},
"helloWorld":function(d){return "Hello World!"},
"incrementPlayerScore":function(d){return "score point"},
"makeProjectileDisappear":function(d){return "disappear"},
"makeProjectileBounce":function(d){return "bounce"},
"makeProjectileBlueFireball":function(d){return "make blue fireball"},
"makeProjectilePurpleFireball":function(d){return "make purple fireball"},
"makeProjectileRedFireball":function(d){return "make red fireball"},
"makeProjectileYellowHearts":function(d){return "make yellow hearts"},
"makeProjectilePurpleHearts":function(d){return "make purple hearts"},
"makeProjectileRedHearts":function(d){return "make red hearts"},
"makeProjectileTooltip":function(d){return "Make the projectile that just collided disappear or bounce."},
"makeYourOwn":function(d){return "Make Your Own Play Lab App"},
"moveDirectionDown":function(d){return "down"},
"moveDirectionLeft":function(d){return "left"},
"moveDirectionRight":function(d){return "right"},
"moveDirectionUp":function(d){return "up"},
"moveDirectionRandom":function(d){return "aleatorio"},
"moveDistance25":function(d){return "25 pixels"},
"moveDistance50":function(d){return "50 pixels"},
"moveDistance100":function(d){return "100 pixels"},
"moveDistance200":function(d){return "200 pixels"},
"moveDistance400":function(d){return "400 pixels"},
"moveDistancePixels":function(d){return "pixels"},
"moveDistanceRandom":function(d){return "random pixels"},
"moveDistanceTooltip":function(d){return "Move an actor a specific distance in the specified direction."},
"moveSprite":function(d){return "move"},
"moveSpriteN":function(d){return "move actor "+appLocale.v(d,"spriteIndex")},
"toXY":function(d){return "to x,y"},
"moveDown":function(d){return "move down"},
"moveDownTooltip":function(d){return "Move an actor down."},
"moveLeft":function(d){return "move left"},
"moveLeftTooltip":function(d){return "Move an actor to the left."},
"moveRight":function(d){return "move right"},
"moveRightTooltip":function(d){return "Move an actor to the right."},
"moveUp":function(d){return "move up"},
"moveUpTooltip":function(d){return "Move an actor up."},
"moveTooltip":function(d){return "Move an actor."},
"nextLevel":function(d){return "Congratulations! You have completed this puzzle."},
"no":function(d){return "No"},
"numBlocksNeeded":function(d){return "This puzzle can be solved with %1 blocks."},
"ouchExclamation":function(d){return "Ouch!"},
"playSoundCrunch":function(d){return "play crunch sound"},
"playSoundGoal1":function(d){return "play goal 1 sound"},
"playSoundGoal2":function(d){return "play goal 2 sound"},
"playSoundHit":function(d){return "play hit sound"},
"playSoundLosePoint":function(d){return "play lose point sound"},
"playSoundLosePoint2":function(d){return "play lose point 2 sound"},
"playSoundRetro":function(d){return "play retro sound"},
"playSoundRubber":function(d){return "play rubber sound"},
"playSoundSlap":function(d){return "play slap sound"},
"playSoundTooltip":function(d){return "Play the chosen sound."},
"playSoundWinPoint":function(d){return "play win point sound"},
"playSoundWinPoint2":function(d){return "play win point 2 sound"},
"playSoundWood":function(d){return "play wood sound"},
"positionOutTopLeft":function(d){return "to the above top left position"},
"positionOutTopRight":function(d){return "to the above top right position"},
"positionTopOutLeft":function(d){return "to the top outside left position"},
"positionTopLeft":function(d){return "to the top left position"},
"positionTopCenter":function(d){return "to the top center position"},
"positionTopRight":function(d){return "to the top right position"},
"positionTopOutRight":function(d){return "to the top outside right position"},
"positionMiddleLeft":function(d){return "to the middle left position"},
"positionMiddleCenter":function(d){return "to the middle center position"},
"positionMiddleRight":function(d){return "to the middle right position"},
"positionBottomOutLeft":function(d){return "to the bottom outside left position"},
"positionBottomLeft":function(d){return "to the bottom left position"},
"positionBottomCenter":function(d){return "to the bottom center position"},
"positionBottomRight":function(d){return "to the bottom right position"},
"positionBottomOutRight":function(d){return "to the bottom outside right position"},
"positionOutBottomLeft":function(d){return "to the below bottom left position"},
"positionOutBottomRight":function(d){return "to the below bottom right position"},
"positionRandom":function(d){return "to the random position"},
"projectileBlueFireball":function(d){return "blue fireball"},
"projectilePurpleFireball":function(d){return "purple fireball"},
"projectileRedFireball":function(d){return "red fireball"},
"projectileYellowHearts":function(d){return "yellow hearts"},
"projectilePurpleHearts":function(d){return "purple hearts"},
"projectileRedHearts":function(d){return "red hearts"},
"projectileRandom":function(d){return "aleatorio"},
"projectileAnna":function(d){return "hook"},
"projectileElsa":function(d){return "sparkle"},
"projectileHiro":function(d){return "microbots"},
"projectileBaymax":function(d){return "rocket"},
"projectileRapunzel":function(d){return "saucepan"},
"projectileCherry":function(d){return "cherry"},
"projectileIce":function(d){return "ice"},
"projectileDuck":function(d){return "duck"},
"reinfFeedbackMsg":function(d){return "You can press the \"Try again\" button to go back to playing your story."},
"repeatForever":function(d){return "repeat forever"},
"repeatDo":function(d){return "do"},
"repeatForeverTooltip":function(d){return "Execute the actions in this block repeatedly while the story is running."},
"saySprite":function(d){return "say"},
"saySpriteN":function(d){return "actor "+appLocale.v(d,"spriteIndex")+" say"},
"saySpriteTooltip":function(d){return "Pop up a speech bubble with the associated text from the specified actor."},
"saySpriteChoices_1":function(d){return "Hi there!"},
"saySpriteChoices_2":function(d){return "How are you?"},
"saySpriteChoices_3":function(d){return "This is fun..."},
"scoreText":function(d){return "Score: "+appLocale.v(d,"playerScore")},
"setBackground":function(d){return "set background"},
"setBackgroundRandom":function(d){return "set random background"},
"setBackgroundBlack":function(d){return "set black background"},
"setBackgroundCave":function(d){return "set cave background"},
"setBackgroundCloudy":function(d){return "set cloudy background"},
"setBackgroundHardcourt":function(d){return "set hardcourt background"},
"setBackgroundNight":function(d){return "set night background"},
"setBackgroundUnderwater":function(d){return "set underwater background"},
"setBackgroundCity":function(d){return "set city background"},
"setBackgroundDesert":function(d){return "set desert background"},
"setBackgroundRainbow":function(d){return "set rainbow background"},
"setBackgroundSoccer":function(d){return "set soccer background"},
"setBackgroundSpace":function(d){return "set space background"},
"setBackgroundTennis":function(d){return "set tennis background"},
"setBackgroundWinter":function(d){return "set winter background"},
"setBackgroundLeafy":function(d){return "set leafy background"},
"setBackgroundGrassy":function(d){return "set grassy background"},
"setBackgroundFlower":function(d){return "set flower background"},
"setBackgroundTile":function(d){return "set tile background"},
"setBackgroundIcy":function(d){return "set icy background"},
"setBackgroundSnowy":function(d){return "set snowy background"},
"setBackgroundTooltip":function(d){return "Sets the background image"},
"setEnemySpeed":function(d){return "set enemy speed"},
"setPlayerSpeed":function(d){return "set player speed"},
"setScoreText":function(d){return "set score"},
"setScoreTextTooltip":function(d){return "Sets the text to be displayed in the score area."},
"setSpriteEmotionAngry":function(d){return "to a angry mood"},
"setSpriteEmotionHappy":function(d){return "to a happy mood"},
"setSpriteEmotionNormal":function(d){return "to a normal mood"},
"setSpriteEmotionRandom":function(d){return "to a random mood"},
"setSpriteEmotionSad":function(d){return "to a sad mood"},
"setSpriteEmotionTooltip":function(d){return "Sets the actor mood"},
"setSpriteAlien":function(d){return "to an alien image"},
"setSpriteBat":function(d){return "to a bat image"},
"setSpriteBird":function(d){return "to a bird image"},
"setSpriteCat":function(d){return "to a cat image"},
"setSpriteCaveBoy":function(d){return "to a cave boy image"},
"setSpriteCaveGirl":function(d){return "to a cave girl image"},
"setSpriteDinosaur":function(d){return "to a dinosaur image"},
"setSpriteDog":function(d){return "to a dog image"},
"setSpriteDragon":function(d){return "to a dragon image"},
"setSpriteGhost":function(d){return "to a ghost image"},
"setSpriteHidden":function(d){return "to a hidden image"},
"setSpriteHideK1":function(d){return "hide"},
"setSpriteAnna":function(d){return "to a Anna image"},
"setSpriteElsa":function(d){return "to a Elsa image"},
"setSpriteHiro":function(d){return "to a Hiro image"},
"setSpriteBaymax":function(d){return "to a Baymax image"},
"setSpriteRapunzel":function(d){return "to a Rapunzel image"},
"setSpriteKnight":function(d){return "to a knight image"},
"setSpriteMonster":function(d){return "to a monster image"},
"setSpriteNinja":function(d){return "to a masked ninja image"},
"setSpriteOctopus":function(d){return "to an octopus image"},
"setSpritePenguin":function(d){return "to a penguin image"},
"setSpritePirate":function(d){return "to a pirate image"},
"setSpritePrincess":function(d){return "to a princess image"},
"setSpriteRandom":function(d){return "to a random image"},
"setSpriteRobot":function(d){return "to a robot image"},
"setSpriteShowK1":function(d){return "show"},
"setSpriteSpacebot":function(d){return "to a spacebot image"},
"setSpriteSoccerGirl":function(d){return "to a soccer girl image"},
"setSpriteSoccerBoy":function(d){return "to a soccer boy image"},
"setSpriteSquirrel":function(d){return "to a squirrel image"},
"setSpriteTennisGirl":function(d){return "to a tennis girl image"},
"setSpriteTennisBoy":function(d){return "to a tennis boy image"},
"setSpriteUnicorn":function(d){return "to a unicorn image"},
"setSpriteWitch":function(d){return "to a witch image"},
"setSpriteWizard":function(d){return "to a wizard image"},
"setSpritePositionTooltip":function(d){return "Instantly moves an actor to the specified location."},
"setSpriteK1Tooltip":function(d){return "Shows or hides the specified actor."},
"setSpriteTooltip":function(d){return "Sets the actor image"},
"setSpriteSizeRandom":function(d){return "to a random size"},
"setSpriteSizeVerySmall":function(d){return "to a very small size"},
"setSpriteSizeSmall":function(d){return "to a small size"},
"setSpriteSizeNormal":function(d){return "to a normal size"},
"setSpriteSizeLarge":function(d){return "to a large size"},
"setSpriteSizeVeryLarge":function(d){return "to a very large size"},
"setSpriteSizeTooltip":function(d){return "Sets the size of an actor"},
"setSpriteSpeedRandom":function(d){return "to a random speed"},
"setSpriteSpeedVerySlow":function(d){return "to a very slow speed"},
"setSpriteSpeedSlow":function(d){return "to a slow speed"},
"setSpriteSpeedNormal":function(d){return "to a normal speed"},
"setSpriteSpeedFast":function(d){return "to a fast speed"},
"setSpriteSpeedVeryFast":function(d){return "to a very fast speed"},
"setSpriteSpeedTooltip":function(d){return "Sets the speed of an actor"},
"setSpriteZombie":function(d){return "to a zombie image"},
"shareStudioTwitter":function(d){return "Check out the story I made. I wrote it myself with @codeorg"},
"shareGame":function(d){return "Share your story:"},
"showCoordinates":function(d){return "show coordinates"},
"showCoordinatesTooltip":function(d){return "show the protagonist's coordinates on the screen"},
"showTitleScreen":function(d){return "show title screen"},
"showTitleScreenTitle":function(d){return "title"},
"showTitleScreenText":function(d){return "text"},
"showTSDefTitle":function(d){return "type title here"},
"showTSDefText":function(d){return "type text here"},
"showTitleScreenTooltip":function(d){return "Show a title screen with the associated title and text."},
"size":function(d){return "size"},
"setSprite":function(d){return "estabelecer"},
"setSpriteN":function(d){return "set actor "+appLocale.v(d,"spriteIndex")},
"soundCrunch":function(d){return "crunch"},
"soundGoal1":function(d){return "goal 1"},
"soundGoal2":function(d){return "goal 2"},
"soundHit":function(d){return "hit"},
"soundLosePoint":function(d){return "lose point"},
"soundLosePoint2":function(d){return "lose point 2"},
"soundRetro":function(d){return "retro"},
"soundRubber":function(d){return "rubber"},
"soundSlap":function(d){return "slap"},
"soundWinPoint":function(d){return "win point"},
"soundWinPoint2":function(d){return "win point 2"},
"soundWood":function(d){return "wood"},
"speed":function(d){return "speed"},
"startSetValue":function(d){return "start (rocket-height function)"},
"startSetVars":function(d){return "game_vars (title, subtitle, background, target, danger, player)"},
"startSetFuncs":function(d){return "game_funcs (update-target, update-danger, update-player, collide?, on-screen?)"},
"stopSprite":function(d){return "stop"},
"stopSpriteN":function(d){return "stop actor "+appLocale.v(d,"spriteIndex")},
"stopTooltip":function(d){return "Stops an actor's movement."},
"throwSprite":function(d){return "throw"},
"throwSpriteN":function(d){return "actor "+appLocale.v(d,"spriteIndex")+" throw"},
"throwTooltip":function(d){return "Throws a projectile from the specified actor."},
"vanish":function(d){return "vanish"},
"vanishActorN":function(d){return "vanish actor "+appLocale.v(d,"spriteIndex")},
"vanishTooltip":function(d){return "Vanishes the actor."},
"waitFor":function(d){return "wait for"},
"waitSeconds":function(d){return "seconds"},
"waitForClick":function(d){return "wait for click"},
"waitForRandom":function(d){return "wait for random"},
"waitForHalfSecond":function(d){return "wait for a half second"},
"waitFor1Second":function(d){return "wait for 1 second"},
"waitFor2Seconds":function(d){return "wait for 2 seconds"},
"waitFor5Seconds":function(d){return "wait for 5 seconds"},
"waitFor10Seconds":function(d){return "wait for 10 seconds"},
"waitParamsTooltip":function(d){return "Waits for a specified number of seconds or use zero to wait until a click occurs."},
"waitTooltip":function(d){return "Waits for a specified amount of time or until a click occurs."},
"whenArrowDown":function(d){return "down arrow"},
"whenArrowLeft":function(d){return "left arrow"},
"whenArrowRight":function(d){return "right arrow"},
"whenArrowUp":function(d){return "up arrow"},
"whenArrowTooltip":function(d){return "Execute the actions below when the specified arrow key is pressed."},
"whenDown":function(d){return "when down arrow"},
"whenDownTooltip":function(d){return "Execute the actions below when the down arrow key is pressed."},
"whenGameStarts":function(d){return "when story starts"},
"whenGameStartsTooltip":function(d){return "Execute the actions below when the story starts."},
"whenLeft":function(d){return "when left arrow"},
"whenLeftTooltip":function(d){return "Execute the actions below when the left arrow key is pressed."},
"whenRight":function(d){return "when right arrow"},
"whenRightTooltip":function(d){return "Execute the actions below when the right arrow key is pressed."},
"whenSpriteClicked":function(d){return "when actor clicked"},
"whenSpriteClickedN":function(d){return "when actor "+appLocale.v(d,"spriteIndex")+" clicked"},
"whenSpriteClickedTooltip":function(d){return "Execute the actions below when an actor is clicked."},
"whenSpriteCollidedN":function(d){return "when actor "+appLocale.v(d,"spriteIndex")},
"whenSpriteCollidedTooltip":function(d){return "Execute the actions below when an actor touches another actor."},
"whenSpriteCollidedWith":function(d){return "touches"},
"whenSpriteCollidedWithAnyActor":function(d){return "touches any actor"},
"whenSpriteCollidedWithAnyEdge":function(d){return "touches any edge"},
"whenSpriteCollidedWithAnyProjectile":function(d){return "touches any projectile"},
"whenSpriteCollidedWithAnything":function(d){return "touches anything"},
"whenSpriteCollidedWithN":function(d){return "touches actor "+appLocale.v(d,"spriteIndex")},
"whenSpriteCollidedWithBlueFireball":function(d){return "touches blue fireball"},
"whenSpriteCollidedWithPurpleFireball":function(d){return "touches purple fireball"},
"whenSpriteCollidedWithRedFireball":function(d){return "touches red fireball"},
"whenSpriteCollidedWithYellowHearts":function(d){return "touches yellow hearts"},
"whenSpriteCollidedWithPurpleHearts":function(d){return "touches purple hearts"},
"whenSpriteCollidedWithRedHearts":function(d){return "touches red hearts"},
"whenSpriteCollidedWithBottomEdge":function(d){return "touches bottom edge"},
"whenSpriteCollidedWithLeftEdge":function(d){return "touches left edge"},
"whenSpriteCollidedWithRightEdge":function(d){return "touches right edge"},
"whenSpriteCollidedWithTopEdge":function(d){return "touches top edge"},
"whenUp":function(d){return "when up arrow"},
"whenUpTooltip":function(d){return "Execute the actions below when the up arrow key is pressed."},
"yes":function(d){return "Yes"}}; | bakerfranke/code-dot-org | dashboard/public/apps-package/js/gl_es/studio_locale.js | JavaScript | apache-2.0 | 24,633 |
// Copyright 2014 The Oppia Authors. 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.
/**
* @fileoverview Directive for the state graph visualization.
*/
/* eslint-disable angular/directive-restrict */
oppia.directive('stateGraphViz', [
'UrlInterpolationService', function(UrlInterpolationService) {
return {
// Note: This directive is used as attribute because pannability does not
// work when directive is used as element. (Convention in the codebase
// is to use directive as element.)
restrict: 'A',
scope: {
allowPanning: '@',
centerAtCurrentState: '@',
currentStateId: '&',
// A function returning an object with these keys:
// - 'nodes': An object whose keys are node ids and whose values are
// node labels
// - 'links': A list of objects with keys:
// 'source': id of source node
// 'target': id of target node
// 'linkProperty': property of link which determines how
// it is styled (styles in linkPropertyMapping). If
// linkProperty or corresponding linkPropertyMatching
// is undefined, link style defaults to the gray arrow.
// - 'initStateId': The initial state id
// - 'finalStateIds': The list of ids corresponding to terminal states
// (i.e., those whose interactions are terminal).
graphData: '&',
// Object whose keys are ids of nodes to display a warning tooltip over
highlightStates: '=',
// Id of a second initial state, which will be styled as an initial
// state
initStateId2: '=',
isEditable: '=',
// Object which maps linkProperty to a style
linkPropertyMapping: '=',
// Object whose keys are node ids and whose values are node colors
nodeColors: '=',
// A value which is the color of all nodes
nodeFill: '@',
// Object whose keys are node ids with secondary labels and whose
// values are secondary labels. If this is undefined, it means no nodes
// have secondary labels.
nodeSecondaryLabels: '=',
// Function called when node is clicked. Should take a parameter
// node.id.
onClickFunction: '=',
onDeleteFunction: '=',
onMaximizeFunction: '=',
// Object whose keys are ids of nodes, and whose values are the
// corresponding node opacities.
opacityMap: '=',
showWarningSign: '@'
},
templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
'/pages/exploration_editor/editor_tab/' +
'state_graph_visualization_directive.html'),
controller: [
'$scope', '$element', '$timeout', '$filter', 'StateGraphLayoutService',
'ExplorationWarningsService', 'MAX_NODES_PER_ROW',
'MAX_NODE_LABEL_LENGTH',
function(
$scope, $element, $timeout, $filter, StateGraphLayoutService,
ExplorationWarningsService, MAX_NODES_PER_ROW,
MAX_NODE_LABEL_LENGTH) {
var redrawGraph = function() {
if ($scope.graphData()) {
$scope.graphLoaded = false;
$scope.drawGraph(
$scope.graphData().nodes, $scope.graphData().links,
$scope.graphData().initStateId, $scope.graphData().finalStateIds
);
// Wait for the graph to finish loading before showing it again.
$timeout(function() {
$scope.graphLoaded = true;
});
}
};
$scope.$on('redrawGraph', function() {
redrawGraph();
});
$scope.$watch('graphData()', redrawGraph, true);
$scope.$watch('currentStateId()', redrawGraph);
// If statistics for a different version of the exploration are
// loaded, this may change the opacities of the nodes.
$scope.$watch('opacityMap', redrawGraph);
$(window).resize(redrawGraph);
var getElementDimensions = function() {
return {
h: $element.height(),
w: $element.width()
};
};
// Returns the closest number to `value` in the range
// [bound1, bound2].
var clamp = function(value, bound1, bound2) {
var minValue = Math.min(bound1, bound2);
var maxValue = Math.max(bound1, bound2);
return Math.min(Math.max(value, minValue), maxValue);
};
$scope.getGraphHeightInPixels = function() {
return Math.max($scope.GRAPH_HEIGHT, 300);
};
$scope.drawGraph = function(
nodes, originalLinks, initStateId, finalStateIds) {
$scope.finalStateIds = finalStateIds;
var links = angular.copy(originalLinks);
var nodeData = StateGraphLayoutService.computeLayout(
nodes, links, initStateId, angular.copy(finalStateIds));
$scope.GRAPH_WIDTH = StateGraphLayoutService.getGraphWidth(
MAX_NODES_PER_ROW, MAX_NODE_LABEL_LENGTH);
$scope.GRAPH_HEIGHT = StateGraphLayoutService.getGraphHeight(
nodeData);
nodeData = StateGraphLayoutService.modifyPositionValues(
nodeData, $scope.GRAPH_WIDTH, $scope.GRAPH_HEIGHT);
// These constants correspond to the rectangle that, when clicked
// and dragged, translates the graph. Its height, width, and x and
// y offsets are set to arbitrary large values so that the
// draggable area extends beyond the graph.
$scope.VIEWPORT_WIDTH = Math.max(10000, $scope.GRAPH_WIDTH * 5);
$scope.VIEWPORT_HEIGHT = Math.max(10000, $scope.GRAPH_HEIGHT * 5);
$scope.VIEWPORT_X = -Math.max(1000, $scope.GRAPH_WIDTH * 2);
$scope.VIEWPORT_Y = -Math.max(1000, $scope.GRAPH_HEIGHT * 2);
var graphBounds = StateGraphLayoutService.getGraphBoundaries(
nodeData);
$scope.augmentedLinks = StateGraphLayoutService.getAugmentedLinks(
nodeData, links);
for (var i = 0; i < $scope.augmentedLinks.length; i++) {
// Style links if link properties and style mappings are
// provided
if (links[i].hasOwnProperty('linkProperty') &&
$scope.linkPropertyMapping) {
if ($scope.linkPropertyMapping.hasOwnProperty(
links[i].linkProperty)) {
$scope.augmentedLinks[i].style = (
$scope.linkPropertyMapping[links[i].linkProperty]);
}
}
}
var getNodeStrokeWidth = function(nodeId) {
var currentNodeIsTerminal = (
$scope.finalStateIds.indexOf(nodeId) !== -1);
return (
nodeId === $scope.currentStateId() ? '3' :
(nodeId === $scope.initStateId2 || currentNodeIsTerminal) ?
'2' : '1');
};
var getNodeFillOpacity = function(nodeId) {
return $scope.opacityMap ? $scope.opacityMap[nodeId] : 0.5;
};
$scope.isStateFlagged = function(nodeId) {
return (
$scope.highlightStates &&
$scope.highlightStates.hasOwnProperty(nodeId));
};
$scope.getNodeTitle = function(node) {
var warning = '';
if (node.reachable === false) {
warning = 'Warning: this state is unreachable.';
} else if (node.reachableFromEnd === false) {
warning = (
'Warning: there is no path from this state to the END state.'
);
}
var tooltip = node.label;
if (node.hasOwnProperty('secondaryLabel')) {
tooltip += ' ' + node.secondaryLabel;
}
if (warning) {
tooltip += ' (' + warning + ')';
}
return tooltip;
};
$scope.onNodeDeletionClick = function(nodeId) {
if (nodeId !== initStateId) {
$scope.onDeleteFunction(nodeId);
}
};
$scope.getHighlightTransform = function(x0, y0) {
return 'rotate(-10,' + (x0 - 10) + ',' + (y0 - 5) + ')';
};
$scope.getHighlightTextTransform = function(x0, y0) {
return 'rotate(-10,' + x0 + ',' + (y0 - 4) + ')';
};
$scope.canNavigateToNode = function(nodeId) {
return nodeId !== $scope.currentStateId();
};
$scope.getTruncatedLabel = function(nodeLabel) {
return $filter('truncate')(nodeLabel, MAX_NODE_LABEL_LENGTH);
};
// Update the nodes.
$scope.nodeList = [];
for (var nodeId in nodeData) {
nodeData[nodeId].style = (
'stroke-width: ' + getNodeStrokeWidth(nodeId) + '; ' +
'fill-opacity: ' + getNodeFillOpacity(nodeId) + ';');
if ($scope.nodeFill) {
nodeData[nodeId].style += ('fill: ' + $scope.nodeFill + '; ');
}
// Color nodes
if ($scope.nodeColors) {
nodeData[nodeId].style += (
'fill: ' + $scope.nodeColors[nodeId] + '; ');
}
// Add secondary label if it exists
if ($scope.nodeSecondaryLabels) {
if ($scope.nodeSecondaryLabels.hasOwnProperty(nodeId)) {
nodeData[nodeId].secondaryLabel = (
$scope.nodeSecondaryLabels[nodeId]);
nodeData[nodeId].height *= 1.1;
}
}
var currentNodeIsTerminal = (
$scope.finalStateIds.indexOf(nodeId) !== -1);
nodeData[nodeId].nodeClass = (
currentNodeIsTerminal ? 'terminal-node' :
nodeId === $scope.currentStateId() ? 'current-node' :
nodeId === initStateId ? 'init-node' :
!(nodeData[nodeId].reachable &&
nodeData[nodeId].reachableFromEnd) ? 'bad-node' :
'normal-node');
nodeData[nodeId].canDelete = (nodeId !== initStateId);
$scope.nodeList.push(nodeData[nodeId]);
}
$scope.getNodeErrorMessage = function(nodeLabel) {
var warnings =
ExplorationWarningsService.getAllStateRelatedWarnings();
if (warnings.hasOwnProperty(nodeLabel)) {
return warnings[nodeLabel][0].toString();
}
};
// The translation applied when the graph is first loaded.
var origTranslations = [0, 0];
$scope.overallTransformStr = 'translate(0,0)';
$scope.innerTransformStr = 'translate(0,0)';
if ($scope.allowPanning) {
// Without the timeout, $element.find fails to find the required
// rect in the state graph modal dialog.
$timeout(function() {
var dimensions = getElementDimensions();
d3.select($element.find('rect.pannable-rect')[0])
.call(d3.behavior.zoom().scaleExtent([1, 1])
.on('zoom', function() {
if (graphBounds.right - graphBounds.left < dimensions.w) {
d3.event.translate[0] = 0;
} else {
d3.event.translate[0] = clamp(
d3.event.translate[0],
dimensions.w - graphBounds.right -
origTranslations[0],
-graphBounds.left - origTranslations[0]);
}
if (graphBounds.bottom - graphBounds.top < dimensions.h) {
d3.event.translate[1] = 0;
} else {
d3.event.translate[1] = clamp(
d3.event.translate[1],
dimensions.h - graphBounds.bottom -
origTranslations[1],
-graphBounds.top - origTranslations[1]);
}
// We need a separate layer here so that the translation
// does not influence the panning event receivers.
$scope.innerTransformStr = (
'translate(' + d3.event.translate + ')');
$scope.$apply();
})
);
}, 10);
}
if ($scope.centerAtCurrentState) {
$timeout(function() {
var dimensions = getElementDimensions();
// Center the graph at the node representing the current state.
origTranslations[0] = (
dimensions.w / 2 - nodeData[$scope.currentStateId()].x0 -
nodeData[$scope.currentStateId()].width / 2);
origTranslations[1] = (
dimensions.h / 2 - nodeData[$scope.currentStateId()].y0 -
nodeData[$scope.currentStateId()].height / 2);
if (graphBounds.right - graphBounds.left < dimensions.w) {
origTranslations[0] = (
dimensions.w / 2 -
(graphBounds.right + graphBounds.left) / 2);
} else {
origTranslations[0] = clamp(
origTranslations[0],
dimensions.w - graphBounds.right,
-graphBounds.left);
}
if (graphBounds.bottom - graphBounds.top < dimensions.h) {
origTranslations[1] = (
dimensions.h / 2 -
(graphBounds.bottom + graphBounds.top) / 2);
} else {
origTranslations[1] = clamp(
origTranslations[1],
dimensions.h - graphBounds.bottom,
-graphBounds.top);
}
$scope.overallTransformStr = (
'translate(' + origTranslations + ')');
$scope.$apply();
}, 20);
}
};
}
]
};
}]);
/* eslint-enable angular/directive-restrict */
| AllanYangZhou/oppia | core/templates/dev/head/pages/exploration_editor/editor_tab/StateGraphVisualizationDirective.js | JavaScript | apache-2.0 | 15,193 |
function Controller() {
function closeModal(e) {
$.modal.fireEvent("removeClose", e);
}
function handleTableViewClick(e) {
if (1 == Alloy.Globals.purchases[e.index] || 1 == Alloy.Globals.purchases[1]) {
for (var i = 0; $.tv.data[0].rows.length > i; i++) $.tv.data[0].rows[i].hasCheck = false;
for (var i = 0; $.tv.data[1].rows.length > i; i++) $.tv.data[1].rows[i].hasCheck = false;
e.row.hasCheck = true;
Ti.API.info(" e.index: " + e.index);
settings.set({
question_set: e.index
});
settings.save();
} else alert("You must purchase this item before being able to select it");
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "set_select";
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
arguments[0] ? arguments[0]["__itemTemplate"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.modal = Ti.UI.createWindow(function() {
var o = {};
_.extend(o, {});
Alloy.isTablet && _.extend(o, {
width: "100%",
height: "90%",
borderRadius: 5,
top: 0,
backgroundColor: "#eeeeee"
});
_.extend(o, {});
Alloy.isHandheld && _.extend(o, {
backgroundColor: "#f1f1f1"
});
_.extend(o, {
id: "modal",
navBarHidden: "true"
});
return o;
}());
$.__views.modal && $.addTopLevelView($.__views.modal);
$.__views.vertical = Ti.UI.createView({
id: "vertical"
});
$.__views.modal.add($.__views.vertical);
$.__views.header = Ti.UI.createView(function() {
var o = {};
_.extend(o, {
top: 0,
backgroundColor: "#1b4fb4"
});
Alloy.isTablet && _.extend(o, {
height: 60,
backgroundColor: "#1b4fb4"
});
_.extend(o, {});
Alloy.isHandheld && _.extend(o, {
height: 45
});
_.extend(o, {
id: "header"
});
return o;
}());
$.__views.vertical.add($.__views.header);
$.__views.title = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
font: {
fontSize: 21,
fontFamily: "AvenirLTStd-Medium"
},
color: "#fff"
});
Alloy.isTablet && _.extend(o, {
font: {
fontSize: 30,
fontFamily: "AvenirLTStd-Medium"
},
color: "#fff"
});
_.extend(o, {
text: "Question Set",
id: "title"
});
return o;
}());
$.__views.header.add($.__views.title);
$.__views.settings_back_btn = Alloy.createController("settings_back_btn", {
id: "settings_back_btn",
__parentSymbol: $.__views.header
});
$.__views.settings_back_btn.setParent($.__views.header);
closeModal ? $.__views.settings_back_btn.on("click", closeModal) : __defers["$.__views.settings_back_btn!click!closeModal"] = true;
$.__views.scrollView = Ti.UI.createScrollView(function() {
var o = {};
_.extend(o, {
layout: "vertical",
top: 45,
bottom: 0
});
Alloy.isTablet && _.extend(o, {
layout: "vertical",
top: 80,
width: "100%",
height: "90%",
bottom: 0
});
_.extend(o, {
id: "scrollView",
showVerticalScrollIndicator: "true"
});
return o;
}());
$.__views.vertical.add($.__views.scrollView);
$.__views.description = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
font: {
fontSize: 14,
fontFamily: "AvenirLTStd-Roman"
},
color: "#222222",
left: 10,
right: 10,
top: 10
});
Alloy.isTablet && _.extend(o, {
font: {
fontSize: 25,
fontFamily: "AvenirLTStd-Roman"
},
color: "#222222",
left: 10,
right: 10,
top: 10
});
_.extend(o, {
text: "Choose where your questions will come from.\n\nThe starter and full sets have questions from every topic. You can also choose to study just one subject if you’ve purchased it.",
id: "description"
});
return o;
}());
$.__views.scrollView.add($.__views.description);
$.__views.page_title = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
font: {
fontSize: 16,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222",
left: 10,
right: 10,
top: 10
});
Alloy.isTablet && _.extend(o, {
font: {
fontSize: 25,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222",
left: 10,
right: 10,
top: 10
});
_.extend(o, {
text: "Question Sets",
id: "page_title"
});
return o;
}());
$.__views.scrollView.add($.__views.page_title);
$.__views.__alloyId170 = Ti.UI.createTableViewSection({
id: "__alloyId170"
});
var __alloyId171 = [];
__alloyId171.push($.__views.__alloyId170);
$.__views.__alloyId172 = Ti.UI.createTableViewRow(function() {
var o = {};
_.extend(o, {
height: 60
});
Alloy.isTablet && _.extend(o, {
height: 100
});
_.extend(o, {
touchEnabled: "false",
backgroundColor: "white",
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY,
id: "__alloyId172"
});
return o;
}());
$.__views.__alloyId170.add($.__views.__alloyId172);
$.__views.__alloyId173 = Ti.UI.createView({
left: "10",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId173"
});
$.__views.__alloyId172.add($.__views.__alloyId173);
$.__views.__alloyId174 = Ti.UI.createView({
layout: "vertical",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId174"
});
$.__views.__alloyId173.add($.__views.__alloyId174);
$.__views.__alloyId175 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 16,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 30,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
_.extend(o, {
text: "Starter Set",
id: "__alloyId175"
});
return o;
}());
$.__views.__alloyId174.add($.__views.__alloyId175);
$.__views.__alloyId176 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 14,
fontFamily: "AvenirLTStd-Roman"
},
color: "#666666"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 25,
fontFamily: "AvenirLTStd-Roman"
},
color: "#666666"
});
_.extend(o, {
text: "A sample set from every subject",
id: "__alloyId176"
});
return o;
}());
$.__views.__alloyId174.add($.__views.__alloyId176);
$.__views.__alloyId177 = Ti.UI.createTableViewRow(function() {
var o = {};
_.extend(o, {
height: 60
});
Alloy.isTablet && _.extend(o, {
height: 100
});
_.extend(o, {
touchEnabled: "false",
backgroundColor: "white",
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY,
id: "__alloyId177"
});
return o;
}());
$.__views.__alloyId170.add($.__views.__alloyId177);
$.__views.__alloyId178 = Ti.UI.createView({
left: "10",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId178"
});
$.__views.__alloyId177.add($.__views.__alloyId178);
$.__views.__alloyId179 = Ti.UI.createView({
layout: "vertical",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId179"
});
$.__views.__alloyId178.add($.__views.__alloyId179);
$.__views.__alloyId180 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 16,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 30,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
_.extend(o, {
text: "Full Set",
id: "__alloyId180"
});
return o;
}());
$.__views.__alloyId179.add($.__views.__alloyId180);
$.__views.__alloyId181 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 14,
fontFamily: "AvenirLTStd-Roman"
},
color: "#666666"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 25,
fontFamily: "AvenirLTStd-Roman"
},
color: "#666666"
});
_.extend(o, {
text: "All the blocks at a discount",
id: "__alloyId181"
});
return o;
}());
$.__views.__alloyId179.add($.__views.__alloyId181);
$.__views.__alloyId182 = Ti.UI.createTableViewSection({
id: "__alloyId182"
});
__alloyId171.push($.__views.__alloyId182);
$.__views.__alloyId183 = Ti.UI.createTableViewRow(function() {
var o = {};
_.extend(o, {
height: 45
});
Alloy.isTablet && _.extend(o, {
height: 90
});
_.extend(o, {
touchEnabled: "false",
backgroundColor: "white",
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY,
id: "__alloyId183"
});
return o;
}());
$.__views.__alloyId182.add($.__views.__alloyId183);
$.__views.__alloyId184 = Ti.UI.createView({
left: "10",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId184"
});
$.__views.__alloyId183.add($.__views.__alloyId184);
$.__views.__alloyId185 = Ti.UI.createView({
layout: "vertical",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId185"
});
$.__views.__alloyId184.add($.__views.__alloyId185);
$.__views.__alloyId186 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 16,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 30,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
_.extend(o, {
text: "Block A",
id: "__alloyId186"
});
return o;
}());
$.__views.__alloyId185.add($.__views.__alloyId186);
$.__views.__alloyId187 = Ti.UI.createTableViewRow(function() {
var o = {};
_.extend(o, {
height: 45
});
Alloy.isTablet && _.extend(o, {
height: 90
});
_.extend(o, {
touchEnabled: "false",
backgroundColor: "white",
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY,
id: "__alloyId187"
});
return o;
}());
$.__views.__alloyId182.add($.__views.__alloyId187);
$.__views.__alloyId188 = Ti.UI.createView({
left: "10",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId188"
});
$.__views.__alloyId187.add($.__views.__alloyId188);
$.__views.__alloyId189 = Ti.UI.createView({
layout: "vertical",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId189"
});
$.__views.__alloyId188.add($.__views.__alloyId189);
$.__views.__alloyId190 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 16,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 30,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
_.extend(o, {
text: "Block B",
id: "__alloyId190"
});
return o;
}());
$.__views.__alloyId189.add($.__views.__alloyId190);
$.__views.__alloyId191 = Ti.UI.createTableViewRow(function() {
var o = {};
_.extend(o, {
height: 45
});
Alloy.isTablet && _.extend(o, {
height: 90
});
_.extend(o, {
touchEnabled: "false",
backgroundColor: "white",
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY,
id: "__alloyId191"
});
return o;
}());
$.__views.__alloyId182.add($.__views.__alloyId191);
$.__views.__alloyId192 = Ti.UI.createView({
left: "10",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId192"
});
$.__views.__alloyId191.add($.__views.__alloyId192);
$.__views.__alloyId193 = Ti.UI.createView({
layout: "vertical",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId193"
});
$.__views.__alloyId192.add($.__views.__alloyId193);
$.__views.__alloyId194 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 16,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 30,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
_.extend(o, {
text: "Block C",
id: "__alloyId194"
});
return o;
}());
$.__views.__alloyId193.add($.__views.__alloyId194);
$.__views.__alloyId195 = Ti.UI.createTableViewRow(function() {
var o = {};
_.extend(o, {
height: 45
});
Alloy.isTablet && _.extend(o, {
height: 90
});
_.extend(o, {
touchEnabled: "false",
backgroundColor: "white",
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY,
id: "__alloyId195"
});
return o;
}());
$.__views.__alloyId182.add($.__views.__alloyId195);
$.__views.__alloyId196 = Ti.UI.createView({
left: "10",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId196"
});
$.__views.__alloyId195.add($.__views.__alloyId196);
$.__views.__alloyId197 = Ti.UI.createView({
layout: "vertical",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId197"
});
$.__views.__alloyId196.add($.__views.__alloyId197);
$.__views.__alloyId198 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 16,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 30,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
_.extend(o, {
text: "Block D",
id: "__alloyId198"
});
return o;
}());
$.__views.__alloyId197.add($.__views.__alloyId198);
$.__views.__alloyId199 = Ti.UI.createTableViewRow(function() {
var o = {};
_.extend(o, {
height: 45
});
Alloy.isTablet && _.extend(o, {
height: 90
});
_.extend(o, {
touchEnabled: "false",
backgroundColor: "white",
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY,
id: "__alloyId199"
});
return o;
}());
$.__views.__alloyId182.add($.__views.__alloyId199);
$.__views.__alloyId200 = Ti.UI.createView({
left: "10",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId200"
});
$.__views.__alloyId199.add($.__views.__alloyId200);
$.__views.__alloyId201 = Ti.UI.createView({
layout: "vertical",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId201"
});
$.__views.__alloyId200.add($.__views.__alloyId201);
$.__views.__alloyId202 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 16,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 30,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
_.extend(o, {
text: "Block E",
id: "__alloyId202"
});
return o;
}());
$.__views.__alloyId201.add($.__views.__alloyId202);
$.__views.__alloyId203 = Ti.UI.createTableViewRow(function() {
var o = {};
_.extend(o, {
height: 45
});
Alloy.isTablet && _.extend(o, {
height: 90
});
_.extend(o, {
touchEnabled: "false",
backgroundColor: "white",
selectionStyle: Ti.UI.iPhone.TableViewCellSelectionStyle.GRAY,
id: "__alloyId203"
});
return o;
}());
$.__views.__alloyId182.add($.__views.__alloyId203);
$.__views.__alloyId204 = Ti.UI.createView({
left: "10",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId204"
});
$.__views.__alloyId203.add($.__views.__alloyId204);
$.__views.__alloyId205 = Ti.UI.createView({
layout: "vertical",
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
id: "__alloyId205"
});
$.__views.__alloyId204.add($.__views.__alloyId205);
$.__views.__alloyId206 = Ti.UI.createLabel(function() {
var o = {};
_.extend(o, {
left: 0,
font: {
fontSize: 16,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
Alloy.isTablet && _.extend(o, {
left: 0,
font: {
fontSize: 30,
fontFamily: "AvenirLTStd-Black"
},
color: "#222222"
});
_.extend(o, {
text: "Block F",
id: "__alloyId206"
});
return o;
}());
$.__views.__alloyId205.add($.__views.__alloyId206);
$.__views.tv = Ti.UI.createTableView(function() {
var o = {};
_.extend(o, {
height: 460
});
Alloy.isTablet && _.extend(o, {
height: 800,
width: 600
});
_.extend(o, {
data: __alloyId171,
id: "tv",
style: Ti.UI.iPhone.TableViewStyle.GROUPED,
backgroundColor: "transparent",
scrollable: "false"
});
return o;
}());
$.__views.scrollView.add($.__views.tv);
handleTableViewClick ? $.__views.tv.addEventListener("click", handleTableViewClick) : __defers["$.__views.tv!click!handleTableViewClick"] = true;
exports.destroy = function() {};
_.extend($, $.__views);
var settings = Alloy.Models.settings;
2 > settings.toJSON().question_set ? $.tv.data[0].rows[settings.toJSON().question_set].hasCheck = true : $.tv.data[1].rows[Number(settings.toJSON().question_set) - 2].hasCheck = true;
__defers["$.__views.settings_back_btn!click!closeModal"] && $.__views.settings_back_btn.on("click", closeModal);
__defers["$.__views.tv!click!handleTableViewClick"] && $.__views.tv.addEventListener("click", handleTableViewClick);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller; | ponnam/ESAT-131226 | Resources/alloy/controllers/set_select.js | JavaScript | apache-2.0 | 21,537 |
/*
* ! ${copyright}
*/
// Provides control sap.m.P13nSelectionItem.
sap.ui.define([
'jquery.sap.global', './library', 'sap/ui/core/Item'
], function(jQuery, library, Item) {
"use strict";
/**
* Constructor for a new P13nSelectionItem.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] initial settings for the new control
* @class Type for <code>selectionItems</code> aggregation in <code>P13nSelectionPanel</code> control.
* @extends sap.ui.core.Item
* @version ${version}
* @constructor
* @author SAP SE
* @private
* @since 1.46.0
* @alias sap.m.P13nSelectionItem
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var P13nSelectionItem = Item.extend("sap.m.P13nSelectionItem", /** @lends sap.m.P13nSelectionItem.prototype */
{
metadata: {
library: "sap.m",
properties: {
/**
* Defines the unique table column key.
*/
columnKey: {
type: "string",
defaultValue: undefined
},
/**
* Defines the index of a table column.
*/
index: {
type: "int",
defaultValue: -1
},
/**
* Defines whether the <code>P13nSelectionItem</code> is selected.
*/
selected: {
type: "boolean",
defaultValue: false
}
}
}
});
return P13nSelectionItem;
}, /* bExport= */true);
| olirogers/openui5 | src/sap.m/src/sap/m/P13nSelectionItem.js | JavaScript | apache-2.0 | 1,426 |
/********************************************************************************
* Ledger Node JS API
* (c) 2016-2017 Ledger
*
* 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.
********************************************************************************/
function runTest(comm, ledger, timeout) {
return comm.create_async(timeout, true).then(function (comm) {
var eth = new ledger.eth(comm);
return eth.signPersonalMessage_async("44'/60'/0'/0'/0", Buffer.from('test').toString('hex')).then(function (result) {
var v = result['v'] - 27;
v = v.toString(16);
if (v.length < 2) {
v = "0" + v;
}
console.log("Signature 0x" + result['r'] + result['s'] + v);
})
})
}
module.exports = runTest;
| shyft-network/ledger-node-js-api | test/testEth4.js | JavaScript | apache-2.0 | 1,310 |
var params = {
title: 'Hello Dynamic :-)',
resourcesPath: portal.url.createResourceUrl('')
};
var body = system.thymeleaf.render('view/page.html', params);
portal.response.contentType = 'text/html';
portal.response.body = body;
| RF0/wem-sample-package | modules/strongly.typed-1.0.0/page/page/get.js | JavaScript | apache-2.0 | 236 |
var yt = yt || {};
//加载图片
yt.loadImg = function ($imgs, time) {
var _time = 0;
time = time || 200;
$imgs.each(function () {
var $that = $(this);
if ($that.data('hasload')) {
return false;
}
setTimeout(function () {
$that.fadeOut(0);
$that.attr('src', $that.data('src'));
$that.attr('data-hasload', 'true');
$that.fadeIn(500);
}, _time);
_time += time;
});
};
//wap端环境
yt.isWap = function () {
var s = navigator.userAgent.toLowerCase();
var ipad = s.match(/ipad/i) == "ipad"
, iphone = s.match(/iphone os/i) == "iphone os"
, midp = s.match(/midp/i) == "midp"
, uc7 = s.match(/rv:1.2.3.4/i) == "rv:1.2.3.4"
, uc = s.match(/ucweb/i) == "ucweb"
, android = s.match(/android/i) == "android"
, ce = s.match(/windows ce/i) == "windows ce"
, wm = s.match(/windows mobile/i) == "windows mobile";
if (iphone || midp || uc7 || uc || android || ce || wm || ipad) { return true; }
return false;
};
//滑动绑定
yt.app = function () {
var $swiperContainer = $("#swiper-container1"),
$pages = $("#wrapper").children(),
$as = $("#nav li a"),
$lis = $("#nav li"),
$win =$(window),
slideCount = $pages.length,
nowIndex = 0,
acn = "animation",
mySwiper,
_zx = 1;
var params = {
selectorClassName: "swiper-container",
animationClassName: acn,
animationElm: $("." + acn)
};
var setCssText = function (prop, value) {
return prop + ': ' + value + '; ';
};
/*
* insertCss(rule)
* 向文档<head>底部插入css rule操作
* rule: 传入的css text
* */
var insertCss = function (rule) {
var head = document.head || document.getElementsByTagName('head')[0],
style;
if (!!head.getElementsByTagName('style').length) {
style = head.getElementsByTagName('style')[0];
if (style.styleSheet) {
style.styleSheet.cssText = rule;
} else {
style.innerHTML = '';
style.appendChild(document.createTextNode(rule));
}
} else {
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = rule;
} else {
style.appendChild(document.createTextNode(rule));
}
head.appendChild(style);
}
};
var setAnimationStyle=function() {
var cssText = '';
cssText += '.' + params.animationClassName + '{' +
setCssText('display', 'none') +
'}' +
'.touchstart .' + params.animationClassName + '{' +
setCssText('-webkit-animation-duration', '0 !important') +
setCssText('-webkit-animation-delay', '0 !important') +
setCssText('-webkit-animation-iteration-count', '1 !important') +
'}';
var index = mySwiper.activeIndex,
_index = index + 1,
$ans = $pages.eq(index).find('.' + params.animationClassName);
$ans.each(function () {
var obj = $(this);
_className = obj.attr('data-item'),
_animation = obj.attr('data-animation'),
_duration = ((obj.attr('data-duration') / 1000) || 1) + 's',
_timing = obj.attr('data-timing-function') || 'ease',
_delay = ((obj.attr('data-delay') || 0) / 1000) + 's',
_count = obj.attr('data-iteration-count') || 1;
var _t = '.' + params.selectorClassName +
' .page-' + _index +
' .' + _className;
cssText += _t + '{' +
setCssText('display', 'block !important') +
setCssText('-webkit-animation-name', _animation) +
setCssText('-webkit-animation-duration', _duration) +
setCssText('-webkit-animation-timing-function', _timing) +
setCssText('-webkit-animation-delay', _delay) +
setCssText('-webkit-animation-fill-mode', 'both') +
setCssText('-webkit-animation-iteration-count', _count) +
'}';
});
return cssText;
};
//设置动画
var setAms = function () {
insertCss(setAnimationStyle());
};
//设置布局
var setLayout = function () {
var $wrapers = $("#swiper-container1 .wraper"),
$wraper1 = $("#wraper1"),
isWap=yt.isWap(),
w = 720,
h = 1135;
var sl = function () {
var _w = $wraper1.width(),
h = $win.height(),
_h = isWap && _w<h?$win.height():_w * 1135 / 720;
$wrapers.height(_h);
if($win.height()<300){
$(".cn-slidetips").hide();
}else{
$(".cn-slidetips").show();
}
};
sl();
$win.resize(sl);
};
//滑动绑定函数
var onSlideChangeTime = 0;
var onSlideChange = function () {
if (onSlideChangeTime>1) {
return;
}
var index = mySwiper.activeIndex;
if (nowIndex == index && mySwiper.touches['abs'] < 50) {
return;
}
onSlideChangeTime = 20;
setAms();
nowIndex = index || 0;
//history.pushState(null, null, "index.html?p=" + (nowIndex + 1));
//执行动画
var timer=setInterval(function () {
onSlideChangeTime -= 1;
if (onSlideChangeTime == 0) {
clearInterval(timer);
}
},1);
};
//触摸结束绑定
var onTouchEnd = function () {
/* var index = mySwiper.index;
if (nowIndex == slideCount-1 && +mySwiper.touches['diff'] <-50) {
return mySwiper.swipeTo(0);
}*/
};
//滑动结束绑定
var onSlideChangeEnd = function () {
//console.log(mySwiper.activeIndex)
onSlideChange();
if(mySwiper.activeIndex == 2){
setTimeout(function(){
mySwiper.swipeTo(3);
},2500)
}
};
//绑定滑动主函数
var bindSwiper = function () {
mySwiper = $swiperContainer.swiper({
onTouchEnd: onTouchEnd,
onSlideChangeEnd: onSlideChangeEnd,
moveStartThreshold:10000
//mousewheelControl:true,
//mode: 'vertical'
});
};
//滚到下一个屏
var bindNext = function () {
$(".next").on("click", function () {
mySwiper.activeIndex = mySwiper.activeIndex || 0;
var index = mySwiper.activeIndex == slideCount - 1 ? 0 : (mySwiper.activeIndex||0) + 1;
mySwiper.swipeTo(index);
});
};
var btn1 = $('#btn1').jRange({
from: 0,
to: 100,
step: 1,
scale: [0,25,50,75,100],
format: '%s',
width: "100%"
});
var btn2 = $('#btn2').jRange({
from: 0,
to: 100,
step: 1,
scale: [0,25,50,75,100],
format: '%s',
width: "100%"
});
var btn3 = $('#btn3').jRange({
from: 0,
to: 100,
step: 1,
scale: [0,25,50,75,100],
format: '%s',
width: "100%"
});
var btn4 = $('#btn4').jRange({
from: 0,
to: 100,
step: 1,
scale: [0,25,50,75,100],
format: '%s',
width: "100%"
});
var btn5 = $('#btn5').jRange({
from: 0,
to: 100,
step: 1,
scale: [0,25,50,75,100],
format: '%s',
width: "100%"
});
var btn6 = $('#btn6').jRange({
from: 0,
to: 100,
step: 1,
scale: [0,25,50,75,100],
format: '%s',
width: "100%"
});
//抽选人物
var setPerson = function () {
var i = (Math.random()*7).toFixed(0);
var span = $("#p3 .cy span");
switch(i){
case "1":$("#p4 .rw").hide().eq(0).show();
$("#p5 .rw").hide().eq(0).show();
span.eq(0).html(1);
span.eq(1).html(9);
span.eq(2).html(9);
span.eq(3).html(2);
break;
case "2":$("#p4 .rw").hide().eq(1).show();
$("#p5 .rw").hide().eq(1).show();
span.eq(0).html(2);
span.eq(1).html(0);
span.eq(2).html(0);
span.eq(3).html(3);
break;
case "3":$("#p4 .rw").hide().eq(2).show();
$("#p5 .rw").hide().eq(2).show();
$("#p5 .rw").hide().eq(1).show();
span.eq(0).html(1);
span.eq(1).html(9);
span.eq(2).html(8);
span.eq(3).html(6);
break;
case "4":$("#p4 .rw").hide().eq(3).show();
$("#p5 .rw").hide().eq(3).show();
$("#p5 .rw").hide().eq(1).show();
span.eq(0).html(1);
span.eq(1).html(9);
span.eq(2).html(8);
span.eq(3).html(6);
break;
case "5":$("#p4 .rw").hide().eq(4).show();
$("#p5 .rw").hide().eq(4).show();
$("#p5 .rw").hide().eq(1).show();
span.eq(0).html(1);
span.eq(1).html(9);
span.eq(2).html(9);
span.eq(3).html(5);
break;
default:$("#p4 .rw").hide().eq(5).show();
$("#p5 .rw").hide().eq(5).show();
$("#p5 .rw").hide().eq(1).show();
span.eq(0).html(1);
span.eq(1).html(9);
span.eq(2).html(9);
span.eq(3).html(6);
break;
}
}
//更换造型
var setZX = function () {
//console.log(_zx%6)
$("#p4").removeClass("style"+(_zx%6)).addClass("style"+(_zx+1)%6);
$("#p5").removeClass("style"+(_zx%6)).addClass("style"+(_zx+1)%6);
_zx++;
}
//初始化
bindSwiper();
bindNext();
setLayout();
setAms();
setPerson();
setZX();
//mySwiper.swipeTo(0);
$("#in .am3 .high").click(function(){
if($(this).next().html()>25){
console.log("跳转页面");
}
});
$("#in .am4 .high").click(function(){
if($(this).next().html()<25){
console.log("分享提示");
$("#shareTips").fadeIn();
}
});
$("#p1 .high").click(function(){
//console.log($(this).next().html())
if($(this).next().html()<20){
console.log("翻页 goto2")
mySwiper.swipeTo(1);
}
});
$("#p4 .high").click(function(){
//console.log($(this).next().html())
if($(this).next().html()<20){
console.log("翻页 goto5")
mySwiper.swipeTo(4);
}
});
$("#p5 .am3 .high").click(function(){
//console.log($(this).next().html())
if($(this).next().html()>80){
console.log("重置");
location.reload(false);
/*_zx = 1;
setPerson();
setZX();
$(".whiteBg").empty();
$(".btnBox input").val(0)
mySwiper.swipeTo(2);*/
}
});
$("#p5 .am4 .high").click(function(){
//console.log($(this).next().html())
if($(this).next().html()<25){
console.log("分享提示");
$("#shareTips").fadeIn();
}
});
$("#shareTips").click(function(){
$("#shareTips").fadeOut();
});
$("#p2 .am1").click(function(){
mySwiper.swipeTo(2);
});
$(".upload").click(function(){
$("#file").click();
});
$("#file").on("change", function(){
// Get a reference to the fileList
var files = !!this.files ? this.files : [];
// If no files were selected, or no FileReader support, return
if (!files.length || !window.FileReader) return;
// Only proceed if the selected file is an image
if (/^image/.test( files[0].type)){
// Create a new instance of the FileReader
var reader = new FileReader();
// Read the local file as a DataURL
reader.readAsDataURL(files[0]);
// When loaded, set image data as background of div
reader.onloadend = function(){
console.log(this.result)
$(".whiteBg").empty().append("<img src='"+this.result+"'>");
}
}else{
alert("请上传图片");
}
});
if(window.DeviceMotionEvent) {
var speed = 10;
var x = y = z = lastX = lastY = lastZ = 0;
window.addEventListener('devicemotion', function(){
var acceleration =event.accelerationIncludingGravity;
x = acceleration.x;
y = acceleration.y;
if((Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed)) {
setZX();
/*if(shake){
shake = false;
}
if (navigator.vibrate) {
navigator.vibrate(1000);
} else if (navigator.webkitVibrate) {
navigator.webkitVibrate(1000);
}*/
}
lastX = x;
lastY = y;
}, false);
}else{
//不支持摇一摇
alert("您的手机暂不支持摇一摇!");
}
//测试用
$("#p4 .am1").click(function(){
setZX();
});
};
//初始化
yt.init = function () {
window.onload = function () {
$("#loading").hide();
setTimeout(yt.app);
};
};
yt.init();
| linmingling/demo | zt/sgj/js/my.js | JavaScript | apache-2.0 | 14,161 |
/*
* Twitter Search Plugin jquery.retina.js
* https://github.com/tylercraft/jQuery-Retina
*
* Copyright (c) 2012 tylercraft.com
* Author: Tyler Craft
* Dual licensed under the MIT and GPL licenses.
* https://github.com/tylercraft/jQuery-Retina
*
*/
(function( $ ) {
$.fn.retina = function( options ) {
var settings = {
// Check for data-retina attribute. If exists, swap out image
dataRetina: true,
// Suffix to append to image file name
suffix: "",
// Check if image exists before swapping out
checkIfImageExists: false,
// Callback function if custom logic needs to be
// applied to image file name
customFileNameCallback: "",
// override window.devicePixelRatio
overridePixelRation: false
};
if(options){
jQuery.extend(settings,options);
}
var retinaEnabled = false;
// If retina enabled only
if(settings.overridePixelRation || window.devicePixelRatio >= 1.2) {
retinaEnabled = true;
}
// Begin to iterate over the jQuery collection that the method was called on
return this.each(function () {
// Cache `this`
var $this = $(this);
$this.addClass('retina-off');
if(!retinaEnabled){
return false;
}
var newImageSrc = '';
// Get data-retina attribute
if(settings.dataRetina && $this.attr('data-retina')){
newImageSrc = $this.attr('data-retina');
}
if(settings.suffix){
// If there is a data-retina attribute, suffix that
// Otherwise, suffix the primary image
if(!newImageSrc){
newImageSrc = $this.attr('src');
}
}
if(settings.suffix){
// Get filename sans extension
var baseFileName = newImageSrc.replace(/.[^.]+$/,'');
var baseFileExtension = newImageSrc.replace(/^.*\./,'');
newImageSrc = baseFileName + settings.suffix + '.' + baseFileExtension;
}
if(settings.customFileNameCallback){
newImageSrc = settings.customFileNameCallback($this);
}
if(settings.checkIfImageExists && newImageSrc){
$.ajax({url: newImageSrc, type: "HEAD", success: function() {
$this.attr('src',newImageSrc);
$this.removeClass('retina-off');
$this.addClass('retina-on');
}});
}else if(newImageSrc){
$this.attr('src',newImageSrc);
$this.removeClass('retina-off');
$this.addClass('retina-on');
}
});
};
}(jQuery)); | ygrinev/ygrinev | Study/ASP.NET/jQuery/HTML5 & jQuery Examples/assets/js/jquery.retina.js | JavaScript | apache-2.0 | 2,765 |
var structofp13__meter__band__dscp__remark =
[
[ "burst_size", "structofp13__meter__band__dscp__remark.html#a65ae2e874c730303bbc5d780640f7fc9", null ],
[ "len", "structofp13__meter__band__dscp__remark.html#ad56aaad8bcc7a48f6f2328ff81b0d67f", null ],
[ "pad", "structofp13__meter__band__dscp__remark.html#a5e621372646568aa14544869bbbdcf46", null ],
[ "prec_level", "structofp13__meter__band__dscp__remark.html#a753ecc92ac6a4685c02baa954acee8aa", null ],
[ "rate", "structofp13__meter__band__dscp__remark.html#a1087876e1f2f5eacbb785424dad28347", null ],
[ "type", "structofp13__meter__band__dscp__remark.html#a6837249197a1667e26a848d4870ebaff", null ]
]; | vladn-ma/vladn-ovs-doc | doxygen/ovs_all/html/structofp13__meter__band__dscp__remark.js | JavaScript | apache-2.0 | 676 |
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import { visitDashboard } from '@web-stories-wp/e2e-test-utils';
describe('Admin Menu', () => {
// eslint-disable-next-line jest/no-disabled-tests -- broken by https://github.com/googleforcreators/web-stories-wp/pull/7213, needs updating.
it.skip('should sync the WP nav with the dashboard nav', async () => {
await visitDashboard();
// Initial visit to `/` makes `Dashboard` link current in WP
await page.hover('#menu-posts-web-story');
await expect(page.$('#menu-posts-web-story .current a')).resolves.toMatch(
'Dashboard'
);
await page.hover('[aria-label="Main dashboard navigation"]');
// Navigating through the application to a new page syncs the WP current page in Nav
await page.waitForTimeout(100);
await Promise.all([
page.waitForNavigation(),
expect(page).toClick('[aria-label="Main dashboard navigation"] a', {
text: 'Explore Templates',
}),
]);
await page.waitForTimeout(100);
await page.hover('#menu-posts-web-story');
await expect(page.$('#menu-posts-web-story .current a')).resolves.toMatch(
'Explore Templates'
);
await page.hover('[aria-label="Main dashboard navigation"]');
// Navigating through WP to a new page syncs the WP current page in Nav
await page.hover('#menu-posts-web-story');
await page.waitForTimeout(100);
await Promise.all([
page.waitForNavigation(),
expect(page).toClick('#menu-posts-web-story a', {
text: 'Settings',
}),
]);
await page.waitForTimeout(100);
await expect(page.$('#menu-posts-web-story .current a')).resolves.toMatch(
'Settings'
);
// await page.hover('[aria-label="Main dashboard navigation"]');
// Navigating through application back to My Story from another route
await page.waitForTimeout(100);
await Promise.all([
page.waitForNavigation(),
expect(page).toClick('[aria-label="Main dashboard navigation"] a', {
text: 'Dashboard',
}),
]);
await page.waitForTimeout(100);
await page.hover('#menu-posts-web-story');
await expect(page.$('#menu-posts-web-story .current a')).resolves.toMatch(
'Dashboard'
);
});
});
| GoogleForCreators/web-stories-wp | packages/e2e-tests/src/specs/dashboard/adminMenu.js | JavaScript | apache-2.0 | 2,834 |
/* eslint camelcase: "off" */
/* eslint angular/angularelement: "off" */
(function() {
'use strict';
angular.module('app.services')
.factory('DialogFieldRefresh', ['lodash', 'CollectionsApi', 'EventNotifications', DialogFieldRefreshFactory]);
/** @ngInject */
function DialogFieldRefreshFactory(lodash, CollectionsApi, EventNotifications) {
var service = {
listenForAutoRefreshMessages: listenForAutoRefreshMessages,
refreshSingleDialogField: refreshSingleDialogField,
setupDialogData: setupDialogData,
triggerAutoRefresh: triggerAutoRefresh,
};
return service;
function listenForAutoRefreshMessages(allDialogFields, autoRefreshableDialogFields, url, resourceId) {
var listenerFunction = function(event) {
var dialogFieldsToRefresh = autoRefreshableDialogFields.filter(function(fieldName) {
if (event.originalEvent.data.fieldName !== fieldName) {
return fieldName;
}
});
allDialogFields.forEach(function(dialogField) {
if (lodash.includes(dialogFieldsToRefresh, dialogField.name)) {
dialogField.beingRefreshed = true;
}
});
if (dialogFieldsToRefresh !== []) {
refreshMultipleDialogFields(allDialogFields, dialogFieldsToRefresh, url, resourceId);
}
};
$(window).off('message'); // Unbind all previous message listeners
$(window).on('message', listenerFunction);
}
function refreshSingleDialogField(allDialogFields, dialogField, url, resourceId) {
function refreshSuccess(result) {
var resultObj = result.result[dialogField.name];
updateAttributesForDialogField(dialogField, resultObj);
triggerAutoRefresh(dialogField);
}
function refreshFailure(result) {
EventNotifications.error('There was an error refreshing this dialog: ' + result);
}
dialogField.beingRefreshed = true;
fetchDialogFieldInfo(allDialogFields, [dialogField.name], url, resourceId, refreshSuccess, refreshFailure);
}
function selectDefaultValue(dialogField, newDialogField) {
if (angular.isObject(newDialogField.values)) {
dialogField.values = newDialogField.values;
if (angular.isDefined(newDialogField.default_value) && newDialogField.default_value !== null) {
dialogField.default_value = newDialogField.default_value;
} else {
dialogField.default_value = newDialogField.values[0][0];
}
} else {
if (dialogField.type === 'DialogFieldDateControl' || dialogField.type === 'DialogFieldDateTimeControl') {
dialogField.default_value = new Date(newDialogField.values);
} else {
if (angular.isUndefined(newDialogField.default_value) || newDialogField.default_value === null
|| newDialogField.default_value === '') {
dialogField.default_value = newDialogField.values;
}
}
}
}
function setupDialogData(dialogs, allDialogFields, autoRefreshableDialogFields) {
angular.forEach(dialogs, function(dialog) {
angular.forEach(dialog.dialog_tabs, function(dialogTab) {
angular.forEach(dialogTab.dialog_groups, function(dialogGroup) {
angular.forEach(dialogGroup.dialog_fields, function(dialogField) {
allDialogFields.push(dialogField);
selectDefaultValue(dialogField, dialogField);
dialogField.triggerAutoRefresh = function() {
triggerAutoRefresh(dialogField);
};
if (dialogField.auto_refresh === true) {
autoRefreshableDialogFields.push(dialogField.name);
}
});
});
});
});
}
function triggerAutoRefresh(dialogField) {
if (dialogField.trigger_auto_refresh === true) {
parent.postMessage({fieldName: dialogField.name}, '*');
}
}
// Private
function refreshMultipleDialogFields(allDialogFields, fieldNamesToRefresh, url, resourceId) {
function refreshSuccess(result) {
angular.forEach(allDialogFields, function(dialogField) {
if (fieldNamesToRefresh.indexOf(dialogField.name) > -1) {
var resultObj = result.result[dialogField.name];
updateAttributesForDialogField(dialogField, resultObj);
}
});
}
function refreshFailure(result) {
EventNotifications.error('There was an error automatically refreshing dialogs' + result);
}
fetchDialogFieldInfo(allDialogFields, fieldNamesToRefresh, url, resourceId, refreshSuccess, refreshFailure);
}
function updateAttributesForDialogField(dialogField, newDialogField) {
copyDynamicAttributes(dialogField, newDialogField);
selectDefaultValue(dialogField, newDialogField);
dialogField.beingRefreshed = false;
function copyDynamicAttributes(currentDialogField, newDialogField) {
currentDialogField.data_type = newDialogField.data_type;
currentDialogField.options = newDialogField.options;
currentDialogField.read_only = newDialogField.read_only;
currentDialogField.required = newDialogField.required;
}
}
function fetchDialogFieldInfo(allDialogFields, dialogFieldsToFetch, url, resourceId, successCallback, failureCallback) {
CollectionsApi.post(
url,
resourceId,
{},
angular.toJson({
action: 'refresh_dialog_fields',
resource: {
dialog_fields: dialogFieldInfoToSend(allDialogFields),
fields: dialogFieldsToFetch,
},
})
).then(successCallback, failureCallback);
}
function dialogFieldInfoToSend(allDialogFields) {
var fieldValues = {};
angular.forEach(allDialogFields, function(dialogField) {
fieldValues[dialogField.name] = dialogField.default_value;
});
return fieldValues;
}
}
})();
| dtaylor113/manageiq-ui-self_service | client/app/services/dialog-field-refresh.service.js | JavaScript | apache-2.0 | 5,991 |
var dir_449a8fc0a8176498514757a163fc6e60 =
[
[ "SensorBarControl.g.cs", "_a_r_m_2_debug_2_controls_2_sensor_bar_2_sensor_bar_control_8g_8cs.html", [
[ "SensorBarControl", "class_x_labs_1_1_forms_1_1_controls_1_1_sensor_bar_control.html", "class_x_labs_1_1_forms_1_1_controls_1_1_sensor_bar_control" ]
] ],
[ "SensorBarControl.g.i.cs", "_a_r_m_2_debug_2_controls_2_sensor_bar_2_sensor_bar_control_8g_8i_8cs.html", [
[ "SensorBarControl", "class_x_labs_1_1_forms_1_1_controls_1_1_sensor_bar_control.html", "class_x_labs_1_1_forms_1_1_controls_1_1_sensor_bar_control" ]
] ]
]; | XLabs/xlabs.github.io | html/dir_449a8fc0a8176498514757a163fc6e60.js | JavaScript | apache-2.0 | 601 |
/*
Copyright (c) 2004-2009, 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.gfx.path"]){
dojo._hasResource["dojox.gfx.path"]=true;
dojo.provide("dojox.gfx.path");
dojo.require("dojox.gfx.shape");
dojo.declare("dojox.gfx.path.Path",dojox.gfx.Shape,{constructor:function(_1){
this.shape=dojo.clone(dojox.gfx.defaultPath);
this.segments=[];
this.absolute=true;
this.last={};
this.rawNode=_1;
},setAbsoluteMode:function(_2){
this.absolute=typeof _2=="string"?(_2=="absolute"):_2;
return this;
},getAbsoluteMode:function(){
return this.absolute;
},getBoundingBox:function(){
return (this.bbox&&("l" in this.bbox))?{x:this.bbox.l,y:this.bbox.t,width:this.bbox.r-this.bbox.l,height:this.bbox.b-this.bbox.t}:null;
},getLastPosition:function(){
return "x" in this.last?this.last:null;
},_updateBBox:function(x,y){
if(this.bbox&&("l" in this.bbox)){
if(this.bbox.l>x){
this.bbox.l=x;
}
if(this.bbox.r<x){
this.bbox.r=x;
}
if(this.bbox.t>y){
this.bbox.t=y;
}
if(this.bbox.b<y){
this.bbox.b=y;
}
}else{
this.bbox={l:x,b:y,r:x,t:y};
}
},_updateWithSegment:function(_5){
var n=_5.args,l=n.length;
switch(_5.action){
case "M":
case "L":
case "C":
case "S":
case "Q":
case "T":
for(var i=0;i<l;i+=2){
this._updateBBox(n[i],n[i+1]);
}
this.last.x=n[l-2];
this.last.y=n[l-1];
this.absolute=true;
break;
case "H":
for(var i=0;i<l;++i){
this._updateBBox(n[i],this.last.y);
}
this.last.x=n[l-1];
this.absolute=true;
break;
case "V":
for(var i=0;i<l;++i){
this._updateBBox(this.last.x,n[i]);
}
this.last.y=n[l-1];
this.absolute=true;
break;
case "m":
var _9=0;
if(!("x" in this.last)){
this._updateBBox(this.last.x=n[0],this.last.y=n[1]);
_9=2;
}
for(var i=_9;i<l;i+=2){
this._updateBBox(this.last.x+=n[i],this.last.y+=n[i+1]);
}
this.absolute=false;
break;
case "l":
case "t":
for(var i=0;i<l;i+=2){
this._updateBBox(this.last.x+=n[i],this.last.y+=n[i+1]);
}
this.absolute=false;
break;
case "h":
for(var i=0;i<l;++i){
this._updateBBox(this.last.x+=n[i],this.last.y);
}
this.absolute=false;
break;
case "v":
for(var i=0;i<l;++i){
this._updateBBox(this.last.x,this.last.y+=n[i]);
}
this.absolute=false;
break;
case "c":
for(var i=0;i<l;i+=6){
this._updateBBox(this.last.x+n[i],this.last.y+n[i+1]);
this._updateBBox(this.last.x+n[i+2],this.last.y+n[i+3]);
this._updateBBox(this.last.x+=n[i+4],this.last.y+=n[i+5]);
}
this.absolute=false;
break;
case "s":
case "q":
for(var i=0;i<l;i+=4){
this._updateBBox(this.last.x+n[i],this.last.y+n[i+1]);
this._updateBBox(this.last.x+=n[i+2],this.last.y+=n[i+3]);
}
this.absolute=false;
break;
case "A":
for(var i=0;i<l;i+=7){
this._updateBBox(n[i+5],n[i+6]);
}
this.last.x=n[l-2];
this.last.y=n[l-1];
this.absolute=true;
break;
case "a":
for(var i=0;i<l;i+=7){
this._updateBBox(this.last.x+=n[i+5],this.last.y+=n[i+6]);
}
this.absolute=false;
break;
}
var _a=[_5.action];
for(var i=0;i<l;++i){
_a.push(dojox.gfx.formatNumber(n[i],true));
}
if(typeof this.shape.path=="string"){
this.shape.path+=_a.join("");
}else{
Array.prototype.push.apply(this.shape.path,_a);
}
},_validSegments:{m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7,z:0},_pushSegment:function(_b,_c){
var _d=this._validSegments[_b.toLowerCase()];
if(typeof _d=="number"){
if(_d){
if(_c.length>=_d){
var _e={action:_b,args:_c.slice(0,_c.length-_c.length%_d)};
this.segments.push(_e);
this._updateWithSegment(_e);
}
}else{
var _e={action:_b,args:[]};
this.segments.push(_e);
this._updateWithSegment(_e);
}
}
},_collectArgs:function(_f,_10){
for(var i=0;i<_10.length;++i){
var t=_10[i];
if(typeof t=="boolean"){
_f.push(t?1:0);
}else{
if(typeof t=="number"){
_f.push(t);
}else{
if(t instanceof Array){
this._collectArgs(_f,t);
}else{
if("x" in t&&"y" in t){
_f.push(t.x,t.y);
}
}
}
}
}
},moveTo:function(){
var _13=[];
this._collectArgs(_13,arguments);
this._pushSegment(this.absolute?"M":"m",_13);
return this;
},lineTo:function(){
var _14=[];
this._collectArgs(_14,arguments);
this._pushSegment(this.absolute?"L":"l",_14);
return this;
},hLineTo:function(){
var _15=[];
this._collectArgs(_15,arguments);
this._pushSegment(this.absolute?"H":"h",_15);
return this;
},vLineTo:function(){
var _16=[];
this._collectArgs(_16,arguments);
this._pushSegment(this.absolute?"V":"v",_16);
return this;
},curveTo:function(){
var _17=[];
this._collectArgs(_17,arguments);
this._pushSegment(this.absolute?"C":"c",_17);
return this;
},smoothCurveTo:function(){
var _18=[];
this._collectArgs(_18,arguments);
this._pushSegment(this.absolute?"S":"s",_18);
return this;
},qCurveTo:function(){
var _19=[];
this._collectArgs(_19,arguments);
this._pushSegment(this.absolute?"Q":"q",_19);
return this;
},qSmoothCurveTo:function(){
var _1a=[];
this._collectArgs(_1a,arguments);
this._pushSegment(this.absolute?"T":"t",_1a);
return this;
},arcTo:function(){
var _1b=[];
this._collectArgs(_1b,arguments);
this._pushSegment(this.absolute?"A":"a",_1b);
return this;
},closePath:function(){
this._pushSegment("Z",[]);
return this;
},_setPath:function(_1c){
var p=dojo.isArray(_1c)?_1c:_1c.match(dojox.gfx.pathSvgRegExp);
this.segments=[];
this.absolute=true;
this.bbox={};
this.last={};
if(!p){
return;
}
var _1e="",_1f=[],l=p.length;
for(var i=0;i<l;++i){
var t=p[i],x=parseFloat(t);
if(isNaN(x)){
if(_1e){
this._pushSegment(_1e,_1f);
}
_1f=[];
_1e=t;
}else{
_1f.push(x);
}
}
this._pushSegment(_1e,_1f);
},setShape:function(_24){
dojox.gfx.Shape.prototype.setShape.call(this,typeof _24=="string"?{path:_24}:_24);
var _25=this.shape.path;
this.shape.path=[];
this._setPath(_25);
this.shape.path=this.shape.path.join("");
return this;
},_2PI:Math.PI*2});
dojo.declare("dojox.gfx.path.TextPath",dojox.gfx.path.Path,{constructor:function(_26){
if(!("text" in this)){
this.text=dojo.clone(dojox.gfx.defaultTextPath);
}
if(!("fontStyle" in this)){
this.fontStyle=dojo.clone(dojox.gfx.defaultFont);
}
},getText:function(){
return this.text;
},setText:function(_27){
this.text=dojox.gfx.makeParameters(this.text,typeof _27=="string"?{text:_27}:_27);
this._setText();
return this;
},getFont:function(){
return this.fontStyle;
},setFont:function(_28){
this.fontStyle=typeof _28=="string"?dojox.gfx.splitFontString(_28):dojox.gfx.makeParameters(dojox.gfx.defaultFont,_28);
this._setFont();
return this;
}});
}
| everttigchelaar/camel-svn | components/camel-web/src/main/webapp/js/dojox/gfx/path.js | JavaScript | apache-2.0 | 6,565 |
/**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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';
// MODULES //
var bench = require( '@stdlib/bench' );
var pow = require( '@stdlib/math/base/special/pow' );
var isArray = require( '@stdlib/assert/is-array' );
var filled = require( '@stdlib/array/base/filled' );
var abs = require( '@stdlib/math/base/special/abs' );
var pkg = require( './../package.json' ).name;
var map = require( './../lib' );
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x = filled( -3.0, len );
return benchmark;
/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var out;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
out = map( x, abs );
if ( out.length !== len ) {
b.fail( 'unexpected length' );
}
}
b.toc();
if ( !isArray( out ) ) {
b.fail( 'should return an array' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::array:len='+len, f );
}
}
main();
| stdlib-js/stdlib | lib/node_modules/@stdlib/utils/map/benchmark/benchmark.array.js | JavaScript | apache-2.0 | 1,951 |
/**
* @copyright Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
*/
/*jshint jquery:true*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
define([
"jquery",
"mage/validation",
"mage/translate"
], factory);
} else {
factory(jQuery);
}
}(function ($) {
"use strict";
/**
* Validation rule for grouped product, with multiple qty fields,
* only one qty needs to have a positive integer
*/
$.validator.addMethod(
"validate-grouped-qty",
function(value, element, params) {
var result = false;
var total = 0;
$(params).find('input[data-validate*="validate-grouped-qty"]').each(function(i, e) {
var val = $(e).val();
if (val && val.length > 0) {
result = true;
var valInt = parseInt(val, 10) || 0;
if (valInt >= 0) {
total += valInt;
} else {
result = false;
return result;
}
}
});
return result && total > 0;
},
'Please specify the quantity of product(s).'
);
$.validator.addMethod(
"validate-one-checkbox-required-by-name",
function(value, element, params) {
var checkedCount = 0;
if (element.type === 'checkbox') {
$('[name="' + element.name + '"]').each(function() {
if ($(this).is(':checked')) {
checkedCount += 1;
return false;
}
});
}
var container = '#' + params;
if (checkedCount > 0) {
$(container).removeClass('validation-failed');
$(container).addClass('validation-passed');
return true;
} else {
$(container).addClass('validation-failed');
$(container).removeClass('validation-passed');
return false;
}
},
'Please select one of the options.'
);
$.validator.addMethod(
"validate-date-between",
function(value, element, params) {
var minDate = new Date(params[0]),
maxDate = new Date(params[1]),
inputDate = new Date(element.value);
minDate.setHours(0);
maxDate.setHours(0);
if (inputDate >= minDate && inputDate <= maxDate) {
return true;
}
this.dateBetweenErrorMessage = $.mage.__('Please enter a date between %min and %max.').replace('%min', minDate).replace('%max', maxDate);
return false;
},
function(){
return this.dateBetweenErrorMessage;
}
);
}));
| webadvancedservicescom/magento | lib/web/mage/validation/validation.js | JavaScript | apache-2.0 | 2,961 |
/*
Copyright (c) 2004-2006, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/community/licensing.shtml
*/
dojo.provide("dojo.validate.common");
dojo.require("dojo.regexp");
dojo.validate.isText = function(/*String*/value, /*Object?*/flags){
// summary:
// Checks if a string has non whitespace characters.
// Parameters allow you to constrain the length.
//
// value: A string
// flags: {length: Number, minlength: Number, maxlength: Number}
// flags.length If set, checks if there are exactly flags.length number of characters.
// flags.minlength If set, checks if there are at least flags.minlength number of characters.
// flags.maxlength If set, checks if there are at most flags.maxlength number of characters.
flags = (typeof flags == "object") ? flags : {};
// test for text
if(/^\s*$/.test(value)){ return false; } // Boolean
// length tests
if(typeof flags.length == "number" && flags.length != value.length){ return false; } // Boolean
if(typeof flags.minlength == "number" && flags.minlength > value.length){ return false; } // Boolean
if(typeof flags.maxlength == "number" && flags.maxlength < value.length){ return false; } // Boolean
return true; // Boolean
}
dojo.validate.isInteger = function(/*String*/value, /*Object?*/flags){
// summary:
// Validates whether a string is in an integer format
//
// value A string
// flags {signed: Boolean|[true,false], separator: String}
// flags.signed The leading plus-or-minus sign. Can be true, false, or [true, false].
// Default is [true, false], (i.e. sign is optional).
// flags.separator The character used as the thousands separator. Default is no separator.
// For more than one symbol use an array, e.g. [",", ""], makes ',' optional.
var re = new RegExp("^" + dojo.regexp.integer(flags) + "$");
return re.test(value); // Boolean
}
dojo.validate.isRealNumber = function(/*String*/value, /*Object?*/flags){
// summary:
// Validates whether a string is a real valued number.
// Format is the usual exponential notation.
//
// value: A string
// flags: {places: Number, decimal: String, exponent: Boolean|[true,false], eSigned: Boolean|[true,false], ...}
// flags.places The integer number of decimal places.
// If not given, the decimal part is optional and the number of places is unlimited.
// flags.decimal The character used for the decimal point. Default is ".".
// flags.exponent Express in exponential notation. Can be true, false, or [true, false].
// Default is [true, false], (i.e. the exponential part is optional).
// flags.eSigned The leading plus-or-minus sign on the exponent. Can be true, false,
// or [true, false]. Default is [true, false], (i.e. sign is optional).
// flags in regexp.integer can be applied.
var re = new RegExp("^" + dojo.regexp.realNumber(flags) + "$");
return re.test(value); // Boolean
}
dojo.validate.isCurrency = function(/*String*/value, /*Object?*/flags){
// summary:
// Validates whether a string denotes a monetary value.
// value: A string
// flags: {signed:Boolean|[true,false], symbol:String, placement:String, separator:String,
// fractional:Boolean|[true,false], decimal:String}
// flags.signed The leading plus-or-minus sign. Can be true, false, or [true, false].
// Default is [true, false], (i.e. sign is optional).
// flags.symbol A currency symbol such as Yen "�", Pound "�", or the Euro sign "�".
// Default is "$". For more than one symbol use an array, e.g. ["$", ""], makes $ optional.
// flags.placement The symbol can come "before" the number or "after". Default is "before".
// flags.separator The character used as the thousands separator. The default is ",".
// flags.fractional The appropriate number of decimal places for fractional currency (e.g. cents)
// Can be true, false, or [true, false]. Default is [true, false], (i.e. cents are optional).
// flags.decimal The character used for the decimal point. Default is ".".
var re = new RegExp("^" + dojo.regexp.currency(flags) + "$");
return re.test(value); // Boolean
}
dojo.validate.isInRange = function(/*String*/value, /*Object?*/flags){
//summary:
// Validates whether a string denoting an integer,
// real number, or monetary value is between a max and min.
//
// value: A string
// flags: {max:Number, min:Number, decimal:String}
// flags.max A number, which the value must be less than or equal to for the validation to be true.
// flags.min A number, which the value must be greater than or equal to for the validation to be true.
// flags.decimal The character used for the decimal point. Default is ".".
//stripping the seperator allows NaN to perform as expected, if no separator, we assume ','
//once i18n support is ready for this, instead of assuming, we default to i18n's recommended value
value = value.replace((dojo.lang.has(flags,'separator'))?flags.separator:',','');
if(isNaN(value)){
return false; // Boolean
}
// assign default values to missing paramters
flags = (typeof flags == "object") ? flags : {};
var max = (typeof flags.max == "number") ? flags.max : Infinity;
var min = (typeof flags.min == "number") ? flags.min : -Infinity;
var dec = (typeof flags.decimal == "string") ? flags.decimal : ".";
// splice out anything not part of a number
var pattern = "[^" + dec + "\\deE+-]";
value = value.replace(RegExp(pattern, "g"), "");
// trim ends of things like e, E, or the decimal character
value = value.replace(/^([+-]?)(\D*)/, "$1");
value = value.replace(/(\D*)$/, "");
// replace decimal with ".". The minus sign '-' could be the decimal!
pattern = "(\\d)[" + dec + "](\\d)";
value = value.replace(RegExp(pattern, "g"), "$1.$2");
value = Number(value);
if ( value < min || value > max ) { return false; } // Boolean
return true; // Boolean
}
dojo.validate.isNumberFormat = function(/*String*/value, /*Object?*/flags){
// summary:
// Validates any sort of number based format
//
// description:
// Use it for phone numbers, social security numbers, zip-codes, etc.
// The value can be validated against one format or one of multiple formats.
//
// Format
// # Stands for a digit, 0-9.
// ? Stands for an optional digit, 0-9 or nothing.
// All other characters must appear literally in the expression.
//
// Example
// "(###) ###-####" -> (510) 542-9742
// "(###) ###-#### x#???" -> (510) 542-9742 x153
// "###-##-####" -> 506-82-1089 i.e. social security number
// "#####-####" -> 98225-1649 i.e. zip code
//
// value: A string
// flags: {format:String}
// flags.format A string or an Array of strings for multiple formats.
var re = new RegExp("^" + dojo.regexp.numberFormat(flags) + "$", "i");
return re.test(value); // Boolean
}
dojo.validate.isValidLuhn = function(/*String*/value){
//summary: Compares value against the Luhn algorithm to verify its integrity
var sum, parity, curDigit;
if(typeof value!='string'){
value = String(value);
}
value = value.replace(/[- ]/g,''); //ignore dashes and whitespaces
parity = value.length%2;
sum=0;
for(var i=0;i<value.length;i++){
curDigit = parseInt(value.charAt(i));
if(i%2==parity){
curDigit*=2;
}
if(curDigit>9){
curDigit-=9;
}
sum+=curDigit;
}
return !(sum%10);
}
/**
Procedural API Description
The main aim is to make input validation expressible in a simple format.
You define profiles which declare the required and optional fields and any constraints they might have.
The results are provided as an object that makes it easy to handle missing and invalid input.
Usage
var results = dojo.validate.check(form, profile);
Profile Object
var profile = {
// filters change the field value and are applied before validation.
trim: ["tx1", "tx2"],
uppercase: ["tx9"],
lowercase: ["tx5", "tx6", "tx7"],
ucfirst: ["tx10"],
digit: ["tx11"],
// required input fields that are blank will be reported missing.
// required radio button groups and drop-down lists with no selection will be reported missing.
// checkbox groups and selectboxes can be required to have more than one value selected.
// List required fields by name and use this notation to require more than one value: {checkboxgroup: 2}, {selectboxname: 3}.
required: ["tx7", "tx8", "pw1", "ta1", "rb1", "rb2", "cb3", "s1", {"doubledip":2}, {"tripledip":3}],
// dependant/conditional fields are required if the target field is present and not blank.
// At present only textbox, password, and textarea fields are supported.
dependencies: {
cc_exp: "cc_no",
cc_type: "cc_no",
},
// Fields can be validated using any boolean valued function.
// Use arrays to specify parameters in addition to the field value.
constraints: {
field_name1: myValidationFunction,
field_name2: dojo.validate.isInteger,
field_name3: [myValidationFunction, additional parameters],
field_name4: [dojo.validate.isValidDate, "YYYY.MM.DD"],
field_name5: [dojo.validate.isEmailAddress, false, true],
},
// Confirm is a sort of conditional validation.
// It associates each field in its property list with another field whose value should be equal.
// If the values are not equal, the field in the property list is reported as Invalid. Unless the target field is blank.
confirm: {
email_confirm: "email",
pw2: "pw1",
}
};
Results Object
isSuccessful(): Returns true if there were no invalid or missing fields, else it returns false.
hasMissing(): Returns true if the results contain any missing fields.
getMissing(): Returns a list of required fields that have values missing.
isMissing(field): Returns true if the field is required and the value is missing.
hasInvalid(): Returns true if the results contain fields with invalid data.
getInvalid(): Returns a list of fields that have invalid values.
isInvalid(field): Returns true if the field has an invalid value.
*/
| gepesz/chat | WebContent/js/src/validate/common.js | JavaScript | apache-2.0 | 10,447 |
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
export { createContext, useContext } from 'use-context-selector';
export const identity = (state) => state;
| GoogleForCreators/web-stories-wp | packages/react/src/context.js | JavaScript | apache-2.0 | 705 |
// Link.test.js - temporary example class to show unit tests working
// Use React's test renderer and Jest's snapshot feature to interact
// with the component and capture the rendered output and create a snapshot file
import React from 'react';
import Link from '../../src/components/Link';
import renderer from 'react-test-renderer';
test('Link changes the class when hovered', () => {
const component = renderer.create(
<Link page="http://www.facebook.com">Facebook</Link>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
// manually trigger the callback
tree.props.onMouseEnter();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
// manually trigger the callback
tree.props.onMouseLeave();
// re-rendering
tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
| diivanand/DataBrowser | test/components/Link.test.js | JavaScript | apache-2.0 | 883 |
angular.module('n52.core.diagram')
.service('flotChartServ', [
'timeseriesService',
'timeService',
'settingsService',
'flotDataHelperServ',
'$rootScope',
'monthNamesTranslaterServ',
'labelMapperSrvc',
'$q',
function(
timeseriesService,
timeService,
settingsService,
flotDataHelperServ,
$rootScope,
monthNamesTranslaterServ,
labelMapperSrvc,
$q
) {
var createYAxis = () => {
var axesList = {};
var requests = [];
angular.forEach(timeseriesService.getAllTimeseries(), (elem) => {
var requestUom, requestLabel, requestBundle = [];
if (elem.uom) {
requestUom = labelMapperSrvc.getMappedLabel(elem.uom);
requestBundle.push(requestUom);
requests.push(requestUom);
}
if (elem.parameters && elem.parameters.phenomenon) {
requestLabel = labelMapperSrvc.getMappedLabel(elem.parameters.phenomenon.label);
requestBundle.push(requestLabel);
requests.push(requestLabel);
}
$q.all(requestBundle).then((result) => {
if (elem.styles.groupedAxis === undefined || elem.styles.groupedAxis) {
var label;
if (result.length === 2 && !result[1].indexOf('http')) {
label = result[1] + ' [' + result[0] + ']';
} else {
label = '[' + result[0] + ']';
}
if (!axesList.hasOwnProperty(label)) {
axesList[label] = {
id: ++Object.keys(axesList).length,
uom: label,
tsColors: [elem.styles.color],
zeroScaled: elem.styles.zeroScaled
};
elem.styles.yaxis = axesList[label].id;
} else {
axesList[label].tsColors.push(elem.styles.color);
elem.styles.yaxis = axesList[label].id;
}
} else {
axesList[elem.internalId] = {
id: ++Object.keys(axesList).length,
uom: label,
tsColors: [elem.styles.color],
zeroScaled: elem.styles.zeroScaled
};
elem.styles.yaxis = axesList[elem.internalId].id;
}
});
});
$q.all(requests).then(() => {
var axes = [];
angular.forEach(axesList, (elem) => {
axes.splice(elem.id - 1, 0, {
uom: elem.uom,
tsColors: elem.tsColors,
min: elem.zeroScaled ? 0 : this.options.yaxis.min
});
});
this.options.yaxes = axes;
});
};
var createDataSet = () => {
createYAxis();
var dataset = [];
if (timeseriesService.getTimeseriesCount() > 0) {
angular.forEach(timeseriesService.timeseries, (elem) => {
flotDataHelperServ.updateTimeseriesInDataSet(dataset, renderOptions, elem.internalId, timeseriesService.getData(elem.internalId));
});
}
return dataset;
};
this.options = {
series: {
downsample: {
threshold: 0
},
lines: {
show: true,
fill: false
},
// points : {
// show: true
// },
shadowSize: 1
},
selection: {
mode: null
},
grid: {
hoverable: true,
autoHighlight: true
},
crosshair: {
mode: 'x'
},
xaxis: {
mode: 'time',
timezone: 'browser',
monthNames: monthNamesTranslaterServ.getMonthNames()
// timeformat: '%Y/%m/%d',
//use these the following two lines to have small ticks at the bottom ob the diagram
// tickLength: 5,
// tickColor: '#000'
},
yaxis: {
show: true,
additionalWidth: 17,
panRange: false,
min: null,
labelWidth: 50
// tickFormatter : function(val, axis) {
// var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1;
// var formatted = '' + Math.round(val * factor) / factor;
// return formatted + '<br>' + this.uom;
// }
},
legend: {
show: false
},
pan: {
interactive: true,
frameRate: 10
},
touch: {
delayTouchEnded: 200,
pan: 'x',
scale: ''
}
};
angular.merge(this.options, settingsService.chartOptions);
var renderOptions = {
showRefValues: true,
showSelection: true,
showActive: true
};
this.setTimeExtent = () => {
this.options.xaxis.min = timeService.time.start.toDate().getTime();
this.options.xaxis.max = timeService.time.end.toDate().getTime();
};
this.timeseriesDataChanged = (timeseries) => {
createYAxis();
flotDataHelperServ.updateAllTimeseriesToDataSet(this.dataset, renderOptions, timeseries);
};
this.setTimeExtent();
$rootScope.$on('timeseriesChanged', (evt, id) => {
createYAxis();
flotDataHelperServ.updateTimeseriesInDataSet(this.dataset, renderOptions, id, timeseriesService.getData(id));
});
$rootScope.$on('$translateChangeEnd', () => {
this.options.xaxis.monthNames = monthNamesTranslaterServ.getMonthNames();
});
$rootScope.$on('allTimeseriesChanged', () => {
createYAxis();
flotDataHelperServ.updateAllTimeseriesToDataSet(this.dataset, renderOptions, timeseriesService.getAllTimeseries());
});
this.dataset = createDataSet();
}
]);
| 52North/sensorweb-client-core | src/js/Chart/services/flotChartServ.js | JavaScript | apache-2.0 | 7,537 |
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('stage-details', 'Integration | Component | stage details', {
integration: true
});
test('it renders', function(assert) {
assert.expect(2);
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.render(hbs`{{stage-details}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:
this.render(hbs`
{{#stage-details}}
template block text
{{/stage-details}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
| AcalephStorage/kontinuous-ui | tests/integration/components/stage-details-test.js | JavaScript | apache-2.0 | 681 |
const { Command } = require("klasa");
const { MessageEmbed } = require("discord.js");
const statusList = {
online: "online",
idle: "idle",
dnd: "in do not disturb"
};
module.exports = class extends Command {
constructor(...args) {
super(...args, {
name: "userinfo",
enabled: true,
runIn: ["text"],
aliases: ["user"],
description: "Get a user's information",
usage: "<user:usersearch>",
extendedHelp: "Need Discord info on a specific user? I got you covered!"
});
this.humanUse = "<user>";
}
async run(msg, [user]) {
user = msg.guild.members.cache.get(user.id);
var userActivity = null;
// If presence intent is enabled, grab presence activity for display.
if (user.presence.clientStatus != null) {
var status = statusList[user.presence.status] || "offline";
var activity = user.presence.activities[0];
if (user.presence.activity === null) { userActivity += " "; }
else {
switch (activity.type) { //All cases covered
case "PLAYING":
userActivity = " while playing ";
break;
case "LISTENING":
userActivity = " while listening to ";
break;
case "WATCHING":
userActivity = " while watching ";
break;
case "STREAMING":
userActivity = " while streaming ";
break;
}
userActivity += activity.name;
}
}
var lastMsgTime;
if (user.lastMessageChannelID) {
var lastMsg = user.guild.channels.cache.get(user.lastMessageChannelID)
.messages.cache.get(user.lastMessageID);
lastMsgTime = this.client.util.dateDisplay(new Date(lastMsg.createdTimestamp));
}
else {
lastMsgTime = "No message found...";
}
const embed = new MessageEmbed()
.setTimestamp()
.setFooter(msg.guild.name, msg.guild.iconURL())
.setThumbnail(user.user.displayAvatarURL())
.setAuthor(user.user.tag);
if (userActivity != null) {
embed.setDescription(`Currently ${status}${userActivity}`);
}
embed.addField("ID", user.id, true);
if (user.nickname) {
embed.addField("Nickname", user.nickname, true);
}
embed.addField("User Type", user.user.bot ? "Bot": "Human", true)
.addField("Last Guild Message", lastMsgTime)
.addField("Created", this.client.util.dateDisplay(user.user.createdAt), true)
.addField("Joined", this.client.util.dateDisplay(user.joinedAt), true)
.setColor(0x04d5fd);
msg.channel.send({embed});
}
}; | Butterstroke/MargarineBot | commands/General/userinfo.js | JavaScript | apache-2.0 | 3,031 |
function dictionaryAddCtrl($scope, DictService, $state) {
$scope.$emit("update-title", {
pageTitle: "字典列表",
links: [
{
url: "common.dictionary-list",
name: "字典列表"
},
{
url: "common.dictionary-add",
name: "新增字典"
}
]
});
$scope.save = function () {
DictService.save($scope.dict, function () {
//MessageService.saveSuccess();
//LocationTo.path("/sys/dict/list");
$state.transitionTo('common.dictionary-list')
}, function () {
});
};
}
dictionaryAddCtrl.$inject = [ '$scope', 'DictService', '$state'];
| edgar615/admin-ng | app/modules/common/js/dictionary-add.js | JavaScript | apache-2.0 | 736 |
#!/usr/bin/env node
'use strict';
const Engine = require('../').Engine;
const browserScripts = require('../lib/support/browserScript');
const logging = require('../').logging;
const cli = require('../lib/support/cli');
const StorageManager = require('../lib/support/storageManager');
const merge = require('lodash.merge');
const fs = require('fs');
const path = require('path');
const log = require('intel').getLogger('browsertime');
const engineUtils = require('../lib/support/engineUtils');
const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor;
async function parseUserScripts(scripts) {
if (!Array.isArray(scripts)) scripts = [scripts];
const results = {};
for (const script of scripts) {
const code = await browserScripts.findAndParseScripts(
path.resolve(script),
'custom'
);
merge(results, code);
}
return results;
}
async function run(urls, options) {
try {
let dir = 'browsertime-results';
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
}
let engine = new Engine(options);
const scriptCategories = await browserScripts.allScriptCategories;
let scriptsByCategory = await browserScripts.getScriptsForCategories(
scriptCategories
);
if (options.script) {
const userScripts = await parseUserScripts(options.script);
scriptsByCategory = merge(scriptsByCategory, userScripts);
}
try {
await engine.start();
const result = await engine.runMultiple(urls, scriptsByCategory);
let saveOperations = [];
// TODO setup by name
let firstUrl = urls[0];
// if the url is an array, it's of the form [filename, function]
if (firstUrl instanceof Array) {
firstUrl = firstUrl[0];
}
const storageManager = new StorageManager(firstUrl, options);
const harName = options.har ? options.har : 'browsertime';
const jsonName = options.output ? options.output : 'browsertime';
saveOperations.push(storageManager.writeJson(jsonName + '.json', result));
if (result.har) {
const useGzip = options.gzipHar === true;
saveOperations.push(
storageManager.writeJson(harName + '.har', result.har, useGzip)
);
}
await Promise.all(saveOperations);
const resultDir = path.relative(process.cwd(), storageManager.directory);
// check for errors
for (let eachResult of result) {
for (let errors of eachResult.errors) {
if (errors.length > 0) {
process.exitCode = 1;
}
}
}
log.info(`Wrote data to ${resultDir}`);
} finally {
log.debug('Stopping Browsertime');
try {
await engine.stop();
log.debug('Stopped Browsertime');
} catch (e) {
log.error('Error stopping Browsertime!', e);
process.exitCode = 1;
}
}
} catch (e) {
log.error('Error running browsertime', e);
process.exitCode = 1;
} finally {
process.exit();
}
}
let cliResult = cli.parseCommandLine();
/*
Each url can be:
- an url value
- an array of tests. In that case it's a mapping containing
theses values:
- test: an async function containing the test to run
- setUp: an async function for the preScript [optional]
- tearDown: an async function for the postScript [optional]
*/
const tests = [];
cliResult.urls.forEach(function convert(url) {
// for each url, we try to load it as a script, that may contain
// export a single function or an object containing setUp/test/tearDown functions.
let testScript = engineUtils.loadScript(url);
// if the value is an url or a not a single function, we can return the original value
if (typeof testScript == 'string' || testScript instanceof AsyncFunction) {
tests.push(url);
return;
}
if (testScript.setUp) {
if (!cliResult.options.preScript) {
cliResult.options.preScript = [];
}
cliResult.options.preScript.push(testScript.setUp);
}
if (testScript.tearDown) {
if (!cliResult.options.postScript) {
cliResult.options.postScript = [];
}
cliResult.options.postScript.push(testScript.tearDown);
}
// here, url is the filename containing the script, and test the callable.
tests.push([url, testScript.test]);
});
logging.configure(cliResult.options);
run(tests, cliResult.options);
| tobli/browsertime | bin/browsertime.js | JavaScript | apache-2.0 | 4,376 |
$(function() {
$("input,textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Votre message a bien été envoyé. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Désolé " + firstName + ", il semble que mon serveur mail ne réponde pas. Réessayez plus tard !");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
| Lamx/cv | js/contact_me.js | JavaScript | apache-2.0 | 2,868 |