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
/************************************************************* * * MathJax/jax/output/HTML-CSS/config.js * * Initializes the HTML-CCS OutputJax (the main definition is in * MathJax/jax/input/HTML-CSS/jax.js, which is loaded when needed). * * --------------------------------------------------------------------- * * Copyright (c) 2009-2011 Design Science, 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. */ MathJax.OutputJax["HTML-CSS"] = MathJax.OutputJax({ id: "HTML-CSS", version: "1.1.5", directory: MathJax.OutputJax.directory + "/HTML-CSS", extensionDir: MathJax.OutputJax.extensionDir + "/HTML-CSS", autoloadDir: MathJax.OutputJax.directory + "/HTML-CSS/autoload", fontDir: MathJax.OutputJax.directory + "/HTML-CSS/fonts", // font name added later webfontDir: MathJax.OutputJax.fontDir + "/HTML-CSS", // font name added later config: { scale: 100, minScaleAdjust: 50, availableFonts: ["STIX","TeX"], preferredFont: "TeX", webFont: "TeX", imageFont: "TeX", undefinedFamily: "STIXGeneral,'Arial Unicode MS',serif", showMathMenu: true, styles: { ".MathJax_Display": { "text-align": "center", margin: "1em 0em" }, ".MathJax .merror": { "background-color": "#FFFF88", color: "#CC0000", border: "1px solid #CC0000", padding: "1px 3px", "font-family": "serif", "font-style": "normal", "font-size": "90%" }, ".MathJax_Preview": {color: "#888888"}, "#MathJax_Tooltip": { "background-color": "InfoBackground", color: "InfoText", border: "1px solid black", "box-shadow": "2px 2px 5px #AAAAAA", // Opera 10.5 "-webkit-box-shadow": "2px 2px 5px #AAAAAA", // Safari 3 and Chrome "-moz-box-shadow": "2px 2px 5px #AAAAAA", // Forefox 3.5 "-khtml-box-shadow": "2px 2px 5px #AAAAAA", // Konqueror filter: "progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true')", // IE padding: "3px 4px" } } } }); if (MathJax.Hub.Browser.isMSIE && document.documentMode >= 9) {delete MathJax.OutputJax["HTML-CSS"].config.styles["#MathJax_Tooltip"].filter} if (!MathJax.Hub.config.delayJaxRegistration) {MathJax.OutputJax["HTML-CSS"].Register("jax/mml")} MathJax.Hub.Register.StartupHook("End Config",[function (HUB,HTMLCSS) { var CONFIG = HUB.Insert({ // // The minimum versions that HTML-CSS supports // minBrowserVersion: { Firefox: 3.0, Opera: 9.52, MSIE: 6.0, Chrome: 0.3, Safari: 2.0, Konqueror: 4.0 }, // // For unsupported browsers, put back these delimiters for the preview // inlineMathDelimiters: ['$','$'], // or ["",""] or ["\\(","\\)"] displayMathDelimiters: ['$$','$$'], // or ["",""] or ["\\[","\\]"] // // For displayed math, insert <BR> for \n? // multilineDisplay: true, // // The function to call to display the math for unsupported browsers // minBrowserTranslate: function (script) { var MJ = HUB.getJaxFor(script), text = ["[Math]"], delim; var span = document.createElement("span",{className: "MathJax_Preview"}); if (MJ.inputJax.id === "TeX") { if (MJ.root.Get("displaystyle")) { delim = CONFIG.displayMathDelimiters; text = [delim[0]+MJ.originalText+delim[1]]; if (CONFIG.multilineDisplay) text = text[0].split(/\n/); } else { delim = CONFIG.inlineMathDelimiters; text = [delim[0]+MJ.originalText.replace(/^\s+/,"").replace(/\s+$/,"")+delim[1]]; } } for (var i = 0, m = text.length; i < m; i++) { span.appendChild(document.createTextNode(text[i])); if (i < m-1) {span.appendChild(document.createElement("br"))} } script.parentNode.insertBefore(span,script); } },(HUB.config["HTML-CSS"]||{})); if (HUB.Browser.version !== "0.0" && !HUB.Browser.versionAtLeast(CONFIG.minBrowserVersion[HUB.Browser]||0.0)) { HTMLCSS.Translate = CONFIG.minBrowserTranslate; HUB.Config({showProcessingMessages: false}); MathJax.Message.Set("Your browser does not support MathJax",null,4000); HUB.Startup.signal.Post("MathJax not supported"); } },MathJax.Hub,MathJax.OutputJax["HTML-CSS"]]); MathJax.OutputJax["HTML-CSS"].loadComplete("config.js");
AKSW/SlideWiki
slidewiki/libraries/frontend/MathJax/unpacked/jax/output/HTML-CSS/config.js
JavaScript
apache-2.0
5,162
define(["jquery", "underscore", "backbone"], function ($,_,Backbone) { /* ***************************************************************************************************************** Prototype Inheritance **************************************************************************************************************** */ $.curCSS = $.css; // back-port jquery 1.8+ /* ***************************************************************************************************************** **************************************************************************************************************** */ return { DEBUG: false, idAttribute: "id", labelAttribute: "label", typeAttribute: "type", commentAttribute: "comment", fact: { }, ux: { i18n: {}, types: {}, mixin: {}, view: { field: {} } }, iq: { }, NS: { "owl": "http://www.w3.org/2002/07/owl#", "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "xsd": "http://www.w3.org/2001/XMLSchema#", "ux": "meta4:ux:", "iq": "meta4:iq:", "fact": "meta4:fact:", "asq": "meta4:asq:", }, /** curried fn() when invoked returns a fn() that in turns calls a named fn() on a context object e.g: dispatch(source, "doSomething")(a,b,c) -> source.doSomething(a,b,c) **/ dispatch: function(self, event) { return function() { return self[event] && self[event].apply(self, arguments) } }, resolve: function(options, modelled) { if (!options) throw "meta4:ux:oops:missing-options" var _DEBUG = options.debug || this.ux.DEBUG modelled = modelled || _.extend({},options); // Resolve Backbone Model - last resort, use 'options' if (_.isString(options.model)) { modelled.model = this.fact.models.get(options.model); //_DEBUG && console.warn("Model$ (%s) %o %o -> %o", options.model, this.fact.models, options, modelled); } else if ( options.model instanceof Backbone.Model ) { modelled.model = options.model; } else if (_.isFunction(options.model)) { modelled.model = options.model(options); } else if (_.isObject(options.model)) { modelled.model = new this.fact.Model( options.model ); } else if ( options.model === false ) { // modelled.model = new Backbone.Model() _DEBUG && console.debug("No Model: %o %o", options, modelled) } else if ( options.model === true || options.model == undefined) { var _options = { label: options.label, comment: (options.comment || ""), icon: (options.icon || "") }; _options.idAttribute = options[this.ux.idAttribute] modelled.model = new this.fact.Model({}) modelled.model.set(_options) _DEBUG && console.debug("View Model (%s): %o %o", modelled.id, _options, modelled.model) } else throw "meta4:ux:oops:invalid-model#"+options.model // Resolve Backbone Collection if (_.isString(options.collection)) { // recursively re-model ... check if a sub-model first var _collection = false // nested-collection if (options.collection.indexOf(".")==0) { var cid = options.collection.substring(1) _collection = modelled.model.get(cid) if (!_collection) { _collection = new Backbone.Collection() _DEBUG && console.log("New Local Collection (%s): %o %o %o", cid, options, modelled, _collection) modelled.model.set(cid, _collection) } else { _DEBUG && console.log("Existing Local Collection (%s): %o %o %o", cid, options, modelled, _collection) } } else if (options.collection.indexOf("!")==0) { // global-collection var cid = options.collection.substring(1) _collection = fact.models.get(cid) _DEBUG && console.log("Global Collection (%s): %o %o %o", cid, options, modelled, _collection) } else { var cid = options.collection _collection = modelled.model.get(cid) || this.fact.models.get(cid) _DEBUG && console.log("Local/Global Collection (%s): %o %o %o", cid, options, modelled, _collection) } if (!_collection) { _collection = this.fact.factory.Local({ id: options.collection, fetch: false }) _DEBUG && console.log("Local Collection: %o %o %o %o", options.collection, options, modelled, _collection) } // resolve any string models this.ux.model( { model: modelled.model, collection: _collection }, modelled); _DEBUG && console.log("String Modelled: %o", modelled) } else if (_.isArray(options.collection)) { _DEBUG && console.log("Array Collection", options.collection, this.fact) modelled.collection = this.fact.Collection(options.collection); } else if (_.isObject(options.collection) && options.collection instanceof Backbone.Collection ) { _DEBUG && console.log("Existing Collection: %o", options.collection) modelled.collection = options.collection; } else if (_.isObject(options.collection) && _.isString(options.collection.id) ) { //_DEBUG && console.log("Register Collection: %s -> %o / %o", options.collection.id, options.collection, this.fact) modelled.collection = this.fact.models.get(options.collection.id) || this.fact.register(options.collection) } else if (_.isFunction(options.collection)) { _DEBUG && console.log("Function Collection", options.collection, this.fact) modelled.collection = options.collection(options); } // cloned originally options - with resolved Model, optionally a Collection return modelled; }, /** Uses a curried fn() to replace key/values in options{} if a matching option key exists within mix_ins{} if the mixin is fn() then execute & bind the returned value **/ curry: function(options, mix_ins, _options) { if (!options || !mix_ins) return options; _options = _options || {} // cloned object _.each(options, function(option,key) { var mixin = mix_ins[key] _options[key] = _.isFunction(mixin)?mixin(option):option }) return _options; }, /** Rename/Replace the keys in an key/value Object using a re-mapping object @param: options - Object of key/values @param: remap - Object of key1/key2 **/ remap: function(options, remap) { if (!options || !remap) return options; var map = {} _.each(remap, function(v,k) { var n = options[k] if (_.isFunction(v)) map[v] = v(n, k, map) else if ( !_.isUndefined(n) && !_.isUndefined(v) ) map[v] = n }) return map; }, /** De-reference string-based 'values' to a mix-in fn() Replaces string values in options with corresponding fn() from mixin **/ mixin: function(options, mix_ins, _options) { if (!options || !mix_ins) return options; _options = _options || options // default original _.each(options, function(value,key) { if (_.isString(value)) { var mixin = mix_ins[value] if (mixin && _.isFunction(mixin)) { options[key] = _.isFunction(mixin)?mixin:value } } }) return _options; }, isDefaultTrue: function(options, key) { if (_.isUndefined(options)) return true; return options[key]?true:false }, /** Utilities to deal with Strings (including special cases for 'id' strings) **/ /** Generate a reasonably unique UUID **/ uuid: function() { function _id() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); }; return (_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()+"-"+_id()); }, /** Generate a scoped UUID by pre-pending a prefix **/ urn: function(prefix) { return (prefix || core[idAttribute])+"#"+this.uuid(); }, /** Turn camel-cased strings into a capitalised, space-separated string **/ humanize: function(s) { return s.replace(/\W+|_|-/g, " ").toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, function($1) { return $1.toUpperCase() }); }, toQueryString(obj, prefix) { serialize = function(obj, prefix) { var str = []; for(var p in obj) { if (obj.hasOwnProperty(p)) { var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push(typeof v == "object" ? serialize(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v)); } } return str.join("&"); } return serialize(obj, prefix) } } });
troven/meta4nms
node_modules/meta4ux/src/static/js/meta4beta/core.js
JavaScript
apache-2.0
8,170
/* * Copyright 2015 NamieTown * http://www.town.namie.fukushima.jp/ * 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(function(require, exports, module) { "use strict"; module.exports = { HeaderView : require("./HeaderView") }; });
codefornamie/namie-tablet-html5
www_dev/app/modules/view/dojo/common/index.js
JavaScript
apache-2.0
783
checkRolesInFunction = function (doRole, userId) { if (!Meteor.userId() || ENUM.getUserById(userId)) throw ENUM.ERROR(403); }; getSelector = function (selector) { var baseSelector = { delete_flg: {$ne: 1} }; return _.extend(baseSelector, selector); }; detectEnv = function(){ var appFolder = process.env.PWD; var lastEnv = ""; for (let env in Meteor.settings.env_address){ var addr = Meteor.settings.env_address[env] if (appFolder === addr){ return env; } if (addr === "default"){ lastEnv = env; } } return lastEnv; }; getSettings = function(){ var env = detectEnv(); return Meteor.settings[env]; }
Designveloper/MeteorMeetupHCM
server/lib/0base.js
JavaScript
apache-2.0
662
module.exports = { attach: function attach(app) { app.actions.flip = (image, metadata, config, callback) => { const axis = config.axis || 'y'; if (axis === 'y') { return callback(undefined, image.flip()); } return callback(undefined, image.flop()); }; }, };
voidberg/imagecache-sharp
src/plugins/flip.js
JavaScript
apache-2.0
304
import SerialNumber from './SerialNumber.jsx'; export default SerialNumber;
bingweichen/GOKU
goku-admin/src/routes/NO/index.js
JavaScript
apache-2.0
77
exports.netCheck = function() { var url = "http://api.openbeerdatabase.com/v1/beers.json"; var client = Ti.Network.createHTTPClient({ onload : function(evt) { var newCrud = new crud(); newCrud.dele(); var data = JSON.parse(this.responseText); var beers = data.beers; for ( i = 0, j = beers.length; i < j; i++) { var post = { title : beers[i].name, desc : beers[i].description }; newCrud.create(post); } }, onerror : function(evt) { if (!Ti.Network.online) { alert("Could not find connection!"); var newCrud = new crud(); newCrud.read(); } } }); client.open("GET", url); client.send(); };
Pcanniff/ASDAGAIN
Resources/network.js
JavaScript
apache-2.0
664
const elixir = require('laravel-elixir'); require('laravel-elixir-vue-2'); var jsuglify = require('gulp-uglify'); var rename = require('gulp-rename'); var node_path = 'node_modules'; var paths = { 'jquery': node_path + '/jquery', 'bootstrap': node_path + '/bootstrap', 'icheck': node_path + '/icheck', 'jqueryvalidation': node_path + '/jquery-validation', 'fontawesome': node_path + '/font-awesome', }; elixir.config.sourcemaps = false; elixir.config.versioning = { buildFolder: '' }; elixir.extend('jsminify', function () { new elixir.Task('jsminify', function () { return gulp.src(['public/js/admin.js', paths.jqueryvalidation + '/dist/jquery.validate.js']) .pipe(rename({suffix: '.min'})) .pipe(jsuglify()) .pipe(gulp.dest('public/js')); }); }); elixir(mix => { mix.less([ 'AdminLTE/AdminLTE.less', 'AdminLTE/skins/skin-green.less' ], 'public/css/admin.css') .copy(paths.jquery + '/dist/jquery.min.js', 'public/js/jquery.min.js') // .copy(paths.jqueryvalidation + '/dist/jquery.validate.js', 'public/js/jquery.validate.js') .copy(paths.icheck + '/icheck.min.js', 'public/icheck/icheck.min.js') .copy(paths.icheck + '/skins', 'public/icheck/skins') .copy(paths.bootstrap + '/dist/js/bootstrap.min.js', 'public/bootstrap/js/bootstrap.min.js') .copy(paths.bootstrap + '/dist/fonts', 'public/bootstrap/fonts') .copy(paths.bootstrap + '/dist/css/bootstrap.min.css', 'public/bootstrap/css/bootstrap.min.css') .copy(paths.fontawesome + '/fonts', 'public/font-awesome/fonts') .copy(paths.fontawesome + '/css/font-awesome.min.css', 'public/font-awesome/css/font-awesome.min.css') .copy('resources/assets/fonts', 'public/fonts') .copy('resources/assets/js/admin', 'public/js/admin') .webpack('admin.js') .jsminify() // .webpack('jquery.validate.js', 'public/js/jquery.validate.min.js', 'public/js') .version(['css/admin.css', 'js/admin.min.js']) ; });
ScoLib/ScoCMF
gulpfile.js
JavaScript
apache-2.0
2,085
import React from "react"; import StorybookWrapper from "stories/helpers/storybookWrapper.js"; import baseProps from "stories/helpers/baseProps.js"; import Component, { MEDICAL_ROSTER_CREW_SUB, MEDICAL_ROSTER_QUERY, MEDICAL_ROSTER_SUB, } from "components/views/MedicalRoster/index.js"; export default { title: "Cards|Medical/MedicalRoster", }; export const MedicalRoster = () => ( <StorybookWrapper queries={[ MEDICAL_ROSTER_CREW_SUB, MEDICAL_ROSTER_QUERY, MEDICAL_ROSTER_SUB, ]} > <Component {...baseProps} /> </StorybookWrapper> );
Thorium-Sim/thorium
src/components/views/MedicalRoster/MedicalRoster.stories.js
JavaScript
apache-2.0
580
(function () { "use strict"; /** Product detail view controller */ angular.module('app') .controller('DetailController', ['$scope', '$location', '$routeParams', 'catalogService', 'ProductUtils', function ($scope, $location, $routeParams, catalogService, ProductUtils) { $scope.product = {}; catalogService.getProduct($routeParams.id).success(function (result) { $scope.product = result; }); $scope.quantity = 1; $scope.getImage = ProductUtils.getImage; /** Returns the CSS class for the average rating of a given product. */ $scope.getCSSRating = ProductUtils.getRatingCss; }]); })();
ffacon/BookCat
src/main/webapp/bookcat/js/controllers/DetailController.js
JavaScript
apache-2.0
726
/* * 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. */ Ext.define('OPF.console.domain.model.FilestoreModel', { extend: 'Ext.data.Model', statics: { pageSuffixUrl: 'console/domain', restSuffixUrl: 'registry/filestore', editorClassName: 'OPF.console.domain.view.system.FilestoreEditor', constraintName: 'OPF.registry.Filestore' }, idProperty: 'id', fields: [ { name: 'id', type: 'int', useNull: true }, { name: 'name', type: 'string' }, { name: 'type', type: 'string' }, { name: 'path', type: 'string' }, { name: 'lookup', type: 'string' }, { name: 'description', type: 'string' }, { name: 'serverName', type: 'string' }, { name: 'port', type: 'int', defaultValue: 8080 }, { name: 'urlPath', type: 'string' }, { name: 'status', type: 'string' }, { name: 'serverDirectory', type: 'string' }, { name: 'parentId', type: 'int' }, { name: 'childCount', type: 'int' }, { name: 'created', type: 'int' }, { name: 'canUpdate', type: 'boolean' }, { name: 'canDelete', type: 'boolean' } ] });
firejack-open/Firejack-Platform
platform/src/main/webapp/js/net/firejack/platform/console/domain/model/FilestoreModel.js
JavaScript
apache-2.0
1,924
/** * Created by zhangh on 2017/02/12. */ $(function () { //平衡左右侧高度 $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()); //展开左侧导航 $(".selected").parents("ul").addClass("open"); $(".selected").parents(".menu_item").children('a').find(".angle-icon").addClass('fa-angle-up').removeClass("fa-angle-down"); //左侧导航伸缩 $('.menu_box a[data-toggle="menuParent"]').on('click', function () { if ($(this).next().hasClass("open")) { $(this).parent().find('ul').removeClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-down').removeClass("fa-angle-up"); } else { $(this).next().addClass("open") $(this).parent().find('.angle-icon').addClass('fa-angle-up').removeClass("fa-angle-down"); } $('#rightContent').css("minHeight", $('#leftNav').height() > $('#rightContent').height() ? $('#leftNav').height() : $('#rightContent').height()) }) //手机屏幕点击显示隐藏左侧菜单栏 $('#toggleLeftNav').click(function (e) { e.preventDefault(); if ($("#leftNav").is(":hidden")) { $("#leftNav").css('cssText', 'display:block !important'); //如果元素为隐藏,则将它显现 } else { $("#leftNav").css('cssText', 'display:none !important'); //如果元素为显现,则将其隐藏 } $('#leftNav').css({'minHeight': 'auto'}); }) if($(".tablesorter").length > 0) { $(".tablesorter").tablesorter(); } // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { // $('.selectpicker').selectpicker('mobile'); // } confirmModalClose(); //页面加载后初始化提示信息弹出框 //监听删除按钮点击事件 $('[data-toggle="doAjax"]').each(function () { $(this).click(function (e) { e.preventDefault(); var DelBtn = $(this); confirmModalOpen($(DelBtn).data('info')); // 提示信息 $('#ConfirmModal').find('#btnConfirm').click(function () { var modal = $('#ConfirmModal'); // 获取modal对象 modal.find('button').attr('disabled', true); // 禁用modal按钮 confirmModalInfo('正在处理,请稍后...', ' fa-spinner fa-spin '); //进行ajax处理 CommonAjax($(DelBtn).data('objurl'), 'GET', '', function (data) { if (data['status'] == '200') { confirmModalInfo(data['info'], ' fa-check '); } else if (data['status'] == '300') { confirmModalInfo(data['info'], ''); } setTimeout(function () { window.location.replace(window.location.href); }, 2000); }) }) $('#ConfirmModal').on('hidden.bs.modal', function (e) { e.preventDefault(); confirmModalClose(); }) }); }); //初始化插件 initPlugin(); //从远端的数据源加载完数据之后触发该事件 $('#HandleModal').on('loaded.bs.modal', function () { //load模态框后再次初始化插件 initPlugin(); //selectpicker $(this).find('.selectpicker').each(function () { $(this).selectpicker('refresh'); }) }); //此事件在模态框被隐藏(并且同时在 CSS 过渡效果完成)之后被触发 $('#HandleModal').on('hidden.bs.modal', function () { $(this).removeData('bs.modal'); $(this).find(".modal-content").html('<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close" id="btnClose{:MCA}"><span aria-hidden="true"><i class="fa fa-times-circle"></i></span></button><h4 class="modal-title" id="{:MCA}HandleModalLabel">提示</h4></div><div class="modal-body text-center fontsize20" style="padding:20px 0;"><i class="fa fa-spinner fa-spin"></i>加载中......</div>'); }); //BEGIN BACK TO TOP $(window).scroll(function () { if ($(this).scrollTop() < 200) { $('#totop').fadeOut(); } else { $('#totop').fadeIn(); } }); $('#totop').on('click', function (e) { e.preventDefault(); $('html, body').animate({scrollTop: 0}, 'fast'); return false; }); //END BACK TO TOP }) /** * 页面加载和异步页面加载时,初始化插件 */ function initPlugin() { //radio默认选中第一个 $('input:radio').each(function () { var $name = $(this).attr('name'); if (!$('input:radio[name=' + $name + ']').is(':checked')) { $('input:radio[name=' + $name + ']').eq(0).attr("checked", true); } }); //selectpicker JiLian $('.selectpicker[data-action="jiLian"]').each(function () { $(this).change(function () { var thisSelect = $(this); CommonAjax(thisSelect.data('link'), 'POST', {param: thisSelect.val()}, function (jiLianResult) { if (jiLianResult.status == '300') { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + jiLianResult.info).show(); setTimeout(function () { $('#alertBox').remove(); }, 4000); } else if (jiLianResult.status == '200') { var str = ''; var deptData = jiLianResult.data; for (var i = 0, len = deptData.length; i < len; i++) { str += '<option value="' + deptData[i].id + '">' + deptData[i].name + '</option>'; } $('#' + thisSelect.data('subject')).html(str).selectpicker('refresh').change(); } }); }) }); //kindeditor $('textarea[data-toggle="kindeditor"]').each(function () { createKindeditor($(this).attr('id'), $(this).data()); }); //kindeditorImageUpload $('span[data-toggle="kindeditorImage"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png' }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('image', function () { $editor.plugin.imageDialog({ imageUrl: $($this.data('target')).val(), clickFn: function (url, title, width, height, border, align) { console.log($this.data('preview')); $($this.data('target')).val(url); $($this.data('preview')).prop('src', url).show(500); $editor.hideDialog(); } }); }); }) }); //kindeditorFileUpload $('span[data-toggle="kindeditorFile"]').each(function () { var $obj = $(this); var $editor = KindEditor.editor({ uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true }); $obj.click(function () { var $this = $(this); $editor.pluginsPath = LibPath + 'kindeditor/plugins/'; $editor.loadPlugin('insertfile', function () { $editor.plugin.fileDialog({ fileUrl: $($this.data('target')).val(), clickFn: function (url, title) { $($this.data('target')).val(url); $($this.data('preview')).html('选中文件:<a target="_blank" href="' + url + '">' + title + '</a>').show(500); $editor.hideDialog(); } }); }); }) }); //datetimepicker $('input[data-toggle="datetimepicker"]').each(function () { var $options = $(this).data(); if (!$options.hasOwnProperty('format')) $options.format = 'yyyy-mm-dd'; if (!$options.hasOwnProperty("autoclose")) $options.autoclose = true; if (!$options.hasOwnProperty("todayBtn")) $options.todayBtn = true; if (!$options.hasOwnProperty("language")) $options.language = "zh-CN"; if (!$options.hasOwnProperty("minView")) $options.minView = 2; $(this).datetimepicker($options).on('changeDate show', function (e) { $(this).closest('form[data-toggle="validateForm"]').bootstrapValidator('revalidateField', $(this).attr('name')); }); $(this).attr("readonly", "readonly"); }); //validateForm $('form[data-toggle="validateForm"]').each(function () { validateForm($(this), eval($(this).data('field'))); }); $('div[data-toggle="echarts"]').each(function () { var eChart = echarts.init($(this).get(0), 'macarons'); if ($(this).data('method') == 'ajax') { eChart.showLoading(); CommonAjax($(this).data('url'), 'GET', '', function (data) { eChart.hideLoading(); eChart.setOption(data); }) } else if ($(this).data('option') != '') { eChart.setOption($(this).data('option')); } }) } /** * 提示信息弹出框打开 * @param info 提示信息 * @param showBtn 是否显示确认取消按钮 * @param icon 提示信息图标 */ function confirmModalOpen(info, showBtn, icon) { if (!showBtn) showBtn = '1'; if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').on('show.bs.modal', function (event) { var modal = $(this); confirmModalInfo(info, icon); if (showBtn !== '1') { modal.find('button').hide(); } }) $('#ConfirmModal').modal({ backdrop: 'static', keyboard: false, show: true }) return; } /** * 提示信息弹出框提示文字修改 * @param info 文字信息 * @param icon 图标 */ function confirmModalInfo(info, icon) { if (!icon) icon = 'fa-exclamation-circle'; $('#ConfirmModal').find('.modal-body').html("<i class='fa " + icon + " fontsize30 colorf00'></i>" + info); } /** * 提示信息弹出框关闭 */ function confirmModalClose() { var modal = $('#ConfirmModal'); modal.find('.modal-body').html(''); modal.find('button').removeAttr('disabled').show(); modal.modal('hide'); } /** * 统一ajax方法 * @param url * @param type * @param data * @param success * @constructor */ function CommonAjax(url, type, data, success) { $.ajax({ url: url, type: type, data: data, dataType: 'json', success: function (result) { success && success(result); }, error: function (e) { alert("ajax错误提示: " + e.status + " " + e.statusText); } }); } /** * 统一验证调用方法 * @param $thisForm 需要验证的表单 * @param $field 验证的字段 */ function validateForm($thisForm, $field) { $thisForm.bootstrapValidator({ message: '您输入的信息有误,请仔细检查!', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: $field }).on('success.form.bv', function (e) { e.preventDefault(); var $form = $(e.target); //获取表单实例 //禁用所有按钮 $('#HandleModal').find('button').attr('disabled', true); $($form).find('button').attr('disabled', true); //显示提示信息 if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } $('#alertBox').removeClass('alert-success').removeClass('alert-danger').addClass('alert-info'); $('#alertBoxMsg').html('<i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...').show(); if (typeof(beforeAjax) == 'function') beforeAjax($form); //ajax处理 CommonAjax($form.attr('action'), 'POST', $form.serialize(), function (data) { if (!$('#alertBox').length) { $('<div class="alert alert-info alert-dismissible" role="alert" id="alertBox"><button type="button" class="close" style="top:3px;right:-5px;" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><span id="alertBoxMsg" style="text-align: center;"><i class="fa fa-spinner fa-spin"></i>数据正在处理,请稍等...</span></div>').appendTo('body'); } if (data.status == '300') { $('#alertBox').removeClass('alert-info').addClass('alert-danger'); $('#alertBoxMsg').html('<i class="fa fa-exclamation-circle"></i> ' + data.info).show(); //启用所有按钮 $('#HandleModal').find('button').removeAttr('disabled'); $($form).find('button').removeAttr('disabled'); setTimeout(function () { $('#alertBox').remove(); }, 8000); } else if (data.status == '200') { $('#alertBox').removeClass('alert-info').addClass('alert-success'); $('#alertBoxMsg').html('<i class="fa fa-check"></i> ' + data.info).show(); //启用所有按钮 // $('#HandleModal').find('button').removeAttr('disabled'); // $($form).find('button').removeAttr('disabled'); setTimeout(function () { window.location.replace(RefreshUrl); }, 1000); } }); }); } /** * 统一创建kindeditor * @param $objId 对象ID */ function createKindeditor($objId, $options) { KindEditor.create('#' + $objId, { uploadJson: UploadJson, fileManagerJson: FileManagerJson, allowFileManager: true, imageSizeLimit: '2MB', imageUploadLimit: '20', imageFileTypes: '*.jpg;*.jpeg;*.bmp;*.gif;*.png', afterBlur: function () { this.sync(); } }); }
izhangh/yunwuUI
common/js/mdui.js
JavaScript
apache-2.0
15,443
try { await kuzzle.ms.sadd('set1', ['foo', 'bar', 'baz']); await kuzzle.ms.sadd('set2', ['qux']); await kuzzle.ms.smove('set1', 'set2', 'foo'); // Prints: [ 'bar', 'baz' ] console.log(await kuzzle.ms.smembers('set1')); // Prints: [ 'foo', 'qux' ] console.log(await kuzzle.ms.smembers('set2')); } catch (error) { console.error(error.message); }
kuzzleio/sdk-javascript
doc/7/controllers/ms/smove/snippets/smove.js
JavaScript
apache-2.0
363
function Migrator(config, transactionDb) { this.db = transactionDb; this.dbname = config.adapter.db_name; this.table = config.adapter.collection_name; this.idAttribute = config.adapter.idAttribute; this.column = function(name) { var parts = name.split(/\s+/), type = parts[0]; switch (type.toLowerCase()) { case "string": case "varchar": case "date": case "datetime": Ti.API.warn("\"" + type + "\" is not a valid sqlite field, using TEXT instead"); case "text": type = "TEXT"; break; case "int": case "tinyint": case "smallint": case "bigint": case "boolean": Ti.API.warn("\"" + type + "\" is not a valid sqlite field, using INTEGER instead"); case "integer": type = "INTEGER"; break; case "double": case "float": case "decimal": case "number": Ti.API.warn("\"" + name + "\" is not a valid sqlite field, using REAL instead"); case "real": type = "REAL"; break; case "blob": type = "BLOB"; break; case "null": type = "NULL"; break; default: type = "TEXT"; } parts[0] = type; return parts.join(" "); }; this.createTable = function(config) { var columns = [], found = !1; for (var k in config.columns) { k === this.idAttribute && (found = !0); columns.push(k + " " + this.column(config.columns[k])); } !found && this.idAttribute === ALLOY_ID_DEFAULT && columns.push(ALLOY_ID_DEFAULT + " TEXT"); var sql = "CREATE TABLE IF NOT EXISTS " + this.table + " ( " + columns.join(",") + ")"; this.db.execute(sql); }; this.dropTable = function(config) { this.db.execute("DROP TABLE IF EXISTS " + this.table); }; this.insertRow = function(columnValues) { var columns = [], values = [], qs = [], found = !1; for (var key in columnValues) { key === this.idAttribute && (found = !0); columns.push(key); values.push(columnValues[key]); qs.push("?"); } if (!found && this.idAttribute === ALLOY_ID_DEFAULT) { columns.push(this.idAttribute); values.push(util.guid()); qs.push("?"); } this.db.execute("INSERT INTO " + this.table + " (" + columns.join(",") + ") VALUES (" + qs.join(",") + ");", values); }; this.deleteRow = function(columns) { var sql = "DELETE FROM " + this.table, keys = _.keys(columns), len = keys.length, conditions = [], values = []; len && (sql += " WHERE "); for (var i = 0; i < len; i++) { conditions.push(keys[i] + " = ?"); values.push(columns[keys[i]]); } sql += conditions.join(" AND "); this.db.execute(sql, values); }; } function Sync(method, model, opts) { var table = model.config.adapter.collection_name, columns = model.config.columns, dbName = model.config.adapter.db_name || ALLOY_DB_DEFAULT, resp = null, db; switch (method) { case "create": resp = function() { var attrObj = {}; if (!model.id) if (model.idAttribute === ALLOY_ID_DEFAULT) { model.id = util.guid(); attrObj[model.idAttribute] = model.id; model.set(attrObj, { silent: !0 }); } else { var tmpM = model.get(model.idAttribute); model.id = tmpM !== null && typeof tmpM != "undefined" ? tmpM : null; } var names = [], values = [], q = []; for (var k in columns) { names.push(k); values.push(model.get(k)); q.push("?"); } var sqlInsert = "INSERT INTO " + table + " (" + names.join(",") + ") VALUES (" + q.join(",") + ");", sqlId = "SELECT last_insert_rowid();"; db = Ti.Database.open(dbName); db.execute("BEGIN;"); db.execute(sqlInsert, values); if (model.id === null) { var rs = db.execute(sqlId); if (rs.isValidRow()) { model.id = rs.field(0); attrObj[model.idAttribute] = model.id; model.set(attrObj, { silent: !0 }); } else Ti.API.warn("Unable to get ID from database for model: " + model.toJSON()); } db.execute("COMMIT;"); db.close(); return model.toJSON(); }(); break; case "read": var sql = opts.query || "SELECT * FROM " + table; db = Ti.Database.open(dbName); var rs = db.execute(sql), len = 0, values = []; while (rs.isValidRow()) { var o = {}, fc = 0; fc = _.isFunction(rs.fieldCount) ? rs.fieldCount() : rs.fieldCount; _.times(fc, function(c) { var fn = rs.fieldName(c); o[fn] = rs.fieldByName(fn); }); values.push(o); len++; rs.next(); } rs.close(); db.close(); model.length = len; len === 1 ? resp = values[0] : resp = values; break; case "update": var names = [], values = [], q = []; for (var k in columns) { names.push(k + "=?"); values.push(model.get(k)); q.push("?"); } var sql = "UPDATE " + table + " SET " + names.join(",") + " WHERE " + model.idAttribute + "=?"; values.push(model.id); db = Ti.Database.open(dbName); db.execute(sql, values); db.close(); resp = model.toJSON(); break; case "delete": var sql = "DELETE FROM " + table + " WHERE " + model.idAttribute + "=?"; db = Ti.Database.open(dbName); db.execute(sql, model.id); db.close(); model.id = null; resp = model.toJSON(); } if (resp) { _.isFunction(opts.success) && opts.success(resp); method === "read" && model.trigger("fetch"); } else _.isFunction(opts.error) && opts.error(resp); } function GetMigrationFor(dbname, table) { var mid = null, db = Ti.Database.open(dbname); db.execute("CREATE TABLE IF NOT EXISTS migrations (latest TEXT, model TEXT);"); var rs = db.execute("SELECT latest FROM migrations where model = ?;", table); if (rs.isValidRow()) var mid = rs.field(0) + ""; rs.close(); db.close(); return mid; } function Migrate(Model) { var migrations = Model.migrations || [], lastMigration = {}; migrations.length && migrations[migrations.length - 1](lastMigration); var config = Model.prototype.config; config.adapter.db_name || (config.adapter.db_name = ALLOY_DB_DEFAULT); var migrator = new Migrator(config), targetNumber = typeof config.adapter.migration == "undefined" || config.adapter.migration === null ? lastMigration.id : config.adapter.migration; if (typeof targetNumber == "undefined" || targetNumber === null) { var tmpDb = Ti.Database.open(config.adapter.db_name); migrator.db = tmpDb; migrator.createTable(config); tmpDb.close(); return; } targetNumber += ""; var currentNumber = GetMigrationFor(config.adapter.db_name, config.adapter.collection_name), direction; if (currentNumber === targetNumber) return; if (currentNumber && currentNumber > targetNumber) { direction = 0; migrations.reverse(); } else direction = 1; db = Ti.Database.open(config.adapter.db_name); migrator.db = db; db.execute("BEGIN;"); if (migrations.length) for (var i = 0; i < migrations.length; i++) { var migration = migrations[i], context = {}; migration(context); if (direction) { if (context.id > targetNumber) break; if (context.id <= currentNumber) continue; } else { if (context.id <= targetNumber) break; if (context.id > currentNumber) continue; } var funcName = direction ? "up" : "down"; _.isFunction(context[funcName]) && context[funcName](migrator); } else migrator.createTable(config); db.execute("DELETE FROM migrations where model = ?", config.adapter.collection_name); db.execute("INSERT INTO migrations VALUES (?,?)", targetNumber, config.adapter.collection_name); db.execute("COMMIT;"); db.close(); migrator.db = null; } function installDatabase(config) { var dbFile = config.adapter.db_file, table = config.adapter.collection_name, rx = /^([\/]{0,1})([^\/]+)\.[^\/]+$/, match = dbFile.match(rx); if (match === null) throw "Invalid sql database filename \"" + dbFile + "\""; var dbName = config.adapter.db_name = match[2]; Ti.API.debug("Installing sql database \"" + dbFile + "\" with name \"" + dbName + "\""); var db = Ti.Database.install(dbFile, dbName), rs = db.execute("pragma table_info(\"" + table + "\");"), columns = {}; while (rs.isValidRow()) { var cName = rs.fieldByName("name"), cType = rs.fieldByName("type"); columns[cName] = cType; cName === ALLOY_ID_DEFAULT && !config.adapter.idAttribute && (config.adapter.idAttribute = ALLOY_ID_DEFAULT); rs.next(); } config.columns = columns; rs.close(); if (config.adapter.idAttribute) { if (!_.contains(_.keys(config.columns), config.adapter.idAttribute)) throw "config.adapter.idAttribute \"" + config.adapter.idAttribute + "\" not found in list of columns for table \"" + table + "\"\n" + "columns: [" + _.keys(config.columns).join(",") + "]"; } else { Ti.API.info("No config.adapter.idAttribute specified for table \"" + table + "\""); Ti.API.info("Adding \"" + ALLOY_ID_DEFAULT + "\" to uniquely identify rows"); db.execute("ALTER TABLE " + table + " ADD " + ALLOY_ID_DEFAULT + " TEXT;"); config.columns[ALLOY_ID_DEFAULT] = "TEXT"; config.adapter.idAttribute = ALLOY_ID_DEFAULT; } db.close(); } var _ = require("alloy/underscore")._, util = require("alloy/sync/util"), ALLOY_DB_DEFAULT = "_alloy_", ALLOY_ID_DEFAULT = "alloy_id", cache = { config: {}, Model: {} }; module.exports.beforeModelCreate = function(config, name) { if (cache.config[name]) return cache.config[name]; throw "No support for Titanium.Database in MobileWeb environment."; }; module.exports.afterModelCreate = function(Model, name) { if (cache.Model[name]) return cache.Model[name]; Model || (Model = {}); Model.prototype.idAttribute = Model.prototype.config.adapter.idAttribute; Migrate(Model); cache.Model[name] = Model; return Model; }; module.exports.sync = Sync;
rosvi/device_query
Resources/alloy/sync/sql.js
JavaScript
apache-2.0
11,019
// ***************************************************************************** // Copyright 2013-2019 Aerospike, Inc. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ***************************************************************************** 'use strict' /* global expect, describe, it, before, after */ const Aerospike = require('../lib/aerospike') const helper = require('./test_helper') const AerospikeError = Aerospike.AerospikeError const keygen = helper.keygen describe('client.apply()', function () { const client = helper.client const key = keygen.string(helper.namespace, helper.set, { prefix: 'test/apply/' })() before(() => helper.udf.register('udf.lua') .then(() => client.put(key, { foo: 'bar' }, { ttl: 1000 }))) after(() => helper.udf.remove('udf.lua') .then(() => client.remove(key))) it('should invoke an UDF to without any args', function (done) { const udfArgs = { module: 'udf', funcname: 'withoutArguments' } client.apply(key, udfArgs, function (error, result) { if (error) throw error expect(result).to.equal(1) done() }) }) it('should invoke an UDF with arguments', function (done) { const udfArgs = { module: 'udf', funcname: 'withArguments', args: [42] } client.apply(key, udfArgs, function (error, result) { if (error) throw error expect(result).to.equal(42) done() }) }) it('should invoke an UDF with apply policy', function (done) { const policy = new Aerospike.ApplyPolicy({ totalTimeout: 1500 }) const udf = { module: 'udf', funcname: 'withArguments', args: [[1, 2, 3]] } client.apply(key, udf, policy, function (error, result) { if (error) throw error expect(result).to.eql([1, 2, 3]) done() }) }) it('should return an error if the user-defined function does not exist', function (done) { const udfArgs = { module: 'udf', funcname: 'not-such-function' } client.apply(key, udfArgs, function (error, result) { expect(error).to.be.instanceof(AerospikeError).with.property('code', Aerospike.status.ERR_UDF) done() }) }) it('should return an error if the UDF arguments are invalid', function (done) { const udfArgs = { module: 'udf', funcname: 'noop', args: 42 } // args should always be an array client.apply(key, udfArgs, function (error, result) { expect(error).to.be.instanceof(AerospikeError).with.property('code', Aerospike.status.ERR_PARAM) done() }) }) it('should return a Promise that resolves to the return value of the UDF function', function () { const udfArgs = { module: 'udf', funcname: 'withoutArguments' } return client.apply(key, udfArgs) .then(result => expect(result).to.equal(1)) }) })
aerospike/aerospike-client-nodejs
test/apply.js
JavaScript
apache-2.0
3,293
/* JSPWiki - a JSP-based WikiWiki clone. 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"); fyou 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. */ /* Mootools Extension: Form.File.js Creates a multiple file upload form, based on styles from Bootstrap. Includes a json-rpc based progress-bar implemention for non-xhr2.0 browsers See also: [Form.File.Multiple, Request.File] Credit: Arian Stolwijk, [https://github.com/arian/mootools-form-upload] */ !(function(){ function readableFileSize(bytes, precision){ var exp = " KMGT".split(""), K = 1024; while( bytes >= K ){ bytes /= K; exp.shift(); } return bytes.toFixed(precision || 1) + " " + ( exp[0] || "" ) + "B"; } //"use strict"; if (!this.Form) this.Form = {}; var Form = this.Form; Form.File = new Class({ Implements: [Options, Events], options: { max: 5, //maximum number of files to upload in one go... 0=unlimited. list: ".list-group", item: ".list-group-item", drop: ".droppable", progress: ".progress-bar", fireAtOnce: false, onComplete: function(){ // reload window.location.href = window.location.href; } }, initialize: function(input, options){ var form, isXHR20 = false; //force old browser -- FIXME: "FormData" in window; //isXHR20 = "FormData" in window; input = document.id(input); form = input.getParent("form"); if(!form) return false; options = this.setOptions(options).options; this.nbr = 0; //upload file counter this.list = input.getParent(options.list); this.submit = form.getElement("input[type=submit]"); this.progress = form.getElement(options.progress); //console.log("XHR20 ? ", isXHR20); form.ifClass( isXHR20, "XHR20" , "legacy" ); this[ isXHR20 ? "uploadXHR2" : "upload"](form, input, this.list, options); }, update: function( step ){ var self = this, disabled = "disabled"; console.log("update ",self.nbr,step); self.nbr += step; self.submit.set(disabled, self.nbr ? "":disabled ); self.list.getFirst().ifClass(self.nbr >= self.options.max, disabled); }, uploadXHR2: function(form,input,list, options){ var self = this, name = input.get("name"), drop = form.getElement(options.drop), progress = self.progress, fireAtOnce = function(){ if(options.fireAtOnce) submit(); }, uploadReq = new Request.File({ url: form.get("action"), onRequest: function(){ progress.setStyle("width", 0).getParent().removeClass("hidden"); }, onProgress: function(event){ var percent = event.loaded.toInt(10) / event.total.toInt(10); progress.setStyle("width", (percent * 100).toInt().limit(0,100) + "%"); }, onComplete: function(){ progress.setStyle("width", "100%"); self.fireEvent("complete", Array.slice(arguments)); this.reset(); } }), //select one or more files via input[type=file] or drag/drop inputFiles = new Form.MultipleFile(input, list, drop, { onDrop: fireAtOnce, onChange: fireAtOnce, onAdd: self.update.pass(+1,self), onRemove: self.update.pass(-1,self) }), submit = function(event){ if (event) event.preventDefault(); inputFiles.getFiles().each(function(file,i){ uploadReq.append(name+"-"+i, file); }); uploadReq.send(); }; form.addEvent("submit", submit); self.reset = function(){ console.log(" reset "); var files = inputFiles.getFiles(); while( files[0] ){ inputFiles.remove( files.shift() ); } /* for (var i = 0; i < files.length; i++){ inputFiles.remove(files[i]); } */ }; }, /* Function: upload Legacy upload handler, compatible with legacy input[type=file] capabilities. The script works by hiding the file input element when a file is selected, then immediately replacing it with a new, empty one. Although ideally the extra elements would be hidden using the CSS setting "display:none", this causes Safari to ignore the element completely when the form is submitted. So instead, elements are moved to a position off-screen. On submit, any remaining empty file input element is removed. DOM structure: (start code) ul.list-group li.list-group-item a label.add input[type=file][id=attachefilename][name=content[?]] a.delete li.list-group-item a label.add input[type=file][id=unique] a.delete (end) */ upload: function(form,input,list,options){ var self = this; list.addEvents({ "change:relay(input)": function(){ //this event can only be received on the first input[type=file] var input = this, item = input.getParent(options.item), newItem = item.clone(true, true), fileNames = ""; for( var i=0; i< input.files.length; i++){ var file = input.files[i]; fileNames += file.name.replace(/.*[\\\/]/, "") + " <span class='badge'>" + readableFileSize( file.size )+ "</span><br />"; } input.set("id",String.uniqueID()); input.set("name",String.uniqueID()); input.set ("title",""); item.getElement("label").set("html", fileNames ); item.getElement(".delete").removeClass("hidden"); item.removeClass("droppable"); list.grab(newItem,"top"); self.update(+1); }, "click:relay(a.delete)": function(){ this.getParent(options.item).destroy(); self.update(-1); } }); form.addEvent("submit", function(){ list.getElement("input").destroy(); //remove first input[type=file] which is empty self.progressRpc(); //legacy rpc-based progress handler... }); /* not used this.reset = function(){ list.getElements(":not(:first-child)").destroy(); }; */ }, /* Function: progressRpc JSPWiki progress-bar implementation based on JSON-RPC JSON-RPC protocol: {{{ --> {"id":10000,"method":"progressTracker.getProgress","params":["2a0d2563-1ec7-4d1e-9d10-5f4ae62e8251"]}: <-- {"id":10000,"result":30} }}}} */ progressRpc: function(){ var progress = this.progress; if( progress ){ progress.getParent().removeClass("hidden"); this.options.rpc( progress.get("data-progressid"), function(result){ //CHECKME: alert("rpc progress result ",result); if( result ){ result = result.toInt().limit(0,100); progress.setStyle("width",result + "%"); if( result < 100 ){ progressRpc.delay(500); } } }); } } }); })();
tateshitah/jspwiki
jspwiki-war/src/main/scripts/moo-extend/Form.File.js
JavaScript
apache-2.0
8,474
#!/usr/bin/env node var execSync = require('child_process').execSync; var fs = require("fs"); var args = process.argv.slice(2); var guid = args[0]; if (typeof guid === "undefined") { console.log("provide a guid"); } else { var fileList = ""+execSync("ls -lh"); var lines = fileList.split("\n"); var count = 0; for (l in lines) { if (lines[l].indexOf(".wav") != -1) { count++; } } var rep = 0; console.log("About "+count+" audio files to analyze..."); for (l in lines) { if (lines[l].indexOf(".wav") != -1) { rep++; var fileName = lines[l].substr(lines[l].lastIndexOf(".wav")-32,32)+".wav"; var timestamp = lines[l].substr(lines[l].lastIndexOf(".wav")-19,19); var dateTime = (new Date(timestamp.substr(0,timestamp.indexOf("T"))+"T"+timestamp.substr(1+timestamp.indexOf("T")).replace(/-/g,":"))).toISOString(); var checkInId = lines[l].substr(lines[l].lastIndexOf(".wav")-32,32); var audioId = lines[l].substr(lines[l].lastIndexOf(".wav")-32,32); var execStr = "cd /Users/topher/code/rfcx/worker-analysis && /usr/local/bin/python2.7" +" /Users/topher/code/rfcx/worker-analysis/analyze.py" +" --wav_path /Volumes/rfcx-audio/GuardianAudio/"+guid+"/"+fileName // +" -data /Users/topher/code/rfcx/worker-analysis/config/input_defaults.properties" +" --guardian_id "+guid +" --checkin_id checkin-"+checkInId +" --audio_id audio-"+audioId +" --start_time '"+dateTime+"'" +" --ambient_temp "+40 +" --lat_lng "+"3.6141375,14.2108033" +" --local" +" >> /Volumes/rfcx-audio/GuardianAudio/"+guid+"/"+fileName+".txt" ; console.log(fileName); execSync(execStr); } } }
topherwhite/rfcx-data-analysis
filtering_scripts/analyze.js
JavaScript
apache-2.0
1,746
// This file was automatically generated. Do not modify. 'use strict'; goog.provide('Blockly.Msg.lki'); goog.require('Blockly.Msg'); Blockly.Msg.ADD_COMMENT = "گةپ دائن"; Blockly.Msg.AUTH = "لطفا ئئ اپلیکیشن را ثبت کةن و آثارتان فعال کةن تا ذخیره بو و اجازهٔ اشتراک‌ نیائن توسط هؤمة بو"; Blockly.Msg.CHANGE_VALUE_TITLE = "تةغییر مقدار:"; Blockly.Msg.CHAT = "!وةگةرد هؤمکارةتان وة نام ئئ کادرة گةپ بةن"; 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 = "دو رنگ را با نسبت مشخص‌شده مخلوط می‌کند (۰٫۰ - ۱٫۰)"; Blockly.Msg.COLOUR_PICKER_HELPURL = "https://en.wikipedia.org/wiki/رةنگ"; 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 = "ئةرا هر مورد %1 وۀ نام لیست%2"; 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 = "متغیر %1 را در مقادیر شروع‌شده از عدد انتهای به عدد انتهایی را دارد، با فواصل مشخص‌شده می‌شمارد و این بلوک مشخص‌شده را انجام می‌دهد."; Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "افزودن یک شرط به بلوک اگر."; Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "اضافه‌کردن نهایی، گرفتن همهٔ شرایط به بلوک اگر."; Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "افزودن، حذف یا بازمرتب‌سازی قسمت‌ها برای پیکربندی دوبارهٔ این بلوک اگر."; 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 = "اگر مقدار اول صحیح بود، از آن بلوک اول عبارات را انجام بده. در غیر این صورت، اگر مقدار دوم صحیح است، بلوک دوم عبارات را انجام بده."; Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "اگر مقدار اول درست است، بلوک اول عبارات را انجام بده. در غیر این صورت، اگر مقدار دوم درست باشد بلوک دوم عبارات را انجام بده. اگر هیچ از مقادیر درست نبود، آخرین بلوک عبارات را انجام بده."; Blockly.Msg.CONTROLS_REPEAT_HELPURL = "https://lki.wikipedia.org/wiki/حلقه_فور"; 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_X_BLOCKS = "حةذف %1 بلاکةل"; Blockly.Msg.DISABLE_BLOCK = "إ کار کةتن(غیرفعال‌سازی) بلاک"; Blockly.Msg.DUPLICATE_BLOCK = "کؤپی کردن"; 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.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "ایجاد فهرست خالی"; Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "فهرستی با طول صفر شامل هیچ رکورد داده‌ای بر می‌گرداند."; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "لیست"; Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "اضافه‌کردن، حذف‌کردن یا ترتیب‌سازی مجدد بخش‌ها این بلوک فهرستی."; Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "ایجاد فهرست با"; Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "اضافه‌کردن یک مورد به فهرست."; Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "فهرستی از هر عددی از موارد می‌سازد."; Blockly.Msg.LISTS_GET_INDEX_FIRST = "إژ أؤةل"; Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# إژ دؤما آخر"; Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#"; // untranslated Blockly.Msg.LISTS_GET_INDEX_GET = "گِرتِن"; Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "گِرتِن و حةذف کردن"; Blockly.Msg.LISTS_GET_INDEX_LAST = "دؤمائن/آخرین"; Blockly.Msg.LISTS_GET_INDEX_RANDOM = "بةختةکی"; Blockly.Msg.LISTS_GET_INDEX_REMOVE = "حةذف کردن"; Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "اولین مورد یک فهرست را بر می‌گرداند."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_END = "موردی در محل مشخص در فهرست بر می‌گرداند. #1 آخرین مورد است."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM_START = "موردی در محل مشخص‌شده بر می‌گرداند. #1 اولین مورد است."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "آخرین مورد در یک فهرست را بر می‌گرداند."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "یک مورد تصادفی در یک فهرست بر می‌گرداند."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "اولین مورد مشخص‌شده در فهرست را حذف و بر می‌گرداند."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_END = "مورد در محل مشخص‌شده در فهرست را حذف و بر می‌گرداند. #1 آخرین مورد است."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM_START = "مورد در محل مشخص‌شده در فهرست را حذف و بر می‌گرداند. #1 اولین مورد است."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "آخرین مورد مشخص‌شده در فهرست را حذف و بر می‌گرداند."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "مورد تصادفی‌ای را در فهرست حذف و بر می‌گرداند."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "اولین مورد را در یک فهرست حذف می‌کند."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_END = "مورد مشخص‌شده در موقعیت مشخص در یک فهرست را حذف و بر می‌گرداند. #1 آخرین مورد است."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM_START = "مورد مشخص‌شده در موقعیت مشخص در یک فهرست را حذف و بر می‌گرداند. #1 اولین مورد است."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "آخرین مورد را در یک فهرست حذف می‌کند."; Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "یک مورد تصادفی را یک فهرست حذف می‌کند."; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "به # از انتها"; Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "به #"; Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "به آخرین"; Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "گرفتن زیرمجموعه‌ای از ابتدا"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "گرفتن زیرمجموعه‌ای از # از انتها"; Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "گرفتن زیرمجموعه‌ای از #"; Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "کپی از قسمت مشخص‌شدهٔ لیست درست می‌کند."; Blockly.Msg.LISTS_INDEX_OF_FIRST = "یافتن اولین رخ‌داد مورد"; 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 = "یافتن آخرین رخ‌داد مورد"; Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "شاخصی از اولین/آخرین رخ‌داد مورد در فهرست را بر می‌گرداند. ۰ بر می‌گرداند اگر آیتم موجود نبود."; Blockly.Msg.LISTS_INLIST = "در فهرست"; Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 خالی است"; Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "اگر فهرست خالی است مقدار صجیج بر می‌گرداند."; Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated Blockly.Msg.LISTS_LENGTH_TITLE = "طول %1"; Blockly.Msg.LISTS_LENGTH_TOOLTIP = "طول یک فهرست را برمی‌گرداند."; Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated Blockly.Msg.LISTS_REPEAT_TITLE = "فهرستی با %1 تکرارشده به اندازهٔ %2 می‌سازد"; Blockly.Msg.LISTS_REPEAT_TOOLTIP = "فهرستی شامل مقادیر داده‌شدهٔ تکرار شده عدد مشخص‌شده می‌سازد."; Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "به عنوان"; Blockly.Msg.LISTS_SET_INDEX_INSERT = "درج در"; Blockly.Msg.LISTS_SET_INDEX_SET = "مجموعه"; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "موردی به ته فهرست اضافه می‌کند."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_END = "موردی در موقعیت مشخص‌شده در یک فهرست اضافه می‌کند. #1 آخرین مورد است."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM_START = "موردی در موقعیت مشخص‌شده در یک فهرست اضافه می‌کند. #1 اولین مورد است."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "موردی به ته فهرست الحاق می‌کند."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "مورد را به صورت تصادفی در یک فهرست می‌افزاید."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "اولین مورد در یک فهرست را تعیین می‌کند."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_END = "مورد مشخص‌شده در یک فهرست را قرار می‌دهد. #1 آخرین مورد است."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM_START = "مورد مشخص‌شده در یک فهرست را قرار می‌دهد. #1 اولین مورد است."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "آخرین مورد در یک فهرست را تعیین می‌کند."; Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "یک مورد تصادفی در یک فهرست را تعیین می‌کند."; 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 = "ساخت لیست إژ متن"; Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "ساخت متن إژ لیست"; Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Join a list of texts into one text, separated by a delimiter."; Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Split text into a list of texts, breaking at each delimiter."; Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "همراه جداساز"; 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 = "نه %1"; 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 = "آزمائشت"; Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:"; // untranslated Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "اگر نادرست"; Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "اگر درست"; Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "بررسی وضعیت در «آزمایش». اگر وضعیت صحیح باشد، مقدار «اگر صحیح» را بر می‌گرداند در غیر اینصورت مقدار «اگر ناصحیح» را."; Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; // untranslated Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://en.wikipedia.org/wiki/Arithmetic"; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "بازگرداندن مقدار جمع دو عدد."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "بازگرداندن باقی‌ماندهٔ دو عدد."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "بازگرداندن تفاوت دو عدد."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "بازگرداندن حاصلضرب دو عدد."; Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "بازگرداندن اولین عددی که از توان عدد دوم حاصل شده باشد."; Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter"; Blockly.Msg.MATH_CHANGE_TITLE = "تغییر %1 با %2"; Blockly.Msg.MATH_CHANGE_TOOLTIP = "افزودن یک عدد به متغیر '%1'."; Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant"; Blockly.Msg.MATH_CONSTANT_TOOLTIP = "یکی از مقادیر مشترک را برمی‌گرداند: π (۳٫۱۴۱…)، e (۲٫۷۱۸...)، φ (۱٫۶۱۸)، sqrt(۲) (۱٫۴۱۴)، sqrt(۱/۲) (۰٫۷۰۷...) و یا ∞ (بی‌نهایت)."; Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; // untranslated Blockly.Msg.MATH_CONSTRAIN_TITLE = "محدودکردن %1 پایین %2 بالا %3"; Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "محدودکردن یک عدد بین محدودیت‌های مشخص‌شده (بسته)."; Blockly.Msg.MATH_DIVISION_SYMBOL = "÷"; // untranslated Blockly.Msg.MATH_IS_DIVISIBLE_BY = "تقسیم شده بر"; Blockly.Msg.MATH_IS_EVEN = "زوج است"; Blockly.Msg.MATH_IS_NEGATIVE = "منفی است"; Blockly.Msg.MATH_IS_ODD = "فرد است"; Blockly.Msg.MATH_IS_POSITIVE = "مثبت است"; Blockly.Msg.MATH_IS_PRIME = "عدد اول است"; Blockly.Msg.MATH_IS_TOOLTIP = "بررسی می‌کند که آیا یک عدد زوج، فرد، اول، کامل، مثبت، منفی یا بخش‌پذیر عدد خاصی باشد را بررسی می‌کند. درست یا نادرست باز می‌گرداند."; Blockly.Msg.MATH_IS_WHOLE = "کامل است"; Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation"; Blockly.Msg.MATH_MODULO_TITLE = "باقی‌ماندهٔ %1 + %2"; Blockly.Msg.MATH_MODULO_TOOLTIP = "باقی‌ماندهٔ تقسیم دو عدد را بر می‌گرداند."; Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; // untranslated Blockly.Msg.MATH_NUMBER_HELPURL = "https://en.wikipedia.org/wiki/Number"; Blockly.Msg.MATH_NUMBER_TOOLTIP = "شؤمارە یەک"; Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "میانگین فهرست"; Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "بزرگ‌ترین فهرست"; Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "میانهٔ فهرست"; Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "گوجةرتةرین لیست"; Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "مد فهرست"; Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "مورد تصادفی از فهرست"; Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "انحراف معیار فهرست"; Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "جمع لیست"; Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "میانگین (میانگین ریاضی) مقادیر عددی فهرست را بر می‌گرداند."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "بزرگ‌ترین عدد در فهرست را باز می‌گرداند."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "میانهٔ عدد در فهرست را بر می‌گرداند."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "کوچک‌ترین عدد در فهرست را باز می‌گرداند."; Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "شایع‌ترین قلم(های) در فهرست را بر می‌گرداند."; Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "موردی تصادفی از فهرست را بر می‌گرداند."; Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "انحراف معیار فهرست را بر می‌گرداند."; Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "جمع همهٔ عددهای فهرست را باز می‌گرداند."; Blockly.Msg.MATH_POWER_SYMBOL = "^"; // untranslated Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "کسر تصادفی"; Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "بازگرداندن کسری تصادفی بین ۰٫۰ (بسته) تا ۱٫۰ (باز)."; Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation"; Blockly.Msg.MATH_RANDOM_INT_TITLE = "عدد صحیح تصادفی بین %1 تا %2"; Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "یک عدد تصادفی بین دو مقدار مشخص‌شده به صورت بسته باز می‌گرداند."; Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "گردکردن"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "گرد به پایین"; Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "گرد به بالا"; Blockly.Msg.MATH_ROUND_TOOLTIP = "گردکردن یک عدد به بالا یا پایین."; Blockly.Msg.MATH_SINGLE_HELPURL = "https://en.wikipedia.org/wiki/Square_root"; Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "مطلق"; Blockly.Msg.MATH_SINGLE_OP_ROOT = "ریشهٔ دوم"; Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "قدر مطلق یک عدد را بازمی‌گرداند."; Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "بازگرداندن توان e یک عدد."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "لوگاریتم طبیعی یک عدد را باز می‌گرداند."; Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "بازگرداندن لگاریتم بر پایهٔ ۱۰ یک عدد."; Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "منفی‌شدهٔ یک عدد را باز می‌گرداند."; Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "بازگرداندن توان ۱۰ یک عدد."; Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "ریشهٔ دوم یک عدد را باز می‌گرداند."; 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"; Blockly.Msg.MATH_TRIG_SIN = "sin"; // untranslated Blockly.Msg.MATH_TRIG_TAN = "tan"; // untranslated Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "بازگرداندن آرک‌کسینوس درجه (نه رادیان)."; Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = ".(بازگرداندن آرک‌سینوس درجه (نه رادیان"; Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "بازگرداندن آرک‌تانژانت درجه (نه رادیان)."; Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "بازگرداندن کسینوس درجه (نه رادیان)."; Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "بازگرداندن سینوس درجه (نه رادیان)."; Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "بازگرداندن تانژانت یک درجه (نه رادیان)."; Blockly.Msg.ME = "مإ"; Blockly.Msg.NEW_VARIABLE = "متغیر تازه..."; Blockly.Msg.NEW_VARIABLE_TITLE = "نام متغیر تازه:"; Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "اجازه اظهارات"; Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "با:"; Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "اجرای تابع تعریف‌شده توسط کاربر «%1»."; Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "اجرای تابع تعریف‌شده توسط کاربر «%1» و استفاده از خروجی آن."; Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "با:"; Blockly.Msg.PROCEDURES_CREATE_DO = "ساختن «%1»"; 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/Procedure_%28computer_science%29"; // untranslated Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "انجام چیزی"; Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "به"; Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "تابعی می‌سازد بدون هیچ خروجی."; Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "بازگشت"; Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "تابعی با یک خروجی می‌سازد."; Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "اخطار: این تابعی پارامتر تکراری دارد."; Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "برجسته‌سازی تعریف تابع"; Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = "http://c2.com/cgi/wiki?GuardClause"; // untranslated Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "اگر یک مقدار صحیح است، مقدار دوم را برگردان."; Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "اخطار: این بلوک احتمالاً فقط داخل یک تابع استفاده می‌شود."; Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "نام ورودی:"; Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "اضافه کردن ورودی به تابع."; Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "ورودی‌ها"; Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "افزودن، حذف یا دوباره مرتب‌کردن ورودی این تابع."; Blockly.Msg.REDO = "Redo"; // untranslated Blockly.Msg.REMOVE_COMMENT = "پاک کردن گةپةل/قِسةل"; Blockly.Msg.RENAME_VARIABLE = "تغییر نام متغیر..."; Blockly.Msg.RENAME_VARIABLE_TITLE = "تغییر نام همهٔ متغیرهای «%1» به:"; Blockly.Msg.TEXT_APPEND_APPENDTEXT = "چسباندن متن"; Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg.TEXT_APPEND_TO = "به"; Blockly.Msg.TEXT_APPEND_TOOLTIP = "الحاق متنی به متغیر «%1»."; Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "به حروف کوچک"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "به حروف بزرگ عنوان"; Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "به حروف بزرگ"; Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "بازگرداندن کپی متن در حالتی متفاوت."; Blockly.Msg.TEXT_CHARAT_FIRST = "گرفتن اولین حرف"; Blockly.Msg.TEXT_CHARAT_FROM_END = "گرفتن حرف # از آخر"; Blockly.Msg.TEXT_CHARAT_FROM_START = "گرفتن حرف #"; Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "در متن"; Blockly.Msg.TEXT_CHARAT_LAST = "گرفتن آخرین حرف"; Blockly.Msg.TEXT_CHARAT_RANDOM = "گرفتن حرف تصادفی"; Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated Blockly.Msg.TEXT_CHARAT_TOOLTIP = "حرفی در موقعیت مشخص‌شده بر می‌گرداند."; Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "افزودن یک مورد به متن."; Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "نام نؤیسی"; Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "اضافه‌کردن، حذف یا مرتب‌سازی بحش‌ها برای تنظیم مجدد این بلوک متنی."; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "به حرف # از انتها"; Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "به حرف #"; Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "به آخرین حرف"; 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 = "در متن"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "گرفتن زیرمتن از اولین حرف"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "گرفتن زیرمتن از حرف # به انتها"; Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "گرفتن زیرمتن از حرف #"; Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "قسمت مشخصی‌شده‌ای از متن را بر می‌گرداند."; Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "در متن"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "اولین رخداد متن را بیاب"; Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "آخرین رخداد متن را بیاب"; Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "شاخصی از اولین آخرین رخ‌داد متن اول در متن دوم بر می‌گرداند. اگر متن یافت نشد ۰ باز می‌گرداند."; Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 خالی است"; Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "اضافه‌کردن صحیح اگر متن فراهم‌شده خالی است."; Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "ایجاد متن با"; Blockly.Msg.TEXT_JOIN_TOOLTIP = "یک تکه‌ای از متن را با چسپاندن همهٔ تعداد از موارد ایجاد می‌کند."; Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated Blockly.Msg.TEXT_LENGTH_TITLE = "طول %1"; Blockly.Msg.TEXT_LENGTH_TOOLTIP = "بازگرداندن عددی از حروف (شامل فاصله‌ها) در متن فراهم‌شده."; Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated Blockly.Msg.TEXT_PRINT_TITLE = "چاپ %1"; Blockly.Msg.TEXT_PRINT_TOOLTIP = "چاپ متن، عدد یا هر مقدار دیگر مشخص‌شده."; Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "اعلان برای کاربر با یک عدد."; Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "اعلان برای کاربر برای یک متن."; Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "اعلان برای عدد با پیام"; Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "اعلان برای متن با پیام"; Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)"; Blockly.Msg.TEXT_TEXT_TOOLTIP = "یک حرف، کلمه یا خطی از متن."; Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "تراشیدن فاصله‌ها از هر دو طرف"; Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "تراشیدن فاصله‌ها از طرف چپ"; Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "تراشیدن فاصله‌ها از طرف چپ"; Blockly.Msg.TEXT_TRIM_TOOLTIP = "کپی از متن با فاصله‌های حذف‌شده از یک یا هر دو پایان باز می‌گرداند."; Blockly.Msg.TODAY = "ایمڕۆ"; Blockly.Msg.TYPE_WARN01 = "The variable '"; // untranslated Blockly.Msg.TYPE_WARN02 = "' has been first assigned to the '"; // untranslated Blockly.Msg.TYPE_WARN03 = "' type and this block tries to assign the type '"; // untranslated Blockly.Msg.TYPE_WARN04 = "'!"; // untranslated Blockly.Msg.UNDO = "Undo"; // untranslated Blockly.Msg.VARIABLES_DEFAULT_NAME = "آیتم"; Blockly.Msg.VARIABLES_GET_CREATE_SET = "درست‌کردن «تنظیم %1»"; Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated Blockly.Msg.VARIABLES_GET_TOOLTIP = "مقدار این متغیر را بر می‌گرداند."; Blockly.Msg.VARIABLES_SET = "مجموعه %1 به %2"; Blockly.Msg.VARIABLES_SET_CREATE_GET = "درست‌کردن «گرفتن %1»"; Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated Blockly.Msg.VARIABLES_SET_TOOLTIP = "متغیر برابر با خروجی را مشخص می‌کند."; 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; // Ardublockly strings Blockly.Msg.ARD_180SERVO = "0~180 degree Servo (angle)"; // untranslated Blockly.Msg.ARD_360SERVO = "0~360 degree Servo (rotation)"; // untranslated Blockly.Msg.ARD_7SEGMENT_COMPONENT = "7-Segment Display"; // untranslated Blockly.Msg.ARD_7SEGMENT_COMPONENT_TIP = "7-Segment LED Display can be used to show numbers and some characters. It has 7 segments and 1 dot, requiring 8 digital pins on the Arduino to use."; // untranslated Blockly.Msg.ARD_7SEGMENT_COMPONENT_WARN = "Pin used in segment %1 is also present in one of the other segments! Change the pin number."; // untranslated Blockly.Msg.ARD_7SEGMENT_WRITE = "show number"; // untranslated Blockly.Msg.ARD_7SEGMENT_WRITESEG = "Set segment"; // untranslated Blockly.Msg.ARD_7SEGMENT_WRITESEG_TIP = "Set a specific segment of the 7-Segment display high"; // untranslated Blockly.Msg.ARD_7SEGMENT_WRITE_TIP = "Write a specific number to the 7-segment display. Number must be between 0 and 9, otherwise nothing is shown."; // untranslated Blockly.Msg.ARD_ALLBOTSERVO_ANIMATE = "Move AllBot Servo "; // untranslated Blockly.Msg.ARD_ALLBOTSERVO_ANIMATE_TIP = "Move Servo to a specified angle gradually over the animation duration. You can combine this with other servo movements"; // untranslated Blockly.Msg.ARD_ALLBOTSERVO_WRITE = "Set AllBot Servo "; // untranslated Blockly.Msg.ARD_ALLBOT_ANIMATE = "Animate AllBot"; // untranslated Blockly.Msg.ARD_ALLBOT_ANIMATESERVOS = "Servos"; // untranslated Blockly.Msg.ARD_ALLBOT_ANIMATESPEED = "Animation duration (ms):"; // untranslated Blockly.Msg.ARD_ALLBOT_ANIMATE_TIP = "Animate the allbot by moving different servos at the same time. Total duration of this animation can be set. A servo may have only one movement block present."; // untranslated Blockly.Msg.ARD_ALLBOT_ANKLEFRONTLEFT = "ankleFrontLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_ANKLEFRONTRIGHT = "ankleFrontRight"; // untranslated Blockly.Msg.ARD_ALLBOT_ANKLELEFT = "ankleLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_ANKLEMIDDLELEFT = "ankleMiddleLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_ANKLEMIDDLERIGHT = "ankleMiddleRight"; // untranslated Blockly.Msg.ARD_ALLBOT_ANKLEREARLEFT = "ankleRearLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_ANKLEREARRIGHT = "ankleRearRight"; // untranslated Blockly.Msg.ARD_ALLBOT_ANKLERIGHT = "ankleRight"; // untranslated Blockly.Msg.ARD_ALLBOT_BACKWARD = "AllBot Backward:"; // untranslated Blockly.Msg.ARD_ALLBOT_CHIRP = "AllBot Chirp:"; // untranslated Blockly.Msg.ARD_ALLBOT_CHIRPSPEED = "beeps, beepspeed"; // untranslated Blockly.Msg.ARD_ALLBOT_CHIRP_TIP = "Make the allbot chirp a number of beeps at the given speed (delay in microseconds, use 1 to 255)"; // untranslated Blockly.Msg.ARD_ALLBOT_FORWARD = "AllBot Forward:"; // untranslated Blockly.Msg.ARD_ALLBOT_HIPFRONTLEFT = "hipFrontLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_HIPFRONTRIGHT = "hipFrontRight"; // untranslated Blockly.Msg.ARD_ALLBOT_HIPLEFT = "hipLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_HIPMIDDLELEFT = "hipMiddleLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_HIPMIDDLERIGHT = "hipMiddleRight"; // untranslated Blockly.Msg.ARD_ALLBOT_HIPREARLEFT = "hipRearLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_HIPREARRIGHT = "hipRearRight"; // untranslated Blockly.Msg.ARD_ALLBOT_HIPRIGHT = "hipRight"; // untranslated Blockly.Msg.ARD_ALLBOT_KNEEFRONTLEFT = "kneeFrontLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_KNEEFRONTRIGHT = "kneeFrontRight"; // untranslated Blockly.Msg.ARD_ALLBOT_KNEEMIDDLELEFT = "kneeMiddleLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_KNEEMIDDLERIGHT = "kneeMiddleRight"; // untranslated Blockly.Msg.ARD_ALLBOT_KNEEREARLEFT = "kneeRearLeft"; // untranslated Blockly.Msg.ARD_ALLBOT_KNEEREARRIGHT = "kneeRearRight"; // untranslated Blockly.Msg.ARD_ALLBOT_LEFT = "AllBot Left:"; // untranslated Blockly.Msg.ARD_ALLBOT_LOOKLEFT = "AllBot Look Left, speed (ms):"; // untranslated Blockly.Msg.ARD_ALLBOT_LOOKRIGHT = "AllBot Look Right, speed (ms):"; // untranslated Blockly.Msg.ARD_ALLBOT_LOOK_TIP = "Make the allbot look towards a specific direction with the given speed (ms)"; // untranslated Blockly.Msg.ARD_ALLBOT_RC = "AllBot Remote Control Handling"; // untranslated Blockly.Msg.ARD_ALLBOT_RCCOMMAND = "On receiving command "; // untranslated Blockly.Msg.ARD_ALLBOT_RCCOMMANDS = "Commands "; // untranslated Blockly.Msg.ARD_ALLBOT_RCCOMMAND_SINGLE = "This block must be inside an AllBot Remote Control block "; // untranslated Blockly.Msg.ARD_ALLBOT_RCCOMMAND_TIP = "Set the actions the AllBot must do on receiving a command."; // untranslated Blockly.Msg.ARD_ALLBOT_RCDO = "Do "; // untranslated Blockly.Msg.ARD_ALLBOT_RCSERIAL = "Use Serial to view Commands"; // untranslated Blockly.Msg.ARD_ALLBOT_RC_SPEED = "RC Speed"; // untranslated Blockly.Msg.ARD_ALLBOT_RC_SPEED_TIP = "The speed as set in the Remote Control App"; // untranslated Blockly.Msg.ARD_ALLBOT_RC_TIMES = "RC Times"; // untranslated Blockly.Msg.ARD_ALLBOT_RC_TIMES_TIP = "The times (number of steps) as set in the Remote Control App"; // untranslated Blockly.Msg.ARD_ALLBOT_RC_TIP = "A block to react to the AllBot Remote Control App on your smarthphone. Check Serial to see in the serial monitor what commands are received. Note: Your AllBot shield must be switched to RECEIVE after programming it."; // untranslated Blockly.Msg.ARD_ALLBOT_RIGHT = "AllBot Right:"; // untranslated Blockly.Msg.ARD_ALLBOT_SCARED = "AllBot Look Scared:"; // untranslated Blockly.Msg.ARD_ALLBOT_SCAREDBEEPS = "shakes, beeps:"; // untranslated Blockly.Msg.ARD_ALLBOT_SCARED_TIP = "Make the allbot shake the given number of shakes, and beep the given number of beeps "; // untranslated Blockly.Msg.ARD_ALLBOT_SERVOHUB = "AllBot Servo motor"; // untranslated Blockly.Msg.ARD_ALLBOT_STEPS = "steps, stepspeed"; // untranslated Blockly.Msg.ARD_ALLBOT_WALK_TIP = "Make the allbot move a number of steps with the given speed (ms) for one step"; // untranslated Blockly.Msg.ARD_ANALOGREAD = "read analog pin#"; // untranslated Blockly.Msg.ARD_ANALOGREAD_TIP = "Return value between 0 and 1024"; // untranslated Blockly.Msg.ARD_ANALOGWRITE = "set analog pin#"; // untranslated Blockly.Msg.ARD_ANALOGWRITE_ERROR = "The analogue value set must be between 0 and 255"; // untranslated Blockly.Msg.ARD_ANALOGWRITE_TIP = "Write analog value between 0 and 255 to a specific PWM Port"; // untranslated Blockly.Msg.ARD_ANASENSOR = "Analog Sensor"; // untranslated Blockly.Msg.ARD_ANASENSOR_COMPONENT = "Analog Sensor"; // untranslated Blockly.Msg.ARD_ANASENSOR_DEFAULT_NAME = "AnaSensor1"; // untranslated Blockly.Msg.ARD_ANASENSOR_READ = "Read analog sensor"; // untranslated Blockly.Msg.ARD_ANASENSOR_TIP = "Connect an analog sensor to an analog pin, so as to read its value. On an Arduino UNO a value between 0 and 1024 is returned, corresponding to a measured value between 0 and 5V. Eg.: an LDR sensor, a potmeter, ..."; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_LENGTH = "of length"; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_LENGTH_TOOLTIP = "Create an array containing the given number of elements"; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_TITLE = "array"; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_TITLE0 = "Create"; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_TITLE2 = "with values"; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_WITH_CONTAINER_TITLE_ADD = "array"; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_WITH_CONTAINER_TOOLTIP = "Add, remove, or reorder sections to reconfigure this array block."; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_WITH_INPUT_WITH = "Create array with"; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_WITH_ITEM_TITLE = "item"; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_WITH_ITEM_TOOLTIP = "Add an item to the array."; // untranslated Blockly.Msg.ARD_ARRAY_CREATE_WITH_TOOLTIP = "Create an array with any number of items"; // untranslated Blockly.Msg.ARD_ARRAY_DEFAULT_NAME = "Array1"; // untranslated Blockly.Msg.ARD_ARRAY_GETINDEX_AT = "get element with index"; // untranslated Blockly.Msg.ARD_ARRAY_GETINDEX_ITEM = "in array"; // untranslated Blockly.Msg.ARD_ARRAY_GETINDEX_TOOLTIP = "Obtain element in the array at given index. Index must be a number from 0 to the length minus 1!"; // untranslated Blockly.Msg.ARD_ARRAY_GETLENGTH = "Length of array"; // untranslated Blockly.Msg.ARD_ARRAY_GETLENGTH_TOOLTIP = "Return the length (=number of elements) of the selected array"; // untranslated Blockly.Msg.ARD_ARRAY_IND_ERR1 = "Index must be number >= 0"; // untranslated Blockly.Msg.ARD_ARRAY_IND_ERR2 = "Index must be number < length array"; // untranslated Blockly.Msg.ARD_ARRAY_LEN_ERR1 = "Length of array must be 1 or more"; // untranslated Blockly.Msg.ARD_ARRAY_LEN_ERR2 = "Length of array must be an integer number"; // untranslated Blockly.Msg.ARD_ARRAY_LEN_ERR3 = "Length of array must be a number, not a variable"; // untranslated Blockly.Msg.ARD_ARRAY_NOT_FLOAT = "One of the values is not a numeric value"; // untranslated Blockly.Msg.ARD_ARRAY_NOT_INT = "One of the values is not an integer"; // untranslated Blockly.Msg.ARD_ARRAY_NOT_KNOWN = "Unknown type of array given"; // untranslated Blockly.Msg.ARD_ARRAY_NOT_NUMBER = "Only assign numbers, not variables when defining an array!"; // untranslated Blockly.Msg.ARD_ARRAY_SETINDEX_AT = "the element with index"; // untranslated Blockly.Msg.ARD_ARRAY_SETINDEX_ITEM = "Set in array"; // untranslated Blockly.Msg.ARD_ARRAY_SETINDEX_TOOLTIP = "Set an element in the array at given index equal to the given value. Index must be a number from 0 to the length minus 1!"; // untranslated Blockly.Msg.ARD_ARRAY_SETINDEX_VALUE = "to the value"; // untranslated Blockly.Msg.ARD_AS_ANAINPUT_PIN = "as analog input"; // untranslated Blockly.Msg.ARD_AS_ANAINPUT_PIN_TIP = "Declare a variable as a analog input pin"; // untranslated Blockly.Msg.ARD_AS_ANAOUTPUT_PIN = "as analg output"; // untranslated Blockly.Msg.ARD_AS_ANAOUTPUT_PIN_TIP = "Declare a variable as a analog PWM output pin"; // untranslated Blockly.Msg.ARD_AS_BOOL_NUMBER = "as boolean"; // untranslated Blockly.Msg.ARD_AS_BOOL_NUMBER_TIP = "Declare a variable as boolean with value true or false"; // untranslated Blockly.Msg.ARD_AS_DIGINPUT_PIN = "as digital input"; // untranslated Blockly.Msg.ARD_AS_DIGINPUT_PIN_TIP = "Declare a variable as a digital input pin"; // untranslated Blockly.Msg.ARD_AS_DIGOUTPUT_PIN = "as digital output"; // untranslated Blockly.Msg.ARD_AS_DIGOUTPUT_PIN_TIP = "Declare a variable as a digital output pin"; // untranslated Blockly.Msg.ARD_AS_FLOAT_NUMBER = "as decimal number"; // untranslated Blockly.Msg.ARD_AS_FLOAT_NUMBER_TIP = "Declare a variable as a decimal number, eg 3.6 or 5e4 or -3.14"; // untranslated Blockly.Msg.ARD_AS_INTEGER_NUMBER = "as integer number"; // untranslated Blockly.Msg.ARD_AS_INTEGER_NUMBER_TIP = "Declare a variable as integer, -32768 to 32767"; // untranslated Blockly.Msg.ARD_AS_LONG_NUMBER = "as long integer number"; // untranslated Blockly.Msg.ARD_AS_LONG_NUMBER_TIP = "Declare a variable as a long integer, -2,147,483,648 to 2,147,483,647"; // untranslated Blockly.Msg.ARD_AS_UINT_NUMBER = "as positive integer number"; // untranslated Blockly.Msg.ARD_AS_UINT_NUMBER_TIP = "Declare a variable as a positive integer, 0 to 65535"; // untranslated Blockly.Msg.ARD_AS_ULONG_NUMBER = "as long positive integer number"; // untranslated Blockly.Msg.ARD_AS_ULONG_NUMBER_TIP = "Declare a variable as a long positive integer, 0 to 4,294,967,295"; // untranslated Blockly.Msg.ARD_BLOCKS = "You have this block twice on the canvas. That is once too many!"; // untranslated Blockly.Msg.ARD_BOARD = "Board"; // untranslated Blockly.Msg.ARD_BOARD_WARN = "This block requires as board %1, but or a duplicate block is present or another block is present that requires another Arduino board!"; // untranslated Blockly.Msg.ARD_BUILTIN_LED = "set built-in LED"; // untranslated Blockly.Msg.ARD_BUILTIN_LED_TIP = "Light on or off for the built-in LED of the Arduino"; // untranslated Blockly.Msg.ARD_BUTTON_COMPONENT = "Push Button"; // untranslated Blockly.Msg.ARD_BUTTON_DEFAULT_NAME = "PushButton1"; // untranslated Blockly.Msg.ARD_BUTTON_IFPUSHED = "If pushed we measure value"; // untranslated Blockly.Msg.ARD_BUTTON_INPUT_CLICK = " is clicked"; // untranslated Blockly.Msg.ARD_BUTTON_INPUT_IF = "If button"; // untranslated Blockly.Msg.ARD_BUTTON_INPUT_LONGCLICK = "is undergoing a long click"; // untranslated Blockly.Msg.ARD_BUTTON_INPUT_PRESSED = "is being pressed"; // untranslated Blockly.Msg.ARD_BUTTON_INPUT_PULLUP_COMPONENT = "Pushbutton 2-wire no resistor"; // untranslated Blockly.Msg.ARD_BUTTON_INPUT_PULLUP_TIP = "A push button which can be ON or OFF, connected to the Arduino with 2 wires: GND, and a digital pin"; // untranslated Blockly.Msg.ARD_BUTTON_INPUT_THEN = "do"; // untranslated Blockly.Msg.ARD_BUTTON_INPUT_TIP = "Check the input received on a button, and react to it. This function does not block your program if you do not check the checkbox to wait for a click. A click is a press and a release of the button, a long press a click and holding long time before you release, press is active as soon as the button is pressed down."; // untranslated Blockly.Msg.ARD_BUTTON_INPUT_WAIT = "wait for a click to happen"; // untranslated Blockly.Msg.ARD_BUTTON_READ = "Read value button"; // untranslated Blockly.Msg.ARD_BUTTON_TIP = "A push button which can be ON or OFF, connected to the Arduino with 3 wires: GND, 5V over resisotor, and a digital pin"; // untranslated Blockly.Msg.ARD_BUZNOTONE = "No tone on buzzer"; // untranslated Blockly.Msg.ARD_BUZNOTONE_TIP = "Stop generating a tone on the buzzer"; // untranslated Blockly.Msg.ARD_BUZOUTPUT_COMPONENT = "Buzzer/Speaker"; // untranslated Blockly.Msg.ARD_BUZOUTPUT_DEFAULT_NAME = "MyBuzzer1"; // untranslated Blockly.Msg.ARD_BUZOUTPUT_TIP = "This component is a Buzzer or a Loudspeaker. You can connect it to a digital pin of the Arduino."; // untranslated Blockly.Msg.ARD_BUZSELECTPITCH = "Pitch"; // untranslated Blockly.Msg.ARD_BUZSELECTPITCH_TIP = "Select the pitch you want. This block returns a number which is the frequency of the selected pitch."; // untranslated Blockly.Msg.ARD_BUZSETPITCH = "with pitch"; // untranslated Blockly.Msg.ARD_BUZSETTONE = "Set tone on buzzer"; // untranslated Blockly.Msg.ARD_BUZZEROUTPUT = "Buzzer/Speaker"; // untranslated Blockly.Msg.ARD_COMMENT = "Comment"; // untranslated Blockly.Msg.ARD_COMMENT_TIP = "Add the given text as comment to the Arduino code"; // untranslated Blockly.Msg.ARD_COMPONENT_BOARD = "a specific Arduino Board"; // untranslated Blockly.Msg.ARD_COMPONENT_BOARD_HUB_TIP = "Set the Arduino board you work with, and to what it connects"; // untranslated Blockly.Msg.ARD_COMPONENT_BOARD_TIP = "Set which Arduino board you work with, and connect components to the pins."; // untranslated Blockly.Msg.ARD_COMPONENT_WARN1 = "A %1 configuration block with the same %2 name must be added to use this block!"; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_ELSEIF_TOOLTIP = "Add an extra effect time at which statements must be done"; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_ELSE_TOOLTIP = "Add a block for statements when the effect is finished."; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_MSG_ELSE = "at the end do"; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_MSG_ELSEIF = "if effect time becomes greater than"; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_MSG_FIRST1 = "Effect"; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_MSG_FIRST2 = "with total duration (ms) ="; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_MSG_IF = "at the start do"; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_TOOLTIP_1 = "At the start of an effect, do some statements"; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_TOOLTIP_2 = "At the start of an effect, do some statements, and at the end of the effect too"; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_TOOLTIP_3 = "At the start of an effect, do some statements, if the effect time becomes larger than the given time, do the next statements."; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_TOOLTIP_4 = "At the start of an effect, do some statements, if the effect time becomes larger than the given time, do the next statements. Ath end of the effect the final statements are done."; // untranslated Blockly.Msg.ARD_DEFINE = "Define"; // untranslated Blockly.Msg.ARD_DHTHUB = "Temperature and humidity sensor"; // untranslated Blockly.Msg.ARD_DHTHUB_READHEATINDEX = "Heat Index at"; // untranslated Blockly.Msg.ARD_DHTHUB_READRH = "Relative Humidity at"; // untranslated Blockly.Msg.ARD_DHTHUB_READTEMP = "°C temperature at"; // untranslated Blockly.Msg.ARD_DHTHUB_TIP = "Block to assign to an Arduino pin a DHT type sensor"; // untranslated Blockly.Msg.ARD_DHT_COMPONENT = "DHT sensor"; // untranslated Blockly.Msg.ARD_DHT_DEFAULT_NAME = "TempRH_Sensor"; // untranslated Blockly.Msg.ARD_DHT_READHEATINDEX_TIP = "Obtain the Heat Index ( human-perceived equivalent temperature in °C) of a DHT sensor"; // untranslated Blockly.Msg.ARD_DHT_READRH_TIP = "Obtain the RH (Relative Humidity in %) as a value from 0 to 100 a DHT sensor"; // untranslated Blockly.Msg.ARD_DHT_READTEMP_TIP = "Obtain the temperature in degree Celcius of a DHT sensor"; // untranslated Blockly.Msg.ARD_DIGINPUT = "Digital input"; // untranslated Blockly.Msg.ARD_DIGINPUT_COMPONENT = "Digital Input"; // untranslated Blockly.Msg.ARD_DIGINPUT_DEFAULT_NAME = "DigInput1"; // untranslated Blockly.Msg.ARD_DIGINPUT_READ = "Read digital input"; // untranslated Blockly.Msg.ARD_DIGINPUT_TIP = "Connect a digital input to a digital pin, so as to read its value. The digital state can then be read, corresponding to 0V or 5V on the pin for an Arduino UNO."; // untranslated Blockly.Msg.ARD_DIGITALREAD = "read digital pin#"; // untranslated Blockly.Msg.ARD_DIGITALREAD_TIP = "Read digital value on a pin: HIGH or LOW"; // untranslated Blockly.Msg.ARD_DIGITALWRITE = "set digitial pin#"; // untranslated Blockly.Msg.ARD_DIGITALWRITEVAR_TIP = "Write digital value to a Port, the value and port can be computed variables"; // untranslated Blockly.Msg.ARD_DIGITALWRITE_TIP = "Write digital value HIGH or LOW to a specific Port"; // untranslated Blockly.Msg.ARD_DIGOUTPUT = "Digital output"; // untranslated Blockly.Msg.ARD_DIGOUTPUT_COMPONENT = "Digital Output"; // untranslated Blockly.Msg.ARD_DIGOUTPUT_DEFAULT_NAME = "DigOutput1"; // untranslated Blockly.Msg.ARD_DIGOUTPUT_TIP = "Connect a generic digital ouput to a digital pin, so as to write to that pin. The digital state can be set to LOW or HIGH, corresponding to 0V and 5V on the pin for an Arduino UNO."; // untranslated Blockly.Msg.ARD_DIGOUTPUT_WRITE = "Write to digital output"; // untranslated Blockly.Msg.ARD_DIORAMA_BOARD_TIP = "The Ingegno Diorama board - See manual for info"; // untranslated Blockly.Msg.ARD_DIORAMA_BTN_TIP = "Diorama button code, executed in a loop once the button has been pressed"; // untranslated Blockly.Msg.ARD_DIO_BOARD_MISSING = "No Diorama board present. Add it to the canvas!"; // untranslated Blockly.Msg.ARD_DIO_DISPLAYTEXT = "Show on display: "; // untranslated Blockly.Msg.ARD_DIO_DISPLAYTEXT_TIP = "Give a text of 8 characters to show on the diorama display"; // untranslated Blockly.Msg.ARD_DIO_DISPLAYTEXT_WARNING = "Text can only be 8 long, not longer!"; // untranslated Blockly.Msg.ARD_DIO_LESSLOUD = "Diorama: less loud output"; // untranslated Blockly.Msg.ARD_DIO_LOUDER = "Diorama: louder output"; // untranslated Blockly.Msg.ARD_DIO_PLAYTRACK = "Play track number "; // untranslated Blockly.Msg.ARD_DIO_RESETBTN = "stop buttons"; // untranslated Blockly.Msg.ARD_DIO_RESETBTNNR_TIP = "Stop action of the given button."; // untranslated Blockly.Msg.ARD_DIO_RESETBTN_TIP = "Reset the buttons, so no button is considered pressed."; // untranslated Blockly.Msg.ARD_DIO_SETLOUDNESS = "Diorama: set volume to (0-10):"; // untranslated Blockly.Msg.ARD_DIO_SOUND_TIP = "Change sound output of the Diorama board. If louder or quieter, we stop processing the button after the call."; // untranslated Blockly.Msg.ARD_DIO_SOUND_WARNING = "Volume must be between 0 and 10!"; // untranslated Blockly.Msg.ARD_DIO_STOPBTN = "Pushbutton 8: stop"; // untranslated Blockly.Msg.ARD_DIO_STOPTRACK = "Stop playing"; // untranslated Blockly.Msg.ARD_DIO_STOPTRACK_TIP = "Immediately stop playing the track that is playing"; // untranslated Blockly.Msg.ARD_DIO_TRACKPLAYING = "track is playing"; // untranslated Blockly.Msg.ARD_DIO_TRACKPLAYING_TIP = "Return true if a track is still playing, false otherwise"; // untranslated Blockly.Msg.ARD_DIO_TRACK_TIP = "If number 1, then play a track stored on SD card as 'track001.mp3'"; // untranslated Blockly.Msg.ARD_DIO_TRACK_WARNING = "Track must be a number between 1 and 100!"; // untranslated Blockly.Msg.ARD_FUN_RUN_DECL = "Arduino define up front:"; // untranslated Blockly.Msg.ARD_FUN_RUN_DECL_TIP = "Code you want to declare up front (use this e.g. for variables you need in setup)"; // untranslated Blockly.Msg.ARD_FUN_RUN_LOOP = "Arduino loop forever:"; // untranslated Blockly.Msg.ARD_FUN_RUN_SETUP = "Arduino run first:"; // untranslated Blockly.Msg.ARD_FUN_RUN_TIP = "Defines the Arduino setup() and loop() functions."; // untranslated Blockly.Msg.ARD_HIGH = "HIGH"; // untranslated Blockly.Msg.ARD_HIGHLOW_TIP = "Set a pin state logic High or Low."; // untranslated Blockly.Msg.ARD_LEDLEG = "LED"; // untranslated Blockly.Msg.ARD_LEDLEGNEG = "minus"; // untranslated Blockly.Msg.ARD_LEDLEGPOL = "leg polarity"; // untranslated Blockly.Msg.ARD_LEDLEGPOS = "plus"; // untranslated Blockly.Msg.ARD_LEDLEG_COMPONENT = "LED"; // untranslated Blockly.Msg.ARD_LEDLEG_DEFAULT_NAME = "Led1"; // untranslated Blockly.Msg.ARD_LEDLEG_OFF = "OFF"; // untranslated Blockly.Msg.ARD_LEDLEG_ON = "ON"; // untranslated Blockly.Msg.ARD_LEDLEG_SET = "Set LED"; // untranslated Blockly.Msg.ARD_LEDLEG_TIP = "A LED light, on of the legs (the positive or negative) is connected to the Arduino. Can be ON or OFF."; // untranslated Blockly.Msg.ARD_LEDUP_GADGET = "Gadget LedUpKidz"; // untranslated Blockly.Msg.ARD_LEDUP_HUB = "LedUpKidz, destination: "; // untranslated Blockly.Msg.ARD_LEDUP_HUB_TIP = "LedUpKidz is a gadget with 6 LED that you can program. There is a big prototype connected to an Arduino UNO, choose 'prototype' for code destined for this. The gadget itself works on a small attiny85 microchip, for code with that destination, select destination 'gadget'"; // untranslated Blockly.Msg.ARD_LEDUP_LED0 = "LED 0"; // untranslated Blockly.Msg.ARD_LEDUP_LED1 = "LED 1"; // untranslated Blockly.Msg.ARD_LEDUP_LED2 = "LED 2"; // untranslated Blockly.Msg.ARD_LEDUP_LED3 = "LED 3"; // untranslated Blockly.Msg.ARD_LEDUP_LED4 = "LED 4"; // untranslated Blockly.Msg.ARD_LEDUP_LED5 = "LED 5"; // untranslated Blockly.Msg.ARD_LEDUP_LED_ONOFF1 = "Put LedUp LED"; // untranslated Blockly.Msg.ARD_LEDUP_LED_ONOFF2 = "on? True/False:"; // untranslated Blockly.Msg.ARD_LEDUP_LED_ONOFF_TIP = "Set a given LedUpKidz light to on or off using variable blocks"; // untranslated Blockly.Msg.ARD_LEDUP_PROTO = "Prototype Arduino UNO"; // untranslated Blockly.Msg.ARD_LOW = "LOW"; // untranslated Blockly.Msg.ARD_MAP = "Map"; // untranslated Blockly.Msg.ARD_MAP_TIP = "Re-maps a number from [0-1024] to another."; // untranslated Blockly.Msg.ARD_MAP_VAL = "value to [0-"; // untranslated Blockly.Msg.ARD_MD_180SERVO = "0~180 degree Servo"; // untranslated Blockly.Msg.ARD_MD_360SERVO = "0~360 degree Servo"; // untranslated Blockly.Msg.ARD_MD_AAABLOCK = "AAA 3V Battery module"; // untranslated Blockly.Msg.ARD_MD_AAABLOCK_TIP = "The battery block for Microduino"; // untranslated Blockly.Msg.ARD_MD_AAASOUNDWARN = "A AAA Battery module must be added to your blocks if you work with sound"; // untranslated Blockly.Msg.ARD_MD_AMPBLOCK = "Loudspeaker (Amplifier) Module"; // untranslated Blockly.Msg.ARD_MD_AMPBLOCK_TIP = "Amplifier module, connect the loudspeaker to it to hear sound."; // untranslated Blockly.Msg.ARD_MD_AMPWARN = "An Amplifier module must be added to your blocks"; // untranslated Blockly.Msg.ARD_MD_AUDIOAMPWARN = "An Audio module must be added to your blocks if you work with an amplifier"; // untranslated Blockly.Msg.ARD_MD_AUDIOBLOCK = "Sound modules (Audio). Mode:"; // untranslated Blockly.Msg.ARD_MD_AUDIOBLOCK_TIP = "Audio Function Module, Choose a mode and a volume"; // untranslated Blockly.Msg.ARD_MD_AUDIOSOUNDWARN = "An Audio module must be added to your blocks to be able to work with music."; // untranslated Blockly.Msg.ARD_MD_AUDIO_PAUSE = "Pause sound fragment"; // untranslated Blockly.Msg.ARD_MD_AUDIO_PAUSE_TIP = "Pause the sound fragment that is playing"; // untranslated Blockly.Msg.ARD_MD_AUDIO_PLAY = ""; // untranslated Blockly.Msg.ARD_MD_AUDIO_PLAYNR = "Play sound fragment"; // untranslated Blockly.Msg.ARD_MD_AUDIO_PLAY_TIP = "Write the number of the sound fragment you want to play. On the this number corresponds to the order in which files have been copied to the SD Card. Best: 1/Empty the SD card 2/copy files to SD card in the order you want to play them 3/it is easier if you name the files 001.mp3, 002.mp3, ... and copy them one after the other to the card!"; // untranslated Blockly.Msg.ARD_MD_AUDIO_REP1 = "Repeat everything"; // untranslated Blockly.Msg.ARD_MD_AUDIO_REP2 = "Play everything 1 time"; // untranslated Blockly.Msg.ARD_MD_AUDIO_REP3 = "Repeat 1 track"; // untranslated Blockly.Msg.ARD_MD_AUDIO_REP4 = "Play 1 track"; // untranslated Blockly.Msg.ARD_MD_BLOCKS = "Microduino blocks: "; // untranslated Blockly.Msg.ARD_MD_COOKIEBUTTON_COMPONENT = "Microduino MCookie CoreUSB"; // untranslated Blockly.Msg.ARD_MD_COREBLOCK = "Brain (CoreUSB)"; // untranslated Blockly.Msg.ARD_MD_COREBLOCK_TIP = "The Brain of your construction, the MCookie-CoreUSB"; // untranslated Blockly.Msg.ARD_MD_COREWARN = "A Brain (CoreUSB) module must be added to your blocks"; // untranslated Blockly.Msg.ARD_MD_CRASHBUTTON_COMPONENT = "Microduino Crash Button"; // untranslated Blockly.Msg.ARD_MD_CRASHBUTTON_DEFAULT_NAME = "Crashbutton1"; // untranslated Blockly.Msg.ARD_MD_CRASHBUTTON_TIP = "The microduino crash-button with which you can detect if you hit something, or that you can use as a push button."; // untranslated Blockly.Msg.ARD_MD_HUBBLOCK = "The Cable holder (Sensor Hub)"; // untranslated Blockly.Msg.ARD_MD_HUBBLOCK01 = "connected to pins: IIC"; // untranslated Blockly.Msg.ARD_MD_HUBBLOCK_TIP = "The Hub allows to connect up to 12 sensors to your Microduino"; // untranslated Blockly.Msg.ARD_MD_NOSERVO = "Geen Servo gekoppeld"; // untranslated Blockly.Msg.ARD_MD_SERVOBOT_DEFAULT_NAME = "BottomServo1"; // untranslated Blockly.Msg.ARD_MD_SERVOCON = "Servo Motor Connector."; // untranslated Blockly.Msg.ARD_MD_SERVOCON_BOTTOM = "Define bottom Servo"; // untranslated Blockly.Msg.ARD_MD_SERVOCON_TIP = "Servo Motor Connector, can control two Servo (top and bottom). You have to give the servo a name, and what type it is (no servo attached, a 180 degree servo or a 360 degree servo."; // untranslated Blockly.Msg.ARD_MD_SERVOCON_TOP = "Define top Servo"; // untranslated Blockly.Msg.ARD_MD_SERVOCON_TYPE = "Type:"; // untranslated Blockly.Msg.ARD_MD_SERVOTOP_DEFAULT_NAME = "TopServo1"; // untranslated Blockly.Msg.ARD_MD_SERVOTYPE_TIP = "Select the type of Servo you attach to the Servo connnector"; // untranslated Blockly.Msg.ARD_MD_SERVO_READ = "read Servo "; // untranslated Blockly.Msg.ARD_MD_SERVO_STEP_WARN1 = "A Servo configuration block must be added to the hub to use this block!"; // untranslated Blockly.Msg.ARD_MD_SERVO_STEP_WARN2 = "A Name input must be added to the Servo configuration block!"; // untranslated Blockly.Msg.ARD_MD_SERVO_STEP_WARN3 = "Selected servo does not exist any more, please select a new one."; // untranslated Blockly.Msg.ARD_MD_SERVO_WRITE = "set 180 degree Servo "; // untranslated Blockly.Msg.ARD_NEOPIXEL = "NeoPixel LED light"; // untranslated Blockly.Msg.ARD_NEOPIXEL_BRIGHTNESS = " brightness (%)"; // untranslated Blockly.Msg.ARD_NEOPIXEL_COMPONENT = "Neopixel strip"; // untranslated Blockly.Msg.ARD_NEOPIXEL_DEFAULT_NAME = "NeoPixel1"; // untranslated Blockly.Msg.ARD_NEOPIXEL_HZ = "Frequency:"; // untranslated Blockly.Msg.ARD_NEOPIXEL_ONCOLOUR = "on colour"; // untranslated Blockly.Msg.ARD_NEOPIXEL_ONCOLOURVALBLUE = "blue:"; // untranslated Blockly.Msg.ARD_NEOPIXEL_ONCOLOURVALGREEN = "green:"; // untranslated Blockly.Msg.ARD_NEOPIXEL_ONCOLOURVALRED = "on colour (0-255) red:"; // untranslated Blockly.Msg.ARD_NEOPIXEL_PIXEL = "pixel"; // untranslated Blockly.Msg.ARD_NEOPIXEL_PIXELS = "Pixels."; // untranslated Blockly.Msg.ARD_NEOPIXEL_SET = "Set Neopixel"; // untranslated Blockly.Msg.ARD_NEOPIXEL_STRIP = "Strip with"; // untranslated Blockly.Msg.ARD_NEOPIXEL_TIP = "A NEOPIXEL LED light or a strip with multiple neopixels."; // untranslated Blockly.Msg.ARD_NEOPIXEL_TYPE = "Type:"; // untranslated Blockly.Msg.ARD_NOTONE = "Turn off tone on pin #"; // untranslated Blockly.Msg.ARD_NOTONE_PIN = "No tone PIN#"; // untranslated Blockly.Msg.ARD_NOTONE_PIN_TIP = "Stop generating a tone on a pin"; // untranslated Blockly.Msg.ARD_NOTONE_TIP = "Turns the tone off on the selected pin"; // untranslated Blockly.Msg.ARD_NO_ALLBOT = "No AllBot present"; // untranslated Blockly.Msg.ARD_OLED = "OLED"; // untranslated Blockly.Msg.ARD_OLED_CLEAR = "clear display"; // untranslated Blockly.Msg.ARD_OLED_CLEAR_TIP = "Before writing new text to the display, use this block to clear it first."; // untranslated Blockly.Msg.ARD_OLED_CONFIG_TIP = "Define a display of the given resolution to use to write text to"; // untranslated Blockly.Msg.ARD_OLED_CURSORX = "set cursor position X"; // untranslated Blockly.Msg.ARD_OLED_CURSORY = "Y"; // untranslated Blockly.Msg.ARD_OLED_DEFAULT_NAME = "OLED1"; // untranslated Blockly.Msg.ARD_OLED_FONT_SIZE = "choose font size"; // untranslated Blockly.Msg.ARD_OLED_FONT_TIP = "Select the font size to use to write text from now on"; // untranslated Blockly.Msg.ARD_OLED_INIT = "OLED Initialise"; // untranslated Blockly.Msg.ARD_OLED_PRINT = "print"; // untranslated Blockly.Msg.ARD_OLED_PRINT_NUMBER = "print number"; // untranslated Blockly.Msg.ARD_OLED_PRINT_NUMBER_DIGITS = "with #digits:"; // untranslated Blockly.Msg.ARD_OLED_PRINT_TIP = "Prepare to show the given text on the display in the given size. You need to use the write block to actually see it!"; // untranslated Blockly.Msg.ARD_OLED_RESOLUTIE = "with resolution"; // untranslated Blockly.Msg.ARD_OLED_WRITE = "write to display"; // untranslated Blockly.Msg.ARD_OLED_WRITE_TIP = "After you have printed text on the display, use this block to actually show the text."; // untranslated Blockly.Msg.ARD_OUTPUT_WRITE_TO = "value"; // untranslated Blockly.Msg.ARD_PIN_AN = "analog pin"; // untranslated Blockly.Msg.ARD_PIN_AN_TIP = "One of the analog pins of the Arduino Board"; // untranslated Blockly.Msg.ARD_PIN_DIG = "digital pin"; // untranslated Blockly.Msg.ARD_PIN_DIGDIG = "digital pin1 and pin2"; // untranslated Blockly.Msg.ARD_PIN_DIGDIG1 = "digital pin1#"; // untranslated Blockly.Msg.ARD_PIN_DIGDIG2 = "pin2#"; // untranslated Blockly.Msg.ARD_PIN_DIGDIG_TIP = "Component requiring two digital pins, pin1 and pin2"; // untranslated Blockly.Msg.ARD_PIN_DIG_TIP = "One of the digital pins of the Arduino Board"; // untranslated Blockly.Msg.ARD_PIN_PWM = "PWM pin"; // untranslated Blockly.Msg.ARD_PIN_PWM_TIP = "One of the Pulse Width Modeling (PWM) pins of the Arduino Board"; // untranslated Blockly.Msg.ARD_PIN_WARN1 = "Pin %1 is needed for %2 as pin %3. Already used as %4."; // untranslated Blockly.Msg.ARD_PULSEON = "pulse on pin #"; // untranslated Blockly.Msg.ARD_PULSEREAD = "Read"; // untranslated Blockly.Msg.ARD_PULSETIMEOUT = "timeout after"; // untranslated Blockly.Msg.ARD_PULSETIMEOUT_MS = ""; // untranslated Blockly.Msg.ARD_PULSETIMEOUT_TIP = "Measures the duration of a pulse on the selected pin, if it is within the timeout."; // untranslated Blockly.Msg.ARD_PULSE_READ = "measure %1 pulse on pin #%2"; // untranslated Blockly.Msg.ARD_PULSE_READ_TIMEOUT = "measure %1 pulse on pin #%2 (timeout after %3 μs)"; // untranslated Blockly.Msg.ARD_PULSE_TIP = "Measures the duration of a pulse on the selected pin."; // untranslated Blockly.Msg.ARD_PWMOUTPUT = "PWM output"; // untranslated Blockly.Msg.ARD_PWMOUTPUT_COMPONENT = "PWM Output"; // untranslated Blockly.Msg.ARD_PWMOUTPUT_DEFAULT_NAME = "PWMOutput1"; // untranslated Blockly.Msg.ARD_PWMOUTPUT_TIP = "Connect a generic PWM (Pulse Width Modulation) ouput to a pwm pin, so as to write an analog value to that pin. The value written should be a number between 0 and 255, and will generate a block pulse over this pin."; // untranslated Blockly.Msg.ARD_PWMOUTPUT_WRITE = "Write to PWM output"; // untranslated Blockly.Msg.ARD_SERIAL_BPS = "bps"; // untranslated Blockly.Msg.ARD_SERIAL_PRINT = "print"; // untranslated Blockly.Msg.ARD_SERIAL_PRINT_NEWLINE = "add new line"; // untranslated Blockly.Msg.ARD_SERIAL_PRINT_TIP = "Prints data to the console/serial port as human-readable ASCII text."; // untranslated Blockly.Msg.ARD_SERIAL_PRINT_WARN = "A setup block for %1 must be added to the workspace to use this block!"; // untranslated Blockly.Msg.ARD_SERIAL_SETUP = "Setup"; // untranslated Blockly.Msg.ARD_SERIAL_SETUP_TIP = "Selects the speed for a specific Serial peripheral"; // untranslated Blockly.Msg.ARD_SERIAL_SPEED = ": speed to"; // untranslated Blockly.Msg.ARD_SERVOHUB = "Servo motor"; // untranslated Blockly.Msg.ARD_SERVOHUB_READ = "read Servo "; // untranslated Blockly.Msg.ARD_SERVOHUB_TIP = "Servo Motor Connection, which can attach to a PWM pin. You have to give the servo a name, and what type it is (a 180 degree servo or a 360 degree servo.)"; // untranslated Blockly.Msg.ARD_SERVOHUB_WRITE = "set 180 degree Servo "; // untranslated Blockly.Msg.ARD_SERVO_COMPONENT = "servo"; // untranslated Blockly.Msg.ARD_SERVO_DEFAULT_NAME = "Servo1"; // untranslated Blockly.Msg.ARD_SERVO_READ = "read SERVO from PIN#"; // untranslated Blockly.Msg.ARD_SERVO_READ_TIP = "Read a Servo angle"; // untranslated Blockly.Msg.ARD_SERVO_ROTATE360 = "Rotate 360 degree Servo"; // untranslated Blockly.Msg.ARD_SERVO_ROTATEPERC = "% (-100 to 100)"; // untranslated Blockly.Msg.ARD_SERVO_ROTATESPEED = "with speed"; // untranslated Blockly.Msg.ARD_SERVO_ROTATE_TIP = "Turn a Servo with a specific speed"; // untranslated Blockly.Msg.ARD_SERVO_TYPE = "Type:"; // untranslated Blockly.Msg.ARD_SERVO_WRITE = "set SERVO from Pin"; // untranslated Blockly.Msg.ARD_SERVO_WRITE_DEG_180 = "Degrees (0~180)"; // untranslated Blockly.Msg.ARD_SERVO_WRITE_TIP = "Set a Servo to an specified angle"; // untranslated Blockly.Msg.ARD_SERVO_WRITE_TO = "to"; // untranslated Blockly.Msg.ARD_SETTONE = "Set tone on pin #"; // untranslated Blockly.Msg.ARD_SPI_SETUP = "Setup"; // untranslated Blockly.Msg.ARD_SPI_SETUP_CONF = "configuration:"; // untranslated Blockly.Msg.ARD_SPI_SETUP_DIVIDE = "clock divide"; // untranslated Blockly.Msg.ARD_SPI_SETUP_LSBFIRST = "LSBFIRST"; // untranslated Blockly.Msg.ARD_SPI_SETUP_MODE = "SPI mode (idle - edge)"; // untranslated Blockly.Msg.ARD_SPI_SETUP_MODE0 = "0 (Low - Falling)"; // untranslated Blockly.Msg.ARD_SPI_SETUP_MODE1 = "1 (Low - Rising)"; // untranslated Blockly.Msg.ARD_SPI_SETUP_MODE2 = "2 (High - Falling)"; // untranslated Blockly.Msg.ARD_SPI_SETUP_MODE3 = "3 (High - Rising)"; // untranslated Blockly.Msg.ARD_SPI_SETUP_MSBFIRST = "MSBFIRST"; // untranslated Blockly.Msg.ARD_SPI_SETUP_SHIFT = "data shift"; // untranslated Blockly.Msg.ARD_SPI_SETUP_TIP = "Configures the SPI peripheral."; // untranslated Blockly.Msg.ARD_SPI_TRANSRETURN_TIP = "Send a SPI message to an specified slave device and get data back."; // untranslated Blockly.Msg.ARD_SPI_TRANS_NONE = "none"; // untranslated Blockly.Msg.ARD_SPI_TRANS_SLAVE = "to slave pin"; // untranslated Blockly.Msg.ARD_SPI_TRANS_TIP = "Send a SPI message to an specified slave device."; // untranslated Blockly.Msg.ARD_SPI_TRANS_VAL = "transfer"; // untranslated Blockly.Msg.ARD_SPI_TRANS_WARN1 = "A setup block for %1 must be added to the workspace to use this block!"; // untranslated Blockly.Msg.ARD_SPI_TRANS_WARN2 = "Old pin value %1 is no longer available."; // untranslated Blockly.Msg.ARD_STEPPER_COMPONENT = "stepper"; // untranslated Blockly.Msg.ARD_STEPPER_DEFAULT_NAME = "MyStepper"; // untranslated Blockly.Msg.ARD_STEPPER_DEGREES = "degrees"; // untranslated Blockly.Msg.ARD_STEPPER_FOUR_PINS = "4"; // untranslated Blockly.Msg.ARD_STEPPER_ISROTATING = "in movement"; // untranslated Blockly.Msg.ARD_STEPPER_ISROTATING_TIP = "Returns true if the stepper is moving."; // untranslated Blockly.Msg.ARD_STEPPER_MOTOR = "stepper motor:"; // untranslated Blockly.Msg.ARD_STEPPER_NUMBER_OF_PINS = "Number of pins"; // untranslated Blockly.Msg.ARD_STEPPER_PIN1 = "pin1#"; // untranslated Blockly.Msg.ARD_STEPPER_PIN2 = "pin2#"; // untranslated Blockly.Msg.ARD_STEPPER_PIN3 = "pin3#"; // untranslated Blockly.Msg.ARD_STEPPER_PIN4 = "pin4#"; // untranslated Blockly.Msg.ARD_STEPPER_RESTART = "Get"; // untranslated Blockly.Msg.ARD_STEPPER_RESTART_AFTER = "ready"; // untranslated Blockly.Msg.ARD_STEPPER_RESTART_TIP = "Reset the motor ready after a rotation block has finished, so as to be able to rotate again"; // untranslated Blockly.Msg.ARD_STEPPER_REVOLVS = "how many steps per revolution"; // untranslated Blockly.Msg.ARD_STEPPER_ROTATE = "Rotate"; // untranslated Blockly.Msg.ARD_STEPPER_ROTATE_TIP = "Rotate the stepper motor over a number of degrees in a non-blocking way. This block must be called in the loop. When finished the stepper is blocked, and a call to restart movement is needed for the block to cause a next movement."; // untranslated Blockly.Msg.ARD_STEPPER_SETUP = "Setup stepper motor"; // untranslated Blockly.Msg.ARD_STEPPER_SETUP_TIP = "Configures a stepper motor pinout and other settings."; // untranslated Blockly.Msg.ARD_STEPPER_SPEED = "set speed (rpm) to"; // untranslated Blockly.Msg.ARD_STEPPER_SPEED_TIP = "Sets speed of the stepper motor. The steps are set at the speed needed to have the set RPM speed based on the given steps per revolution in the constructor."; // untranslated Blockly.Msg.ARD_STEPPER_STEP = "move stepper"; // untranslated Blockly.Msg.ARD_STEPPER_STEPS = "steps"; // untranslated Blockly.Msg.ARD_STEPPER_STEP_TIP = "Turns the stepper motor a specific number of steps."; // untranslated Blockly.Msg.ARD_STEPPER_TWO_PINS = "2"; // untranslated Blockly.Msg.ARD_TFT_BG_COLOUR = "Color of the background"; // untranslated Blockly.Msg.ARD_TFT_BG_TIP = "Fill the entire screen with the given colour"; // untranslated Blockly.Msg.ARD_TFT_CIRC_HEIGHT = "Height"; // untranslated Blockly.Msg.ARD_TFT_CIRC_RADIUS = "Radius"; // untranslated Blockly.Msg.ARD_TFT_CIRC_TIP = "Draw a circle on the screen with the given coordinates in the given colour. If Filled is checked the circle is filled, otherwise only an outline"; // untranslated Blockly.Msg.ARD_TFT_CIRC_XPOS = "X Position Center"; // untranslated Blockly.Msg.ARD_TFT_CIRC_YPOS = "Y Position Center"; // untranslated Blockly.Msg.ARD_TFT_COMPONENT = "TFT-Scherm"; // untranslated Blockly.Msg.ARD_TFT_COMPONENT_TIP = "The ST7735 1.8” Color TFT scherm. Scherm is 128x160 pixels."; // untranslated Blockly.Msg.ARD_TFT_FILLED = "Fill the drawing"; // untranslated Blockly.Msg.ARD_TFT_LINE_COLOUR = "Colour"; // untranslated Blockly.Msg.ARD_TFT_LINE_TIP = "Draw a line on the screen with the given coordinates in the given colour."; // untranslated Blockly.Msg.ARD_TFT_LINE_XPOSBEGIN = "X Position Start"; // untranslated Blockly.Msg.ARD_TFT_LINE_XPOSEND = "X Position End"; // untranslated Blockly.Msg.ARD_TFT_LINE_YPOSBEGIN = "Y Position Start"; // untranslated Blockly.Msg.ARD_TFT_LINE_YPOSEND = "Y Position End"; // untranslated Blockly.Msg.ARD_TFT_MAKE_CIRC = "Draw Circle"; // untranslated Blockly.Msg.ARD_TFT_MAKE_LINE = "Draw Line"; // untranslated Blockly.Msg.ARD_TFT_MAKE_RECT = "Draw Rectangle"; // untranslated Blockly.Msg.ARD_TFT_RECT_COLOUR = "Colour"; // untranslated Blockly.Msg.ARD_TFT_RECT_HEIGHT = "Height"; // untranslated Blockly.Msg.ARD_TFT_RECT_TIP = "Draw a rectangle on the screen with the given coordinates in the given colour. If Filled is checked the rectangle is filled, otherwise only an outline"; // untranslated Blockly.Msg.ARD_TFT_RECT_WIDTH = "Width"; // untranslated Blockly.Msg.ARD_TFT_RECT_XPOSBEGIN = "X Position Top Left"; // untranslated Blockly.Msg.ARD_TFT_RECT_YPOSBEGIN = "Y Position Top Left"; // untranslated Blockly.Msg.ARD_TFT_SPRITE_NAME = "Sprite named"; // untranslated Blockly.Msg.ARD_TFT_TEXT_COLOUR = "Colour of the text"; // untranslated Blockly.Msg.ARD_TFT_TEXT_SIZE = "Size"; // untranslated Blockly.Msg.ARD_TFT_TEXT_TIP = "Write a text to the screen in the given colour at the given position."; // untranslated Blockly.Msg.ARD_TFT_TEXT_WRITE = "Write text"; // untranslated Blockly.Msg.ARD_TFT_TEXT_XPOS = "X Position"; // untranslated Blockly.Msg.ARD_TFT_TEXT_YPOS = "Y Position"; // untranslated Blockly.Msg.ARD_TIME_DELAY = "wait"; // untranslated Blockly.Msg.ARD_TIME_DELAY_MICROS = "microseconds"; // untranslated Blockly.Msg.ARD_TIME_DELAY_MICRO_TIP = "Wait specific time in microseconds"; // untranslated Blockly.Msg.ARD_TIME_DELAY_TIP = "Wait specific time in milliseconds"; // untranslated Blockly.Msg.ARD_TIME_INF = "wait forever (end program)"; // untranslated Blockly.Msg.ARD_TIME_INF_TIP = "Wait indefinitely, stopping the program."; // untranslated Blockly.Msg.ARD_TIME_MICROS = "current elapsed Time (microseconds)"; // untranslated Blockly.Msg.ARD_TIME_MICROS_TIP = "Returns the number of microseconds since the Arduino board began running the current program. Has to be stored in a positive long integer"; // untranslated Blockly.Msg.ARD_TIME_MILLIS = "current elapsed Time (milliseconds)"; // untranslated Blockly.Msg.ARD_TIME_MILLIS_TIP = "Returns the number of milliseconds since the Arduino board began running the current program. Has to be stored in a positive long integer"; // untranslated Blockly.Msg.ARD_TIME_MS = "milliseconds"; // untranslated Blockly.Msg.ARD_TONEDURATION = "and duration (ms)"; // untranslated Blockly.Msg.ARD_TONEDURATION_TIP = "Sets tone on a buzzer to the specified frequency within range 31 - 65535 and given duration in milliseconds. Careful: a durations continues, also during delays, a new tone can only be given if a previous tone is terminated!"; // untranslated Blockly.Msg.ARD_TONEFREQ = "at frequency"; // untranslated Blockly.Msg.ARD_TONEPITCH_TIP = "Sets tone on a buzzer to the specified pitch and given duration in milliseconds. Careful: a durations continues, also during delays, a new tone can only be given if a previous tone is terminated!"; // untranslated Blockly.Msg.ARD_TONE_FREQ = "frequency"; // untranslated Blockly.Msg.ARD_TONE_PIN = "Tone PIN#"; // untranslated Blockly.Msg.ARD_TONE_PIN_TIP = "Generate audio tones on a pin"; // untranslated Blockly.Msg.ARD_TONE_TIP = "Sets tone on pin to specified frequency within range 31 - 65535"; // untranslated Blockly.Msg.ARD_TONE_WARNING = "Frequency must be in range 31 - 65535"; // untranslated Blockly.Msg.ARD_TONE_WARNING2 = "A duration must be positive (>0)"; // untranslated Blockly.Msg.ARD_TYPE_ARRAY = "Array"; // untranslated Blockly.Msg.ARD_TYPE_BOOL = "Boolean"; // untranslated Blockly.Msg.ARD_TYPE_CHAR = "Character"; // untranslated Blockly.Msg.ARD_TYPE_CHILDBLOCKMISSING = "ChildBlockMissing"; // untranslated Blockly.Msg.ARD_TYPE_DECIMAL = "Decimal"; // untranslated Blockly.Msg.ARD_TYPE_LONG = "Large Number"; // untranslated Blockly.Msg.ARD_TYPE_NULL = "Null"; // untranslated Blockly.Msg.ARD_TYPE_NUMBER = "Number"; // untranslated Blockly.Msg.ARD_TYPE_SHORT = "Short Number"; // untranslated Blockly.Msg.ARD_TYPE_TEXT = "Text"; // untranslated Blockly.Msg.ARD_TYPE_UNDEF = "Undefined"; // untranslated Blockly.Msg.ARD_UNKNOWN_ALLBOTJOINT = "The old joint value %1 is no longer available"; // untranslated Blockly.Msg.ARD_VAR_AS = "as"; // untranslated Blockly.Msg.ARD_VAR_AS_TIP = "Sets a value to a specific type"; // untranslated Blockly.Msg.ARD_WRITE_TO = "to"; // untranslated Blockly.Msg.B4A_COMPILE_EMPTY = "Compiler returned empty file - Device not flashed"; // untranslated Blockly.Msg.B4A_ERROR = "ERROR!"; // untranslated Blockly.Msg.B4A_FLASHING = "Flashing to device"; // untranslated Blockly.Msg.B4A_MSG_EXTENSION = "Message from extension: "; // untranslated Blockly.Msg.B4A_NO_CHROME = "You need to use Google Chrome to use this Upload functionality"; // untranslated Blockly.Msg.B4A_NO_EXTENSION = "Chrome Extension is not installed"; // untranslated Blockly.Msg.B4A_SET_IP_COMPILER = "New IP Address Compiler"; // untranslated Blockly.Msg.B4A_SUCCESS = "SUCCESS!"; // untranslated Blockly.Msg.B4A_UPLOAD_FAIL = "Upload failed. Chrome Extension is not installed"; // untranslated Blockly.Msg.B4A_VERIFY_FAIL = "Verify failed. Chrome Extension is not installed"; // untranslated Blockly.Msg.COLOUR_RGB255_TOOLTIP = "Create a colour with the specified amount of red, green, and blue. All values must be between 0 and 255. See https://www.google.be/search?q=color+picker"; // untranslated Blockly.Msg.NEW_INSTANCE = "New instance..."; // untranslated Blockly.Msg.NEW_INSTANCE_TITLE = "New instance name:"; // untranslated Blockly.Msg.RENAME_INSTANCE = "Rename instance..."; // untranslated Blockly.Msg.RENAME_INSTANCE_TITLE = "Rename all '%1' instances to:"; // untranslated Blockly.Msg.REPLACE_EXISTING_BLOCKS = "Replace existing blocks? 'Cancel' will merge."; // untranslated Blockly.Msg.UPLOAD_CLICK_1 = "To Upload your code to Arduino:"; // untranslated Blockly.Msg.UPLOAD_CLICK_2 = " 1. click on the Arduino tab"; // untranslated Blockly.Msg.UPLOAD_CLICK_3 = " 2. select all the code, and copy (CTRL+A and CTRL+C)"; // untranslated Blockly.Msg.UPLOAD_CLICK_4 = " 3. In the Arduino IDE or in a http://codebender.cc sketch, paste the code (CTRL+V)"; // untranslated Blockly.Msg.UPLOAD_CLICK_5 = " 4. Upload to your connected Arduino"; // untranslated Blockly.Msg.ARD_CONTROLS_EFFECT_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO; Blockly.Msg.ARD_CONTROLS_EFFECT_IF_TITLE_IF = Blockly.Msg.ARD_CONTROLS_EFFECT_MSG_IF; Blockly.Msg.ARD_CONTROLS_EFFECT_IF_TOOLTIP = Blockly.Msg.CONTROLS_IF_IF_TOOLTIP; Blockly.Msg.ARD_CONTROLS_EFFECT_ELSEIF_TITLE_ELSEIF = Blockly.Msg.ARD_CONTROLS_EFFECT_MSG_ELSEIF; Blockly.Msg.ARD_CONTROLS_EFFECT_ELSE_TITLE_ELSE = Blockly.Msg.ARD_CONTROLS_EFFECT_MSG_ELSE;
ingegno/Blockly4Arduino
Blockly4Arduino/msg/js/lki.js
JavaScript
apache-2.0
84,017
import React, {Component, Fragment} from "react"; import {Card, Button, ListGroup, ListGroupItem} from "helpers/reactstrap"; import {Duration} from "luxon"; import {Mutation} from "react-apollo"; import gql from "graphql-tag.macro"; import {capitalCase} from "change-case"; export function parseDuration(time) { return Object.entries( Duration.fromObject({ months: 0, weeks: 0, days: 0, hours: 0, minutes: 0, seconds: Math.round((time || 0) / 1000), }) .normalize() .toObject(), ) .filter(t => t[1] !== 0) .map(t => `${t[1]} ${capitalCase(t[0])}`) .join(", "); } class Timer extends Component { state = {}; componentDidMount() { this.timeout = setInterval(() => { this.forceUpdate(); }, 1000); } componentWillUnmount() { clearInterval(this.timeout); } render() { const {endTime, startTime} = this.props; if (!startTime) return parseDuration(endTime); return parseDuration( (endTime ? new Date(endTime) : new Date()) - new Date(startTime), ); } } class TasksManager extends Component { state = {}; render() { const {tasks, newTask, stats} = this.props; const {selectedTask, showDismissed} = this.state; const taskGroup = tasks.reduce((prev, next) => { if (!showDismissed && next.dismissed) return prev; prev[next.station] = prev[next.station] ? prev[next.station].concat(next) : [next]; return prev; }, {}); const task = tasks.find(t => t.id === selectedTask); return ( <div style={{display: "flex", flexDirection: "column", height: "100%"}}> <div style={{display: "flex", flex: 1}}> <div style={{flex: 1, display: "flex", flexDirection: "column"}}> <p>Tasks</p> <Mutation mutation={gql` mutation DismissVerified($simulatorId: ID!) { dismissVerifiedTasks(simulatorId: $simulatorId) } `} variables={{simulatorId: this.props.simulator.id}} > {action => ( <Button size="sm" color="info" block onClick={action}> Dismiss Verified </Button> )} </Mutation> <p> <label> Show Dismissed:{" "} <input type="checkbox" checked={showDismissed} onChange={e => this.setState({showDismissed: e.target.checked}) } /> </label> </p> <ListGroup style={{flex: 1, overflowY: "auto"}}> {Object.entries(taskGroup).map(([key, value]) => ( <Fragment key={key}> <ListGroupItem disabled>{key}</ListGroupItem> {value .concat() .sort((a, b) => { if (a.verified > b.verified) return 1; if (b.verified > a.verified) return -1; return 0; }) .map(t => ( <ListGroupItem key={t.id} active={t.id === selectedTask} onClick={() => this.setState({selectedTask: t.id})} className={`${t.verifyRequested ? "text-info" : ""} ${ t.verified ? "text-success" : "" }`} > {t.definition} </ListGroupItem> ))} </Fragment> ))} </ListGroup> </div> <div style={{flex: 3, overflowY: "auto"}}> <p>Task Information</p> {task && ( <Fragment> <p> <strong>Verified:</strong> {task.verified ? "Yes" : "No"} </p> <p> <strong>Time Elapsed:</strong> <Timer {...task} />{" "} </p> <p> <strong>Instructions:</strong> </p> <Card style={{whiteSpace: "pre-wrap"}}> {task.instructions} </Card> {!task.verified && ( <Fragment> <Mutation mutation={gql` mutation VerifyTask($taskId: ID!) { verifyTask(taskId: $taskId) } `} variables={{taskId: task.id}} > {action => ( <Button size="sm" color="success" onClick={() => { action(); this.setState({selectedTask: null}); }} > Verify </Button> )} </Mutation> <Mutation mutation={gql` mutation VerifyTask($taskId: ID!) { verifyTask(taskId: $taskId, dismiss: true) } `} variables={{taskId: task.id}} > {action => ( <Button size="sm" color="success" onClick={() => { action(); this.setState({selectedTask: null}); }} > Verify {"&"} Dismiss </Button> )} </Mutation> {task.verifyRequested && ( <Mutation mutation={gql` mutation RejectTask($taskId: ID!) { denyTaskVerify(id: $taskId) } `} variables={{taskId: task.id}} > {action => ( <Button size="sm" color="danger" onClick={() => { action(); }} > Reject </Button> )} </Mutation> )} </Fragment> )} </Fragment> )} </div> </div> <div style={{display: "flex"}}> <Button block color="success" size="sm" onClick={newTask}> New Task </Button> <Button block color="info" size="sm" onClick={stats}> Stats </Button> </div> </div> ); } } export default TasksManager;
Thorium-Sim/thorium
src/components/views/Tasks/core/TasksManager.js
JavaScript
apache-2.0
7,238
/* Copyright 2017 Aleksandar Jankovic 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 express = require('express'); const objectValidator = require('../../utils/objectValidator'); const walletManager = require('../../managers/wallets'); const transactionManager = require('../../managers/transactions'); const restErrorChecker = require('../../helpers/restErrorChecker'); const errorCreator = require('../../objects/error/errorCreator'); const router = new express.Router(); /** * @param {Object} io Socket io * @returns {Object} Router */ function handle(io) { /** * @api {get} /wallets/ Get wallets * @apiVersion 6.0.0 * @apiName GetWallets * @apiGroup Wallets * * @apiHeader {String} Authorization Your JSON Web Token * * @apiDescription Get wallets that is owned by the user ot their team * * @apiSuccess {Object} data * @apiSuccess {Object} data.wallet Found wallets * @apiSuccessExample {json} Success-Response: * { * "data": { * "wallets": [{ * "owner": "abc", * "amount": 10, * "isProtected": false, * "accessLevel": 1 * }, { * "owner": "qwer", * "amount": 13, * "isProtected": false, * "accessLevel": 1 * }] * } * } */ router.get('/', (request, response) => { walletManager.getWallets({ token: request.headers.authorization, callback: ({ error, data }) => { if (error) { restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); return; } response.json({ data }); }, }); }); /** * @api {get} /wallets/:owner Get wallet by owner * @apiVersion 6.0.0 * @apiName GetWallet * @apiGroup Wallets * * @apiHeader {String} Authorization Your JSON Web Token * * @apiDescription Get wallet by owner * * @apiParam {string} owner Name of the owner of the wallet * * @apiSuccess {Object} data * @apiSuccess {Object} data.wallet Found wallet * @apiSuccessExample {json} Success-Response: * { * "data": { * "wallet": { * "owner": "", * "amount": 10, * "isProtected": false, * "accessLevel": 1 * } * } * } */ router.get('/:owner', (request, response) => { if (!objectValidator.isValidData(request.params, { owner: true })) { restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '' }), sentData: request.body.data }); return; } walletManager.getWallet({ owner: request.params.owner, token: request.headers.authorization, callback: ({ error, data }) => { if (error) { restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); return; } response.json({ data }); }, }); }); /** * @api {post} /wallets/:owner/increase Increase wallet amount * @apiVersion 6.0.0 * @apiName IncreaseWalletAmount * @apiGroup Wallets * * @apiHeader {String} Authorization Your JSON Web Token * * @apiDescription Increase wallet amount * * @apiParam {String} owner Name of the owner of the wallet * * @apiParam {Object} data * @apiParam {Object} data.amount Amount to increase * @apiParamExample {json} Request-Example: * { * "data": { * "amount": 8 * } * } * * @apiSuccess {Object} data * @apiSuccess {Object} data.wallet Updated wallet * @apiSuccessExample {json} Success-Response: * { * "data": { * "wallet": { * "owner": "abc", * "amount": 18, * "isProtected": false, * "accessLevel": 1 * } * } * } */ router.post('/:owner/increase', (request, response) => { if (!objectValidator.isValidData(request.params, { owner: true })) { restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '' }), sentData: request.body.data }); return; } else if (!objectValidator.isValidData(request.body, { data: { amount: true } })) { restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '' }), sentData: request.body.data }); return; } walletManager.increaseWalletAmount({ token: request.headers.authorization, amount: request.body.data.amount, owner: request.params.owner, callback: ({ error, data }) => { if (error) { restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); return; } response.json({ data }); }, }); }); /** * @api {post} /wallets/:owner/decrease Decrease wallet amount * @apiVersion 6.0.0 * @apiName DecreaseWalletAmount * @apiGroup Wallets * * @apiHeader {String} Authorization Your JSON Web Token * * @apiDescription Decrease wallet amount * * @apiParam {String} owner Name of the owner of the wallet * * @apiParam {Object} data * @apiParam {Object} data.amount Amount to decrease * @apiParamExample {json} Request-Example: * { * "data": { * "amount": 8 * } * } * * @apiSuccess {Object} data * @apiSuccess {Object} data.wallet Updated wallet * @apiSuccessExample {json} Success-Response: * { * "data": { * "wallet": { * "owner": "abc", * "amount": 2, * "isProtected": false, * "accessLevel": 1 * } * } * } */ router.post('/:owner/decrease', (request, response) => { if (!objectValidator.isValidData(request.params, { owner: true })) { restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '' }), sentData: request.body.data }); return; } else if (!objectValidator.isValidData(request.body, { data: { amount: true } })) { restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '' }), sentData: request.body.data }); return; } walletManager.decreaseWalletAmount({ owner: request.params.owner, amount: request.body.data.amount, token: request.headers.authorization, callback: ({ error, data }) => { if (error) { restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); return; } response.json({ data }); }, }); }); /** * @api {post} /wallets/:owner/empty Reset wallet amount to 0 * @apiVersion 6.0.0 * @apiName EmptyWallet * @apiGroup Wallets * * @apiHeader {String} Authorization Your JSON Web Token * * @apiDescription Reset wallet amount to 0 * * @apiParam {String} owner Name of the owner of the wallet * * @apiSuccess {Object} data * @apiSuccess {Object} data.wallet Updated wallet * @apiSuccessExample {json} Success-Response: * { * "data": { * "wallet": { * "owner": "abc", * "amount": 0, * "isProtected": false, * "accessLevel": 1 * } * } * } */ router.post('/:owner/empty', (request, response) => { if (!objectValidator.isValidData(request.params, { owner: true })) { restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '' }), sentData: request.body.data }); return; } walletManager.emptyWallet({ owner: request.params.owner, token: request.headers.authorization, callback: ({ error, data }) => { if (error) { restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); return; } response.json({ data }); }, }); }); /** * @api {get} /wallets/:owner/transactions Get transactions * @apiVersion 6.0.0 * @apiName GetTransactions * @apiGroup Transactions * * @apiHeader {string} Authorization Your JSON Web Token * * @apiDescription Get transactions * * @apiParam {string} owner Name of the owner of the wallet * * @apiSuccess {Object} data * @apiSuccess {Object[]} data.toTransactions Transactions with the user being the receiver * @apiSuccess {Object[]} data.fromTransactions Transactions with the user being the sender * @apiSuccessExample {json} Success-Response: * { * "data": { * "toTransactions": [ * { * "to": "rez", * "from": "n4", * "time": "2016-11-28T22:42:06.262Z", * "note": "Bounty payment", * "amount": 10 * } * ], * "fromTransactions": [ * { * "to": "bas", * "from": "rez", * "time:" "2016-10-28T22:42:06.262Z" * "amount:" 5 * } * ] * } * } */ router.get('/:owner/transactions', (request, response) => { if (!objectValidator.isValidData(request.params, { owner: true })) { restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '' }), sentData: request.body.data }); return; } transactionManager.getTransactions({ owner: request.params.owner, token: request.headers.authorization, callback: ({ error, data }) => { if (error) { restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); return; } response.json({ data }); }, }); }); /** * @api {post} /wallets/:owner/transactions Create a transaction * @apiVersion 6.0.0 * @apiName CreateTransaction * @apiGroup Wallets * * @apiHeader {String} Authorization Your JSON Web Token * * @apiDescription Create a transaction * * @apiParam {Object} data * @apiParam {Object} data.transaction Transaction * @apiParam {string} data.transaction.to User or team name of the receiver * @apiParam {string} data.transaction.amount Amount to transfer * @apiParam {string} [data.transaction.note] Note to the receiver * @apiParam {Object} [data.transaction.coordinates] GPS coordinates to where the transaction was made * @apiParam {number} data.transaction.coordinates.longitude Longitude * @apiParam {number} data.transaction.coordinates.latitude Latitude * @apiParam {number} [data.isTeamWallet] Should the transaction be created on the user's team? * @apiParamExample {json} Request-Example: * { * "data": { * "transaction": { * "to": "baz", * "amount": 10, * "note": "Bounty payment", * "coordinates": { * "longitude": 10.11, * "latitude": 12.4443 * } * } * } * } * * @apiSuccess {Object} data * @apiSuccess {Object} data.transaction Transaction created * @apiSuccess {Object} data.wallet Wallet with new amount after transfer * @apiSuccessExample {json} Success-Response: * { * "data": { * "transaction": { * "to": "baz", * "amount": 10, * "note": "Bounty payment", * "coordinates": { * "longitude": 10.11, * "latitude": 12.4443 * } * }, * "wallet": { * "amount": 23 * } * } * } */ router.post('/:owner/transactions', (request, response) => { if (!objectValidator.isValidData(request.body, { data: { transaction: { to: true, amount: true } } }) || isNaN(request.body.data.transaction.amount)) { restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '' }), sentData: request.body.data }); return; } transactionManager.createTransactionBasedOnToken({ io, transaction: request.body.data.transaction, fromTeam: request.body.data.isTeamWallet, token: request.headers.authorization, callback: ({ error, data }) => { if (error) { restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); return; } response.json({ data }); }, }); }); return router; } module.exports = handle;
stanislavb/roleHaven
routes/rest/wallets.js
JavaScript
apache-2.0
12,825
#!/usr/bin/env node /** * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ let baseModule; try { // To support easy development when making changes in the source repo, we // first try looking for a copy of the base module using a relative path. In // this context, we prefer the local copy over one that may already be // installed. baseModule = require('../../generic-webdriver-server'); } catch (error) { if (!error.message.includes('Cannot find module')) { throw error; } // When this module is running in an installed context, we fall back to // requiring the installed base module by name. baseModule = require('generic-webdriver-server'); } const {GenericSingleSessionWebDriverServer, yargs} = baseModule; const { checkPlatformRequirements, loadOnXboxOne, takeScreenshot, addXboxOneArgs, } = require('./xbox-one-utils'); /** WebDriver server backend for Xbox One */ class XboxOneWebDriverServer extends GenericSingleSessionWebDriverServer { constructor() { super(); checkPlatformRequirements(); } /** @override */ async navigateToSingleSession(url) { await loadOnXboxOne(this.flags, this.log, url); } /** @override */ async closeSingleSession() { // Send the device back to the home screen. await loadOnXboxOne(this.flags, this.log, null); } /** @override */ async screenshot(sessionId) { return await takeScreenshot( this.flags.hostname, this.flags.username, this.flags.password); } } addXboxOneArgs(yargs); const server = new XboxOneWebDriverServer(); server.listen();
shaka-project/generic-webdriver-server
backends/xboxone/xbox-one-webdriver-server.js
JavaScript
apache-2.0
2,114
import app from './app'; app.run(process.argv);
kennethlimcp/particle-cli
src/app/launch.js
JavaScript
apache-2.0
48
/***************************************************************************** ** Copyright (C) 2015 Intel 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. ** *****************************************************************************/ console.log('you\'r in the world of content.js'); var cryptid = 1; var script = document.createElement('script'); script.src = chrome.extension.getURL('gmail/inject.js'); script.onload = function() { this.parentNode.removeChild(this); }; (document.head||document.documentElement).appendChild(script); function reeeplace() { $( ".a3s:contains(crypted_stuff)").each(function() { if($(this).hasClass("handled")) { } else { $(this).addClass("handled") cryptid = cryptid + 1; var cryid = "cryptid" + cryptid; var old_content = $(this).html().replace('crypted_stuff ',''); $(this).empty().append("<div class='crypted' id='"+cryid+"'>" + old_content + "</div>"); $(this).append("<div class='crypted_info' onclick='decrypt(\""+cryid+"\");style.visibility=\"hidden\";'>content is crypted, click here to show</div>"); $(this).children(".crypted").css("opacity","0.3"); $(this).children(".crypted_info").css("background-color","red"); console.log('added uncrypt button'); } }); $( ".editable").each(function() { if($(this).hasClass("encryption")) { } else { $(this).addClass("encryption"); console.log("id" + $(this).attr('id') ); $(this).closest('tr').append("<td class='Ap'><div class='crypted_info' style=\"background-color:green;color:white\" onclick='encrypt(\""+$(this).attr('id') +"\");style.visibility=\"hidden\";'>encrypt</div></td>"); } }); } reeeplace(); MutationObserver = window.MutationObserver || window.WebKitMutationObserver; var observer = new MutationObserver(function(mutations, observer) { reeeplace(); }); // define what element should be observed by the observer // and what types of mutations trigger the callback observer.observe(document, { subtree: true, attributes: true //... });
Open-TEE/opentee-extension-chrome
extension/gmail/content.js
JavaScript
apache-2.0
3,021
/** * Copyright 2015 The AMP HTML 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 argv = require('minimist')(process.argv.slice(2)); const browserifyPersistFs = require('browserify-persist-fs'); const crypto = require('crypto'); const fs = require('fs'); const globby = require('globby'); const {isCiBuild} = require('../common/ci'); const TEST_SERVER_PORT = 8081; const COMMON_CHROME_FLAGS = [ // Dramatically speeds up iframe creation time. '--disable-extensions', // Allows simulating user actions (e.g unmute) which otherwise will be denied. '--autoplay-policy=no-user-gesture-required', ]; if (argv.debug) { COMMON_CHROME_FLAGS.push('--auto-open-devtools-for-tabs'); } // Used by persistent browserify caching to further salt hashes with our // environment state. Eg, when updating a babel-plugin, the environment hash // must change somehow so that the cache busts and the file is retransformed. const createHash = (input) => crypto.createHash('sha1').update(input).digest('hex'); const persistentCache = browserifyPersistFs( '.karma-cache', { deps: createHash(fs.readFileSync('./package-lock.json')), build: globby .sync([ 'build-system/**/*.js', '!build-system/eslint-rules', '!**/test/**', ]) .map((f) => { return createHash(fs.readFileSync(f)); }), }, () => { process.stdout.write('.'); } ); persistentCache.gc( { maxAge: 1000 * 60 * 60 * 24 * 7, }, () => { // swallow errors } ); /** * @param {!Object} config */ module.exports = { frameworks: [ 'fixture', 'browserify', 'mocha', 'sinon-chai', 'chai', 'source-map-support', ], preprocessors: { // `test-bin` is the output directory of the postHTML transformation. './test-bin/test/fixtures/*.html': ['html2js'], './test/**/*.js': ['browserify'], './ads/**/test/test-*.js': ['browserify'], './extensions/**/test/**/*.js': ['browserify'], './testing/**/*.js': ['browserify'], }, html2JsPreprocessor: { // Strip the test-bin/ prefix for the transformer destination so that the // change is transparent for users of the path. stripPrefix: 'test-bin/', }, hostname: 'localhost', browserify: { watch: true, debug: true, fast: true, basedir: __dirname + '/../../', transform: [['babelify', {caller: {name: 'test'}, global: true}]], // Prevent "cannot find module" errors during CI. See #14166. bundleDelay: isCiBuild() ? 5000 : 1200, persistentCache, }, reporters: ['super-dots', 'karmaSimpleReporter'], superDotsReporter: { nbDotsPerLine: 100000, color: { success: 'green', failure: 'red', ignore: 'yellow', }, icon: { success: '●', failure: '●', ignore: '○', }, }, specReporter: { suppressPassed: true, suppressSkipped: true, suppressFailed: false, suppressErrorSummary: true, maxLogLines: 20, }, mochaReporter: { output: 'full', colors: { success: 'green', error: 'red', info: 'yellow', }, symbols: { success: '●', error: '●', info: '○', }, }, port: 9876, colors: true, proxies: { '/ads/': '/base/ads/', '/dist/': '/base/dist/', '/dist.3p/': '/base/dist.3p/', '/examples/': '/base/examples/', '/extensions/': '/base/extensions/', '/src/': '/base/src/', '/test/': '/base/test/', }, // Can't import the Karma constant config.LOG_ERROR, so we hard code it here. // Hopefully it'll never change. logLevel: 'ERROR', autoWatch: true, customLaunchers: { /* eslint "google-camelcase/google-camelcase": 0*/ Chrome_ci: { base: 'Chrome', flags: ['--no-sandbox'].concat(COMMON_CHROME_FLAGS), }, Chrome_no_extensions: { base: 'Chrome', flags: COMMON_CHROME_FLAGS, }, Chrome_no_extensions_headless: { base: 'ChromeHeadless', flags: [ // https://developers.google.com/web/updates/2017/04/headless-chrome#frontend '--no-sandbox', '--remote-debugging-port=9222', // https://github.com/karma-runner/karma-chrome-launcher/issues/175 "--proxy-server='direct://'", '--proxy-bypass-list=*', ].concat(COMMON_CHROME_FLAGS), }, }, client: { mocha: { reporter: 'html', // Longer timeout during CI; fail quickly during local runs. timeout: isCiBuild() ? 10000 : 2000, // Run tests up to 3 times before failing them during CI. retries: isCiBuild() ? 2 : 0, }, captureConsole: false, verboseLogging: false, testServerPort: TEST_SERVER_PORT, }, singleRun: true, captureTimeout: 4 * 60 * 1000, failOnEmptyTestSuite: false, // Give a disconnected browser 2 minutes to reconnect with Karma. // This allows a browser to retry 2 times per `browserDisconnectTolerance` // during CI before stalling out after 10 minutes. browserDisconnectTimeout: 2 * 60 * 1000, // If there's no message from the browser, make Karma wait 2 minutes // until it disconnects. browserNoActivityTimeout: 2 * 60 * 1000, // IF YOU CHANGE THIS, DEBUGGING WILL RANDOMLY KILL THE BROWSER browserDisconnectTolerance: isCiBuild() ? 2 : 0, // Import our gulp webserver as a Karma server middleware // So we instantly have all the custom server endpoints available beforeMiddleware: ['custom'], plugins: [ '@chiragrupani/karma-chromium-edge-launcher', 'karma-browserify', 'karma-chai', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-fixture', 'karma-html2js-preprocessor', 'karma-ie-launcher', 'karma-structured-json-reporter', 'karma-mocha', 'karma-mocha-reporter', 'karma-safarinative-launcher', 'karma-simple-reporter', 'karma-sinon-chai', 'karma-source-map-support', 'karma-super-dots-reporter', { 'middleware:custom': [ 'factory', function () { return require(require.resolve('../server/app.js')); }, ], }, ], };
zhouyx/amphtml
build-system/tasks/karma.conf.js
JavaScript
apache-2.0
6,661
/* * Copyright 2017 The CodeWorld 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. */ /* * Utility function for sending an HTTP request to fetch a resource. * * Args: * - method: The HTTP method to use, such as 'GET' * - url: The URL to fetch, whether absolute or relative. * - body: The request body to send. Use null for no body. * - callback: A callback function to send when complete. (optional) * * If provided, the callback will be given the XmlHttpRequest object, so * it can inspect the response code and headers as well as the contents. */ function sendHttp(method, url, body, callback) { var request = new XMLHttpRequest(); if (callback) { request.onreadystatechange = function() { if (request.readyState == 4) callback(request); }; } request.open(method, url, true); request.send(body); } function registerStandardHints(successFunc) { function createHint(line, wordStart, wordEnd, cname) { var word = line.slice(wordStart, wordEnd); if (!cname) cname = 'hint-word'; function renderer(elem, data, cur) { if (wordStart > 0) { elem.appendChild(document.createTextNode(line.slice(0, wordStart))); } var wordElem = document.createElement("span"); wordElem.className = cname; wordElem.appendChild(document.createTextNode(word)); elem.appendChild(wordElem); if (wordEnd < line.length) { elem.appendChild(document.createTextNode(line.slice(wordEnd))); } } return { text: word, render: renderer, source: line }; } // Add hint highlighting var hints = [ createHint("main :: Program", 0, 4), createHint("program :: Program", 0, 7), createHint("-- single line comment", 0, 2, 'hint-keyword'), createHint("{- start a multi-line comment", 0, 2, 'hint-keyword'), createHint("-} end a multi-line comment", 0, 2, 'hint-keyword'), createHint(":: write a type annotation", 0, 2, 'hint-keyword'), createHint("-> declare a function type or case branch", 0, 2, 'hint-keyword'), createHint("<- list comprehension index", 0, 2, 'hint-keyword'), createHint(".. list range", 0, 2, 'hint-keyword'), createHint("case decide between many options", 0, 4, 'hint-keyword'), createHint("of finish a case statement", 0, 2, 'hint-keyword'), createHint("if decide between two choices", 0, 2, 'hint-keyword'), createHint("then 1st choice of an if statement", 0, 4, 'hint-keyword'), createHint("else 2nd choice of an if statement", 0, 4, 'hint-keyword'), createHint("data define a new data type", 0, 4, 'hint-keyword'), createHint("let define local variables", 0, 3, 'hint-keyword'), createHint("in finish a let statement", 0, 2, 'hint-keyword'), createHint("where define local variables", 0, 5, 'hint-keyword'), createHint("type define a type synonym", 0, 4, 'hint-keyword'), createHint("(:) :: a -> [a] -> [a]", 1, 2) ]; CodeMirror.registerHelper('hint', 'codeworld', function(cm) { var cur = cm.getCursor(); var token = cm.getTokenAt(cur); var to = CodeMirror.Pos(cur.line, token.end); //To check for the case of insertion in between two parameters r = new RegExp("^\\s+$"); // If string is completely made of spaces if (r.test(token.string)) { token.string = token.string.substr(0, cur.ch - token.start); token.end = cur.ch; to = CodeMirror.Pos(cur.line, token.end); } if (token.string && /\w/.test(token.string[token.string.length - 1])) { var term = token.string, from = CodeMirror.Pos(cur.line, token.start); } else { var term = "", from = to; } var found = []; for (var i = 0; i < hints.length; i++) { var hint = hints[i]; if (hint.text.slice(0, term.length) == term) found.push(hint); } if (found.length) return { list: found, from: from, to: to }; }); sendHttp('GET', 'codeworld-base.txt', null, function(request) { var lines = []; if (request.status != 200) { console.log('Failed to load autocomplete word list.'); } else { lines = request.responseText.split('\n'); } var startLine = lines.indexOf('module Prelude') + 1; var endLine = startLine; while (endLine < lines.length) { if (lines[endLine].startsWith("module ")) { break; } endLine++; } lines = lines.slice(startLine, endLine); // Special case for "main" and "program", since they are morally // built-in names. codeworldKeywords['main'] = 'builtin'; codeworldKeywords['program'] = 'builtin'; lines = lines.sort().filter(function(item, pos, array) { return !pos || item != array[pos - 1]; }); var hintBlacklist = [ // Symbols that only exist to implement RebindableSyntax, map to // built-in Haskell types, or maintain backward compatibility. "Bool", "IO", "fail", "fromCWText", "fromDouble", "fromHSL", "fromInt", "fromInteger", "fromRandomSeed", "fromRational", "fromString", "ifThenElse", "line", "negate", "pictureOf", "randomsFrom", "thickLine", "toCWText", "toDouble", "toInt", ]; lines.forEach(function(line) { if (line.startsWith("type Program")) { // We must intervene to hide the IO type. line = "data Program"; } else if (line.startsWith("type Truth")) { line = "data Truth"; } else if (line.startsWith("True ::")) { line = "True :: Truth"; } else if (line.startsWith("False ::")) { line = "False :: Truth"; } else if (line.startsWith("newtype ")) { // Hide the distinction between newtype and data. line = "data " + line.substr(8); } else if (line.startsWith("pattern ")) { // Hide the distinction between patterns and constructors. line = line.substr(8); } else if (line.startsWith("class ")) { return; } else if (line.startsWith("instance ")) { return; } else if (line.startsWith("-- ")) { return; } else if (line.startsWith("infix ")) { return; } else if (line.startsWith("infixl ")) { return; } else if (line.startsWith("infixr ")) { return; } // Filter out strictness annotations. line = line.replace(/(\s)!([A-Za-z\(\[])/g, '$1$2'); // Filter out CallStack constraints. line = line.replace(/:: HasCallStack =>/g, '::'); var wordStart = 0; if (line.startsWith("type ") || line.startsWith("data ")) { wordStart += 5; // Hide kind annotations. var kindIndex = line.indexOf(" ::"); if (kindIndex != -1) { line = line.substr(0, kindIndex); } } var wordEnd = line.indexOf(" ", wordStart); if (wordEnd == -1) { wordEnd = line.length; } if (wordStart == wordEnd) { return; } if (line[wordStart] == "(" && line[wordEnd - 1] == ")") { wordStart++; wordEnd--; } var word = line.substr(wordStart, wordEnd - wordStart); if (hintBlacklist.indexOf(word) >= 0) { codeworldKeywords[word] = 'deprecated'; } else if (/^[A-Z:]/.test(word)) { codeworldKeywords[word] = 'builtin-2'; hints.push(createHint(line, wordStart, wordEnd)); } else { codeworldKeywords[word] = 'builtin'; hints.push(createHint(line, wordStart, wordEnd)); } }); hints.sort(function(a, b) { return a.source < b.source ? -1 : 1 }); CodeMirror.registerHelper('hintWords', 'codeworld', hints); successFunc(); }); } function addToMessage(msg) { while (msg.match(/(\r\n|[^\x08]|)\x08/)) { msg = msg.replace(/(\r\n|[^\x08])\x08/g, ""); } msg = msg .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/program\.hs:(\d+):((\d+)(-\d+)?)/g, '<a href="#" onclick="goto($1, $3);">Line $1, Column $2</a>') .replace(/program\.hs:\((\d+),(\d+)\)-\((\d+),(\d+)\)/g, '<a href="#" onclick="goto($1, $2);">Line $1-$3, Column $2-$4</a>'); var message = document.getElementById('message'); message.innerHTML += msg } function signin() { if (window.auth2) auth2.signIn({prompt: 'login'}); } function signout() { if (window.auth2) auth2.signOut(); } function signedIn() { return window.auth2 && auth2.isSignedIn.get(); } //signinCallback must be defined function handleGAPILoad() { gapi.load('auth2', function() { withClientId(function(clientId) { window.auth2 = gapi.auth2.init({ client_id: clientId, scope: 'profile', fetch_basic_profile: false }); auth2.isSignedIn.listen(signinCallback); auth2.currentUser.listen(signinCallback); if (auth2.isSignedIn.get() == true) auth2.signIn(); }); }); discoverProjects("", 0); updateUI(); } function withClientId(f) { if (window.clientId) return f(window.clientId); sendHttp('GET', 'clientId.txt', null, function(request) { if (request.status != 200 || request.responseText == '') { sweetAlert('Oops!', 'Missing API client key. You will not be able to sign in.', 'warning'); return null; } window.clientId = request.responseText.trim(); return f(window.clientId); }); } function discoverProjects_(path, buildMode, index) { if (!signedIn()) { allProjectNames = window.openProjectName ? [[window.openProjectName]] : [[]]; allFolderNames = [[]]; nestedDirs = [""]; updateUI(); return; } var data = new FormData(); data.append('id_token', auth2.currentUser.get().getAuthResponse().id_token); data.append('mode', buildMode); data.append('path', path); sendHttp('POST', 'listFolder', data, function(request) { if (request.status != 200) { return; } var allContents = JSON.parse(request.responseText); allProjectNames[index] = allContents['files']; allFolderNames[index] = allContents['dirs']; updateNavBar(); }); } function cancelMove() { updateUI(); } function moveHere_(path, buildMode, successFunc) { if (!signedIn()) { sweetAlert('Oops!', 'You must sign in before moving.', 'error'); cancelMove(); return; } if (window.move == undefined) { sweetAlert('Oops!', 'You must first select something to move.', 'error'); cancelMove(); return; } var data = new FormData(); data.append('id_token', auth2.currentUser.get().getAuthResponse().id_token); data.append('mode', buildMode); data.append('moveTo', path); data.append('moveFrom', window.move.path); if (window.move.file != undefined) { data.append('isFile', "true"); data.append('name', window.move.file); } else { data.append('isFile', "false"); } sendHttp('POST', 'moveProject', data, function(request) { if (request.status != 200) { sweetAlert('Oops', 'Could not move your project! Please try again.', 'error'); cancelMove(); return; } successFunc(); }); } function warnIfUnsaved(action, showAnother) { if (isEditorClean()) { action(); } else { var msg = 'There are unsaved changes to your project. ' + 'Continue and throw away your changes?'; sweetAlert({ title: 'Warning', text: msg, type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: 'Yes, discard my changes!', closeOnConfirm: !showAnother }, action); } } function saveProjectAs() { if (!signedIn()) { sweetAlert('Oops!', 'You must sign in to save files.', 'error'); updateUI(); return; } // window.codeworldEditor.focus(); var text = 'Save Project As: <input type="text" style="width: 10em"/>'; var defaultName; if (window.openProjectName) { defaultName = window.openProjectName; } else { defaultName = ''; } function go(projectName) { saveProjectBase(nestedDirs.slice(1).join('/'), projectName); } sweetAlert({ html: true, title: '<i class="mdi mdi-72px mdi-cloud-upload"></i>&nbsp; Save As', text: 'Enter a name for your project:', type: 'input', inputValue: defaultName, confirmButtonText: 'Save', showCancelButton: true, closeOnConfirm: false }, go); } function saveProject() { if (!signedIn()) { sweetAlert('Oops!', 'You must sign in to save files.', 'error'); updateUI(); return; } if (window.openProjectName) { saveProjectBase(nestedDirs.slice(1).join('/'), openProjectName); } else { saveProjectAs(); } } function saveProjectBase_(path, projectName, mode, successFunc) { if (projectName == null || projectName == '') return; if (!signedIn()) { sweetAlert('Oops!', 'You must sign in to save files.', 'error'); updateUI(); return; } function go() { sweetAlert.close(); var project = getCurrentProject(); project['name'] = projectName; var data = new FormData(); data.append('id_token', auth2.currentUser.get().getAuthResponse().id_token); data.append('project', JSON.stringify(project)); data.append('mode', mode); data.append('path', path); sendHttp('POST', 'saveProject', data, function(request) { if (request.status != 200) { sweetAlert('Oops!', 'Could not save your project!!! Please try again.', 'error'); return; } successFunc(); updateUI(); if (allProjectNames[allProjectNames.length - 1].indexOf(projectName) == -1) { discoverProjects(path, allProjectNames.length - 1); } }); } if (allProjectNames[allProjectNames.length - 1].indexOf(projectName) == -1 || projectName == openProjectName) { go(); } else { var msg = 'Are you sure you want to save over another project?\n\n' + 'The previous contents of ' + projectName + ' will be permanently destroyed!'; sweetAlert({ title: 'Warning', text: msg, type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: 'Yes, overwrite it!' }, go); } } function deleteProject_(path, buildMode, successFunc) { if (!window.openProjectName) return; if (!signedIn()) { sweetAlert('Oops', 'You must sign in to delete a project.', 'error'); updateUI(); return; } function go() { var data = new FormData(); data.append('id_token', auth2.currentUser.get().getAuthResponse().id_token); data.append('name', window.openProjectName); data.append('mode', buildMode); data.append('path', path); sendHttp('POST', 'deleteProject', data, function(request) { if (request.status == 200) { successFunc(); discoverProjects(path, allProjectNames.length - 1); } }); } var msg = 'Deleting a project will throw away all work, and cannot be undone. ' + 'Are you sure?'; sweetAlert({ title: 'Warning', text: msg, type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: 'Yes, delete it!' }, go); } function deleteFolder_(path, buildMode, successFunc) { if(path == "" || window.openProjectName != null) { return; } if(!signedIn()) { sweetAlert('Oops', 'You must sign in to delete a folder.', 'error'); updateUI(); return; } function go() { var data = new FormData(); data.append('id_token', auth2.currentUser.get().getAuthResponse().id_token); data.append('mode', buildMode); data.append('path', path); sendHttp('POST', 'deleteFolder', data, function(request) { if (request.status == 200) { successFunc(); nestedDirs.pop(); allProjectNames.pop(); allFolderNames.pop(); discoverProjects(nestedDirs.slice(1).join('/'), allProjectNames.length - 1); } }); } var msg = 'Deleting a folder will throw away all of its content, cannot be undone. ' + 'Are you sure?'; sweetAlert({ title: 'Warning', text: msg, type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55', confirmButtonText: 'Yes, delete it!' }, go); } function createFolder(path, buildMode, successFunc) { warnIfUnsaved(function() { if(!signedIn()) { sweetAlert('Oops!', 'You must sign in to create a folder.', 'error'); updateUI(); return; } function go(folderName) { if(folderName == null || folderName == '') { return; } sweetAlert.close(); var data = new FormData(); data.append('id_token', auth2.currentUser.get().getAuthResponse().id_token); data.append('mode', buildMode); if (path == "") data.append('path', folderName); else data.append('path', path + '/' + folderName); sendHttp('POST', 'createFolder', data, function(request) { if (request.status != 200) { sweetAlert('Oops', 'Could not create your directory! Please try again.', 'error'); return; } allFolderNames[allFolderNames.length - 1].push(folderName); nestedDirs.push(folderName); allFolderNames.push([]); allProjectNames.push([]); successFunc(); updateNavBar(); }); } sweetAlert({ html: true, title: '<i class="mdi mdi72px mdi-folder-plus"></i>&nbsp; Create Folder', text: 'Enter a name for your folder:', type: 'input', inputValue: '', confirmButtonText: 'Create', showCancelButton: true, closeOnConfirm: false }, go); }, true); } function loadProject_(index, name, buildMode, successFunc) { warnIfUnsaved(function(){ if (!signedIn()) { sweetAlert('Oops!', 'You must sign in to open projects.', 'error'); updateUI(); return; } var data = new FormData(); data.append('id_token', auth2.currentUser.get().getAuthResponse().id_token); data.append('name', name); data.append('mode', buildMode); data.append('path', nestedDirs.slice(1, index + 1).join('/')); sendHttp('POST', 'loadProject', data, function(request) { if (request.status == 200) { var project = JSON.parse(request.responseText); successFunc(project); window.nestedDirs = nestedDirs.slice(0, index + 1); window.allProjectNames = allProjectNames.slice(0, index + 1); window.allFolderNames = allFolderNames.slice(0, index + 1); updateUI(); } }); }, false); } function share() { var offerSource = true; function go() { var url; var msg; var showConfirm; var confirmText; if (!window.deployHash) { url = window.location.href; msg = 'Copy this link to share your program and source code with others!'; showConfirm = false; } else if (offerSource) { url = window.location.href; msg = 'Copy this link to share your program and source code with others!'; showConfirm = true; confirmText = 'Remove Source Code'; } else { var a = document.createElement('a'); a.href = window.location.href; a.hash = ''; a.pathname = '/run.html' a.search = '?mode=' + window.buildMode + '&dhash=' + window.deployHash; url = a.href; msg = 'Copy this link to share your program (not source code) with others!'; showConfirm = true; confirmText = 'Share Source Code'; } sweetAlert({ html: true, title: '<i class="mdi mdi-72px mdi-share"></i>&nbsp; Share', text: msg, type: 'input', inputValue: url, showConfirmButton: showConfirm, confirmButtonText: confirmText, closeOnConfirm: false, showCancelButton: true, cancelButtonText: 'Done', animation: 'slide-from-bottom' }, function() { offerSource = !offerSource; go(); }); } go(); } function inspect() { document.getElementById('runner').contentWindow.toggleDebugMode(); updateUI(); } function shareFolder_(mode) { if(!signedIn()) { sweetAlert('Oops!', 'You must sign in to share your folder.', 'error'); updateUI(); return; } if(nestedDirs.length == 1 || (openProjectName != null && openProjectName != '')) { sweetAlert('Oops!', 'YOu must select a folder to share!', 'error'); updateUI(); return; } var path = nestedDirs.slice(1).join('/'); function go() { var msg = 'Copy this link to share your folder with others!'; var id_token = auth2.currentUser.get().getAuthResponse().id_token; var data = new FormData(); data.append('id_token', id_token); data.append('mode', mode); data.append('path', path); sendHttp('POST', 'shareFolder', data, function(request) { if(request.status != 200) { sweetAlert('Oops!', 'Could not share your folder! Please try again.', 'error'); return; } var shareHash = request.responseText; var a = document.createElement('a'); a.href = window.location.href; a.hash = '#' + shareHash; var url = a.href; sweetAlert({ html: true, title: '<i class="mdi mdi-72px mdi-folder-outline"></i>&nbsp; Share Folder', text: msg, type: 'input', inputValue: url, showConfirmButton: false, showCancelButton: true, cancelButtonText: 'Done', animation: 'slide-from-bottom' }); }); } go(); }
three/codeworld
web/js/codeworld_shared.js
JavaScript
apache-2.0
24,076
'use strict'; /** * Module dependencies. */ var fs = require('fs'), http = require('http'), https = require('https'), express = require('express'), morgan = require('morgan'), logger = require('./logger'), bodyParser = require('body-parser'), session = require('express-session'), compress = require('compression'), methodOverride = require('method-override'), cookieParser = require('cookie-parser'), helmet = require('helmet'), passport = require('passport'), mongoStore = require('connect-mongo')({ session: session }), flash = require('connect-flash'), config = require('./config'), consolidate = require('consolidate'), path = require('path'); // multer = require('multer') module.exports = function(db) { // Initialize express app var app = express(); // Globbing model files config.getGlobbedFiles('./models/**/*.js').forEach(function(modelPath) { require(path.resolve(modelPath)); }); // Setting application local variables app.locals.title = config.app.title; app.locals.description = config.app.description; app.locals.keywords = config.app.keywords; // app.locals.facebookAppId = config.facebook.clientID; if (!fs.existsSync(config.uploadDir)){ fs.mkdirSync(config.uploadDir); fs.mkdirSync(config.uploadDirTmp); } // Passing the request url to environment locals app.use(function(req, res, next) { res.locals.url = req.protocol + '://' + req.headers.host + req.url; next(); }); // Should be placed before express.static app.use(compress({ filter: function(req, res) { return (/json|text|javascript|css/).test(res.getHeader('Content-Type')); }, level: 9 })); // Showing stack errors app.set('showStackError', true); // Set swig as the template engine app.engine('server.view.html', consolidate[config.templateEngine]); // TODO: Review this. // Set views path and view engine app.set('view engine', 'server.view.html'); // TODO: Review this. // app.set('views', './app/views'); // TODO: Review this. app.set('views', './templates'); // TODO: Review this. // Enable logger (morgan) app.use(morgan(logger.getLogFormat(), logger.getLogOptions())); // Environment dependent middleware if (process.env.NODE_ENV === 'development') { // Disable views cache app.set('view cache', false); } else if (process.env.NODE_ENV === 'production') { app.locals.cache = 'memory'; } // app.use(multer({ // dest: './uploads/', // limits: { // files: 10, // fileSize: 2, // parts: 10 // }, // rename: function(fieldname, filename) { // return filename.replace(/\W+/g, '-').toLowerCase(); // }, // onFileUploadStart: function(file) { // console.log(file.fieldname + ' is starting ...'); // }, // onFileUploadComplete: function(file) { // console.log(file.fieldname + ' uploaded to ' + file.path); // }, // onError: function(error, next) { // console.log(error); // next(error); // }, // onFileSizeLimit: function(file) { // console.log('Failed: ', file.originalname); // fs.unlink('./' + file.path); // delete the partially written file // }, // onFilesLimit: function() { // console.log('Crossed file limit!'); // } // })); // Request body parsing middleware should be above methodOverride app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(methodOverride()); // CookieParser should be above session app.use(cookieParser()); // Express MongoDB session storage app.use(session({ saveUninitialized: true, resave: true, secret: config.sessionSecret, store: new mongoStore({ db: db.connection.db, collection: config.sessionCollection }), cookie: config.sessionCookie, name: config.sessionName })); // use passport session app.use(passport.initialize()); app.use(passport.session()); // connect flash for flash messages app.use(flash()); // Use helmet to secure Express headers app.use(helmet.xframe()); app.use(helmet.xssFilter()); app.use(helmet.nosniff()); app.use(helmet.ienoopen()); app.disable('x-powered-by'); // Setting the app router and static folder app.use(express.static(path.resolve(config.root))); // Globbing routing files config.getGlobbedFiles('./routers/**/*.js').forEach(function(routePath) { require(path.resolve(routePath))(app); }); // require('../routers/routes'); // Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc. app.use(function(err, req, res, next) { // If the error object doesn't exists if (!err) return next(); // Log it console.error(err.stack); res.status(500).json({ error: err.stack }); }); // Assume 404 since no middleware responded app.use(function(req, res) { res.status(404).json({ msg: 'Not Found' }); }); if (process.env.NODE_ENV === 'secure') { // Load SSL key and certificate var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8'); var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8'); // Create HTTPS Server var httpsServer = https.createServer({ key: privateKey, cert: certificate }, app); // Return HTTPS server instance return httpsServer; } // Return Express server instance return app; };
mauroBus/element
server/config/express.js
JavaScript
apache-2.0
5,566
export default function (value, opts) { return value > Date.now() ? opts.fn(this) : ''; }
elauria/yourturn
client/lib/common/src/handlebars/inFuture.js
JavaScript
apache-2.0
93
"use strict"; var valueToString = require("@sinonjs/commons").valueToString; var indexOf = require("@sinonjs/commons").prototypes.string.indexOf; var forEach = require("@sinonjs/commons").prototypes.array.forEach; var type = require("type-detect"); var engineCanCompareMaps = typeof Array.from === "function"; var deepEqual = require("./deep-equal").use(match); // eslint-disable-line no-use-before-define var isArrayType = require("./is-array-type"); var isSubset = require("./is-subset"); var createMatcher = require("./create-matcher"); /** * Returns true when `array` contains all of `subset` as defined by the `compare` * argument * * @param {Array} array An array to search for a subset * @param {Array} subset The subset to find in the array * @param {Function} compare A comparison function * @returns {boolean} [description] * @private */ function arrayContains(array, subset, compare) { if (subset.length === 0) { return true; } var i, l, j, k; for (i = 0, l = array.length; i < l; ++i) { if (compare(array[i], subset[0])) { for (j = 0, k = subset.length; j < k; ++j) { if (i + j >= l) { return false; } if (!compare(array[i + j], subset[j])) { return false; } } return true; } } return false; } /* eslint-disable complexity */ /** * Matches an object with a matcher (or value) * * @alias module:samsam.match * @param {object} object The object candidate to match * @param {object} matcherOrValue A matcher or value to match against * @returns {boolean} true when `object` matches `matcherOrValue` */ function match(object, matcherOrValue) { if (matcherOrValue && typeof matcherOrValue.test === "function") { return matcherOrValue.test(object); } switch (type(matcherOrValue)) { case "bigint": case "boolean": case "number": case "symbol": return matcherOrValue === object; case "function": return matcherOrValue(object) === true; case "string": var notNull = typeof object === "string" || Boolean(object); return ( notNull && indexOf( valueToString(object).toLowerCase(), matcherOrValue.toLowerCase() ) >= 0 ); case "null": return object === null; case "undefined": return typeof object === "undefined"; case "Date": /* istanbul ignore else */ if (type(object) === "Date") { return object.getTime() === matcherOrValue.getTime(); } /* istanbul ignore next: this is basically the rest of the function, which is covered */ break; case "Array": case "Int8Array": case "Uint8Array": case "Uint8ClampedArray": case "Int16Array": case "Uint16Array": case "Int32Array": case "Uint32Array": case "Float32Array": case "Float64Array": return ( isArrayType(matcherOrValue) && arrayContains(object, matcherOrValue, match) ); case "Map": /* istanbul ignore next: this is covered by a test, that is only run in IE, but we collect coverage information in node*/ if (!engineCanCompareMaps) { throw new Error( "The JavaScript engine does not support Array.from and cannot reliably do value comparison of Map instances" ); } return ( type(object) === "Map" && arrayContains( Array.from(object), Array.from(matcherOrValue), match ) ); default: break; } switch (type(object)) { case "null": return false; case "Set": return isSubset(matcherOrValue, object, match); default: break; } /* istanbul ignore else */ if (matcherOrValue && typeof matcherOrValue === "object") { if (matcherOrValue === object) { return true; } if (typeof object !== "object") { return false; } var prop; // eslint-disable-next-line guard-for-in for (prop in matcherOrValue) { var value = object[prop]; if ( typeof value === "undefined" && typeof object.getAttribute === "function" ) { value = object.getAttribute(prop); } if ( matcherOrValue[prop] === null || typeof matcherOrValue[prop] === "undefined" ) { if (value !== matcherOrValue[prop]) { return false; } } else if ( typeof value === "undefined" || !deepEqual(value, matcherOrValue[prop]) ) { return false; } } return true; } /* istanbul ignore next */ throw new Error("Matcher was an unknown or unsupported type"); } /* eslint-enable complexity */ forEach(Object.keys(createMatcher), function(key) { match[key] = createMatcher[key]; }); module.exports = match;
GoogleCloudPlatform/prometheus-engine
third_party/prometheus_ui/base/web/ui/react-app/node_modules/@sinonjs/samsam/lib/match.js
JavaScript
apache-2.0
5,516
//>>built define("dojox/grid/enhanced/plugins/DnD","dojo/_base/kernel dojo/_base/declare dojo/_base/connect dojo/_base/array dojo/_base/lang dojo/_base/html dojo/_base/json dojo/_base/window dojo/query dojo/keys dojo/dnd/Source dojo/dnd/Avatar ../_Plugin ../../EnhancedGrid dojo/dnd/Manager ./Selector ./Rearrange".split(" "),function(y,x,B,h,r,f,C,p,z,A,D,E,F,G,H){var I=function(a){a.sort(function(a,b){return a-b});for(var c=[[a[0]]],b=1,d=0;b<a.length;++b)a[b]==a[b-1]+1?c[d].push(a[b]):c[++d]=[a[b]];return c}, u=function(a){for(var c=a[0],b=1;b<a.length;++b)c=c.concat(a[b]);return c},J=x("dojox.grid.enhanced.plugins.GridDnDElement",null,{constructor:function(a){this.plugin=a;this.node=f.create("div");this._items={}},destroy:function(){this.plugin=null;f.destroy(this.node);this._items=this.node=null},createDnDNodes:function(a){this.destroyDnDNodes();var c=["grid/"+a.type+"s"],b=this.plugin.grid.id+"_dndItem";h.forEach(a.selected,function(a,g){var d=b+g;this._items[d]={type:c,data:a,dndPlugin:this.plugin}; this.node.appendChild(f.create("div",{id:d}))},this)},getDnDNodes:function(){return h.map(this.node.childNodes,function(a){return a})},destroyDnDNodes:function(){f.empty(this.node);this._items={}},getItem:function(a){return this._items[a]}}),K=x("dojox.grid.enhanced.plugins.GridDnDSource",D,{accept:["grid/cells","grid/rows","grid/cols"],constructor:function(a,c){this.grid=c.grid;this.dndElem=c.dndElem;this.dndPlugin=c.dnd;this.sourcePlugin=null},destroy:function(){this.inherited(arguments);this.sourcePlugin= this.dndPlugin=this.dndElem=this.grid=null},getItem:function(a){return this.dndElem.getItem(a)},checkAcceptance:function(a,c){if(this!=a&&c[0]){var b=a.getItem(c[0].id);if(b.dndPlugin)for(var d=b.type,g=0;g<d.length;++g){if(d[g]in this.accept){if(this.dndPlugin._canAccept(b.dndPlugin))this.sourcePlugin=b.dndPlugin;else return!1;break}}else if("grid/rows"in this.accept){var e=[];h.forEach(c,function(b){b=a.getItem(b.id);if(b.data&&0<=h.indexOf(b.type,"grid/rows")){var c=b.data;"string"==typeof b.data&& (c=C.fromJson(b.data));c&&e.push(c)}});if(e.length)this.sourcePlugin={_dndRegion:{type:"row",selected:[e]}};else return!1}}return this.inherited(arguments)},onDraggingOver:function(){this.dndPlugin.onDraggingOver(this.sourcePlugin)},onDraggingOut:function(){this.dndPlugin.onDraggingOut(this.sourcePlugin)},onDndDrop:function(a,c,b,d){this.onDndCancel();if(this!=a&&this==d)this.dndPlugin.onDragIn(this.sourcePlugin,b)}}),L=x("dojox.grid.enhanced.plugins.GridDnDAvatar",E,{construct:function(){this._itemType= this.manager._dndPlugin._dndRegion.type;this._itemCount=this._getItemCount();this.isA11y=f.hasClass(p.body(),"dijit_a11y");var a=f.create("table",{border:"0",cellspacing:"0","class":"dojoxGridDndAvatar",style:{position:"absolute",zIndex:"1999",margin:"0px"}}),c=this.manager.source,b=f.create("tbody",null,a),b=f.create("tr",null,b),d=f.create("td",{"class":"dojoxGridDnDIcon"},b);this.isA11y&&f.create("span",{id:"a11yIcon",innerHTML:this.manager.copy?"+":"\x3c"},d);d=f.create("td",{"class":"dojoxGridDnDItemIcon "+ this._getGridDnDIconClass()},b);d=f.create("td",null,b);f.create("span",{"class":"dojoxGridDnDItemCount",innerHTML:c.generateText?this._generateText():""},d);f.style(b,{opacity:.9});this.node=a},_getItemCount:function(){var a=this.manager._dndPlugin._dndRegion.selected,c=0;switch(this._itemType){case "cell":var a=a[0],c=this.manager._dndPlugin.grid.layout.cells,b=a.max.col-a.min.col+1,d=a.max.row-a.min.row+1;if(1<b)for(var g=a.min.col;g<=a.max.col;++g)c[g].hidden&&--b;c=b*d;break;case "row":case "col":c= u(a).length}return c},_getGridDnDIconClass:function(){return{row:["dojoxGridDnDIconRowSingle","dojoxGridDnDIconRowMulti"],col:["dojoxGridDnDIconColSingle","dojoxGridDnDIconColMulti"],cell:["dojoxGridDnDIconCellSingle","dojoxGridDnDIconCellMulti"]}[this._itemType][1==this._itemCount?0:1]},_generateText:function(){return"("+this._itemCount+")"}});y=x("dojox.grid.enhanced.plugins.DnD",F,{name:"dnd",_targetAnchorBorderWidth:2,_copyOnly:!1,_config:{row:{within:!0,"in":!0,out:!0},col:{within:!0,"in":!0, out:!0},cell:{within:!0,"in":!0,out:!0}},constructor:function(a,c){this.grid=a;this._config=r.clone(this._config);c=r.isObject(c)?c:{};this.setupConfig(c.dndConfig);this._copyOnly=!!c.copyOnly;this._mixinGrid();this.selector=a.pluginMgr.getPlugin("selector");this.rearranger=a.pluginMgr.getPlugin("rearrange");this.rearranger.setArgs(c);this._clear();this._elem=new J(this);this._source=new K(this._elem.node,{grid:a,dndElem:this._elem,dnd:this});this._container=z(".dojoxGridMasterView",this.grid.domNode)[0]; this._initEvents()},destroy:function(){this.inherited(arguments);this._clear();this._source.destroy();this._elem.destroy();this._config=this.rearranger=this.selector=this.grid=this._container=null},_mixinGrid:function(){this.grid.setupDnDConfig=r.hitch(this,"setupConfig");this.grid.dndCopyOnly=r.hitch(this,"copyOnly")},setupConfig:function(a){if(a&&r.isObject(a)){var c=["row","col","cell"],b=["within","in","out"],d=this._config;h.forEach(c,function(c){if(c in a){var e=a[c];e&&r.isObject(e)?h.forEach(b, function(a){a in e&&(d[c][a]=!!e[a])}):h.forEach(b,function(a){d[c][a]=!!e})}});h.forEach(b,function(b){if(b in a){var e=a[b];e&&r.isObject(e)?h.forEach(c,function(a){a in e&&(d[a][b]=!!e[a])}):h.forEach(c,function(a){d[a][b]=!!e})}})}},copyOnly:function(a){"undefined"!=typeof a&&(this._copyOnly=!!a);return this._copyOnly},_isOutOfGrid:function(a){var c=f.position(this.grid.domNode),b=a.clientX;a=a.clientY;return a<c.y||a>c.y+c.h||b<c.x||b>c.x+c.w},_onMouseMove:function(a){if(!this._dndRegion||this._dnding|| this._externalDnd){this._isMouseDown&&!this._dndRegion&&(delete this._isMouseDown,this._oldCursor=f.style(p.body(),"cursor"),f.style(p.body(),"cursor","not-allowed"));var c=this._isOutOfGrid(a);!this._alreadyOut&&c?(this._alreadyOut=!0,this._dnding&&this._destroyDnDUI(!0,!1),this._moveEvent=a,this._source.onOutEvent()):this._alreadyOut&&!c&&(this._alreadyOut=!1,this._dnding&&this._createDnDUI(a,!0),this._moveEvent=a,this._source.onOverEvent())}else this._dnding=!0,this._startDnd(a)},_onMouseUp:function(){if(!this._extDnding&& !this._isSource){var a=this._dnding&&!this._alreadyOut;a&&this._config[this._dndRegion.type].within&&this._rearrange();this._endDnd(a)}f.style(p.body(),"cursor",this._oldCursor||"");delete this._isMouseDown},_initEvents:function(){var a=this.grid,c=this.selector;this.connect(p.doc,"onmousemove","_onMouseMove");this.connect(p.doc,"onmouseup","_onMouseUp");this.connect(a,"onCellMouseOver",function(a){this._dnding||c.isSelecting()||a.ctrlKey||(this._dndReady=c.isSelected("cell",a.rowIndex,a.cell.index), c.selectEnabled(!this._dndReady))});this.connect(a,"onHeaderCellMouseOver",function(a){this._dndReady&&c.selectEnabled(!0)});this.connect(a,"onRowMouseOver",function(a){this._dndReady&&!a.cell&&c.selectEnabled(!0)});this.connect(a,"onCellMouseDown",function(a){!a.ctrlKey&&this._dndReady&&(this._dndRegion=this._getDnDRegion(a.rowIndex,a.cell.index),this._isMouseDown=!0)});this.connect(a,"onCellMouseUp",function(a){this._dndReady||c.isSelecting()||!a.cell||(this._dndReady=c.isSelected("cell",a.rowIndex, a.cell.index),c.selectEnabled(!this._dndReady))});this.connect(a,"onCellClick",function(a){!this._dndReady||a.ctrlKey||a.shiftKey||c.select("cell",a.rowIndex,a.cell.index)});this.connect(a,"onEndAutoScroll",function(a,c,g,e,f){this._dnding&&this._markTargetAnchor(f)});this.connect(p.doc,"onkeydown",function(a){a.keyCode==A.ESCAPE?this._endDnd(!1):a.keyCode==A.CTRL&&(c.selectEnabled(!0),this._isCopy=!0)});this.connect(p.doc,"onkeyup",function(a){a.keyCode==A.CTRL&&(c.selectEnabled(!this._dndReady), this._isCopy=!1)})},_clear:function(){this._moveEvent=this._target=this._dndRegion=null;this._targetAnchor={};this._extDnding=this._alreadyOut=this._isSource=this._externalDnd=this._dnding=!1},_getDnDRegion:function(a,c){var b=this.selector,d=b._selected,g=!!d.cell.length|!!d.row.length<<1|!!d.col.length<<2,e;switch(g){case 1:e="cell";if(!this._config[e].within&&!this._config[e].out)break;var f=this.grid.layout.cells,g=function(a){for(var b=0,c=a.min.col;c<=a.max.col;++c)f[c].hidden&&++b;return(a.max.row- a.min.row+1)*(a.max.col-a.min.col+1-b)},k={max:{row:-1,col:-1},min:{row:Infinity,col:Infinity}};h.forEach(d[e],function(a){a.row<k.min.row&&(k.min.row=a.row);a.row>k.max.row&&(k.max.row=a.row);a.col<k.min.col&&(k.min.col=a.col);a.col>k.max.col&&(k.max.col=a.col)});if(h.some(d[e],function(b){return b.row==a&&b.col==c})&&g(k)==d[e].length&&h.every(d[e],function(a){return a.row>=k.min.row&&a.row<=k.max.row&&a.col>=k.min.col&&a.col<=k.max.col}))return{type:e,selected:[k],handle:{row:a,col:c}};break;case 2:case 4:if(e= 2==g?"row":"col",this._config[e].within||this._config[e].out)if(d=b.getSelected(e),d.length)return{type:e,selected:I(d),handle:2==g?a:c}}return null},_startDnd:function(a){this._createDnDUI(a)},_endDnd:function(a){this._destroyDnDUI(!1,a);this._clear()},_createDnDUI:function(a,c){var b=f.position(this.grid.views.views[0].domNode);f.style(this._container,"height",b.h+"px");try{c||this._createSource(a),this._createMoveable(a),this._oldCursor=f.style(p.body(),"cursor"),f.style(p.body(),"cursor","default")}catch(d){console.warn("DnD._createDnDUI() error:", d)}},_destroyDnDUI:function(a,c){try{c&&this._destroySource(),this._unmarkTargetAnchor(),a||this._destroyMoveable(),f.style(p.body(),"cursor",this._oldCursor)}catch(b){console.warn("DnD._destroyDnDUI() error:",this.grid.id,b)}},_createSource:function(a){this._elem.createDnDNodes(this._dndRegion);var c=H.manager(),b=c.makeAvatar;c._dndPlugin=this;c.makeAvatar=function(){var a=new L(c);delete c._dndPlugin;return a};c.startDrag(this._source,this._elem.getDnDNodes(),a.ctrlKey);c.makeAvatar=b;c.onMouseMove(a)}, _destroySource:function(){B.publish("/dnd/cancel")},_createMoveable:function(a){this._markTagetAnchorHandler||(this._markTagetAnchorHandler=this.connect(p.doc,"onmousemove","_markTargetAnchor"))},_destroyMoveable:function(){this.disconnect(this._markTagetAnchorHandler);delete this._markTagetAnchorHandler},_calcColTargetAnchorPos:function(a,c){var b,d,g,e;e=a.clientX;var l=this.grid.layout.cells,k=f._isBodyLtr(),q=this._getVisibleHeaders();for(b=0;b<q.length;++b)if(d=f.position(q[b].node),k?(0===b|| e>=d.x)&&e<d.x+d.w:(0===b||e<d.x+d.w)&&e>=d.x){g=d.x+(k?0:d.w);break}else if(k?b===q.length-1&&e>=d.x+d.w:b===q.length-1&&e<d.x){++b;g=d.x+(k?d.w:0);break}if(b<q.length){if(e=q[b].cell.index,this.selector.isSelected("col",e)&&this.selector.isSelected("col",e-1))for(d=this._dndRegion.selected,b=0;b<d.length;++b)if(0<=h.indexOf(d[b],e)){e=d[b][0];d=f.position(l[e].getHeaderNode());g=d.x+(k?0:d.w);break}}else e=l.length;this._target=e;return g-c.x},_calcRowTargetAnchorPos:function(a,c){for(var b=this.grid, d=0,g=b.layout.cells;g[d].hidden;)++d;var e=b.layout.cells[d],g=b.scroller.firstVisibleRow,d=e.getNode(g);if(!d)return this._target=-1,0;for(var l=f.position(d);l.y+l.h<a.clientY&&!(++g>=b.rowCount);)l=f.position(e.getNode(g));if(g<b.rowCount){if(this.selector.isSelected("row",g)&&this.selector.isSelected("row",g-1))for(b=this._dndRegion.selected,d=0;d<b.length;++d)if(0<=h.indexOf(b[d],g)){g=b[d][0];l=f.position(e.getNode(g));break}b=l.y}else b=l.y+l.h;this._target=g;return b-c.y},_calcCellTargetAnchorPos:function(a, c,b){var d=this._dndRegion.selected[0],g=this._dndRegion.handle,e=this.grid,l=f._isBodyLtr(),k=e.layout.cells,q,m,h,p,r,u,t,v,n;m=g.col-d.min.col;h=d.max.col-g.col;var w;b.childNodes.length?(w=z(".dojoxGridCellBorderLeftTopDIV",b)[0],b=z(".dojoxGridCellBorderRightBottomDIV",b)[0]):(w=f.create("div",{"class":"dojoxGridCellBorderLeftTopDIV"},b),b=f.create("div",{"class":"dojoxGridCellBorderRightBottomDIV"},b));for(n=d.min.col+1;n<g.col;++n)k[n].hidden&&--m;for(n=g.col+1;n<d.max.col;++n)k[n].hidden&& --h;p=this._getVisibleHeaders();for(n=m;n<p.length-h;++n)if(q=f.position(p[n].node),a.clientX>=q.x&&a.clientX<q.x+q.w||n==m&&(l?a.clientX<q.x:a.clientX>=q.x+q.w)||n==p.length-h-1&&(l?a.clientX>=q.x+q.w:a<q.x)){t=p[n-m];v=p[n+h];m=f.position(t.node);h=f.position(v.node);t=t.cell.index;v=v.cell.index;u=l?m.x:h.x;r=l?h.x+h.w-m.x:m.x+m.w-h.x;break}for(n=0;k[n].hidden;)++n;l=k[n];m=e.scroller.firstVisibleRow;for(h=f.position(l.getNode(m));h.y+h.h<a.clientY;)if(++m<e.rowCount)h=f.position(l.getNode(m)); else break;g=m>=g.row-d.min.row?m-g.row+d.min.row:0;a=g+d.max.row-d.min.row;a>=e.rowCount&&(a=e.rowCount-1,g=a-d.max.row+d.min.row);m=f.position(l.getNode(g));h=f.position(l.getNode(a));d=m.y;e=h.y+h.h-m.y;this._target={min:{row:g,col:t},max:{row:a,col:v}};l=(f.marginBox(w).w-f.contentBox(w).w)/2;t=f.position(k[t].getNode(g));f.style(w,{width:t.w-l+"px",height:t.h-l+"px"});k=f.position(k[v].getNode(a));f.style(b,{width:k.w-l+"px",height:k.h-l+"px"});return{h:e,w:r,l:u-c.x,t:d-c.y}},_markTargetAnchor:function(a){try{var c= this._dndRegion.type;if(!(this._alreadyOut||this._dnding&&!this._config[c].within||this._extDnding&&!this._config[c]["in"])){var b,d,g,e,l=this._targetAnchor[c],k=f.position(this._container);l||(l=this._targetAnchor[c]=f.create("div",{"class":"cell"==c?"dojoxGridCellBorderDIV":"dojoxGridBorderDIV"}),f.style(l,"display","none"),this._container.appendChild(l));switch(c){case "col":b=k.h;d=this._targetAnchorBorderWidth;g=this._calcColTargetAnchorPos(a,k);e=0;break;case "row":b=this._targetAnchorBorderWidth; d=k.w;g=0;e=this._calcRowTargetAnchorPos(a,k);break;case "cell":var h=this._calcCellTargetAnchorPos(a,k,l);b=h.h;d=h.w;g=h.l;e=h.t}"number"==typeof b&&"number"==typeof d&&"number"==typeof g&&"number"==typeof e?(f.style(l,{height:b+"px",width:d+"px",left:g+"px",top:e+"px"}),f.style(l,"display","")):this._target=null}}catch(m){console.warn("DnD._markTargetAnchor() error:",m)}},_unmarkTargetAnchor:function(){this._dndRegion&&this._targetAnchor[this._dndRegion.type]&&f.style(this._targetAnchor[this._dndRegion.type], "display","none")},_getVisibleHeaders:function(){return h.map(h.filter(this.grid.layout.cells,function(a){return!a.hidden}),function(a){return{node:a.getHeaderNode(),cell:a}})},_rearrange:function(){if(null!==this._target){var a=this._dndRegion.type,c=this._dndRegion.selected;if("cell"===a)this.rearranger[this._isCopy||this._copyOnly?"copyCells":"moveCells"](c[0],-1===this._target?null:this._target);else this.rearranger["col"==a?"moveColumns":"moveRows"](u(c),-1===this._target?null:this._target); this._target=null}},onDraggingOver:function(a){!this._dnding&&a&&(this._extDnding=a._isSource=!0,this._externalDnd||(this._externalDnd=!0,this._dndRegion=this._mapRegion(a.grid,a._dndRegion)),this._createDnDUI(this._moveEvent,!0),this.grid.pluginMgr.getPlugin("autoScroll").readyForAutoScroll=!0)},_mapRegion:function(a,c){if("cell"===c.type){var b=c.selected[0],d=this.grid.layout.cells,g=a.layout.cells,e,f=0;for(e=b.min.col;e<=b.max.col;++e)g[e].hidden||++f;for(e=0;0<f;++e)d[e].hidden||--f;var k=r.clone(c); k.selected[0].min.col=0;k.selected[0].max.col=e-1;for(e=b.min.col;e<=c.handle.col;++e)g[e].hidden||++f;for(e=0;0<f;++e)d[e].hidden||--f;k.handle.col=e}return c},onDraggingOut:function(a){this._externalDnd&&(this._extDnding=!1,this._destroyDnDUI(!0,!1),a&&(a._isSource=!1))},onDragIn:function(a,c){var b=!1;if(null!==this._target){b=a._dndRegion.selected;switch(a._dndRegion.type){case "cell":this.rearranger.changeCells(a.grid,b[0],this._target);break;case "row":b=u(b),this.rearranger.insertRows(a.grid, b,this._target)}b=!0}this._endDnd(!0);if(a.onDragOut)a.onDragOut(b&&!c)},onDragOut:function(a){if(a&&!this._copyOnly)switch(a=this._dndRegion.selected,this._dndRegion.type){case "cell":this.rearranger.clearCells(a[0]);break;case "row":this.rearranger.removeRows(u(a))}this._endDnd(!0)},_canAccept:function(a){if(!a)return!1;var c=a._dndRegion,b=c.type;if(!this._config[b]["in"]||!a._config[b].out)return!1;var d=this.grid,g=c.selected,c=h.filter(d.layout.cells,function(a){return!a.hidden}).length,e=d.rowCount, f=!0;switch(b){case "cell":g=g[0],f=d.store.getFeatures()["dojo.data.api.Write"]&&g.max.row-g.min.row<=e&&h.filter(a.grid.layout.cells,function(a){return a.index>=g.min.col&&a.index<=g.max.col&&!a.hidden}).length<=c;case "row":if(a._allDnDItemsLoaded())return f}return!1},_allDnDItemsLoaded:function(){if(this._dndRegion){var a=this._dndRegion.selected,c=[];switch(this._dndRegion.type){case "cell":for(var b=a[0].min.row,a=a[0].max.row;b<=a;++b)c.push(b);break;case "row":c=u(a);break;default:return!1}var d= this.grid._by_idx;return h.every(c,function(a){return!!d[a]})}return!1}});G.registerPlugin(y,{dependency:["selector","rearrange"]});return y});
wanglongbiao/webapp-tools
Highlander/ship-gis/src/main/webapp/js/arcgis_js_api/library/3.22/dojox/grid/enhanced/plugins/DnD.js
JavaScript
apache-2.0
16,547
// 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 FormData */ import app from "../../../app"; import FauxtonAPI from "../../../core/api"; import ActionTypes from "./actiontypes"; var xhr; function initDocEditor (params) { var doc = params.doc; // ensure a clean slate FauxtonAPI.dispatch({ type: ActionTypes.RESET_DOC }); doc.fetch().then(function () { FauxtonAPI.dispatch({ type: ActionTypes.DOC_LOADED, options: { doc: doc } }); if (params.onLoaded) { params.onLoaded(); } }, function (xhr) { if (xhr.status === 404) { errorNotification('The document does not exist.'); } FauxtonAPI.navigate(FauxtonAPI.urls('allDocs', 'app', params.database.id, '')); }); } function saveDoc (doc, isValidDoc, onSave) { if (isValidDoc) { FauxtonAPI.addNotification({ msg: 'Saving document.', clear: true }); doc.save().then(function () { onSave(doc.prettyJSON()); FauxtonAPI.navigate('#/' + FauxtonAPI.urls('allDocs', 'app', FauxtonAPI.url.encode(doc.database.id)), {trigger: true}); }).fail(function (xhr) { FauxtonAPI.addNotification({ msg: 'Save failed: ' + JSON.parse(xhr.responseText).reason, type: 'error', fade: false, clear: true }); }); } else if (doc.validationError && doc.validationError === 'Cannot change a documents id.') { errorNotification('You cannot edit the _id of an existing document. Try this: Click \'Clone Document\', then change the _id on the clone before saving.'); delete doc.validationError; } else { errorNotification('Please fix the JSON errors and try saving again.'); } } function showDeleteDocModal () { FauxtonAPI.dispatch({ type: ActionTypes.SHOW_DELETE_DOC_CONFIRMATION_MODAL }); } function hideDeleteDocModal () { FauxtonAPI.dispatch({ type: ActionTypes.HIDE_DELETE_DOC_CONFIRMATION_MODAL }); } function deleteDoc (doc) { var databaseName = doc.database.safeID(); var query = '?rev=' + doc.get('_rev'); $.ajax({ url: FauxtonAPI.urls('document', 'server', databaseName, doc.safeID(), query), type: 'DELETE', contentType: 'application/json; charset=UTF-8', xhrFields: { withCredentials: true }, success: function () { FauxtonAPI.addNotification({ msg: 'Your document has been successfully deleted.', clear: true }); FauxtonAPI.navigate(FauxtonAPI.urls('allDocs', 'app', databaseName, '')); }, error: function () { FauxtonAPI.addNotification({ msg: 'Failed to delete your document!', type: 'error', clear: true }); } }); } function showCloneDocModal () { FauxtonAPI.dispatch({ type: ActionTypes.SHOW_CLONE_DOC_MODAL }); } function hideCloneDocModal () { FauxtonAPI.dispatch({ type: ActionTypes.HIDE_CLONE_DOC_MODAL }); } function cloneDoc (database, doc, newId) { const docId = app.utils.getSafeIdForDoc(newId); hideCloneDocModal(); doc.copy(docId).then(() => { doc.set({ _id: docId }); FauxtonAPI.navigate('/database/' + database.safeID() + '/' + docId, { trigger: true }); FauxtonAPI.addNotification({ msg: 'Document has been duplicated.' }); }, (error) => { const errorMsg = `Could not duplicate document, reason: ${error.responseText}.`; FauxtonAPI.addNotification({ msg: errorMsg, type: 'error' }); }); } function showUploadModal () { FauxtonAPI.dispatch({ type: ActionTypes.SHOW_UPLOAD_MODAL }); } function hideUploadModal () { FauxtonAPI.dispatch({ type: ActionTypes.HIDE_UPLOAD_MODAL }); } function uploadAttachment (params) { if (params.files.length === 0) { FauxtonAPI.dispatch({ type: ActionTypes.FILE_UPLOAD_ERROR, options: { error: 'Please select a file to be uploaded.' } }); return; } FauxtonAPI.dispatch({ type: ActionTypes.START_FILE_UPLOAD }); // store the xhr in parent scope to allow us to cancel any uploads if the user closes the modal xhr = $.ajaxSettings.xhr(); var query = '?rev=' + params.rev; var db = params.doc.getDatabase().safeID(); var docId = params.doc.safeID(); var file = params.files[0]; $.ajax({ url: FauxtonAPI.urls('document', 'attachment', db, docId, file.name, query), type: 'PUT', data: file, contentType: file.type, processData: false, xhrFields: { withCredentials: true }, xhr: function () { xhr.upload.onprogress = function (evt) { var percentComplete = evt.loaded / evt.total * 100; FauxtonAPI.dispatch({ type: ActionTypes.SET_FILE_UPLOAD_PERCENTAGE, options: { percent: percentComplete } }); }; return xhr; }, success: function () { // re-initialize the document editor. Only announce it's been updated when initDocEditor({ doc: params.doc, onLoaded: function () { FauxtonAPI.dispatch({ type: ActionTypes.FILE_UPLOAD_SUCCESS }); FauxtonAPI.addNotification({ msg: 'Document saved successfully.', type: 'success', clear: true }); }.bind(this) }); }, error: function (resp) { // cancelled uploads throw an ajax error but they don't contain a response. We don't want to publish an error // event in those cases if (_.isEmpty(resp.responseText)) { return; } FauxtonAPI.dispatch({ type: ActionTypes.FILE_UPLOAD_ERROR, options: { error: JSON.parse(resp.responseText).reason } }); } }); } function cancelUpload () { xhr.abort(); } function resetUploadModal () { FauxtonAPI.dispatch({ type: ActionTypes.RESET_UPLOAD_MODAL }); } // helpers function errorNotification (msg) { FauxtonAPI.addNotification({ msg: msg, type: 'error', clear: true }); } export default { initDocEditor: initDocEditor, saveDoc: saveDoc, // clone doc showCloneDocModal: showCloneDocModal, hideCloneDocModal: hideCloneDocModal, cloneDoc: cloneDoc, // delete doc showDeleteDocModal: showDeleteDocModal, hideDeleteDocModal: hideDeleteDocModal, deleteDoc: deleteDoc, // upload modal showUploadModal: showUploadModal, hideUploadModal: hideUploadModal, uploadAttachment: uploadAttachment, cancelUpload: cancelUpload, resetUploadModal: resetUploadModal };
garrensmith/couchdb-fauxton
app/addons/documents/doc-editor/actions.js
JavaScript
apache-2.0
6,952
/** * @license * Copyright 2013 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. */ /** * @fileoverview Utilities for asynchronous operations. */ goog.provide('e2e.async.util'); goog.require('e2e.async.Result'); goog.require('goog.async.Deferred'); /** * Wraps a function within a port. * @param {function(...*):*} callback The callback to use. * @return {!MessagePort} The port that wraps the callback. */ e2e.async.util.wrapFunction = function(callback) { var mc = new MessageChannel(); mc.port1.onmessage = function(event) { var args = []; for (var i = 0; i < event.data.arguments.length; i++) { var arg = event.data.arguments[i]; if (goog.isObject(arg) && typeof arg.__port__ === 'number') { args.push(e2e.async.util.unwrapFunction(event.ports[arg.__port__])); } else { args.push(arg); } } try { var returnValue = callback.apply(null, args); if (goog.async.Deferred && returnValue instanceof goog.async.Deferred) { returnValue.addCallback(function(ret) { e2e.async.util.return_(event.target, ret, ''); }).addErrback(function(err) { e2e.async.util.return_(event.target, undefined, String(err)); }); } else { e2e.async.util.return_(event.target, returnValue, ''); } } catch (e) { if (e instanceof Error) { e2e.async.util.return_(event.target, undefined, String(e.message)); } else { e2e.async.util.return_(event.target, undefined, 'Unknown error'); } } }; return mc.port2; }; /** * Sends a return message to the port. * @param {MessagePort} port The port to respond to. * @param {*} returnValue The return value of the function. * @param {string} error The error to send. * @private */ e2e.async.util.return_ = function(port, returnValue, error) { port.postMessage({ 'returnValue': returnValue, 'error': error }); }; /** * Unwraps a function from a port. * @param {MessagePort} port The port that is wrapping the function. * @return {function(...*):!e2e.async.Result} A function that calls the wrapped * function and returns a deferred result object. */ e2e.async.util.unwrapFunction = function(port) { return function() { var result = new e2e.async.Result(); port.onmessage = function(event) { if (event.data.error) { result.errback(event.data.error); } else { result.callback(event.data.returnValue); } }; var args = []; var ports = []; for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] == 'function') { var wrappedPort = e2e.async.util.wrapFunction(arguments[i]); ports.push(wrappedPort); args.push({ '__port__': ports.length - 1 }); } else { args.push(arguments[i]); } } port.postMessage({ 'arguments': args }, ports); return result; }; };
google/end-to-end
src/javascript/crypto/e2e/async/util.js
JavaScript
apache-2.0
3,479
'use strict'; /** * 어떤 일을 하고 있습니까? * @class VBOKeysNation */ var VBOKeysNation = function(bufferSizes, minSize) { if (!(this instanceof VBOKeysNation)) { throw new Error(Messages.CONSTRUCT_ERROR); } // buffer sizes are in bytes. this.vboKeysStoreMap = {}; this.bufferSizes = bufferSizes; this.minSize = minSize; this.maxSize = bufferSizes[bufferSizes.length-1]; this.totalBytesUsed = 0; var vboKeysStore; var sizesCount = bufferSizes.length; for (var i=0; i<sizesCount; i++) { vboKeysStore = new VBOKeysStore(bufferSizes[i]); this.vboKeysStoreMap[bufferSizes[i]] = vboKeysStore; if (bufferSizes[i] > this.maxSize) { this.maxSize = bufferSizes[i]; } } }; /** * 어떤 일을 하고 있습니까? * @returns vboBufferKey. */ VBOKeysNation.prototype.getClassifiedBufferKey = function(gl, bufferSize, keyWorld, onlyReuse) { // 1rst find the vboKeyStore for this bufferSize. var closestBufferSize = this.getClosestBufferSize(bufferSize); var vboKeyStore = this.vboKeysStoreMap[closestBufferSize]; if (vboKeyStore) { return vboKeyStore.getBufferKey(gl, this, keyWorld, onlyReuse); } else { return -1; } }; /** * 어떤 일을 하고 있습니까? * @returns vboBufferKey. */ VBOKeysNation.prototype.storeClassifiedBufferKey = function(bufferKey, bufferSize) { // 1rst find the vboKeyStore for this bufferSize. var vboKeyStore = this.vboKeysStoreMap[bufferSize]; if (vboKeyStore) { vboKeyStore.storeBufferKey(bufferKey); } }; /** * 어떤 일을 하고 있습니까? * @returns boolean. true if the currentBufferSize is in the range of this nation. */ VBOKeysNation.prototype.getClosestBufferSize = function(currentBufferSize) { if (!this.isInsideRange(currentBufferSize)) { return -1; } var sizesCount = this.bufferSizes.length; for (var i=0; i<sizesCount; i++) { if (currentBufferSize <= this.bufferSizes[i]) { return this.bufferSizes[i]; } } return -1; }; /** * 어떤 일을 하고 있습니까? * @returns boolean. true if the currentBufferSize is in the range of this nation. */ VBOKeysNation.prototype.isInsideRange = function(bufferSize) { if (bufferSize > this.maxSize || bufferSize < this.minSize) { return false; } return true; };
Gaia3D/mago3djs
src/mago3d/core/VBOKeysNation.js
JavaScript
apache-2.0
2,247
'use strict'; var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var yosay = require('yosay'); var path = require('path'); var urllib = require('urllib'); module.exports = yeoman.generators.Base.extend({ prompting: function () { var done = this.async(); this.pkg = require(path.join(__dirname, '../../package.json')); let noUpdate = null if (process && process.argv && process.argv[3]) { noUpdate = process.argv[3] } if (noUpdate !== '-noupdate') { this.log( chalk.yellow('正在检查更新...') ); urllib.request('http://registry.npm.taobao.org/generator-tvwheel/latest', function (err, data, res) { if (err || res.statusCode != 200) { this.log( chalk.red('检查更新出错') ); } else { data = JSON.parse(data.toString()); if (data.version !== this.pkg.version) { this.log( '发现新版本:' + chalk.red(data.version) + ', 当前版本:' + chalk.yellow(this.pkg.version) + '.' ); this.log( '版本有更新,建议更新:npm install -g generator-tvwheel' ); } else { this.log( '当前版本为最新版本' ); } } this.log(yosay( 'Welcome to the polished ' + chalk.red('tvwheel') + ' generator!' )); done(); }.bind(this)); } else { done(); } }, writing: { init: function () { }, askFor: function () { var cb = this.async(); var fileName = path.basename(process.cwd()); var prompts = [ { type: 'rawlist', name: 'type', message: 'Type of Component?', choices: [ { name: 'BaseComponent(无界面功能性组件)', value: '0' }, { name: 'DisplayComponent(显示UI组件)', value: '1' }, { name: 'FocusableComponent(有焦点切换组件,且基于FocusEngine)', value: '2' } ], default: '0', warning: '' }, { name: 'projectName', message: 'Name of Component?', default: fileName, warning: '' }, { name: 'author', message: 'Author Name:', default: '', warning: '' }, { name: 'email', message: 'Author Email:', default: '', warning: '' }, // { // name: 'groupName', // message: 'Group Name:', // default: 'de', // warning: '' // }, { name: 'version', message: 'Version:', default: '0.0.1', warning: '' } ]; // your-mojo-name => YourMojoName function parseMojoName(name) { return name.replace(/\b(\w)|(-\w)/g, function (m) { return m.toUpperCase().replace('-', ''); }); } this.prompt(prompts, function (props) { this.type = props.type; this.packageName = props.projectName;// project-name this.projectName = parseMojoName(this.packageName); //ProjectName this.author = props.author; this.email = props.email; this.version = props.version; // this.groupName = props.groupName; var base = '~0.0.1' var display = '~0.0.1' var focusable = '~0.0.1' if (props.type == '0') { this.dependencies = '{\n' + '\t\t"silver-base": "' + base + '"\n' + '\t}'; } else if (props.type == '1') { this.dependencies = '{\n' + '\t\t"silver-base": "' + base + '",\n' + '\t\t"silver-display": "' + display + '"\n' + '\t}'; } else { this.dependencies = '{\n' + '\t\t"silver-base": "' + base + '",\n' + '\t\t"silver-display": "' + display + '",\n' + '\t\t"silver-focusable": "' + focusable + '"\n' + '\t}'; } cb(); }.bind(this)); }, app: function () { this.template( this.templatePath('index.js'), this.destinationPath('index.js') ); this.template( this.templatePath('index.mobile.js'), this.destinationPath('index.mobile.js') ); this.fs.copy( this.templatePath('gulpfile.js'), this.destinationPath('gulpfile.js') ); this.fs.copy( this.templatePath('gulp'), this.destinationPath('gulp') ); this.template( this.templatePath('_package.json'), this.destinationPath('package.json') ); this.fs.copy( this.templatePath('_hubrc'), this.destinationPath('.hubrc') ); this.fs.copy( this.templatePath('_docConfig.json'), this.destinationPath('docConfig.json') ); this.fs.copy( this.templatePath('_gitignore'), this.destinationPath('.gitignore') ); this.template( this.templatePath('README.md'), this.destinationPath('README.md') ); //this.template( // this.templatePath('lib'), // this.destinationPath('lib') //); this.mkdir('lib'); this.mkdir('build'); this.mkdir('demo'); if (this.type == 1) { this.template( this.templatePath('lib/index-1.js'), this.destinationPath('lib/index.js') ); } else if (this.type == 2) { this.template( this.templatePath('lib/index-2.js'), this.destinationPath('lib/index.js') ); } else { this.template( this.templatePath('lib/index.js'), this.destinationPath('lib/index.js') ); } }, projectfiles: function () { this.fs.copy( this.templatePath('editorconfig'), this.destinationPath('.editorconfig') ); } }, install: function () { //this.installDependencies(); } });
liudan92221/generator-tvwheel
generators/app/index.js
JavaScript
apache-2.0
6,185
var mongoose = require('mongoose'); var Schemas = require('./Schemas'); var Game = mongoose.model('Game',Schemas.gameSchema); exports.Game = Game;
urobo/Gambler
Models.js
JavaScript
apache-2.0
148
var // get util library util = require("core/Util"), // get product manager ProductManager = require("core/ProductManager"); function ProductListWindow() { var Window = Ti.UI.createWindow({ title : L("products"), navBarHidden : false, barColor : Theme.TabGroup.BarColor, navTintColor : Theme.TabGroup.NavTintColor, backgroundColor : Theme.Windows.BackgroundColor }), Table = Ti.UI.createTableView({ width : Ti.UI.FILL, height : Ti.UI.FILL, backgroundColor : "#FFFFFF" }); // get product manager var products = require("core/ProductManager"), productEvents = products.events; // assemble UI Window.add(Table); /* * Product row factory method * * @param {String} name: the product name to display * @param {String} image: the icon image to display * @param {String} desc: description of item to display in row * @param {String} itemId: item id used to load product page */ function createRow(name, image, desc, itemId){ var row = Ti.UI.createTableViewRow({ className : "product_rows", backgroundColor : Theme.ProductsList.RowsBackgroundColor, selectedBackgroundColor : Theme.ProductsList.SelectedBackgroundColor, hasChild : true }), img = Ti.UI.createImageView({ image : image, left : 1, top : 1, borderWidth : 3, borderColor : Theme.ProductsList.ImageBorderColor, defaultImage : Config.PRODUCTS_DEFAULT_THUMB_IMAGE }), bodyView = Ti.UI.createView({ layout : "vertical" }), title = Ti.UI.createLabel({ text : name, minimumFontSize : 12, color : Theme.ProductsList.TitleColor, height : Ti.UI.SIZE, left : 2, top : 4, font : { fontSize : Theme.ProductsList.TitleFontSize, fontWeight : Theme.ProductsList.TitleFontWeight } }), body = Ti.UI.createLabel({ text : desc, height : Ti.UI.SIZE, left : 2, top : 2, color : Theme.ProductsList.DescriptionColor, font : { fontSize : Theme.ProductsList.DescriptionFontSize, fontWeight : Theme.ProductsList.DescriptionFontWeight } }); // assemble row bodyView.add(title); bodyView.add(body); row.add(img); if(util.osname==="android"){ img.width = Theme.ProductsList.ImageWidth + "dip"; img.height = Theme.ProductsList.ImageHeight + "dip"; bodyView.left = (Theme.ProductsList.ImageWidth + 1) + "dip"; bodyView.right = "3dip"; bodyView.top = 0; bodyView.bottom = 0; body.height = Ti.UI.SIZE; } else{ img.width = 81; bodyView.left = 82; bodyView.height = Ti.UI.SIZE; } row.add(bodyView); // handle featured item click event row.addEventListener( "click", function(e){ Ti.App.fireEvent( "APP:SHOW_PRODUCT", { "itemId" : itemId, "tab" : "Products" } ); } ); return row; } /* * Product group factory method * * @param {String} name: the name of the group/section * @param {Array} products: array of products for this group/section */ function createProductGroup(name, products){ var productGroupHeader = Ti.UI.createLabel({ text : " "+name, //add space for padding (border not working for left padding) textAlign : Ti.UI.TEXT_ALIGNMENT_LEFT, color : Theme.ProductsList.HeaderColor, backgroundColor : Theme.ProductsList.HeaderBackgroundColor, borderWidth : 2, borderColor : Theme.ProductsList.HeaderBackgroundColor, font : { fontSize : Theme.ProductsList.HeaderFontSize, fontWeight : Theme.ProductsList.HeaderFontWeight } }), productGroup = Ti.UI.createTableViewSection({ headerView : productGroupHeader }); for(var i=0,l=products.length;i<l;i++){ productGroup.add( createRow( products[i].name, products[i].imgs.thumb, products[i].desc.short, products[i].id ) ); } return productGroup; } /* * Assemble product groups for table view * * @param {Object} groups: the groups object containing product arrays for each group/section */ function displayProducts(){ var data = [], groups = require("core/ProductManager").getProductGroup("__ALL__"); for(var key in groups){ data.push( createProductGroup( key, groups[key] ) ); } Table.setData(data); } Window.addEventListener( "focus", displayProducts ); return Window; }; module.exports = ProductListWindow;
nicolascine/TiClassicApp
Resources/ui/ProductsListWindow.js
JavaScript
apache-2.0
4,611
var AutoSubmit = { setupAutoSubmit: function(field, button) { $(field).keypress(function(evt) { if (AutoSubmit.isEnter(evt)) { return false; } }); $(field).keydown(function(evt) { if (AutoSubmit.isEnter(evt)) { $(button).click(); return false; } return true; }); $(field).bind("focus", function() { $(button).addClass("autoselect"); }); $(field).bind("blur", function() { $(button).removeClass("autoselect"); }); }, isEnter: function(evt) { var key = 0; if (evt && evt.keyCode) { key = evt.keyCode; } else if (evt && evt.which) { key = evt.which; } if (key == 13) { return true; } return false; } };
equella/Equella
Source/Plugins/Core/com.equella.core/resources/web/js/autosubmit.js
JavaScript
apache-2.0
707
(function($) { module("applicationSettings1"); // Test case : Application Settings _asyncTest("Application Settings 1", function() { expect(14); var gitana = GitanaTest.authenticateFullOAuth(); gitana.then(function() { // NOTE: this = platform var platform = this; // create a application this.createApplication().then(function() { // NOTE: this = application var application = this; // ensure zero settings at onset this.listSettings().count(function(count) { equal(count, 0, "No settings"); }); var applicationSettings; this.readApplicationSettings().then(function() { applicationSettings = this; }); // should now be 1 setting this.listSettings().count(function(count) { equal(count, 1, "One setting"); }); this.then(function() { this.subchain(applicationSettings).then(function() { this.setSetting('key1','val1'); this.setSetting('key2',true); this.setSetting('key3',['arr1','arr2']); this.setSetting('key4',3); this.setSetting('key5',{ "foo" : "bar", "foo2" : "bar2" }); this.update(); }); }); this.readApplicationSettings().then(function() { equal(this.getSetting('key1'), 'val1', "String setting is set with correct value."); equal(this.getSetting('key2'), true, "Boolean setting is set with correct value."); deepEqual(this.getSetting('key3'), ['arr1','arr2'], "Array setting is set with correct value."); equal(this.getSetting('key4'), 3, "Integer setting is set with correct value."); deepEqual(this.getSetting('key5'), { "foo" : "bar", "foo2" : "bar2" }, "Object setting is set with correct value."); }); this.querySettings({ "settings.key1" : "val1" }).count(function(count) { equal(count, 1, "Found the setting via query."); }); this.subchain(platform).readPrimaryDomain().then(function() { var user1 = null; var userName1 = "user" + new Date().getTime(); this.createUser({ "name": userName1 }).then(function() { user1 = this; this.subchain(application).readApplicationPrincipalSettings(user1).then(function() { this.setSetting('ukey1', 'val1'); this.setSetting('ukey2', true); this.setSetting('ukey3', ['arr1','arr2']); this.setSetting('ukey4', 3); this.setSetting('ukey5', { "foo" : "bar", "foo2" : "bar2" }); this.update().reload().then(function() { equal(this.getSetting('ukey1'), 'val1', "Principal string setting is set with correct value."); equal(this.getSetting('ukey2'), true, "Principal boolean setting is set with correct value."); deepEqual(this.getSetting('ukey3'), ['arr1','arr2'], "Principal array setting is set with correct value."); equal(this.getSetting('ukey4'), 3, "Principal integer setting is set with correct value."); deepEqual(this.getSetting('ukey5'), { "foo" : "bar", "foo2" : "bar2" }, "Object setting is set with correct value."); }); this.then(function() { this.subchain(user1).del(); }); }); }); }); this.then(function() { this.subchain(applicationSettings).del().then(function() { this.subchain(application).querySettings({ "settings.key1" : "val1" }).count(function(count) { equal(count, 0, "Application settings has been deleted."); }); }); }); this.del(); }); this.then(function() { success(); }); }); var success = function() { start(); }; }); }(jQuery) );
gitana/gitana-javascript-driver
tests/js/testApplicationSettings1.js
JavaScript
apache-2.0
5,226
import Base from '../Base'; import RelaunchMixin from '../mixins/Relaunch.mixin'; const BASE_URLS = { playbook: '/jobs/', project: '/project_updates/', system: '/system_jobs/', inventory: '/inventory_updates/', command: '/ad_hoc_commands/', workflow: '/workflow_jobs/', }; class Jobs extends RelaunchMixin(Base) { constructor(http) { super(http); this.baseUrl = '/api/v2/jobs/'; } readDetail(id, type) { return this.http.get(`/api/v2${BASE_URLS[type]}${id}/`); } readEvents(id, type = 'playbook', params = {}) { let endpoint; if (type === 'playbook') { endpoint = `/api/v2${BASE_URLS[type]}${id}/job_events/`; } else { endpoint = `/api/v2${BASE_URLS[type]}${id}/events/`; } return this.http.get(endpoint, { params }); } } export default Jobs;
GoogleCloudPlatform/sap-deployment-automation
third_party/github.com/ansible/awx/awx/ui_next/src/api/models/Jobs.js
JavaScript
apache-2.0
816
/** * Copyright 2014 SCN SDK Community * * Original Source Code Location: * https://github.com/org-scn-design-studio-community/sdkpackage/ * * 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. */ jQuery.sap.require("sap.ui.table.Table"); sap.ui.commons.layout.AbsoluteLayout.extend("org.scn.community.databound.UI5Table", { setData : function(value) { var that = this; this._data = value; // clean mixed Data that._flatData = undefined; return this; }, getData : function(value) { return this._data; }, setMetadata : function(value) { this._metadata = value; return this; }, getMetadata : function() { return this._metadata; }, /* special code as we want to reset */ setDElements : function(value) { this.DElements = value; this._isInitialized = undefined; this._flatData = undefined; return this; }, getDElements : function() { return this.DElements; }, /* special code as we want to reset */ setDContentMode : function(value) { this.DContentMode = value; this._isInitialized = undefined; this._flatData = undefined; return this; }, getDContentMode : function() { return this.DContentMode; }, metadata: { properties: { "DVisibleRowCount": {type: "int"}, "DRowHeight": {type: "int"}, "DNavigationMode": {type: "string"}, "DCustomDimensions": {type: "string"}, "DHeaderColWidth": {type: "int"}, } }, initDesignStudio: function() { var that = this; that._table = new sap.ui.table.Table(this.getId() + "_ta", { selectionMode: sap.ui.table.SelectionMode.Single, // enableGrouping: true, } ); this.addStyleClass("scn-pack-FullSizeChildren"); // set the model that._oModel = new sap.ui.model.json.JSONModel(); that._table.setModel(that._oModel); that._table.bindRows("/data2DPlain"); this.addContent( that._table, {left: "0px", top: "0px"} ); org_scn_community_basics.hideNoDataOverlay(this.getId(), true); that.onAfterRendering = function() { }; }, renderer: {}, afterDesignStudioUpdate: function() { var that = this; that._table.setVisibleRowCount(this.getDVisibleRowCount()); that._table.setRowHeight(this.getDRowHeight()); var lNavMode = this.getDNavigationMode(); if(lNavMode == "Paginator") { that._table.setNavigationMode(sap.ui.table.NavigationMode.Paginator); } else { that._table.setNavigationMode(sap.ui.table.NavigationMode.Scrollbar); } // define model if(that._flatData == undefined) { var lData = this._data; var lMetadata = this._metadata; var lDimensions = this.getDElements(); if(lMetadata == undefined) { lMetadata = lData; } if(lData == "") { this._fakeData(); } else { var options = org_scn_community_databound.initializeOptions(); options.ignoreResults = true; that._vals = []; try{ that._flatData = org_scn_community_databound.flatten(lData,options); that._rowData = org_scn_community_databound.toRowTable(that._flatData,options); if(that._flatData && that._flatData.formattedValues && that._flatData.formattedValues.length > 0) { that._vals = that._flatData.formattedValues.slice(); }else if(that._flatData && that._flatData.values && that._flatData.values.length > 0){ that._vals = that._flatData.values.slice(); }else{ // Something happened. throw("No formatted or unformatted values found."); } }catch(e){ var errorMessage = e; if(e && e.indexOf("Incomplete data given.")>-1) errorMessage = "Incomplete data. Try assigning a datasource."; if(!that._flatData) that._flatData = { columnHeaders : ["Error"], rowHeaders : [errorMessage] }; that._vals = [[]]; } } that._table.removeAllColumns(); var rI=0; if(that._rowData) { for(rI=0;rI<that._rowData.dimensionHeaders.length;rI++){ that._table.addColumn(new sap.ui.table.Column({ label: new sap.ui.commons.Label( { text: that._rowData.dimensionHeaders[rI], design: sap.ui.commons.LabelDesign.Bold, }), template: new sap.ui.commons.Label( { design: sap.ui.commons.LabelDesign.Bold, }).bindProperty("text", ""+rI), sortProperty: ""+rI, filterProperty: ""+rI, width: that.getDHeaderColWidth()+"px" })); } for(var cI=0;cI<that._rowData.columnHeaders.length;cI++){ that._table.addColumn(new sap.ui.table.Column({ label: new sap.ui.commons.Label({text: that._rowData.columnHeaders[cI]}), template: new sap.ui.commons.Label( { design: sap.ui.commons.LabelDesign.Normal, textAlign: sap.ui.core.TextAlign.Right, } ).bindProperty("text", ""+rI), sortProperty: ""+rI, filterProperty: ""+rI, })); rI = rI+1; } that._table.setFixedColumnCount(that._rowData.dimensionHeaders.length); } } that._oModel.setData(that._rowData); }, _fakeData : function () { } });
YunuSahin/sdk
src/org.scn.community.databound/res/UI5Table/UI5Table.js
JavaScript
apache-2.0
5,598
module.exports = function (client) { const baseUrl = '/api-endpoints/'; return { create (name, endpointConfig) { return client .put(`${baseUrl}${encodeURIComponent(name)}`) .send(endpointConfig) .then(res => res.body); }, update (name, endpointConfig) { return this.create(name, endpointConfig); }, remove (name) { return client .del(`${baseUrl}${encodeURIComponent(name)}`) .then(res => res.body); }, info (name) { return client .get(`${baseUrl}${encodeURIComponent(name)}`) .then(res => res.body); }, list () { return client .get(baseUrl) .then(res => res.body); } }; };
ExpressGateway/express-gateway
admin/config/api-endpoints.js
JavaScript
apache-2.0
722
define(function(require) { 'use strict'; var modules = require('modules'); var states = require('states'); var _ = require('lodash'); var angular = require('angular'); states.state('applications.detail.deployment.input', { url: '/input', templateUrl: 'views/applications/application_deployment_input.html', controller: 'ApplicationDeploymentSetupCtrl', menu: { id: 'am.applications.detail.deployment.input', state: 'applications.detail.deployment.input', key: 'APPLICATIONS.DEPLOYMENT.INPUT', icon: 'fa fa-sign-in', roles: ['APPLICATION_MANAGER', 'APPLICATION_DEPLOYER'], // is deployer, priority: 300, step: { nextStepId: 'am.applications.detail.deployment.deploy', taskCodes: ['INPUT_PROPERTY', 'ORCHESTRATOR_PROPERTY'] } } }); modules.get('a4c-applications').controller('ApplicationDeploymentSetupCtrl', ['$scope', '$upload', 'applicationServices', '$http', '$filter', 'deploymentTopologyServices', function($scope, $upload, applicationServices, $http, $filter, deploymentTopologyServices) { $scope.isAllowedInputDeployment = function() { return !_.isEmpty($filter('allowedInputs')($scope.deploymentContext.deploymentTopologyDTO.topology.inputs)); }; /* Handle properties inputs */ $scope.updateInputValue = function(definition, inputValue, inputId) { // No update if it's the same value if (_.undefined($scope.deploymentContext.deploymentTopologyDTO.topology.inputProperties)) { $scope.deploymentContext.deploymentTopologyDTO.topology.inputProperties = {}; } if (inputValue === $scope.deploymentContext.deploymentTopologyDTO.topology.inputProperties[inputId]) { return; } else { $scope.deploymentContext.deploymentTopologyDTO.topology.inputProperties[inputId] = inputValue; } return deploymentTopologyServices.updateInputProperties({ appId: $scope.application.id, envId: $scope.deploymentContext.selectedEnvironment.id }, angular.toJson({ inputProperties: $scope.deploymentContext.deploymentTopologyDTO.topology.inputProperties }), function(result){ if(!result.error) { $scope.updateScopeDeploymentTopologyDTO(result.data); } }).$promise; }; // Artifact upload handler $scope.doUploadArtifact = function(file, artifactName) { if (_.undefined($scope.uploads)) { $scope.uploads = {}; } $scope.uploads[artifactName] = { 'isUploading': true, 'type': 'info' }; $upload.upload({ url: 'rest/latest/topologies/' + $scope.topologyDTO.topology.id + '/inputArtifacts/' + artifactName + '/upload', file: file }).progress(function(evt) { $scope.uploads[artifactName].uploadProgress = parseInt(100.0 * evt.loaded / evt.total); }).success(function(success) { $scope.deploymentContext.deploymentTopologyDTO.topology.inputArtifacts[artifactName].artifactRef = success.data.topology.inputArtifacts[artifactName].artifactRef; $scope.deploymentContext.deploymentTopologyDTO.topology.inputArtifacts[artifactName].artifactName = success.data.topology.inputArtifacts[artifactName].artifactName; $scope.uploads[artifactName].isUploading = false; $scope.uploads[artifactName].type = 'success'; }).error(function(data, status) { $scope.uploads[artifactName].type = 'error'; $scope.uploads[artifactName].error = {}; $scope.uploads[artifactName].error.code = status; $scope.uploads[artifactName].error.message = 'An Error has occurred on the server!'; }); }; $scope.onArtifactSelected = function($files, artifactName) { var file = $files[0]; $scope.doUploadArtifact(file, artifactName); }; $scope.refreshOrchestratorDeploymentPropertyDefinitions = function() { return $http.get('rest/latest/orchestrators/' + $scope.deploymentContext.deploymentTopologyDTO.topology.orchestratorId + '/deployment-property-definitions').success(function(result) { if (result.data) { $scope.deploymentContext.orchestratorDeploymentPropertyDefinitions = result.data; } }); }; $scope.refreshOrchestratorDeploymentPropertyDefinitions(); $scope.updateDeploymentProperty = function(propertyDefinition, propertyName, propertyValue) { if (propertyValue === $scope.deploymentContext.deploymentTopologyDTO.topology.providerDeploymentProperties[propertyName]) { return; // no change } var deploymentPropertyObject = { 'definitionId': propertyName, 'value': propertyValue }; return applicationServices.checkProperty({ orchestratorId: $scope.deploymentContext.deploymentTopologyDTO.topology.orchestratorId }, angular.toJson(deploymentPropertyObject), function(data) { if (data.error === null) { $scope.deploymentContext.deploymentTopologyDTO.topology.providerDeploymentProperties[propertyName] = propertyValue; // Update deployment setup when properties change deploymentTopologyServices.updateInputProperties({ appId: $scope.application.id, envId: $scope.deploymentContext.selectedEnvironment.id }, angular.toJson({ providerDeploymentProperties: $scope.deploymentContext.deploymentTopologyDTO.topology.providerDeploymentProperties }), function(result){ if(!result.error) { $scope.updateScopeDeploymentTopologyDTO(result.data); } } ); } }).$promise; }; } ]); //controller }); //Define
PierreLemordant/alien4cloud
alien4cloud-ui/src/main/webapp/scripts/applications/controllers/application_deployment_input.js
JavaScript
apache-2.0
6,101
'use strict'; var pkg = require('../package'); var log = require('debug')(pkg.name + ':Query'); console.log.bind(log); var error = require('debug')(pkg.name + ':Query'); console.error.bind(error); var async = require('async'); var spawn = require('child_process').spawn; var moment = require('moment'); var xml2js = require('xml2js'); var setClass = function(className, cb) { if (typeof(className) === 'function') { cb = className; className = undefined; } log('Set class property for instance to %s.', className); this._params.class = className; if (typeof(cb) === 'function') { log('setClass called with callback function. Execute query.'); this.exec(cb); } return this; }; var setHost = function(host, cb) { if (typeof(host) === 'function') { cb = host; host = undefined; } log('Set host property for instance to %s.', host); this._params.host = host || 'localhost'; if (typeof(cb) === 'function') { log('setHost called with callback function. Execute query.'); this.exec(cb); } return this; }; var setNamespace = function(namespace, cb) { if (typeof(namespace) === 'function') { cb = namespace; namespace = undefined; } if (!namespace) { namespace = 'root\\CIMV2'; } namespace = namespace.replace(/\//g, '\\'); log('Set namespace property for instance to %s.', namespace); this._params.namespace = namespace; if (typeof(cb) === 'function') { log('setNamespace called with callback function. Execute query.'); this.exec(cb); } return this; }; var setPassword = function(password, cb) { if (typeof(password) === 'function') { cb = password; password = undefined; } log('Set password property for instance to %s.', password); this._params.password = password; if (typeof(cb) === 'function') { log('setPassword called with callback function. Execute query.'); this.exec(cb); } return this; }; var setProps = function(props, cb) { if (typeof(props) === 'function') { cb = props; props = undefined; } if (Array.isArray(props)) { props = props.join(','); } log('Set props property for instance to %s.', props); this._params.props = props; if (typeof(cb) === 'function') { log('setProps called with callback function. Execute query.'); this.exec(cb); } return this; }; var setUsername = function(username, cb) { if (typeof(username) === 'function') { cb = username; username = undefined; } log('Set username property for instance to %s.', username); this._params.username = username; if (typeof(cb) === 'function') { log('setUsername called with callback function. Execute query.'); this.exec(cb); } return this; }; var setWhere = function(where, cb) { if (typeof(where) === 'function') { cb = where; where = undefined; } log('Set where property for instance to %s.', where); this._params.where = where; if (typeof(cb) === 'function') { log('setWhere called with callback function. Execute query.'); this.exec(cb); } return this; }; var getArgsArray = function(params) { log('Create array of arguments.'); var args = [ '/NAMESPACE:\\\\' + params.namespace, '/NODE:\'' + params.host + '\'', ]; if (params.username) { args.push('/USER:\'' + params.username + '\''); } if (params.password) { args.push('/PASSWORD:\'' + params.password + '\''); } args.push('path'); args.push(params.class); if (params.where) { if (typeof(params.where) === 'string' && params.where.length) { args.push('Where'); if (params.where.substr(0, 1) !== '(') { params.where = '(' + params.where + ')'; } args.push(params.where); } else if (Array.isArray(params.where) && params.where.length) { var str = ''; for (var i = 0; i < params.where.length; i++) { var tmp = params.where[i]; if (typeof(tmp) === 'string') { str += ' And ' + tmp; } else if (typeof(tmp) === 'object') { str += ' And ' + params.where[i].property + '=\'' + params.where[i].value + '\''; } } str = '(' + str.replace(/^\sAnd\s/, '') + ')'; if (str !== '()') { args.push('Where'); args.push(str); } } } args.push('get'); if (params.props) { var props = params.props; if (Array.isArray(props)) { props = props.join(','); } args.push(props); } args.push('/FORMAT:rawxml'); log('Created array of arguments.', args); return args; }; var typeValue = function(value, type) { if (value !== undefined) { if (['uint64', 'uint32', 'uint16', 'uint8', 'sint64', 'sint32', 'sint16', 'sint8' ].indexOf(type) !== -1) { value = parseInt(value); } else if (['real64', 'real32', 'real16', 'real8'].indexOf(type) !== -1) { value = parseFloat(value); } else if (type === 'boolean') { if (value === 'TRUE') { value = true; } else { value = false; } } else if (type === 'datetime') { value = moment(value).toDate(); } } return value; }; var extractProperty = function(prop) { var name; var type; var value; if ('$' in prop) { name = prop.$.NAME; type = prop.$.TYPE; } else { name = prop.NAME; type = prop.TYPE; } if ('VALUE' in prop) { value = prop.VALUE; if (Array.isArray(value)) { value = value[0]; } value = typeValue(value, type); } else if ('VALUE.ARRAY' in prop && prop['VALUE.ARRAY'].length > 0 && prop['VALUE.ARRAY'][0].VALUE) { value = []; for (var i = 0; i < prop['VALUE.ARRAY'][0].VALUE.length; i++) { value.push(typeValue(prop['VALUE.ARRAY'][0].VALUE[i], type)); } } return { name: name, type: type, value: value }; }; var exec = function(cb) { log('Execute query.'); if (typeof(cb) !== 'function') { cb = function() {}; } if (!this._params.class) { log('Unable to execute query. Class is undefined.'); return cb(new Error('No class defined to query.')); } var args = getArgsArray(this._params); var cp = spawn('wmic', args, { stdio: ['ignore', 'pipe', 'pipe'] }); cp.on('error', function(err) { error('Error while performing query.', err); cb(err); }); var stdout = ''; var stderr = ''; cp.stdout.on('data', function(data) { stdout += data; }); cp.stderr.on('data', function(data) { stderr += data; }); cp.on('close', function(code) { if (code !== 0) { stderr = stderr.toString().replace(/ERROR:\r\r\n/, ''); stderr = stderr.replace(/\r\r\n$/g, '').replace(/Description = /, ''); var err = new Error(stderr); err.exitCode = code; log('Query finished with error code.'); return cb(err); } stdout = stdout.toString(); if (!stdout) { return cb(); } var parser = new xml2js.Parser({ explicitArray: true }); async.auto({ parse: function(cb) { log('Parse results into xml.'); parser.parseString(stdout, cb); }, mangle: ['parse', function(cb, result) { if (!result.parse.COMMAND.RESULTS[0].CIM) { log('No results from query.'); return cb(); } log('Parse xml into formatted json.'); async.map(result.parse.COMMAND.RESULTS[0].CIM[0].INSTANCE, function(instance, cb) { var props = {}; async.auto({ nativeProperties: function(cb) { async.each(instance.PROPERTY, function(prop, cb) { var propInfo = extractProperty(prop); props[propInfo.name] = propInfo.value; cb(); }, cb); }, relatedProperties: function(cb) { async.each(instance['PROPERTY.ARRAY'], function(prop, cb) { var propInfo = extractProperty(prop); props[propInfo.name] = propInfo.value; cb(); }, cb); } }, function() { cb(null, props); }); }, cb); }] }, function(err, result) { log('Execution completed.'); cb(err, result.mangle); }); }); }; var Query = function Query(options, cb) { if (!(this instanceof Query)) { log('Query class called without. Instantiate new instance automatically.'); return new Query(options, cb); } log('Create new instance of query class.'); if (typeof(options) === 'function') { cb = options; options = {}; } else if (typeof(options) !== 'object') { options = {}; } this._params = {}; setClass.call(this, options.class); setHost.call(this, options.host || 'localhost'); setNamespace.call(this, options.namespace || 'root\\CIMV2'); setPassword.call(this, options.password); setProps.call(this, options.properties || options.props); setUsername.call(this, options.username); setWhere.call(this, options.where); log('Param values set during class creation.'); if (typeof(cb) === 'function') { log('Class called with immediate function callback.'); this.exec(cb); } Query.prototype.exec = exec.bind(this); return this; }; Query.prototype.host = setHost; Query.prototype.namespace = setNamespace; Query.prototype.class = setClass; Query.prototype.username = setUsername; Query.prototype.password = setPassword; Query.prototype.props = Query.prototype.properties = setProps; Query.prototype.where = setWhere; exports = module.exports = Query;
WeHaus/WeHaus_NodeJS_Client
node_modules/node-wmi/lib/Query.js
JavaScript
apache-2.0
9,589
var searchData= [ ['ebert_5fgraph_2eh_0',['ebert_graph.h',['../ebert__graph_8h.html',1,'']]], ['element_2ecc_1',['element.cc',['../element_8cc.html',1,'']]], ['encoding_2ecc_2',['encoding.cc',['../encoding_8cc.html',1,'']]], ['encoding_2eh_3',['encoding.h',['../encoding_8h.html',1,'']]], ['encodingutils_2eh_4',['encodingutils.h',['../encodingutils_8h.html',1,'']]], ['entering_5fvariable_2ecc_5',['entering_variable.cc',['../entering__variable_8cc.html',1,'']]], ['entering_5fvariable_2eh_6',['entering_variable.h',['../entering__variable_8h.html',1,'']]], ['environment_2ecc_7',['environment.cc',['../environment_8cc.html',1,'']]], ['environment_2eh_8',['environment.h',['../environment_8h.html',1,'']]], ['eulerian_5fpath_2eh_9',['eulerian_path.h',['../eulerian__path_8h.html',1,'']]], ['expr_5farray_2ecc_10',['expr_array.cc',['../expr__array_8cc.html',1,'']]], ['expr_5fcst_2ecc_11',['expr_cst.cc',['../expr__cst_8cc.html',1,'']]], ['expressions_2ecc_12',['expressions.cc',['../expressions_8cc.html',1,'']]] ];
google/or-tools
docs/cpp/search/files_4.js
JavaScript
apache-2.0
1,043
/* Run a HTTP server that registers its location using the Datawire * Microservices Development Kit (MDK). * * Make sure you have the DATAWIRE_TOKEN environment variable set with your * access control token. */ /* jshint node: true */ "use strict"; var process = require("process"); var args = process.argv.splice(process.execArgv.length + 2); if (args.length === 0) { throw "usage: server service-name [port]"; } var mdk = require("datawire_mdk").mdk; var MDK = mdk.start(); process.on("beforeExit", function (code) { MDK.stop(); }); var host = "127.0.0.1"; // We are reachable only on localhost var port = 5000; var service = args[0]; if (args.length > 1) { port = parseInt(args[1]) || port; } MDK.register(service, "1.0.0", "http://" + host + ":" + port.toString()); var express = require("express"); var app = express(); app.get("/", function (req, res) { // Join the logging context from the request, if possible: var ssn = MDK.join(req.get(mdk.MDK.CONTEXT_HEADER)); ssn.info(service, "Received a request."); res.send("Hello World (Node/Express)"); }); app.listen(port, host);
datawire/mdk-docs
examples/javascript-local/server.js
JavaScript
apache-2.0
1,134
'use strict'; var common = require('../common'); var assert = require('assert'); var Transform = require('stream').Transform; var _transformCalled = false; function _transform(d, e, n) { _transformCalled = true; n(); } var _flushCalled = false; function _flush(n) { _flushCalled = true; n(); } var t = new Transform({ transform: _transform, flush: _flush }); t.end(new Buffer('blerg')); t.resume(); process.on('exit', function() { assert.equal(t._transform, _transform); assert.equal(t._flush, _flush); assert(_transformCalled); assert(_flushCalled); });
dreamllq/node
test/parallel/test-stream-transform-constructor-set-methods.js
JavaScript
apache-2.0
581
/** * @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 resolve = require( 'path' ).resolve; var glob = require( 'glob' ).sync; var cwd = require( '@stdlib/process/cwd' ); var copy = require( '@stdlib/utils/copy' ); var DEFAULTS = require( './defaults.json' ); var validate = require( './validate.js' ); var linter = require( './lint.js' ); var IGNORE = require( './ignore_patterns.json' ); // MAIN // /** * Synchronously lints filenames. * * @param {Options} [options] - function options * @param {string} [options.dir] - root directory from which to search for files * @param {string} [options.pattern='**\/*'] - filename pattern * @throws {TypeError} options argument must be an object * @throws {TypeError} must provide valid options * @returns {(ObjectArray|EmptyArray)} list of lint errors * * @example * var errs = lint(); * // returns [...] */ function lint( options ) { var pattern; var names; var opts; var err; var dir; opts = copy( DEFAULTS ); if ( arguments.length ) { err = validate( opts, options ); if ( err ) { throw err; } } if ( opts.dir ) { dir = resolve( cwd(), opts.dir ); } else { dir = cwd(); } pattern = opts.pattern; opts = { 'cwd': dir, 'ignore': IGNORE, 'nodir': true // do not match directories }; names = glob( pattern, opts ); return linter( names ); } // EXPORTS // module.exports = lint;
stdlib-js/stdlib
lib/node_modules/@stdlib/_tools/lint/filenames/lib/sync.js
JavaScript
apache-2.0
1,960
"use strict"; // check number && integer && strictly positive module.exports.isNatural = function (d) { return (typeof d === "number") && (d % 1 === 0) && (d > 0); }; module.exports.isPositive = function (d) { return (typeof d === "number") && (d > 0); };
amida-tech/orange-api
lib/models/helpers/numbers.js
JavaScript
apache-2.0
265
ace.define("ace/keyboard/vscode",[], function(require, exports, module) { "use strict"; var HashHandler = require("../keyboard/hash_handler").HashHandler; var config = require("../config"); exports.handler = new HashHandler(); exports.handler.$id = "ace/keyboard/vscode"; exports.handler.addCommands([{ name: "toggleWordWrap", exec: function(editor) { var wrapUsed = editor.session.getUseWrapMode(); editor.session.setUseWrapMode(!wrapUsed); }, readOnly: true }, { name: "navigateToLastEditLocation", exec: function(editor) { var lastDelta = editor.session.getUndoManager().$lastDelta; var range = (lastDelta.action == "remove")? lastDelta.start: lastDelta.end; editor.moveCursorTo(range.row, range.column); editor.clearSelection(); } }, { name: "replaceAll", exec: function (editor) { if (!editor.searchBox) { config.loadModule("ace/ext/searchbox", function(e) { e.Search(editor, true); }); } else { if (editor.searchBox.active === true && editor.searchBox.replaceOption.checked === true) { editor.searchBox.replaceAll(); } } } }, { name: "replaceOne", exec: function (editor) { if (!editor.searchBox) { config.loadModule("ace/ext/searchbox", function(e) { e.Search(editor, true); }); } else { if (editor.searchBox.active === true && editor.searchBox.replaceOption.checked === true) { editor.searchBox.replace(); } } } }, { name: "selectAllMatches", exec: function (editor) { if (!editor.searchBox) { config.loadModule("ace/ext/searchbox", function(e) { e.Search(editor, false); }); } else { if (editor.searchBox.active === true) { editor.searchBox.findAll(); } } } }, { name: "toggleFindCaseSensitive", exec: function (editor) { config.loadModule("ace/ext/searchbox", function(e) { e.Search(editor, false); var sb = editor.searchBox; sb.caseSensitiveOption.checked = !sb.caseSensitiveOption.checked; sb.$syncOptions(); }); } }, { name: "toggleFindInSelection", exec: function (editor) { config.loadModule("ace/ext/searchbox", function(e) { e.Search(editor, false); var sb = editor.searchBox; sb.searchOption.checked = !sb.searchRange; sb.setSearchRange(sb.searchOption.checked && sb.editor.getSelectionRange()); sb.$syncOptions(); }); } }, { name: "toggleFindRegex", exec: function (editor) { config.loadModule("ace/ext/searchbox", function(e) { e.Search(editor, false); var sb = editor.searchBox; sb.regExpOption.checked = !sb.regExpOption.checked; sb.$syncOptions(); }); } }, { name: "toggleFindWholeWord", exec: function (editor) { config.loadModule("ace/ext/searchbox", function(e) { e.Search(editor, false); var sb = editor.searchBox; sb.wholeWordOption.checked = !sb.wholeWordOption.checked; sb.$syncOptions(); }); } }, { name: "removeSecondaryCursors", exec: function (editor) { var ranges = editor.selection.ranges; if (ranges && ranges.length > 1) editor.selection.toSingleRange(ranges[ranges.length - 1]); else editor.selection.clearSelection(); } }]); [{ bindKey: {mac: "Ctrl-G", win: "Ctrl-G"}, name: "gotoline" }, { bindKey: {mac: "Command-Shift-L|Command-F2", win: "Ctrl-Shift-L|Ctrl-F2"}, name: "findAll" }, { bindKey: {mac: "Shift-F8|Shift-Option-F8", win: "Shift-F8|Shift-Alt-F8"}, name: "goToPreviousError" }, { bindKey: {mac: "F8|Option-F8", win: "F8|Alt-F8"}, name: "goToNextError" }, { bindKey: {mac: "Command-Shift-P|F1", win: "Ctrl-Shift-P|F1"}, name: "openCommandPallete" }, { bindKey: {mac: "Command-K|Command-S", win: "Ctrl-K|Ctrl-S"}, name: "showKeyboardShortcuts" }, { bindKey: {mac: "Shift-Option-Up", win: "Alt-Shift-Up"}, name: "copylinesup" }, { bindKey: {mac: "Shift-Option-Down", win: "Alt-Shift-Down"}, name: "copylinesdown" }, { bindKey: {mac: "Command-Shift-K", win: "Ctrl-Shift-K"}, name: "removeline" }, { bindKey: {mac: "Command-Enter", win: "Ctrl-Enter"}, name: "addLineAfter" }, { bindKey: {mac: "Command-Shift-Enter", win: "Ctrl-Shift-Enter"}, name: "addLineBefore" }, { bindKey: {mac: "Command-Shift-\\", win: "Ctrl-Shift-\\"}, name: "jumptomatching" }, { bindKey: {mac: "Command-]", win: "Ctrl-]"}, name: "blockindent" }, { bindKey: {mac: "Command-[", win: "Ctrl-["}, name: "blockoutdent" }, { bindKey: {mac: "Ctrl-PageDown", win: "Alt-PageDown"}, name: "pagedown" }, { bindKey: {mac: "Ctrl-PageUp", win: "Alt-PageUp"}, name: "pageup" }, { bindKey: {mac: "Shift-Option-A", win: "Shift-Alt-A"}, name: "toggleBlockComment" }, { bindKey: {mac: "Option-Z", win: "Alt-Z"}, name: "toggleWordWrap" }, { bindKey: {mac: "Command-G", win: "F3|Ctrl-K Ctrl-D"}, name: "findnext" }, { bindKey: {mac: "Command-Shift-G", win: "Shift-F3"}, name: "findprevious" }, { bindKey: {mac: "Option-Enter", win: "Alt-Enter"}, name: "selectAllMatches" }, { bindKey: {mac: "Command-D", win: "Ctrl-D"}, name: "selectMoreAfter" }, { bindKey: {mac: "Command-K Command-D", win: "Ctrl-K Ctrl-D"}, name: "selectOrFindNext" }, { bindKey: {mac: "Shift-Option-I", win: "Shift-Alt-I"}, name: "splitSelectionIntoLines" }, { bindKey: {mac: "Command-K M", win: "Ctrl-K M"}, name: "modeSelect" }, { bindKey: {mac: "Command-Option-[", win: "Ctrl-Shift-["}, name: "toggleFoldWidget" }, { bindKey: {mac: "Command-Option-]", win: "Ctrl-Shift-]"}, name: "toggleFoldWidget" }, { bindKey: {mac: "Command-K Command-0", win: "Ctrl-K Ctrl-0"}, name: "foldall" }, { bindKey: {mac: "Command-K Command-J", win: "Ctrl-K Ctrl-J"}, name: "unfoldall" }, { bindKey: { mac: "Command-K Command-1", win: "Ctrl-K Ctrl-1" }, name: "foldOther" }, { bindKey: { mac: "Command-K Command-Q", win: "Ctrl-K Ctrl-Q" }, name: "navigateToLastEditLocation" }, { bindKey: { mac: "Command-K Command-R|Command-K Command-S", win: "Ctrl-K Ctrl-R|Ctrl-K Ctrl-S" }, name: "showKeyboardShortcuts" }, { bindKey: { mac: "Command-K Command-X", win: "Ctrl-K Ctrl-X" }, name: "trimTrailingSpace" }, { bindKey: {mac: "Shift-Down|Command-Shift-Down", win: "Shift-Down|Ctrl-Shift-Down"}, name: "selectdown" }, { bindKey: {mac: "Shift-Up|Command-Shift-Up", win: "Shift-Up|Ctrl-Shift-Up"}, name: "selectup" }, { bindKey: {mac: "Command-Alt-Enter", win: "Ctrl-Alt-Enter"}, name: "replaceAll" }, { bindKey: {mac: "Command-Shift-1", win: "Ctrl-Shift-1"}, name: "replaceOne" }, { bindKey: {mac: "Option-C", win: "Alt-C"}, name: "toggleFindCaseSensitive" }, { bindKey: {mac: "Option-L", win: "Alt-L"}, name: "toggleFindInSelection" }, { bindKey: {mac: "Option-R", win: "Alt-R"}, name: "toggleFindRegex" }, { bindKey: {mac: "Option-W", win: "Alt-W"}, name: "toggleFindWholeWord" }, { bindKey: {mac: "Command-L", win: "Ctrl-L"}, name: "expandtoline" }, { bindKey: {mac: "Shift-Esc", win: "Shift-Esc"}, name: "removeSecondaryCursors" } ].forEach(function(binding) { var command = exports.handler.commands[binding.name]; if (command) command.bindKey = binding.bindKey; exports.handler.bindKey(binding.bindKey, command || binding.name); }); }); (function() { ace.require(["ace/keyboard/vscode"], function(m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
SAP/openui5
src/sap.ui.codeeditor/src/sap/ui/codeeditor/js/ace/keybinding-vscode.js
JavaScript
apache-2.0
8,190
const { Command } = require("discord.js-commando"); module.exports = class Say extends Command { constructor(client) { super(client, { name: "say", aliases: ["echo", "speak"], group: "util", memberName: "say", description: "Says what you want it to say", examples: ["say hello"], autoAliases: true, args: [{ key: "sayText", prompt: "What do you want me to say?", type: "string" }] }); } run(msg, { sayText }) { if (msg.deletable === true) { msg.delete(); } return msg.say(sayText); }; }
SJHSBot/SJHS-Bot
commands/util/say.js
JavaScript
apache-2.0
729
var getColor = function (value, p, record) { return "<span style='color:blue;'>" + value + "</span>"; } var getDayNumber = function (value, p, record) { if (value == "" || value == 0) { return "<span style='float:right;'>0</span>"; } return "<b style='float:right;color:blue;'>" + value + "</b>"; } //Lấy số ngày phép được hưởng mỗi tháng var getUsedDayPerMonth = function (value, p, record) { if (value == "" || value == 0) { return ""; } return "<b style='float:right;color:red;'>" + value + "</b>"; } //Lấy số ngày phép được hưởng mỗi năm var getUsedDayPerYear = function (value, p, record) { if (value == "" || value == 0) { return "<span style='float:right;'>0</span>"; } return "<b style='float:right;color:red;'>" + value + "</b>"; } //Lấy tổng số ngày phép được hưởng var getTotalDaysPerYear = function (value, p, record) { if (value == "" || value == 0) { return "<span style='float:right;'>0</span>"; } return "<b style='float:right;color:blue;'>" + value + "</b>"; } var enterKeyPressHandler = function (f, e) { if (e.getKey() == e.ENTER) { PagingToolbar1.pageIndex = 0; PagingToolbar1.doLoad(); Store1.reload(); } } //Xóa các điều kiện lọc var clearFilter = function () { txtMaCB.reset(); txtHoTen.reset(); cbPhongBan.reset(); cbTo.reset(); txtTongSoNgayPhep.reset(); txtSoNgayDaSuDung.reset(); txtSoNgayConLai.reset(); txtCongDonNgayPhep.reset(); txtThamNien.reset(); PagingToolbar1.pageIndex = 0; PagingToolbar1.doLoad(); Store1.reload(); } var ValidateNgayPhep = function () { if (nbfSoNgayPhep.getValue() == '') { alert("Bạn chưa nhập số ngày nghỉ phép năm nay"); nbfSoNgayPhep.focus(); return false; } if (nbfSoNgayPhepCongDonToiDaTrong1Thang.getValue() == '') { alert("Bạn chưa nhập số ngày phép được cộng dồn trong 1 tháng"); nbfSoNgayPhepCongDonToiDaTrong1Thang.focus(); return false; } if (nbfSoNgayPhepThuongThem.getValue() != '' && dfHanDungNgayPhepThuongThem.getValue() == '') { alert("Bạn chưa nhập hạn sử dụng ngày phép được thưởng thêm"); return false; } if (chkNgayNghiPhepNamTruoc.checked == true && dfHanDungNgayPhepNamTruoc.getValue() == '') { alert("Bạn chưa nhập hạn dùng ngày nghỉ phép của năm trước"); return false; } if (rdChiNhungNhanVienDuocChon.checked == false && rdApDungChoTatCaNhanVien.checked == false) { alert("Bạn chưa chọn đối tượng được tính ngày phép"); return false; } return true; } var RenderSoNgayPhepDaSuDung = function (value, p, record) { if (value == "0" || value == null) { return ""; } return value; } var ResetForm = function () { dfHanSuDungNPNamTruoc.reset(); nbfSoNgayPhep.reset(); nbfSoNgayPhepThuongThem.reset(); chkNgayNghiPhepNamTruoc.reset(); dfHanDungNgayPhepNamTruoc.reset(); dfHanDungNgayPhepThuongThem.reset(); nbfSoNgayPhepCongDonToiDaTrong1Thang.reset(); rdApDungChoTatCaNhanVien.enable(); rdChiNhungNhanVienDuocChon.setValue(false); rdApDungChoTatCaNhanVien.setValue(false); } var RenderThamNien = function (value, p, record) { var totalDay = value * 1; if (totalDay == 0) { return ""; } var month = Math.floor(totalDay / 30); var remainDay = totalDay % 30; var year = 0; var remainMonth = 0; var rs = ""; if (month >= 12) { year = Math.floor(month / 12); remainMonth = month % 12; } if (year > 0) { rs = year + " năm "; if (remainMonth > 0) { rs += remainMonth + " tháng"; } } else { rs = month + " tháng "; if (remainDay > 0) { rs += remainDay + " ngày"; } } return rs; }
blackapple2017/qAustfeed
Austfeed/Modules/ChamCongDoanhNghiep/Resource/JsQuanLyNgayPhep.js
JavaScript
apache-2.0
4,131
Package('{Name}.Services', { Bootstrap : new Class({ implements: ['exportService', 'importService', 'getUserId'], initialize : function() { this.serviceName = 'bootstrap'; this.exportServices = [this.serviceName]; this.importServices = [] SYMPHONY.services.make(this.serviceName, this, this.implements, true); SAPPHIRE.application.listen('start', this.onStart.bind(this)); SAPPHIRE.application.listen('ready', this.onReady.bind(this)); }, exportService : function(name) { this.exportServices.push(name); }, importService : function(name) { this.importServices.push(name); }, getUserId : function() { return this.userId; }, onStart : function(done) { SYMPHONY.remote.hello() .then(function(data) { done(); }.bind(this)) }, onReady : function() { return SYMPHONY.application.register({NAME}.appId, this.importServices.unique(), this.exportServices.unique()) .then(function(response) { this.userId = response.userReferenceId; {NAME}.events.fire('start'); }.bind(this)) .done(); }, }) }); new {Name}.Services.Bootstrap();
Ondoher/symphony-app
bin/controller/templates/start-service.js
JavaScript
apache-2.0
1,140
/*! * ${copyright} */ sap.ui.define([ "jquery.sap.global", "./_AnnotationHelperBasics" ], function (jQuery, _AnnotationHelperBasics) { "use strict"; /*global Promise */ var oBoolFalse = { "Bool" : "false" }, oBoolTrue = { "Bool" : "true" }, // maps V2 sap:semantics value for a date part to corresponding V4 term relative to // com.sap.vocabularies.Common.v1. mDatePartSemantics2CommonTerm = { "fiscalyear" : "IsFiscalYear", "fiscalyearperiod" : "IsFiscalYearPeriod", "year" : "IsCalendarYear", "yearmonth" : "IsCalendarYearMonth", "yearmonthday" : "IsCalendarDate", "yearquarter" : "IsCalendarYearQuarter", "yearweek" : "IsCalendarYearWeek" }, // maps V2 filter-restriction value to corresponding V4 FilterExpressionType enum value mFilterRestrictions = { "interval" : "SingleInterval", "multi-value" : "MultiValue", "single-value" : "SingleValue" }, sLoggingModule = "sap.ui.model.odata.ODataMetaModel", // maps V2 sap semantics annotations to a V4 annotations relative to // com.sap.vocabularies.Communication.v1. mSemanticsToV4AnnotationPath = { // contact annotations "bday" : "Contact", "city" : "Contact/adr", "country" : "Contact/adr", "email" : "Contact/email", "familyname" : "Contact/n", "givenname" : "Contact/n", "honorific" : "Contact/n", "middlename" : "Contact/n", "name" : "Contact", "nickname" : "Contact", "note" : "Contact", "org" : "Contact", "org-role" : "Contact", "org-unit" : "Contact", "photo" : "Contact", "pobox" : "Contact/adr", "region" : "Contact/adr", "street" : "Contact/adr", "suffix" : "Contact/n", "tel" : "Contact/tel", "title" : "Contact", "zip" : "Contact/adr", // event annotations "class" : "Event", "dtend" : "Event", "dtstart" : "Event", "duration" : "Event", "fbtype" : "Event", "location" : "Event", "status" : "Event", "transp" : "Event", "wholeday" : "Event", // message annotations "body" : "Message", "from" : "Message", "received" : "Message", "sender" : "Message", "subject" : "Message", // task annotations "completed" : "Task", "due" : "Task", "percent-complete" : "Task", "priority" : "Task" }, rSemanticsWithTypes = /(\w+)(?:;type=([\w,]+))?/, mV2SemanticsToV4TypeInfo = { "email" : { typeMapping : { "home" : "home", "pref" : "preferred", "work" : "work" }, v4EnumType : "com.sap.vocabularies.Communication.v1.ContactInformationType", v4PropertyAnnotation : "com.sap.vocabularies.Communication.v1.IsEmailAddress" }, "tel" : { typeMapping : { "cell" : "cell", "fax" : "fax", "home" : "home", "pref" : "preferred", "video" : "video", "voice" : "voice", "work" : "work" }, v4EnumType : "com.sap.vocabularies.Communication.v1.PhoneType", v4PropertyAnnotation : "com.sap.vocabularies.Communication.v1.IsPhoneNumber" } }, // map from V2 to V4 for NON-DEFAULT cases only mV2ToV4 = { creatable : { "Org.OData.Capabilities.V1.InsertRestrictions" : { "Insertable" : oBoolFalse } }, // deletable : { // "Org.OData.Capabilities.V1.DeleteRestrictions" : { "Deletable" : oBoolFalse } // }, // see handleXableAndXablePath() pageable : { "Org.OData.Capabilities.V1.SkipSupported" : oBoolFalse, "Org.OData.Capabilities.V1.TopSupported" : oBoolFalse }, "requires-filter" : { "Org.OData.Capabilities.V1.FilterRestrictions" : { "RequiresFilter" : oBoolTrue } }, topable : { "Org.OData.Capabilities.V1.TopSupported" : oBoolFalse } // updatable : { // "Org.OData.Capabilities.V1.UpdateRestrictions" : { "Updatable" : oBoolFalse } // } // see handleXableAndXablePath() }, // only if V4 name is different from V2 name mV2ToV4Attribute = { "city" : "locality", "email" : "address", "familyname" : "surname", "givenname" : "given", "honorific" : "prefix", "middlename" : "additional", "name" : "fn", "org-role" : "role", "org-unit" : "orgunit", "percent-complete" : "percentcomplete", "tel" : "uri", "zip" : "code" }, // map from V2 annotation to an array of an annotation term and a name in that annotation // that holds a collection of property references mV2ToV4PropertyCollection = { "sap:filterable" : [ "Org.OData.Capabilities.V1.FilterRestrictions", "NonFilterableProperties" ], "sap:required-in-filter" : [ "Org.OData.Capabilities.V1.FilterRestrictions", "RequiredProperties" ], "sap:sortable" : [ "Org.OData.Capabilities.V1.SortRestrictions", "NonSortableProperties" ] }, rValueList = /^com\.sap\.vocabularies\.Common\.v1\.ValueList(#.*)?$/, iWARNING = jQuery.sap.log.Level.WARNING, Utils; /** * This object contains helper functions for ODataMetaModel. * * @since 1.29.0 */ Utils = { /** * Adds EntitySet V4 annotation for current extension if extension value is equal to * the given non-default value. Depending on bDeepCopy the annotation will be merged * with deep copy. * @param {object} o * any object * @param {object} oExtension * the SAP Annotation (OData Version 2.0) for which a V4 annotation needs to be added * @param {string} sTypeClass * the type class of the given object; supported type classes are "Property" and * "EntitySet" * @param {string} sNonDefaultValue * if current extension value is equal to this sNonDefaultValue the annotation is * added * @param {boolean} bDeepCopy * if true the annotation is mixed in as deep copy of the entry in mV2ToV4 map */ addEntitySetAnnotation : function (o, oExtension, sTypeClass, sNonDefaultValue, bDeepCopy) { if (sTypeClass === "EntitySet" && oExtension.value === sNonDefaultValue) { // potentially nested structure so do deep copy if (bDeepCopy) { jQuery.extend(true, o, mV2ToV4[oExtension.name]); } else { // Warning: Passing false for the first argument is not supported! jQuery.extend(o, mV2ToV4[oExtension.name]); } } }, /** * Adds corresponding V4 annotation for V2 <code>sap:filter-restriction</code> to the given * entity set. * * @param {object} oProperty * the property of the entity * @param {object} oEntitySet * the entity set to which the corresponding V4 annotations need to be added */ addFilterRestriction : function (oProperty, oEntitySet) { var aFilterRestrictions, sFilterRestrictionValue = mFilterRestrictions[oProperty["sap:filter-restriction"]]; if (!sFilterRestrictionValue) { if (jQuery.sap.log.isLoggable(iWARNING, sLoggingModule)) { jQuery.sap.log.warning("Unsupported sap:filter-restriction: " + oProperty["sap:filter-restriction"], oEntitySet.entityType + "." + oProperty.name, sLoggingModule); } return; } aFilterRestrictions = oEntitySet["com.sap.vocabularies.Common.v1.FilterExpressionRestrictions"] || []; aFilterRestrictions.push({ "Property" : { "PropertyPath" : oProperty.name}, "AllowedExpressions" : { "EnumMember" : "com.sap.vocabularies.Common.v1.FilterExpressionType/" + sFilterRestrictionValue } }); oEntitySet["com.sap.vocabularies.Common.v1.FilterExpressionRestrictions"] = aFilterRestrictions; }, /** * Adds a V4 navigation restriction annotation with a filter restriction to the given entity * set for the given navigation property with the V2 annotation * <code>sap:filterable="false"</code>. * * @param {object} oNavigationProperty * the navigation property of the entity with the V2 annotation * <code>sap:filterable="false"</code> * @param {object} oEntitySet * the entity set to which the corresponding V4 annotation needs to be added */ addNavigationFilterRestriction : function (oNavigationProperty, oEntitySet) { var oNavigationRestrictions = oEntitySet["Org.OData.Capabilities.V1.NavigationRestrictions"] || {}; oNavigationRestrictions.RestrictedProperties = oNavigationRestrictions.RestrictedProperties || []; oNavigationRestrictions.RestrictedProperties.push({ "FilterRestrictions" : { "Filterable": oBoolFalse }, "NavigationProperty" : { "NavigationPropertyPath" : oNavigationProperty.name } }); oEntitySet["Org.OData.Capabilities.V1.NavigationRestrictions"] = oNavigationRestrictions; }, /** * Adds current property to the property collection for given V2 annotation. * * @param {string} sV2AnnotationName * V2 annotation name (key in map mV2ToV4PropertyCollection) * @param {object} oEntitySet * the entity set * @param {object} oProperty * the property of the entity */ addPropertyToAnnotation : function (sV2AnnotationName, oEntitySet, oProperty) { var aNames = mV2ToV4PropertyCollection[sV2AnnotationName], sTerm = aNames[0], sCollection = aNames[1], oAnnotation = oEntitySet[sTerm] || {}, aCollection = oAnnotation[sCollection] || []; aCollection.push({ "PropertyPath" : oProperty.name }); oAnnotation[sCollection] = aCollection; oEntitySet[sTerm] = oAnnotation; }, /** * Collects sap:semantics annotations of the given type's properties at the type. * * @param {object} oType * the entity type or the complex type for which sap:semantics needs to be added */ addSapSemantics : function (oType) { if (oType.property) { oType.property.forEach(function (oProperty) { var aAnnotationParts, bIsCollection, aMatches, sSubStructure, vTmp, sV2Semantics = oProperty["sap:semantics"], sV4Annotation, sV4AnnotationPath, oV4Annotation, oV4TypeInfo, sV4TypeList; if (!sV2Semantics) { return; } if (sV2Semantics === "url") { oProperty["Org.OData.Core.V1.IsURL"] = oBoolTrue; return; } if (sV2Semantics in mDatePartSemantics2CommonTerm) { sV4Annotation = "com.sap.vocabularies.Common.v1." + mDatePartSemantics2CommonTerm[sV2Semantics]; oProperty[sV4Annotation] = oBoolTrue; return; } aMatches = rSemanticsWithTypes.exec(sV2Semantics); if (!aMatches) { if (jQuery.sap.log.isLoggable(iWARNING, sLoggingModule)) { jQuery.sap.log.warning("Unsupported sap:semantics: " + sV2Semantics, oType.name + "." + oProperty.name, sLoggingModule); } return; } if (aMatches[2]) { sV2Semantics = aMatches[1]; sV4TypeList = Utils.getV4TypesForV2Semantics(sV2Semantics, aMatches[2], oProperty, oType); } oV4TypeInfo = mV2SemanticsToV4TypeInfo[sV2Semantics]; bIsCollection = sV2Semantics === "tel" || sV2Semantics === "email"; sV4AnnotationPath = mSemanticsToV4AnnotationPath[sV2Semantics]; if (sV4AnnotationPath) { aAnnotationParts = sV4AnnotationPath.split("/"); sV4Annotation = "com.sap.vocabularies.Communication.v1." + aAnnotationParts[0]; oType[sV4Annotation] = oType[sV4Annotation] || {}; oV4Annotation = oType[sV4Annotation]; sSubStructure = aAnnotationParts[1]; if (sSubStructure) { oV4Annotation[sSubStructure] = oV4Annotation[sSubStructure] || (bIsCollection ? [] : {}); if (bIsCollection) { vTmp = {}; oV4Annotation[sSubStructure].push(vTmp); oV4Annotation = vTmp; } else { oV4Annotation = oV4Annotation[sSubStructure]; } } oV4Annotation[mV2ToV4Attribute[sV2Semantics] || sV2Semantics] = { "Path" : oProperty.name }; if (sV4TypeList) { // set also type attribute oV4Annotation.type = { "EnumMember" : sV4TypeList }; } } // Additional annotation at the property with sap:semantics "tel" or "email"; // ensure not to overwrite existing V4 annotations if (oV4TypeInfo) { oProperty[oV4TypeInfo.v4PropertyAnnotation] = oProperty[oV4TypeInfo.v4PropertyAnnotation] || oBoolTrue; } }); } }, /** * Adds unit annotations to properties that have a <code>sap:unit</code> OData V2 * annotation. * * Iterates over the given schemas and searches in their complex and entity types for * properties with a <code>sap:unit</code> OData V2 annotation. Creates a corresponding * OData V4 annotation <code>Org.OData.Measures.V1.Unit</code> or * <code>Org.OData.Measures.V1.ISOCurrency</code> based on the * <code>sap:semantics</code> V2 annotation of the referenced unit property, unless such an * annotation already exists. * * @param {object[]} aSchemas * the array of schemas * @param {sap.ui.model.odata.ODataMetaModel} oMetaModel * the OData meta model */ addUnitAnnotations : function (aSchemas, oMetaModel) { /** * Process all types in the given array. * @param {object[]} [aTypes] A list of complex types or entity types. */ function processTypes(aTypes) { (aTypes || []).forEach(function (oType) { (oType.property || []).forEach(function (oProperty) { var sAnnotationName, sSemantics, oTarget, oUnitPath, sUnitPath = oProperty["sap:unit"], oUnitProperty; if (sUnitPath) { oUnitPath = {"Path" : sUnitPath}; oTarget = _AnnotationHelperBasics.followPath({ getModel : function () { return oMetaModel; }, getPath : function () { return oType.$path; } }, oUnitPath); if (oTarget && oTarget.resolvedPath) { oUnitProperty = oMetaModel.getProperty(oTarget.resolvedPath); sSemantics = oUnitProperty["sap:semantics"]; if (sSemantics === "unit-of-measure") { sAnnotationName = "Org.OData.Measures.V1.Unit"; } else if (sSemantics === "currency-code") { sAnnotationName = "Org.OData.Measures.V1.ISOCurrency"; } else if (jQuery.sap.log.isLoggable(iWARNING, sLoggingModule)) { jQuery.sap.log.warning("Unsupported sap:semantics='" + sSemantics + "' at sap:unit='" + sUnitPath + "'; " + "expected 'currency-code' or 'unit-of-measure'", oType.namespace + "." + oType.name + "/" + oProperty.name, sLoggingModule); } // Do not overwrite an existing annotation if (sAnnotationName && !(sAnnotationName in oProperty)) { oProperty[sAnnotationName] = oUnitPath; } } else if (jQuery.sap.log.isLoggable(iWARNING, sLoggingModule)) { jQuery.sap.log.warning("Path '" + sUnitPath + "' for sap:unit cannot be resolved", oType.namespace + "." + oType.name + "/" + oProperty.name, sLoggingModule); } } }); }); } aSchemas.forEach(function (oSchema) { processTypes(oSchema.complexType); processTypes(oSchema.entityType); }); }, /** * Adds the corresponding V4 annotation to the given object based on the given SAP * extension. * * @param {object} o * any object * @param {object} oExtension * the SAP Annotation (OData Version 2.0) for which a V4 annotation needs to be added * @param {string} sTypeClass * the type class of the given object; supported type classes are "Property" and * "EntitySet" */ addV4Annotation : function (o, oExtension, sTypeClass) { switch (oExtension.name) { case "aggregation-role": if (oExtension.value === "dimension") { o["com.sap.vocabularies.Analytics.v1.Dimension"] = oBoolTrue; } else if (oExtension.value === "measure") { o["com.sap.vocabularies.Analytics.v1.Measure"] = oBoolTrue; } break; case "display-format": if (oExtension.value === "NonNegative") { o["com.sap.vocabularies.Common.v1.IsDigitSequence"] = oBoolTrue; } else if (oExtension.value === "UpperCase") { o["com.sap.vocabularies.Common.v1.IsUpperCase"] = oBoolTrue; } break; case "pageable": case "topable": Utils.addEntitySetAnnotation(o, oExtension, sTypeClass, "false", false); break; case "creatable": Utils.addEntitySetAnnotation(o, oExtension, sTypeClass, "false", true); break; case "deletable": case "deletable-path": Utils.handleXableAndXablePath(o, oExtension, sTypeClass, "Org.OData.Capabilities.V1.DeleteRestrictions", "Deletable"); break; case "updatable": case "updatable-path": Utils.handleXableAndXablePath(o, oExtension, sTypeClass, "Org.OData.Capabilities.V1.UpdateRestrictions", "Updatable"); break; case "requires-filter": Utils.addEntitySetAnnotation(o, oExtension, sTypeClass, "true", true); break; case "field-control": o["com.sap.vocabularies.Common.v1.FieldControl"] = { "Path" : oExtension.value }; break; case "heading": o["com.sap.vocabularies.Common.v1.Heading"] = { "String" : oExtension.value }; break; case "label": o["com.sap.vocabularies.Common.v1.Label"] = { "String" : oExtension.value }; break; case "precision": o["Org.OData.Measures.V1.Scale"] = { "Path" : oExtension.value }; break; case "quickinfo": o["com.sap.vocabularies.Common.v1.QuickInfo"] = { "String" : oExtension.value }; break; case "text": o["com.sap.vocabularies.Common.v1.Text"] = { "Path" : oExtension.value }; break; case "visible": if (oExtension.value === "false") { o["com.sap.vocabularies.Common.v1.FieldControl"] = { "EnumMember" : "com.sap.vocabularies.Common.v1.FieldControlType/Hidden" }; o["com.sap.vocabularies.UI.v1.Hidden"] = oBoolTrue; } break; default: // no transformation for V2 annotation supported or necessary } }, /** * Iterate over all properties of the associated entity type for given entity * set and check whether the property needs to be added to an annotation at the * entity set. * For example all properties with "sap:sortable=false" are collected in * annotation Org.OData.Capabilities.V1.SortRestrictions/NonSortableProperties. * * @param {object} oEntitySet * the entity set * @param {object} oEntityType * the corresponding entity type */ calculateEntitySetAnnotations : function (oEntitySet, oEntityType) { if (oEntityType.property) { oEntityType.property.forEach(function (oProperty) { if (oProperty["sap:filterable"] === "false") { Utils.addPropertyToAnnotation("sap:filterable", oEntitySet, oProperty); } if (oProperty["sap:required-in-filter"] === "true") { Utils.addPropertyToAnnotation("sap:required-in-filter", oEntitySet, oProperty); } if (oProperty["sap:sortable"] === "false") { Utils.addPropertyToAnnotation("sap:sortable", oEntitySet, oProperty); } if (oProperty["sap:filter-restriction"]) { Utils.addFilterRestriction(oProperty, oEntitySet); } }); } if (oEntityType.navigationProperty) { oEntityType.navigationProperty.forEach(function (oNavigationProperty) { if (oNavigationProperty["sap:filterable"] === "false") { Utils.addNavigationFilterRestriction(oNavigationProperty, oEntitySet); // keep deprecated conversion for compatibility reasons Utils.addPropertyToAnnotation("sap:filterable", oEntitySet, oNavigationProperty); } Utils.handleCreatableNavigationProperty(oEntitySet, oNavigationProperty); }); } }, /** * Returns the index of the object inside the given array, where the property with the * given name has the given expected value. * * @param {object[]} aArray * some array * @param {any} vExpectedPropertyValue * expected value of the property with given name * @param {string} [sPropertyName="name"] * some property name * @returns {number} * the index of the object found or <code>-1</code> if no such object is found */ findIndex : function (aArray, vExpectedPropertyValue, sPropertyName) { var iIndex = -1; sPropertyName = sPropertyName || "name"; if (aArray) { aArray.forEach(function (oObject, i) { if (oObject[sPropertyName] === vExpectedPropertyValue) { iIndex = i; return false; // break } }); } return iIndex; }, /** * Returns the object inside the given array, where the property with the given name has * the given expected value. * * @param {object[]} aArray * some array * @param {any} vExpectedPropertyValue * expected value of the property with given name * @param {string} [sPropertyName="name"] * some property name * @returns {object} * the object found or <code>null</code> if no such object is found */ findObject : function (aArray, vExpectedPropertyValue, sPropertyName) { var iIndex = Utils.findIndex(aArray, vExpectedPropertyValue, sPropertyName); return iIndex < 0 ? null : aArray[iIndex]; }, /** * Gets the map from child name to annotations for a parent with the given qualified * name which lives inside the entity container as indicated. * * @param {sap.ui.model.odata.ODataAnnotations} oAnnotations * the OData annotations * @param {string} sQualifiedName * the parent's qualified name * @param {boolean} bInContainer * whether the parent lives inside the entity container (or beside it) * @returns {object} * the map from child name to annotations */ getChildAnnotations : function (oAnnotations, sQualifiedName, bInContainer) { var o = bInContainer ? oAnnotations.EntityContainer : oAnnotations.propertyAnnotations; return o && o[sQualifiedName] || {}; }, /** * Returns the thing with the given simple name from the given entity container. * * @param {object} oEntityContainer * the entity container * @param {string} sArrayName * name of array within entity container which will be searched * @param {string} sName * a simple name, e.g. "Foo" * @param {boolean} [bAsPath=false] * determines whether the thing itself is returned or just its path * @returns {object|string} * (the path to) the thing with the given qualified name; <code>undefined</code> (for a * path) or <code>null</code> (for an object) if no such thing is found */ getFromContainer : function (oEntityContainer, sArrayName, sName, bAsPath) { var k, vResult = bAsPath ? undefined : null; if (oEntityContainer) { k = Utils.findIndex(oEntityContainer[sArrayName], sName); if (k >= 0) { vResult = bAsPath ? oEntityContainer.$path + "/" + sArrayName + "/" + k : oEntityContainer[sArrayName][k]; } } return vResult; }, /** * Returns the thing with the given qualified name from the given model's array (within a * schema) of given name. * * @param {sap.ui.model.Model|object[]} vModel * either a model or an array of schemas * @param {string} sArrayName * name of array within schema which will be searched * @param {string} sQualifiedName * a qualified name, e.g. "ACME.Foo" * @param {boolean} [bAsPath=false] * determines whether the thing itself is returned or just its path * @returns {object|string} * (the path to) the thing with the given qualified name; <code>undefined</code> (for a * path) or <code>null</code> (for an object) if no such thing is found */ getObject : function (vModel, sArrayName, sQualifiedName, bAsPath) { var aArray, vResult = bAsPath ? undefined : null, oSchema, iSeparatorPos, sNamespace, sName; sQualifiedName = sQualifiedName || ""; iSeparatorPos = sQualifiedName.lastIndexOf("."); sNamespace = sQualifiedName.slice(0, iSeparatorPos); sName = sQualifiedName.slice(iSeparatorPos + 1); oSchema = Utils.getSchema(vModel, sNamespace); if (oSchema) { aArray = oSchema[sArrayName]; if (aArray) { aArray.forEach(function (oThing) { if (oThing.name === sName) { vResult = bAsPath ? oThing.$path : oThing; return false; // break } }); } } return vResult; }, /** * Returns the schema with the given namespace. * * @param {sap.ui.model.Model|object[]} vModel * either a model or an array of schemas * @param {string} sNamespace * a namespace, e.g. "ACME" * @returns {object} * the schema with the given namespace; <code>null</code> if no such schema is found */ getSchema : function (vModel, sNamespace) { var oSchema = null, aSchemas = Array.isArray(vModel) ? vModel : vModel.getObject("/dataServices/schema"); if (aSchemas) { aSchemas.forEach(function (o) { if (o.namespace === sNamespace) { oSchema = o; return false; // break } }); } return oSchema; }, /** * Compute a space-separated list of V4 annotation enumeration values for the given * sap:semantics "tel" and "email". * E.g. for <code>sap:semantics="tel;type=fax"</code> this function returns * "com.sap.vocabularies.Communication.v1.PhoneType/fax". * * @param {string} sSemantics * the sap:semantivs value ("tel" or "email") * @param {string} sTypesList * the comma-separated list of types for sap:semantics * @param {object} oProperty * the property * @param {object} oType * the type * @returns {string} * the corresponding space-separated list of V4 annotation enumeration values; * returns an empty string if the sap:semantics value is not supported; unsupported types * are logged and skipped; */ getV4TypesForV2Semantics : function (sSemantics, sTypesList, oProperty, oType) { var aResult = [], oV4TypeInfo = mV2SemanticsToV4TypeInfo[sSemantics]; if (oV4TypeInfo) { sTypesList.split(",").forEach(function (sType) { var sTargetType = oV4TypeInfo.typeMapping[sType]; if (sTargetType) { aResult.push(oV4TypeInfo.v4EnumType + "/" + sTargetType); } else if (jQuery.sap.log.isLoggable(iWARNING, sLoggingModule)) { jQuery.sap.log.warning("Unsupported type for sap:semantics: " + sType, oType.name + "." + oProperty.name, sLoggingModule); } }); } return aResult.join(" "); }, /** * Returns the map representing the <code>com.sap.vocabularies.Common.v1.ValueList</code> * annotations of the given property. * * @param {object} oProperty the property * @returns {object} map of ValueList annotations contained in oProperty */ getValueLists : function (oProperty) { var aMatches, sName, sQualifier, mValueLists = {}; for (sName in oProperty) { aMatches = rValueList.exec(sName); if (aMatches){ sQualifier = (aMatches[1] || "").slice(1); // remove leading # mValueLists[sQualifier] = oProperty[sName]; } } return mValueLists; }, /** * Convert sap:creatable and sap:creatable-path at navigation property to V4 annotation * 'Org.OData.Capabilities.V1.InsertRestrictions/NonInsertableNavigationProperties' at * the given entity set. * If both V2 annotations 'sap:creatable' and 'sap:creatable-path' are given the service is * broken and the navigation property is added as non-insertable navigation property. * If neither 'sap:creatable' nor 'sap:creatable-path' are given this function does * nothing. * * @param {object} oEntitySet * The entity set * @param {object} oNavigationProperty * The navigation property */ handleCreatableNavigationProperty : function (oEntitySet, oNavigationProperty) { var sCreatable = oNavigationProperty["sap:creatable"], sCreatablePath = oNavigationProperty["sap:creatable-path"], oInsertRestrictions, oNonInsertable = {"NavigationPropertyPath" : oNavigationProperty.name}, aNonInsertableNavigationProperties; if (sCreatable && sCreatablePath) { // inconsistent service if both v2 annotations are set jQuery.sap.log.warning("Inconsistent service", "Use either 'sap:creatable' or 'sap:creatable-path' at navigation property " + "'" + oEntitySet.entityType + "/" + oNavigationProperty.name + "'", sLoggingModule); sCreatable = "false"; sCreatablePath = undefined; } if (sCreatable === "false" || sCreatablePath) { oInsertRestrictions = oEntitySet["Org.OData.Capabilities.V1.InsertRestrictions"] = oEntitySet["Org.OData.Capabilities.V1.InsertRestrictions"] || {}; aNonInsertableNavigationProperties = oInsertRestrictions["NonInsertableNavigationProperties"] = oInsertRestrictions["NonInsertableNavigationProperties"] || []; if (sCreatablePath) { oNonInsertable = { "If" : [{ "Not" : { "Path" : sCreatablePath } }, oNonInsertable] }; } aNonInsertableNavigationProperties.push(oNonInsertable); } }, /** * Converts deletable/updatable and delatable-path/updatable-path into corresponding V4 * annotation. * If both deletable/updatable and delatable-path/updatable-path are defined the service is * broken and the object is marked as non-deletable/non-updatable. * * @param {object} o * any object * @param {object} oExtension * the SAP Annotation (OData Version 2.0) for which a V4 annotation needs to be added * @param {string} sTypeClass * the type class of the given object; supported type is "EntitySet" * @param {string} sTerm * the V4 annotation term to use * @param {string} sProperty * the V4 annotation property to use */ handleXableAndXablePath : function (o, oExtension, sTypeClass, sTerm, sProperty) { var sV2Annotation = sProperty.toLowerCase(), oValue; if (sTypeClass !== "EntitySet") { return; // "Property" not supported here, see liftSAPData() } if (o["sap:" + sV2Annotation] && o["sap:" + sV2Annotation + "-path"]) { // the first extension (sap:xable or sap:xable-path) is processed as usual; // only if a second extension (sap:xable-path or sap:xable) is processed, // the warning is logged and the entity set is marked as non-deletable or // non-updatable jQuery.sap.log.warning("Inconsistent service", "Use either 'sap:" + sV2Annotation + "' or 'sap:" + sV2Annotation + "-path'" + " at entity set '" + o.name + "'", sLoggingModule); oValue = oBoolFalse; } else if (sV2Annotation !== oExtension.name) { // delatable-path/updatable-path oValue = { "Path" : oExtension.value }; } else if (oExtension.value === "false") { oValue = oBoolFalse; } if (oValue) { o[sTerm] = o[sTerm] || {}; o[sTerm][sProperty] = oValue; } }, /** * Lift all extensions from the <a href="http://www.sap.com/Protocols/SAPData"> SAP * Annotations for OData Version 2.0</a> namespace up as attributes with "sap:" prefix. * * @param {object} o * any object * @param {string} sTypeClass * the type class of the given object; supported type classes are "Property" and * "EntitySet" */ liftSAPData : function (o, sTypeClass) { if (!o.extensions) { return; } o.extensions.forEach(function (oExtension) { if (oExtension.namespace === "http://www.sap.com/Protocols/SAPData") { o["sap:" + oExtension.name] = oExtension.value; Utils.addV4Annotation(o, oExtension, sTypeClass); } }); // after all SAP V2 annotations are lifted up add V4 annotations that are calculated // by multiple V2 annotations or that have a different default value switch (sTypeClass) { case "Property": if (o["sap:updatable"] === "false") { if (o["sap:creatable"] === "false") { o["Org.OData.Core.V1.Computed"] = oBoolTrue; } else { o["Org.OData.Core.V1.Immutable"] = oBoolTrue; } } break; case "EntitySet": if (o["sap:searchable"] !== "true") { o["Org.OData.Capabilities.V1.SearchRestrictions"] = { "Searchable" : oBoolFalse }; } break; default: // nothing to do } }, /** * Merges the given annotation data into the given metadata and lifts SAPData extensions. * * @param {object} oAnnotations * annotations "JSON" * @param {object} oData * metadata "JSON" * @param {sap.ui.model.odata.ODataMetaModel} oMetaModel * the metamodel */ merge : function (oAnnotations, oData, oMetaModel) { var aSchemas = oData.dataServices.schema; if (!aSchemas) { return; } aSchemas.forEach(function (oSchema, i) { var sSchemaVersion; // remove datajs artefact for inline annotations in $metadata delete oSchema.annotations; Utils.liftSAPData(oSchema); oSchema.$path = "/dataServices/schema/" + i; sSchemaVersion = oSchema["sap:schema-version"]; if (sSchemaVersion) { oSchema["Org.Odata.Core.V1.SchemaVersion"] = { String : sSchemaVersion }; } jQuery.extend(oSchema, oAnnotations[oSchema.namespace]); Utils.visitParents(oSchema, oAnnotations, "association", function (oAssociation, mChildAnnotations) { Utils.visitChildren(oAssociation.end, mChildAnnotations); }); Utils.visitParents(oSchema, oAnnotations, "complexType", function (oComplexType, mChildAnnotations) { Utils.visitChildren(oComplexType.property, mChildAnnotations, "Property"); Utils.addSapSemantics(oComplexType); }); // visit all entity types before visiting the entity sets to ensure that V2 // annotations are already lifted up and can be used for calculating entity // set annotations which are based on V2 annotations on entity properties Utils.visitParents(oSchema, oAnnotations, "entityType", Utils.visitEntityType); Utils.visitParents(oSchema, oAnnotations, "entityContainer", function (oEntityContainer, mChildAnnotations) { Utils.visitChildren(oEntityContainer.associationSet, mChildAnnotations); Utils.visitChildren(oEntityContainer.entitySet, mChildAnnotations, "EntitySet", aSchemas); Utils.visitChildren(oEntityContainer.functionImport, mChildAnnotations, "", null, Utils.visitParameters.bind(this, oAnnotations, oSchema, oEntityContainer)); }); }); Utils.addUnitAnnotations(aSchemas, oMetaModel); }, /** * Visits all children inside the given array, lifts "SAPData" extensions and * inlines OData V4 annotations for each child. * * @param {object[]} aChildren * any array of children * @param {object} mChildAnnotations * map from child name (or role) to annotations * @param {string} [sTypeClass] * the type class of the given children; supported type classes are "Property" * and "EntitySet" * @param {object[]} [aSchemas] * Array of OData data service schemas (needed only for type class "EntitySet") * @param {function} [fnCallback] * optional callback for each child * @param {number} [iStartIndex=0] * optional start index in the given array */ visitChildren : function (aChildren, mChildAnnotations, sTypeClass, aSchemas, fnCallback, iStartIndex) { if (!aChildren) { return; } if (iStartIndex) { aChildren = aChildren.slice(iStartIndex); } aChildren.forEach(function (oChild) { // lift SAP data for easy access to SAP Annotations for OData V 2.0 Utils.liftSAPData(oChild, sTypeClass); }); aChildren.forEach(function (oChild) { var oEntityType; if (sTypeClass === "EntitySet") { // calculated entity set annotations need to be added before V4 // annotations are merged oEntityType = Utils.getObject(aSchemas, "entityType", oChild.entityType); Utils.calculateEntitySetAnnotations(oChild, oEntityType); } if (fnCallback) { fnCallback(oChild); } // merge V4 annotations after child annotations are processed jQuery.extend(oChild, mChildAnnotations[oChild.name || oChild.role]); }); }, /** * Visits the given entity type and its (structural or navigation) properties. * * @param {object} oEntityType * the entity type * @param {object} mChildAnnotations * map from child name (or role) to annotations */ visitEntityType : function (oEntityType, mChildAnnotations) { Utils.visitChildren(oEntityType.property, mChildAnnotations, "Property"); Utils.visitChildren(oEntityType.navigationProperty, mChildAnnotations); Utils.addSapSemantics(oEntityType); }, /** * Visits all parameters of the given function import. * * @param {object} oAnnotations * annotations "JSON" * @param {object} oSchema * OData data service schema * @param {object} oEntityContainer * the entity container * @param {object} oFunctionImport * a function import's V2 metadata object */ visitParameters : function (oAnnotations, oSchema, oEntityContainer, oFunctionImport) { var mAnnotations; if (!oFunctionImport.parameter) { return; } mAnnotations = Utils.getChildAnnotations(oAnnotations, oSchema.namespace + "." + oEntityContainer.name, true); oFunctionImport.parameter.forEach( function (oParam) { Utils.liftSAPData(oParam); jQuery.extend(oParam, mAnnotations[oFunctionImport.name + "/" + oParam.name]); } ); }, /** * Visits all parents (or a single parent) inside the current schema's array of given name, * lifts "SAPData" extensions, inlines OData V4 annotations, and adds <code>$path</code> * for each parent. * * @param {object} oSchema * OData data service schema * @param {object} oAnnotations * annotations "JSON" * @param {string} sArrayName * name of array of parents * @param {function} fnCallback * mandatory callback for each parent, child annotations are passed in * @param {number} [iIndex] * optional index of a single parent to visit; default is to visit all */ visitParents : function (oSchema, oAnnotations, sArrayName, fnCallback, iIndex) { var aParents = oSchema[sArrayName]; function visitParent(oParent, j) { var sQualifiedName = oSchema.namespace + "." + oParent.name, mChildAnnotations = Utils.getChildAnnotations(oAnnotations, sQualifiedName, sArrayName === "entityContainer"); Utils.liftSAPData(oParent); // @see sap.ui.model.odata.ODataMetadata#_getEntityTypeByName oParent.namespace = oSchema.namespace; oParent.$path = oSchema.$path + "/" + sArrayName + "/" + j; fnCallback(oParent, mChildAnnotations); // merge V4 annotations after child annotations are processed jQuery.extend(oParent, oAnnotations[sQualifiedName]); } if (!aParents) { return; } if (iIndex !== undefined) { visitParent(aParents[iIndex], iIndex); } else { aParents.forEach(visitParent); } } }; return Utils; }, /* bExport= */ false);
nzamani/openui5
src/sap.ui.core/src/sap/ui/model/odata/_ODataMetaModelUtils.js
JavaScript
apache-2.0
38,791
/*global QUnit, sinon */ sap.ui.define([ 'sap/ui/test/Opa', 'sap/ui/test/Opa5', "sap/m/Button", "sap/m/Input", "sap/ui/test/matchers/PropertyStrictEquals", "sap/ui/test/matchers/Ancestor", "sap/ui/test/matchers/Descendant", "sap/ui/test/matchers/MatcherFactory", "sap/ui/layout/HorizontalLayout" ], function (Opa, Opa5, Button, Input, PropertyStrictEquals, Ancestor, Descendant, MatcherFactory, HorizontalLayout) { "use strict"; QUnit.test("Should not execute the test in debug mode", function (assert) { assert.ok(!window["sap-ui-debug"], "Starting the OPA tests in debug mode is not supported since it changes timeouts"); }); var iExecutionDelay = Opa.config.executionDelay; QUnit.module("matchers without fake time", { beforeEach: function () { this.oButton = new Button("testButton", {text : "foo"}); this.oButton.placeAt("qunit-fixture"); sap.ui.getCore().applyChanges(); }, afterEach: function () { this.oButton.destroy(); } }); QUnit.test("Should find a control by id without matchers", function(assert) { var done = assert.async(); var oSuccessSpy = this.spy(); // System under Test var oOpa5 = new Opa5(); // Act oOpa5.waitFor({ id : "testButton", success : oSuccessSpy, timeout : 1, //second pollingInterval : 200 //millisecond }); oOpa5.emptyQueue().done(function() { var oSuccessButton = oSuccessSpy.args[0][0]; assert.strictEqual(oSuccessButton, this.oButton, "found a control"); done(); }.bind(this)); }); QUnit.test("Should not call check if no matcher is matching on a single control", function(assert) { var oCheckSpy = this.spy(); var done = assert.async(); // System under Test var oOpa5 = new Opa5(); var oMatcher = new PropertyStrictEquals({ name : "text", value : "bar" }); // Act oOpa5.waitFor({ id : "testButton", matchers : [ oMatcher ], check : oCheckSpy, timeout : 1, //second pollingInterval : 200 //millisecond }); oOpa5.emptyQueue().fail(function () { assert.strictEqual(oCheckSpy.callCount, 0, "did not call the check"); done(); }); }); QUnit.test("Should skip a check if matchers filtered out all controls", function(assert) { var oCheckSpy = this.spy(); var done = assert.async(); var oTextMatcher = new PropertyStrictEquals({ name : "text", value : "baz" }); // System under Test var oOpa5 = new Opa5(); // Act oOpa5.waitFor({ id : ["myButton", "myButton2"], matchers : oTextMatcher, check : oCheckSpy, timeout : 1 //second }); Opa5.emptyQueue().fail(function () { assert.strictEqual(oCheckSpy.callCount, 0, "did not call the check"); done(); }); }); QUnit.module("matchers in waitfor", { beforeEach : function () { sinon.config.useFakeTimers = true; this.oLayout1 = new HorizontalLayout({id: "layout1"}); this.oButton = new Button("myButton", {text : "foo"}); this.oButton2 = new Button("myButton2", {text : "bar"}); this.oButton.placeAt(this.oLayout1); this.oLayout1.placeAt("qunit-fixture"); this.oButton2.placeAt("qunit-fixture"); sap.ui.getCore().applyChanges(); }, afterEach : function () { sinon.config.useFakeTimers = false; this.oButton.destroy(); this.oButton2.destroy(); this.oLayout1.destroy(); } }); QUnit.test("Should execute a matcher and pass its value to success if no control is searched", function (assert) { var oOpa5 = new Opa5(), fnMatcherStub = this.stub().returns("foo"), fnActionSpy = this.spy(), done = assert.async(); // give some common defaults to see if they interfere and the plugin thinks we are looking for a control Opa5.extendConfig({ viewNamespace: "foo", visible: true }); oOpa5.waitFor({ matchers: fnMatcherStub, actions: fnActionSpy }); oOpa5.emptyQueue().done(function () { // Assert sinon.assert.calledOnce(fnMatcherStub); sinon.assert.calledWith(fnActionSpy, "foo"); done(); }); this.clock.tick(1000); }); QUnit.test("Should not call check if no matcher is matching", function(assert) { var oCheckSpy = this.spy(); // System under Test var oOpa5 = new Opa5(); var oMatcher = new PropertyStrictEquals({ name : "text", value : "bar" }); var oMatchSpy = this.spy(oMatcher, "isMatching"); // Act oOpa5.waitFor({ id : "myButton", matchers : [ oMatcher ], check : oCheckSpy, timeout : 1, //second pollingInterval : 200 //millisecond }); oOpa5.emptyQueue(); this.clock.tick(iExecutionDelay); assert.strictEqual(oMatchSpy.callCount, 1, "called the matcher for the first time"); this.clock.tick(200); assert.strictEqual(oMatchSpy.callCount, 2, "called the matcher for the second time"); // Assert assert.strictEqual(oCheckSpy.callCount, 0, "did not call the check"); // Cleanup this.clock.tick(1000); }); QUnit.test("Should call check when all matchers are matching", function(assert) { var oSuccessSpy = this.spy(); // System under Test var oOpa5 = new Opa5(); var oTextMatcher = new PropertyStrictEquals({ name : "text", value : "foo" }); var oEnabledMatcher = new PropertyStrictEquals({ name : "enabled", value : false }); var oTextMatcherSpy = this.spy(oTextMatcher, "isMatching"); var oEnabledMatcherSpy = this.spy(oEnabledMatcher, "isMatching"); this.oButton.setEnabled(true); // Act oOpa5.waitFor({ id : "myButton", matchers : [ oEnabledMatcher, oTextMatcher ], success : oSuccessSpy, timeout : 1, //second pollingInterval : 200 //millisecond }); Opa5.emptyQueue(); this.clock.tick(iExecutionDelay); // Assert assert.strictEqual(oTextMatcherSpy.callCount, 0, "did not call the oTextMatcher yet"); assert.strictEqual(oEnabledMatcherSpy.callCount, 1, "called the oEnabledMatcher"); this.oButton.setEnabled(false); this.clock.tick(200); assert.strictEqual(oTextMatcherSpy.callCount, 1, "did call the oTextMatcher"); assert.strictEqual(oEnabledMatcherSpy.callCount, 2, "did call the oEnabledMatcher again"); assert.strictEqual(oSuccessSpy.callCount, 1, "did call the success"); }); QUnit.test("Should use declarative matchers", function(assert) { var oSuccessSpy = this.spy(); var oOpa5 = new Opa5(); var fnIsMatching = PropertyStrictEquals.prototype.isMatching; var mCalls = {text: 0, enabled: 0, busy: 0}; PropertyStrictEquals.prototype.isMatching = function () { mCalls[this.getName()] += 1; return fnIsMatching.apply(this, arguments); }; this.oButton.setEnabled(true); oOpa5.waitFor({ id : "myButton", propertyStrictEquals: [{ name : "enabled", value : false }, { name : "text", value : "foo" }], matchers: { propertyStrictEquals: { name: "busy", value: false } }, success : oSuccessSpy, timeout : 1, //second pollingInterval : 200 //millisecond }); Opa5.emptyQueue(); this.clock.tick(iExecutionDelay); assert.strictEqual(mCalls.enabled, 1, "called the enabled (state) matcher"); assert.strictEqual(mCalls.text, 0, "did not call the text matcher yet (declared on root)"); assert.strictEqual(mCalls.busy, 0, "did not call the busy matcher yet (declared in matchers)"); this.oButton.setEnabled(false); this.clock.tick(200); assert.strictEqual(mCalls.enabled, 2, "did call the enabled (state) matcher again"); assert.strictEqual(mCalls.text, 1, "did call the text matcher (declared on root)"); assert.strictEqual(mCalls.busy, 1, "did call the busy matcher (declared in matchers)"); assert.strictEqual(oSuccessSpy.callCount, 1, "did call the success"); PropertyStrictEquals.prototype.isMatching = fnIsMatching; }); QUnit.test("Should use declarative matchers with expansions", function (assert) { var oSuccessSpy = this.spy(); var mCalls = { propertyStrictEquals: {text: 0}, ancestor: [], descendant: [] }; var fnPropertyMatch = PropertyStrictEquals.prototype.isMatching; PropertyStrictEquals.prototype.isMatching = function () { mCalls.propertyStrictEquals[this.getName()] += 1; return fnPropertyMatch.apply(this, arguments); }; var fnAncestor = Ancestor; Ancestor = function () { var ancestor = arguments[0]; return function () { mCalls.ancestor.push({ ancestor: ancestor, child: arguments[0] }); return fnAncestor.call(this, ancestor).apply(this, arguments); }; }; var fnDescendant = Descendant; Descendant = function () { var descendant = arguments[0]; return function () { mCalls.descendant.push({ descendant: descendant, parent: arguments[0] }); return fnDescendant.call(this, descendant).apply(this, arguments); }; }; var fnGetMatchers = sinon.stub(MatcherFactory.prototype, "_getSupportedMatchers").returns({ propertyStrictEquals: PropertyStrictEquals, ancestor: Ancestor, descendant: Descendant }); var oOpa5 = new Opa5(); oOpa5.waitFor({ id : "myButton", propertyStrictEquals: { name : "text", value : "foo" }, matchers: { ancestor: { id: "layout1", descendant: { id: "myButton" } } }, success : oSuccessSpy, timeout : 1, //second pollingInterval : 200 //millisecond }); Opa5.emptyQueue(); this.clock.tick(200); assert.strictEqual(mCalls.propertyStrictEquals.text, 1, "called the text matcher"); assert.strictEqual(mCalls.descendant.length, 1, "called the descendant matcher"); assert.strictEqual(mCalls.ancestor.length, 1, "called the ancestor matcher"); assert.strictEqual(oSuccessSpy.callCount, 1, "did call the success"); // restore PropertyStrictEquals.prototype.isMatching = fnPropertyMatch; Ancestor = fnAncestor; Descendant = fnDescendant; fnGetMatchers.restore(); }); QUnit.test("Should only pass matching controls to success", function(assert) { var oSuccessSpy = this.spy(); var oTextMatcher = new PropertyStrictEquals({ name : "text", value : "bar" }); // System under Test var oOpa5 = new Opa5(); // Act oOpa5.waitFor({ id : ["myButton", "myButton2"], matchers : [ oTextMatcher ], success : oSuccessSpy, timeout : 1, //second pollingInterval : 200 //millisecond }); Opa5.emptyQueue(); // Assert this.clock.tick(200); assert.strictEqual(oSuccessSpy.callCount, 1, "did call the success"); var aControls = oSuccessSpy.args[0][0]; assert.strictEqual(aControls.length, 1, "did pass only one button"); assert.strictEqual(aControls[0].sId, "myButton2", "did pass the correct button"); }); QUnit.test("Should only pass a single matching control to success", function(assert) { var oSuccessSpy = this.spy(); var oTextMatcher = new PropertyStrictEquals({ name : "text", value : "foo" }); // System under Test var oOpa5 = new Opa5(); // Act oOpa5.waitFor({ id : "myButton", matchers : [ oTextMatcher ], success : oSuccessSpy, timeout : 1, //second pollingInterval : 200 //millisecond }); Opa5.emptyQueue(); // Assert this.clock.tick(200); assert.strictEqual(oSuccessSpy.callCount, 1, "did call the success"); var oControl = oSuccessSpy.args[0][0]; assert.strictEqual(oControl.sId, "myButton", "did pass the correct button"); }); QUnit.test("Should call a matcher which is an inline function", function(assert) { // System under Test var oOpa5 = new Opa5(); oOpa5.extendConfig({pollingInterval : 200 /*millisecond*/}); var fnMatcher = this.spy(function(oControl) { return !!oControl; }); // Act var fnCheckSpy1 = this.spy(function(){ return true; }); var fnCheckSpy2 = this.spy(function(){ return true; }); oOpa5.waitFor({ id : "myButton", matchers : fnMatcher, check : fnCheckSpy1, timeout : 1 //second }); oOpa5.waitFor({ id : "myButton", matchers : [ fnMatcher ], check : fnCheckSpy2, timeout : 1 //second }); oOpa5.emptyQueue(); this.clock.tick(iExecutionDelay); this.clock.tick(iExecutionDelay); assert.strictEqual(fnMatcher.callCount, 2, "called the matcher twice"); // Assert assert.ok(fnCheckSpy1.calledBefore(fnCheckSpy2), "Checks executed in correct order"); assert.strictEqual(fnCheckSpy1.callCount, 1, "called first check"); assert.strictEqual(fnCheckSpy2.callCount, 1, "called last check"); // Cleanup this.clock.tick(1000); }); var waitForIdWithChangingMatchers = function(vId, oCheckSpy, oSuccessSpy) { var fnReturnTextMatcher = function(oControl) { return oControl.getText(); }; var fnStringChangeMathcer = function(sText) { return sText + "test"; }; // System under Test var oOpa5 = new Opa5(); // Act oOpa5.waitFor({ id : vId, matchers : [ fnReturnTextMatcher, fnStringChangeMathcer ], check : function() { oCheckSpy.call(this, arguments); return true; }, success : oSuccessSpy, timeout : 1, //second pollingInterval : 200 //millisecond }); Opa5.emptyQueue(); }; QUnit.test("Should pass multiple truthy results of matching to the next matchers and to success as array", function(assert) { var oSuccessSpy = this.spy(); var oCheckSpy = this.spy(); waitForIdWithChangingMatchers(["myButton", "myButton2"], oCheckSpy, oSuccessSpy); // Assert this.clock.tick(200); var aText = oSuccessSpy.args[0][0]; assert.strictEqual(aText.length, 2, "Matchers did pass two values"); assert.strictEqual(aText[0], "footest", "The first value is 'footest'"); assert.strictEqual(aText[1], "bartest", "The second value is 'bartest'"); var aCheckText = oCheckSpy.args[0][0][0]; assert.strictEqual(aCheckText.length, aText.length, "Check got same amout of values"); assert.strictEqual(aCheckText[0], aText[0], "The first value is same"); assert.strictEqual(aCheckText[1], aText[1], "The second value is same"); }); QUnit.test("Should pass only truthy result of matching to the next matchers and to success as value", function(assert) { var oSuccessSpy = this.spy(); var oCheckSpy = this.spy(); waitForIdWithChangingMatchers("myButton", oCheckSpy, oSuccessSpy); // Assert this.clock.tick(200); var aText = oSuccessSpy.args[0][0]; assert.strictEqual(aText, "footest", "The matched value is 'footest'"); var aCheckText = oCheckSpy.args[0][0][0]; assert.strictEqual(aCheckText, aText, "Check got same value as success"); }); QUnit.module("state matchers", { beforeEach : function () { this.oButton = new Button("enabledButton", {text : "foo"}); this.oButton2 = new Button("disabledButton", {text : "bar", enabled: false}); this.oInput = new Input("editableInput"); this.oInput2 = new Input("noneditableInput", {editable: false}); this.oButton.placeAt("qunit-fixture"); this.oButton2.placeAt("qunit-fixture"); this.oInput.placeAt("qunit-fixture"); this.oInput2.placeAt("qunit-fixture"); sap.ui.getCore().applyChanges(); }, afterEach : function () { this.oButton.destroy(); this.oButton2.destroy(); this.oInput.destroy(); this.oInput2.destroy(); } }); QUnit.test("Should filter by enabled state when autoWait is true", function (assert) { var done = assert.async(); var oOpa5 = new Opa5(); Opa5.extendConfig({ autoWait: true }); oOpa5.waitFor({ controlType: "sap.m.Button", success: function (aButtons) { assert.strictEqual(aButtons.length, 1, "Should include only enabled controls by default (enabled: undefined)"); } }); oOpa5.waitFor({ controlType: "sap.m.Button", enabled: false, success: function (aButtons) { assert.strictEqual(aButtons.length, 2, "Should include both enabled and disabled controls when enabled: false"); } }); Opa5.emptyQueue().done(function () { Opa5.resetConfig(); done(); }); }); QUnit.test("Should filter by enabled state when autoWait is false", function (assert) { var done = assert.async(); var oOpa5 = new Opa5(); oOpa5.waitFor({ controlType: "sap.m.Button", success: function (aButtons) { assert.strictEqual(aButtons.length, 2, "Should include both enabled and disabled controls by default (enabled: undefined)"); } }); oOpa5.waitFor({ controlType: "sap.m.Button", enabled: true, success: function (aButtons) { assert.strictEqual(aButtons.length, 1, "Should include only enabled controls when enabled: true"); } }); Opa5.emptyQueue().done(done); }); QUnit.test("Should apply interactable matcher when interactable is true and autoWait is false", function (assert) { var done = assert.async(); var oOpa5 = new Opa5(); this.oButton2.setEnabled(true); this.oButton2.setBusy(true); oOpa5.waitFor({ controlType: "sap.m.Button", interactable: true, success: function (aButtons) { assert.strictEqual(aButtons.length, 1, "Should include only interactable controls when interactable: true"); } }); Opa5.emptyQueue().done(function () { Opa5.resetConfig(); done(); }); }); QUnit.test("Should filter by enabled state when interactable is true", function (assert) { var done = assert.async(); var oOpa5 = new Opa5(); oOpa5.waitFor({ controlType: "sap.m.Button", interactable: true, success: function (aButtons) { assert.strictEqual(aButtons.length, 1, "Should include only enabled controls when enabled: undefined"); } }); oOpa5.waitFor({ controlType: "sap.m.Button", interactable: true, enabled: false, success: function (aButtons) { assert.strictEqual(aButtons.length, 2, "Should include both enabled and disabled controls when enabled: false"); } }); Opa5.emptyQueue().done(function () { Opa5.resetConfig(); done(); }); }); QUnit.test("Should filter by editable state", function (assert) { var done = assert.async(); var oOpa5 = new Opa5(); Opa5.extendConfig({ autoWait: true }); oOpa5.waitFor({ controlType: "sap.m.Input", editable: true, success: function (aInputs) { assert.strictEqual(aInputs.length, 1, "Should include only editable controls by default (editable: undefined)"); } }); oOpa5.waitFor({ controlType: "sap.m.Input", editable: false, success: function (aInputs) { assert.strictEqual(aInputs.length, 2, "Should include all controls when editable: false"); } }); Opa5.emptyQueue().done(function () { Opa5.resetConfig(); done(); }); }); });
SAP/openui5
src/sap.ui.core/test/sap/ui/core/qunit/opa/opa5/matchers.qunit.js
JavaScript
apache-2.0
18,298
var net = require('net'); Stomp = require('./stomp'); wrapTCP = function(port, host) { var socket, ws; socket = null; ws = { url: 'tcp:// ' + host + ':' + port, send: function(d) { return socket.write(d); }, close: function() { return socket.end(); } }; socket = net.connect(port, host, function(e) { return ws.onopen(); }); socket.on('error', function(e) { return typeof ws.onclose === "function" ? ws.onclose(e) : void 0; }); socket.on('close', function(e) { return typeof ws.onclose === "function" ? ws.onclose(e) : void 0; }); socket.on('data', function(data) { var event; event = { 'data': data.toString() }; return ws.onmessage(event); }); return ws; };
starksm64/RaspberryPiBeaconParser
websocket/testSocketIO.js
JavaScript
apache-2.0
753
var structdpctl__params = [ [ "aux", "structdpctl__params.html#a875761aaf475439ac2f51f564f8a558d", null ], [ "is_appctl", "structdpctl__params.html#a4d1857bb1afb99d03f1586a81c415b17", null ], [ "may_create", "structdpctl__params.html#aad17dd95f7fe3ebcceb3a0745e84b372", null ], [ "output", "structdpctl__params.html#a9dce609f19744eec92e846c45eef8b5a", null ], [ "print_statistics", "structdpctl__params.html#ab7e264c4a84c35d004e4e5df863438a7", null ], [ "usage", "structdpctl__params.html#a4d369f75cf9f886b57ead7cf1aabd1cf", null ], [ "verbosity", "structdpctl__params.html#a08a8be187581be2eb16d38bf0ede8f57", null ], [ "zero_statistics", "structdpctl__params.html#ae830308818ce5edb0dcb5a6a70f48eb8", null ] ];
vladn-ma/vladn-ovs-doc
doxygen/ovs_all/html/structdpctl__params.js
JavaScript
apache-2.0
742
const path = require('path'); const fs = require('fs'); const { flattenDeep, memoize } = require('lodash'); function locateSourceFile(modulesPath, moduleName, importPath = '') { const srcPrefixes = ['src', '']; const indexFiles = ['', 'index']; const extensions = ['.ts', '.tsx', '.js', '.jsx']; const paths = srcPrefixes.map(prefix => extensions.map(extension => indexFiles.map(indexFile => { return path.join(modulesPath, moduleName, prefix, importPath, indexFile) + extension; }), ), ); return flattenDeep(paths).find(p => fs.existsSync(p)); } function _getAllSpinnakerPackages(modulesPath) { const paths = fs.readdirSync(modulesPath); return paths .map(file => path.join(modulesPath, file)) .filter(child => fs.statSync(child).isDirectory()) .map(packagePath => packagePath.split('/').pop()); } const getAllSpinnakerPackages = memoize(_getAllSpinnakerPackages); function makeResult(pkg, importPath) { const subPkg = getSubPackage(pkg, importPath); importPath = importPath || ''; const importPathWithSlash = importPath ? '/' + importPath : ''; return pkg ? { pkg, subPkg, importPath, importPathWithSlash } : undefined; } /** * Given '@spinnaker/amazon', returns { pkg: 'amazon', path: undefined }; * Given '@spinnaker/core/deep/import', returns { pkg: 'core', path: 'deep/import' }; * Given 'anythingelse', returns undefined */ function getImportFromNpm(importString) { const regexp = new RegExp(`^@spinnaker/([^/]+)(/.*)?$`); const [, pkg, importPath] = regexp.exec(importString) || []; return makeResult(pkg, importPath); } /** * If code imports from a known spinnaker package alias * Given 'amazon', returns { pkg: 'amazon', path: undefined }; * Given 'core/deep/import', returns { pkg: 'core', path: 'deep/import' }; * Given 'nonspinnakerpackage/deep/import', returns undefined */ function getAliasImport(allSpinnakerPackages, importString) { const [, pkg, importPath] = /^([^/]+)\/(.*)$/.exec(importString) || []; return allSpinnakerPackages.includes(pkg) ? makeResult(pkg, importPath) : undefined; } /** * If code imports from .. relatively, returns the potential alias * Assume all examples are from a file /app/scripts/modules/core/subdir/file.ts * Given '../../amazon/loadbalancers/loadbalancer', returns { pkg: 'amazon', path: 'loadbalancers/loadbalancer' }; * Given '../widgets/button', returns { pkg: 'core', path: 'widgets/button' }; * Given './file2', returns { pkg: 'core', path: 'subdir/file2' }; */ function getRelativeImport(sourceFileName, modulesPath, importString) { if (!importString.startsWith('../')) { return undefined; } const resolvedPath = path.resolve(sourceFileName, importString); const maybeImport = path.relative(modulesPath, resolvedPath); const [pkg, ...rest] = maybeImport.split(path.sep); return pkg ? makeResult(pkg, rest.join('/')) : undefined; } function _getSourceFileDetails(sourceFile) { const [, modulesPath, ownPackage, filePath] = /^(.*app\/scripts\/modules)\/([^/]+)\/(?:src\/)?(.*)$/.exec(sourceFile) || []; const ownSubPackage = getSubPackage(ownPackage, filePath); const sourceDirectory = path.resolve(sourceFile, '..'); return { modulesPath, sourceDirectory, ownPackage, ownSubPackage, filePath }; } function getSubPackage(packageName, filePath) { if (packageName === 'kubernetes') { // subpackage is v1/foo or v2/foo const [, subPkg] = /^((?:v[12]\/)?[^/]+)\/?.*/.exec(filePath) || []; return subPkg; } else { const [, subPkg] = /^([^/]+)\/?.*/.exec(filePath) || []; return subPkg; } } const getSourceFileDetails = memoize(_getSourceFileDetails); module.exports = { getAliasImport, getAllSpinnakerPackages, getImportFromNpm, getRelativeImport, getSourceFileDetails, locateSourceFile, };
duftler/deck
packages/eslint-plugin/utils/import-aliases.js
JavaScript
apache-2.0
3,812
"use strict"; var marvelNameGenerator = require('./index.js'); console.log("Expect to see a cool name:\n"+marvelNameGenerator());
bdargan/marvel-chars-name-gen
test.js
JavaScript
apache-2.0
131
class Queue { constructor() { this.items = []; } add(item) { this.items.push(item); } remove() { return this.items.shift(); } peek() { return this.items[this.items.length - 1]; } isEmpty() { return this.items.length === 0; } } module.exports = Queue;
telmanagababov/ctci
part3-stacks/common/queue.js
JavaScript
apache-2.0
339
"use strict"; // // Bot Player // assignmentClientPlayer.js // Created by Milad Nazeri on 2019-06-06 // Copyright 2019 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // (function() { // ************************************* // START UTILITY FUNCTIONS // ************************************* // #region UTILITY FUNCTIONS // Keep trying to see if the manager is available before registering var MANAGER_CHECK_RETRY_MS = 2000; function searchForManager() { if (manager) { Messages.sendMessage(ASSIGNMENT_MANAGER_CHANNEL, JSON.stringify({ action: "REGISTER_ME", uuid: scriptUUID })); return; } else { Messages.sendMessage(ASSIGNMENT_MANAGER_CHANNEL, JSON.stringify({ action: "ARE_YOU_THERE_MANAGER_ITS_ME_BOT" })); } Script.setTimeout(function() { searchForManager(); }, MANAGER_CHECK_RETRY_MS); } // #endregion // ************************************* // END UTILITY FUNCTIONS // ************************************* // ************************************* // START CONSTS_AND_VARS // ************************************* // #region CONSTS_AND_VARS var ASSIGNMENT_MANAGER_CHANNEL = "ASSIGNMENT_MANAGER_CHANNEL"; var scriptUUID; var player; var manager; // #endregion // ************************************* // END CONSTS_AND_VARS // ************************************* // ************************************* // START PLAYER // ************************************* // #region PLAYER // Player Class for the hfr recordings function Player() { this.isPlayingRecording = false; this.recordingFilename = ""; } // Play the bot function play(fileToPlay) { console.log("play playing " + JSON.stringify(fileToPlay)); this.recordingFilename = fileToPlay; var _this = this; Recording.loadRecording(fileToPlay, function(success, url) { if (success) { _this.isPlayingRecording = true; Users.disableIgnoreRadius(); Agent.isAvatar = true; Recording.setPlayFromCurrentLocation(false); Recording.setPlayerUseDisplayName(true); Recording.setPlayerUseHeadModel(false); Recording.setPlayerUseAttachments(true); Recording.setPlayerLoop(true); Recording.setPlayerUseSkeletonModel(true); Recording.setPlayerTime(0.0); Recording.setPlayerVolume(0.5); Recording.startPlaying(); } else { console.log("Could not load recording " + fileToPlay); _this.isPlayingRecording = false; _this.recordingFilename = ""; // This should remove the avatars however they are coming back in as white spheres at the origin // Agent.isAvatar = false; } }); } // Stop the bot and remove // #NOTE: Adding and removing the agent is currently causing issues. Using a work around for the meantime function stop() { console.log("Stop playing " + this.recordingFilename); if (Recording.isPlaying()) { Recording.stopPlaying(); // This looks like it's a platform bug that this can't be removed // Agent.isAvatar = false; } this.isPlayingRecording = false; } // Check if the bot is playing function isPlaying() { return this.isPlayingRecording; } Player.prototype = { play: play, stop: stop, isPlaying: isPlaying }; // #endregion // ************************************* // END PLAYER // ************************************* // ************************************* // START MESSAGES // ************************************* // #region MESSAGES // Handle messages fromt he manager var IGNORE_PLAYER_MESSAGES = ["REGISTER_ME", "ARE_YOU_THERE_MANAGER"]; var playInterval = null; function onMessageReceived(channel, message, sender) { if (channel !== ASSIGNMENT_MANAGER_CHANNEL || sender === scriptUUID || IGNORE_PLAYER_MESSAGES.indexOf(message.action) > -1) { return; } try { message = JSON.parse(message); } catch (e) { console.log("Can not parse message object"); console.log(e); return; } if (message.uuid !== scriptUUID) { return; } switch (message.action){ case "PLAY": if (!player.isPlaying()) { player.play(message.fileToPlay); } else { console.log("Didn't start playing " + message.fileToPlay + " because already playing "); } break; case "STOP": if (player.isPlaying()) { player.stop(); } break; case "REGISTER_MANAGER": manager = true; break; default: console.log("unrecongized action in assignmentClientPlayer.js"); break; } } // #endregion // ************************************* // END MESSAGES // ************************************* // ************************************* // START MAIN // ************************************* // #region MAIN // Main function to run when player comes online function startUp() { scriptUUID = Agent.sessionUUID; player = new Player(); Messages.messageReceived.connect(onMessageReceived); Messages.subscribe(ASSIGNMENT_MANAGER_CHANNEL); searchForManager(); Script.scriptEnding.connect(onEnding); } startUp(); // #endregion // ************************************* // END MAIN // ************************************* // ************************************* // START CLEANUP // ************************************* // #region CLEANUP function onEnding() { player.stop(); Messages.messageReceived.disconnect(onMessageReceived); Messages.unsubscribe(ASSIGNMENT_MANAGER_CHANNEL); if (playInterval) { Script.clearInterval(playInterval); playInterval = null; } } // #endregion // ************************************* // END CLEANUP // ************************************* })();
RebeccaStankus/hifi-content
usefulUtilities/botPlayer/assignmentClientPlayer.js
JavaScript
apache-2.0
6,999
import {TextFileLoader} from './painter/TextFileLoader' import {InstancedGrid} from './painter/InstancedGrid' import {QCurve} from './painter/QCurve' import {QCurveObj} from './painter/QCurve' import {StrokePath} from './painter/StrokePath' import {Particle} from './painter/Particle' import {VectorField} from './painter/VectorField' import Preloader from "./preloader/Preloader" import {MathUtils} from "./util/MathUtils" import * as THREE from 'three' import * as Stats from 'stats-js' /** * Created by David on 14/12/2016. */ //if ( !Detector.webgl ) Detector.addGetWebGLMessage(); /////////////////////// var container, stats; var controls; var camera, scene, renderer; //var orientations; //var offsets; //var lengths; //var speeds; var fragshader; var vertshader; TextFileLoader.Instance().loadFiles(["shaders/fragShader.glsl","shaders/vertShader.glsl"], filesLoaded); var textureFilenames = []; for(var i=1;i<=41;++i) { textureFilenames.push( "colourful" + "/" + ((i < 10) ?"0":"") + i + ".jpg"); } var textureIX = 0; function filesLoaded(files) { fragshader = files[0]; vertshader = files[1]; makeMeshObj(); } // emit particles from a bound, bottom of the bound is the horizon line? // if camera is cetnered, then it should be centered in x pos // if camera is not centered, var ExportMode = { "png": "png", "jpg": "jpg" }; var exportMode = ExportMode.png; //var renderScale = 5.4; var renderScale,bw,bh,bottomy; var Mode = { "skyline": "skyline", "maps": "maps" }; var mode = Mode.maps; //renderScale = 7.2; renderScale = 1.0; if(mode == Mode.skyline) { bw = 1000; bh = bw*(3/4); bottomy = bh *0.6; } else{ // "maps" // renderScale = 7.2; bh = 1000; bw = bh*(3/4); bottomy = bh * 1.0; } var w = bw * renderScale; var h = bh * renderScale; var noiseOffsetX, noiseOffsetY ; function init() { randomiseField(); container = document.getElementById( 'container' ); //var w = window.innerWidth; //var h = window.innerHeight; // w = 6000; // h = 6000; // todo uncenter the camera //camera = new THREE.OrthographicCamera( w / - 2, w / 2, h / 2, h / - 2, - 500, 500 ); camera = new THREE.OrthographicCamera( 0, w , h , 0, - 500, 500 ); // camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 10000 ); //camera.position.z = 20; //camera.position.z = 50; renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true }); scene = new THREE.Scene(); // mouse orbit control /* controls = new THREE.OrbitControls( camera, renderer.domElement ); controls.enableDamping = true; controls.dampingFactor = 0.25; controls.enableZoom = false;*/ /* controls = new THREE.TrackballControls(camera); controls.rotateSpeed = 10.0; controls.zoomSpeed = 10.2; controls.panSpeed = 0.8; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; */ if ( renderer.extensions.get( 'ANGLE_instanced_arrays' ) === false ) { document.getElementById( "notSupported" ).style.display = ""; return; } renderer.setClearColor( 0xFFFFFF ); renderer.autoClear = false; renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( w,h); var div = document.getElementById("canvasContainer"); div.appendChild(renderer.domElement ); // document.body.appendChild( renderer.domElement ); renderer.clear(); /* stats = new Stats(); stats.domElement.style.position = 'absolute'; stats.domElement.style.top = '0px'; document.body.appendChild( stats.domElement ); */ window.addEventListener( 'resize', onWindowResize, false ); renderer.domElement.addEventListener( 'mousemove', onMouseMove, true ); renderer.domElement.addEventListener( 'mousedown', onMouseDown, true ); renderer.domElement.addEventListener( 'mouseup', onMouseUp, true ); createGui(); reset(); } var ismousedown =false; var mousex = 0; var mousey = 0; document.addEventListener('keydown',onDocumentKeyDown,false); function onDocumentKeyDown(event) { console.log(event); if(event.key == 's') { //saveAsImage(); // savePixels(); saveCanvas(); } if(event.key == " ") { // next teuxtre textureIX = (textureIX + 1) % textureFilenames.length; reset(); } if(event.key == "r") { randomiseField(); // refresh noise field reset(); } } var gui; var originalPoints = []; for(var i = 0; i< 4;++i) { originalPoints.push({"x":0, "y":0}); } var points = originalPoints.slice(0); var rectModel = { xOffset: 0.5, // yOffset: 0.5, xScale: 1, yScale: 1, imageFilename: "image" }; updatePoints(); // inital points should be a normalised rect console.log(points); ////////////////////////////////////////////////////////////////////////////////////////////// // colour map sampling options var particleOptions = { directionForward: true } function createGui() { gui = new dat.GUI(); // My sample abject var obj = { flipX: function() {flipX();}, flipY: function() {flipY();}, rotate: function(){rotate();}, resetPoints: function(){resetPoints();} }; // Number field with slider gui.add(rectModel, "xOffset").min(0).max(1).step(0.01).onChange(function(val) { // console.log("changed " + val); updatePoints(); } ).listen(); gui.add(rectModel, "yOffset").min(0).max(1).step(0.01).onChange(function(val) { // console.log("changed " + val); updatePoints(); } ).listen(); gui.add(rectModel, "xScale").min(0).max(1).step(0.01).onChange(function(val) { // console.log("changed " + val); updatePoints(); } ).listen(); gui.add(rectModel, "yScale").min(0).max(1).step(0.01).onChange(function(val) { //console.log("changed " + val); updatePoints(); } ).listen(); // Checkbox field gui.add(obj, "flipX"); gui.add(obj, "flipY"); gui.add(obj, "rotate"); gui.add(obj, "resetPoints"); gui.add(rectModel, "imageFilename").listen(); gui.add(particleOptions, "directionForward").listen(); } function flipX() { console.log("flip x"); var temp = points.slice(0); points[0] = temp[1]; points[1] = temp[0]; points[2] = temp[3]; points[3] = temp[2]; console.log(points); } function flipY() { console.log("flipY"); var temp = points.slice(0); points[0] = temp[3]; points[1] = temp[2]; points[2] = temp[1]; points[3] = temp[0]; console.log(points); } function rotate() { var temp = points.slice(0); points[0] = temp[1]; points[1] = temp[2]; points[2] = temp[3]; points[3] = temp[0]; console.log(points); } function resetPoints() { rectModel.xOffset = 0.5; rectModel.yOffset = 0.5; rectModel.xScale = 1; rectModel.yScale = 1; updatePoints(); points = originalPoints.slice(0); console.log(points); } function updatePoints() { var w = rectModel.xScale; var h = rectModel.yScale; var x = (rectModel.xOffset - 0.5)*(1-w) - 0.5*w +0.5; var y = (rectModel.yOffset - 0.5)*(1-h) - 0.5*h + 0.5; originalPoints[0].x = x; originalPoints[0].y = y; originalPoints[1].x = x + w; originalPoints[1].y = y; originalPoints[2].x = x + w; originalPoints[2].y = y + h; originalPoints[3].x = x ; originalPoints[3].y = y + h; console.log(originalPoints); } function getPoint(x,y) { var p0 = points[0]; var p1 = points[1]; var p2 = points[2]; var p3 = points[3]; var x0 = p0.x + x*(p1.x - p0.x); var y0 = p0.y + x*(p1.y - p0.y); var x1 = p2.x + x*(p2.x - p3.x); var y1 = p2.y + x*(p2.y - p3.y); var tx = x0 + y*(x1- x0); var ty = y0 + y*(y1- y0); return {"y":ty,"x":tx}; } ////////////////////////////////////////////////////////////////////////////////////////////// function randomiseField() { noiseOffsetX = MathUtils.GetRandomFloat(0,100); noiseOffsetY = MathUtils.GetRandomFloat(0,100); } function reset() { console.log("reset"); imageDataLoaded = false; // clear renderer.clear(); // choose a texture and load it var loader = new THREE.TextureLoader(); loader.setPath('textures/'); var imageURL = textureFilenames[textureIX]; // var imageURL = 'grad.png'; console.log("imageURL "+ imageURL); rectModel.imageFilename = imageURL; // show filename for debugin var _this = this; var texture = loader.load(imageURL, function ( texture ) { // do something with the texture on complete // console.log("texture", texture); imagedata = getImageData(texture.image ); // console.log("imagedata", imagedata); imageDataLoaded = true; //test(); } ); } ///////////////////////////////////////////////////////////////////////////////////////////// function saveCanvas() { if(exportMode == ExportMode.png) { renderer.domElement.toBlob(function(blob) { saveAs(blob, "output" + MathUtils.GenerateUUID() + ".png"); }); } else { renderer.domElement.toBlob(function (blob) { saveAs(blob, "output" + MathUtils.GenerateUUID() + ".jpg"); }, "image/jpeg"); } } //////////////////////////////////////////////// function getImageData( image ) { var canvas = document.createElement( 'canvas' ); canvas.width = image.width; canvas.height = image.height; var context = canvas.getContext( '2d' ); context.drawImage( image, 0, 0 ); return context.getImageData( 0, 0, image.width, image.height ); } function getPixel( imagedata, nx, ny ) { var x = Math.floor( nx *(imagedata.width - 1)); var y = Math.floor( ny *(imagedata.height-1)); var position = ( x + imagedata.width * y ) * 4, data = imagedata.data; return { r: data[ position ] /255.0, g: data[ position + 1 ]/255.0, b: data[ position + 2 ]/255.0, a: data[ position + 3 ]/255.0 }; } var imagedata = null; var imageDataLoaded = false; //var preloader = new Preloader(); //load(); function load() { //preloader.load(() => { // this.scene.add(this.cube); //this.render(); // var imgTexture = THREE.ImageUtils.loadTexture( "environment/floor.jpg" ); var loader = new THREE.TextureLoader(); loader.setPath('textures/'); var imageURL = '01.jpg'; // var imageURL = 'grad.png'; var _this = this; var texture = loader.load(imageURL, function (texture) { // do something with the texture on complete console.log("texture", texture); imagedata = getImageData(texture.image); console.log("imagedata", imagedata); imageDataLoaded = true; //test(); } ); } var field = new VectorField(); var p0s; var p1s; var p2s; var q0s; var q1s; var q2s; var colours0; var colours1; var startRs; var endRs; var nInstances; var basepath; var pathobj; var ready = false; var bufferix; var grid; function makeMeshObj() { // basepath = new QCurve(); basepath.p1.x = 200; basepath.p1.y = 0; basepath.p2.x = 200; basepath.p2.y = 100; pathobj = new QCurveObj(basepath, 10); // pathobj.addToScene(scene); // geometry nInstances = 200000; // max number of instances that can be render in one go bufferix = 0; grid = new InstancedGrid(); grid.print(); var nx = 2; // keep this as 2 var nz = 5; // resolution var zLen = 25; //grid.createTube(nx,nz,1,1,zLen); //grid.createRectTube(7,5,100,40); grid.createFlatGrid(nx,nz,1,1); grid.createIndices(nx,nz); grid.createUVGrid(nx,nz); // per instance data // offsets = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 3 ), 3, 1 ).setDynamic( false ); p0s = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 3 ), 3, 1 ).setDynamic( true); p1s = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 3 ), 3, 1 ).setDynamic( true); p2s = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 3 ), 3, 1 ).setDynamic( true); q0s = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 3 ), 3, 1 ).setDynamic( true); q1s = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 3 ), 3, 1 ).setDynamic( true); q2s = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 3 ), 3, 1 ).setDynamic( true); colours0 = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 4 ), 4, 1 ).setDynamic( true); colours1 = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 4 ), 4, 1 ).setDynamic( true); // remove this // startRs = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 1 ), 1, 1 ).setDynamic( true); // endRs = new THREE.InstancedBufferAttribute( new Float32Array( nInstances * 1 ), 1, 1 ).setDynamic( true); //grid.geometry.addAttribute( 'offset', offsets ); // per mesh translation grid.geometry.addAttribute( 'p0', p0s); grid.geometry.addAttribute( 'p1', p1s); grid.geometry.addAttribute( 'p2', p2s); grid.geometry.addAttribute( 'q0', q0s); grid.geometry.addAttribute( 'q1', q1s); grid.geometry.addAttribute( 'q2', q2s); grid.geometry.addAttribute( 'colour0', colours0); grid.geometry.addAttribute( 'colour1', colours1); // grid.geometry.addAttribute( 'startR', startRs); // grid.geometry.addAttribute( 'endR', endRs); var material = new THREE.RawShaderMaterial( { uniforms: { //map: { type: "t", value: texture } }, vertexShader: vertshader, //fragmentShader: FragShader, fragmentShader: fragshader, //side: THREE.DoubleSide, transparent: true, // wireframe: true } ); var mesh = new THREE.Mesh( grid.geometry, material ); mesh.frustumCulled = false; //var zoom = 0.5; // mesh.position.y = meshPositionY; mesh.scale.set(renderScale,renderScale); scene.add( mesh ); //add a test horizon line //addTestLine(); ready = true; // drawParticle(); } function addTestLine() { var material = new THREE.LineBasicMaterial({ color: 0xff0000 }); var geometry = new THREE.Geometry(); geometry.vertices.push( new THREE.Vector3( -1000*renderScale, 0, 0 ), new THREE.Vector3( 1000*renderScale, 0, 0 ) ); var line = new THREE.Line( geometry, material ); scene.add( line ); } Math.clamp = function(number, min, max) { return Math.max(min, Math.min(number, max)); } function onMouseMove(event){ mousex = (event.clientX); mousey = (event.clientY); console.log(mousex,mousey); //mouseY = (event.clientY - window.innerHeight/2) / window.innerHeight/2; } function onMouseUp(event){ ismousedown = false; console.log("onMouseUp"); } function onMouseDown(event){ ismousedown = true; console.log("onMouseDown"); nsteps = 20 + Math.random()*160; } var nsteps = 20; function drawParticleUpdate() { if(ismousedown) { var n = 50; var nx = mousex/w + Math.random()*0.02 ; var ny = mousey/h + Math.random()*0.02 ; console.log(mousex/w, mousex/h); var direction = particleOptions.directionForward ? 1: -1;// (Math.random() < 0.5)? -1 : 1; var thickness = 0.5 + Math.random()*1.5; var alpha = 0.3 + 0.7*Math.random(); for (var i = 0; i < n; ++i) { drawParticle(nx,ny, direction, nsteps, thickness, alpha); } } //drawRandomParticles(400); } function drawRandomParticles(n) { for (var i = 0; i < n; ++i) { // particles are nomralised [0,1] -> remap to [-h,h] var nx = Math.random()*0.99 ; var ny = Math.random()*0.99 ; var direction = (Math.random() < 0.5)? -1 : 1; var thickness = 0.5 + Math.random()*1.5; var nsteps = 30 + Math.random()*100; var alpha = 0.3 + 0.7*Math.random(); drawParticle(nx,ny, direction, nsteps, thickness, alpha); } } // draw particle at nx,ny function drawParticle(nx,ny, direction, nsteps, thickness, alpha) { // todo use canvas coordinates // convert to the emission bound var canvasx = nx*bw; // stretch the width var canvasy = bh - ny*( bottomy); // do //get slight random position var randomColPositionAmount= 0.01; var colx = Math.clamp( MathUtils.GetRandomFloat(nx- randomColPositionAmount,nx + randomColPositionAmount) ,0,0.999); var coly = Math.clamp( MathUtils.GetRandomFloat(ny- randomColPositionAmount,ny + randomColPositionAmount) ,0,0.999); var transformedPoint = getPoint(colx,coly); colx = transformedPoint.x; coly = transformedPoint.y; var col = getPixel(imagedata, colx,coly); //var x =-1000+ nx*2000; //var y =-450+ ny*950; var particle; // set a random seed var seed = MathUtils.GetRandomIntBetween(0,100000); // draw the shading (alpha black) var brightness = 0.5; MathUtils.SetSeed(seed); // rset seed particle = new Particle(field); var thicknessShade = Math.min( thickness + 4, thickness *1.2); particle.init( canvasx,canvasy, thicknessShade, direction); particle.noiseOffsetX = noiseOffsetX; particle.noiseOffsetY = noiseOffsetY; particle.strokePath.colour = new THREE.Vector3(col.r*brightness,col.g*brightness,col.b*brightness); particle.strokePath.alpha = alpha*0.2; for(var i =0; i< nsteps;++i) { particle.update(thicknessShade); } bufferix = particle.strokePath.constructPath(p0s,p1s,p2s,q0s,q1s,q2s,colours0,colours1,bufferix); // draw the colour MathUtils.SetSeed(seed); // rset seed particle = new Particle(field); particle.init(canvasx,canvasy, thickness, direction); particle.noiseOffsetX = noiseOffsetX; particle.noiseOffsetY = noiseOffsetY; particle.strokePath.colour = new THREE.Vector3(col.r,col.g,col.b); particle.strokePath.alpha =alpha; for(var i =0; i< nsteps;++i) { particle.update(thickness); } bufferix = particle.strokePath.constructPath(p0s,p1s,p2s,q0s,q1s,q2s,colours0,colours1,bufferix); /* // test a couple of curves var i = 0; p0s.setXY(i, 0,0); p1s.setXY(i, 102,0); p2s.setXY(i, 202,25); q0s.setXY(i, 0,0 + 50); q1s.setXY(i, 102,0 + 50); q2s.setXY(i, 202,25); */ } function onWindowResize( event ) { /* camera.left = window.innerWidth / - 2; camera.right = window.innerWidth / 2; camera.top = window.innerHeight / 2; camera.bottom = window.innerHeight / - 2; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); */ } // function animate() { requestAnimationFrame( animate ); if(ready && imageDataLoaded) { bufferix = 0; // console.log("imageDataLoaded", imageDataLoaded); drawParticleUpdate(); grid.setDrawCount(bufferix); //console.log(bufferix); // update p0s.needsUpdate = true; p1s.needsUpdate = true; p2s.needsUpdate = true; q0s.needsUpdate = true; q1s.needsUpdate = true; q2s.needsUpdate = true; colours0.needsUpdate =true; colours1.needsUpdate =true; render(); } // stats.update(); //controls.update(); // required if controls.enableDamping = true, or if controls.autoRotate = true } var lastTime = 0; var moveQ = ( new THREE.Quaternion( .5, .5, .5, 0.0 ) ).normalize(); var tmpQ = new THREE.Quaternion(); var currentQ = new THREE.Quaternion(); function render() { var time = performance.now(); if(ready) { //var object = scene.children[0]; var x; var age; var introDuration = 0.2; var outroDuration = 0.2; var r; // endRs.needsUpdate = true; // startRs.needsUpdate = true; } //renderer.autoClear = false; renderer.render( scene, camera ); // pathobj.update(); lastTime = time; } init(); animate();
davidhoe/noisepainter
src/js/index3.js
JavaScript
apache-2.0
20,410
/* * Waltz - Enterprise Architecture * Copyright (C) 2016, 2017, 2018, 2019 Waltz open source project * See README.md 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 * */ import _ from "lodash"; /** * Given a set of nodes with id and parentId constructs a 'searchStr' property for each * node which is the concatenation of a specified property (attr) (or function) of all the nodes * parent nodes. */ export function prepareSearchNodes(nodes = [], attr = "name", parentKey = "parentId") { const nodesById = _.keyBy(nodes, "id"); const attrFn = _.isString(attr) ? n => n[attr] : attr; return _.map(nodes, n => { let ptr = n; let searchStr = ""; const nodePath = []; while (ptr) { nodePath.push(ptr); searchStr += (attrFn(ptr) || "") + " "; const parentId = ptr[parentKey]; ptr = nodesById[parentId]; } return { searchStr: searchStr.toLowerCase(), node: n, nodePath }; }); } /** * The given `termStr` will be tokenised and * all nodes (given in `searchNodes`) which contain all tokens * will be returned (de-duped). * * Use `prepareSearchNodes` to prepare the search nodes. * @param termStr * @param searchNodes */ export function doSearch(termStr = "", searchNodes = []) { const terms = _.split(termStr.toLowerCase(), /\W+/); return _ .chain(searchNodes) .filter(sn => { const noTerms = termStr.trim().length === 0; const allMatch = _.every(terms, t => sn.searchStr.indexOf(t) >=0); return noTerms || allMatch; }) .flatMap("nodePath") .uniqBy(n => n.id) .value(); } /** * Given data that looks like: * * [ { id: "", parentId: ?, ... } , .. ] * * Gives back an array of top level objects which have children * nested in them, the result looks something like: * * [ id: "", parentId : ?, parent : {}?, children : [ .. ], ... }, .. ] * * @param nodes * @param parentsAsRefs - whether to include parent as references or simple ids * @returns {Array} */ export function populateParents(nodes, parentsAsRefs = true) { const byId = _.chain(_.cloneDeep(nodes)) .map(u => _.merge(u, { children: [], parent: null })) .keyBy("id") .value(); _.each(_.values(byId), u => { if (u.parentId) { const parent = byId[u.parentId]; if (parent) { parent.children.push(u); u.parent = parentsAsRefs ? parent : parent.id; } } }); return _.values(byId); } export function buildHierarchies(nodes, parentsAsRefs = true) { // only give back root element/s return _.reject(populateParents(nodes, parentsAsRefs), n => n.parent); } export const reduceToSelectedNodesOnly = (nodes, selectedNodeIds = []) => { const byId = _.keyBy(nodes, d => d.id); const selectedNodesOnly = _ .chain(selectedNodeIds) .map(nId => byId[nId]) .compact() .value(); const selectedWithParents = _ .chain(selectedNodesOnly) .flatMap(n => _.concat([n], getParents(n, d => byId[d.parentId]))) .uniq() .value(); return selectedWithParents; } /** * Given a forest like structure (typically generated by buildHierarchies) * returns a flattened map object representing the hierarchical structure, * the map is indexed by the value returned by the keyFn. * * The second argument is a function which returns the key value for a given node * * End users should call this function without passing a third argument * as it is simply the accumulator used when recursing down the branches of the * trees. */ export function indexHierarchyByKey(tree = [], keyFn = n => n.id, acc = {}) { _.forEach(tree, node => { acc[keyFn(node)] = node; indexHierarchyByKey(node.children, keyFn, acc); }); return acc; } export function groupHierarchyByKey(tree = [], keyFn = n => n.id, acc = {}) { _.forEach(tree, node => { const key = keyFn(node); const bucket = acc[key] || []; bucket.push(node) acc[key] = bucket; groupHierarchyByKey(node.children, keyFn, acc); }); return acc; } export function flattenChildren(node, acc = []) { _.forEach(node.children || [], child => { acc.push(child); flattenChildren(child, acc); }); return acc; } /** The wix tree widget does deep comparisons. Having parents as refs therefore blows the callstack. This method will replace refs with id's. */ export function switchToParentIds(treeData = []) { _.each(treeData, td => { td.parent = td.parent ? td.parent.id : null; switchToParentIds(td.children); }); return treeData; } export function findNode(nodes = [], id) { const found = _.find(nodes, { id }); if (found) return found; for(let i = 0; i < nodes.length; i++) { const f = findNode(nodes[i].children, id); if (f) return f; } return null; } /** * * @param node * @param getParentFn - function to resolve parent, defaults to `n => n.parent` * @returns {Array} */ export function getParents(node, getParentFn = (n) => n.parent) { if (! node) return []; let ptr = getParentFn(node); const result = []; while (ptr) { result.push(ptr); ptr = getParentFn(ptr); } return result; }
rovats/waltz
waltz-ng/client/common/hierarchy-utils.js
JavaScript
apache-2.0
6,084
import React from 'react'; import { graphql } from 'react-relay'; import { makeFilter } from '@ncigdc/utils/filters'; import { compose, withPropsOnChange } from 'recompose'; import { BaseQuery } from '@ncigdc/modern_components/Query'; export default (Component: ReactClass<*>) => compose( withPropsOnChange(['projectId', 'mutated'], ({ projectId, mutated }) => { return { variables: { filters: makeFilter([ { field: 'cases.project.project_id', value: [projectId], }, ...(mutated ? [{ field: 'cases.available_variation_data', value: ['ssm'] }] : []), ]), }, }; }), )((props: Object) => { return ( <BaseQuery parentProps={props} name="HasCases" variables={props.variables} Component={Component} query={graphql` query HasCases_relayQuery($filters: FiltersArgument) { viewer { explore { cases { hits(first: 0, filters: $filters) { total } } } } } `} /> ); });
NCI-GDC/portal-ui
src/packages/@ncigdc/modern_components/HasCases/HasCases.relay.js
JavaScript
apache-2.0
1,239
'use strict'; /** * NetSuite Records * @return {Records} */ var Records = module.exports = {}; Records.RecordRef = require('./recordRef');
CrossLead/netsuite-js
lib/netsuite/records/index.js
JavaScript
apache-2.0
144
/** * Copyright (c) 2015 Intel 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. */ describe("Unit: orgUserService", function () { var $httpBackend; var orgUserServiceSUT; var targetProviderStub; var $rootScope; beforeEach(module('app')); beforeEach(module(function($provide){ targetProviderStub = {} $provide.value('targetProvider', targetProviderStub); })); beforeEach(inject(function (_orgUserService_, $injector, _$httpBackend_, _$rootScope_) { $httpBackend = _$httpBackend_; orgUserServiceSUT = _orgUserService_; $rootScope = _$rootScope_; })); afterEach(function () { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should call for users from apropriate organization on refresh', inject(function () { targetProviderStub.getOrganization = sinon.stub().returns({ guid: "1234" }); var callbackSpied = sinon.stub(); $httpBackend.expectGET('/rest/orgs/1234/users').respond(200, []); orgUserServiceSUT.getAll() .then(callbackSpied); $httpBackend.flush(); expect(callbackSpied.called).to.be.true; })); it('should fail while calling for users form unavailable organization on refresh', inject(function () { targetProviderStub.getOrganization = sinon.stub().returns(null); var errcallbackSpied = sinon.stub(); orgUserServiceSUT.getAll().catch(errcallbackSpied); $rootScope.$digest(); expect(errcallbackSpied.called).to.be.true; })); it('should send POST on adding user', inject(function () { var user = { username: "waclaw", roles: ["manager"] }; targetProviderStub.getOrganization = sinon.stub().returns({ guid: "1234" }); $httpBackend.expectPOST('/rest/orgs/1234/users').respond(201, {}); var callbackSpied = sinon.stub(); orgUserServiceSUT.addUser(user).then(callbackSpied); $httpBackend.flush(); expect(callbackSpied.called).to.be.true; })); });
rkoster/console
test/javascript/ui/manageusers/orgUserServiceTest.js
JavaScript
apache-2.0
2,643
/* Copyright 2012 - $Date $ by PeopleWare n.v. 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(["dojo/_base/declare", "ppwcode-util-oddsAndEnds/ui/horizontalPanesContainer/DraggablePane", "ppwcode-vernacular-persistence/ui/persistentObjectButtonEditPane/PersistentObjectButtonEditPane", "dojo/keys", "dojo/Deferred", "ppwcode-util-oddsAndEnds/log/logger!", "dojo/aspect", "dojo/text!./persistentObjectDraggableEditPane.html", "dojo/i18n!./nls/labels", "module", "dijit/layout/LayoutContainer", "dijit/layout/ContentPane", "dojo/_base/lang", "dojox/mvc/at", "xstyle/css!./persistentObjectDraggableEditPane.css"], function(declare, DraggablePane, PersistentObjectButtonEditPane, keys, Deferred, logger, aspect, template, labels, module) { //noinspection LocalVariableNamingConventionJS var PersistentObjectDraggableEditPane = declare([PersistentObjectButtonEditPane, DraggablePane], { // summary: // A PersistentObjectDraggableEditPane is a PersistentObjectButtonEditPane with a different template. templateString: template, labels: labels, constructor: function(kwargs) { var self = this; self.set("opener", function(po) { return self.container.openPaneFor(po, /*after*/ self); }); }, postCreate: function() { this.inherited(arguments); var self = this; self.own(self.on("keypress", function(event) { var presentationMode = self.get("presentationMode"); var target = self.get("target"); if (presentationMode === self.VIEW && event.keyChar === "e" && target && target.get("editable")) { event.preventDefault(); event.stopPropagation(); self.edit(); } else if (event.keyChar === "w" && presentationMode === self.VIEW) { event.preventDefault(); event.stopPropagation(); self.close(); } else if ((presentationMode === self.EDIT || presentationMode === self.WILD) && (event.ctrlKey || event.metaKey) && (event.keyChar === "s" || (event.keyChar === "w" && event.altKey))) { event.preventDefault(); event.stopPropagation(); self.save(event); } })); // TODO below function too complex; refactor self.own(self.on("keydown", function(event) { var presentationMode = self.get("presentationMode"); if ((presentationMode === self.EDIT || presentationMode === self.DELETE_ONLY || presentationMode === self.WILD) && event.keyCode === keys.ESCAPE) { event.preventDefault(); event.stopPropagation(); self.cancel(event); } else if ( ((event.keyCode === keys.LEFT_ARROW || event.keyCode === keys.RIGHT_ARROW) && (presentationMode === self.VIEW || presentationMode === self.BUSY)) || ((event.keyCode === keys.PAGE_UP || event.keyCode === keys.PAGE_DOWN || event.keyCode === keys.HOME || event.keyCode === keys.END) && (presentationMode === self.EDIT || presentationMode === self.DELETE_ONLY || presentationMode === self.WILD || presentationMode === self.VIEW || presentationMode === self.BUSY) && event.metaKey) ) { event.preventDefault(); event.stopPropagation(); if ((event.keyCode === keys.LEFT_ARROW || event.keyCode === keys.PAGE_UP) && self.previous !== self.getFirst()) { self.previous.focus(); } else if ((event.keyCode === keys.RIGHT_ARROW || event.keyCode === keys.PAGE_DOWN) && self.next !== self.getLast()) { self.next.focus(); } else if (event.keyCode === keys.HOME && self.getFirst().next !== self.getLast()) { self.getFirst().next.focus(); } else if (event.keyCode === keys.END && self.getLast().previous !== self.getFirst()) { self.getLast().previous.focus(); } // IDEA: with shift: move left, right } })); self.own(aspect.after( self._btnDelete, "_onDropDownMouseDown", function(/*Event*/ e) { // we need to stopPropagation, or else the enclosing movable will think we are starting a drag, and it will eat the mouse up e.stopPropagation(); }, true )); }, isVisualizationOf: function(object) { return this.get("target") === object; }, _setButtonsStyles: function(stylePresentationMode) { this.inherited(arguments); this._setVisible(this._btnClose, stylePresentationMode === this.VIEW, stylePresentationMode === this.BUSY); }, cancel: function(event) { return this._closeOnAlt(event, this.inherited(arguments)); }, save: function(event) { return this._closeOnAlt(event, this.inherited(arguments)); }, remove: function(event) { return this._closeOnAlt(event, this.inherited(arguments)); }, _closeOnAlt: function(/*Event*/ event, /*Promise*/ promise) { if (!event || !event.altKey) { return promise; } // also close var self = this; return promise.then( function(result) { return self.close().then(function() {return result;}); } ); }, close: function() { // summary: // Close and destroy. var self = this; var inheritedResult = self.inherited(arguments); return inheritedResult.then( function(po) { var removed = self.removeFromContainer(); // this is destroyed. if (removed) { return removed.then(function() { return po; }); } else { return new Deferred().resolve(po); // returns the promise } } ); } }); PersistentObjectDraggableEditPane.mid = module.id; return PersistentObjectDraggableEditPane; });
peopleware/js-ppwcode-vernacular-persistence
ui/horizontalPanesContainer/PersistentObjectDraggableEditPane.js
JavaScript
apache-2.0
7,345
import '@polymer/iron-icon/iron-icon.js'; import '@polymer/iron-icons/iron-icons.js'; import '@polymer/paper-card/paper-card.js'; import '@polymer/paper-ripple/paper-ripple.js'; import '@polymer/paper-item/paper-icon-item.js'; import '@polymer/paper-icon-button/paper-icon-button.js'; import {html, PolymerElement} from '@polymer/polymer'; import css from './dashboard-view.css'; import template from './dashboard-view.pug'; import './card-styles.js'; import './iframe-link.js'; import './notebooks-card.js'; import './pipelines-card.js'; import './resource-chart.js'; import {getGCPData} from './resources/cloud-platform-data.js'; import utilitiesMixin from './utilities-mixin.js'; export class DashboardView extends utilitiesMixin(PolymerElement) { static get template() { return html([` <style include="card-styles"> ${css.toString()} </style> ${template()} `]); } /** * Object describing property-related metadata used by Polymer features */ static get properties() { return { documentationItems: Array, quickLinks: Array, namespace: { type: Object, observer: '_namespaceChanged', }, platformDetails: Object, platformInfo: { type: Object, observer: '_platformInfoChanged', }, }; } /** * Observer for platformInfo property */ _platformInfoChanged() { if (this.platformInfo && this.platformInfo.providerName === 'gce') { this.platformName = 'GCP'; const pieces = this.platformInfo.provider.split('/'); let gcpProject = ''; if (pieces.length >= 3) { gcpProject = pieces[2]; } this.platformDetails = getGCPData(gcpProject); } } /** * Rewrites the links adding the namespace as a query parameter. * @param {namespace} namespace */ _namespaceChanged(namespace) { this.quickLinks.map((quickLink) => { quickLink.link = this.buildHref(quickLink.link, {ns: namespace}); return quickLink; }); // We need to deep-copy and re-assign in order to trigger the // re-rendering of the component this.quickLinks = JSON.parse(JSON.stringify(this.quickLinks)); } } customElements.define('dashboard-view', DashboardView);
kubeflow/kubeflow
components/centraldashboard/public/components/dashboard-view.js
JavaScript
apache-2.0
2,491
/* * @Author: yw850 * @Date: 2017-07-24 18:13:22 * @Last Modified by: yw850 * @Last Modified time: 2017-07-24 18:41:42 */ 'use strict'; require('./index.css') require('page/common/header/index.js'); require('page/common/nav/index.js'); var _mm = require('util/mm.js'); var _payment = require('service/payment-service.js'); var templateIndex = require('./index.string'); // page逻辑部分 var page = { data : { orderNumber : _mm.getUrlParam('orderNumber') }, init : function(){ this.onLoad(); }, onLoad : function(){ this.loadPaymentInfo(); }, loadPaymentInfo : function(){ var paymentHtml = '', _this = this, $pageWrap = $('.page-wrap'); // loading icon $pageWrap.html('<div class="loading"></div>'); _payment.getPaymentInfo(this.data.orderNumber, function(res){ // render paymentHtml = _mm.renderHtml(templateIndex, res); $pageWrap.html(paymentHtml); _this.listenOrderStatus(); }, function(errMsg){ $pageWrap.html('<p class="err-tip">' + errMsg + '</p>'); }); }, // 监听订单状态,轮询 listenOrderStatus : function(){ var _this = this; this.paymentTimer = window.setInterval(function(){ _payment.getPaymentStatus(_this.data.orderNumber, function(res){ if (res === true) { window.location.href = './result.html?type=payment&orderNumber=' + _this.data.orderNumber; } }); }, 5e3); } }; $(function(){ page.init(); });
Yongze/mmall-fe
src/page/payment/index.js
JavaScript
apache-2.0
1,418
/* eslint-env jest */ jest.unmock('../as-array'); import { asArray, } from '../as-array'; describe('asArray()', () => { it('returns input as it is if an array', () => { expect(asArray([1, 2, 3])).toEqual([1, 2, 3]); }); it('converts scalar value to an array which contains it', () => { expect(asArray(42)).toEqual([42]); }); it('converts null and undefined to an empty array', () => { expect(asArray(null)).toEqual([]); expect(asArray(undefined)).toEqual([]); }); });
asha-nepal/AshaFusionCross
src/web/forms/fields/common/__tests__/as-array-test.js
JavaScript
apache-2.0
503
'use strict'; describe('myApp.view3 module', function() { var scope, view3Ctrl; beforeEach(module('myApp.view3')); beforeEach(module('matchingServices')); beforeEach(inject(function ($controller, $rootScope) { // inject $rootScope scope = $rootScope.$new(); view3Ctrl = $controller('View3Ctrl',{$scope : scope}); })); describe('view3 controller', function(){ it('should ....', function() { //spec body expect(view3Ctrl).toBeDefined(); }); }); });
johandoornenbal/matchingfront
app/view3/view3_test.js
JavaScript
apache-2.0
498
describe('import.js', function() { describe('ImportSetup', function() { describe('#respondToPostMessages', function() { var test = { callback: function(uploadId, message) { } }; beforeEach(function() { spyOn(test, 'callback'); spyOn(window, 'miqSparkleOff'); spyOn(window, 'clearMessages'); spyOn(window, 'showWarningMessage'); spyOn(window, 'showErrorMessage'); }); context('when the import file upload id exists', function() { beforeEach(function() { var event = { data: { import_file_upload_id: 123, message: 'the message' } }; ImportSetup.respondToPostMessages(event, test.callback); }); it('turns the sparkle off', function() { expect(window.miqSparkleOff).toHaveBeenCalled(); }); it('clears the messages', function() { expect(window.clearMessages).toHaveBeenCalled(); }); it('triggers the callback', function() { expect(test.callback).toHaveBeenCalledWith(123, 'the message'); }); }); context('when the import file upload id does not exist', function() { var event = {data: {import_file_upload_id: ''}}; context('when the message level is warning', function() { beforeEach(function() { event.data.message = '{&quot;message&quot;:&quot;lol&quot;,&quot;level&quot;:&quot;warning&quot;}'; ImportSetup.respondToPostMessages(event, test.callback); }); it('turns the sparkle off', function() { expect(window.miqSparkleOff).toHaveBeenCalled(); }); it('clears the messages', function() { expect(window.clearMessages).toHaveBeenCalled(); }); it('displays a warning message with the message', function() { expect(window.showWarningMessage).toHaveBeenCalledWith('lol'); }); }); context('when the message level is not warning', function() { beforeEach(function() { event.data.message = '{&quot;message&quot;:&quot;lol2&quot;,&quot;level&quot;:&quot;error&quot;}'; ImportSetup.respondToPostMessages(event, test.callback); }); it('turns the sparkle off', function() { expect(window.miqSparkleOff).toHaveBeenCalled(); }); it('clears the messages', function() { expect(window.clearMessages).toHaveBeenCalled(); }); it('displays an error message with the message', function() { expect(window.showErrorMessage).toHaveBeenCalledWith('lol2'); }); }); }); }); describe('#listenForGitPostMessages', function() { var gitPostMessageCallback; beforeEach(function() { spyOn(window, 'addEventListener').and.callFake( function(_, callback) { gitPostMessageCallback = callback; } ); }); it('sets up an event listener', function() { ImportSetup.listenForGitPostMessages(); expect(window.addEventListener).toHaveBeenCalledWith('message', gitPostMessageCallback); }); describe('post message callback', function() { var event = {}; beforeEach(function() { spyOn(window, 'miqSparkleOff'); }); context('when the message data level is an error', function() { beforeEach(function() { spyOn(window, 'showErrorMessage'); spyOn($.fn, 'prop'); event.data = { message: {level: 'error', message: 'test'} }; gitPostMessageCallback(event); }); it('shows the error message', function() { expect(window.showErrorMessage).toHaveBeenCalledWith('test'); }); it('disables the git-url-import', function() { expect($.fn.prop).toHaveBeenCalledWith('disabled', null); expect($.fn.prop.calls.mostRecent().object.selector).toEqual('#git-url-import'); }); it('turns the spinner off', function() { expect(window.miqSparkleOff).toHaveBeenCalled(); }); }); context('when the message data level is not error', function() { beforeEach(function() { spyOn(Automate, 'renderGitImport'); event.data = { message: '{&quot;level&quot;: &quot;success&quot;, &quot;message&quot;: &quot;test&quot;}', git_repo_id: 123 }; }); context('when the data has branches', function() { beforeEach(function() { event.data.git_branches = 'branches'; gitPostMessageCallback(event); }); it('calls renderGitImport with the branches, tags, repo_id, and message', function() { expect(Automate.renderGitImport).toHaveBeenCalledWith('branches', undefined, 123, event.data.message); }); it('turns the spinner off', function() { expect(window.miqSparkleOff).toHaveBeenCalled(); }); }); context('when the data has tags with no branches', function() { beforeEach(function() { event.data.git_tags = 'tags'; gitPostMessageCallback(event); }); it('calls renderGitImport with the branches, tags, repo_id, and message', function() { expect(Automate.renderGitImport).toHaveBeenCalledWith(undefined, 'tags', 123, event.data.message); }); it('turns the spinner off', function() { expect(window.miqSparkleOff).toHaveBeenCalled(); }); }); context('when the data has neither tags nor branches', function() { beforeEach(function() { gitPostMessageCallback(event); }); it('does not call renderGitImport', function() { expect(Automate.renderGitImport).not.toHaveBeenCalled(); }); it('turns the spinner off', function() { expect(window.miqSparkleOff).toHaveBeenCalled(); }); }); }); }); }); describe('SettingUpImportButton', function() { beforeEach(function() { var html = ''; html += '<div class="col-md-6">' html += ' <input id="upload_button" />'; html += '</div>'; html += '<div>'; html += ' <input id="upload_file" />'; html += '</div>'; setFixtures(html); }); it('make upload button to not be disabled', function(){ $('#upload_button').prop('disabled', true); $('#upload_file').prop('value', 'test_value'); ImportSetup.setUpUploadImportButton('#upload_button'); expect($('#upload_button').prop('disabled')).toEqual(false); }); it('make upload button to be disabled', function(){ $('#upload_button').prop('disabled', false); ImportSetup.setUpUploadImportButton('#upload_button'); expect($('#upload_button').prop('disabled')).toEqual(true); }); }); }); describe('#clearMessages', function() { beforeEach(function() { var html = ''; html += '<div class="import-flash-message">'; html += ' <div class="alert alert-success alert-danger alert-warning"></div>'; html += '</div>'; html += '<div class="icon-placeholder pficon pficon-ok pficon-layered"></div>'; html += '<div id="error-circle-o" class="pficon-error-circle-o"></div>'; html += '<div id="error-exclamation" class="pficon-error-exclamation"></div>'; html += '<div id="warning-triangle" class="pficon-warning-triangle-o"></div>'; html += '<div id="warning-exclamation" class="pficon-warning-exclamation"></div>'; setFixtures(html); clearMessages(); }); it('removes alert classes', function() { expect($('.import-flash-message')).not.toHaveClass('alert-success'); expect($('.import-flash-message')).not.toHaveClass('alert-danger'); expect($('.import-flash-message')).not.toHaveClass('alert-warning'); }); it('removes pficon classes', function() { expect($('.icon-placeholder')).not.toHaveClass('pficon'); expect($('.icon-placeholder')).not.toHaveClass('pficon-ok'); expect($('.icon-placeholder')).not.toHaveClass('pficon-layered'); }); it('removes pficon-error-circle-o class', function() { expect($('#error-circle-o')).not.toHaveClass('pficon-error-circle-o'); }); it('removes pficon-error-exclamation class', function() { expect($('#error-exclamation')).not.toHaveClass('pficon-error-exclamation'); }); it('removes pficon-warning-triangle class', function() { expect($('#warning-triangle')).not.toHaveClass('pficon-warning-triangle-o'); }); it('removes pficon-warning-exclamation class', function() { expect($('#warning-exclamation')).not.toHaveClass('pficon-warning-exclamation'); }); }); });
ManageIQ/manageiq-ui-classic
spec/javascripts/import_spec.js
JavaScript
apache-2.0
9,147
import Firebase from 'firebase/firebase'; export class AngularFire { ref: Firebase; constructor(ref: Firebase) { this.ref = ref; } asArray() { return new FirebaseArray(this.ref); } } /* FirebaseArray */ export class FirebaseArray { ref: Firebase; error: any; list: Array; constructor(ref: Firebase) { this.ref = ref; this.list = []; // listen for changes at the Firebase instance this.ref.on('child_added', this.created.bind(this), this.error); this.ref.on('child_moved', this.moved.bind(this), this.error); this.ref.on('child_changed', this.updated.bind(this), this.error); this.ref.on('child_removed', this.removed.bind(this), this.error); // determine when initial load is completed // ref.once('value', function() { resolve(null); }, resolve); } getItem(recOrIndex: any) { var item = recOrIndex; if(typeof(recOrIndex) === "number") { item = this.getRecord(recOrIndex); } return item; } getChild(recOrIndex: any) { var item = this.getItem(recOrIndex); return this.ref.child(item._key); } add(rec: any) { this.ref.push(rec); } remove(recOrIndex: any) { this.getChild(recOrIndex).remove(); } save(recOrIndex: any) { var item = this.getItem(recOrIndex); this.getChild(recOrIndex).update(item); } keyify(snap) { var item = snap.val(); item._key = snap.key(); return item; } created(snap) { debugger; var addedValue = this.keyify(snap); this.list.push(addedValue); } moved(snap) { var key = snap.key(); this.spliceOut(key); } updated(snap) { var key = snap.key(); var indexToUpdate = this.indexFor(key); this.list[indexToUpdate] = this.keyify(snap); } removed(snap) { var key = snap.key(); this.spliceOut(key); } bulkUpdate(items) { this.ref.update(items); } spliceOut(key) { var i = this.indexFor(key); if( i > -1 ) { return this.list.splice(i, 1)[0]; } return null; } indexFor(key) { var record = this.getRecord(key); return this.list.indexOf(record); } getRecord(key) { return this.list.find((item) => key === item._key); } }
mainyaa/zapzapzap
deps/firebase/AngularFire.js
JavaScript
apache-2.0
2,206
/** * epubBundle * * Copyright 2015 David Herron * * This file is part of epubtools (http://akashacms.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. */ var util = require('util'); var epubber = require('../epubber'); module.exports = function(grunt) { grunt.registerTask('epubBundle', function() { var renderTo = grunt.config.get('epubtools.renderTo'); var epubFileName = grunt.config.get('epubtools.bookYaml.epub'); var done = this.async(); epubber.bundleEPUB(renderTo, epubFileName) .then(() => { done(); }) .catch(err => { done(err); }); }); };
epubtools/epubtools
tasks/epubBundle.js
JavaScript
apache-2.0
1,140
var fs = require('fs'); var path = require('path'); var createSourceMapLocatorPreprocessor = function(args, logger, helper) { var log = logger.create('preprocessor.sourcemap'); return function(content, file, done) { function sourceMapData(data){ file.sourceMap = JSON.parse(data); done(content); } function inlineMap(inlineData){ var data; var b64Match = inlineData.match(/^data:.+\/(.+);base64,(.*)$/); if (b64Match !== null && b64Match.length == 3) { // base64-encoded JSON string log.debug('base64-encoded source map for', file.originalPath); var buffer = new Buffer(b64Match[2], 'base64'); sourceMapData(buffer.toString()); } else { // straight-up URL-encoded JSON string log.debug('raw inline source map for', file.originalPath); sourceMapData(decodeURIComponent(inlineData.slice('data:application/json'.length))); } } function fileMap(mapPath){ fs.exists(mapPath, function(exists) { if (!exists) { done(content); return; } fs.readFile(mapPath, function(err, data) { if (err){ throw err; } log.debug('external source map exists for', file.originalPath); sourceMapData(data); }); }); } var lastLine = content.split(new RegExp(require('os').EOL)).pop(); var match = lastLine.match(/^\/\/#\s*sourceMappingURL=(.+)$/); var mapUrl = match && match[1]; if (!mapUrl) { fileMap(file.path + ".map"); } else if (/^data:application\/json/.test(mapUrl)) { inlineMap(mapUrl); } else { fileMap(path.resolve(path.dirname(file.path), mapUrl)); } }; }; createSourceMapLocatorPreprocessor.$inject = ['args', 'logger', 'helper']; // PUBLISH DI MODULE module.exports = { 'preprocessor:sourcemap': ['factory', createSourceMapLocatorPreprocessor] };
spatialdev/seed-angular-multipage-app
node_modules/karma-sourcemap-loader/index.js
JavaScript
apache-2.0
1,911
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main(name) { // [START vision_v1p3beta1_generated_ProductSearch_DeleteReferenceImage_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The resource name of the reference image to delete. * Format is: * `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID` */ // const name = 'abc123' // Imports the Vision library const {ProductSearchClient} = require('@google-cloud/vision').v1p3beta1; // Instantiates a client const visionClient = new ProductSearchClient(); async function callDeleteReferenceImage() { // Construct request const request = { name, }; // Run request const response = await visionClient.deleteReferenceImage(request); console.log(response); } callDeleteReferenceImage(); // [END vision_v1p3beta1_generated_ProductSearch_DeleteReferenceImage_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
googleapis/nodejs-vision
samples/generated/v1p3beta1/product_search.delete_reference_image.js
JavaScript
apache-2.0
1,876
load("jstests/libs/slow_weekly_util.js"); test = new SlowWeeklyMongod("conc_update"); db = test.getDB("concurrency"); db.dropDatabase(); NRECORDS = 3 * 1024 * 1024; print("loading " + NRECORDS + " documents (progress msg every 1024*1024 documents)"); var bulk = db.conc.initializeUnorderedBulkOp(); for (var i = 0; i < NRECORDS; i++) { bulk.insert({x: i}); } assert.writeOK(bulk.execute()); print("making an index (this will take a while)"); db.conc.ensureIndex({x: 1}); var c1 = db.conc.count({x: {$lt: NRECORDS}}); updater = startParallelShell( "db = db.getSisterDB('concurrency');\ db.concflag.insert({ inprog: true });\ sleep(20);\ assert.writeOK(db.conc.update({}, \ { $inc: { x: " + NRECORDS + "}}, false, true)); \ assert.writeOK(db.concflag.update({}, { inprog: false }));"); assert.soon(function() { var x = db.concflag.findOne(); return x && x.inprog; }, "wait for fork", 30000, 1); querycount = 0; decrements = 0; misses = 0; assert.soon(function() { c2 = db.conc.count({x: {$lt: NRECORDS}}); print(c2); querycount++; if (c2 < c1) decrements++; else misses++; c1 = c2; return !db.concflag.findOne().inprog; }, "update never finished", 2 * 60 * 60 * 1000, 10); print(querycount + " queries, " + decrements + " decrements, " + misses + " misses"); assert.eq(NRECORDS, db.conc.count(), "AT END 1"); updater(); // wait() test.stop();
christkv/mongo-shell
test/jstests/slow1/conc_update.js
JavaScript
apache-2.0
1,587
import { postToServer } from "../app/utils"; import { wait } from "../app/utils"; /** * Google Authentication and linking module * @returns {{link: function:object, login: function}} */ const googleProvider = new firebase.auth.GoogleAuthProvider(); function callIfFunction(func, arg1, arg2) { if ($.isFunction(func)) func(arg1, arg2); } export function login() { return firebase.auth().signInWithPopup(googleProvider) .then(function (result) { const userLoggedIn = result && result.user; if (userLoggedIn) return result.user.getIdToken(false); else throw Error('Could not authenticate'); }); } /** * Google Linking Module * @returns {{linkGoogle: function(callback), unlinkGoogle: function(callback), isGoogleLinked: function(callback}} */ export function link() { function getProviderData(providerDataArray, providerId) { if (!providerDataArray) return null; for (var i = 0; i < providerDataArray.length; i++) if (providerDataArray[i].providerId === providerId) return providerDataArray[i]; return null; } function isProvider(providerData, providerId) { return getProviderData(providerData, providerId) !== null; } function updateUser(user, providerData) { if (!providerData) return; const updateUser = {}; if (!user.displayName) updateUser.displayName = providerData.displayName; if (!user.photoURL) updateUser.photoURL = providerData.photoURL; user.updateProfile(updateUser) .then(function () { return firebase.auth().currentUser.getIdToken(false); }).then(function (token) { return postToServer('/profile/api/link', token); }).then(function (response) { if (response !== 'OK') return; wait(5000).then(function () { window.location = '/profile?refresh'; }); }); } function accountLinked(linkCallback, user) { callIfFunction(linkCallback, true); updateUser(user, getProviderData(user.providerData, googleProvider.providerId)); } function deletePreviousUser(prevUser, credential) { const auth = firebase.auth(); return auth.signInWithCredential(credential) .then(function(user) { return user.delete(); }).then(function() { return prevUser.linkWithCredential(credential); }).then(function() { return auth.signInWithCredential(credential); }); } return { linkGoogle: function (linkCallback) { firebase.auth().currentUser.linkWithPopup(googleProvider) .then(function(result) { accountLinked(linkCallback, result.user); }).catch(function(error) { if (error.code === 'auth/credential-already-in-use') { const prevUser = firebase.auth().currentUser; const credential = error.credential; deletePreviousUser(prevUser, credential) .then(function (user) { accountLinked(linkCallback, user); }).catch(function(error) { callIfFunction(linkCallback, false, error); }); } else { callIfFunction(linkCallback, false, error); } }); }, unlinkGoogle: function (unlinkCallback) { firebase.auth().currentUser.unlink(googleProvider.providerId) .then(function () { callIfFunction(unlinkCallback, true); }).catch(function (error) { callIfFunction(unlinkCallback, false, error); }); }, isGoogleLinked: function (linked) { firebase.auth().onAuthStateChanged(function (user) { if (!$.isFunction(linked)) return; if (user) { linked(isProvider(user.providerData, googleProvider.providerId)); } else { linked(); // Trigger hiding the button } }); } }; } export default { link, login }
zhcet-amu/zhcet-web
src/main/resources/src/authentication/google.js
JavaScript
apache-2.0
4,462
import Ember from 'ember'; const { Controller } = Ember; export default Controller.extend({ columns: [ { propertyName : 'name', template : 'components/ui-table/cell/cell-event', title : 'Name' }, { propertyName : 'starts-at', template : 'components/ui-table/cell/cell-date', title : 'Date' }, { propertyName : 'roles', template : 'components/ui-table/cell/cell-roles', title : 'Roles', disableSorting : true, disableFiltering : true }, { propertyName : 'sessionsByState', template : 'components/ui-table/cell/cell-sessions', title : 'Sessions', disableSorting : true, disableFiltering : true }, { propertyName : 'speakers.length', title : 'Speakers', disableSorting : true, disableFiltering : true }, { propertyName : 'tickets', template : 'components/ui-table/cell/cell-tickets', title : 'Tickets', disableSorting : true, disableFiltering : true }, { propertyName : 'url', template : 'components/ui-table/cell/cell-link', title : 'Public URL', disableSorting : true, disableFiltering : true }, { template : 'components/ui-table/cell/cell-buttons', title : 'Action', disableSorting : true, disableFiltering : true } ], actions: { moveToDetails(id) { this.transitionToRoute('events.view', id); }, editEvent(id) { this.transitionToRoute('events.view.edit.basic-details', id); }, openDeleteEventModal(id, name) { this.set('isEventDeleteModalOpen', true); this.set('confirmName', ''); this.set('eventName', name); this.set('eventId', id); }, deleteEvent() { this.set('isLoading', true); this.store.findRecord('event', this.get('eventId'), { backgroundReload: false }).then(function(event) { event.destroyRecord(); }) .then(() => { this.notify.success(this.l10n.t('Event has been deleted successfully.')); }) .catch(()=> { this.notify.error(this.l10n.t('An unexpected error has occurred.')); }) .finally(() => { this.set('isLoading', false); }); this.set('isEventDeleteModalOpen', false); } } });
harshitagupta30/open-event-frontend
app/controllers/events/list.js
JavaScript
apache-2.0
2,508
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main(fulfillment, updateMask) { // [START dialogflow_v2_generated_Fulfillments_UpdateFulfillment_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The fulfillment to update. */ // const fulfillment = {} /** * Required. The mask to control which fields get updated. If the mask is not * present, all fields will be updated. */ // const updateMask = {} // Imports the Dialogflow library const {FulfillmentsClient} = require('@google-cloud/dialogflow').v2; // Instantiates a client const dialogflowClient = new FulfillmentsClient(); async function callUpdateFulfillment() { // Construct request const request = { fulfillment, updateMask, }; // Run request const response = await dialogflowClient.updateFulfillment(request); console.log(response); } callUpdateFulfillment(); // [END dialogflow_v2_generated_Fulfillments_UpdateFulfillment_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
googleapis/nodejs-dialogflow
samples/generated/v2/fulfillments.update_fulfillment.js
JavaScript
apache-2.0
1,936
/** * @license Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'magicline', 'ko', { title: '여기에 그래프 삽입' } );
iWoozy/TextEasy
ckeditor/plugins/magicline/lang/ko.js
JavaScript
apache-2.0
253
var RoonApi = require("node-roon-api"), RoonApiStatus = require("node-roon-api-status"), RoonApiSettings = require("node-roon-api-settings"), RoonApiSourceControl = require("node-roon-api-source-control"), RoonApiVolumeControl = require("node-roon-api-volume-control"), Yamaha = require("node-yamaha-avr"); var roon = new RoonApi({ extension_id: 'com.statesofpop.roon-yamaha', display_name: "Yamaha Control", display_version: "0.0.7", publisher: 'states of pop', email: 'hi@statesofpop.de', website: 'https://github.com/statesofpop/roon-yamaha' }); var yamaha = { "default_device_name": "Yamaha", "default_input": "HDMI1", "volume": -50 }; var svc_status = new RoonApiStatus(roon); var svc_volume = new RoonApiVolumeControl(roon); var svc_source = new RoonApiSourceControl(roon); var svc_settings = new RoonApiSettings(roon); var volTimeout = null; var mysettings = roon.load_config("settings") || { receiver_url: "", input: yamaha.default_input, device_name: yamaha.default_device_name, input_list: [ { title: "HDMI 1", value: "HDMI1" }, { title: "HDMI 2", value: "HDMI2" }, { title: "HDMI 3", value: "HDMI3" }, { title: "HDMI 4", value: "HDMI4" }, { title: "HDMI 5", value: "HDMI5" }, { title: "HDMI 6", value: "HDMI6" } ] }; function makelayout(settings) { var l = { values: settings, layout: [], has_error: false }; l.layout.push({ type: "string", title: "Device name", subtitle: "Changing this might take some time to take effect.", setting: "device_name" }); l.layout.push({ type: "dropdown", title: "Input", values: mysettings.input_list, setting: "input" }); let v = { type: "string", title: "Receiver IP", subtitle: "Your device should be recognized automatically. If not, please configure your receiver to use a fixed IP-address.", setting: "receiver_url" }; if (settings.receiver_url != "" && settings.receiver_url.match(/^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/) === null) { v.error = "Please enter a valid IP-address"; l.has_error = true; } l.layout.push(v); return l; } var svc_settings = new RoonApiSettings(roon, { get_settings: function(cb) { cb(makelayout(mysettings)); }, save_settings: function(req, isdryrun, settings) { let l = makelayout(settings.values); req.send_complete(l.has_error ? "NotValid" : "Success", { settings: l }); if (!isdryrun && !l.has_error) { mysettings = l.values; svc_settings.update_settings(l); roon.save_config("settings", mysettings); } } }); svc_status.set_status("Initialising", false); function update_status() { if (yamaha.hid && yamaha.device_name) { svc_status.set_status("Found Yamaha " + yamaha.device_name + " at " + yamaha.ip, false); } else if (yamaha.hid && yamaha.ip) { svc_status.set_status("Found Yamaha device at " + yamaha.ip, false); } else if (yamaha.hid) { svc_status.set_status("Found Yamaha device. Discovering…", false); } else { svc_status.set_status("Could not find Yamaha device.", true) } } function check_status() { if (yamaha.hid) { yamaha.hid.getStatus() .then( (result) => { // exit if a change through roon is in progress if (volTimeout) return; // this seems to only get called on success let vol_status = result["YAMAHA_AV"]["Main_Zone"][0]["Basic_Status"][0]["Volume"][0]; // should get current state first, to see if update is necessary yamaha.svc_volume.update_state({ volume_value: vol_status["Lvl"][0]["Val"] / 10, is_muted: (vol_status["Mute"] == "On") }); update_status() }) .catch( (error) => { // this seems not to get called when device is offline yamaha.hid == ""; svc_status.set_status("Could not find Yamaha device.", true); }); } } function setup_yamaha() { if (yamaha.hid) { yamaha.hid = undefined; } if (yamaha.source_control) { yamaha.source_control.destroy(); delete(yamaha.source_control); } if (yamaha.svc_volume) { yamaha.svc_volume.destroy(); delete(yamaha.svc_volume); } yamaha.hid = new Yamaha(mysettings.receiver_url); // should check whether the device is behind the given url // only then start to discover. yamaha.hid.discover() .then( (ip) => { yamaha.ip = ip; update_status(); }) .catch( (error) => { yamaha.hid = undefined; svc_status.set_status("Could not find Yamaha device.", true) }); try { yamaha.hid.getSystemConfig().then(function(config) { if (mysettings.device_name == yamaha.default_device_name) { mysettings.device_name = config["YAMAHA_AV"]["System"][0]["Config"][0]["Model_Name"][0]; } let inputs = config["YAMAHA_AV"]["System"][0]["Config"][0]["Name"][0]["Input"][0]; mysettings.input_list = []; for (let key in inputs) { mysettings.input_list.push({ "title": inputs[key][0].trim(), "value": key.replace("_", "") }) } update_status(); }) } catch(e) { // getting the device name is not critical, so let's continue } yamaha.svc_volume = svc_volume.new_device({ state: { display_name: mysettings.device_name, volume_type: "db", volume_min: -87.5, volume_max: -20, volume_value: -50, volume_step: 0.5, is_muted: 0 }, set_volume: function (req, mode, value) { let newvol = mode == "absolute" ? value : (yamaha.volume + value); if (newvol < this.state.volume_min) newvol = this.state.volume_min; else if (newvol > this.state.volume_max) newvol = this.state.volume_max; yamaha.svc_volume.update_state({ volume_value: newvol }); clearTimeout(volTimeout); volTimeout = setTimeout(() => { // node-yamaha-avr sends full ints yamaha.hid.setVolume( value * 10 ); clearTimeout(volTimeout); volTimeout = null; }, 500) req.send_complete("Success"); }, set_mute: function (req, action) { let is_muted = !this.state.is_muted; yamaha.hid.setMute( (is_muted)? "on": "off" ) yamaha.svc_volume.update_state({ is_muted: is_muted }); req.send_complete("Success"); } }); yamaha.source_control = svc_source.new_device({ state: { display_name: mysettings.device_name, supports_standby: true, status: "selected", }, convenience_switch: function (req) { yamaha.hid.setInput(mysettings.input); req.send_complete("Success"); }, standby: function (req) { let state = this.state.status; this.state.status = (state == "selected")? "standby": "selected"; yamaha.hid.setPower((state == "selected")? "off": "on"); req.send_complete("Success"); } }); } roon.init_services({ provided_services: [ svc_status, svc_settings, svc_volume, svc_source ] }); setInterval(() => { if (!yamaha.hid) setup_yamaha(); }, 1000); setInterval(() => { if (yamaha.hid) check_status(); }, 5000); roon.start_discovery();
statesofpop/roon-yamaha
app.js
JavaScript
apache-2.0
7,950
$(function () { $(window).scroll(function() { if ($(".navbar").offset().top>30) { $(".navbar-fixed-top").addClass("sticky"); } else { $(".navbar-fixed-top").removeClass("sticky"); } }); // Flex if ($(".flexslider").length) { $('.flexslider').flexslider(); } servicesOptions.initialize(); staticHeader.initialize(); portfolioItem.initialize(); // segun esto corrige el pedo del dropdown en tablets and such // hay que testearlo! $('.dropdown-toggle').click(function(e) { e.preventDefault(); setTimeout($.proxy(function() { if ('ontouchstart' in document.documentElement) { $(this).siblings('.dropdown-backdrop').off().remove(); } }, this), 0); }); }); var portfolioItem = { initialize: function () { var $container = $("#portfolio_tem .left_box"); var $bigPics = $container.find(".big img"); var $thumbs = $container.find(".thumbs .thumb"); $bigPics.hide().eq(0).show(); $thumbs.click(function (e) { e.preventDefault(); var index = $thumbs.index(this); $bigPics.fadeOut(); $bigPics.eq(index).fadeIn(); }); } } var staticHeader = { initialize: function () { if ($(".navbar-static-top").length) { $("body").css("padding-top", 0); } } } var servicesOptions = { initialize: function () { var $container = $(".services_circles"); var $texts = $container.find(".description .text"); var $circles = $container.find(".areas .circle"); $circles.click(function () { var index = $circles.index(this); $texts.fadeOut(); $texts.eq(index).fadeIn(); $circles.removeClass("active"); $(this).addClass("active"); }); } } $(document).ready(function(){ $("#menuContent div").hide(); $("#menuContent div:first").show(); $("#subMenu li:first").addClass("active"); $("#subMenu li a").click(function(){ $('#subMenu li').removeClass("active"); $(this).parent().addClass("active"); var current = $(this).attr("href"); $("#menuContent div:visible").fadeOut("fast"); $("#menuContent").animate({"height":$(current).height()},function(){ $(current).fadeIn("fast"); }); return false; }); });
pointwesthealthcare/pwhmcdw
deploy/js/theme.js
JavaScript
apache-2.0
2,502
$(function() { YtopMgr = { //退出账号 logOut : function() { window.parent.location.href = "logout"; } } })
AndroidBoy/BAMService
WebRoot/page/manager/mainpage/top.js
JavaScript
apache-2.0
124
define( ({ _widgetLabel: "분석", executeAnalysisTip: "실행할 분석 도구 클릭", noToolTip: "분석 도구를 선택하지 않았습니다!", back: "뒤로", next: "다음", home: "홈", jobSubmitted: "제출하였습니다.", jobCancelled: "취소되었습니다.", jobFailed: "실패함", jobSuccess: "성공했습니다.", executing: "실행 중", cancelJob: "분석 작업 취소", paramName: "매개변수 이름", link: "링크", learnMore: "자세한 정보", messages: "메시지", outputs: "결과", outputtip: "참고: 결과 피처 및 테이블은 운영 레이어로 맵에 추가됩니다.", outputSaveInPortal: "데이터가 포털에 저장되었습니다.", privilegeError: "내 사용자 역할은 분석을 수행할 수 없습니다. 분석을 수행하려면 내 기관의 관리자가 특정 <a href=\"http://doc.arcgis.com/en/arcgis-online/reference/roles.htm\" target=\"_blank\">권한</a>을 부여해야 합니다." }) );
cob222/CPG
widgets/Analysis/nls/ko/strings.js
JavaScript
apache-2.0
1,046
var game, gameOptions; gameOptions = { renderer: Kiwi.RENDERER_WEBGL, deviceTarget: Kiwi.TARGET_BROWSER, width: 1280, height: 800 }; game = new Kiwi.Game("content", "MAZE", null, gameOptions); game.states.addState(MAZE.Game); game.states.switchState("Game"); //# sourceMappingURL=main.js.map
black-knight/magic_lamp
Content/MAZE/src/main.js
JavaScript
apache-2.0
305
var interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore = [ [ "getDevices", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#a31af140046e965889b1e344e53ab37e1", null ], [ "getMaster", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#a2bed6e1e4895ca63cb4e5bd55c15e48f", null ], [ "getNodes", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#afb48638578c77456adf13f1cd46614c7", null ], [ "getRole", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#ac2d2cf6f0fc0057267ce7b285bdb91e7", null ], [ "getTermFor", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#af1f35746cf3838fc0b143fb8c8baae5d", null ], [ "relinquishAllRole", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#ab1d5f9847d612b2884a86ce70f476404", null ], [ "relinquishRole", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#a2e80344c4c9d4225937db2fa9ead93b7", null ], [ "requestRole", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#a0835c16a1d78211cec93c738450470ab", null ], [ "setMaster", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#aefe91986d2d154a58b4a2bef73ec1c7a", null ], [ "setStandby", "interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.html#ae6569bb66221e4fbd3c585f309035744", null ] ];
onosfw/apis
onos/apis/interfaceorg_1_1onosproject_1_1mastership_1_1MastershipStore.js
JavaScript
apache-2.0
1,385
/** * Copyright IBM Corp. 2020, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * @jest-environment node */ 'use strict'; describe('yml', () => { let vol; let adapter; beforeEach(() => { jest.mock('fs', () => { const memfs = require('memfs'); vol = memfs.vol; return memfs.fs; }); adapter = require('../yml'); }); afterEach(() => { vol.reset(); }); it('should read a filepath and return its content as a value', async () => { const data = { foo: 'bar' }; vol.fromJSON({ '/test.yml': adapter.serialize(data), }); const result = await adapter.read('/', 'test'); expect(result).toEqual(data); }); it('should write the given data as yml to the given filepath', async () => { const data = { foo: 'bar' }; await adapter.write('/', 'test', data); const result = await adapter.read('/', 'test'); expect(result).toEqual(data); }); it('should throw if the file its trying to read from does not exist', async () => { await expect( adapter.read('/', 'test') ).rejects.toThrowErrorMatchingInlineSnapshot( `"Unable to find extension \`test\` at filepath: /test.yml. Either create the file or update the extension to be computed."` ); }); it('should throw if the given data is invalid yml', async () => { await expect( adapter.write('/', 'test', { data: undefined }) ).rejects.toThrow(); }); });
carbon-design-system/carbon-components
packages/icon-build-helpers/src/metadata/adapters/__tests__/yml-test.js
JavaScript
apache-2.0
1,532
angular.module("userTableModule", []) .controller('userTableController', ['$http', function ($http, $scope, $log) { var userTable = this; userTable.users = []; $http.get('/allUsers').success(function (data) { userTable.users = data; }).error(function (data) { }); userTable.addRow = function() { userTable.users = push({ 'id' : $scope.id, 'fullName' : userTable.fullName, 'lastName' : userTable.lastName, 'description' : userTable.description }); userTable.fullName = ''; userTable.lastName = ''; userTable.description = ''; }; userTable.deleteUserById = function (id) { var userArr = eval(userTable.users); var index = -1; for (var i = 0; i < userArr.length; i++) { if (userArr[i].id == id) { index = i; break; } } if (index == -1) { alert("Не удалось найти строку с таким id:" + id); } userTable.users.splice(index, 1); }; }]);
andreevym/stadium
src/main/resources/public/js/userTableModule.js
JavaScript
apache-2.0
1,250
// 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. import eventsModule from 'events/events_module'; describe('Event Card List controller', () => { /** * Event Card List controller. * @type {!events/eventcardlist_component.EventCardListController} */ let ctrl; beforeEach(() => { angular.mock.module(eventsModule.name); angular.mock.inject( ($componentController) => { ctrl = $componentController('kdEventCardList', {}); }); }); it('should not filter any events if all option is selected', () => { // given let eventType = 'All'; let events = [ { type: 'Warning', message: 'event-1', }, { type: 'Normal', message: 'event-2', }, ]; // when let result = ctrl.filterByType(events, eventType); // then expect(result.length).toEqual(2); }); it('should filter all non-warning events if warning option is selected', () => { // given let eventType = 'Warning'; let events = [ { type: 'Warning', message: 'event-1', }, { type: 'Normal', message: 'event-2', }, { type: 'Normal', message: 'event-3', }, ]; // when let result = ctrl.filterByType(events, eventType); // then expect(result.length).toEqual(1); }); it('should return true when there are events to display', () => { // given ctrl.filteredEvents = ['Some event']; // when let result = ctrl.hasEvents(); // then expect(result).toBeTruthy(); }); it('should return false if there are no events to display', () => { // when let result = ctrl.hasEvents(); // then expect(result).toBeFalsy(); }); it('should filter events and show only warnings', () => { // given ctrl.eventType = 'Warning'; ctrl.events = [ { type: 'Warning', message: 'event-1', }, { type: 'Normal', message: 'event-2', }, { type: 'Normal', message: 'event-3', }, ]; // when ctrl.handleEventFiltering(); // then expect(ctrl.filteredEvents.length).toEqual(1); }); it('should not filter any events and show all', () => { // given ctrl.eventType = 'All'; ctrl.events = [ { type: 'Warning', message: 'event-1', }, { type: 'Normal', message: 'event-2', }, { type: 'Normal', message: 'event-3', }, ]; // when ctrl.handleEventFiltering(); // then expect(ctrl.filteredEvents.length).toEqual(3); }); it('should return true when warning event', () => { // given let event = { type: 'Warning', message: 'event-1', }; // when let result = ctrl.isEventWarning(event); // then expect(result).toBeTruthy(); }); it('should return false when not warning event', () => { // given let event = { type: 'Normal', message: 'event-1', }; // when let result = ctrl.isEventWarning(event); // then expect(result).toBeFalsy(); }); });
wzzlYwzzl/kdashboard
src/test/frontend/events/eventcardlist_component_test.js
JavaScript
apache-2.0
3,724
'use strict' const config = { local: { pino: { prettyPrint: false } }, ci: { pino: { prettyPrint: false } }, staging: { pino: { prettyPrint: false } }, prod: { pino: { prettyPrint: false } } } module.exports = function resolveConfig (mode) { return config[mode || process.env.NODE_ENV || 'local'] }
OmniJeff/hapi-soup
lib/config/logger.js
JavaScript
apache-2.0
378
'use strict'; var ContextHistory = require('./context_history'); var ContextTouch = require('./context_touch'); /** * @param {!angular.Scope} $rootScope * @param {!Window} $window * @param {!Document} $document * @param {!angular.Attributes} options * @param {!TouchSurface.TouchChangedHandler} startHandler * @param {!TouchSurface.TouchChangedHandler} moveHandler * @param {!TouchSurface.TouchChangedHandler} endHandler * @constructor * @ngInject */ var TouchSurface = module.exports = function TouchSurface( $rootScope, $window, $document, options, startHandler, moveHandler, endHandler) { /** @private {!angular.Scope} */ this.rootScope_ = $rootScope; /** @private {!angular.Attributes} */ this.options_ = options; /** @private {!Window} */ this.window_ = $window; /** @private {!TouchSurface.TouchChangedHandler} */ this.touchStartChangedCallback_ = startHandler; /** @private {!TouchSurface.TouchChangedHandler} */ this.touchMoveChangedCallback_ = moveHandler; /** @private {!TouchSurface.TouchChangedHandler} */ this.touchEndChangedCallback_ = endHandler; /** * Identifiers need to cancel currently queued callbacks * using {@link Window.cancelAnimationFrame}. * * Sequentially keyed (as Array indices) * {@link Window.requestAnimationFrame} queued callbacks, where values are * the cancel-identifier requestAnimationFrame returns. Null indicates the * request has been cancelled, or already executed. * * @private {!Object.<number, ?number>} */ this.rafCancelIds_ = {}; /** @private {?CanvasRenderingContext2D} */ this.context_ = null; /** @type {?ContextTouch} */ this.contextTouch = null; /** @type {!ContextHistory} */ this.contextHistory = new ContextHistory(); /** @private {!Object.<Controller.Setting, ?string} */ this.settings_ = {}; angular.forEach(TouchSurface.DefaultSettings, function(value, key) { this.updateSettings_(key, value); }.bind(this)); $document.eq(0)[0].addEventListener( 'contextmenu', this.contextmenuEventHandler_.bind(this), false /*useCapture*/); }; /** * Handler API which will be called for individual {@link Touch} objects in a * {@link TouchEvent#changedTouches} list, with the arguments: * - animationFrame: the {@link Window.requestAnimationFrame}'s timestamp during * which this handler is being executed. * - timeStamp: {@link TouchEvent#timeStamp} of the event that triggered this * handler. * - changedTouch: One of {@link TouchEvent#changedTouches} * * @typedef {function(DOMHighResTimeStamp, number, !Touch)} */ TouchSurface.TouchChangedHandler; /** * @typedef {{ * hex: {r: string, g: string, b: string}, * dec: {r: number, g: number, b: number} * }} * @private */ TouchSurface.RgbMap_; /** @enum {string} */ TouchSurface.Options = { MAXIMIZED: 'touchSurfaceMaximized' }; /** @enum {string} */ TouchSurface.Events = { LOADED: 'TouchSurface.Events.LOADED', RESIZE: 'TouchSurface.Events.RESIZE' }; /** @enum {string} */ TouchSurface.Setting = { LINE_COLOR: 'LINE_COLOR', LINE_WIDTH: 'LINE_WIDTH', BACKGROUND_COLOR: 'BACKGROUND_COLOR' }; /** @enum {TouchSurface.Setting} */ TouchSurface.DefaultSettings = { BACKGROUND_COLOR: '#ffffff', LINE_COLOR: '#000000' }; /** @return {string} RGB hex value */ TouchSurface.buildRandomRgbStyle = function() { return '#' + (Math.random().toString(16) + '0000000').slice(2, 8); }; /** @param {!HTMLCanvasElement} canvasEl */ TouchSurface.prototype.bindToCanvas = function(canvasEl) { if (!canvasEl.nodeName || !canvasEl.nodeName.toLowerCase || canvasEl.nodeName.toLowerCase() != 'canvas') { throw new Error('`el` of `bindToCanvas(el)` MUST be a <canvas> Element'); } if (this.context_) { throw new Error('bindToCanvas should only be called once!'); } this.context_ = canvasEl.getContext('2d'); this.contextTouch = new ContextTouch(this.context_); if (this.isEnabled(TouchSurface.Options.MAXIMIZED)) { // Maximize playing surface now this.window_.requestAnimationFrame( this.resizeSurfaceToContainer_.bind( this, this.context_ /*surface*/, this.window_ /*container*/)); // .. and in the future this.queueRefreshTask_( this.window_, 'resize', this.resizeSurfaceToTarget_.bind(this, this.context_)); } // Listen to interactions var renderSurfaceOn = this.queueRefreshTask_.bind(this, canvasEl); renderSurfaceOn('touchstart', this.handleTouchStart_.bind(this)); renderSurfaceOn('touchmove', this.handleTouchMove_.bind(this)); renderSurfaceOn('touchend', this.handleTouchEnd_.bind(this)); renderSurfaceOn('touchcancel', this.handleTouchEnd_.bind(this)); this.rootScope_.$broadcast(TouchSurface.Events.LOADED, this); }; /** * @param {TouchSurface.Setting} setting * @param {string=} opt_value * @private */ TouchSurface.prototype.updateSettings_ = function(setting, opt_value) { this.settings_[setting] = angular.isDefined(opt_value) ? opt_value : (TouchSurface.DefaultSettings[setting] || null); }; /** @param {string=} opt_lineColor to optionally override default value */ TouchSurface.prototype.setLineColorSetting = function(opt_lineColor) { this.updateSettings_(TouchSurface.Setting.LINE_COLOR, opt_lineColor); }; /** @return {?string} */ TouchSurface.prototype.getLineColorSetting = function() { return this.settings_[TouchSurface.Setting.LINE_COLOR] || null; }; /** @param {string=} opt_backgroundColor to optionally override default */ TouchSurface.prototype.setBackgroundColorSetting = function( opt_backgroundColor) { this.updateSettings_( TouchSurface.Setting.BACKGROUND_COLOR, opt_backgroundColor); }; /** @return {?string} */ TouchSurface.prototype.getBackgroundColorSetting = function() { return this.settings_[TouchSurface.Setting.BACKGROUND_COLOR] || null; }; /** @param {string=} opt_lineWidth to optionally override default value */ TouchSurface.prototype.setLineWidthSetting = function(opt_lineWidth) { this.updateSettings_(TouchSurface.Setting.LINE_WIDTH, opt_lineWidth); }; /** @return {?string} */ TouchSurface.prototype.getLineWidthSetting = function() { return this.settings_[TouchSurface.Setting.LINE_WIDTH] || null; }; /** @return {!Canvas} */ TouchSurface.prototype.getCanvas = function() { return this.context_.canvas; }; /** @return {!Canvas} */ TouchSurface.prototype.getContext = function() { return this.context_; }; /** * @param {!Event} event * @private */ TouchSurface.prototype.attemptPreventDefault_ = function(event) { if (event.cancelable) { event.preventDefault(); } }; /** * @param {string} hexColorStyle * CSS style hex value starting with hash symbol, followed by 3 pairs of * alpha-numeric characters in hex range. eg: <code>'#ff12e3'</code> * @return {TouchSurface.RgbMap_} * Decimal values for "red", "green", "blue" as scraped * from {@code hexColorStyle}. eg: <code>{r: 'ff', g: '12', b: 'e3'}</code> * @private */ TouchSurface.buildHexMapFromRgbStyle_ = function(hexColorStyle) { var hashRgb = hexColorStyle. match(/^#(\w\w)(\w\w)(\w\w)$/); var rgb = {hex: {r: hashRgb[1], g: hashRgb[2], b: hashRgb[3]}}; rgb.dec = { r: parseInt(rgb.hex.r, 16), g: parseInt(rgb.hex.g, 16), b: parseInt(rgb.hex.b, 16) }; return rgb; }; /** * Plays back all rendered history, whether its been erased or not. * * @param {number=} opt_endIndex */ TouchSurface.prototype.playBack = function(opt_endIndex) { this.contextHistory.playBack(this.context_, opt_endIndex); }; /** * Re-renders the current animations on surface as they currently appear. * * @param {boolean=} opt_retainCurrentSurface */ TouchSurface.prototype.redraw = function(opt_retainCurrentSurface) { var currentIndex = this.contextHistory.getPresentIndex(); if (!opt_retainCurrentSurface) { this.clear(true /*opt_offTheRecord*/); } this.playBack(currentIndex); }; /** * Erases all currently rendered animations on the surface. * * @param {boolean=} opt_offTheRecord */ TouchSurface.prototype.clear = function(opt_offTheRecord) { if (opt_offTheRecord) { ContextHistory.erase(this.context_); } else { this.contextHistory.undoAll(this.context_); } }; /** Unrenders the most previously added update */ TouchSurface.prototype.undo = function() { if (!this.contextHistory.isUndoPossible()) { return; } this.playBack(this.contextHistory.getPreviousUpdateIndex()); }; /** Re-renders the last update erased with {@link #undo}. */ TouchSurface.prototype.redo = function() { if (!this.contextHistory.isRedoPossible()) { return; } this.playBack(this.contextHistory.getNextUpdateIndex()); }; /** * @param {TouchSurface.Options} option * @return {boolean} */ TouchSurface.prototype.isEnabled = function(option) { return Boolean(this.options_.$attr[option]); }; /** @return {boolean} */ TouchSurface.prototype.isDirty = function() { return !this.contextHistory.isEmpty() && this.contextHistory.getPresentIndex() >= 0; }; /** * @param {!Event} event * @return {boolean} * @private */ TouchSurface.prototype.contextmenuEventHandler_ = function(event) { this.attemptPreventDefault_(event); return false; }; /** * Calls {@link EventTarget.addEventListener} with some performant defaults. * * NOTE: Passes "false" for "useCapture" parameter. * * @param {!EventTarget} target * @param {string} eventName * @param {function} handler * @private */ TouchSurface.prototype.queueRefreshTask_ = function( target, eventName, handler) { target.addEventListener(eventName, function(event) { var rafIdIdx = Object.keys(this.rafCancelIds_).length; var eventArgs = arguments; this.rafCancelIds_[rafIdIdx] = this.window_. requestAnimationFrame(function() { var args = Array.prototype.slice.call(eventArgs). concat(Array.prototype.slice.call(arguments)); var taskReturn = handler.apply(null /*this*/, args); this.rafCancelIds_[rafIdIdx] = null; this.rootScope_.$apply(); return taskReturn; }.bind(this)); return true; // cancel }.bind(this), false /*useCapture*/); }; /** Scope destroy cleanup handler */ TouchSurface.prototype.destroyHandler = function() { this.rafCancelIds_.forEach(function(rafId, refreshTaskId) { if (rafId === null) { return; } this.window_.cancelAnimationFrame(rafId); }.bind(this)); }; /** * @param {!CanvasRenderingContext2D} surface * @param {!Event} event * @private */ TouchSurface.prototype.resizeSurfaceToTarget_ = function(surface, event) { if (!event.target) { // strange: this happens when opening dev console // (eg: `event` is: 1987.7080000005662) return; } this.resizeSurfaceToContainer_(surface, event.target); this.redraw(); // put everything back where it was }; /** * @param {!CanvasRenderingContext2D} surface * @param {!Window} container * @private */ TouchSurface.prototype.resizeSurfaceToContainer_ = function( surface, container) { surface.canvas.width = container.innerWidth; surface.canvas.height = container.innerHeight; this.rootScope_.$broadcast(TouchSurface.Events.RESIZE); }; /** * @param {!TouchEvent} touchEvent * @param {DOMHighResTimeStamp} animationFrame * @return {boolean} cancelable * @private */ TouchSurface.prototype.handleTouchStart_ = function( touchEvent, animationFrame) { this.attemptPreventDefault_(touchEvent); Array.prototype.forEach.call(touchEvent.changedTouches, function() { this.touchStartChangedCallback_ ? this.touchStartChangedCallback_.apply(null /*this*/, arguments) : null; }.bind(this, animationFrame, touchEvent.timeStamp)); return true; }; /** * @param {string} baseRgbStyle * @return {string} RGB hex value */ TouchSurface.prototype.buildRelatedColor = function(baseRgbStyle) { var baseColors = TouchSurface. buildHexMapFromRgbStyle_(baseRgbStyle); var randomColors = TouchSurface. buildHexMapFromRgbStyle_(TouchSurface.buildRandomRgbStyle()); return '#' + ['r', 'g', 'b'].map(function(color) { return ( (baseColors.dec[color] + randomColors.dec[color]) * 0.5 ).toString(16); }).join(''); }; /** * @param {!TouchEvent} touchEvent * @param {DOMHighResTimeStamp} animationFrame * @return {boolean} cancelable * @private */ TouchSurface.prototype.handleTouchMove_ = function(touchEvent, animationFrame) { this.attemptPreventDefault_(touchEvent); Array.prototype.forEach.call(touchEvent.changedTouches, function() { this.touchMoveChangedCallback_ ? this.touchMoveChangedCallback_.apply(null /*this*/, arguments) : null; }.bind(this, animationFrame, touchEvent.timeStamp)); return true; // cancel }; /** * @param {!TouchEvent} touchEvent * @param {DOMHighResTimeStamp} animationFrame * @return {boolean} cancelable * @private */ TouchSurface.prototype.handleTouchEnd_ = function(touchEvent, animationFrame) { Array.prototype.forEach.call(touchEvent.changedTouches, function() { this.touchEndChangedCallback_ ? this.touchEndChangedCallback_.apply(null /*this*/, arguments) : null; }.bind(this, animationFrame, touchEvent.timeStamp)); return true; };
jzacsh/doodle
src/lib/touch_surface.js
JavaScript
apache-2.0
13,368
/* * Copyright (c) 2014 Juniper Networks, Inc. All rights reserved. */ var rest = require('../../../common/rest.api'), config = require('../../../../../config/config.global.js'), authApi = require('../../../common/auth.api'), url = require('url'), logutils = require('../../../utils/log.utils'), async = require('async'), appErrors = require('../../../errors/app.errors.js'), commonUtils = require('../../../utils/common.utils'), httpsOp = require('../../../common/httpsoptions.api'), oStack = require('./openstack.api') ; var novaAPIServer; novaApi = module.exports; var novaIP = ((config.computeManager) && (config.computeManager.ip)) ? config.computeManager.ip : global.DFLT_SERVER_IP; var novaPort = ((config.computeManager) && (config.computeManager.port)) ? config.computeManager.port : '8774'; novaAPIServer = rest.getAPIServer({apiName:global.label.COMPUTE_SERVER, server:novaIP, port:novaPort}); function getTenantIdByReqCookie (req) { if (req.cookies && req.cookies.project) { return req.cookies.project; } else { var ajaxCall = req.headers['x-requested-with']; if (ajaxCall == 'XMLHttpRequest') { req.res.setHeader('X-Redirect-Url','/logout'); req.res.send(307,''); } else { req.res.redirect('/logout'); } return null; } } /* Function: doNovaOpCb */ function doNovaOpCb (reqUrl, apiProtoIP, tenantId, req, novaCallback, stopRetry, callback) { var forceAuth = stopRetry; authApi.getTokenObj(req, tenantId, forceAuth, function(err, tokenObj) { if ((null != err) || (null == tokenObj) || (null == tokenObj.id)) { if (stopRetry) { console.log("We are done retrying for tenantId:" + tenantId + " with err:" + err); commonUtils.redirectToLogout(req, req.res); } else { /* Retry once again */ console.log("We are about to retry for tenantId:" + tenantId); novaCallback(reqUrl, apiProtoIP, req, callback, true); } } else { console.log("doNovaOpCb() success with tenantId:" + tenantId); callback(err, tokenObj); } }); } /* Wrapper function to GET Data from Nova-Server */ novaApi.get = function(reqUrl, apiProtoIP, req, callback, stopRetry) { var headers = {}; var forceAuth = stopRetry; var tenantId = getTenantIdByReqCookie(req); if (null == tenantId) { /* Just return as we will be redirected to login page */ return; } headers['User-Agent'] = 'Contrail-WebClient'; doNovaOpCb(reqUrl, apiProtoIP, tenantId, req, novaApi.get, stopRetry, function(err, tokenObj) { if ((err) || (null == tokenObj) || (null == tokenObj.id)) { callback(err, null); } else { headers['X-Auth-Token'] = tokenObj.id; novaAPIServer.api['hostname'] = apiProtoIP['ip']; novaAPIServer.api['port'] = apiProtoIP['port']; novaAPIServer.api.get(reqUrl, function(err, data) { if (err) { /* Just retry in case of if it fails, it may happen that failure is * due to token change, so give one more change */ if (stopRetry) { callback(err, data); } else { novaApi.get(reqUrl, apiProtoIP, req, callback, true); } } else { callback(err, data); } }, headers); } }); } /* Wrapper function to POST data to Nova-Server */ novaApi.post = function(reqUrl, reqData, apiProtoIP, req, callback, stopRetry) { var headers = {}; var i = 0; var tenantId = getTenantIdByReqCookie(req); if (null == tenantId) { /* Just return as we will be redirected to login page */ return; } headers['User-Agent'] = 'Contrail-WebClient'; doNovaOpCb(reqUrl, apiProtoIP, tenantId, req, novaApi.post, stopRetry, function(err, tokenObj) { if ((err) || (null == tokenObj) || (null == tokenObj.id)) { callback(err, null); } else { headers['X-Auth-Token'] = tokenObj.id; novaAPIServer.api['hostname'] = apiProtoIP['ip']; novaAPIServer.api['port'] = apiProtoIP['port']; novaAPIServer.api.post(reqUrl, reqData, function(err, data) { if (err) { /* Just retry in case of if it fails, it may happen that failure is * due to token change, so give one more change */ if (stopRetry) { callback(err, data); } else { novaApi.post(reqUrl, reqData, apiProtoIP, req, callback, true); } } else { callback(err, data); } }, headers); } }); } var novaAPIVerList = ['v1.1', 'v2']; var getVMStatsByProjectCB = { 'v1.1': getVMStatsByProjectV11, 'v2': getVMStatsByProjectV11 }; function getVMStatsByProjectV11 (err, data, callback) { callback(err, data); } var getServiceInstanceVMStatusCB = { 'v1.1': getServiceInstanceVMStatusV11, 'v2': getServiceInstanceVMStatusV11 } function getServiceInstanceVMStatusV11 (err, data, callback) { callback(err, data); } var getFlavorsCB = { 'v1.1': getFlavorsV11, 'v2': getFlavorsV11 }; function getFlavorsV11 (err, data, callback) { callback(err, data); } var launchVNCCB = { 'v1.1' : launchVNCV11, 'v2': launchVNCV11 }; function launchVNCV11 (error, data, callback) { if (error) { callback(error, null); } else { callback(null, data); } } function getNovaData (novaCallObj, callback) { var req = novaCallObj['req']; var reqUrl = novaCallObj['reqUrl']; var apiProtoIP = novaCallObj['ver']; novaApi.get(reqUrl, apiProtoIP, req, function(err, data) { callback(err, data); }, true); } function getVMStatsByProjectByAPIVersion (err, data, apiVer, callback) { var VMStatsByProjectCB = getVMStatsByProjectCB[apiVer]; if (null == VMStatsByProjectCB) { var str = 'Nova API Version not supported:' + apiVer; var error = new appErrors.RESTServerError(str); callback(error, null); return; } VMStatsByProjectCB(err, data, callback); } function getVMStatsByProject (projUUID, req, callback) { var tenantStr = getTenantIdByReqCookie(req); var novaCallObjArr = []; var reqUrl = null; authApi.getTokenObj(req, tenantStr, true, function(err, data) { if ((null != err) || (null == data) || (null == data['tenant'])) { logutils.logger.error("Error in getting token object for tenant: " + tenantStr); commonUtils.redirectToLogout(req, req.res); return; } var tenantId = data['tenant']['id']; oStack.getServiceAPIVersionByReqObj(req, global.SERVICE_ENDPT_TYPE_COMPUTE, function(apiVer) { if (null == apiVer) { error = new appErrors.RESTServerError('apiVersion for NOVA is NULL'); callback(error, null); return; } var reqUrlPrefix = '/' + tenantId + '/servers/detail'; var startIndex = 0; var fallbackIndex = novaAPIVerList.length - 1; novaApiGetByAPIVersionList(reqUrlPrefix, apiVer, req, startIndex, fallbackIndex, function(err, data, ver) { if (null != ver) { ver = ver['version']; } getVMStatsByProjectByAPIVersion(err, data, ver, callback); }); }); }); } function getServiceInstanceVMStatusByAPIVersion (err, data, apiVer, callback) { var serviceInstanceVMStatusCB = getServiceInstanceVMStatusCB[apiVer]; if (null == serviceInstanceVMStatusCB) { var str = 'Nova API Version not supported:' + apiVer; var error = new appErrors.RESTServerError(str); callback(error, null); return; } serviceInstanceVMStatusCB(err, data, callback); } function getServiceInstanceVMStatus (req, vmRefs, callback) { var tenantStr = getTenantIdByReqCookie(req); var novaCallObjArr = []; var reqUrl = null; authApi.getTokenObj(req, tenantStr, true, function(err, data) { if ((null != err) || (null == data) || (null == data['tenant'])) { logutils.logger.error("Error in getting token object for tenant: " + tenantStr); commonUtils.redirectToLogout(req, req.res); return; } var tenantId = data['tenant']['id']; var vmRefsCnt = vmRefs.length; oStack.getServiceAPIVersionByReqObj(req, global.SERVICE_ENDPT_TYPE_COMPUTE, function(apiVer) { if (null == apiVer) { error = new appErrors.RESTServerError('apiVersion for NOVA is NULL'); callback(error, null); return; } var reqUrlPrefix = '/' + tenantId + '/servers/' + vmRefs[0]['uuid']; var startIndex = 0; var fallbackIndex = novaAPIVerList.length - 1; novaApiGetByAPIVersionList(reqUrlPrefix, apiVer, req, startIndex, fallbackIndex, function (error, data, ver) { if ((null != error) || (null == data) || (null == ver)) { var err = new appErrors.RESTServerError('apiVersion for NOVA is NULL'); getServiceInstanceVMStatusByAPIVersion(err, null, null, callback); return; } for (var i = 0; i < vmRefsCnt; i++) { reqUrl = '/' + ver['version'] +'/' + tenantId + '/servers/' + vmRefs[i]['uuid']; novaCallObjArr[i] = {}; novaCallObjArr[i]['req'] = req; novaCallObjArr[i]['reqUrl'] = reqUrl; novaCallObjArr[i]['ver'] = ver; } async.map(novaCallObjArr, getNovaData, function(err, data) { getServiceInstanceVMStatusByAPIVersion(err, data, ver['version'], callback); }); }); }); }); } function launchVNCByAPIVersion (data, apiVer, callback) { var lnchCB = launchVNCCB[apiVer]; if (null == lnchCB) { var str = 'Nova API Version not supported:' + apiVer; var err = new appErrors.RESTServerError(str); callback(err, null); return; } lnchCB(err, data, callback); } function launchVNC (request, callback) { var projectId = null; var vmId = null; var requestParams = url.parse(request.url, true); authApi.getTokenObj(request, requestParams.query.project_id, true, function (error, data) { if (null != error) { logutils.logger.error("Error in getting token object for tenant: " + requestParams.query.project_id); } if (null == data) { logutils.logger.error("Trying to illegal access with tenantId: " + requestParams.query.project_id + " With session: " + request.session.id); } if ((null != error) || (null == data) || (null == data.tenant)) { commonUtils.redirectToLogout(request, request.res); return; } projectId = data.tenant.id; /* Now create the final req */ oStack.getServiceAPIVersionByReqObj(request, global.SERVICE_ENDPT_TYPE_COMPUTE, function(apiVer) { if (null == apiVer) { error = new appErrors.RESTServerError('apiVersion for NOVA is NULL'); callback(error, null); return; } var vncURL = '/' + projectId.toString() + "/servers/"; if (requestParams.query.vm_id) { vmId = requestParams.query.vm_id; vncURL += vmId.toString(); } var startIndex = 0; var fallbackIndex = novaAPIVerList.length - 1; novaApiGetByAPIVersionList(vncURL, apiVer, request, startIndex, fallbackIndex, function (error, data, ver) { if ((error) || (null == ver)) { callback(error, null); } else { vncURL = '/' + ver['version'] + vncURL; novaApi.post(vncURL + "/action", {"os-getVNCConsole":{"type":"novnc"}}, ver, request, function (error, data) { launchVNCByAPIVersion(data, ver['version'], callback); }); } }); }); }); } function getFlavorsByAPIVersion (err, data, apiVer, callback) { var flavorsCB = getFlavorsCB[apiVer]; if (null == flavorsCB) { if (null == err) { var str = 'Nova API Version not supported:' + apiVer; err = new appErrors.RESTServerError(str); } callback(err, null); return; } flavorsCB(err, data, callback); } function novaApiGetByAPIVersionList (reqUrlPrefix, apiVerList, req, startIndex, fallbackIndex, callback) { var apiVer = oStack.getApiVersion(novaAPIVerList, apiVerList, startIndex, fallbackIndex, global.label.COMPUTE_SERVER); if (null == apiVer) { var err = new appErrors.RESTServerError('apiVersion for NOVA is NULL'); callback(err, null); return; } httpsOp.apiProtocolList[global.label.COMPUTE_SERVER] = apiVer['protocol']; var reqUrl = '/' + apiVer['version'] + reqUrlPrefix; novaApi.get(reqUrl, apiVer, req, function(err, data) { if ((null != err) || (null == data)) { logutils.logger.error("novaAPI GET error:" + err); novaApiGetByAPIVersionList(reqUrlPrefix, apiVerList, req, startIndex + 1, fallbackIndex - 1, callback); } else { callback(null, data, apiVer); } }); } function getFlavors (req, callback) { var tenantStr = getTenantIdByReqCookie(req); if (null == tenantStr) { /* Just return as we will be redirected to login page */ return; } authApi.getTokenObj(req, tenantStr, true, function(err, data) { if ((null != err) || (null == data) || (null == data['tenant'])) { logutils.logger.error("Error in getting token object for tenant: " + tenantStr); commonUtils.redirectToLogout(req, req.res); return; } var tenantId = data['tenant']['id']; oStack.getServiceAPIVersionByReqObj(req, global.SERVICE_ENDPT_TYPE_COMPUTE, function(apiVer) { if (null == apiVer) { error = new appErrors.RESTServerError('apiVersion for NOVA is NULL'); callback(error, null); return; } var reqUrlPrefix = '/' + tenantId + '/flavors/detail'; var startIndex = 0; var fallbackIndex = novaAPIVerList.length - 1; novaApiGetByAPIVersionList(reqUrlPrefix, apiVer, req, startIndex, fallbackIndex, function(err, data, ver) { if (null != ver) { ver = ver['version']; } getFlavorsByAPIVersion(err, data, ver, callback); }); }); }); } exports.launchVNC = launchVNC; exports.getServiceInstanceVMStatus = getServiceInstanceVMStatus; exports.getVMStatsByProject = getVMStatsByProject; exports.getFlavors = getFlavors; exports.novaAPIVerList = novaAPIVerList;
manojgn/contrail-web-core
src/serverroot/orchestration/plugins/openstack/nova.api.js
JavaScript
apache-2.0
16,868
//// For registering Service Worker // if ('serviceWorker' in navigator) { // navigator.serviceWorker // .register('./service-worker.js', { scope: './' }) // .then(function(registration) { // console.log("Service Worker Registered"); // }) // .catch(function(err) { // console.log("Service Worker Failed to Register", err); // }) // } $(function(){ // Image Slider var leftarrow = $('.slider .left'); var rightarrow = $('.slider .right'); leftarrow.click(function(){ var left = $(this).siblings('.container').css('margin-left').replace('px', ''); left = parseInt(left)+250; if(left <= 50) $('.container').animate({'margin-left': left},500); }); rightarrow.click(function(){ var total = $(this).siblings('.container').children('.item').length; var left = $(this).siblings('.container').css('margin-left').replace('px', '') - 250; if(left >= -(total-5)*250) $('.container').animate({'margin-left': left},500); }); // Feedback Form var arrow = $('.chat-head img'); var textarea = $('.chat-text textarea'); arrow.on('click', function(){ var src = arrow.attr('src'); $('.chat-body').slideToggle('fast'); if(src == 'asset/img/down.png'){ arrow.attr('src', 'asset/img/up.png'); } else{ arrow.attr('src', 'asset/img/down.png'); } }); textarea.keypress(function(event) { var $this = $(this); if(event.keyCode == 13){ var msg = $this.val(); if(msg != ''){ $this.val(''); $('.msg-insert').prepend("<div class='msg-send'>"+msg+"</div>"); } else{alert('xfghjkl');} } }); });
Pahlaz/E-Mart
WebContent/asset/js/main.js
JavaScript
apache-2.0
1,624
'use strict'; angular.module('eventappApp') .config(function ($stateProvider) { $stateProvider .state('register', { parent: 'account', url: '/register', data: { roles: [], pageTitle: 'register.title' }, views: { 'content@': { templateUrl: 'scripts/app/account/register/register.html', controller: 'RegisterController' } }, resolve: { translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) { $translatePartialLoader.addPart('register'); return $translate.refresh(); }] } }); });
SaschaMoellering/event-app
src/main/webapp/scripts/app/account/register/register.js
JavaScript
apache-2.0
921
var interfaceorg_1_1onosproject_1_1net_1_1behaviour_1_1PortAdmin = [ [ "enable", "interfaceorg_1_1onosproject_1_1net_1_1behaviour_1_1PortAdmin.html#a4fa39b1dc477558945e9211986dabcf3", null ] ];
onosfw/apis
onos/apis/interfaceorg_1_1onosproject_1_1net_1_1behaviour_1_1PortAdmin.js
JavaScript
apache-2.0
197
/** * DO NOT EDIT THIS FILE as it will be overwritten by the Pbj compiler. * @link https://github.com/gdbots/pbjc-php * * Returns an array of curies using mixin "gdbots:ncr:mixin:node-marked-as-draft:v1" * @link http://schemas.triniti.io/json-schema/gdbots/ncr/mixin/node-marked-as-draft/1-0-0.json# */ export default [ ];
triniti/schemas
build/js/src/manifests/gdbots/ncr/mixin/node-marked-as-draft/v1.js
JavaScript
apache-2.0
330
function HtmlElementsPlugin(locations) { this.locations = locations; } HtmlElementsPlugin.prototype.apply = function(compiler) { var self = this; compiler.plugin('compilation', function(compilation) { compilation.options.htmlElements = compilation.options.htmlElements || {}; compilation.plugin('html-webpack-plugin-before-html-generation', function(htmlPluginData, callback) { const locations = self.locations; if (locations) { const publicPath = htmlPluginData.assets.publicPath; Object.getOwnPropertyNames(locations).forEach(function(loc) { compilation.options.htmlElements[loc] = getHtmlElementString(locations[loc], publicPath); }); } callback(null, htmlPluginData); }); }); }; const RE_ENDS_WITH_BS = /\/$/; /** * Create an HTML tag with attributes from a map. * * Example: * createTag('link', { rel: "manifest", href: "/assets/manifest.json" }) * // <link rel="manifest" href="/assets/manifest.json"> * @param tagName The name of the tag * @param attrMap A Map of attribute names (keys) and their values. * @param publicPath a path to add to eh start of static asset url * @returns {string} */ function createTag(tagName, attrMap, publicPath) { publicPath = publicPath || ''; // add trailing slash if we have a publicPath and it doesn't have one. if (publicPath && !RE_ENDS_WITH_BS.test(publicPath)) { publicPath += '/'; } const attributes = Object.getOwnPropertyNames(attrMap) .filter(function(name) { return name[0] !== '='; } ) .map(function(name) { var value = attrMap[name]; if (publicPath) { // check if we have explicit instruction, use it if so (e.g: =herf: false) // if no instruction, use public path if it's href attribute. const usePublicPath = attrMap.hasOwnProperty('=' + name) ? !!attrMap['=' + name] : name === 'href'; if (usePublicPath) { // remove a starting trailing slash if the value has one so we wont have // value = publicPath + (value[0] === '/' ? value.substr(1) : value); } } return name + '="' + value + '"'; }); return '<' + tagName + ' ' + attributes.join(' ') + '>'; } /** * Returns a string representing all html elements defined in a data source. * * Example: * * const ds = { * link: [ * { rel: "apple-touch-icon", sizes: "57x57", href: "/assets/icon/apple-icon-57x57.png" } * ], * meta: [ * { name: "msapplication-TileColor", content: "#00bcd4" } * ] * } * * getHeadTags(ds); * // "<link rel="apple-touch-icon" sizes="57x57" href="/assets/icon/apple-icon-57x57.png">" * "<meta name="msapplication-TileColor" content="#00bcd4">" * * @returns {string} */ function getHtmlElementString(dataSource, publicPath) { return Object.getOwnPropertyNames(dataSource) .map(function(name) { if (Array.isArray(dataSource[name])) { return dataSource[name].map(function(attrs) { return createTag(name, attrs, publicPath); } ); } else { return [ createTag(name, dataSource[name], publicPath) ]; } }) .reduce(function(arr, curr) { return arr.concat(curr); }, []) .join('\n\t'); } module.exports = HtmlElementsPlugin;
bulktrade/SMSC
modules/admin/config/html-elements-plugin/index.js
JavaScript
apache-2.0
3,533
export function searchToObject(search) { const params = {}; if (search) { search.slice(1).split('&').forEach((param) => { const [name, value] = param.split('='); params[name] = decodeURIComponent(value); }); } return params; } export function getLocationParams() { return searchToObject(window.location.search); } // export function replaceLocationParams (params) { // const search = Object.keys(params) // .map(name => `${name}=${encodeURIComponent(params[name])}`).join('&'); // window.history.pushState(undefined, undefined, `?${search}`); // }
ericsoderberg/pbc-web
ui/js/utils/Params.js
JavaScript
apache-2.0
587
/** * Module dependencies */ var httpStatus = require('../helpers/http-status') , User = require('mongoose').model('User') , logger = require('../../logger'); exports.login = function (req, res) { res.render('users/login', {title: 'login'}); }; exports.checkAuth = function (req, res, next) { var errors = []; ['username', 'password'].forEach(function (prop) { if (!req.body[prop] || req.body[prop].trim() === '') { errors.push({ error: 'empty', expected: 'not empty', value: req.body[prop] || '', field: prop, msg: prop + ' field is empty' }); } }); if (errors.length > 0) { return checkAccessTokenAuth(req, res, function () { res.send(httpStatus.BAD_REQUEST, { errors: errors }); }); } next(); }; function checkAccessTokenAuth(req, res, next) { var accessToken = req.get('Authorization') || req.query.Authorization; if (accessToken && accessToken !== '') { logger.log('info', 'Trying authentication with accessToken=[%s]', accessToken); User.findByAccessToken(accessToken, function (err, user) { if (user && user.hasAccessToken(accessToken)) { logger.log('info', 'Access token authentication successful for user=[%s]', user.username); req.accessToken = accessToken.replace('Justbrew ', ''); req.user = user; return authenticate(req, res, next); //valid access token } logger.log('warn', 'Access token authentication invalid for token=[%s]', accessToken); return res.send(httpStatus.UNAUTHORIZED); //invalid access token }); return; } next(); } function authenticate(req, res) { var accessToken = req.accessToken || req.user.newAccessToken(); var user = { id: req.user.id, name: req.user.name, email: req.user.email, username: req.user.username }; var ret = { user: user, accessToken: accessToken }; res.format({ html: function () { return res.redirect('/?Authorization=' + accessToken); }, json: function () { return res.json(httpStatus.OK, ret); } }); } exports.authenticate = authenticate;
orapouso/justbrew
app/controllers/users.js
JavaScript
apache-2.0
2,135
import Koa from 'koa' import body from 'koa-bodyparser' import convert from 'koa-convert' import cors from 'koa-cors' import mongoose from 'mongoose' import config from './config' import mongooseConfig from './config/mongoose' import routeRegistry from './routeRegistry' const app = new Koa() app.context.db = mongoose mongooseConfig() app.on('error', (err, context) => { console.error(`Server error: ${err} \nContext: ${context}`) }) app.use(body()) app.use(convert(cors({ origin: true, methods: ['OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'] }))) app.use(async function (ctx, next) { const start = new Date() await next() const ms = new Date() - start ctx.set(`X-Response-Time: ${ms}`) ctx.set('X-Server: node') }) app.use(async function (ctx, next) { const start = new Date() await next() const ms = new Date() - start console.info(`${ctx.method} ${ctx.url} - ${ms}ms`) }) routeRegistry(app) const { server } = config app.listen(server.port, () => console.log(`Server started at http://localhost:${server.port}`)) // export default app
grenti/pacci-api
src/server.js
JavaScript
apache-2.0
1,075
var quickconnect = require('rtc-quickconnect'); var mesh = require('../../'); var Model = require('scuttlebutt/model'); module.exports = function(roomId, members, opts) { return function(t) { var model; var qc; t.plan(1); qc = quickconnect(window.location.origin, { room: roomId }); // create the mesh participant members.push(model = mesh(qc, opts)); t.ok(model instanceof Model, 'successfully created scuttlebutt model'); }; };
rtc-io/rtc-mesh
test/helpers/joinmesh.js
JavaScript
apache-2.0
475