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
|
---|---|---|---|---|---|
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Renderer', 'sap/ui/layout/ResponsiveFlowLayoutRenderer'],
function(jQuery, Renderer, ResponsiveFlowLayoutRenderer1) {
"use strict";
var ResponsiveFlowLayoutRenderer = Renderer.extend(ResponsiveFlowLayoutRenderer1);
return ResponsiveFlowLayoutRenderer;
}, /* bExport= */ true);
| thbonk/electron-openui5-boilerplate | libs/openui5-runtime/resources/sap/ui/commons/layout/ResponsiveFlowLayoutRenderer-dbg.js | JavaScript | apache-2.0 | 520 |
import {observable, action, computed} from 'mobx'
import Todo from '../models/Todo'
export class TodoStore {
@observable todos = [];
@observable showingOnlyIncompleteTodos;
@action createTodo({title, done}) {
this.todos.push(new Todo({title, done}));
}
@action toggleOnlyIncompleteTodos() {
this.showingOnlyIncompleteTodos = !this.showingOnlyIncompleteTodos;
}
@computed get incompleteTodos() {
return this.todos.filter((todo) => !todo.done);
}
constructor() {
this.showingOnlyIncompleteTodos = false;
this.createTodo({title: 'Sample Todo 1', done: true});
this.createTodo({title: 'Sample Todo 2', done: false});
}
}
export default new TodoStore();
| smakazmidd/react-starter | client/src/script/stores/TodoStore.js | JavaScript | apache-2.0 | 700 |
var addChanged=false;
var positionFound = false;
var geocoder = new google.maps.Geocoder();
var newLat;
var newLng;
/**
Code une addresse en 2 coordonnées, latitude et longitude
Si le codage est russit on appelle funcFound, sinon funcFail
*/
function codeAddress(addressToTest, funcFound, funcFail) {
/* Récupération de la valeur de l'adresse saisie */
//var address = document.getElementById("address").value;
/* Appel au service de geocodage avec l'adresse en paramètre */
geocoder.geocode( { 'address': addressToTest}, function(results, status) {
/* Si l'adresse a pu être géolocalisée */
if (status == google.maps.GeocoderStatus.OK) {
/* Récupération de sa latitude et de sa longitude */
var coords = (results[0].geometry.location);
funcFound(coords.lat(), coords.lng());//cette fonction est à définir par l'appelant
}else{
funcFail(addressToTest);//cette fonction est à définir par l'appelant
}
});
}
/**
Cette fonction prend en paramètre des coordonnées et renvoi l'adresse correspondante si trouvée
*/
function getAddress(latitude, longitude, funcFound, funcFail) {
var latlng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status !== google.maps.GeocoderStatus.OK) {
funcFail(latitude, longitude);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
//alert(results[0].formatted_address);
funcFound(results[0].formatted_address);
}
});
}
| gpierre42/optraj | vagrant/optraj.istic.univ-rennes1.fr/GUI/htdocs/js/util/addressResolution.js | JavaScript | apache-2.0 | 1,609 |
'use strict';
var storiesdb = require('nano')('http://localhost:5984/stories');
var viewDoc = {
_id: '_design/story',
language: 'javascript',
views: {
byUser: require('./story-by-user'),
byTitle: require('./story-by-title')
}
};
module.exports = {
// Generates views
init: function () {
storiesdb.insert(viewDoc, function (err) {
if (err) return console.error(err);
console.log('Successfully created story views');
});
}
};
| bananaoomarang/chapters-server | lib/couch-views/index.js | JavaScript | apache-2.0 | 481 |
(function(exports) {
'use strict';
var _settingsPanel, _closeSettingsButton, _logoutSettingsButton,
_cleanCallsButton, _cleanUrlsButton, _videoDefaultSettings,
_commitHashTag, _cameraDefaultSettings, _loggedAs;
var _isVideoDefault = true;
var _isFrontCameraDefault = true;
var _isSingleCamera = false;
const VIDEO_SETTING = 'video-default';
const CAMERA_SETTING = 'camera-default';
var _;
var Settings = {
get isVideoDefault() {
return _isVideoDefault;
},
reset: function s_clear() {
asyncStorage.setItem(
VIDEO_SETTING,
true
);
asyncStorage.setItem(
CAMERA_SETTING,
true
);
_isVideoDefault = true;
_isFrontCameraDefault = true;
_isSingleCamera = false;
},
init: function s_init(identity) {
if (!_settingsPanel) {
// Cache mozL10n functionality
_ = navigator.mozL10n.get;
// Cache DOM elements
_loggedAs = document.getElementById('settings-logout-identity');
_settingsPanel = document.getElementById('settings-panel');
_closeSettingsButton = document.getElementById('settings-close-button');
_logoutSettingsButton = document.getElementById('settings-logout-button');
_cleanCallsButton = document.getElementById('settings-clean-calls-button');
_cleanUrlsButton = document.getElementById('settings-clean-urls-button');
_videoDefaultSettings = document.getElementById('video-default-setting');
_cameraDefaultSettings = document.getElementById('camera-default-setting');
_commitHashTag = document.getElementById('settings-commit-hash-tag');
// Add listeners just once
_cleanCallsButton.addEventListener(
'click',
function() {
var options = new OptionMenu({
// TODO Change with l10n string when ready
section: _('deleteAllConfirmation'),
type: 'confirm',
items: [
{
name: 'Delete',
class: 'danger',
l10nId: 'delete',
method: function() {
CallLog.cleanCalls();
Settings.hide();
},
params: []
},
{
name: 'Cancel',
l10nId: 'cancel'
}
]
});
options.show();
}.bind(this)
);
_cleanUrlsButton.addEventListener(
'click',
function() {
var options = new OptionMenu({
type: 'action',
items: [
{
name: 'Clean just revoked URLs',
l10nId: 'cleanJustRevoked',
method: function() {
CallLog.cleanRevokedUrls();
Settings.hide();
},
params: []
},
{
name: 'Clean all',
l10nId: 'cleanAll',
method: function() {
CallLog.cleanUrls();
Settings.hide();
},
params: []
},
{
name: 'Cancel',
l10nId: 'cancel'
}
]
});
options.show();
}.bind(this)
);
_closeSettingsButton.addEventListener(
'click',
this.hide.bind(this)
);
_logoutSettingsButton.addEventListener(
'click',
function onLogout() {
LoadingOverlay.show(_('loggingOut'));
Controller.logout();
}.bind(this)
);
}
// Set the value taking into account the identity
_loggedAs.innerHTML = _(
'loggedInAs',
{
username: identity || _('unknown')
}
);
// Set the commit based on the version
if (_commitHashTag && Version.id) {
_commitHashTag.textContent = Version.id || _('unknown');
}
// Set the value of the default mode (video/audio)
asyncStorage.getItem(
VIDEO_SETTING,
function onSettingRetrieved(isVideoDefault) {
if (isVideoDefault === null) {
Settings.reset();
} else {
_isVideoDefault = isVideoDefault;
}
_videoDefaultSettings.value = _isVideoDefault;
_videoDefaultSettings.addEventListener(
'change',
function() {
_isVideoDefault = _videoDefaultSettings.options[
_videoDefaultSettings.selectedIndex
].value;
asyncStorage.setItem(
VIDEO_SETTING,
_isVideoDefault
);
}
);
}
);
// Set the value of the default camera if needed
if (!navigator.mozCameras && navigator.mozCameras.getListOfCameras().length < 2) {
_isSingleCamera = true;
_cameraDefaultSettings.parentNode.parentNode.style.display = 'none';
} else {
asyncStorage.getItem(
CAMERA_SETTING,
function onSettingRetrieved(isFrontCamera) {
if (isFrontCamera === null) {
Settings.reset();
} else {
_isFrontCameraDefault = isFrontCamera;
}
_cameraDefaultSettings.value = _isFrontCameraDefault;
_cameraDefaultSettings.addEventListener(
'change',
function() {
_isFrontCameraDefault = _cameraDefaultSettings.options[
_cameraDefaultSettings.selectedIndex
].value;
asyncStorage.setItem(
CAMERA_SETTING,
_isFrontCameraDefault
);
}
);
}
);
}
},
show: function s_show() {
if (!_settingsPanel) {
return;
}
_settingsPanel.classList.add('show');
},
hide: function s_hide() {
if (!_settingsPanel) {
return;
}
_settingsPanel.classList.remove('show');
},
get isFrontalCamera() {
return _isSingleCamera ? false : _isFrontCameraDefault;
}
};
exports.Settings = Settings;
}(this));
| suoko/firefoxos-loop-client-master | js/screens/settings.js | JavaScript | apache-2.0 | 6,400 |
//
// Copyright (c) Microsoft and contributors. 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.
//
var assert = require('assert');
// Test includes
var testutil = require('../../../util/util');
var blobtestutil = require('../../../framework/blob-test-utils');
// Lib includes
var azure = testutil.libRequire('azure');
var Constants = azure.Constants;
var HttpConstants = Constants.HttpConstants;
var containerNames = [];
var containerNamesPrefix = 'cont';
var testPrefix = 'sharedkeylite-tests';
var blobService;
var suiteUtil;
suite('sharedkeylite-tests', function () {
suiteSetup(function (done) {
blobService = azure.createBlobService();
suiteUtil = blobtestutil.createBlobTestUtils(blobService, testPrefix);
suiteUtil.setupSuite(done);
});
suiteTeardown(function (done) {
suiteUtil.teardownSuite(done);
});
setup(function (done) {
suiteUtil.setupTest(done);
});
teardown(function (done) {
suiteUtil.teardownTest(done);
});
test('CreateContainer', function (done) {
blobService.authenticationProvider = new azure.SharedKeyLite(blobService.storageAccount, blobService.storageAccessKey);
var containerName = testutil.generateId(containerNamesPrefix, containerNames, suiteUtil.isMocked);
blobService.createContainer(containerName, function (createError, container1, createContainerResponse) {
assert.equal(createError, null);
assert.notEqual(container1, null);
if (container1) {
assert.notEqual(container1.name, null);
assert.notEqual(container1.etag, null);
assert.notEqual(container1.lastModified, null);
}
assert.equal(createContainerResponse.statusCode, HttpConstants.HttpResponseCodes.Created);
// creating again will result in a duplicate error
blobService.createContainer(containerName, function (createError2, container2) {
assert.equal(createError2.code, Constants.BlobErrorCodeStrings.CONTAINER_ALREADY_EXISTS);
assert.equal(container2, null);
done();
});
});
});
});
| jmspring/azure-sdk-for-node | test/services/blob/internal/sharedkeylite-tests.js | JavaScript | apache-2.0 | 2,589 |
'use strict'
const Primus = require('primus')
const UglifyJS = require('uglify-js')
const fs = require('fs')
const path = require('path')
const util = require('util')
const uuid = require('uuid')
const ActionHero = require('./../index.js')
const api = ActionHero.api
module.exports = class WebSocketServer extends ActionHero.Server {
constructor () {
super()
this.type = 'websocket'
this.attributes = {
canChat: true,
logConnections: true,
logExits: true,
sendWelcomeMessage: true,
verbs: [
'quit',
'exit',
'documentation',
'roomAdd',
'roomLeave',
'roomView',
'detailsView',
'say'
]
}
}
initialize () {}
start () {
const webserver = api.servers.servers.web
this.server = new Primus(webserver.server, this.config.server)
this.writeClientJS()
this.server.on('connection', (rawConnection) => { this.handleConnection(rawConnection) })
this.server.on('disconnection', (rawConnection) => { this.handleDisconnection(rawConnection) })
this.log(`webSockets bound to ${webserver.options.bindIP}: ${webserver.options.port}`, 'debug')
this.active = true
this.on('connection', (connection) => {
connection.rawConnection.on('data', (data) => { this.handleData(connection, data) })
})
this.on('actionComplete', (data) => {
if (data.toRender !== false) {
data.connection.response.messageId = data.messageId
this.sendMessage(data.connection, data.response, data.messageId)
}
})
}
stop () {
this.active = false
if (this.config.destroyClientsOnShutdown === true) {
this.connections().forEach((connection) => { connection.destroy() })
}
if (this.server) { this.server.destroy() }
}
sendMessage (connection, message, messageId) {
if (message.error) {
message.error = api.config.errors.serializers.servers.websocket(message.error)
}
if (!message.context) { message.context = 'response' }
if (!messageId) { messageId = connection.messageId }
if (message.context === 'response' && !message.messageId) { message.messageId = messageId }
connection.rawConnection.write(message)
}
sendFile (connection, error, fileStream, mime, length, lastModified) {
const messageId = connection.messageId
let content = ''
let response = {
error: error,
content: null,
mime: mime,
length: length,
lastModified: lastModified
}
try {
if (!error) {
fileStream.on('data', (d) => { content += d })
fileStream.on('end', () => {
response.content = content
this.sendMessage(connection, response, messageId)
})
} else {
this.sendMessage(connection, response, messageId)
}
} catch (e) {
this.log(e, 'warning')
this.sendMessage(connection, response, messageId)
}
}
goodbye (connection) {
connection.rawConnection.end()
}
compileActionheroWebsocketClientJS () {
let ahClientSource = fs.readFileSync(path.join(__dirname, '/../client/ActionheroWebsocketClient.js')).toString()
let url = this.config.clientUrl
ahClientSource = ahClientSource.replace(/%%URL%%/g, url)
let defaults = {}
for (let i in this.config.client) { defaults[i] = this.config.client[i] }
defaults.url = url
let defaultsString = util.inspect(defaults)
defaultsString = defaultsString.replace('\'window.location.origin\'', 'window.location.origin')
ahClientSource = ahClientSource.replace('%%DEFAULTS%%', 'return ' + defaultsString)
return ahClientSource
}
renderClientJS (minimize) {
if (!minimize) { minimize = false }
let libSource = api.servers.servers.websocket.server.library()
let ahClientSource = this.compileActionheroWebsocketClientJS()
ahClientSource =
';;;\r\n' +
'(function(exports){ \r\n' +
ahClientSource +
'\r\n' +
'exports.ActionheroWebsocketClient = ActionheroWebsocketClient; \r\n' +
'exports.ActionheroWebsocketClient = ActionheroWebsocketClient; \r\n' +
'})(typeof exports === \'undefined\' ? window : exports);'
if (minimize) {
return UglifyJS.minify(libSource + '\r\n\r\n\r\n' + ahClientSource).code
} else {
return (libSource + '\r\n\r\n\r\n' + ahClientSource)
}
}
writeClientJS () {
if (!api.config.general.paths['public'] || api.config.general.paths['public'].length === 0) {
return
}
if (this.config.clientJsPath && this.config.clientJsName) {
let clientJSPath = path.normalize(
api.config.general.paths['public'][0] +
path.sep +
this.config.clientJsPath +
path.sep
)
let clientJSName = this.config.clientJsName
let clientJSFullPath = clientJSPath + clientJSName
try {
if (!fs.existsSync(clientJSPath)) {
fs.mkdirSync(clientJSPath)
}
fs.writeFileSync(clientJSFullPath + '.js', this.renderClientJS(false))
api.log(`wrote ${clientJSFullPath}.js`, 'debug')
fs.writeFileSync(clientJSFullPath + '.min.js', this.renderClientJS(true))
api.log(`wrote ${clientJSFullPath}.min.js`, 'debug')
} catch (e) {
api.log('Cannot write client-side JS for websocket server:', 'warning')
api.log(e, 'warning')
throw e
}
}
}
handleConnection (rawConnection) {
const fingerprint = rawConnection.query[api.config.servers.web.fingerprintOptions.cookieKey]
let { ip, port } = api.utils.parseHeadersForClientAddress(rawConnection.headers)
this.buildConnection({
rawConnection: rawConnection,
remoteAddress: ip || rawConnection.address.ip,
remotePort: port || rawConnection.address.port,
fingerprint: fingerprint
})
}
handleDisconnection (rawConnection) {
const connections = this.connections()
for (let i in connections) {
if (connections[i] && rawConnection.id === connections[i].rawConnection.id) {
connections[i].destroy()
break
}
}
}
async handleData (connection, data) {
const verb = data.event
delete data.event
connection.messageId = data.messageId || uuid.v4()
delete data.messageId
connection.params = {}
if (verb === 'action') {
for (let v in data.params) {
connection.params[v] = data.params[v]
}
connection.error = null
connection.response = {}
return this.processAction(connection)
}
if (verb === 'file') {
connection.params = {
file: data.file
}
return this.processFile(connection)
}
let words = []
let message
if (data.room) {
words.push(data.room)
delete data.room
}
for (let i in data) { words.push(data[i]) }
const messageId = connection.messageId
try {
let data = await connection.verbs(verb, words)
message = { status: 'OK', context: 'response', data: data }
return this.sendMessage(connection, message, messageId)
} catch (error) {
let formattedError = error.toString()
message = { status: formattedError, error: formattedError, context: 'response', data: data }
return this.sendMessage(connection, message, messageId)
}
}
}
| chimmelb/actionhero | servers/websocket.js | JavaScript | apache-2.0 | 7,292 |
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
/**
* Adds default metadata to the given hash.
*/
module.exports.add = function(args) {
const timestamp = args.timestamp;
const fileName = args.fileName;
const canonical = args.config.host + fileName;
const logo = args.config.host + '/img/favicon.png';
const leader = args.config.host + '/img/social.png';
const metadata = {
datePublished: timestamp,
dateModified: timestamp,
fileName: fileName,
canonical: canonical,
logo: logo,
logoWidth: '512',
logoHeight: '512',
leader: leader,
leaderWidth: '1642',
leaderHeight: '715'
};
addMissingMetadata(args, metadata);
};
function addMissingMetadata(target, source) {
for (const prop in source) {
if (!target[prop]) {
target[prop] = source[prop];
}
}
}
| ampproject/amp-by-example | lib/Metadata.js | JavaScript | apache-2.0 | 1,408 |
/******/ (function(modules) { // webpackBootstrap
/******/ function hotDownloadUpdateChunk(chunkId) {
/******/ var filename = require("path").join(__dirname, "" + chunkId + "." + hotCurrentHash + ".hot-update.js");
/******/ require("fs").readFile(filename, "utf-8", function(err, content) {
/******/ if(err) {
/******/ if(__webpack_require__.onError)
/******/ return __webpack_require__.onError(err);
/******/ else
/******/ throw err;
/******/ }
/******/ var chunk = {};
/******/ require("vm").runInThisContext("(function(exports) {" + content + "\n})", filename)(chunk);
/******/ hotAddUpdateChunk(chunk.id, chunk.modules);
/******/ });
/******/ }
/******/
/******/ function hotDownloadManifest(callback) {
/******/ var filename = require("path").join(__dirname, "" + hotCurrentHash + ".hot-update.json");
/******/ require("fs").readFile(filename, "utf-8", function(err, content) {
/******/ if(err) return callback();
/******/ try {
/******/ var update = JSON.parse(content);
/******/ } catch(e) {
/******/ return callback(e);
/******/ }
/******/ callback(null, update);
/******/ });
/******/ }
/******/
/******/
/******/
/******/
/******/ var hotApplyOnUpdate = true;
/******/ var hotCurrentHash = "5cb369ca91b819ced4a3";
/******/ var hotCurrentModuleData = {};
/******/ var hotCurrentParents = [];
/******/
/******/ function hotCreateRequire(moduleId) {
/******/ var me = installedModules[moduleId];
/******/ if(!me) return __webpack_require__;
/******/ var fn = function(request) {
/******/ if(me.hot.active) {
/******/ if(installedModules[request]) {
/******/ if(installedModules[request].parents.indexOf(moduleId) < 0)
/******/ installedModules[request].parents.push(moduleId);
/******/ if(me.children.indexOf(request) < 0)
/******/ me.children.push(request);
/******/ } else hotCurrentParents = [moduleId];
/******/ } else {
/******/ console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
/******/ hotCurrentParents = [];
/******/ }
/******/ return __webpack_require__(request);
/******/ };
/******/ for(var name in __webpack_require__) {
/******/ if(Object.prototype.hasOwnProperty.call(__webpack_require__, name)) {
/******/ fn[name] = __webpack_require__[name];
/******/ }
/******/ }
/******/ fn.e = function(chunkId, callback) {
/******/ if(hotStatus === "ready")
/******/ hotSetStatus("prepare");
/******/ hotChunksLoading++;
/******/ __webpack_require__.e(chunkId, function() {
/******/ try {
/******/ callback.call(null, fn);
/******/ } finally {
/******/ finishChunkLoading();
/******/ }
/******/ function finishChunkLoading() {
/******/ hotChunksLoading--;
/******/ if(hotStatus === "prepare") {
/******/ if(!hotWaitingFilesMap[chunkId]) {
/******/ hotEnsureUpdateChunk(chunkId);
/******/ }
/******/ if(hotChunksLoading === 0 && hotWaitingFiles === 0) {
/******/ hotUpdateDownloaded();
/******/ }
/******/ }
/******/ }
/******/ });
/******/ }
/******/ return fn;
/******/ }
/******/
/******/ function hotCreateModule(moduleId) {
/******/ var hot = {
/******/ // private stuff
/******/ _acceptedDependencies: {},
/******/ _declinedDependencies: {},
/******/ _selfAccepted: false,
/******/ _selfDeclined: false,
/******/ _disposeHandlers: [],
/******/
/******/ // Module API
/******/ active: true,
/******/ accept: function(dep, callback) {
/******/ if(typeof dep === "undefined")
/******/ hot._selfAccepted = true;
/******/ else if(typeof dep === "function")
/******/ hot._selfAccepted = dep;
/******/ else if(typeof dep === "number")
/******/ hot._acceptedDependencies[dep] = callback;
/******/ else for(var i = 0; i < dep.length; i++)
/******/ hot._acceptedDependencies[dep[i]] = callback;
/******/ },
/******/ decline: function(dep) {
/******/ if(typeof dep === "undefined")
/******/ hot._selfDeclined = true;
/******/ else if(typeof dep === "number")
/******/ hot._declinedDependencies[dep] = true;
/******/ else for(var i = 0; i < dep.length; i++)
/******/ hot._declinedDependencies[dep[i]] = true;
/******/ },
/******/ dispose: function(callback) {
/******/ hot._disposeHandlers.push(callback);
/******/ },
/******/ addDisposeHandler: function(callback) {
/******/ hot._disposeHandlers.push(callback);
/******/ },
/******/ removeDisposeHandler: function(callback) {
/******/ var idx = hot._disposeHandlers.indexOf(callback);
/******/ if(idx >= 0) hot._disposeHandlers.splice(idx, 1);
/******/ },
/******/
/******/ // Management API
/******/ check: hotCheck,
/******/ apply: hotApply,
/******/ status: function(l) {
/******/ if(!l) return hotStatus;
/******/ hotStatusHandlers.push(l);
/******/ },
/******/ addStatusHandler: function(l) {
/******/ hotStatusHandlers.push(l);
/******/ },
/******/ removeStatusHandler: function(l) {
/******/ var idx = hotStatusHandlers.indexOf(l);
/******/ if(idx >= 0) hotStatusHandlers.splice(idx, 1);
/******/ },
/******/
/******/ //inherit from previous dispose call
/******/ data: hotCurrentModuleData[moduleId]
/******/ };
/******/ return hot;
/******/ }
/******/
/******/ var hotStatusHandlers = [];
/******/ var hotStatus = "idle";
/******/
/******/ function hotSetStatus(newStatus) {
/******/ var oldStatus = hotStatus;
/******/ hotStatus = newStatus;
/******/ for(var i = 0; i < hotStatusHandlers.length; i++)
/******/ hotStatusHandlers[i].call(null, newStatus);
/******/ }
/******/
/******/ // while downloading
/******/ var hotWaitingFiles = 0;
/******/ var hotChunksLoading = 0;
/******/ var hotWaitingFilesMap = {};
/******/ var hotRequestedFilesMap = {};
/******/ var hotAvailibleFilesMap = {};
/******/ var hotCallback;
/******/
/******/ // The update info
/******/ var hotUpdate, hotUpdateNewHash;
/******/
/******/ function hotCheck(apply, callback) {
/******/ if(hotStatus !== "idle") throw new Error("check() is only allowed in idle status");
/******/ if(typeof apply === "function") {
/******/ hotApplyOnUpdate = false;
/******/ callback = apply;
/******/ } else {
/******/ hotApplyOnUpdate = apply;
/******/ callback = callback || function(err) { if(err) throw err };
/******/ }
/******/ hotSetStatus("check");
/******/ hotDownloadManifest(function(err, update) {
/******/ if(err) return callback(err);
/******/ if(!update) {
/******/ hotSetStatus("idle");
/******/ callback(null, null);
/******/ return;
/******/ }
/******/
/******/ hotRequestedFilesMap = {};
/******/ hotAvailibleFilesMap = {};
/******/ hotWaitingFilesMap = {};
/******/ for(var i = 0; i < update.c.length; i++)
/******/ hotAvailibleFilesMap[update.c[i]] = true;
/******/ hotUpdateNewHash = update.h;
/******/
/******/ hotSetStatus("prepare");
/******/ hotCallback = callback;
/******/ hotUpdate = {};
/******/ var chunkId = 0; {
/******/ hotEnsureUpdateChunk(chunkId);
/******/ }
/******/ if(hotChunksLoading === 0 && hotWaitingFiles === 0) {
/******/ hotUpdateDownloaded();
/******/ }
/******/ });
/******/ }
/******/
/******/ function hotAddUpdateChunk(chunkId, moreModules) {
/******/ if(!hotAvailibleFilesMap[chunkId] || !hotRequestedFilesMap[chunkId])
/******/ return;
/******/ hotRequestedFilesMap[chunkId] = false;
/******/ for(var moduleId in moreModules) {
/******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
/******/ hotUpdate[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(--hotWaitingFiles === 0 && hotChunksLoading === 0) {
/******/ hotUpdateDownloaded();
/******/ }
/******/ }
/******/
/******/ function hotEnsureUpdateChunk(chunkId) {
/******/ if(!hotAvailibleFilesMap[chunkId]) {
/******/ hotWaitingFilesMap[chunkId] = true;
/******/ } else {
/******/ hotRequestedFilesMap[chunkId] = true;
/******/ hotWaitingFiles++;
/******/ hotDownloadUpdateChunk(chunkId);
/******/ }
/******/ }
/******/
/******/ function hotUpdateDownloaded() {
/******/ hotSetStatus("ready");
/******/ var callback = hotCallback;
/******/ hotCallback = null;
/******/ if(!callback) return;
/******/ if(hotApplyOnUpdate) {
/******/ hotApply(hotApplyOnUpdate, callback);
/******/ } else {
/******/ var outdatedModules = [];
/******/ for(var id in hotUpdate) {
/******/ if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
/******/ outdatedModules.push(+id);
/******/ }
/******/ }
/******/ callback(null, outdatedModules);
/******/ }
/******/ }
/******/
/******/ function hotApply(options, callback) {
/******/ if(hotStatus !== "ready") throw new Error("apply() is only allowed in ready status");
/******/ if(typeof options === "function") {
/******/ callback = options;
/******/ options = {};
/******/ } else if(options && typeof options === "object") {
/******/ callback = callback || function(err) { if(err) throw err };
/******/ } else {
/******/ options = {};
/******/ callback = callback || function(err) { if(err) throw err };
/******/ }
/******/
/******/ function getAffectedStuff(module) {
/******/ var outdatedModules = [module];
/******/ var outdatedDependencies = [];
/******/
/******/ var queue = outdatedModules.slice();
/******/ while(queue.length > 0) {
/******/ var moduleId = queue.pop();
/******/ var module = installedModules[moduleId];
/******/ if(!module || module.hot._selfAccepted)
/******/ continue;
/******/ if(module.hot._selfDeclined) {
/******/ return new Error("Aborted because of self decline: " + moduleId);
/******/ }
/******/ if(moduleId === 0) {
/******/ return;
/******/ }
/******/ for(var i = 0; i < module.parents.length; i++) {
/******/ var parentId = module.parents[i];
/******/ var parent = installedModules[parentId];
/******/ if(parent.hot._declinedDependencies[moduleId]) {
/******/ return new Error("Aborted because of declined dependency: " + moduleId + " in " + parentId);
/******/ }
/******/ if(outdatedModules.indexOf(parentId) >= 0) continue;
/******/ if(parent.hot._acceptedDependencies[moduleId]) {
/******/ if(!outdatedDependencies[parentId])
/******/ outdatedDependencies[parentId] = [];
/******/ addAllToSet(outdatedDependencies[parentId], [moduleId]);
/******/ continue;
/******/ }
/******/ delete outdatedDependencies[parentId];
/******/ outdatedModules.push(parentId);
/******/ queue.push(parentId);
/******/ }
/******/ }
/******/
/******/ return [outdatedModules, outdatedDependencies];
/******/ }
/******/ function addAllToSet(a, b) {
/******/ for(var i = 0; i < b.length; i++) {
/******/ var item = b[i];
/******/ if(a.indexOf(item) < 0)
/******/ a.push(item);
/******/ }
/******/ }
/******/
/******/ // at begin all updates modules are outdated
/******/ // the "outdated" status can propagate to parents if they don't accept the children
/******/ var outdatedDependencies = {};
/******/ var outdatedModules = [];
/******/ var appliedUpdate = {};
/******/ for(var id in hotUpdate) {
/******/ if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
/******/ var moduleId = +id;
/******/ var result = getAffectedStuff(moduleId);
/******/ if(!result) {
/******/ if(options.ignoreUnaccepted)
/******/ continue;
/******/ hotSetStatus("abort");
/******/ return callback(new Error("Aborted because " + moduleId + " is not accepted"));
/******/ }
/******/ if(result instanceof Error) {
/******/ hotSetStatus("abort");
/******/ return callback(result);
/******/ }
/******/ appliedUpdate[moduleId] = hotUpdate[moduleId];
/******/ addAllToSet(outdatedModules, result[0]);
/******/ for(var moduleId in result[1]) {
/******/ if(Object.prototype.hasOwnProperty.call(result[1], moduleId)) {
/******/ if(!outdatedDependencies[moduleId])
/******/ outdatedDependencies[moduleId] = [];
/******/ addAllToSet(outdatedDependencies[moduleId], result[1][moduleId]);
/******/ }
/******/ }
/******/ }
/******/ }
/******/
/******/ // Store self accepted outdated modules to require them later by the module system
/******/ var outdatedSelfAcceptedModules = [];
/******/ for(var i = 0; i < outdatedModules.length; i++) {
/******/ var moduleId = outdatedModules[i];
/******/ if(installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted)
/******/ outdatedSelfAcceptedModules.push({
/******/ module: moduleId,
/******/ errorHandler: installedModules[moduleId].hot._selfAccepted
/******/ });
/******/ }
/******/
/******/ // Now in "dispose" phase
/******/ hotSetStatus("dispose");
/******/ var queue = outdatedModules.slice();
/******/ while(queue.length > 0) {
/******/ var moduleId = queue.pop();
/******/ var module = installedModules[moduleId];
/******/ if(!module) continue;
/******/
/******/ var data = {};
/******/
/******/ // Call dispose handlers
/******/ var disposeHandlers = module.hot._disposeHandlers;
/******/ for(var j = 0; j < disposeHandlers.length; j++) {
/******/ var cb = disposeHandlers[j]
/******/ cb(data);
/******/ }
/******/ hotCurrentModuleData[moduleId] = data;
/******/
/******/ // disable module (this disables requires from this module)
/******/ module.hot.active = false;
/******/
/******/ // remove module from cache
/******/ delete installedModules[moduleId];
/******/
/******/ // remove "parents" references from all children
/******/ for(var j = 0; j < module.children.length; j++) {
/******/ var child = installedModules[module.children[j]];
/******/ if(!child) continue;
/******/ var idx = child.parents.indexOf(moduleId);
/******/ if(idx >= 0) {
/******/ child.parents.splice(idx, 1);
/******/ if(child.parents.length === 0 && child.hot && child.hot._disposeHandlers && child.hot._disposeHandlers.length > 0) {
/******/ // Child has dispose handlers and no more references, dispose it too
/******/ queue.push(child.id);
/******/ }
/******/ }
/******/ }
/******/ }
/******/
/******/ // remove outdated dependency from module children
/******/ for(var moduleId in outdatedDependencies) {
/******/ if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
/******/ var module = installedModules[moduleId];
/******/ var moduleOutdatedDependencies = outdatedDependencies[moduleId];
/******/ for(var j = 0; j < moduleOutdatedDependencies.length; j++) {
/******/ var dependency = moduleOutdatedDependencies[j];
/******/ var idx = module.children.indexOf(dependency);
/******/ if(idx >= 0) module.children.splice(idx, 1);
/******/ }
/******/ }
/******/ }
/******/
/******/ // Not in "apply" phase
/******/ hotSetStatus("apply");
/******/
/******/ hotCurrentHash = hotUpdateNewHash;
/******/
/******/ // insert new code
/******/ for(var moduleId in appliedUpdate) {
/******/ if(Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) {
/******/ modules[moduleId] = appliedUpdate[moduleId];
/******/ }
/******/ }
/******/
/******/ // call accept handlers
/******/ var error = null;
/******/ for(var moduleId in outdatedDependencies) {
/******/ if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
/******/ var module = installedModules[moduleId];
/******/ var moduleOutdatedDependencies = outdatedDependencies[moduleId];
/******/ var callbacks = [];
/******/ for(var i = 0; i < moduleOutdatedDependencies.length; i++) {
/******/ var dependency = moduleOutdatedDependencies[i];
/******/ var cb = module.hot._acceptedDependencies[dependency];
/******/ if(callbacks.indexOf(cb) >= 0) continue;
/******/ callbacks.push(cb);
/******/ }
/******/ for(var i = 0; i < callbacks.length; i++) {
/******/ var cb = callbacks[i];
/******/ try {
/******/ cb(outdatedDependencies);
/******/ } catch(err) {
/******/ if(!error)
/******/ error = err;
/******/ }
/******/ }
/******/ }
/******/ }
/******/
/******/ // Load self accepted modules
/******/ for(var i = 0; i < outdatedSelfAcceptedModules.length; i++) {
/******/ var item = outdatedSelfAcceptedModules[i];
/******/ var moduleId = item.module;
/******/ hotCurrentParents = [moduleId];
/******/ try {
/******/ __webpack_require__(moduleId);
/******/ } catch(err) {
/******/ if(typeof item.errorHandler === "function") {
/******/ try {
/******/ item.errorHandler(err);
/******/ } catch(err) {
/******/ if(!error)
/******/ error = err;
/******/ }
/******/ } else if(!error)
/******/ error = err;
/******/ }
/******/ }
/******/
/******/ // handle errors in accept handlers and self accepted module load
/******/ if(error) {
/******/ hotSetStatus("fail");
/******/ return callback(error);
/******/ }
/******/
/******/ hotSetStatus("idle");
/******/ callback(null, outdatedModules);
/******/ }
/******/
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false,
/******/ hot: hotCreateModule(moduleId),
/******/ parents: hotCurrentParents,
/******/ children: []
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // __webpack_hash__
/******/ __webpack_require__.h = function() { return hotCurrentHash; };
/******/
/******/ // Load entry module and return exports
/******/ return hotCreateRequire(0)(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/*!*************************************!*\
!*** ./loaders/val-loader/index.js ***!
\*************************************/
/***/ function(module, exports, __webpack_require__) {
it("should handle the val loader (piped with css loader) correctly", function() {
(__webpack_require__(/*! css!val!../_css/generateCss */ 1) + "").indexOf("generated").should.not.be.eql(-1);
(__webpack_require__(/*! css!val!../_css/generateCss */ 1) + "").indexOf(".rule-import2").should.not.be.eql(-1);
(__webpack_require__(/*! raw!val!../_css/generateCss */ 2) + "").indexOf("generated").should.not.be.eql(-1);
});
/***/ },
/* 1 */
/*!***********************************************************************************!*\
!*** (webpack)/~/css-loader!(webpack)/~/val-loader!./loaders/_css/generateCss.js ***!
\***********************************************************************************/
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(/*! (webpack)/~/css-loader/cssToString.js */ 3)();
__webpack_require__(/*! (webpack)/~/css-loader/mergeImport.js */ 4)(exports, __webpack_require__(/*! -!(webpack)/~/css-loader!./folder/stylesheet-import1.css */ 5), "");
exports.push([module.id, "\r\n\r\n.rule-direct {\r\n\tbackground: lightgreen;\r\n}\n.generated { color: red; }", ""]);
/***/ },
/* 2 */
/*!***********************************************************************************!*\
!*** (webpack)/~/raw-loader!(webpack)/~/val-loader!./loaders/_css/generateCss.js ***!
\***********************************************************************************/
/***/ function(module, exports, __webpack_require__) {
module.exports = "@import url(folder/stylesheet-import1.css);\r\n\r\n.rule-direct {\r\n\tbackground: lightgreen;\r\n}\n.generated { color: red; }"
/***/ },
/* 3 */
/*!*********************************************!*\
!*** (webpack)/~/css-loader/cssToString.js ***!
\*********************************************/
/***/ function(module, exports, __webpack_require__) {
module.exports = function() {
var list = [];
list.toString = function toString() {
var result = [];
for(var i = 0; i < this.length; i++) {
var item = this[i];
if(item[2]) {
result.push("@media " + item[2] + "{" + item[1] + "}");
} else {
result.push(item[1]);
}
}
return result.join("");
};
return list;
}
/***/ },
/* 4 */
/*!*********************************************!*\
!*** (webpack)/~/css-loader/mergeImport.js ***!
\*********************************************/
/***/ function(module, exports, __webpack_require__) {
module.exports = function(list, importedList, media) {
for(var i = 0; i < importedList.length; i++) {
var item = importedList[i];
if(media && !item[2])
item[2] = media;
else if(media) {
item[2] = "(" + item[2] + ") and (" + media + ")";
}
list.push(item);
}
};
/***/ },
/* 5 */
/*!***************************************************************************!*\
!*** (webpack)/~/css-loader!./loaders/_css/folder/stylesheet-import1.css ***!
\***************************************************************************/
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(/*! (webpack)/~/css-loader/cssToString.js */ 3)();
__webpack_require__(/*! (webpack)/~/css-loader/mergeImport.js */ 4)(exports, __webpack_require__(/*! -!(webpack)/~/css-loader!resources-module/stylesheet-import2.css */ 7), "print, screen");
__webpack_require__(/*! (webpack)/~/css-loader/mergeImport.js */ 4)(exports, __webpack_require__(/*! -!(webpack)/~/css-loader!./stylesheet-import3.css */ 6), "print and screen");
exports.push([module.id, "\r\n\r\n\r\n.rule-import1 {\r\n\tbackground: lightgreen;\r\n}\r\n", ""]);
/***/ },
/* 6 */
/*!***************************************************************************!*\
!*** (webpack)/~/css-loader!./loaders/_css/folder/stylesheet-import3.css ***!
\***************************************************************************/
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(/*! (webpack)/~/css-loader/cssToString.js */ 3)();
exports.push([module.id, ".rule-import2 {\r\n\tbackground: red !important;\r\n}", ""]);
/***/ },
/* 7 */
/*!***************************************************************************************!*\
!*** (webpack)/~/css-loader!./loaders/_css/~/resources-module/stylesheet-import2.css ***!
\***************************************************************************************/
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(/*! (webpack)/~/css-loader/cssToString.js */ 3)();
exports.push([module.id, ".rule-import2 {\r\n\tbackground: lightgreen;\r\n}", ""]);
/***/ }
/******/ ]) | raml-org/raml-dotnet-parser-2 | source/Raml.Parser/node_modules/raml-1-0-parser/node_modules/webpack/test/js/hot/loaders/val-loader/bundle.js | JavaScript | apache-2.0 | 24,067 |
/**
* @license Copyright 2019 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';
const Audit = require('../audit.js');
const ComputedTBT = require('../../computed/metrics/total-blocking-time.js');
const i18n = require('../../lib/i18n/i18n.js');
const UIStrings = {
/** Description of the Total Blocking Time (TBT) metric, which calculates the total duration of blocking time for a web page. Blocking times are time periods when the page would be blocked (prevented) from responding to user input (clicks, taps, and keypresses will feel slow to respond). This is displayed within a tooltip when the user hovers on the metric name to see more. No character length limits.*/
description: 'Sum of all time periods between FCP and Time to Interactive, ' +
'when task length exceeded 50ms, expressed in milliseconds. [Learn more](https://web.dev/lighthouse-total-blocking-time/).',
};
const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);
class TotalBlockingTime extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'total-blocking-time',
title: str_(i18n.UIStrings.totalBlockingTimeMetric),
description: str_(UIStrings.description),
scoreDisplayMode: Audit.SCORING_MODES.NUMERIC,
requiredArtifacts: ['traces', 'devtoolsLogs', 'TestedAsMobileDevice'],
};
}
/**
* @return {{mobile: {scoring: LH.Audit.ScoreOptions}, desktop: {scoring: LH.Audit.ScoreOptions}}}
*/
static get defaultOptions() {
return {
mobile: {
// According to a cluster telemetry run over top 10k sites on mobile, 5th percentile was 0ms,
// 25th percentile was 270ms and median was 895ms. These numbers include 404 pages. Picking
// thresholds according to our 25/75-th rule will be quite harsh scoring (a single 350ms task)
// after FCP will yield a score of .5. The following coefficients are semi-arbitrarily picked
// to give 600ms jank a score of .5 and 100ms jank a score of .999. We can tweak these numbers
// in the future. See https://www.desmos.com/calculator/bbsv8fedg5
scoring: {
p10: 287,
median: 600,
},
},
desktop: {
// Chosen in HTTP Archive desktop results to approximate curve easing described above.
// SELECT
// APPROX_QUANTILES(tbtValue, 100)[OFFSET(40)] AS p40_tbt,
// APPROX_QUANTILES(tbtValue, 100)[OFFSET(60)] AS p60_tbt
// FROM (
// SELECT CAST(JSON_EXTRACT_SCALAR(payload, '$._TotalBlockingTime') AS NUMERIC) AS tbtValue
// FROM `httparchive.pages.2020_04_01_desktop`
// )
scoring: {
p10: 150,
median: 350,
},
},
};
}
/**
* Audits the page to calculate Total Blocking Time.
*
* We define Blocking Time as any time interval in the loading timeline where task length exceeds
* 50ms. For example, if there is a 110ms main thread task, the last 60ms of it is blocking time.
* Total Blocking Time is the sum of all Blocking Time between First Contentful Paint and
* Interactive Time (TTI).
*
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
const trace = artifacts.traces[Audit.DEFAULT_PASS];
const devtoolsLog = artifacts.devtoolsLogs[Audit.DEFAULT_PASS];
const metricComputationData = {trace, devtoolsLog, settings: context.settings};
const metricResult = await ComputedTBT.request(metricComputationData, context);
const isDesktop = artifacts.TestedAsMobileDevice === false;
const options = isDesktop ? context.options.desktop : context.options.mobile;
return {
score: Audit.computeLogNormalScore(
options.scoring,
metricResult.timing
),
numericValue: metricResult.timing,
numericUnit: 'millisecond',
displayValue: str_(i18n.UIStrings.ms, {timeInMs: metricResult.timing}),
};
}
}
module.exports = TotalBlockingTime;
module.exports.UIStrings = UIStrings;
| umaar/lighthouse | lighthouse-core/audits/metrics/total-blocking-time.js | JavaScript | apache-2.0 | 4,644 |
angular.module('dCare.Authentication', ['ionic',
'dCare.Services.UserStore', 'dCare.ApiInvoker'])
.factory("AuthenticationService", function ($q, UserStore, ApiInvokerService, $ionicLoading, $mdDialog) {
var login = function (userID,password) {
//NR: TODO: Call Rest api for login
//NR: TODO: if Login Success => merge the recieved User Data with existing User Data {wireup following code}
var deferredLogin = $q.defer();
//NR: Mock call
var apiPayLoad = { email: userID, password: password };
ApiInvokerService.login(apiPayLoad).then(function (remoteUserData) { /// This Call will be replased by Actual Login Service call-promise
UserStore.getUser().then(function (user) {
var localUserData = (user) ? user : {};
localUserData.firstName = remoteUserData.firstname;
localUserData.lastName = remoteUserData.lastname;
localUserData.email = remoteUserData.email;
localUserData.photo = remoteUserData.photo;
localUserData.authToken = remoteUserData.token;
localUserData.tokenExpiryDate = (parseJWT(remoteUserData.token)).exp;
localUserData.loginDatetime = remoteUserData.loginDatetime;
localUserData.patients = (localUserData.patients) ? localUserData.patients : [];
var patientFound;
angular.forEach(remoteUserData.patients, function (remotePatient, key) {
patientFound = false;
//NR: Attempt to find if patient aready present locally
angular.forEach(localUserData.patients, function (localPatient, key) {
if (localPatient.guid === remotePatient.guid) {
patientFound = true;
localPatient.isDefault = remotePatient.isDefault;
localPatient.fullName = remotePatient.fullName;
localPatient.photo = remotePatient.photo;
}
});
//NR: If Patient does not exist, add Sync Flags, add Patient.
if (!patientFound) {
remotePatient.isEdited = false;
remotePatient.initialSyncStatus = "notSynced";
remotePatient.syncStatus = "notSynced";
remotePatient.syncStartDate = '';
remotePatient.syncEndDate = '';
localUserData.patients.push(remotePatient);
}
});
UserStore.save(localUserData).then(function (localUserData) {
//@NR: Saved Latest User Data
deferredLogin.resolve(localUserData);
//@NR: NOTE: Post login, the initi module will automatically handle initial sync responsiblity.
}).fail(function (err) {
//@NR: Save Latest Data Failed, Try Again to Login.
deferredLogin.reject(err);
});
}).fail(function (err) {
// Login Failed try login again.
deferredLogin.reject(err);
});
}).catch(function (error) {
// Login Service call Failed try login again.
app.log.error("Failed Login Call [Error]- " + JSON.stringify(error));
deferredLogin.reject("Unable to connect server !!");
});
return deferredLogin.promise;
};
var refreshToken = function () {
var deferredLogin = $q.defer();
UserStore.getUser().then(function (localUserData) { /// This Call will be replased by Actual Login Service call-promise
ApiInvokerService.refreshToken().then(function (remoteUserData) {
if (localUserData && localUserData.email) {
app.context.dbAuthCookie = remoteUserData.token;
var jwtPayload = parseJWT(remoteUserData.token);
////NR: Only update tokn & login info
localUserData.authToken = remoteUserData.token;
localUserData.tokenExpiryDate = jwtPayload.exp;
////localUserData.loginDatetime = remoteUserData.loginDatetime;
////NR: Set Cookie in app context for consumption by Sync-Services
//app.context.dbAuthCookie = jwtPayload.cookie;
////@NR: Save token to User Data
UserStore.save(localUserData).then(function (localUserData) {
deferredLogin.resolve(localUserData);
}).fail(function (err) {
//@NR: Save Latest Data Failed, Try Again to Login.
deferredLogin.reject(err);
});
} else {
deferredLogin.reject("No User");
}
}).catch(function (err) {
// refreshToken Failed try login again.
deferredLogin.reject(err);
});
}).fail(function (error) {
// Login Service call Failed try login again.
app.log.error("Failed Token Refresh Call [Error]-" + JSON.stringify(error));
deferredLogin.reject("Unable to connect server !!");
});
return deferredLogin.promise;
};
var logout = function () {
var deferredLogout = $q.defer();
UserStore.getUser().then(function (user) {
user.authToken = '';
user.tokenExpiryDate = '';
user.patients = [];
user.loginDatetime = '';
UserStore.save(user).then(function () {
deferredLogout.resolve();
}).fail(function (err) {
//@NR: Save Data Failed, Try Again to Login.
deferredLogout.reject(err);
});
}).fail(function (err) {
// Failed Logout, try again.
deferredLogout.reject(err);
});
return deferredLogout.promise;
};
var checkLogin = function () {
var deferredLoginCheck = $q.defer();
UserStore.getUser().then(function (user) {
//NR: Validate Login [could hav more criteria check]
if (user && user.authToken && castToLongDate(user.tokenExpiryDate) > castToLongDate(new Date())) {
deferredLoginCheck.resolve();
}else{
deferredLoginCheck.reject();
}
}).fail(function () {
deferredLoginCheck.reject();
});
return deferredLoginCheck.promise;
};
var register = function (user) {
var deferredRegisterUser = $q.defer();
//NR: TODO: Do basic User Data validation
//NR: NOTE: User Data will be added to Local store during Successfull login process, and not here
//var mockUserResponse = { authToken: '_T_O_K_E_N_', tokenExpiryDate: castToLongDate(new Date("12/12/2050")), patients: [], loginDatetime: castToLongDate(new Date()) };
//var mockUserData = angular.extend({}, user, mockUserResponse);
ApiInvokerService.signup(user).then(function (newUserData) {
// UserStore.save(newUserData).then(function (userData) {
deferredRegisterUser.resolve(newUserData);
// }).fail(function () {
// deferredRegisterUser.reject();
// });
}).catch(function (err) {
deferredRegisterUser.reject();
});
return deferredRegisterUser.promise;
};
//@private
var decodeBas64 = function (base64string) {
var decodedString = "";
try {
decodedString = window.atob(base64string)
} catch(err) {
decodedString = "";
console.log(err);
}
return decodedString;
};
//@private
var parseJWT = function (token) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
var payload = {exp:''};
var base64Decoded = decodeBas64(base64);
if (base64Decoded) {
payload = JSON.parse(base64Decoded);
//Convert time-stamps to "milliseconds", because server sends in "seconds"
payload.exp = payload.exp * 1000;
payload.iat = payload.iat * 1000;
}
return payload;
};
return {
login: login,
logout: logout,
checkLogin: checkLogin,
register: register,
refreshToken: refreshToken
};
}); | nozelrosario/Dcare | www/controllers/user/authenticationService.js | JavaScript | apache-2.0 | 8,882 |
'use strict';
/**
* @ngdoc function
* @name adsGtApp.controller:AboutCtrl
* @description
* # AboutCtrl
* Controller of the adsGtApp
*/
angular.module('adsGtApp')
.controller('DrugCtrl', ['$scope', '$http','$modal','FDA_API', function ($scope, $http, $modal, FDA_API) {
// console.log(FDA_API.drugEvent);
function getDrugList() {
$http.get(FDA_API.drugEvent+'?count=patient.drug.medicinalproduct.exact&limit=1000')
.success(function(response) {
var results=response.results;
// console.log(results);
$scope.drugList=results.map(function(item){return item.term.toLowerCase();});
});
}
getDrugList();
// $http.get(FDA_API.drugEvent+"?count=patient.drug.medicinalproduct.exact&limit=1000")
// .success(function(response) {
// var results=response.results;
// console.log(results);
// $scope.drugList=results.map(function(item){return item.term.toLowerCase();});
// console.log($scope.drugList);
// });
$scope.onClick=function() {
if ($scope.selected)
$scope.onSelect($scope.selected, $scope.selected, $scope.selected)
}
$scope.paddingForLabel=0;
$scope.onSelect=function($item, $model, $label) {
// console.log($item, $model, $label);
var maxTextLength=function(a, b) { return Math.max(a, b.label.length);};
var chartValues1;
var chartValues2;
var chartHeight1;
var chartHeight2;
var drug=$item.replace(' ', '+');
var fdaUrl1=FDA_API.drugEvent+'?search=patient.drug.medicinalproduct:"'+drug+'"+AND+serious:1&count=patient.reaction.reactionmeddrapt.exact';
var fdaUrl2=FDA_API.drugEvent+'?search=patient.drug.medicinalproduct:"'+drug+'"+AND+serious:2&count=patient.reaction.reactionmeddrapt.exact';
// console.log(fdaUrl1);
$http.get(fdaUrl1).success(function(response) {
var results=response.results;
// console.log(results);
var resultCount=results.length;
chartHeight1=resultCount*50;
chartValues1=results.map(function(item) {return {"label":item.term.toLowerCase(), "value":Math.floor(item.count)};});
var maxEffectLength=chartValues1.reduce(maxTextLength, 0);
$http.get(fdaUrl2).success(function(response) {
var results=response.results;
// console.log(results);
var resultCount=results.length;
chartHeight2=resultCount*50;
chartValues2=results.map(function(item) {return {"label":item.term.toLowerCase(), "value":Math.floor(item.count)};});
maxEffectLength= chartValues2.reduce(maxTextLength,maxEffectLength);
$scope.chartData[0].values=chartValues1;
// $scope.chartData[0].key="Side Effect Count1";
$scope.chartData[1].values=chartValues2;
// $scope.chartData[1].key="Side Effect Count2";
$scope.chartOptions.chart.height=chartHeight1+chartHeight2;
$scope.chartOptions.title.text="Reported Side Effects Related to "+$item;
if (!$scope.chartConfig.visible)
$scope.chartConfig.visible=true;
});
maxEffectLength=Math.ceil(maxEffectLength*4.7);
if (maxEffectLength>120)
maxEffectLength=120;
$scope.paddingForLabel=maxEffectLength;
});
var labelUrl=FDA_API.drugLabel+'?search=substance_name:"'+drug+'"';
$http.get(labelUrl).success(function(response) {
var results=response.results[0];
console.log(results);
$scope.openFdaLabel=results.openfda;
console.log("openfda");
console.log(results.openfda);
delete results.openfda;
// delete results.set_id;
// delete results.id;
// delete results.effective_time;
$scope.drugLabel=results;
$scope.labelNotFound=undefined;
}).error(function() {
$scope.labelNotFound="No labeling information is found for "+$item;
});
};
$scope.formatLabel=function(val) {
var result;
if (typeof val !=="object")
return val;
for (var i=0; val.length && i<val.length; i++) {
result =result?result+", "+val[i]:val[i];
}
return result?result:val;
};
$scope.chartOptions = {
chart: {
type: 'multiBarHorizontalChart',
height: 450,
x: function(d){return d.label;},
y: function(d){return d.value;},
showControls: false,
showValues: true,
transitionDuration: 500,
valueFormat: function (n){return d3.format(',')(n);},
showYAxis:false,
tooltipContent: function(key, x, y, e, graph){return '<center><span class="tooltipUpper">'+key+'</span><br>'+x+': '+y+'</center>'},
xAxis: {
showMaxMin: false,
margin: {
top:0,
left:0,
bottom:0,
right:100
}
},
yAxis: {
axisLabel: 'Incident Count',
tickFormat: function(d){
return d3.format(',')(d);
},
showMaxMin: false
},
},
title: {
enable: true,
text:'',
class: 'h3'
}
};
$scope.chartConfig={
visible: false
}
$scope.chartData = [
{
"key": 'Serious Incidents',
"color": "#d62728",
"values": [
]
},
{
"key": 'Not Serious Incidents',
"color": "#1f77b4",
"values": [
]
}
];
$scope.open = function (size) {
var modalInstance = $modal.open({
animation: false,
templateUrl: 'aboutModalContent.html',
controller: 'ModalInstanceCtrl',
size: size,
// resolve: {
// items: function () {
// return $scope.items;
// }
// }
});
modalInstance.result.then(function (returned) {
console.log("modal returned="+returned);
console.info("modal closed");
// $('.modal').remove();
// $('body').removeClass('modal-open');
// $('.modal-backdrop').remove();
}, function () {
console.log('Modal dismissed at: ' + new Date());
});
};
}]);
angular.module('adsGtApp').controller('ModalInstanceCtrl', function ($scope, $modalInstance) {
$scope.close = function () {
$modalInstance.close("I am closed");
};
});
| globaltunnels/bowlofhygieia | app/scripts/controllers/drug.js | JavaScript | apache-2.0 | 7,212 |
/*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
| sederaa/gozouk | app/scripts/freelancer.js | JavaScript | apache-2.0 | 196 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 _ from 'lodash';
import {nonEmpty, nonNil} from 'app/utils/lodashMixins';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/first';
import Worker from './decompress.worker';
import SimpleWorkerPool from '../../utils/SimpleWorkerPool';
import maskNull from 'app/core/utils/maskNull';
import {ClusterSecretsManager} from './types/ClusterSecretsManager';
import ClusterLoginService from './components/cluster-login/service';
const State = {
DISCONNECTED: 'DISCONNECTED',
AGENT_DISCONNECTED: 'AGENT_DISCONNECTED',
CLUSTER_DISCONNECTED: 'CLUSTER_DISCONNECTED',
CONNECTED: 'CONNECTED'
};
const IGNITE_2_0 = '2.0.0';
const LAZY_QUERY_SINCE = [['2.1.4-p1', '2.2.0'], '2.2.1'];
const COLLOCATED_QUERY_SINCE = [['2.3.5', '2.4.0'], ['2.4.6', '2.5.0'], '2.5.2'];
// Error codes from o.a.i.internal.processors.restGridRestResponse.java
const SuccessStatus = {
/** Command succeeded. */
STATUS_SUCCESS: 0,
/** Command failed. */
STATUS_FAILED: 1,
/** Authentication failure. */
AUTH_FAILED: 2,
/** Security check failed. */
SECURITY_CHECK_FAILED: 3
};
class ConnectionState {
constructor(cluster) {
this.agents = [];
this.cluster = cluster;
this.clusters = [];
this.state = State.DISCONNECTED;
}
updateCluster(cluster) {
this.cluster = cluster;
this.cluster.connected = !!_.find(this.clusters, {id: this.cluster.id});
return cluster;
}
update(demo, count, clusters) {
_.forEach(clusters, (cluster) => {
cluster.name = cluster.id;
});
this.clusters = clusters;
if (_.isEmpty(this.clusters))
this.cluster = null;
if (_.isNil(this.cluster))
this.cluster = _.head(clusters);
if (nonNil(this.cluster))
this.cluster.connected = !!_.find(clusters, {id: this.cluster.id});
if (count === 0)
this.state = State.AGENT_DISCONNECTED;
else if (demo || _.get(this.cluster, 'connected'))
this.state = State.CONNECTED;
else
this.state = State.CLUSTER_DISCONNECTED;
}
useConnectedCluster() {
if (nonEmpty(this.clusters) && !this.cluster.connected) {
this.cluster = _.head(this.clusters);
this.cluster.connected = true;
this.state = State.CONNECTED;
}
}
disconnect() {
this.agents = [];
if (this.cluster)
this.cluster.disconnect = true;
this.clusters = [];
this.state = State.DISCONNECTED;
}
}
export default class AgentManager {
static $inject = ['$rootScope', '$q', '$transitions', 'igniteSocketFactory', 'AgentModal', 'UserNotifications', 'IgniteVersion', ClusterLoginService.name];
/** @type {ng.IScope} */
$root;
/** @type {ng.IQService} */
$q;
/** @type {ClusterLoginService} */
ClusterLoginSrv;
/** @type {String} */
clusterVersion = '2.4.0';
connectionSbj = new BehaviorSubject(new ConnectionState(AgentManager.restoreActiveCluster()));
/** @type {ClusterSecretsManager} */
clustersSecrets = new ClusterSecretsManager();
pool = new SimpleWorkerPool('decompressor', Worker, 4);
/** @type {Set<ng.IDifferend>} */
promises = new Set();
socket = null;
static restoreActiveCluster() {
try {
return JSON.parse(localStorage.cluster);
}
catch (ignore) {
return null;
}
finally {
localStorage.removeItem('cluster');
}
}
constructor($root, $q, $transitions, socketFactory, AgentModal, UserNotifications, Version, ClusterLoginSrv) {
Object.assign(this, {$root, $q, $transitions, socketFactory, AgentModal, UserNotifications, Version, ClusterLoginSrv});
let prevCluster;
this.currentCluster$ = this.connectionSbj
.distinctUntilChanged(({ cluster }) => prevCluster === cluster)
.do(({ cluster }) => prevCluster = cluster);
if (!this.isDemoMode()) {
this.connectionSbj.subscribe({
next: ({cluster}) => {
const version = _.get(cluster, 'clusterVersion');
if (_.isEmpty(version))
return;
this.clusterVersion = version;
}
});
}
}
isDemoMode() {
return this.$root.IgniteDemoMode;
}
available(...sinceVersion) {
return this.Version.since(this.clusterVersion, ...sinceVersion);
}
connect() {
const self = this;
if (nonNil(self.socket))
return;
self.socket = self.socketFactory();
const onDisconnect = () => {
const conn = self.connectionSbj.getValue();
conn.disconnect();
self.connectionSbj.next(conn);
};
self.socket.on('connect_error', onDisconnect);
self.socket.on('disconnect', onDisconnect);
self.socket.on('agents:stat', ({clusters, count}) => {
const conn = self.connectionSbj.getValue();
conn.update(self.isDemoMode(), count, clusters);
self.connectionSbj.next(conn);
});
self.socket.on('cluster:changed', (cluster) => this.updateCluster(cluster));
self.socket.on('user:notifications', (notification) => this.UserNotifications.notification = notification);
}
saveToStorage(cluster = this.connectionSbj.getValue().cluster) {
try {
localStorage.cluster = JSON.stringify(cluster);
} catch (ignore) {
// No-op.
}
}
updateCluster(newCluster) {
const state = this.connectionSbj.getValue();
const oldCluster = _.find(state.clusters, (cluster) => cluster.id === newCluster.id);
if (!_.isNil(oldCluster)) {
oldCluster.nids = newCluster.nids;
oldCluster.addresses = newCluster.addresses;
oldCluster.clusterVersion = newCluster.clusterVersion;
oldCluster.active = newCluster.active;
this.connectionSbj.next(state);
}
}
switchCluster(cluster) {
const state = this.connectionSbj.getValue();
state.updateCluster(cluster);
this.connectionSbj.next(state);
this.saveToStorage(cluster);
}
/**
* @param states
* @returns {ng.IPromise}
*/
awaitConnectionState(...states) {
const defer = this.$q.defer();
this.promises.add(defer);
const subscription = this.connectionSbj.subscribe({
next: ({state}) => {
if (_.includes(states, state))
defer.resolve();
}
});
return defer.promise
.finally(() => {
subscription.unsubscribe();
this.promises.delete(defer);
});
}
awaitCluster() {
return this.awaitConnectionState(State.CONNECTED);
}
awaitAgent() {
return this.awaitConnectionState(State.CONNECTED, State.CLUSTER_DISCONNECTED);
}
/**
* @param {String} backText
* @param {String} [backState]
* @returns {ng.IPromise}
*/
startAgentWatch(backText, backState) {
const self = this;
self.backText = backText;
self.backState = backState;
const conn = self.connectionSbj.getValue();
conn.useConnectedCluster();
self.connectionSbj.next(conn);
this.modalSubscription && this.modalSubscription.unsubscribe();
self.modalSubscription = this.connectionSbj.subscribe({
next: ({state}) => {
switch (state) {
case State.CONNECTED:
case State.CLUSTER_DISCONNECTED:
this.AgentModal.hide();
break;
case State.AGENT_DISCONNECTED:
this.AgentModal.agentDisconnected(self.backText, self.backState);
break;
default:
// Connection to backend is not established yet.
}
}
});
return self.awaitAgent();
}
/**
* @param {String} backText
* @param {String} [backState]
* @returns {ng.IPromise}
*/
startClusterWatch(backText, backState) {
const self = this;
self.backText = backText;
self.backState = backState;
const conn = self.connectionSbj.getValue();
conn.useConnectedCluster();
self.connectionSbj.next(conn);
this.modalSubscription && this.modalSubscription.unsubscribe();
self.modalSubscription = this.connectionSbj.subscribe({
next: ({state}) => {
switch (state) {
case State.CONNECTED:
this.AgentModal.hide();
break;
case State.AGENT_DISCONNECTED:
this.AgentModal.agentDisconnected(self.backText, self.backState);
break;
case State.CLUSTER_DISCONNECTED:
self.AgentModal.clusterDisconnected(self.backText, self.backState);
break;
default:
// Connection to backend is not established yet.
}
}
});
self.$transitions.onExit({}, () => self.stopWatch());
return self.awaitCluster();
}
stopWatch() {
this.modalSubscription && this.modalSubscription.unsubscribe();
this.promises.forEach((promise) => promise.reject('Agent watch stopped.'));
}
/**
*
* @param {String} event
* @param {Object} [payload]
* @returns {ng.IPromise}
* @private
*/
_sendToAgent(event, payload = {}) {
if (!this.socket)
return this.$q.reject('Failed to connect to server');
const latch = this.$q.defer();
const onDisconnect = () => {
this.socket.removeListener('disconnect', onDisconnect);
latch.reject('Connection to server was closed');
};
this.socket.on('disconnect', onDisconnect);
this.socket.emit(event, payload, (err, res) => {
this.socket.removeListener('disconnect', onDisconnect);
if (err)
return latch.reject(err);
latch.resolve(res);
});
return latch.promise;
}
drivers() {
return this._sendToAgent('schemaImport:drivers');
}
/**
* @param {Object} jdbcDriverJar
* @param {Object} jdbcDriverClass
* @param {Object} jdbcUrl
* @param {Object} user
* @param {Object} password
* @returns {Promise}
*/
schemas({jdbcDriverJar, jdbcDriverClass, jdbcUrl, user, password}) {
const info = {user, password};
return this._sendToAgent('schemaImport:schemas', {jdbcDriverJar, jdbcDriverClass, jdbcUrl, info});
}
/**
* @param {Object} jdbcDriverJar
* @param {Object} jdbcDriverClass
* @param {Object} jdbcUrl
* @param {Object} user
* @param {Object} password
* @param {Object} schemas
* @param {Object} tablesOnly
* @returns {ng.IPromise} Promise on list of tables (see org.apache.ignite.schema.parser.DbTable java class)
*/
tables({jdbcDriverJar, jdbcDriverClass, jdbcUrl, user, password, schemas, tablesOnly}) {
const info = {user, password};
return this._sendToAgent('schemaImport:metadata', {jdbcDriverJar, jdbcDriverClass, jdbcUrl, info, schemas, tablesOnly});
}
/**
* @param {String} event
* @param {Object} params
* @returns {Promise}
* @private
*/
_executeOnCurrentCluster(event, params) {
return this.connectionSbj.first().toPromise()
.then(({cluster}) => {
if (_.isNil(cluster))
throw new Error('Failed to execute request on cluster.');
if (cluster.secured) {
return Promise.resolve(this.clustersSecrets.get(cluster.id))
.then((secrets) => {
if (secrets.hasCredentials())
return secrets;
return this.ClusterLoginSrv.askCredentials(secrets)
.then((secrets) => {
this.clustersSecrets.put(cluster.id, secrets);
return secrets;
});
})
.then((secrets) => ({cluster, credentials: secrets.getCredentials()}));
}
return {cluster, credentials: {}};
})
.then(({cluster, credentials}) => {
return this._sendToAgent(event, {clusterId: cluster.id, params, credentials})
.then((res) => {
const {status = SuccessStatus.STATUS_SUCCESS} = res;
switch (status) {
case SuccessStatus.STATUS_SUCCESS:
if (cluster.secured)
this.clustersSecrets.get(cluster.id).sessionToken = res.sessionToken;
if (res.zipped)
return this.pool.postMessage(res.data);
return res;
case SuccessStatus.STATUS_FAILED:
if (res.error.startsWith('Failed to handle request - unknown session token (maybe expired session)')) {
this.clustersSecrets.get(cluster.id).resetSessionToken();
return this._executeOnCurrentCluster(event, params);
}
throw new Error(res.error);
case SuccessStatus.AUTH_FAILED:
this.clustersSecrets.get(cluster.id).resetCredentials();
throw new Error('Failed to authenticate in cluster with provided credentials');
case SuccessStatus.SECURITY_CHECK_FAILED:
throw new Error('Access denied. You are not authorized to access this functionality. Contact your cluster administrator.');
default:
throw new Error('Illegal status in node response');
}
});
});
}
/**
* @param {Boolean} [attr]
* @param {Boolean} [mtr]
* @returns {Promise}
*/
topology(attr = false, mtr = false) {
return this._executeOnCurrentCluster('node:rest', {cmd: 'top', attr, mtr});
}
/**
* @returns {Promise}
*/
metadata() {
return this._executeOnCurrentCluster('node:rest', {cmd: 'metadata'})
.then((caches) => {
let types = [];
const _compact = (className) => {
return className.replace('java.lang.', '').replace('java.util.', '').replace('java.sql.', '');
};
const _typeMapper = (meta, typeName) => {
const maskedName = _.isEmpty(meta.cacheName) ? '<default>' : meta.cacheName;
let fields = meta.fields[typeName];
let columns = [];
for (const fieldName in fields) {
if (fields.hasOwnProperty(fieldName)) {
const fieldClass = _compact(fields[fieldName]);
columns.push({
type: 'field',
name: fieldName,
clazz: fieldClass,
system: fieldName === '_KEY' || fieldName === '_VAL',
cacheName: meta.cacheName,
typeName,
maskedName
});
}
}
const indexes = [];
for (const index of meta.indexes[typeName]) {
fields = [];
for (const field of index.fields) {
fields.push({
type: 'index-field',
name: field,
order: index.descendings.indexOf(field) < 0,
unique: index.unique,
cacheName: meta.cacheName,
typeName,
maskedName
});
}
if (fields.length > 0) {
indexes.push({
type: 'index',
name: index.name,
children: fields,
cacheName: meta.cacheName,
typeName,
maskedName
});
}
}
columns = _.sortBy(columns, 'name');
if (nonEmpty(indexes)) {
columns = columns.concat({
type: 'indexes',
name: 'Indexes',
cacheName: meta.cacheName,
typeName,
maskedName,
children: indexes
});
}
return {
type: 'type',
cacheName: meta.cacheName || '',
typeName,
maskedName,
children: columns
};
};
for (const meta of caches) {
const cacheTypes = meta.types.map(_typeMapper.bind(null, meta));
if (!_.isEmpty(cacheTypes))
types = types.concat(cacheTypes);
}
return types;
});
}
/**
* @param {String} taskId
* @param {Array.<String>|String} nids
* @param {Array.<Object>} args
*/
visorTask(taskId, nids, ...args) {
args = _.map(args, (arg) => maskNull(arg));
nids = _.isArray(nids) ? nids.join(';') : maskNull(nids);
return this._executeOnCurrentCluster('node:visor', {taskId, nids, args});
}
/**
* @param {String} nid Node id.
* @param {String} cacheName Cache name.
* @param {String} [query] Query if null then scan query.
* @param {Boolean} nonCollocatedJoins Flag whether to execute non collocated joins.
* @param {Boolean} enforceJoinOrder Flag whether enforce join order is enabled.
* @param {Boolean} replicatedOnly Flag whether query contains only replicated tables.
* @param {Boolean} local Flag whether to execute query locally.
* @param {Number} pageSz
* @param {Boolean} [lazy] query flag.
* @param {Boolean} [collocated] Collocated query.
* @returns {Promise}
*/
querySql(nid, cacheName, query, nonCollocatedJoins, enforceJoinOrder, replicatedOnly, local, pageSz, lazy = false, collocated = false) {
if (this.available(IGNITE_2_0)) {
let args = [cacheName, query, nonCollocatedJoins, enforceJoinOrder, replicatedOnly, local, pageSz];
if (this.available(...COLLOCATED_QUERY_SINCE))
args = [...args, lazy, collocated];
else if (this.available(...LAZY_QUERY_SINCE))
args = [...args, lazy];
return this.visorTask('querySqlX2', nid, ...args).then(({error, result}) => {
if (_.isEmpty(error))
return result;
return Promise.reject(error);
});
}
cacheName = _.isEmpty(cacheName) ? null : cacheName;
let queryPromise;
if (enforceJoinOrder)
queryPromise = this.visorTask('querySqlV3', nid, cacheName, query, nonCollocatedJoins, enforceJoinOrder, local, pageSz);
else if (nonCollocatedJoins)
queryPromise = this.visorTask('querySqlV2', nid, cacheName, query, nonCollocatedJoins, local, pageSz);
else
queryPromise = this.visorTask('querySql', nid, cacheName, query, local, pageSz);
return queryPromise
.then(({key, value}) => {
if (_.isEmpty(key))
return value;
return Promise.reject(key);
});
}
/**
* @param {String} nid Node id.
* @param {Number} queryId
* @param {Number} pageSize
* @returns {Promise}
*/
queryNextPage(nid, queryId, pageSize) {
if (this.available(IGNITE_2_0))
return this.visorTask('queryFetchX2', nid, queryId, pageSize);
return this.visorTask('queryFetch', nid, queryId, pageSize);
}
/**
* @param {String} nid Node id.
* @param {String} cacheName Cache name.
* @param {String} [query] Query if null then scan query.
* @param {Boolean} nonCollocatedJoins Flag whether to execute non collocated joins.
* @param {Boolean} enforceJoinOrder Flag whether enforce join order is enabled.
* @param {Boolean} replicatedOnly Flag whether query contains only replicated tables.
* @param {Boolean} local Flag whether to execute query locally.
* @param {Boolean} lazy query flag.
* @param {Boolean} collocated Collocated query.
* @returns {Promise}
*/
querySqlGetAll(nid, cacheName, query, nonCollocatedJoins, enforceJoinOrder, replicatedOnly, local, lazy, collocated) {
// Page size for query.
const pageSz = 1024;
const fetchResult = (acc) => {
if (!acc.hasMore)
return acc;
return this.queryNextPage(acc.responseNodeId, acc.queryId, pageSz)
.then((res) => {
acc.rows = acc.rows.concat(res.rows);
acc.hasMore = res.hasMore;
return fetchResult(acc);
});
};
return this.querySql(nid, cacheName, query, nonCollocatedJoins, enforceJoinOrder, replicatedOnly, local, pageSz, lazy, collocated)
.then(fetchResult);
}
/**
* @param {String} nid Node id.
* @param {Number} [queryId]
* @returns {Promise}
*/
queryClose(nid, queryId) {
if (this.available(IGNITE_2_0)) {
return this.visorTask('queryCloseX2', nid, 'java.util.Map', 'java.util.UUID', 'java.util.Collection',
nid + '=' + queryId);
}
return this.visorTask('queryClose', nid, nid, queryId);
}
/**
* @param {String} nid Node id.
* @param {String} cacheName Cache name.
* @param {String} filter Filter text.
* @param {Boolean} regEx Flag whether filter by regexp.
* @param {Boolean} caseSensitive Case sensitive filtration.
* @param {Boolean} near Scan near cache.
* @param {Boolean} local Flag whether to execute query locally.
* @param {Number} pageSize Page size.
* @returns {Promise}
*/
queryScan(nid, cacheName, filter, regEx, caseSensitive, near, local, pageSize) {
if (this.available(IGNITE_2_0)) {
return this.visorTask('queryScanX2', nid, cacheName, filter, regEx, caseSensitive, near, local, pageSize)
.then(({error, result}) => {
if (_.isEmpty(error))
return result;
return Promise.reject(error);
});
}
/** Prefix for node local key for SCAN near queries. */
const SCAN_CACHE_WITH_FILTER = 'VISOR_SCAN_CACHE_WITH_FILTER';
/** Prefix for node local key for SCAN near queries. */
const SCAN_CACHE_WITH_FILTER_CASE_SENSITIVE = 'VISOR_SCAN_CACHE_WITH_FILTER_CASE_SENSITIVE';
const prefix = caseSensitive ? SCAN_CACHE_WITH_FILTER_CASE_SENSITIVE : SCAN_CACHE_WITH_FILTER;
const query = `${prefix}${filter}`;
return this.querySql(nid, cacheName, query, false, false, false, local, pageSize);
}
/**
* @param {String} nid Node id.
* @param {String} cacheName Cache name.
* @param {String} filter Filter text.
* @param {Boolean} regEx Flag whether filter by regexp.
* @param {Boolean} caseSensitive Case sensitive filtration.
* @param {Boolean} near Scan near cache.
* @param {Boolean} local Flag whether to execute query locally.
* @returns {Promise}
*/
queryScanGetAll(nid, cacheName, filter, regEx, caseSensitive, near, local) {
// Page size for query.
const pageSz = 1024;
const fetchResult = (acc) => {
if (!acc.hasMore)
return acc;
return this.queryNextPage(acc.responseNodeId, acc.queryId, pageSz)
.then((res) => {
acc.rows = acc.rows.concat(res.rows);
acc.hasMore = res.hasMore;
return fetchResult(acc);
});
};
return this.queryScan(nid, cacheName, filter, regEx, caseSensitive, near, local, pageSz)
.then(fetchResult);
}
/**
* Change cluster active state.
*
* @returns {Promise}
*/
toggleClusterState() {
const state = this.connectionSbj.getValue();
const active = !state.cluster.active;
return this.visorTask('toggleClusterState', null, active)
.then(() => state.updateCluster(Object.assign(state.cluster, { active })));
}
hasCredentials(clusterId) {
return this.clustersSecrets.get(clusterId).hasCredentials();
}
}
| irudyak/ignite | modules/web-console/frontend/app/modules/agent/AgentManager.service.js | JavaScript | apache-2.0 | 26,984 |
define(function(){return {"AM":"ܩ.ܛ","PM":"ܒ.ܛ","\/":"\/",":":":","days":{"names":["ܚܕ ܒܫܒܐ","ܬܪܝܢ ܒܫܒܐ","ܬܠܬܐ ܒܫܒܐ","ܐܪܒܥܐ ܒܫܒܐ","ܚܡܫܐ ܒܫܒܐ","ܥܪܘܒܬܐ","ܫܒܬܐ"],"namesAbbr":["ܐ ܒܫ","ܒ ܒܫ","ܓ ܒܫ","ܕ ܒܫ","ܗ ܒܫ","ܥܪܘܒ","ܫܒ"],"namesShort":["ܐ","ܒ","ܓ","ܕ","ܗ","ܥ","ܫ"]},"months":{"names":["ܟܢܘܢ ܐܚܪܝ","ܫܒܛ","ܐܕܪ","ܢܝܣܢ","ܐܝܪ","ܚܙܝܪܢ","ܬܡܘܙ","ܐܒ","ܐܝܠܘܠ","ܬܫܪܝ ܩܕܝܡ","ܬܫܪܝ ܐܚܪܝ","ܟܢܘܢ ܩܕܝܡ",""],"namesAbbr":["ܟܢ ܒ","ܫܒܛ","ܐܕܪ","ܢܝܣܢ","ܐܝܪ","ܚܙܝܪܢ","ܬܡܘܙ","ܐܒ","ܐܝܠܘܠ","ܬܫ ܐ","ܬܫ ܒ","ܟܢ ܐ",""]},"patterns":{"D":"dd MMMM, yyyy","T":"hh:mm:ss tt","d":"dd\/MM\/yyyy","t":"hh:mm tt"}}}); | appcelerator/titanium_mobile_tizen | titanium/Ti/_/Locale/Calendar/syr.js | JavaScript | apache-2.0 | 816 |
export function getScreenBrightness () {
return {
errMsg: 'getScreenBrightness:ok',
value: plus.screen.getBrightness(false)
}
}
export function setScreenBrightness ({
value
} = {}) {
plus.screen.setBrightness(value, false)
return {
errMsg: 'setScreenBrightness:ok'
}
}
export function setKeepScreenOn ({
keepScreenOn
} = {}) {
plus.device.setWakelock(!!keepScreenOn)
return {
errMsg: 'setKeepScreenOn:ok'
}
}
| dcloudio/uni-app | src/platforms/app-plus/service/api/device/brightness.js | JavaScript | apache-2.0 | 471 |
//
// Copyright (c) Microsoft and contributors. 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.
//
var assert = require('assert');
// Test includes
var testutil = require('../../util/util');
var queuetestutil = require('../../framework/queue-test-utils');
// Lib includes
var azure = testutil.libRequire('azure');
var azureutil = testutil.libRequire('common/lib/util/util');
var Constants = azure.Constants;
var ServiceClientConstants = azure.ServiceClientConstants;
var HttpConstants = Constants.HttpConstants;
var queueService;
var queueNames = [];
var queueNamesPrefix = 'queue';
var testPrefix = 'queueservice-tests';
var tableService;
var suiteUtil;
suite('queueservice-tests', function () {
suiteSetup(function (done) {
queueService = azure.createQueueService()
.withFilter(new azure.ExponentialRetryPolicyFilter());
suiteUtil = queuetestutil.createQueueTestUtils(queueService, testPrefix);
suiteUtil.setupSuite(done);
});
suiteTeardown(function (done) {
suiteUtil.teardownSuite(done);
});
setup(function (done) {
suiteUtil.setupTest(done);
});
teardown(function (done) {
suiteUtil.teardownTest(done);
});
test('GetServiceProperties', function (done) {
queueService.getServiceProperties(function (error, serviceProperties) {
assert.equal(error, null);
assert.notEqual(serviceProperties, null);
if (serviceProperties) {
assert.notEqual(serviceProperties.Logging, null);
if (serviceProperties.Logging) {
assert.notEqual(serviceProperties.Logging.RetentionPolicy);
assert.notEqual(serviceProperties.Logging.Version);
}
if (serviceProperties.Metrics) {
assert.notEqual(serviceProperties.Metrics, null);
assert.notEqual(serviceProperties.Metrics.RetentionPolicy);
assert.notEqual(serviceProperties.Metrics.Version);
}
}
done();
});
});
test('SetServiceProperties', function (done) {
queueService.getServiceProperties(function (error, serviceProperties) {
assert.equal(error, null);
serviceProperties.Logging.Read = true;
queueService.setServiceProperties(serviceProperties, function (error2) {
assert.equal(error2, null);
queueService.getServiceProperties(function (error3, serviceProperties2) {
assert.equal(error3, null);
assert.equal(serviceProperties2.Logging.Read, true);
done();
});
});
});
});
test('CreateQueue', function (done) {
var queueName = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
var metadata = { 'class': 'test' };
// Create
queueService.createQueue(queueName, { metadata: metadata }, function (createError, queue, createResponse) {
assert.equal(createError, null);
assert.notEqual(queue, null);
assert.ok(createResponse.isSuccessful);
assert.equal(createResponse.statusCode, HttpConstants.HttpResponseCodes.Created);
assert.ok(queue);
if (createResponse.queue) {
assert.ok(queue.name);
assert.equal(queue.name, queueName);
assert.ok(queue.metadata);
assert.equal(queue.metadata['class'], metadata['class']);
}
// Get
queueService.getQueueMetadata(queueName, function (getError, getQueue, getResponse) {
assert.equal(getError, null);
assert.ok(getResponse.isSuccessful);
assert.equal(getResponse.statusCode, HttpConstants.HttpResponseCodes.Ok);
assert.ok(getQueue);
if (getQueue) {
assert.ok(getQueue.name);
assert.equal(getQueue.name, queueName);
assert.ok(getQueue.metadata);
assert.equal(getQueue.metadata['class'], metadata['class']);
}
// Delete
queueService.deleteQueue(queueName, function (deleteError, deleted, deleteResponse) {
assert.equal(deleteError, null);
assert.equal(deleted, true);
assert.ok(deleteResponse.isSuccessful);
assert.equal(deleteResponse.statusCode, HttpConstants.HttpResponseCodes.NoContent);
done();
});
});
});
});
test('CreateQueueIfNotExists', function (done) {
var queueName = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
var metadata = { 'class': 'test' };
// Create
queueService.createQueue(queueName, { metadata: metadata }, function (createError, queue, createResponse) {
assert.equal(createError, null);
assert.notEqual(queue, null);
assert.ok(createResponse.isSuccessful);
assert.equal(createResponse.statusCode, HttpConstants.HttpResponseCodes.Created);
assert.ok(queue);
if (createResponse.queue) {
assert.ok(queue.name);
assert.equal(queue.name, queueName);
assert.ok(queue.metadata);
assert.equal(queue.metadata['class'], metadata['class']);
}
// Try creating again
queueService.createQueueIfNotExists(queueName, { metadata: metadata }, function (createError2, queueCreated2) {
assert.equal(createError2, null);
assert.equal(queueCreated2, false);
done();
});
});
});
test('ListQueues', function (done) {
var queueName1 = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
var queueName2 = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
var metadata = { 'class': 'test' };
queueService.listQueues({ 'include': 'metadata' }, function (listErrorEmpty, queuesEmpty) {
assert.equal(listErrorEmpty, null);
assert.notEqual(queuesEmpty, null);
if (queuesEmpty) {
assert.equal(queuesEmpty.length, 0);
}
queueService.createQueue(queueName1, function (createError1, queue1, createResponse1) {
assert.equal(createError1, null);
assert.notEqual(queue1, null);
assert.ok(createResponse1.isSuccessful);
assert.equal(createResponse1.statusCode, HttpConstants.HttpResponseCodes.Created);
queueService.createQueue(queueName2, { metadata: metadata }, function (createError2, queue2, createResponse2) {
assert.equal(createError2, null);
assert.notEqual(queue2, null);
assert.ok(createResponse2.isSuccessful);
assert.equal(createResponse2.statusCode, HttpConstants.HttpResponseCodes.Created);
queueService.listQueues({ 'include': 'metadata' }, function (listError, queues, nextMarker, listResponse) {
assert.equal(listError, null);
assert.notEqual(queues, null);
assert.ok(listResponse.isSuccessful);
assert.equal(listResponse.statusCode, HttpConstants.HttpResponseCodes.Ok);
assert.ok(queues);
var entries = 0;
for (var queue in queues) {
var currentQueue = queues[queue];
if (currentQueue.name === queueName1) {
entries += 1;
}
else if (currentQueue.name === queueName2) {
entries += 2;
assert.equal(currentQueue.metadata['class'], metadata['class']);
}
}
assert.equal(entries, 3);
done();
});
});
});
});
});
test('CreateMessage', function (done) {
var queueName = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
var messageText1 = 'hi there';
var messageText2 = 'bye there';
// Create Queue
queueService.createQueue(queueName, function (createError1, queue1, createResponse1) {
assert.equal(createError1, null);
assert.notEqual(queue1, null);
assert.ok(createResponse1.isSuccessful);
assert.equal(createResponse1.statusCode, HttpConstants.HttpResponseCodes.Created);
// Create message
queueService.createMessage(queueName, messageText1, function (createMessageError, message, createMessageResponse) {
assert.equal(createMessageError, null);
assert.ok(createMessageResponse.isSuccessful);
assert.equal(createMessageResponse.statusCode, HttpConstants.HttpResponseCodes.Created);
// Create another message
queueService.createMessage(queueName, messageText2, function (createMessageError2, message2, createMessageResponse2) {
assert.equal(createMessageError, null);
assert.ok(createMessageResponse2.isSuccessful);
assert.equal(createMessageResponse2.statusCode, HttpConstants.HttpResponseCodes.Created);
// Peek message
queueService.peekMessages(queueName, function (peekError, queueMessages, peekResponse) {
assert.equal(peekError, null);
assert.notEqual(queueMessages, null);
var queueMessage = queueMessages[0];
if (queueMessage) {
assert.ok(queueMessage['messageid']);
assert.ok(queueMessage['insertiontime']);
assert.ok(queueMessage['expirationtime']);
assert.equal(queueMessage.messagetext, messageText1);
}
assert.ok(peekResponse.isSuccessful);
assert.equal(peekResponse.statusCode, HttpConstants.HttpResponseCodes.Ok);
// Get messages
queueService.getMessages(queueName, function (getError, getQueueMessages, getResponse) {
assert.equal(getError, null);
assert.notEqual(getQueueMessages, null);
assert.equal(getQueueMessages.length, 1);
assert.ok(getResponse.isSuccessful);
assert.equal(getResponse.statusCode, HttpConstants.HttpResponseCodes.Ok);
var getQueueMessage = getQueueMessages[0];
assert.equal(getQueueMessage.messagetext, messageText1);
// Delete message
queueService.deleteMessage(queueName, getQueueMessage.messageid, getQueueMessage.popreceipt, function (deleteError, deleted, deleteResponse) {
assert.equal(deleteError, null);
assert.equal(deleted, true);
assert.ok(deleteResponse.isSuccessful);
assert.equal(deleteResponse.statusCode, HttpConstants.HttpResponseCodes.NoContent);
// Get messages again
queueService.getMessages(queueName, function (getError2, getQueueMessages2, getResponse2) {
assert.equal(getError2, null);
assert.notEqual(getQueueMessages2, null);
assert.ok(getResponse2.isSuccessful);
assert.equal(getResponse2.statusCode, HttpConstants.HttpResponseCodes.Ok);
var getQueueMessage2 = getQueueMessages2[0];
assert.equal(getQueueMessage2.messagetext, messageText2);
// Clear messages
queueService.clearMessages(queueName, function (clearError, clearResponse) {
assert.equal(clearError, null);
assert.ok(clearResponse.isSuccessful);
assert.equal(clearResponse.statusCode, HttpConstants.HttpResponseCodes.NoContent);
// Get message again should yield empty
queueService.getMessages(queueName, function (getError3, getQueueMessage3, getResponse3) {
assert.equal(getError3, null);
assert.ok(getResponse3.isSuccessful);
assert.equal(getResponse3.statusCode, HttpConstants.HttpResponseCodes.Ok);
assert.equal(getQueueMessage3.length, 0);
done();
});
});
});
});
});
});
});
});
});
});
test('CreateEmptyMessage', function (done) {
var queueName = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
// Create Queue
queueService.createQueue(queueName, function (createError1) {
assert.equal(createError1, null);
// Create message
queueService.createMessage(queueName, '', function (createMessageError, message, createMessageResponse) {
assert.equal(createMessageError, null);
assert.equal(createMessageResponse.statusCode, HttpConstants.HttpResponseCodes.Created);
done();
});
});
});
test('SetQueueMetadataName', function (done) {
var queueName = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
var metadata = { '\Uc8fc\Uba39\Uc774\Uc6b4\Ub2e4': 'test' };
queueService.createQueue(queueName, function (createError) {
assert.equal(createError, null);
// unicode headers are valid
queueService.setQueueMetadata(queueName, metadata, function (setError) {
assert.equal(setError, null);
done();
});
});
});
test('SetQueueMetadata', function (done) {
var queueName = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
var metadata = { 'class': 'test' };
queueService.createQueue(queueName, function (createError) {
assert.equal(createError, null);
queueService.setQueueMetadata(queueName, metadata, function (setError) {
assert.equal(setError, null);
queueService.getQueueMetadata(queueName, function (getError, queue) {
assert.equal(getError, null);
assert.notEqual(queue, null);
if (queue) {
assert.notEqual(queue.metadata, null);
assert.equal(queue.metadata.class, 'test');
done();
}
});
});
});
});
test('GetMessages', function (done) {
var queueName = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
queueService.createQueue(queueName, function (createError) {
assert.equal(createError, null);
queueService.getMessages(queueName, function (error, emptyMessages) {
assert.equal(error, null);
assert.notEqual(emptyMessages, null);
assert.equal(emptyMessages.length, 0);
queueService.createMessage(queueName, 'msg1', function (error1) {
assert.equal(error1, null);
queueService.createMessage(queueName, 'msg2', function (error2) {
assert.equal(error2, null);
queueService.getMessages(queueName, { peekonly: true }, function (error3, messages) {
assert.equal(error3, null);
assert.notEqual(messages, null);
if (messages) {
// By default only one is returned
assert.equal(messages.length, 1);
assert.equal(messages[0].messagetext, 'msg1');
}
queueService.getMessages(queueName, { numofmessages: 2 }, function (error4, messages2) {
assert.equal(error4, null);
assert.notEqual(messages2, null);
if (messages2) {
assert.equal(messages2.length, 2);
}
done();
});
});
});
});
});
});
});
test('UpdateMessage', function (done) {
var queueName = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
queueService.createQueue(queueName, function (error) {
assert.equal(error, null);
queueService.createMessage(queueName, 'hi there', function (error2) {
assert.equal(error2, null);
queueService.getMessages(queueName, function (error3, messages) {
assert.equal(error2, null);
assert.notEqual(messages, null);
var message = messages[0];
queueService.updateMessage(queueName, message.messageid, message.popreceipt, 10, { messagetext: 'bye there' }, function (error4) {
assert.equal(error4, null);
done();
});
});
});
});
});
test('UpdateMessageEncodingPopReceipt', function (done) {
var queueName = testutil.generateId(queueNamesPrefix, queueNames, suiteUtil.isMocked);
// no messages in the queue try to update a message should give fail to update instead of blowing up on authentication
queueService.updateMessage(queueName, 'mymsg', 'AgAAAAEAAACucgAAvMW8+dqjzAE=', 10, { messagetext: 'bye there' }, function (error) {
assert.notEqual(error, null);
assert.equal(error.code, Constants.QueueErrorCodeStrings.QUEUE_NOT_FOUND);
done();
});
});
test('storageConnectionStrings', function (done) {
var key = 'AhlzsbLRkjfwObuqff3xrhB2yWJNh1EMptmcmxFJ6fvPTVX3PZXwrG2YtYWf5DPMVgNsteKStM5iBLlknYFVoA==';
var connectionString = 'DefaultEndpointsProtocol=https;AccountName=myaccount;AccountKey=' + key;
var queueService = azure.createQueueService(connectionString);
assert.equal(queueService.storageAccount, 'myaccount');
assert.equal(queueService.storageAccessKey, key);
assert.equal(queueService.protocol, 'https:');
done();
});
test('storageConnectionStringsDevStore', function (done) {
var connectionString = 'UseDevelopmentStorage=true';
var queueService = azure.createQueueService(connectionString);
assert.equal(queueService.storageAccount, ServiceClientConstants.DEVSTORE_STORAGE_ACCOUNT);
assert.equal(queueService.storageAccessKey, ServiceClientConstants.DEVSTORE_STORAGE_ACCESS_KEY);
assert.equal(queueService.protocol, 'http:');
assert.equal(queueService.host, '127.0.0.1');
assert.equal(queueService.port, '10001');
done();
});
});
| jmspring/azure-sdk-for-node | test/services/queue/queueservice-tests.js | JavaScript | apache-2.0 | 18,029 |
App.source = {
controllers : {},
models : {}
};
App.source.controllers.repository = {
/**
* Add repository
*/
add : function() {
$(document).ready(function() {
App.source.AddEditForm.init();
});
},
/**
* Edit repository
*/
edit : function() {
$(document).ready(function() {
App.source.AddEditForm.init();
});
},
/**
* History page behaviour
*/
history : function() {
$(document).ready(function() {
$('tr.commit div.commit_files').hide(); // hide all paths on page load
$('#toggle_all_paths span').text(App.lang('Show all paths')); // set initial text
// show/hide one
$('tr.commit').each(function() {
var wrapper = $(this);
wrapper.find('a.toggle_files').click(function() {
wrapper.find('div.commit_files').toggle();
return false;
});
}); // show/hide one
$('#repository_delete_page_action').click(function() {
return confirm(App.lang('Are you sure that you wish to delete this repository from activeCollab?'));
});
// show/hide all
var toggle_new_class = null;
var link_text = null;
$('#toggle_all_paths').click(function() {
var toggle_button = $(this);
if (toggle_button.is('.hide')) {
$('tr.commit div.commit_files').hide();
link_text = App.lang('Show all paths');
toggle_button.removeClass('hide');
toggle_button.addClass('show');
}
else {
$('tr.commit div.commit_files').show();
link_text = App.lang('Hide all paths');
toggle_button.removeClass('show');
toggle_button.addClass('hide');
}
$('span', toggle_button).text(link_text);
return false;
}); //show/hide all
// Update repository
/*
$('#repository_ajax_update, a.repository_ajax_update').click(function() {
var delimiter = App.data.path_info_through_query_string ? '&' : '?';
App.ModalDialog.show('repository_update', App.lang('Repository update'), $('<p><img src="' + App.data.assets_url + '/images/indicator.gif" alt="" /> ' + App.lang('Checking for updates...') + '</p>').load($(this).attr('href')+ delimiter + 'skip_layout=1&async=1'), {
buttons : false,
width: 400
});
return false;
});
*/
});
}, // history
update : function() {
progress_div = $('#repository_update_progress');
var delimiter = App.data.path_info_through_query_string ? '&' : '?';
var notify_subscribers = function(total_commits) {
$('#progress_content').append('<p class="subscribers"><img src="' + App.data.assets_url + '/images/indicator.gif" alt="" /> ' + App.lang('Sending subscriptions...') + ' </p>');
$.ajax({
url: App.data.repository_update_url + delimiter + 'async=1¬ify=' + total_commits,
type: 'GET',
success : function(response) {
$('#progress_content p.subscribers img').attr({
'src' : App.data.assets_url + '/images/ok_indicator.gif'
});
$('#progress_content p.subscribers').append(App.lang('Done!'));
}
});
}
var get_logs = function(commit, total_commits) {
progress_content = $('#progress_content');
progress_content.html('<p><img src="' + App.data.assets_url + '/images/indicator.gif" alt="" /> Importing commit #' + commit + '</p>');
$.ajax( {
url: App.data.repository_update_url + delimiter + 'r=' + commit + '&async=1&skip_missing_revisions=1',
type: 'GET',
success : function(response) {
if (response == 'success') {
if (commit !== App.data.repository_head_revision) {
commit++;
get_logs(commit, total_commits);
}
else {
progress_content.html('<p><img src="' + App.data.assets_url + '/images/ok_indicator.gif" alt="" /> '+ App.lang('Repository successfully updated') + '</p>');
notify_subscribers(total_commits);
}
}
else {
progress_content.html(response); // if not success, reponse is a svn error message
}
}
});
}
if (App.data.repository_uptodate == 1) {
progress_div.html('<p><img src="' + App.data.assets_url + '/images/ok_indicator.gif" alt="" /> '+ App.lang('Repository is already up-to-date') + '</p>');
}
else {
total_commits = App.data.repository_head_revision - App.data.repository_last_revision;
commit = App.data.repository_last_revision+1;
if (total_commits > 0) {
progress_div.prepend('<p>There are new commits, please wait until the repository gets updated to revision #'+App.data.repository_head_revision+'</p>');
get_logs(commit, total_commits);
}
else {
progress_div.prepend('<p>' + App.lang('Error getting new commits') + ':</p>');
}
}
}, // update
browse : function() {
$(document).ready(function () {
App.widgets.SourceFilePages.init();
$('a.source_item_info').each(function() {
var link_obj = $(this);
link_obj.click(function() {
App.ModalDialog.show('item_info', App.lang('Item info'), $('<p><img src="' + App.data.assets_url + '/images/indicator.gif" alt="" /> ' + App.lang('Fetching data...') + '</p>').load(link_obj.attr('href')), {
buttons : false,
width: 700
});
return false;
});
}); // show/hide one
})
}, // browse
repository_users : function() {
$(document).ready(function () {
var select_box = $('#repository_user');
$('table.mapped_users').find('a.remove_source_user').click(function() {
if (confirm(App.lang('Are you sure that you wish to delete remove this mapping?'))) {
var link = $(this);
var img = link.find('img');
var old_src = img.attr('src');
img.attr('src', App.data.indicator_url);
$.ajax({
url : App.extendUrl(link.attr('href'), {'async' : 1}),
type : 'POST',
data : {'submitted' : 'submitted', 'repository_user' : link.attr('name')},
success : function(response) {
if (response == 'true') {
link.parent().parent().remove();
select_box.append('<option value="'+link.attr('name')+'">'+link.attr('name')+'</option>');
$('#all_mapped').hide();
$('#no_users').hide();
$('#new_record').show();
if ($('#records tbody').children().length == 0) {
$('#records').hide();
}
} else {
img.attr('src', old_src);
}
}
});
}
return false;
});
var form = $('form.map_user_form');
form.attr('action', App.extendUrl(form.attr('action'), { async : 1 }));
form.submit(function() {
if ($('#user_id').find('option:selected').val() == '') {
alert(App.lang('Please select activeCollab user'));
return false;
}
var form = $(this);
$('#new_record td.actions').prepend('<img src="' + App.data.indicator_url + '" alt="" />').find('button').hide();
$(this).ajaxSubmit({
success: function(responseText) {
$('#records tbody').prepend(responseText);
$('#records').show();
$('#new_record td.actions').find('img').remove();
$('#new_record td.actions').find('button').show();
var new_row = $('#records tbody tr:first');
new_row.find('td').highlightFade();
select_box.find('option:selected').remove();
if (select_box.children().length == 0) {
$('#new_record').hide();
$('#all_mapped').show();
}
},
error : function() {
$('#new_record td.actions').find('img').remove();
$('#new_record td.actions').find('button').show();
}
});
return false;
});
});
}
};
/**
* Javascript for source administration
*/
App.source.controllers.source_admin = {
index : function () {
$(document).ready(function () {
var test_results_div = $(this).find('.test_results');
var test_div = test_results_div.parent();
test_results_div.prepend('<img class="source_results_img" src="" alt=""/>');
$('.source_results_img').hide();
$('#check_svn_path button:eq(0)').click(function () {
$('.source_results_img').show();
var svn_path = $('#svn_path').val();
var indicator_img = $('.source_results_img');
var result_span = test_div.find('.test_results span:eq(0)');
indicator_img.attr('src', App.data.indicator_url);
result_span.html('');
$.ajax({
type: "GET",
data: "svn_path=" + svn_path,
url: App.data.test_svn_url,
success: function(msg){
if (msg=='true') {
indicator_img.attr('src', App.data.ok_indicator_url);
result_span.html(App.lang('Subversion executable found'));
} else {
indicator_img.attr('src', App.data.error_indicator_url);
result_span.html(App.lang('Error accessing SVN executable') + ': ' + msg);
} // if
}
});
});
});
}
};
/**
* Init JS functions for source file pages
*/
App.widgets.SourceFilePages = function () {
return {
init : function () {
var delimiter = '&';
$('#object_quick_option_compare a').click(function () {
var compared_revision = parseInt(prompt(App.lang('Enter revision number'), ""));
if (isNaN(compared_revision)) {
alert(App.lang('Please insert a revision number'));
} else {
window.location = App.data.compare_url + delimiter + 'compare_to=' + compared_revision + 'peg=' + App.data.active_revision;
} // if
return false;
});
$('#change_revision').click(function () {
var new_revision = parseInt(prompt(App.lang('Enter new revision number'), ""));
if (isNaN(new_revision)) {
alert(App.lang('Please insert a revision number'));
} else {
window.location = App.data.browse_url + delimiter + 'r=' + new_revision + delimiter + 'peg=' + App.data.active_revision;
} // if
return false;
});
}
}
} ();
/**
* Test repository connection
*/
App.source.AddEditForm = function() {
return {
init : function () {
var result_container = $('#test_connection .test_connection_results');
var result_image = $('img:eq(0)', result_container);
var result_output = $('span:eq(0)', result_container);
$('#test_connection button').click(function () {
result_output.html(App.lang('Checking...'));
result_image.attr('src', App.data.indicator_url);
if ($('#repositoryUrl').attr('value') == undefined) {
result_image.attr('src', App.data.error_indicator_url);
result_output.html(App.lang('You need to enter repository URL first'));
}
else {
var delimiter = App.data.path_info_through_query_string ? '&' : '?';
$.ajax( {
url: App.data.repository_test_connection_url + delimiter + 'url=' + $('#repositoryUrl').attr('value') + '&user=' + $('#repositoryUsername').attr('value') + '&pass=' + $('#repositoryPassword').attr('value') + '&engine=' + $('#repositoryType option:selected').attr('value'),
type: 'GET',
success : function(response) {
if (response == 'ok') {
result_image.attr('src', App.data.ok_indicator_url);
result_output.html(App.lang('Connection parameters are valid'));
}
else {
result_image.attr('src', App.data.error_indicator_url);
result_output.html(App.lang('Could not connect to repository:') + ' ' + response); // if not success, reponse is a svn error message
}
}
});
}
});
}
};
} (); | hammadalinaqvi/bookstoregenie | projMan/public/assets/modules/source/javascript/main.js | JavaScript | apache-2.0 | 12,557 |
var show = require('./demo10');
show('hh')
| fanbrightup/firsthalf2017 | feb/2-18/test.js | JavaScript | apache-2.0 | 43 |
function changeThemeFun(themeName) {/* 更换主题 */
//alert(themeName);
var $easyuiTheme = $('#easyuiTheme');
var url = $easyuiTheme.attr('href');
var href = url.substring(0, url.indexOf('themes')) + 'themes/' + themeName + '/easyui.css';
//alert(url);
$easyuiTheme.attr('href', href);
var $iframe = $('iframe');
//setInterval(show,3000);// 注意函数名没有引号和括弧!
//alert(href);
//alert($iframe.length);
//setTimeout(function(){
//在这里执行你的代码
//},500);
if ($iframe.length > 0) {
for ( var i = 0; i < $iframe.length; i++) {
var ifr = $iframe[i];
//alert($(ifr).contents().find('#easyuiTheme'));
$(ifr).contents().find('#easyuiTheme').attr('href', href);
}
}
$.cookie('easyuiThemeName', themeName, {
expires : 7
});
};
if ($.cookie('easyuiThemeName')) {
//火狐下不用延迟加载会有问题
setTimeout(function(){
//在这里执行你的代码
changeThemeFun($.cookie('easyuiThemeName'));
},500);
} | zhgo116/fancy | Fancy/src/main/webapp/ui/changeEasyuiTheme.js | JavaScript | apache-2.0 | 1,014 |
cordova.define("nl.x-services.plugins.toast.tests", function(require, exports, module) { exports.defineAutoTests = function() {
var fail = function (done) {
expect(true).toBe(false);
done();
},
succeed = function (done) {
expect(true).toBe(true);
done();
};
describe('Plugin availability', function () {
it("window.plugins.toast should exist", function() {
expect(window.plugins.toast).toBeDefined();
});
});
describe('API functions', function () {
it("should define show", function() {
expect(window.plugins.toast.show).toBeDefined();
});
it("should define showShortTop", function() {
expect(window.plugins.toast.showShortTop).toBeDefined();
});
it("should define showShortCenter", function() {
expect(window.plugins.toast.showShortCenter).toBeDefined();
});
it("should define showShortBottom", function() {
expect(window.plugins.toast.showShortBottom).toBeDefined();
});
it("should define showLongTop", function() {
expect(window.plugins.toast.showLongTop).toBeDefined();
});
it("should define showLongCenter", function() {
expect(window.plugins.toast.showLongCenter).toBeDefined();
});
it("should define showLongBottom", function() {
expect(window.plugins.toast.showLongBottom).toBeDefined();
});
});
describe('Invalid usage', function () {
it("should fail due to an invalid position", function(done) {
window.plugins.toast.show('hi', 'short', 'nowhere', fail.bind(null, done), succeed.bind(null, done));
});
it("should fail due to an invalid duration", function(done) {
window.plugins.toast.show('hi', 'medium', 'top', fail.bind(null, done), succeed.bind(null, done));
});
});
};
});
| digitalunity/wbtest | platforms/windows/www/plugins/nl.x-services.plugins.toast/test/tests.js | JavaScript | apache-2.0 | 1,779 |
/*
Copyright 2014 Joukou Ltd
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 GraphStateModel, Model, Q, schema;
schema = require('./schema');
Model = require('../../../../lib/Model');
Q = require('q');
GraphStateModel = Model.define({
schema: schema,
type: 'graph_state',
bucket: 'graph_state'
});
GraphStateModel.retrieveForGraph = function(agentKey, graphKey) {
return GraphStateModel.search("agent_key:" + agentKey + " graph_key:" + graphKey, {
firstOnly: true
});
};
GraphStateModel.put = function(agentKey, graphKey, state) {
var data, deferred, numberOr, save;
if (state == null) {
state = {};
}
deferred = Q.defer();
save = function(model) {
return model.save().then(function() {
return deferred.resolve(model);
}).fail(deferred.reject);
};
numberOr = function(number, other) {
if (typeof number !== 'number') {
return other;
}
if (isNaN(number)) {
return other;
}
return number;
};
data = {
agent_key: agentKey,
graph_key: graphKey,
x: numberOr(state.x, 0),
y: numberOr(state.y, 0),
scale: numberOr(state.scale, 1),
metadata: state.metadata || {}
};
GraphStateModel.retrieveForGraph(agentKey, graphKey).then(function(model) {
model.setValue(data);
return save(model);
}).fail(function() {
return GraphStateModel.create(data).then(save).fail(deferred.reject);
});
return deferred.promise;
};
GraphStateModel.afterCreate = function(model) {
model.afterRetrieve();
return Q.resolve(model);
};
GraphStateModel.prototype.beforeSave = function() {};
GraphStateModel.prototype.afterRetrieve = function() {
this.addSecondaryIndex('agent_key_bin');
return this.addSecondaryIndex('graph_key_bin');
};
module.exports = GraphStateModel;
/*
//# sourceMappingURL=index.js.map
*/
| joukou/joukou-data | dist/models/agent/graph/state/index.js | JavaScript | apache-2.0 | 2,304 |
'use strict';
var JpipStructureParser = function JpipStructureParserClosure(
databinsSaver, markersParser, messageHeaderParser, offsetsCalculator) {
this.parseCodestreamStructure = function parseCodestreamStructure() {
// A.5.1 (Image and Tile Size)
var bytes = [];
var mainHeaderDatabin = databinsSaver.getMainHeaderDatabin();
var sizMarkerOffset = offsetsCalculator.getImageAndTileSizeOffset();
var bytes = getBytes(
mainHeaderDatabin,
/*numBytes=*/38,
sizMarkerOffset + j2kOffsets.MARKER_SIZE + j2kOffsets.LENGTH_FIELD_SIZE);
var referenceGridSizeOffset =
j2kOffsets.REFERENCE_GRID_SIZE_OFFSET_AFTER_SIZ_MARKER -
(j2kOffsets.MARKER_SIZE + j2kOffsets.LENGTH_FIELD_SIZE);
var numComponentsOffset =
j2kOffsets.NUM_COMPONENTS_OFFSET_AFTER_SIZ_MARKER -
(j2kOffsets.MARKER_SIZE + j2kOffsets.LENGTH_FIELD_SIZE);
var referenceGridSizeX = messageHeaderParser.getInt32(
bytes, referenceGridSizeOffset); // XSiz
var referenceGridSizeY = messageHeaderParser.getInt32(
bytes, referenceGridSizeOffset + 4); // YSiz
var imageOffsetX = messageHeaderParser.getInt32(bytes, 10); // XOSiz
var imageOffsetY = messageHeaderParser.getInt32(bytes, 14); // YOSiz
var tileSizeX = messageHeaderParser.getInt32(bytes, 18); // XTSiz
var tileSizeY = messageHeaderParser.getInt32(bytes, 22); // YTSiz
var firstTileOffsetX = messageHeaderParser.getInt32(bytes, 26); // XTOSiz
var firstTileOffsetY = messageHeaderParser.getInt32(bytes, 30); // YTOSiz
var numComponents = messageHeaderParser.getInt16(bytes, numComponentsOffset); // CSiz
var componentsDataOffset =
sizMarkerOffset + j2kOffsets.NUM_COMPONENTS_OFFSET_AFTER_SIZ_MARKER + 2;
var componentsDataLength = numComponents * 3;
var componentsDataBytes = getBytes(
mainHeaderDatabin, componentsDataLength, componentsDataOffset);
var componentsScaleX = new Array(numComponents);
var componentsScaleY = new Array(numComponents);
for (var i = 0; i < numComponents; ++i) {
componentsScaleX[i] = componentsDataBytes[i * 3 + 1];
componentsScaleY[i] = componentsDataBytes[i * 3 + 2];
}
var result = {
numComponents: numComponents,
componentsScaleX: componentsScaleX,
componentsScaleY: componentsScaleY,
imageWidth: referenceGridSizeX - firstTileOffsetX,
imageHeight: referenceGridSizeY - firstTileOffsetY,
tileWidth: tileSizeX,
tileHeight: tileSizeY,
firstTileOffsetX: firstTileOffsetX,
firstTileOffsetY: firstTileOffsetY
};
return result;
};
this.parseDefaultTileParams = function() {
var mainHeaderDatabin = databinsSaver.getMainHeaderDatabin();
var tileParams = parseCodingStyle(mainHeaderDatabin, /*isMandatory=*/true);
return tileParams;
};
this.parseOverridenTileParams = function(tileIndex) {
var tileHeaderDatabin = databinsSaver.getTileHeaderDatabin(tileIndex);
// A.4.2 (Start Of Tile-part)
var tileParams = parseCodingStyle(tileHeaderDatabin, /*isMandatory=*/false);
return tileParams;
};
function parseCodingStyle(databin, isMandatory) {
// A.5.1 (Image and Tile Size)
var baseParams = offsetsCalculator.getCodingStyleBaseParams(
databin, isMandatory);
if (baseParams === null) {
return null;
}
var mainHeaderDatabin = databinsSaver.getMainHeaderDatabin();
var sizMarkerOffset = offsetsCalculator.getImageAndTileSizeOffset();
var numComponentsOffset =
sizMarkerOffset + j2kOffsets.NUM_COMPONENTS_OFFSET_AFTER_SIZ_MARKER;
var numComponentsBytes = getBytes(
mainHeaderDatabin,
/*numBytes=*/2,
/*startOffset=*/numComponentsOffset);
var numComponents = messageHeaderParser.getInt16(numComponentsBytes, 0);
var packedPacketHeadersMarkerInTileHeader =
markersParser.getMarkerOffsetInDatabin(
databin, j2kMarkers.PackedPacketHeadersInTileHeader);
var packedPacketHeadersMarkerInMainHeader =
markersParser.getMarkerOffsetInDatabin(
mainHeaderDatabin, j2kMarkers.PackedPacketHeadersInMainHeader);
var isPacketHeadersNearData =
packedPacketHeadersMarkerInTileHeader === null &&
packedPacketHeadersMarkerInMainHeader === null;
var codingStyleMoreDataOffset = baseParams.codingStyleDefaultOffset + 6;
var codingStyleMoreDataBytes = getBytes(
databin,
/*numBytes=*/6,
/*startOffset=*/codingStyleMoreDataOffset);
var numQualityLayers = messageHeaderParser.getInt16(
codingStyleMoreDataBytes, 0);
var codeblockWidth = parseCodeblockSize(
codingStyleMoreDataBytes, 4);
var codeblockHeight = parseCodeblockSize(
codingStyleMoreDataBytes, 5);
var precinctWidths = new Array(baseParams.numResolutionLevels);
var precinctHeights = new Array(baseParams.numResolutionLevels);
var precinctSizesBytes = null;
if (!baseParams.isDefaultPrecinctSize) {
var precinctSizesBytesNeeded = baseParams.numResolutionLevels;
precinctSizesBytes = getBytes(
databin,
precinctSizesBytesNeeded,
baseParams.precinctSizesOffset);
}
var defaultSize = 1 << 15;
for (var i = 0; i < baseParams.numResolutionLevels; ++i) {
if (baseParams.isDefaultPrecinctSize) {
precinctWidths[i] = defaultSize;
precinctHeights[i] = defaultSize;
continue;
}
var precinctSizeOffset = i;
var sizeExponents = precinctSizesBytes[precinctSizeOffset];
var ppx = sizeExponents & 0x0F;
var ppy = sizeExponents >>> 4;
precinctWidths[i] = 1 * Math.pow(2, ppx); // Avoid negative result due to signed calculation
precinctHeights[i] = 1 * Math.pow(2, ppy); // Avoid negative result due to signed calculation
}
var paramsPerComponent = new Array(numComponents);
for (var i = 0; i < numComponents; ++i) {
paramsPerComponent[i] = {
maxCodeblockWidth: codeblockWidth,
maxCodeblockHeight: codeblockHeight,
numResolutionLevels: baseParams.numResolutionLevels,
precinctWidthPerLevel: precinctWidths,
precinctHeightPerLevel: precinctHeights
};
}
var defaultComponentParams = {
maxCodeblockWidth: codeblockWidth,
maxCodeblockHeight: codeblockHeight,
numResolutionLevels: baseParams.numResolutionLevels,
precinctWidthPerLevel: precinctWidths,
precinctHeightPerLevel: precinctHeights
};
var tileParams = {
numQualityLayers: numQualityLayers,
isPacketHeadersNearData: isPacketHeadersNearData,
isStartOfPacketMarkerAllowed: baseParams.isStartOfPacketMarkerAllowed,
isEndPacketHeaderMarkerAllowed: baseParams.isEndPacketHeaderMarkerAllowed,
paramsPerComponent: paramsPerComponent,
defaultComponentParams: defaultComponentParams
};
return tileParams;
}
function parseCodeblockSize(bytes, offset) {
var codeblockSizeExponentMinus2 = bytes[offset];
var codeblockSizeExponent = 2 + (codeblockSizeExponentMinus2 & 0x0F);
if (codeblockSizeExponent > 10) {
throw new j2kExceptions.IllegalDataException(
'Illegal codeblock width exponent ' + codeblockSizeExponent,
'A.6.1, Table A.18');
}
var size = 1 << codeblockSizeExponent;
return size;
}
function getBytes(databin, numBytes, databinStartOffset, allowEndOfRange) {
var bytes = [];
var rangeOptions = {
forceCopyAllRange: true,
maxLengthToCopy: numBytes,
databinStartOffset: databinStartOffset
};
var bytesCopied = databin.copyBytes(bytes, /*startOffset=*/0, rangeOptions);
if (bytesCopied === null) {
throw new jpipExceptions.InternalErrorException(
'Header data-bin has not yet recieved ' + numBytes +
' bytes starting from offset ' + databinStartOffset);
}
return bytes;
}
}; | MaMazav/MaMazav.github.io | webjpip.js/old/webjpip.js/jpipcore/parsers/jpipstructureparser.js | JavaScript | apache-2.0 | 9,141 |
var path = require('path'),
sys = require('util'),
url = require('url'),
request,
fs = require('fs');
var less = {
version: [1, 4, 0],
Parser: require('./parser').Parser,
importer: require('./parser').importer,
tree: require('./tree'),
render: function (input, options, callback) {
options = options || {};
if (typeof(options) === 'function') {
callback = options, options = {};
}
var parser = new(less.Parser)(options),
ee;
if (callback) {
parser.parse(input, function (e, root) {
callback(e, root && root.toCSS && root.toCSS(options));
});
} else {
ee = new(require('events').EventEmitter);
process.nextTick(function () {
parser.parse(input, function (e, root) {
if (e) { ee.emit('error', e) }
else { ee.emit('success', root.toCSS(options)) }
});
});
return ee;
}
},
formatError: function(ctx, options) {
options = options || {};
var message = "";
var extract = ctx.extract;
var error = [];
var stylize = options.color ? require('./lessc_helper').stylize : function (str) { return str };
// only output a stack if it isn't a less error
if (ctx.stack && !ctx.type) { return stylize(ctx.stack, 'red') }
if (!ctx.hasOwnProperty('index') || !extract) {
return ctx.stack || ctx.message;
}
if (typeof(extract[0]) === 'string') {
error.push(stylize((ctx.line - 1) + ' ' + extract[0], 'grey'));
}
if (extract[1]) {
error.push(ctx.line + ' ' + extract[1].slice(0, ctx.column)
+ stylize(stylize(stylize(extract[1][ctx.column], 'bold')
+ extract[1].slice(ctx.column + 1), 'red'), 'inverse'));
}
if (typeof(extract[2]) === 'string') {
error.push(stylize((ctx.line + 1) + ' ' + extract[2], 'grey'));
}
error = error.join('\n') + stylize('', 'reset') + '\n';
message += stylize(ctx.type + 'Error: ' + ctx.message, 'red');
ctx.filename && (message += stylize(' in ', 'red') + ctx.filename +
stylize(':' + ctx.line + ':' + ctx.column, 'grey'));
message += '\n' + error;
if (ctx.callLine) {
message += stylize('from ', 'red') + (ctx.filename || '') + '/n';
message += stylize(ctx.callLine, 'grey') + ' ' + ctx.callExtract + '/n';
}
return message;
},
writeError: function (ctx, options) {
options = options || {};
if (options.silent) { return }
sys.error(less.formatError(ctx, options));
}
};
['color', 'directive', 'operation', 'dimension',
'keyword', 'variable', 'ruleset', 'element',
'selector', 'quoted', 'expression', 'rule',
'call', 'url', 'alpha', 'import',
'mixin', 'comment', 'anonymous', 'value',
'javascript', 'assignment', 'condition', 'paren',
'media', 'ratio', 'unicode-descriptor', 'extend'
].forEach(function (n) {
require('./tree/' + n);
});
var isUrlRe = /^(?:https?:)?\/\//i;
less.Parser.importer = function (file, paths, callback, env) {
var pathname, dirname, data;
function parseFile(e, data) {
if (e) { return callback(e); }
env = new less.tree.parseEnv(env);
var j = file.lastIndexOf('/');
// Pass on an updated rootpath if path of imported file is relative and file
// is in a (sub|sup) directory
//
// Examples:
// - If path of imported file is 'module/nav/nav.less' and rootpath is 'less/',
// then rootpath should become 'less/module/nav/'
// - If path of imported file is '../mixins.less' and rootpath is 'less/',
// then rootpath should become 'less/../'
if(env.relativeUrls && !/^(?:[a-z-]+:|\/)/.test(file) && j != -1) {
env.rootpath = env.rootpath + file.slice(0, j+1); // append (sub|sup) directory path of imported file
}
env.contents[pathname] = data; // Updating top importing parser content cache.
env.paths = [dirname].concat(paths);
env.filename = pathname;
new(less.Parser)(env).parse(data, function (e, root) {
callback(e, root, pathname);
});
};
var isUrl = isUrlRe.test( file );
if (isUrl || isUrlRe.test(paths[0])) {
if (request === undefined) {
try { request = require('request'); }
catch(e) { request = null; }
}
if (!request) {
callback({ type: 'File', message: "optional dependency 'request' required to import over http(s)\n" });
return;
}
var urlStr = isUrl ? file : url.resolve(paths[0], file),
urlObj = url.parse(urlStr),
req = {
host: urlObj.hostname,
port: urlObj.port || 80,
path: urlObj.pathname + (urlObj.search||'')
};
request.get(urlStr, function (error, res, body) {
if (res.statusCode === 404) {
callback({ type: 'File', message: "resource '" + urlStr + "' was not found\n" });
return;
}
if (!body) {
sys.error( 'Warning: Empty body (HTTP '+ res.statusCode + ') returned by "' + urlStr +'"' );
}
if (error) {
callback({ type: 'File', message: "resource '" + urlStr + "' gave this Error:\n "+ error +"\n" });
}
pathname = urlStr;
dirname = urlObj.protocol +'//'+ urlObj.host + urlObj.pathname.replace(/[^\/]*$/, '');
parseFile(null, body);
});
} else {
// TODO: Undo this at some point,
// or use different approach.
var paths = [].concat(paths);
paths.push('.');
for (var i = 0; i < paths.length; i++) {
try {
pathname = path.join(paths[i], file);
fs.statSync(pathname);
break;
} catch (e) {
pathname = null;
}
}
paths = paths.slice(0, paths.length - 1);
if (!pathname) {
if (typeof(env.errback) === "function") {
env.errback(file, paths, callback);
} else {
callback({ type: 'File', message: "'" + file + "' wasn't found.\n" });
}
return;
}
dirname = path.dirname(pathname);
if (env.syncImport) {
try {
data = fs.readFileSync(pathname, 'utf-8');
parseFile(null, data);
} catch (e) {
parseFile(e);
}
} else {
fs.readFile(pathname, 'utf-8', parseFile);
}
}
}
require('./env');
require('./functions');
require('./colors');
for (var k in less) { exports[k] = less[k] }
| ricardobeat/less-less | lib/less/index.js | JavaScript | apache-2.0 | 7,200 |
var db = require('../db');
var Schema = db.Schema;
var ParticipantSchema = Schema({
id:{ type: Schema.Types.ObjectId},
fitbitid: {type: String, required: true},
dateofbirth: {type: String, required: true},
name: {type: String, required: true},
gender: {type: String},
age: {type: Number},
fitbittoken: [Schema.Types.Mixed]
});
module.exports = db.model('Participant', ParticipantSchema);
| KHP-Informatics/RADAR-platform | producers/fitbit/models/ParticipantModel.js | JavaScript | apache-2.0 | 419 |
/**
* The jdbc module provides access to java database connectivity (JDBC).
* Typically you acquire access to the module by naming it as a dependency in a call to `define()`
* when defining your own module.
* The object passed to the `define()` callback to represent the dependency can be considered
* a singleton `jdbc` class, which exposes all its functionality as static methods.
*
* @module jdbc
*/
(function(exports){
/**
* This is not a standalone class. Rather it describes the properties required to establish a JDBC connection.
* As such it appears as type for arguments to various methods that use JDBC.
*
* @Class JDBCConnectionProperties
*/
/**
* The name for the connection. If the name is present when the JDBCConnectionProperties object is passed to a method
* that creates a connection, then this name will be used to store this connection in a connection cache. The name can
* then later be used to retrieve the connection.
* If passed to functions that just need a connection to work with, then an attempt will be made to retrieve the connection.
* If the connection cannot be retrieved, and the JDBCConnectionProperties also contains properties that can be used to create
* a connection, then a connection will be created and stored under this name.
*
* @property {name} name The name that will be used to store this connection in the connection cache.
* @optional
*/
/**
*
* If present, the driver property will be used to load the JDBC driver class.
* This should take care of registering the driver with the JDBC DriverManager.
*
* @property {string} driver The fully qualified (java) class name of the JDBC driver that manages the connection.
* @optional
*/
/**
* A class to create JDBC database connections.
* Can also load JDBC drivers dynamically from a jar file.
*
* Example:
*
* (function(){
* define("src/jdbc/jdbc.js", function(jdbc){
*
* var connection = jdbc.openConnection({
* //optional: specify a name so you can refer to this connection by name later on`
* name: "My Sakila Connection",
* //The fully qualified class name of the driver. Optional if you're sure the driver was already registered.
* driver: "com.mysql.jdbc.Driver",
* //A string that can be resolved as a path identifying a jar file that contains the driver.
* //This is required to load drivers dyntamically from jar files that are not on the class path.
* jar: "/usr/share/java/mysql-connection-java-5.1.38-bin.jar",
* //The driver specific JDBC url to connect to your database.
* url: "jdbc:mysql://localhost/sakila",
* //JDBC user.
* user: "sakila",
* //JDBC password.
* password: "sakila"
* });
*
* ...use the connection...
*
* //get an existing connection
* var connection = jdbc.getConnection("My Sakila Connection");
*
* //close existing connection
* jdbc.closeConnection("My Sakila Connection");
*
* //You can also explicitly close the connection itself:
* connection.close();
*
* });
* })();
*
* @class JDBC
* @static
*/
var Class = Java.type("java.lang.Class");
var DriverManager = Java.type("java.sql.DriverManager");
var connections = {};
function loadDriverClassFromJar(jar, driver){
var File = Java.type("java.io.File");
var file = new File(jar);
var uri = file.toURI();
var url = uri.toURL();
var URLClassLoader = Java.type("java.net.URLClassLoader");
var urlClassLoader = new URLClassLoader([url], file.getClass().getClassLoader());
var driverClass = Class.forName(driver, true, urlClassLoader);
return driverClass;
}
/**
*
* Load a JDBC driver, and register it with the JDBC DriverManager.
*
* The `conf` argument can either be a string, or an object.
*
* If it is a string, it should be the fully qualified class name of the driver.
* This class will then be loaded and this should automatically register the driver with the driver manager.
* In order for this to work, the driver should already be on the system classpath.
* To dynamically load a JDBC driver from a jar that is not on the classpath, consider passing a `conf` object instead.
*
* If `conf` is an object, it should have a `driver` key, which should be the fully qualified class name of the driver.
*
* Optionally, the conf object can contain a `jar` key.
* If a `jar` key is specified, then an attempt will be made to load the driver class from the specified jarfile.
* To register the driver with the DriverManager, it is passed to an instance of the jjsutils DriverDelegate.
* The DriverDelegate is a utility class that wraps the dyncamically loaded Driver from the jar.
* Since the DriverDelegate is assumed to be in the classpath, this can be succesfully registred by the DriverManager.
*
* @method loadDriver
* @param conf {string | JDBCConnectionProperties}
* @static
*/
function loadDriver(conf){
var typeOfConf = typeof(conf);
var driver, jar, driverClass;
switch (typeOfConf) {
case "string":
driver = conf;
break;
case "object":
driver = conf.driver;
jar = conf.jar;
break;
default:
throw new Error("Configuration must either be a driverName or an object with a driver key, and optionally a jar key.");
}
if (jar) {
var driverDelegateClassName = "org.jjsutils.jdbc.DriverDelegate";
try {
var DriverDelegate = Java.type(driverDelegateClassName);
var driver = new DriverDelegate(driver, jar);
}
catch (ex){
ex.printStackTrace();
throw new Error(
"Error getting Java Type " + driverDelegateClassName + ".\n\n" +
"Maybe you forgot to pass -J-Djava.class.path=lib/jjsutils-yyyymmdd.jar to the jjs executable?"
);
}
}
else {
driverClass = Class.forName(driver);
}
return driverClass;
}
function connect(conf, driverManager){
var connection = DriverManager.getConnection(conf.url, conf.user, conf.password);
if (conf.name) {
connections[name] = connection;
}
return connection;
}
/**
* Opens a JDBC connection based on properties passed in the argument configuration object.
*
* The configuration object supports the following properties:
* * driver
* * jar
* * url
* * user
* * password
* * name
*
* The driver and jar properties maybe used by `loadDriver()` to load the driver.
* The url, user and password properties are used to obtain a connection from the JDBC DriverManager
* The name (if present) will be used to store this connection in a cache of connections.
* This way you can later refer to this connection by name using `getConnection()`.
*
* @method openConnection
* @static
* @param {JDBCConnectionProperties} conf An object that specifies data required to actually establish the JDBC connection.
* @return {java.sql.Connection} Retuns the JDBC connection.
*/
function openConnection(conf){
if (conf.driver) {
loadDriver(conf);
}
var connection = connect(conf);
return connection;
}
/**
* Obtain a connection created prior with `openConnection()`.
*
* @method getConnection
* @static
* @param {string} name The name of a connection created prior using `openConnection()`.
* @return {java.sql.Connection} The connection.
*/
function getConnection(name){
return connections[name];
}
function obtainConnection(connection) {
var type = typeof(connection);
var conn;
if (type === "string") {
if (!(conn = getConnection(connection))) {
throw new Error("No such connection: " + connection);
}
}
else
if (type === "object") {
var name = connection.name;
if (typeof(name) === "string") {
conn = getConnection(connection);
}
if (!conn) {
conn = openConnection(connection);
}
}
if (!conn) {
throw new Error("Could not open connection.");
}
return conn;
}
/**
*
* Execute a SQL-SELECT statement (a query) and obtain the results.
*
* @method query
* @static
* @param {string | object} connection Either a connection name, or an object such as one would pass to `openConnection()`.
* @param {string} sql A SQL SELECT statement.
* @return {java.sql.ResultSet} A resultset object that represents the result of the SQL query.
*/
function executeQuery(connection, sql){
var conn = obtainConnection(connection);
var res;
try {
var stmt = conn.createStatement();
res = stmt.executeQuery(sql);
}
catch (e){
throw e;
}
return res;
}
/**
*
* Execute a non-query SQL statement (a INSERT, UPDATE, DELETE or DDL statement) and obtain the results.
*
* @method execute
* @static
* @param {string | object} connection Either a connection name, or an object such as one would pass to `openConnection()`.
* @param {string} sql A SQL DDL statement, or INSERT, UPDATE, DELETE statement.
* @return {java.sql.ResultSet} A resultset object that represents the result of the SQL query.
*/
function executeUpdate(connection, sql){
var conn = obtainConnection(connection);
var res;
try {
var stmt = conn.createStatement();
res = stmt.executeUpdate(sql);
}
catch (e){
throw e;
}
return res;
}
/**
* Close a connection created prior with `openConnection()`, and remove it from the connection cache.
*
* @method closeConnection
* @static
* @param {string} name The name of a connection created prior using `openConnection()`.
*/
function closeConnection(name) {
var connection = connections[name];
if (typeof(connection) === "undefined") {
return;
}
delete connections[name];
connection.close();
}
/**
* Closes all connections stored in the connection cache.
*
* @method closeAllConnections
* @static
*/
function closeAllConnections(){
var name;
for (name in connections) {
try {
closeConnection(name);
}
catch (e) {
}
}
}
return define(function(){
return {
loadDriver: loadDriver,
openConnection: openConnection,
query: executeQuery,
execute: executeUpdate,
getConnection: getConnection,
closeConnection: closeConnection,
closeAll: closeAllConnections
};
});
})(this); | rpbouman/jjsutils | src/jdbc/jdbc.js | JavaScript | apache-2.0 | 10,572 |
/* eslint-env jest */
import eventize, {
PRIO_DEFAULT,
EVENT_CATCH_EM_ALL,
} from '../eventize';
describe('on()', () => {
describe('eventName is a string', () => {
describe('on( eventName, priority, listenerFunc, listenerObject )', () => {
const listenerObject = {};
const listenerFunc = jest.fn();
const obj = eventize({});
let context;
const unsubscribe = obj.on('foo', 7, function () { // eslint-disable-line
context = this;
}, listenerObject);
obj.on('foo', 0, listenerFunc, listenerObject);
obj.emit('foo', 'bar', 666);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('bar', 666);
});
it('emit() calls the listener with correct context', () => {
expect(context).toBe(listenerObject);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(7);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe('foo');
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(false);
});
});
describe('on( eventName, priority, listenerFuncName, listenerObject )', () => {
const listenerObject = {
foo(...args) {
this.args = args;
},
};
const obj = eventize({});
const unsubscribe = obj.on('foo', 9, 'foo', listenerObject);
obj.emit('foo', 'bar', 666);
it('emit() calls the listener', () => {
expect(listenerObject.args).toEqual(['bar', 666]);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(9);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe('foo');
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(false);
});
});
describe('on( eventName, priority, listenerFunc )', () => {
const listenerFunc = jest.fn();
const obj = eventize({});
const unsubscribe = obj.on('foo', 11, listenerFunc);
obj.emit('foo', 'plah', 669);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('plah', 669);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(11);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe('foo');
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(false);
});
});
describe('on( eventName, priority, object )', () => {
const listenerFunc = jest.fn();
let listenerContext;
const listener = {
foo(...args) {
listenerContext = this;
listenerFunc(...args);
},
};
const obj = eventize({});
const unsubscribe = obj.on('foo', 13, listener);
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(13);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe('foo');
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(false);
});
obj.emit('foo', 'plah', 667);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('plah', 667);
});
it('emit() calls the listener with correct context', () => {
expect(listener).toBe(listenerContext);
});
});
describe('on( eventName, listenerFunc, listenerObject )', () => {
const listenerObject = {};
const listenerFunc = jest.fn();
const obj = eventize({});
let context;
const unsubscribe = obj.on('foo', function () { // eslint-disable-line
context = this;
}, listenerObject);
obj.on('foo', listenerFunc, listenerObject);
obj.emit('foo', 'bar', 666);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('bar', 666);
});
it('emit() calls the listener with correct context', () => {
expect(context).toBe(listenerObject);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(PRIO_DEFAULT);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe('foo');
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(false);
});
});
describe('on( eventName, listenerFunc )', () => {
const listenerFunc = jest.fn();
const obj = eventize({});
const unsubscribe = obj.on('foo', listenerFunc);
obj.emit('foo', 'plah', 669);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('plah', 669);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(PRIO_DEFAULT);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe('foo');
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(false);
});
});
}); // eventName is a string
describe('eventName is an array', () => {
describe('on( eventNameArray, priority, listenerFunc, listenerObject )', () => {
const listenerObject = {};
const listenerFunc = jest.fn();
const obj = eventize({});
const context = [];
const { listeners } = obj.on(['foo', 'fu'], 7, function () { // eslint-disable-line
context.push(this);
}, listenerObject);
obj.on(['foo', 'fu'], 0, listenerFunc, listenerObject);
obj.emit(['foo', 'fu'], 'bar', 666);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledTimes(2);
expect(listenerFunc).toHaveBeenCalledWith('bar', 666);
});
it('emit() calls the listener with correct context', () => {
expect(context).toEqual([listenerObject, listenerObject]);
});
it('priorites are correct', () => {
expect(listeners[0].priority).toBe(7);
expect(listeners[1].priority).toBe(7);
});
it('eventNames are correct', () => {
expect(listeners[0].eventName).toBe('foo');
expect(listeners[1].eventName).toBe('fu');
});
it('isCatchEmAll is correct', () => {
expect(listeners[0].isCatchEmAll).toBe(false);
expect(listeners[1].isCatchEmAll).toBe(false);
});
});
describe('on( eventName*, priority, listenerFuncName, listenerObject )', () => {
const mockFunc = jest.fn();
const listenerObject = {
foo(...args) {
this.context = this;
this.args = args;
mockFunc(...args);
},
};
const obj = eventize({});
const { listeners } = obj.on(['foo', 'fu'], 9, 'foo', listenerObject);
obj.emit(['foo', 'fu'], 'bar', 666);
it('emit() calls the listener', () => {
expect(mockFunc).toHaveBeenCalledTimes(2);
expect(listenerObject.args).toEqual(['bar', 666]);
expect(listenerObject.context).toBe(listenerObject);
});
it('priorities are correct', () => {
expect(listeners[0].priority).toBe(9);
expect(listeners[1].priority).toBe(9);
});
it('eventNames is correct', () => {
expect(listeners[0].eventName).toBe('foo');
expect(listeners[1].eventName).toBe('fu');
});
it('isCatchEmAll is correct', () => {
expect(listeners[0].isCatchEmAll).toBe(false);
expect(listeners[1].isCatchEmAll).toBe(false);
});
});
describe('on( eventName*, priority, listenerFunc )', () => {
const listenerFunc = jest.fn();
const obj = eventize({});
const { listeners } = obj.on(['foo', 'bar'], 11, listenerFunc);
obj.emit(['foo', 'bar'], 'plah', 669);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledTimes(2);
expect(listenerFunc).toHaveBeenCalledWith('plah', 669);
});
it('priorities are correct', () => {
expect(listeners[0].priority).toBe(11);
expect(listeners[1].priority).toBe(11);
});
it('eventNames are correct', () => {
expect(listeners[0].eventName).toBe('foo');
expect(listeners[1].eventName).toBe('bar');
});
it('isCatchEmAll is correct', () => {
expect(listeners[0].isCatchEmAll).toBe(false);
expect(listeners[1].isCatchEmAll).toBe(false);
});
});
describe('on( eventName*, priority, object )', () => {
const listenerFuncFoo = jest.fn();
const listenerFuncBar = jest.fn();
const obj = eventize({});
const { listeners } = obj.on(['foo', 'bar'], 13, {
foo: listenerFuncFoo,
bar: listenerFuncBar,
});
it('priorities are correct', () => {
expect(listeners[0].priority).toBe(13);
expect(listeners[1].priority).toBe(13);
});
it('eventNames are correct', () => {
expect(listeners[0].eventName).toBe('foo');
expect(listeners[1].eventName).toBe('bar');
});
it('isCatchEmAll is correct', () => {
expect(listeners[0].isCatchEmAll).toBe(false);
expect(listeners[1].isCatchEmAll).toBe(false);
});
obj.emit(['foo', 'bar'], 'plah', 667);
it('emit() calls the :foo listener', () => {
expect(listenerFuncFoo).toHaveBeenCalledWith('plah', 667);
});
it('emit() calls the :bar listener', () => {
expect(listenerFuncBar).toHaveBeenCalledWith('plah', 667);
});
});
describe('on( eventName*, listenerFunc, listenerObject )', () => {
const listenerObject = {};
const listenerFunc = jest.fn();
const obj = eventize({});
const contexts = [];
const { listeners } = obj.on(['foo', 'bar'], function fooBar(...args) {
contexts.push(this);
listenerFunc(...args);
}, listenerObject);
obj.emit(['foo', 'bar'], 'plah', 669);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledTimes(2);
expect(listenerFunc).toHaveBeenCalledWith('plah', 669);
});
it('priorities are correct', () => {
expect(listeners[0].priority).toBe(PRIO_DEFAULT);
expect(listeners[1].priority).toBe(PRIO_DEFAULT);
});
it('eventNames are correct', () => {
expect(listeners[0].eventName).toBe('foo');
expect(listeners[1].eventName).toBe('bar');
});
it('isCatchEmAll is correct', () => {
expect(listeners[0].isCatchEmAll).toBe(false);
expect(listeners[1].isCatchEmAll).toBe(false);
});
it('emit() calls the listener with correct context', () => {
expect(contexts[0]).toBe(listenerObject);
expect(contexts[1]).toBe(listenerObject);
});
});
describe('on( eventName*, listenerFunc )', () => {
const listenerFunc = jest.fn();
const obj = eventize({});
const { listeners } = obj.on(['foo', 'bar'], listenerFunc);
obj.emit(['foo', 'bar'], 'plah', 669);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledTimes(2);
expect(listenerFunc).toHaveBeenCalledWith('plah', 669);
});
it('priorities are correct', () => {
expect(listeners[0].priority).toBe(PRIO_DEFAULT);
expect(listeners[1].priority).toBe(PRIO_DEFAULT);
});
it('eventNames are correct', () => {
expect(listeners[0].eventName).toBe('foo');
expect(listeners[1].eventName).toBe('bar');
});
it('isCatchEmAll is correct', () => {
expect(listeners[0].isCatchEmAll).toBe(false);
expect(listeners[1].isCatchEmAll).toBe(false);
});
});
describe('on( eventName*, listenerFunc ) supports [ [eventName, PRIO], .. ]', () => {
const listenerFunc = jest.fn();
const obj = eventize({});
const { listeners } = obj.on([['foo', 500], ['bar', 1000]], listenerFunc);
obj.emit(['foo', 'bar'], 'plah', 669);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledTimes(2);
expect(listenerFunc).toHaveBeenCalledWith('plah', 669);
});
it('priorities are correct', () => {
expect(listeners[0].priority).toBe(500);
expect(listeners[1].priority).toBe(1000);
});
it('eventNames are correct', () => {
expect(listeners[0].eventName).toBe('foo');
expect(listeners[1].eventName).toBe('bar');
});
it('isCatchEmAll is correct', () => {
expect(listeners[0].isCatchEmAll).toBe(false);
expect(listeners[1].isCatchEmAll).toBe(false);
});
});
}); // eventName is an array
describe('on( priority, listenerFunc, listenerObject ) => object.on( "*", priority, listenerFunc, listenerObject )', () => {
const listenerObject = {};
const listenerFunc = jest.fn();
const obj = eventize({});
let context;
const unsubscribe = obj.on(7, function () { // eslint-disable-line
context = this;
}, listenerObject);
obj.on(listenerFunc, listenerObject);
obj.emit('foo', 'bar', 666);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('bar', 666);
});
it('emit() calls the listener with correct context', () => {
expect(context).toBe(listenerObject);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(7);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe(EVENT_CATCH_EM_ALL);
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(true);
});
});
describe('on( priority, listenerFunc ) => object.on( "*", priority, listenerFunc )', () => {
const listenerFunc = jest.fn();
const obj = eventize({});
const unsubscribe = obj.on(11, listenerFunc);
obj.emit('foo', 'plah', 669);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('plah', 669);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(11);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe(EVENT_CATCH_EM_ALL);
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(true);
});
});
describe('on( listenerFunc, listenerObject ) => object.on( "*", PRIO_DEFAULT, listenerFunc, listenerObject )', () => {
const listenerObject = {};
const listenerFunc = jest.fn();
const obj = eventize({});
let context;
const unsubscribe = obj.on(function () { // eslint-disable-line
context = this;
}, listenerObject);
obj.on(listenerFunc, listenerObject);
obj.emit('foo', 'bar', 666);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('bar', 666);
});
it('emit() calls the listener with correct context', () => {
expect(context).toBe(listenerObject);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(PRIO_DEFAULT);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe(EVENT_CATCH_EM_ALL);
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(true);
});
});
describe('on( listenerFunc ) => object.on( "*", PRIO_DEFAULT, listenerFunc )', () => {
const listenerFunc = jest.fn();
const obj = eventize({});
const unsubscribe = obj.on(listenerFunc);
obj.emit('foo', 'plah', 669);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('plah', 669);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(PRIO_DEFAULT);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe(EVENT_CATCH_EM_ALL);
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(true);
});
});
describe('on( priority, object ) => object.on( "*", priority, object )', () => {
const listenerFunc = jest.fn();
const obj = eventize({});
const unsubscribe = obj.on(13, { foo: listenerFunc });
obj.emit('foo', 'plah', 667);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('plah', 667);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(13);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe(EVENT_CATCH_EM_ALL);
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(true);
});
});
describe('on( object ) => object.on( "*", PRIO_DEFAULT, object )', () => {
const listenerFunc = jest.fn();
const obj = eventize({});
const unsubscribe = obj.on({ foo: listenerFunc });
obj.emit('foo', 'plah', 667);
it('emit() calls the listener', () => {
expect(listenerFunc).toHaveBeenCalledWith('plah', 667);
});
it('priority is correct', () => {
expect(unsubscribe.listener.priority).toBe(PRIO_DEFAULT);
});
it('eventName is correct', () => {
expect(unsubscribe.listener.eventName).toBe(EVENT_CATCH_EM_ALL);
});
it('isCatchEmAll is correct', () => {
expect(unsubscribe.listener.isCatchEmAll).toBe(true);
});
});
});
| spearwolf/eventize | src/__tests__/on.spec.js | JavaScript | apache-2.0 | 17,681 |
(function () {
'use strict';
angular.module('app').factory('contactService', ['$http', function ($http) {
return {
send : function(data) {
return $http.post('api/contact', data);
}
};
}]);
})(); | bmobsoftwares/bmobsoftwares.github.io | app/contact/contactService.js | JavaScript | apache-2.0 | 267 |
/* global Buffer */
var dgram = require('dgram');
var client = dgram.createSocket("udp4");
var rfidReader = require("../index.js");
var broadcastAddress = "255.255.255.255";
var deviceBroadcastPort = 39169;
function failOnError(err) {
if (err) {
throw err;
}
}
client.on("error", function (err) {
console.log("Server error:\n" + err.stack);
client.close();
});
//var deviceIpMask = "255.255.255.0";
var deviceIpMask = "255.255.240.0";
//var deviceMask = "255.255.254.0";
var data = [
{
ip: "192.168.1.218",
gateway: "192.168.1.108",
serial: "144-1-31-95"
},
{
ip: "192.168.1.217",
gateway: "192.168.1.108",
serial: "199-1-112-40"
},
// 01
{
ip: "10.240.66.10",
gateway: "10.240.66.1",
serial: "193-1-110-217"
},
// 02
{
ip: "10.240.66.11",
gateway: "10.240.66.1",
serial: "141-1-33-145"
},
// 03
{
ip: "10.240.66.12",
gateway: "10.240.66.1",
serial: "193-1-110-141"
},
// 04
{
ip: "10.240.66.13",
gateway: "10.240.66.1",
serial: "144-1-31-91"
},
// 05
{
ip: "10.240.66.14",
gateway: "10.240.66.1",
serial: "144-1-31-84"
},
// 06
{
ip: "10.240.66.15",
gateway: "10.240.66.1",
serial: "144-1-31-119"
},
// 07
{
ip: "10.240.66.16",
gateway: "10.240.66.1",
serial: "152-1-34-192"
},
// 08
{
ip: "10.240.66.17",
gateway: "10.240.66.1",
serial: "193-1-110-184"
},
// 09
{
ip: "10.240.66.18",
gateway: "10.240.66.1",
serial: "172-1-115-52"
},
// 10
{
ip: "10.240.66.19",
gateway: "10.240.66.1",
serial: "146-1-34-58"
},
// 11
{
ip: "10.240.66.20",
gateway: "10.240.66.1",
serial: "172-1-115-88"
},
// 12
{
ip: "10.240.66.21",
gateway: "10.240.66.1",
serial: "141-1-33-202"
},
// 13
{
ip: "10.240.66.22",
gateway: "10.240.66.1",
serial: "199-1-112-40"
},
// 14
{
ip: "10.240.66.23",
gateway: "10.240.66.1",
serial: "144-1-31-95"
}
];
client.on("listening", function () {
var address = client.address();
console.log("Server listening " + address.address + ":" + address.port);
console.log("Start listening.")
client.setBroadcast(true);
var setSound = rfidReader.setSoundCommand(0, rfidReader.soundType.shortBeepOnce);
client.send(setSound, 0, setSound.length, deviceBroadcastPort, broadcastAddress, failOnError);
var deviceData = data[10];
var updateReaderCommand = rfidReader.updateReaderCommand(deviceData.ip, deviceIpMask, deviceData.gateway, 0, deviceData.serial, 1);
client.send(updateReaderCommand, 0, updateReaderCommand.length, deviceBroadcastPort, broadcastAddress, function (err) {
console.log(arguments);
if (err) {
throw err;
}
var setSound = rfidReader.setSoundCommand(0, rfidReader.soundType.shortBeepOnce);
client.send(setSound, 0, setSound.length, deviceBroadcastPort, broadcastAddress, failOnError);
});
});
client.bind({
port: deviceBroadcastPort,
address: "169.254.167.154"
});
| kant2002/node-rfidreader | tools/updateSettings.js | JavaScript | apache-2.0 | 2,783 |
GBG.EquipmentArcs = {
shields:{buclet:{
orientation:-45,
deepLevel:1,
type:['block'],
widthLevels:[{from:40,to:60, color: '#3a3', cost:0},
{from:35,to:40, color: '#8a3', cost:1},
{from:30,to:35, color: '#777', cost:2},
{from:60,to:70, color: '#8a3', cost:1},
{from:70,to:75, color: '#777', cost:3}]
}
},
weapons:{
shortSword:{
orientation:45,
deepLevel:2,
type:['slash','parry'],
widthLevels:[{from:30,to:60, color: '#a33', cost:0},
{from:25,to:30, color: '#a83', cost:1},
{from:20,to:25, color: '#777', cost:2},
{from:60,to:77, color: '#a83', cost:1},
{from:77,to:85, color: '#777', cost:3}]
}
},
};
GBG.Movements = {
front:{
body05: { coordinates : {y:-50,x:0},rotation:0},
body1: { coordinates : {y:-100,x:0},rotation:0},
body15: { coordinates : {y:-150,x:0},rotation:0},
body2: { coordinates : {y:-200,x:0},rotation:0},
run3: { coordinates : {y:-300,x:0},rotation:0},
run4: { coordinates : {y:-400,x:0},rotation:0},
run5: { coordinates : {y:-500,x:0},rotation:0},
run6: { coordinates : {y:-600,x:0},rotation:0}
},
left:{},
right:{},
back:{},
turn:{}
};
/*
XWing template distances:
straight :
width 200mm
length => 1: 40mm, 2: 80mm, 3: 120mm, 4: 160mm, 5: 200mm
90 Turn , defined by arc radius. 90 degrees
Inner => 1: 25mm, 1: 53mm, 1: 80mm
outer => 1: 45mm, 1: 73mm, 1: 100mm
banc Turn , defined by arc radius. 45 degrees
Inner => 1: 70mm, 1: 120mm, 1: 170mm
outer => 1: 90mm, 1: 140mm, 1: 190mm
*/
GBG.XwingMovements = {
front:{
green1: { coordinates : {y:-200,x:0},rotation:0},
green2: { coordinates : {y:-300,x:0},rotation:0},
green3: { coordinates : {y:-400,x:0},rotation:0},
green4: { coordinates : {y:-500,x:0},rotation:0},
green5: { coordinates : {y:-600,x:0},rotation:0},
},
left:{
green1: { coordinates : {y:-137.5,x:-137.5},rotation:-90},
green2: { coordinates : {y:-207.5,x:-207.5},rotation:-90},
green3: { coordinates : {y:-275,x:-275},rotation:-90},
},
right:{
green1: { coordinates : {y:-137.5,x:137.5},rotation:90},
green2: { coordinates : {y:-207.5,x:207.5},rotation:90},
green3: { coordinates : {y:-275,x:275},rotation:90},
},
bancoLeft:{
green1: { coordinates : {y:-225.5 ,x:-45 },rotation:-45},
green2: { coordinates : {y:-313 ,x:-82.5 },rotation:-45},
green3: { coordinates : {y:-400.5 ,x:-120 },rotation:-45},
},
bancoRight:{
green1: { coordinates : {y:-225.5 ,x:45 },rotation:45},
green2: { coordinates : {y:-313 ,x:82.5 },rotation:45},
green3: { coordinates : {y:-400.5 ,x:120 },rotation:45},
},
back:{},
turn:{}
}; | Raising/GladiatorBoardGame | js/configurable.js | JavaScript | apache-2.0 | 3,052 |
$_L(["java.util.Vector"],"java.util.Stack",["java.util.EmptyStackException"],function(){
c$=$_T(java.util,"Stack",java.util.Vector);
$_M(c$,"empty",
function(){
return this.elementCount==0;
});
$_M(c$,"peek",
function(){
try{
return this.elementData[this.elementCount-1];
}catch(e){
if($_e(e,IndexOutOfBoundsException)){
throw new java.util.EmptyStackException();
}else{
throw e;
}
}
});
$_M(c$,"pop",
function(){
try{
var index=this.elementCount-1;
var obj=this.elementData[index];
this.removeElementAt(index);
return obj;
}catch(e){
if($_e(e,IndexOutOfBoundsException)){
throw new java.util.EmptyStackException();
}else{
throw e;
}
}
});
$_M(c$,"push",
function(object){
this.addElement(object);
return object;
},"~O");
$_M(c$,"search",
function(o){
var index=this.lastIndexOf(o);
if(index>=0)return(this.elementCount-index);
return-1;
},"~O");
});
| abego/j2slib | src/main/j2slib/java/util/Stack.js | JavaScript | apache-2.0 | 896 |
/*
* Copyright (c) 2012-2015 S-Core Co., Ltd.
*
* 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.
*/
define(['other-lib/underscore/lodash.min',
'webida-lib/util/path',
'./reference',
'./html-io',
'lib/css-parse-stringify/css-parse',
],
function (_, pathUtil, reference, htmlio, cssParse) {
'use strict';
function getRemoteFile(path, c) {
require(['webida-lib/app'], function (ide) {
//ide.getMount().readFile(path, function (error, content) {
ide.getFSCache().readFile(path, function (error, content) {
if (content === undefined) {
content = null;
}
c(error, content);
});
});
}
var FileServer = {
files: {},
getRemoteFileCallback: getRemoteFile,
listenersForReferencesUpdate: []
};
/**
* @contructor
* @param {string} path the file path of this text
*/
function FileModel(path) {
this.path = path;
this.version = undefined;
this.text = undefined;
this.html = {};
this.css = {};
}
FileModel.prototype.getHtmlDom = function () {
if (this.html.version === this.version && this.html.dom !== undefined) {
return this.html.dom;
}
var dom = htmlio.parse(this.text);
this.html = {};
this.html.dom = dom;
this.html.version = this.version;
return dom;
};
FileModel.prototype.getHtmlScripts = function () {
if (this.html.version === this.version && this.html.scripts !== undefined) {
return this.html.scripts;
}
var dom = this.getHtmlDom();
var scripts = [];
if (dom) {
scripts = dom.getElementsByTagName('script');
}
this.html.scripts = scripts;
return scripts;
};
FileModel.prototype._getTextLineEnds = function () {
if (this.textLineEndsVersion && this.textLineEndsVersion === this.version) {
return this.textLineEnds;
}
var ends = [];
var lastIndex = 0;
var re = /\r?\n/g;
while (re.test(this.text)) {
ends.push(re.lastIndex);
lastIndex = re.lastIndex;
}
ends.push(this.text.length - 1);
this.textLineEnds = ends;
this.textLineEndsVersion = this.version;
return ends;
};
FileModel.prototype.getPositionFromIndex = function (index) {
var ends = this._getTextLineEnds();
for (var i = 0; i < ends.length; i++) {
if (ends[i] > index) {
return {
line : i,
ch : index - ends[i]
};
}
}
return {
line : ends.length - 1,
ch : 0
};
};
FileModel.prototype.getIndexFromPosition = function (line, ch) {
var ends = this._getTextLineEnds();
var beforeLine = line - 1;
if (beforeLine >= 0 && beforeLine < ends.length) {
return ends[beforeLine] + ch;
}
return -1;
};
FileModel.prototype.isSubfile = function () {
return this.parent;
};
/**
* @return {[FileModel]} sub files (script) of html
**/
FileModel.prototype.getHtmlScriptSubfiles = function () {
if (this.html.version === this.version && this.html.scriptSubfiles !== undefined) {
return this.html.scriptSubfiles;
}
var scriptSubfiles = [];
var scripts = this.getHtmlScripts();
var i = 1000;
if (scripts) {
_.each(scripts, function (script) {
if (script.closingStart - script.openingEnd > 1) {
var subpath = this.path + '*' + (++i) + '.js';
var startIndex = script.openingEnd + 1;
var endIndex = script.closingStart - 1;
var subfile = FileServer.setText(subpath, this.text.substring(startIndex, endIndex));
subfile.subfileStartPosition = this.getPositionFromIndex(startIndex);
subfile.subfileEndPosition = this.getPositionFromIndex(endIndex);
subfile.parent = this;
scriptSubfiles.push(subfile);
reference.addReference(this.path, subpath);
}
}, this);
}
var subpath, subfile;
for (i = scriptSubfiles.length; true; i++) {
subpath = this.path + '*' + (++i) + '.js';
subfile = FileServer.getLocalFile(subpath);
if (subfile) {
FileServer.setText(subpath, null);
reference.removeReference(this.path, subpath);
} else {
break;
}
}
this.html.scriptSubfiles = scriptSubfiles;
return scriptSubfiles;
};
FileModel.prototype.getHtmlScriptPaths = function () {
if (this.html.version === this.version && this.html.scriptPaths !== undefined) {
return this.html.scriptPaths;
}
var scripts = this.getHtmlScripts();
var scriptPaths = [];
if (scripts) {
var dirPath = pathUtil.getDirPath(this.path);
_.each(scripts, function (script) {
var src = script.getAttribute('src');
if (src) {
var abspath = pathUtil.flatten(pathUtil.combine(dirPath, src));
scriptPaths.push(abspath);
}
});
}
this.html.scriptPaths = scriptPaths;
return scriptPaths;
};
FileModel.prototype.getHtmlLinks = function () {
if (this.html.version === this.version && this.html.links !== undefined) {
return this.html.links;
}
var dom = this.getHtmlDom();
var links = [];
if (dom) {
links = dom.getElementsByTagName('link');
}
this.html.links = links;
return links;
};
FileModel.prototype.getHtmlLinkPaths = function () {
if (this.html.version === this.version && this.html.linkPaths !== undefined) {
return this.html.linkPaths;
}
var links = this.getHtmlLinks();
var linkPaths = [];
if (links) {
var dirPath = pathUtil.getDirPath(this.path);
_.each(links, function (link) {
var href = link.getAttribute('href');
if (href) {
var abspath = pathUtil.flatten(pathUtil.combine(dirPath, href));
linkPaths.push(abspath);
}
});
}
this.html.linkPaths = linkPaths;
return linkPaths;
};
FileModel.prototype.getHtmlIds = function () {
if (this.html.version === this.version && this.html.ids !== undefined) {
return this.html.ids;
}
var dom = this.getHtmlDom();
var elems = dom.getElementsByTagName('*');
var ids = [];
_.each(elems, function (elem) {
if (elem.hasAttribute('id')) {
ids.push(elem.getAttribute('id'));
}
});
this.html.ids = ids;
return ids;
};
FileModel.prototype.getHtmlClasses = function () {
if (this.html.version === this.version && this.html.classes !== undefined) {
return this.html.classes;
}
var dom = this.getHtmlDom();
var elems = dom.getElementsByTagName('*');
var classes = [];
_.each(elems, function (elem) {
if (elem.hasAttribute('class')) {
classes = _.union(classes, elem.getAttribute('class').split(/\s+/));
}
});
this.html.classes = classes;
return classes;
};
function getHtmlNodeOfIndex(nodes, index) {
if (nodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].openingStart < index && (nodes[i].openingEnd >= index || nodes[i].closingEnd >= index)) {
var childnode = getHtmlNodeOfIndex(nodes[i].children, index);
if (childnode) {
return childnode;
} else {
return nodes[i];
}
}
}
}
return null;
}
FileModel.prototype.getHtmlNodeOfIndex = function (index) {
var dom = this.getHtmlDom();
return getHtmlNodeOfIndex(dom.children, index);
};
FileModel.prototype.getHtmlNodeOfPos = function (line, ch) {
var index = this.getIndexFromPosition(line, ch);
return this.getHtmlNodeOfIndex(index);
};
// CSS methods
FileModel.prototype.getCssom = function () {
if (this.css.version === this.version && this.css.cssom !== undefined) {
return this.css.cssom;
}
var cssom = cssParse(this.text);
this.css = {};
this.css.cssom = cssom;
this.css.version = this.version;
return cssom;
};
FileModel.prototype.getCssIds = function () {
if (this.css.version === this.version && this.css.ids !== undefined) {
return this.css.ids;
}
var cssom = this.getCssom();
var ids = [];
if (cssom && cssom.stylesheet && cssom.stylesheet.rules) {
_.each(cssom.stylesheet.rules, function (rule) {
_.each(rule.selectors, function (selector) {
var regexp = /#(\w*)/g;
var match;
while ((match = regexp.exec(selector))) {
if (match.length > 1) {
ids.push(match[1]);
}
}
});
});
}
this.css.ids = ids;
return ids;
};
FileModel.prototype.getCssClasses = function () {
if (this.css.version === this.version && this.css.classes !== undefined) {
return this.css.classes;
}
var cssom = this.getCssom();
var classes = [];
if (cssom && cssom.stylesheet && cssom.stylesheet.rules) {
_.each(cssom.stylesheet.rules, function (rule) {
_.each(rule.selectors, function (selector) {
var regexp = /\.(\w*)/g;
var match;
while ((match = regexp.exec(selector))) {
if (match.length > 1) {
classes.push(match[1]);
}
}
});
});
}
this.css.classes = classes;
return classes;
};
/**
@param {function} getRemoteFileCallback callback function for get remote file
*/
FileServer.init = function (getRemoteFileCallback) {
FileServer.getRemoteFileCallback = getRemoteFileCallback;
};
FileServer._newFile = function (path) {
var file = new FileModel(path);
FileServer.files[path] = file;
return file;
};
FileServer.setText = function (path, text) {
var file = this.getLocalFile(path);
if (!file) {
file = this._newFile(path);
}
if (text === undefined) {
console.error('## cc : text should not be undefined');
return file;
}
var newversion = new Date().getTime();
file.version = newversion;
file.text = text;
_updateReferences(file);
return file;
};
FileServer.setUpdated = function (path) {
var file = this.getLocalFile(path);
if (file) {
var newversion = new Date().getTime();
file.version = newversion;
}
return file;
};
var _updateReferences = function (file) {
if (pathUtil.endsWith(file.path, '.html', true)) {
var oldrefs = reference.getReferenceTos(file.path) || [];
/*if (pathUtil.isJavaScript(file.path)) {
} else if (pathUtil.isJson(file.path)) {
// TODO impl
} else */
if (pathUtil.isHtml(file.path)) {
reference.removeReferences(file.path);
_.each(file.getHtmlScriptSubfiles(), function (subfile) {
reference.addReference(file.path, subfile.path);
});
_.each(file.getHtmlScriptPaths(), function (scriptpath) {
reference.addReference(file.path, scriptpath);
});
_.each(file.getHtmlLinkPaths(), function (csspath) {
reference.addReference(file.path, csspath);
});
}
var newrefs = reference.getReferenceTos(file.path) || [];
_.each(FileServer.listenersForReferencesUpdate, function (listener) {
listener(file, newrefs, oldrefs);
});
}
};
FileServer.addReferenceUpdateListener = function (c) {
FileServer.listenersForReferencesUpdate.push(c);
};
FileServer.removeReferenceUpdateListener = function (c) {
FileServer.listenersForReferencesUpdate = _.without(FileServer.listenersForReferencesUpdate, c);
};
/**
@param {Fn(error,file)} c
**/
FileServer.getFile = function (path, c) {
var file = FileServer.files[path];
if (!file) {
file = this._newFile(path);
}
if (file.text !== undefined) {
c(undefined, file);
} else if (file.waitings) {
file.waitings.push(c);
} else {
file.waitings = [];
file.waitings.push(c);
var self = this;
FileServer.getRemoteFileCallback(path, function (error, data) {
if (error) {
console.warn(path + ' : ' + error);
}
self.setText(path, data);
_.each(file.waitings, function (c) {
c(error, file);
});
delete file.waitings;
});
}
};
FileServer.getLocalFile = function (path) {
return FileServer.files[path];
};
FileServer.getUpdatedFile = function (path, version) {
var file = this.getLocalFile(path);
if (file) {
if (version && file.version === version) {
file = null;
}
} else {
console.warn('## cc : unknown file requested [' + path + ']');
}
return file;
};
return FileServer;
});
| 5hk/webida-client | apps/ide/src/plugins/codeeditor/content-assist/file-server.js | JavaScript | apache-2.0 | 15,220 |
angular.module('JobsTrackerSpring')
.controller('PositionsEditCtrl', ['$scope', '$location', '$routeParams', 'PositionResource',
function ($scope, $location, $routeParams, PositionResource) {
'use strict';
$scope.submitLabel = 'Update';
$scope.position = PositionResource.get({id: $routeParams.id});
$scope.submit = function () {
if ($scope.positionForm.$valid) {
PositionResource.update(
{id: $scope.position.id},
$scope.position
).$promise.then(
function (data) {
$scope.$emit('successMessage', 'Saved ' + $scope.position.position);
$location.path('/positions/' + $scope.position.id);
},
function (err) {
$scope.emit('errorMessage', 'Error while saving: ' + err);
});
}
};
}]); | witty-pigeon/jobstracker-spring | src/main/webapp/WEB-INF/js/controllers/positions-edit-ctrl.js | JavaScript | apache-2.0 | 1,066 |
'use strict';
angular.module('dashboardApp')
.directive('hasAnyAuthority', ['Principal', function (Principal) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var setVisible = function () {
element.removeClass('hidden');
},
setHidden = function () {
element.addClass('hidden');
},
defineVisibility = function (reset) {
var result;
if (reset) {
setVisible();
}
result = Principal.hasAnyAuthority(authorities);
if (result) {
setVisible();
} else {
setHidden();
}
},
authorities = attrs.hasAnyAuthority.replace(/\s+/g, '').split(',');
if (authorities.length > 0) {
defineVisibility(true);
}
}
};
}])
.directive('hasAuthority', ['Principal', function (Principal) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var setVisible = function () {
element.removeClass('hidden');
},
setHidden = function () {
element.addClass('hidden');
},
defineVisibility = function (reset) {
if (reset) {
setVisible();
}
Principal.hasAuthority(authority)
.then(function (result) {
if (result) {
setVisible();
} else {
setHidden();
}
});
},
authority = attrs.hasAuthority.replace(/\s+/g, '');
if (authority.length > 0) {
defineVisibility(true);
}
}
};
}]);
| SemanticCloud/SemanticCloud | Dashboard/src/main/webapp/scripts/components/auth/authority.directive.js | JavaScript | apache-2.0 | 2,342 |
import { test } from 'qunit';
import moduleForAcceptance from 'cargo/tests/helpers/module-for-acceptance';
import hasText from 'cargo/tests/helpers/has-text';
moduleForAcceptance('Acceptance | team page');
test('has team organization display', async function(assert) {
server.loadFixtures();
await visit('/teams/github:org:thehydroimpulse');
hasText(assert, '.team-info h1', 'org');
hasText(assert, '.team-info h2', 'thehydroimpulseteam');
});
test('has link to github in team header', async function(assert) {
server.loadFixtures();
await visit('/teams/github:org:thehydroimpulse');
const $githubLink = findWithAssert('.info a');
assert.equal($githubLink.attr('href').trim(), 'https://github.com/org_test');
});
test('github link has image in team header', async function(assert) {
server.loadFixtures();
await visit('/teams/github:org:thehydroimpulse');
const $githubImg = findWithAssert('.info a img');
assert.equal($githubImg.attr('src').trim(), '/assets/GitHub-Mark-32px.png');
});
test('team organization details has github profile icon', async function(assert) {
server.loadFixtures();
await visit('/teams/github:org:thehydroimpulse');
const $githubProfileImg = findWithAssert('.info img');
assert.equal($githubProfileImg.attr('src').trim(), 'https://avatars.githubusercontent.com/u/565790?v=3&s=170');
});
| steveklabnik/crates.io | tests/acceptance/team-page-test.js | JavaScript | apache-2.0 | 1,391 |
var u = Ti.Android != undefined ? 'dp' : 0;
//A window object which will be associated with the stack of windows
exports.AppWindow = function(args) {
var instance = Ti.UI.createWindow(args);
var view = Ti.UI.createView({
height : 40 + u,
width : 320 + u,
layout : 'horizontal',
top : 0 + u,
borderColor : '#133899',
borderWidth : 1,
borderRadius : 1
});
instance.add(view);
var buttonshare = Ti.UI.createButton({
title : 'Share',
left : 5 + u,
right : 5 + u,
bottom : 1 + u,
height : 40 + u,
width : 150 + u
});
view.add(buttonshare);
var buttoncheckin = Ti.UI.createButton({
title : 'Check-In',
left : 5 + u,
right : 5 + u,
bottom : 1 + u,
height : 40 + u,
width : 150 + u
});
view.add(buttoncheckin);
buttoncheckin.addEventListener('click', function() {
globals.tabs.currentTab.open(Ti.UI.createWindow({
title : 'New Window',
backgroundColor : 'white'
}));
});
//news feed
var scrollView = Titanium.UI.createScrollView({
contentWidth:'auto',
contentHeight:'auto',
top:50,
showVerticalScrollIndicator:true,
showHorizontalScrollIndicator:false
});
instance.add(scrollView);
var view = Ti.UI.createView({
backgroundColor:'#EFEFEF',
borderRadius:10,
width:300,
height:1000,
top:0
});
scrollView.add(view);
var button = Titanium.UI.createButton({
title:'Scroll to Top',
height:40,
width:200,
bottom:10
});
view.add(button);
button.addEventListener('click', function()
{
scrollView.scrollTo(0,0);
});
return instance;
};
| fziegler/plates | Resources/views/main/AppWindow.js | JavaScript | apache-2.0 | 1,546 |
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.now();
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = 'December 31 2016 23:59:59 GMT+07:00';
initializeClock('clockdiv', deadline);
| maharanidanathallah/athallah-site-ma | newyear2017.js | JavaScript | apache-2.0 | 1,193 |
/*jshint strict: false, maxlen: 500 */
/*global require, assertEqual */
////////////////////////////////////////////////////////////////////////////////
/// @brief tests for query language, functions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
var internal = require("internal");
var errors = internal.errors;
var jsunity = require("jsunity");
var helper = require("org/arangodb/aql-helper");
var getQueryResults = helper.getQueryResults;
var assertQueryError = helper.assertQueryError;
var assertQueryWarningAndNull = helper.assertQueryWarningAndNull;
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite
////////////////////////////////////////////////////////////////////////////////
function ahuacatlDateFunctionsTestSuite () {
return {
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_now function
////////////////////////////////////////////////////////////////////////////////
testDateNowInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_NOW(1)");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_NOW(1, 1)");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_now function
////////////////////////////////////////////////////////////////////////////////
testDateNow : function () {
var actual = getQueryResults("RETURN IS_NUMBER(DATE_NOW())")[0];
assertEqual(true, actual);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_dayofweek function
////////////////////////////////////////////////////////////////////////////////
testDateDayOfWeekInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_DAYOFWEEK()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_DAYOFWEEK(1, 1)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAYOFWEEK(null)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAYOFWEEK(false)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAYOFWEEK([])");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAYOFWEEK({})");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_dayofweek function
////////////////////////////////////////////////////////////////////////////////
testDateDayOfWeek : function () {
var values = [
[ "2000-04-29", 6 ],
[ "2000-04-29Z", 6 ],
[ "2012-02-12 13:24:12", 0 ],
[ "2012-02-12 13:24:12Z", 0 ],
[ "2012-02-12 23:59:59.991", 0 ],
[ "2012-02-12 23:59:59.991Z", 0 ],
[ "2012-02-12", 0 ],
[ "2012-02-12Z", 0 ],
[ "2012-02-12T13:24:12Z", 0 ],
[ "2012-02-12Z", 0 ],
[ "2012-2-12Z", 0 ],
[ "1910-01-02T03:04:05Z", 0 ],
[ "1910-01-02 03:04:05Z", 0 ],
[ "1910-01-02", 0 ],
[ "1910-01-02Z", 0 ],
[ "1970-01-01T01:05:27", 4 ],
[ "1970-01-01T01:05:27Z", 4 ],
[ "1970-01-01 01:05:27Z", 4 ],
[ "1970-1-1Z", 4 ],
[ "1221-02-28T23:59:59Z", 0 ],
[ "1221-02-28 23:59:59Z", 0 ],
[ "1221-02-28Z", 0 ],
[ "1221-2-28Z", 0 ],
[ "1000-12-24T04:12:00Z", 3 ],
[ "1000-12-24Z", 3 ],
[ "1000-12-24 04:12:00Z", 3 ],
[ "6789-12-31T23:59:58.99Z", 0 ],
[ "6789-12-31Z", 0 ],
[ "9999-12-31T23:59:59.999Z", 5 ],
[ "9999-12-31Z", 5 ],
[ "9999-12-31z", 5 ],
[ "9999-12-31", 5 ],
[ "2012Z", 0 ],
[ "2012z", 0 ],
[ "2012", 0 ],
[ "2012-1Z", 0 ],
[ "2012-1z", 0 ],
[ "2012-1-1z", 0 ],
[ "2012-01-01Z", 0 ],
[ "2012-01-01Z", 0 ],
[ " 2012-01-01Z", 0 ],
[ " 2012-01-01z", 0 ],
[ 1399395674000, 2 ],
[ 60123, 4 ],
[ 1, 4 ],
[ 0, 4 ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_DAYOFWEEK(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_year function
////////////////////////////////////////////////////////////////////////////////
testDateYearInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_YEAR()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_YEAR(1, 1)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_YEAR(null)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_YEAR(false)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_YEAR([])");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_YEAR({})");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_year function
////////////////////////////////////////////////////////////////////////////////
testDateYear : function () {
var values = [
[ "2000-04-29Z", 2000 ],
[ "2012-02-12 13:24:12Z", 2012 ],
[ "2012-02-12 23:59:59.991Z", 2012 ],
[ "2012-02-12Z", 2012 ],
[ "2012-02-12T13:24:12Z", 2012 ],
[ "2012-02-12Z", 2012 ],
[ "2012-2-12Z", 2012 ],
[ "1910-01-02T03:04:05Z", 1910 ],
[ "1910-01-02 03:04:05Z", 1910 ],
[ "1910-01-02Z", 1910 ],
[ "1970-01-01T01:05:27Z", 1970 ],
[ "1970-01-01 01:05:27Z", 1970 ],
[ "1970-1-1Z", 1970 ],
[ "1221-02-28T23:59:59Z", 1221 ],
[ "1221-02-28 23:59:59Z", 1221 ],
[ "1221-02-28Z", 1221 ],
[ "1221-2-28Z", 1221 ],
[ "1000-12-24T04:12:00Z", 1000 ],
[ "1000-12-24Z", 1000 ],
[ "1000-12-24 04:12:00Z", 1000 ],
[ "6789-12-31T23:59:58.99Z", 6789 ],
[ "6789-12-31Z", 6789 ],
[ "9999-12-31T23:59:59.999Z", 9999 ],
[ "9999-12-31Z", 9999 ],
[ "9999-12-31z", 9999 ],
[ "9999-12-31", 9999 ],
[ "2012Z", 2012 ],
[ "2012z", 2012 ],
[ "2012", 2012 ],
[ "2012-1Z", 2012 ],
[ "2012-1z", 2012 ],
[ "2012-1-1z", 2012 ],
[ "2012-01-01Z", 2012 ],
[ "2012-01-01Z", 2012 ],
[ " 2012-01-01Z", 2012 ],
[ " 2012-01-01z", 2012 ],
[ 1399395674000, 2014 ],
[ 60123, 1970 ],
[ 1, 1970 ],
[ 0, 1970 ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_YEAR(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_month function
////////////////////////////////////////////////////////////////////////////////
testDateMonthInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MONTH()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MONTH(1, 1)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MONTH(null)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MONTH(false)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MONTH([])");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MONTH({})");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_month function
////////////////////////////////////////////////////////////////////////////////
testDateMonth : function () {
var values = [
[ "2000-04-29Z", 4 ],
[ "2012-02-12 13:24:12Z", 2 ],
[ "2012-02-12 23:59:59.991Z", 2 ],
[ "2012-02-12Z", 2 ],
[ "2012-02-12T13:24:12Z", 2 ],
[ "2012-02-12Z", 2 ],
[ "2012-2-12Z", 2 ],
[ "1910-01-02T03:04:05Z", 1 ],
[ "1910-01-02 03:04:05Z", 1 ],
[ "1910-01-02Z", 1 ],
[ "1970-01-01T01:05:27Z", 1 ],
[ "1970-01-01 01:05:27Z", 1 ],
[ "1970-1-1Z", 1 ],
[ "1221-02-28T23:59:59Z", 2 ],
[ "1221-02-28 23:59:59Z", 2 ],
[ "1221-02-28Z", 2 ],
[ "1221-2-28Z", 2 ],
[ "1000-12-24T04:12:00Z", 12 ],
[ "1000-12-24Z", 12 ],
[ "1000-12-24 04:12:00Z", 12 ],
[ "6789-12-31T23:59:58.99Z", 12 ],
[ "6789-12-31Z", 12 ],
[ "9999-12-31T23:59:59.999Z", 12 ],
[ "9999-12-31Z", 12 ],
[ "9999-12-31z", 12 ],
[ "9999-12-31", 12 ],
[ "2012Z", 1 ],
[ "2012z", 1 ],
[ "2012", 1 ],
[ "2012-2Z", 2 ],
[ "2012-1Z", 1 ],
[ "2012-1z", 1 ],
[ "2012-1-1z", 1 ],
[ "2012-01-01Z", 1 ],
[ "2012-01-01Z", 1 ],
[ " 2012-01-01Z", 1 ],
[ " 2012-01-01z", 1 ],
[ 1399395674000, 5 ],
[ 60123, 1 ],
[ 1, 1 ],
[ 0, 1 ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_MONTH(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_day function
////////////////////////////////////////////////////////////////////////////////
testDateDayInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_DAY()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_DAY(1, 1)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAY(null)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAY(false)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAY([])");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_DAY({})");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_day function
////////////////////////////////////////////////////////////////////////////////
testDateDay : function () {
var values = [
[ "2000-04-29Z", 29 ],
[ "2012-02-12 13:24:12Z", 12 ],
[ "2012-02-12 23:59:59.991Z", 12 ],
[ "2012-02-12Z", 12 ],
[ "2012-02-12T13:24:12Z", 12 ],
[ "2012-02-12Z", 12 ],
[ "2012-2-12Z", 12 ],
[ "1910-01-02T03:04:05Z", 2 ],
[ "1910-01-02 03:04:05Z", 2 ],
[ "1910-01-02Z", 2 ],
[ "1970-01-01T01:05:27Z", 1 ],
[ "1970-01-01 01:05:27Z", 1 ],
[ "1970-1-1Z", 1 ],
[ "1221-02-28T23:59:59Z", 28 ],
[ "1221-02-28 23:59:59Z", 28 ],
[ "1221-02-28Z", 28 ],
[ "1221-2-28Z", 28 ],
[ "1000-12-24T04:12:00Z", 24 ],
[ "1000-12-24Z", 24 ],
[ "1000-12-24 04:12:00Z", 24 ],
[ "6789-12-31T23:59:58.99Z", 31 ],
[ "6789-12-31Z", 31 ],
[ "9999-12-31T23:59:59.999Z", 31 ],
[ "9999-12-31Z", 31 ],
[ "9999-12-31z", 31 ],
[ "9999-12-31", 31 ],
[ "2012Z", 1 ],
[ "2012z", 1 ],
[ "2012", 1 ],
[ "2012-2Z", 1 ],
[ "2012-1Z", 1 ],
[ "2012-1z", 1 ],
[ "2012-1-1z", 1 ],
[ "2012-01-01Z", 1 ],
[ "2012-01-01Z", 1 ],
[ "2012-01-02Z", 2 ],
[ "2012-01-2Z", 2 ],
[ " 2012-01-01Z", 1 ],
[ " 2012-01-01z", 1 ],
[ 1399395674000, 6 ],
[ 60123, 1 ],
[ 1, 1 ],
[ 0, 1 ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_DAY(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_hour function
////////////////////////////////////////////////////////////////////////////////
testDateHourInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_HOUR()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_HOUR(1, 1)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_HOUR(null)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_HOUR(false)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_HOUR([])");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_HOUR({})");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_hour function
////////////////////////////////////////////////////////////////////////////////
testDateHour : function () {
var values = [
[ "2000-04-29", 0 ],
[ "2000-04-29Z", 0 ],
[ "2012-02-12 13:24:12", 13 ],
[ "2012-02-12 13:24:12Z", 13 ],
[ "2012-02-12 23:59:59.991Z", 23 ],
[ "2012-02-12", 0 ],
[ "2012-02-12Z", 0 ],
[ "2012-02-12T13:24:12", 13 ],
[ "2012-02-12T13:24:12Z", 13 ],
[ "2012-02-12", 0 ],
[ "2012-02-12Z", 0 ],
[ "2012-2-12Z", 0 ],
[ "1910-01-02T03:04:05", 3 ],
[ "1910-01-02T03:04:05Z", 3 ],
[ "1910-01-02 03:04:05Z", 3 ],
[ "1910-01-02Z", 0 ],
[ "1970-01-01T01:05:27Z", 1 ],
[ "1970-01-01 01:05:27Z", 1 ],
[ "1970-01-01T12:05:27Z", 12 ],
[ "1970-01-01 12:05:27Z", 12 ],
[ "1970-1-1Z", 0 ],
[ "1221-02-28T23:59:59Z", 23 ],
[ "1221-02-28 23:59:59Z", 23 ],
[ "1221-02-28Z", 0 ],
[ "1221-2-28Z", 0 ],
[ "1000-12-24T04:12:00Z", 4 ],
[ "1000-12-24Z", 0 ],
[ "1000-12-24 04:12:00Z", 4 ],
[ "6789-12-31T23:59:58.99Z", 23 ],
[ "6789-12-31Z", 0 ],
[ "9999-12-31T23:59:59.999Z", 23 ],
[ "9999-12-31Z", 0 ],
[ "9999-12-31z", 0 ],
[ "9999-12-31", 0 ],
[ "2012Z", 0 ],
[ "2012z", 0 ],
[ "2012", 0 ],
[ "2012-2Z", 0 ],
[ "2012-1Z", 0 ],
[ "2012-1z", 0 ],
[ "2012-1-1z", 0 ],
[ "2012-01-01Z", 0 ],
[ "2012-01-01Z", 0 ],
[ "2012-01-02Z", 0 ],
[ "2012-01-2Z", 0 ],
[ " 2012-01-01Z", 0 ],
[ " 2012-01-01z", 0 ],
[ 1399395674000, 17 ],
[ 3600000, 1 ],
[ 7200000, 2 ],
[ 8200000, 2 ],
[ 60123, 0 ],
[ 1, 0 ],
[ 0, 0 ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_HOUR(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_minute function
////////////////////////////////////////////////////////////////////////////////
testDateMinuteInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MINUTE()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MINUTE(1, 1)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MINUTE(null)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MINUTE(false)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MINUTE([])");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MINUTE({})");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_minute function
////////////////////////////////////////////////////////////////////////////////
testDateMinute : function () {
var values = [
[ "2000-04-29Z", 0 ],
[ "2012-02-12 13:24:12Z", 24 ],
[ "2012-02-12 23:59:59.991Z", 59 ],
[ "2012-02-12Z", 0 ],
[ "2012-02-12T13:24:12Z", 24 ],
[ "2012-02-12Z", 0 ],
[ "2012-2-12Z", 0 ],
[ "1910-01-02T03:04:05Z", 4 ],
[ "1910-01-02 03:04:05Z", 4 ],
[ "1910-01-02Z", 0 ],
[ "1970-01-01T01:05:27Z", 5 ],
[ "1970-01-01 01:05:27Z", 5 ],
[ "1970-01-01T12:05:27Z", 5 ],
[ "1970-01-01 12:05:27Z", 5 ],
[ "1970-1-1Z", 0 ],
[ "1221-02-28T23:59:59Z", 59 ],
[ "1221-02-28 23:59:59Z", 59 ],
[ "1221-02-28Z", 0 ],
[ "1221-2-28Z", 0 ],
[ "1000-12-24T04:12:00Z", 12 ],
[ "1000-12-24Z", 0 ],
[ "1000-12-24 04:12:00Z", 12 ],
[ "6789-12-31T23:59:58.99Z", 59 ],
[ "6789-12-31Z", 0 ],
[ "9999-12-31T23:59:59.999Z", 59 ],
[ "9999-12-31Z", 0 ],
[ "9999-12-31z", 0 ],
[ "9999-12-31", 0 ],
[ "2012Z", 0 ],
[ "2012z", 0 ],
[ "2012", 0 ],
[ "2012-2Z", 0 ],
[ "2012-1Z", 0 ],
[ "2012-1z", 0 ],
[ "2012-1-1z", 0 ],
[ "2012-01-01Z", 0 ],
[ "2012-01-01Z", 0 ],
[ "2012-01-02Z", 0 ],
[ "2012-01-2Z", 0 ],
[ " 2012-01-01Z", 0 ],
[ " 2012-01-01z", 0 ],
[ 1399395674000, 1 ],
[ 3600000, 0 ],
[ 7200000, 0 ],
[ 8200000, 16 ],
[ 60123, 1 ],
[ 1, 0 ],
[ 0, 0 ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_MINUTE(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_second function
////////////////////////////////////////////////////////////////////////////////
testDateSecondInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_SECOND()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_SECOND(1, 1)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_SECOND(null)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_SECOND(false)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_SECOND([])");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_SECOND({})");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_second function
////////////////////////////////////////////////////////////////////////////////
testDateSecond : function () {
var values = [
[ "2000-04-29Z", 0 ],
[ "2012-02-12 13:24:12Z", 12 ],
[ "2012-02-12 23:59:59.991Z", 59 ],
[ "2012-02-12Z", 0 ],
[ "2012-02-12T13:24:12Z", 12 ],
[ "2012-02-12Z", 0 ],
[ "2012-2-12Z", 0 ],
[ "1910-01-02T03:04:05Z", 5 ],
[ "1910-01-02 03:04:05Z", 5 ],
[ "1910-01-02Z", 0 ],
[ "1970-01-01T01:05:27Z", 27 ],
[ "1970-01-01 01:05:27Z", 27 ],
[ "1970-01-01T12:05:27Z", 27 ],
[ "1970-01-01 12:05:27Z", 27 ],
[ "1970-1-1Z", 0 ],
[ "1221-02-28T23:59:59Z", 59 ],
[ "1221-02-28 23:59:59Z", 59 ],
[ "1221-02-28Z", 0 ],
[ "1221-2-28Z", 0 ],
[ "1000-12-24T04:12:00Z", 0 ],
[ "1000-12-24Z", 0 ],
[ "1000-12-24 04:12:00Z", 0 ],
[ "6789-12-31T23:59:58.99Z", 58 ],
[ "6789-12-31Z", 0 ],
[ "9999-12-31T23:59:59.999Z", 59 ],
[ "9999-12-31Z", 0 ],
[ "9999-12-31z", 0 ],
[ "9999-12-31", 0 ],
[ "2012Z", 0 ],
[ "2012z", 0 ],
[ "2012", 0 ],
[ "2012-2Z", 0 ],
[ "2012-1Z", 0 ],
[ "2012-1z", 0 ],
[ "2012-1-1z", 0 ],
[ "2012-01-01Z", 0 ],
[ "2012-01-01Z", 0 ],
[ "2012-01-02Z", 0 ],
[ "2012-01-2Z", 0 ],
[ " 2012-01-01Z", 0 ],
[ " 2012-01-01z", 0 ],
[ 1399395674000, 14 ],
[ 3600000, 0 ],
[ 7200000, 0 ],
[ 8200000, 40 ],
[ 61123, 1 ],
[ 60123, 0 ],
[ 2001, 2 ],
[ 2000, 2 ],
[ 1000, 1 ],
[ 1, 0 ],
[ 0, 0 ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_SECOND(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_millisecond function
////////////////////////////////////////////////////////////////////////////////
testDateMillisecondInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MILLISECOND()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_MILLISECOND(1, 1)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MILLISECOND(null)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MILLISECOND(false)");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MILLISECOND([])");
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_MILLISECOND({})");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_millisecond function
////////////////////////////////////////////////////////////////////////////////
testDateMillisecond : function () {
var values = [
[ "2000-04-29Z", 0 ],
[ "2012-02-12 13:24:12Z", 0 ],
[ "2012-02-12 23:59:59.991Z", 991 ],
[ "2012-02-12Z", 0 ],
[ "2012-02-12T13:24:12Z", 0 ],
[ "2012-02-12Z", 0 ],
[ "2012-2-12Z", 0 ],
[ "1910-01-02T03:04:05Z", 0 ],
[ "1910-01-02 03:04:05Z", 0 ],
[ "1910-01-02Z", 0 ],
[ "1970-01-01T01:05:27Z", 0 ],
[ "1970-01-01 01:05:27Z", 0 ],
[ "1970-01-01T12:05:27Z", 0 ],
[ "1970-01-01 12:05:27Z", 0 ],
[ "1970-1-1Z", 0 ],
[ "1221-02-28T23:59:59Z", 0 ],
[ "1221-02-28 23:59:59Z", 0 ],
[ "1221-02-28Z", 0 ],
[ "1221-2-28Z", 0 ],
[ "1000-12-24T04:12:00Z", 0 ],
[ "1000-12-24Z", 0 ],
[ "1000-12-24 04:12:00Z", 0 ],
[ "6789-12-31T23:59:58.99Z", 990 ],
[ "6789-12-31Z", 0 ],
[ "9999-12-31T23:59:59.999Z", 999 ],
[ "9999-12-31Z", 0 ],
[ "9999-12-31z", 0 ],
[ "9999-12-31", 0 ],
[ "2012Z", 0 ],
[ "2012z", 0 ],
[ "2012", 0 ],
[ "2012-2Z", 0 ],
[ "2012-1Z", 0 ],
[ "2012-1z", 0 ],
[ "2012-1-1z", 0 ],
[ "2012-01-01Z", 0 ],
[ "2012-01-01Z", 0 ],
[ "2012-01-02Z", 0 ],
[ "2012-01-2Z", 0 ],
[ " 2012-01-01Z", 0 ],
[ " 2012-01-01z", 0 ],
[ 1399395674000, 0 ],
[ 1399395674123, 123 ],
[ 3600000, 0 ],
[ 7200000, 0 ],
[ 8200000, 0 ],
[ 8200040, 40 ],
[ 61123, 123 ],
[ 60123, 123 ],
[ 2001, 1 ],
[ 2000, 0 ],
[ 1000, 0 ],
[ 753, 753 ],
[ 53, 53 ],
[ 1, 1 ],
[ 0, 0 ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_MILLISECOND(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_timestamp function
////////////////////////////////////////////////////////////////////////////////
testDateTimestampInvalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_TIMESTAMP()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_TIMESTAMP(1, 1, 1, 1, 1, 1, 1, 1)");
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_timestamp function
////////////////////////////////////////////////////////////////////////////////
testDateTimestamp : function () {
var values = [
[ "2000-04-29", 956966400000 ],
[ "2000-04-29Z", 956966400000 ],
[ "2012-02-12 13:24:12", 1329053052000 ],
[ "2012-02-12 13:24:12Z", 1329053052000 ],
[ "2012-02-12 23:59:59.991", 1329091199991 ],
[ "2012-02-12 23:59:59.991Z", 1329091199991 ],
[ "2012-02-12", 1329004800000 ],
[ "2012-02-12Z", 1329004800000 ],
[ "2012-02-12T13:24:12", 1329053052000 ],
[ "2012-02-12T13:24:12Z", 1329053052000 ],
[ "2012-02-12Z", 1329004800000 ],
[ "2012-2-12Z", 1329004800000 ],
[ "1910-01-02T03:04:05", -1893358555000 ],
[ "1910-01-02T03:04:05Z", -1893358555000 ],
[ "1910-01-02 03:04:05Z", -1893358555000 ],
[ "1910-01-02", -1893369600000 ],
[ "1910-01-02Z", -1893369600000 ],
[ "1970-01-01T01:05:27Z", 3927000 ],
[ "1970-01-01 01:05:27Z", 3927000 ],
[ "1970-01-01T12:05:27Z", 43527000 ],
[ "1970-01-01 12:05:27Z", 43527000 ],
[ "1970-1-1Z", 0 ],
[ "1221-02-28T23:59:59Z", -23631004801000 ],
[ "1221-02-28 23:59:59Z", -23631004801000 ],
[ "1221-02-28Z", -23631091200000 ],
[ "1221-2-28Z", -23631091200000 ],
[ "1000-12-24T04:12:00Z", -30579364080000 ],
[ "1000-12-24Z", -30579379200000 ],
[ "1000-12-24 04:12:00Z", -30579364080000 ],
[ "6789-12-31T23:59:58.99Z", 152104521598990 ],
[ "6789-12-31Z", 152104435200000 ],
[ "9999-12-31T23:59:59.999Z", 253402300799999 ],
[ "9999-12-31Z", 253402214400000 ],
[ "9999-12-31z", 253402214400000 ],
[ "9999-12-31", 253402214400000 ],
[ "2012Z", 1325376000000 ],
[ "2012z", 1325376000000 ],
[ "2012", 1325376000000 ],
[ "2012-2Z", 1328054400000 ],
[ "2012-1Z", 1325376000000 ],
[ "2012-1z", 1325376000000 ],
[ "2012-1-1z", 1325376000000 ],
[ "2012-01-01Z", 1325376000000 ],
[ "2012-01-01Z", 1325376000000 ],
[ "2012-01-02Z", 1325462400000 ],
[ "2012-01-2Z", 1325462400000 ],
[ " 2012-01-01Z", 1325376000000 ],
[ " 2012-01-01z", 1325376000000 ],
[ 1399395674000, 1399395674000 ],
[ 3600000, 3600000 ],
[ 7200000, 7200000 ],
[ 8200000, 8200000 ],
[ 61123, 61123 ],
[ 60123, 60123 ],
[ 2001, 2001 ],
[ 2000, 2000 ],
[ 1000, 1000 ],
[ 121, 121 ],
[ 1, 1 ],
[ 0, 0 ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_TIMESTAMP(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_iso8601 function
////////////////////////////////////////////////////////////////////////////////
testDateIso8601Invalid : function () {
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_ISO8601()");
assertQueryError(errors.ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH.code, "RETURN DATE_ISO8601(1, 1, 1, 1, 1, 1, 1, 1)");
var values = [
"foobar",
"2012fjh",
" 2012tjjgg",
"",
" ",
"abc2012-01-01",
"2000-00-00",
"2001-02-11 24:00:00",
"2001-02-11 24:01:01",
"2001-02-11 25:01:01",
"2001-02-11 23:60:00",
"2001-02-11 23:01:60",
"2001-02-11 23:01:99",
"2001-00-11",
"2001-0-11",
"2001-13-11",
"2001-13-32",
"2001-01-0",
"2001-01-00",
"2001-01-32",
"2001-1-32"
];
values.forEach(function(value) {
assertQueryWarningAndNull(errors.ERROR_QUERY_INVALID_DATE_VALUE.code, "RETURN DATE_ISO8601(@value)", { value: value });
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_iso8601 function
////////////////////////////////////////////////////////////////////////////////
testDateIso8601 : function () {
var values = [
[ "2000-04-29", "2000-04-29T00:00:00.000Z" ],
[ "2000-04-29Z", "2000-04-29T00:00:00.000Z" ],
[ "2012-02-12 13:24:12", "2012-02-12T13:24:12.000Z" ],
[ "2012-02-12 13:24:12Z", "2012-02-12T13:24:12.000Z" ],
[ "2012-02-12 23:59:59.991", "2012-02-12T23:59:59.991Z" ],
[ "2012-02-12 23:59:59.991Z", "2012-02-12T23:59:59.991Z" ],
[ "2012-02-12", "2012-02-12T00:00:00.000Z" ],
[ "2012-02-12Z", "2012-02-12T00:00:00.000Z" ],
[ "2012-02-12T13:24:12", "2012-02-12T13:24:12.000Z" ],
[ "2012-02-12T13:24:12Z", "2012-02-12T13:24:12.000Z" ],
[ "2012-02-12Z", "2012-02-12T00:00:00.000Z" ],
[ "2012-2-12Z", "2012-02-12T00:00:00.000Z" ],
[ "1910-01-02T03:04:05", "1910-01-02T03:04:05.000Z" ],
[ "1910-01-02T03:04:05Z", "1910-01-02T03:04:05.000Z" ],
[ "1910-01-02 03:04:05", "1910-01-02T03:04:05.000Z" ],
[ "1910-01-02 03:04:05Z", "1910-01-02T03:04:05.000Z" ],
[ "1910-01-02", "1910-01-02T00:00:00.000Z" ],
[ "1910-01-02Z", "1910-01-02T00:00:00.000Z" ],
[ "1970-01-01T01:05:27+01:00", "1970-01-01T00:05:27.000Z" ],
[ "1970-01-01T01:05:27-01:00", "1970-01-01T02:05:27.000Z" ],
[ "1970-01-01T01:05:27", "1970-01-01T01:05:27.000Z" ],
[ "1970-01-01T01:05:27Z", "1970-01-01T01:05:27.000Z" ],
[ "1970-01-01 01:05:27Z", "1970-01-01T01:05:27.000Z" ],
[ "1970-01-01T12:05:27Z", "1970-01-01T12:05:27.000Z" ],
[ "1970-01-01 12:05:27Z", "1970-01-01T12:05:27.000Z" ],
[ "1970-1-1Z", "1970-01-01T00:00:00.000Z" ],
[ "1221-02-28T23:59:59", "1221-02-28T23:59:59.000Z" ],
[ "1221-02-28T23:59:59Z", "1221-02-28T23:59:59.000Z" ],
[ "1221-02-28 23:59:59Z", "1221-02-28T23:59:59.000Z" ],
[ "1221-02-28", "1221-02-28T00:00:00.000Z" ],
[ "1221-02-28Z", "1221-02-28T00:00:00.000Z" ],
[ "1221-2-28Z", "1221-02-28T00:00:00.000Z" ],
[ "1000-12-24T04:12:00Z", "1000-12-24T04:12:00.000Z" ],
[ "1000-12-24Z", "1000-12-24T00:00:00.000Z" ],
[ "1000-12-24 04:12:00Z", "1000-12-24T04:12:00.000Z" ],
[ "6789-12-31T23:59:58.99Z", "6789-12-31T23:59:58.990Z" ],
[ "6789-12-31Z", "6789-12-31T00:00:00.000Z" ],
[ "9999-12-31T23:59:59.999Z", "9999-12-31T23:59:59.999Z" ],
[ "9999-12-31Z", "9999-12-31T00:00:00.000Z" ],
[ "9999-12-31z", "9999-12-31T00:00:00.000Z" ],
[ "9999-12-31", "9999-12-31T00:00:00.000Z" ],
[ "2012Z", "2012-01-01T00:00:00.000Z" ],
[ "2012z", "2012-01-01T00:00:00.000Z" ],
[ "2012", "2012-01-01T00:00:00.000Z" ],
[ "2012-2Z", "2012-02-01T00:00:00.000Z" ],
[ "2012-1Z", "2012-01-01T00:00:00.000Z" ],
[ "2012-1z", "2012-01-01T00:00:00.000Z" ],
[ "2012-1-1z", "2012-01-01T00:00:00.000Z" ],
[ "2012-01-01", "2012-01-01T00:00:00.000Z" ],
[ "2012-01-01Z", "2012-01-01T00:00:00.000Z" ],
[ "2012-01-01Z", "2012-01-01T00:00:00.000Z" ],
[ "2012-01-02Z", "2012-01-02T00:00:00.000Z" ],
[ "2012-01-2Z", "2012-01-02T00:00:00.000Z" ],
[ " 2012-01-01Z", "2012-01-01T00:00:00.000Z" ],
[ " 2012-01-01z", "2012-01-01T00:00:00.000Z" ],
[ 1399395674000, "2014-05-06T17:01:14.000Z" ],
[ 3600000, "1970-01-01T01:00:00.000Z" ],
[ 7200000, "1970-01-01T02:00:00.000Z" ],
[ 8200000, "1970-01-01T02:16:40.000Z" ],
[ 61123, "1970-01-01T00:01:01.123Z" ],
[ 60123, "1970-01-01T00:01:00.123Z" ],
[ 2001, "1970-01-01T00:00:02.001Z" ],
[ 2000, "1970-01-01T00:00:02.000Z" ],
[ 1000, "1970-01-01T00:00:01.000Z" ],
[ 121, "1970-01-01T00:00:00.121Z" ],
[ 1, "1970-01-01T00:00:00.001Z" ],
[ 0, "1970-01-01T00:00:00.000Z" ]
];
values.forEach(function (value) {
var actual = getQueryResults("RETURN DATE_ISO8601(@value)", { value: value[0] });
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date_iso8601 function
////////////////////////////////////////////////////////////////////////////////
testDateIso8601Alternative : function () {
var values = [
[ [ 1000, 1, 1, 0, 0, 0, 0 ], "1000-01-01T00:00:00.000Z" ],
[ [ 9999, 12, 31, 23, 59, 59, 999 ], "9999-12-31T23:59:59.999Z" ],
[ [ 2012, 1, 1, 13, 12, 14, 95 ], "2012-01-01T13:12:14.095Z" ],
[ [ 1234, 12, 31, 23, 59, 59, 477 ], "1234-12-31T23:59:59.477Z" ],
[ [ 2014, 5, 7, 12, 6 ], "2014-05-07T12:06:00.000Z" ],
[ [ 2014, 5, 7, 12 ], "2014-05-07T12:00:00.000Z" ],
[ [ 2014, 5, 7 ], "2014-05-07T00:00:00.000Z" ],
[ [ 2014, 5, 7 ], "2014-05-07T00:00:00.000Z" ],
[ [ 1000, 1, 1 ], "1000-01-01T00:00:00.000Z" ],
[ [ "1000", "01", "01", "00", "00", "00", "00" ], "1000-01-01T00:00:00.000Z" ],
[ [ "1000", "1", "1", "0", "0", "0", "0" ], "1000-01-01T00:00:00.000Z" ],
[ [ "9999", "12", "31", "23", "59", "59", "999" ], "9999-12-31T23:59:59.999Z" ],
[ [ "2012", "1", "1", "13", "12", "14", "95" ], "2012-01-01T13:12:14.095Z" ],
[ [ "1234", "12", "31", "23", "59", "59", "477" ], "1234-12-31T23:59:59.477Z" ],
[ [ "2014", "05", "07", "12", "06" ], "2014-05-07T12:06:00.000Z" ],
[ [ "2014", "5", "7", "12", "6" ], "2014-05-07T12:06:00.000Z" ],
[ [ "2014", "5", "7", "12" ], "2014-05-07T12:00:00.000Z" ],
[ [ "2014", "5", "7" ], "2014-05-07T00:00:00.000Z" ],
[ [ "2014", "5", "7" ], "2014-05-07T00:00:00.000Z" ],
[ [ "1000", "01", "01" ], "1000-01-01T00:00:00.000Z" ],
[ [ "1000", "1", "1" ], "1000-01-01T00:00:00.000Z" ],
];
values.forEach(function (value) {
var query = "RETURN DATE_ISO8601(" +
value[0].map(function(v) {
return JSON.stringify(v);
}).join(", ") + ")";
var actual = getQueryResults(query);
assertEqual([ value[1] ], actual);
});
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date transformations
////////////////////////////////////////////////////////////////////////////////
testDateTransformations1 : function () {
var dt = "2014-05-07T15:23:21.446";
var actual;
actual = getQueryResults("RETURN DATE_TIMESTAMP(DATE_YEAR(@value), DATE_MONTH(@value), DATE_DAY(@value), DATE_HOUR(@value), DATE_MINUTE(@value), DATE_SECOND(@value), DATE_MILLISECOND(@value))", { value: dt });
assertEqual([ new Date(dt).getTime() ], actual);
actual = getQueryResults("RETURN DATE_TIMESTAMP(DATE_YEAR(@value), DATE_MONTH(@value), DATE_DAY(@value), DATE_HOUR(@value), DATE_MINUTE(@value), DATE_SECOND(@value), DATE_MILLISECOND(@value))", { value: dt + "Z" });
assertEqual([ new Date(dt).getTime() ], actual);
},
////////////////////////////////////////////////////////////////////////////////
/// @brief test date transformations
////////////////////////////////////////////////////////////////////////////////
testDateTransformations2 : function () {
var dt = "2014-05-07T15:23:21.446";
var actual;
actual = getQueryResults("RETURN DATE_ISO8601(DATE_TIMESTAMP(DATE_YEAR(@value), DATE_MONTH(@value), DATE_DAY(@value), DATE_HOUR(@value), DATE_MINUTE(@value), DATE_SECOND(@value), DATE_MILLISECOND(@value)))", { value: dt });
assertEqual([ dt + "Z" ], actual);
actual = getQueryResults("RETURN DATE_ISO8601(DATE_TIMESTAMP(DATE_YEAR(@value), DATE_MONTH(@value), DATE_DAY(@value), DATE_HOUR(@value), DATE_MINUTE(@value), DATE_SECOND(@value), DATE_MILLISECOND(@value)))", { value: dt + "Z" });
assertEqual([ dt + "Z" ], actual);
}
};
}
////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suite
////////////////////////////////////////////////////////////////////////////////
jsunity.run(ahuacatlDateFunctionsTestSuite);
return jsunity.done();
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:
| morsdatum/ArangoDB | js/server/tests/aql-functions-date.js | JavaScript | apache-2.0 | 38,362 |
var functions_dup =
[
[ "_", "functions.html", null ],
[ "a", "functions_a.html", null ],
[ "b", "functions_b.html", null ],
[ "c", "functions_c.html", null ],
[ "d", "functions_d.html", null ],
[ "e", "functions_e.html", null ],
[ "f", "functions_f.html", null ],
[ "g", "functions_g.html", null ],
[ "h", "functions_h.html", null ],
[ "i", "functions_i.html", null ],
[ "k", "functions_k.html", null ],
[ "l", "functions_l.html", null ],
[ "m", "functions_m.html", null ],
[ "n", "functions_n.html", null ],
[ "o", "functions_o.html", null ],
[ "p", "functions_p.html", null ],
[ "r", "functions_r.html", null ],
[ "s", "functions_s.html", null ],
[ "t", "functions_t.html", null ],
[ "u", "functions_u.html", null ],
[ "v", "functions_v.html", null ],
[ "w", "functions_w.html", null ],
[ "x", "functions_x.html", null ],
[ "z", "functions_z.html", null ]
]; | grbd/GBD.Build.BlackJack | docs/doxygen/html/functions_dup.js | JavaScript | apache-2.0 | 957 |
/**
* Forge SDK
* The Forge Platform contains an expanding collection of web service components that can be used with Autodesk cloud-based products or your own technologies. Take advantage of Autodesk’s expertise in design and engineering.
*
* OpenAPI spec version: 0.1.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* 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.
*/
module.export = (function() {
'use strict';
var expect = require('expect.js'),
ForgeSdk = require('../../src');
describe('JobPayloadInput', function() {
it('should create an instance of JobPayloadInput', function() {
var instance = new ForgeSdk.JobPayloadInput();
expect(instance).to.be.a(ForgeSdk.JobPayloadInput);
});
});
}());
| Autodesk-Forge/forge-api-nodejs-client | test/model/JobPayloadInput.spec.js | JavaScript | apache-2.0 | 1,409 |
import React from 'react'
import PropTypes from 'prop-types'
import Search from '../components/Search//Search'
import FacetQueryParms from '../modules/FacetQueryParams'
import HoneycombURL from '../modules/HoneycombURL'
const SearchPage = ({ match, children }) => {
const queryParams = new URLSearchParams(window.location.search)
return (
<div>
<Search
collection={HoneycombURL() + '/v1/collections/' + match.params.collectionID}
hits={HoneycombURL() + '/v1/collections/' + match.params.collectionID + '/search'}
searchTerm={queryParams.get('q') || ''}
sortTerm={queryParams.get('sort')}
facet={FacetQueryParms()}
matchMode={queryParams.get('mode')}
field={queryParams.get('field')}
start={parseInt(queryParams.get('start'), 10)}
view={queryParams.get('view')}
currentItem={queryParams.get('item')}
/>
{children}
</div>
)
}
SearchPage.propTypes = {
match: PropTypes.shape({
params: PropTypes.shape({
collectionID: PropTypes.string,
}),
}),
children: PropTypes.node,
}
export default SearchPage
| ndlib/beehive | src/routes/SearchPage.js | JavaScript | apache-2.0 | 1,127 |
/*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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 { shallow } from 'enzyme';
import Immutable from 'immutable';
import WorkersGrid, { WORKER_STATE_TO_COLOR as gridColors } from './WorkersGrid';
describe('WorkersGrid', () => {
let minimalProps;
let commonProps;
beforeEach(() => {
minimalProps = {
entity: Immutable.fromJS({
workersSummary: {
active: 0,
pending: 0,
disconnected: 0,
decommissioning: 0
}
})
};
commonProps = {
...minimalProps,
entity: Immutable.fromJS({
workersSummary: {
active: 1,
pending: 2,
disconnected: 3,
decommissioning: 4
}
})
};
});
it('should render with minimal props without exploding', () => {
const wrapper = shallow(<WorkersGrid {...minimalProps}/>);
expect(wrapper).to.have.length(1);
});
describe('getGridItemSize', () => {
let wrapper;
let instance;
beforeEach(() => {
wrapper = shallow(<WorkersGrid {...minimalProps}/>);
instance = wrapper.instance();
});
it('should return 15 when worker\'s count less then 40', () => {
const gridItems = [
{ workerState: 'active', value: 39 },
{ workerState: 'pending', value: 1 },
{ workerState: 'provisioning', value: 0 },
{ workerState: 'decommissioning', value: 0 }
];
expect(instance.getGridItemSize(gridItems)).to.be.eql(15);
});
it('should return 9 when worker\'s count less more then 40 but less then 175', () => {
let gridItems = [
{ workerState: 'active', value: 39 },
{ workerState: 'pending', value: 2 },
{ workerState: 'disconnected', value: 0 },
{ workerState: 'decommissioning', value: 0 }
];
expect(instance.getGridItemSize(gridItems)).to.be.eql(9);
gridItems = [
{ workerState: 'active', value: 174 },
{ workerState: 'pending', value: 1 },
{ workerState: 'disconnected', value: 0 },
{ workerState: 'decommissioning', value: 0 }
];
expect(instance.getGridItemSize(gridItems)).to.be.eql(9);
});
it('should return 5 when worker\'s count less more then 175', () => {
const gridItems = [
{ workerState: 'active', value: 175 },
{ workerState: 'pending', value: 1 },
{ workerState: 'disconnected', value: 0 },
{ workerState: 'decommissioning', value: 0 }
];
expect(instance.getGridItemSize(gridItems)).to.be.eql(5);
});
});
describe('renderWorkersGrid', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<WorkersGrid {...minimalProps}/>);
});
it('should render no items by default', () => {
expect(wrapper.find('.grid-list').children()).to.have.length(0);
});
it('should render same quantity of squares as total workers size', () => {
wrapper.setProps(commonProps);
expect(wrapper.find('.grid-list').children()).to.have.length(10);
});
it('should render squares in following order: active, pending, provisioning, decommissioning', () => {
wrapper.setProps(commonProps);
const allGridItems = wrapper.find('.grid-list').children();
const getChildrenInRange = (start, end) => {
const range = [];
allGridItems.forEach((item, i) => {
if (i < start || i >= end) {
return;
}
range.push(item);
});
return range;
};
const getItemsColor = (children) => {
return Immutable.Set(children.map((child) => child.props('style').style.background)).toJS();
};
const active = getChildrenInRange(0, 1);
const pending = getChildrenInRange(1, 3);
const disconnected = getChildrenInRange(3, 6);
const decommissioning = getChildrenInRange(6, 9);
expect(getItemsColor(active)).to.be.eql([gridColors.active]);
expect(getItemsColor(pending)).to.be.eql([gridColors.pending]);
expect(getItemsColor(disconnected)).to.be.eql([gridColors.disconnected]);
expect(getItemsColor(decommissioning)).to.be.eql([gridColors.decommissioning]);
});
});
});
| dremio/dremio-oss | dac/ui/src/pages/AdminPage/subpages/Provisioning/components/WorkersGrid-spec.js | JavaScript | apache-2.0 | 4,743 |
(function($) {
$.Arte.Toolbar.ButtonWithDialog = function(toolbar, buttonName, config) {
var me = this;
$.Arte.Toolbar.Button.call(this, toolbar, buttonName, config);
var dialogClasses = $.Arte.Toolbar.configuration.classes.dialog;
this.executeCommand = function() {
if (me.isEnabled()) {
me.showPopup();
}
};
this.getOkCancelControl = function() {
var wrapper = $("<div>").addClass(dialogClasses.okCancel);
$("<a>").attr("href", "#").addClass(dialogClasses.button + " ok").html("✓").appendTo(wrapper);
$("<a>").attr("href", "#").addClass(dialogClasses.button + " cancel").html("✗").appendTo(wrapper);
return wrapper;
};
this.showPopup = function() {
var dialogContainer = $("." + dialogClasses.container);
var contentWrapper = $("<div>").addClass(dialogClasses.contentWrapper).appendTo(dialogContainer);
contentWrapper.append(me.getDialogContent());
contentWrapper.append(me.getOkCancelControl());
dialogContainer.on("mousedown ", function(e) {
e.stopPropagation();
});
var savedSelection = rangy.saveSelection();
me.addContent();
contentWrapper.find(".ok").on("click", function() {
rangy.restoreSelection(savedSelection);
me.onOk();
me.closePopup();
});
contentWrapper.find(".cancel").on("click", function() {
rangy.restoreSelection(savedSelection);
me.closePopup();
});
dialogContainer.show({
duration: 200,
complete: function() {
contentWrapper.css("margin-top", -1 * contentWrapper.height() / 2);
}
});
};
this.closePopup = function() {
var dialogContainer = $("." + dialogClasses.container);
dialogContainer.children().each(function() {
this.remove();
});
dialogContainer.hide();
};
return me;
};
})(jQuery);
(function() {
$.Arte.Toolbar.InsertLink = function(toolbar, buttonName, config) {
var dialogClasses = $.Arte.Toolbar.configuration.classes.dialog;
var insertLinkClasses = dialogClasses.insertLink;
$.Arte.Toolbar.ButtonWithDialog.call(this, toolbar, buttonName, config);
var insertContent = function(contentToInsert) {
$.each(toolbar.selectionManager.getSelectedEditors(), function() {
this.insert.call(this, {
commandValue: contentToInsert
});
});
};
this.getDialogContent = function() {
var textToShow = $("<div>").addClass(dialogClasses.insertLink.textToShow);
$("<span>").html("Text to Show: ").addClass(dialogClasses.label).appendTo(textToShow);
$("<input>").addClass(insertLinkClasses.input + " textToShow").attr({
type: "text"
}).appendTo(textToShow);
var urlInput = $("<div>").addClass(dialogClasses.insertLink.urlInput);
$("<span>").html("Url: ").addClass(dialogClasses.label).appendTo(urlInput);
$("<input>").addClass(insertLinkClasses.input + " url").attr({
type: "text"
}).appendTo(urlInput);
var dialogContent = $("<div>").addClass(dialogClasses.content).append(textToShow).append(urlInput);
return dialogContent;
};
this.onOk = function() {
var textToShow = $("." + dialogClasses.container + " ." + dialogClasses.insertLink.textToShow + " input").val();
var url = $("." + dialogClasses.container + " ." + dialogClasses.insertLink.urlInput + " input").val();
if (url) {
var html = $("<a>").attr("href", url).html(textToShow || url);
insertContent(html.get(0).outerHTML);
}
};
this.addContent = function() {
$("." + dialogClasses.container + " .textToShow").val(rangy.getSelection().toHtml());
};
};
})(jQuery);
(function() {
$.Arte.Toolbar.InsertImage = function(toolbar, buttonName, config) {
var dialogClasses = $.Arte.Toolbar.configuration.classes.dialog;
var insertLinkClasses = dialogClasses.insertLink;
$.Arte.Toolbar.ButtonWithDialog.call(this, toolbar, buttonName, config);
var insertContent = function(contentToInsert) {
$.each(toolbar.selectionManager.getSelectedEditors(), function() {
this.insert.call(this, {
commandValue: contentToInsert
});
});
};
this.getDialogContent = function() {
var dialogContent = $("<div>").addClass("input-prepend input-append");
$("<span>").html("Text to Show: ").addClass(insertLinkClasses.label).appendTo(dialogContent);
$("<input>").addClass(insertLinkClasses.input + " textToShow").attr({
type: "text"
}).appendTo(dialogContent).css({
height: "auto"
});
$("<span>").html("Url: ").addClass(insertLinkClasses.label).appendTo(dialogContent);
$("<input>").addClass(insertLinkClasses.input + " url").attr({
type: "text"
}).appendTo(dialogContent).css({
height: "auto"
});
return dialogContent;
};
this.onOk = function() {
var contentToInsert = $("." + dialogClasses.container + " .url").val();
if (contentToInsert) {
var html = $("<img>").attr("src", contentToInsert);
insertContent(html.get(0).outerHTML);
}
};
this.addContent = function() {
$("." + dialogClasses.container + " .textToShow").val(rangy.getSelection().toHtml());
};
};
})(jQuery);
| vistaprint/ArteJS | src/toolbar/Buttons/ButtonWithDialog.js | JavaScript | apache-2.0 | 6,093 |
webpackHotUpdate(0,[
/* 0 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function($) {var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(158);
var bootstrap = __webpack_require__(159);
var pullRight = {
float: "right",
marginRight: "5%"
};
var footStyle = {
position: "absolute",
bottom: "0",
height: "50px",
width: "100%",
borderTop: "1px solid #ccc"
};
var ContactBox = React.createClass({displayName: "ContactBox",
LoadContactsFromServer: function(){
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data){
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err){
console.log(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function(){
this.LoadContactsFromServer();
},
render: function(){
return (
React.createElement("div", null,
React.createElement(ContactHeader, null),
React.createElement(ContactList, {data: this.state.data}),
React.createElement(ContactFoot, null)
)
);
}
});
var ContactHeader = React.createClass({displayName: "ContactHeader",
render: function(){
return (
React.createElement(bootstrap.Navbar, {toggleNavKey: 0},
React.createElement(bootstrap.NavBrand, null, "G-Address"),
React.createElement(bootstrap.CollapsibleNav, {eventKey: 0},
React.createElement(bootstrap.Nav, {navbar: true, right: true},
React.createElement(bootstrap.NavItem, {href: "/login", eventKey: 1}, "登录")
)
)
)
);
}
});
var ContactList = React.createClass({displayName: "ContactList",
render: function(){
var contactNodes = this.props.data.map(function(contact, index){
return (
React.createElement(Contact, {key: index}, contact.name)
);
});
return (
React.createElement(bootstrap.ListGroup, null,
contactNodes
)
);
}
});
var Contact = React.createClass({displayName: "Contact",
render: function(){
return (
React.createElement(bootstrap.ListGroupItem, {href: "#"},
this.props.children,
React.createElement("span", null, React.createElement(bootstrap.Glyphicon, {glyph: "chevron-right", style: pullRight}))
)
);
}
});
var ContactFoot = React.createClass({displayName: "ContactFoot",
render: function(){
return (
React.createElement("div", {style: footStyle}
)
);
}
});
ReactDOM.render(React.createElement(ContactBox, {url: "/contacts/data"}), document.getElementById("content"));
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1)))
/***/ }
]) | JivaGzw/Gaddress | build/0.ce253bb41e20f52ec882.hot-update.js | JavaScript | apache-2.0 | 2,854 |
function updateScreenSize(size) {
return {
type: 'RECEIVE_SIZE',
size
};
}
function setRenderer(renderer) {
return {
type: 'RECEIVE_RENDERER',
renderer
};
}
function setCanvas(canvas) {
return {
type: 'RECEIVE_CANVAS',
canvas
};
}
export default {
updateScreenSize,
setRenderer,
setCanvas,
};
| eventbrite/cartogram | src/actions/core.js | JavaScript | apache-2.0 | 381 |
// This file was automatically generated. Do not modify.
'use strict';
goog.provide('Blockly.Msg.dty');
goog.require('Blockly.Msg');
Blockly.Msg["ADD_COMMENT"] = "टिप्पणी थप्दे";
Blockly.Msg["CANNOT_DELETE_VARIABLE_PROCEDURE"] = "Can't delete the variable '%1' because it's part of the definition of the function '%2'"; // untranslated
Blockly.Msg["CHANGE_VALUE_TITLE"] = "मान बदल";
Blockly.Msg["CLEAN_UP"] = "ब्लकनलाई हटाओ";
Blockly.Msg["COLLAPSE_ALL"] = "ब्लक भत्काओ";
Blockly.Msg["COLLAPSE_BLOCK"] = "ब्लक भत्का";
Blockly.Msg["COLOUR_BLEND_COLOUR1"] = "रंग 1";
Blockly.Msg["COLOUR_BLEND_COLOUR2"] = "रंग 2";
Blockly.Msg["COLOUR_BLEND_HELPURL"] = "http://meyerweb.com/eric/tools/color-blend/"; // untranslated
Blockly.Msg["COLOUR_BLEND_RATIO"] = "अनुपात";
Blockly.Msg["COLOUR_BLEND_TITLE"] = "मिश्रण गर";
Blockly.Msg["COLOUR_BLEND_TOOLTIP"] = "दियाका अनुपात (0.0 - 1.0) का साथ दुई रंगहरूको मिश्रण गरन्छ ।";
Blockly.Msg["COLOUR_PICKER_HELPURL"] = "https://en.wikipedia.org/wiki/Color";
Blockly.Msg["COLOUR_PICKER_TOOLTIP"] = "पैलेट बाट एक रंग चुन ।";
Blockly.Msg["COLOUR_RANDOM_HELPURL"] = "http://randomcolour.com"; // untranslated
Blockly.Msg["COLOUR_RANDOM_TITLE"] = "जुनसुकै रङ्ग";
Blockly.Msg["COLOUR_RANDOM_TOOLTIP"] = "रैन्डम्ली एक रंग चयन गर ।";
Blockly.Msg["COLOUR_RGB_BLUE"] = "निलो";
Blockly.Msg["COLOUR_RGB_GREEN"] = "हरियो";
Blockly.Msg["COLOUR_RGB_HELPURL"] = "http://www.december.com/html/spec/colorper.html"; // untranslated
Blockly.Msg["COLOUR_RGB_RED"] = "रातो";
Blockly.Msg["COLOUR_RGB_TITLE"] = "यै रङ्गको";
Blockly.Msg["COLOUR_RGB_TOOLTIP"] = "रातो, हरियो और नीलोको निर्दिष्ट मात्राकी साथ एक रंग बनाओ । सबै मान ० देखि १०० का बीच हुनु पडन्छ ।";
Blockly.Msg["CONTROLS_FLOW_STATEMENTS_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated
Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK"] = "लूप बाट भाइर निकलौं";
Blockly.Msg["CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE"] = "लूपको अर्को आईटरेशन जारी राख";
Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK"] = "भीत्री लूप बाट बाहिर निस्कने";
Blockly.Msg["CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE"] = "बचेका लूपलाई छोड, और अर्को आईटरेशन जारी राख ।";
Blockly.Msg["CONTROLS_FLOW_STATEMENTS_WARNING"] = "सावधान: यो ब्लक केवल लूप भित्रमात्र प्रयोग गद्द सकिन्छ ।";
Blockly.Msg["CONTROLS_FOREACH_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated
Blockly.Msg["CONTROLS_FOREACH_TITLE"] = "%2 सूचीमी भयाः प्रत्येक आइटम %1 खिलाइ";
Blockly.Msg["CONTROLS_FOREACH_TOOLTIP"] = "सूचीको प्रत्येक आइटमको लागी, आइटममी चरको मान '%1' राखौं और पाछा क्यै कथन लेख ।";
Blockly.Msg["CONTROLS_FOR_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated
Blockly.Msg["CONTROLS_FOR_TITLE"] = "गन्ती गर %1 देखी %2 %3 %4 सम्म";
Blockly.Msg["CONTROLS_FOR_TOOLTIP"] = "Have the variable '%1' take on the values from the start number to the end number, counting by the specified interval, and do the specified blocks.";
Blockly.Msg["CONTROLS_IF_ELSEIF_TOOLTIP"] = "यदि ब्लकमा एक शर्त जोडौं ।";
Blockly.Msg["CONTROLS_IF_ELSE_TOOLTIP"] = "Add a final, catch-all condition to the if block.";
Blockly.Msg["CONTROLS_IF_HELPURL"] = "https://github.com/google/blockly/wiki/IfElse"; // untranslated
Blockly.Msg["CONTROLS_IF_IF_TOOLTIP"] = "Add, remove, or reorder sections to reconfigure this if block.";
Blockly.Msg["CONTROLS_IF_MSG_ELSE"] = "एल्स";
Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"] = "एल्स इफ";
Blockly.Msg["CONTROLS_IF_MSG_IF"] = "इफ";
Blockly.Msg["CONTROLS_IF_TOOLTIP_1"] = "जब तलक मान सत्य छ, तब तलक क्यै स्टेट्मेंट चलाओ ।";
Blockly.Msg["CONTROLS_IF_TOOLTIP_2"] = "यदि एक मान सत्य छ भण्या कथनहरूको प्रथम खण्ड बणाओ । अन्यथा कथनहरूको अर्को भाग निर्मित गर ।";
Blockly.Msg["CONTROLS_IF_TOOLTIP_3"] = "If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements.";
Blockly.Msg["CONTROLS_IF_TOOLTIP_4"] = "If the first value is true, then do the first block of statements. Otherwise, if the second value is true, do the second block of statements. If none of the values are true, do the last block of statements.";
Blockly.Msg["CONTROLS_REPEAT_HELPURL"] = "https://en.wikipedia.org/wiki/Color";
Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"] = "डू";
Blockly.Msg["CONTROLS_REPEAT_TITLE"] = "%1 पल्ट दोसराओ";
Blockly.Msg["CONTROLS_REPEAT_TOOLTIP"] = "क्यै स्टेट्मन्ट कैयों पल्ट चलाओ ।";
Blockly.Msg["CONTROLS_WHILEUNTIL_HELPURL"] = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated
Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_UNTIL"] = "दोहराओ जब तलक";
Blockly.Msg["CONTROLS_WHILEUNTIL_OPERATOR_WHILE"] = "दोहराओ जब की";
Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL"] = "जब तक मान फॉल्स छ, तब तक क्यै स्टेट्मेंट्स चलाओ ।";
Blockly.Msg["CONTROLS_WHILEUNTIL_TOOLTIP_WHILE"] = "जब तलक मान सत्य छ, तब तलक क्यै स्टेट्मेंट चलाओ ।";
Blockly.Msg["DELETE_ALL_BLOCKS"] = "सबै %1 ब्लकनलाई हटाउन्या ?";
Blockly.Msg["DELETE_BLOCK"] = "ब्लक हटाउन्या";
Blockly.Msg["DELETE_VARIABLE"] = "'%1' भेरिएबल मेट:";
Blockly.Msg["DELETE_VARIABLE_CONFIRMATION"] = "'%2' भेरिएबला %1 प्रयोग मेट्ट्या?";
Blockly.Msg["DELETE_X_BLOCKS"] = " %1 ब्लकहरू हटाउन्या";
Blockly.Msg["DISABLE_BLOCK"] = "ब्लकलाई निश्क्रिय पाड्डे";
Blockly.Msg["DUPLICATE_BLOCK"] = "कपी गर";
Blockly.Msg["DUPLICATE_COMMENT"] = "हूबहू टिप्पणी";
Blockly.Msg["ENABLE_BLOCK"] = "ब्लकलाई सक्रिय पाड्डे";
Blockly.Msg["EXPAND_ALL"] = "ब्लकनलाई फैलाओ";
Blockly.Msg["EXPAND_BLOCK"] = "ब्लकनलाई फैलाओ";
Blockly.Msg["EXTERNAL_INPUTS"] = "भाइरका इन्पुटहरू";
Blockly.Msg["HELP"] = "सहायता";
Blockly.Msg["INLINE_INPUTS"] = "इनलाइन इन्पुटहरू";
Blockly.Msg["IOS_CANCEL"] = "खारेजी";
Blockly.Msg["IOS_ERROR"] = "गल्ती";
Blockly.Msg["IOS_OK"] = "हुन्छ";
Blockly.Msg["IOS_PROCEDURES_ADD_INPUT"] = "+ इनपुट थपः";
Blockly.Msg["IOS_PROCEDURES_ALLOW_STATEMENTS"] = "Allow statements"; // untranslated
Blockly.Msg["IOS_PROCEDURES_DUPLICATE_INPUTS_ERROR"] = "This function has duplicate inputs."; // untranslated
Blockly.Msg["IOS_PROCEDURES_INPUTS"] = "इनपुटन";
Blockly.Msg["IOS_VARIABLES_ADD_BUTTON"] = "जोड़ऽ";
Blockly.Msg["IOS_VARIABLES_ADD_VARIABLE"] = "+ Add Variable"; // untranslated
Blockly.Msg["IOS_VARIABLES_DELETE_BUTTON"] = "मेटः";
Blockly.Msg["IOS_VARIABLES_EMPTY_NAME_ERROR"] = "तम खाली चल नाउँ प्रयोग अरीनाइसक्दाः।";
Blockly.Msg["IOS_VARIABLES_RENAME_BUTTON"] = "पुनर्नामकरण";
Blockly.Msg["IOS_VARIABLES_VARIABLE_NAME"] = "चल(भेरिएबल) नाउँ";
Blockly.Msg["LISTS_CREATE_EMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated
Blockly.Msg["LISTS_CREATE_EMPTY_TITLE"] = "create empty list"; // untranslated
Blockly.Msg["LISTS_CREATE_EMPTY_TOOLTIP"] = "Returns a list, of length 0, containing no data records"; // untranslated
Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TITLE_ADD"] = "list"; // untranslated
Blockly.Msg["LISTS_CREATE_WITH_CONTAINER_TOOLTIP"] = "Add, remove, or reorder sections to reconfigure this list block."; // untranslated
Blockly.Msg["LISTS_CREATE_WITH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg["LISTS_CREATE_WITH_INPUT_WITH"] = "create list with"; // untranslated
Blockly.Msg["LISTS_CREATE_WITH_ITEM_TOOLTIP"] = "Add an item to the list."; // untranslated
Blockly.Msg["LISTS_CREATE_WITH_TOOLTIP"] = "Create a list with any number of items."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_FIRST"] = "first"; // untranslated
Blockly.Msg["LISTS_GET_INDEX_FROM_END"] = "# from end"; // untranslated
Blockly.Msg["LISTS_GET_INDEX_FROM_START"] = "#"; // untranslated
Blockly.Msg["LISTS_GET_INDEX_GET"] = "get"; // untranslated
Blockly.Msg["LISTS_GET_INDEX_GET_REMOVE"] = "get and remove"; // untranslated
Blockly.Msg["LISTS_GET_INDEX_LAST"] = "last"; // untranslated
Blockly.Msg["LISTS_GET_INDEX_RANDOM"] = "random"; // untranslated
Blockly.Msg["LISTS_GET_INDEX_REMOVE"] = "remove"; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TAIL"] = ""; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FIRST"] = "Returns the first item in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_FROM"] = "Returns the item at the specified position in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_LAST"] = "Returns the last item in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_RANDOM"] = "Returns a random item in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST"] = "Removes and returns the first item in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM"] = "Removes and returns the item at the specified position in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST"] = "Removes and returns the last item in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM"] = "Removes and returns a random item in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST"] = "Removes the first item in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM"] = "Removes the item at the specified position in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST"] = "Removes the last item in a list."; // untranslated
Blockly.Msg["LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM"] = "Removes a random item in a list."; // untranslated
Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_END"] = "to # from end"; // untranslated
Blockly.Msg["LISTS_GET_SUBLIST_END_FROM_START"] = "to #"; // untranslated
Blockly.Msg["LISTS_GET_SUBLIST_END_LAST"] = "to last"; // untranslated
Blockly.Msg["LISTS_GET_SUBLIST_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated
Blockly.Msg["LISTS_GET_SUBLIST_START_FIRST"] = "get sub-list from first"; // untranslated
Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_END"] = "get sub-list from # from end"; // untranslated
Blockly.Msg["LISTS_GET_SUBLIST_START_FROM_START"] = "get sub-list from #"; // untranslated
Blockly.Msg["LISTS_GET_SUBLIST_TAIL"] = ""; // untranslated
Blockly.Msg["LISTS_GET_SUBLIST_TOOLTIP"] = "Creates a copy of the specified portion of a list."; // untranslated
Blockly.Msg["LISTS_INDEX_FROM_END_TOOLTIP"] = "%1 is the last item."; // untranslated
Blockly.Msg["LISTS_INDEX_FROM_START_TOOLTIP"] = "%1 is the first item."; // untranslated
Blockly.Msg["LISTS_INDEX_OF_FIRST"] = "find first occurrence of item"; // untranslated
Blockly.Msg["LISTS_INDEX_OF_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated
Blockly.Msg["LISTS_INDEX_OF_LAST"] = "find last occurrence of item"; // untranslated
Blockly.Msg["LISTS_INDEX_OF_TOOLTIP"] = "Returns the index of the first/last occurrence of the item in the list. Returns %1 if item is not found."; // untranslated
Blockly.Msg["LISTS_INLIST"] = "in list"; // untranslated
Blockly.Msg["LISTS_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated
Blockly.Msg["LISTS_ISEMPTY_TITLE"] = "%1 is empty"; // untranslated
Blockly.Msg["LISTS_ISEMPTY_TOOLTIP"] = "Returns true if the list is empty."; // untranslated
Blockly.Msg["LISTS_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated
Blockly.Msg["LISTS_LENGTH_TITLE"] = "length of %1"; // untranslated
Blockly.Msg["LISTS_LENGTH_TOOLTIP"] = "Returns the length of a list."; // untranslated
Blockly.Msg["LISTS_REPEAT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg["LISTS_REPEAT_TITLE"] = "create list with item %1 repeated %2 times"; // untranslated
Blockly.Msg["LISTS_REPEAT_TOOLTIP"] = "Creates a list consisting of the given value repeated the specified number of times."; // untranslated
Blockly.Msg["LISTS_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#reversing-a-list"; // untranslated
Blockly.Msg["LISTS_REVERSE_MESSAGE0"] = "reverse %1"; // untranslated
Blockly.Msg["LISTS_REVERSE_TOOLTIP"] = "Reverse a copy of a list."; // untranslated
Blockly.Msg["LISTS_SET_INDEX_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated
Blockly.Msg["LISTS_SET_INDEX_INPUT_TO"] = "as"; // untranslated
Blockly.Msg["LISTS_SET_INDEX_INSERT"] = "insert at"; // untranslated
Blockly.Msg["LISTS_SET_INDEX_SET"] = "set"; // untranslated
Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST"] = "Inserts the item at the start of a list."; // untranslated
Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_FROM"] = "Inserts the item at the specified position in a list."; // untranslated
Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_LAST"] = "Append the item to the end of a list."; // untranslated
Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM"] = "Inserts the item randomly in a list."; // untranslated
Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FIRST"] = "Sets the first item in a list."; // untranslated
Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_FROM"] = "Sets the item at the specified position in a list."; // untranslated
Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_LAST"] = "Sets the last item in a list."; // untranslated
Blockly.Msg["LISTS_SET_INDEX_TOOLTIP_SET_RANDOM"] = "Sets a random item in a list."; // untranslated
Blockly.Msg["LISTS_SORT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#sorting-a-list"; // untranslated
Blockly.Msg["LISTS_SORT_ORDER_ASCENDING"] = "ascending"; // untranslated
Blockly.Msg["LISTS_SORT_ORDER_DESCENDING"] = "descending"; // untranslated
Blockly.Msg["LISTS_SORT_TITLE"] = "sort %1 %2 %3"; // untranslated
Blockly.Msg["LISTS_SORT_TOOLTIP"] = "Sort a copy of a list."; // untranslated
Blockly.Msg["LISTS_SORT_TYPE_IGNORECASE"] = "alphabetic, ignore case"; // untranslated
Blockly.Msg["LISTS_SORT_TYPE_NUMERIC"] = "numeric"; // untranslated
Blockly.Msg["LISTS_SORT_TYPE_TEXT"] = "alphabetic"; // untranslated
Blockly.Msg["LISTS_SPLIT_HELPURL"] = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists"; // untranslated
Blockly.Msg["LISTS_SPLIT_LIST_FROM_TEXT"] = "make list from text"; // untranslated
Blockly.Msg["LISTS_SPLIT_TEXT_FROM_LIST"] = "make text from list"; // untranslated
Blockly.Msg["LISTS_SPLIT_TOOLTIP_JOIN"] = "Join a list of texts into one text, separated by a delimiter."; // untranslated
Blockly.Msg["LISTS_SPLIT_TOOLTIP_SPLIT"] = "Split text into a list of texts, breaking at each delimiter."; // untranslated
Blockly.Msg["LISTS_SPLIT_WITH_DELIMITER"] = "with delimiter"; // untranslated
Blockly.Msg["LOGIC_BOOLEAN_FALSE"] = "असत्य";
Blockly.Msg["LOGIC_BOOLEAN_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated
Blockly.Msg["LOGIC_BOOLEAN_TOOLTIP"] = "सत्य या असत्य फिर्ता अरन्छ।";
Blockly.Msg["LOGIC_BOOLEAN_TRUE"] = "सत्य";
Blockly.Msg["LOGIC_COMPARE_HELPURL"] = "https://en.wikipedia.org/wiki/Inequality_(mathematics)";
Blockly.Msg["LOGIC_COMPARE_TOOLTIP_EQ"] = "यदी दुवै इनपुट एक अर्काका बराबर छन् भण्या टु रिटर्न गर ।";
Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GT"] = "पैल्लो इनपुट दोसरा इनपुट है ठुलो भया ट्रू फिर्ता अर:।";
Blockly.Msg["LOGIC_COMPARE_TOOLTIP_GTE"] = "पैल्लो इनपुट दोसरा इनपुट है ठुलो या उइ सित बराबर भया ट्रू फिर्ता अर:।";
Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LT"] = "पैल्लो इनपुट दोसरा इनपुट है नानो भया ट्रू फिर्ता अर:।";
Blockly.Msg["LOGIC_COMPARE_TOOLTIP_LTE"] = "पैल्लो इनपुट दोसरा इनपुट है नानो या उइ सित बराबर भया ट्रू फिर्ता अर:।";
Blockly.Msg["LOGIC_COMPARE_TOOLTIP_NEQ"] = "यदी दुवै इनपुट एक अर्काको बराबर नाइथिन् भणया टु रिटर्न गर ।";
Blockly.Msg["LOGIC_NEGATE_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated
Blockly.Msg["LOGIC_NEGATE_TITLE"] = "not %1"; // untranslated
Blockly.Msg["LOGIC_NEGATE_TOOLTIP"] = "इनपुट असत्य भयाले सन्य फिर्ता अरन्छ। इनपुट सत्य भयाले असत्य फिर्ता अरन्छ।";
Blockly.Msg["LOGIC_NULL"] = "शू्य";
Blockly.Msg["LOGIC_NULL_HELPURL"] = "https://en.wikipedia.org/wiki/Nullable_type"; // untranslated
Blockly.Msg["LOGIC_NULL_TOOLTIP"] = "शून्य फिर्ता अरन्छ।";
Blockly.Msg["LOGIC_OPERATION_AND"] = "रे";
Blockly.Msg["LOGIC_OPERATION_HELPURL"] = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated
Blockly.Msg["LOGIC_OPERATION_OR"] = "या";
Blockly.Msg["LOGIC_OPERATION_TOOLTIP_AND"] = "दुएइ इनपुट ट्रू भया ट्रू फिर्ता अर:।";
Blockly.Msg["LOGIC_OPERATION_TOOLTIP_OR"] = "कम्तीमी लै १ इनपुट सत्य भयाले सत्य फिर्ता अर।";
Blockly.Msg["LOGIC_TERNARY_CONDITION"] = "test"; // untranslated
Blockly.Msg["LOGIC_TERNARY_HELPURL"] = "https://en.wikipedia.org/wiki/%3F:"; // untranslated
Blockly.Msg["LOGIC_TERNARY_IF_FALSE"] = "if false"; // untranslated
Blockly.Msg["LOGIC_TERNARY_IF_TRUE"] = "if true"; // untranslated
Blockly.Msg["LOGIC_TERNARY_TOOLTIP"] = "Check the condition in 'test'. If the condition is true, returns the 'if true' value; otherwise returns the 'if false' value."; // untranslated
Blockly.Msg["MATH_ADDITION_SYMBOL"] = "+"; // untranslated
Blockly.Msg["MATH_ARITHMETIC_HELPURL"] = "https://en.wikipedia.org/wiki/Arithmetic"; // untranslated
Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_ADD"] = "Return the sum of the two numbers."; // untranslated
Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_DIVIDE"] = "Return the quotient of the two numbers."; // untranslated
Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_FLOOR_DIVISION"] = "Return the quotient of the two numbers with decimals removed."; // untranslated
Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MINUS"] = "Return the difference of the two numbers."; // untranslated
Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MODULUS"] = "Return the remainder after dividing the two numbers."; // untranslated
Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_MULTIPLY"] = "Return the product of the two numbers."; // untranslated
Blockly.Msg["MATH_ARITHMETIC_TOOLTIP_POWER"] = "Return the first number raised to the power of the second number."; // untranslated
Blockly.Msg["MATH_CHANGE_HELPURL"] = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; // untranslated
Blockly.Msg["MATH_CHANGE_TITLE"] = "change %1 by %2"; // untranslated
Blockly.Msg["MATH_CHANGE_TOOLTIP"] = "Add a number to variable '%1'."; // untranslated
Blockly.Msg["MATH_CONSTANT_HELPURL"] = "https://en.wikipedia.org/wiki/Mathematical_constant"; // untranslated
Blockly.Msg["MATH_CONSTANT_TOOLTIP"] = "Return one of the common constants: π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), or ∞ (infinity)."; // untranslated
Blockly.Msg["MATH_CONSTRAIN_HELPURL"] = "https://en.wikipedia.org/wiki/Clamping_(graphics)"; // untranslated
Blockly.Msg["MATH_CONSTRAIN_TITLE"] = "constrain %1 low %2 high %3"; // untranslated
Blockly.Msg["MATH_CONSTRAIN_TOOLTIP"] = "Constrain a number to be between the specified limits (inclusive)."; // untranslated
Blockly.Msg["MATH_DIVISION_SYMBOL"] = "÷"; // untranslated
Blockly.Msg["MATH_FLOOR_DIVISION_SYMBOL"] = "//"; // untranslated
Blockly.Msg["MATH_IS_DIVISIBLE_BY"] = "is divisible by"; // untranslated
Blockly.Msg["MATH_IS_EVEN"] = "is even"; // untranslated
Blockly.Msg["MATH_IS_NEGATIVE"] = "is negative"; // untranslated
Blockly.Msg["MATH_IS_ODD"] = "is odd"; // untranslated
Blockly.Msg["MATH_IS_POSITIVE"] = "is positive"; // untranslated
Blockly.Msg["MATH_IS_PRIME"] = "is prime"; // untranslated
Blockly.Msg["MATH_IS_TOOLTIP"] = "Check if a number is an even, odd, prime, whole, positive, negative, or if it is divisible by certain number. Returns true or false."; // untranslated
Blockly.Msg["MATH_IS_WHOLE"] = "is whole"; // untranslated
Blockly.Msg["MATH_MODULO_HELPURL"] = "https://en.wikipedia.org/wiki/Modulo_operation"; // untranslated
Blockly.Msg["MATH_MODULO_TITLE"] = "remainder of %1 ÷ %2"; // untranslated
Blockly.Msg["MATH_MODULO_TOOLTIP"] = "Return the remainder from dividing the two numbers."; // untranslated
Blockly.Msg["MATH_MODULUS_SYMBOL"] = "%"; // untranslated
Blockly.Msg["MATH_MULTIPLICATION_SYMBOL"] = "×"; // untranslated
Blockly.Msg["MATH_NUMBER_HELPURL"] = "https://en.wikipedia.org/wiki/Number"; // untranslated
Blockly.Msg["MATH_NUMBER_TOOLTIP"] = "A number."; // untranslated
Blockly.Msg["MATH_ONLIST_HELPURL"] = ""; // untranslated
Blockly.Msg["MATH_ONLIST_OPERATOR_AVERAGE"] = "average of list"; // untranslated
Blockly.Msg["MATH_ONLIST_OPERATOR_MAX"] = "max of list"; // untranslated
Blockly.Msg["MATH_ONLIST_OPERATOR_MEDIAN"] = "median of list"; // untranslated
Blockly.Msg["MATH_ONLIST_OPERATOR_MIN"] = "min of list"; // untranslated
Blockly.Msg["MATH_ONLIST_OPERATOR_MODE"] = "modes of list"; // untranslated
Blockly.Msg["MATH_ONLIST_OPERATOR_RANDOM"] = "random item of list"; // untranslated
Blockly.Msg["MATH_ONLIST_OPERATOR_STD_DEV"] = "standard deviation of list"; // untranslated
Blockly.Msg["MATH_ONLIST_OPERATOR_SUM"] = "sum of list"; // untranslated
Blockly.Msg["MATH_ONLIST_TOOLTIP_AVERAGE"] = "Return the average (arithmetic mean) of the numeric values in the list."; // untranslated
Blockly.Msg["MATH_ONLIST_TOOLTIP_MAX"] = "Return the largest number in the list."; // untranslated
Blockly.Msg["MATH_ONLIST_TOOLTIP_MEDIAN"] = "Return the median number in the list."; // untranslated
Blockly.Msg["MATH_ONLIST_TOOLTIP_MIN"] = "Return the smallest number in the list."; // untranslated
Blockly.Msg["MATH_ONLIST_TOOLTIP_MODE"] = "Return a list of the most common item(s) in the list."; // untranslated
Blockly.Msg["MATH_ONLIST_TOOLTIP_RANDOM"] = "Return a random element from the list."; // untranslated
Blockly.Msg["MATH_ONLIST_TOOLTIP_STD_DEV"] = "Return the standard deviation of the list."; // untranslated
Blockly.Msg["MATH_ONLIST_TOOLTIP_SUM"] = "Return the sum of all the numbers in the list."; // untranslated
Blockly.Msg["MATH_POWER_SYMBOL"] = "^"; // untranslated
Blockly.Msg["MATH_RANDOM_FLOAT_HELPURL"] = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated
Blockly.Msg["MATH_RANDOM_FLOAT_TITLE_RANDOM"] = "random fraction"; // untranslated
Blockly.Msg["MATH_RANDOM_FLOAT_TOOLTIP"] = "Return a random fraction between 0.0 (inclusive) and 1.0 (exclusive)."; // untranslated
Blockly.Msg["MATH_RANDOM_INT_HELPURL"] = "https://en.wikipedia.org/wiki/Random_number_generation"; // untranslated
Blockly.Msg["MATH_RANDOM_INT_TITLE"] = "random integer from %1 to %2"; // untranslated
Blockly.Msg["MATH_RANDOM_INT_TOOLTIP"] = "Return a random integer between the two specified limits, inclusive."; // untranslated
Blockly.Msg["MATH_ROUND_HELPURL"] = "https://en.wikipedia.org/wiki/Rounding"; // untranslated
Blockly.Msg["MATH_ROUND_OPERATOR_ROUND"] = "round"; // untranslated
Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDDOWN"] = "round down"; // untranslated
Blockly.Msg["MATH_ROUND_OPERATOR_ROUNDUP"] = "round up"; // untranslated
Blockly.Msg["MATH_ROUND_TOOLTIP"] = "Round a number up or down."; // untranslated
Blockly.Msg["MATH_SINGLE_HELPURL"] = "https://en.wikipedia.org/wiki/Square_root"; // untranslated
Blockly.Msg["MATH_SINGLE_OP_ABSOLUTE"] = "absolute"; // untranslated
Blockly.Msg["MATH_SINGLE_OP_ROOT"] = "square root"; // untranslated
Blockly.Msg["MATH_SINGLE_TOOLTIP_ABS"] = "Return the absolute value of a number."; // untranslated
Blockly.Msg["MATH_SINGLE_TOOLTIP_EXP"] = "Return e to the power of a number."; // untranslated
Blockly.Msg["MATH_SINGLE_TOOLTIP_LN"] = "Return the natural logarithm of a number."; // untranslated
Blockly.Msg["MATH_SINGLE_TOOLTIP_LOG10"] = "Return the base 10 logarithm of a number."; // untranslated
Blockly.Msg["MATH_SINGLE_TOOLTIP_NEG"] = "Return the negation of a number."; // untranslated
Blockly.Msg["MATH_SINGLE_TOOLTIP_POW10"] = "Return 10 to the power of a number."; // untranslated
Blockly.Msg["MATH_SINGLE_TOOLTIP_ROOT"] = "Return the square root of a number."; // untranslated
Blockly.Msg["MATH_SUBTRACTION_SYMBOL"] = "-"; // untranslated
Blockly.Msg["MATH_TRIG_ACOS"] = "acos"; // untranslated
Blockly.Msg["MATH_TRIG_ASIN"] = "asin"; // untranslated
Blockly.Msg["MATH_TRIG_ATAN"] = "atan"; // untranslated
Blockly.Msg["MATH_TRIG_COS"] = "cos"; // untranslated
Blockly.Msg["MATH_TRIG_HELPURL"] = "https://en.wikipedia.org/wiki/Trigonometric_functions"; // untranslated
Blockly.Msg["MATH_TRIG_SIN"] = "sin"; // untranslated
Blockly.Msg["MATH_TRIG_TAN"] = "tan"; // untranslated
Blockly.Msg["MATH_TRIG_TOOLTIP_ACOS"] = "Return the arccosine of a number."; // untranslated
Blockly.Msg["MATH_TRIG_TOOLTIP_ASIN"] = "Return the arcsine of a number."; // untranslated
Blockly.Msg["MATH_TRIG_TOOLTIP_ATAN"] = "Return the arctangent of a number."; // untranslated
Blockly.Msg["MATH_TRIG_TOOLTIP_COS"] = "Return the cosine of a degree (not radian)."; // untranslated
Blockly.Msg["MATH_TRIG_TOOLTIP_SIN"] = "Return the sine of a degree (not radian)."; // untranslated
Blockly.Msg["MATH_TRIG_TOOLTIP_TAN"] = "Return the tangent of a degree (not radian)."; // untranslated
Blockly.Msg["NEW_COLOUR_VARIABLE"] = "Create colour variable..."; // untranslated
Blockly.Msg["NEW_NUMBER_VARIABLE"] = "Create number variable..."; // untranslated
Blockly.Msg["NEW_STRING_VARIABLE"] = "Create string variable..."; // untranslated
Blockly.Msg["NEW_VARIABLE"] = "भेरिएवल बना:";
Blockly.Msg["NEW_VARIABLE_TITLE"] = "नयाँ भेरिबलको नाम:";
Blockly.Msg["NEW_VARIABLE_TYPE_TITLE"] = "New variable type:"; // untranslated
Blockly.Msg["ORDINAL_NUMBER_SUFFIX"] = ""; // untranslated
Blockly.Msg["PROCEDURES_ALLOW_STATEMENTS"] = "allow statements"; // untranslated
Blockly.Msg["PROCEDURES_BEFORE_PARAMS"] = "with:"; // untranslated
Blockly.Msg["PROCEDURES_CALLNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated
Blockly.Msg["PROCEDURES_CALLNORETURN_TOOLTIP"] = "Run the user-defined function '%1'."; // untranslated
Blockly.Msg["PROCEDURES_CALLRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated
Blockly.Msg["PROCEDURES_CALLRETURN_TOOLTIP"] = "Run the user-defined function '%1' and use its output."; // untranslated
Blockly.Msg["PROCEDURES_CALL_BEFORE_PARAMS"] = "with:"; // untranslated
Blockly.Msg["PROCEDURES_CREATE_DO"] = "Create '%1'"; // untranslated
Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"] = "Describe this function..."; // untranslated
Blockly.Msg["PROCEDURES_DEFNORETURN_DO"] = ""; // untranslated
Blockly.Msg["PROCEDURES_DEFNORETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated
Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"] = "do something"; // untranslated
Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"] = "to"; // untranslated
Blockly.Msg["PROCEDURES_DEFNORETURN_TOOLTIP"] = "Creates a function with no output."; // untranslated
Blockly.Msg["PROCEDURES_DEFRETURN_HELPURL"] = "https://en.wikipedia.org/wiki/Subroutine"; // untranslated
Blockly.Msg["PROCEDURES_DEFRETURN_RETURN"] = "return"; // untranslated
Blockly.Msg["PROCEDURES_DEFRETURN_TOOLTIP"] = "Creates a function with an output."; // untranslated
Blockly.Msg["PROCEDURES_DEF_DUPLICATE_WARNING"] = "Warning: This function has duplicate parameters."; // untranslated
Blockly.Msg["PROCEDURES_HIGHLIGHT_DEF"] = "Highlight function definition"; // untranslated
Blockly.Msg["PROCEDURES_IFRETURN_HELPURL"] = "http://c2.com/cgi/wiki?GuardClause"; // untranslated
Blockly.Msg["PROCEDURES_IFRETURN_TOOLTIP"] = "If a value is true, then return a second value."; // untranslated
Blockly.Msg["PROCEDURES_IFRETURN_WARNING"] = "Warning: This block may be used only within a function definition."; // untranslated
Blockly.Msg["PROCEDURES_MUTATORARG_TITLE"] = "input name:"; // untranslated
Blockly.Msg["PROCEDURES_MUTATORARG_TOOLTIP"] = "Add an input to the function."; // untranslated
Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TITLE"] = "inputs"; // untranslated
Blockly.Msg["PROCEDURES_MUTATORCONTAINER_TOOLTIP"] = "Add, remove, or reorder inputs to this function."; // untranslated
Blockly.Msg["REDO"] = "पुन: कायम गद्दे";
Blockly.Msg["REMOVE_COMMENT"] = "टिप्पणी हटाउन्या";
Blockly.Msg["RENAME_VARIABLE"] = "भेरिबललाई पुनः नामांकन गर...";
Blockly.Msg["RENAME_VARIABLE_TITLE"] = "सबै भेरिबलनका %1 नाम बदल्न्या:";
Blockly.Msg["TEXT_APPEND_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg["TEXT_APPEND_TITLE"] = "to %1 append text %2"; // untranslated
Blockly.Msg["TEXT_APPEND_TOOLTIP"] = "Append some text to variable '%1'."; // untranslated
Blockly.Msg["TEXT_CHANGECASE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated
Blockly.Msg["TEXT_CHANGECASE_OPERATOR_LOWERCASE"] = "to lower case"; // untranslated
Blockly.Msg["TEXT_CHANGECASE_OPERATOR_TITLECASE"] = "to Title Case"; // untranslated
Blockly.Msg["TEXT_CHANGECASE_OPERATOR_UPPERCASE"] = "to UPPER CASE"; // untranslated
Blockly.Msg["TEXT_CHANGECASE_TOOLTIP"] = "Return a copy of the text in a different case."; // untranslated
Blockly.Msg["TEXT_CHARAT_FIRST"] = "get first letter"; // untranslated
Blockly.Msg["TEXT_CHARAT_FROM_END"] = "get letter # from end"; // untranslated
Blockly.Msg["TEXT_CHARAT_FROM_START"] = "get letter #"; // untranslated
Blockly.Msg["TEXT_CHARAT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated
Blockly.Msg["TEXT_CHARAT_LAST"] = "get last letter"; // untranslated
Blockly.Msg["TEXT_CHARAT_RANDOM"] = "get random letter"; // untranslated
Blockly.Msg["TEXT_CHARAT_TAIL"] = ""; // untranslated
Blockly.Msg["TEXT_CHARAT_TITLE"] = "in text %1 %2"; // untranslated
Blockly.Msg["TEXT_CHARAT_TOOLTIP"] = "Returns the letter at the specified position."; // untranslated
Blockly.Msg["TEXT_COUNT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#counting-substrings"; // untranslated
Blockly.Msg["TEXT_COUNT_MESSAGE0"] = "count %1 in %2"; // untranslated
Blockly.Msg["TEXT_COUNT_TOOLTIP"] = "Count how many times some text occurs within some other text."; // untranslated
Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TOOLTIP"] = "Add an item to the text."; // untranslated
Blockly.Msg["TEXT_CREATE_JOIN_TITLE_JOIN"] = "join"; // untranslated
Blockly.Msg["TEXT_CREATE_JOIN_TOOLTIP"] = "Add, remove, or reorder sections to reconfigure this text block."; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_END"] = "to letter # from end"; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_END_FROM_START"] = "to letter #"; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_END_LAST"] = "to last letter"; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_HELPURL"] = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_INPUT_IN_TEXT"] = "in text"; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_START_FIRST"] = "get substring from first letter"; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_END"] = "get substring from letter # from end"; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_START_FROM_START"] = "get substring from letter #"; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_TAIL"] = ""; // untranslated
Blockly.Msg["TEXT_GET_SUBSTRING_TOOLTIP"] = "Returns a specified portion of the text."; // untranslated
Blockly.Msg["TEXT_INDEXOF_HELPURL"] = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated
Blockly.Msg["TEXT_INDEXOF_OPERATOR_FIRST"] = "find first occurrence of text"; // untranslated
Blockly.Msg["TEXT_INDEXOF_OPERATOR_LAST"] = "find last occurrence of text"; // untranslated
Blockly.Msg["TEXT_INDEXOF_TITLE"] = "in text %1 %2 %3"; // untranslated
Blockly.Msg["TEXT_INDEXOF_TOOLTIP"] = "Returns the index of the first/last occurrence of the first text in the second text. Returns %1 if text is not found."; // untranslated
Blockly.Msg["TEXT_ISEMPTY_HELPURL"] = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated
Blockly.Msg["TEXT_ISEMPTY_TITLE"] = "%1 is empty"; // untranslated
Blockly.Msg["TEXT_ISEMPTY_TOOLTIP"] = "Returns true if the provided text is empty."; // untranslated
Blockly.Msg["TEXT_JOIN_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated
Blockly.Msg["TEXT_JOIN_TITLE_CREATEWITH"] = "create text with"; // untranslated
Blockly.Msg["TEXT_JOIN_TOOLTIP"] = "Create a piece of text by joining together any number of items."; // untranslated
Blockly.Msg["TEXT_LENGTH_HELPURL"] = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg["TEXT_LENGTH_TITLE"] = "length of %1"; // untranslated
Blockly.Msg["TEXT_LENGTH_TOOLTIP"] = "Returns the number of letters (including spaces) in the provided text."; // untranslated
Blockly.Msg["TEXT_PRINT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated
Blockly.Msg["TEXT_PRINT_TITLE"] = "print %1"; // untranslated
Blockly.Msg["TEXT_PRINT_TOOLTIP"] = "Print the specified text, number or other value."; // untranslated
Blockly.Msg["TEXT_PROMPT_HELPURL"] = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated
Blockly.Msg["TEXT_PROMPT_TOOLTIP_NUMBER"] = "Prompt for user for a number."; // untranslated
Blockly.Msg["TEXT_PROMPT_TOOLTIP_TEXT"] = "Prompt for user for some text."; // untranslated
Blockly.Msg["TEXT_PROMPT_TYPE_NUMBER"] = "prompt for number with message"; // untranslated
Blockly.Msg["TEXT_PROMPT_TYPE_TEXT"] = "prompt for text with message"; // untranslated
Blockly.Msg["TEXT_REPLACE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#replacing-substrings"; // untranslated
Blockly.Msg["TEXT_REPLACE_MESSAGE0"] = "replace %1 with %2 in %3"; // untranslated
Blockly.Msg["TEXT_REPLACE_TOOLTIP"] = "Replace all occurances of some text within some other text."; // untranslated
Blockly.Msg["TEXT_REVERSE_HELPURL"] = "https://github.com/google/blockly/wiki/Text#reversing-text"; // untranslated
Blockly.Msg["TEXT_REVERSE_MESSAGE0"] = "reverse %1"; // untranslated
Blockly.Msg["TEXT_REVERSE_TOOLTIP"] = "Reverses the order of the characters in the text."; // untranslated
Blockly.Msg["TEXT_TEXT_HELPURL"] = "https://en.wikipedia.org/wiki/String_(computer_science)"; // untranslated
Blockly.Msg["TEXT_TEXT_TOOLTIP"] = "A letter, word, or line of text."; // untranslated
Blockly.Msg["TEXT_TRIM_HELPURL"] = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated
Blockly.Msg["TEXT_TRIM_OPERATOR_BOTH"] = "trim spaces from both sides of"; // untranslated
Blockly.Msg["TEXT_TRIM_OPERATOR_LEFT"] = "trim spaces from left side of"; // untranslated
Blockly.Msg["TEXT_TRIM_OPERATOR_RIGHT"] = "trim spaces from right side of"; // untranslated
Blockly.Msg["TEXT_TRIM_TOOLTIP"] = "Return a copy of the text with spaces removed from one or both ends."; // untranslated
Blockly.Msg["TODAY"] = "आज";
Blockly.Msg["UNDO"] = "रद्द गर्न्या";
Blockly.Msg["VARIABLES_DEFAULT_NAME"] = "वस्तु";
Blockly.Msg["VARIABLES_GET_CREATE_SET"] = "Create 'set %1'"; // untranslated
Blockly.Msg["VARIABLES_GET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated
Blockly.Msg["VARIABLES_GET_TOOLTIP"] = "Returns the value of this variable."; // untranslated
Blockly.Msg["VARIABLES_SET"] = "set %1 to %2"; // untranslated
Blockly.Msg["VARIABLES_SET_CREATE_GET"] = "Create 'get %1'"; // untranslated
Blockly.Msg["VARIABLES_SET_HELPURL"] = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated
Blockly.Msg["VARIABLES_SET_TOOLTIP"] = "Sets this variable to be equal to the input."; // untranslated
Blockly.Msg["VARIABLE_ALREADY_EXISTS"] = "'%1' नाउँ अरियाऽ भेरिएबल पैली बठेइ छ।";
Blockly.Msg["VARIABLE_ALREADY_EXISTS_FOR_ANOTHER_TYPE"] = "A variable named '%1' already exists for another type: '%2'."; // untranslated
Blockly.Msg["WORKSPACE_COMMENT_DEFAULT_TEXT"] = "केयि भँण...";
Blockly.Msg["PROCEDURES_DEFRETURN_TITLE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_TITLE"];
Blockly.Msg["CONTROLS_IF_IF_TITLE_IF"] = Blockly.Msg["CONTROLS_IF_MSG_IF"];
Blockly.Msg["CONTROLS_WHILEUNTIL_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"];
Blockly.Msg["CONTROLS_IF_MSG_THEN"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"];
Blockly.Msg["CONTROLS_IF_ELSE_TITLE_ELSE"] = Blockly.Msg["CONTROLS_IF_MSG_ELSE"];
Blockly.Msg["PROCEDURES_DEFRETURN_PROCEDURE"] = Blockly.Msg["PROCEDURES_DEFNORETURN_PROCEDURE"];
Blockly.Msg["LISTS_GET_SUBLIST_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"];
Blockly.Msg["LISTS_GET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"];
Blockly.Msg["MATH_CHANGE_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"];
Blockly.Msg["PROCEDURES_DEFRETURN_DO"] = Blockly.Msg["PROCEDURES_DEFNORETURN_DO"];
Blockly.Msg["CONTROLS_IF_ELSEIF_TITLE_ELSEIF"] = Blockly.Msg["CONTROLS_IF_MSG_ELSEIF"];
Blockly.Msg["LISTS_GET_INDEX_HELPURL"] = Blockly.Msg["LISTS_INDEX_OF_HELPURL"];
Blockly.Msg["CONTROLS_FOREACH_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"];
Blockly.Msg["LISTS_SET_INDEX_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"];
Blockly.Msg["CONTROLS_FOR_INPUT_DO"] = Blockly.Msg["CONTROLS_REPEAT_INPUT_DO"];
Blockly.Msg["LISTS_CREATE_WITH_ITEM_TITLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"];
Blockly.Msg["TEXT_APPEND_VARIABLE"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"];
Blockly.Msg["TEXT_CREATE_JOIN_ITEM_TITLE_ITEM"] = Blockly.Msg["VARIABLES_DEFAULT_NAME"];
Blockly.Msg["LISTS_INDEX_OF_INPUT_IN_LIST"] = Blockly.Msg["LISTS_INLIST"];
Blockly.Msg["PROCEDURES_DEFRETURN_COMMENT"] = Blockly.Msg["PROCEDURES_DEFNORETURN_COMMENT"];
Blockly.Msg["MATH_HUE"] = "230";
Blockly.Msg["LOOPS_HUE"] = "120";
Blockly.Msg["LISTS_HUE"] = "260";
Blockly.Msg["LOGIC_HUE"] = "210";
Blockly.Msg["VARIABLES_HUE"] = "330";
Blockly.Msg["TEXTS_HUE"] = "160";
Blockly.Msg["PROCEDURES_HUE"] = "290";
Blockly.Msg["COLOUR_HUE"] = "20";
Blockly.Msg["VARIABLES_DYNAMIC_HUE"] = "310"; | trinketapp/blockly | msg/js/dty.js | JavaScript | apache-2.0 | 41,108 |
sap.ui.define(['sap/ui/webc/common/thirdparty/base/config/Theme', './v5/attachment-video', './v4/attachment-video'], function (Theme, attachmentVideo$2, attachmentVideo$1) { 'use strict';
const pathData = Theme.isThemeFamily("sap_horizon") ? attachmentVideo$1 : attachmentVideo$2;
var attachmentVideo = { pathData };
return attachmentVideo;
});
| SAP/openui5 | src/sap.ui.webc.common/src/sap/ui/webc/common/thirdparty/icons/attachment-video.js | JavaScript | apache-2.0 | 351 |
/**
* @license Copyright 2016 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
const defaultConfigPath = './default-config.js';
const defaultConfig = require('./default-config.js');
const constants = require('./constants.js');
const i18n = require('./../lib/i18n/i18n.js');
const isDeepEqual = require('lodash.isequal');
const log = require('lighthouse-logger');
const path = require('path');
const Runner = require('../runner.js');
const ConfigPlugin = require('./config-plugin.js');
const Budget = require('./budget.js');
const {requireAudits, mergeOptionsOfItems, resolveModule} = require('./config-helpers.js');
/** @typedef {typeof import('../gather/gatherers/gatherer.js')} GathererConstructor */
/** @typedef {InstanceType<GathererConstructor>} Gatherer */
/**
* Define with object literal so that tsc will require it to stay updated.
* @type {Record<keyof LH.BaseArtifacts, ''>}
*/
const BASE_ARTIFACT_BLANKS = {
fetchTime: '',
LighthouseRunWarnings: '',
TestedAsMobileDevice: '',
HostFormFactor: '',
HostUserAgent: '',
NetworkUserAgent: '',
BenchmarkIndex: '',
WebAppManifest: '',
Stacks: '',
traces: '',
devtoolsLogs: '',
settings: '',
URL: '',
Timing: '',
PageLoadError: '',
};
const BASE_ARTIFACT_NAMES = Object.keys(BASE_ARTIFACT_BLANKS);
/**
* @param {Config['passes']} passes
* @param {Config['audits']} audits
*/
function assertValidPasses(passes, audits) {
if (!Array.isArray(passes)) {
return;
}
const requiredGatherers = Config.getGatherersNeededByAudits(audits);
// Base artifacts are provided by GatherRunner, so start foundGatherers with them.
const foundGatherers = new Set(BASE_ARTIFACT_NAMES);
// Log if we are running gathers that are not needed by the audits listed in the config
passes.forEach((pass, passIndex) => {
if (passIndex === 0 && pass.loadFailureMode !== 'fatal') {
log.warn(`"${pass.passName}" is the first pass but was marked as non-fatal. ` +
`The first pass will always be treated as loadFailureMode=fatal.`);
pass.loadFailureMode = 'fatal';
}
pass.gatherers.forEach(gathererDefn => {
const gatherer = gathererDefn.instance;
foundGatherers.add(gatherer.name);
const isGatherRequiredByAudits = requiredGatherers.has(gatherer.name);
if (!isGatherRequiredByAudits) {
const msg = `${gatherer.name} gatherer requested, however no audit requires it.`;
log.warn('config', msg);
}
});
});
// All required gatherers must be found in the config. Throw otherwise.
for (const auditDefn of audits || []) {
const auditMeta = auditDefn.implementation.meta;
for (const requiredArtifact of auditMeta.requiredArtifacts) {
if (!foundGatherers.has(requiredArtifact)) {
throw new Error(`${requiredArtifact} gatherer, required by audit ${auditMeta.id}, ` +
'was not found in config.');
}
}
}
// Passes must have unique `passName`s. Throw otherwise.
const usedNames = new Set();
passes.forEach(pass => {
const passName = pass.passName;
if (usedNames.has(passName)) {
throw new Error(`Passes must have unique names (repeated passName: ${passName}.`);
}
usedNames.add(passName);
});
}
/**
* @param {Config['categories']} categories
* @param {Config['audits']} audits
* @param {Config['groups']} groups
*/
function assertValidCategories(categories, audits, groups) {
if (!categories) {
return;
}
const auditsKeyedById = new Map((audits || []).map(audit =>
/** @type {[string, LH.Config.AuditDefn]} */
([audit.implementation.meta.id, audit])
));
Object.keys(categories).forEach(categoryId => {
categories[categoryId].auditRefs.forEach((auditRef, index) => {
if (!auditRef.id) {
throw new Error(`missing an audit id at ${categoryId}[${index}]`);
}
const audit = auditsKeyedById.get(auditRef.id);
if (!audit) {
throw new Error(`could not find ${auditRef.id} audit for category ${categoryId}`);
}
const auditImpl = audit.implementation;
const isManual = auditImpl.meta.scoreDisplayMode === 'manual';
if (categoryId === 'accessibility' && !auditRef.group && !isManual) {
throw new Error(`${auditRef.id} accessibility audit does not have a group`);
}
if (auditRef.weight > 0 && isManual) {
throw new Error(`${auditRef.id} is manual but has a positive weight`);
}
if (auditRef.group && (!groups || !groups[auditRef.group])) {
throw new Error(`${auditRef.id} references unknown group ${auditRef.group}`);
}
});
});
}
/**
* @param {Gatherer} gathererInstance
* @param {string=} gathererName
*/
function assertValidGatherer(gathererInstance, gathererName) {
gathererName = gathererName || gathererInstance.name || 'gatherer';
if (typeof gathererInstance.beforePass !== 'function') {
throw new Error(`${gathererName} has no beforePass() method.`);
}
if (typeof gathererInstance.pass !== 'function') {
throw new Error(`${gathererName} has no pass() method.`);
}
if (typeof gathererInstance.afterPass !== 'function') {
throw new Error(`${gathererName} has no afterPass() method.`);
}
}
/**
* Throws if pluginName is invalid or (somehow) collides with a category in the
* configJSON being added to.
* @param {LH.Config.Json} configJSON
* @param {string} pluginName
*/
function assertValidPluginName(configJSON, pluginName) {
if (!pluginName.startsWith('lighthouse-plugin-')) {
throw new Error(`plugin name '${pluginName}' does not start with 'lighthouse-plugin-'`);
}
if (configJSON.categories && configJSON.categories[pluginName]) {
throw new Error(`plugin name '${pluginName}' not allowed because it is the id of a category already found in config`); // eslint-disable-line max-len
}
}
/**
* Creates a settings object from potential flags object by dropping all the properties
* that don't exist on Config.Settings.
* @param {Partial<LH.Flags>=} flags
* @return {RecursivePartial<LH.Config.Settings>}
*/
function cleanFlagsForSettings(flags = {}) {
/** @type {RecursivePartial<LH.Config.Settings>} */
const settings = {};
for (const key of Object.keys(flags)) {
if (key in constants.defaultSettings) {
// @ts-ignore tsc can't yet express that key is only a single type in each iteration, not a union of types.
settings[key] = flags[key];
}
}
return settings;
}
/**
* More widely typed than exposed merge() function, below.
* @param {Object<string, any>|Array<any>|undefined|null} base
* @param {Object<string, any>|Array<any>} extension
* @param {boolean=} overwriteArrays
*/
function _merge(base, extension, overwriteArrays = false) {
// If the default value doesn't exist or is explicitly null, defer to the extending value
if (typeof base === 'undefined' || base === null) {
return extension;
} else if (typeof extension === 'undefined') {
return base;
} else if (Array.isArray(extension)) {
if (overwriteArrays) return extension;
if (!Array.isArray(base)) throw new TypeError(`Expected array but got ${typeof base}`);
const merged = base.slice();
extension.forEach(item => {
if (!merged.some(candidate => isDeepEqual(candidate, item))) merged.push(item);
});
return merged;
} else if (typeof extension === 'object') {
if (typeof base !== 'object') throw new TypeError(`Expected object but got ${typeof base}`);
if (Array.isArray(base)) throw new TypeError('Expected object but got Array');
Object.keys(extension).forEach(key => {
const localOverwriteArrays = overwriteArrays ||
(key === 'settings' && typeof base[key] === 'object');
base[key] = _merge(base[key], extension[key], localOverwriteArrays);
});
return base;
}
return extension;
}
/**
* Until support of jsdoc templates with constraints, type in config.d.ts.
* See https://github.com/Microsoft/TypeScript/issues/24283
* @type {LH.Config.Merge}
*/
const merge = _merge;
/**
* @template T
* @param {Array<T>} array
* @return {Array<T>}
*/
function cloneArrayWithPluginSafety(array) {
return array.map(item => {
if (typeof item === 'object') {
// Return copy of instance and prototype chain (in case item is instantiated class).
return Object.assign(
Object.create(
Object.getPrototypeOf(item)
),
item
);
}
return item;
});
}
/**
* // TODO(bckenny): could adopt "jsonified" type to ensure T will survive JSON
* round trip: https://github.com/Microsoft/TypeScript/issues/21838
* @template T
* @param {T} json
* @return {T}
*/
function deepClone(json) {
return JSON.parse(JSON.stringify(json));
}
/**
* Deep clone a ConfigJson, copying over any "live" gatherer or audit that
* wouldn't make the JSON round trip.
* @param {LH.Config.Json} json
* @return {LH.Config.Json}
*/
function deepCloneConfigJson(json) {
const cloned = deepClone(json);
// Copy arrays that could contain plugins to allow for programmatic
// injection of plugins.
if (Array.isArray(cloned.passes) && Array.isArray(json.passes)) {
for (let i = 0; i < cloned.passes.length; i++) {
const pass = cloned.passes[i];
pass.gatherers = cloneArrayWithPluginSafety(json.passes[i].gatherers || []);
}
}
if (Array.isArray(json.audits)) {
cloned.audits = cloneArrayWithPluginSafety(json.audits);
}
return cloned;
}
class Config {
/**
* @constructor
* @implements {LH.Config.Json}
* @param {LH.Config.Json=} configJSON
* @param {LH.Flags=} flags
*/
constructor(configJSON, flags) {
const status = {msg: 'Create config', id: 'lh:init:config'};
log.time(status, 'verbose');
let configPath = flags && flags.configPath;
if (!configJSON) {
configJSON = defaultConfig;
configPath = path.resolve(__dirname, defaultConfigPath);
}
if (configPath && !path.isAbsolute(configPath)) {
throw new Error('configPath must be an absolute path.');
}
// We don't want to mutate the original config object
configJSON = deepCloneConfigJson(configJSON);
// Extend the default config if specified
if (configJSON.extends) {
configJSON = Config.extendConfigJSON(deepCloneConfigJson(defaultConfig), configJSON);
}
// The directory of the config path, if one was provided.
const configDir = configPath ? path.dirname(configPath) : undefined;
// Validate and merge in plugins (if any).
configJSON = Config.mergePlugins(configJSON, flags, configDir);
const settings = Config.initSettings(configJSON.settings, flags);
// Augment passes with necessary defaults and require gatherers.
const passesWithDefaults = Config.augmentPassesWithDefaults(configJSON.passes);
Config.adjustDefaultPassForThrottling(settings, passesWithDefaults);
const passes = Config.requireGatherers(passesWithDefaults, configDir);
/** @type {LH.Config.Settings} */
this.settings = settings;
/** @type {?Array<LH.Config.Pass>} */
this.passes = passes;
/** @type {?Array<LH.Config.AuditDefn>} */
this.audits = Config.requireAudits(configJSON.audits, configDir);
/** @type {?Record<string, LH.Config.Category>} */
this.categories = configJSON.categories || null;
/** @type {?Record<string, LH.Config.Group>} */
this.groups = configJSON.groups || null;
Config.filterConfigIfNeeded(this);
assertValidPasses(this.passes, this.audits);
assertValidCategories(this.categories, this.audits, this.groups);
// TODO(bckenny): until tsc adds @implements support, assert that Config is a ConfigJson.
/** @type {LH.Config.Json} */
const configJson = this; // eslint-disable-line no-unused-vars
log.timeEnd(status);
}
/**
* Provides a cleaned-up, stringified version of this config. Gatherer and
* Audit `implementation` and `instance` do not survive this process.
* @return {string}
*/
getPrintString() {
const jsonConfig = deepClone(this);
if (jsonConfig.passes) {
for (const pass of jsonConfig.passes) {
for (const gathererDefn of pass.gatherers) {
gathererDefn.implementation = undefined;
// @ts-ignore Breaking the Config.GathererDefn type.
gathererDefn.instance = undefined;
if (Object.keys(gathererDefn.options).length === 0) {
// @ts-ignore Breaking the Config.GathererDefn type.
gathererDefn.options = undefined;
}
}
}
}
if (jsonConfig.audits) {
for (const auditDefn of jsonConfig.audits) {
// @ts-ignore Breaking the Config.AuditDefn type.
auditDefn.implementation = undefined;
if (Object.keys(auditDefn.options).length === 0) {
// @ts-ignore Breaking the Config.AuditDefn type.
auditDefn.options = undefined;
}
}
}
// Printed config is more useful with localized strings.
i18n.replaceIcuMessageInstanceIds(jsonConfig, jsonConfig.settings.locale);
return JSON.stringify(jsonConfig, null, 2);
}
/**
* @param {LH.Config.Json} baseJSON The JSON of the configuration to extend
* @param {LH.Config.Json} extendJSON The JSON of the extensions
* @return {LH.Config.Json}
*/
static extendConfigJSON(baseJSON, extendJSON) {
if (extendJSON.passes && baseJSON.passes) {
for (const pass of extendJSON.passes) {
// use the default pass name if one is not specified
const passName = pass.passName || constants.defaultPassConfig.passName;
const basePass = baseJSON.passes.find(candidate => candidate.passName === passName);
if (!basePass) {
baseJSON.passes.push(pass);
} else {
merge(basePass, pass);
}
}
delete extendJSON.passes;
}
return merge(baseJSON, extendJSON);
}
/**
* @param {LH.Config.Json} configJSON
* @param {LH.Flags=} flags
* @param {string=} configDir
* @return {LH.Config.Json}
*/
static mergePlugins(configJSON, flags, configDir) {
const configPlugins = configJSON.plugins || [];
const flagPlugins = (flags && flags.plugins) || [];
const pluginNames = new Set([...configPlugins, ...flagPlugins]);
for (const pluginName of pluginNames) {
assertValidPluginName(configJSON, pluginName);
const pluginPath = resolveModule(pluginName, configDir, 'plugin');
const rawPluginJson = require(pluginPath);
const pluginJson = ConfigPlugin.parsePlugin(rawPluginJson, pluginName);
configJSON = Config.extendConfigJSON(configJSON, pluginJson);
}
return configJSON;
}
/**
* @param {LH.Config.Json['passes']} passes
* @return {?Array<Required<LH.Config.PassJson>>}
*/
static augmentPassesWithDefaults(passes) {
if (!passes) {
return null;
}
const {defaultPassConfig} = constants;
return passes.map(pass => merge(deepClone(defaultPassConfig), pass));
}
/**
* @param {LH.SharedFlagsSettings=} settingsJson
* @param {LH.Flags=} flags
* @return {LH.Config.Settings}
*/
static initSettings(settingsJson = {}, flags) {
// If a locale is requested in flags or settings, use it. A typical CLI run will not have one,
// however `lookupLocale` will always determine which of our supported locales to use (falling
// back if necessary).
const locale = i18n.lookupLocale((flags && flags.locale) || settingsJson.locale);
// Fill in missing settings with defaults
const {defaultSettings} = constants;
const settingWithDefaults = merge(deepClone(defaultSettings), settingsJson, true);
// Override any applicable settings with CLI flags
const settingsWithFlags = merge(settingWithDefaults || {}, cleanFlagsForSettings(flags), true);
if (settingsWithFlags.budgets) {
settingsWithFlags.budgets = Budget.initializeBudget(settingsWithFlags.budgets);
}
// Locale is special and comes only from flags/settings/lookupLocale.
settingsWithFlags.locale = locale;
return settingsWithFlags;
}
/**
* Expands the gatherers from user-specified to an internal gatherer definition format.
*
* Input Examples:
* - 'my-gatherer'
* - class MyGatherer extends Gatherer { }
* - {instance: myGathererInstance}
*
* @param {Array<LH.Config.GathererJson>} gatherers
* @return {Array<{instance?: Gatherer, implementation?: GathererConstructor, path?: string, options?: {}}>} passes
*/
static expandGathererShorthand(gatherers) {
const expanded = gatherers.map(gatherer => {
if (typeof gatherer === 'string') {
// just 'path/to/gatherer'
return {path: gatherer, options: {}};
} else if ('implementation' in gatherer || 'instance' in gatherer) {
// {implementation: GathererConstructor, ...} or {instance: GathererInstance, ...}
return gatherer;
} else if ('path' in gatherer) {
// {path: 'path/to/gatherer', ...}
if (typeof gatherer.path !== 'string') {
throw new Error('Invalid Gatherer type ' + JSON.stringify(gatherer));
}
return gatherer;
} else if (typeof gatherer === 'function') {
// just GathererConstructor
return {implementation: gatherer, options: {}};
} else if (gatherer && typeof gatherer.beforePass === 'function') {
// just GathererInstance
return {instance: gatherer, options: {}};
} else {
throw new Error('Invalid Gatherer type ' + JSON.stringify(gatherer));
}
});
return expanded;
}
/**
* Observed throttling methods (devtools/provided) require at least 5s of quiet for the metrics to
* be computed. This method adjusts the quiet thresholds to the required minimums if necessary.
* @param {LH.Config.Settings} settings
* @param {?Array<Required<LH.Config.PassJson>>} passes
*/
static adjustDefaultPassForThrottling(settings, passes) {
if (!passes ||
(settings.throttlingMethod !== 'devtools' && settings.throttlingMethod !== 'provided')) {
return;
}
const defaultPass = passes.find(pass => pass.passName === 'defaultPass');
if (!defaultPass) return;
const overrides = constants.nonSimulatedPassConfigOverrides;
defaultPass.pauseAfterLoadMs =
Math.max(overrides.pauseAfterLoadMs, defaultPass.pauseAfterLoadMs);
defaultPass.cpuQuietThresholdMs =
Math.max(overrides.cpuQuietThresholdMs, defaultPass.cpuQuietThresholdMs);
defaultPass.networkQuietThresholdMs =
Math.max(overrides.networkQuietThresholdMs, defaultPass.networkQuietThresholdMs);
}
/**
* Filter out any unrequested items from the config, based on requested categories or audits.
* @param {Config} config
*/
static filterConfigIfNeeded(config) {
const settings = config.settings;
if (!settings.onlyCategories && !settings.onlyAudits && !settings.skipAudits) {
return;
}
// 1. Filter to just the chosen categories/audits
const {categories, requestedAuditNames} = Config.filterCategoriesAndAudits(config.categories,
settings);
// 2. Resolve which audits will need to run
const audits = config.audits && config.audits.filter(auditDefn =>
requestedAuditNames.has(auditDefn.implementation.meta.id));
// 3. Resolve which gatherers will need to run
const requiredGathererIds = Config.getGatherersNeededByAudits(audits);
// 4. Filter to only the neccessary passes
const passes = Config.generatePassesNeededByGatherers(config.passes, requiredGathererIds);
config.categories = categories;
config.audits = audits;
config.passes = passes;
}
/**
* Filter out any unrequested categories or audits from the categories object.
* @param {Config['categories']} oldCategories
* @param {LH.Config.Settings} settings
* @return {{categories: Config['categories'], requestedAuditNames: Set<string>}}
*/
static filterCategoriesAndAudits(oldCategories, settings) {
if (!oldCategories) {
return {categories: null, requestedAuditNames: new Set()};
}
if (settings.onlyAudits && settings.skipAudits) {
throw new Error('Cannot set both skipAudits and onlyAudits');
}
/** @type {NonNullable<Config['categories']>} */
const categories = {};
const filterByIncludedCategory = !!settings.onlyCategories;
const filterByIncludedAudit = !!settings.onlyAudits;
const categoryIds = settings.onlyCategories || [];
const auditIds = settings.onlyAudits || [];
const skipAuditIds = settings.skipAudits || [];
// warn if the category is not found
categoryIds.forEach(categoryId => {
if (!oldCategories[categoryId]) {
log.warn('config', `unrecognized category in 'onlyCategories': ${categoryId}`);
}
});
// warn if the audit is not found in a category or there are overlaps
const auditsToValidate = new Set(auditIds.concat(skipAuditIds));
for (const auditId of auditsToValidate) {
const foundCategory = Object.keys(oldCategories).find(categoryId => {
const auditRefs = oldCategories[categoryId].auditRefs;
return !!auditRefs.find(candidate => candidate.id === auditId);
});
if (!foundCategory) {
const parentKeyName = skipAuditIds.includes(auditId) ? 'skipAudits' : 'onlyAudits';
log.warn('config', `unrecognized audit in '${parentKeyName}': ${auditId}`);
} else if (auditIds.includes(auditId) && categoryIds.includes(foundCategory)) {
log.warn('config', `${auditId} in 'onlyAudits' is already included by ` +
`${foundCategory} in 'onlyCategories'`);
}
}
const includedAudits = new Set(auditIds);
skipAuditIds.forEach(id => includedAudits.delete(id));
Object.keys(oldCategories).forEach(categoryId => {
const category = deepClone(oldCategories[categoryId]);
if (filterByIncludedCategory && filterByIncludedAudit) {
// If we're filtering to the category and audit whitelist, include the union of the two
if (!categoryIds.includes(categoryId)) {
category.auditRefs = category.auditRefs.filter(audit => auditIds.includes(audit.id));
}
} else if (filterByIncludedCategory) {
// If we're filtering to just the category whitelist and the category is not included, skip it
if (!categoryIds.includes(categoryId)) {
return;
}
} else if (filterByIncludedAudit) {
category.auditRefs = category.auditRefs.filter(audit => auditIds.includes(audit.id));
}
// always filter to the audit blacklist
category.auditRefs = category.auditRefs.filter(audit => !skipAuditIds.includes(audit.id));
if (category.auditRefs.length) {
categories[categoryId] = category;
category.auditRefs.forEach(audit => includedAudits.add(audit.id));
}
});
return {categories, requestedAuditNames: includedAudits};
}
/**
* @param {LH.Config.Json} config
* @return {Array<{id: string, title: string}>}
*/
static getCategories(config) {
const categories = config.categories;
if (!categories) {
return [];
}
return Object.keys(categories).map(id => {
const title = categories[id].title;
return {id, title};
});
}
/**
* From some requested audits, return names of all required artifacts
* @param {Config['audits']} audits
* @return {Set<string>}
*/
static getGatherersNeededByAudits(audits) {
// It's possible we weren't given any audits (but existing audit results), in which case
// there is no need to do any work here.
if (!audits) {
return new Set();
}
return audits.reduce((list, auditDefn) => {
auditDefn.implementation.meta.requiredArtifacts.forEach(artifact => list.add(artifact));
return list;
}, new Set());
}
/**
* Filters to only required passes and gatherers, returning a new passes array.
* @param {Config['passes']} passes
* @param {Set<string>} requiredGatherers
* @return {Config['passes']}
*/
static generatePassesNeededByGatherers(passes, requiredGatherers) {
if (!passes) {
return null;
}
const auditsNeedTrace = requiredGatherers.has('traces');
const filteredPasses = passes.map(pass => {
// remove any unncessary gatherers from within the passes
pass.gatherers = pass.gatherers.filter(gathererDefn => {
const gatherer = gathererDefn.instance;
return requiredGatherers.has(gatherer.name);
});
// disable the trace if no audit requires a trace
if (pass.recordTrace && !auditsNeedTrace) {
const passName = pass.passName || 'unknown pass';
log.warn('config', `Trace not requested by an audit, dropping trace in ${passName}`);
pass.recordTrace = false;
}
return pass;
}).filter(pass => {
// remove any passes lacking concrete gatherers, unless they are dependent on the trace
if (pass.recordTrace) return true;
// Always keep defaultPass
if (pass.passName === 'defaultPass') return true;
return pass.gatherers.length > 0;
});
return filteredPasses;
}
/**
* Take an array of audits and audit paths and require any paths (possibly
* relative to the optional `configDir`) using `resolveModule`,
* leaving only an array of AuditDefns.
* @param {LH.Config.Json['audits']} audits
* @param {string=} configDir
* @return {Config['audits']}
*/
static requireAudits(audits, configDir) {
const status = {msg: 'Requiring audits', id: 'lh:config:requireAudits'};
log.time(status, 'verbose');
const auditDefns = requireAudits(audits, configDir);
log.timeEnd(status);
return auditDefns;
}
/**
* @param {string} path
* @param {{}=} options
* @param {Array<string>} coreAuditList
* @param {string=} configDir
* @return {LH.Config.GathererDefn}
*/
static requireGathererFromPath(path, options, coreAuditList, configDir) {
const coreGatherer = coreAuditList.find(a => a === `${path}.js`);
let requirePath = `../gather/gatherers/${path}`;
if (!coreGatherer) {
// Otherwise, attempt to find it elsewhere. This throws if not found.
requirePath = resolveModule(path, configDir, 'gatherer');
}
const GathererClass = /** @type {GathererConstructor} */ (require(requirePath));
return {
instance: new GathererClass(),
implementation: GathererClass,
path,
options: options || {},
};
}
/**
* Takes an array of passes with every property now initialized except the
* gatherers and requires them, (relative to the optional `configDir` if
* provided) using `resolveModule`, returning an array of full Passes.
* @param {?Array<Required<LH.Config.PassJson>>} passes
* @param {string=} configDir
* @return {Config['passes']}
*/
static requireGatherers(passes, configDir) {
if (!passes) {
return null;
}
const status = {msg: 'Requiring gatherers', id: 'lh:config:requireGatherers'};
log.time(status, 'verbose');
const coreList = Runner.getGathererList();
const fullPasses = passes.map(pass => {
const gathererDefns = Config.expandGathererShorthand(pass.gatherers).map(gathererDefn => {
if (gathererDefn.instance) {
return {
instance: gathererDefn.instance,
implementation: gathererDefn.implementation,
path: gathererDefn.path,
options: gathererDefn.options || {},
};
} else if (gathererDefn.implementation) {
const GathererClass = gathererDefn.implementation;
return {
instance: new GathererClass(),
implementation: gathererDefn.implementation,
path: gathererDefn.path,
options: gathererDefn.options || {},
};
} else if (gathererDefn.path) {
const path = gathererDefn.path;
const options = gathererDefn.options;
return Config.requireGathererFromPath(path, options, coreList, configDir);
} else {
throw new Error('Invalid expanded Gatherer: ' + JSON.stringify(gathererDefn));
}
});
const mergedDefns = mergeOptionsOfItems(gathererDefns);
mergedDefns.forEach(gatherer => assertValidGatherer(gatherer.instance, gatherer.path));
return Object.assign(pass, {gatherers: mergedDefns});
});
log.timeEnd(status);
return fullPasses;
}
}
module.exports = Config;
| wardpeet/lighthouse | lighthouse-core/config/config.js | JavaScript | apache-2.0 | 29,048 |
// Copyright 2017 Google 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.
/**
* controller-ray
*
* Ray line indicator for VR hand controllers.
*
* This replaces the parabola arc whenever the user is not holding the
* controller button down.
*/
import { Scene } from '../core/scene';
if ( typeof AFRAME !== 'undefined' && AFRAME ) {
AFRAME.registerComponent( 'controller-ray', {
schema: {
width: { default: 0.005 },
length: { default: 1 }
},
init: function() {
this.isInteractive = false;
this.geometry = new THREE.PlaneBufferGeometry( this.data.width, this.data.length );
this.geometry.rotateX( Math.PI / -2 );
this.geometry.translate( 0, 0, this.data.length / -2 );
this.material = new THREE.MeshBasicMaterial();
this.mesh = new THREE.Mesh( this.geometry, this.material );
this.el.setObject3D( 'mesh', this.mesh );
this.el.setAttribute( 'visible', false );
this.el.sceneEl.addEventListener( 'terrain-intersected-cleared', () => {
if ( !this.isInteractive ) return;
if ( Scene.controllerType === 'mouse-touch' ) return;
this.el.setAttribute( 'visible', true );
});
this.el.sceneEl.addEventListener( 'terrain-intersected', () => {
if ( !this.isInteractive ) return;
if ( Scene.controllerType === 'mouse-touch' ) return;
this.el.setAttribute( 'visible', false );
});
this.el.sceneEl.addEventListener( 'stateadded', event => {
if ( event.detail.state === 'interactive' ) this.isInteractive = true;
if ( event.target !== this.el.sceneEl ) return;
});
this.el.sceneEl.addEventListener( 'stateremoved', event => {
if ( event.detail.state === 'interactive' ) this.isInteractive = false;
if ( event.target !== this.el.sceneEl ) return;
});
},
play: function() {
}
});
}
| googlecreativelab/access-mars | src/js/components/controller-ray.js | JavaScript | apache-2.0 | 2,310 |
import { helper } from '@ember/component/helper';
export function runTime(params) {
var s = moment(params[0]);
var e = moment(params[1]);
var time = Math.round(e.diff(s)/100)/10;
if ( time )
{
if ( time > 60 )
{
time = Math.round(time);
}
return `${time} sec`;
}
else
{
return '<span class="text-muted">-</span>'.htmlSafe();
}
}
export default helper(runTime);
| pengjiang80/ui | lib/shared/addon/helpers/run-time.js | JavaScript | apache-2.0 | 409 |
/*
+-----------------------------------------------------------------------------+
@grahamzibar presents:
_______ _______ _______ _______ _______ _______
( )( ___ )( ____ )( ____ )|\ /|( ____ \|\ /|( ____ \
| () () || ( ) || ( )|| ( )|| ) ( || ( \/| ) ( || ( \/
| || || || | | || (____)|| (____)|| (___) || (__ | | | || (_____
| |(_)| || | | || __)| _____)| ___ || __) | | | |(_____ )
| | | || | | || (\ ( | ( | ( ) || ( | | | | ) |
| ) ( || (___) || ) \ \__| ) | ) ( || (____/\| (___) |/\____) |
|/ \|(_______)|/ \__/|/ |/ \|(_______/(_______)\_______)
* version 0.1.0 - ALPHA
* https://www.github.com/grahamzibar/Morpheus
* What if I told you... this is not an animation library?
+-----------------------------------------------------------------------------+
*/
(function MorpheusModule(_win) {
if (!_win.morpheus)
_win.morpheus = new Object();
var Morpheus = _win.morpheus;
/*
CONSTANTS
*/
Morpheus.LINEAR = 'linear';
Morpheus.EASE = 'ease';
Morpheus.EASE_IN = 'ease-in';
Morpheus.EASE_OUT = 'ease-out';
Morpheus.EASE_IN_OUT = 'ease-in-out';
Morpheus.EASE_OUT_IN = 'ease-out-in';
Morpheus.LEFT = 'left';
Morpheus.RIGHT = 'right';
Morpheus.CENTER = 'center';
Morpheus.THREE_D = 'preserve-3d';
Morpheus.FLAT = 'flat';
Morpheus.PIXELS = 'px';
Morpheus.PERCENT = '%';
Morpheus.RADIANS = 'rad';
Morpheus.DEGREES = 'deg';
Morpheus.TRANSFORM = '-webkit-transform';
/*
CLASSES
*/
var Vector = function Vector(x, y, z) {
this.x = x != null ? x : 0.0;
this.y = y != null ? y : 0.0;
this.z = z != null ? z : 0.0;
};
Vector.prototype.set = function(x, y, z) {
this.x = x;
if (y != null) {
this.y = y;
if (z != null)
this.z = z;
}
};
var Collection = function Collection() {
var _collection = new Array();
var _cache = {};
this.collection = _collection;
this.add = function(key, value) {
var index = _cache[key];
if (typeof index === 'number')
_collection[index] = value;
else {
index = _cache[key] = _collection.length;
_collection[index] = value;
}
};
this.get = function(key) {
var index = _cache[key];
if (!index && index !== 0)
return null;
return _collection[index];
};
this.remove = function(key) {
if (_cache[key])
_collection.splice(_cache[key], 1);
};
};
var Style = function Style(_name, _value, _unit) {
this.name = _name;
this.value = _value;
this.unit = _unit != null ? _unit : '';
};
var StyleCollection = function StyleCollection() {
this.inheritFrom = Collection;
this.inheritFrom();
delete this.inheritFrom;
var add = this.add;
this.add = function(style) {
add(style.name, style);
};
};
var Transition = function Transition(_property) {
this.property = _property;
this.duration = 500;
this.delay = 0;
this.timing = Morpheus.LINEAR;
};
var TransitionCollection = function TransitionCollection() {
this.inheritFrom = Collection;
this.inheritFrom();
delete this.inheritFrom;
var add = this.add;
this.add = function(transition) {
add(transition.property, transition);
};
};
var Transform = function Transform() {
this.translate = new Vector();
this.translateUnit = 'px';
this.scale = new Vector(1, 1, 1);
this.rotate = new Vector();
this.rotateUnit = 'rad';
//this.skew?
this.origin = new Vector(Morpheus.CENTER, Morpheus.CENTER, Morpheus.CENTER);
this.style = Morpheus.THREE_D;
};
// How should the renderer work?
Morpheus.Renderer = function Renderer(_el) {
var _render = false;
var onEnterFrame = function(e) {
if (_render) {
_render = false;
var output = '';
var styles = _el.styles;
var transitions = _el.transitions;
var transform = _el.transform;
if (styles) {
for (var i = 0, len = styles.collection.length; i < len; i++)
output += renderStyle(styles.collection[i]);
}
if (transitions)
output += renderTransitionCollection(transitions);
if (transform)
output += renderTransform(transform);
_el.css = output;
}
window.requestAnimationFrame(onEnterFrame);
};
var renderStyle = function(style) {
var output = style.name;
output += ':';
output += style.value;
output += style.unit;
output += ';';
return output;
};
var renderTransitionCollection = function(tc) {
var output = 'transition:';
for (var i = 0, ts = tc.collection, len = ts.length; i < len; i++) {
if (i)
output += ', ';
output += renderTransition(ts[i]);
}
output += ';';
return output;
};
var renderTransition = function(transition) {
var space = ' ';
var t = transition.property;
t += space;
t += transition.duration;
t += 'ms';
t += space;
t += transition.timing;
t += space;
t += transition.delay;
t += 'ms';
return t;
};
var renderTransform = function(transform) {
var space = ' ';
var t = '-webkit-transform:translate3d';
t += renderVector(transform.translate, transform.translateUnit);
t += space;
t += 'rotateX(';
t += transform.rotate.x;
t += transform.rotateUnit;
t += ')';
t += 'rotateY(';
t += transform.rotate.y;
t += transform.rotateUnit;
t += ')';
t += 'rotateZ(';
t += transform.rotate.z;
t += transform.rotateUnit;
t += ')';
t += space;
t += 'scale3d';
t += renderVector(transform.scale);
t += ';';
t += '-webkit-transform-origin:';
t += transform.origin.x;
t += space;
t += transform.origin.y;
t += space;
t += transform.origin.z;
t += ';';
t += '-webkit-transform-style:';
t += transform.style;
t += ';';
return t;
};
var renderVector = function(vector, unit) {
unit = unit != null ? unit : '';
var coord = '(';
coord += vector.x;
if (vector.x)
coord += unit;
coord += ', ';
coord += vector.y;
if (vector.y)
coord += unit;
coord += ', ';
coord += vector.z;
if (vector.z)
coord += unit;
coord += ')';
return coord;
};
this.step = function() {
_render = true;
};
window.requestAnimationFrame(onEnterFrame);
};
/*
FUNCTIONS
*/
var getStyle = function(property) {
if (document.defaultView && document.defaultView.getComputedStyle)
return document.defaultView.getComputedStyle(this, false).getPropertyValue(property);
if (this.currentStyle) {
return this.currentStyle[property.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
})];
}
return null;
};
var getStyleNumber = function(property, unit) {
var value = this.getStyle(property);
if (unit)
value = value.split(unit)[0];
return Number(value);
};
var setStyle = function(property, value, unit) {
if (!this.styles)
this.styles = new StyleCollection();
this.styles.add(new Style(property, value, unit));
if (!this.renderer)
this.renderer = new Morpheus.Renderer(this);
this.renderer.step();
};
var setCSS = function(css) {
if (typeof this.style.cssText != 'undefined')
this.style.cssText = css;
else
this.setAttribute('style', css);
};
var translation = function(x, y, z, unit) {
if (!this.transform)
this.transform = new Transform();
this.transform.translate.x = x;
this.transform.translate.y = y;
if (z != null) {
if (arguments.length === 3 && typeof z !== 'number')
this.transform.translateUnit = z;
else
this.transform.z = z;
}
if (unit)
this.transform.translateUnit = unit;
if (!this.renderer)
this.renderer = new Morpheus.Renderer(this);
this.renderer.step();
};
var scale = function(x, y, z) {
if (!this.transform)
this.transform = new Transform();
this.transform.scale.x = x;
this.transform.scale.y = y;
if (z != null)
this.transform.scale.z = z;
if (!this.renderer)
this.renderer = new Morpheus.Renderer(this);
this.renderer.step();
};
var rotate = function(x, y, z, unit) {
if (!this.transform)
this.transform = new Transform();
this.transform.rotate.x = x;
this.transform.rotate.y = y;
this.transform.rotate.z = z;
if (unit)
this.transform.rotateUnit = unit;
if (!this.renderer)
this.renderer = new Morpheus.Renderer(this);
this.renderer.step();
};
var setOrigin = function(x, y, z) {
if (!this.transform)
this.transform = new Transform();
this.transform.origin.x = x;
if (y != null) {
this.transform.origin.y = y;
if (z != null)
this.transform.origin.z = z;
}
if (!this.renderer)
this.renderer = new Morpheus.Renderer(this);
this.renderer.step();
};
var addTransition = function(property, duration, timing, delay) {
if (!this.transitions)
this.transitions = new TransitionCollection();
var transition = this.transitions.get(property);
if (!transition)
transition = new Transition(property);
if (duration)
transition.duration = duration;
if (timing)
transition.timing = timing;
if (delay)
transition.delay = delay;
this.transitions.add(transition);
};
var removeTransition = function(property) {
if (this.transitions)
this.transitions.remove(property);
};
/*
EXTENSION
*/
var HTMLElement = _win.HTMLElement;
HTMLElement.prototype.styles = null;
HTMLElement.prototype.transitions = null;
HTMLElement.prototype.transform = null;
HTMLElement.prototype.__defineSetter__('css', setCSS);
HTMLElement.prototype.getStyle = getStyle;
HTMLElement.prototype.getStyleNumber = getStyleNumber;
HTMLElement.prototype.setStyle = setStyle;
HTMLElement.prototype.translation = translation;
HTMLElement.prototype.scale = scale;
HTMLElement.prototype.rotate = rotate;
HTMLElement.prototype.setOrigin = setOrigin;
HTMLElement.prototype.addTransition = addTransition;
HTMLElement.prototype.removeTransition = removeTransition;
if (!HTMLElement.prototype.dispatchEvent) {
// implement
}
// THIS NEEDS TO CHANGE, YO -- should be in the renderer class.
(function(window) {
var time, vendor, vendors, _i, _len;
time = 0;
vendors = ['ms', 'moz', 'webkit', 'o'];
for (_i = 0, _len = vendors.length; _i < _len; _i++) {
vendor = vendors[_i];
if (!(!window.requestAnimationFrame))
continue;
window.requestAnimationFrame = window[vendor + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendor + 'CancelAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback) {
var delta, now, old;
now = new Date().getTime();
delta = Math.max(0, 16 - (now - old));
setTimeout(function() {
return callback(time + delta);
}, delta);
return old = now + delta;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
return clearTimeout(id);
};
}
})(_win);
})(window);
/*
+-----------------------------------------------------------------------------+
written & directed by:
_ _ _
___ ___ ___| |_ ___ _____ ___|_| |_ ___ ___
| . | _| .'| | .'| |- _| | . | .'| _|
|_ |_| |__,|_|_|__,|_|_|_|___|_|___|__,|_|
|___|
+-----------------------------------------------------------------------------+
*/ | grahamzibar/AirChat | src/js/ext/morpheus/Morpheus.js | JavaScript | apache-2.0 | 11,243 |
define([
'./core',
'./var/indexOf',
'./traversing/var/rneedsContext',
'./core/init',
'./traversing/findFilter',
'./selector'
], function(jQuery, indexOf, rneedsContext) {
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function(elem, dir, until) {
var matched = [],
truncate = until !== undefined;
while ((elem = elem[dir]) && elem.nodeType !== 9) {
if (elem.nodeType === 1) {
if (truncate && jQuery(elem).is(until)) {
break;
}
matched.push(elem);
}
}
return matched;
},
sibling: function(n, elem) {
var matched = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1 && n !== elem) {
matched.push(n);
}
}
return matched;
}
});
jQuery.fn.extend({
has: function(target) {
var targets = jQuery(target, this),
l = targets.length;
return this.filter(function() {
var i = 0;
for (; i < l; i++) {
if (jQuery.contains(this, targets[i])) {
return true;
}
}
});
},
closest: function(selectors, context) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test(selectors) || typeof selectors !== 'string' ?
jQuery(selectors, context || this.context) :
0;
for (; i < l; i++) {
for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) {
// Always skip document fragments
if (cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors))) {
matched.push(cur);
break;
}
}
}
return this.pushStack(matched.length > 1 ? jQuery.unique(matched) : matched);
},
// Determine the position of an element within the set
index: function(elem) {
// No argument, return index in parent
if (!elem) {
return (this[0] && this[0].parentNode) ? this.first().prevAll().length : -1;
}
// Index in selector
if (typeof elem === 'string') {
return indexOf.call(jQuery(elem), this[0]);
}
// Locate the position of the desired element
return indexOf.call(this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem
);
},
add: function(selector, context) {
return this.pushStack(
jQuery.unique(
jQuery.merge(this.get(), jQuery(selector, context))
)
);
},
addBack: function(selector) {
return this.add(selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling(cur, dir) {
while ((cur = cur[dir]) && cur.nodeType !== 1) {
}
return cur;
}
jQuery.each({
parent: function(elem) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function(elem) {
return jQuery.dir(elem, 'parentNode');
},
parentsUntil: function(elem, i, until) {
return jQuery.dir(elem, 'parentNode', until);
},
next: function(elem) {
return sibling(elem, 'nextSibling');
},
prev: function(elem) {
return sibling(elem, 'previousSibling');
},
nextAll: function(elem) {
return jQuery.dir(elem, 'nextSibling');
},
prevAll: function(elem) {
return jQuery.dir(elem, 'previousSibling');
},
nextUntil: function(elem, i, until) {
return jQuery.dir(elem, 'nextSibling', until);
},
prevUntil: function(elem, i, until) {
return jQuery.dir(elem, 'previousSibling', until);
},
siblings: function(elem) {
return jQuery.sibling((elem.parentNode || {}).firstChild, elem);
},
children: function(elem) {
return jQuery.sibling(elem.firstChild);
},
contents: function(elem) {
return elem.contentDocument || jQuery.merge([], elem.childNodes);
}
}, function(name, fn) {
jQuery.fn[name] = function(until, selector) {
var matched = jQuery.map(this, fn, until);
if (name.slice(-5) !== 'Until') {
selector = until;
}
if (selector && typeof selector === 'string') {
matched = jQuery.filter(selector, matched);
}
if (this.length > 1) {
// Remove duplicates
if (!guaranteedUnique[name]) {
jQuery.unique(matched);
}
// Reverse order for parents* and prev-derivatives
if (rparentsprev.test(name)) {
matched.reverse();
}
}
return this.pushStack(matched);
};
});
return jQuery;
}); | amido/Amido.VersionDashboard | src/Amido.VersionDashboard.Web/bower_components/jquery/src/traversing.js | JavaScript | apache-2.0 | 6,056 |
'use strict';
angular.module('sproutStudyApp')
.controller('settingsController', function ($scope, $location, $routeParams, settingsService) {
$scope.settings = null;
$scope.user = null;
settingsService.getUser(null, function(data) {
$scope.user = data;
});
});
| stephenlorenz/sproutstudy | sproutStudy_web/src/main/webapp/scripts/controllers/settingsController.js | JavaScript | apache-2.0 | 294 |
var mustInputDM = 'Hãy nhập "tên danh mục" !';
var mustNumber = '"Thứ tự sấp xếp" phải là số !';
var mustInput_Name = 'Hãy nhập "họ tên" !';
var mustInput_Company = 'Hãy nhập "tên công ty" !';
var mustInput_Address = 'Hãy nhập "địa chỉ" !';
var mustInput_city = 'Hãy nhập "tỉnh / thành phố" !';
var mustInput_Tel = 'Hãy nhập "số điện thoại" !';
var mustInterger_Tel = '"Số điện thoại" phải là số !';
var mustInput_Email = 'Hãy nhập "hộp thư" !';
var invalid_Email = '"Hộp thư" không đúng định dạng !';
var mustSelect_Country = 'Hãy chọn "quốc gia" !';
//var mustInput_Detail = 'Hãy nhập "nội dung" !';
var mustInput_Search = 'Hãy nhập "nội dung tìm kiếm" !'; | vikigroup/cbuilk | lib/varAlert.vn.unicode.js | JavaScript | apache-2.0 | 819 |
//
// browser.js - client-side engine
//
var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(location.protocol);
less.env = less.env || (location.hostname == '127.0.0.1' ||
location.hostname == '0.0.0.0' ||
location.hostname == 'localhost' ||
location.port.length > 0 ||
isFileProtocol ? 'development'
: 'production');
// Load styles asynchronously (default: false)
//
// This is set to `false` by default, so that the body
// doesn't start loading before the stylesheets are parsed.
// Setting this to `true` can result in flickering.
//
less.async = less.async || false;
less.fileAsync = less.fileAsync || false;
// Interval between watch polls
less.poll = less.poll || (isFileProtocol ? 1000 : 1500);
//Setup user functions
if (less.functions) {
for(var func in less.functions) {
less.tree.functions[func] = less.functions[func];
}
}
var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(location.hash);
if (dumpLineNumbers) {
less.dumpLineNumbers = dumpLineNumbers[1];
}
//
// Watch mode
//
less.watch = function () {
if (!less.watchMode ){
less.env = 'development';
initRunningMode();
}
return this.watchMode = true
};
less.unwatch = function () {clearInterval(less.watchTimer); return this.watchMode = false; };
function initRunningMode(){
if (less.env === 'development') {
less.optimization = 0;
less.watchTimer = setInterval(function () {
if (less.watchMode) {
loadStyleSheets(function (e, root, _, sheet, env) {
if (e) {
error(e, sheet.href);
} else if (root) {
createCSS(root.toCSS(less), sheet, env.lastModified);
}
});
}
}, less.poll);
} else {
less.optimization = 3;
}
}
if (/!watch/.test(location.hash)) {
less.watch();
}
var cache = null;
if (less.env != 'development') {
try {
cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage;
} catch (_) {}
}
//
// Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
//
var links = document.getElementsByTagName('link');
var typePattern = /^text\/(x-)?less$/;
less.sheets = [];
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
(links[i].type.match(typePattern)))) {
less.sheets.push(links[i]);
}
}
//
// With this function, it's possible to alter variables and re-render
// CSS without reloading less-files
//
var session_cache = '';
less.modifyVars = function(record) {
var str = session_cache;
for (name in record) {
str += ((name.slice(0,1) === '@')? '' : '@') + name +': '+
((record[name].slice(-1) === ';')? record[name] : record[name] +';');
}
new(less.Parser)(new less.tree.parseEnv(less)).parse(str, function (e, root) {
if (e) {
error(e, "session_cache");
} else {
createCSS(root.toCSS(less), less.sheets[less.sheets.length - 1]);
}
});
};
less.refresh = function (reload) {
var startTime, endTime;
startTime = endTime = new(Date);
loadStyleSheets(function (e, root, _, sheet, env) {
if (e) {
return error(e, sheet.href);
}
if (env.local) {
log("loading " + sheet.href + " from cache.");
} else {
log("parsed " + sheet.href + " successfully.");
createCSS(root.toCSS(less), sheet, env.lastModified);
}
log("css for " + sheet.href + " generated in " + (new(Date) - endTime) + 'ms');
(env.remaining === 0) && log("css generated in " + (new(Date) - startTime) + 'ms');
endTime = new(Date);
}, reload);
loadStyles();
};
less.refreshStyles = loadStyles;
less.refresh(less.env === 'development');
function loadStyles() {
var styles = document.getElementsByTagName('style');
for (var i = 0; i < styles.length; i++) {
if (styles[i].type.match(typePattern)) {
var env = new less.tree.parseEnv(less);
env.filename = document.location.href.replace(/#.*$/, '');
new(less.Parser)(env).parse(styles[i].innerHTML || '', function (e, cssAST) {
if (e) {
return error(e, "inline");
}
var css = cssAST.toCSS(less);
var style = styles[i];
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.innerHTML = css;
}
});
}
}
}
function loadStyleSheets(callback, reload) {
for (var i = 0; i < less.sheets.length; i++) {
loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1));
}
}
function pathDiff(url, baseUrl) {
// diff between two paths to create a relative path
var urlParts = extractUrlParts(url),
baseUrlParts = extractUrlParts(baseUrl),
i, max, urlDirectories, baseUrlDirectories, diff = "";
if (urlParts.hostPart !== baseUrlParts.hostPart) {
return "";
}
max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
for(i = 0; i < max; i++) {
if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; }
}
baseUrlDirectories = baseUrlParts.directories.slice(i);
urlDirectories = urlParts.directories.slice(i);
for(i = 0; i < baseUrlDirectories.length-1; i++) {
diff += "../";
}
for(i = 0; i < urlDirectories.length-1; i++) {
diff += urlDirectories[i] + "/";
}
return diff;
}
function extractUrlParts(url, baseUrl) {
// urlParts[1] = protocol&hostname || /
// urlParts[2] = / if path relative to host base
// urlParts[3] = directories
// urlParts[4] = filename
// urlParts[5] = parameters
var urlPartsRegex = /^((?:[a-z-]+:)?\/+?(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/,
urlParts = url.match(urlPartsRegex),
returner = {}, directories = [], i, baseUrlParts;
if (!urlParts) {
throw new Error("Could not parse sheet href - '"+url+"'");
}
// Stylesheets in IE don't always return the full path
if (!urlParts[1] || urlParts[2]) {
baseUrlParts = baseUrl.match(urlPartsRegex);
if (!baseUrlParts) {
throw new Error("Could not parse page url - '"+baseUrl+"'");
}
urlParts[1] = baseUrlParts[1];
if (!urlParts[2]) {
urlParts[3] = baseUrlParts[3] + urlParts[3];
}
}
if (urlParts[3]) {
directories = urlParts[3].replace("\\", "/").split("/");
for(i = 0; i < directories.length; i++) {
if (directories[i] === ".." && i > 0) {
directories.splice(i-1, 2);
i -= 2;
}
}
}
returner.hostPart = urlParts[1];
returner.directories = directories;
returner.path = urlParts[1] + directories.join("/");
returner.fileUrl = returner.path + (urlParts[4] || "");
returner.url = returner.fileUrl + (urlParts[5] || "");
return returner;
}
function loadStyleSheet(sheet, callback, reload, remaining) {
// sheet may be set to the stylesheet for the initial load or a collection of properties including
// some env variables for imports
var hrefParts = extractUrlParts(sheet.href, window.location.href);
var href = hrefParts.url;
var css = cache && cache.getItem(href);
var timestamp = cache && cache.getItem(href + ':timestamp');
var styles = { css: css, timestamp: timestamp };
var env;
if (sheet instanceof less.tree.parseEnv) {
env = new less.tree.parseEnv(sheet);
} else {
env = new less.tree.parseEnv(less);
env.entryPath = hrefParts.path;
env.mime = sheet.type;
}
if (env.relativeUrls) {
//todo - this relies on option being set on less object rather than being passed in as an option
// - need an originalRootpath
if (less.rootpath) {
env.rootpath = extractUrlParts(less.rootpath + pathDiff(hrefParts.path, env.entryPath)).path;
} else {
env.rootpath = hrefParts.path;
}
} else {
if (!less.rootpath) {
env.rootpath = env.entryPath;
}
}
xhr(href, sheet.type, function (data, lastModified) {
// Store data this session
session_cache += data.replace(/@import .+?;/ig, '');
if (!reload && styles && lastModified &&
(new(Date)(lastModified).valueOf() ===
new(Date)(styles.timestamp).valueOf())) {
// Use local copy
createCSS(styles.css, sheet);
callback(null, null, data, sheet, { local: true, remaining: remaining }, href);
} else {
// Use remote copy (re-parse)
try {
env.contents[href] = data; // Updating content cache
env.paths = [hrefParts.path];
env.filename = href;
env.rootFilename = env.rootFilename || href;
new(less.Parser)(env).parse(data, function (e, root) {
if (e) { return callback(e, null, null, sheet); }
try {
callback(e, root, data, sheet, { local: false, lastModified: lastModified, remaining: remaining }, href);
//TODO - there must be a better way? A generic less-to-css function that can both call error
//and removeNode where appropriate
//should also add tests
if (env.rootFilename === href) {
removeNode(document.getElementById('less-error-message:' + extractId(href)));
}
} catch (e) {
callback(e, null, null, sheet);
}
});
} catch (e) {
callback(e, null, null, sheet);
}
}
}, function (status, url) {
callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, null, sheet);
});
}
function extractId(href) {
return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain
.replace(/^\//, '' ) // Remove root /
.replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension
.replace(/[^\.\w-]+/g, '-') // Replace illegal characters
.replace(/\./g, ':'); // Replace dots with colons(for valid id)
}
function createCSS(styles, sheet, lastModified) {
var css;
// Strip the query-string
var href = sheet.href || '';
// If there is no title set, use the filename, minus the extension
var id = 'less:' + (sheet.title || extractId(href));
// If the stylesheet doesn't exist, create a new node
if ((css = document.getElementById(id)) === null) {
css = document.createElement('style');
css.type = 'text/css';
if( sheet.media ){ css.media = sheet.media; }
css.id = id;
var nextEl = sheet && sheet.nextSibling || null;
(nextEl || document.getElementsByTagName('head')[0]).parentNode.insertBefore(css, nextEl);
}
if (css.styleSheet) { // IE
try {
css.styleSheet.cssText = styles;
} catch (e) {
throw new(Error)("Couldn't reassign styleSheet.cssText.");
}
} else {
(function (node) {
if (css.childNodes.length > 0) {
if (css.firstChild.nodeValue !== node.nodeValue) {
css.replaceChild(node, css.firstChild);
}
} else {
css.appendChild(node);
}
})(document.createTextNode(styles));
}
// Don't update the local store if the file wasn't modified
if (lastModified && cache) {
log('saving ' + href + ' to cache.');
try {
cache.setItem(href, styles);
cache.setItem(href + ':timestamp', lastModified);
} catch(e) {
//TODO - could do with adding more robust error handling
log('failed to save');
}
}
}
function xhr(url, type, callback, errback) {
var xhr = getXMLHttpRequest();
var async = isFileProtocol ? less.fileAsync : less.async;
if (typeof(xhr.overrideMimeType) === 'function') {
xhr.overrideMimeType('text/css');
}
xhr.open('GET', url, async);
xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
xhr.send(null);
if (isFileProtocol && !less.fileAsync) {
if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
callback(xhr.responseText);
} else {
errback(xhr.status, url);
}
} else if (async) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
handleResponse(xhr, callback, errback);
}
};
} else {
handleResponse(xhr, callback, errback);
}
function handleResponse(xhr, callback, errback) {
if (xhr.status >= 200 && xhr.status < 300) {
callback(xhr.responseText,
xhr.getResponseHeader("Last-Modified"));
} else if (typeof(errback) === 'function') {
errback(xhr.status, url);
}
}
}
function getXMLHttpRequest() {
if (window.XMLHttpRequest) {
return new(XMLHttpRequest);
} else {
try {
return new(ActiveXObject)("MSXML2.XMLHTTP.3.0");
} catch (e) {
log("browser doesn't support AJAX.");
return null;
}
}
}
function removeNode(node) {
return node && node.parentNode.removeChild(node);
}
function log(str) {
if (less.env == 'development' && typeof(console) !== "undefined") { console.log('less: ' + str) }
}
function error(e, rootHref) {
var id = 'less-error-message:' + extractId(rootHref || "");
var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
var elem = document.createElement('div'), timer, content, error = [];
var filename = e.filename || rootHref;
var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
elem.id = id;
elem.className = "less-error-message";
content = '<h3>' + (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') +
'</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + "</a> ";
var errorline = function (e, i, classname) {
if (e.extract[i] != undefined) {
error.push(template.replace(/\{line\}/, (parseInt(e.line) || 0) + (i - 1))
.replace(/\{class\}/, classname)
.replace(/\{content\}/, e.extract[i]));
}
};
if (e.extract) {
errorline(e, 0, '');
errorline(e, 1, 'line');
errorline(e, 2, '');
content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' +
'<ul>' + error.join('') + '</ul>';
} else if (e.stack) {
content += '<br/>' + e.stack.split('\n').slice(1).join('<br/>');
}
elem.innerHTML = content;
// CSS for error messages
createCSS([
'.less-error-message ul, .less-error-message li {',
'list-style-type: none;',
'margin-right: 15px;',
'padding: 4px 0;',
'margin: 0;',
'}',
'.less-error-message label {',
'font-size: 12px;',
'margin-right: 15px;',
'padding: 4px 0;',
'color: #cc7777;',
'}',
'.less-error-message pre {',
'color: #dd6666;',
'padding: 4px 0;',
'margin: 0;',
'display: inline-block;',
'}',
'.less-error-message pre.line {',
'color: #ff0000;',
'}',
'.less-error-message h3 {',
'font-size: 20px;',
'font-weight: bold;',
'padding: 15px 0 5px 0;',
'margin: 0;',
'}',
'.less-error-message a {',
'color: #10a',
'}',
'.less-error-message .error {',
'color: red;',
'font-weight: bold;',
'padding-bottom: 2px;',
'border-bottom: 1px dashed red;',
'}'
].join('\n'), { title: 'error-message' });
elem.style.cssText = [
"font-family: Arial, sans-serif",
"border: 1px solid #e00",
"background-color: #eee",
"border-radius: 5px",
"-webkit-border-radius: 5px",
"-moz-border-radius: 5px",
"color: #e00",
"padding: 15px",
"margin-bottom: 15px"
].join(';');
if (less.env == 'development') {
timer = setInterval(function () {
if (document.body) {
if (document.getElementById(id)) {
document.body.replaceChild(elem, document.getElementById(id));
} else {
document.body.insertBefore(elem, document.body.firstChild);
}
clearInterval(timer);
}
}, 10);
}
}
| wcea/less.js | lib/less/browser.js | JavaScript | apache-2.0 | 17,695 |
/* global QUnit, sinon, testEventHandlerResolver, someGlobalMethodOnWindow */
sap.ui.define([
"sap/ui/core/Control",
"sap/ui/model/json/JSONModel",
"sap/ui/core/mvc/EventHandlerResolver",
"sap/base/Log"
], function(Control, JSONModel, EventHandlerResolver, Log) {
"use strict";
var oController;
var thisContext;
var oDummySource;
var DummyControl = Control.extend("test.DummyControl", {
metadata: {
properties: {
someControlProperty: "string"
}
}
});
var oDummyEvent = {
getSource: function() {
return oDummySource;
},
mParameters: {
someEventParameter: "someEventParameterValue"
}
};
var mLocals = {
someMethod: function() {
thisContext = this;
},
someFormatter: function() {
return "#" + Array.prototype.slice.call(arguments).join(",") + "#";
}
};
QUnit.module("sap.ui.core.mvc.EventHandlerResolver - handler function", {
beforeEach: function() {
thisContext = null;
oController = {
fnControllerMethod: function() {
thisContext = this;
},
ns: {
deepMethod: function() {
}
}
};
window.testEventHandlerResolver = {
subobject: {
someGlobalMethod: function() {
thisContext = this;
}
}
};
window.someGlobalMethodOnWindow = function() {
thisContext = this;
};
oDummySource = new DummyControl();
},
afterEach: function() {
oController = null;
window.testEventHandlerResolver = null;
oDummySource.destroy();
}
});
QUnit.test("Plain handler resolution", function(assert) {
var fnController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod", oController)[0];
assert.equal(fnController, oController.fnControllerMethod, "Controller method should be found");
var fnGlobal = EventHandlerResolver.resolveEventHandler("testEventHandlerResolver.subobject.someGlobalMethod", oController)[0];
assert.equal(fnGlobal, window.testEventHandlerResolver.subobject.someGlobalMethod, "Global method should be found");
fnGlobal = EventHandlerResolver.resolveEventHandler("ns.deepMethod", oController);
assert.strictEqual(fnGlobal, undefined, "Function name with deeper path shouldn't be searched in the controller");
});
QUnit.test("Handler resolution when parentheses are present", function(assert) {
sinon.spy(oController, "fnControllerMethod");
var fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod()", oController)[0];
fnFromController(oDummyEvent);
assert.equal(oController.fnControllerMethod.callCount, 1, "Controller method should be called");
oController.fnControllerMethod.resetHistory();
var fnFromController2 = EventHandlerResolver.resolveEventHandler("fnControllerMethod()", oController)[0];
fnFromController2(oDummyEvent);
assert.equal(oController.fnControllerMethod.callCount, 1, "Controller method without dot should be called");
sinon.spy(testEventHandlerResolver.subobject, "someGlobalMethod");
var fnFromGlobal = EventHandlerResolver.resolveEventHandler("testEventHandlerResolver.subobject.someGlobalMethod()", oController)[0];
fnFromGlobal(oDummyEvent);
assert.equal(testEventHandlerResolver.subobject.someGlobalMethod.callCount, 1, "Global method should be called once");
sinon.spy(window, "someGlobalMethodOnWindow");
fnFromGlobal = EventHandlerResolver.resolveEventHandler("someGlobalMethodOnWindow()", oController)[0];
fnFromGlobal(oDummyEvent);
assert.equal(someGlobalMethodOnWindow.callCount, 1, "Global method without dot should be called once");
});
QUnit.test("Handler resolution with local variables", function(assert) {
var oSpy = this.spy(mLocals, "someMethod");
// immediately call the resolving handler
EventHandlerResolver.resolveEventHandler("Module.someMethod()", oController, {Module: mLocals})[0]();
assert.equal(oSpy.callCount, 1, "Module method should be called once");
oSpy.resetHistory();
// without parentheses
EventHandlerResolver.resolveEventHandler("Module.someMethod", oController, {Module: mLocals})[0]();
assert.equal(oSpy.callCount, 1, "Module method should be called once");
oSpy.resetHistory();
// test without associated controller
EventHandlerResolver.resolveEventHandler("Module.someMethod()", null, {Module: mLocals})[0]();
assert.equal(oSpy.callCount, 1, "Module method should be called once");
oSpy.resetHistory();
// without parentheses
EventHandlerResolver.resolveEventHandler("Module.someMethod", null, {Module: mLocals})[0]();
assert.equal(oSpy.callCount, 1, "Module method should be called once");
});
QUnit.test("Log warning for usage of not properly XML-required modules", function(assert) {
var logSpy = sinon.spy(Log, "warning");
// immediately call the resolving handler
EventHandlerResolver.resolveEventHandler("Module.someMethod()", oController, {Module: {}});
sinon.assert.calledWithExactly(logSpy, "Event handler name 'Module.someMethod()' could not be resolved to an event handler function");
logSpy.resetHistory();
// test without associated controller
EventHandlerResolver.resolveEventHandler("Module.someMethod()", null, {Module: {}});
sinon.assert.calledWithExactly(logSpy, "Event handler name 'Module.someMethod()' could not be resolved to an event handler function");
logSpy.restore();
});
QUnit.test("'this' context when no parenthese is present", function(assert) {
// controller functions
var vResolvedHandler = EventHandlerResolver.resolveEventHandler(".fnControllerMethod", oController);
vResolvedHandler[0].call(vResolvedHandler[1], oDummyEvent);
assert.equal(thisContext, oController, "Controller method should be called with controller as 'this' context");
thisContext = "wrong"; // to make sure non-calls don't accidentally get the correct value
// controller functions without dot
vResolvedHandler = EventHandlerResolver.resolveEventHandler("fnControllerMethod", oController);
vResolvedHandler[0].call(vResolvedHandler[1], oDummyEvent);
assert.equal(thisContext, oController, "Controller method without dot should be called with controller as 'this' context");
thisContext = "wrong";
// global functions
vResolvedHandler = EventHandlerResolver.resolveEventHandler("testEventHandlerResolver.subobject.someGlobalMethod", oController);
vResolvedHandler[0].call(vResolvedHandler[1], oDummyEvent);
assert.equal(thisContext, oController, "Global method should be called with controller as 'this' context when there's no parenthese");
thisContext = "wrong";
// global functions without dot
vResolvedHandler = EventHandlerResolver.resolveEventHandler("someGlobalMethodOnWindow", oController);
vResolvedHandler[0].call(vResolvedHandler[1], oDummyEvent);
assert.equal(thisContext, oController, "Global method without dot should be called with oController as 'this' context when there's no parenthese");
thisContext = "wrong";
// with local variables
vResolvedHandler = EventHandlerResolver.resolveEventHandler("Module.someMethod", oController, {Module: mLocals});
vResolvedHandler[0].call(vResolvedHandler[1], oDummyEvent);
assert.equal(thisContext, oController, "XML-required module should be called with oController as 'this' context when there's no parenthese");
thisContext = "wrong";
});
QUnit.test("'this' context when parentheses are present", function(assert) {
// controller functions
var fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod()", oController)[0];
fnFromController(oDummyEvent);
assert.equal(thisContext, oController, "Controller method should be called with controller as 'this' context");
thisContext = "wrong"; // to make sure non-calls don't accidentally get the correct value
// controller functions without dot
fnFromController = EventHandlerResolver.resolveEventHandler("fnControllerMethod()", oController)[0];
fnFromController(oDummyEvent);
assert.equal(thisContext, oController, "Controller method without dot should be called with controller as 'this' context");
thisContext = "wrong";
// global functions
var fnFromGlobal = EventHandlerResolver.resolveEventHandler("testEventHandlerResolver.subobject.someGlobalMethod()", oController)[0];
fnFromGlobal(oDummyEvent);
assert.equal(thisContext, testEventHandlerResolver.subobject, "Global method should be called with testEventHandlerResolver.subobject as 'this' context");
thisContext = "wrong";
// global functions without dot
fnFromGlobal = EventHandlerResolver.resolveEventHandler("someGlobalMethodOnWindow()", oController)[0];
fnFromGlobal(oDummyEvent);
assert.equal(thisContext, undefined, "Global method without dot should be called with undefined as 'this' context");
thisContext = "wrong";
// global functions with .call()
fnFromGlobal = EventHandlerResolver.resolveEventHandler("testEventHandlerResolver.subobject.someGlobalMethod.call($controller)", oController)[0];
fnFromGlobal(oDummyEvent);
assert.equal(thisContext, oController, "Global method should be called with controller as 'this' context when set using .call($controller)");
thisContext = "wrong";
// with local variables
var fnFromModule = EventHandlerResolver.resolveEventHandler("Module.someMethod()", oController, {Module: mLocals})[0];
fnFromModule(oDummyEvent);
assert.equal(thisContext, mLocals, "XML-required module should be called with the module as 'this' context");
thisContext = "wrong";
// with local variables and with .call()
fnFromModule = EventHandlerResolver.resolveEventHandler("Module.someMethod.call($controller)", oController, {Module: mLocals})[0];
fnFromModule(oDummyEvent);
assert.equal(thisContext, oController, "XML-required module should be called with controller as 'this' context when set using .call($controller)");
thisContext = "wrong";
});
QUnit.module("sap.ui.core.mvc.EventHandlerResolver - parameter resolution", {
beforeEach: function() {
oController = {
fnControllerMethod: function(){},
myFormatter: function() {
return "#" + Array.prototype.slice.call(arguments).join(",") + "#";
}
};
window.testEventHandlerResolver = {
subobject: {
someGlobalMethod: function(){}
}
};
oDummySource = new DummyControl({someControlProperty: "someControlPropertyValue"});
var oModel = new JSONModel({
someModelProperty: "someModelValue",
someDateProperty: '2011-10-29',
someNumberProperty: 49
});
oDummySource.setModel(oModel);
oModel = new JSONModel({
subnode: {
someSecondModelProperty: "someSecondModelValue"
}
});
oDummySource.setModel(oModel, "secondModel");
oDummySource.bindElement({path: "/subnode", model: "secondModel"});
},
afterEach: function() {
oController = null;
window.testEventHandlerResolver = null;
oDummySource.getModel().destroy();
oDummySource.getModel("secondModel").destroy();
oDummySource.destroy();
}
});
QUnit.test("static values", function(assert) {
var spy = sinon.spy(oController, "fnControllerMethod");
var aTests = [
{src: ".fnControllerMethod(\"test\")", expected: "test", message: "Static value with double quotes within double quotes should be correctly given"},
{src: ".fnControllerMethod('test')", expected: "test", message: "Static value with single quotes within double quotes should be correctly given"},
{src: '.fnControllerMethod("test")', expected: "test", message: "Static value with double quotes within single quotes should be correctly given"},
{src: '.fnControllerMethod(\'test\')', expected: "test", message: "Static value with single quotes within single quotes should be correctly given"},
{src: ".fnControllerMethod(true)", expected: true, message: "Boolean static value 'true' should be correctly given"},
{src: ".fnControllerMethod(false)", expected: false, message: "Boolean static value 'false' should be correctly given"},
{src: ".fnControllerMethod(49)", expected: 49, message: "Static number value should be correctly given"},
{src: ".fnControllerMethod(49.95)", expected: 49.95, message: "Static float value should be correctly given"},
{src: ".fnControllerMethod({'x': 'y'})", expected: {'x': 'y'}, message: "Static object value should be correctly given"},
{src: ".fnControllerMethod({x: 'y'})", expected: {'x': 'y'}, message: "Static object value should be correctly given"},
{src: ".fnControllerMethod({x: 'y', z: {a: 1}})", expected: {'x': 'y', z: {a: 1}}, message: "Static object value should be correctly given"},
{src: ".fnControllerMethod(null)", expected: null, message: "Static null value should be correctly given"}
];
var fnFromController;
for (var i = 0; i < aTests.length; i++) {
fnFromController = EventHandlerResolver.resolveEventHandler(aTests[i].src, oController)[0];
fnFromController(oDummyEvent);
assert.deepEqual(spy.args[i], [aTests[i].expected], aTests[i].message);
}
});
QUnit.test("Special value: $controller", function(assert) {
var spy = sinon.spy(oController, "fnControllerMethod");
var fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod($controller)", oController)[0];
fnFromController(oDummyEvent);
assert.deepEqual(spy.args[0], [oController], "Parameter $controller should be given as the controller instance");
});
QUnit.test("Special value: $event", function(assert) {
var spy = sinon.spy(oController, "fnControllerMethod");
var fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod($event)", oController)[0];
fnFromController(oDummyEvent);
assert.deepEqual(spy.args[0], [oDummyEvent], "Parameter $event should be given as the event object");
});
QUnit.test("bound values with controller method", function(assert) {
var spy = sinon.spy(oController, "fnControllerMethod");
var fnFromController;
var mTestSet = {
".fnControllerMethod(${/someModelProperty})": "someModelValue", // plain, absolute binding path
" .fnControllerMethod ( ${/someModelProperty} ) ": "someModelValue", // some whitespace fun
".fnControllerMethod(${secondModel>someSecondModelProperty})": "someSecondModelValue", // relative path using element binding, in named model
".fnControllerMethod(${path:'/someModelProperty'})": "someModelValue", // complex syntax, entry-level
".fnControllerMethod(${path:'/someModelProperty', formatter: '.myFormatter'})": "#someModelValue#", // complex syntax with formatter
".fnControllerMethod(${path:'/someModelProperty', formatter: '.myFormatter', type: 'sap.ui.model.type.String'})": "#someModelValue#", // complex syntax with type
// does not work, deep nesting of parts is not supported in EventHandlerResolver:
//".fnControllerMethod(${parts: ['/someModelProperty'], formatter: '.myFormatter'})": "#someModelValue,someModelValue#", // complex syntax with mixed parts
".fnControllerMethod(${$parameters>/someEventParameter})": "someEventParameterValue", // another model (event parameters)
".fnControllerMethod(${$source>/someControlProperty})": "someControlPropertyValue", // the event source model
".fnControllerMethod('Value is: ' + ${/someModelProperty})": "Value is: someModelValue", // “calculated fields” (template string)
".fnControllerMethod(${/someModelProperty} + ',' + ${/someModelProperty})": "someModelValue,someModelValue", // attention, also a calculated field!
".fnControllerMethod(\"Value is: \" + ${path:'/someModelProperty', formatter: '.myFormatter', type: 'sap.ui.model.type.String'})": "Value is: #someModelValue#", // calculated field with complex binding syntax
// not allowed to use binding expressions inside because the entire string is a binding expression:
//".fnControllerMethod({= ${/someModelProperty} + ${/someModelProperty}})": "someModelValuesomeModelValue", // expression binding
".fnControllerMethod({x: 'y', z: {a: ${/someModelProperty}}})": {x: 'y', z: {a: "someModelValue"}}, // binding in object
'.fnControllerMethod(${path:\'/someModelProperty\',formatter: \'.myFormatter\'})': "#someModelValue#", // single quotes escaped
".fnControllerMethod(${path:\"/someModelProperty\",formatter: \".myFormatter\"})": "#someModelValue#" // double quotes escaped
};
for (var sTestString in mTestSet) {
spy.resetHistory();
fnFromController = EventHandlerResolver.resolveEventHandler(sTestString, oController)[0];
fnFromController(oDummyEvent);
assert.deepEqual(spy.args[0], [mTestSet[sTestString]], "Bound model property value should be correctly calculated for: " + sTestString);
}
});
QUnit.test("bound values with XML-required modules", function(assert) {
var methodSpy = this.spy(mLocals, "someMethod");
var fnFromModule;
var mTestSet = {
"Module.someMethod(${/someModelProperty})": "someModelValue", // plain, absolute binding path
" Module.someMethod ( ${/someModelProperty} ) ": "someModelValue", // some whitespace fun
"Module.someMethod(${secondModel>someSecondModelProperty})": "someSecondModelValue", // relative path using element binding, in named model
"Module.someMethod(${path:'/someModelProperty'})": "someModelValue", // complex syntax, entry-level
"Module.someMethod(${path:'/someModelProperty', formatter: 'Module.someFormatter'})": "#someModelValue#", // complex syntax with formatter
"Module.someMethod(${path:'/someModelProperty', formatter: 'Module.someFormatter', type: 'sap.ui.model.type.String'})": "#someModelValue#", // complex syntax with type
// does not work, deep nesting of parts is not supported in EventHandlerResolver:
//"Module.someMethod(${parts: ['/someModelProperty'], formatter: 'Module.someFormatter'})": "#someModelValue,someModelValue#", // complex syntax with mixed parts
"Module.someMethod(${$parameters>/someEventParameter})": "someEventParameterValue", // another model (event parameters)
"Module.someMethod(${$source>/someControlProperty})": "someControlPropertyValue", // the event source model
"Module.someMethod('Value is: ' + ${/someModelProperty})": "Value is: someModelValue", // “calculated fields” (template string)
"Module.someMethod(${/someModelProperty} + ',' + ${/someModelProperty})": "someModelValue,someModelValue", // attention, also a calculated field!
"Module.someMethod(\"Value is: \" + ${path:'/someModelProperty', formatter: 'Module.someFormatter', type: 'sap.ui.model.type.String'})": "Value is: #someModelValue#", // calculated field with complex binding syntax
// not allowed to use binding expressions inside because the entire string is a binding expression:
//"Module.someMethod({= ${/someModelProperty} + ${/someModelProperty}})": "someModelValuesomeModelValue", // expression binding
"Module.someMethod({x: 'y', z: {a: ${/someModelProperty}}})": {x: 'y', z: {a: "someModelValue"}}, // binding in object
'Module.someMethod(${path:\'/someModelProperty\',formatter: \'Module.someFormatter\'})': "#someModelValue#", // single quotes escaped
"Module.someMethod(${path:\"/someModelProperty\",formatter: \"Module.someFormatter\"})": "#someModelValue#" // double quotes escaped
};
for (var sTestString in mTestSet) {
methodSpy.resetHistory();
fnFromModule = EventHandlerResolver.resolveEventHandler(sTestString, oController, {Module: mLocals})[0];
fnFromModule(oDummyEvent);
assert.deepEqual(methodSpy.args[0], [mTestSet[sTestString]], "Bound model property value should be correctly calculated for: " + sTestString);
}
});
QUnit.test("multiple parameters", function(assert) {
var spy = sinon.spy(oController, "fnControllerMethod");
var fnFromController;
var mTestSet = { // now the values are arrays
".fnControllerMethod('test',${/someModelProperty})": ["test", "someModelValue"], // two parameters
".fnControllerMethod( 'test' , ${/someModelProperty} )": ["test", "someModelValue"] // some whitespace fun
};
for (var sTestString in mTestSet) {
spy.resetHistory();
fnFromController = EventHandlerResolver.resolveEventHandler(sTestString, oController)[0];
fnFromController(oDummyEvent);
assert.deepEqual(spy.args[0], mTestSet[sTestString], "Bound model property value should be correctly calculated for: " + sTestString);
}
});
QUnit.test("types", function(assert) {
var spy = sinon.spy(oController, "fnControllerMethod");
var fnFromController;
var mTestSet = {
".fnControllerMethod(${path:'/someNumberProperty', type: 'sap.ui.model.type.Integer', targetType: 'int'})": 49, // complex syntax with type
".fnControllerMethod(${path:'/someNumberProperty', type: 'sap.ui.model.type.Integer', targetType: 'string'})": "49", // type conversion
".fnControllerMethod(${path:'/someDateProperty', type: 'sap.ui.model.type.Date', formatOptions: {pattern: 'dd.MM.yyyy',source: {pattern: 'yyyy-MM-dd'}}})": "29.10.2011" // type with format options
};
for (var sTestString in mTestSet) {
spy.resetHistory();
fnFromController = EventHandlerResolver.resolveEventHandler(sTestString, oController)[0];
fnFromController(oDummyEvent);
assert.strictEqual(spy.args[0][0], mTestSet[sTestString], "Bound model property value should be correctly calculated for: " + sTestString);
}
});
QUnit.test("error cases (and edge cases)", function(assert) {
var fnFromController;
// unclosed braces
assert.throws(function(){
fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod(${/someModelProperty)", oController)[0];
fnFromController(oDummyEvent);
} , function(err){
return err.message.indexOf("no closing braces found") > -1;
}, "Correct error should be thrown for non-matching braces");
// unresolvable formatter
var spy = sinon.spy(Log, "error");
fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod(${path:'/someModelProperty', formatter: '.myNotExistingFormatter'})", oController)[0];
fnFromController(oDummyEvent);
assert.equal(spy.callCount, 1, "Error should be logged for unresolvable formatter");
assert.ok(spy.args[0][0].indexOf("formatter function .myNotExistingFormatter not found") > -1, "Error should be logged for unresolvable formatter");
// globals within the expression
spy = sinon.spy(Log, "warning");
fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod(Math.max(1))", oController)[0];
fnFromController(oDummyEvent);
assert.equal(spy.callCount, 2, "Warning should be logged for globals inside parameter section");
assert.ok(spy.args[0][0].indexOf("Unsupported global identifier") > -1, "Warning should be logged for globals inside parameter section");
Log.warning.restore();
// wrong expression syntax
assert.throws(function(){
fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod(${/someModelProperty} + {/someModelProperty})", oController)[0];
fnFromController(oDummyEvent);
}, function(err){
return err.message.indexOf("Expected IDENTIFIER") > -1;
}, "Error should be thrown for expression syntax error");
// no expressions within
spy = sinon.spy(Log, "warning");
fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod({= 'abc'})", oController)[0];
assert.equal(spy.callCount, 1, "Warning should be logged for expressions inside parameter section");
assert.ok(spy.args[0][0].indexOf("event handler parameter contains a binding expression") > -1, "Warning should be logged for expressions inside parameter section");
Log.warning.restore();
assert.throws(function(){
fnFromController(oDummyEvent);
}, function(err){
return true; // browser-dependent message
}, "Error should be thrown for expressions inside parameter section");
// starting with a brace
assert.throws(function(){
fnFromController = EventHandlerResolver.resolveEventHandler("(${/someModelProperty})", oController)[0];
fnFromController(oDummyEvent);
}, function(err){
return err.message.indexOf("starts with a bracket") > -1;
}, "Error should be thrown when starting with a bracket");
// wrong binding path
/* TODO: help the user detect such issues without making too much noise when an empty value is perfectly fine
spy = sinon.spy(Log, "warning");
fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod(${/thisdoesnotExist})", oController)[0];
fnFromController(oDummyEvent);
assert.equal(spy.callCount, 1, "Warning should be logged for empty values (which may indicate wrong bindings)");
assert.ok(spy.args[0][0].indexOf("EventHandlerResolver: no value was returned") > -1, "Warning should be logged for empty values (which may indicate wrong bindings)");
*/
// too many closing braces
assert.throws(function(){
fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod(${/someModelProperty}})", oController)[0];
fnFromController(oDummyEvent);
}, function(err){
return err.message.indexOf("but instead saw }") > -1;
}, "Error should be thrown for too many closing braces");
// non-closed single quotes
assert.throws(function(){
fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod('x)", oController)[0];
fnFromController(oDummyEvent);
}, function(err){
return err.message.indexOf("Bad") > -1;
}, "Error should be thrown for non-closed single quotes");
// non-closed double quotes
assert.throws(function(){
fnFromController = EventHandlerResolver.resolveEventHandler(".fnControllerMethod(\"x)", oController)[0];
fnFromController(oDummyEvent);
}, function(err){
return err.message.indexOf("Bad") > -1;
}, "Error should be thrown for non-closed double quotes");
});
QUnit.module("sap.ui.core.mvc.EventHandlerResolver - parse()");
QUnit.test("one event handler", function (assert) {
assert.deepEqual(EventHandlerResolver.parse(".fnControllerMethod"), [".fnControllerMethod"]);
});
QUnit.test("several event handlers", function (assert) {
assert.deepEqual(
EventHandlerResolver.parse(".fnControllerMethod; globalFunction"),
[".fnControllerMethod", "globalFunction"]
);
});
QUnit.test("several event handlers with trailing semicolon", function (assert) {
assert.deepEqual(
EventHandlerResolver.parse(".fnControllerMethod; globalFunction;"),
[".fnControllerMethod", "globalFunction"]
);
});
QUnit.test("several event handlers with parameters", function (assert) {
assert.deepEqual(
EventHandlerResolver.parse(".fnControllerMethod; .fnControllerMethod(${ path:'/someModelProperty', formatter: '.myFormatter', type: 'sap.ui.model.type.String'} ); globalFunction"),
[".fnControllerMethod", ".fnControllerMethod(${ path:'/someModelProperty', formatter: '.myFormatter', type: 'sap.ui.model.type.String'} )", "globalFunction"]
);
});
QUnit.test("several event handlers with parameters and string literals", function (assert) {
assert.deepEqual(
EventHandlerResolver.parse(".fnControllerMethod('bad);luck'); .fnControllerMethod(\"\\\");\"); globalFunction"),
[".fnControllerMethod('bad);luck')", ".fnControllerMethod(\"\\\");\")", "globalFunction"]
);
});
});
| SAP/openui5 | src/sap.ui.core/test/sap/ui/core/qunit/mvc/EventHandlerResolver.qunit.js | JavaScript | apache-2.0 | 27,088 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.22/esri/copyright.txt for details.
//>>built
define("esri/dijit/metadata/nls/pt-pt/i18nBase",{general:{cancel:"Cancelar",close:"Fechar",none:"Nenhum",ok:"OK",other:"Outro",stamp:"Data",now:"Agora",choose:"Selecione Um:"},editor:{noMetadata:"N\u00e3o existem metadados para este item.",xmlViewOnly:"O tipo de metadados associados com este item n\u00e3o \u00e9 suportado pelo editor. Metadados devem estar em formato ArcGIS.",editorDialog:{caption:"Metadados",captionPattern:"Metadados para {title}"},primaryToolbar:{view:"Visualiza\u00e7\u00e3o",viewXml:"Visualizar XML",
edit:"Editar",initializing:"Carregando...",startingEditor:"A iniciar editor...",loadingDocument:"A carregar documento...",updatingDocument:"A atualizar documento...",generatingView:"A gerar visualiza\u00e7\u00e3o...",errors:{errorGeneratingView:"Ocorreu um erro ao gerar a visualiza\u00e7\u00e3o.",errorLoadingDocument:"Ocorreu um erro ao carregar o ficheiro."}},changesNotSaved:{prompt:"O seu documento possui altera\u00e7\u00f5es que n\u00e3o foram guardadas.",dialogTitle:"Fechar Editor de Metadados",
closeButton:"Fechar"},download:{caption:"Descarregar",dialogTitle:"Descarregar",prompt:"Clique aqui para descarregar o seu ficheiro."},load:{caption:"Abrir",dialogTitle:"Abrir",typeTab:"Novo Documento",fileTab:"Abrir Ficheiro",templateTab:"Um Modelo",itemTab:"O Seu item",filePrompt:"Seleccionar um ficheiro local Metadados XML ArcGIS. Metadados devem estar em formato ArcGIS.",templatePrompt:"Criar Metadados",pullItem:"Preencher metadados com os detalhes do item.",importWarning:"O ficheiro seleccionado n\u00e3o aparece em formato ArcGIS. Metadados carregados devem ter formato ArcGIS.",
loading:"Carregando...",noMetadata:"Metadados podem ser criados para este item escolhendo uma das seguintes op\u00e7\u00f5es.",unrecognizedMetadata:"Este tipo de metadados associado com este item n\u00e3o \u00e9 suportado pelo editor. Metadados suportados podem ser criados escolhendo uma das seguintes op\u00e7\u00f5es.",errorLoading:"Ocorreu um erro durante o carregamento.",warnings:{badFile:"O ficheiro selecionado n\u00e3o p\u00f4de ser carregado.",notAnXml:"O ficheiro selecionado n\u00e3o \u00e9 um ficheiro XML.",
notSupported:"Este tipo de ficheiro n\u00e3o \u00e9 suportado."}},save:{caption:"Guardar",dialogTitle:"Guardar Metadados",working:"A Guardar Metadados...",errorSaving:"Ocorreu um erro, os seus metadados n\u00e3o foram guardados.",saveDialog:{pushCaption:"Aplicar altera\u00e7\u00f5es ao seu item."}},saveAndClose:{caption:"Guardar e Fechar"},saveDraft:{caption:"Guardar C\u00f3pia Local",dialogTitle:"Guardar C\u00f3pia Local"},validate:{caption:"Validar",dialogTitle:"Valida\u00e7\u00e3o",docIsValid:"O seu documento \u00e9 v\u00e1lido."},
del:{caption:"Eliminar",dialogTitle:"Eliminar Metadados",prompt:"Tem a certeza de que pretende eliminar estes metadados?",working:"A Eliminar Metadados...",errorDeleting:"Ocorreu um erro, os seus metadados n\u00e3o foram eliminados."},transform:{caption:"Transformar",dialogTitle:"Transformar Para",prompt:"",working:"A Transformar...",errorTransforming:"Ocorreu um erro ao transformar o seu documento."},errorDialog:{dialogTitle:"Ocorreu um erro"}},arcgis:{portal:{metadataButton:{caption:"Metadados"}}},
calendar:{button:"Calend\u00e1rio...",title:"Calend\u00e1rio"},geoExtent:{button:"Definir Extens\u00e3o Geogr\u00e1fica...",title:"Extens\u00e3o Geogr\u00e1fica",navigate:"Navegar",draw:"Desenhar um Rect\u00e2ngulo",drawHint:"Pressione para come\u00e7ar e solte para finalizar."},hints:{date:"(yyyy ou yyyy-mm ou yyyy-mm-dd)",dateTime:"(yyyy-mm-ddThh:mm:ss.sss[+-]hh:mm)",dateOrDateTime:"(yyyy ou yyyy-mm ou yyyy-mm-dd ou yyyy-mm-ddThh:mm:ss.sss[+-]hh:mm)",delimitedTextArea:"(utilize v\u00edrgula ou uma nova linha para separar)",
fgdcDate:"(yyyy ou yyyy-mm ou yyyy-mm-dd)",fgdcTime:"(yyyy-mm-ddThh:mm:ss.sss[+-]hh:mm)",integer:"(introduza um valor inteiro)",latitude:"(graus decimais)",longitude:"(graus decimais)",number:"(introduza um n\u00famero)",numberGreaterThanZero:"(introduza um n\u00famero \x3e 0)"},isoTopicCategoryCode:{caption:"Categoria de T\u00f3picos",boundaries:"Limites Administrativos e Pol\u00edticos",farming:"Agricultura e Pecu\u00e1ria",climatologyMeteorologyAtmosphere:"Atmosfera e Clima",biota:"Biologia e Ecologia",
economy:"Neg\u00f3cios e Economia",planningCadastre:"Cadastro",society:"Cultura, Sociedade e Demografia",elevation:"Eleva\u00e7\u00e3o e Produtos Derivados",environment:"Ambiente e Conserva\u00e7\u00e3o",structure:"Instala\u00e7\u00f5es e Estruturas",geoscientificInformation:"Geologia e Geof\u00edsica",health:"Sa\u00fade e Doen\u00e7as",imageryBaseMapsEarthCover:"Imagem e Mapas Base",inlandWaters:"Recursos H\u00eddricos do Interior",location:"Localiza\u00e7\u00f5es e Redes Geod\u00e9sicas",intelligenceMilitary:"Militar",
oceans:"Oceanos e Estu\u00e1rios",transportation:"Redes de Transporte",utilitiesCommunication:"Utilities e Comunica\u00e7\u00f5es"},multiplicity:{moveElementDown:"Mover sec\u00e7\u00e3o para baixo",moveElementUp:"Mover sec\u00e7\u00e3o para cima",removeElement:"Remover Sec\u00e7\u00e3o",repeatElement:"Repetir Sec\u00e7\u00e3o"},optionalNode:{switchTip:"Incluir ou excluir esta sec\u00e7\u00e3o."},serviceTypes:{featureService:"Servi\u00e7o de Elementos",mapService:"Servi\u00e7o de Mapas",imageService:"Servi\u00e7o de Imagem",
wms:"WMS",wfs:"WFS",wcs:"WCS"},validation:{pattern:"{label} - {message}",patternWithHint:"{label} - {message} {hint}",ok:"OK",empty:"\u00c9 necess\u00e1rio um valor.",date:"O valor deve ser uma data.",integer:"O valor deve ser inteiro.",number:"O valor deve ser um n\u00famero.",other:"O valor n\u00e3o \u00e9 v\u00e1lido."},validationPane:{clearMessages:"Limpar Mensagens",prompt:"(clicar em cada mensagem em baixo e forne\u00e7a a informa\u00e7\u00e3o requerida no campo especificado)"}}); | wanglongbiao/webapp-tools | Highlander/ship-gis/src/main/webapp/js/arcgis_js_api/library/3.22/esri/dijit/metadata/nls/pt-pt/i18nBase.js | JavaScript | apache-2.0 | 5,940 |
'use strict';
/**
* @ngdoc function
* @name sbAdminApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the sbAdminApp
*/
angular.module('sbAdminApp')
.controller('ChartCtrl', ['$scope', '$timeout', '$http', 'employeeService', 'socket', '$modalStack', 'settingsService', '$state', function ($scope, $timeout, $http, employeeService, socket, $modalStack, settingsService, $state) {
var currentUser = Parse.User.current();
if(!currentUser){
$state.go('login');
}
var settingId = currentUser.get('settingId');
var fingerPrintIdPool = [];
var idToBeDeleted = '';
$scope.totalUsers = null;
// $scope.uploadFile = {};
$scope.isScanFinger = true;
$scope.defaultProfPic = "img/logo/logo_placeholder.png";
$scope.scanStatus = 'Scan';
$scope.sortLists=[{id:0, name:"Id"},{id:1,name:"firstName"},{id:2,name:"lastName"},{id:3,name:"gender"},{id:4,name:"age"}]
$scope.changedValue=function(item){
if(item.name === 'Id'){
getAll('fingerPrintId');
}
getAll(item.name);
}
var currentEmployee = '';
function getAll(sort){
employeeService.getEmployees(sort)
.then(function(results) {
// Handle the result
console.log(results);
$scope.rowCollection = results;
$scope.totalUsers = results.length;
return results;
}, function(err) {
// Error occurred
console.log(err);
}, function(percentComplete) {
console.log(percentComplete);
});
};
getAll();
getSettings();
function getSettings(){
settingsService.getSetting(settingId)
.then(function(results) {
// Handle the result
console.log(results);
$scope.settings = results[0];
console.log($scope.settings);
$scope.userTable = $scope.settings.get('userTable');
$scope.userInfo = {}
fingerPrintIdPool = $scope.settings.get('fingerPrintIdPool');
console.log(fingerPrintIdPool);
}, function(err) {
// Error occurred
console.log(err);
}, function(percentComplete) {
console.log(percentComplete);
});
};
$scope.user = {
'firstName' : '',
'lastName' : '',
'gender' : 'Male',
'age' : ''
}
$scope.modal = {
title : '',
mode : '',
isUpdate : false
}
$scope.deleteSelected = function(){
var delay = 0;
$scope.isDeleteProgress = true;
(function myLoop (i) {
if($scope.rowCollection[i-1].get('isSelected')){
setTimeout(function () {
currentEmployee = $scope.rowCollection[i-1];
$scope.deleteUser();
if (--i){
myLoop(i);
}else{
$scope.isDeleteProgress = false;
$scope.isDeleteCompleted = true;
}
}, 5000)
}else{
if (--i) myLoop(i);
}
})($scope.rowCollection.length);
}
$scope.selectedUser = function(user, status, isAll){
console.log(user);
console.log(status);
if(!isAll){
user.set('isSelected', status);
}else{
angular.forEach($scope.rowCollection, function(value, key) {
value.set('isSelected', status);
});
}
};
$scope.openModal = function () {
$scope.modal.title = 'Add User';
$scope.modal.mode = 'Create';
$scope.modal.isUpdate = false;
$scope.user.employeeId = '';
$scope.user.firstName = '';
$scope.user.lastName = '';
$scope.user.gender = 'Male';
$scope.user.age = '';
$scope.user.position = '';
$scope.previewImage = '';
$scope.scanStatus = 'Scan';
$scope.buttonScanStatus = 'btn-info';
$scope.deleteConfirmation = false;
};
$scope.editModal = function (id) {
console.log(id);
$scope.modal.title = 'Edit User';
$scope.modal.mode = 'Update';
$scope.modal.isUpdate = true;
currentEmployee = '';
$scope.previewImage = '';
$scope.scanStatus = 'Change Fingerprint';
$scope.buttonScanStatus = 'btn-info';
$scope.deleteConfirmation = false;
$scope.isCurrentFingerDeleted = false;
employeeService.getEmployee(id)
.then(function(result) {
// Handle the result
console.log(result);
$scope.user.employeeId = result[0].get('employeeId');
$scope.user.firstName = result[0].get('firstName');
$scope.user.lastName = result[0].get('lastName');
$scope.user.gender = result[0].get('gender');
$scope.user.age = result[0].get('age');
$scope.user.position = result[0].get('position');
$scope.user.fingerPrintId = result[0].get('fingerPrintId');
$scope.previewImage = result[0].get('avatarUrl');
currentEmployee = result[0];
}, function(err) {
// Error occurred
console.log(err);
}, function(percentComplete) {
console.log(percentComplete);
});
};
$scope.updateUser = function(){
console.log($scope.uploadFile);
currentEmployee.set("employeeId", $scope.user.employeeId);
currentEmployee.set("firstName", $scope.user.firstName);
currentEmployee.set("lastName", $scope.user.lastName);
currentEmployee.set("gender", $scope.user.gender);
currentEmployee.set("age", $scope.user.age);
currentEmployee.set("position", $scope.user.position);
if($scope.isCurrentFingerDeleted){
var fingerPrintId = fingerPrintIdPool[0];
removeA(fingerPrintIdPool, fingerPrintId);
currentEmployee.set("fingerPrintId", fingerPrintId.toString());
}
if($scope.uploadFile){
$http.post("http://172.24.1.1:1337/parse/files/image.jpg", $scope.uploadFile, {
withCredentials: false,
headers: {
'X-Parse-Application-Id': 'myAppId',
'X-Parse-REST-API-Key': 'myRestAPIKey',
'Content-Type': 'image/jpeg'
},
transformRequest: angular.identity
}).then(function(data) {
currentEmployee.set("avatarUrl", data.data.url);
currentEmployee.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
getAll();
var Settings = Parse.Object.extend("Settings");
var settings = new Settings();
settings.id = settingId;
settings.set("fingerPrintIdPool", fingerPrintIdPool);
settings.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
$scope.userTableResult = [];
console.log(result);
getSettings();
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
},function(err){
alert('Picture should not exceed 2mb, Please Try again.');
});
} else{
currentEmployee.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
getAll();
var Settings = Parse.Object.extend("Settings");
var settings = new Settings();
settings.id = settingId;
settings.set("fingerPrintIdPool", fingerPrintIdPool);
settings.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
$scope.userTableResult = [];
console.log(result);
getSettings();
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
}
}
$scope.manualDeleteUserFromSensor = function(){
console.log($scope.detectedFingerPrintId);
employeeService.getEmployeeByFingerPrintId($scope.detectedFingerPrintId)
.then(function(result) {
// Handle the result
var detectedEmployee = result[0];
var Settings = Parse.Object.extend("Settings");
var settings = new Settings();
settings.id = settingId;
fingerPrintIdPool.push(parseInt($scope.detectedFingerPrintId));
settings.set("fingerPrintIdPool", fingerPrintIdPool);
console.log(fingerPrintIdPool);
settings.save(null, {
success: function(result) {
getSettings();
idToBeDeleted = parseInt($scope.detectedFingerPrintId);
socket.emit('toPublicServer', 'm:delete');
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
if(result.length){
var detectedEmployee = result[0];
detectedEmployee.set("fingerPrintId", "");
detectedEmployee.save(null, {
success: function(result) {
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
}
}, function(err) {
// Error occurred
console.log(err);
}, function(percentComplete) {
console.log(percentComplete);
});
}
$scope.deleteUser = function(){
console.log(parseInt(currentEmployee.get('fingerPrintId')));
idToBeDeleted = parseInt(currentEmployee.get('fingerPrintId'));
currentEmployee.destroy({
success: function(myObject) {
$scope.modal.title = 'This User no longer exists.';
$scope.modal.mode = 'Create';
$scope.modal.isUpdate = false;
$scope.user.employeeId = '';
$scope.user.firstName = '';
$scope.user.lastName = '';
$scope.user.gender = 'Male';
$scope.user.age = '';
$scope.user.position = '';
$scope.previewImage = '';
$scope.scanStatus = 'Scan';
$scope.buttonScanStatus = 'btn-info';
$modalStack.dismissAll();
getAll();
var Settings = Parse.Object.extend("Settings");
var settings = new Settings();
settings.id = settingId;
fingerPrintIdPool.push(parseInt(currentEmployee.get('fingerPrintId')));
settings.set("fingerPrintIdPool", fingerPrintIdPool);
settings.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
$scope.userTableResult = [];
console.log(result);
getSettings();
socket.emit('toPublicServer', 'm:delete');
var DailyLogObject = Parse.Object.extend("DailyLog");
var query = new Parse.Query(DailyLogObject);
query.equalTo("employeeId", currentEmployee.id);
query.find().then(function (users) {
users.forEach(function(user) {
user.destroy({
success: function() {
// SUCCESS CODE HERE, IF YOU WANT
console.log('daily log deleted');
},
error: function() {
// ERROR CODE HERE, IF YOU WANT
console.log('daily log error delete');
}
});
});
}, function (error) {
response.error(error);
});
var PeriodLogObject = Parse.Object.extend("PeriodLog");
var queryPeriod = new Parse.Query(PeriodLogObject);
queryPeriod.equalTo("employeeId", currentEmployee.id);
queryPeriod.find().then(function (users) {
users.forEach(function(user) {
user.destroy({
success: function() {
// SUCCESS CODE HERE, IF YOU WANT
console.log('period log deleted');
},
error: function() {
// ERROR CODE HERE, IF YOU WANT
console.log('period log error delete');
}
});
});
}, function (error) {
response.error(error);
});
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
},
error: function(myObject, error) {
// The delete failed.
// error is a Parse.Error with an error code and message.
}
});
}
$scope.confirmDelete = function(){
$scope.deleteConfirmation = true;
}
$scope.cancelDelete = function(){
$scope.deleteConfirmation = false;
}
$scope.convertToMB = function(size){
var value = size/1000000;
if(value){
return value.toFixed(2);
}else{
return 0;
}
}
$scope.checkFileSize = function(size){
if(size > 2000000){
return 'log-bold';
} else{
return '';
}
}
$scope.addUser = function(){
console.log($scope.uploadFile);
if($scope.uploadFile){
$http.post("http://172.24.1.1:1337/parse/files/image.jpg", $scope.uploadFile, {
withCredentials: false,
headers: {
'X-Parse-Application-Id': 'myAppId',
'X-Parse-REST-API-Key': 'myRestAPIKey',
'Content-Type': 'image/jpeg'
},
transformRequest: angular.identity
}).then(function(data) {
console.log(data.data.url);
var Employee = Parse.Object.extend("Employee");
var employee = new Employee();
var fingerPrintId = fingerPrintIdPool[0];
removeA(fingerPrintIdPool, fingerPrintId);
employee.set("employeeId", $scope.user.employeeId);
employee.set("firstName", $scope.user.firstName);
employee.set("lastName", $scope.user.lastName);
employee.set("gender", $scope.user.gender);
employee.set("age", $scope.user.age);
employee.set("position", $scope.user.position);
employee.set("avatarUrl", data.data.url);
employee.set("fingerPrintId", fingerPrintId.toString());
employee.set("currentPeriodLog", {"id":null,"date":null,"sequence":0,"totalTime":0});
employee.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
getAll();
var Settings = Parse.Object.extend("Settings");
var settings = new Settings();
settings.id = settingId;
settings.set("fingerPrintIdPool", fingerPrintIdPool);
settings.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
$scope.userTableResult = [];
console.log(result);
getSettings();
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
},function(err){
alert('Picture should not exceed 2mb, Please Try again.');
});
}
else {
var Employee = Parse.Object.extend("Employee");
var employee = new Employee();
var fingerPrintId = $scope.totalUsers + 1
var fingerPrintId = fingerPrintIdPool[0];
removeA(fingerPrintIdPool, fingerPrintId);
employee.set("employeeId", $scope.user.employeeId);
employee.set("firstName", $scope.user.firstName);
employee.set("lastName", $scope.user.lastName);
employee.set("gender", $scope.user.gender);
employee.set("age", $scope.user.age);
employee.set("position", $scope.user.position);
employee.set("avatarUrl", $scope.defaultProfPic);
employee.set("fingerPrintId", fingerPrintId.toString());
employee.set("currentPeriodLog", {"id":null,"date":null,"sequence":0,"totalTime":0});
employee.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
getAll();
var Settings = Parse.Object.extend("Settings");
var settings = new Settings();
settings.id = settingId;
settings.set("fingerPrintIdPool", fingerPrintIdPool);
settings.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
$scope.userTableResult = [];
console.log(result);
getSettings();
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
}
};
$scope.scanFinger = function(){
console.log('Scan Finger');
socket.emit('toPublicServer', 'm:enroll');
$scope.isScanFinger = false;
}
$scope.updateFingerPrintInit = function(){
console.log('Delete Old FingerPrint');
$scope.isCurrentFingerDeleted = false;
idToBeDeleted = $scope.user.fingerPrintId;
console.log(idToBeDeleted);
if(idToBeDeleted){
console.log('not empty');
var Settings = Parse.Object.extend("Settings");
var settings = new Settings();
settings.id = settingId;
fingerPrintIdPool.push(parseInt(idToBeDeleted));
settings.set("fingerPrintIdPool", fingerPrintIdPool);
settings.save(null, {
success: function(result) {
// Execute any logic that should take place after the object is saved.
$scope.userTableResult = [];
getSettings();
socket.emit('toPublicServer', 'm:delete');
},
error: function(gameScore, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and message.
}
});
} else {
$scope.isCurrentFingerDeleted = true;
$scope.scanStatus = 'Click to Continue';
$scope.buttonScanStatus = 'btn-success';
}
}
$scope.updateFingerPrintGo = function(){
console.log('Update Scan Finger');
socket.emit('toPublicServer', 'm:enroll');
}
socket.on('fromPublicServer', function(data){
console.log(data);
var tmp = fingerPrintIdPool[0];
if(stringContains(data, 'm:enroll')){
console.log(tmp);
socket.emit('toPublicServer', tmp.toString());
}
if(stringContains(data, 'm:delete')){
console.log(tmp);
socket.emit('toPublicServer', idToBeDeleted.toString());
}
if(stringContains(data, 'Deleted!')){
$scope.isCurrentFingerDeleted = true;
socket.emit('toPublicServer', idToBeDeleted.toString());
$scope.scanStatus = 'Click to Continue';
$scope.buttonScanStatus = 'btn-success';
}
if(stringContains(data, 'command:place.finger.1')){
$scope.scanStatus = 'Please Place Finger';
$scope.buttonScanStatus = 'btn-warning';
}
if(stringContains(data, 'command:remove.finger')){
$scope.scanStatus = 'Please Remove Finger';
}
if(stringContains(data, 'command:place.finger.2')){
$scope.scanStatus = 'Place Same Finger Again';
}
if(stringContains(data, 'Ok.status:prints.matched.success')){
$scope.scanStatus = 'Prints Matched';
}
if(stringContains(data, 'Ok.status:print')){
console.log('print stored');
$scope.buttonScanStatus = 'btn-success';
$scope.scanStatus = 'Print Successfully Stored!';
}
if(stringContains(data, 'status.prints.matched.failed')){
$scope.buttonScanStatus = 'btn-danger';
$scope.scanStatus = 'Prints Not Matched.';
alert('Prints Not Matched. Please Try Again.');
socket.emit('toPublicServer', tmp.toString());
}
if(stringContains(data, 'found:')){
console.log(tmp);
var tmpData = data;
tmpData = tmpData.split(":");
$scope.isDetectedFingerPrint = true;
$scope.detectedFingerPrintId = tmpData[1].toString();
}
});
$scope.closeModal = function(){
console.log('Close Modal');
socket.emit('toPublicServer', 'x');
}
$scope.$on("$destroy", function(){
socket.removeAllListeners("fromPublicServer");
});
function stringContains(data, compare){
return data.indexOf(compare) > -1;
}
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
}]);
| vynci/deped-tas | app/scripts/controllers/chartContoller.js | JavaScript | apache-2.0 | 22,657 |
/**
* Kendo UI v2016.1.412 (http://www.telerik.com/kendo-ui)
* Copyright 2016 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){
if (typeof define === 'function' && define.amd) {
define(["kendo.core"], f);
} else {
f();
}
}(function(){
(function( window, undefined ) {
kendo.cultures["ta-LK"] = {
name: "ta-LK",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
symbol: "%"
},
currency: {
name: "Sri Lanka Rupee",
abbr: "LKR",
pattern: ["$ -n","$ n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,2],
symbol: "Rs"
}
},
calendars: {
standard: {
days: {
names: ["ஞாயிற்றுக்கிழமை","திங்கட்கிழமை","செவ்வாய்க்கிழமை","புதன்கிழமை","வியாழக்கிழமை","வெள்ளிக்கிழமை","சனிக்கிழமை"],
namesAbbr: ["ஞாயிறு","திங்கள்","செவ்வாய்","புதன்","வியாழன்","வெள்ளி","சனி"],
namesShort: ["ஞா","தி","செ","பு","வி","வெ","ச"]
},
months: {
names: ["ஜனவரி","பெப்ரவரி","மார்ச்","ஏப்ரல்","மே","ஜூன்","ஜூலை","ஓகஸ்ட்","செப்ரம்பர்","ஒக்ரோபர்","நவம்பர்","டிசம்பர்"],
namesAbbr: ["ஜன.","பெப்.","மார்.","ஏப்","மே","ஜூன்","ஜூலை","ஓக.","செப்.","ஒக்.","நவ.","டிச."]
},
AM: ["காலை","காலை","காலை"],
PM: ["மாலை","மாலை","மாலை"],
patterns: {
d: "dd-MM-yyyy",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy HH:mm:ss",
g: "dd-MM-yyyy HH:mm",
G: "dd-MM-yyyy HH:mm:ss",
m: "d MMMM",
M: "d MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "-",
":": ":",
firstDay: 1
}
}
}
})(this);
})); | ytodorov/AntServices | AdvancedNetToolsSolution/AntWeb/Scripts/kendo/cultures/kendo.culture.ta-LK.js | JavaScript | apache-2.0 | 7,162 |
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/base/util/deepClone"
], function (Controller, deepClone) {
"use strict";
var oCardManifest = {
"_version": "1.8.0",
"sap.app": {
"id": "dataMode1",
"type": "card",
"i18n": "i18n/i18n.properties"
},
"sap.ui5": {
"services": {
"RandomRevenue": {
"factoryName": "cardsdemo.service.RandomRevenueFactory"
}
}
},
"sap.card": {
"type": "Analytical",
"header": {
"type": "Numeric",
"data": {
"request": {
"url": "../kpi.json"
},
"path": "/kpiInfos/kpi"
},
"title": "{{contactDetails}}",
"subTitle": "Revenue",
"unitOfMeasurement": "EUR",
"mainIndicator": {
"number": "{number}",
"unit": "{unit}",
"trend": "{trend}",
"state": "{state}"
},
"details": "{details}",
"sideIndicators": [
{
"title": "Target",
"number": "{target/number}",
"unit": "{target/unit}"
},
{
"title": "Deviation",
"number": "{deviation/number}",
"unit": "%"
}
]
},
"content": {
"data": {
"service": {
"name": "RandomRevenue"
},
"path": "/"
},
"chartType": "Line",
"legend": {
"visible": true,
"position": "Right",
"alignment": "Center"
},
"plotArea": {
"dataLabel": {
"visible": true
}
},
"title": {
"text": "Line chart",
"visible": true,
"alignment": "Bottom"
},
"measureAxis": "valueAxis",
"dimensionAxis": "categoryAxis",
"dimensions": [
{
"label": "Weeks",
"value": "{Week}"
}
],
"measures": [
{
"label": "Revenue",
"value": "{Revenue}"
},
{
"label": "Cost",
"value": "{Cost}"
}
]
}
}
};
return Controller.extend("sap.f.cardsdemo.controller.DataMode", {
onBeforeRendering: function () {
this.getView().byId("card").setManifest(oCardManifest);
this.getView().byId("card").setBaseUrl("./cardsdemo/cardcontent/objectcontent/");
},
onSelectionChange: function (oEvent) {
var sDataMode = oEvent.getParameter("item").getText();
this.getView().byId("card").setDataMode(sDataMode);
},
onTryToRefresh: function () {
var oCard = this.getView().byId("card");
if (oCard) {
this.getView().byId("card").refresh();
}
},
onSubmit: function (oEvent) {
var iInterval = oEvent.getParameter("value"),
oClone = deepClone(oCardManifest);
oClone["sap.card"].content.data.updateInterval = iInterval;
this.getView().byId("card").setManifest(oClone);
}
});
}); | SAP/openui5 | src/sap.f/test/sap/f/cardsdemo/controller/DataMode.controller.js | JavaScript | apache-2.0 | 2,613 |
/*
* Copyright 2015-present Boundless Spatial Inc., http://boundlessgeo.com
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations
* under the License.
*/
/**
* A collection of useful constants.
* @ignore
*/
export const LAYER_VERSION_KEY = 'bnd:layer-version';
export const SOURCE_VERSION_KEY = 'bnd:source-version';
export const TITLE_KEY = 'bnd:title';
export const TIME_KEY = 'bnd:time';
export const TIME_START_KEY = 'bnd:start-time';
export const TIME_END_KEY = 'bnd:end-time';
export const DATA_VERSION_KEY = 'bnd:data-version';
export const GROUPS_KEY = 'mapbox:groups';
export const GROUP_KEY = 'mapbox:group';
export const LAYERLIST_HIDE_KEY = 'bnd:hide-layerlist';
export const QUERYABLE_KEY = 'bnd:queryable';
export const QUERY_ENDPOINT_KEY = 'bnd:query-endpoint';
export const QUERY_TYPE_KEY = 'bnd:query-type';
export const QUERY_PARAMS_KEY = 'bnd:query-params';
export const GEOMETRY_NAME_KEY = 'bnd:geometry-name';
export const MIN_ZOOM_KEY = 'bnd:minzoom';
export const MAX_ZOOM_KEY = 'bnd:maxzoom';
export const QUERY_TYPE_WFS = 'WFS';
export const DEFAULT_ZOOM = {
MIN: 0,
MAX: 22,
};
export const INTERACTIONS = {
modify: 'Modify',
select: 'Select',
point: 'Point',
line: 'LineString',
polygon: 'Polygon',
box: 'Box',
measure_point: 'measure:Point',
measure_line: 'measure:LineString',
measure_polygon: 'measure:Polygon',
};
// useful for deciding what is or is not a drawing interaction
INTERACTIONS.drawing = [
INTERACTIONS.point,
INTERACTIONS.line,
INTERACTIONS.polygon,
INTERACTIONS.box
];
// determine which is a measuring interaction
INTERACTIONS.measuring = [
INTERACTIONS.measure_point,
INTERACTIONS.measure_line,
INTERACTIONS.measure_polygon,
];
/** Export all the const's in a convenient Object.
*/
export default {
LAYER_VERSION_KEY,
SOURCE_VERSION_KEY,
TITLE_KEY,
TIME_KEY,
GROUP_KEY,
GROUPS_KEY,
TIME_START_KEY,
TIME_END_KEY,
DATA_VERSION_KEY,
INTERACTIONS,
DEFAULT_ZOOM,
};
| jjmulenex/sdk | src/constants.js | JavaScript | apache-2.0 | 2,452 |
/*
* ../../../..//extensions/a11y/mathmaps/es/symbols/latin-upper-double-accent.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* 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.
*/
[
{ locale: "es" },
{ key: "1E08", mappings: { default: { default: "mayúscula C con cedilla y agudo" } }, category: "Lu" },
{ key: "1E14", mappings: { default: { default: "mayúscula E con macrón y grave" } }, category: "Lu" },
{ key: "1E16", mappings: { default: { default: "mayúscula E con macrón y agudo" } }, category: "Lu" },
{ key: "1E1C", mappings: { default: { default: "mayúscula E with cedilla and breve" } }, category: "Lu" },
{ key: "1E2E", mappings: { default: { default: "mayúscula I con diéresis y agudo" } }, category: "Lu" },
{ key: "1E38", mappings: { default: { default: "mayúscula L con punto debajo y macrón" } }, category: "Lu" },
{ key: "1E4C", mappings: { default: { default: "mayúscula O con tilde y acute" } }, category: "Lu" },
{ key: "1E4E", mappings: { default: { default: "mayúscula O con tilde y diéresis" } }, category: "Lu" },
{ key: "1E50", mappings: { default: { default: "mayúscula O con macrón y grave" } }, category: "Lu" },
{ key: "1E52", mappings: { default: { default: "mayúscula O con macrón y agudo" } }, category: "Lu" },
{ key: "1E5C", mappings: { default: { default: "mayúscula R con punto debajo y macrón" } }, category: "Lu" },
{ key: "1E64", mappings: { default: { default: "mayúscula S con agudo y punto arriba" } }, category: "Lu" },
{ key: "1E66", mappings: { default: { default: "mayúscula S con carón y punto arriba" } }, category: "Lu" },
{ key: "1E68", mappings: { default: { default: "mayúscula S con punto debajo y punto arriba" } }, category: "Lu" },
{ key: "1E78", mappings: { default: { default: "mayúscula U con tilde y agudo" } }, category: "Lu" },
{ key: "1E7A", mappings: { default: { default: "mayúscula U con macrón y diéresis" } }, category: "Lu" },
{ key: "1EA4", mappings: { default: { default: "mayúscula A con acento circunflejo y agudo" } }, category: "Lu" },
{ key: "1EA6", mappings: { default: { default: "mayúscula A con acento circunflejo y grave" } }, category: "Lu" },
{
key: "1EA8",
mappings: { default: { default: "mayúscula A con acento circunflejo y gancho arriba" } },
category: "Lu"
},
{ key: "1EAA", mappings: { default: { default: "mayúscula A con acento circunflejo y tilde" } }, category: "Lu" },
{
key: "1EAC",
mappings: { default: { default: "mayúscula A con acento circunflejo y punto debajo" } },
category: "Lu"
},
{ key: "1EAE", mappings: { default: { default: "mayúscula A con breve y agudo" } }, category: "Lu" },
{ key: "1EB0", mappings: { default: { default: "mayúscula A con breve y grave" } }, category: "Lu" },
{ key: "1EB2", mappings: { default: { default: "mayúscula A con breve y gancho arriba" } }, category: "Lu" },
{ key: "1EB4", mappings: { default: { default: "mayúscula A con breve y tilde" } }, category: "Lu" },
{ key: "1EB6", mappings: { default: { default: "mayúscula A con breve y punto debajo" } }, category: "Lu" },
{ key: "1EBE", mappings: { default: { default: "mayúscula E con acento circunflejo y agudo" } }, category: "Lu" },
{ key: "1EC0", mappings: { default: { default: "mayúscula E con acento circunflejo y grave" } }, category: "Lu" },
{
key: "1EC2",
mappings: { default: { default: "mayúscula E con acento circunflejo y gancho arriba" } },
category: "Lu"
},
{ key: "1EC4", mappings: { default: { default: "mayúscula E con acento circunflejo y tilde" } }, category: "Lu" },
{
key: "1EC6",
mappings: { default: { default: "mayúscula E con acento circunflejo y punto debajo" } },
category: "Lu"
},
{ key: "1ED0", mappings: { default: { default: "mayúscula O con acento circunflejo y agudo" } }, category: "Lu" },
{ key: "1ED2", mappings: { default: { default: "mayúscula O con acento circunflejo y grave" } }, category: "Lu" },
{
key: "1ED4",
mappings: { default: { default: "mayúscula O con acento circunflejo y gancho arriba" } },
category: "Lu"
},
{ key: "1ED6", mappings: { default: { default: "mayúscula O con acento circunflejo y tilde" } }, category: "Lu" },
{
key: "1ED8",
mappings: { default: { default: "mayúscula O con acento circunflejo y punto debajo" } },
category: "Lu"
},
{ key: "1EDA", mappings: { default: { default: "mayúscula O with horn and acute" } }, category: "Lu" },
{ key: "1EDC", mappings: { default: { default: "mayúscula O with horn and grave" } }, category: "Lu" },
{ key: "1EDE", mappings: { default: { default: "mayúscula O with horn and hook above" } }, category: "Lu" },
{ key: "1EE0", mappings: { default: { default: "mayúscula O with horn and tilde" } }, category: "Lu" },
{ key: "1EE2", mappings: { default: { default: "mayúscula O con cuerno y punto debajo" } }, category: "Lu" },
{ key: "1EE8", mappings: { default: { default: "mayúscula U con cuerno y agudo" } }, category: "Lu" },
{ key: "1EEA", mappings: { default: { default: "mayúscula U con cuerno y grave" } }, category: "Lu" },
{ key: "1EEC", mappings: { default: { default: "mayúscula U con cuerno y gancho arriba" } }, category: "Lu" },
{ key: "1EEE", mappings: { default: { default: "mayúscula U con cuerno y tilde" } }, category: "Lu" },
{ key: "1EF0", mappings: { default: { default: "mayúscula U con cuerno y punto debajo" } }, category: "Lu" }
];
| GerHobbelt/MathJax | extensions/a11y/mathmaps/es/symbols/latin-upper-double-accent.js | JavaScript | apache-2.0 | 6,021 |
// Copyright 2007 The Closure Library 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 Base class for UI MDL controls.
* @author [email protected] (Artem Lytvynov)
*/
/**********************************************************************************************************************
* Provide section *
**********************************************************************************************************************/
goog.provide( 'zz.ui.mdl.ControlRenderer' );
/**********************************************************************************************************************
* Dependencies section *
**********************************************************************************************************************/
goog.require( 'goog.ui.registry' );
goog.require( 'goog.ui.ControlRenderer' );
/**********************************************************************************************************************
* Renderer definition section *
**********************************************************************************************************************/
/**
* Default renderer for {@link zz.ui.mdl.Control}s. Extends the superclass to support checkbox states.
* @constructor
* @extends {goog.ui.ControlRenderer}
*/
zz.ui.mdl.ControlRenderer = function( ){
zz.ui.mdl.ControlRenderer.base( this, 'constructor' );
};
goog.inherits( zz.ui.mdl.ControlRenderer, goog.ui.ControlRenderer );
goog.addSingletonGetter( zz.ui.mdl.ControlRenderer );
/**********************************************************************************************************************
* Life cycle methods *
**********************************************************************************************************************/
/**
* @override
*/
zz.ui.mdl.ControlRenderer.prototype.createDom = function( ){
goog.base( this, 'createDom' );
};
/**
* @override
*/
zz.ui.mdl.ControlRenderer.prototype.canDecorate = function( ){
//TODO: add check of the element
return true;
};
/**
* @param {zz.ui.mdl.Control} control
* @param {Element} element
* @override
*/
zz.ui.mdl.ControlRenderer.prototype.decorate = function( control, element ){
// Input element.
control.setInputElement( control.getDomHelper( ).getElementsByTagNameAndClass(
goog.dom.TagName.INPUT,
undefined,
element )[ 0 ]
);
return goog.base( this, 'decorate', control, element );
};
/**********************************************************************************************************************
* Helpers methods *
**********************************************************************************************************************/
/**
* Updates the appearance of the control in response to a state change.
* @param {zz.ui.mdl.Control} control Control instance to update.
* @param {goog.ui.Component.State} state State to enable or disable.
* @param {boolean} enable Whether the control is entering or exiting the state.
* @override
*/
zz.ui.mdl.ControlRenderer.prototype.setState = function( control, state, enable ){
var element = control.getElement( );
if( element ){
// TODO (user): Here we can/must add necessary classes for state.
this.updateAriaState(element, state, enable);
}
};
/**
* Returns the element within the component's DOM that should receive keyboard focus (null if none). The default
* implementation returns the control's root element.
* @param {zz.ui.mdl.Control} control Control whose key event target is to be returned.
* @return {Element} The key event target.
* @override
*/
zz.ui.mdl.ControlRenderer.prototype.getKeyEventTarget = function( control ){
return control.getInputElement( );
};
/**
* Set control input element value.
* @param {zz.ui.mdl.Control} control
* @param {*} value
*/
zz.ui.mdl.ControlRenderer.prototype.setValue = function( control, value ){
control.getInputElement( ).value = value;
};
/**
* Return control input element value.
* @param {zz.ui.mdl.Control} control
* @returns {*} value
*/
zz.ui.mdl.ControlRenderer.prototype.getValue = function( control ){
return control.getInputElement( ).value;
}; | alex-popkov/zz.ui.mdl | lib/sources/controlrenderer.js | JavaScript | apache-2.0 | 5,156 |
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.m.PagingButton.
sap.ui.define(['jquery.sap.global', './Button', 'sap/ui/core/Control'],
function (jQuery, Button, Control) {
"use strict";
/**
* Constructor for a new PagingButton.
*
* @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
* Enables users to navigate between items/entities.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version 1.30.4-SNAPSHOT
*
* @constructor
* @public
* @since 1.30
* @alias sap.m.PagingButton
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var PagingButton = Control.extend("sap.m.PagingButton", {
metadata: {
library: "sap.m",
properties: {
/**
* The total count of items/entities that the control navigates through.
* Minimum number of items/entities is 1.
*/
count: {type: "int", group: "Data", defaultValue: 1},
/**
* The current position in the items/entities that the control navigates through. One-based.
* Minimum position number is 1.
*/
position: {type: "int", group: "Data", defaultValue: 1}
},
aggregations: {
previousButton: {type: "sap.m.Button", multiple: false, visibility: "hidden"},
nextButton: {type: "sap.m.Button", multiple: false, visibility: "hidden"}
},
events: {
/**
* This event is fired when the current position is changed
*/
positionChange: {
parameters: {
/**
* The number of the new position. One-based.
*/
newPosition: {type: "int"},
/**
* The number of the old position. One-based.
*/
oldPosition: {type: "int"}
}
}
}
}
});
PagingButton.prototype.init = function () {
this._attachPressEvents();
};
PagingButton.prototype.onBeforeRendering = function () {
this._enforceValidPosition(this.getPosition());
this._updateButtonState();
};
/**
* This function lazily retrieves the nextButton
* @returns {sap.m.Button}
*/
PagingButton.prototype._getNextButton = function () {
if (!this.getAggregation("nextButton")) {
this.setAggregation("nextButton", new sap.m.Button({
icon: "sap-icon://slim-arrow-down",
enabled: false,
id: this.getId() + "-nextButton"
}));
}
return this.getAggregation("nextButton");
};
/**
* This function lazily retrieves the previousButton
* @returns {sap.m.Button}
*/
PagingButton.prototype._getPreviousButton = function () {
if (!this.getAggregation("previousButton")) {
this.setAggregation("previousButton", new sap.m.Button({
icon: "sap-icon://slim-arrow-up",
enabled: false,
id: this.getId() + "-previousButton"
}));
}
return this.getAggregation("previousButton");
};
PagingButton.prototype._attachPressEvents = function () {
this._getPreviousButton().attachPress(this._handlePositionChange.bind(this, false));
this._getNextButton().attachPress(this._handlePositionChange.bind(this, true));
};
/**
* This function handles the position change
* @params {boolean} bIncrease - Indicates the direction of the change of position
* @returns {sap.m.PagingButton} Reference to the control instance for chaining
*/
PagingButton.prototype._handlePositionChange = function (bIncrease) {
var iOldPosition = this.getPosition(),
iNewPosition = bIncrease ? iOldPosition + 1 : iOldPosition - 1;
this.setPosition(iNewPosition);
this.firePositionChange({newPosition: iNewPosition, oldPosition: iOldPosition});
this._updateButtonState();
return this;
};
/**
* Sets the appropriate state (enabled/disabled) for the buttons based on the total count / position
* @returns {sap.m.PagingButton} Reference to the control instance for chaining
*/
PagingButton.prototype._updateButtonState = function () {
var iTotalCount = this.getCount(),
iCurrentPosition = this.getPosition();
this._getPreviousButton().setEnabled(iCurrentPosition > 1);
this._getNextButton().setEnabled(iCurrentPosition < iTotalCount);
return this;
};
PagingButton.prototype.setPosition = function (iPosition) {
return this._validateProperty("position", iPosition);
};
PagingButton.prototype.setCount = function (iCount) {
return this._validateProperty("count", iCount);
};
/**
* Validate both the count/position properties and ensure they are correct
* @params {string} sProperty - The property to be checked, {number} iValue - The value to be checked
* @returns {sap.m.PagingButton} Reference to the control instance for chaining
*/
PagingButton.prototype._validateProperty = function (sProperty, iValue) {
if (iValue < 1) {
jQuery.sap.log.warning("Property '" + sProperty + "' must be greater or equal to 1", this);
return this;
}
return this.setProperty(sProperty, iValue);
};
/**
* Validates the position property to ensure that it's not set higher than the total count
* @params {number} iPosition
* @returns {sap.m.PagingButton} Reference to the control instance for chaining
*/
PagingButton.prototype._enforceValidPosition = function (iPosition) {
var iCount = this.getCount();
if (iPosition > iCount) {
jQuery.sap.log.warning("Property position must be less or equal to the total count");
this.setPosition(iCount);
}
return this;
};
return PagingButton;
}, /* bExport= */ true); | fconFGDCA/DetailCADA | resources/sap/m/PagingButton-dbg.js | JavaScript | apache-2.0 | 5,788 |
// Copyright 2017 Foxysoft GmbH
//
// 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.
/* global fx_trace */
/**
* <div>Returns the main (SAP Master) Identity Store's ID.</div>
* <div><strong>SAP IDM 8.0:</strong> If $IDSID is non-empty and not -1,
* returns that. Otherwise, obtains the minimum Identity Store ID
* from the database and returns that.</div>
* <div><strong>SAP IDM 7.2:</strong> Returns the value of global
* constant SAP_MASTER_IDS_ID.</div>
* @return {string} IDSID
* @requires fx_trace
* @since 1.1.0
*/
function fx_IDSID()
{
return fx_trace({compat: 1.0}).fx_IDSID();
}
| foxysoft/idm-connector-bobj | src/main/javascript/fx_IDSID.js | JavaScript | apache-2.0 | 1,139 |
/*
ClosureCompiler.js (c) 2013 Daniel Wirtz <[email protected]>
Released under the Apache License, Version 2.0
see: https://github.com/dcodeIO/ClosureCompiler.js for details
*/
var $jscomp={scope:{}};$jscomp.defineProperty="function"==typeof Object.defineProperties?Object.defineProperty:function(a,e,c){if(c.get||c.set)throw new TypeError("ES3 does not support getters and setters.");a!=Array.prototype&&a!=Object.prototype&&(a[e]=c.value)};$jscomp.getGlobal=function(a){return"undefined"!=typeof window&&window===a?a:"undefined"!=typeof global&&null!=global?global:a};$jscomp.global=$jscomp.getGlobal(this);$jscomp.SYMBOL_PREFIX="jscomp_symbol_";
$jscomp.initSymbol=function(){$jscomp.initSymbol=function(){};$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)};$jscomp.symbolCounter_=0;$jscomp.Symbol=function(a){return $jscomp.SYMBOL_PREFIX+(a||"")+$jscomp.symbolCounter_++};
$jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var a=$jscomp.global.Symbol.iterator;a||(a=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator"));"function"!=typeof Array.prototype[a]&&$jscomp.defineProperty(Array.prototype,a,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}});$jscomp.initSymbolIterator=function(){}};$jscomp.arrayIterator=function(a){var e=0;return $jscomp.iteratorPrototype(function(){return e<a.length?{done:!1,value:a[e++]}:{done:!0}})};
$jscomp.iteratorPrototype=function(a){$jscomp.initSymbolIterator();a={next:a};a[$jscomp.global.Symbol.iterator]=function(){return this};return a};$jscomp.array=$jscomp.array||{};$jscomp.iteratorFromArray=function(a,e){$jscomp.initSymbolIterator();a instanceof String&&(a+="");var c=0,g={next:function(){if(c<a.length){var m=c++;return{value:e(m,a[m]),done:!1}}g.next=function(){return{done:!0,value:void 0}};return g.next()}};g[Symbol.iterator]=function(){return g};return g};
$jscomp.polyfill=function(a,e,c,g){if(e){c=$jscomp.global;a=a.split(".");for(g=0;g<a.length-1;g++){var m=a[g];m in c||(c[m]={});c=c[m]}a=a[a.length-1];g=c[a];e=e(g);e!=g&&null!=e&&$jscomp.defineProperty(c,a,{configurable:!0,writable:!0,value:e})}};$jscomp.polyfill("Array.prototype.keys",function(a){return a?a:function(){return $jscomp.iteratorFromArray(this,function(a){return a})}},"es6-impl","es3");
(function(a){if("function"!=typeof require||!module||!module.exports||!process)throw Error("ClosureCompiler.js can only be used within node.js");var e=require("path"),c=require("fs"),g=require("child_process"),m=require("bl");c.existsSync||(c.existsSync=e.existsSync);var f=function(a){this.options="object"===typeof a&&a?a:{}};f._assertOption=function(a,c,e){if(0>e.indexOf(c))throw"Illegal "+a+" value: "+c+" ("+e+" expected)";};f.JAVA_EXT="win32"==process.platform?".exe":"";f.getGlobalJava=function(){var a=
null;process.env.JAVA_HOME&&(a=e.join(process.env.JAVA_HOME,"bin","java"+f.JAVA_EXT),c.existsSync(a)||(a=null));a||(a="java");return a};f.getBundledJava=function(){return e.normalize(e.join(__dirname,"jre","bin","java"+f.JAVA_EXT))};f.testJava=function(a,c){g.exec('"'+a+'" -version',{},function(a,e,f){f+="";f.match(/1\.[7-8]+/)?c(!0,null):0<=f.indexOf('version "')?c(!1,Error("Not Java 7")):c(!1,a)})};f.compile=function(a,c,e,g){4>arguments.length&&(g=e,e=null);(new f(c)).compile(a,e,g)};f.prototype.compile=
function(a,q,r){function w(a,b,c,d){var e=m(),f=m();a=g.spawn(a,b,{stdio:[c||"ignore","pipe","pipe"]});a.stdout.pipe(e);a.stderr.pipe(f);a.on("exit",function(a,b){var c;a&&(c=Error(a),c.code=a,c.signal=b);d(c,e,f)});a.on("error",function(a){d(a,e,f)})}function u(a,b){w(a,b,q,function(a,b,c){0<b.length||0<c.length?r(c+"",b+""):r(a,null)})}3>arguments.length&&(r=q,q=null);for(var d={},l=Object.keys(this.options),b=0;b<l.length;b++)d[l[b].toLowerCase()]=this.options[l[b]];delete d.js;delete d.js_output_file;
var b=d.xms||null,h=d.xmx||"1024m";delete d.xms;delete d.xmx;var t;if(d.compiler_jar)t=d.compiler_jar,delete d.compiler_jar;else{var v=__dirname+"/compiler";c.readdirSync(v).forEach(function(a){-1!==a.indexOf("closure-compiler")&&(t=v+"/"+a)})}var n=["-XX:+TieredCompilation"];b&&n.push("-Xms"+b);n.push("-Xmx"+h,"-jar",t);a instanceof Array||(a=[a]);for(b=0;b<a.length;b++){if("string"!=typeof a[b])throw Error("Illegal source file: "+a[b]);if(0<=a[b].indexOf('"'))n.push("--js="+a[b]);else{h=c.statSync(a[b]);
if(!h.isFile())throw Error("Source file not found: "+a[b]);n.push("--js",a[b])}}d.externs||(d.externs=[]);d.externs instanceof Array||(d.externs=[d.externs]);l=[];for(b=0;b<d.externs.length;b++){if("string"!=typeof d.externs[b]||""==d.externs[b])throw Error("Externs directive does not point to a file or directory: "+d.externs[b]);"node"==d.externs[b].toLowerCase()&&(d.externs[b]=__dirname+"/node_modules/closurecompiler-externs");h=c.statSync(d.externs[b]);if(h.isDirectory())for(var p=c.readdirSync(d.externs[b]),
h=0;h<p.length;h++){var k=d.externs[b]+"/"+p[h];c.statSync(k).isFile()&&".js"==e.extname(k).toLowerCase()&&l.push(k)}else if(h.isFile())l.push(d.externs[b]);else throw Error("Externs file not found: "+d.externs[b]);}delete d.externs;for(b=0;b<l.length;b++)n.push("--externs",l[b]);l=Object.keys(d);for(b=0;b<l.length;b++){p=l[b];k=d[l[b]];if(!/[a-zA-Z0-9_]+/.test(p))throw Error("Illegal option: "+p);if(!0===k)n.push("--"+p);else if(!1!==k)for(k instanceof Array||(k=[k]),h=0;h<k.length;h++){if(!/[^\s]*/.test(k[h]))throw Error("Illegal value for option "+
p+": "+k[h]);n.push("--"+p,k[h])}}f.testJava(f.getGlobalJava(),function(a){a?u(f.getGlobalJava(),n):f.testJava(f.getBundledJava(),function(a){if(a)u(f.getBundledJava(),n);else throw Error("Java is not available, neither the bundled nor a global one.");})})};f.prototype.toString=function(){return"ClosureCompiler"};module.exports=f})(this);
| dcodeIO/ClosureCompiler.js | ClosureCompiler.min.js | JavaScript | apache-2.0 | 5,750 |
var classorg_1_1onosproject_1_1cordvtn_1_1cli_1_1CordVtnNodeListCommand =
[
[ "execute", "classorg_1_1onosproject_1_1cordvtn_1_1cli_1_1CordVtnNodeListCommand.html#a8795ed63dd8a80eb314b7c3ea072f75a", null ]
]; | onosfw/apis | onos/apis/classorg_1_1onosproject_1_1cordvtn_1_1cli_1_1CordVtnNodeListCommand.js | JavaScript | apache-2.0 | 212 |
var searchData=
[
['leaderboard_2ecpp',['Leaderboard.cpp',['../a00044.html',1,'']]],
['leaderboard_2eh',['Leaderboard.h',['../a00047.html',1,'']]],
['leaderboardview_2ecpp',['LeaderboardView.cpp',['../a00134.html',1,'']]],
['leaderboardview_2eh',['LeaderboardView.h',['../a00137.html',1,'']]]
];
| Bokoblin/DUTS2-POO-ProjetRunner | docs/search/files_7.js | JavaScript | apache-2.0 | 304 |
import async from 'async';
import { RateVideoResponse } from './protos';
import { UserRatedVideo } from './events';
import { toCassandraUuid, toProtobufTimestamp } from '../common/protobuf-conversions';
import { getCassandraClient } from '../../common/cassandra';
import { publish } from '../../common/message-bus';
// Update the video_ratings counter table
const updateRatingsCql = `
UPDATE video_ratings
SET rating_counter = rating_counter + 1, rating_total = rating_total + ?
WHERE videoid = ?`;
// Insert rating for a user and specific video
const insertUserRatingCql = `
INSERT INTO video_ratings_by_user (
videoid, userid, rating)
VALUES (?, ?, ?)`;
/**
* Adds a user's rating of a video.
*/
export function rateVideo(call, cb) {
let { request } = call;
async.waterfall([
// Get client
async.asyncify(getCassandraClient),
// Execute CQL
(client, next) => {
// Get some bind variable values for the CQL we're going to run
let videoId = toCassandraUuid(request.videoId);
let userId = toCassandraUuid(request.userId);
let { rating } = request;
// We can't use a batch to do inserts to multiple tables here because one the video_ratings table
// is a counter table (and Cassandra doesn't let us mix counter DML with regular DML in a batch),
// but we can execute the inserts in parallel
async.parallel([
execCb => client.execute(updateRatingsCql, [ rating, videoId ], execCb),
execCb => client.execute(insertUserRatingCql, [ videoId, userId, rating ], execCb)
], next);
},
// If successful with inserts, publish an event
(resultSets, next) => {
// Tell the world about the user rating the video
let event = new UserRatedVideo({
videoId: request.videoId,
userId: request.userId,
rating: request.rating,
ratingTimestamp: toProtobufTimestamp(new Date(Date.now()))
});
publish(event, next);
},
// Finally, return a response object
next => {
next(null, new RateVideoResponse());
}
], cb);
}; | KillrVideo/killrvideo-nodejs | src/services/ratings/rate-video.js | JavaScript | apache-2.0 | 2,086 |
onmessage = function(e) {
var args = e.data;
var MAXIMUM_ROUNDS = (!args[0])? 1000000 : args[0];
var fee = (!args[1])? 10 : args[1];
var coinRecord = {}; // { "123": 10, "245": 145 .... }
var totalEarning = 0;
for (var currentRound = 0; currentRound < MAXIMUM_ROUNDS; currentRound++) {
var coinAccumulation = 0, pow = 0;
// 0 is negative, and 1 is positive
while (((Math.random() / .5) & 1) == 0) {
pow++;
};
coinAccumulation = Math.pow(2, pow);
totalEarning += coinAccumulation;
var property = "" + coinAccumulation; // fast converting integer to string
coinRecord[property] = (!coinRecord[property])? 1 : coinRecord[property] + 1;
};
var totalCost = fee * MAXIMUM_ROUNDS;
var earnPerRound = totalEarning / MAXIMUM_ROUNDS;
console.log("Earn: " + totalEarning);
console.log("Cost: " + totalCost);
console.log("Earn per round: " + earnPerRound);
// converting coinRecord to [ [123, 10], [245, 145] ]
var distDataSet = [],
properties = Object.keys(coinRecord);
for (var i = 0; i < properties.length; i++) {
distDataSet.push([parseFloat(properties[i]), coinRecord[properties[i]]]);
};
postMessage([distDataSet, totalEarning, totalCost, earnPerRound, MAXIMUM_ROUNDS, fee]);
// console.log(distDataSet);
close();
} | duraraxbaccano/gist | st.petersburg.paradox.js | JavaScript | apache-2.0 | 1,299 |
//FILE: bg.js
/**
* this is a background service and this code will run *every* time the
* application goes into the foreground
*/
var value = "Hello from Running BG service - bg.js";
Ti.API.info(value);
var notification = Ti.App.iOS.scheduleLocalNotification({
alertBody:"App was put in background",
alertAction:"Re-Launch!",
userInfo:{"hello":"world"},
date:new Date(new Date().getTime() + 3000) // 3 seconds after backgrounding
});
Ti.App.iOS.addEventListener('notification',function(){
Ti.API.info('background event received = '+notification);
//Ti.App.currentService.unregister();
});
// we need to explicitly stop the service or it will continue to run
// you should only stop it if you aren't listening for notifications in the background
// to conserve system resources. you can stop like this:
//Ti.App.currentService.stop();
// you can unregister the service by calling
// Ti.App.currentService.unregister()
// and this service will be unregistered and never invoked again | mixandmatch/titanium | app/assets/bg.js | JavaScript | apache-2.0 | 1,022 |
/*
* Copyright (c) 2008-2021, Hazelcast, 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';
const { Client } = require('hazelcast-client');
class CustomSerializable {
constructor(value) {
this.value = value;
this.hzCustomId = 10;
}
}
class CustomSerializer {
constructor() {
this.id = 10;
}
read(input) {
const len = input.readInt();
let str = '';
for (let i = 0; i < len; i++) {
str = str + String.fromCharCode(input.readInt());
}
return new CustomSerializable(str);
}
write(output, obj) {
output.writeInt(obj.value.length);
for (let i = 0; i < obj.value.length; i++) {
output.writeInt(obj.value.charCodeAt(i));
}
}
}
(async () => {
try {
// Start the Hazelcast Client and connect to an already running
// Hazelcast Cluster on 127.0.0.1
const hz = await Client.newHazelcastClient({
serialization: {
customSerializers: [new CustomSerializer()]
}
});
// CustomSerializer will serialize/deserialize CustomSerializable objects
// Shutdown this Hazelcast client
await hz.shutdown();
} catch (err) {
console.error('Error occurred:', err);
process.exit(1);
}
})();
| hazelcast-incubator/hazelcast-nodejs-client | code_samples/com-website/CustomSerializerSample.js | JavaScript | apache-2.0 | 1,882 |
//----- Requires -----
dojo.require('comum.format');
dojo.require('comum.CampoRedondo');
dojo.require('main.Pedido');
dojo.provide('main.Restaurante');
dojo.declare('main.Restaurante', null, {
restaurante : null,
loader : null,
restaurantes : new Array(),
pedido : null,
constructor : function () {
this.pedido = new main.Pedido();
this.pedido.preenchePedido();
},
carregando : function () {
this.loader = colocaLoader(dojo.query('#cardapio tbody')[0], 'only');
dojo.query('#tituloRestaurante h2')[0].innerHTML = 'Carregando';
},
carregaRestaurante : function (id) {
if (this.restaurante != null && this.restaurante.id == id) return;
var novoRestaurante = null;
dojo.forEach(this.restaurantes, function (item) {
if (item.id == id) {
novoRestaurante = item;
return false;
}
}, this);
// Se encontrou o restaurante já carregado
if (novoRestaurante != null) {
this.restaurante = novoRestaurante;
this.preencheRestaurante();
return;
}
var callback = dojo.hitch(this, function (response) {
if (response.failure) {
alert('Restaurante não encontrado.');
this.preencheRestaurante();
return;
}
this.restaurante = response;
this.restaurantes.push(this.restaurante);
this.preencheRestaurante();
});
// Se não, carrega
dojo.xhr('GET', {
url : contexto + '/getRestaurant.do',
content : {id : id},
handleAs : 'json',
load : callback,
error: callback
});
},
criaItemCardapio : function (item) {
var resultado = dojo.create('tr', { id : item.id });
var descricao = dojo.create('td', null, resultado);
dojo.addClass(descricao, 'descricao');
descricao.innerHTML = '<span>' + item.title + '</span> - ' + item.description;
dojo.place('<td>' + formataMoeda(item.price) + '</td>', resultado);
var quantidade = dojo.place('<td class="quantidade"></td>', resultado);
dojo.place('<span>- </span>', quantidade);
var campo = new comum.CampoRedondo({largura:25, altura: 15, name: 'quantidade'});
var outroNo = dojo.place(campo.domNode, quantidade);
dojo.place('<span> +</span>', quantidade);
campo.setValor(1);
var acompanhamentos = dojo.place('<td><a href="#">Selecionar</a></td>', resultado);
var pedir = dojo.place('<td></td>', resultado);
var callback = dojo.hitch(this, function (evt) {
var tr = evt.currentTarget.parentNode;
var id = dojo.attr(tr, 'id');
var campoQtd = dojo.query('input', tr)[0];
var quantidade = campoQtd.value;
var nome = dojo.query('.descricao span', tr)[0].innerHTML;
this.pedido.adicionar({id : id, quantity : quantidade, name : nome});
});
dojo.connect(pedir, 'onclick', callback);
var imagemPedir = dojo.place('<img src="../../resources/img/btPedir.png" alt="Pedir" />', pedir);
return resultado;
},
limpaCampos : function () {
var titulo = dojo.byId('tituloRestaurante');
var imagem = dojo.query('img', titulo)[0];
dojo.attr(imagem, 'src', '');
dojo.attr(imagem, 'alt', '');
var nomeRestaurante = dojo.query('h2', titulo)[0];
dojo.empty(nomeRestaurante);
var descricao = dojo.query('p', titulo)[0];
descricao.innerHTML = '';
var listaCategorias = dojo.byId('categorias');
dojo.empty(listaCategorias);
var tabelaCardapio = dojo.query('#cardapio tbody')[0];
dojo.empty(tabelaCardapio);
},
mostraCategoria : function (categoria) {
if (this.restaurante == null) return;
dojo.query('#categorias li').forEach(function (item) {
if (item.innerHTML == categoria) {
dojo.addClass(item, 'selecionado');
return false;
}
});
var tabelaCardapio = dojo.query('#cardapio tbody')[0];
dojo.empty(tabelaCardapio);
var pratos = this.restaurante.plates;
for (var i = 0; i < pratos.length; i++) {
var prato = pratos[i];
if (prato.category == categoria) {
dojo.place(this.criaItemCardapio(prato), tabelaCardapio);
}
}
},
preencheCardapio : function (itens) {
if (!itens) return;
var listaCategorias = dojo.byId('categorias');
dojo.empty(listaCategorias);
var categorias = new Array();
for (var i = 0; i < itens.length; i++) {
if (dojo.indexOf(categorias, itens[i].category) == -1) {
var categoria = itens[i].category;
categorias.push(categoria);
var itemCategoria = dojo.place('<li>' + categoria + '</li>', listaCategorias);
var callback = dojo.hitch(this, function (evt) {
var categoria = evt.target.innerHTML;
var selecionado = dojo.query('.selecionado', listaCategorias)[0];
if (selecionado) {
// se for o mesmo não faz nada
if (selecionado.innerHTML == categoria) return;
// Se não for o mesmo, remove a classe
dojo.removeClass(selecionado, 'selecionado');
}
this.mostraCategoria(categoria);
});
dojo.connect(itemCategoria, 'onclick', callback);
}
}
categorias.sort();
this.mostraCategoria(categorias[0]);
},
preencheRestaurante : function () {
if (!this.restaurante) {
dojo.style('conteudo_main', 'display', 'block');
dojo.style('conteudo_restaurante', 'display', 'none');
return;
}
// Remove o loader se tiver
if (this.loader) dojo.destroy(this.loader);
var titulo = dojo.byId('tituloRestaurante');
var imagem = dojo.query('img', titulo)[0];
dojo.attr(imagem, {
src : contexto + '/' + this.restaurante.imageUrl,
alt : this.restaurante.imageAlt
});
var nomeRestaurante = dojo.query('h2', titulo)[0];
nomeRestaurante.innerHTML = this.restaurante.name;
var descricao = dojo.query('p', titulo)[0];
descricao.innerHTML = this.restaurante.description;
this.preencheCardapio(this.restaurante.plates);
this.pedido.mostraPedido();
},
setRestaurante : function (id) {
window.location.hash = 'restaurantId=' + id;
if (this.restaurante == null || id != this.restaurante.id) {
this.limpaCampos();
this.carregando();
this.carregaRestaurante(id);
}
}
}); | rafaelcoutinho/comendobemdelivery | war/scripts/main/Restaurante.js | JavaScript | apache-2.0 | 5,972 |
import React from 'react';
import planList from './plans';
import {paymentCountries} from './config';
import Popover from 'material-ui/Popover';
class PlanDetails extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedPlan: planList[0],
openPlanSelector: false
};
}
handleTouchTap = (event) => {
event.preventDefault();
this.setState({openPlanSelector: true, anchorEl: event.currentTarget})
}
handleRequestClose = () => {
this.setState({openPlanSelector: false})
}
selectPlan(plan) {
this.setState({selectedPlan: plan})
this.handleRequestClose()
}
render() {
return (
<div className="plans">
<div className="planname" onTouchTap={this.handleTouchTap}>
<span className="type">{this.state.selectedPlan.label}</span>
<span className="value">{this.state.selectedPlan.price || this.state.selectedPlan.price === 0
? '$ ' + this.state.selectedPlan.price
: ''}</span>
<i className="icon ion-ios-arrow-down arrow"></i>
</div>
<Popover open={this.state.openPlanSelector} anchorEl={this.state.anchorEl} anchorOrigin={{
horizontal: 'left',
vertical: 'bottom'
}} targetOrigin={{
horizontal: 'left',
vertical: 'top'
}} onRequestClose={this.handleRequestClose}>
{planList.map((plan, i) => {
return <div className="plannamepop" key={i} onClick={this.selectPlan.bind(this, plan)}>
<span className="type">{plan.label}</span>
<span className="value">{plan.price || plan.price === 0
? '$ ' + plan.price
: 'Custom'}</span>
</div>
})
}
</Popover>
<p className="divlabel">DATABASE</p>
<div className="divdetail">
<span className="type">API Calls</span>
<span className="value">{this.state.selectedPlan.usage[0].features[0].limit.label}</span>
</div>
<div className="divdetail">
<span className="type">Storage</span>
<span className="value">{this.state.selectedPlan.usage[0].features[1].limit.label}</span>
</div>
<p className="divlabel">REALTIME</p>
<div className="divdetail">
<span className="type">Connections</span>
<span className="value">{this.state.selectedPlan.usage[1].features[0].limit.label}</span>
</div>
<p className="divlabel">MISC</p>
<div className="divdetail">
<span className="type">MongoDB Access</span>
<span className="value">{this.state.selectedPlan.usage[2].features[0].limit.show
? 'Available'
: '-'}</span>
</div>
</div>
)
}
}
export default PlanDetails
| CloudBoost/cloudboost | payment-ui/src/planDetails.js | JavaScript | apache-2.0 | 3,357 |
/**
* Created by Pawan on 1/4/2016.
*/
/**
* Created by Pawan on 12/11/2015.
*/
(function () {
var commoncontroller = function ($http,$mdDialog,$mdMedia) {
var showConfirm = function(title, label, okbutton, cancelbutton, content, OkCallback, CancelCallBack, okObj) {
var confirm = $mdDialog.confirm()
.title(title)
.content(content)
.ok(okbutton)
.cancel(cancelbutton);
$mdDialog.show(confirm).then(function() {
OkCallback();
}, function() {
CancelCallBack();
});
};
var showAdvanced = function(controller,template,clickOutSt) {
var useFullScreen = ($mdMedia('sm') || $mdMedia('xs')) && $scope.customFullscreen;
$mdDialog.show({
controller: controller,
templateUrl: template,
//parent: angular.element(document.body),
clickOutsideToClose:clickOutSt,
fullscreen: useFullScreen
})
.then(function(answer) {
//$scope.status = 'You said the information was "' + answer + '".';
}, function() {
//$scope.status = 'You cancelled the dialog.';
});
/*$scope.$watch(function() {
return $mdMedia('xs') || $mdMedia('sm');
}, function(wantsFullScreen) {
$scope.customFullscreen = (wantsFullScreen === true);
});*/
};
var showAlert = function(title,content)
{
$mdDialog.show(
$mdDialog.alert()
//.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(false)
.title(title)
.content(content)
.ariaLabel('Alert Dialog Demo')
.ok('OK')
// .targetEvent(ev)
);
}
return{
showConfirm:showConfirm,
showAdvanced:showAdvanced,
showAlert:showAlert
};
};
var module = angular.module("trunkApp");
module.factory("commoncontroller",commoncontroller);
}());
| DuoSoftware/DVP-Apps | DVP-TrunkApp/scripts/services/CommonController.js | JavaScript | apache-2.0 | 1,940 |
var fileio = require("../fileio")();
var wildcard = require("../wildcard");
var fs = require("fs");
var items = [];
var cells = [
["Medication","dropdown"],
["Dosage","text"],
["Per Use","text"],
["Frequency","dropdown"],
["Type of Med.","text"],
["Method","text"],
["To Dispense","text"],
["PRN","checkbox"]
];
var settings;
function buildTable() {
var table = document.getElementById("table");
while ( table.firstChild ) {
table.removeChild(table.firstChild);
}
var row = document.createElement("tr");
var col = document.createElement("td");
col.innerText = "X";
row.appendChild(col);
for ( var i = 0; i < cells.length; i++ ) {
var col = document.createElement("td");
col.innerText = cells[i][0];
row.appendChild(col);
}
table.appendChild(row);
for ( var i = 0; i < items.length; i++ ) {
var row = document.createElement("tr");
var col = document.createElement("td");
var button = document.createElement("button");
button.innerText = "X";
button.className = "del";
button.id = "d:" + i;
button.onclick = function() {
var index = parseInt(this.id.split(":")[1]);
items = items.slice(0,index).concat(items.slice(index + 1));
buildTable();
}
col.appendChild(button);
row.appendChild(col);
for ( var j = 0; j < cells.length; j++ ) {
if ( cells[j][1] == "dropdown" ) {
var col = document.createElement("td");
var select = document.createElement("select");
for ( var k = 0; k < (cells[j][0] == "Medication" ? settings.medications : settings.frequencies).length; k++ ) {
var option = document.createElement("option");
var item = cells[j][0] == "Medication" ? settings.medications[k][0] : settings.frequencies[k];
option.innerText = item;
option.value = item;
select.appendChild(option);
}
select.value = items[i][j] || "";
select.id = "i:" + i + ":" + j;
select.onchange = function() {
var index = this.id.split(":").map(item => parseInt(item));
cells[index[2]][0] == "Medication" ? items[index[1]] = settings.medications.filter(item => item[0] == this.value)[0] : items[index[1]][index[2]] = this.value;
buildTable();
}
col.appendChild(select);
row.appendChild(col);
} else if ( cells[j][1] == "text" ) {
var col = document.createElement("td");
var input = document.createElement("input");
input.size = 10;
input.value = items[i][j] || "";
input.id = "i:" + i + ":" + j;
input.onkeyup = function() {
var index = this.id.split(":").map(item => parseInt(item));
items[index[1]][index[2]] = this.value;
}
col.appendChild(input);
row.appendChild(col);
} else if ( cells[j][1] == "checkbox" ) {
var col = document.createElement("td");
var box = document.createElement("input");
box.type = "checkbox";
box.checked = items[i][j];
box.id = "i:" + i + ":" + j;
box.onchange = function() {
var index = this.id.split(":").map(item => parseInt(item));
items[index[1]][index[2]] = this.checked;
}
col.appendChild(box);
row.appendChild(col);
}
}
table.appendChild(row);
}
}
function buildList(data) {
var select = document.getElementById("patients");
for ( var i = 0; i < data.length; i++ ) {
var option = document.createElement("option");
option.innerText = data[i]["Name"];
option.value = i;
select.appendChild(option);
}
select.value = "";
}
function addMedication() {
items.push([]);
buildTable();
}
function toPrint() {
localStorage.setItem("items",JSON.stringify([items,parseInt(document.getElementById("patients").value)]));
open(__dirname + "/print/index.html","","width=600,height=600");
}
function toList() {
location.href = __dirname + "/../list/index.html";
}
window.onload = function() {
wildcard.onLoad(function(char) {
if ( char == "p" ) toPrint();
});
fileio.loadData("patients",function(hold) {
var patients = JSON.parse(hold.toString());
fileio.loadData("settings",function(hold) {
hold = JSON.parse(hold.toString());
settings = {
medications: hold.prescript.medications,
frequencies: hold.prescript.frequencies
};
buildList(patients);
buildTable();
});
});
};
| Simas2006/Treat | client/prescript/script.js | JavaScript | apache-2.0 | 4,465 |
var searchData=
[
['all',['all',['../unionMQTT__Connect__Header__Flags.html#aac6e7ff76de4ce79fb198a5c043614ce',1,'MQTT_Connect_Header_Flags::all()'],['../unionMQTT__Connack__Header__Flags.html#ac1d68764617031a6d7f0e48c21b11807',1,'MQTT_Connack_Header_Flags::all()']]]
];
| chainlinq/boatkeeper | linux_mqtt_mbedtls-2.1.1/docs/html/search/variables_0.js | JavaScript | apache-2.0 | 273 |
/*!
* ${copyright}
*/
sap.ui.define([
"jquery.sap.global",
"./Base",
"sap/ui/fl/Utils"
],
function(
jQuery,
Base,
FlexUtils
) {
"use strict";
/**
* Change handler for moving of an element.
*
* @alias sap.ui.fl.changeHandler.MoveControls
* @author SAP SE
* @version ${version}
* @experimental Since 1.46
*/
var MoveControls = { };
// Defines object which contains constants used in the handler
MoveControls.SOURCE_ALIAS = "source";
MoveControls.TARGET_ALIAS = "target";
MoveControls.MOVED_ELEMENTS_ALIAS = "movedElements";
MoveControls._checkConditions = function (oChange, oModifier, oView, oAppComponent) {
if (!oChange) {
throw new Error("No change instance");
}
var oChangeContent = oChange.getContent();
if (!oChangeContent || !oChangeContent.movedElements || oChangeContent.movedElements.length === 0) {
throw new Error("Change format invalid");
}
if (!oChangeContent.source || !oChangeContent.source.selector) {
throw new Error("No source supplied for move");
}
if (!oChangeContent.target || !oChangeContent.target.selector) {
throw new Error("No target supplied for move");
}
if (!oModifier.bySelector(oChangeContent.source.selector, oAppComponent, oView)) {
throw new Error("Move source parent not found");
}
if (!oModifier.bySelector(oChangeContent.target.selector, oAppComponent, oView)) {
throw new Error("Move target parent not found");
}
if (!oChangeContent.source.selector.aggregation) {
throw new Error("No source aggregation supplied for move");
}
if (!oChangeContent.target.selector.aggregation) {
throw new Error("No target aggregation supplied for move");
}
};
MoveControls._getElementControlOrThrowError = function(mMovedElement, oModifier, oAppComponent, oView) {
if (!mMovedElement.selector && !mMovedElement.id) {
throw new Error("Change format invalid - moveElements element has no id attribute");
}
if (typeof mMovedElement.targetIndex !== "number") {
throw new Error("Missing targetIndex for element with id '" + mMovedElement.selector.id
+ "' in movedElements supplied");
}
var oControl = oModifier.bySelector(mMovedElement.selector || mMovedElement.id, oAppComponent, oView);
if (!oControl) {
throw new Error("Control to move was not found. Id: '" + mMovedElement.selector.id + "'");
}
return oControl;
};
MoveControls._checkCompleteChangeContentConditions = function(mSpecificChangeInfo) {
if (!mSpecificChangeInfo.movedElements) {
throw new Error("mSpecificChangeInfo.movedElements attribute required");
}
if (mSpecificChangeInfo.movedElements.length === 0) {
throw new Error("MovedElements array is empty");
}
mSpecificChangeInfo.movedElements.forEach(function (mElement) {
if (!mElement.id) {
throw new Error("MovedControls element has no id attribute");
}
if (typeof (mElement.sourceIndex) !== "number") {
throw new Error("SourceIndex attribute at MovedElements element is no number");
}
if (typeof (mElement.targetIndex) !== "number") {
throw new Error("TargetIndex attribute at MovedElements element is no number");
}
});
};
MoveControls._getSpecificChangeInfo = function(oModifier, mSpecificChangeInfo, oAppComponent) {
delete mSpecificChangeInfo.source.publicAggregation;
delete mSpecificChangeInfo.target.publicAggregation;
var oSourceParent = mSpecificChangeInfo.source.parent || oModifier.bySelector(mSpecificChangeInfo.source.id, oAppComponent);
var oTargetParent = mSpecificChangeInfo.target.parent || oModifier.bySelector(mSpecificChangeInfo.target.id, oAppComponent);
var sSourceAggregation = mSpecificChangeInfo.source.aggregation;
var sTargetAggregation = mSpecificChangeInfo.target.aggregation;
var mAdditionalSourceInfo = {
aggregation: mSpecificChangeInfo.source.aggregation,
type: oModifier.getControlType(oSourceParent)
};
var mAdditionalTargetInfo = {
aggregation: mSpecificChangeInfo.target.aggregation,
type: oModifier.getControlType(oTargetParent)
};
var mSpecificInfo = {
source : {
id : oSourceParent.getId(),
aggregation : sSourceAggregation,
type : mAdditionalSourceInfo.type,
selector : oModifier.getSelector(mSpecificChangeInfo.source.id, oAppComponent, mAdditionalSourceInfo)
},
target : {
id : oTargetParent.getId(),
aggregation : sTargetAggregation,
type : mAdditionalTargetInfo.type,
selector : oModifier.getSelector(mSpecificChangeInfo.target.id, oAppComponent, mAdditionalTargetInfo)
},
movedElements : mSpecificChangeInfo.movedElements
};
return mSpecificInfo;
};
/**
* Moves an element from one aggregation to another.
*
* @param {sap.ui.fl.Change} oChange change object with instructions to be applied on the control map
* @param {sap.ui.core.Control} oRelevantContainer control that matches the change selector for applying the change, which is the source of the move
* @param {object} mPropertyBag - map of properties
* @param {object} mPropertyBag.view - xml node representing a ui5 view
* @param {string} [mPropertyBag.sourceAggregation] - name of the source aggregation. Overwrites the aggregation from the change. Can be provided by a custom ChangeHandler, that uses this ChangeHandler
* @param {string} [mPropertyBag.targetAggregation] - name of the target aggregation. Overwrites the aggregation from the change. Can be provided by a custom ChangeHandler, that uses this ChangeHandler
* @param {sap.ui.core.util.reflection.BaseTreeModifier} mPropertyBag.modifier - modifier for the controls
* @param {sap.ui.core.UIComponent} mPropertyBag.appComponent - appComopnent
* @return {boolean} Returns true if change could be applied, otherwise undefined
* @public
* @function
* @name sap.ui.fl.changeHandler.MoveControls#applyChange
*/
MoveControls.applyChange = function(oChange, oRelevantContainer, mPropertyBag) {
var oModifier = mPropertyBag.modifier;
var oView = mPropertyBag.view;
var oAppComponent = mPropertyBag.appComponent;
this._checkConditions(oChange, oModifier, oView, oAppComponent);
var oChangeContent = oChange.getContent();
var sSourceAggregation = mPropertyBag.sourceAggregation || oChangeContent.source.selector.aggregation;
var oTargetParent = oModifier.bySelector(oChangeContent.target.selector, oAppComponent, oView);
var sTargetAggregation = mPropertyBag.targetAggregation || oChangeContent.target.selector.aggregation;
var aRevertData = [];
oChangeContent.movedElements.forEach(function(mMovedElement, iElementIndex) {
var oMovedElement = this._getElementControlOrThrowError(mMovedElement, oModifier, oAppComponent, oView);
var oSourceParent = oModifier.getParent(oMovedElement);
var iInsertIndex = mMovedElement.targetIndex;
// save the current index, sourceParent and sourceAggregation for revert
var iIndex = oModifier.findIndexInParentAggregation(oMovedElement);
if (iIndex > -1) {
// mPropertyBag.sourceAggregation should always be used when available
sSourceAggregation = mPropertyBag.sourceAggregation || oModifier.getParentAggregationName(oMovedElement, oSourceParent);
// if iIndex === iInsertIndex the operation was already performed
// in this case we need the sourceIndex that is saved in the change in order to revert it to the correct index
if (iIndex === iInsertIndex) {
iIndex = mMovedElement.sourceIndex;
}
aRevertData.unshift({
index: iIndex,
aggregation: sSourceAggregation,
sourceParent: oSourceParent
});
}
oModifier.removeAggregation(oSourceParent, sSourceAggregation, oMovedElement);
oModifier.insertAggregation(oTargetParent, sTargetAggregation, oMovedElement, iInsertIndex, oView);
}, this);
oChange.setRevertData(aRevertData);
return true;
};
/**
* Reverts the Change MoveControls.
*
* @param {sap.ui.fl.Change} oChange change object with instructions to be applied on the control map
* @param {sap.ui.core.Control} oRelevantContainer control that matches the change selector for applying the change, which is the source of the move
* @param {object} mPropertyBag - map of properties
* @param {object} mPropertyBag.view - xml node representing a ui5 view
* @param {sap.ui.core.util.reflection.BaseTreeModifier} mPropertyBag.modifier - modifier for the controls
* @param {sap.ui.core.UIComponent} mPropertyBag.appComponent - appComopnent
* @return {boolean} true - if change could be applied
* @public
* @function
* @name sap.ui.fl.changeHandler.MoveControls#revertChange
*/
MoveControls.revertChange = function(oChange, oRelevantContainer, mPropertyBag) {
var oModifier = mPropertyBag.modifier;
var oView = mPropertyBag.view;
var oAppComponent = mPropertyBag.appComponent;
this._checkConditions(oChange, oModifier, oView, oAppComponent);
// we still have to set sourceParent and sourceAggregation initially from the change data,
// because for XML changes this data can't be stored in the revertData yet.
var oChangeContent = oChange.getContent();
var oSourceParent = oModifier.bySelector(oChangeContent.source.selector, oAppComponent, oView);
var sSourceAggregation = oChangeContent.source.selector.aggregation;
var oTargetParent = oModifier.bySelector(oChangeContent.target.selector, oAppComponent, oView);
var sTargetAggregation = oChangeContent.target.selector.aggregation;
var aRevertData = oChange.getRevertData();
oChange.getContent().movedElements.reverse();
oChangeContent.movedElements.forEach(function(mMovedElement, iElementIndex) {
var oMovedElement = this._getElementControlOrThrowError(mMovedElement, oModifier, oAppComponent, oView);
if (!oMovedElement) {
FlexUtils.log.warning("Element to move not found");
return;
}
var iInsertIndex = mMovedElement.sourceIndex;
if (aRevertData) {
oSourceParent = aRevertData[iElementIndex].sourceParent;
sSourceAggregation = aRevertData[iElementIndex].aggregation;
iInsertIndex = aRevertData[iElementIndex].index;
}
oModifier.removeAggregation(oTargetParent, sTargetAggregation, oMovedElement);
oModifier.insertAggregation(oSourceParent, sSourceAggregation, oMovedElement, iInsertIndex, oView);
}, this);
oChange.resetRevertData();
return true;
};
/**
* Completes the change by adding change handler specific content.
*
* @param {sap.ui.fl.Change} oChange change object to be completed
* @param {object} mSpecificChangeInfo as an empty object since no additional attributes are required for this operation
* @param {object} mPropertyBag - map of properties
* @param {sap.ui.core.UiComponent} mPropertyBag.appComponent component in which the change should be applied
* @public
* @function
* @name sap.ui.fl.changeHandler.MoveControls#completeChangeContent
*/
MoveControls.completeChangeContent = function(oChange, mSpecificChangeInfo, mPropertyBag) {
this._checkCompleteChangeContentConditions(mSpecificChangeInfo);
var oModifier = mPropertyBag.modifier;
var oAppComponent = mPropertyBag.appComponent;
var mChangeData = oChange.getDefinition();
mSpecificChangeInfo = this._getSpecificChangeInfo(oModifier, mSpecificChangeInfo, oAppComponent);
mChangeData.content = {
movedElements : [],
source : {
selector : mSpecificChangeInfo.source.selector
},
target : {
selector : mSpecificChangeInfo.target.selector
}
};
mSpecificChangeInfo.movedElements.forEach(function(mElement) {
var oElement = mElement.element || oModifier.bySelector(mElement.id, oAppComponent);
mChangeData.content.movedElements.push({
selector: oModifier.getSelector(oElement, oAppComponent),
sourceIndex : mElement.sourceIndex,
targetIndex : mElement.targetIndex
});
});
oChange.addDependentControl(mSpecificChangeInfo.source.id, MoveControls.SOURCE_ALIAS, mPropertyBag);
oChange.addDependentControl(mSpecificChangeInfo.target.id, MoveControls.TARGET_ALIAS, mPropertyBag);
oChange.addDependentControl(mSpecificChangeInfo.movedElements.map(function (element) {
return element.id;
}), MoveControls.MOVED_ELEMENTS_ALIAS, mPropertyBag);
};
return MoveControls;
},
/* bExport= */true);
| cschuff/openui5 | src/sap.ui.fl/src/sap/ui/fl/changeHandler/MoveControls.js | JavaScript | apache-2.0 | 12,171 |
var skin = {
// recent news title bar color and image
// if use image, bar color and title should empty
// if use text title, bar image should empty
"RECENT_BAR_IMAGE" : "", // example: imgs/wpapp.png, size: 320x45
"RECENT_BAR_COLOR" : "#0e8dd0", // example: #ff840a
// category title bar color and image
// if use image, bar color and title should empty
// if use text title, bar image should empty
"CATEG_BAR_IMAGE" : "", // example: imgs/wpapp.png, size: 320x45
"CATEG_BAR_COLOR" : "#0e8dd0", // example: #ff840a
"CATEG_DASHBOARD_BGCOLOR" : "#333",
// blog post title bar color and image
// if use image, bar color should empty
// if use text title, bar image should empty
"POST_BAR_IMAGE" : "", // example: imgs/wpapp.png, size: 320x45
"POST_BAR_COLOR" : "#0e8dd0", // example: #ff840a
// about tab bar color and image
// if use image, bar color and title should empty
// if use text title, bar image should empty
"ABOUT_BAR_IMAGE" : "", // example: imgs/wpapp.png, size: 320x45
"ABOUT_BAR_COLOR" : "#0e8dd0", // example: #ff840a
"WEBVIEW_BAR_IMAGE" : "", // example: imgs/wpapp.png, size: 320x45
"WEBVIEW_BAR_COLOR" : "#0e8dd0", // example: #ff840a
"TWITTER_BAR_IMAGE" : "", // example: imgs/wpapp.png, size: 320x45
"TWITTER_BAR_COLOR" : "#0e8dd0", // example: #ff840a
"PAGES_BAR_IMAGE" : "", // example: imgs/wpapp.png, size: 320x45
"PAGES_BAR_COLOR" : "#0e8dd0", // example: #ff840a
// table view for recent news
"RECENT_TV_BGCOLOR" : "#eee",
"RECENT_TV_BGCOLOR_ALT": "#eee",
"RECENT_TV_SEPARATOR_COLOR": "#eee",
"RECENT_TV_TITLE_COLOR": "#23589a",
"RECENT_TV_META_COLOR" : "#6c6c6c",
// table view for categories
"CATEG_TV_BGCOLOR" : "#eee",
"CATEG_TV_BGCOLOR_ALT": "#eee",
"CATEG_TV_SEPARATOR_COLOR": "#eee",
"CATEG_TV_TITLE_COLOR": "#23589a",
"CATEG_TV_META_COLOR" : "#6c6c6c",
// table view for twitter
"TWITTER_TV_BGCOLOR" : "#eee",
"TWITTER_TV_BGCOLOR_ALT": "#eee",
"TWITTER_TV_SEPARATOR_COLOR": "#eee",
"TWITTER_TV_TITLE_COLOR": "#23589a",
"TWITTER_TV_META_COLOR" : "#6c6c6c",
// table view for pages
"PAGES_TV_BGCOLOR" : "#eee",
"PAGES_TV_BGCOLOR_ALT": "#eee",
"PAGES_TV_TITLE_COLOR": "#23589a",
"DUMMY" : ""
};
// skin.RECENT_TV_GRADIENT = {
// type:'linear',
// colors:[{color:'#d4d4d4',position:0.0},
// {color:'#c4c4c4',position:0.50},{color:'#b4b4b4',position:1.0}
// ]};
// skin.CATEG_TV_GRADIENT = {
// type:'linear',
// colors:[{color:'#d4d4d4',position:0.0},
// {color:'#c4c4c4',position:0.50},{color:'#b4b4b4',position:1.0}
// ]};
// skin.TWITTER_TV_GRADIENT = {
// type:'linear',
// colors:[ {color:'#404040',position:0.0},{color:'#2f2f2f',position:0.5},{color:'#272727',position:1.0} ]
// }; | TagYourIt/inspirationapp | Resources/skin/blue.js | JavaScript | apache-2.0 | 3,029 |
'use strict';
var util = require('../../../util/index');
var DimensionError = require('../../../error/DimensionError');
var string = util.string,
isString = string.isString;
function factory (type, config, load, typed) {
var equalScalar = load(require('../../../function/relational/equalScalar'));
var SparseMatrix = type.SparseMatrix;
/**
* Iterates over SparseMatrix A and invokes the callback function f(Aij, Bij).
* Callback function invoked NZA times, number of nonzero elements in A.
*
*
* ┌ f(Aij, Bij) ; A(i,j) !== 0
* C(i,j) = ┤
* └ 0 ; otherwise
*
*
* @param {Matrix} a The SparseMatrix instance (A)
* @param {Matrix} b The SparseMatrix instance (B)
* @param {Function} callback The f(Aij,Bij) operation to invoke
*
* @return {Matrix} SparseMatrix (C)
*
* see https://github.com/josdejong/mathjs/pull/346#issuecomment-97620294
*/
var algorithm09 = function (a, b, callback) {
// sparse matrix arrays
var avalues = a._values;
var aindex = a._index;
var aptr = a._ptr;
var asize = a._size;
var adt = a._datatype;
// sparse matrix arrays
var bvalues = b._values;
var bindex = b._index;
var bptr = b._ptr;
var bsize = b._size;
var bdt = b._datatype;
// validate dimensions
if (asize.length !== bsize.length)
throw new DimensionError(asize.length, bsize.length);
// check rows & columns
if (asize[0] !== bsize[0] || asize[1] !== bsize[1])
throw new RangeError('Dimension mismatch. Matrix A (' + asize + ') must match Matrix B (' + bsize + ')');
// rows & columns
var rows = asize[0];
var columns = asize[1];
// datatype
var dt;
// equal signature to use
var eq = equalScalar;
// zero value
var zero = 0;
// callback signature to use
var cf = callback;
// process data types
if (adt && bdt && adt === bdt && isString(adt)) {
// datatype
dt = adt;
// find signature that matches (dt, dt)
eq = typed.find(equalScalar, [dt, dt]);
// convert 0 to the same datatype
zero = typed.convert(0, dt);
// callback
cf = typed.find(callback, [dt, dt]);
}
// result arrays
var cvalues = avalues && bvalues ? [] : undefined;
var cindex = [];
var cptr = [];
// matrix
var c = new SparseMatrix({
values: cvalues,
index: cindex,
ptr: cptr,
size: [rows, columns],
datatype: dt
});
// workspaces
var x = cvalues ? [] : undefined;
// marks indicating we have a value in x for a given column
var w = [];
// vars
var i, j, k, k0, k1;
// loop columns
for (j = 0; j < columns; j++) {
// update cptr
cptr[j] = cindex.length;
// column mark
var mark = j + 1;
// check we need to process values
if (x) {
// loop B(:,j)
for (k0 = bptr[j], k1 = bptr[j + 1], k = k0; k < k1; k++) {
// row
i = bindex[k];
// update workspace
w[i] = mark;
x[i] = bvalues[k];
}
}
// loop A(:,j)
for (k0 = aptr[j], k1 = aptr[j + 1], k = k0; k < k1; k++) {
// row
i = aindex[k];
// check we need to process values
if (x) {
// b value @ i,j
var vb = w[i] === mark ? x[i] : zero;
// invoke f
var vc = cf(avalues[k], vb);
// check zero value
if (!eq(vc, zero)) {
// push index
cindex.push(i);
// push value
cvalues.push(vc);
}
}
else {
// push index
cindex.push(i);
}
}
}
// update cptr
cptr[columns] = cindex.length;
// return sparse matrix
return c;
};
return algorithm09;
}
exports.name = 'algorithm09';
exports.factory = factory;
| mikberg/mathjs | lib/type/matrix/util/algorithm09.js | JavaScript | apache-2.0 | 3,994 |
var singleQuote = require('..');
describe('singlequote with \\r', function () {
var result;
before(function () {
function x() {
return 'hello" I am a string\'s for sure';
}
result = singleQuote(x.toString().replace(/\r/g, '').replace(/\n/g, '\r\n')); //make sure we have \r on both mac an win
});
it('should return code with single quotes string', function () {
function x() {
return 'hello" I am a string\'s for sure';
}
expect(result, result).to.equal(x.toString().replace(/\r/g, '').replace(/\n/g, '\r\n'));
});
});
describe('singlequote without \\r', function () {
var result;
before(function () {
function x() {
return 'hello" I am a string\'s for sure';
}
result = singleQuote(x.toString().replace(/\r/g, ''));
});
it('should return code with single quotes string', function () {
function x() {
return 'hello" I am a string\'s for sure';
}
expect(result, result).to.equal(x.toString().replace(/\r/g, ''));
});
});
describe('singlequote already single quoted string', function () {
var result;
before(function () {
function x() {
return 'when customer payment term is "dueDate"';
}
result = singleQuote(x.toString());
});
it('should return code with single quotes string', function () {
function x() {
return 'when customer payment term is "dueDate"';
}
expect(result, result).to.equal(x.toString());
});
});
describe('singlequote with tab in string', function () {
var code, result;
before(function () {
code = 'var x="\t"';
result = singleQuote(code);
});
it('should return code with tab in string', function () {
expect(result, result).to.equal('var x=\'\t\'');
});
});
describe('singlequote with \\t in string', function () {
var code, result;
before(function () {
code = 'var x="\\t"';
result = singleQuote(code);
});
it('should return code with \\t in string', function () {
expect(result, result).to.equal('var x=\'\\t\'');
});
});
describe('singlequote with #!/usr/bin/env node', function () {
var result;
before(function () {
function x() {
return 'hello" I am a string\'s for sure';
}
result = singleQuote('#!/usr/bin/env node\n' + x.toString().replace(/\r/g, ''));
});
it('should return code with single quotes string', function () {
function x() {
return 'hello" I am a string\'s for sure';
}
expect(result, result).to.equal('#!/usr/bin/env node\n' + x.toString().replace(/\r/g, ''));
});
});
describe('singlequote code with UTF-8 Byte Order Mark and #!/usr/bin/env node', function () {
var result;
before(function () {
function x() {
return 'hello" I am a string\'s for sure';
}
result = singleQuote('\ufeff#!/usr/bin/env node\n' + x.toString().replace(/\r/g, ''));
});
it('should return code with single quotes string', function () {
function x() {
return 'hello" I am a string\'s for sure';
}
expect(result, result).to.equal('\ufeff#!/usr/bin/env node\n' + x.toString().replace(/\r/g, ''));
});
});
describe('singlequote code with return-statment in main cod (allowed in node.js)', function () {
var code, result;
before(function () {
code = 'var x=3;\nreturn;';
result = singleQuote(code);
});
it('should return code with \\t in string', function () {
expect(result, result).to.equal(code);
});
}); | ebdrup/singlequote | test/basic.spec.js | JavaScript | apache-2.0 | 3,283 |
/**
* Copyright 2013-2017 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see http://www.jhipster.tech/
* for more information.
*
* 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.
*/
/* eslint-disable consistent-return */
const chalk = require('chalk');
const _ = require('lodash');
const BaseGenerator = require('../generator-base');
const prompts = require('./prompts');
const writeAngularFiles = require('./files-angular').writeFiles;
const writeAngularJsFiles = require('./files-angularjs').writeFiles;
const writeReactFiles = require('./files-react').writeFiles;
const packagejs = require('../../package.json');
const constants = require('../generator-constants');
let useBlueprint;
module.exports = class extends BaseGenerator {
constructor(args, opts) {
super(args, opts);
this.configOptions = this.options.configOptions || {};
// This adds support for a `--protractor` flag
this.option('protractor', {
desc: 'Enable protractor tests',
type: Boolean,
defaults: false
});
// This adds support for a `--uaa-base-name` flag
this.option('uaa-base-name', {
desc: 'Provide the name of UAA server, when using --auth uaa',
type: String
});
// This adds support for a `--build` flag
this.option('build', {
desc: 'Provide build tool for the application',
type: String
});
// This adds support for a `--websocket` flag
this.option('websocket', {
desc: 'Provide websocket option for the application',
type: String
});
// This adds support for a `--auth` flag
this.option('auth', {
desc: 'Provide authentication type for the application',
type: String
});
// This adds support for a `--db` flag
this.option('db', {
desc: 'Provide DB name for the application',
type: String
});
// This adds support for a `--social` flag
this.option('social', {
desc: 'Provide development DB option for the application',
type: Boolean,
default: false
});
// This adds support for a `--search-engine` flag
this.option('search-engine', {
desc: 'Provide development DB option for the application',
type: String
});
// This adds support for a `--search-engine` flag
this.option('hb-cache', {
desc: 'Provide hibernate cache option for the application',
type: String
});
// This adds support for a `--jhi-prefix` flag
this.option('jhi-prefix', {
desc: 'Add prefix before services, controllers and states name',
type: String,
defaults: 'jhi'
});
// This adds support for a `--skip-user-management` flag
this.option('skip-user-management', {
desc: 'Skip the user management module during app generation',
type: Boolean,
defaults: false
});
// This adds support for a `--npm` flag
this.option('npm', {
desc: 'Use npm instead of yarn',
type: Boolean,
defaults: false
});
// This adds support for a `--experimental` flag which can be used to enable experimental features
this.option('experimental', {
desc: 'Enable experimental features. Please note that these features may be unstable and may undergo breaking changes at any time',
type: Boolean,
defaults: false
});
this.setupClientOptions(this);
const blueprint = this.options.blueprint || this.configOptions.blueprint || this.config.get('blueprint');
useBlueprint = this.composeBlueprint(blueprint, 'client'); // use global variable since getters dont have access to instance property
}
get initializing() {
if (useBlueprint) return;
return {
displayLogo() {
if (this.logo) {
this.printJHipsterLogo();
}
},
setupClientconsts() {
// Make constants available in templates
this.MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
this.TEST_SRC_DIR = constants.CLIENT_TEST_SRC_DIR;
this.serverPort = this.config.get('serverPort') || this.configOptions.serverPort || 8080;
this.applicationType = this.config.get('applicationType') || this.configOptions.applicationType;
if (!this.applicationType) {
this.applicationType = 'monolith';
}
this.clientFramework = this.config.get('clientFramework');
if (!this.clientFramework) {
/* for backward compatibility */
this.clientFramework = 'angular1';
}
if (this.clientFramework === 'angular2') {
/* for backward compatibility */
this.clientFramework = 'angularX';
}
this.useSass = this.config.get('useSass');
this.enableTranslation = this.config.get('enableTranslation'); // this is enabled by default to avoid conflicts for existing applications
this.nativeLanguage = this.config.get('nativeLanguage');
this.languages = this.config.get('languages');
this.enableI18nRTL = this.isI18nRTLSupportNecessary(this.languages);
this.messageBroker = this.config.get('messageBroker');
this.packagejs = packagejs;
const baseName = this.config.get('baseName');
if (baseName) {
this.baseName = baseName;
}
const clientConfigFound = this.useSass !== undefined;
if (clientConfigFound) {
// If translation is not defined, it is enabled by default
if (this.enableTranslation === undefined) {
this.enableTranslation = true;
}
if (this.nativeLanguage === undefined) {
this.nativeLanguage = 'en';
}
if (this.languages === undefined) {
this.languages = ['en', 'fr'];
}
this.existingProject = true;
}
if (!this.clientPackageManager) {
if (this.useYarn) {
this.clientPackageManager = 'yarn';
} else {
this.clientPackageManager = 'npm';
}
}
},
validateSkipServer() {
if (this.skipServer && !(this.databaseType && this.devDatabaseType && this.prodDatabaseType && this.authenticationType)) {
this.error(`When using skip-server flag, you must pass a database option and authentication type using ${chalk.yellow('--db')} and ${chalk.yellow('--auth')} flags`);
}
}
};
}
get prompting() {
if (useBlueprint) return;
return {
askForModuleName: prompts.askForModuleName,
askForClient: prompts.askForClient,
askForClientSideOpts: prompts.askForClientSideOpts,
askFori18n: prompts.askFori18n,
setSharedConfigOptions() {
this.configOptions.clientFramework = this.clientFramework;
this.configOptions.useSass = this.useSass;
}
};
}
get configuring() {
if (useBlueprint) return;
return {
insight() {
const insight = this.insight();
insight.trackWithEvent('generator', 'client');
insight.track('app/clientFramework', this.clientFramework);
insight.track('app/useSass', this.useSass);
insight.track('app/enableTranslation', this.enableTranslation);
insight.track('app/nativeLanguage', this.nativeLanguage);
insight.track('app/languages', this.languages);
},
configureGlobal() {
// Application name modified, using each technology's conventions
this.camelizedBaseName = _.camelCase(this.baseName);
this.angularAppName = this.getAngularAppName();
this.angularXAppName = this.getAngularXAppName();
this.capitalizedBaseName = _.upperFirst(this.baseName);
this.dasherizedBaseName = _.kebabCase(this.baseName);
this.lowercaseBaseName = this.baseName.toLowerCase();
if (!this.nativeLanguage) {
// set to english when translation is set to false
this.nativeLanguage = 'en';
}
},
saveConfig() {
this.config.set('jhipsterVersion', packagejs.version);
this.config.set('baseName', this.baseName);
this.config.set('clientFramework', this.clientFramework);
this.config.set('useSass', this.useSass);
this.config.set('enableTranslation', this.enableTranslation);
if (this.enableTranslation && !this.configOptions.skipI18nQuestion) {
this.config.set('nativeLanguage', this.nativeLanguage);
this.config.set('languages', this.languages);
}
this.config.set('clientPackageManager', this.clientPackageManager);
if (this.skipServer) {
this.authenticationType && this.config.set('authenticationType', this.authenticationType);
this.uaaBaseName && this.config.set('uaaBaseName', this.uaaBaseName);
this.hibernateCache && this.config.set('hibernateCache', this.hibernateCache);
this.websocket && this.config.set('websocket', this.websocket);
this.databaseType && this.config.set('databaseType', this.databaseType);
this.devDatabaseType && this.config.set('devDatabaseType', this.devDatabaseType);
this.prodDatabaseType && this.config.set('prodDatabaseType', this.prodDatabaseType);
this.searchEngine && this.config.set('searchEngine', this.searchEngine);
this.buildTool && this.config.set('buildTool', this.buildTool);
}
}
};
}
get default() {
if (useBlueprint) return;
return {
getSharedConfigOptions() {
if (this.configOptions.hibernateCache) {
this.hibernateCache = this.configOptions.hibernateCache;
}
if (this.configOptions.websocket !== undefined) {
this.websocket = this.configOptions.websocket;
}
if (this.configOptions.clientFramework) {
this.clientFramework = this.configOptions.clientFramework;
}
if (this.configOptions.databaseType) {
this.databaseType = this.configOptions.databaseType;
}
if (this.configOptions.devDatabaseType) {
this.devDatabaseType = this.configOptions.devDatabaseType;
}
if (this.configOptions.prodDatabaseType) {
this.prodDatabaseType = this.configOptions.prodDatabaseType;
}
if (this.configOptions.messageBroker !== undefined) {
this.messageBroker = this.configOptions.messageBroker;
}
if (this.configOptions.searchEngine !== undefined) {
this.searchEngine = this.configOptions.searchEngine;
}
if (this.configOptions.buildTool) {
this.buildTool = this.configOptions.buildTool;
}
if (this.configOptions.enableSocialSignIn !== undefined) {
this.enableSocialSignIn = this.configOptions.enableSocialSignIn;
}
if (this.configOptions.authenticationType) {
this.authenticationType = this.configOptions.authenticationType;
}
if (this.configOptions.otherModules) {
this.otherModules = this.configOptions.otherModules;
}
if (this.configOptions.testFrameworks) {
this.testFrameworks = this.configOptions.testFrameworks;
}
this.protractorTests = this.testFrameworks.includes('protractor');
if (this.configOptions.enableTranslation !== undefined) {
this.enableTranslation = this.configOptions.enableTranslation;
}
if (this.configOptions.nativeLanguage !== undefined) {
this.nativeLanguage = this.configOptions.nativeLanguage;
}
if (this.configOptions.languages !== undefined) {
this.languages = this.configOptions.languages;
this.enableI18nRTL = this.isI18nRTLSupportNecessary(this.languages);
}
if (this.configOptions.uaaBaseName !== undefined) {
this.uaaBaseName = this.configOptions.uaaBaseName;
}
// Make dist dir available in templates
if (this.configOptions.buildTool === 'maven') {
this.BUILD_DIR = 'target/';
} else {
this.BUILD_DIR = 'build/';
}
this.styleSheetExt = this.useSass ? 'scss' : 'css';
this.pkType = this.getPkType(this.databaseType);
this.apiUrlPrefix = `${this.authenticationType === 'uaa' ? `'${this.uaaBaseName.toLowerCase()}/` : 'SERVER_API_URL + \''}`;
this.apiUaaUrlPrefix = `${this.authenticationType === 'uaa' ? `${this.uaaBaseName.toLowerCase()}/` : ''}`;
this.apiServerUrlPrefix = `${this.authenticationType !== 'uaa' ? 'SERVER_API_URL + \'' : '\''}`;
this.DIST_DIR = this.BUILD_DIR + constants.CLIENT_DIST_DIR;
},
composeLanguages() {
if (this.configOptions.skipI18nQuestion) return;
this.composeLanguagesSub(this, this.configOptions, 'client');
}
};
}
writing() {
if (useBlueprint) return;
switch (this.clientFramework) {
case 'angular1':
return writeAngularJsFiles.call(this);
case 'react':
return writeReactFiles.call(this);
default:
return writeAngularFiles.call(this);
}
}
install() {
if (useBlueprint) return;
let logMsg =
`To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install`)}`;
if (this.clientFramework === 'angular1') {
logMsg =
`To install your dependencies manually, run: ${chalk.yellow.bold(`${this.clientPackageManager} install & bower install`)}`;
}
const installConfig = {
bower: this.clientFramework === 'angular1',
npm: this.clientPackageManager !== 'yarn',
yarn: this.clientPackageManager === 'yarn'
};
if (this.options['skip-install']) {
this.log(logMsg);
} else {
this.installDependencies(installConfig).then(
() => {
if (this.clientFramework === 'angular1') {
this.spawnCommandSync('gulp', ['install']);
} else {
this.spawnCommandSync(this.clientPackageManager, ['run', 'webpack:build']);
}
},
(err) => {
this.warning('Install of dependencies failed!');
this.log(logMsg);
}
);
}
}
end() {
if (useBlueprint) return;
this.log(chalk.green.bold('\nClient application generated successfully.\n'));
let logMsg =
`Start your Webpack development server with:\n ${chalk.yellow.bold(`${this.clientPackageManager} start`)}\n`;
if (this.clientFramework === 'angular1') {
logMsg =
'Inject your front end dependencies into your source code:\n' +
` ${chalk.yellow.bold('gulp inject')}\n\n` +
'Generate the AngularJS constants:\n' +
` ${chalk.yellow.bold('gulp ngconstant:dev')}` +
`${this.useSass ? '\n\nCompile your Sass style sheets:\n\n' +
`${chalk.yellow.bold('gulp sass')}` : ''}\n\n` +
'Or do all of the above:\n' +
` ${chalk.yellow.bold('gulp install')}\n`;
}
this.log(chalk.green(logMsg));
}
};
| deepu105/generator-jhipster | generators/client/index.js | JavaScript | apache-2.0 | 17,806 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 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 isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isCollection = require( '@stdlib/assert/is-collection' );
var isTypedArrayLike = require( '@stdlib/assert/is-typed-array-like' );
var isArrayBuffer = require( '@stdlib/assert/is-arraybuffer' );
var isComplex64Array = require( '@stdlib/assert/is-complex64array' );
var isComplex128Array = require( '@stdlib/assert/is-complex128array' );
var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-nonenumerable-read-only-accessor' );
var ctors = require( '@stdlib/array/typed-ctors' );
var reinterpret64 = require( '@stdlib/strided/base/reinterpret-complex64' );
var reinterpret128 = require( '@stdlib/strided/base/reinterpret-complex128' );
var arraylike2object = require( '@stdlib/array/base/arraylike2object' );
var copy = require( '@stdlib/utils/copy' );
var ArrayBuffer = require( '@stdlib/array/buffer' );
var ceil = require( '@stdlib/math/base/special/ceil' );
var floor = require( '@stdlib/math/base/special/floor' );
var ceil2 = require( '@stdlib/math/base/special/ceil2' );
var log2 = require( '@stdlib/math/base/special/log2' );
var min = require( '@stdlib/math/base/special/min' );
var defaults = require( './defaults.json' );
var validate = require( './validate.js' );
var createPool = require( './pool.js' );
var BYTES_PER_ELEMENT = require( './bytes_per_element.json' );
// VARIABLES //
var Complex64Array = ctors( 'complex64' );
var Complex128Array = ctors( 'complex128' );
// FUNCTIONS //
/**
* Tests whether an array is a single-precision complex floating-point number array.
*
* @private
* @param {Collection} arr - input array
* @returns {boolean} boolean indicating whether an input array is a single-precision complex floating-point number array
*/
function isCmplx64Array( arr ) {
return ( arr instanceof Complex64Array );
}
/**
* Tests whether an array is a double-precision complex floating-point number array.
*
* @private
* @param {Collection} arr - input array
* @returns {boolean} boolean indicating whether an input array is a double-precision complex floating-point number array
*/
function isCmplx128Array( arr ) {
return ( arr instanceof Complex128Array );
}
// MAIN //
/**
* Creates a typed array pool.
*
* @param {Options} [options] - pool options
* @param {NonNegativeInteger} [options.highWaterMark] - maximum total memory which can be allocated
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {Function} allocator
*
* @example
* var typedarraypool = factory();
*
* // Allocate an array of doubles:
* var arr = typedarraypool( 5, 'float64' );
* // returns <Float64Array>[ 0.0, 0.0, 0.0, 0.0, 0.0 ]
*
* arr[ 0 ] = 3.14;
* arr[ 1 ] = 3.14;
*
* // ...
*
* // Free the allocated memory to be used in a future allocation:
* typedarraypool.free( arr );
*/
function factory( options ) {
var nbytes;
var pool;
var opts;
var err;
opts = copy( defaults );
if ( arguments.length ) {
err = validate( opts, options );
if ( err ) {
throw err;
}
}
pool = createPool( ceil( log2( opts.highWaterMark ) ) );
nbytes = 0;
setReadOnly( malloc, 'malloc', malloc ); // circular reference
setReadOnly( malloc, 'calloc', calloc );
setReadOnly( malloc, 'free', free );
setReadOnly( malloc, 'clear', clear );
setReadOnly( malloc, 'highWaterMark', opts.highWaterMark );
setReadOnlyAccessor( malloc, 'nbytes', getBytes );
return malloc;
/**
* Returns the number of allocated bytes.
*
* @private
* @returns {NonNegativeInteger} number of allocated bytes
*/
function getBytes() {
return nbytes;
}
/**
* Returns an array buffer.
*
* @private
* @param {NonNegativeInteger} n - number of bytes
* @returns {(ArrayBuffer|null)} array buffer or null
*/
function arraybuffer( n ) {
var buf;
var i;
// Convert the number of bytes to an index in our pool table:
i = log2( n );
// If we already have an available array buffer, use it...
if ( i < pool.length && pool[ i ].length ) {
return pool[ i ].pop();
}
// Before allocating a new array buffer, ensure that we have not exceeded the maximum number of bytes we are allowed to allocate...
if ( nbytes+n > opts.highWaterMark ) {
return null;
}
buf = new ArrayBuffer( n );
// Update the running counter of allocated bytes:
nbytes += n;
return buf;
}
/**
* Returns a typed array.
*
* @private
* @param {Function} ctor - typed array constructor
* @param {NonNegativeInteger} len - view length
* @param {string} dtype - data type
* @returns {(TypedArray|null)} typed array or null
*/
function typedarray( ctor, len, dtype ) {
var buf;
if ( len === 0 ) {
return new ctor( 0 );
}
buf = arraybuffer( ceil2( len )*BYTES_PER_ELEMENT[ dtype ] );
if ( buf === null ) {
return buf;
}
return new ctor( buf, 0, len );
}
/**
* Returns an uninitialized typed array.
*
* ## Notes
*
* - Memory is **not** initialized.
* - Memory is lazily allocated.
* - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory).
*
* @private
* @param {(NonNegativeInteger|Collection)} [arg] - an array length or an array-like object
* @param {string} [dtype="float64"] - data type
* @throws {TypeError} must provide a valid array length or an array-like object
* @throws {TypeError} must provide a recognized data type
* @returns {(TypedArray|null)} typed array or null
*/
function malloc() {
var nargs;
var dtype;
var ctor;
var arr;
var out;
var set;
var get;
var len;
var i;
nargs = arguments.length;
if ( nargs && isString( arguments[ nargs-1 ] ) ) {
nargs -= 1;
dtype = arguments[ nargs ];
} else {
dtype = 'float64';
}
ctor = ctors( dtype );
if ( ctor === null ) {
throw new TypeError( 'invalid argument. Must provide a recognized data type. Value: `'+dtype+'`.' );
}
if ( nargs <= 0 ) {
return new ctor( 0 );
}
// Check if provided a typed array length...
if ( isNonNegativeInteger( arguments[ 0 ] ) ) {
return typedarray( ctor, arguments[ 0 ], dtype );
}
// Check if provided an array-like object containing data elements...
if ( isCollection( arguments[ 0 ] ) ) {
arr = arguments[ 0 ];
len = arr.length;
if ( isComplex128Array( arr ) ) {
arr = reinterpret128( arr, 0 );
} else if ( isComplex64Array( arr ) ) {
arr = reinterpret64( arr, 0 );
} else if ( /^complex/.test( dtype ) ) {
// Assume we've been provided an array of interleaved real and imaginary components...
len /= 2;
}
out = typedarray( ctor, len, dtype );
if ( out === null ) {
return out;
}
if ( isCmplx128Array( out ) || isCmplx64Array( out ) ) {
out.set( arr );
return out;
}
// Wrap the arrays in order to account for the possibility that `arr` is a complex number array. As we don't prohibit other "unsafe" casts (e.g., providing a `Float64Array` and specifying a `dtype` of `uint8`), we don't prohibit providing a complex number array and specifying a real `dtype`. The results will probably be unexpected/gibberish, but I am not sure we should be overly pedantic in ensuring user's don't do ill-advised things...
get = arraylike2object( arr ).getter;
set = arraylike2object( out ).setter;
for ( i = 0; i < len; i++ ) {
set( out, i, get( arr, i ) );
}
return out;
}
throw new TypeError( 'invalid argument. First argument must be either an array length or an array-like object. Value: `'+arguments[ 0 ]+'`.' );
}
/**
* Returns a zero-initialized typed array.
*
* ## Notes
*
* - If the function returns `null`, the function was unable to allocate a new typed array from the typed array pool (most likely due to insufficient memory).
*
* @private
* @param {NonNegativeInteger} [len=0] - array length
* @param {string} [dtype="float64"] - data type
* @throws {TypeError} must provide a valid array length
* @throws {TypeError} must provide a recognized data type
* @returns {(TypedArray|null)} typed array or null
*/
function calloc() {
var nargs;
var out;
var tmp;
var i;
nargs = arguments.length;
if ( nargs === 0 ) {
out = malloc();
} else if ( nargs === 1 ) {
out = malloc( arguments[ 0 ] );
} else {
out = malloc( arguments[ 0 ], arguments[ 1 ] );
}
if ( out !== null ) {
// Initialize the memory...
if ( isCmplx128Array( out ) ) {
tmp = reinterpret128( out, 0 );
} else if ( isCmplx64Array( out ) ) {
tmp = reinterpret64( out, 0 );
} else {
tmp = out;
}
for ( i = 0; i < tmp.length; i++ ) {
tmp[ i ] = 0.0;
}
}
return out;
}
/**
* Frees a typed array or typed array buffer.
*
* ## Notes
*
* - Implicitly, we support providing non-internally allocated arrays and array buffer (e.g., "freeing" a typed array allocated in userland); however, the freed array buffer is likely to have excess capacity when compared to other members in its pool.
*
* @private
* @param {(TypedArray|ArrayBuffer)} buf - typed array or array buffer to free
* @throws {TypeError} must provide a typed array or typed array buffer
* @returns {boolean} boolean indicating whether the typed array or array buffer was successfully freed
*/
function free( buf ) {
var n;
var p;
var i;
if ( isTypedArrayLike( buf ) && buf.buffer ) {
buf = buf.buffer;
} else if ( !isArrayBuffer( buf ) ) {
throw new TypeError( 'invalid argument. Must provide a typed array or typed array buffer. Value: `'+buf+'`.' );
}
if ( buf.byteLength > 0 ) {
n = floor( log2( buf.byteLength ) );
// Prohibit "freeing" array buffers which would potentially allow users to circumvent high water mark limits:
n = min( pool.length-1, n );
// Ensure that we do not attempt to free the same buffer more than once...
p = pool[ n ];
for ( i = 0; i < p.length; i++ ) {
if ( p[ i ] === buf ) {
return false;
}
}
// Add the buffer to our pool of free buffers:
p.push( buf );
}
return true;
}
/**
* Clears the typed array pool allowing garbage collection of previously allocated (and currently free) array buffers.
*
* @private
*/
function clear() {
var i;
for ( i = 0; i < pool.length; i++ ) {
pool[ i ].length = 0;
}
nbytes = 0;
}
}
// EXPORTS //
module.exports = factory;
| stdlib-js/stdlib | lib/node_modules/@stdlib/array/pool/lib/factory.js | JavaScript | apache-2.0 | 11,150 |
var notifyDesktop = function(msg, link) {
$.notify(msg, 'info');
var doNotification = function() {
var options = {
body: 'Notification from knowledge.',
icon: _CONTEXT + '/favicon.ico'
};
var n = new Notification(msg, options);
n.onclick = function() {
window.location.href = link;
};
};
checkPermission().then(function(result) {
if (result) {
doNotification();
}
});
};
var checkPermission = function() {
return Promise.try(function() {
if (window.Notification) {
if (Notification.permission === 'granted') {
console.log('Notification.permission is granted');
return Promise.resolve(true);
} else if (Notification.permission === 'denied') {
console.log('Notification.permission is denied');
Notification.requestPermission(function(result) {
if (result === 'denied') {
console.log('requestPermission is denied');
return Promise.resolve(false);
} else if (result === 'default') {
console.log('requestPermission is default');
return Promise.resolve(false);
} else if (result === 'granted') {
console.log('requestPermission is granted');
return Promise.resolve(true);
}
});
} else if (Notification.permission === 'default') {
console.log('Notification.permission is default');
Notification.requestPermission(function(result) {
if (result === 'denied') {
console.log('requestPermission is denied');
return Promise.resolve(false);
} else if (result === 'default') {
console.log('requestPermission is default');
return Promise.resolve(false);
} else if (result === 'granted') {
console.log('requestPermission is granted');
return Promise.resolve(true);
}
});
}
} else {
console.log('Notification is not available');
return Promise.resolve(false);
}
});
};
var webSocket;
window.onload = function() {
checkPermission();
var forRtoA = document.createElement('a');
forRtoA.href = _CONTEXT + '/notify';
console.log(forRtoA.href.replace("http://", "ws://").replace("https://",
"wss://"));
webSocket = new WebSocket(forRtoA.href.replace("http://", "ws://").replace(
"https://", "wss://"));
webSocket.onopen = function() {
}
webSocket.onclose = function() {
}
webSocket.onmessage = function(message) {
console.log('[RECEIVE] ');
var result = JSON.parse(message.data);
console.log(result);
notifyDesktop(result.message, result.result);
}
webSocket.onerror = function(message) {
}
setInterval(function() {
console.log('interval connection check');
webSocket.send('a');
}, 1000 * 60 * 4); // 3分に1回通信する(ALBのタイムアウトを300秒に設定していると、コネクションを切ってしまう)
};
| support-project/knowledge | src/main/webapp/js/notification.js | JavaScript | apache-2.0 | 3,455 |
'use strict';
const chai = require('chai');
const assert = chai.assert;
const extensions = require('../../lib/extensions');
describe('Extensions Tests', function () {
const noop = function () {
return undefined;
};
const noop2 = function () {
return undefined;
};
describe('add', function () {
it('undefined', function () {
const output = extensions.add();
assert.isFalse(output);
});
it('missing type', function () {
const output = extensions.add(undefined, 'myfunc', noop);
assert.isFalse(output);
});
it('type not string', function () {
const output = extensions.add(123, 'myfunc', noop);
assert.isFalse(output);
});
it('invalid type', function () {
const output = extensions.add('test', 'myfunc', noop);
assert.isFalse(output);
});
it('missing name', function () {
const output = extensions.add('connection', undefined, noop);
assert.isFalse(output);
});
it('name not string', function () {
const output = extensions.add('connection', 123, noop);
assert.isFalse(output);
});
it('missing function', function () {
const output = extensions.add('connection', 'myfunc');
assert.isFalse(output);
});
it('invalid function type', function () {
const output = extensions.add('connection', 'myfunc', 123);
assert.isFalse(output);
});
it('valid', function () {
let output = extensions.add('connection', 'myfunc1', noop);
assert.isTrue(output);
output = extensions.add('connection', 'myfunc2', noop2);
assert.isTrue(output);
output = extensions.add('pool', 'myfunc1', noop);
assert.isTrue(output);
assert.isFunction(extensions.extensions.connection.myfunc1);
assert.isFunction(extensions.extensions.connection.myfunc2);
output = extensions.add('connection', 'myfunc2', noop);
assert.isTrue(output);
assert.isFunction(extensions.extensions.connection.myfunc1);
assert.isFunction(extensions.extensions.connection.myfunc2);
assert.isFunction(extensions.get('connection').myfunc1);
assert.isFunction(extensions.get('connection').myfunc2);
assert.isFunction(extensions.get('pool').myfunc1);
});
it('valid, no promise', function () {
let output = extensions.add('connection', 'myfunc1', noop, {
promise: {
noPromise: true
}
});
assert.isTrue(output);
output = extensions.add('connection', 'myfunc2', noop2, {
promise: {
noPromise: true
}
});
assert.isTrue(output);
output = extensions.add('pool', 'myfunc1', noop, {
promise: {
noPromise: true
}
});
assert.isTrue(output);
assert.deepEqual(extensions.extensions.connection, {
myfunc1: noop,
myfunc2: noop2
});
output = extensions.add('connection', 'myfunc2', noop, {
promise: {
noPromise: true
}
});
assert.isTrue(output);
assert.deepEqual(extensions.extensions.connection, {
myfunc1: noop,
myfunc2: noop
});
assert.deepEqual(extensions.get('connection'), {
myfunc1: noop,
myfunc2: noop
});
assert.deepEqual(extensions.get('pool'), {
myfunc1: noop
});
});
});
describe('get', function () {
it('undefined', function () {
const output = extensions.get();
assert.isUndefined(output);
});
it('null', function () {
const output = extensions.get(null);
assert.isUndefined(output);
});
it('empty', function () {
extensions.extensions.connection = {};
const output = extensions.get('connection');
assert.deepEqual(output, {});
});
it('functions exist', function () {
extensions.extensions.connection = {
test: noop,
test2: noop2
};
const output = extensions.get('connection');
assert.deepEqual(output, {
test: noop,
test2: noop2
});
});
});
});
| sagiegurari/simple-oracledb | test/spec/extensions-spec.js | JavaScript | apache-2.0 | 4,815 |
/* Typechecking With PropTypes
As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like Flow or
TypeScript to typecheck your whole application. But even if you don’t use those, React has some built-in typechecking abilities. To run
typechecking on the props for a component, you can assign the special propTypes property:'PropTypes' allow us to supply a property type
for all of our different properties, so that it will validate to
make sure that we're supplying the right type.
Note: For performance reasons, propTypes is only checked in development mode.
NOTENOTE: React.PropTypes has moved into a different package since React v15.5. Please use the "prop-types" library instead.
primitives:
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalSymbol: React.PropTypes.symbol,
PropTypes.instanceOf(Date) //for date objects
There are many more complex data types: https://facebook.github.io/react/docs/typechecking-with-proptypes.html
*/
/* Type 1: Creating Components using Class */
(SkiDayCount-createClass.js)
import { createClass, PropTypes } from 'react'
//Just after `export const SkiDayCount = createClass({` and before `getDefaultProps() {`
propTypes: {
total: PropTypes.number.isRequired, //make sure a warning is shown if the prop isn't provided. (if defaults are there,this will never give a warning)
powder: PropTypes.number,
backcountry: PropTypes.number
},
//note that we've destructured PropTypes from 'react'. Hadn't we done that, we should use React.propTypes.number etc
(index.js)
import { SkiDayCount } from './components/SkiDayCount-createClass.js'
render(
<SkiDayCount total="lots" />, //we're intentionally giving wrong type(string) to `total` (which shuld have number type)
document.getElementById('react-container')
)
//Once you run, You'll see that it will still render but in console, you will get a warning!
/* Type-2: Using ES6 Syntax */
(in SkiDayCount-ES6.js)
import { Component, PropTypes } from 'react'
//completely outside the class definition
SkiDayCount.propTypes = {
total: PropTypes.number,
powder: PropTypes.number,
backcountry: PropTypes.number
}
(in index.js)
import { SkiDayCount } from './components/SkiDayCount-ES6.js'
render( //supplied wrong type(boolean) instead of number
<SkiDayCount backcountry={false} />,
document.getElementById('react-container')
)
/* Type-3: Statless Function Types */
(in SkiDay.js)
import { PropTypes } from 'react'
//completely outside the class definition
SkiDayCount.propTypes = {
total: PropTypes.number,
powder: PropTypes.number,
backcountry: PropTypes.number
}
(in index.js)
import { SkiDayCount } from './components/SkiDayCount'
render(
<SkiDayCount backcountry={false} />,
document.getElementById('react-container')
)
| iitjee/SteppinsWebDev | React/08 Prop Types.js | JavaScript | apache-2.0 | 3,584 |
const { spawn } = require('child_process')
module.exports = function myExec(cmd, ...args) {
return new Promise((resolve, reject) => {
const run = spawn(cmd, args)
let out = ''
run.stdout.on('data', (data) => {
console.log(`[stdout]: ${data.toString().trimEnd()}`)
out += data.toString()
})
run.stderr.on('data', (data) => {
console.log(`[stderr]: ${data.toString().trimEnd()}`)
})
run.on('exit', function (code) {
console.log('child process exited with code ' + code.toString())
if (code === 0) {
resolve(out)
} else {
reject(code)
}
})
})
}
| oldj/SwitchHosts | scripts/libs/my_exec.js | JavaScript | apache-2.0 | 641 |
'use strict';
exports.__esModule = true;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIntl = require('react-intl');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ModalCloseButton = function (_Component) {
_inherits(ModalCloseButton, _Component);
function ModalCloseButton(props) {
_classCallCheck(this, ModalCloseButton);
var _this = _possibleConstructorReturn(this, _Component.call(this, props));
_this.handleClick = _this.handleClick.bind(_this);
return _this;
}
ModalCloseButton.prototype.handleClick = function handleClick() {
this.props.onClick();
};
ModalCloseButton.prototype.render = function render() {
return _react2.default.createElement(
'div',
{ className: 'modal__close-button', onClick: this.handleClick },
_react2.default.createElement(
'i',
{ className: 'close_icon material-icons' },
'close'
),
_react2.default.createElement(
'div',
{ className: 'text' },
_react2.default.createElement(_reactIntl.FormattedMessage, { id: 'button.close' })
)
);
};
return ModalCloseButton;
}(_react.Component);
ModalCloseButton.propTypes = {
onClick: _react.PropTypes.func.isRequired
};
exports.default = ModalCloseButton;
//# sourceMappingURL=ModalCloseButton.react.js.map | EaglesoftZJ/iGem_Web | build/components/modals/ModalCloseButton.react.js | JavaScript | apache-2.0 | 2,305 |
/*
* Copyright (C) 2015 City of Lund (Lunds kommun)
*
* 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.
*/
app.Plugin = L.Class.extend({
name: null, // same as the class name
type: null,
copyright: null,
options: {
styles: {}
},
initialize: function() {}
});
/**
* Static properties and methods
*/
app.Plugin.options = {
walkSpeed: 5, // km/h Affects the calc of energy (kcal)
bikeSpeed: 18, // km/h
tripsPerYear: 440 // number of trips per year (incl. return)
};
app.Plugin.getTypeResult = function() {
return {
time: null, // seconds
distance: null, // meters
costPerTrip: null, // SEK
costPerYear: null, // SEK
co2PerTrip: null, // kg
co2PerYear: null, // kg
kcalYear: null, // kcal per year
kgChok: null, //chocolate per year
copyright: null
}
};
app.Plugin.getTypePath = function() {
return {
coords: typeof coords !== 'undefined' ? coords : [ ],
color: typeof color !== 'undefined' ? color : 'black',
pattern: typeof pattern !== 'undefined' ? pattern : null
}
};
| lundskommun/resejamforaren | rjweb/static/rjweb/plugins/Plugin.js | JavaScript | apache-2.0 | 1,534 |
/**
* @license Apache-2.0
*
* Copyright (c) 2020 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 addon = require( './../src/addon.node' );
// MAIN //
/**
* Fills a double-precision floating-point strided array with a specified scalar constant.
*
* @param {PositiveInteger} N - number of indexed elements
* @param {number} alpha - scalar
* @param {Float64Array} x - input array
* @param {integer} stride - index increment
* @returns {Float64Array} input array
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ -2.0, 1.0, 3.0, -5.0, 4.0, 0.0, -1.0, -3.0 ] );
*
* dfill( x.length, 5.0, x, 1 );
* // x => <Float64Array>[ 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0 ]
*/
function dfill( N, alpha, x, stride ) {
addon( N, alpha, x, stride );
return x;
}
// EXPORTS //
module.exports = dfill;
| stdlib-js/stdlib | lib/node_modules/@stdlib/blas/ext/base/dfill/lib/dfill.native.js | JavaScript | apache-2.0 | 1,396 |
/*!
* ${copyright}
*/
// Provides control sap.m.VBox.
sap.ui.define(['jquery.sap.global', './FlexBox', './library'],
function(jQuery, FlexBox, library) {
"use strict";
/**
* Constructor for a new VBox.
*
* @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
* The VBox control builds the container for a vertical flexible box layout. VBox is a convenience control, as it is just a specialized FlexBox control.<br>
* <br>
* <b>Note:</b> Be sure to check the <code>renderType</code> setting to avoid issues due to browser inconsistencies.
*
* @extends sap.m.FlexBox
*
* @author SAP SE
* @version ${version}
*
* @constructor
* @public
* @alias sap.m.VBox
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var VBox = FlexBox.extend("sap.m.VBox", /** @lends sap.m.VBox.prototype */ { metadata : {
library : "sap.m"
}});
return VBox;
}, /* bExport= */ true);
| olirogers/openui5 | src/sap.m/src/sap/m/VBox.js | JavaScript | apache-2.0 | 1,081 |
// Karma configuration
// Generated on Thu Sep 17 2015 09:48:07 GMT+0530 (IST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
// list of files / patterns to load in the browser
files: [
'../www/lib/angular/angular.js',
'../www/js/*.js',
'../www/lib/angular-mocks/angular-mocks.js',
'**/*tests.js'
],
// Use the PhantomJS browser instead of Chrome
browsers: ['PhantomJS'],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
//browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
| magnusmel/ramisdance | tests/my.conf.js | JavaScript | apache-2.0 | 1,793 |
/* Copyright 2015 Kyle E. Mitchell
*
* 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 concat = require('concat-stream')
var http = require('http')
var merkleize = require('commonform-merkleize')
var series = require('async-series')
var server = require('./server')
var tape = require('tape')
var url = require('url')
tape('POST /callbacks with URL', function(test) {
server(function(port, done) {
http
.request({ method: 'POST', path: '/callbacks', port: port })
.once('response', function(response) {
test.equal(response.statusCode, 202, 'responds 202')
done()
test.end() })
.end('https://somewhere.else/endpoint') }) })
tape('POST /callbacks with bad URL', function(test) {
server(function(port, done) {
http
.request({ method: 'POST', path: '/callbacks', port: port })
.once('response', function(response) {
test.equal(response.statusCode, 400, 'responds 400')
done()
test.end() })
.end('blah blah blah') }) })
tape('GET /callbacks', function(test) {
server(function(port, done) {
var request = { method: 'GET', path: '/callbacks', port: port }
http.request(request, function(response) {
test.equal(response.statusCode, 405, 'responds 405')
done()
test.end() })
.end() }) })
tape('callback on POST /forms', function(test) {
test.plan(3)
var form = { content: [ 'Some text' ] }
var digest = merkleize(form).digest
var endpoint = '/x'
var calledback = http
.createServer()
.on('request', function(request, response) {
var parsed = url.parse(request.url)
var path = parsed.pathname
var callback = ( request.method === 'POST' && path === endpoint )
if (callback) {
request.pipe(concat(function(buffer) {
test.equal(
buffer.toString(), digest,
'called back with digest')
response.end()
calledback.close() } )) }
else {
throw new Error() } })
.listen(0, function() {
var calledbackPort = this.address().port
var callbackURL = ( 'http://localhost:' + calledbackPort + endpoint )
server(function(port, done) {
series(
[ function(done) {
http
.request({ method: 'POST', path: '/callbacks', port: port })
.once('response', function(response) {
test.equal(response.statusCode, 202, 'registered')
done() })
.once('error', done)
.end(callbackURL) },
function(done) {
http
.request({ method: 'POST', path: '/forms', port: port })
.once('response', function(response) {
test.equal(response.statusCode, 201, 'posted form')
done() })
.once('error', done)
.end(JSON.stringify(form)) },
function () {
done() } ],
function(error) {
test.ifError(error)
done() }) }) }) })
tape('no callback on POST /forms with existing form', function(test) {
var form = { content: [ 'Some text' ] }
var calledback = http
.createServer()
.on('request', function(request, response) {
test.equal(true, false, 'no callback request received')
response.end()
calledback.close() })
.listen(0, function() {
var calledbackPort = this.address().port
var callbackURL = ( 'http://localhost:' + calledbackPort + '/x' )
server(function(port, done) {
series(
[ function(done) {
http
.request({ method: 'POST', path: '/forms', port: port })
.once('response', function(response) {
test.equal(response.statusCode, 201, 'posted form')
done() })
.once('error', done)
.end(JSON.stringify(form)) },
function(done) {
http
.request({ method: 'POST', path: '/callbacks', port: port })
.once('response', function(response) {
test.equal(response.statusCode, 202, 'registered')
done() })
.once('error', done)
.end(callbackURL) },
function(done) {
http
.request({ method: 'POST', path: '/forms', port: port })
.once('response', function(response) {
test.equal(response.statusCode, 200, 'posted form')
done() })
.once('error', done)
.end(JSON.stringify(form)) },
function () {
setTimeout(
function() {
calledback.close()
done()
test.end() },
100) } ],
function(error) {
test.ifError(error)
calledback.close()
done() }) }) }) })
| commonform/commonform-serve | test/callbacks.test.js | JavaScript | apache-2.0 | 5,465 |
//>>built
define("dojox/mobile/TreeView","dojo/_base/kernel dojo/_base/array dojo/_base/declare dojo/_base/lang dojo/_base/window dojo/dom-construct dijit/registry ./Heading ./ListItem ./ProgressIndicator ./RoundRectList ./ScrollableView ./viewRegistry dojo/has dojo/has!dojo-bidi?dojox/mobile/bidi/TreeView".split(" "),function(b,r,e,k,l,t,h,u,m,v,n,p,w,q,x){b.experimental("dojox.mobile.TreeView");b=e(q("dojo-bidi")?"dojox.mobile.NonBidiTreeView":"dojox.mobile.TreeView",p,{postCreate:function(){this._load();
this.inherited(arguments)},_customizeListItem:function(a){},_load:function(){this.model.getRoot(k.hitch(this,function(a){var c=this,d=new n;a={label:c.model.rootLabel,moveTo:"#",onClick:function(){c.handleClick(this)},item:a};this._customizeListItem(a);a=new m(a);d.addChild(a);this.addChild(d)}))},handleClick:function(a){var c="view_",c=a.item[this.model.newItemIdAttr]?c+a.item[this.model.newItemIdAttr]:c+"rootView",c=c.replace("/","_");if(h.byId(c))h.byNode(a.domNode).transitionTo(c);else{var d=
v.getInstance();l.body().appendChild(d.domNode);d.start();this.model.getChildren(a.item,k.hitch(this,function(b){var f=this,e=new n;r.forEach(b,function(a,c){var b={item:a,label:a[f.model.store.label],transition:"slide"};f._customizeListItem(b);f.model.mayHaveChildren(a)&&(b.moveTo="#",b.onClick=function(){f.handleClick(this)});b=new m(b);e.addChild(b)});b=new u({label:"Dynamic View",back:"Back",moveTo:w.getEnclosingView(a.domNode).id,dir:this.isLeftToRight()?"ltr":"rtl"});var g=p({id:c,dir:this.isLeftToRight()?
"ltr":"rtl"},t.create("div",null,l.body()));g.addChild(b);g.addChild(e);g.startup();d.stop();h.byNode(a.domNode).transitionTo(g.id)}))}}});return q("dojo-bidi")?e("dojox.mobile.TreeView",[b,x]):b}); | wanglongbiao/webapp-tools | Highlander/ship-gis/src/main/webapp/js/arcgis_js_api/library/3.22/dojox/mobile/TreeView.js | JavaScript | apache-2.0 | 1,731 |
var handlebars = require('handlebars')
, HAProxy = require('haproxy')
, fs = require('fs')
, resolve = require('path').resolve
, util = require('util')
, f = util.format
, assert = require('assert')
, EventEmitter = require('events').EventEmitter
, debounce = require('debounce')
, deepEqual = require('deep-equal')
;
var HAProxyManager = module.exports = function HAProxyManager (opts) {
if (typeof opts !== 'object') opts = {};
assert(opts.data, 'opts.data required');
assert(opts.haproxy, 'opts.haproxy required');
this.config = {};
this.config.templateFile = resolve(opts.templateFile || __dirname + '/../default.haproxycfg.tmpl');
this.config.haproxyCfgPath = resolve(opts.haproxyCfgPath || '/etc/haproxy/haproxy.cfg');
this.config.watchConfigFile = (opts.watchConfigFile !== undefined) ? opts.watchConfigFile : true;
this.config.debounceRate = opts.debounceRate || 2000;
this.log = (typeof opts.log === 'function') ? opts.log : function (){};
this.throttleTimeout = null
this.latestConfig = "";
if (!fs.existsSync(this.config.templateFile)) {
this.log('error', f("template file %s doesn't exists!", this.config.templateFile));
}
this.template = handlebars.compile(fs.readFileSync(this.config.templateFile, 'utf-8'));
this.writeConfigDebounced = debounce(this.writeConfig.bind(this), this.config.debounceRate, false);
this.data = opts.data;
this.haproxy = opts.haproxy;
this.data.frontends.on( 'changes', this._changeFrontEnd.bind(this) );
this.data.backends.on ( 'changes', this._changeBackEnd.bind(this) );
this.writeConfigDebounced();
};
util.inherits(HAProxyManager, EventEmitter);
HAProxyManager.prototype.writeConfig = function() {
var data = {
frontends: this.data.frontends.toJSON(),
backends: this.data.backends.toJSON(),
haproxySocketPath: this.haproxy.socket
};
var previousConfig = this.latestConfig;
this.latestConfig = this.template(data);
// only write the config and reload if it actually changed
if (!deepEqual(previousConfig, this.latestConfig)) {
clearTimeout(this.throttleTimeout);
fs.writeFileSync(this.config.haproxyCfgPath, this.latestConfig , 'utf-8');
this.emit('configChanged');
this.throttledReload();
}
};
HAProxyManager.prototype.throttledReload = function() {
this.throttleTimeout = null;
this.log('info', 'HaproxyManager.throttledReload', 'Scheduling reload of haproxy');
this.throttleTimeout = setTimeout((function() {
this.reload();
}).bind(this), 500);
}
HAProxyManager.prototype.reload = function () {
var self = this;
self.haproxy.running(function (err, running) {
if (err) return self.log('error', 'HaproxyManager.reload', { error: String(err) });
function handleRestart (err) {
if (err) return self.log('error', 'HaproxyManager.reload', { error: String(err) });
}
if (running) {
self.log('info', 'HaproxyManager.reload', 'Reloading haproxy config');
self.haproxy.reload(handleRestart);
} else {
self.log('info', 'HaproxyManager.reload', 'Starting haproxy');
self.haproxy.start(handleRestart);
}
});
};
HAProxyManager.prototype._changeFrontEnd = function(row, changed) {
this.log('debug', 'HaproxyManager._changeFrontEnd', changed);
this.writeConfigDebounced();
};
HAProxyManager.prototype._changeBackEnd = function(row, changed) {
this.log('debug', 'HaproxyManager_changeBackEnd', changed);
this.writeConfigDebounced();
};
//
//
//
//
//
//
//
// TODO refactor all these helper, reconsider business logic
//
// template helper for outputing FrontEnd acl rules
handlebars.registerHelper('aclRule', function (rule) {
var rand = Math.random().toString(36).substring(3);
var name = rule.type + '_' + rand;
if (rule.type === 'path' || rule.type === 'url') {
return util.format("acl %s %s %s\nuse_backend %s if %s\n", name, rule.operation, rule.value, rule.backend, name);
}
else if (rule.type === 'header') {
return util.format("acl %s %s(%s) %s\nuse_backend %s if %s\n", name, rule.operation, rule.header, rule.value, rule.backend, name);
}
});
handlebars.registerHelper('frontendHelper', function (frontend) {
var output = [];
var hasRules = frontend.rules && frontend.rules.length > 0;
var hasNatives = frontend.natives && frontend.natives.length > 0;
output.push("bind " + frontend.bind);
output.push("mode " + frontend.mode);
output.push("default_backend " + frontend.backend);
// http only default options
if (frontend.mode === 'http') {
output.push("option httplog");
// The default keep-alive behavior is to use keep-alive if clients and
// backends support it. However, if haproxy will only process rules when
// a connection is first established so if any rules are used then server-close
// should be specified at least and haproxy will let clients use keep-alive
// to haproxy but close the backend connections each time.
//
// If there are any rules, the default behavior is to use http-server-close
// and http-pretend-keepalive
if (frontend.keepalive === 'server-close') {
output.push("option http-server-close");
output.push("option http-pretend-keepalive");
}
else if (frontend.keepalive === 'close'){
output.push("option forceclose");
}
// the default if there are rules is to use server close
else if (hasRules) {
output.push("option http-server-close");
output.push("option http-pretend-keepalive");
}
}
if (hasRules) {
frontend.rules.forEach(function (rule) {
var rand = Math.random().toString(36).substring(3);
var name = rule.type + '_' + rand;
if (rule.type === 'path' || rule.type === 'url') {
output.push(util.format("acl %s %s %s\nuse_backend %s if %s",
name, rule.operation, rule.value, rule.backend, name));
}
else if (rule.type === 'header') {
output.push(util.format("acl %s %s(%s) %s\nuse_backend %s if %s",
name, rule.operation, rule.header, rule.value, rule.backend, name));
}
});
}
if (hasNatives) {
frontend.natives.forEach(function (native) {
output.push(native);
});
}
return output.join('\n ');
});
// helper to output http check and servers block
handlebars.registerHelper('backendHelper', function (backend) {
var host = backend.host;
var health = backend.health;
var members = backend.members;
var output = [];
var hasNatives = backend.natives && backend.natives.length > 0;
// output mode and balance options
output.push("mode " + backend.mode);
output.push("balance " + backend.balance);
// host header propagation
if (backend.host) {
output.push("reqirep ^Host:\\ .* Host:\\ " + backend.host);
}
// option httpchk
if (backend.mode === 'http' && health) {
var httpVersion = (health.httpVersion === 'HTTP/1.1') ?
('HTTP/1.1\\r\\nHost:\\ ' + backend.host) :
health.httpVersion;
output.push(util.format("option httpchk %s %s %s", health.method, health.uri, httpVersion));
}
if (hasNatives) {
backend.natives.forEach(function (native) {
output.push(native);
});
}
if (members) {
// server lines for each member
members.forEach(function (member) {
var name = util.format("%s_%s:%s", backend.key, member.host, member.port);
var interval = (health) ? health.interval : 2000;
output.push(util.format("server %s %s:%s check inter %s", name, member.host, member.port, interval));
});
}
return output.join('\n ');
});
| apuckey/thalassa-aqueduct | lib/HaproxyManager.js | JavaScript | apache-2.0 | 7,597 |
// HTTP.methods({
// 'api/v1/staffMembers': {
// get: function(data) {
// this.setContentType('application/json');
// var staffMembers = StaffMembers.find();
// var test = [];
// staffMembers.forEach(function(staffMember) {
// test.push(staffMember);
// // // SECOND RUN
// // delete staffMember.animeIdOld;
// // delete staffMember.personIdOld;
// // First RUN
// // var anime = Anime.findOne({id: staffMember.animeIdOld});
// // var person = People.findOne({id: staffMember.personIdOld});
// // if (anime)
// // staffMember.animeId = anime._id;
// // if (person)
// // staffMember.personId = person._id;
// // // Delete the old one and insert a new one
// // StaffMembers.remove(staffMember._id);
// // delete staffMember._id;
// // staffMember.createdAt = new Date();
// // staffMember.updatedAt = new Date();
// // StaffMembers.insert(staffMember);
// });
// return JSON.stringify(test);
// }
// }
// });
| phanime/phanime | server/restapi/legacy/staffMembers.js | JavaScript | apache-2.0 | 1,026 |
(function ($){
$(".social-link").click(function (e) {
var type = $("[name=social_type]:checked").val();
if (!type) return;
var href = this.href;
this.href = href.replace(/next=\/([^\/]+)\/([^\/]+)\/([^\/]+)\//, function (all, action, backend, old_type) {
return "next=/{action}/{backend}/{type}/"
.replace("{action}", action)
.replace("{backend}", backend)
.replace("{type}", type);
});
});
$(".cgu-checkbox").click(function () {
var toggable = $(this).data("toggle");
var $el = $(toggable);
if ($el.attr("disabled")) $el.removeAttr("disabled");
else $el.attr("disabled", "disabled");
});
$(".btn-register").click(function (e) {
var checkbox = $(this).data("checkbox");
var name = ($(this).hasClass("btn-register-social")) ? "social_type" : "type";
function abort () {
e.preventDefault();
e.stopPropagation();
}
if (!assertTypeChecked(name)) {
abort();
var $container = $("[name="+ name +"]").parents(".form-group");
if (!$(".text-danger", $container).length) {
$container.append("<span class='text-danger'>Veuillez sélectionner une valeur.</span>");
}
}
else if (!$(checkbox).is(':checked')) abort();
});
function assertTypeChecked(name) {
if (!$("[type=radio][name="+ name +"]").length) return true;
return $("[name="+ name +"]:checked").length !== 0;
}
})(jQuery);
| huguesmayolle/famille | famille/static/js/register.js | JavaScript | apache-2.0 | 1,594 |
import classNames from "classnames";
import React, { Component } from "react";
import { Tooltip } from "reactjs-components";
import {
FormReducer as ContainerReducer
} from "../../reducers/serviceForm/Container";
import {
FormReducer as ContainersReducer
} from "../../reducers/serviceForm/Containers";
import {
findNestedPropertyInObject
} from "../../../../../../src/js/utils/Util";
import ArtifactsSection from "./ArtifactsSection";
import ContainerConstants from "../../constants/ContainerConstants";
import FieldError from "../../../../../../src/js/components/form/FieldError";
import FieldHelp from "../../../../../../src/js/components/form/FieldHelp";
import FieldInput from "../../../../../../src/js/components/form/FieldInput";
import FieldLabel from "../../../../../../src/js/components/form/FieldLabel";
import FormGroup from "../../../../../../src/js/components/form/FormGroup";
import FormGroupHeadingContent
from "../../../../../../src/js/components/form/FormGroupHeadingContent";
import FormRow from "../../../../../../src/js/components/form/FormRow";
import PodSpec from "../../structs/PodSpec";
const { DOCKER } = ContainerConstants.type;
const containerSettings = {
privileged: {
label: "授予容器特权",
helpText: "默认容器都是非授权的,并且没有特殊权限。比如在一个docker内运行另一个docker.",
dockerOnly: "只有在Docker容器中才支持授予特权操作."
},
forcePullImage: {
label: "启动时强制拉取镜像",
helpText: "在启动每个实例前强制拉取镜像.",
dockerOnly: "启动前强制拉取镜像只在docker容器下才支持."
}
};
const appPaths = {
artifacts: "fetch",
cmd: "cmd",
containerName: "",
cpus: "cpus",
disk: "disk",
forcePullImage: "{basePath}.docker.forcePullImage",
gpus: "gpus",
image: "{basePath}.docker.image",
mem: "mem",
privileged: "{basePath}.docker.privileged",
type: "{basePath}.type"
};
const podPaths = {
artifacts: "{basePath}.artifacts",
cmd: "{basePath}.exec.command.shell",
containerName: "{basePath}.name",
cpus: "{basePath}.resources.cpus",
disk: "{basePath}.resources.disk",
forcePullImage: "",
gpus: "",
image: "{basePath}.image.id",
mem: "{basePath}.resources.mem",
privileged: "",
type: "{basePath}.type"
};
class ContainerServiceFormAdvancedSection extends Component {
getFieldPath(basePath, fieldName) {
if (this.props.service instanceof PodSpec) {
return podPaths[fieldName].replace("{basePath}", basePath);
}
return appPaths[fieldName].replace("{basePath}", basePath);
}
isGpusDisabled() {
const { data, path } = this.props;
const typePath = this.getFieldPath(path, "type");
return findNestedPropertyInObject(data, typePath) === DOCKER;
}
getGPUSField() {
const { data, errors, path, service } = this.props;
if (service instanceof PodSpec) {
return null;
}
const gpusPath = this.getFieldPath(path, "gpus");
const gpusErrors = findNestedPropertyInObject(errors, gpusPath);
const gpusDisabled = this.isGpusDisabled();
let inputNode = (
<FieldInput
disabled={gpusDisabled}
min="0"
name={gpusPath}
step="any"
type="number"
value={findNestedPropertyInObject(data, gpusPath)}
/>
);
if (gpusDisabled) {
inputNode = (
<Tooltip
content="Docker 引擎不支持GPU 资源, 如果想使用GPU资源,请选择 Universal 容器环境."
interactive={true}
maxWidth={300}
scrollContainer=".gm-scroll-view"
wrapText={true}
wrapperClassName="tooltip-wrapper tooltip-block-wrapper"
>
{inputNode}
</Tooltip>
);
}
return (
<FormGroup
className="column-4"
showError={Boolean(!gpusDisabled && gpusErrors)}
>
<FieldLabel className="text-no-transform">
<FormGroupHeadingContent primary={true}>
GPUs
</FormGroupHeadingContent>
</FieldLabel>
{inputNode}
<FieldError>{gpusErrors}</FieldError>
</FormGroup>
);
}
getContainerSettings() {
const { data, errors, path, service } = this.props;
if (service instanceof PodSpec) {
return null;
}
const typePath = this.getFieldPath(path, "type");
const containerType = findNestedPropertyInObject(data, typePath);
const typeErrors = findNestedPropertyInObject(errors, typePath);
const sectionCount = Object.keys(containerSettings).length;
const selections = Object.keys(
containerSettings
).map((settingName, index) => {
const { helpText, label, dockerOnly } = containerSettings[settingName];
const settingsPath = this.getFieldPath(path, settingName);
const checked = findNestedPropertyInObject(data, settingsPath);
const isDisabled = containerType !== DOCKER;
const labelNodeClasses = classNames({
"disabled muted": isDisabled,
"flush-bottom": index === sectionCount - 1
});
let labelNode = (
<FieldLabel key={`label.${index}`} className={labelNodeClasses}>
<FieldInput
checked={!isDisabled && Boolean(checked)}
name={settingsPath}
type="checkbox"
disabled={isDisabled}
value={settingName}
/>
{label}
<FieldHelp>{helpText}</FieldHelp>
</FieldLabel>
);
if (isDisabled) {
labelNode = (
<Tooltip
content={dockerOnly}
key={`tooltip.${index}`}
position="top"
scrollContainer=".gm-scroll-view"
width={300}
wrapperClassName="tooltip-wrapper tooltip-block-wrapper"
wrapText={true}
>
{labelNode}
</Tooltip>
);
}
return labelNode;
});
return (
<FormGroup showError={Boolean(typeErrors)}>
{selections}
<FieldError>{typeErrors}</FieldError>
</FormGroup>
);
}
render() {
const { data, errors, path } = this.props;
const artifactsPath = this.getFieldPath(path, "artifacts");
const artifacts = findNestedPropertyInObject(data, artifactsPath) || [];
const artifactErrors = findNestedPropertyInObject(
errors,
artifactsPath
) || [];
const diskPath = this.getFieldPath(path, "disk");
const diskErrors = findNestedPropertyInObject(errors, diskPath);
return (
<div>
<h3 className="short-bottom">
高级设置
</h3>
<p>高级设置与您选择的运行时环境有关.</p>
{this.getContainerSettings()}
<FormRow>
{this.getGPUSField()}
<FormGroup className="column-4" showError={Boolean(diskErrors)}>
<FieldLabel className="text-no-transform">
<FormGroupHeadingContent primary={true}>
硬盘 (MiB)
</FormGroupHeadingContent>
</FieldLabel>
<FieldInput
min="0.001"
name={diskPath}
step="any"
type="number"
value={findNestedPropertyInObject(data, diskPath)}
/>
<FieldError>{diskErrors}</FieldError>
</FormGroup>
</FormRow>
<ArtifactsSection
data={artifacts}
path={artifactsPath}
errors={artifactErrors}
onRemoveItem={this.props.onRemoveItem}
onAddItem={this.props.onAddItem}
/>
</div>
);
}
}
ContainerServiceFormAdvancedSection.defaultProps = {
data: {},
errors: {},
onAddItem() {},
onRemoveItem() {},
path: "container"
};
ContainerServiceFormAdvancedSection.propTypes = {
data: React.PropTypes.object,
errors: React.PropTypes.object,
onAddItem: React.PropTypes.func,
onRemoveItem: React.PropTypes.func,
path: React.PropTypes.string
};
ContainerServiceFormAdvancedSection.configReducers = {
container: ContainerReducer,
containers: ContainersReducer
};
module.exports = ContainerServiceFormAdvancedSection;
| jcloud-shengtai/dcos-ui_CN | plugins/services/src/js/components/forms/ContainerServiceFormAdvancedSection.js | JavaScript | apache-2.0 | 8,131 |
export const indicators = Object.freeze({
CARET: "caret",
OPERATOR: "operator"
});
export const AVAILABLE_INDICATORS = Object.freeze(Object.values(indicators));
| Autodesk/hig | packages/tree-view/src/constants.js | JavaScript | apache-2.0 | 166 |
var version="2.7";var _summarisedStatistics=[];var _recentStatistics=[];var _hasDetailedTableBeenRendered=false;var _hasSummaryTableBeenRendered=false;var _haveHistoricGraphsBeenRendered=false;var GraphTab={Recent:1,Historic:2};function convertTimeIntoSeconds(time)
{var timeParts=time.split(":");return timeParts[0]*3600+timeParts[1]*60+parseInt(timeParts[2]);}
function summariseStatistics()
{var lastDate="";var statsGroupedByDay={};if(_statistics.length==0)
{return statsGroupedByDay;}
var projectDays=distinct(_statistics,"Date");for(var dayIndex=0;dayIndex<projectDays.length;dayIndex++)
{var currentDate=projectDays[dayIndex];if(typeof(currentDate)=='string')
{currentDate=new Date(currentDate);}
statsGroupedByDay[currentDate.toDateString()]=[];}
var currentStatistic=[];for(var i=0;i<_statistics.length;i++)
{var statistic=_statistics[i];var statisticsDate=new Date(statistic.Date);var dayText=statisticsDate.toDateString();statsGroupedByDay[dayText].push(statistic);}
return generateDailySummaries(statsGroupedByDay);}
function getTimelineDays()
{var firstDate=new Date(_statistics[0].Date);var lastDate=new Date(_statistics[_statistics.length-1].Date);return generateDateRange(firstDate,lastDate);}
function prepareStatistics()
{var usedStats=getUsedStatisticAttributes();for(var i=0;i<_statistics.length;i++)
{var statistic=_statistics[i];statistic["index"]=i;statistic["DurationInSeconds"]=convertTimeIntoSeconds(statistic["Duration"]);statistic["TestsPassed"]=statistic["TestCount"]-statistic["TestFailures"]-statistic["TestIgnored"];for(var attributeIndex=0;attributeIndex<usedStats.length;attributeIndex++)
{var attributeName=usedStats[attributeIndex];statistic[attributeName]=zeroIfInvalid(statistic[attributeName]);}}}
function getUsedStatisticAttributes()
{var usedStats={};for(var configIndex=0;configIndex<_recentGraphConfigurations.length;configIndex++)
{var config=_recentGraphConfigurations[configIndex];for(var seriesIndex=0;seriesIndex<config.series.length;seriesIndex++)
{var series=config.series[seriesIndex];usedStats[series.attributeName]='';}}
var attributes=[];for(var attribute in usedStats)
{attributes.push(attribute);}
return attributes;}
function zeroIfInvalid(dataItem)
{if(dataItem==''||typeof(dataItem)=='undefined'||isNaN(dataItem))
{return'0';}
else
{return dataItem;}}
function getRecentStatistics(numberOfBuilds)
{var startIndex=Math.max(_statistics.length-numberOfBuilds,0);for(var i=startIndex;i<_statistics.length;i++)
{var clonedStatistic=cloneObject(_statistics[i]);clonedStatistic["index"]=_recentStatistics.length;clonedStatistic["label"]=clonedStatistic["BuildLabel"];_recentStatistics.push(clonedStatistic);}}
function cloneObject(sourceObject)
{var clone={};for(var attribute in sourceObject)
{clone[attribute]=sourceObject[attribute];}
return clone;}
function generateDateRange(startDate,endDate)
{var dayDifference=24*60*60*1000;var currentDate=startDate;var dateRange=[];endDate.setHours(23);endDate.setMinutes(59);while(currentDate<=endDate)
{dateRange.push(currentDate);currentDate=new Date(currentDate.getTime()+dayDifference);}
return dateRange;}
function generateDailySummaries(statsGroupedByDay)
{var lastBuildLabel="";var index=0;for(var day in statsGroupedByDay)
{var currentStatistics=statsGroupedByDay[day];var currentBuildLabel=getLastValue(currentStatistics,"BuildLabel");if(currentBuildLabel.length==0)
{currentBuildLabel=lastBuildLabel;}
var successfulBuilds=select(currentStatistics,successfulBuildsFilter);var failedBuilds=select(currentStatistics,failedBuildsFilter);var daySummary={day:day,index:index++,lastBuildLabel:currentBuildLabel};for(var attribute in _summaryConfiguration)
{daySummary[attribute]=_summaryConfiguration[attribute](successfulBuilds,failedBuilds);}
var dayDate=new Date(day);daySummary.label=daySummary.lastBuildLabel+"\n("+day+")";_summarisedStatistics.push(daySummary);lastBuildLabel=currentBuildLabel;}}
function successfulBuildsFilter(item)
{return(item["Status"]=="Success");}
function failedBuildsFilter(item)
{var status=item["Status"];return(status=="Failure"||status=="Exception");}
function processGraphList(configurationList,containerElement)
{for(var i=0;i<configurationList.length;i++)
{var graphOptions=configurationList[i];graphOptions.containerElement=containerElement;createGraph(graphOptions);}}
function createRecentGraphs()
{processGraphList(_recentGraphConfigurations,dojo.byId("RecentBuildsContainerArea"));}
function createHistoricGraphs()
{processGraphList(_historicGraphConfigurations,dojo.byId("HistoricGraphContainerArea"));}
function summaryDataTabChangeHandler()
{if(!_hasSummaryTableBeenRendered)
{ensureStatisticsHaveBeenSummarised();var tableContainerArea=dojo.byId("SummaryTableStatisticsContainerArea");generateStatisticsTable(tableContainerArea,"Build Summary Statistics",_summarisedStatistics,cellRenderer,true,summaryTableDrillDown);_hasSummaryTableBeenRendered=true;}}
function detailedDataTabChangeHandler()
{if(!_hasDetailedTableBeenRendered)
{var tableContainerArea=dojo.byId("DetailedTableStatisticsContainerArea");generateStatisticsTable(tableContainerArea,"Build Detailed Statistics",_statistics,cellRenderer,false,null);_hasDetailedTableBeenRendered=true;}}
function historicGraphsTabChangeHandler(evt)
{if(!_haveHistoricGraphsBeenRendered)
{ensureStatisticsHaveBeenSummarised();createHistoricGraphs();_haveHistoricGraphsBeenRendered=true;}}
function ensureStatisticsHaveBeenSummarised()
{if(_summarisedStatistics.length==0)
{summariseStatistics();}}
function setupLazyTabInitialization()
{var historicalTabWidget=dojo.widget.byId("HistoricalTabWidget");var detailedTabularTabWidget=dojo.widget.byId("DetailedDataTabWidget");var summarisedTabularTabWidget=dojo.widget.byId("SummarisedDataTabWidget");dojo.event.connect("before",historicalTabWidget,"show",historicGraphsTabChangeHandler);dojo.event.connect("before",detailedTabularTabWidget,"show",detailedDataTabChangeHandler);dojo.event.connect("before",summarisedTabularTabWidget,"show",summaryDataTabChangeHandler);}
dojo.addOnLoad(function()
{prepareStatistics();getRecentStatistics(20);setupLazyTabInitialization();window.setTimeout("createRecentGraphs()",100);}); | Gallio/infrastructure | ccnet/WebDashboard/javascript/StatisticsGraphs.js | JavaScript | apache-2.0 | 6,162 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.