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
/** * A script for handling the bootstrap switch on the resume page. */ // Import css. require("bootstrap-switch/dist/css/bootstrap3/bootstrap-switch.min.css"); require('bootstrap-switch'); $("[name='my-checkbox']").bootstrapSwitch(); // http://www.bootstrap-switch.org/events.html $('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) { var img = document.getElementById("resume-image"); var pdf_link = document.getElementById('pdf_link'); if (state) { img.src = "/Content/Resume/resume.png"; // Changes the download link. pdf_link.href = "/Content/Resume/resume.pdf"; pdf_link.download = 'MattGaikemaResume'; } else { img.src = "/Content/Resume/cv.png"; pdf_link.href = "/Content/Resume/cv.pdf"; pdf_link.download = 'MattGaikemaCV'; } });
TexAgg/website
website/Scripts/resume/resumeButtons.js
JavaScript
gpl-3.0
808
/* * Copyright (C) 2016-2021 phantombot.github.io/PhantomBot * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * lang.js * * Provide a language API * Use the $.lang API * * NOTE: Reading from/writing to the lang data directly is not possbile anymore! * Use the register(), exists() and get() functions! */ (function() { var data = [], curLang = ($.inidb.exists('settings', 'lang') ? $.inidb.get('settings', 'lang') : 'english'); /** * @function load */ function load(force) { $.bot.loadScriptRecursive('./lang/english', true, (force ? force : false)); if (curLang != 'english') { $.bot.loadScriptRecursive('./lang/' + curLang, true, (force ? force : false)); } if ($.isDirectory('./scripts/lang/custom')) { $.bot.loadScriptRecursive('./lang/custom', true, (force ? force : false)); } // Set "response_@chat" to true if it hasn't been set yet, so the bot isn't muted when using a fresh install if (!$.inidb.exists('settings', 'response_@chat')) { $.setIniDbBoolean('settings', 'response_@chat', true); } } /** * @function register * @export $.lang * @param {string} key * @param {string} string */ function register(key, string) { if (key && string) { data[key.toLowerCase()] = string; } if (key && string.length === 0) { data[key.toLowerCase()] = '<<EMPTY_PLACEHOLDER>>'; } } /** * @function get * @export $.lang * @param {string} key * @returns {string} */ function get(key) { var string = data[key.toLowerCase()], i; if (string === undefined) { $.log.warn('Lang string for key "' + key + '" was not found.'); return ''; } if (string == '<<EMPTY_PLACEHOLDER>>') { return ''; } for (i = 1; i < arguments.length; i++) { while (string.indexOf("$" + i) >= 0) { string = string.replace("$" + i, arguments[i]); } } return string; } /** * @function paramCount * @export $.lang * @param {string} key * @returns {Number} */ function paramCount(key) { var string = data[key.toLowerCase()], i, ctr = 0; if (!string) { return 0; } for (i = 1; i < 99; i++) { if (string.indexOf("$" + i) >= 0) { ctr++; } else { break; } } return ctr; } /** * @function exists * @export $.lang * @param {string} key * @returns {boolean} */ function exists(key) { return (data[key.toLowerCase()]); } /** * @event command */ $.bind('command', function(event) { var sender = event.getSender().toLowerCase(), command = event.getCommand(), args = event.getArgs(), action = args[0], inversedState; /** * @commandpath lang [language name] - Get or optionally set the current language (use folder name from "./lang" directory); */ if (command.equalsIgnoreCase('lang')) { if (!action) { $.say($.whisperPrefix(sender) + get('lang.curlang', curLang)); } else { action = action.toLowerCase(); if (!$.fileExists('./scripts/lang/' + action + '/main.js')) { $.say($.whisperPrefix(sender) + get('lang.lang.404')); } else { $.inidb.set('settings', 'lang', action); curLang = action; load(true); $.say($.whisperPrefix(sender) + get('lang.lang.changed', action)); } } } /** * @commandpath mute - Toggle muting the bot in the chat */ if (command.equalsIgnoreCase('mute')) { inversedState = !$.getIniDbBoolean('settings', 'response_@chat'); $.setIniDbBoolean('settings', 'response_@chat', inversedState); $.reloadMisc(); $.say($.whisperPrefix(sender) + (inversedState ? get('lang.response.enabled') : get('lang.response.disabled'))); } /** * @commandpath toggleme - Toggle prepending chat output with "/me". */ if (command.equalsIgnoreCase('toggleme')) { inversedState = !$.getIniDbBoolean('settings', 'response_action'); $.setIniDbBoolean('settings', 'response_action', inversedState); $.reloadMisc(); $.say($.whisperPrefix(sender) + (inversedState ? get('lang.response.action.enabled') : get('lang.response.action.disabled'))); } }); /** * @event initReady */ $.bind('initReady', function() { $.registerChatCommand('./core/lang.js', 'lang', 1); $.registerChatCommand('./core/lang.js', 'mute', 1); $.registerChatCommand('./core/lang.js', 'toggleme', 1); }); /** Export functions to API */ $.lang = { exists: exists, get: get, register: register, paramCount: paramCount }; // Run the load function to enable modules, loaded after lang.js, to access the language strings immediatly load(); })();
Stargamers/PhantomBot
javascript-source/core/lang.js
JavaScript
gpl-3.0
6,046
(function (root, factory) { if (typeof module === 'object' && module.exports) { module.exports = factory(require('jquery'), require('../common/utility')); } else { root.api = factory(root.jQuery, root.utility); } }(this, function ($, util) { // API var self = {}; // Object -> Promise[[Entity]] self.searchEntity = function(query){ return get('/search/entity', { num: 10, q: query }) .then(format) .catch(handleError); // [Entity] -> [Entity] function format(results){ // stringify id & rename keys (`primary_type` -> `primary_ext`; `description` -> `blurb`) return results.map(function(result) { var _result = Object.assign({}, result, { primary_ext: result.primary_ext || result.primary_type, blurb: result.blurb || result.description, id: String(result.id) }); delete _result.primary_type; delete _result.description; return _result; }); } // Error -> [] function handleError(err){ console.error('API request error: ', err); return []; } }; // [EntityWithoutId] -> Promise[[Entity]] self.createEntities = function(entities){ return post('/entities/bulk', formatReq(entities)) .then(formatResp); // [Entity] -> [Entity] function formatReq(entities){ return { data: entities.map(function(entity){ return { type: "entities", attributes: entity }; }) }; }; // [Entity] -> [Entity] function formatResp(resp){ // copy, but stringify id return resp.data.map(function(datum){ return Object.assign( datum.attributes, { id: String(datum.attributes.id)} ); }); } }; // Integer, [Integer] -> Promise[[ListEntity]] self.addEntitiesToList = function(listId, entityIds, reference){ return post('/lists/'+listId+'/entities/bulk', formatReq(entityIds)) .then(formatResp); function formatReq(entityIds){ return { data: entityIds.map(function(id){ return { type: 'entities', id: id }; }).concat({ type: 'references', attributes: reference }) }; }; function formatResp(resp){ return resp.data.map(function(datum){ return util.stringifyValues(datum.attributes); }); } }; // String, Integer -> Promise // helpers function get(url, queryParams){ return fetch(url + qs(queryParams), { headers: headers(), method: 'get', credentials: 'include' // use auth tokens stored in session cookies }).then(jsonify); } function post(url, payload){ return fetch(url, { headers: headers(), method: 'post', credentials: 'include', // use auth tokens stored in session cookies body: JSON.stringify(payload) }).then(jsonify); }; function patch(url, payload){ return fetch(url, { headers: headers(), method: 'PATCH', credentials: 'include', // use auth tokens stored in session cookies body: JSON.stringify(payload) }).then(function(response) { if (response.body) { return jsonify(response); } else { return response; } }); }; function headers(){ return { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'Littlesis-Request-Type': 'API', // TODO: retrieve this w/o JQuery 'X-CSRF-Token': $("meta[name='csrf-token']").attr("content") || "" }; } function qs(queryParams){ return '?' + $.param(queryParams); } // Response -> Promise[Error|JSON] function jsonify(response){ return response .json() .then(function(json){ return json.errors ? Promise.reject(json.errors[0].title) : Promise.resolve(json); }); } return self; }));
public-accountability/littlesis-rails
app/javascript/src/common/api.js
JavaScript
gpl-3.0
3,991
import VK from 'VK'; import { VK_API_VERSION } from '../constants'; /** * Fetch friends. * @param {Object} options * @return {Promise<Object>} */ export function fetchFriends(options = {}) { const mergedOptions = { ...options, order: 'hints', fields: 'photo_100', v: VK_API_VERSION, }; return new Promise((resolve, reject) => { VK.api('friends.get', mergedOptions, response => { if (response.response) resolve(response.response); else reject(response.error); }); }); }
AlexeySmolyakov/likeometer-redux
src/api/friends.js
JavaScript
gpl-3.0
519
/** @ignore */ Kekule.LOCAL_RES = true; Kekule.Localization.setCurrModule("widget"); Kekule.Localization.addResource("zh", "WidgetTexts", { "CAPTION_OK": "确定", "CAPTION_CANCEL": "取消", "CAPTION_YES": "是", "CAPTION_NO": "否", "CAPTION_BROWSE_COLOR": "浏览颜色", "HINT_BROWSE_COLOR": "浏览更多颜色", "S_COLOR_UNSET": "(未设置)", "S_COLOR_DEFAULT": "(缺省值)", "S_COLOR_MIXED": "(多个值)", "S_COLOR_TRANSPARENT": "(透明)", "S_OBJECT_UNSET": "(无)", "S_ITEMS": "条目", "S_OBJECT": "对象", "S_VALUE_UNSET": "(未设置)", "CAPTION_MENU": "Menu", "HINT_MENU": "Open menu", "S_INSPECT_NONE": "(无)", "S_INSPECT_OBJECTS": "({0}个对象)", "S_INSPECT_ID_OBJECT": "{0}: {1}", "S_INSPECT_ANONYMOUS_OBJECT": "({0})", "CAPTION_TOGGLE_TEXTWRAP": "切换文本换行", "CAPTION_INC_TEXT_SIZE": "增大字号", "CAPTION_DEC_TEXT_SIZE": "减小字号", "HINT_TOGGLE_TEXTWRAP": "切换文本是否自动换行", "HINT_INC_TEXT_SIZE": "增大字号", "HINT_DEC_TEXT_SIZE": "减小字号", "HINT_CHOOSE_FONT_FAMILY": "选择字体", "CAPTION_FIRST_PAGE": "首页", "CAPTION_LAST_PAGE": "末页", "CAPTION_PREV_PAGE": "前一页", "CAPTION_NEXT_PAGE": "后一页", "HINT_FIRST_PAGE": "首页", "HINT_LAST_PAGE": "末页", "HINT_PREV_PAGE": "前一页", "HINT_NEXT_PAGE": "后一页", "HINT_CURR_PAGE": "当前页", "MSG_RETRIEVING_DATA": "载入数据…", "CAPTION_DATATABLE_EDIT": "编辑", "CAPTION_DATATABLE_DELETE": "删除", "CAPTION_DATATABLE_INSERT": "插入", "HINT_DATATABLE_EDIT": "编辑数据", "HINT_DATATABLE_DELETE": "删除数据", "HINT_DATATABLE_INSERT": "插入数据", "CAPTION_ADD_CELL": "+", "HINT_ADD_CELL": "添加新单元格", "CAPTION_REMOVE_CELL": "移除", "HINT_REMOVE_CELL": "移除单元格", "CAPTION_CONFIG": "设置…", "HINT_CONFIG": "修改设置" }); Kekule.Localization.addResource("zh", "ChemWidgetTexts", { "CAPTION_CLEAROBJS": "清除", "CAPTION_LOADFILE": "载入…", "CAPTION_LOADDATA": "载入…", "CAPTION_SAVEFILE": "保存…", "CAPTION_ZOOMIN": "放大", "CAPTION_ZOOMOUT": "缩小", "CAPTION_RESETZOOM": "重置缩放", "CAPTION_RESETVIEW": "重置", "CAPTION_ROTATE": "旋转", "CAPTION_ROTATELEFT": "向左旋转", "CAPTION_ROTATERIGHT": "向右旋转", "CAPTION_ROTATEX": "沿X轴旋转", "CAPTION_ROTATEY": "沿Y轴旋转", "CAPTION_ROTATEZ": "沿Z轴旋转", "CAPTION_MOL_DISPLAY_TYPE": "分子显示样式", "CAPTION_SKELETAL": "键线式", "CAPTION_CONDENSED": "缩写式", "CAPTION_WIRE": "单线模型", "CAPTION_STICKS": "棍式模型", "CAPTION_BALLSTICK": "球棍模型", "CAPTION_SPACEFILL": "比例模型", "CAPTION_HIDEHYDROGENS": "显示/隐藏氢原子", "CAPTION_OPENEDITOR": "编辑…", "CAPTION_EDIT_OBJ": "编辑", "HINT_CLEAROBJS": "清除对象", "HINT_LOADFILE": "自文件载入", "HINT_LOADDATA": "载入数据", "HINT_SAVEFILE": "存储到文件", "HINT_ZOOMIN": "放大", "HINT_ZOOMOUT": "缩小", "HINT_RESETZOOM": "重置缩放", "HINT_RESETVIEW": "重置缩放与旋转", "HINT_ROTATE": "旋转", "HINT_ROTATELEFT": "逆时针旋转", "HINT_ROTATERIGHT": "顺时针旋转", "HINT_ROTATEX": "沿X轴旋转", "HINT_ROTATEY": "沿Y轴旋转", "HINT_ROTATEZ": "沿Z轴旋转", "HINT_MOL_DISPLAY_TYPE": "改变分子显示样式", "HINT_SKELETAL": "以键线式显示", "HINT_CONDENSED": "以缩写式显示", "HINT_WIRE": "以单线模型显示", "HINT_STICKS": "以棍式模型显示", "HINT_BALLSTICK": "以球棍模型显示", "HINT_SPACEFILL": "以比例模型显示", "HINT_HIDEHYDROGENS": "模型中显示/隐藏氢原子", "HINT_OPENEDITOR": "编辑当前对象", "CAPTION_NEWDOC": "新建", "CAPTION_UNDO": "撤销", "CAPTION_REDO": "重做", "CAPTION_COPY": "复制", "CAPTION_CUT": "剪切", "CAPTION_PASTE": "粘贴", "CAPTION_CLONE_SELECTION": "克隆选区", "CAPTION_TOGGLE_INSPECTOR": "对象检视器", "CAPTION_MANIPULATE": "选取", "CAPTION_ERASE": "删除", "CAPTION_MOL_BOND": "键", "CAPTION_MOL_BOND_SINGLE": "单键", "CAPTION_MOL_BOND_DOUBLE": "双键", "CAPTION_MOL_BOND_TRIPLE": "三键", "CAPTION_MOL_BOND_WEDGEUP": "实楔线键", "CAPTION_MOL_BOND_WEDGEDOWN": "虚楔线键", "CAPTION_MOL_BOND_CLOSER": "突出(加粗)键", "CAPTION_MOL_BOND_WAVY": "波浪键", "CAPTION_MOL_BOND_DOUBLE_EITHER": "顺或反式双键", "CAPTION_MOL_ATOM": "原子", "CAPTION_MOL_FORMULA": "分子式", "CAPTION_MOL_CHARGE": "电荷", "CAPTION_MOL_CHARGE_CLEAR": "清除电荷", "CAPTION_MOL_CHARGE_POSITIVE": "正电荷", "CAPTION_MOL_CHARGE_NEGATIVE": "负电荷", "CAPTION_MOL_CHARGE_SINGLET": "单线态", "CAPTION_MOL_CHARGE_DOUBLET": "双线态自由基", "CAPTION_MOL_CHARGE_TRIPLET": "三线态", "CAPTION_TEXT_BLOCK": "文本", "CAPTION_REPOSITORY_RING": "环", "CAPTION_REPOSITORY_RING_3": "环丙烷", "CAPTION_REPOSITORY_RING_4": "环丁烷", "CAPTION_REPOSITORY_RING_5": "环戊烷", "CAPTION_REPOSITORY_RING_6": "环己烷", "CAPTION_REPOSITORY_RING_7": "环庚烷", "CAPTION_REPOSITORY_RING_8": "环辛烷", "CAPTION_REPOSITORY_RING_AR_6": "苯", "CAPTION_REPOSITORY_RING_AR_5": "环戊二烯", "CAPTION_REPOSITORY_ARROWLINE": "线段与箭头", "CAPTION_REPOSITORY_GLYPH": "图符", "CAPTION_REPOSITORY_GLYPH_LINE": "直线", "CAPTION_REPOSITORY_GLYPH_OPEN_ARROW_LINE": "开放箭头线", "CAPTION_REPOSITORY_GLYPH_TRIANGLE_ARROW_LINE": "三角箭头线", "CAPTION_REPOSITORY_GLYPH_DI_OPEN_ARROW_LINE": "双向开放箭头线", "CAPTION_REPOSITORY_GLYPH_DI_TRIANGLE_ARROW_LINE": "双向三角箭头线", "CAPTION_REPOSITORY_GLYPH_REV_ARROW_LINE": "可逆箭头线", "CAPTION_REPOSITORY_GLYPH_OPEN_ARROW_DILINE": "开放箭头双线", "CAPTION_REPOSITORY_HEAT_SYMBOL": "加热符号", "CAPTION_REPOSITORY_ADD_SYMBOL": "加号", "CAPTION_PICK_COLOR": "颜色", "CAPTION_TEXT_DIRECTION": "文字方向", "CAPTION_TEXT_DIRECTION_DEFAULT": "缺省", "CAPTION_TEXT_DIRECTION_LTR": "由左至右", "CAPTION_TEXT_DIRECTION_RTL": "由右至左", "CAPTION_TEXT_DIRECTION_TTB": "由上至下", "CAPTION_TEXT_DIRECTION_BTT": "由下至上", "CAPTION_TEXT_HORIZONTAL_ALIGN": "文字水平对齐", "CAPTION_TEXT_VERTICAL_ALIGN": "文字垂直对齐", "CAPTION_TEXT_ALIGN_DEFAULT": "缺省", "CAPTION_TEXT_ALIGN_LEADING": "首对齐", "CAPTION_TEXT_ALIGN_TRAILING": "尾对齐", "CAPTION_TEXT_ALIGN_CENTER": "居中对齐", "CAPTION_TEXT_ALIGN_LEFT": "左对齐", "CAPTION_TEXT_ALIGN_RIGHT": "右对齐", "CAPTION_TEXT_ALIGN_TOP": "上对齐", "CAPTION_TEXT_ALIGN_BOTTOM": "下对齐", "HINT_NEWDOC": "创建新文档", "HINT_UNDO": "撤销", "HINT_REDO": "重做", "HINT_COPY": "将选定对象复制至内部剪贴板", "HINT_CUT": "将选定对象剪切至内部剪贴板", "HINT_PASTE": "自内部剪贴板复制", "HINT_CLONE_SELECTION": "克隆当前选区", "HINT_TOGGLE_INSPECTOR": "显示或隐藏对象检视器", "HINT_MANIPULATE": "选择工具", "HINT_ERASE": "删除工具", "HINT_MOL_BOND": "化学键工具", "HINT_MOL_BOND_SINGLE": "单键", "HINT_MOL_BOND_DOUBLE": "双键", "HINT_MOL_BOND_TRIPLE": "叁键", "HINT_MOL_BOND_WEDGEUP": "实楔线键", "HINT_MOL_BOND_WEDGEDOWN": "虚楔线键", "HINT_MOL_BOND_CLOSER": "突出(加粗)键", "HINT_MOL_BOND_WAVY": "波浪键", "HINT_MOL_BOND_DOUBLE_EITHER": "顺或反式双键", "HINT_MOL_ATOM": "原子工具", "HINT_MOL_FORMULA": "分子式工具", "HINT_MOL_CHARGE": "电荷工具", "HINT_MOL_CHARGE_CLEAR": "清除电荷或自由基", "HINT_MOL_CHARGE_POSITIVE": "正电荷", "HINT_MOL_CHARGE_NEGATIVE": "负电荷", "HINT_MOL_CHARGE_SINGLET": "单线态自由基", "HINT_MOL_CHARGE_DOUBLET": "双线态自由基", "HINT_MOL_CHARGE_TRIPLET": "三线态自由基", "HINT_TEXT_BLOCK": "文字工具", "HINT_REPOSITORY_RING": "环工具", "HINT_REPOSITORY_RING_3": "环丙烷", "HINT_REPOSITORY_RING_4": "环丁烷", "HINT_REPOSITORY_RING_5": "环戊烷", "HINT_REPOSITORY_RING_6": "环己烷", "HINT_REPOSITORY_RING_7": "环庚烷", "HINT_REPOSITORY_RING_8": "环辛烷", "HINT_REPOSITORY_RING_AR_6": "苯", "HINT_REPOSITORY_RING_AR_5": "环戊二烯", "HINT_REPOSITORY_ARROWLINE": "线段与箭头", "HINT_REPOSITORY_GLYPH": "图符", "HINT_REPOSITORY_GLYPH_LINE": "直线", "HINT_REPOSITORY_GLYPH_OPEN_ARROW_LINE": "开放箭头线", "HINT_REPOSITORY_GLYPH_TRIANGLE_ARROW_LINE": "三角箭头线", "HINT_REPOSITORY_GLYPH_DI_OPEN_ARROW_LINE": "双向开放箭头线", "HINT_REPOSITORY_GLYPH_DI_TRIANGLE_ARROW_LINE": "双向三角箭头线", "HINT_REPOSITORY_GLYPH_REV_ARROW_LINE": "可逆箭头线", "HINT_REPOSITORY_GLYPH_OPEN_ARROW_DILINE": "开放箭头双线", "HINT_REPOSITORY_HEAT_SYMBOL": "加热符号", "HINT_REPOSITORY_ADD_SYMBOL": "加号", "HINT_FONTNAME": "设置字体", "HINT_FONTSIZE": "设置字号", "HINT_PICK_COLOR": "选择颜色", "HINT_TEXT_DIRECTION": "设置文字方向", "HINT_TEXT_HORIZONTAL_ALIGN": "设置文字水平对齐方式", "HINT_TEXT_VERTICAL_ALIGN": "设置文字水平垂直方式", "CAPTION_LOADDATA_DIALOG": "载入数据", "CAPTION_DATA_FORMAT": "数据格式:", "CAPTION_DATA_SRC": "在下方输入或粘贴数据:", "CAPTION_LOADDATA_FROM_FILE": "载入文件", "CAPTION_CHOOSEFILEFORMAT": "选择文件格式", "CAPTION_SELECT_FORMAT": "选择格式:", "CAPTION_PREVIEW_FILE_CONTENT": "预览文件内容…", "S_DEF_SAVE_FILENAME": "Unnamed", "CAPTION_ATOMLIST_PERIODIC_TABLE": "更多…", "CAPTION_RGROUP": "取代基", "CAPTION_VARIABLE_ATOM": "(包含)原子列表", "CAPTION_VARIABLE_NOT_ATOM": "(不包含)原子列表", "CAPTION_PSEUDOATOM": "赝原子(Pseudoatom)", "CAPTION_DUMMY_ATOM": "虚原子(Dummy atom)", "CAPTION_HETERO_ATOM": "杂原子", "CAPTION_ANY_ATOM": "任意原子", "CAPTION_PERIODIC_TABLE_DIALOG": "元素周期表", "CAPTION_PERIODIC_TABLE_DIALOG_SEL_ELEM": "选择元素", "CAPTION_PERIODIC_TABLE_DIALOG_SEL_ELEMS": "选择多个元素", "CAPTION_TEXTBLOCK_INIT": "在此输入文字", "LEGEND_CAPTION": "图例", "LEGEND_ELEM_SYMBOL": "元素符号", "LEGEND_ELEM_NAME": "名称", "LEGEND_ATOMIC_NUM": "原子序数", "LEGEND_ATOMIC_WEIGHT": "原子量", "CAPTION_2D": "2D", "CAPTION_3D": "3D", "CAPTION_AUTOSIZE": "自动尺寸", "CAPTION_AUTOFIT": "自动缩放", "CAPTION_SHOWSIZEINFO": "显示尺寸信息", "CAPTION_LABEL_SIZE": "尺寸:", "CAPTION_BACKGROUND_COLOR": "背景颜色:", "CAPTION_WIDTH_HEIGHT": "宽:{0}、高:{1}", "PLACEHOLDER_WIDTH": "宽", "PLACEHOLDER_HEIGHT": "高", "HINT_AUTOSIZE": "图形尺寸是否由对象大小自动调整", "HINT_AUTOFIT": "对象是否填满图形区域", "S_VALUE_DEFAULT": "(缺省)" }); Kekule.Localization.addResource("zh", "ErrorMsg", { "WIDGET_CLASS_NOT_FOUND": "控件类不存在", "WIDGET_CAN_NOT_BIND_TO_ELEM": "控件{0}无法绑定到HTML元素<{1}>", "LOAD_CHEMDATA_FAILED": "载入数据失败", "FILE_API_NOT_SUPPORTED": "您当前的浏览器不支持HTML文件操作,请升级浏览器。", "DRAW_BRIDGE_NOT_SUPPORTED": "您当前的浏览器不支持该绘图功能,请升级浏览器。", "COMMAND_NOT_REVERSIBLE": "命令无法撤销", "PAGE_INDEX_OUTOF_RANGE": "页面超出范围", "FETCH_DATA_TIMEOUT": "加载数据超时", "RENDER_TYPE_CHANGE_NOT_ALLOWED": "渲染类型无法改变", "CAN_NOT_CREATE_EDITOR": "创建编辑器失败", "CAN_NOT_SET_COORD_OF_CLASS": "无法设置对象{0}实例的坐标", "CAN_NOT_SET_DIMENSION_OF_CLASS": "无法设置对象{0}实例的尺寸", "CAN_NOT_MERGE_CONNECTORS": "化学键或连接符无法合并", "NOT_A_VALID_ATOM": "无效的原子", "INVALID_ATOM_SYMBOL": "原子符号无效" });
deepchem/deepchem-gui
gui/static/kekulejs/src/localization/zh/kekule.localize.widget.zh.js
JavaScript
gpl-3.0
12,211
var repl = repl || {}; repl.prompt = "> "; repl.cont = "+\t"; repl.command = {}; load(":/resources/core.js"); soft_version = "SOFT v" + version() + " "; soft_license = "GNU LESSER GENERAL PUBLIC LICENSE (v 2.1, February 1999)"; function showHelp() { var message = soft_version + "(" + soft_license + ")\n\n" + "Welcome to Soft Shell\n" + "Shell commands:\n" + ":h This message\n"+ ":ld <file> Load and evaluate file <file>\n" + ":chk <file> Checks the syntax of the program <file>\n" + ":q Quit the shell\n\n"; print (message); } function quit() { repl.exit = true; print ("Bye"); } repl.command['q'] = quit; repl.command['quit'] = quit; repl.command['ld'] = load; repl.command['chk'] = checkSyntax; repl.command['h'] = showHelp; repl.command['help'] = showHelp; function parseCommand(cmd) { if( cmd != undefined ) { var command = cmd[1]; if( command !== undefined && repl.command[command] !== undefined) { repl.command[command](cmd[2]); return true; } else { print("Unknown command " + command); } } return undefined; } function mainrepl() { var s = ""; while(repl.exit === undefined) { try { if( s.length == 0 ) writeline(repl.prompt); s += readline(); cmd = s.match(/^[\:]([a-zA-Z]*)\s?(\S*)/); if( cmd != undefined ) { s = ""; parseCommand(cmd); } else { if( s.trim().length == 0 ) continue; if( isIncompleteSyntax(s) || s[s.length-1] == '\\' ) { if(s[s.length-1] == '\\') { s = s.substring(0,s.length-1); } writeline(repl.cont); } else { ret = eval(s); s = ""; if(!isQObject(ret) && isObject(ret)) { print(JSON.stringify(ret, null, 2)); } else if( ret != undefined) print(ret); else print('undefined'); } } } catch (err) { if (isIncompleteSyntax(s)) continue; print (err); s = ""; } } } function __main__() { var message = soft_version + "(" + soft_license + ")\n\n" + "For help, type :help\n"; print(message); mainrepl(); return 0; }
NanoSim/Porto
tools/src/softshell/resources/repl.js
JavaScript
gpl-3.0
2,146
import { Meteor } from 'meteor/meteor'; import '../images.js'; import { Devs } from '../../devs/devs.js'; import { Teams } from '../../teams/teams.js'; import { Visitors } from '../../visitors/visitors.js'; import { Sponsors } from '../../sponsors/sponsors.js'; Meteor.publish('profile.image', function(id){ let d = Devs.findOne({"user":id}); //console.log(Images.findOne({"_id":d.picture})); return Images.find({"_id":d.picture}).cursor; }); Meteor.publish('profile.image.user', function(username){ let u = Meteor.users.findOne({"username":username}); let d = Devs.findOne({"user":u._id}); return Images.find({"_id":d.picture}).cursor; }); Meteor.publish('profile.image.team', function(id){ let t = Teams.findOne({'_id':id}); if ( t !== undefined ) { let list = []; let c = Devs.findOne({"user":t.captain}); list.push(c.picture); t.members.forEach(function(m){ let d = Devs.findOne({"user":m}); if ( d.picture != undefined ) list.push(d.picture); }); return Images.find({'_id':{ $in : list }}).cursor; } }); Meteor.publish('visitor.image', function(){ let d = Visitors.findOne({"user":this.userId}); if ( d !== undefined ) return Images.find({"_id":d.picture}).cursor; }); Meteor.publish('sponsors.members.image', function(name){ let s = Sponsors.findOne({'short':name}); if ( s !== undefined ) { let list = []; s.members.forEach(function(m){ let v = Visitors.findOne({"user":m}); if ( v.picture !== undefined ) list.push(v.picture); }); return Images.find({'_id':{ $in : list }}).cursor; } }); Meteor.publish('sponsors.single.image', function(name){ let s = Sponsors.findOne({"short":name}); if ( s !== undefined ) return Images.find({"_id":s.picture}).cursor; }); Meteor.publish('sponsor.image', function(){ let v = Visitors.findOne({"user":this.userId}); if ( v !== undefined ) { let s = Sponsors.findOne({"short":v.company}); if ( s !== undefined ) return Images.find({"_id":s.picture}).cursor; } }); Meteor.publish('alldevs.image', function(){ let d = Devs.find({"picture":{"$exists":true}}); if ( d !== undefined ) { //console.log(d); let list = []; d.forEach(function(m){ list.push(m.picture); }); return Images.find({'_id':{ $in : list }}).cursor; //return Images.find({}).cursor; } }); //Admin Use Meteor.publish('files.images.all', function () { return Images.find().cursor; });
NEETIIST/BreakingDev17
imports/api/images/server/publications.js
JavaScript
gpl-3.0
2,393
import React from 'react'; import { shallow, mount } from 'enzyme'; import Tabs from '../components/layout/Tabs'; describe('Tabs render with different props', () => { const tabs = [ { label: 'Přihlášení', render: () => {} }, { label: 'Registrace', render: () => {} } ]; it('renders without crashing', () => { expect( shallow(<Tabs tabs={tabs} />).length ).toEqual(1); }); it('contains exactly two tabs', () => { const wrapper = mount(<Tabs tabs={tabs} />); expect(wrapper.render().find('li').length).toEqual(2); }); it('contains correct labels in tabs', () => { const wrapper = mount(<Tabs tabs={tabs} />); expect(wrapper.find('li').at(0).text()).toEqual(tabs[0].label); expect(wrapper.find('li').at(1).text()).toEqual(tabs[1].label); }); });
jirkae/hobby_hub
src/Base/__tests__/Tabs.test.js
JavaScript
gpl-3.0
869
var fs = require('fs'); const readline = require('readline'); Lexer = require("./Lexer.js") const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('File name please. ', (answer) => { var data = fs.readFileSync(answer, 'utf8'); console.log("Got", answer, "->", data) var test = new Lexer(data) console.log(test) test.lex() console.log("Lexed!") console.log(test.tokens) rl.close(); });
olegispe/Loaf
src/ReadAndLexer.js
JavaScript
gpl-3.0
451
'use strict'; /** * app settings factory * stores the custom user settings and shares it app wide */ var app = angular.module('istart'); app.factory('appSettings', ['$q', '$rootScope',function ($q, $rootScope) { /** * migrate the old settings from istart 1.x to the * istartV2! * @type {{loaded: null, settingsDefault: {background: {imageadd: boolean, cssadd: boolean, css: string, image: string}}, config: null, save: save, loadOptions: loadOptions, background: background}} */ //if(localStorage.istartbackground) var settings = { loaded:null, backgroundSizeOptions: ['cover', 'initial'], backgroundRepeatOptions: ['no-repeat', 'repeat'], settingsDefault : { background: { imageadd:false, cssadd:false, css: '', image:'', options:null, backgroundSize: 'cover', backgroundRepeat: 'no-repeat' }, mouseWheel: { active:true }, globalsearch: { active:false }, updateCenter: { show:false, version:"2.0.1.60" }, header: { alternative:false, menuIconColor:'rgba(0, 0, 0, 0.87)', menuDimension: { w:30, h:30 } } }, config:null, save : function() { try { chrome.storage.local.set({'options': JSON.stringify(settings.config)}, function( ){ }); } catch(e) { console.error(e); } }, loadOptions : function() { var defer = $q.defer(); chrome.storage.local.get('options', function(settingsRaw) { var settingsArr=null; if(typeof settingsRaw.options == "undefined") { //first run save init config settings.config=settings.settingsDefault; settings.loaded=true; settings.save(); defer.resolve(); return; } try { settingsArr = JSON.parse(settingsRaw.options); console.log(settingsArr); settings.config=settingsArr; settings.loaded=true; defer.resolve(); } catch(e) { } }); return defer.promise; }, setBackgroundImage: function(bgImage) { settings.config.background.imageadd=true; settings.config.background.image=bgImage; settings.save(); }, setBackgroundSize: function(backgroundSize) { settings.config.background.backgroundSize = backgroundSize; settings.save(); $rootScope.$broadcast('changeBackground'); }, setBackgroundRepeat: function(backgroundRepeat) { settings.config.background.backgroundRepeat = backgroundRepeat; settings.save(); $rootScope.$broadcast('changeBackground'); }, setmouseWheelActive: function(activeState) { if(typeof settings.config.mouseWheel !== "undefined") { settings.config.mouseWheel.active=activeState; } else { settings.config.mouseWheel = { active: activeState }; } settings.save(); $rootScope.$broadcast('mouseWheelSettingsChanged', {}); }, checkSettingsLoaded: function() { var defer = $q.defer(); if(settings.loaded==null) { //console.log(localStorage.istartbackground, 'BACKGROUND SETTINGS', localStorage.istartbackground!="null", localStorage.istartbackground!==null); if(localStorage.istartbackground!="null") { settings.loadV1BackgroundSettings(); } //nothing loaded load the settings settings.loadOptions() .then(function() { defer.resolve(true); }) } else { defer.resolve(true); } return defer.promise; }, updateCenter: function() { var defer = $q.defer(); this.checkSettingsLoaded().then( function() { if(typeof settings.config.updateCenter !== "undefined") { defer.resolve(settings.config.updateCenter); } else { /** * if the settings are not present than this version didnt has the * updated settings object! So we add simply true to this object * and resolve it */ defer.resolve(settings.settingsDefault.updateCenter); } }); return defer.promise; }, setUpdateCenter: function(show, versionString) { if(typeof settings.config.updateCenter !== "undefined") { settings.config.updateCenter.show=show; settings.config.updateCenter.version=versionString; } else { settings.config.updateCenter = { show: show, version: versionString }; } settings.save(); //$rootScope.$broadcast('globalsearchSettingsChanged', {}); }, setGlobalSearch: function(activeState) { if(typeof settings.config.globalsearch !== "undefined") { settings.config.globalsearch.active=activeState; } else { settings.config.globalsearch = { active: activeState }; } settings.save(); $rootScope.$broadcast('globalsearchSettingsChanged', {}); }, globalSearch: function() { var defer = $q.defer(); this.checkSettingsLoaded().then( function() { if(typeof settings.config.globalsearch !== "undefined") { defer.resolve(settings.config.globalsearch); } else { /** * if the settings are not present than this version didnt has the * updated settings object! So we add simply true to this object * and resolve it */ defer.resolve(settings.settingsDefault.globalsearch); } }); return defer.promise; }, ensureHeaderConfigExists: function() { if(typeof settings.config.header == "undefined") { settings.config.header = settings.settingsDefault.header; } }, setHeaderAlternative: function(alternativeState) { settings.ensureHeaderConfigExists(); settings.config.header.alternative = alternativeState; settings.save(); $rootScope.$broadcast('globalHeaderChanged'); }, setMenuIconColor: function(color) { settings.ensureHeaderConfigExists(); settings.config.header.menuIconColor=color; settings.save(); $rootScope.$broadcast('globalHeaderChanged'); }, setMenuDimension: function(dimsObject) { settings.ensureHeaderConfigExists(); settings.config.header.menuDimension=dimsObject; settings.save(); $rootScope.$broadcast('globalHeaderChanged'); }, setHeader: function(headerConfigObject) { settings.config.header = headerConfigObject; settings.save(); $rootScope.$broadcast('globalHeaderChanged'); //we need an relaod, this works with an ng-if! }, header: function() { var defer = $q.defer(); this.checkSettingsLoaded().then( function() { if(typeof settings.config.header !== "undefined") { defer.resolve(settings.config.header); } else { /** * if the settings are not present than this version didnt has the * updated settings object! So we add simply true to this object * and resolve it */ defer.resolve(settings.settingsDefault.header); } }); return defer.promise; }, mouseWheel: function() { var defer = $q.defer(); this.checkSettingsLoaded().then( function() { if(typeof settings.config.mouseWheel !== "undefined") { defer.resolve(settings.config.mouseWheel); } else { /** * if the settings are not present than this version didnt has the * updated settings object! So we add simply true to this object * and resolve it */ defer.resolve(settings.settingsDefault.mouseWheel); } }); return defer.promise; }, background : function() { var deferr = $q.defer(); var resolveBackground = function() { if(typeof settings.config.background !== "undefined") { deferr.resolve(settings.config.background); } else { deferr.reject(settings.config.background); } }; if(settings.loaded==null) { //console.log(localStorage.istartbackground, 'BACKGROUND SETTINGS', localStorage.istartbackground!="null", localStorage.istartbackground!==null); if(localStorage.istartbackground!="null") { settings.loadV1BackgroundSettings(); } //nothing loaded load the settings settings.loadOptions() .then(function() { resolveBackground(); }) } else { resolveBackground(); } return deferr.promise; }, loadV1BackgroundSettings: function() { /** * migrate here the old Settings into the new settingsFormat. * clear the old settings directly after setting them into * the new format of V2 */ var bgsetting; var bgoptions; console.log(localStorage.istartbackground); if(localStorage.istartbackground != "null" && typeof localStorage.istartbackground != "undefined") { if(settings.config==null) { settings.config = settings.settingsDefault; } bgsetting = localStorage.istartbackground; /** * check if this is an image or color: */ if(bgsetting.indexOf('url(')!=-1) { //image ! settings.config.background.imageadd=true; settings.config.background.image = bgsetting;//the complete string? } else{ //css gradient settings.config.background.imageadd=false; settings.config.background.cssadd=true; settings.config.background.css = bgsetting; settings.save();//store the new things } } //load additional settings if(localStorage.istartbgoptions != null) { if(settings.config==null) { settings.config = settings.settingsDefault; } bgoptions = JSON.parse(localStorage.istartbgoptions); settings.config.background.options = bgoptions; settings.save();//store the new things } //todo:implement load functions to load the background from options //$('#mbg').css('backgroundImage', this.bgsetting ); localStorage.istartbackground=null; localStorage.istartbgoptions=null; /*if(this.bgoptions != null) { this.setBgOptionsFromObj(); }*/ }, setBgOptionsFromObj: function () { /** * TODO:replace this into the backGroundSettings * directive */ for(var option in this.bgoptions) { var cso = option; if(option == 'backgroundattachment') { cso = 'background-attachment'; } $('#mbg').css(cso, this.bgoptions[option] ); } } }; /** * returns the current apps list! */ return { settings:settings } }]);
KaySchneider/istart-ntp
app/service/settings.js
JavaScript
gpl-3.0
13,401
/* jshint -W117 */ /* Copyright 2016 Herko ter Horst __________________________________________________________________________ Filename: _videoplayerApp.js __________________________________________________________________________ */ log.addSrcFile("_videoplayerApp.js", "_videoplayer"); function _videoplayerApp(uiaId) { log.debug("Constructor called."); // Base application functionality is provided in a common location via this call to baseApp.init(). // See framework/js/BaseApp.js for details. baseApp.init(this, uiaId); } // load jQuery Globally (if needed) if (!window.jQuery) { utility.loadScript("addon-common/jquery.min.js"); } /********************************* * App Init is standard function * * called by framework * *********************************/ /* * Called just after the app is instantiated by framework. * All variables local to this app should be declared in this function */ _videoplayerApp.prototype.appInit = function() { log.debug("_videoplayerApp appInit called..."); // These values need to persist through videoplayer instances this.hold = false; this.resumePlay = 0; this.musicIsPaused = false; this.savedVideoList = null; this.resumeVideo = JSON.parse(localStorage.getItem('videoplayer.resumevideo')) || true; // resume is now checked by default this.currentVideoTrack = JSON.parse(localStorage.getItem('videoplayer.currentvideo')) || null; //this.resumePlay = JSON.parse(localStorage.getItem('videoplayer.resume')) || 0; //Context table //@formatter:off this._contextTable = { "Start": { // initial context must be called "Start" "sbName": "Video Player", "template": "VideoPlayerTmplt", "templatePath": "apps/_videoplayer/templates/VideoPlayer", //only needed for app-specific templates "readyFunction": this._StartContextReady.bind(this), "contextOutFunction": this._StartContextOut.bind(this), "noLongerDisplayedFunction": this._noLongerDisplayed.bind(this) } // end of "VideoPlayer" }; // end of this.contextTable object //@formatter:on //@formatter:off this._messageTable = { // haven't yet been able to receive messages from MMUI }; //@formatter:on framework.transitionsObj._genObj._TEMPLATE_CATEGORIES_TABLE.VideoPlayerTmplt = "Detail with UMP"; }; /** * ========================= * CONTEXT CALLBACKS * ========================= */ _videoplayerApp.prototype._StartContextReady = function() { framework.common.setSbDomainIcon("apps/_videoplayer/templates/VideoPlayer/images/icon.png"); }; _videoplayerApp.prototype._StartContextOut = function() { CloseVideoFrame(); framework.common.setSbName(''); }; _videoplayerApp.prototype._noLongerDisplayed = function() { // Stop and close video frame CloseVideoFrame(); // If we are in reverse then save CurrentVideoPlayTime to resume the video where we left of if (framework.getCurrentApp() === 'backupparking'|| framework.getCurrentApp() === 'phone' || (ResumePlay && CurrentVideoPlayTime !== null)) { this.resumePlay = this.resumePlay || CurrentVideoPlayTime; CurrentVideoPlayTime = 0; //localStorage.setItem('videoplayer.resume', JSON.stringify(CurrentVideoPlayTime)); } // If we press the 'Entertainment' button we will be running this in the 'usbaudio' context if (!this.musicIsPaused) { setTimeout(function() { if (framework.getCurrentApp() === 'usbaudio') { framework.sendEventToMmui('Common', 'Global.Pause'); framework.sendEventToMmui('Common', 'Global.GoBack'); this.musicIsPaused = true; // Only run this once } }, 100); } }; /** * ========================= * Framework register * Tell framework this .js file has finished loading * ========================= */ framework.registerAppLoaded("_videoplayer", null, false);
Trevelopment/MZD-AIO-TI-X
app/files/tweaks/config/videoplayer/jci/gui/apps/_videoplayer/js/_videoplayerApp.js
JavaScript
gpl-3.0
3,832
import { Link, LocationProvider } from '@reach/router'; import router from '@elementor/router'; import { arrayToClassName } from 'elementor-app/utils/utils.js'; import './inline-link.scss'; export default function InlineLink( props ) { const baseClassName = 'eps-inline-link', colorClassName = `${ baseClassName }--color-${ props.color }`, underlineClassName = 'none' !== props.underline ? `${ baseClassName }--underline-${ props.underline }` : '', italicClassName = props.italic ? `${ baseClassName }--italic` : '', classes = [ baseClassName, colorClassName, underlineClassName, italicClassName, props.className, ], className = arrayToClassName( classes ), getRouterLink = () => ( <LocationProvider history={ router.appHistory }> <Link to={ props.url } className={ className } > { props.children } </Link> </LocationProvider> ), getExternalLink = () => ( <a href={ props.url } target={ props.target } rel={ props.rel } className={ className } > { props.children } </a> ); return props.url.includes( 'http' ) ? getExternalLink() : getRouterLink(); } InlineLink.propTypes = { className: PropTypes.string, children: PropTypes.string, url: PropTypes.string, target: PropTypes.string, rel: PropTypes.string, text: PropTypes.string, color: PropTypes.oneOf( [ 'primary', 'secondary', 'cta', 'link', 'disabled' ] ), underline: PropTypes.oneOf( [ 'none', 'hover', 'always' ] ), italic: PropTypes.bool, }; InlineLink.defaultProps = { className: '', color: 'link', underline: 'always', target: '_blank', rel: 'noopener noreferrer', };
ramiy/elementor
core/app/assets/js/ui/molecules/inline-link.js
JavaScript
gpl-3.0
1,644
/// <reference path="windowbutton/battlelog.windowbutton.js" /> /// <reference path="playbar/battlelog.bf3.playbar.js" /> /// <reference path="dialog/battlelog.bf3.dialog.js" /> /// <reference path="stats/battlelog.bf3.stats.js" /> var baseurl = 'http://battlelogium.github.io/Battlelogium/Battlelogium.Core/Javascript'; function injectOnce() { if (document.getElementById('_windowbutton') == null) { injectScript('_windowbutton', baseurl+'/windowbutton/battlelog.windowbutton.min.js'); } if (document.getElementById('css_windowbutton') == null) { injectCSS('css_windowbutton', baseurl + '/windowbutton/battlelog.windowbutton.min.css'); } if (document.getElementById('css_misc') == null) { injectCSS('css_misc', baseurl + '/misc/battlelog.misc.min.css'); } if (document.getElementById('_battlelogplaybar') == null) { injectScript('_battlelogplaybar', baseurl + '/playbar/battlelog.mohw.playbar.min.js'); } if (document.getElementById('_battlelogstats') == null) { injectScript('_battlelogstats', baseurl + '/stats/battlelog.mohw.stats.min.js'); } if (document.getElementById('_battlelogsettings') == null) { injectScript('_battlelogsettings', baseurl + '/settings/battlelog.mohw.settings.min.js'); } } function runCustomJS() { try { battlelogplaybar.fixQuickMatchButtons(); windowbutton.addWindowButtons(); windowbutton.updateMaximizeButton(); battlelogplaybar.fixEAPlaybarButtons(); battlelogplaybar.addPlaybarButton(battlelogplaybar.createPlaybarButton('btnServers', 'SERVERS', 'location.href = "http://battlelog.battlefield.com/mohw/servers/"')); $("#base-header-secondary-nav>ul>li>a:contains('Buy Battlefield 4')").remove(); } catch (error) { } if (window.location.href.match(/\/soldier\//) != null) { battlelogstats.overview(); } if (window.location.href == 'http://battlelog.battlefield.com/mohw/profile/edit/') { battlelogsettings.addSettingsSection(); } } function injectScript(id, url) { var script = document.createElement('script'); script.setAttribute('src', url); script.setAttribute('id', id); document.getElementsByTagName('head')[0].appendChild(script); } function injectCSS(id, url) { var script = document.createElement('link'); script.setAttribute('rel', 'stylesheet'); script.setAttribute('type', 'text/css'); script.setAttribute('href', url); script.setAttribute('id', id); document.getElementsByTagName('head')[0].appendChild(script); } injectOnce();
Battlelogium/Battlelogium
Battlelogium.Core/Javascript/battlelog.mohw.inject.js
JavaScript
gpl-3.0
2,616
/** * Created by gjrwcs on 10/25/2016. */ 'use strict'; /** * Game Behavior and Logic for Warp * @module pulsar.warp */ var warp = require('angular').module('pulsar.warp', []); const ADT = require('../app.dependency-tree.js').ADT; ADT.warp = { Level: 'warp.Level', WarpField: 'warp.WarpField', Bar: 'warp.Bar', State: 'warp.State', }; require('./bar.factory'); require('./game.controller'); require('./hud.directive'); require('./level-loader.svc'); require('./level.svc'); require('./scoring.svc'); require('./ship.svc'); require('./ship-effects.svc'); require('./warp-field.factory'); require('./warp-field-cache.svc'); require('./warp-field-draw.svc'); require('./state.svc'); module.exports = warp;
thunder033/RMWA
pulsar/app/warp/index.js
JavaScript
gpl-3.0
742
/* Copyright (c) 2012 Richard Klancer <rpk@pobox.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*global $ console */ var x = 0, y = 0, intervalID, INTERVAL_LENGTH = 200; // ms // define console as a noop if not defined if (typeof console === 'undefined') console = { log: function() {} }; function postJoystickPosition() { $.post('/joystick', { x: x, y: y }); } function startSending() { intervalID = setInterval(postJoystickPosition, INTERVAL_LENGTH); } function stopSending() { // one last time postJoystickPosition(); clearInterval(intervalID); } // draws "joystick", updates x and y function joystickGo() { // Just do the dead simplest thing right now -- we have one draggable element, and no encapsulation var dragInfo = {}, centerX, centerY, radialLimit, radialLimitSquared; function updatePosition(_x, _y) { x = _x / radialLimit; y = - _y / radialLimit; console.log(x,y); } function centerKnob() { var $el = $(dragInfo.element), width = $('#background').width(); $el.animate({ left: width/2, top: width/2 }, 200); updatePosition(0, 0); } function dragStart(evt) { dragInfo.dragging = true; evt.preventDefault(); var $el = $(dragInfo.element), offset = $el.offset(), width = $el.width(), cx = offset.left + width/2 - centerX, cy = offset.top + width/2 - centerY; dragInfo.dx = evt.pageX - cx; dragInfo.dy = evt.pageY - cy; startSending(); } function drag(evt) { if ( ! dragInfo.dragging ) return; evt.preventDefault(); var $el = $(dragInfo.element), offset = $el.offset(), width = $el.width(), // find the current center of the element cx = offset.left + width/2 - centerX, cy = offset.top + width/2 - centerY, newcx = evt.pageX - dragInfo.dx, newcy = evt.pageY - dragInfo.dy, newRadiusSquared = newcx*newcx + newcy*newcy, scale; if (newRadiusSquared > radialLimitSquared) { scale = Math.sqrt( radialLimitSquared / newRadiusSquared ); newcx *= scale; newcy *= scale; } updatePosition(newcx, newcy); offset.left += (newcx - cx); offset.top += (newcy - cy); $(dragInfo.element).offset(offset); } function dragEnd() { dragInfo.dragging = false; centerKnob(); stopSending(); } function adjustDimensions() { var $background = $('#background'), $knob = $('#knob'), offset = $background.offset(), width = $background.width(); makeCircular($background); makeCircular($knob); centerX = width/2 + offset.left; centerY = width/2 + offset.top; radialLimit = (width - $knob.width()) / 2; radialLimitSquared = radialLimit * radialLimit; } function makeCircular($el) { var width = $el.width(); // Android 2 browser doesn't seem to understand percentage border-radius, so we need to set it // via an inline style once we know the width $el.css({ height: width, borderRadius: width/2 }); } function wrapForTouch(f) { return function(evt) { if (evt.originalEvent && evt.originalEvent.touches && evt.originalEvent.touches.length === 1) { evt.pageX = evt.originalEvent.touches[0].pageX; evt.pageY = evt.originalEvent.touches[0].pageY; } return f(evt); }; } $(function() { var $background = $('#background'), $knob = $('#knob'); adjustDimensions(); dragInfo.element = $knob[0]; $knob.bind('touchstart mousedown', wrapForTouch(dragStart)); $(document).bind('touchmove mousemove', wrapForTouch(drag)); $(document).bind('touchend mouseup', wrapForTouch(dragEnd)); $background.bind('mousedown', function() { return false; }); $(window).bind('resize', adjustDimensions); }); } // and...go: joystickGo();
rascalmicro/control-freak
public/static/js/joystick.js
JavaScript
gpl-3.0
4,902
/* This file is part of KUMobile. KUMobile is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. KUMobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with KUMobile. If not, see <http://www.gnu.org/licenses/>. */ /****************************************************************************** * Contains all news related functions for loading and controlling the news page. * * @class KUMobile.News ******************************************************************************/ KUMobile.News = { /****************************************************************************** * Current page number as referenced from the news website. * * @attribute page * @type {int} * @for KUMobile.News * @default 0 ******************************************************************************/ page: 0, /****************************************************************************** * Number of pages to load from the news website after a trigger event occurs. * * @attribute PAGES_TO_LOAD * @type {int} * @for KUMobile.News * @default 2 ******************************************************************************/ PAGES_TO_LOAD: 2, /****************************************************************************** * Is the news page loading? * * @attribute loading * @type {boolean} * @for KUMobile.News * @default false ******************************************************************************/ loading: false, /****************************************************************************** * Designates the minimum number of pixels that the user can scroll * (calculated from the bottom) before another load event is triggered. * * @attribute LOAD_THRESHOLD_PX * @type {int} * @for KUMobile.News * @default 660 ******************************************************************************/ LOAD_THRESHOLD_PX: 660, /****************************************************************************** * How many pages that need to be downloaded still. This is used to asynchronously * download pages. * * @attribute queue * @type {int} * @for KUMobile.News * @default 0 * @private ******************************************************************************/ queue: 0, /****************************************************************************** * Contains the current list of article DOM <li> tag items that still need * to be added to the DOM (much faster to add all at once after load * is done downloading). This helps prevent the application from seeming to * hang or become unresponsive. * * @attribute listQueue * @type {Array} * @for KUMobile.News * @private ******************************************************************************/ listQueue: [], /****************************************************************************** * Contains the current list of pages DOM data-role="page" * items that still need to be added to the DOM (much faster to * add all at once after load is done downloading). This helps * prevent the app from seeming to hang or become unresponsive. * * @attribute pageQueue * @type {Array} * @for KUMobile.News * @private ******************************************************************************/ pageQueue: [], /****************************************************************************** * Triggered when the news page is first initialized based on jQuery Mobile * pageinit event. * * @event pageInit * @for KUMobile.News ******************************************************************************/ pageInit: function(event){ KUMobile.News.initialized = true; // Check overflow scroll position $('#news-scroller').on("scroll", KUMobile.News.scroll); }, /****************************************************************************** * Triggered when the news page is first created based on jQuery Mobile * pagecreate event. This is called after the page itself is created but * before any jQuery Mobile styling is applied. * * @event pageCreate * @for KUMobile.News ******************************************************************************/ pageCreate: function(event){ // Resize and get first page $(window).trigger("throttledresize"); KUMobile.News.loadNextPage(); }, /****************************************************************************** * Triggered when regular scroll event happens in news scroller window. It * is used to check if the user is *near* the bottom of the page, so more * content can be loaded (simulate *infinite scrolling*). * * @event scroll * @for KUMobile.News ******************************************************************************/ scroll: function(event){ // Get scroll position var scrollPosition = $('#news-scroller').scrollTop() + $('#news-scroller').outerHeight(); // Break threshold? if($('#news-list').height() < (KUMobile.News.LOAD_THRESHOLD_PX + $('#news-scroller').scrollTop() + $('#news-scroller').outerHeight()) && $('#news').is(':visible') && !(KUMobile.News.loading)){ // Get the next page! KUMobile.News.loadNextPage(); } }, /****************************************************************************** * Loads and displays the next set of news items. * * @method loadNextPage * @for KUMobile.News * @example * KUMobile.News.loadNextPage(); ******************************************************************************/ loadNextPage: function (){ if(!this.loading){ // Now loading this.loading = true; // Empty queue? if(this.queue <= 0){ // Initialize the queue // start with default pages // show loading indicator! this.queue = KUMobile.News.PAGES_TO_LOAD; KUMobile.showLoading("news-header"); } /** Success **/ var success = function(items){ // Increment page KUMobile.News.page++; // Setup data for(var index = 0; index < items.length; index++){ // Current item and template var item = items[index]; var captionTpl = Handlebars.getTemplate("news-item"); var pageTpl = Handlebars.getTemplate("dynamic-page"); var pageId = 'news-' + KUMobile.News.page + '-' + index; var info = item.author; info += (info == "")? item.date: " | " + item.date; // Caption data var captionHtml = captionTpl({ "title": item.title, "imgUrl": (item.imgUrl=="")?("img/default_icon.jpg"):(item.imgUrl), "info": info, "pageId": pageId }); // Page data var pageHtml = pageTpl({ "link": item.detailsUrl, "pageId": pageId, "headerTitle": "News", "scrollerId": pageId + "-scroller" }); // Register event $(document).on("pagecreate",'#' + pageId, KUMobile.News.articlePageCreate); // Add list item to queue KUMobile.News.listQueue[KUMobile.News.listQueue.length] = captionHtml; KUMobile.News.pageQueue[KUMobile.News.pageQueue.length] = pageHtml; } // Flush? if(--KUMobile.News.queue <= 0){ // Not loading KUMobile.hideLoading("news-header"); KUMobile.News.loading = false; // Go through all list items for (var index = 0; index < KUMobile.News.listQueue.length; index++){ // Append to news list $(KUMobile.News.listQueue[index]).appendTo("#news-list"); } // Go through all page items for (var index = 0; index < KUMobile.News.pageQueue.length; index++){ // Append to news list $(KUMobile.News.pageQueue[index]).appendTo("body"); } // Setup link opener KUMobile.safeBinder("click", ".dynamic-news-events-page .scroller a", function(e){ // Android open? Otherwise use _system target if (KUMobile.Config.isAndroid) navigator.app.loadUrl($(this).attr('href'), {openExternal : true}); else window.open($(this).attr('href'), '_system'); // Prevent default e.preventDefault(); return false; }); // Check for new articles only during initialization if(KUMobile.News.initialized != true){ // Get read news var news_list = window.localStorage.getItem("ku_news_read"); // Make empty or parse array if(news_list != null){ try{ // Parse news array news_list = JSON.parse(news_list); } catch(object){ news_list = []; } // Go through each list item $("#news-list li a div.main-text").each(function(i){ // Get id var id = $("h1", this).text().trim(); var found = false; // Search for match for (var readIndex = 0; readIndex < news_list.length; readIndex++){ if (id == news_list[readIndex]) found = true; } // Not found? if (!found){ KUMobile.addNewIndicator("#news-listitem a div.main-text"); KUMobile.addNewIndicator(this); } }); } } // Refresh and clear both lists if(KUMobile.News.initialized) $('#news-list').listview('refresh'); KUMobile.News.listQueue = []; KUMobile.News.pageQueue = []; } // More news to be downloaded! else { // Load more KUMobile.News.loading = false; KUMobile.News.loadNextPage(); } }; /** Fail **/ var failure = function(error){ // Not loading anymore presumably.. KUMobile.hideLoading("news-header"); KUMobile.News.loading = false; KUMobile.safeAlert("Error", "Sorry the news could not be loaded. Check your" + " internet connection. If the issue persists then please report the bug.", "ok"); }; // Get next page KU.News.nextPage(success, failure); } }, /****************************************************************************** * Called on create of an article page. Mainly this function just * attempts to download the article and show it. * * @event articlePageCreate * @for KUMobile.News ******************************************************************************/ articlePageCreate: function(event){ // Now loading KUMobile.News.loading = true; KUMobile.showLoading(this.id); var identifier = this.id; var success = function(article){ var articleTpl = Handlebars.getTemplate("news-article"); var html = articleTpl({ "title": article.title, "info": article.headerInfo }); $(html).appendTo("#" + identifier + "-scroller"); mainParagraph = KUMobile.sanitize(article.mainHtml); // Fix max width and height mainParagraph.find('*').css("max-width", "100%").css("height","auto"); // Remove hard-coded width from table mainParagraph.find('table').css('width',''); mainParagraph.css('padding','4px'); // Remove "Related" fields mainParagraph.find("h3").each(function(i){ // Related header if($(this).text() === "Related:"){ // Find all links under it $(this).parent().parent().parent().find("tr td ul li a").each(function(j){ // Remove! $(this).parent().parent().parent().parent().remove(); }); // Remove related! $(this).parent().parent().remove(); } }); // Fix youtube videos mainParagraph.find("embed").each(function(i){ if($(this).attr("src") != undefined && $(this).attr("src").indexOf("youtube") > -1){ // Complex regex var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/; var match = $(this).attr("src").match(regExp); // Match? if (match && match[2].length == 11) { var id = match[2]; var youtubeFrame = $("<iframe></iframe>",{ "width":"100%", "height":"auto", "src":"http://www.youtube.com/embed/" + id + "?version=3&rel=0&amp;controls=0&amp;showinfo=0", "frameborder":"0", "allowfullscreen":"true" }); $(this).parent().append(youtubeFrame); $(this).remove(); } } }); // Append mainParagraph.appendTo("#" + identifier + "-scroller"); // Resize when new elements load $(mainParagraph).find('*').load(function(){ $(window).trigger("resize");}); // Resize anyways! in case there was nothing to load from above $(window).trigger("resize"); // Done loading! KUMobile.hideLoading(identifier); KUMobile.News.loading = false; } var failure = function(error){ // Not loading anymore presumably.. KUMobile.hideLoading(identifier); KUMobile.News.loading = false; KUMobile.safeAlert("Error", "Sorry the news could not be loaded. Check your" + " internet connection. If the issue persists then please report the bug.", "ok"); } // Get the article! KU.News.downloadArticle($('#' + identifier).attr("kulink"), success, failure) } };
garrickbrazil/kumobile
www/js/news.js
JavaScript
gpl-3.0
17,619
/** * This file is part of "PCPIN Chat 6". * * "PCPIN Chat 6" is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * "PCPIN Chat 6" is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Callback function to execute after confirm box receives "OK". */ var confirmboxCallback=''; /** * Display confirm box * @param string $text Text to display * @param int top_offset Optional. How many pixels to add to the top position. Can be negative or positive. * @param int left_offset Optional. How many pixels to add to the left position. Can be negative or positive. * @param string callback Optional. Callback function to execute after confirm box receives "OK". */ function confirm(text, top_offset, left_offset, callback) { if (typeof(text)!='undefined' && typeof(text)!='string') { try { text=text.toString(); } catch (e) {} } if (typeof(text)=='string') { document.onkeyup_confirmbox=document.onkeyup; document.onkeyup=function(e) { switch (getKC(e)) { case 27: hideConfirmBox(false); break; } }; if (typeof(top_offset)!='number') top_offset=0; if (typeof(left_offset)!='number') left_offset=0; $('confirmbox_text').innerHTML=nl2br(htmlspecialchars(text)); $('confirmbox').style.display=''; $('confirmbox_btn_ok').focus(); setTimeout("moveToCenter($('confirmbox'), "+top_offset+", "+left_offset+"); $('confirmbox_btn_ok').focus();", 25); if (typeof(callback)=='string') { confirmboxCallback=callback; } else { confirmboxCallback=''; } setTimeout("$('confirmbox').style.display='none'; $('confirmbox').style.display='';", 200); } } /** * Hide confirm box @param boolean ok TRUE, if "OK" button was clicked */ function hideConfirmBox(ok) { document.onkeyup=document.onkeyup_confirmbox; $('confirmbox').style.display='none'; if (typeof(ok)=='boolean' && ok && confirmboxCallback!='') { eval('try { '+confirmboxCallback+' } catch(e) {}'); } }
Dark1revan/chat1
js/base/confirmbox.js
JavaScript
gpl-3.0
2,595
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; document.addEventListener('DOMContentLoaded', function () { var items = __webpack_require__(1), categoryDefs = __webpack_require__(2), contactDefs = __webpack_require__(3), ResultPage = __webpack_require__(4), LocationPage = __webpack_require__(5), ItemPage = __webpack_require__(6), DirectionsPage = __webpack_require__(7), DogsApp = React.createClass({ displayName: 'DogsApp', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, categoryDefs: React.PropTypes.array, contactDefs: React.PropTypes.array, items: React.PropTypes.array }, getDefaultProps: function getDefaultProps() { return { categoryDefs: categoryDefs, contactDefs: contactDefs, colors: { colorMeta: '#0a5a83', // dark blue hsv(200,92,51) colorSelected: '#80d4ff', // light blue hsx(200,50,100) colorLink: '#0000ff', // blue hsv(240,100,100) colorItem: '#000000', // black colorBackground: '#ffffff' // white }, layout: { lineHeightMeta: '2.5rem', heightCategoryList: '164px', // 4 * (2.5rem + 1px) widthSymbol: '1rem', marginNarrow: '0.5rem', marginWide: '2.5rem' // marginNarrow + 2 * widthCategorySymbol } }; }, getInitialState: function getInitialState() { var props = this.props, categoryMap = {}, indexMap = 0; props.categoryDefs.forEach(function (categoryDef) { categoryMap[categoryDef.key] = categoryDef; }); items.forEach(function (item) { // TODO: Ask Enrique if it is okay to add a property to a props object? item.categoryDef = categoryMap[item.categoryKey]; item.indexMap = ++indexMap; // demo }); return { page: React.createElement(ResultPage, { colors: props.colors, layout: props.layout, categoryDefs: props.categoryDefs, items: items, setItemPage: this.setItemPage, setLocationPage: this.setLocationPage }) }; }, setPage: function setPage(page) { this.setState({ page: page }); }, setItems: function setItems(items) { var props = this.props; this.setState({ page: React.createElement(ResultPage, { colors: props.colors, layout: props.layout, categoryDefs: props.categoryDefs, items: items, setItemPage: this.setItemPage }) }); }, setLocation: function setLocation(location) { // TODO: get items for new location this.setItems(items); }, setLocationPage: function setLocationPage() { var props = this.props, setPrevPage = this.setPage.bind(this, this.state.page); this.setState({ page: React.createElement(LocationPage, { colors: props.colors, layout: props.layout, setLocation: this.setLocation, setPrevPage: setPrevPage }) }); }, setItemPage: function setItemPage(item) { var props = this.props, setPrevPage = this.setPage.bind(this, this.state.page); this.setState({ page: React.createElement(ItemPage, { colors: props.colors, layout: props.layout, contactDefs: props.contactDefs, item: item, setPrevPage: setPrevPage, setDirectionsPage: this.setDirectionsPage }) }); }, setDirectionsPage: function setDirectionsPage(item) { var props = this.props, setPrevPage = this.setPage.bind(this, this.state.page); this.setState({ page: React.createElement(DirectionsPage, { colors: props.colors, layout: props.layout, item: item, setPrevPage: setPrevPage }) }); }, render: function render() { return this.state.page; } }); // TODO: property will become the data API object React.render(React.createElement(DogsApp, { items: items }), document.getElementsByTagName('body')[0]); }); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { module.exports = [{ id: 0, categoryKey: 'park', // bar, restaurant, park, event //time: 'yyyy-mm-ddThh:mm:ss +oo:oo', // for event dogFriendly: false, // boolean if possible, otherwise string name: 'Freedom Park', address: '1900 East Boulevard', city: 'Charlotte', state: 'NC', postalCode: '28203', // zip code neighborhood: 'Dilworth, Myers Park', contacts: { phone: '(704) 432-4280', web: 'http://charmeck.org%2Fmecklenburg%2Fcounty%2Fparkandrec%2Fparks%2Fparksbyregion%2Fcentralregion%2Fpages%2Ffreedom.aspx' }, description: '', amenities: ['', ''], // list of strings, or booleans, or object? hours: '', // string? distance: 1.8, // is derived from location of item to current location location: { // unless you know that there is a more useful format latitude: '35 13 37 N', // TODO: specific format longitude: '80 50 36 W' } }, { id: 1, categoryKey: 'park', name: 'Marshall Park', address: '800 East Third Street', city: 'Charlotte', state: 'NC', postalCode: '', neighborhood: '', contacts: { phone: '', web: '' }, description: '', distance: 1.9, location: null }, { id: 2, categoryKey: 'park', name: 'Romare Bearden Park', address: '300 S Church St', city: 'Charlotte', state: 'NC', postalCode: '28202', neighborhood: 'Uptown', contacts: { phone: '', web: '' }, description: '', distance: 0.4, location: null }, { id: 3, categoryKey: 'park', dogFriendly: true, name: 'Frazier Park', address: '1201 W Trade St', city: 'Charlotte', state: 'NC', postalCode: '28202', neighborhood: 'Third Ward', contacts: { phone: '704-432-4280', web: 'http://charmeck.org/mecklenburg/county/ParkandRec/Parks/ParksByRegion/CentralRegion/Pages/frazier.aspx' }, description: '', distance: 1.9, // placeholder location: null }, { id: 4, categoryKey: 'park', dogFriendly: true, name: 'William R. Davie Park', address: '4635 Pineville-Matthews Road', city: 'Charlotte', state: 'NC', postalCode: '28226', neighborhood: 'Arboretum', contacts: { phone: '(704) 541-9880', web: 'http://charmeck.org/mecklenburg/county/ParkandRec/Parks/ParksByRegion/SouthRegion/Pages/WilliamRDavie.aspx' }, description: '', distance: 13, // placeholder location: null }, { id: 5, categoryKey: 'bar', dogFriendly: false, name: 'Dandelion Market', address: '118 W 5th St', city: 'Charlotte', state: 'NC', postalCode: '28202', neighborhood: 'Fourth Ward', contacts: { phone: '(704) 333-7989', web: 'http://www.dandelionmarketcharlotte.com' }, description: '', distance: 0.3, // placeholder location: null }]; /* { id: 7, categoryKey: '', dogFriendly: false, name: '', address: '', city: 'Charlotte', state: 'NC', postalCode: '', neighborhood: '', contacts: { phone: '', web: '' }, description: '', distance: 0, // placeholder location: null } */ /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var srcImage = function (name) { return name + '.svg'; }; module.exports = [{ key: 'bar', text: 'Bars', srcImage: srcImage('glass') }, { key: 'restaurant', text: 'Restaurants', srcImage: srcImage('cutlery') }, { key: 'park', text: 'Parks', srcImage: srcImage('compass') }, { key: 'event', text: 'Events', srcImage: srcImage('calendar') }]; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var srcImage = function (name) { return name + '.svg'; }; module.exports = [{ key: 'phone', srcImage: srcImage('phone'), callback: function (number) { window.alert('Call phone number: ' + number); } }, { key: 'web', srcImage: srcImage('external-link-square'), callback: function (address) { window.open(address); } }]; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Header = __webpack_require__(8), CategoryList = __webpack_require__(9), ResultList = __webpack_require__(10); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, categoryDefs: React.PropTypes.array, items: React.PropTypes.array, setItemPage: React.PropTypes.func, setLocationPage: React.PropTypes.func }, getInitialState: function getInitialState() { var items = this.props.items, categoriesSelected = {}, props = this.props; props.categoryDefs.forEach(function (categoryDef) { categoriesSelected[categoryDef.key] = false; // all false means unfiltered }); return { initial: true, categoriesSelected: categoriesSelected, itemsFiltered: items.concat() // shallow copy }; }, onCategorySelected: function onCategorySelected(categoryDef) { var categoriesSelected = Object.create(this.state.categoriesSelected), key = categoryDef.key, noneSelected = true, itemsFiltered = []; categoriesSelected[key] = !categoriesSelected[key]; this.props.categoryDefs.forEach(function (categoryDef) { noneSelected = noneSelected && !categoriesSelected[categoryDef.key]; }); this.props.items.forEach(function (item) { if (noneSelected || categoriesSelected[item.categoryKey] === true) { idsFiltered.push(item); } }); this.setState({ initial: false, categoriesSelected: categoriesSelected, itemsFiltered: itemsFiltered }); }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, state = this.state, styleSideBySide = { display: 'flex', alignItems: 'flex-start', width: '100%' }, styleMap = { flexGrow: 1, flexShrink: 1, boxSizing: 'border-box', height: layout.heightCategoryList, borderColor: colors.colorMeta, borderWidth: '1px', borderLeftStyle: 'solid', borderBottomStyle: 'solid' }, initial = state.initial, linkRight = { srcImage: 'search.svg', setPage: props.setLocationPage }, map; if (!initial) { map = React.createElement('img', { style: styleMap, src: 'TODO.jpg', alt: 'Map' }); } return React.createElement( 'div', null, React.createElement(Header, { colors: colors, layout: layout, linkRight: linkRight }), React.createElement( 'div', { style: styleSideBySide }, React.createElement(CategoryList, { colors: colors, layout: layout, initial: state.initial, categoryDefs: props.categoryDefs, categoriesSelected: state.categoriesSelected, onCategorySelected: this.onCategorySelected }), map ), React.createElement(ResultList, { items: state.itemsFiltered, mapIndexDemo: !initial, colors: colors, layout: props.layout, setItemPage: props.setItemPage }) ); } }); /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Header = __webpack_require__(8); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, item: React.PropTypes.object, setPrevPage: React.PropTypes.func }, onClickOK: function onClickOK() { // TODO setLocation() this.props.setPrevPage(); }, onClickCancel: function onClickCancel() { this.props.setPrevPage(); }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, marginWide = layout.marginWide, styleDiv = {}, styleForm = { marginLeft: marginWide, marginRight: marginWide }, styleFieldsetInput = { marginTop: '1rem' }, styleInput = { borderColor: colors.colorItem, borderWidth: '1px', borderStyle: 'solid' }, styleFieldsetButtons = { display: 'flex', alignItems: 'flex-start', marginTop: '1rem' }, styleButton = { backgroundColor: colors.colorBackground, borderColor: colors.colorItem, borderWidth: '1px', borderStyle: 'solid', padding: layout.marginNarrow, marginLeft: marginWide }; return React.createElement( 'div', { style: styleDiv }, React.createElement(Header, { colors: colors, layout: layout }), React.createElement( 'form', { style: styleForm }, React.createElement( 'fieldset', { style: styleFieldsetInput }, React.createElement('input', { type: 'text', style: styleInput }) ), React.createElement( 'fieldset', { style: styleFieldsetButtons }, React.createElement( 'button', { style: styleButton, onClick: this.onClickOK }, 'OK' ), React.createElement( 'button', { style: styleButton, onclick: this.onClickCancel }, 'Cancel' ) ) ) ); } }); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Header = __webpack_require__(8), ResultItem = __webpack_require__(11), ContactList = __webpack_require__(12); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, contactDefs: React.PropTypes.array, item: React.PropTypes.object, setPrevPage: React.PropTypes.func, setDirectionsPage: React.PropTypes.func }, onClickDirections: function onClickDirections() { // TODO: location too? this.props.setDirectionsPage(this.props.item); }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, marginWide = layout.marginWide, // TO DO: align ContactList at bottom? styleDiv = {}, styleImage = { boxSizing: 'border-box', width: '100%', height: layout.heightCategoryList, borderWidth: '1px', borderBottomStyle: 'solid' }, styleList = { listStyle: 'none', width: '100%' }, stylePara = { display: 'flex', alignItems: 'baseline', marginLeft: marginWide }, styleDirections = { color: colors.colorLink, marginLeft: 'auto', padding: layout.marginNarrow, borderWidth: '1px', borderStyle: 'solid' }, linkLeft = { srcImage: 'angle-left.svg', setPage: props.setPrevPage }, item = props.item; // TODO: description, hours, amenities return React.createElement( 'div', { style: styleDiv }, React.createElement(Header, { colors: colors, layout: layout, linkLeft: linkLeft }), React.createElement('img', { style: styleImage, src: 'TODO.jpg', alt: 'Picture' }), React.createElement( 'ul', { style: styleList }, React.createElement(ResultItem, { colors: colors, layout: layout, item: item }), React.createElement( 'li', null, React.createElement( 'p', { style: stylePara }, React.createElement( 'span', null, item.neighborhood ), React.createElement( 'span', { style: styleDirections, onClick: this.onClickDirections }, 'Directions' ) ) ) ), React.createElement(ContactList, { colors: colors, layout: layout, contactDefs: props.contactDefs, contacts: item.contacts }) ); } }); //display: 'flex', //alignItems: 'flex-start', //alignContent: 'flex-start', //flexWrap: 'wrap', //overflow: 'hidden' /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Header = __webpack_require__(8); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, item: React.PropTypes.object, setPrevPage: React.PropTypes.func }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, styleDiv = {}, linkLeft = { srcImage: 'angle-left.svg', setPage: props.setPrevPage }; return React.createElement( 'div', { style: styleDiv }, React.createElement(Header, { colors: colors, layout: layout, linkLeft: linkLeft }) ); } }); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SymbolDiv = __webpack_require__(14); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, linkLeft: React.PropTypes.object, linkRight: React.PropTypes.object }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, linkLeft = props.linkLeft, linkRight = props.linkRight, marginWide = layout.marginWide, styleHeader = { display: 'flex', alignItems: 'flex-start', boxSizing: 'border-box', lineHeight: layout.lineHeightMeta, width: '100%', paddingLeft: linkLeft ? 0 : marginWide, paddingRight: linkRight ? 0 : marginWide, color: colors.colorMeta, backgroundColor: colors.colorBackground, borderWidth: '2px', borderBottomStyle: 'solid' }, styleHeading = { flexShrink: 1, fontSize: '1.25rem' }, symbolDiv = function symbolDiv(link, alignment) { if (link) { return React.createElement(SymbolDiv, { layout: layout, srcImage: link.srcImage, alignment: alignment, setPage: link.setPage }); } }, symbolDivLeft = symbolDiv(linkLeft, 'left'), symbolDivRight = symbolDiv(linkRight, 'right'); return React.createElement( 'header', { style: styleHeader }, symbolDivLeft, React.createElement( 'h1', { style: styleHeading }, 'Dogs-in' ), symbolDivRight ); } }); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var CategoryItem = __webpack_require__(13); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, initial: React.PropTypes.bool, categoryDefs: React.PropTypes.array, categoriesSelected: React.PropTypes.object, onCategorySelected: React.PropTypes.func }, render: function render() { var props = this.props, categoriesSelected = props.categoriesSelected, onCategorySelected = props.onCategorySelected, colors = props.colors, layout = props.layout, initial = props.initial, style = { listStyle: 'none', width: initial ? '100%' : layout.marginWide }, categoryItems = props.categoryDefs.map(function (categoryDef) { return React.createElement(CategoryItem, { colors: colors, layout: layout, initial: initial, categoryDef: categoryDef, selected: categoriesSelected[categoryDef.key], onCategorySelected: onCategorySelected }); }); return React.createElement( 'ul', { style: style }, categoryItems ); } }); /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ResultItem = __webpack_require__(11); module.exports = React.createClass({ displayName: 'exports', propTypes: { items: React.PropTypes.array, mapIndexDemo: React.PropTypes.bool, colors: React.PropTypes.object, layout: React.PropTypes.object, setItemPage: React.PropTypes.func }, style: { listStyle: 'none' }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, resultItems = props.items.map(function (item) { return React.createElement(ResultItem, { item: item, mapIndexDemo: props.mapIndexDemo, colors: colors, layout: layout, setItemPage: props.setItemPage }); }); return React.createElement( 'ul', { style: this.style }, resultItems ); } }); /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SymbolDiv = __webpack_require__(14), MapIndex = __webpack_require__(15); module.exports = React.createClass({ displayName: 'exports', propTypes: { item: React.PropTypes.object, mapIndexDemo: React.PropTypes.bool, layout: React.PropTypes.object, setItemPage: React.PropTypes.func }, onClick: function onClick() { var props = this.props, setItemPage = props.setItemPage; if (setItemPage) { setItemPage(props.item); } }, render: function render() { var props = this.props, layout = props.layout, inResultPage = !props.setItemPage, styleItem = { display: 'flex', alignItems: 'flex-start', paddingTop: layout.marginNarrow, paddingBottom: layout.marginNarrow, borderWidth: '1px', borderBottomStyle: inResultPage ? 'none' : 'solid' }, styleDiv = { flexShrink: 1 }, styleDistance = { flexShrink: 0, marginLeft: 'auto' // align right }, item = props.item, city = function city() { if (inResultPage) { return React.createElement( 'p', null, item.city + ', ' + item.state + ' ' + item.postalCode ); } }, distance = item.distance + 'mi', index; if (props.mapIndexDemo) { index = item.indexMap; } return React.createElement( 'li', { style: styleItem, onClick: this.onClick }, React.createElement(SymbolDiv, { layout: layout, srcImage: item.categoryDef.srcImage, srcImageOptional: item.dogFriendly ? 'paw.svg' : '' }), React.createElement( 'div', { style: styleDiv }, React.createElement( 'p', null, item.name ), React.createElement( 'p', null, item.address ), city() ), React.createElement( 'span', { style: styleDistance }, distance ), React.createElement(MapIndex, { colors: props.colors, layout: layout, index: index }) ); } }); /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ContactItem = __webpack_require__(16); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, contactDefs: React.PropTypes.array, contacts: React.PropTypes.object }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, contacts = props.contacts, styleList = { listStyle: 'none', width: '100%', marginTop: layout.marginNarrow }, contactItems = []; props.contactDefs.forEach(function (contactDef) { var value = contacts[contactDef.key]; if (value) { contactItems.push(React.createElement(ContactItem, { colors: colors, layout: layout, contactDef: contactDef, value: value })); } }); return React.createElement( 'ul', { style: styleList }, contactItems ); } }); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SymbolDiv = __webpack_require__(14); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, initial: React.PropTypes.bool, categoryDef: React.PropTypes.object, selected: React.PropTypes.bool, onCategorySelected: React.PropTypes.func }, onClick: function onClick() { this.props.onCategorySelected(this.props.categoryDef); }, render: function render() { var props = this.props, categoryDef = props.categoryDef, selected = props.selected, colors = props.colors, colorMeta = colors.colorMeta, colorBackground = colors.colorBackground, layout = props.layout, styleItem = { display: 'flex', alignItems: 'flex-start', lineHeight: layout.lineHeightMeta, color: selected ? colorBackground : colorMeta, backgroundColor: selected ? colorMeta : colorBackground, borderWidth: '1px', borderBottomStyle: 'solid' }, styleText = { flexShrink: 1, marginRight: layout.marginNarrow }; if (!props.initial) { styleText.display = 'none'; } return React.createElement( 'li', { style: styleItem, 'aria-clicked': props.selected, onClick: this.onClick }, React.createElement(SymbolDiv, { layout: layout, srcImage: categoryDef.srcImage }), React.createElement( 'span', { style: styleText }, categoryDef.text ) ); } }); /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = React.createClass({ displayName: 'exports', propTypes: { layout: React.PropTypes.object, srcImage: React.PropTypes.string, srcImageOptional: React.PropTypes.string, alignment: React.PropTypes.string, setPage: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { alignment: 'left' }; }, onClick: function onClick() { this.props.setPage(); }, render: function render() { var props = this.props, layout = props.layout, width = layout.widthSymbol, marginNarrow = layout.marginNarrow, left = props.alignment === 'left', styleDiv = { flexShrink: 0, display: 'flex', alignItems: 'flex-start', marginLeft: left ? 0 : 'auto', paddingLeft: left ? 0 : marginNarrow, paddingRight: left ? marginNarrow : 0 }, styleSpan = { flexShrink: 0, width: width, textAlign: 'center' }, styleImage = { height: width }, img = (function (_img) { function img(_x) { return _img.apply(this, arguments); } img.toString = function () { return _img.toString(); }; return img; })(function (srcImage) { if (srcImage) { return React.createElement('img', { style: styleImage, src: srcImage }); } }), span = (function (_span) { function span(_x2) { return _span.apply(this, arguments); } span.toString = function () { return _span.toString(); }; return span; })(function (srcImage) { return React.createElement( 'span', { style: styleSpan }, img(srcImage) ); }), spanImage = span(props.srcImage), spanImageOptional = span(props.srcImageOptional); return React.createElement( 'div', { style: styleDiv, onClick: this.onClick }, left ? spanImageOptional : spanImage, left ? spanImage : spanImageOptional ); } }); /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, index: React.PropTypes.number }, render: function render() { var props = this.props, colors = props.colors, layout = props.layout, styleDiv = { flexShrink: 0, marginLeft: layout.marginNarrow, minWidth: '2rem', // 2 * layout.widthSymbol, textAlign: 'right' }, padding = '0.25em', styleSpan = { fontWeight: 'bold', color: colors.colorBackground, backgroundColor: colors.colorItem, paddingLeft: padding, paddingRight: padding, borderTopLeftRadius: padding, borderBottomLeftRadius: padding }, index = props.index, span; if (index) { span = React.createElement( 'span', { style: styleSpan }, index ); } return React.createElement( 'div', { style: styleDiv }, span ); } }); /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var SymbolDiv = __webpack_require__(14); module.exports = React.createClass({ displayName: 'exports', propTypes: { colors: React.PropTypes.object, layout: React.PropTypes.object, contactDef: React.PropTypes.object, value: React.PropTypes.string }, onClick: function onClick() { var props = this.props; props.contactDef.callback(props.value); }, render: function render() { var props = this.props, layout = props.layout, styleItem = { display: 'flex', alignItems: 'flex-start', lineHeight: layout.lineHeightMeta, color: props.colors.colorLink, borderWidth: '1px', borderTopStyle: 'solid' }, styleValue = { flexShrink: 1, marginRight: layout.marginNarrow, whiteSpace: 'nowrap', // TODO: or 2 lines for web address? overflow: 'hidden', textOverflow: 'ellipsis' }; return React.createElement( 'li', { style: styleItem, onClick: this.onClick }, React.createElement(SymbolDiv, { layout: layout, srcImage: props.contactDef.srcImage }), React.createElement( 'span', { style: styleValue }, props.value ) ); } }); /***/ } /******/ ]);
Skookum-Nightshift/who-let-the-dogs-in
prototype.js
JavaScript
gpl-3.0
37,139
function processData(allText) { var allTextLines = allText.split(/\r\n|\n/); var headers = allTextLines[0].split(','); var lines = []; for (var i=1; i<allTextLines.length; i++) { var data = allTextLines[i].split(','); if (data.length == headers.length) { var tarr = []; for (var j=0; j<headers.length; j++) { tarr.push(headers[j]+":"+data[j]); } lines.push(tarr); } } console.log(lines); } csv = "heading1,heading2,heading3,heading4,heading5\nvalue1_1,value2_1,value3_1,value4_1,value5_1\nvalue1_2,value2_2,value3_2,value4_2,value5_2" $(document).ready(function() { $.ajax({ type: "POST", url: "/echo/html/", dataType: "text", data: { html: csv }, success: function(data) { processData(data); } }); });
Aakast/self_website
Documents/code/GIT/self_website/scripts/showCSV.js
JavaScript
gpl-3.0
905
/** Namespace NotificationsTable */ var NotificationsTable = new function() { var ns = this; // reference to the namespace ns.oTable = null; var asInitVals = []; /** Update the table to list the notifications. */ this.update = function() { ns.oTable.fnClearTable( 0 ); ns.oTable.fnDraw(); }; /** Update the table to list the notifications. */ refresh_notifications = function() { if (ns.oTable) { ns.oTable.fnClearTable( 0 ); ns.oTable.fnDraw(); } }; this.approve = function(changeRequestID) { requestQueue.register(django_url + project.id + '/changerequest/approve', "POST", { "id": changeRequestID }, function (status, text, xml) { if (status == 200) { if (text && text != " ") { var jso = JSON.parse(text); if (jso.error) { alert(jso.error); } else { refresh_notifications(); } } } else if (status == 500) { win = window.open('', '', 'width=1100,height=620'); win.document.write(text); win.focus(); } return true; }); }; this.reject = function(changeRequestID) { requestQueue.register(django_url + project.id + '/changerequest/reject', "POST", { "id": changeRequestID }, function (status, text, xml) { if (status == 200) { if (text && text != " ") { var jso = JSON.parse(text); if (jso.error) { alert(jso.error); } else { refresh_notifications(); } } } else if (status == 500) { win = window.open('', '', 'width=1100,height=620'); win.document.write(text); win.focus(); } return true; }); }; this.perform_action = function(row_id) { var node = document.getElementById('action_select_' + row_id); if (node && node.tagName == "SELECT") { var row = $(node).closest('tr'); if (1 !== row.length) { CATMAID.error("Couldn't find table row for notification"); return; } var row_data = ns.oTable.fnGetData(row[0]); var action = node.options[node.selectedIndex].value; if (action == 'Show') { SkeletonAnnotations.staticMoveTo(row_data[6], row_data[5], row_data[4], function () {SkeletonAnnotations.staticSelectNode(row_data[7], row_data[8]);}); } else if (action == 'Approve') { NotificationsTable.approve(row_data[0]); CATMAID.client.get_messages(); // Refresh the notifications icon badge } else if (action == 'Reject') { NotificationsTable.reject(row_data[0]); CATMAID.client.get_messages(); // Refresh the notifications icon badge } node.selectedIndex = 0; } }; this.init = function (pid) { ns.pid = pid; ns.oTable = $('#notificationstable').dataTable({ // http://www.datatables.net/usage/options "bDestroy": true, "sDom": '<"H"lr>t<"F"ip>', // default: <"H"lfr>t<"F"ip> "bProcessing": true, "bServerSide": true, "bAutoWidth": false, "sAjaxSource": django_url + project.id + '/notifications/list', "fnServerData": function (sSource, aoData, fnCallback) { $.ajax({ "dataType": 'json', "type": "POST", "cache": false, "url": sSource, "data": aoData, "success": fnCallback }); }, "fnRowCallback": function ( nRow, aaData, iDisplayIndex ) { // Color each row based on its status. if (aaData[3] === 'Open') { nRow.style.backgroundColor = '#ffffdd'; } else if (aaData[3] === 'Approved') { nRow.style.backgroundColor = '#ddffdd'; } else if (aaData[3] === 'Rejected') { nRow.style.backgroundColor = '#ffdddd'; } else if (aaData[3] === 'Invalid') { nRow.style.backgroundColor = '#dddddd'; } return nRow; }, "iDisplayLength": 50, "aLengthMenu": [CATMAID.pageLengthOptions, CATMAID.pageLengthLabels], "bJQueryUI": true, "aoColumns": [{ "bSearchable": false, "bSortable": true, "bVisible": false }, // id { "sClass": "center", "bSearchable": true, "bSortable": false, }, // type { "bSearchable": false, "bSortable": false, }, // description { "sClass": "center", "bSearchable": true, "bSortable": true, "sWidth": "120px" }, // status { "bSearchable": false, "bVisible": false }, // x { "bSearchable": false, "bVisible": false }, // y { "bSearchable": false, "bVisible": false }, // z { "bSearchable": false, "bVisible": false }, // node_id { "bSearchable": false, "bVisible": false }, // skeleton_id { "bSearchable": true, "bSortable": true }, // from { "bSearchable": false, "bSortable": true, "sWidth": "100px" }, // date { "sClass": "center", "bSearchable": false, "bSortable": false, "mData": null, "mRender" : function(obj, type, full) { var id = full[0]; var disabled = (full[3] == 'Open' ? '' : ' disabled'); return '<select id="action_select_' + id + '" onchange="NotificationsTable.perform_action(' + id + ')">' + ' <option>Action:</option>' + ' <option>Show</option>' + ' <option' + disabled + '>Approve</option>' + ' <option' + disabled + '>Reject</option>' + '</select>'; }, "sWidth": "100px" } // actions ] }); // filter table $.each(asInitVals, function(index, value) { if(value==="Search") return; if(value) { ns.oTable.fnFilter(value, index); } }); $("#notificationstable thead input").keyup(function () { /* Filter on the column (the index) of this element */ var i = $("thead input").index(this) + 2; asInitVals[i] = this.value; ns.oTable.fnFilter(this.value, i); }); $("#notificationstable thead input").each(function (i) { asInitVals[i+2] = this.value; }); $("#notificationstable thead input").focus(function () { if (this.className === "search_init") { this.className = ""; this.value = ""; } }); $("#notificationstable thead input").blur(function (event) { if (this.value === "") { this.className = "search_init"; this.value = asInitVals[$("thead input").index(this)+2]; } }); $('select#search_type').change( function() { ns.oTable.fnFilter( $(this).val(), 1 ); asInitVals[1] = $(this).val(); }); }; }();
catsop/CATMAID
django/applications/catmaid/static/js/widgets/table-notifications.js
JavaScript
gpl-3.0
6,977
define(["exports"], function (_exports) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.phpLang = phpLang; function phpLang(hljs) { var VARIABLE = { begin: "\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" }; var PREPROCESSOR = { className: "meta", begin: /<\?(php)?|\?>/ }; var STRING = { className: "string", contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR], variants: [{ begin: 'b"', end: '"' }, { begin: "b'", end: "'" }, hljs.inherit(hljs.APOS_STRING_MODE, { illegal: null }), hljs.inherit(hljs.QUOTE_STRING_MODE, { illegal: null })] }; var NUMBER = { variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE] }; return { aliases: ["php", "php3", "php4", "php5", "php6", "php7"], case_insensitive: true, keywords: "and include_once list abstract global private echo interface as static endswitch " + "array null if endwhile or const for endforeach self var while isset public " + "protected exit foreach throw elseif include __FILE__ empty require_once do xor " + "return parent clone use __CLASS__ __LINE__ else break print eval new " + "catch __METHOD__ case exception default die require __FUNCTION__ " + "enddeclare final try switch continue endfor endif declare unset true false " + "trait goto instanceof insteadof __DIR__ __NAMESPACE__ " + "yield finally", contains: [hljs.HASH_COMMENT_MODE, hljs.COMMENT("//", "$", { contains: [PREPROCESSOR] }), hljs.COMMENT("/\\*", "\\*/", { contains: [{ className: "doctag", begin: "@[A-Za-z]+" }] }), hljs.COMMENT("__halt_compiler.+?;", false, { endsWithParent: true, keywords: "__halt_compiler", lexemes: hljs.UNDERSCORE_IDENT_RE }), { className: "string", begin: /<<<['"]?\w+['"]?$/, end: /^\w+;?$/, contains: [hljs.BACKSLASH_ESCAPE, { className: "subst", variants: [{ begin: /\$\w+/ }, { begin: /\{\$/, end: /\}/ }] }] }, PREPROCESSOR, { className: "keyword", begin: /\$this\b/ }, VARIABLE, { // swallow composed identifiers to avoid parsing them as keywords begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/ }, { className: "function", beginKeywords: "function", end: /[;{]/, excludeEnd: true, illegal: "\\$|\\[|%", contains: [hljs.UNDERSCORE_TITLE_MODE, { className: "params", begin: "\\(", end: "\\)", contains: ["self", VARIABLE, hljs.C_BLOCK_COMMENT_MODE, STRING, NUMBER] }] }, { className: "class", beginKeywords: "class interface", end: "{", excludeEnd: true, illegal: /[:\(\$"]/, contains: [{ beginKeywords: "extends implements" }, hljs.UNDERSCORE_TITLE_MODE] }, { beginKeywords: "namespace", end: ";", illegal: /[\.']/, contains: [hljs.UNDERSCORE_TITLE_MODE] }, { beginKeywords: "use", end: ";", contains: [hljs.UNDERSCORE_TITLE_MODE] }, { begin: "=>" // No markup, just a relevance booster }, STRING, NUMBER] }; } });
elmsln/elmsln
core/dslmcode/cores/haxcms-1/build/es5-amd/node_modules/@lrnwebcomponents/code-sample/lib/highlightjs/languages/php.js
JavaScript
gpl-3.0
3,428
/** * Policy mappings (ACL) * * Policies are simply Express middleware functions which run **before** your controllers. * You can apply one or more policies to a given controller, or protect just one of its actions. * * Any policy file (e.g. `authenticated.js`) can be dropped into the `/policies` folder, * at which point it can be accessed below by its filename, minus the extension, (e.g. `authenticated`) * * For more information on policies, check out: * http://sailsjs.org/#documentation */ // var serviceStack = ADCore.policy.serviceStack([ 'policy1', 'policy2']); module.exports = { // 'opstool-process-reports/YourController': { // method: ['isAuthenticatedService'], // auth: [], // sync: serviceStack, // logout:true // } };
appdevdesigns/opstool-process-reports
config/policies.js
JavaScript
gpl-3.0
785
/* * Copyright (c) 2011-2013 Lp digital system * * This file is part of BackBuilder5. * * BackBuilder5 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BackBuilder5 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BackBuilder5. If not, see <http://www.gnu.org/licenses/>. */ define(['tb.core'], function (Core) { 'use strict'; /** * Register every routes of bundle application into Core.routeManager */ Core.RouteManager.registerRoute('user', { prefix: 'user', routes: { index: { url: '/index', action: 'MainController:index' } } }); });
ndufreche/bb-core-js-dist
src/tb/apps/user/routes.js
JavaScript
gpl-3.0
1,111
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ 'use strict' /* brave ledger integration for the brave browser module entry points: init() - called by app/index.js to start module quit() - .. .. .. .. prior to browser quitting boot() - .. .. .. .. to create wallet IPC entry point: LEDGER_PUBLISHER - called synchronously by app/extensions/brave/content/scripts/pageInformation.js CHANGE_SETTING - called asynchronously to record a settings change eventStore entry point: addChangeListener - called when tabs render or gain focus */ const fs = require('fs') const path = require('path') const url = require('url') const util = require('util') const electron = require('electron') const app = electron.app const ipc = electron.ipcMain const session = electron.session const acorn = require('acorn') const ledgerBalance = require('ledger-balance') const ledgerClient = require('ledger-client') const ledgerGeoIP = require('ledger-geoip') const ledgerPublisher = require('ledger-publisher') const qr = require('qr-image') const random = require('random-lib') const tldjs = require('tldjs') const underscore = require('underscore') const uuid = require('node-uuid') const appActions = require('../js/actions/appActions') const appConstants = require('../js/constants/appConstants') const appDispatcher = require('../js/dispatcher/appDispatcher') const messages = require('../js/constants/messages') const settings = require('../js/constants/settings') const request = require('../js/lib/request') const getSetting = require('../js/settings').getSetting const locale = require('./locale') const appStore = require('../js/stores/appStore') const eventStore = require('../js/stores/eventStore') const rulesolver = require('./extensions/brave/content/scripts/pageInformation.js') const ledgerUtil = require('./common/lib/ledgerUtil') // TBD: remove these post beta [MTR] const logPath = 'ledger-log.json' const publisherPath = 'ledger-publisher.json' const scoresPath = 'ledger-scores.json' // TBD: move these to secureState post beta [MTR] const statePath = 'ledger-state.json' const synopsisPath = 'ledger-synopsis.json' /* * ledger globals */ var bootP = false var client const clientOptions = { debugP: process.env.LEDGER_DEBUG, loggingP: process.env.LEDGER_LOGGING, verboseP: process.env.LEDGER_VERBOSE } /* * publisher globals */ var synopsis var locations = {} var publishers = {} /* * utility globals */ const msecs = { year: 365 * 24 * 60 * 60 * 1000, week: 7 * 24 * 60 * 60 * 1000, day: 24 * 60 * 60 * 1000, hour: 60 * 60 * 1000, minute: 60 * 1000, second: 1000 } /* * notification state globals */ let addFundsMessage let reconciliationMessage let suppressNotifications = false let reconciliationNotificationShown = false let notificationTimeout = null // TODO(bridiver) - create a better way to get setting changes const doAction = (action) => { switch (action.actionType) { case appConstants.APP_CHANGE_SETTING: if (action.key === settings.PAYMENTS_ENABLED) return initialize(action.value) if (action.key === settings.PAYMENTS_CONTRIBUTION_AMOUNT) return setPaymentInfo(action.value) break case appConstants.APP_NETWORK_CONNECTED: setTimeout(networkConnected, 1 * msecs.second) break default: break } } /* * module entry points */ var init = () => { try { ledgerInfo._internal.debugP = ledgerClient.prototype.boolion(process.env.LEDGER_CLIENT_DEBUG) publisherInfo._internal.debugP = ledgerClient.prototype.boolion(process.env.LEDGER_PUBLISHER_DEBUG) publisherInfo._internal.verboseP = ledgerClient.prototype.boolion(process.env.LEDGER_PUBLISHER_VERBOSE) appDispatcher.register(doAction) initialize(getSetting(settings.PAYMENTS_ENABLED)) } catch (ex) { console.log('ledger.js initialization failed: ' + ex.toString() + '\n' + ex.stack) } } var quit = () => { visit('NOOP', underscore.now(), null) } var boot = () => { if ((bootP) || (client)) return bootP = true fs.access(pathName(statePath), fs.FF_OK, (err) => { if (!err) return if (err.code !== 'ENOENT') console.log('statePath read error: ' + err.toString()) ledgerInfo.creating = true appActions.updateLedgerInfo({ creating: true }) try { client = ledgerClient(null, underscore.extend({ roundtrip: roundtrip }, clientOptions), null) } catch (ex) { appActions.updateLedgerInfo({}) bootP = false return console.log('ledger client boot error: ' + ex.toString() + '\n' + ex.stack) } if (client.sync(callback) === true) run(random.randomInt({ min: msecs.minute, max: 10 * msecs.minute })) getBalance() bootP = false }) } /* * IPC entry point */ if (ipc) { ipc.on(messages.CHECK_BITCOIN_HANDLER, (event, partition) => { const protocolHandler = session.fromPartition(partition).protocol // TODO: https://github.com/brave/browser-laptop/issues/3625 if (typeof protocolHandler.isNavigatorProtocolHandled === 'function') { ledgerInfo.hasBitcoinHandler = protocolHandler.isNavigatorProtocolHandled('bitcoin') appActions.updateLedgerInfo(underscore.omit(ledgerInfo, [ '_internal' ])) } }) ipc.on(messages.LEDGER_PUBLISHER, (event, location) => { var ctx if ((!synopsis) || (event.sender.session === session.fromPartition('default')) || (!tldjs.isValid(location))) { event.returnValue = {} return } ctx = url.parse(location, true) ctx.TLD = tldjs.getPublicSuffix(ctx.host) if (!ctx.TLD) { if (publisherInfo._internal.verboseP) console.log('\nno TLD for:' + ctx.host) event.returnValue = {} return } ctx = underscore.mapObject(ctx, function (value, key) { if (!underscore.isFunction(value)) return value }) ctx.URL = location ctx.SLD = tldjs.getDomain(ctx.host) ctx.RLD = tldjs.getSubdomain(ctx.host) ctx.QLD = ctx.RLD ? underscore.last(ctx.RLD.split('.')) : '' event.returnValue = { context: ctx, rules: publisherInfo._internal.ruleset.cooked } }) ipc.on(messages.NOTIFICATION_RESPONSE, (e, message, buttonIndex) => { const win = electron.BrowserWindow.getFocusedWindow() if (message === addFundsMessage) { appActions.hideMessageBox(message) if (buttonIndex === 0) { // Don't show notifications for the next 6 hours. suppressNotifications = true setTimeout(() => { suppressNotifications = false }, 6 * msecs.hour) } else { // Open payments panel if (win) { win.webContents.send(messages.SHORTCUT_NEW_FRAME, 'about:preferences#payments', { singleFrame: true }) } } } else if (message === reconciliationMessage) { appActions.hideMessageBox(message) if (win) { win.webContents.send(messages.SHORTCUT_NEW_FRAME, 'about:preferences#payments', { singleFrame: true }) } // If > 24 hours has passed, it might be time to show the reconciliation // message again setTimeout(() => { reconciliationNotificationShown = false }, 1 * msecs.day) } }) ipc.on(messages.ADD_FUNDS_CLOSED, () => { if (balanceTimeoutId) clearTimeout(balanceTimeoutId) balanceTimeoutId = setTimeout(getBalance, 5 * msecs.second) }) } /* * eventStore entry point */ var fileTypes = { bmp: new Buffer([ 0x42, 0x4d ]), gif: new Buffer([ 0x47, 0x49, 0x46, 0x38, [0x37, 0x39], 0x61 ]), ico: new Buffer([ 0x00, 0x00, 0x01, 0x00 ]), jpeg: new Buffer([ 0xff, 0xd8, 0xff ]), png: new Buffer([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a ]) } var signatureMax = 0 underscore.keys(fileTypes).forEach((fileType) => { if (signatureMax < fileTypes[fileType].length) signatureMax = fileTypes[fileType].length }) signatureMax = Math.ceil(signatureMax * 1.5) eventStore.addChangeListener(() => { const eventState = eventStore.getState().toJS() var view = eventState.page_view var info = eventState.page_info var pageLoad = eventState.page_load if ((!synopsis) || (!util.isArray(info))) return info.forEach((page) => { var entry, faviconURL, publisher var location = page.url if ((location.match(/^about/)) || ((locations[location]) && (locations[location].publisher))) return if (!page.publisher) { try { publisher = ledgerPublisher.getPublisher(location) if (publisher) page.publisher = publisher } catch (ex) { console.log('getPublisher error for ' + location + ': ' + ex.toString()) } } locations[location] = underscore.omit(page, [ 'url' ]) if (!page.publisher) return publisher = page.publisher synopsis.initPublisher(publisher) entry = synopsis.publishers[publisher] if ((page.protocol) && (!entry.protocol)) entry.protocol = page.protocol if ((typeof entry.faviconURL === 'undefined') && ((page.faviconURL) || (entry.protocol))) { var fetch = (url, redirects) => { if (typeof redirects === 'undefined') redirects = 0 request.request({ url: url, responseType: 'blob' }, (err, response, blob) => { var matchP, prefix, tail if (publisherInfo._internal.debugP) { console.log('\nresponse: ' + url + ' errP=' + (!!err) + ' blob=' + (blob || '').substr(0, 80) + '\nresponse=' + JSON.stringify(response, null, 2)) } if (err) return console.log('response error: ' + err.toString() + '\n' + err.stack) if ((response.statusCode === 301) && (response.headers.location)) { if (redirects < 3) fetch(response.headers.location, redirects++) return } if ((response.statusCode !== 200) || (response.headers['content-length'] === '0')) return if (blob.indexOf('data:image/') !== 0) { // NB: for some reason, some sites return an image, but with the wrong content-type... tail = blob.indexOf(';base64,') if (tail <= 0) return prefix = new Buffer(blob.substr(tail + 8, signatureMax), 'base64') underscore.keys(fileTypes).forEach((fileType) => { if (matchP) return if ((prefix.length < fileTypes[fileType].length) && (fileTypes[fileType].compare(prefix, 0, fileTypes[fileType].length) !== 0)) return blob = 'data:image/' + fileType + blob.substr(tail) matchP = true }) } entry.faviconURL = blob updatePublisherInfo() if (publisherInfo._internal.debugP) { console.log('\n' + publisher + ' synopsis=' + JSON.stringify(underscore.extend(underscore.omit(entry, [ 'faviconURL', 'window' ]), { faviconURL: entry.faviconURL && '... ' }), null, 2)) } }) } faviconURL = page.faviconURL || entry.protocol + '//' + url.parse(location).host + '/favicon.ico' entry.faviconURL = null if (publisherInfo._internal.debugP) console.log('request: ' + faviconURL) fetch(faviconURL) } }) view = underscore.last(view) || {} if (ledgerUtil.shouldTrackView(view, pageLoad)) { visit(view.url || 'NOOP', view.timestamp || underscore.now(), view.tabId) } }) /* * module initialization */ var initialize = (onoff) => { enable(onoff) if (!onoff) { client = null return appActions.updateLedgerInfo({}) } if (client) return cacheRuleSet(ledgerPublisher.rules) fs.access(pathName(statePath), fs.FF_OK, (err) => { if (!err) { if (clientOptions.verboseP) console.log('\nfound ' + pathName(statePath)) fs.readFile(pathName(statePath), (err, data) => { var state if (err) return console.log('read error: ' + err.toString()) try { state = JSON.parse(data) if (clientOptions.verboseP) console.log('\nstarting up ledger client integration') } catch (ex) { return console.log('statePath parse error: ' + ex.toString()) } getStateInfo(state) try { client = ledgerClient(state.personaId, underscore.extend(state.options, { roundtrip: roundtrip }, clientOptions), state) } catch (ex) { return console.log('ledger client creation error: ' + ex.toString() + '\n' + ex.stack) } if (client.sync(callback) === true) run(random.randomInt({ min: msecs.minute, max: 10 * msecs.minute })) cacheRuleSet(state.ruleset) // Make sure bravery props are up-to-date with user settings setPaymentInfo(getSetting(settings.PAYMENTS_CONTRIBUTION_AMOUNT)) getBalance() }) return } if (err.code !== 'ENOENT') console.log('statePath read error: ' + err.toString()) appActions.updateLedgerInfo({}) }) } var enable = (onoff) => { if (!onoff) { synopsis = null if (notificationTimeout) { clearInterval(notificationTimeout) notificationTimeout = null } return updatePublisherInfo() } synopsis = new (ledgerPublisher.Synopsis)() fs.readFile(pathName(synopsisPath), (err, data) => { if (publisherInfo._internal.verboseP) console.log('\nstarting up ledger publisher integration') if (err) { if (err.code !== 'ENOENT') console.log('synopsisPath read error: ' + err.toString()) return updatePublisherInfo() } if (publisherInfo._internal.verboseP) console.log('\nfound ' + pathName(synopsisPath)) try { synopsis = new (ledgerPublisher.Synopsis)(data) } catch (ex) { console.log('synopsisPath parse error: ' + ex.toString()) } // cf., the `Synopsis` constructor, https://github.com/brave/ledger-publisher/blob/master/index.js#L167 if (process.env.NODE_ENV === 'test') { synopsis.options.minDuration = 0 synopsis.options.minPublisherDuration = 0 synopsis.options.minPublisherVisits = 0 } else { if (process.env.LEDGER_PUBLISHER_VISIT_DURATION) { synopsis.options.minDuration = ledgerClient.prototype.numbion(process.env.LEDGER_PUBLISHER_VISIT_DURATION) } if (process.env.LEDGER_PUBLISHER_MIN_DURATION) { synopsis.options.minPublisherDuration = ledgerClient.prototype.numbion(process.env.LEDGER_PUBLISHER_MIN_DURATION) } if (process.env.LEDGER_PUBLISHER_MIN_VISITS) { synopsis.options.minPublisherVisits = ledgerClient.prototype.numbion(process.env.LEDGER_PUBLISHER_MIN_VISITS) } } underscore.keys(synopsis.publishers).forEach((publisher) => { if (synopsis.publishers[publisher].faviconURL === null) delete synopsis.publishers[publisher].faviconURL }) updatePublisherInfo() // Check if relevant browser notifications should be shown every 15 minutes notificationTimeout = setInterval(showNotifications, 15 * msecs.minute) fs.readFile(pathName(publisherPath), (err, data) => { if (err) { if (err.code !== 'ENOENT') console.log('publisherPath read error: ' + err.toString()) return } if (publisherInfo._internal.verboseP) console.log('\nfound ' + pathName(publisherPath)) try { data = JSON.parse(data) underscore.keys(data).sort().forEach((publisher) => { var entries = data[publisher] publishers[publisher] = {} entries.forEach((entry) => { locations[entry.location] = entry publishers[publisher][entry.location] = { timestamp: entry.when, tabIds: [] } }) }) } catch (ex) { console.log('publishersPath parse error: ' + ex.toString()) } }) }) } /* * update publisher information */ var publisherInfo = { synopsis: undefined, _internal: { ruleset: { raw: [], cooked: [] } } } var updatePublisherInfo = () => { var data = {} var then = underscore.now() - msecs.week if (!synopsis) return underscore.keys(publishers).sort().forEach((publisher) => { var entries = [] underscore.keys(publishers[publisher]).forEach((location) => { var when = publishers[publisher][location].timestamp if (when > then) entries.push({ location: location, when: when }) }) if (entries.length > 0) data[publisher] = entries }) syncWriter(pathName(publisherPath), data, () => {}) syncWriter(pathName(scoresPath), synopsis.allN(), () => {}) syncWriter(pathName(synopsisPath), synopsis, () => {}) publisherInfo.synopsis = synopsisNormalizer() if (publisherInfo._internal.debugP) { data = [] publisherInfo.synopsis.forEach((entry) => { data.push(underscore.extend(underscore.omit(entry, [ 'faviconURL' ]), { faviconURL: entry.faviconURL && '...' })) }) console.log('\nupdatePublisherInfo: ' + JSON.stringify(data, null, 2)) } appActions.updatePublisherInfo(underscore.omit(publisherInfo, [ '_internal' ])) } var synopsisNormalizer = () => { var i, duration, n, pct, publisher, results, total var data = [] var scorekeeper = synopsis.options.scorekeeper results = [] underscore.keys(synopsis.publishers).forEach((publisher) => { if (synopsis.publishers[publisher].scores[scorekeeper] <= 0) return if ((synopsis.options.minPublisherDuration > synopsis.publishers[publisher].duration) || (synopsis.options.minPublisherVisits > synopsis.publishers[publisher].visits)) return results.push(underscore.extend({ publisher: publisher }, underscore.omit(synopsis.publishers[publisher], 'window'))) }, synopsis) results = underscore.sortBy(results, (entry) => { return -entry.scores[scorekeeper] }) n = results.length total = 0 for (i = 0; i < n; i++) { total += results[i].scores[scorekeeper] } if (total === 0) return data pct = [] for (i = 0; i < n; i++) { publisher = synopsis.publishers[results[i].publisher] duration = results[i].duration data[i] = { rank: i + 1, // TBD: the `ledger-publisher` package does not currently report `verified` ... verified: publisher.verified || false, site: results[i].publisher, views: results[i].visits, duration: duration, daysSpent: 0, hoursSpent: 0, minutesSpent: 0, secondsSpent: 0, faviconURL: publisher.faviconURL, score: results[i].scores[scorekeeper] } // HACK: Protocol is sometimes blank here, so default to http:// so we can // still generate publisherURL. data[i].publisherURL = (results[i].protocol || 'http:') + '//' + results[i].publisher pct[i] = Math.round((results[i].scores[scorekeeper] * 100) / total) if (duration >= msecs.day) { data[i].daysSpent = Math.max(Math.round(duration / msecs.day), 1) } else if (duration >= msecs.hour) { data[i].hoursSpent = Math.max(Math.floor(duration / msecs.hour), 1) data[i].minutesSpent = Math.round((duration % msecs.hour) / msecs.minute) } else if (duration >= msecs.minute) { data[i].minutesSpent = Math.max(Math.round(duration / msecs.minute), 1) data[i].secondsSpent = Math.round((duration % msecs.minute) / msecs.second) } else { data[i].secondsSpent = Math.max(Math.round(duration / msecs.second), 1) } } // courtesy of https://stackoverflow.com/questions/13483430/how-to-make-rounded-percentages-add-up-to-100#13485888 var foo = (l, target) => { var off = target - underscore.reduce(l, (acc, x) => { return acc + Math.round(x) }, 0) return underscore.chain(l) .sortBy((x) => { return Math.round(x) - x }) .map((x, i) => { return Math.round(x) + (off > i) - (i >= (l.length + off)) }) .value() } pct = foo(pct, 100) total = 0 for (i = 0; i < n; i++) { /* if (pct[i] <= 0) { data = data.slice(0, i) break } */ if (pct[i] < 0) pct[i] = 0 data[i].percentage = pct[i] total += pct[i] } for (i = data.length - 1; (total > 100) && (i >= 0); i--) { if (data[i].percentage < 2) continue data[i].percentage-- total-- } return data } /* * publisher utilities */ var currentLocation = 'NOOP' var currentTimestamp = underscore.now() var visit = (location, timestamp, tabId) => { var setLocation = () => { var duration, publisher, revisitP if (!synopsis) return if (publisherInfo._internal.verboseP) { console.log('locations[' + currentLocation + ']=' + JSON.stringify(locations[currentLocation], null, 2) + ' duration=' + (timestamp - currentTimestamp) + ' msec' + ' tabId=' + tabId) } if ((location === currentLocation) || (!locations[currentLocation]) || (!tabId)) return publisher = locations[currentLocation].publisher if (!publisher) return if (!publishers[publisher]) publishers[publisher] = {} if (!publishers[publisher][currentLocation]) publishers[publisher][currentLocation] = { tabIds: [] } publishers[publisher][currentLocation].timestamp = timestamp revisitP = publishers[publisher][currentLocation].tabIds.indexOf(tabId) !== -1 if (!revisitP) publishers[publisher][currentLocation].tabIds.push(tabId) duration = timestamp - currentTimestamp if (publisherInfo._internal.verboseP) { console.log('\nadd publisher ' + publisher + ': ' + duration + ' msec' + ' revisitP=' + revisitP + ' state=' + JSON.stringify(underscore.extend({ location: currentLocation }, publishers[publisher][currentLocation]), null, 2)) } synopsis.addPublisher(publisher, { duration: duration, revisitP: revisitP }) updatePublisherInfo() } setLocation() if (location === currentLocation) return currentLocation = location.match(/^about/) ? 'NOOP' : location currentTimestamp = timestamp } var cacheRuleSet = (ruleset) => { var stewed, syncP if ((!ruleset) || (underscore.isEqual(publisherInfo._internal.ruleset.raw, ruleset))) return try { stewed = [] ruleset.forEach((rule) => { var entry = { condition: acorn.parse(rule.condition) } if (rule.dom) { if (rule.dom.publisher) { entry.publisher = { selector: rule.dom.publisher.nodeSelector, consequent: acorn.parse(rule.dom.publisher.consequent) } } if (rule.dom.faviconURL) { entry.faviconURL = { selector: rule.dom.faviconURL.nodeSelector, consequent: acorn.parse(rule.dom.faviconURL.consequent) } } } if (!entry.publisher) entry.consequent = rule.consequent ? acorn.parse(rule.consequent) : rule.consequent stewed.push(entry) }) publisherInfo._internal.ruleset.raw = ruleset publisherInfo._internal.ruleset.cooked = stewed if (!synopsis) return underscore.keys(synopsis.publishers).forEach((publisher) => { var location = (synopsis.publishers[publisher].protocol || 'http:') + '//' + publisher var ctx = url.parse(location, true) ctx.TLD = tldjs.getPublicSuffix(ctx.host) if (!ctx.TLD) return ctx = underscore.mapObject(ctx, function (value, key) { if (!underscore.isFunction(value)) return value }) ctx.URL = location ctx.SLD = tldjs.getDomain(ctx.host) ctx.RLD = tldjs.getSubdomain(ctx.host) ctx.QLD = ctx.RLD ? underscore.last(ctx.RLD.split('.')) : '' stewed.forEach((rule) => { if ((rule.consequent !== null) || (rule.dom)) return if (!rulesolver.resolve(rule.condition, ctx)) return if (publisherInfo._internal.verboseP) console.log('\npurging ' + publisher) delete synopsis.publishers[publisher] delete publishers[publisher] syncP = true }) }) if (!syncP) return updatePublisherInfo() } catch (ex) { console.log('ruleset error: ' + ex.toString() + '\n' + ex.stack) } } /* * update ledger information */ var ledgerInfo = { creating: false, created: false, delayStamp: undefined, reconcileStamp: undefined, reconcileDelay: undefined, transactions: [ /* { viewingId: undefined, surveyorId: undefined, contribution: { fiat: { amount: undefined, currency: undefined }, rates: { [currency]: undefined // bitcoin value in <currency> }, satoshis: undefined, fee: undefined }, submissionStamp: undefined, submissionId: undefined, count: undefined, satoshis: undefined, votes: undefined, ballots: { [publisher]: undefined } , ... */ ], // set from ledger client's state.paymentInfo OR client's getWalletProperties // Bitcoin wallet address address: undefined, // Bitcoin wallet balance (truncated BTC and satoshis) balance: undefined, unconfirmed: undefined, satoshis: undefined, // the desired contribution (the btc value approximates the amount/currency designation) btc: undefined, amount: undefined, currency: undefined, paymentURL: undefined, buyURL: undefined, bravery: undefined, hasBitcoinHandler: false, // geoIP/exchange information countryCode: undefined, exchangeInfo: undefined, _internal: { exchangeExpiry: 0, exchanges: {}, geoipExpiry: 0 }, error: null } var updateLedgerInfo = () => { var info = ledgerInfo._internal.paymentInfo var now = underscore.now() if (info) { underscore.extend(ledgerInfo, underscore.pick(info, [ 'address', 'balance', 'unconfirmed', 'satoshis', 'btc', 'amount', 'currency' ])) if ((!info.buyURLExpires) || (info.buyURLExpires > now)) ledgerInfo.buyURL = info.buyURL underscore.extend(ledgerInfo, ledgerInfo._internal.cache || {}) } if ((client) && (now > ledgerInfo._internal.geoipExpiry)) { ledgerInfo._internal.geoipExpiry = now + (5 * msecs.minute) return ledgerGeoIP.getGeoIP(client.options, (err, provider, result) => { if (err) console.log('ledger geoip warning: ' + JSON.stringify(err, null, 2)) if (result) ledgerInfo.countryCode = result ledgerInfo.exchangeInfo = ledgerInfo._internal.exchanges[ledgerInfo.countryCode] if (now <= ledgerInfo._internal.exchangeExpiry) return updateLedgerInfo() ledgerInfo._internal.exchangeExpiry = now + msecs.day roundtrip({ path: '/v1/exchange/providers' }, client.options, (err, response, body) => { if (err) console.log('ledger exchange error: ' + JSON.stringify(err, null, 2)) ledgerInfo._internal.exchanges = body || {} ledgerInfo.exchangeInfo = ledgerInfo._internal.exchanges[ledgerInfo.countryCode] updateLedgerInfo() }) }) } if (ledgerInfo._internal.debugP) { console.log('\nupdateLedgerInfo: ' + JSON.stringify(underscore.omit(ledgerInfo, [ '_internal' ]), null, 2)) } appActions.updateLedgerInfo(underscore.omit(ledgerInfo, [ '_internal' ])) } /* * ledger client callbacks */ var logs = [] var callback = (err, result, delayTime) => { var i, then var entries = client && client.report() var now = underscore.now() if (clientOptions.verboseP) { console.log('\nledger client callback: clientP=' + (!!client) + ' errP=' + (!!err) + ' resultP=' + (!!result) + ' delayTime=' + delayTime) } if (entries) { then = now - msecs.week logs = logs.concat(entries) for (i = 0; i < logs.length; i++) if (logs[i].when > then) break if ((i !== 0) && (i !== logs.length)) logs = logs.slice(i) if (result) entries.push({ who: 'callback', what: result, when: underscore.now() }) syncWriter(pathName(logPath), entries, { flag: 'a' }, () => {}) } if (err) { console.log('ledger client error(1): ' + JSON.stringify(err, null, 2) + (err.stack ? ('\n' + err.stack) : '')) if (!client) return if (typeof delayTime === 'undefined') delayTime = random.randomInt({ min: msecs.minute, max: 10 * msecs.minute }) } if (!result) return run(delayTime) if ((client) && (result.properties.wallet)) { if (!ledgerInfo.created) setPaymentInfo(getSetting(settings.PAYMENTS_CONTRIBUTION_AMOUNT)) getStateInfo(result) getPaymentInfo() } cacheRuleSet(result.ruleset) syncWriter(pathName(statePath), result, () => {}) run(delayTime) } var roundtrip = (params, options, callback) => { var i var parts = typeof params.server === 'string' ? url.parse(params.server) : typeof params.server !== 'undefined' ? params.server : typeof options.server === 'string' ? url.parse(options.server) : options.server if (!params.method) params.method = 'GET' parts = underscore.extend(underscore.pick(parts, [ 'protocol', 'hostname', 'port' ]), underscore.omit(params, [ 'headers', 'payload', 'timeout' ])) // TBD: let the user configure this via preferences [MTR] if ((parts.hostname === 'ledger.brave.com') && (params.useProxy)) parts.hostname = 'ledger-proxy.privateinternetaccess.com' i = parts.path.indexOf('?') if (i !== -1) { parts.pathname = parts.path.substring(0, i) parts.search = parts.path.substring(i) } else { parts.pathname = parts.path } options = { url: url.format(parts), method: params.method, payload: params.payload, responseType: 'text', headers: underscore.defaults(params.headers || {}, { 'content-type': 'application/json; charset=utf-8' }), verboseP: options.verboseP } request.request(options, (err, response, body) => { var payload if ((response) && (options.verboseP)) { console.log('[ response for ' + params.method + ' ' + parts.protocol + '//' + parts.hostname + params.path + ' ]') console.log('>>> HTTP/' + response.httpVersionMajor + '.' + response.httpVersionMinor + ' ' + response.statusCode + ' ' + (response.statusMessage || '')) underscore.keys(response.headers).forEach((header) => { console.log('>>> ' + header + ': ' + response.headers[header]) }) console.log('>>>') console.log('>>> ' + (body || '').split('\n').join('\n>>> ')) } if (err) return callback(err) if (Math.floor(response.statusCode / 100) !== 2) { return callback(new Error('HTTP response ' + response.statusCode) + ' for ' + params.method + ' ' + params.path) } try { payload = (response.statusCode !== 204) ? JSON.parse(body) : null } catch (err) { return callback(err) } try { callback(null, response, payload) } catch (err0) { if (options.verboseP) console.log('\ncallback: ' + err0.toString() + '\n' + err0.stack) } }) if (!options.verboseP) return console.log('<<< ' + params.method + ' ' + parts.protocol + '//' + parts.hostname + params.path) underscore.keys(options.headers).forEach((header) => { console.log('<<< ' + header + ': ' + options.headers[header]) }) console.log('<<<') if (options.payload) console.log('<<< ' + JSON.stringify(params.payload, null, 2).split('\n').join('\n<<< ')) } var runTimeoutId = false var run = (delayTime) => { if (clientOptions.verboseP) console.log('\nledger client run: clientP=' + (!!client) + ' delayTime=' + delayTime) if ((typeof delayTime === 'undefined') || (!client)) return var active, state var ballots = client.ballots() var siteSettings = appStore.getState().get('siteSettings') var winners = ((synopsis) && (ballots > 0) && (synopsis.winners(ballots))) || [] try { winners.forEach((winner) => { var result var siteSetting = siteSettings.get(`https?://${winner}`) if ((siteSetting) && (siteSetting.get('ledgerPayments') === false)) return result = client.vote(winner) if (result) state = result }) if (state) syncWriter(pathName(statePath), state, () => {}) } catch (ex) { console.log('ledger client error(2): ' + ex.toString() + (ex.stack ? ('\n' + ex.stack) : '')) } if (delayTime === 0) { try { delayTime = client.timeUntilReconcile() } catch (ex) { delayTime = false } if (delayTime === false) delayTime = random.randomInt({ min: msecs.minute, max: 10 * msecs.minute }) } if (delayTime > 0) { if (runTimeoutId) return active = client if (delayTime > (1 * msecs.hour)) delayTime = random.randomInt({ min: 3 * msecs.minute, max: msecs.hour }) runTimeoutId = setTimeout(() => { runTimeoutId = false if (active !== client) return if (!client) return console.log('\n\n*** MTR says this can\'t happen(1)... please tell him that he\'s wrong!\n\n') if (client.sync(callback) === true) return run(0) }, delayTime) return } if (client.isReadyToReconcile()) return client.reconcile(uuid.v4().toLowerCase(), callback) console.log('what? wait, how can this happen?') } /* * ledger client utilities */ var getStateInfo = (state) => { var ballots, i, transaction var info = state.paymentInfo var then = underscore.now() - msecs.year ledgerInfo.created = !!state.properties.wallet ledgerInfo.creating = !ledgerInfo.created ledgerInfo.delayStamp = state.delayStamp ledgerInfo.reconcileStamp = state.reconcileStamp ledgerInfo.reconcileDelay = state.prepareTransaction && state.delayStamp if (info) { ledgerInfo._internal.paymentInfo = info cacheReturnValue() } ledgerInfo.transactions = [] if (!state.transactions) return updateLedgerInfo() for (i = state.transactions.length - 1; i >= 0; i--) { transaction = state.transactions[i] if (transaction.stamp < then) break ballots = underscore.clone(transaction.ballots || {}) state.ballots.forEach((ballot) => { if (ballot.viewingId !== transaction.viewingId) return if (!ballots[ballot.publisher]) ballots[ballot.publisher] = 0 ballots[ballot.publisher]++ }) ledgerInfo.transactions.push(underscore.extend(underscore.pick(transaction, [ 'viewingId', 'contribution', 'submissionStamp', 'count' ]), { ballots: ballots })) } updateLedgerInfo() } var balanceTimeoutId = false var getBalance = () => { if (!client) return balanceTimeoutId = setTimeout(getBalance, 1 * msecs.minute) if (!ledgerInfo.address) return ledgerBalance.getBalance(ledgerInfo.address, underscore.extend({ balancesP: true }, client.options), (err, provider, result) => { var unconfirmed var info = ledgerInfo._internal.paymentInfo if (err) return console.log('ledger balance warning: ' + JSON.stringify(err, null, 2)) if (typeof result.unconfirmed === 'undefined') return if (result.unconfirmed > 0) { unconfirmed = (result.unconfirmed / 1e8).toFixed(4) if ((info || ledgerInfo).unconfirmed === unconfirmed) return ledgerInfo.unconfirmed = unconfirmed if (info) info.unconfirmed = ledgerInfo.unconfirmed if (clientOptions.verboseP) console.log('\ngetBalance refreshes ledger info: ' + ledgerInfo.unconfirmed) return updateLedgerInfo() } if (ledgerInfo.unconfirmed === '0.0000') return if (clientOptions.verboseP) console.log('\ngetBalance refreshes payment info') getPaymentInfo() }) } var logError = (err, caller) => { if (err) { ledgerInfo.error = { caller: caller, error: err } console.log('Error in %j: %j', caller, err) return true } else { ledgerInfo.error = null return false } } var getPaymentInfo = () => { var amount, currency if (!client) return try { ledgerInfo.bravery = client.getBraveryProperties() if (ledgerInfo.bravery.fee) { amount = ledgerInfo.bravery.fee.amount currency = ledgerInfo.bravery.fee.currency } client.getWalletProperties(amount, currency, function (err, body) { var info = ledgerInfo._internal.paymentInfo || {} if (logError(err, 'getWalletProperties')) { return } info = underscore.extend(info, underscore.pick(body, [ 'buyURL', 'buyURLExpires', 'balance', 'unconfirmed', 'satoshis' ])) info.address = client.getWalletAddress() if ((amount) && (currency)) { info = underscore.extend(info, { amount: amount, currency: currency }) if ((body.rates) && (body.rates[currency])) { info.btc = (amount / body.rates[currency]).toFixed(8) } } ledgerInfo._internal.paymentInfo = info updateLedgerInfo() cacheReturnValue() }) } catch (ex) { console.log('properties error: ' + ex.toString()) } } var setPaymentInfo = (amount) => { if (!client) return var bravery = client.getBraveryProperties() amount = parseInt(amount, 10) if (isNaN(amount) || (amount <= 0)) return underscore.extend(bravery.fee, { amount: amount }) client.setBraveryProperties(bravery, (err, result) => { if (err) return console.log('ledger setBraveryProperties: ' + err.toString()) if (result) syncWriter(pathName(statePath), result, () => {}) }) if (ledgerInfo.created) getPaymentInfo() } var cacheReturnValue = () => { var chunks, cache, paymentURL var info = ledgerInfo._internal.paymentInfo if (!info) return if (!ledgerInfo._internal.cache) ledgerInfo._internal.cache = {} cache = ledgerInfo._internal.cache paymentURL = 'bitcoin:' + info.address + '?amount=' + info.btc + '&label=' + encodeURI('Brave Software') if (cache.paymentURL === paymentURL) return cache.paymentURL = paymentURL updateLedgerInfo() try { chunks = [] qr.image(paymentURL, { type: 'png' }).on('data', (chunk) => { chunks.push(chunk) }).on('end', () => { cache.paymentIMG = 'data:image/png;base64,' + Buffer.concat(chunks).toString('base64') updateLedgerInfo() }) } catch (ex) { console.log('qr.imageSync error: ' + ex.toString()) } } var networkConnected = underscore.debounce(() => { if (!client) return if (runTimeoutId) { clearTimeout(runTimeoutId) runTimeoutId = false } if (client.sync(callback) === true) run(random.randomInt({ min: msecs.minute, max: 10 * msecs.minute })) if (balanceTimeoutId) clearTimeout(balanceTimeoutId) balanceTimeoutId = setTimeout(getBalance, 5 * msecs.second) }, 1 * msecs.minute, true) /* * low-level utilities */ var syncingP = {} var syncWriter = (path, obj, options, cb) => { if (typeof options === 'function') { cb = options options = null } options = underscore.defaults(options || {}, { encoding: 'utf8', mode: parseInt('644', 8) }) if (syncingP[path]) { syncingP[path] = { obj: obj, options: options, cb: cb } if (ledgerInfo._internal.debugP) console.log('deferring ' + path) return } syncingP[path] = true if (ledgerInfo._internal.debugP) console.log('writing ' + path) fs.writeFile(path, JSON.stringify(obj, null, 2), options, (err) => { var deferred = syncingP[path] delete syncingP[path] if (typeof deferred === 'object') { if (ledgerInfo._internal.debugP) console.log('restarting ' + path) syncWriter(path, deferred.obj, deferred.options, deferred.cb) } if (err) console.log('write error: ' + err.toString()) cb(err) }) } const pathSuffix = { development: '-dev', test: '-test' }[process.env.NODE_ENV] || '' var pathName = (name) => { var parts = path.parse(name) var basePath = process.env.NODE_ENV === 'test' ? path.join(process.env.HOME, '.brave-test-ledger') : app.getPath('userData') return path.join(basePath, parts.name + pathSuffix + parts.ext) } /** * UI controller functionality */ /** * Show message that it's time to add funds if reconciliation is less than * a day in the future and balance is too low. * 24 hours prior to reconciliation, show message asking user to review * their votes. */ const showNotifications = () => { if (!getSetting(settings.PAYMENTS_ENABLED) || !getSetting(settings.PAYMENTS_NOTIFICATIONS) || suppressNotifications) { return } const reconcileStamp = ledgerInfo.reconcileStamp const balance = Number(ledgerInfo.balance || 0) const unconfirmed = Number(ledgerInfo.unconfirmed || 0) if (reconcileStamp && reconcileStamp - underscore.now() < msecs.day) { if (ledgerInfo.btc && balance + unconfirmed < 0.9 * Number(ledgerInfo.btc)) { addFundsMessage = addFundsMessage || locale.translation('addFundsNotification') appActions.showMessageBox({ greeting: locale.translation('updateHello'), message: addFundsMessage, buttons: [ {text: locale.translation('updateLater')}, {text: locale.translation('addFunds'), className: 'primary'} ], options: { style: 'greetingStyle', persist: false } }) } else if (!reconciliationNotificationShown) { reconciliationMessage = reconciliationMessage || locale.translation('reconciliationNotification') appActions.showMessageBox({ greeting: locale.translation('updateHello'), message: reconciliationMessage, buttons: [ {text: locale.translation('reviewSites'), className: 'primary'} ], options: { style: 'greetingStyle', persist: false } }) reconciliationNotificationShown = true } } } module.exports = { init: init, quit: quit, boot: boot }
MKuenzi/browser-laptop
app/ledger.js
JavaScript
mpl-2.0
41,776
"use strict"; let Ci = Components.interfaces; let Cc = Components.classes; let Cu = Components.utils; let Cr = Components.results; var loader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader); loader.loadSubScript("resource://emic/sugar.js"); Cu.import("resource://emic/mailtodate.js"); var myStateListener = { init: function(e){ gMsgCompose.RegisterStateListener(myStateListener); emicComposeObj.init(); }, NotifyComposeFieldsReady: function() { }, NotifyComposeBodyReady: function() { }, ComposeProcessDone: function(aResult) { }, SaveInFolderDone: function(folderURI) { } }; var emicComposeObj = { consoleService: Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService), promptService: Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService), prefs: Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.emic."), global_strBundle: null, compose_strBundle: null, expdatestr: "", menu_insert_never: null, menu_insert_now: null, menu_insert_custom: null, menu_context_never: null, menu_context_now: null, menu_context_custom: null, menu_select_nothing: function(){ this.menu_insert_never .setAttribute("checked", "false"); this.menu_context_never .setAttribute("checked", "false"); this.menu_insert_now .setAttribute("checked", "false"); this.menu_context_now .setAttribute("checked", "false"); this.menu_insert_custom .setAttribute("checked", "false"); this.menu_context_custom .setAttribute("checked", "false"); }, menu_select_custom: function(){ this.menu_insert_never .setAttribute("checked", "false"); this.menu_context_never .setAttribute("checked", "false"); this.menu_insert_now .setAttribute("checked", "false"); this.menu_context_now .setAttribute("checked", "false"); this.menu_insert_custom .setAttribute("checked", "true"); this.menu_context_custom .setAttribute("checked", "true"); }, menu_select_never: function(){ this.menu_insert_now .setAttribute("checked", "false"); this.menu_context_now .setAttribute("checked", "false"); this.menu_insert_custom .setAttribute("checked", "false"); this.menu_context_custom .setAttribute("checked", "false"); this.menu_insert_never .setAttribute("checked", "true"); this.menu_context_never .setAttribute("checked", "true"); }, menu_select_now: function(){ this.menu_insert_never .setAttribute("checked", "false"); this.menu_context_never .setAttribute("checked", "false"); this.menu_insert_custom .setAttribute("checked", "false"); this.menu_context_custom .setAttribute("checked", "false"); this.menu_insert_now .setAttribute("checked", "true"); this.menu_context_now .setAttribute("checked", "true"); }, setExpirationDateCustom: function() { // this.consoleService.logStringMessage("emicComposeObj.setExpirationDateCustom() called"); // this.consoleService.logStringMessage("new Date(this.expdatestr): " + new Date(this.expdatestr).toString()); // this.consoleService.logStringMessage("subject: " + document.getElementById("msgSubject").value); // this.consoleService.logStringMessage("body: " + GetCurrentEditor().outputToString('text/plain',4)); var mailtodate = new MailToDate(document.getElementById("msgSubject").value, GetCurrentEditor().outputToString('text/plain',4)); //call Dialog: var params = {inn:{customdate:(new Date(this.expdatestr)), suggestions: mailtodate.extractDates(window.navigator.language)}, out:null}; window.openDialog("chrome://emic/content/dialogcustomdate.xul","","chrome, dialog, modal, resizable=no", params).focus(); if(params.out) { // User clicked ok. Process changed arguments; e.g. write them to disk or whatever if(params.out.datestr == this.global_strBundle.getString("global.identifier.never")) this.menu_select_never(); else if(params.out.date.isPast()) this.menu_select_now(); else this.menu_select_custom(); this.expdatestr = params.out.datestr; // this.consoleService.logStringMessage("this.expdatestr: " + this.expdatestr); } else { // User clicked cancel. Typically, nothing is done here. } }, setExpirationDateNever: function() { // this.consoleService.logStringMessage("emicComposeObj.setExpirationDateNever() called"); this.menu_select_never(); this.expdatestr = this.global_strBundle.getString("global.identifier.never"); }, setExpirationDateNow: function() { // this.consoleService.logStringMessage("emicComposeObj.setExpirationDateNow() called"); this.menu_select_now(); this.expdatestr = Date.create().toString(); }, send_event_listener: function(e) { // this.consoleService.logStringMessage("emicComposeObj.send_event_handler(e) called, e: " + e); // this.consoleService.logStringMessage("e.detail: " + e.detail); // this.consoleService.logStringMessage("e.view: " + e.view); if(this.expdatestr.length <= 0){ var result = this.promptService.confirmEx( window, this.compose_strBundle.getString("compose.noexpirationdateset.confirm.title"), this.compose_strBundle.getString("compose.noexpirationdateset.confirm.text"), Ci.nsIPromptService.STD_YES_NO_BUTTONS, null,null,null,null,{} ); if(result == 0) { // this.consoleService.logStringMessage("subject: " + gMsgCompose.compFields.subject); // this.consoleService.logStringMessage("body: " + GetCurrentEditor().outputToString('text/plain',4)); var mailtodate = new MailToDate(gMsgCompose.compFields.subject, GetCurrentEditor().outputToString('text/plain',4)); var params = {inn:{customdate:null, suggestions:mailtodate.extractDates(window.navigator.language)}, out:null}; window.openDialog("chrome://emic/content/dialogcustomdate.xul","","chrome, dialog, modal, resizable=no", params).focus(); if (params.out) { this.expdatestr = params.out.datestr; } else { this.expdatestr = this.global_strBundle.getString("global.identifier.never"); } } else { this.expdatestr = this.global_strBundle.getString("global.identifier.never"); } } if(this.expdatestr.length > 0 && this.expdatestr != this.global_strBundle.getString("global.identifier.never")) { var headeridentifieroutlook = this.global_strBundle.getString("global.identifier.expirationdate.mailheader.outlook"); if(this.prefs.getBoolPref("compose.compatiblewithoutlook") && !gMsgCompose.compFields.otherRandomHeaders.contains(headeridentifieroutlook)) gMsgCompose.compFields.otherRandomHeaders += headeridentifieroutlook + this.expdatestr + "\r\n"; var headeridentifier = this.global_strBundle.getString("global.identifier.expirationdate.mailheader"); if(!gMsgCompose.compFields.otherRandomHeaders.contains(headeridentifier)) gMsgCompose.compFields.otherRandomHeaders += headeridentifier + this.expdatestr + "\r\n"; } }, init: function() { // this.consoleService.logStringMessage("emicComposeObj.init() called"); // this.setExpirationDateNever(); //not optimal this.expdatestr = ""; // this.consoleService.logStringMessage("expdatestr: " + this.expdatestr); this.global_strBundle = document.getElementById("emic-strings-global"); this.compose_strBundle = document.getElementById("emic-strings-compose"); this.menu_insert_never = document.getElementById("emic-menu-compose-insert-never"); this.menu_insert_now = document.getElementById("emic-menu-compose-insert-now"); this.menu_insert_custom = document.getElementById("emic-menu-compose-insert-custom"); this.menu_context_never = document.getElementById("emic-menu-compose-context-never"); this.menu_context_now = document.getElementById("emic-menu-compose-context-now"); this.menu_context_custom = document.getElementById("emic-menu-compose-context-custom"); this.menu_select_nothing(); } } window.addEventListener( "compose-send-message", function(e){emicComposeObj.send_event_listener(e);}, true); window.addEventListener( "compose-window-init", myStateListener.init, true);
XxJo3yxX/emic
content/compose.js
JavaScript
mpl-2.0
8,930
const products = [{id : 'classic', name : 'Classic Ad', price : 269.99}, {id : 'standout', name : 'Standout Ad', price : 322.99}, {id : 'premium', name : 'Premium Ad', price : 394.99}] class ProductDao { constructor() { console.log('Instantiating ProductDao') } listAll(){ return products } findById(id){ } } module.exports = new ProductDao
marcos-goes/ads-checkout-nodejs
dao/ProductDao.js
JavaScript
mpl-2.0
408
import Ember from 'ember'; const { Route, RSVP } = Ember; export default Route.extend({ model() { const job = this.modelFor('jobs.job'); return RSVP.all([job.get('deployments'), job.get('versions')]).then(() => job); }, });
Ashald/nomad
ui/app/routes/jobs/job/deployments.js
JavaScript
mpl-2.0
238
import animate; import event.Emitter as Emitter; import device; import ui.View; import ui.ImageView; import ui.TextView; import src.Match3Core as Core; import src.Utils as Utils; //var Chance = require('chance'); //Some constants var CoreGame = new Core(); var level = new Core(); //var chance = new Chance(); /* The Game Screen code. * The child of the main application in * the game. Everything else is a child * of game so it is all visible. */ exports = Class(ui.View, function(supr) { this.init = function(opts) { opts = merge(opts, { x: 0, y: 0, width: 576, height: 1024, backgroundColor: '#37b34a' }); supr(this, 'init', [opts]); this.build(); }; this.build = function() { this.on('app:start', start_game_flow.bind(this)); }; // Main Menu Functions this.SetMenu = function(menu) { this._menu = menu; }; this.GetMenu = function() { return this._menu; }; this.OnLaunchMainMenu = function(){ this.emit('MainMenu'); }; }); /* function ReadyGame() { CoreGame.InitializeBoard(); CoreGame.CreateLevel(); //Find Initial Moves and Clusters CoreGame.FindMoves(); CoreGame.FindClusters(); } */ // Starts the game function start_game_flow() { CoreGame.ReadyGame(); play_game(this); } // Game play function play_game() { if(CoreGame.moves.length === 0) { end_game_flow.call(this); } } // function tick() {} // function update_countdown() {} // Game End function end_game_flow() { //slight delay before allowing a tap reset setTimeout(emit_endgame_event.bind(this), 2000); } function emit_endgame_event() { this.once('InputSelect', function() { this.emit('gamescreen:end'); reset_game.call(this); }); } function reset_game() {}
CoderBear/HoneyBear
src/GameScreen.js
JavaScript
mpl-2.0
1,811
var fs = require("fs"); var path = require("path"); var _ = require("underscore"); var chai = require("chai"); var expect = chai.expect; var profile = require("../../lib/profile"); var PREFS = require("../../data/preferences"); var simpleXpiPath = path.join(__dirname, '..', 'xpis', 'simple-addon.xpi'); describe("lib/profile", function () { it("creates a profile and returns the path", function (done) { profile().then(function (profilePath) { var contents = fs.readFileSync(path.join(profilePath, "user.js"), "utf8"); expect(contents).to.be.ok; }) .then(done, done); }); it("creates a profile with proper default preferences (Firefox)", function (done) { profile().then(function (profilePath) { var contents = fs.readFileSync(path.join(profilePath, "user.js"), "utf8"); var defaults = _.extend({}, PREFS.DEFAULT_COMMON_PREFS, PREFS.DEFAULT_FIREFOX_PREFS); comparePrefs(defaults, contents); }) .then(done, done); }); it("creates a profile with an addon installed when given a XPI", function (done) { profile({ xpi: simpleXpiPath }).then(function (profilePath) { var addonPath = path.join(profilePath, "extensions", "simple-addon"); var files = fs.readdirSync(addonPath, "utf8"); var index = fs.readFileSync(path.join(addonPath, "index.js")); var manifest = fs.readFileSync(path.join(addonPath, "package.json")); expect(index).to.be.ok; expect(manifest).to.be.ok; }) .then(done, done); }); }); function comparePrefs (defaults, prefs) { var count = Object.keys(defaults).length; prefs.split("\n").forEach(function (pref) { var parsed = pref.match(/user_pref\("(.*)", "?([^"]*)"?\)\;$/); if (!parsed || parsed.length < 2) return; var key = parsed[1]; var value = parsed[2]; // Cast booleans and numbers in string formative to primitives if (value === 'true') value = true; else if (value === 'false') value = false; else if (!isNaN(parseFloat(value)) && isFinite(value)) value = +value; // TODO need to override firefox-profile setting default prefs // but we still override them if we explicitly set them if (key in defaults) { expect(defaults[key]).to.be.equal(value); --count; } }); expect(count).to.be.equal(0); }
Gozala/jpm
test/unit/test.profile.js
JavaScript
mpl-2.0
2,323
var langPrettyprint = {"bg":"Bulgarian","ca@valencia":"Catalan (Valencian)","cs":"Czech","da":"Danish","de":"German","el":"Greek","en":"English","en-GB":"English (United Kingdom)","eo":"Esperanto","es":"Spanish","es-ES":"Spanish (Spain)","eu":"Basque","fi":"Finnish","fr":"French","fr-CA":"French (Canada)","fy":"Western Frisian","hu":"Hungarian","id":"Indonesian","it":"Italian","ja":"Japanese","ko-KR":"Korean (Korea)","lt":"Lithuanian","nb":"Norwegian Bokmål","nl":"Dutch","nn":"Norwegian Nynorsk","pl":"Polish","pt-BR":"Portuguese (Brazil)","pt-PT":"Portuguese (Portugal)","ru":"Russian","sk":"Slovak","sv":"Swedish","tr":"Turkish","uk":"Ukrainian","vi":"Vietnamese","zh-CN":"Chinese (China)"}
nrm21/syncthing
gui/default/assets/lang/prettyprint.js
JavaScript
mpl-2.0
699
/* @flow */ import * as React from 'react'; import Link from 'amo/components/Link'; import { addParamsToHeroURL, checkInternalURL } from 'amo/utils'; import tracking from 'core/tracking'; import LoadingText from 'ui/components/LoadingText'; import type { HeroCallToActionType, SecondaryHeroShelfType, } from 'amo/reducers/home'; import './styles.scss'; export const SECONDARY_HERO_CLICK_CATEGORY = 'AMO Secondary Hero Clicks'; export const SECONDARY_HERO_SRC = 'homepage-secondary-hero'; type Props = {| shelfData?: SecondaryHeroShelfType |}; type InternalProps = {| ...Props, _checkInternalURL: typeof checkInternalURL, _tracking: typeof tracking, |}; const makeCallToActionURL = (urlString: string) => { return addParamsToHeroURL({ heroSrcCode: SECONDARY_HERO_SRC, urlString }); }; export const SecondaryHeroBase = ({ _checkInternalURL = checkInternalURL, _tracking = tracking, shelfData, }: InternalProps) => { const { headline, description, cta } = shelfData || {}; const modules = (shelfData && shelfData.modules) || Array(3).fill({}); const onHeroClick = (event: SyntheticEvent<HTMLAnchorElement>) => { _tracking.sendEvent({ action: event.currentTarget.href, category: SECONDARY_HERO_CLICK_CATEGORY, }); }; const getLinkProps = (link: HeroCallToActionType | null) => { const props = { onClick: onHeroClick }; if (link) { const urlInfo = _checkInternalURL({ urlString: link.url }); if (urlInfo.isInternal) { return { ...props, to: makeCallToActionURL(urlInfo.relativeURL) }; } return { ...props, href: makeCallToActionURL(link.url), prependClientApp: false, prependLang: false, target: '_blank', }; } return {}; }; const renderedModules = []; modules.forEach((module) => { renderedModules.push( <div className="SecondaryHero-module" key={module.description}> {module.icon ? ( <img alt={module.description} className="SecondaryHero-module-icon" src={module.icon} /> ) : ( <div className="SecondaryHero-module-icon" /> )} <div className="SecondaryHero-module-description"> {module.description || <LoadingText width={60} />} </div> {module.cta && ( <Link className="SecondaryHero-module-link" {...getLinkProps(module.cta)} > <span className="SecondaryHero-module-linkText"> {module.cta.text} </span> </Link> )} {!module.description && ( <div className="SecondaryHero-module-link"> <LoadingText width={50} /> </div> )} </div>, ); }); return ( <section className="SecondaryHero"> <div className="SecondaryHero-message"> <h2 className="SecondaryHero-message-headline"> {headline || ( <> <LoadingText width={70} /> <br /> <LoadingText width={50} /> </> )} </h2> <div className="SecondaryHero-message-description"> {description || ( <> <LoadingText width={80} /> <br /> <LoadingText width={60} /> </> )} </div> {cta && ( <Link className="SecondaryHero-message-link" {...getLinkProps(cta)}> <span className="SecondaryHero-message-linkText">{cta.text}</span> </Link> )} {!headline && ( <div className="SecondaryHero-message-link"> <LoadingText width={50} /> </div> )} </div> {renderedModules} </section> ); }; export default SecondaryHeroBase;
kumar303/addons-frontend
src/amo/components/SecondaryHero/index.js
JavaScript
mpl-2.0
3,823
#!/usr/bin/env node const fs = require('fs'); const Gcp = require('../static/app/js/classes/Gcp'); const argv = process.argv.slice(2); function die(s){ console.log(s); process.exit(1); } if (argv.length != 2){ die(`Usage: ./resize_gcp.js <path/to/gcp_file.txt> <JSON encoded image-->ratio map>`); } const [inputFile, jsonMap] = argv; if (!fs.existsSync(inputFile)){ die('File does not exist: ' + inputFile); } const originalGcp = new Gcp(fs.readFileSync(inputFile, 'utf8')); try{ const map = JSON.parse(jsonMap); const newGcp = originalGcp.resize(map, true); console.log(newGcp.toString()); }catch(e){ die("Not a valid JSON string: " + jsonMap); }
pierotofy/WebODM
app/scripts/resize_gcp.js
JavaScript
mpl-2.0
658
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2015, Joyent, Inc. */ var url = require('url'); var assert = require('assert-plus'); var async = require('async'); var libuuid = require('libuuid'); var common = require('./common'); var vmTest = require('./lib/vm'); var MORAY = require('../lib/apis/moray'); var sortValidation = require('../lib/validation/sort.js'); var vmCommon = require('../lib/common/vm-common.js'); var client; exports.setUp = function (callback) { common.setUp(function (err, _client) { assert.ifError(err); assert.ok(_client, 'restify client'); client = _client; callback(); }); }; /* * Creates a marker object that can be used to paginate through ListVms's * results. It returns an object that has the properties listed in the * "markerKeys" array and the values for these keys are copied from the * "vmObject" object. */ function buildMarker(vmObject, markerKeys) { assert.object(vmObject, 'vmObject must be an object'); assert.arrayOfString(markerKeys, 'markerKeys must be an array of strings'); var marker = {}; markerKeys.forEach(function (markerKey) { if (markerKey === 'tags') marker[markerKey] = vmCommon.objectToTagFormat(vmObject[markerKey]); else marker[markerKey] = vmObject[markerKey]; }); return marker; } /* * This function creates a large number of "test" VMs * (VMs with alias='test--', unless otherwise specified), and then sends GET * requests to /vms to retrieve them by chunks. It uses the "marker" * querystring param to paginate through the results. It then makes sure that * after going through all test VMs, a subsequent request returns an empty set. * Finally, it checks that there's no overlap between the different chunks * received. */ function testMarkerPagination(options, t, callback) { options = options || {}; assert.object(options, 'options'); assert.object(t, 't'); assert.func(callback, 'callback'); var NB_TEST_VMS_TO_CREATE = options.nbTestVms || 200; var LIMIT = NB_TEST_VMS_TO_CREATE / 2; var moray = new MORAY(common.config.moray); moray.connect(); var vmsCreationParams = options.vmsCreationParams || {}; assert.object(vmsCreationParams, 'options.vmsCreationParams must be an object'); assert.ok(typeof (options.sort === 'string') || options.sort === undefined, 'options.sort must be undefined or a string'); var queryStringObject = { limit: LIMIT }; if (vmsCreationParams.alias !== undefined) queryStringObject.alias = vmTest.TEST_VMS_ALIAS + vmsCreationParams.alias; else queryStringObject.alias = vmTest.TEST_VMS_ALIAS; if (options.sort !== undefined) queryStringObject.sort = options.sort; var markerKeys = options.markerKeys || []; assert.arrayOfString(markerKeys, 'options.markerKeys must be an array of strings'); moray.once('moray-ready', function () { var firstVmsChunk; var secondVmsChunk; async.waterfall([ // Delete test VMs leftover from previous tests run function deleteTestVms(next) { vmTest.deleteTestVMs(moray, {}, function vmsDeleted(err) { t.ifError(err, 'deleting test VMs should not error'); return next(err); }); }, function createFakeVms(next) { vmTest.createTestVMs(NB_TEST_VMS_TO_CREATE, moray, {concurrency: 100}, vmsCreationParams, function fakeVmsCreated(err, vmsUuid) { moray.connection.close(); t.equal(vmsUuid.length, NB_TEST_VMS_TO_CREATE, NB_TEST_VMS_TO_CREATE + ' vms should have been created'); t.ifError(err, NB_TEST_VMS_TO_CREATE + ' vms should be created successfully'); return next(err); }); }, function listFirstVmsChunk(next) { var listVmsQuery = url.format({pathname: '/vms', query: queryStringObject}); client.get(listVmsQuery, function (err, req, res, body) { var lastItem; t.ifError(err); if (err) return next(err); t.equal(res.headers['x-joyent-resource-count'], NB_TEST_VMS_TO_CREATE, 'x-joyent-resource-count header should be equal to ' + NB_TEST_VMS_TO_CREATE); t.equal(body.length, LIMIT, LIMIT + ' vms should be returned from first list vms'); lastItem = body[body.length - 1]; var marker = buildMarker(lastItem, markerKeys); firstVmsChunk = body; return next(null, JSON.stringify(marker)); }); }, function listNextVmsChunk(marker, next) { assert.string(marker, 'marker'); queryStringObject.marker = marker; var listVmsQuery = url.format({pathname: '/vms', query: queryStringObject}); client.get(listVmsQuery, function (err, req, res, body) { var lastItem; t.ifError(err); if (err) return next(err); t.equal(res.headers['x-joyent-resource-count'], NB_TEST_VMS_TO_CREATE, 'x-joyent-resource-count header should be equal to ' + NB_TEST_VMS_TO_CREATE); t.equal(body.length, LIMIT, 'second vms list request should return ' + LIMIT + ' vms'); lastItem = body[body.length - 1]; var nextMarker = buildMarker(lastItem, markerKeys); secondVmsChunk = body; return next(null, JSON.stringify(nextMarker)); }); }, function listLastVmsChunk(marker, next) { assert.string(marker, 'marker must be a string'); queryStringObject.marker = marker; var listVmsQuery = url.format({pathname: '/vms', query: queryStringObject}); client.get(listVmsQuery, function (err, req, res, body) { t.ifError(err); if (err) return next(err); t.equal(res.headers['x-joyent-resource-count'], NB_TEST_VMS_TO_CREATE, 'x-joyent-resource-count header should be equal to ' + NB_TEST_VMS_TO_CREATE); t.equal(body.length, 0, 'last vms list request should return no vm'); return next(); }); }, function checkNoOverlap(next) { function getVmUuid(vm) { assert.object(vm, 'vm must be an object'); return vm.uuid; } var firstVmsChunkUuids = firstVmsChunk.map(getVmUuid); var secondVmsChunkUuids = secondVmsChunk.map(getVmUuid); var chunksOverlap = firstVmsChunkUuids.some(function (vmUuid) { return secondVmsChunkUuids.indexOf(vmUuid) !== -1; }); t.equal(chunksOverlap, false, 'subsequent responses should not overlap'); return next(); } ], function allDone(err, results) { t.ifError(err); return callback(); }); }); } /* * Checks that invalid markers result in the response containing * the proper error status code and error message. */ exports.list_vms_marker_not_valid_JSON_object_not_ok = function (t) { async.eachSeries([ '["uuid: 00000000-0000-0000-0000-000000000000"]', '00000000-0000-0000-0000-000000000000', '""', '' ], function testBadMarker(badMarker, next) { var expectedError = { code: 'ValidationFailed', message: 'Invalid Parameters', errors: [ { field: 'marker', code: 'Invalid', message: 'Invalid marker: ' + JSON.stringify(badMarker) + '. Marker must represent an object.' }] }; return common.testListInvalidParams(client, {marker: JSON.stringify(badMarker)}, expectedError, t, next); }, function allDone(err) { t.done(); }); }; /* * Using offset and marker params in the same request is not valid. * Check that using them both in the same request results in the * response having the proper error code and message. */ exports.list_vms_offset_and_marker_not_ok = function (t) { var FAKE_VM_UUID = '00000000-0000-0000-0000-000000000000'; var marker = { uuid: FAKE_VM_UUID }; var queryString = '/vms?offset=1&marker=' + JSON.stringify(marker); client.get(queryString, function (err, req, res, body) { t.equal(res.statusCode, 409); t.deepEqual(body, { code: 'ValidationFailed', message: 'Invalid Parameters', errors: [ { fields: ['offset', 'marker'], code: 'ConflictingParameters', message: 'offset and marker cannot be used at the same time' } ] }); t.done(); }); }; /* * Checks that using the only key that can establish a strict total order * as a marker to paginate through a test VMs set works as expected, * without any error. */ exports.list_vms_marker_ok = function (t) { testMarkerPagination({ markerKeys: ['uuid'] }, t, function testDone() { t.done(); }); }; /* * Cleanup test VMs created by the previous test (list_vms_marker_ok). */ exports.delete_test_vms_marker_ok = function (t) { var moray = new MORAY(common.config.moray); moray.connect(); moray.once('moray-ready', function () { vmTest.deleteTestVMs(moray, {}, function testVmsDeleted(err) { moray.connection.close(); t.ifError(err, 'deleting fake VMs should not error'); t.done(); }); }); }; /* * Same test as list_vms_marker_ok, but adding a sort param on uuid ascending. * Check that it works successfully as expected. */ exports.list_vms_marker_and_sort_on_uuid_asc_ok = function (t) { testMarkerPagination({ sort: 'uuid.ASC', markerKeys: ['uuid'] }, t, function testDone() { t.done(); }); }; /* * Cleanup test VMs created by the previous test * (list_vms_marker_and_sort_on_uuid_asc_ok). */ exports.delete_test_vms_marker_and_sort_on_uuid_asc_ok = function (t) { var moray = new MORAY(common.config.moray); moray.connect(); moray.once('moray-ready', function () { vmTest.deleteTestVMs(moray, {}, function testVmsDeleted(err) { moray.connection.close(); t.ifError(err, 'deleting fake VMs should not error'); t.done(); }); }); }; /* * Same test as list_vms_marker_ok, but adding a sort param on uuid descending. * Check that it works successfully as expected. */ exports.list_vms_marker_and_sort_on_uuid_desc_ok = function (t) { testMarkerPagination({ sort: 'uuid.DESC', markerKeys: ['uuid'] }, t, function testDone() { t.done(); }); }; /* * Cleanup test VMs created by the previous test * (list_vms_marker_and_sort_on_uuid_desc_ok). */ exports.delete_test_vms_marker_and_sort_on_uuid_desc_ok = function (t) { var moray = new MORAY(common.config.moray); moray.connect(); moray.once('moray-ready', function () { vmTest.deleteTestVMs(moray, {}, function testVmsDeleted(err) { moray.connection.close(); t.ifError(err, 'deleting fake VMs should not error'); t.done(); }); }); }; exports.marker_key_not_in_sort_field_not_ok = function (t) { var TEST_MARKER = {create_timestamp: Date.now(), uuid: libuuid.create()}; var expectedError = { code: 'ValidationFailed', message: 'Invalid Parameters', errors: [ { field: 'marker', code: 'Invalid', message: 'Invalid marker: ' + JSON.stringify(TEST_MARKER) + '. All marker keys except uuid must be present in the sort ' + 'parameter. Sort fields: undefined.' } ] }; common.testListInvalidParams(client, {marker: JSON.stringify(TEST_MARKER)}, expectedError, t, function testDone(err) { t.done(); }); }; /* * Most sort parameters do not allow to establish a strict total order relation * between all VMs. For instance, sorting on "create_timestamp" and paginating * through results by using the create_timestamp property as a marker, * it is possible that two VM objects have the same create_timestamp. When * sending the create_timestamp value of the latest VM item from the first page * of results as a marker to get the second page of results, the server cannot * tell which one of the two VMs the marker represents, and thus results can * be unexpected. * * In order to be able to "break the tie", an attribute of VMs that allows * to establish a strict total order has to be specified in the marker. * Currently, the only attribute that has this property is "uuid". * * For each VM attribute on which users can sort that do not provide a strict * total order, the tests below a series of tests that uses each sort criteria * and a variety of marker configurations to make sure that the implementation * behaves as expected. */ /* * This table associates each sort key that doesn't provide a strict * total order with a constant value. These constant values are used * for all VMs of a test data set, so that using only these keys in * a marker to identify the first item of the next page of results is * not sufficient. */ var NON_STRICT_TOTAL_ORDER_SORT_KEYS = { owner_uuid: libuuid.create(), image_uuid: libuuid.create(), billing_id: libuuid.create(), server_uuid: libuuid.create(), package_name: 'package_name_foo', package_version: 'package_version_foo', tags: vmCommon.objectToTagFormat({sometag: 'foo'}), brand: 'foobrand', state: 'test', alias: 'test--marker-pagination', max_physical_memory: 42, create_timestamp: Date.now(), docker: true }; /* * Given a sort key, creates a set of tests that check a few expected * behaviors with that key. */ function createMarkerTests(sortKey, exports) { assert.string(sortKey, 'sortKey must be a string'); assert.object(exports, 'exports must be an object'); sortValidation.VALID_SORT_ORDERS.forEach(function (sortOrder) { createValidMarkerTest(sortKey, sortOrder, exports); createDeleteVMsTest(sortKey, sortOrder, exports); createSortKeyNotInMarkerTest(sortKey, sortOrder, exports); createNoStrictTotalOrderKeyInMarkerTest(sortKey, sortOrder, exports); }); } /* * Given a sort key and a sort order, it creates a fake data set with the same * value for the property "sortKey". Then, it paginates through this data set * by using a marker composed of the sort key and "uuid" (which establishes a * strict total order) and checks that it can paginate through the all results * set without any error and duplicate entries. */ function createValidMarkerTest(sortKey, sortOrder, exports) { var newTestName = 'list_vms_marker_with_identical_' + sortKey + '_' + sortOrder + '_ok'; var vmsCreationParams = {}; vmsCreationParams[sortKey] = NON_STRICT_TOTAL_ORDER_SORT_KEYS[sortKey]; exports[newTestName] = function (t) { testMarkerPagination({ sort: sortKey + '.' + sortOrder, markerKeys: [sortKey, 'uuid'], vmsCreationParams: vmsCreationParams }, t, function testDone() { t.done(); }); }; } /* * Creates a test that deletes the fake VMs created by the tests created * by createValidMarkerTest. */ function createDeleteVMsTest(sortKey, sortOrder, exports) { var clearVmsTestName = 'delete_test_vms_marker_with_identical_' + sortKey + '_' + sortOrder + '_ok'; exports[clearVmsTestName] = function (t) { var moray = new MORAY(common.config.moray); moray.connect(); moray.once('moray-ready', function () { vmTest.deleteTestVMs(moray, {}, function testVmsDeleted(err) { moray.connection.close(); t.ifError(err, 'deleting fake VMs should not error'); t.done(); }); }); }; } /* * Creates a test that makes sure that when using sort to list VMs and a * marker, not adding the sort key to the marker results in the proper error * being sent. */ function createSortKeyNotInMarkerTest(sortKey, sortOrder, exports) { var testName = 'list_vms_marker_sortkey_' + sortKey + '_' + sortOrder + '_not_in_marker_not_ok'; var TEST_MARKER = {uuid: 'some-uuid'}; var TEST_SORT_PARAM = sortKey + '.' + sortOrder; var expectedError = { code: 'ValidationFailed', message: 'Invalid Parameters', errors: [ { field: 'marker', code: 'Invalid', message: 'Invalid marker: ' + JSON.stringify(TEST_MARKER) + '. All sort fields must be present in marker. Sort fields: ' + TEST_SORT_PARAM + '.' } ] }; exports[testName] = function (t) { common.testListInvalidParams(client, {marker: JSON.stringify(TEST_MARKER), sort: TEST_SORT_PARAM}, expectedError, t, function testDone(err) { t.done(); }); }; } /* * Creates a test that makes sure that when using a marker without a property * that can establish a strict total order over a set of VMs, the proper error * is sent. */ function createNoStrictTotalOrderKeyInMarkerTest(sortKey, sortOrder, exports) { var testName = 'list_vms_marker_' + sortKey + '_' + sortOrder + '_no_strict_total_order_key'; exports[testName] = function (t) { var TEST_MARKER = {}; TEST_MARKER[sortKey] = NON_STRICT_TOTAL_ORDER_SORT_KEYS[sortKey]; var expectedError = { code: 'ValidationFailed', message: 'Invalid Parameters', errors: [ { field: 'marker', code: 'Invalid', message: 'Invalid marker: ' + JSON.stringify(TEST_MARKER) + '. A marker needs to have a uuid property from ' + 'which a strict total order can be established' } ] }; common.testListInvalidParams(client, {marker: JSON.stringify(TEST_MARKER), sort: sortKey}, expectedError, t, function testDone(err) { t.done(); }); }; } Object.keys(NON_STRICT_TOTAL_ORDER_SORT_KEYS).forEach(function (sortKey) { createMarkerTests(sortKey, exports); });
richardkiene/sdc-vmapi
test/vms.marker.test.js
JavaScript
mpl-2.0
19,701
// listen and handle messages from the content script // via the background script import { addStackingContext } from "./actions/stacking-context"; function connectToInspectedWindow({ dispatch }) { browser.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.tabId !== browser.devtools.inspectedWindow.tabId) { return; } switch (request.action) { case "SET_STACKING_CONTEXT_TREE": const { tree, selector } = request.data; dispatch(addStackingContext(tree, selector)); } }); } export { connectToInspectedWindow };
gregtatum/z-index-devtool
extension/src/bootstrap.js
JavaScript
mpl-2.0
588
/** * Image Processing * * In imaging science, image processing is any form of signal processing for * which the input is an image, such as a photograph or video frame; the output * of image processing may be either an image or a set of characteristics or * parameters related to the image. Most image-processing techniques involve * treating the image as a two-dimensional signal and applying standard * signal-processing techniques to it. * * -->Image Processing (image in -> image out) * Image Analysis (image in -> measurements out) * Image Understanding (image in -> high-level description out) * * - http://en.wikipedia.org/wiki/Image_processing */ var util = require('util'); var stream = require('stream'); var Transform = stream.Transform; var cv = require('opencv'); function Processing(settings, options) { if (!(this instanceof Processing)) return new Processing(options); if (options === undefined) options = {}; options.objectMode = true; Transform.call(this, options); this.settings = settings; this.decodeSettings(); } util.inherits(Processing, Transform); Processing.prototype.decodeSettings = function() { var profile = this.settings.profile; this.profile = this.settings[profile]; this.lowerbound = this.profile.lowerb.reverse(); this.upperbound = this.profile.upperb.reverse(); }; /** * Expects a full image */ Processing.prototype._transform = function(chunk, encoding, callback) { var self = this; cv.readImage(chunk, function(err, image) { // Color filter image.inRange(self.lowerbound, self.upperbound); // Do canny operations on a copy var im_canny = image.copy(); // Feature detection with canny algorithm im_canny.canny(self.settings.lowThresh, self.settings.highThresh); im_canny.dilate(self.settings.nIters); // All done self.push({ 'original': chunk, 'image': image }); callback(); }); }; module.exports = Processing;
team178/oculus.js
lib/processing.js
JavaScript
mpl-2.0
1,968
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileOverview WebAudio layout test utility library. Built around W3C's * testharness.js. Includes asynchronous test task manager, * assertion utilities. * @dependency testharness.js */ (function() { 'use strict'; // Selected methods from testharness.js. let testharnessProperties = [ 'test', 'async_test', 'promise_test', 'promise_rejects', 'generate_tests', 'setup', 'done', 'assert_true', 'assert_false' ]; // Check if testharness.js is properly loaded. Throw otherwise. for (let name in testharnessProperties) { if (!self.hasOwnProperty(testharnessProperties[name])) throw new Error('Cannot proceed. testharness.js is not loaded.'); } })(); window.Audit = (function() { 'use strict'; // NOTE: Moving this method (or any other code above) will change the location // of 'CONSOLE ERROR...' message in the expected text files. function _logError(message) { console.error('[audit.js] ' + message); } function _logPassed(message) { test(function(arg) { assert_true(true); }, message); } function _logFailed(message, detail) { test(function() { assert_true(false, detail); }, message); } function _throwException(message) { throw new Error(message); } // TODO(hongchan): remove this hack after confirming all the tests are // finished correctly. (crbug.com/708817) const _testharnessDone = window.done; window.done = () => { _throwException('Do NOT call done() method from the test code.'); }; // Generate a descriptive string from a target value in various types. function _generateDescription(target, options) { let targetString; switch (typeof target) { case 'object': // Handle Arrays. if (target instanceof Array || target instanceof Float32Array || target instanceof Float64Array || target instanceof Uint8Array) { let arrayElements = target.length < options.numberOfArrayElements ? String(target) : String(target.slice(0, options.numberOfArrayElements)) + '...'; targetString = '[' + arrayElements + ']'; } else if (target === null) { targetString = String(target); } else { targetString = '' + String(target).split(/[\s\]]/)[1]; } break; case 'function': if (Error.isPrototypeOf(target)) { targetString = "EcmaScript error " + target.name; } else { targetString = String(target); } break; default: targetString = String(target); break; } return targetString; } // Return a string suitable for printing one failed element in // |beCloseToArray|. function _formatFailureEntry(index, actual, expected, abserr, threshold) { return '\t[' + index + ']\t' + actual.toExponential(16) + '\t' + expected.toExponential(16) + '\t' + abserr.toExponential(16) + '\t' + (abserr / Math.abs(expected)).toExponential(16) + '\t' + threshold.toExponential(16); } // Compute the error threshold criterion for |beCloseToArray| function _closeToThreshold(abserr, relerr, expected) { return Math.max(abserr, relerr * Math.abs(expected)); } /** * @class Should * @description Assertion subtask for the Audit task. * @param {Task} parentTask Associated Task object. * @param {Any} actual Target value to be tested. * @param {String} actualDescription String description of the test target. */ class Should { constructor(parentTask, actual, actualDescription) { this._task = parentTask; this._actual = actual; this._actualDescription = (actualDescription || null); this._expected = null; this._expectedDescription = null; this._detail = ''; // If true and the test failed, print the actual value at the // end of the message. this._printActualForFailure = true; this._result = null; /** * @param {Number} numberOfErrors Number of errors to be printed. * @param {Number} numberOfArrayElements Number of array elements to be * printed in the test log. * @param {Boolean} verbose Verbose output from the assertion. */ this._options = { numberOfErrors: 4, numberOfArrayElements: 16, verbose: false }; } _processArguments(args) { if (args.length === 0) return; if (args.length > 0) this._expected = args[0]; if (typeof args[1] === 'string') { // case 1: (expected, description, options) this._expectedDescription = args[1]; Object.assign(this._options, args[2]); } else if (typeof args[1] === 'object') { // case 2: (expected, options) Object.assign(this._options, args[1]); } } _buildResultText() { if (this._result === null) _throwException('Illegal invocation: the assertion is not finished.'); let actualString = _generateDescription(this._actual, this._options); // Use generated text when the description is not provided. if (!this._actualDescription) this._actualDescription = actualString; if (!this._expectedDescription) { this._expectedDescription = _generateDescription(this._expected, this._options); } // For the assertion with a single operand. this._detail = this._detail.replace(/\$\{actual\}/g, this._actualDescription); // If there is a second operand (i.e. expected value), we have to build // the string for it as well. this._detail = this._detail.replace(/\$\{expected\}/g, this._expectedDescription); // If there is any property in |_options|, replace the property name // with the value. for (let name in this._options) { if (name === 'numberOfErrors' || name === 'numberOfArrayElements' || name === 'verbose') { continue; } // The RegExp key string contains special character. Take care of it. let re = '\$\{' + name + '\}'; re = re.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1'); this._detail = this._detail.replace( new RegExp(re, 'g'), _generateDescription(this._options[name])); } // If the test failed, add the actual value at the end. if (this._result === false && this._printActualForFailure === true) { this._detail += ' Got ' + actualString + '.'; } } _finalize() { if (this._result) { _logPassed(' ' + this._detail); } else { _logFailed('X ' + this._detail); } // This assertion is finished, so update the parent task accordingly. this._task.update(this); // TODO(hongchan): configurable 'detail' message. } _assert(condition, passDetail, failDetail) { this._result = Boolean(condition); this._detail = this._result ? passDetail : failDetail; this._buildResultText(); this._finalize(); return this._result; } get result() { return this._result; } get detail() { return this._detail; } /** * should() assertions. * * @example All the assertions can have 1, 2 or 3 arguments: * should().doAssert(expected); * should().doAssert(expected, options); * should().doAssert(expected, expectedDescription, options); * * @param {Any} expected Expected value of the assertion. * @param {String} expectedDescription Description of expected value. * @param {Object} options Options for assertion. * @param {Number} options.numberOfErrors Number of errors to be printed. * (if applicable) * @param {Number} options.numberOfArrayElements Number of array elements * to be printed. (if * applicable) * @notes Some assertions can have additional options for their specific * testing. */ /** * Check if |actual| exists. * * @example * should({}, 'An empty object').exist(); * @result * "PASS An empty object does exist." */ exist() { return this._assert( this._actual !== null && this._actual !== undefined, '${actual} does exist.', '${actual} does not exist.'); } /** * Check if |actual| operation wrapped in a function throws an exception * with a expected error type correctly. |expected| is optional. If it is an * instance of DOMException, then the description (second argument) can be * provided to be more strict about the expected exception type. |expected| * also can be other generic error types such as TypeError, RangeError or * etc. * * @example * should(() => { let a = b; }, 'A bad code').throw(); * should(() => { new SomeConstructor(); }, 'A bad construction') * .throw(DOMException, 'NotSupportedError'); * should(() => { let c = d; }, 'Assigning d to c') * .throw(ReferenceError); * should(() => { let e = f; }, 'Assigning e to f') * .throw(ReferenceError, { omitErrorMessage: true }); * * @result * "PASS A bad code threw an exception of ReferenceError: b is not * defined." * "PASS A bad construction threw DOMException:NotSupportedError." * "PASS Assigning d to c threw ReferenceError: d is not defined." * "PASS Assigning e to f threw ReferenceError: [error message * omitted]." */ throw() { this._processArguments(arguments); this._printActualForFailure = false; let didThrowCorrectly = false; let passDetail, failDetail; try { // This should throw. this._actual(); // Catch did not happen, so the test is failed. failDetail = '${actual} did not throw an exception.'; } catch (error) { let errorMessage = this._options.omitErrorMessage ? ': [error message omitted]' : ': "' + error.message + '"'; if (this._expected === null || this._expected === undefined) { // The expected error type was not given. didThrowCorrectly = true; passDetail = '${actual} threw ' + error.name + errorMessage + '.'; } else if (this._expected === DOMException && (this._expectedDescription === undefined || this._expectedDescription === error.name)) { // Handles DOMException with the associated name. didThrowCorrectly = true; passDetail = '${actual} threw ${expected}' + errorMessage + '.'; } else if (this._expected == error.constructor) { // Handler other error types. didThrowCorrectly = true; passDetail = '${actual} threw ' + error.name + errorMessage + '.'; } else { didThrowCorrectly = false; failDetail = '${actual} threw "' + error.name + '" instead of ${expected}.'; } } return this._assert(didThrowCorrectly, passDetail, failDetail); } /** * Check if |actual| operation wrapped in a function does not throws an * exception correctly. * * @example * should(() => { let foo = 'bar'; }, 'let foo = "bar"').notThrow(); * * @result * "PASS let foo = "bar" did not throw an exception." */ notThrow() { this._printActualForFailure = false; let didThrowCorrectly = false; let passDetail, failDetail; try { this._actual(); passDetail = '${actual} did not throw an exception.'; } catch (error) { didThrowCorrectly = true; failDetail = '${actual} incorrectly threw ' + error.name + ': "' + error.message + '".'; } return this._assert(!didThrowCorrectly, passDetail, failDetail); } /** * Check if |actual| promise is resolved correctly. Note that the returned * result from promise object will be passed to the following then() * function. * * @example * should('My promise', promise).beResolve().then((result) => { * log(result); * }); * * @result * "PASS My promise resolved correctly." * "FAIL X My promise rejected *INCORRECTLY* with _ERROR_." */ beResolved() { return this._actual.then( function(result) { this._assert(true, '${actual} resolved correctly.', null); return result; }.bind(this), function(error) { this._assert( false, null, '${actual} rejected incorrectly with ' + error + '.'); }.bind(this)); } /** * Check if |actual| promise is rejected correctly. * * @example * should('My promise', promise).beRejected().then(nextStuff); * * @result * "PASS My promise rejected correctly (with _ERROR_)." * "FAIL X My promise resolved *INCORRECTLY*." */ beRejected() { return this._actual.then( function() { this._assert(false, null, '${actual} resolved incorrectly.'); }.bind(this), function(error) { this._assert( true, '${actual} rejected correctly with ' + error + '.', null); }.bind(this)); } /** * Check if |actual| promise is rejected correctly. * * @example * should(promise, 'My promise').beRejectedWith('_ERROR_').then(); * * @result * "PASS My promise rejected correctly with _ERROR_." * "FAIL X My promise rejected correctly but got _ACTUAL_ERROR instead of * _EXPECTED_ERROR_." * "FAIL X My promise resolved incorrectly." */ beRejectedWith() { this._processArguments(arguments); return this._actual.then( function() { this._assert(false, null, '${actual} resolved incorrectly.'); }.bind(this), function(error) { if (this._expected !== error.name) { this._assert( false, null, '${actual} rejected correctly but got ' + error.name + ' instead of ' + this._expected + '.'); } else { this._assert( true, '${actual} rejected correctly with ' + this._expected + '.', null); } }.bind(this)); } /** * Check if |actual| is a boolean true. * * @example * should(3 < 5, '3 < 5').beTrue(); * * @result * "PASS 3 < 5 is true." */ beTrue() { return this._assert( this._actual === true, '${actual} is true.', '${actual} is not true.'); } /** * Check if |actual| is a boolean false. * * @example * should(3 > 5, '3 > 5').beFalse(); * * @result * "PASS 3 > 5 is false." */ beFalse() { return this._assert( this._actual === false, '${actual} is false.', '${actual} is not false.'); } /** * Check if |actual| is strictly equal to |expected|. (no type coercion) * * @example * should(1).beEqualTo(1); * * @result * "PASS 1 is equal to 1." */ beEqualTo() { this._processArguments(arguments); return this._assert( this._actual === this._expected, '${actual} is equal to ${expected}.', '${actual} is not equal to ${expected}.'); } /** * Check if |actual| is not equal to |expected|. * * @example * should(1).notBeEqualTo(2); * * @result * "PASS 1 is not equal to 2." */ notBeEqualTo() { this._processArguments(arguments); return this._assert( this._actual !== this._expected, '${actual} is not equal to ${expected}.', '${actual} should not be equal to ${expected}.'); } /** * check if |actual| is NaN * * @example * should(NaN).beNaN(); * * @result * "PASS NaN is NaN" * */ beNaN() { this._processArguments(arguments); return this._assert( isNaN(this._actual), '${actual} is NaN.', '${actual} is not NaN but should be.'); } /** * check if |actual| is NOT NaN * * @example * should(42).notBeNaN(); * * @result * "PASS 42 is not NaN" * */ notBeNaN() { this._processArguments(arguments); return this._assert( !isNaN(this._actual), '${actual} is not NaN.', '${actual} is NaN but should not be.'); } /** * Check if |actual| is greater than |expected|. * * @example * should(2).beGreaterThanOrEqualTo(2); * * @result * "PASS 2 is greater than or equal to 2." */ beGreaterThan() { this._processArguments(arguments); return this._assert( this._actual > this._expected, '${actual} is greater than ${expected}.', '${actual} is not greater than ${expected}.'); } /** * Check if |actual| is greater than or equal to |expected|. * * @example * should(2).beGreaterThan(1); * * @result * "PASS 2 is greater than 1." */ beGreaterThanOrEqualTo() { this._processArguments(arguments); return this._assert( this._actual >= this._expected, '${actual} is greater than or equal to ${expected}.', '${actual} is not greater than or equal to ${expected}.'); } /** * Check if |actual| is less than |expected|. * * @example * should(1).beLessThan(2); * * @result * "PASS 1 is less than 2." */ beLessThan() { this._processArguments(arguments); return this._assert( this._actual < this._expected, '${actual} is less than ${expected}.', '${actual} is not less than ${expected}.'); } /** * Check if |actual| is less than or equal to |expected|. * * @example * should(1).beLessThanOrEqualTo(1); * * @result * "PASS 1 is less than or equal to 1." */ beLessThanOrEqualTo() { this._processArguments(arguments); return this._assert( this._actual <= this._expected, '${actual} is less than or equal to ${expected}.', '${actual} is not less than or equal to ${expected}.'); } /** * Check if |actual| array is filled with a constant |expected| value. * * @example * should([1, 1, 1]).beConstantValueOf(1); * * @result * "PASS [1,1,1] contains only the constant 1." */ beConstantValueOf() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail, failDetail; let errors = {}; let actual = this._actual; let expected = this._expected; for (let index = 0; index < actual.length; ++index) { if (actual[index] !== expected) errors[index] = actual[index]; } let numberOfErrors = Object.keys(errors).length; passed = numberOfErrors === 0; if (passed) { passDetail = '${actual} contains only the constant ${expected}.'; } else { let counter = 0; failDetail = '${actual}: Expected ${expected} for all values but found ' + numberOfErrors + ' unexpected values: '; failDetail += '\n\tIndex\tActual'; for (let errorIndex in errors) { failDetail += '\n\t[' + errorIndex + ']' + '\t' + errors[errorIndex]; if (++counter >= this._options.numberOfErrors) { failDetail += '\n\t...and ' + (numberOfErrors - counter) + ' more errors.'; break; } } } return this._assert(passed, passDetail, failDetail); } /** * Check if |actual| array is not filled with a constant |expected| value. * * @example * should([1, 0, 1]).notBeConstantValueOf(1); * should([0, 0, 0]).notBeConstantValueOf(0); * * @result * "PASS [1,0,1] is not constantly 1 (contains 1 different value)." * "FAIL X [0,0,0] should have contain at least one value different * from 0." */ notBeConstantValueOf() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail; let failDetail; let differences = {}; let actual = this._actual; let expected = this._expected; for (let index = 0; index < actual.length; ++index) { if (actual[index] !== expected) differences[index] = actual[index]; } let numberOfDifferences = Object.keys(differences).length; passed = numberOfDifferences > 0; if (passed) { let valueString = numberOfDifferences > 1 ? 'values' : 'value'; passDetail = '${actual} is not constantly ${expected} (contains ' + numberOfDifferences + ' different ' + valueString + ').'; } else { failDetail = '${actual} should have contain at least one value ' + 'different from ${expected}.'; } return this._assert(passed, passDetail, failDetail); } /** * Check if |actual| array is identical to |expected| array element-wise. * * @example * should([1, 2, 3]).beEqualToArray([1, 2, 3]); * * @result * "[1,2,3] is identical to the array [1,2,3]." */ beEqualToArray() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail, failDetail; let errorIndices = []; if (this._actual.length !== this._expected.length) { passed = false; failDetail = 'The array length does not match.'; return this._assert(passed, passDetail, failDetail); } let actual = this._actual; let expected = this._expected; for (let index = 0; index < actual.length; ++index) { if (actual[index] !== expected[index]) errorIndices.push(index); } passed = errorIndices.length === 0; if (passed) { passDetail = '${actual} is identical to the array ${expected}.'; } else { let counter = 0; failDetail = '${actual} expected to be equal to the array ${expected} ' + 'but differs in ' + errorIndices.length + ' places:' + '\n\tIndex\tActual\t\t\tExpected'; for (let index of errorIndices) { failDetail += '\n\t[' + index + ']' + '\t' + this._actual[index].toExponential(16) + '\t' + this._expected[index].toExponential(16); if (++counter >= this._options.numberOfErrors) { failDetail += '\n\t...and ' + (errorIndices.length - counter) + ' more errors.'; break; } } } return this._assert(passed, passDetail, failDetail); } /** * Check if |actual| array contains only the values in |expected| in the * order of values in |expected|. * * @example * Should([1, 1, 3, 3, 2], 'My random array').containValues([1, 3, 2]); * * @result * "PASS [1,1,3,3,2] contains all the expected values in the correct * order: [1,3,2]. */ containValues() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let indexedActual = []; let firstErrorIndex = null; // Collect the unique value sequence from the actual. for (let i = 0, prev = null; i < this._actual.length; i++) { if (this._actual[i] !== prev) { indexedActual.push({index: i, value: this._actual[i]}); prev = this._actual[i]; } } // Compare against the expected sequence. let failMessage = '${actual} expected to have the value sequence of ${expected} but ' + 'got '; if (this._expected.length === indexedActual.length) { for (let j = 0; j < this._expected.length; j++) { if (this._expected[j] !== indexedActual[j].value) { firstErrorIndex = indexedActual[j].index; passed = false; failMessage += this._actual[firstErrorIndex] + ' at index ' + firstErrorIndex + '.'; break; } } } else { passed = false; let indexedValues = indexedActual.map(x => x.value); failMessage += `${indexedActual.length} values, [${ indexedValues}], instead of ${this._expected.length}.`; } return this._assert( passed, '${actual} contains all the expected values in the correct order: ' + '${expected}.', failMessage); } /** * Check if |actual| array does not have any glitches. Note that |threshold| * is not optional and is to define the desired threshold value. * * @example * should([0.5, 0.5, 0.55, 0.5, 0.45, 0.5]).notGlitch(0.06); * * @result * "PASS [0.5,0.5,0.55,0.5,0.45,0.5] has no glitch above the threshold * of 0.06." * */ notGlitch() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail, failDetail; let actual = this._actual; let expected = this._expected; for (let index = 0; index < actual.length; ++index) { let diff = Math.abs(actual[index - 1] - actual[index]); if (diff >= expected) { passed = false; failDetail = '${actual} has a glitch at index ' + index + ' of size ' + diff + '.'; } } passDetail = '${actual} has no glitch above the threshold of ${expected}.'; return this._assert(passed, passDetail, failDetail); } /** * Check if |actual| is close to |expected| using the given relative error * |threshold|. * * @example * should(2.3).beCloseTo(2, { threshold: 0.3 }); * * @result * "PASS 2.3 is 2 within an error of 0.3." * @param {Object} options Options for assertion. * @param {Number} options.threshold Threshold value for the comparison. */ beCloseTo() { this._processArguments(arguments); // The threshold is relative except when |expected| is zero, in which case // it is absolute. let absExpected = this._expected ? Math.abs(this._expected) : 1; let error = Math.abs(this._actual - this._expected) / absExpected; // debugger; return this._assert( error <= this._options.threshold, '${actual} is ${expected} within an error of ${threshold}.', '${actual} is not close to ${expected} within a relative error of ' + '${threshold} (RelErr=' + error + ').'); } /** * Check if |target| array is close to |expected| array element-wise within * a certain error bound given by the |options|. * * The error criterion is: * abs(actual[k] - expected[k]) < max(absErr, relErr * abs(expected)) * * If nothing is given for |options|, then absErr = relErr = 0. If * absErr = 0, then the error criterion is a relative error. A non-zero * absErr value produces a mix intended to handle the case where the * expected value is 0, allowing the target value to differ by absErr from * the expected. * * @param {Number} options.absoluteThreshold Absolute threshold. * @param {Number} options.relativeThreshold Relative threshold. */ beCloseToArray() { this._processArguments(arguments); this._printActualForFailure = false; let passed = true; let passDetail, failDetail; // Parsing options. let absErrorThreshold = (this._options.absoluteThreshold || 0); let relErrorThreshold = (this._options.relativeThreshold || 0); // A collection of all of the values that satisfy the error criterion. // This holds the absolute difference between the target element and the // expected element. let errors = {}; // Keep track of the max absolute error found. let maxAbsError = -Infinity, maxAbsErrorIndex = -1; // Keep track of the max relative error found, ignoring cases where the // relative error is Infinity because the expected value is 0. let maxRelError = -Infinity, maxRelErrorIndex = -1; let actual = this._actual; let expected = this._expected; for (let index = 0; index < expected.length; ++index) { let diff = Math.abs(actual[index] - expected[index]); let absExpected = Math.abs(expected[index]); let relError = diff / absExpected; if (diff > Math.max(absErrorThreshold, relErrorThreshold * absExpected)) { if (diff > maxAbsError) { maxAbsErrorIndex = index; maxAbsError = diff; } if (!isNaN(relError) && relError > maxRelError) { maxRelErrorIndex = index; maxRelError = relError; } errors[index] = diff; } } let numberOfErrors = Object.keys(errors).length; let maxAllowedErrorDetail = JSON.stringify({ absoluteThreshold: absErrorThreshold, relativeThreshold: relErrorThreshold }); if (numberOfErrors === 0) { // The assertion was successful. passDetail = '${actual} equals ${expected} with an element-wise ' + 'tolerance of ' + maxAllowedErrorDetail + '.'; } else { // Failed. Prepare the detailed failure log. passed = false; failDetail = '${actual} does not equal ${expected} with an ' + 'element-wise tolerance of ' + maxAllowedErrorDetail + '.\n'; // Print out actual, expected, absolute error, and relative error. let counter = 0; failDetail += '\tIndex\tActual\t\t\tExpected\t\tAbsError' + '\t\tRelError\t\tTest threshold'; let printedIndices = []; for (let index in errors) { failDetail += '\n' + _formatFailureEntry( index, actual[index], expected[index], errors[index], _closeToThreshold( absErrorThreshold, relErrorThreshold, expected[index])); printedIndices.push(index); if (++counter > this._options.numberOfErrors) { failDetail += '\n\t...and ' + (numberOfErrors - counter) + ' more errors.'; break; } } // Finalize the error log: print out the location of both the maxAbs // error and the maxRel error so we can adjust thresholds appropriately // in the test. failDetail += '\n' + '\tMax AbsError of ' + maxAbsError.toExponential(16) + ' at index of ' + maxAbsErrorIndex + '.\n'; if (printedIndices.find(element => { return element == maxAbsErrorIndex; }) === undefined) { // Print an entry for this index if we haven't already. failDetail += _formatFailureEntry( maxAbsErrorIndex, actual[maxAbsErrorIndex], expected[maxAbsErrorIndex], errors[maxAbsErrorIndex], _closeToThreshold( absErrorThreshold, relErrorThreshold, expected[maxAbsErrorIndex])) + '\n'; } failDetail += '\tMax RelError of ' + maxRelError.toExponential(16) + ' at index of ' + maxRelErrorIndex + '.\n'; if (printedIndices.find(element => { return element == maxRelErrorIndex; }) === undefined) { // Print an entry for this index if we haven't already. failDetail += _formatFailureEntry( maxRelErrorIndex, actual[maxRelErrorIndex], expected[maxRelErrorIndex], errors[maxRelErrorIndex], _closeToThreshold( absErrorThreshold, relErrorThreshold, expected[maxRelErrorIndex])) + '\n'; } } return this._assert(passed, passDetail, failDetail); } /** * A temporary escape hat for printing an in-task message. The description * for the |actual| is required to get the message printed properly. * * TODO(hongchan): remove this method when the transition from the old Audit * to the new Audit is completed. * @example * should(true, 'The message is').message('truthful!', 'false!'); * * @result * "PASS The message is truthful!" */ message(passDetail, failDetail) { return this._assert( this._actual, '${actual} ' + passDetail, '${actual} ' + failDetail); } /** * Check if |expected| property is truly owned by |actual| object. * * @example * should(BaseAudioContext.prototype, * 'BaseAudioContext.prototype').haveOwnProperty('createGain'); * * @result * "PASS BaseAudioContext.prototype has an own property of * 'createGain'." */ haveOwnProperty() { this._processArguments(arguments); return this._assert( this._actual.hasOwnProperty(this._expected), '${actual} has an own property of "${expected}".', '${actual} does not own the property of "${expected}".'); } /** * Check if |expected| property is not owned by |actual| object. * * @example * should(BaseAudioContext.prototype, * 'BaseAudioContext.prototype') * .notHaveOwnProperty('startRendering'); * * @result * "PASS BaseAudioContext.prototype does not have an own property of * 'startRendering'." */ notHaveOwnProperty() { this._processArguments(arguments); return this._assert( !this._actual.hasOwnProperty(this._expected), '${actual} does not have an own property of "${expected}".', '${actual} has an own the property of "${expected}".') } /** * Check if an object is inherited from a class. This looks up the entire * prototype chain of a given object and tries to find a match. * * @example * should(sourceNode, 'A buffer source node') * .inheritFrom('AudioScheduledSourceNode'); * * @result * "PASS A buffer source node inherits from 'AudioScheduledSourceNode'." */ inheritFrom() { this._processArguments(arguments); let prototypes = []; let currentPrototype = Object.getPrototypeOf(this._actual); while (currentPrototype) { prototypes.push(currentPrototype.constructor.name); currentPrototype = Object.getPrototypeOf(currentPrototype); } return this._assert( prototypes.includes(this._expected), '${actual} inherits from "${expected}".', '${actual} does not inherit from "${expected}".'); } } // Task Class state enum. const TaskState = {PENDING: 0, STARTED: 1, FINISHED: 2}; /** * @class Task * @description WebAudio testing task. Managed by TaskRunner. */ class Task { /** * Task constructor. * @param {Object} taskRunner Reference of associated task runner. * @param {String||Object} taskLabel Task label if a string is given. This * parameter can be a dictionary with the * following fields. * @param {String} taskLabel.label Task label. * @param {String} taskLabel.description Description of task. * @param {Function} taskFunction Task function to be performed. * @return {Object} Task object. */ constructor(taskRunner, taskLabel, taskFunction) { this._taskRunner = taskRunner; this._taskFunction = taskFunction; if (typeof taskLabel === 'string') { this._label = taskLabel; this._description = null; } else if (typeof taskLabel === 'object') { if (typeof taskLabel.label !== 'string') { _throwException('Task.constructor:: task label must be string.'); } this._label = taskLabel.label; this._description = (typeof taskLabel.description === 'string') ? taskLabel.description : null; } else { _throwException( 'Task.constructor:: task label must be a string or ' + 'a dictionary.'); } this._state = TaskState.PENDING; this._result = true; this._totalAssertions = 0; this._failedAssertions = 0; } get label() { return this._label; } get state() { return this._state; } get result() { return this._result; } // Start the assertion chain. should(actual, actualDescription) { // If no argument is given, we cannot proceed. Halt. if (arguments.length === 0) _throwException('Task.should:: requires at least 1 argument.'); return new Should(this, actual, actualDescription); } // Run this task. |this| task will be passed into the user-supplied test // task function. run(harnessTest) { this._state = TaskState.STARTED; this._harnessTest = harnessTest; // Print out the task entry with label and description. _logPassed( '> [' + this._label + '] ' + (this._description ? this._description : '')); return new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; let result = this._taskFunction(this, this.should.bind(this)); if (result && typeof result.then === "function") { result.then(() => this.done()).catch(reject); } }); } // Update the task success based on the individual assertion/test inside. update(subTask) { // After one of tests fails within a task, the result is irreversible. if (subTask.result === false) { this._result = false; this._failedAssertions++; } this._totalAssertions++; } // Finish the current task and start the next one if available. done() { assert_equals(this._state, TaskState.STARTED) this._state = TaskState.FINISHED; let message = '< [' + this._label + '] '; if (this._result) { message += 'All assertions passed. (total ' + this._totalAssertions + ' assertions)'; _logPassed(message); } else { message += this._failedAssertions + ' out of ' + this._totalAssertions + ' assertions were failed.' _logFailed(message); } this._resolve(); } // Runs |subTask| |time| milliseconds later. |setTimeout| is not allowed in // WPT linter, so a thin wrapper around the harness's |step_timeout| is // used here. Returns a Promise which is resolved after |subTask| runs. timeout(subTask, time) { return new Promise(resolve => { this._harnessTest.step_timeout(() => { let result = subTask(); if (result && typeof result.then === "function") { // Chain rejection directly to the harness test Promise, to report // the rejection against the subtest even when the caller of // timeout does not handle the rejection. result.then(resolve, this._reject()); } else { resolve(); } }, time); }); } isPassed() { return this._state === TaskState.FINISHED && this._result; } toString() { return '"' + this._label + '": ' + this._description; } } /** * @class TaskRunner * @description WebAudio testing task runner. Manages tasks. */ class TaskRunner { constructor() { this._tasks = {}; this._taskSequence = []; // Configure testharness.js for the async operation. setup(new Function(), {explicit_done: true}); } _finish() { let numberOfFailures = 0; for (let taskIndex in this._taskSequence) { let task = this._tasks[this._taskSequence[taskIndex]]; numberOfFailures += task.result ? 0 : 1; } let prefix = '# AUDIT TASK RUNNER FINISHED: '; if (numberOfFailures > 0) { _logFailed( prefix + numberOfFailures + ' out of ' + this._taskSequence.length + ' tasks were failed.'); } else { _logPassed( prefix + this._taskSequence.length + ' tasks ran successfully.'); } return Promise.resolve(); } // |taskLabel| can be either a string or a dictionary. See Task constructor // for the detail. If |taskFunction| returns a thenable, then the task // is considered complete when the thenable is fulfilled; otherwise the // task must be completed with an explicit call to |task.done()|. define(taskLabel, taskFunction) { let task = new Task(this, taskLabel, taskFunction); if (this._tasks.hasOwnProperty(task.label)) { _throwException('Audit.define:: Duplicate task definition.'); return; } this._tasks[task.label] = task; this._taskSequence.push(task.label); } // Start running all the tasks scheduled. Multiple task names can be passed // to execute them sequentially. Zero argument will perform all defined // tasks in the order of definition. run() { // Display the beginning of the test suite. _logPassed('# AUDIT TASK RUNNER STARTED.'); // If the argument is specified, override the default task sequence with // the specified one. if (arguments.length > 0) { this._taskSequence = []; for (let i = 0; i < arguments.length; i++) { let taskLabel = arguments[i]; if (!this._tasks.hasOwnProperty(taskLabel)) { _throwException('Audit.run:: undefined task.'); } else if (this._taskSequence.includes(taskLabel)) { _throwException('Audit.run:: duplicate task request.'); } else { this._taskSequence.push(taskLabel); } } } if (this._taskSequence.length === 0) { _throwException('Audit.run:: no task to run.'); return; } for (let taskIndex in this._taskSequence) { let task = this._tasks[this._taskSequence[taskIndex]]; // Some tests assume that tasks run in sequence, which is provided by // promise_test(). promise_test((t) => task.run(t), `Executing "${task.label}"`); } // Schedule a summary report on completion. promise_test(() => this._finish(), "Audit report"); // From testharness.js. The harness now need not wait for more subtests // to be added. _testharnessDone(); } } /** * Load file from a given URL and pass ArrayBuffer to the following promise. * @param {String} fileUrl file URL. * @return {Promise} * * @example * Audit.loadFileFromUrl('resources/my-sound.ogg').then((response) => { * audioContext.decodeAudioData(response).then((audioBuffer) => { * // Do something with AudioBuffer. * }); * }); */ function loadFileFromUrl(fileUrl) { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); xhr.open('GET', fileUrl, true); xhr.responseType = 'arraybuffer'; xhr.onload = () => { // |status = 0| is a workaround for the run_web_test.py server. We are // speculating the server quits the transaction prematurely without // completing the request. if (xhr.status === 200 || xhr.status === 0) { resolve(xhr.response); } else { let errorMessage = 'loadFile: Request failed when loading ' + fileUrl + '. ' + xhr.statusText + '. (status = ' + xhr.status + ')'; if (reject) { reject(errorMessage); } else { new Error(errorMessage); } } }; xhr.onerror = (event) => { let errorMessage = 'loadFile: Network failure when loading ' + fileUrl + '.'; if (reject) { reject(errorMessage); } else { new Error(errorMessage); } }; xhr.send(); }); } /** * @class Audit * @description A WebAudio layout test task manager. * @example * let audit = Audit.createTaskRunner(); * audit.define('first-task', function (task, should) { * should(someValue).beEqualTo(someValue); * task.done(); * }); * audit.run(); */ return { /** * Creates an instance of Audit task runner. * @param {Object} options Options for task runner. * @param {Boolean} options.requireResultFile True if the test suite * requires explicit text * comparison with the expected * result file. */ createTaskRunner: function(options) { if (options && options.requireResultFile == true) { _logError( 'this test requires the explicit comparison with the ' + 'expected result when it runs with run_web_tests.py.'); } return new TaskRunner(); }, /** * Load file from a given URL and pass ArrayBuffer to the following promise. * See |loadFileFromUrl| method for the detail. */ loadFileFromUrl: loadFileFromUrl }; })();
DominoTree/servo
tests/wpt/web-platform-tests/webaudio/resources/audit.js
JavaScript
mpl-2.0
46,546
/* * taskapi. */ var input_taskname_text = '<input type="text" id="task_name_{0}" value="{1}" class="form-control">'; var input_taskdesc_text = '<input type="text" id="task_desc_{0}" value="{1}" class="form-control">'; var btn_update_task = '<a href="#" class="btn-update-task btn btn-sm btn-success" data-taskid="{0}" id="task_update_btn_{0}">Update</a>&nbsp;'; var btn_remove_task = '<a href="#" class="{2} btn btn-sm btn-danger" data-taskid="{0}" id="taskbtn_{0}">{1}</a>'; var taskilyTasks = (function (survey, table) { var tsk = {}; var tableID = table; var surveyID = survey; tsk.loadTasks = function() { $.ajax({ url: '/api/tasks/all/' + surveyID, type: 'GET', success: function(data) { for (var i = 0; i < data.length; i++) { var activeclass = ''; if (data[i].Active == false) { activeclass = 'task-row-inactive'; } var row = ['<tr id="taskrow_' + data[i].ID + '" class="task-row '+ activeclass + '">', '<td>' + input_taskname_text.format(data[i].ID, data[i].Name) + '</td>', '<td>' + input_taskdesc_text.format(data[i].ID, data[i].Description) + '</td>'] ; if (data[i].Active == true) { row.push('<td>' + btn_update_task.format(data[i].ID) + btn_remove_task.format(data[i].ID, 'Remove', 'btn-remove-task') + '</td>'); } else { row.push('<td>' + btn_remove_task.format(data[i].ID, 'Activate', 'btn-activate-task') + '</td>') ; } row.push('</tr>'); $( row.join() ).appendTo(tableID); } bindTaskButtons(); }, error: function(msg) { alert(msg); } }); } function bindTaskButtons() { $(".btn-remove-task").click(function (e) { e.stopPropagation(); e.preventDefault(); var taskID = $(this).data("taskid"); removeTask(taskID); }); $(".btn-update-task").click(function (e) { e.stopPropagation(); e.preventDefault(); var taskID = $(this).data("taskid"); updateTask(taskID); }); $("#addTask").click(function (e) { e.stopPropagation(); e.preventDefault(); var tName = $("#newTask").val(); var tDesc = $("#newDesc").val(); addTask(tName, tDesc); }); $(".btn-activate-task").click(function (e) { e.stopPropagation(); e.preventDefault(); var taskID = $(this).data("taskid"); activateTask(taskID); }); } function removeTask(taskId) { $.ajax({ url: '/api/tasks/delete/' + taskId, type: 'DELETE', success: function (data) { if (data.Active == false) { toggleButton(data.ID); btn.unbind('click'); btn.click(function (e) { e.stopPropagation(); var taskID = $(this).data("taskid"); activateTask(taskID); }); } else { $("#taskrow_" + data.ID).fadeOut(); } }, error: function (data) { alert("Error removing task"); } }); } function updateTask(taskId) { var taskName = $("#task_name_" + taskId).val(); var taskDesc = $("#task_desc_" + taskId).val(); var task = { 'ID': taskId, 'SurveyID': surveyID, 'Name': taskName, 'Description': taskDesc }; $.ajax({ url: '/api/tasks/update/' + surveyID, type: 'POST', contentType: 'application/json', data: JSON.stringify(task), success: function (data) { var row = $('#taskrow_' + data.ID).addClass('task-done') ; setTimeout(function () { row.toggleClass('task-done'); }, 1000); }, error: function (msg) { alert('failed to update task'); } }); } function activateTask(taskId) { $.ajax({ url: '/api/tasks/activate/' + taskId, type: 'PUT', success: function (data) { toggleButton(data.ID); btn.unbind('click'); btn.click(function (e) { e.stopPropagation(); var taskID = $(this).data("taskid"); removeTask(taskID); }); }, error: function (data) { alert("Error activating task"); } }); } function toggleButton(taskId) { var btn = $('#taskbtn_' + taskId); var row = $('#taskrow_' + taskId).addClass('task-done'); if (btn.html() == 'Activate') { btn.addClass("btn-remove-task"); btn.addClass("btn-danger"); btn.removeClass("btn-activate-task"); btn.removeClass("btn-warning"); row.removeClass("task-row-inactive"); btn.html("Remove"); } else { btn.removeClass("btn-remove-task"); btn.removeClass("btn-danger"); btn.addClass("btn-activate-task"); btn.addClass("btn-warning"); btn.html("Activate"); row.addClass("task-row-inactive"); } setTimeout(function () { row.toggleClass('task-done'); }, 1000); } function addTask(name, description) { var task = { 'SurveyID': surveyID, 'Active': true, 'Name': name, 'Description': description }; $.ajax({ url: '/api/tasks/add/' + surveyID, type: 'POST', contentType: 'application/json', data: JSON.stringify(task), success: function (data) { $( ['<tr id="taskrow_' + data.ID + '" class="task-row">', '<td>' + input_taskname_text.format(data.ID, data.Name) + '</td>', '<td>' + input_taskdesc_text.format(data.ID, data.Description) + '</td>', '<td>' + btn_update_task.format(data.ID) + btn_remove_task.format(data.ID, 'Remove', 'btn-remove-task') + '</td>', '</tr>' ].join()).appendTo(tableID); }, error: function (msg) { alert( "Failed to add " + msg) } }); } return tsk; });
Jumoo/Taskily
TaskilyWeb/Scripts/admin/tasks.js
JavaScript
mpl-2.0
7,154
(function () { 'use strict' var SIZE var COLUMNS var UNICODES = { 'w': '\u26C0', 'b': '\u26C2', 'B': '\u26C3', 'W': '\u26C1', '0': ' ' } var START_FEN function validMove (move) { // move should be a string if (typeof move !== 'string') return false // move should be in the form of "27x31", "23-32" var tmp = move.split(/-|x/) if (tmp.length !== 2) return false return (validSquare(tmp[0]) === true && validSquare(tmp[1]) === true) } function validSquare (square) { if (square && square.substr(0, 1) === 'K') { square = square.substr(1) } square = parseInt(square, 10) return (square >= 0 && square < 51) } function validPieceCode (code) { if (typeof code !== 'string') return false return (code.search(/^[bwBW]$/) !== -1) } // TODO: this whole function could probably be replaced with a single regex function validFen (fen) { if (typeof fen !== 'string') return false if (fen === START_FEN) return true var FENPattern = /^(W|B):(W|B)((?:K?\d*)(?:,K?\d+)*?)(?::(W|B)((?:K?\d*)(?:,K?\d+)*?))?$/ var matches = FENPattern.exec(fen) if (matches != null) { return true } return false } function validPositionObject (pos) { if (typeof pos !== 'object') return false // pos = fenToObj(pos) for (var i in pos) { if (pos.hasOwnProperty(i) !== true) continue if (pos[i] == null) { continue } if (validSquare(i) !== true || validPieceCode(pos[i]) !== true) { // TODO console.trace('flsed in valid check', i,pos[i], validSquare(i), validPieceCode(pos[i])) return false } } return true } // convert FEN string to position object // returns false if the FEN string is invalid function fenToObj (fen) { if (validFen(fen) !== true) { return false } // cut off any move, castling, etc info from the end // we're only interested in position information fen = fen.replace(/\s+/g, '') fen = fen.replace(/\..*$/, '') var rows = fen.split(':') var position = [] var currentRow = 10 // var colIndex = 0 for (var i = 1; i <= 2; i++) { var color = rows[i].substr(0, 1) var row = rows[i].substr(1) var j if (row.indexOf('-') !== -1) { row = row.split('-') for (j = parseInt(row[0], 10); j <= parseInt(row[1], 10); j++) { position[j] = color.toLowerCase() } } else { row = row.split(',') for (j = 0; j < row.length; j++) { if (row[j].substr(0, 1) === 'K') { position[row[j].substr(1)] = color.toUpperCase() } else { position[row[j]] = color.toLowerCase() } } } currentRow-- } return position } // position object to FEN string // returns false if the obj is not a valid position object function objToFen (obj) { if (validPositionObject(obj) !== true) { return false } var black = [] var white = [] for (var i = 0; i < obj.length; i++) { switch (obj[i]) { case 'w': white.push(i) break case 'W': white.push('K' + i) break case 'b': black.push(i) break case 'B': black.push('K' + i) break default: break } } return 'w'.toUpperCase() + ':W' + white.join(',') + ':B' + black.join(',') // return fen } window['DraughtsBoard'] = window['DraughtsBoard'] || function (containerElOrId, cfg, board) { cfg = cfg || {} board = board || 'draughts' // ------------------------------------------------------------------------------ // Constants // ------------------------------------------------------------------------------ var MINIMUM_JQUERY_VERSION = '1.7.0' if (board === 'checkers') { START_FEN = 'W:W21-32:B1-12' SIZE = 8 COLUMNS = '01234567'.split('') } else { START_FEN = 'W:W31-50:B1-20' SIZE = 10 COLUMNS = '0123456789'.split('') } var START_POSITION = fenToObj(START_FEN) // use unique class names to prevent clashing with anything else on the page // and simplify selectors // NOTE: these should never change var CSS = { alpha: 'alpha-d2270', black: 'black-3c85d', board: 'board-b72b1', draughtsboard: 'draughtsboard-63f37', clearfix: 'clearfix-7da63', highlight1: 'highlight1-32417', highlight2: 'highlight2-9c5d2', notation: 'notation-322f9', numeric: 'numeric-fc462', piece: 'piece-417db', row: 'row-5277c', sparePieces: 'spare-pieces-7492f', sparePiecesBottom: 'spare-pieces-bottom-ae20f', sparePiecesTop: 'spare-pieces-top-4028b', square: 'square-55d63', white: 'white-1e1d7' } // ------------------------------------------------------------------------------ // Module Scope Variables // ------------------------------------------------------------------------------ // DOM elements var containerEl, boardEl, draggedPieceEl, sparePiecesTopEl, sparePiecesBottomEl // constructor return object var widget = {} // ------------------------------------------------------------------------------ // Stateful // ------------------------------------------------------------------------------ var ANIMATION_HAPPENING = false var BOARD_BORDER_SIZE = 2 var CURRENT_ORIENTATION = 'white' var CURRENT_POSITION = {} var SQUARE_SIZE var DRAGGED_PIECE var DRAGGED_PIECE_LOCATION var DRAGGED_PIECE_SOURCE var DRAGGING_A_PIECE = false var SPARE_PIECE_ELS_IDS = {} var SQUARE_ELS_IDS = {} var SQUARE_ELS_OFFSETS // ------------------------------------------------------------------------------ // JS Util Functions // ------------------------------------------------------------------------------ // http://tinyurl.com/3ttloxj function uuid () { return 'xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx'.replace(/x/g, function (c) { var r = Math.random() * 16 | 0 return r.toString(16) }) } function deepCopy (thing) { return JSON.parse(JSON.stringify(thing)) } function parseSemVer (version) { var tmp = version.split('.') return { major: parseInt(tmp[0], 10), minor: parseInt(tmp[1], 10), patch: parseInt(tmp[2], 10) } } // returns true if version is >= minimum function compareSemVer (version, minimum) { version = parseSemVer(version) minimum = parseSemVer(minimum) var versionNum = (version.major * 10000 * 10000) + (version.minor * 10000) + version.patch var minimumNum = (minimum.major * 10000 * 10000) + (minimum.minor * 10000) + minimum.patch return (versionNum >= minimumNum) } // ------------------------------------------------------------------------------ // Validation / Errors // ------------------------------------------------------------------------------ function error (code, msg, obj) { // do nothing if showErrors is not set if (cfg.hasOwnProperty('showErrors') !== true || cfg.showErrors === false) { return } var errorText = 'DraughtsBoard Error ' + code + ': ' + msg // print to console if (cfg.showErrors === 'console' && typeof console === 'object' && typeof console.log === 'function') { console.trace(errorText) if (arguments.length >= 2) { console.log(obj) } return } // alert errors if (cfg.showErrors === 'alert') { if (obj) { errorText += '\n\n' + JSON.stringify(obj) } window.alert(errorText) return } // custom function if (typeof cfg.showErrors === 'function') { cfg.showErrors(code, msg, obj) } } // check dependencies function checkDeps () { // if containerId is a string, it must be the ID of a DOM node if (typeof containerElOrId === 'string') { // cannot be empty if (containerElOrId === '') { window.alert('DraughtsBoard Error 1001: ' + 'The first argument to DraughtsBoard() cannot be an empty string.' + '\n\nExiting...') return false } // make sure the container element exists in the DOM var el = document.getElementById(containerElOrId) if (!el) { window.alert('DraughtsBoard Error 1002: Element with id "' + containerElOrId + '" does not exist in the DOM.' + '\n\nExiting...') return false } // set the containerEl containerEl = $(el) } else { // else it must be something that becomes a jQuery collection // with size 1 // ie: a single DOM node or jQuery object containerEl = $(containerElOrId) if (containerEl.length !== 1) { window.alert('DraughtsBoard Error 1003: The first argument to ' + 'DraughtsBoard() must be an ID or a single DOM node.' + '\n\nExiting...') return false } } // JSON must exist if (!window.JSON || typeof JSON.stringify !== 'function' || typeof JSON.parse !== 'function') { window.alert('DraughtsBoard Error 1004: JSON does not exist. ' + 'Please include a JSON polyfill.\n\nExiting...') return false } // check for a compatible version of jQuery if (!(typeof window.$ && $.fn && $.fn.jquery && compareSemVer($.fn.jquery, MINIMUM_JQUERY_VERSION) === true)) { window.alert('DraughtsBoard Error 1005: Unable to find a valid version ' + 'of jQuery. Please include jQuery ' + MINIMUM_JQUERY_VERSION + ' or ' + 'higher on the page.\n\nExiting...') return false } return true } function validAnimationSpeed (speed) { if (speed === 'fast' || speed === 'slow') { return true } if ((parseInt(speed, 10) + '') !== (speed + '')) { return false } return (speed >= 0) } // validate config / set default options function expandConfig () { if (typeof cfg === 'string' || validPositionObject(cfg) === true) { cfg = { position: cfg } } // default for orientation is white if (cfg.orientation !== 'black') { cfg.orientation = 'white' } CURRENT_ORIENTATION = cfg.orientation // default for showNotation is true if (cfg.showNotation !== false) { cfg.showNotation = true } // default for draggable is false if (cfg.draggable !== true) { cfg.draggable = false } // default for dropOffBoard is 'snapback' if (cfg.dropOffBoard !== 'trash') { cfg.dropOffBoard = 'snapback' } // default for sparePieces is false if (cfg.sparePieces !== true) { cfg.sparePieces = false } // draggable must be true if sparePieces is enabled if (cfg.sparePieces === true) { cfg.draggable = true } // default piece theme is unicode if (cfg.hasOwnProperty('pieceTheme') !== true || (typeof cfg.pieceTheme !== 'string' && typeof cfg.pieceTheme !== 'function')) { cfg.pieceTheme = 'unicode' } // animation speeds if (cfg.hasOwnProperty('appearSpeed') !== true || validAnimationSpeed(cfg.appearSpeed) !== true) { cfg.appearSpeed = 200 } if (cfg.hasOwnProperty('moveSpeed') !== true || validAnimationSpeed(cfg.moveSpeed) !== true) { cfg.moveSpeed = 200 } if (cfg.hasOwnProperty('snapbackSpeed') !== true || validAnimationSpeed(cfg.snapbackSpeed) !== true) { cfg.snapbackSpeed = 50 } if (cfg.hasOwnProperty('snapSpeed') !== true || validAnimationSpeed(cfg.snapSpeed) !== true) { cfg.snapSpeed = 25 } if (cfg.hasOwnProperty('trashSpeed') !== true || validAnimationSpeed(cfg.trashSpeed) !== true) { cfg.trashSpeed = 100 } // make sure position is valid if (cfg.hasOwnProperty('position') === true) { if (cfg.position === 'start') { CURRENT_POSITION = deepCopy(START_POSITION) } else if (validFen(cfg.position) === true) { CURRENT_POSITION = fenToObj(cfg.position) } else if (validPositionObject(cfg.position) === true) { CURRENT_POSITION = deepCopy(cfg.position) } else { error(7263, 'Invalid value passed to config.position.', cfg.position) } } return true } // ------------------------------------------------------------------------------ // DOM Misc // ------------------------------------------------------------------------------ // calculates square size based on the width of the container // got a little CSS black magic here, so let me explain: // get the width of the container element (could be anything), reduce by 1 for // fudge factor, and then keep reducing until we find an exact mod SIZE for // our square size function calculateSquareSize () { var containerWidth = parseInt(containerEl.width(), 10) // defensive, prevent infinite loop if (!containerWidth || containerWidth <= 0) { return 0 } // pad one pixel var boardWidth = containerWidth - 1 while (boardWidth % SIZE !== 0 && boardWidth > 0) { boardWidth-- } return (boardWidth / SIZE) } // create random IDs for elements function createElIds () { // squares on the board for (var i = 0; i <= (SIZE - 1); i++) { for (var j = 1; j <= SIZE; j++) { var square = (i * SIZE) + j SQUARE_ELS_IDS[square] = square + '-' + uuid() } } // spare pieces var pieces = 'bBwW'.split('') for (i = 0; i < pieces.length; i++) { SPARE_PIECE_ELS_IDS[pieces[i]] = pieces[i] + '-' + uuid() } } // ------------------------------------------------------------------------------ // Markup Building // ------------------------------------------------------------------------------ function buildBoardContainer () { var html = '<div class="' + CSS.draughtsboard + '">' if (cfg.sparePieces === true) { html += '<div class="' + CSS.sparePieces + ' ' + CSS.sparePiecesTop + '"></div>' } html += '<div class="' + CSS.board + '"></div>' if (cfg.sparePieces === true) { html += '<div class="' + CSS.sparePieces + ' ' + CSS.sparePiecesBottom + '"></div>' } html += '</div>' return html } /* var buildSquare = function(color, size, id) { var html = '<div class="' + CSS.square + ' ' + CSS[color] + '" ' + 'style="width: ' + size + 'px; height: ' + size + 'px" ' + 'id="' + id + '">' if (cfg.showNotation === true) { } html += '</div>' return html } */ function buildBoard (orientation) { if (orientation !== 'black') { orientation = 'white' } var html = '' // algebraic notation / orientation var alpha = deepCopy(COLUMNS) var row = SIZE if (orientation === 'black') { alpha.reverse() row = 1 } var squareColor = 'white' for (var i = 0; i < SIZE; i++) { html += '<div class="' + CSS.row + '">' for (var j = 1; j <= SIZE; j++) { var square if (orientation === 'black') { square = (parseInt(alpha[i], 10) * SIZE) + ((SIZE + 1) - j) } else { square = (parseInt(alpha[i], 10) * SIZE) + j } square = Math.round(square / 2) if (squareColor === 'white') { html += '<div class="' + CSS.square + ' ' + CSS[squareColor] + ' ' + 'square-empty' + '" ' + 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px">' } else { html += '<div class="' + CSS.square + ' ' + CSS[squareColor] + ' ' + 'square-' + square + '" ' + 'style="width: ' + SQUARE_SIZE + 'px; height: ' + SQUARE_SIZE + 'px" ' + 'id="' + SQUARE_ELS_IDS[square] + '" ' + 'data-square="' + square + '">' if (cfg.showNotation === true) { html += '<div class="' + CSS.notation + ' ' + CSS.alpha + '">' + square + '</div>' if (j === 0) { html += '<div class="' + CSS.notation + ' ' + CSS.numeric + '">' + row + '</div>' } } } html += '</div>' // end .square squareColor = (squareColor === 'white' ? 'black' : 'white') } html += '<div class="' + CSS.clearfix + '"></div></div>' squareColor = (squareColor === 'white' ? 'black' : 'white') if (orientation === 'white') { row-- } else { row++ } } return html } function buildPieceImgSrc (piece) { // For handling case insensetive windows :( if (piece === 'W' || piece === 'B') { piece = 'K' + piece } if (typeof cfg.pieceTheme === 'function') { return cfg.pieceTheme(piece) } if (typeof cfg.pieceTheme === 'string') { return cfg.pieceTheme.replace(/{piece}/g, piece) } // NOTE: this should never happen error(8272, 'Unable to build image source for cfg.pieceTheme.') return '' } function buildPiece (piece, hidden, id) { if (!piece) { return false } var html if (cfg.pieceTheme === 'unicode') { html = '<span ' if (id && typeof id === 'string') { html += 'id="' + id + '" ' } html += 'class="unicode ' + piece + ' ' + CSS.piece + '" ' html += 'data-piece="' + piece + '" ' html += 'style="font-size: ' + SQUARE_SIZE + 'px;' if (hidden === true) { html += 'display:none;' } html += '">' + UNICODES[piece] + '</span>' return html } html = '<img src="' + buildPieceImgSrc(piece) + '" ' if (id && typeof id === 'string') { html += 'id="' + id + '" ' } html += 'alt="" ' + 'class="' + CSS.piece + '" ' + 'data-piece="' + piece + '" ' + 'style="width: ' + SQUARE_SIZE + 'px;' + 'height: ' + SQUARE_SIZE + 'px;' if (hidden === true) { html += 'display:none;' } html += '" />' return html } function buildSparePieces (color) { var pieces = ['w', 'W'] if (color === 'black') { pieces = ['b', 'B'] } var html = '' for (var i = 0; i < pieces.length; i++) { html += buildPiece(pieces[i], false, SPARE_PIECE_ELS_IDS[pieces[i]]) } return html } // ------------------------------------------------------------------------------ // Animations // ------------------------------------------------------------------------------ function animateSquareToSquare (src, dest, piece, completeFn) { // get information about the source and destination squares var srcSquareEl = $('#' + SQUARE_ELS_IDS[src]) var srcSquarePosition = srcSquareEl.offset() var destSquareEl = $('#' + SQUARE_ELS_IDS[dest]) var destSquarePosition = destSquareEl.offset() // create the animated piece and absolutely position it // over the source square var animatedPieceId = uuid() $('body').append(buildPiece(piece, true, animatedPieceId)) var animatedPieceEl = $('#' + animatedPieceId) animatedPieceEl.css({ display: '', position: 'absolute', top: srcSquarePosition.top, left: srcSquarePosition.left, fontSize: SQUARE_SIZE + 'px' }) // remove original piece from source square srcSquareEl.find('.' + CSS.piece).remove() // on complete var complete = function () { // add the "real" piece to the destination square destSquareEl.append(buildPiece(piece)) // remove the animated piece animatedPieceEl.remove() // run complete function if (typeof completeFn === 'function') { completeFn() } } // animate the piece to the destination square var opts = { duration: cfg.moveSpeed, complete: complete } animatedPieceEl.animate(destSquarePosition, opts) } function animateSparePieceToSquare (piece, dest, completeFn) { var srcOffset = $('#' + SPARE_PIECE_ELS_IDS[piece]).offset() var destSquareEl = $('#' + SQUARE_ELS_IDS[dest]) var destOffset = destSquareEl.offset() // create the animate piece var pieceId = uuid() $('body').append(buildPiece(piece, true, pieceId)) var animatedPieceEl = $('#' + pieceId) animatedPieceEl.css({ display: '', position: 'absolute', left: srcOffset.left, top: srcOffset.top, fontSize: SQUARE_SIZE + 'px' }) // on complete var complete = function () { // add the "real" piece to the destination square destSquareEl.find('.' + CSS.piece).remove() destSquareEl.append(buildPiece(piece)) // remove the animated piece animatedPieceEl.remove() // run complete function if (typeof completeFn === 'function') { completeFn() } } // animate the piece to the destination square var opts = { duration: cfg.moveSpeed, complete: complete } animatedPieceEl.animate(destOffset, opts) } // execute an array of animations function doAnimations (a, oldPos, newPos) { if (a.length === 0) { return } ANIMATION_HAPPENING = true var numFinished = 0 function onFinish () { numFinished++ // exit if all the animations aren't finished if (numFinished !== a.length) return drawPositionInstant() ANIMATION_HAPPENING = false // run their onMoveEnd function if (cfg.hasOwnProperty('onMoveEnd') === true && typeof cfg.onMoveEnd === 'function') { cfg.onMoveEnd(deepCopy(oldPos), deepCopy(newPos)) } } for (var i = 0; i < a.length; i++) { // clear a piece if (a[i].type === 'clear') { $('#' + SQUARE_ELS_IDS[a[i].square] + ' .' + CSS.piece) .fadeOut(cfg.trashSpeed, onFinish) } // add a piece (no spare pieces) if (a[i].type === 'add' && cfg.sparePieces !== true) { $('#' + SQUARE_ELS_IDS[a[i].square]) .append(buildPiece(a[i].piece, true)) .find('.' + CSS.piece) .fadeIn(cfg.appearSpeed, onFinish) } // add a piece from a spare piece if (a[i].type === 'add' && cfg.sparePieces === true) { animateSparePieceToSquare(a[i].piece, a[i].square, onFinish) } // move a piece if (a[i].type === 'move') { animateSquareToSquare(a[i].source, a[i].destination, a[i].piece, onFinish) } } } // returns the distance between two squares function squareDistance (s1, s2) { s1 = s1.split('') var s1x = COLUMNS.indexOf(s1[0]) + 1 var s1y = parseInt(s1[1], 10) s2 = s2.split('') var s2x = COLUMNS.indexOf(s2[0]) + 1 var s2y = parseInt(s2[1], 10) var xDelta = Math.abs(s1x - s2x) var yDelta = Math.abs(s1y - s2y) if (xDelta >= yDelta) return xDelta return yDelta } // returns an array of closest squares from square function createRadius (square) { var squares = [] // calculate distance of all squares for (var i = 0; i < SIZE; i++) { for (var j = 0; j < SIZE; j++) { var s = COLUMNS[i] + (j + 1) // skip the square we're starting from if (square === s) continue squares.push({ square: s, distance: squareDistance(square, s) }) } } // sort by distance squares.sort(function (a, b) { return a.distance - b.distance }) // just return the square code var squares2 = [] for (i = 0; i < squares.length; i++) { squares2.push(squares[i].square) } return squares2 } // returns the square of the closest instance of piece // returns false if no instance of piece is found in position function findClosestPiece (position, piece, square) { // create array of closest squares from square var closestSquares = createRadius(square) // search through the position in order of distance for the piece for (var i = 0; i < closestSquares.length; i++) { var s = closestSquares[i] if (position.hasOwnProperty(s) === true && position[s] === piece) { return s } } return false } // calculate an array of animations that need to happen in order to get // from pos1 to pos2 function calculateAnimations (pos1, pos2) { // make copies of both pos1 = deepCopy(pos1) pos2 = deepCopy(pos2) var animations = [] var squaresMovedTo = {} // remove pieces that are the same in both positions for (var i in pos2) { if (pos2.hasOwnProperty(i) !== true) continue if (pos1.hasOwnProperty(i) === true && pos1[i] === pos2[i]) { delete pos1[i] delete pos2[i] } } // find all the "move" animations for (i in pos2) { if (pos2.hasOwnProperty(i) !== true) continue var closestPiece = findClosestPiece(pos1, pos2[i], i) if (closestPiece !== false) { animations.push({ type: 'move', source: closestPiece, destination: i, piece: pos2[i] }) delete pos1[closestPiece] delete pos2[i] squaresMovedTo[i] = true } } // add pieces to pos2 for (i in pos2) { if (pos2.hasOwnProperty(i) !== true) continue animations.push({ type: 'add', square: i, piece: pos2[i] }) delete pos2[i] } // clear pieces from pos1 for (i in pos1) { if (pos1.hasOwnProperty(i) !== true) continue // do not clear a piece if it is on a square that is the result // of a "move", ie: a piece capture if (squaresMovedTo.hasOwnProperty(i) === true) continue animations.push({ type: 'clear', square: i, piece: pos1[i] }) delete pos1[i] } return animations } // ------------------------------------------------------------------------------ // Control Flow // ------------------------------------------------------------------------------ function drawPositionInstant () { // clear the board boardEl.find('.' + CSS.piece).remove() // add the pieces for (var i in CURRENT_POSITION) { if (CURRENT_POSITION.hasOwnProperty(i) !== true) { continue } if (CURRENT_POSITION[i] !== null) { $('#' + SQUARE_ELS_IDS[i]).append(buildPiece(CURRENT_POSITION[i])) } } } function drawBoard () { boardEl.html(buildBoard(CURRENT_ORIENTATION)) drawPositionInstant() if (cfg.sparePieces === true) { if (CURRENT_ORIENTATION === 'white') { sparePiecesTopEl.html(buildSparePieces('black')) sparePiecesBottomEl.html(buildSparePieces('white')) } else { sparePiecesTopEl.html(buildSparePieces('white')) sparePiecesBottomEl.html(buildSparePieces('black')) } } } // given a position and a set of moves, return a new position // with the moves executed function calculatePositionFromMoves (position, moves) { position = deepCopy(position) for (var i in moves) { if (moves.hasOwnProperty(i) !== true) continue // skip the move if the position doesn't have a piece on the source square if (position.hasOwnProperty(i) !== true) continue var piece = position[i] delete position[i] position[moves[i]] = piece } return position } function setCurrentPosition (position) { var oldPos = deepCopy(CURRENT_POSITION) var newPos = deepCopy(position) var oldFen = objToFen(oldPos) var newFen = objToFen(newPos) // do nothing if no change in position if (oldFen === newFen) { return false } // run their onChange function if (cfg.hasOwnProperty('onChange') === true && typeof cfg.onChange === 'function') { cfg.onChange(oldPos, newPos) } // update state CURRENT_POSITION = position } function isXYOnSquare (x, y) { for (var i in SQUARE_ELS_OFFSETS) { if (SQUARE_ELS_OFFSETS.hasOwnProperty(i) !== true) continue var s = SQUARE_ELS_OFFSETS[i] if (typeof s !== 'object') continue if (x >= s.left && x < s.left + SQUARE_SIZE && y >= s.top && y < s.top + SQUARE_SIZE) { return i } } return 'offboard' } // records the XY coords of every square into memory function captureSquareOffsets () { SQUARE_ELS_OFFSETS = {} for (var i in SQUARE_ELS_IDS) { if (SQUARE_ELS_IDS.hasOwnProperty(i) !== true) continue SQUARE_ELS_OFFSETS[i] = $('#' + SQUARE_ELS_IDS[i]).offset() } } function removeSquareHighlights () { boardEl.find('.' + CSS.square) .removeClass(CSS.highlight1 + ' ' + CSS.highlight2) } function snapbackDraggedPiece () { // there is no "snapback" for spare pieces if (DRAGGED_PIECE_SOURCE === 'spare') { trashDraggedPiece() return } removeSquareHighlights() // animation complete function complete () { drawPositionInstant() draggedPieceEl.css('display', 'none') // run their onSnapbackEnd function if (cfg.hasOwnProperty('onSnapbackEnd') === true && typeof cfg.onSnapbackEnd === 'function') { cfg.onSnapbackEnd(DRAGGED_PIECE, DRAGGED_PIECE_SOURCE, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) } } // get source square position var sourceSquarePosition = $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_SOURCE]).offset() // animate the piece to the target square var opts = { duration: cfg.snapbackSpeed, complete: complete } draggedPieceEl.animate(sourceSquarePosition, opts) // set state DRAGGING_A_PIECE = false } function trashDraggedPiece () { removeSquareHighlights() // remove the source piece var newPosition = deepCopy(CURRENT_POSITION) delete newPosition[DRAGGED_PIECE_SOURCE] setCurrentPosition(newPosition) // redraw the position drawPositionInstant() // hide the dragged piece draggedPieceEl.fadeOut(cfg.trashSpeed) // set state DRAGGING_A_PIECE = false } function dropDraggedPieceOnSquare (square) { removeSquareHighlights() // update position var newPosition = deepCopy(CURRENT_POSITION) delete newPosition[DRAGGED_PIECE_SOURCE] newPosition[square] = DRAGGED_PIECE setCurrentPosition(newPosition) // get target square information var targetSquarePosition = $('#' + SQUARE_ELS_IDS[square]).offset() // animation complete var complete = function () { drawPositionInstant() draggedPieceEl.css('display', 'none') // execute their onSnapEnd function if (cfg.hasOwnProperty('onSnapEnd') === true && typeof cfg.onSnapEnd === 'function') { cfg.onSnapEnd(DRAGGED_PIECE_SOURCE, square, DRAGGED_PIECE) } } // snap the piece to the target square var opts = { duration: cfg.snapSpeed, complete: complete } draggedPieceEl.animate(targetSquarePosition, opts) // set state DRAGGING_A_PIECE = false } function beginDraggingPiece (source, piece, x, y) { // run their custom onDragStart function // their custom onDragStart function can cancel drag start if (typeof cfg.onDragStart === 'function' && cfg.onDragStart(source, piece, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) === false) { return } // set state DRAGGING_A_PIECE = true DRAGGED_PIECE = piece DRAGGED_PIECE_SOURCE = source // if the piece came from spare pieces, location is offboard if (source === 'spare') { DRAGGED_PIECE_LOCATION = 'offboard' } else { DRAGGED_PIECE_LOCATION = source } // capture the x, y coords of all squares in memory captureSquareOffsets() // create the dragged piece if (cfg.pieceTheme === 'unicode') { draggedPieceEl.text(UNICODES[piece]) draggedPieceEl.attr('class', '').addClass(piece).addClass('unicode') } else { draggedPieceEl.attr('src', buildPieceImgSrc(piece)) } draggedPieceEl .css({ display: '', position: 'absolute', left: x - (SQUARE_SIZE / 2), top: y - (SQUARE_SIZE / 2), fontSize: SQUARE_SIZE + 'px' }) if (source !== 'spare') { // highlight the source square and hide the piece $('#' + SQUARE_ELS_IDS[source]).addClass(CSS.highlight1) .find('.' + CSS.piece).css('display', 'none') } } function updateDraggedPiece (x, y) { // put the dragged piece over the mouse cursor draggedPieceEl.css({ left: x - (SQUARE_SIZE / 2), top: y - (SQUARE_SIZE / 2) }) // get location var location = isXYOnSquare(x, y) // do nothing if the location has not changed if (location === DRAGGED_PIECE_LOCATION) return // remove highlight from previous square if (validSquare(DRAGGED_PIECE_LOCATION) === true) { $('#' + SQUARE_ELS_IDS[DRAGGED_PIECE_LOCATION]) .removeClass(CSS.highlight2) } // add highlight to new square if (validSquare(location) === true) { $('#' + SQUARE_ELS_IDS[location]).addClass(CSS.highlight2) } // run onDragMove if (typeof cfg.onDragMove === 'function') { cfg.onDragMove(location, DRAGGED_PIECE_LOCATION, DRAGGED_PIECE_SOURCE, DRAGGED_PIECE, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) } // update state DRAGGED_PIECE_LOCATION = location } function stopDraggedPiece (location) { // determine what the action should be var action = 'drop' if (location === 'offboard' && cfg.dropOffBoard === 'snapback') { action = 'snapback' } if (location === 'offboard' && cfg.dropOffBoard === 'trash') { action = 'trash' } // run their onDrop function, which can potentially change the drop action if (cfg.hasOwnProperty('onDrop') === true && typeof cfg.onDrop === 'function') { var newPosition = deepCopy(CURRENT_POSITION) // source piece is a spare piece and position is off the board // if (DRAGGED_PIECE_SOURCE === 'spare' && location === 'offboard') {...} // position has not changed; do nothing // source piece is a spare piece and position is on the board if (DRAGGED_PIECE_SOURCE === 'spare' && validSquare(location) === true) { // add the piece to the board newPosition[location] = DRAGGED_PIECE } // source piece was on the board and position is off the board if (validSquare(DRAGGED_PIECE_SOURCE) === true && location === 'offboard') { // remove the piece from the board delete newPosition[DRAGGED_PIECE_SOURCE] } // source piece was on the board and position is on the board if (validSquare(DRAGGED_PIECE_SOURCE) === true && validSquare(location) === true) { // move the piece delete newPosition[DRAGGED_PIECE_SOURCE] newPosition[location] = DRAGGED_PIECE } var oldPosition = deepCopy(CURRENT_POSITION) var result = cfg.onDrop(DRAGGED_PIECE_SOURCE, location, DRAGGED_PIECE, newPosition, oldPosition, CURRENT_ORIENTATION) if (result === 'snapback' || result === 'trash') { action = result } } // do it! if (action === 'snapback') { snapbackDraggedPiece() } else if (action === 'trash') { trashDraggedPiece() } else if (action === 'drop') { dropDraggedPieceOnSquare(location) } } // ------------------------------------------------------------------------------ // Public Methods // ------------------------------------------------------------------------------ // clear the board widget.clear = function (useAnimation) { widget.position({}, useAnimation) } // remove the widget from the page widget.destroy = function () { // remove markup containerEl.html('') draggedPieceEl.remove() // remove event handlers containerEl.unbind() } // shorthand method to get the current FEN widget.fen = function () { return widget.position('fen') } // flip orientation widget.flip = function () { return widget.orientation('flip') } /* // TODO: write this, GitHub Issue #5 widget.highlight = function() { } */ // move pieces widget.move = function () { // no need to throw an error here; just do nothing if (arguments.length === 0) return var useAnimation = true // collect the moves into an object var moves = {} for (var i = 0; i < arguments.length; i++) { // any "false" to this function means no animations if (arguments[i] === false) { useAnimation = false continue } // skip invalid arguments if (validMove(arguments[i]) !== true) { error(2826, 'Invalid move passed to the move method.', arguments[i]) continue } var tmp = arguments[i].split(/-|x/) moves[tmp[0]] = tmp[1] } // calculate position from moves var newPos = calculatePositionFromMoves(CURRENT_POSITION, moves) // update the board widget.position(newPos, useAnimation) // return the new position object return newPos } widget.orientation = function (arg) { // no arguments, return the current orientation if (arguments.length === 0) { return CURRENT_ORIENTATION } // set to white or black if (arg === 'white' || arg === 'black') { CURRENT_ORIENTATION = arg drawBoard() return CURRENT_ORIENTATION } // flip orientation if (arg === 'flip') { CURRENT_ORIENTATION = (CURRENT_ORIENTATION === 'white') ? 'black' : 'white' drawBoard() return CURRENT_ORIENTATION } error(5482, 'Invalid value passed to the orientation method.', arg) } widget.position = function (position, useAnimation) { // no arguments, return the current position if (arguments.length === 0) { return deepCopy(CURRENT_POSITION) } // get position as FEN if (typeof position === 'string' && position.toLowerCase() === 'fen') { return objToFen(CURRENT_POSITION) } // default for useAnimations is true if (useAnimation !== false) { useAnimation = true } // start position if (typeof position === 'string' && position.toLowerCase() === 'start') { position = deepCopy(START_POSITION) } // convert FEN to position object if (validFen(position) === true) { position = fenToObj(position) } // validate position object if (validPositionObject(position) !== true) { error(6482, 'Invalid value passed to the position method.', position) return } if (useAnimation === true) { // start the animations doAnimations(calculateAnimations(CURRENT_POSITION, position), CURRENT_POSITION, position) // set the new position setCurrentPosition(position) drawPositionInstant() } else { // instant update setCurrentPosition(position) drawPositionInstant() } } widget.resize = function () { // calulate the new square size SQUARE_SIZE = calculateSquareSize() // set board width boardEl.css('width', (SQUARE_SIZE * SIZE) + 'px') // set drag piece size draggedPieceEl.css({ height: SQUARE_SIZE, width: SQUARE_SIZE }) // spare pieces if (cfg.sparePieces === true) { containerEl.find('.' + CSS.sparePieces) .css('paddingLeft', (SQUARE_SIZE + BOARD_BORDER_SIZE) + 'px') } // redraw the board drawBoard() } // set the starting position widget.start = function (useAnimation) { widget.position('start', useAnimation) } // ------------------------------------------------------------------------------ // Browser Events // ------------------------------------------------------------------------------ function isTouchDevice () { return ('ontouchstart' in document.documentElement) } // reference: http://www.quirksmode.org/js/detect.html function isMSIE () { return (navigator && navigator.userAgent && navigator.userAgent.search(/MSIE/) !== -1) } function stopDefault (e) { e.preventDefault() } function mousedownSquare (e) { // do nothing if we're not draggable if (cfg.draggable !== true) return var square = $(this).attr('data-square') // no piece on this square if (validSquare(square) !== true || CURRENT_POSITION.hasOwnProperty(square) !== true) { return } beginDraggingPiece(square, CURRENT_POSITION[square], e.pageX, e.pageY) } function touchstartSquare (e) { // do nothing if we're not draggable if (cfg.draggable !== true) return var square = $(this).attr('data-square') // no piece on this square if (validSquare(square) !== true || CURRENT_POSITION.hasOwnProperty(square) !== true) { return } e = e.originalEvent beginDraggingPiece(square, CURRENT_POSITION[square], e.changedTouches[0].pageX, e.changedTouches[0].pageY) } function mousedownSparePiece (e) { // do nothing if sparePieces is not enabled if (cfg.sparePieces !== true) return var piece = $(this).attr('data-piece') beginDraggingPiece('spare', piece, e.pageX, e.pageY) } function touchstartSparePiece (e) { // do nothing if sparePieces is not enabled if (cfg.sparePieces !== true) return var piece = $(this).attr('data-piece') e = e.originalEvent beginDraggingPiece('spare', piece, e.changedTouches[0].pageX, e.changedTouches[0].pageY) } function mousemoveWindow (e) { // do nothing if we are not dragging a piece if (DRAGGING_A_PIECE !== true) return updateDraggedPiece(e.pageX, e.pageY) } function touchmoveWindow (e) { // do nothing if we are not dragging a piece if (DRAGGING_A_PIECE !== true) return // prevent screen from scrolling e.preventDefault() updateDraggedPiece(e.originalEvent.changedTouches[0].pageX, e.originalEvent.changedTouches[0].pageY) } function mouseupWindow (e) { // do nothing if we are not dragging a piece if (DRAGGING_A_PIECE !== true) return // get the location var location = isXYOnSquare(e.pageX, e.pageY) stopDraggedPiece(location) } function touchendWindow (e) { // do nothing if we are not dragging a piece if (DRAGGING_A_PIECE !== true) return // get the location var location = isXYOnSquare(e.originalEvent.changedTouches[0].pageX, e.originalEvent.changedTouches[0].pageY) stopDraggedPiece(location) } function mouseenterSquare (e) { // do not fire this event if we are dragging a piece // NOTE: this should never happen, but it's a safeguard if (DRAGGING_A_PIECE !== false) return if (cfg.hasOwnProperty('onMouseoverSquare') !== true || typeof cfg.onMouseoverSquare !== 'function') return // get the square var square = $(e.currentTarget).attr('data-square') // NOTE: this should never happen; defensive if (validSquare(square) !== true) return // get the piece on this square var piece = false if (CURRENT_POSITION.hasOwnProperty(square) === true) { piece = CURRENT_POSITION[square] } // execute their function cfg.onMouseoverSquare(square, piece, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) } function mouseleaveSquare (e) { // do not fire this event if we are dragging a piece // NOTE: this should never happen, but it's a safeguard if (DRAGGING_A_PIECE !== false) return if (cfg.hasOwnProperty('onMouseoutSquare') !== true || typeof cfg.onMouseoutSquare !== 'function') return // get the square var square = $(e.currentTarget).attr('data-square') // NOTE: this should never happen; defensive if (validSquare(square) !== true) return // get the piece on this square var piece = false if (CURRENT_POSITION.hasOwnProperty(square) === true) { piece = CURRENT_POSITION[square] } // execute their function cfg.onMouseoutSquare(square, piece, deepCopy(CURRENT_POSITION), CURRENT_ORIENTATION) } // ------------------------------------------------------------------------------ // Initialization // ------------------------------------------------------------------------------ function addEvents () { // prevent browser "image drag" $('body').on('mousedown mousemove', '.' + CSS.piece, stopDefault) // mouse drag pieces boardEl.on('mousedown', '.' + CSS.square, mousedownSquare) containerEl.on('mousedown', '.' + CSS.sparePieces + ' .' + CSS.piece, mousedownSparePiece) // mouse enter / leave square boardEl.on('mouseenter', '.' + CSS.square, mouseenterSquare) .on('mouseleave', '.' + CSS.square, mouseleaveSquare) // IE doesn't like the events on the window object, but other browsers // perform better that way if (isMSIE() === true) { // IE-specific prevent browser "image drag" document.ondragstart = function () { return false } $('body').on('mousemove', mousemoveWindow) .on('mouseup', mouseupWindow) } else { $(window).on('mousemove', mousemoveWindow) .on('mouseup', mouseupWindow) } // touch drag pieces if (isTouchDevice() === true) { boardEl.on('touchstart', '.' + CSS.square, touchstartSquare) containerEl.on('touchstart', '.' + CSS.sparePieces + ' .' + CSS.piece, touchstartSparePiece) $(window).on('touchmove', touchmoveWindow) .on('touchend', touchendWindow) } } function initDom () { // create unique IDs for all the elements we will create createElIds() // build board and save it in memory containerEl.html(buildBoardContainer()) boardEl = containerEl.find('.' + CSS.board) if (cfg.sparePieces === true) { sparePiecesTopEl = containerEl.find('.' + CSS.sparePiecesTop) sparePiecesBottomEl = containerEl.find('.' + CSS.sparePiecesBottom) } // create the drag piece var draggedPieceId = uuid() $('body').append(buildPiece('w', true, draggedPieceId)) draggedPieceEl = $('#' + draggedPieceId) // get the border size BOARD_BORDER_SIZE = parseInt(boardEl.css('borderLeftWidth'), 10) // set the size and draw the board widget.resize() } function init () { if (checkDeps() !== true || expandConfig() !== true) return initDom() addEvents() } // go time init() // return the widget object return widget } // end window.DraughtsBoard // expose util functions window.DraughtsBoard.fenToObj = fenToObj window.DraughtsBoard.objToFen = objToFen if (typeof exports !== 'undefined') { exports.DraughtsBoard = DraughtsBoard } if (typeof define !== 'undefined') { define(function () { return DraughtsBoard }) } })()
shubhendusaurabh/draughtsboardJS
draughtsboard.js
JavaScript
mpl-2.0
49,458
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; var convict = require('convict'); var format = require('util').format; var getHashes = require('crypto').getHashes; var path = require('path'); var fs = require('fs'); /** * Validates the keys are present in the configuration object. * * @param {List} keys A list of keys that must be present. * @param {Boolean} options List of options to use. **/ function validateKeys(keys, options) { options = options || {}; var optional = options.optional || false; return function(val) { if (JSON.stringify(val) === "{}" && optional === true) { return; } if (!optional && !val) throw new Error("Should be defined"); keys.forEach(function(key) { if (!val.hasOwnProperty(key)) throw new Error(format("Should have a %s property", key)); }); }; } /** * Build a validator that makes sure of the size and hex format of a key. * * @param {Integer} size Number of bytes of the key. **/ function hexKeyOfSize(size) { return function check(val) { if (val === "") return; if (!new RegExp(format('^[a-fA-FA0-9]{%d}$', size * 2)).test(val)) { throw new Error("Should be an " + size + " bytes key encoded as hexadecimal"); } }; } /** * Validates that each channel has an apiKey and apiSecret as well as * an optional apiUrl and nothing else. Alse make sure the default * channel is defined. **/ function tokBoxCredentials(credentials) { if (!credentials.hasOwnProperty("default")) { throw new Error("Please define the default TokBox channel credentials."); } var authorizedKeys = ["apiKey", "apiSecret", "apiUrl"]; function checkKeys(key) { if (authorizedKeys.indexOf(key) === -1) { throw new Error(key + " configuration value is unknown. " + "Should be one of " + authorizedKeys.join(", ") + "."); } } for (var channel in credentials) { // Verify channel keys validity. Object.keys(credentials[channel]).forEach(checkKeys); if (!credentials[channel].hasOwnProperty("apiKey")) { throw new Error(channel + " channel should define an apiKey."); } if (!credentials[channel].hasOwnProperty("apiSecret")) { throw new Error(channel + " channel should define an apiSecret."); } } } var conf = convict({ env: { doc: "The applicaton environment.", format: [ "dev", "test", "stage", "prod", "loadtest"], default: "dev", env: "NODE_ENV" }, ip: { doc: "The IP address to bind.", format: "ipaddress", default: "127.0.0.1", env: "IP_ADDRESS" }, port: { doc: "The port to bind.", format: "port", default: 5000, env: "PORT" }, acceptBacklog: { doc: "The maximum length of the queue of pending connections", format: Number, default: 511, env: "ACCEPT_BACKLOG" }, publicServerAddress: { doc: "The public-facing server address", format: String, default: "localhost:5000", env: "SERVER_ADDRESS" }, protocol: { doc: "The protocol the server is behind. Should be https behind an ELB.", format: String, default: "http", env: "PROTOCOL" }, macSecret: { doc: "The secret for MAC tokens (32 bytes key encoded as hex)", format: hexKeyOfSize(32), default: "", env: "MAC_SECRET" }, encryptionSecret: { doc: "The secret for encrypting tokens (16 bytes key encoded as hex)", format: hexKeyOfSize(16), default: "", env: "ENCRYPTING_SECRET" }, userMacSecret: { doc: "The secret for hmac-ing userIds (16 bytes key encoded as hex)", format: hexKeyOfSize(16), default: "", env: "USER_MAC_SECRET" }, userMacAlgorithm: { doc: "The algorithm that should be used to mac userIds", format: function(val) { if (getHashes().indexOf(val) === -1) { throw new Error("Given hmac algorithm is not supported"); } }, default: "sha256", env: "USER_MAC_ALGORITHM" }, calls: { maxSubjectSize: { doc: "The maximum number of chars for the subject of a call", format: Number, default: 124 } }, callUrls: { tokenSize: { doc: "The callUrl token size (in bytes).", format: Number, default: 8 }, timeout: { doc: "How much time a token is valid for (in hours)", format: Number, default: 24 * 30 // One month. }, maxTimeout: { doc: "The maximum number of hours a token can be valid for.", format: Number, default: 24 * 30 }, webAppUrl: { doc: "Loop Web App Home Page.", format: "url", default: "http://localhost:3000/c/{token}", env: "WEB_APP_URL" } }, displayVersion: { doc: "Display the server version on the homepage.", default: true, format: Boolean }, storage: { engine: { doc: "engine type", format: String, default: "redis" }, settings: { doc: "js object of options to pass to the storage engine", format: Object, default: { port: 6379, host: 'localhost' } } }, filestorage: { engine: { doc: "engine type", format: ["filesystem", "aws"], default: "filesystem" }, settings: { doc: "js object of options to pass to the files engine", format: Object, default: { base_dir: "/tmp" } } }, pubsub: { doc: "js object of options to pass to the pubsub engine", format: Object, default: { port: 6379, host: 'localhost' } }, fakeTokBox: { doc: "Mock TokBox calls", format: Boolean, default: false }, fakeTokBoxURL: { doc: "URL where to Mock TokBox calls", format: String, default: "https://call.stage.mozaws.net/" }, tokBox: { apiUrl: { doc: 'api endpoint for tokbox', format: String, default: "https://api.opentok.com" }, credentials: { doc: "api credentials based on a channel.", format: tokBoxCredentials, default: {} }, tokenDuration: { doc: 'how long api tokens are valid for in seconds', format: "nat", default: 24 * 3600 }, retryOnError: { doc: 'how many times to retry on error', format: "nat", default: 3 }, timeout: { doc: "Timeout for requests when trying to create the session (ms)", format: Number, default: 2000 } }, sentryDSN: { doc: "Sentry DSN", format: function(val) { if (!(typeof val === "string" || val === false)) { throw new Error("should be either a sentryDSN or 'false'"); } }, default: false, env: "SENTRY_DSN" }, statsd: { doc: "Statsd configuration", format: validateKeys(['port', 'host'], {'optional': true}), default: {} }, statsdEnabled: { doc: "Defines if statsd is enabled or not", format: Boolean, default: false }, allowedOrigins: { doc: "Authorized origins for cross-origin requests.", format: Array, default: ['http://localhost:3000'] }, retryAfter: { doc: "Seconds to wait for on 503", format: Number, default: 30 }, fxaAudiences: { doc: "List of accepted fxa audiences.", format: Array, default: [] }, fxaVerifier: { doc: "The Firefox Accounts verifier url", format: String, env: "FXA_VERIFIER", default: "https://verifier.accounts.firefox.com/v2" }, fxaTrustedIssuers: { doc: "The list of Firefox Accounts trusted issuers", format: Array, default: ["api.accounts.firefox.com"] }, hawkIdSecret: { doc: "The secret for hmac-ing the hawk id (16 bytes key encoded as hex)", format: hexKeyOfSize(16), default: "", env: "HAWK_ID_SECRET" }, hawkSessionDuration: { doc: "The duration of hawk credentials (in seconds)", format: Number, default: 3600 * 24 * 30 // One month. }, callDuration: { doc: "The duration we want to store the call info (in seconds)", format: Number, default: 60 }, maxHTTPSockets: { doc: "The maximum of HTTP sockets to use when doing requests", format: Number, default: 10000000 }, heartbeatTimeout: { doc: "Timeout for requests when doing heartbeat checks (ms)", format: Number, default: 2000 }, timers: { supervisoryDuration: { doc: "Websocket timeout for the supervisory timer (seconds)", format: Number, default: 10 }, ringingDuration: { doc: "Websocket timeout for the ringing timer (seconds)", format: Number, default: 30 }, connectionDuration: { doc: "Websocket timeout for the connection timer (seconds)", format: Number, default: 10 } }, progressURLEndpoint: { doc: "The endpoint to use for the progressURL.", format: String, default: "/websocket" }, i18n: { defaultLang: { format: String, default: 'en-US' } }, pushServerURIs: { doc: "An array of push server URIs", format: Array, default: ["wss://push.services.mozilla.com/"] }, fxaOAuth: { activated: { doc: "Set to false if you want to deactivate FxA-OAuth on this instance.", format: Boolean, default: true }, client_id: { doc: "The FxA client_id (8 bytes key encoded as hex)", format: hexKeyOfSize(8), default: "" }, client_secret: { doc: "The FxA client secret (32 bytes key encoded as hex)", format: hexKeyOfSize(32), default: "" }, oauth_uri: { doc: "The location of the FxA OAuth server.", format: "url", default: "https://oauth.accounts.firefox.com/v1" }, content_uri: { doc: "The location of the FxA content server.", format: "url", default: "https://accounts.firefox.com" }, redirect_uri: { doc: "The redirect_uri.", format: String, default: "urn:ietf:wg:oauth:2.0:fx:webchannel" }, profile_uri: { doc: "The FxA profile uri.", format: "url", default: "https://profile.firefox.com/v1" }, scope: { doc: "The scope we're requesting access to", format: String, default: "profile" } }, logRequests: { activated: { doc: "Defines if requests should be logged to Stdout", default: false, format: Boolean }, consoleDateFormat: { doc: "Date format of the logging line.", format: String, default: "%y/%b/%d %H:%M:%S" } }, hekaMetrics: { activated: { doc: "Defines if metrics should be directed to hekad", default: false, format: Boolean }, debug: { doc: "Heka logger display development logs", format: Boolean, default: false }, level: { doc: "Log level.", format: String, default: "INFO" }, fmt: { doc: "Log level.", format: String, default: "heka" } }, newRelic: { activated: { doc: "Defines if newrelic is activated or not", default: false, format: Boolean }, licenceKey: { doc: "New Relic licence key", format: String, default: "" }, loggingLevel: { doc: "Logging level to use", format: String, default: "info" }, appName: { doc: "New Relic application name", format: String, default: "Loop Server" } }, dumpHeap: { activated: { doc: "Defines if uncaught exceptions should dump snapshots", default: true, format: Boolean }, location: { doc: "Location where to output the files (directory).", format: String, default: '/tmp' } }, rooms: { defaultTTL: { doc: "The default TTL for a room (in hours)", format: Number, default: 8 * 7 * 24 // 8 weeks }, maxTTL: { doc: "The maximum TTL for a room (in hours) allowed by the server", format: Number, default: 8 * 7 * 24 // 8 weeks }, extendTTL: { doc: "The new TTL for a room (in hours) after a participant join.", format: Number, default: 8 * 7 * 24 // 8 weeks }, participantTTL: { doc: "The TTL (in seconds) for a participant in the room", format: Number, default: 5 * 60 // 5 minutes }, deletedTTL: { doc: "The TTL (in seconds) for a room delete notification to be saved", format: Number, default: 27 * 60 // 27 minutes }, maxSize: { doc: "The maximum size of a room", format: Number, default: 5 }, maxRoomNameSize: { doc: "The maximum number of chars to name a room", format: Number, default: 100 }, maxRoomOwnerSize: { doc: "The maximum number of chars for the owner of a room", format: Number, default: 255 }, tokenSize: { doc: "The room token size (in bytes).", format: Number, default: 8 }, webAppUrl: { doc: "Loop Web App rooms url.", format: "url", default: "http://localhost:3000/{token}", env: "ROOMS_WEB_APP_URL" }, HKDFSalt: { doc: "The salt that will be used to cipher profile data " + "(16 bytes key encoded as hex)", format: hexKeyOfSize(16), default: "", env: "ROOMS_HKDF_SECRET" } }, ga: { activated: { doc: "Should we send POST /events data to Google Analytics while true.", default: false, format: Boolean }, id: { doc: "Google analytics ID.", default: "", format: String } } }); // handle configuration files. you can specify a CSV list of configuration // files to process, which will be overlayed in order, in the CONFIG_FILES // environment variable. By default, the ../config/<env>.json file is loaded. var envConfig = path.join(__dirname, '/../config', conf.get('env') + '.json'); var files = (envConfig + ',' + process.env.CONFIG_FILES) .split(',') .filter(fs.existsSync); conf.loadFile(files); conf.validate(); if (conf.get('macSecret') === "") throw "Please define macSecret in your configuration file"; if (conf.get('rooms').HKDFSalt === "") throw "Please define rooms.HKDFSalt in your configuration file"; if (conf.get('encryptionSecret') === "") throw "Please define encryptionSecret in your configuration file"; if (conf.get('allowedOrigins') === "") { throw "Please define the list of allowed origins for CORS."; } if (conf.get('fxaAudiences').length === 0) { throw "Please define the list of allowed Firefox Accounts audiences"; } if (conf.get('hawkSessionDuration') < conf.get('callUrls').maxTimeout * 60 * 60) { throw "hawkSessionDuration should be longer or equal to callUrls.maxTimeout"; } if (conf.get('fxaOAuth').activated && conf.get('fxaOAuth').client_id === "") { throw "fxaOAuth is activated but not well configured. " + "Set fxaOAuth.activated config key to false to continue"; } // Configure S3 the environment variable for tests. if (conf.get('env') === 'test') { process.env.AWS_ACCESS_KEY_ID = 'TESTME'; process.env.AWS_SECRET_ACCESS_KEY = 'TESTME'; } // Verify timers var timers = conf.get("timers"); var minCallDuration = timers.supervisoryDuration + timers.ringingDuration + timers.connectionDuration; if (minCallDuration > conf.get("callDuration")) { throw "the callDuration should be at least " + minCallDuration + " seconds"; } module.exports = { conf: conf, hexKeyOfSize: hexKeyOfSize, validateKeys: validateKeys };
mozilla-services/loop-server
loop/config.js
JavaScript
mpl-2.0
15,679
import basicAuth from 'express-basic-auth' import { Ability } from '@casl/ability' const userAccountAuthorizer = (app) => async (email, password, cb) => { try { const auth = await app .service('authentication') .create({ email, password, strategy: 'local' }, { provider: 'rest' }) const ability = new Ability(auth.abilities) return cb(null, ability.can('read', 'arena')) } catch (e) { app.info('basic auth failed', e) return cb(null, false) } } export default (app) => basicAuth({ authorizer: userAccountAuthorizer(app), challenge: true, authorizeAsync: true, })
teikei/teikei
api/src/middleware/userAccountBasicAuth.js
JavaScript
agpl-3.0
619
function Component(type,id,uri,name,query,inputList,x,y) { // this.code = code; // this.type = type; this.componentId = id; this.uri = uri; this.name = name; this.query = query; this.inputList = inputList; this.x = x; this.y = y; }; Component.prototype = { constructor: Component, // getCode: function() { return this.code; }, getType: function() { return this.type; }, getId: function() { return this.componentId; }, getURI: function() { return this.uri; }, getName: function() { return this.name; }, getQuery: function() { return this.query; }, getInputList: function() { return this.inputList; }, getPositionX: function() { return this.x; }, getPositionY: function() { return this.y; } }; /*Scrive il nome del componente nel div*/ Component.scriviNome = function(div,code,cnt){ var name = Component.getName(code); var label = document.createElement("label"); label.setAttribute("class","activeimg"); var br = document.createElement("br"); if(code == 0 || code == 1){ name = div.title; var text = document.createTextNode(name); label.appendChild(text); label.appendChild(br); label.appendChild(br); return label; } if(name == null){ name = div.title + " " + cnt; var text = document.createTextNode(name); label.appendChild(text); label.appendChild(br); return label; } else{ var text = document.createTextNode(name); label.appendChild(text); label.appendChild(br); return label; } }; /*Ricarica la pipeline creata*/ Component.loadPipeline = function(editor,code,component,id,uri,name,query,inputlist,x,y){ //alert(code + component + id + uri + name + query + inputlist + x + y); var div = document.createElement("div"); div.setAttribute("class","activegraph"); div.setAttribute("id","comp-" + code); div.title = code; var img = document.createElement("img"); img.setAttribute("id","activeimg"); if(component == "inputdefault" || component == "input"){img.src = "IMG/Input.gif";} if(component == "outputdefault" || component == "output"){img.src = "IMG/Output.gif";} if(component == "union"){img.src = "IMG/Union.gif";} if(component == "construct"){img.src = "IMG/Construct.gif";} if(component == "updatable"){img.src = "IMG/Updatable.gif";} if(component == "dataset"){img.src = "IMG/Dataset.gif";} div.appendChild(img); var label = document.createElement("label"); label.setAttribute("class","activeimg"); var br = document.createElement("br"); var text = document.createTextNode(name); label.appendChild(text); label.appendChild(br); label.appendChild(br); div.appendChild(label); if(component == "input" || component == "output" || component == "union" || component == "construct" || component == "updatable" || component == "dataset"){ var proprieta = document.createElement("img"); proprieta.setAttribute("class","bottongraph"); proprieta.src = "IMG/pulsanteproprieta.gif"; proprieta.title = "property"; div.appendChild(proprieta); Core.addEventListener(proprieta,"click",function(){ var body = document.createElement("div"); body.setAttribute("class","body"); formIN = Form.createForm(div,code); document.getElementsByTagName("body")[0].appendChild(formIN); document.getElementsByTagName("body")[0].appendChild(body); }); var elimina = document.createElement("img"); elimina.setAttribute("class","bottongraph"); elimina.src = "IMG/iconaX.gif"; elimina.title = "delete"; div.appendChild(elimina); Core.addEventListener(elimina,"click",function(){ temp = elimina.parentNode.parentNode; jsPlumb.removeAllEndpoints(elimina.parentNode); jsPlumb.detachAllConnections(elimina.parentNode); temp.removeChild(elimina.parentNode); Component.elimina(componentVett,code); Code.cancellaCodice(code); }); } var x = div.style.left = x; var y = div.style.top = y; editor.appendChild(div); Endpoint.createEndpoint(div,code,null); if((component == "construct" || component == "updatable") && inputlist.length != 0){Endpoint.createEndpoint(div,code,2);} Code.modificaCodice(code); };
miguel76/WorldPipes
WebContent/components/Union.js
JavaScript
agpl-3.0
4,217
// EXIF Orientation test // iOS looks at the EXIF Orientation flag in jpgs and rotates the image // accordingly. Looks like most desktop browsers just ignore this data. // description: www.impulseadventure.com/photo/exif-orientation.html // Bug trackers: // bugzil.la/298619 (unimplemented) // crbug.com/56845 (looks incomplete) // webk.it/19688 (available upstream but its up all ports to turn on individually) // // detect by Paul Sayre (function(){ var img = new Image(); img.onerror = function() { Modernizr.addTest('exif-orientation', function () { return false; }); }; img.onload = function() { Modernizr.addTest('exif-orientation', function () { return img.width !== 2; }); }; // There may be a way to shrink this more, it's a 1x2 white jpg with the orientation flag set to 6 img.src = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAASUkqAAgAAAABABIBAwABAAAABgASAAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEIIKxwRVSfAkM2JyggkKFhcYGRolJicoKSoNTY3ODk6QRFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP9fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanNdXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrOtba3uLm6wsPExcbHyMnKtPU1dbX2Nna4uPk5ebn6Onq8vP9fb3+Pn6/9oADAMBAAIRAxEAPwD+/iiiigD/2Q=="; })();
Firescar96/kotoken
app/assets/css-toggle-switch-gh-pages/bower_components/modernizr/feature-detects/exif-orientation.js
JavaScript
agpl-3.0
1,755
/* This file is a part of libertysoil.org website Copyright (C) 2016 Loki Education (Social Enterprise) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import i from 'immutable'; import { getTypeError, createRequirableTypeChecker, createSimplifiedRequirableTypeChecker, checkValues, checkKeys } from './utils'; export const mapOfKeys = (keyCheckType) => ( createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location, ...rest) => { const expectedType = 'object'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } return checkKeys( keyCheckType, propValue, propFullName, componentName, location, ...rest ); } ) ); export const mapOfValues = (valueCheckType) => ( createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location, ...rest) => { const expectedType = 'object'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } return checkValues( valueCheckType, propValue, propFullName, componentName, location, ...rest ); } ) ); export const mapOf = (keyCheckType, valueCheckType) => ( createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location, ...rest) => { const expectedType = 'object'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } const error = checkKeys( keyCheckType, propValue, propFullName, componentName, location, ...rest ); if (error instanceof Error) { return error; } return checkValues( valueCheckType, propValue, propFullName, componentName, location, ...rest ); } ) ); export const Immutable = (checkType) => ( createRequirableTypeChecker( (props, propName, componentName, location, propFullName, ...rest) => { const propValue = props[propName]; // all Immutable date types are subclasses of Immutable.Iterable if (i.Iterable.isIterable(propValue)) { const preparedPropValue = propValue.toJS(); const preraredProps = { ...props, [propName]: preparedPropValue }; // vanilla instance of PropTypes' checkType() // or result of createRequirableTypeChecker() if (!checkType.isSimplified) { return checkType( preraredProps, propName, componentName, location, propFullName, ...rest ); } // result of createSimplifiedRequirableTypeChecker() let fullName = propName; if (propFullName) { fullName = propFullName; } return checkType( preparedPropValue, fullName, componentName, location, ...rest ); } return new Error( `Invalid prop \`${propFullName}\` of type \`${typeof propValue}\` ` + `supplied to \`${componentName}\` isn't an instance of any Immutable data type.` ); } ) ); export const uuid4 = createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location) => { const expectedType = 'string'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } const test = RegExp(/^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}$/i); if (!propValue.match(test)) { return new Error( `Invalid prop \`${propFullName}\` of type \`${expectedType}\` ` + `supplied to \`${componentName}\` doesn't match the UUID pattern.` ); } return null; } ); export const date = createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location) => { if (propValue instanceof Date) { return null; } const expectedType = 'string'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } const date = new Date(propValue); const dateString = date.toString(); if (dateString === 'Invalid date') { return new Error( `Invalid prop \`${propFullName}\` of type \`${expectedType}\` ` + `supplied to \`${componentName}\` is invalid date string representation.` ); } return null; } ); export const url = createSimplifiedRequirableTypeChecker( (propValue, propFullName, componentName, location) => { const expectedType = 'string'; if (typeof propValue !== expectedType) { return getTypeError(propValue, expectedType, propFullName, componentName, location); } const test = RegExp(/^[a-z0-9_.'-]+$/i); if (!propValue.match(test)) { return new Error( `Invalid prop \`${propFullName}\` of type \`${expectedType}\` ` + `supplied to \`${componentName}\` is invalid URL representation.` ); } return null; } );
Lokiedu/libertysoil-site
src/prop-types/common.js
JavaScript
agpl-3.0
5,950
engine.eval("load('nashorn:mozilla_compat.js');"); /* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** -- Odin JavaScript -------------------------------------------------------------------------------- Harry - Before Takeoff <To Orbis>(240000111) -- By --------------------------------------------------------------------------------------------- Information -- Version Info ----------------------------------------------------------------------------------- 1.3 - Add missing return statement [Thanks sadiq for the bug, fix by Information] 1.2 - Replace function to support latest [Information] 1.1 - Fix wrong placed statement [Information] 1.0 - First Version by Information --------------------------------------------------------------------------------------------------- **/ importPackage(Packages.net.sf.odinms.client); function start() { status = -1; cb = cm.getEventManager("Cabin"); action(1, 0, 0); } function action(mode, type, selection) { if(mode == -1) { cm.dispose(); return; } else { status++; if(mode == 0) { cm.sendOk("You'll get to your destination in moment. Go ahead and talk to other people, and before you know it, you'll be there already."); cm.dispose(); return; } if(status == 0) { cm.sendYesNo("Do you want to leave the waiting room? You can, but the ticket is NOT refundable. Are you sure you still want to leave this room?"); } else if(status == 1) { cm.warp(240000110); cm.dispose(); } } }
Micah-S/hidden-ms
src/scripts/npc/2082002.js
JavaScript
agpl-3.0
2,408
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'sourcearea', 'ko', { toolbar: '소스' } );
afshinnj/php-mvc
assets/framework/ckeditor/plugins/sourcearea/lang/ko.js
JavaScript
agpl-3.0
225
// i18n.js App.i18n = { strings: {}, loaded: false, setLanguage: function(languageCode, callback) { this.languageCode = languageCode; App.localStorage.set('selected_interface_locale', languageCode); this.loadStrings(callback); }, getLanguage: function(languageCode) { return this.languageCode; }, translate: function(string, stringId) { if (typeof(stringId) == 'undefined') stringId = string; if (typeof(this.strings[stringId]) === 'undefined' || this.strings[stringId] === false || this.strings[stringId] === '') return string; else return this.strings[stringId]; }, translateDOM: function() { var that = this; $("[data-i18n]").each(function() { var string = $(this).data('i18n'); string = that.translate(string); $(this).text(string); }); $("[data-i18nvalue]").each(function() { var string = $(this).data('i18nvalue'); string = that.translate(string); $(this).val(string); }); $("[data-i18nplaceholder]").each(function() { var string = $(this).data('i18nplaceholder'); string = that.translate(string); $(this).attr('placeholder', string); }); }, loadStrings: function(callback) { var that = this; var process = function(data) { that.strings = data; that.loaded = true; that.translateDOM(); if (typeof(callback) == 'function') callback(); }; this.loaded = false; if (this.languageCode == 'default') process({}); else $.ajax({ url: App.settings.apiEntryPoint + 'i18n/bycode/' + this.languageCode.split('-').join(''), data: {}, success: process, dataType: 'json', mimeType: 'application/json', cache: true }); } };
jeka-kiselyov/dimeshift
public/scripts/app/i18n.js
JavaScript
agpl-3.0
1,657
{ "metadata" : { "formatVersion" : 3.1, "sourceFile" : "Buffalo.obj", "generatedBy" : "OBJConverter", "vertices" : 2202, "faces" : 4134, "normals" : 2113, "uvs" : 0, "materials" : 4 }, "materials": [ { "DbgColor" : 15658734, "DbgIndex" : 0, "DbgName" : "Material.006", "colorDiffuse" : [0.287072, 0.214367, 0.076018], "colorSpecular" : [0.5, 0.5, 0.5], "illumination" : 2, "opacity" : 1.0, "opticalDensity" : 1.0, "specularCoef" : 96.078431 }, { "DbgColor" : 15597568, "DbgIndex" : 1, "DbgName" : "hoof", "colorDiffuse" : [0.017583, 0.008414, 0.0], "colorSpecular" : [0.0, 0.0, 0.0], "illumination" : 2, "opacity" : 1.0, "opticalDensity" : 1.0, "specularCoef" : 96.078431 }, { "DbgColor" : 60928, "DbgIndex" : 2, "DbgName" : "horse_body", "colorDiffuse" : [0.098968, 0.055305, 0.002045], "colorSpecular" : [0.0, 0.0, 0.0], "illumination" : 2, "opacity" : 1.0, "opticalDensity" : 1.0, "specularCoef" : 96.078431 }, { "DbgColor" : 238, "DbgIndex" : 3, "DbgName" : "tail", "colorDiffuse" : [0.0, 0.0, 0.0], "colorSpecular" : [0.0, 0.0, 0.0], "illumination" : 2, "opacity" : 1.0, "opticalDensity" : 1.0, "specularCoef" : 96.078431 }], "buffers": "Buffalo.bin" }
adaxi/freeciv-web
freeciv-web/src/main/webapp/3d-models/Buffalo.js
JavaScript
agpl-3.0
1,330
/* * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting. * * Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4. * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ function BaseDemographicEstimateController($scope, rights, categories, programs , years, $filter) { //TODO: read this configuration from backend. $scope.enableAutoCalculate = false; $scope.showFacilityAggregatesOption = false; $scope.currentPage = 1; $scope.pageSize = 50; $scope.categories = categories; $scope.rights = rights; $scope.years = years; $scope.programs = programs; $scope.$watch('currentPage', function () { if ($scope.isDirty()) { $scope.save(); } if (angular.isDefined($scope.lineItems)) { $scope.pageLineItems(); } }); $scope.isDirty = function () { return $scope.$dirty; }; $scope.hasPermission = function (permission) { return ($scope.rights.indexOf(permission) >= 0); }; $scope.showParent = function (index) { if (index > 0) { return ($scope.form.estimateLineItems[index].parentName !== $scope.form.estimateLineItems[index - 1].parentName); } return true; }; $scope.pageLineItems = function () { $scope.pageCount = Math.ceil($scope.lineItems.length / $scope.pageSize); if ($scope.lineItems.length > $scope.pageSize) { $scope.form.estimateLineItems = $scope.lineItems.slice($scope.pageSize * ($scope.currentPage - 1), $scope.pageSize * Number($scope.currentPage)); } else { $scope.form.estimateLineItems = $scope.lineItems; } }; $scope.clearMessages = function(){ $scope.message = ''; $scope.error = ''; }; $scope.init = function(){ // default to the current year $scope.year = Number( $filter('date')(new Date(), 'yyyy') ); // when the available program is only 1, default to this program. if(programs.length === 1){ $scope.program = programs[0].id; } $scope.onParamChanged(); }; } BaseDemographicEstimateController.resolve = { categories: function ($q, $timeout, DemographicEstimateCategories) { var deferred = $q.defer(); $timeout(function () { DemographicEstimateCategories.get({}, function (data) { deferred.resolve(data.estimate_categories); }, {}); }, 100); return deferred.promise; }, years: function ($q, $timeout, OperationYears) { var deferred = $q.defer(); $timeout(function () { OperationYears.get({}, function (data) { deferred.resolve(data.years); }); }, 100); return deferred.promise; }, programs: function($q, $timeout, DemographicEstimatePrograms){ var deferred = $q.defer(); $timeout(function(){ DemographicEstimatePrograms.get({}, function(data){ deferred.resolve(data.programs); }); },100); return deferred.promise; }, rights: function ($q, $timeout, UserSupervisoryRights) { var deferred = $q.defer(); $timeout(function () { UserSupervisoryRights.get({}, function (data) { deferred.resolve(data.rights); }, {}); }, 100); return deferred.promise; } };
USAID-DELIVER-PROJECT/elmis
modules/openlmis-web/src/main/webapp/public/js/demographics/controller/base-demographic-estimate-controller.js
JavaScript
agpl-3.0
3,940
function recaptcha_verified () { document.querySelector('.recaptcha_submit').removeAttribute('disabled') } function recaptcha_expired () { document.querySelector('.recaptcha_submit').setAttribute('disabled', 'disabled') }
julianguyen/ifme
app/assets/javascripts/require_recaptcha.js
JavaScript
agpl-3.0
227
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details. * * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/ */ function DistrictDemographicEstimateController($scope, categories, years, DistrictDemographicEstimates, SaveDistrictDemographicEstimates) { $scope.categories = categories; $scope.years = years; $scope.year = years[0]; $scope.OnPopulationChanged = function(population, district, category){ var pop = $scope.toNumber(population.value); if(category.isPrimaryEstimate){ angular.forEach(district.districtEstimates, function(estimate){ if(population.demographicEstimateId !== estimate.demographicEstimateId){ estimate.value = $scope.round(estimate.conversionFactor * pop / 100) ; } }); } }; $scope.onParamChanged = function(){ DistrictDemographicEstimates.get({year: $scope.year}, function(data){ $scope.form = data.estimates; angular.forEach($scope.form.estimateLineItems, function(fe){ fe.indexedEstimates = _.indexBy( fe.districtEstimates , 'demographicEstimateId' ); }); }); }; $scope.toNumber = function (val) { if (angular.isDefined(val) && val !== null) { return parseInt(val, 10); } return 0; }; $scope.round = function(val){ return Math.ceil(val); }; $scope.save = function(){ SaveDistrictDemographicEstimates.update($scope.form, function(data){ // show the saved message //TODO: move this string to the messages property file. $scope.message = "District demographic estimates successfully saved."; }); }; $scope.onParamChanged(); } DistrictDemographicEstimateController.resolve = { categories: function ($q, $timeout, DemographicEstimateCategories) { var deferred = $q.defer(); $timeout(function () { DemographicEstimateCategories.get({}, function (data) { deferred.resolve(data.estimate_categories); }, {}); }, 100); return deferred.promise; }, years: function ($q, $timeout, OperationYears) { var deferred = $q.defer(); $timeout(function () { OperationYears.get({}, function (data) { deferred.resolve(data.years); }); }, 100); return deferred.promise; } };
kelvinmbwilo/vims
modules/openlmis-web/src/main/webapp/public/js/vaccine/demographics/controller/district-demographic-estimate-controller.js
JavaScript
agpl-3.0
3,037
module.exports = { error: require('./error'), store: require('./store'), task: require('./task') };
jcolag/mindlessChat
node_modules/hoodie-server/node_modules/hoodie/src/lib/index.js
JavaScript
agpl-3.0
106
/*Copyright (c) Shelloid Systems LLP. All rights reserved. The use and distribution terms for this software are covered by the GNU Affero General Public License 3.0 (http://www.gnu.org/licenses/agpl-3.0.html) which can be found in the file LICENSE at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. */ /** * Created by Harikrishnan on 21/5/14. */ exports.index = function (req, res) { easydb(dbPool) .query(function () { return { query: "SELECT email, name, gen_code FROM pending_registrations WHERE email = ? and gen_code = ? and name = ?", params: [decodeURIComponent(req.body.email), decodeURIComponent(req.body.id), decodeURIComponent(req.body.name)] }; }) .success(function (rows) { if (rows.length > 0) { res.send({status: 200, name: rows[0].name}); } else { throw new Error("Validation failed."); } }). query(function () { return { query: "INSERT INTO users (`email`, `md5_password`, `salt`, `name`, `last_login_time`) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)", params: [req.body.email, req.body.md5_secret, req.body.salt, req.body.name] }; }). query(function () { return { query: "DELETE FROM pending_registrations WHERE email = ?", params: [decodeURIComponent(req.body.email)] }; }). success(function (rows) { res.send({status: 200}); }). error(function (err) { console.log(err); res.send({msg: err, status: 500}); }).execute({transaction: true}); };
jayaraj-poroor/vpt-web
basic-admin/routes/user/signup.js
JavaScript
agpl-3.0
1,917
var BUFFER_SIZE = 2048; var div = 1; var context = new AudioContext(); var masterNode = context.createScriptProcessor(BUFFER_SIZE*4, 2, 2); var nodes = []; var eqs = []; loadSample = function(url) { var request = new XMLHttpRequest(); request.open('GET', url, true); request.responseType = 'arraybuffer'; request.onload = function() { console.log('url loaded'); context.decodeAudioData(request.response, function(decodedData) { console.log('decoded data'); var I = nodes.length; var N = nodes[I] = context.createScriptProcessor(BUFFER_SIZE, 2, 2); masterNode.connect(nodes[I]); eqs[I] = new Equalizer(nodes[I], context); N.buffer = decodedData; N.pvL = new PhaseVocoder(BUFFER_SIZE/div, 44100); N.pvL.init(); N.pvR = new PhaseVocoder(BUFFER_SIZE/div, 44100); N.pvR.init(); N.outBufferL = []; N.outBufferR = []; N.position = 0; N.pitch = 1; N.onaudioprocess = function (e) { var il = this.buffer.getChannelData(0); var ir = this.buffer.getChannelData(1); var ol = e.outputBuffer.getChannelData(0); var or = e.outputBuffer.getChannelData(1); // Fill output buffers (left & right) until the system has // enough processed samples to reproduce. do { // var bufL = new Float64Array(BUFFER_SIZE/div); // var bufR = new Float64Array(BUFFER_SIZE/div); var bufL = il.subarray(this.position, this.position+BUFFER_SIZE/div); var bufR = ir.subarray(this.position, this.position+BUFFER_SIZE/div); this.position += this.pvL.get_analysis_hop(); // Process left input channel this.outBufferL = this.outBufferL.concat(this.pvL.process(bufL)); // Process right input channel this.outBufferR = this.outBufferR.concat(this.pvR.process(bufR)); } while(this.outBufferL.length < BUFFER_SIZE); ol.set(this.outBufferL.splice(0, BUFFER_SIZE)); or.set(this.outBufferR.splice(0, BUFFER_SIZE)); }; }); } console.log('reading url'); request.send(); } // loadSample('../soundtouchjs/4.mp3'); // loadSample('../soundtouchjs/2.mp3'); // loadSample('../soundtouchjs/3.mp3'); function set_pitch(newPitch) { pitch = phasevocoderL1.get_synthesis_hop()*newPitch / phasevocoderL1.get_analysis_hop(); phasevocoderL1.set_overlap_factor(pitch); phasevocoderR1.set_overlap_factor(pitch); } function set_alpha(ids, newFactor) { for (var i=0; i<ids.length; i++) { nodes[i].pvL.set_alpha(newFactor); nodes[i].pvR.set_alpha(newFactor); } } function set_position(ids, newPosition) { for (var i=0; i<ids.length; i++) { nodes[i].position = newPosition; } } function play(ids) { for (var i=0; i<ids.length; i++) eqs[ids[i]].connect(); } function pause(ids) { for (var i=0; i<ids.length; i++) eqs[ids[i]].disconnect(); } function process_samples(input_start, buffer_size, input_channels, output_start, output_channels, rate) { var beat, destination_offset, sample_l, sample_r, source_offset, source_offset_float; while (--buffer_size >= 0) { source_offset_float = input_start + (buffer_size * rate); source_offset = Math.round(source_offset_float); destination_offset = output_start + buffer_size; sample_l = input_channels[0][source_offset]; sample_r = input_channels[1][source_offset]; output_channels[0][destination_offset] = sample_l; output_channels[1][destination_offset] = sample_r; } return null; }; function resample(buffer, fromRate /* or speed */, fromFrequency /* or toRate */, toRate, toFrequency) { var argc = arguments.length, speed = (argc === 2 ? fromRate : (argc === 3 ? fromRate / fromFrequency : toRate / fromRate * toFrequency / fromFrequency)), l = buffer.length, length = Math.ceil(l / speed), newBuffer = new Array(length), i, n; for (i=0, n=0; i<l; i += speed) { newBuffer[n++] = linear_interpolation(buffer, i); } return newBuffer; }; function nearest_interpolation(arr, pos) { return pos >= arr.length - 0.5 ? arr[0] : arr[Math.round(pos)]; }; function linear_interpolation(arr, pos) { var first = Math.floor(pos), second = first + 1, frac = pos - first; second = second < arr.length ? second : 0; return arr[first] * (1 - frac) + arr[second] * frac; }; function linearInterpolation (a, b, t) { return a + (b - a) * t; }; function hannWindow (length) { var window = new Float32Array(length); for (var i = 0; i < length; i++) { window[i] = 0.5 * (1 - Math.cos(2 * Math.PI * i / (length - 1))); } return window; }; grainSize = 512; overlapRatio = 0.70; pitchShifterProcessor = context.createScriptProcessor(grainSize, 1, 1); pitchShifterProcessor.buffer = new Float32Array(grainSize * 2); pitchShifterProcessor.grainWindow = hannWindow(grainSize); pitchRatio = 1; pitchShifterProcessor.onaudioprocess = function (event) { var inputData = event.inputBuffer.getChannelData(0); var outputData = event.outputBuffer.getChannelData(0); for (i = 0; i < inputData.length; i++) { // Apply the window to the input buffer inputData[i] *= this.grainWindow[i]; // Shift half of the buffer this.buffer[i] = this.buffer[i + grainSize]; // Empty the buffer tail this.buffer[i + grainSize] = 0.0; } // Calculate the pitch shifted grain re-sampling and looping the input var grainData = new Float32Array(grainSize * 2); for (var i = 0, j = 0.0; i < grainSize; i++, j += pitchRatio) { var index = Math.floor(j) % grainSize; var a = inputData[index]; var b = inputData[(index + 1) % grainSize]; grainData[i] += linearInterpolation(a, b, j % 1.0) * this.grainWindow[i]; } // Copy the grain multiple times overlapping it for (i = 0; i < grainSize; i += Math.round(grainSize * (1 - overlapRatio))) { for (j = 0; j <= grainSize; j++) { this.buffer[i + j] += grainData[j]; } } // Output the first half of the buffer for (i = 0; i < grainSize; i++) { outputData[i] = this.buffer[i]; } };
echo66/PhaseVocoderJS
test.js
JavaScript
agpl-3.0
6,660
// document.getElementsByTagName('body')[0].style.visibility = 'hidden'; // //console.log("first" + "/\\b" + "Hello" + "\\b/gi"); var fn2 = function() { //console.log('running'); document.getElementsByTagName('body')[0].style.visibility = 'hidden'; //console.log('hidden'); }; fn2();
ContentHolmes/Content-Holmes
src/js/URLInviz.js
JavaScript
agpl-3.0
297
describe('Introduction', function () { beforeEach(function () { cy.login(); cy.createContact('John', 'Doe', 'Man'); cy.createContact('Jane', 'Doe', 'Woman'); cy.createContact('Joe', 'Shmoe', 'Man'); }); it('lets you fill first met without an introducer', function () { cy.url().should('include', '/people/h:'); cy.get('.introductions a[href$="introductions/edit"]').click(); cy.url().should('include', '/introductions/edit'); cy.get('textarea[name=first_met_additional_info]').type('Lorem ipsum'); cy.get('button.btn-primary[type=submit]').click(); cy.url().should('include', '/people/h:'); cy.get('.alert-success'); cy.get('.introductions').contains('Lorem ipsum'); }); it('lets you save first met', function () { cy.url().should('include', '/people/h:'); cy.get('.introductions a[href$="introductions/edit"]').click(); cy.url().should('include', '/introductions/edit'); cy.get('textarea[name=first_met_additional_info]').type('Lorem ipsum'); cy.get('#metThrough > .v-select input').click(); cy.get('#metThrough ul[role="listbox"]').contains('John Doe'); cy.get('#metThrough ul[role="listbox"]').contains('Jane Doe'); cy.get('#metThrough ul[role="listbox"]').contains('Joe Shmoe'); cy.get('#metThrough ul[role="listbox"]').contains('John Doe').click(); cy.get('button.btn-primary[type=submit]').click(); cy.url().should('include', '/people/h:'); cy.get('.alert-success'); cy.get('.introductions').contains('Lorem ipsum'); cy.get('.introductions').contains('John Doe'); }); it('lets you search first met', function () { cy.url().should('include', '/people/h:'); cy.get('.introductions a[href$="introductions/edit"]').click(); cy.url().should('include', '/introductions/edit'); cy.get('textarea[name=first_met_additional_info]').type('Lorem ipsum'); cy.get('#metThrough input[type=search]').type('John'); cy.get('#metThrough ul[role="listbox"]').contains('John Doe'); cy.get('#metThrough ul[role="listbox"]').should('not.contain', 'Joe Shmoe'); cy.get('#metThrough ul[role="listbox"]').should('not.contain', 'Jane Doe'); cy.get('#metThrough ul[role="listbox"]').contains('John Doe').click(); cy.get('button.btn-primary[type=submit]').click(); cy.url().should('include', '/people/h:'); cy.get('.introductions').contains('Lorem ipsum'); cy.get('.introductions').contains('John Doe'); }); });
monicahq/monica
tests/cypress/integration/contacts/introductions_spec.js
JavaScript
agpl-3.0
2,477
var C = crel2; var ventana = API.widget.create(); var textarea; C(ventana, C('button', ['onclick', local_set_test], 'LOCAL SET test'), C('button', ['onclick', local_get_test], 'LOCAL GET test'), C('button', ['onclick', local_delete_test], 'LOCAL DELETE test'), C('button', ['onclick', local_delete_all_test], 'LOCAL DELETE ALL test'), C('button', ['onclick', local_exists], 'LOCAL EXISTS test'), C('br'), C('button', ['onclick', remote_set_test], 'REMOTE SET test'), C('button', ['onclick', remote_get_test], 'REMOTE GET test'), C('button', ['onclick', remote_delete_test], 'REMOTE DELETE test'), C('button', ['onclick', remote_delete_all_test], 'REMOTE DELETE ALL test'), C('button', ['onclick', remote_exists], 'REMOTE EXISTS test'), C('br'), C('button', ['onclick', global_set_test], 'GLOBAL SET test'), C('button', ['onclick', global_get_test], 'GLOBAL GET test'), C('button', ['onclick', global_delete_test], 'GLOBAL DELETE test'), C('button', ['onclick', global_exists], 'GLOBAL EXISTS test'), C('br'), textarea = C('textarea') ); function log(what){ textarea.value += what+"\n"; } //log(API.url(widgetID,'main.js')); // Variables are saved as text ///////////////////////////// // LOCAL ///////////////////////////// function local_set_test(){ var text_rnd = Math.random(); log('LOCAL SET Test Saving the text: '+text_rnd); API.storage.localStorage.set('test', text_rnd, function(entrada){ if(entrada){ log('LOCAL SET Test Text Saved.'); } else{ log('LOCAL SET Test Text NOT saved.'); } }); } function local_get_test(){ log('LOCAL GET Test'); API.storage.localStorage.get('test', function(entrada){ if(entrada){ log('LOCAL GET Test Got the text: '+entrada); } else{ log('LOCAL GET Test There is not a saved variable with that name.'); } }); } function local_delete_test(){ log('LOCAL DELETE Test'); API.storage.localStorage.delete('test', function(entrada){ if(entrada){ log('LOCAL DELETE Test deleted OK.'); } else{ log('LOCAL DELETE Test deleted FAIL.'); } }); API.storage.localStorage.get('test', function(entrada){ if(entrada){ log('LOCAL DELETE Test confirmed FAIL.'); } else{ log('LOCAL DELETE Test confirmed OK.'); } }); } function local_delete_all_test(){ log('LOCAL DELETE ALL Test'); API.storage.localStorage.deleteAll(function(entrada){ if(entrada){ log('LOCAL DELETE ALL Test deleted OK.'); } else{ log('LOCAL DELETE ALL Test deleted FAIL.'); } }); API.storage.localStorage.get('test', function(entrada){ if(entrada){ log('LOCAL DELETE ALL Test confirmed FAIL.'); } else{ log('LOCAL DELETE ALL Test confirmed OK.'); } }); } function local_exists(){ log('LOCAL EXISTS Test'); API.storage.localStorage.exists('test', function(entrada){ if(entrada){ log('LOCAL EXISTS Test variable exists = YES.'); } else{ log('LOCAL EXISTS Test variable exists = NO.'); } }); } ///////////////////////////// // REMOTE ///////////////////////////// function remote_set_test(){ var text_rnd = Math.random(); log('REMOTE SET Test Saving the text: '+text_rnd); API.storage.remoteStorage.set('test', text_rnd, function(entrada){ if(entrada){ log('REMOTE SET Test Text Saved.'); } else{ log('REMOTE SET Test Text NOT saved.'); } }); } function remote_get_test(){ log('REMOTE GET Test'); API.storage.remoteStorage.get('test', function(entrada){ if(entrada){ log('REMOTE GET Test Got the text: '+entrada); } else{ log('REMOTE GET Test There is not a saved variable with that name.'); } }); } function remote_delete_test(){ log('REMOTE DELETE Test'); API.storage.remoteStorage.delete('test', function(entrada){ if(entrada){ log('REMOTE DELETE Test deleted OK.'); } else{ log('REMOTE DELETE Test deleted FAIL.'); } }); API.storage.remoteStorage.get('test', function(entrada){ if(entrada){ log('REMOTE DELETE Test confirmed FAIL.'); } else{ log('REMOTE DELETE Test confirmed OK.'); } }); } function remote_delete_all_test(){ log('REMOTE DELETE ALL Test'); API.storage.remoteStorage.deleteAll(function(entrada){ if(entrada){ log('REMOTE DELETE ALL Test deleted OK.'); } else{ log('REMOTE DELETE ALL Test deleted FAIL.'); } }); API.storage.remoteStorage.get('test', function(entrada){ if(entrada){ log('REMOTE DELETE ALL Test confirmed FAIL.'); } else{ log('REMOTE DELETE ALL Test confirmed OK.'); } }); } function remote_exists(){ log('REMOTE EXISTS Test'); API.storage.remoteStorage.exists('test', function(entrada){ if(entrada){ log('REMOTE EXISTS Test variable exists = YES.'); } else{ log('REMOTE EXISTS Test variable exists = NO.'); } }); } ///////////////////////////// // GLOBAL ///////////////////////////// function global_set_test(){ var text_rnd = Math.random(); log('GLOBAL SET Test Saving the text: '+text_rnd); API.storage.sharedStorage.set('test', text_rnd, function(entrada){ if(entrada){ log('GLOBAL SET Test Text Saved.'); } else{ log('GLOBAL SET Test Text NOT saved.'); } }); } function global_get_test(){ log('GLOBAL GET Test'); API.storage.sharedStorage.get('test', function(entrada){ if(entrada){ log('GLOBAL GET Test Got the text: '+entrada); } else{ log('GLOBAL GET Test There is not a saved variable with that name.'); } }); } function global_delete_test(){ log('GLOBAL DELETE Test'); API.storage.sharedStorage.delete('test', function(entrada){ if(entrada){ log('GLOBAL DELETE Test deleted OK.'); } else{ log('GLOBAL DELETE Test deleted FAIL.'); } }); API.storage.sharedStorage.get('test', function(entrada){ if(entrada){ log('GLOBAL DELETE Test confirmed FAIL.'); } else{ log('GLOBAL DELETE Test confirmed OK.'); } }); } function global_exists(){ log('GLOBAL EXISTS Test'); API.storage.sharedStorage.exists('test', function(entrada){ if(entrada){ log('GLOBAL EXISTS Test variable exists = YES.'); } else{ log('GLOBAL EXISTS Test variable exists = NO.'); } }); }
forestrf/CoolStartNet
widgets/test/main.js
JavaScript
agpl-3.0
6,066
var ERR = require('async-stacktrace'); var assert = require('assert'); var fs = require('fs'); var courseDB = require('../lib/course-db'); var logger = require('./dummyLogger'); describe('courseDB.loadFullCourse() on exampleCourse', function() { this.timeout(20000); var courseDir = 'exampleCourse'; var course; before('load course from disk', function(callback) { courseDB.loadFullCourse(courseDir, logger, function(err, c) { if (ERR(err, callback)) return; course = c; callback(null); }); }); describe('the in-memory "course" object', function() { it('should contain "courseInfo"', function() { assert.ok(course.courseInfo); }); it('should contain "questionDB"', function() { assert.ok(course.questionDB); }); it('should contain "courseInstanceDB"', function() { assert.ok(course.courseInstanceDB); }); }); }); describe('courseDB.loadFullCourse() on brokenCourse', function() { var courseDir = 'tests/testLoadCourse/brokenCourse'; var assessmentFilename = `${courseDir}/courseInstances/Fa18/assessments/quiz1/infoAssessment.json`; var questionFilename = `${courseDir}/questions/basicV3/info.json`; beforeEach('write correct infoAssessment and question', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'Quiz', 'allowAccess': [ { 'startDate': '2018-01-01T00:00:00', 'endDate': '2019-01-01T00:00:00'}, ], }; var questionJson = { 'uuid': 'ba0b8e5b-6348-43f8-b483-083e0bea6332', 'title': 'Basic V3 question', 'topic': 'basic', 'type': 'v3', }; fs.writeFile(assessmentFilename, JSON.stringify(assessmentJson), function(err) { if (ERR(err, callback)) return; fs.writeFile(questionFilename, JSON.stringify(questionJson), function(err) { if (ERR(err, callback)) return; callback(null); }); }); }); after('removing test files', function(callback) { fs.unlink(assessmentFilename, function(err) { if (ERR(err, callback)) return; fs.unlink(questionFilename, function(err) { if (ERR(err, callback)) return; callback(null); }); }); }); describe('trying to load broken course pieces', function() { it('assessment: invalid set should fail', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'NotARealSet', 'allowAccess': [ { 'startDate': '2018-01-01T00:00:00', 'endDate': '2019-01-01T00:00:00'}, ], }; var filename = 'courseInstances/Fa18/assessments/quiz1/infoAssessment.json'; loadHelper(courseDir, filename, assessmentJson, /invalid "set":/, callback); }); it('assessment: access rule: invalid startDate should fail', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'Quiz', 'allowAccess': [ { 'startDate': 'NotADate', 'endDate': '2019-01-01T00:00:00'}, ], }; var filename = 'courseInstances/Fa18/assessments/quiz1/infoAssessment.json'; loadHelper(courseDir, filename, assessmentJson, /invalid allowAccess startDate/, callback); }); it('assessment: access rule: invalid endDate should fail', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'Quiz', 'allowAccess': [ { 'startDate': '2019-01-01T22:22:22', 'endDate': 'AlsoReallyNotADate'}, ], }; var filename = 'courseInstances/Fa18/assessments/quiz1/infoAssessment.json'; loadHelper(courseDir, filename, assessmentJson, /invalid allowAccess endDate/, callback); }); it('assessment: access rule: startDate after endDate should fail', function(callback) { var assessmentJson = { 'uuid': 'bee70f4d-4220-47f1-b4ed-59c88ce08657', 'type': 'Exam', 'number': '1', 'title': 'Test quiz 1', 'set': 'Quiz', 'allowAccess': [ { 'startDate': '2020-01-01T11:11:11', 'endDate': '2019-01-01T00:00:00'}, ], }; var filename = 'courseInstances/Fa18/assessments/quiz1/infoAssessment.json'; loadHelper(courseDir, filename, assessmentJson, /must not be after/, callback); }); }); }); var loadHelper = function(courseDir, filename, contents, expectedErrorRE, callback) { fs.writeFile(courseDir + '/' + filename, JSON.stringify(contents), function(err) { if (err) { return callback(err); } courseDB.loadFullCourse(courseDir, logger, function(err, _c) { if (err) { if (expectedErrorRE.test(err)) { callback(null); } else { callback(new Error('unexpected error ' + err)); } } else { callback(new Error('returned successfully, which should not happen')); } }); }); };
rbessick5/PrairieLearn
tests/testLoadCourse.js
JavaScript
agpl-3.0
6,134
(function() { "use strict"; angular.module("blocktrail.setup") .factory("newAccountFormService", function($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService) { return new NewAccountFormService($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService); } ); function NewAccountFormService($log, $http, $q, _, cryptoJS, device, CONFIG, launchService, settingsService, trackingService) { var self = this; self._$log = $log; self._$http = $http; self._$q = $q; self._lodash = _; self._cryptoJS = cryptoJS; self._device = device || {}; self._CONFIG = CONFIG; self._launchService = launchService; self._settingsService = settingsService; self._trackingService = trackingService; } /** * Register * @param data * @return { promise } */ NewAccountFormService.prototype.register = function(data) { var self = this; var postData = { username: null, email: data.email, password: self._cryptoJS.SHA512(data.password).toString(), password_score: data.passwordCheck && data.passwordCheck.score || 0, platform: ionic.Platform.isIOS() ? "iOS" : "Android", version: self._CONFIG.VERSION || self._CONFIG.VERSION_REV, device_uuid: self._device.uuid, device_name: (self._device.platform || self._device.model) ? ([self._device.platform, self._device.model].clean().join(" / ")) : "Unknown Device", super_secret: null, powtcha: null, browser_fingerprint: null, skip_two_factor: true, // will make the resulting API key not require 2FA in the future captcha : window.captchaToken }; var url = self._CONFIG.API_URL + "/v1/" + data.networkType + "/mywallet/register"; self._$log.debug("M:SETUP:newAccountFormService: register", postData.email, postData.platform, postData.device_name); return self._$http.post(url, postData) .then(self._trackEvent.bind(self)) .then(self._setAccountInfo.bind(self)) .catch(self._errorHandler.bind(self)); }; /** * @param response * @return response * @private */ NewAccountFormService.prototype._trackEvent = function(response) { var self = this; self._trackingService.trackEvent(self._trackingService.EVENTS.SIGN_UP); return response; }; /** * Set the account info * @param response * @return { promise } * @private */ NewAccountFormService.prototype._setAccountInfo = function(response) { var self = this; var accountInfo = { username: response.data.username, email: response.data.email, apiKey: response.data.api_key, apiSecret: response.data.api_secret }; self._$log.debug("M:SETUP:newAccountFormService:_setAccountInfo", accountInfo); return self._launchService.setAccountInfo(accountInfo) .then(function() { return self._launchService.getAccountInfo(); }); }; /** * Error handler * @param error * @return { promise<string> } * @private */ NewAccountFormService.prototype._errorHandler = function(error) { var self = this; var response; var ifr = document.querySelector('#ifr'); ifr.contentWindow.postMessage({a: 1}, '*'); // window.fetchCaptchaToken(); self._$log.debug("M:SETUP:newAccountFormService:_errorHandler", error); if (error && error.data && error.data.msg.toLowerCase().match(/username exists/)) { response = "MSG_USERNAME_TAKEN"; } else if (error && error.data && error.data.msg.toLowerCase().match(/already in use/)) { response = "MSG_EMAIL_TAKEN"; } else if (!!error) { response = "" + (error.message || error.msg || error.data && error.data.msg || error); } return this._$q.reject(response); }; })();
blocktrail/blocktrail-wallet
src/js/modules/setup/services/new-account-form/new-account-form.service.js
JavaScript
agpl-3.0
4,234
import { setAttrs } from '../actions/object' /*MATERIALDB_GROUP*/ export const addGroup = () => ({ type: "MATERIALDB_GROUP_ADD" }); export const deleteGroup = (groupId) => ({ type: "MATERIALDB_GROUP_DELETE", payload: groupId }); export const setGroupAttrs = (groupId, attrs) => ({ type: "MATERIALDB_GROUP_SET_ATTRS", payload: { groupId, attrs } }); export const toggleGroupView = (groupId) => ({ type: "MATERIALDB_GROUP_TOGGLE_VIEW", payload: groupId }); export const toggleGroupEdit = (groupId) => ({ type: "MATERIALDB_GROUP_TOGGLE_EDIT", payload: groupId }); /*MATERIALDB_PRESET (operations)*/ export const addPreset = (groupId, attrs = {}) => ({ type: "MATERIALDB_PRESET_ADD", payload: { groupId, attrs } }) export const deletePreset = (presetId) => ({ type: "MATERIALDB_PRESET_DELETE", payload: presetId }); export const setPresetAttrs = (presetId, attrs) => ({ type: "MATERIALDB_PRESET_SET_ATTRS", payload: { presetId, attrs } }); export const togglePresetEdit = (presetId) => ({ type: "MATERIALDB_PRESET_TOGGLE_EDIT", payload: presetId }); /*MATERIALDB PICKER*/ export const applyPreset = (presetId) => ({ type: "MATERIALDB_PRESET_APPLY", payload: presetId }); export const newPreset = (preset, grouping, name) => ({ type: "MATERIALDB_PRESET_NEW", payload: { preset, grouping, name } }) /*MATERIALDB*/ export const uploadMaterialDatabase = (file, content) => ({ type: "MATERIALDB_UPLOAD", payload: { file, database: JSON.parse(content) } }); export const importMaterialDatabase = (file, content) => ({ type: "MATERIALDB_IMPORT", payload: { file, database: content } }); export const downloadMaterialDatabase = (database) => ({ type: "MATERIALDB_DOWNLOAD", payload: { database } });
LaserWeb/LaserWeb4
src/actions/material-database.js
JavaScript
agpl-3.0
1,695
/* Copyright 2018 Onestein * License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). */ odoo.define('website_lazy_load_image.lazy_image_loader', function (require) { 'use strict'; var Class = require('web.Class'); var mixins = require('web.mixins'); /** * Handles lazy loading of images. */ var LazyImageLoader = Class.extend(mixins.EventDispatcherMixin, { /** * The instance of the jQuery lazy loading plugin. * * @type {jQuery.lazy} */ plugin: null, /** * Use this to hook on the onFinishedAll of the lazy loading plugin * of a specific instance of LazyImageLoader. * * @type {jQuery.Deferred} */ all_finished: null, /** * @class * @param {String} selector The selector for the elements to lazy load. */ init: function (selector) { mixins.EventDispatcherMixin.init.call(this); this.all_finished = $.Deferred(); this.plugin = $(selector).data('loaded', false).lazy( this._getPluginConfiguration() ); }, /** * Get the settings for the initialization of the lazy loading plugin. * * @private * @returns {Object} Lazy loading plugin settings */ _getPluginConfiguration: function () { return { afterLoad: this._afterLoad.bind(this), beforeLoad: this._beforeLoad.bind(this), onError: this._onError.bind(this), onFinishedAll: this._onFinishedAll.bind(this), chainable: false, }; }, /** * Triggered by the beforeLoad event of the lazy loading plugin. * * @param {DOMElement} el * @private */ _beforeLoad: function (el) { this.trigger('beforeLoad', el); }, /** * Triggered by the afterLoad event of the lazy loading plugin. * * @param {DOMElement} el * @private */ _afterLoad: function (el) { this.trigger('afterLoad', el); }, /** * Triggered by the onError event of the lazy loading plugin. * * @param {DOMElement} el * @private */ _onError: function (el) { this.trigger('onError', el); }, /** * Triggered by the onFinished event of the lazy loading plugin. * * @private */ _onFinishedAll: function () { this.all_finished.resolve(); this.trigger('onFinishedAll'); }, }); require('web.dom_ready'); var lazy_image_loader = new LazyImageLoader( '#wrapwrap > main img:not(.lazyload-disable), ' + '#wrapwrap > footer img:not(.lazyload-disable)' ); return { LazyImageLoader: LazyImageLoader, lazy_image_loader: lazy_image_loader, }; });
Vauxoo/website
website_lazy_load_image/static/src/js/frontend.js
JavaScript
agpl-3.0
3,060
/* @flow */ import React, { Component, PropTypes } from 'react'; import ReactNative from 'react-native'; import shallowEqual from 'shallowequal'; import Colors from '../../../Colors'; import AppText from '../AppText'; import ListItem from '../ListItem'; import Icon from '../Icon'; import Time from '../Time'; import ActionSheet from '../ActionSheet'; import ActionSheetItem from '../ActionSheetItem'; import Share from '../../../modules/Share'; import { convertRouteToURL } from '../../../../lib/Route'; import { config } from '../../../../core-client'; const { StyleSheet, TouchableOpacity, View, } = ReactNative; const styles = StyleSheet.create({ item: { flex: 1, justifyContent: 'center', paddingHorizontal: 16, }, title: { color: Colors.darkGrey, fontWeight: 'bold', }, subtitle: { flexDirection: 'row', alignItems: 'center', }, label: { color: Colors.grey, fontSize: 10, lineHeight: 15, }, dot: { fontSize: 2, lineHeight: 3, marginHorizontal: 4, }, badge: { backgroundColor: Colors.accent, height: 6, width: 6, marginRight: 8, borderRadius: 3, elevation: 1, }, expand: { margin: 20, color: Colors.fadedBlack, }, }); type Props = { room: { id: string; name: string; updateTime?: number; }; unread?: boolean; onSelect: Function; } type State = { actionSheetVisible: boolean; } export default class RoomItem extends Component<void, Props, State> { static propTypes = { room: PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string, }), unread: PropTypes.bool, onSelect: PropTypes.func, }; state: State = { actionSheetVisible: false, }; shouldComponentUpdate(nextProps: Props, nextState: State): boolean { return !shallowEqual(this.props, nextProps) || !shallowEqual(this.state, nextState); } _getRoomLink: Function = () => { const { room } = this.props; return config.server.protocol + '//' + config.server.host + convertRouteToURL({ name: 'room', props: { room: room.id, }, }); }; _getShareText: Function = () => { const { room } = this.props; return `Hey! Join me in the ${room.name} group on ${config.app_name}.\n${this._getRoomLink()}`; }; _handleInvite: Function = () => { Share.shareItem('Share group', this._getShareText()); }; _handleShowMenu: Function = () => { this.setState({ actionSheetVisible: true, }); }; _handleRequestClose: Function = () => { this.setState({ actionSheetVisible: false, }); }; _handlePress: Function = () => { if (this.props.onSelect) { this.props.onSelect(this.props.room); } }; render() { const { room, unread, } = this.props; const followers = room.counts && room.counts.follower ? room.counts.follower : 0; let followersLabel; switch (followers) { case 1: followersLabel = '1 person'; break; default: followersLabel = `${followers > 1000 ? Math.round(followers / 100) / 10 + 'k' : followers} people`; } return ( <ListItem {...this.props} onPress={this._handlePress}> <View style={styles.item}> <AppText numberOfLines={1} style={styles.title}>{room.name || 'Loading…'}</AppText> {room.updateTime ? <View style={styles.subtitle}> {unread ? <View style={styles.badge} /> : null } <Time style={styles.label} time={room.updateTime} type='long' /> <AppText style={styles.dot}>●</AppText> <AppText style={styles.label}>{followersLabel}</AppText> </View> : null } </View> <TouchableOpacity onPress={this._handleShowMenu}> <Icon name='expand-more' style={styles.expand} size={20} /> </TouchableOpacity> <ActionSheet visible={this.state.actionSheetVisible} onRequestClose={this._handleRequestClose}> <ActionSheetItem onPress={this._handleInvite}> Invite friends to group </ActionSheetItem> </ActionSheet> </ListItem> ); } }
Anup-Allamsetty/pure
src/ui/components/views/Homescreen/RoomItem.js
JavaScript
agpl-3.0
3,984
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, click } from '@ember/test-helpers'; import { hbs } from 'ember-cli-htmlbars'; import styles from 'irene/components/tri-state-checkbox/index.scss'; module('Integration | Component | tri-state-checkbox', function (hooks) { setupRenderingTest(hooks); test('it does not render component if label is not passed', async function (assert) { await render(hbs`<TriStateCheckbox />`); assert.dom('[data-test-check]').doesNotExist(); const container = this.element.querySelector('[data-test-container]'); assert.equal(container.clientHeight, 0); }); test('it toggles value on checkbox click', async function (assert) { this.set('label', 'Test'); this.set('value', true); this.set('onToggle', () => {}); this.set('onOverrideReset', () => {}); this.set('isToggleRunning', false); this.set('isOverridden', false); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); const checkbox = this.element.querySelector('[data-test-input]'); assert.equal(checkbox.checked, true); await click(checkbox); assert.equal(checkbox.checked, false); await click(checkbox); assert.equal(checkbox.checked, true); }); test('it toggles value on label click', async function (assert) { this.set('label', 'Test'); this.set('value', true); this.set('onToggle', () => {}); this.set('onOverrideReset', () => {}); this.set('isToggleRunning', false); this.set('isOverridden', false); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); const checkbox = this.element.querySelector('[data-test-input]'); assert.equal(checkbox.checked, true); const label = this.element.querySelector('[data-test-label]'); await click(label); assert.equal(checkbox.checked, false); await click(label); assert.equal(checkbox.checked, true); }); test('it should render label title if passed', async function (assert) { this.set('label', 'Test label'); this.set('value', true); this.set('onToggle', () => {}); this.set('onOverrideReset', () => {}); this.set('isToggleRunning', false); this.set('isOverridden', false); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); let label = this.element.querySelector('[data-test-label]'); assert.equal(label.title, ''); this.set('title', 'Test title'); await render( hbs`<TriStateCheckbox @label={{this.label}} @title={{this.title}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); label = this.element.querySelector('[data-test-label]'); assert.equal(label.title, 'Test title'); }); test('it toggles value on label click', async function (assert) { this.set('label', 'Test'); this.set('value', true); this.set('onToggle', () => {}); this.set('onOverrideReset', () => {}); this.set('isToggleRunning', false); this.set('isOverridden', false); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); const checkbox = this.element.querySelector('[data-test-input]'); assert.equal(checkbox.checked, true); const label = this.element.querySelector('[data-test-label]'); await click(label); assert.equal(checkbox.checked, false); await click(label); assert.equal(checkbox.checked, true); }); test('it should render progress spinner based on isToggleRunning value', async function (assert) { this.set('label', 'Test'); this.set('value', true); this.set('onToggle', () => {}); this.set('onOverrideReset', () => {}); this.set('isOverridden', false); this.set('isToggleRunning', true); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); assert.dom('[data-test-progress-spinner]').exists(); this.set('isToggleRunning', false); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); assert.dom('[data-test-progress-spinner]').doesNotExist(); }); test('it should render switch style based on isOverridden value', async function (assert) { this.set('label', 'Test'); this.set('value', true); this.set('onToggle', () => {}); this.set('onOverrideReset', () => {}); this.set('isToggleRunning', false); this.set('isOverridden', false); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); assert.dom('[data-test-check]').hasClass(styles['inherited']); assert.dom('[data-test-check]').doesNotHaveClass(styles['overridden']); this.set('isOverridden', true); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); assert.dom('[data-test-check]').doesNotHaveClass(styles['inherited']); assert.dom('[data-test-check]').hasClass(styles['overridden']); }); test('it should render reset button based on isOverridden value', async function (assert) { this.set('label', 'Test'); this.set('value', true); this.set('onToggle', () => {}); this.set('onOverrideReset', () => {}); this.set('isToggleRunning', false); this.set('isOverridden', true); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); assert.dom('[data-test-reset]').exists(); this.set('isOverridden', false); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); assert.dom('[data-test-reset]').doesNotExist(); }); test('it should execute onOverrideReset function on reset button click', async function (assert) { this.set('label', 'Test'); this.set('value', true); this.set('onToggle', () => {}); this.set('isToggleRunning', false); this.set('isOverridden', true); let flag = 1; this.set('onOverrideReset', function reset() { flag = 0; }); await render( hbs`<TriStateCheckbox @label={{this.label}} @value={{this.value}} @onToggle={{this.onToggle}} @onOverrideReset={{this.onOverrideReset}} @isToggleRunning={{this.isToggleRunning}} @isOverridden={{this.isOverridden}} />` ); assert.equal(flag, 1); const reset = this.element.querySelector('[data-test-reset]'); await click(reset); assert.equal(flag, 0); }); });
appknox/irene
tests/integration/components/tri-state-checkbox-test.js
JavaScript
agpl-3.0
8,101
/* * Include everything. */ var net = require('net'); var MudClient = require("./mudclient.js"); var MudRooms = require("./mudrooms.js"); /* * I wanted to make this a field on a MudServer class and node decided it wanted to monkeypatch my scope and break that idea. */ var clients = [] /* * As much as I feel this should be 'bigger' and 'better', functional is better than perfect ad I only have a few hours to work on this. * * I would love for this to be a graph loaded from a database. */ var rooms = { "Cafe": { "description": "You're in a cozy cafe warmed by an open fire.", "exits": {"outside": "Outside"}, }, "Outside": { "description": "You're standing outside a cafe. It's raining.", "exits": {"inside": "Cafe"}, } } /* * Send text to all clients. * * I envisioned this as being a method on a server class but nodejs didnt co-operate in the limited time I had. */ function sendToAllClients(data) { for(var i = 0; i < clients.length; i++) { clients[i].writeline(data); clients[i].prompt(); } }; /* * Send text to all fully logged in clients except the one. * * I envisioned this as being a method on a server class but nodejs didnt co-operate in the limited time I had. */ function sendToAllOtherClients(socket, data) { for(var i = 0; i< clients.length; i++) { if( clients[i].socket !== socket && clients[i].name !== '') { clients[i].writeline(data); clients[i].prompt(); } } }; /* * Send text and client sending it to the command system. * * I envisioned this as being a method on a dedicated command controller class but nodejs didnt co-operate in the limited time I had. * * Also: NodeJS/NPM hates the low memory of the RasberryPi I'm using to host node so while I would love to use the Command pattern here * NPM can not even read its own index without crashing so if a lib exists that can do this, I'm not aware of it. */ function sendToCommandSystem(client, data) { if(data == 'quit' || data == 'exit'){ client.socket.end('Goodbye!\r\n'); return; } if(data.indexOf('look') == 0){ client.writeline("Location: " + client.location ); client.writeline(rooms[client.location].description); client.writeline("Exits:"); var doors = Object.keys(rooms[client.location].exits); for(var i = 0; i < doors.length; i++) { client.writeline(" " + doors[i]); } var here = []; for(var i = 0; i < clients.length; i++) { if(client.location == clients[i].location && clients[i].socket !== client.socket){ here.push(clients[i].name); } } if(here.length > 0){ client.write("You see "); var useTheAndWord = false; while( here.length > 1 ) { useTheAndWord = true; var user = here.pop(); client.write(user + ", "); } if(useTheAndWord){ client.write("and " + here[0] + " here."); }else{ client.write(here[0] + " here."); } } client.prompt(); return; } if(data.indexOf('go') == 0){ if(data == 'go'){ client.writeline("Go where?"); client.prompt(); return; } var doors = Object.keys(rooms[client.location].exits); var words = data.split(' '); if(words.length == 2 && words[1] in rooms[client.location].exits){ client.writeline("You go " + words[1]); for(var i = 0; i < clients.length; i++) { if(client.location == clients[i].location && clients[i].socket !== client.socket){ clients[i].writeline(client.name + " went " + words[1] ); clients[i].prompt() } } var roomDestination = rooms[client.location].exits[words[1]]; for(var i = 0; i < clients.length; i++) { if(roomDestination == clients[i].location && clients[i].socket !== client.socket){ clients[i].writeline(client.name + " arrived from " + client.location ); clients[i].prompt() } } client.location = roomDestination; }else{ if( words.length > 1){ client.writeline("I do not see the exit " + words[1] + "."); } client.writeline("Valid Exits:"); for(var i = 0; i < doors.length; i++) { client.writeline(" "+ doors[i]); } } client.prompt(); return; } if(data.indexOf('say') == 0){ try{ data = data.slice(3).trim(); if(data.length == 0){ throw 'No data to send after removing prefix.'; } sendToAllOtherClients(client.socket, "\r\n" + client.name + " says: " + data) client.prompt(); return; } catch(e){ client.writeline("What?"); client.prompt(); return; } } client.write("The Command '" + data + "' is not supported yet.\r\n"); client.prompt(); }; /* * Disconnect the clients socket and remove them from the client list. * * I envisioned this as being a method on a server class but nodejs didnt co-operate in the limited time I had. */ function disconnectClient(client) { var index = clients.indexOf(client); if (index != -1) { clients.splice(index, 1); } }; /* * Accept the new connection. * I envisioned this as being a method on a server class but nodejs didnt co-operate in the limited hours I had. */ function newClientConnection(socket) { var client = new MudClient(socket) client.writeline('Welcome to A Simple Node-JS Based MUD!'); client.writeline('What is your name?'); client.socket.on('data', function(data) { // Broken windows clients will write newlines after every character. // This does not fix that client bug nor is it indended to. // This deals with telnet codes and newlines in the most expediant way given my limited time. data = data.toString().trim().replace(/(\r\n|\n|\r)/gm, '').replace(/ /g, '_').replace(/\W/g, '').replace(/_/g, ' ').trim(); if( data == ''){ client.prompt(); return; } if (client.name == ''){ client.name = data; client.location = 'Cafe'; sendToAllOtherClients(client.socket, "\r\n" + client.name + " has joined the server.") client.prompt(); }else{ sendToCommandSystem(client, data); } }); client.socket.on('end', function() { sendToAllOtherClients(client.socket, "\r\n" + client.name + " has left the server."); disconnectClient(client); }); clients.push(client); } module.exports = { /* * Run the server on the port specified when it was constructed * * Nothing else we have defined needs to be public. */ Create: function(port) { var server = net.createServer(newClientConnection); server.listen(port); return server; } };
duaneking/nodejs-derpmud
mudserver.js
JavaScript
agpl-3.0
6,399
/** * @class NetProfile.tickets.controller.TicketGrid * @extends Ext.app.Controller */ Ext.define('NetProfile.tickets.controller.TicketGrid', { extend: 'Ext.app.Controller', requires: [ 'Ext.menu.Menu' ], fromTemplateText: 'From Template', fromTemplateTipText: 'Add ticket from template', scheduleText: 'Schedule', init: function() { this.control({ 'grid_tickets_Ticket' : { beforerender: function(grid) { var tb; tb = grid.getDockedItems('toolbar[dock=top]'); if(!tb || !tb.length) return; tb = tb[0]; tb.add({ text: this.fromTemplateText, tooltip: { text: this.fromTemplateTipText, title: this.fromTemplateText }, iconCls: 'ico-add', handler: function() { grid.spawnWizard('tpl'); } }); } }, 'npwizard button#btn_sched' : { click: { scope: this, fn: function(btn, ev) { var wiz = btn.up('npwizard'), date_field = wiz.down('datetimefield[name=assigned_time]'), cfg = { dateField: date_field }, win, sched, values; values = wiz.getValues(); if(values['assigned_uid']) cfg.userId = parseInt(values['assigned_uid']); if(values['assigned_gid']) cfg.groupId = parseInt(values['assigned_gid']); if(values['ticketid']) cfg.ticketId = parseInt(values['ticketid']); if(values['tstid']) cfg.ticketStateId = parseInt(values['tstid']); if(values['tschedid']) cfg.schedulerId = parseInt(values['tschedid']); if(values['ttplid']) cfg.templateId = parseInt(values['ttplid']); win = Ext.create('Ext.ux.window.CenterWindow', { title: this.scheduleText, modal: true }); sched = Ext.create('NetProfile.tickets.view.Scheduler', cfg); win.add(sched); win.show(); return true; }} } }); } });
annndrey/npui-unik
netprofile_tickets/netprofile_tickets/static/webshell/controller/TicketGrid.js
JavaScript
agpl-3.0
1,850
/** * Copyright (C) 2017 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ "use strict"; (() => { // calulate how many weeks an issue has been created. // 0 - <=1 = week 0 // >1 - <=2 = week 1 // ... module.exports = { "$ceil": { "$divide": [ {"$subtract": [new Date().valueOf(), "$$CURRENT.created"]}, // one week in milliseconds 604800000 ] } }; })();
3drepo/3drepo.io
backend/src/v4/models/aggregate_fields/issue/age.js
JavaScript
agpl-3.0
1,033
//Create an event node var Event = (function($) { return function(properties) { this.properties = properties; this.blip = null; this.listing = null; this.className = properties.event_type_name.replace(/[^\w]/ig,"-").toLowerCase(); this.LatLng = [parseFloat(this.properties.latitude), parseFloat(this.properties.longitude)]; this.startTime = moment(this.properties.start_dt)._d; this.endTime = this.properties.end_dt ? moment(this.properties.end_dt)._d : null; this.visible = true; if (this.properties.capacity) { this.properties.capacity = parseInt(this.properties.capacity); } if (this.properties.attendee_count) { this.properties.attendee_count = parseInt(this.properties.attendee_count); } this.isFull = this.properties.attendee_count && this.properties.capacity > 0 && this.properties.attendee_count >= this.properties.capacity; this.render = function (distance, zipcode) { var that = this; var moreThan5RSVP = that.properties.attendee_count && parseInt(that.properties.attendee_count) > 5 ? true : false; if (!that.properties.attendee_count) { moreThan5RSVP = false; } var datetime = that.properties.id_obfuscated && that.properties.id_obfuscated == '4gw5k' ? 'Mar 20 (Sun) 11:00am' : moment(that.properties.start_dt).format("MMM DD (ddd) h:mma") var lat = that.properties.latitude var lon = that.properties.longitude var endtime = that.endTime ? moment(that.endTime).format("h:mma") : null; var shiftElems = null; if ( that.properties.shift_details ) { var shiftList = that.properties.shift_details.map( function(item) { var current = moment(); var start = moment(item.start); var end = moment(item.end); if (end.isBefore(current)) { return; } return $("<li />") .append($("<input type='checkbox' value='" + item.event_shift_id + "' id='" + item.event_shift_id + "' name='shift_id[]'>")) .append("<label for='" + item.event_shift_id + "'>" + start.format("h:mma") + " - " + end.format("h:mma")) } ); shiftElems = $("<div class='shift-details'/>") .append("<h5>Shifts</h5>") .append($("<ul/>").append(shiftList)) } // end of creating shift items var rendered = $("<div class='lato'/>") .addClass('event-item ' + that.className) .append($("<div />").addClass('event-item lato ' + that.className+'').attr("lat",lat).attr("lon",lon) //appended lat-lon attributes to this class for marker highlighting .append(that.properties.is_campaign_office ? $("<a class='office-image' href='" + (that.properties.opening_event ? that.properties.opening_event : that.properties.url) + "' />").append($("<img src='" + that.properties.image + "'>")) : "") .append($("<h5 class='time-info'/>").html((distance ? ("<span class='time-info-dist'>" + distance + "mi &nbsp;&nbsp;</span>") : "") + datetime + (endtime ? " - " + endtime : "" ))) .append($("<h3/>").html("<a target='_blank' href='" + (that.properties.opening_event ? that.properties.opening_event : that.properties.url) + "'>" + that.properties.name + "</a>")) .append(that.properties.is_official ? $("<h5 class='official-tag'/>").text("Official Event") : "") .append($("<span/>").addClass("label-icon")) .append($("<h5 class='event-type'/>").text(that.properties.event_type_name)) .append($("<p/>").html(that.properties.location)) .append(that.properties.phone && that.properties.phone != "-" ? $("<p/>").text("Phone: " + that.properties.phone) : "") .append(that.properties.notes ? that.properties.notes : "") //Append RSVP Form .append($("<div class='event-rsvp-activity' />") .append($("<form class='event-form lato'>") .append($("<h4/>").html("RSVP to <strong>" + that.properties.name + "</strong>")) .append($("<div class='event-error' />")) .append(shiftElems ? shiftElems : "") // .append($("<input type='text' name='name' placeholder='Name'/>")) .append($("<input type='hidden' name='has_shift'/>").val(shiftElems != null)) .append($("<input type='hidden' name='zipcode'/>").val(zipcode?zipcode:that.properties.venue_zip)) .append($("<input type='hidden' name='id_obfuscated'/>").val(that.properties.id_obfuscated)) .append($("<input type='text' name='phone' placeholder='Phone Number'/>")) .append($("<input type='text' name='email' placeholder='Email Address'/>")) .append($("<input type='submit' class='lato' value='Confirm RSVP' />")) ) ) .append( $("<div class='social-area' />") .addClass(moreThan5RSVP ? "more-than-5" : "") .append( $("<a class='rsvp-link'/>") .attr("href", that.properties.is_campaign_office ? (that.properties.opening_event ? that.properties.opening_event : that.properties.url) : "javascript: void(null) ") .attr("onclick", that.properties.is_campaign_office ? null: "$('.event-rsvp-activity').hide(); $(document).trigger('show-event-form', [this])") // .attr('target', 'blank') // .attr("href", that.properties.is_campaign_office ? (that.properties.opening_event ? that.properties.opening_event : that.properties.url) : that.properties.url) .attr("data-id", that.properties.id_obfuscated) .attr("data-url", (that.properties.opening_event ? that.properties.opening_event : that.properties.url)) .text(that.isFull ? "FULL" : that.properties.is_campaign_office ? (that.properties.opening_event ? "RSVP" : "Get Directions") : "RSVP") ) .append( $("<span class='rsvp-count'/>").text(that.properties.attendee_count + " SIGN UPS") ) ) .append($("<div class='rsvp-attending'/>").html('<a href="https://go.berniesanders.com/page/event/myevents" target="_blank">You are attending this event</a>')) ); return rendered.html(); }; } })(jQuery); //End of events // /**** // * Campaign Offices // */ // var CampaignOffices = (function($) { // return function(properties) { // this.properties = properties; // this.render = function (distance) { // var that = this; // var moreThan5RSVP = that.properties.attendee_count && parseInt(that.properties.attendee_count) > 5 ? true : false; // if (!that.properties.attendee_count) { moreThan5RSVP = false; } // var datetime = moment(that.properties.start_dt).format("MMM DD (ddd) h:mma") // var rendered = $("<div class='lato'/>") // .addClass('event-item ' + that.className) // .append($("<h5 class='time-info'/>").html((distance ? (distance + "mi &nbsp;&nbsp;") : "") + datetime)) // .append($("<h3/>").html("<a target='_blank' href='" + that.properties.url + "'>" + that.properties.name + "</a>")) // .append(that.properties.is_official ? $("<h5 class='official-tag'/>").text("Official Event") : "") // .append($("<span/>").addClass("label-icon")) // .append($("<h5 class='event-type'/>").text(that.properties.event_type_name)) // .append($("<p/>").text(that.properties.location)) // .append( // $("<div class='social-area'/>") // .addClass(moreThan5RSVP ? "more-than-5" : "") // .append( // $("<a class='rsvp-link' target='_blank'/>") // .attr("href", that.properties.url) // .text(that.isFull ? "FULL" : "RSVP") // ) // .append( // $("<span class='rsvp-count'/>").text(that.properties.attendee_count + " SIGN UPS") // ) // ); // return rendered.html(); // }; // }; // })(jQuery); /**** * MapManager proper */ var MapManager = (function($, d3, leaflet) { return ( function(eventData, campaignOffices, zipcodes, options) { var allFilters = window.eventTypeFilters.map(function(i) { return i.id; }); var popup = L.popup(); var options = options; var zipcodes = zipcodes.reduce(function(zips, item) { zips[item.zip] = item; return zips; }, {}); var current_filters = [], current_zipcode = "", current_distance = "", current_sort = ""; var originalEventList = eventData.map(function(d) { return new Event(d); }); var eventsList = originalEventList.slice(0); // var officeList = campaignOffices.map(function(d) { return new CampaignOffices(d); }); leaflet.mapbox.accessToken = "pk.eyJ1IjoiemFja2V4bGV5IiwiYSI6Ijc2OWFhOTE0ZDllODZiMTUyNDYyOGM5MTk1Y2NmZmEyIn0.mfl6MGaSrMmNv5o5D5WBKw"; var mapboxTiles = leaflet.tileLayer('http://{s}.tiles.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=' + leaflet.mapbox.accessToken, { attribution: '<a href="http://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>'}); var CAMPAIGN_OFFICE_ICON = L.icon({ iconUrl: '//dcxc7a0ls04u1.cloudfront.net/img/icon/star.png', iconSize: [17, 14], // size of the icon // shadowSize: [50, 64], // size of the shadow // iconAnchor: [22, 94], // point of the icon which will correspond to marker's location // shadowAnchor: [4, 62], // the same for the shadow // popupAnchor: [-3, -76] // point from which the popup should open relative to the iconAnchor }); var GOTV_CENTER_ICON = L.icon({ iconUrl: '//dcxc7a0ls04u1.cloudfront.net/img/icon/gotv-star.png', iconSize: [13, 10], // size of the icon }); var defaultCoord = options&&options.defaultCoord ? options.defaultCoord : {center: [37.8, -96.9], zoom: 4}; var centralMap = new leaflet .Map("map-container", window.customMapCoord ? window.customMapCoord : defaultCoord) .addLayer(mapboxTiles); if(centralMap) {} var overlays = L.layerGroup().addTo(centralMap); var offices = L.layerGroup().addTo(centralMap); var gotvCenter = L.layerGroup().addTo(centralMap); var campaignOfficeLayer = L.layerGroup().addTo(centralMap); //initialize map var filteredEvents = []; var module = {}; var _popupEvents = function(event) { var target = event.target._latlng; var filtered = eventsList.filter(function(d) { return target.lat == d.LatLng[0] && target.lng == d.LatLng[1] && (!current_filters || current_filters.length == 0 || $(d.properties.filters).not(current_filters).length != d.properties.filters.length); }).sort(function(a, b) { return a.startTime - b.startTime; }); var div = $("<div />") .append(filtered.length > 1 ? "<h3 class='sched-count'>" + filtered.length + " Scheduled Events</h3>" : "") .append( $("<div class='popup-list-container'/>") .append($("<ul class='popup-list'>") .append( filtered.map(function(d) { return $("<li class='lato'/>") .attr('data-attending', (function(prop) { var email = Cookies.get('map.bernie.email'); var events_attended_raw = Cookies.get('map.bernie.eventsJoined.' + email); var events_attended = events_attended_raw ? JSON.parse(events_attended_raw) : []; return $.inArray(prop.id_obfuscated, events_attended) > -1; })(d.properties)) .addClass(d.isFull?"is-full":"not-full") .addClass(d.visible ? "is-visible" : "not-visible") .append(d.render()); }) ) ) ); setTimeout( function() { L.popup() .setLatLng(event.target._latlng) .setContent(div.html()) .openOn(centralMap); } , 100); }; /*** * Initialization */ var initialize = function() { var uniqueLocs = eventsList.reduce(function(arr, item){ var className = item.properties.filters.join(" "); if ( arr.indexOf(item.properties.latitude + "||" + item.properties.longitude + "||" + className) >= 0 ) { return arr; } else { arr.push(item.properties.latitude + "||" + item.properties.longitude + "||" + className); return arr; } }, []); uniqueLocs = uniqueLocs.map(function(d) { var split = d.split("||"); return { latLng: [ parseFloat(split[0]), parseFloat(split[1])], className: split[2] }; }); uniqueLocs.forEach(function(item) { // setTimeout(function() { if (item.className == "campaign-office") { L.marker(item.latLng, {icon: CAMPAIGN_OFFICE_ICON, className: item.className}) .on('click', function(e) { _popupEvents(e); }) .addTo(offices); } else if (item.className == "gotv-center") { L.marker(item.latLng, {icon: GOTV_CENTER_ICON, className: item.className}) .on('click', function(e) { _popupEvents(e); }) .addTo(gotvCenter); }else if (item.className.match(/bernie\-event/ig)) { L.circleMarker(item.latLng, { radius: 12, className: item.className, color: 'white', fillColor: '#F55B5B', opacity: 0.8, fillOpacity: 0.7, weight: 2 }) .on('click', function(e) { _popupEvents(e); }) .addTo(overlays); } else { L.circleMarker(item.latLng, { radius: 5, className: item.className, color: 'white', fillColor: '#1462A2', opacity: 0.8, fillOpacity: 0.7, weight: 2 }) .on('click', function(e) { _popupEvents(e); }) .addTo(overlays); } // }, 10); }); // $(".leaflet-overlay-pane").find(".bernie-event").parent().prependTo('.leaflet-zoom-animated'); }; // End of initialize var toMile = function(meter) { return meter * 0.00062137; }; var filterEventsByCoords = function (center, distance, filterTypes) { var zipLatLng = leaflet.latLng(center); var filtered = eventsList.filter(function(d) { var dist = toMile(zipLatLng.distanceTo(d.LatLng)); if (dist < distance) { d.distance = Math.round(dist*10)/10; //If no filter was a match on the current filter if (options && options.defaultCoord && !filterTypes) { return true; } if($(d.properties.filters).not(filterTypes).length == d.properties.filters.length) { return false; } return true; } return false; }); return filtered; }; var filterEvents = function (zipcode, distance, filterTypes) { return filterEventsByCoords([parseFloat(zipcode.lat), parseFloat(zipcode.lon)], distance, filterTypes) }; var sortEvents = function(filteredEvents, sortType) { switch (sortType) { case 'distance': filteredEvents = filteredEvents.sort(function(a,b) { return a.distance - b.distance; }); break; default: filteredEvents = filteredEvents.sort(function(a,b) { return a.startTime - b.startTime; }); break; } // filteredEvents = filteredEvents.sort(function(a, b) { // var aFull = a.isFull(); // var bFull = b.isFull(); // if (aFull && bFull) { return 0; } // else if (aFull && !bFull) { return 1; } // else if (!aFull && bFull) { return -1; } // }); //sort by fullness; //.. return filteredEvents; }; setTimeout(function(){ initialize(); }, 10); module._eventsList = eventsList; module._zipcodes = zipcodes; module._options = options; /* * Refresh map with new events map */ var _refreshMap = function() { overlays.clearLayers(); initialize(); }; module.filterByType = function(type) { if ($(filters).not(type).length != 0 || $(type).not(filters).length != 0) { current_filters = type; //Filter only items in the list // eventsList = originalEventList.filter(function(eventItem) { // var unmatch = $(eventItem.properties.filters).not(filters); // return unmatch.length != eventItem.properties.filters.length; // }); // var target = type.map(function(i) { return "." + i }).join(","); // $(".leaflet-overlay-pane").find("path:not("+type.map(function(i) { return "." + i }).join(",") + ")") var toHide = $(allFilters).not(type); if (toHide && toHide.length > 0) { toHide = toHide.splice(0,toHide.length); $(".leaflet-overlay-pane").find("." + toHide.join(",.")).hide(); } if (type && type.length > 0) { $(".leaflet-overlay-pane").find("." + type.join(",.")).show(); // _refreshMap(); } //Specifically for campaign office if (!type) { centralMap.removeLayer(offices); } else if (type && type.indexOf('campaign-office') < 0) { centralMap.removeLayer(offices); } else { centralMap.addLayer(offices); } //For gotv-centers if (!type) { centralMap.removeLayer(gotvCenter); } else if (type && type.indexOf('gotv-center') < 0) { centralMap.removeLayer(gotvCenter); } else { centralMap.addLayer(gotvCenter); } } return; }; module.filterByCoords = function(coords, distance, sort, filterTypes) { //Remove list d3.select("#event-list") .selectAll("li").remove(); var filtered = filterEventsByCoords(coords, parseInt(distance), filterTypes); //Sort event filtered = sortEvents(filtered, sort, filterTypes); //Check cookies var email = Cookies.get('map.bernie.email'); var events_attended_raw = Cookies.get('map.bernie.eventsJoined.' + email); var events_attended = events_attended_raw ? JSON.parse(events_attended_raw) : []; //Render event var eventList = d3.select("#event-list") .selectAll("li") .data(filtered, function(d){ return d.properties.id_obfuscated; }); eventList.enter() .append("li") .attr("data-attending", function(d, id) { return $.inArray(d.properties.id_obfuscated, events_attended) > -1; }) .attr("class", function(d) { return (d.isFull ? 'is-full' : 'not-full') + " " + (this.visible ? "is-visible" : "not-visible")}) .classed("lato", true) .html(function(d){ return d.render(d.distance); }); eventList.exit().remove(); //add a highlighted marker function addhighlightedMarker(lat,lon){ var highlightedMarker = new L.circleMarker([lat,lon],{radius: 5, color: '#ea504e', fillColor: '#1462A2', opacity: 0.8, fillOpacity: 0.7, weight: 2}).addTo(centralMap); // event listener to remove highlighted markers $(".not-full").mouseout(function(){ centralMap.removeLayer(highlightedMarker) }) } // event listener to get the mouseover $(".not-full" ).mouseover(function(){ $(this).toggleClass("highlight") var cMarkerLat = $(this).children('div').attr('lat') var cMarkerLon = $(this).children('div').attr('lon') // function call to add highlighted marker addhighlightedMarker(cMarkerLat,cMarkerLon); }) //Push all full items to end of list $("div#event-list-container ul#event-list li.is-full").appendTo("div#event-list-container ul#event-list"); //Move campaign offices to var officeCount = $("div#event-list-container ul#event-list li .campaign-office").length; $("#hide-show-office").attr("data-count", officeCount); $("#campaign-off-count").text(officeCount); $("section#campaign-offices ul#campaign-office-list *").remove(); $("div#event-list-container ul#event-list li .campaign-office").parent().appendTo("section#campaign-offices ul#campaign-office-list"); } /*** * FILTER() -- When the user submits query, we will look at this. */ module.filter = function(zipcode, distance, sort, filterTypes) { //Check type filter if (!zipcode || zipcode == "") { return; }; //Start if other filters changed var targetZipcode = zipcodes[zipcode]; //Remove list d3.select("#event-list") .selectAll("li").remove(); if (targetZipcode == undefined || !targetZipcode) { $("#event-list").append("<li class='error lato'>Zipcode does not exist. <a href=\"https://go.berniesanders.com/page/event/search_results?orderby=zip_radius&zip_radius%5b0%5d=" + zipcode + "&zip_radius%5b1%5d=100&country=US&radius_unit=mi\">Try our events page</a></li>"); return; } //Calibrate map var zoom = 4; switch(parseInt(distance)) { case 5 : zoom = 12; break; case 10: zoom = 11; break; case 20: zoom = 10; break; case 50: zoom = 9; break; case 100: zoom = 8; break; case 250: zoom = 7; break; case 500: zoom = 5; break; case 750: zoom = 5; break; case 1000: zoom = 4; break; case 2000: zoom = 4; break; case 3000: zoom = 3; break; } if (!(targetZipcode.lat && targetZipcode.lat != "")) { return; } if (current_zipcode != zipcode || current_distance != distance) { current_zipcode = zipcode; current_distance = distance; centralMap.setView([parseFloat(targetZipcode.lat), parseFloat(targetZipcode.lon)], zoom); } var filtered = filterEvents(targetZipcode, parseInt(distance), filterTypes); //Sort event filtered = sortEvents(filtered, sort, filterTypes); //Check cookies var email = Cookies.get('map.bernie.email'); var events_attended_raw = Cookies.get('map.bernie.eventsJoined.' + email); var events_attended = events_attended_raw ? JSON.parse(events_attended_raw) : []; //Render event var eventList = d3.select("#event-list") .selectAll("li") .data(filtered, function(d){ return d.properties.id_obfuscated; }); eventList.enter() .append("li") .attr("data-attending", function(d, id) { return $.inArray(d.properties.id_obfuscated, events_attended) > -1; }) .attr("class", function(d) { return (d.isFull ? 'is-full' : 'not-full') + " " + (this.visible ? "is-visible" : "not-visible")}) .classed("lato", true) .html(function(d){ return d.render(d.distance); }); eventList.exit().remove(); //add a highlighted marker function addhighlightedMarker(lat,lon){ var highlightedMarker = new L.circleMarker([lat,lon],{radius: 5, color: '#ea504e', fillColor: '#1462A2', opacity: 0.8, fillOpacity: 0.7, weight: 2}).addTo(centralMap); // event listener to remove highlighted markers $(".not-full").mouseout(function(){ centralMap.removeLayer(highlightedMarker) }) } // event listener to get the mouseover $(".not-full" ).mouseover(function(){ $(this).toggleClass("highlight") var cMarkerLat = $(this).children('div').attr('lat') var cMarkerLon = $(this).children('div').attr('lon') // function call to add highlighted marker addhighlightedMarker(cMarkerLat,cMarkerLon); }) //Push all full items to end of list $("div#event-list-container ul#event-list li.is-full").appendTo("div#event-list-container ul#event-list"); //Move campaign offices to var officeCount = $("div#event-list-container ul#event-list li .campaign-office").length; $("#hide-show-office").attr("data-count", officeCount); $("#campaign-off-count").text(officeCount); $("section#campaign-offices ul#campaign-office-list *").remove(); $("div#event-list-container ul#event-list li .campaign-office").parent().appendTo("section#campaign-offices ul#campaign-office-list"); }; module.toMapView = function () { $("body").removeClass("list-view").addClass("map-view"); centralMap.invalidateSize(); centralMap._onResize(); } module.toListView = function () { $("body").removeClass("map-view").addClass("list-view"); } module.getMap = function() { return centralMap; } return module; }); })(jQuery, d3, L); var VotingInfoManager = (function($) { return (function(votingInfo) { var votingInfo = votingInfo; var module = {}; function buildRegistrationMessage(state) { var $msg = $("<div class='registration-msg'/>").append($("<h3/>").text("Registration deadline: " + moment(new Date(state.registration_deadline)).format("MMM D"))) .append($("<p />").html(state.name + " has <strong>" + state.is_open + " " + state.type + "</strong>. " + state.you_must)) .append($("<p />").html("Find out where and how to register at <a target='_blank' href='https://vote.berniesanders.com/" + state.state + "'>vote.berniesanders.com</a>")) return $msg; } function buildPrimaryInfo(state) { var $msg = $("<div class='registration-msg'/>").append($("<h3/>").text("Primary day: " + moment(new Date(state.voting_day)).format("MMM D"))) .append($("<p />").html(state.name + " has <strong>" + state.is_open + " " + state.type + "</strong>. " + state.you_must)) .append($("<p />").html("Find out where and how to vote at <a target='_blank' href='https://vote.berniesanders.com/" + state.state + "'>vote.berniesanders.com</a>")) return $msg; } function buildCaucusInfo(state) { var $msg = $("<div class='registration-msg'/>").append($("<h3/>").text("Caucus day: " + moment(new Date(state.voting_day)).format("MMM D"))) .append($("<p />").html(state.name + " has <strong>" + state.is_open + " " + state.type + "</strong>. " + state.you_must)) .append($("<p />").html("Find out where and how to caucus at <a target='_blank' href='https://vote.berniesanders.com/" + state.state + "'>vote.berniesanders.com</a>")) return $msg; } module.getInfo = function(state) { var targetState = votingInfo.filter(function(d) { return d.state == state })[0]; //return first if(!targetState) return null; var today = new Date(); today.setDate(today.getDate() - 1); if(today <= new Date(targetState.registration_deadline)) { return buildRegistrationMessage(targetState); } else if (today <= new Date(targetState.voting_day)) { if (targetState.type == "primaries") { return buildPrimaryInfo(targetState); } else { // return buildCaucusInfo(targetState); } } else { return null; } } return module; }); })(jQuery); // More events (function($) { $(document).on("click", function(event, params) { $(".event-rsvp-activity").hide(); }); $(document).on("click", ".rsvp-link, .event-rsvp-activity", function(event, params) { event.stopPropagation(); }); //Show email $(document).on("show-event-form", function(events, target) { var form = $(target).closest(".event-item").find(".event-rsvp-activity"); if (Cookies.get('map.bernie.email')) { form.find("input[name=email]").val(Cookies.get('map.bernie.email')); } if (Cookies.get('map.bernie.phone')) { form.find("input[name=phone]").val(Cookies.get('map.bernie.phone')); } // var params = $.deparam(window.location.hash.substring(1) || ""); // form.find("input[name=zipcode]").val(params.zipcode ? params.zipcode : Cookies.get('map.bernie.zipcode')); form.fadeIn(100); }); $(document).on("submit", "form.event-form", function() { var query = $.deparam($(this).serialize()); var params = $.deparam(window.location.hash.substring(1) || ""); query['zipcode'] = params['zipcode'] || query['zipcode']; var $error = $(this).find(".event-error"); var $container = $(this).closest(".event-rsvp-activity"); if (query['has_shift'] == 'true' && (!query['shift_id'] || query['shift_id'].length == 0)) { $error.text("You must pick a shift").show(); return false; } var shifts = null; var guests = 0; if (query['shift_id']) { shifts = query['shift_id'].join(); } if (!query['phone'] || query['phone'] == '') { $error.text("Phone number is required").show(); return false; } if (!query['email'] || query['email'] == '') { $error.text("Email is required").show(); return false; } if (!query['email'].toUpperCase().match(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/)) { $error.text("Please input valid email").show(); return false; } // if (!query['name'] || query['name'] == "") { // $error.text("Please include your name").show(); // return false; // } $(this).find(".event-error").hide(); var $this = $(this) $.ajax({ type: 'POST', url: 'https://organize.berniesanders.com/events/add-rsvp', // url: 'https://bernie-ground-control-staging.herokuapp.com/events/add-rsvp', crossDomain: true, dataType: 'json', data: { // name: query['name'], phone: query['phone'], email: query['email'], zip: query['zipcode'], shift_ids: shifts, event_id_obfuscated: query['id_obfuscated'] }, success: function(data) { Cookies.set('map.bernie.zipcode', query['zipcode'], {expires: 7}); Cookies.set('map.bernie.email', query['email'], {expires: 7}); Cookies.set('map.bernie.name', query['name'], {expires: 7}); if (query['phone'] != '') { Cookies.set('map.bernie.phone', query['phone'], {expires: 7}); } //Storing the events joined var events_joined = JSON.parse(Cookies.get('map.bernie.eventsJoined.' + query['email']) || "[]") || []; events_joined.push(query['id_obfuscated']); Cookies.set('map.bernie.eventsJoined.' + query['email'], events_joined, {expires: 7}); $this.closest("li").attr("data-attending", true); $this.html("<h4 style='border-bottom: none'>RSVP Successful! Thank you for joining to this event!</h4>"); $container.delay(1000).fadeOut('fast') } }) return false; }); })(jQuery);
Bernie-2016/EventMap
js/MapManager.js
JavaScript
agpl-3.0
31,622
export default (original) => { const url = getHashUrl(original); let [path, params] = url.split('?'); if (path.length >= 2) { path = path.replace(/\/$/, ''); } if (params) { params = parseSearchParams(params); } else { params = {} } const actual = path + joinSearchParams(params); return { path, params, original, actual }; } const getHashUrl = (original) => { let url = original.split('#'); if (url.length >= 2) { url = url[1]; } else { url = '/'; } if (url === '') { url = '/'; } if (url[0] !== '/') { url = '/' + url; } return url; } const parseSearchParams = (searchString) => { let pairSplit; return (searchString || '').replace(/^\?/, '').split('&').reduce((p, pair) => { pairSplit = pair.split('='); if (pairSplit.length >= 1 && pairSplit[0].length >= 1) { p[decodeURIComponent(pairSplit[0])] = decodeURIComponent(pairSplit[1]) || ''; } return p; }, {}); } const joinSearchParams = (searchParams) => { const searchString = Object .keys(searchParams) .reduce((p, paramKey) => p += `&${paramKey}=${searchParams[paramKey]}`, '?'); if (searchString.length <= 1) { return ''; } return searchString.replace('?&', '?'); }
regenduft/kartevonmorgen
src/util/parseUrl.js
JavaScript
agpl-3.0
1,271
/* * decaffeinate suggestions: * DS207: Consider shorter variations of null checks * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ //############################################################################## // // CoCalc: Collaborative web-based calculation // Copyright (C) 2017, Sagemath Inc. // AGPLv3 // //############################################################################## /* Custom Prop Validation for immutable.js types, so they work just like other React prop-types. FUTURE: Put prop validation code in a debug area so that it doesn't get loaded for production In addition to React Prop checks, we implement the following type checkers: immutable, immutable.List, immutable.Map, immutable.Set, immutable.Stack, which may be chained with .isRequired just like normal React prop checks Additional validations may be added with the following signature rtypes.custom_checker_name<function ( props, propName, componentName, location, propFullName, secret ) => <Error-Like-Object or null> > Check React lib to see if this has changed. */ const check_is_immutable = function( props, propName, componentName, location, propFullName ) { if (componentName == null) { componentName = "ANONYMOUS"; } if (props[propName] == null || props[propName].toJS != null) { return null; } else { const type = typeof props[propName]; return new Error( `Invalid prop \`${propName}\` of` + ` type ${type} supplied to` + ` \`${componentName}\`, expected an immutable collection or frozen object.` ); } }; const allow_isRequired = function(validate) { const check_type = function( isRequired, props, propName, componentName, location ) { if (componentName == null) { componentName = "ANONYMOUS"; } if (props[propName] == null && isRequired) { return new Error( `Required prop \`${propName}\` was not specified in \`${componentName}\`` ); } return validate(props, propName, componentName, location); }; const chainedCheckType = check_type.bind(null, false); chainedCheckType.isRequired = check_type.bind(null, true); chainedCheckType.isRequired.category = "IMMUTABLE"; chainedCheckType.category = "IMMUTABLE"; return chainedCheckType; }; const create_immutable_type_required_chain = function(validate) { const check_type = function( immutable_type_name, props, propName, componentName ) { if (componentName == null) { componentName = "ANONYMOUS"; } if (immutable_type_name && props[propName] != null) { const T = immutable_type_name; if (props[propName].toJS == null) { return new Error( `NOT EVEN IMMUTABLE, wanted immutable.${T} ${props}, ${propName}` ); } if (require("immutable")[`${T}`][`is${T}`](props[propName])) { return null; } else { return new Error( `Component \`${componentName}\`` + ` expected ${propName} to be an immutable.${T}` + ` but was supplied ${props[propName]}` ); } } else { return validate(props, propName, componentName, location); } }; // To add more immutable.js types, mimic code below. const check_immutable_chain = allow_isRequired( check_type.bind(null, undefined) ); check_immutable_chain.Map = allow_isRequired(check_type.bind(null, "Map")); check_immutable_chain.List = allow_isRequired(check_type.bind(null, "List")); check_immutable_chain.Set = allow_isRequired(check_type.bind(null, "Set")); check_immutable_chain.Stack = allow_isRequired( check_type.bind(null, "Stack") ); check_immutable_chain.category = "IMMUTABLE"; return check_immutable_chain; }; exports.immutable = create_immutable_type_required_chain(check_is_immutable);
DrXyzzy/smc
src/smc-util/immutable-types.js
JavaScript
agpl-3.0
3,924
'use strict'; var openUrl = require('./utils').open; module.exports = new PublishQueue(); function PublishQueue() { this.openPublishQueue = function() { openUrl('/#/publish_queue'); }; this.getRow = function(rowNo) { return element.all(by.css('[ng-click="preview(queue_item);"]')).get(rowNo); }; this.getHeadline = function(rowNo) { var row = this.getRow(rowNo); return row.all(by.className('ng-binding')).get(2); }; this.getUniqueName = function(rowNo) { var row = this.getRow(rowNo); return row.all(by.className('ng-binding')).get(1); }; this.getDestination = function(rowNo) { var row = this.getRow(rowNo); return row.all(by.className('ng-binding')).get(6); }; this.previewAction = function(rowNo) { var row = this.getRow(rowNo); row.click(); }; this.openCompositeItem = function(group) { var _list = element(by.css('[data-title="' + group.toLowerCase() + '"]')) .all(by.repeater('child in item.childData')); _list.all(by.css('[ng-click="open(data)"]')).get(0).click(); }; this.getCompositeItemHeadline = function(index) { return element.all(by.className('package-item__item-headline')).get(index).getText(); }; this.getOpenedItemHeadline = function() { return element.all(by.className('headline')).get(0).getText(); }; this.getPreviewTitle = function() { return element(by.css('.content-container')) .element(by.binding('selected.preview.headline')) .getText(); }; this.searchAction = function(search) { element(by.css('.flat-searchbar')).click(); browser.sleep(100); element(by.model('query')).clear(); element(by.model('query')).sendKeys(search); }; var list = element(by.className('list-pane')); this.getItemCount = function () { browser.sleep(500); // wait for a while to get list populated. return list.all(by.repeater('queue_item in publish_queue track by queue_item._id')).count(); }; }
vladnicoara/superdesk-client-core
spec/helpers/publish_queue.js
JavaScript
agpl-3.0
2,111
var PlayerWrapper = function() { this.underlyingPlayer = 'aurora'; this.aurora = {}; this.sm2 = {}; this.duration = 0; this.volume = 100; return this; }; PlayerWrapper.prototype = _.extend({}, OC.Backbone.Events); PlayerWrapper.prototype.play = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.play('ownCloudSound'); break; case 'aurora': this.aurora.play(); break; } }; PlayerWrapper.prototype.stop = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.stop('ownCloudSound'); this.sm2.destroySound('ownCloudSound'); break; case 'aurora': if(this.aurora.asset !== undefined) { // check if player's constructor has been called, // if so, stop() will be available this.aurora.stop(); } break; } }; PlayerWrapper.prototype.togglePlayback = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.togglePause('ownCloudSound'); break; case 'aurora': this.aurora.togglePlayback(); break; } }; PlayerWrapper.prototype.seekingSupported = function() { // Seeking is not implemented in aurora/flac.js and does not work on all // files with aurora/mp3.js. Hence, we disable seeking with aurora. return this.underlyingPlayer == 'sm2'; }; PlayerWrapper.prototype.pause = function() { switch(this.underlyingPlayer) { case 'sm2': this.sm2.pause('ownCloudSound'); break; case 'aurora': this.aurora.pause(); break; } }; PlayerWrapper.prototype.seek = function(percentage) { if (this.seekingSupported()) { console.log('seek to '+percentage); switch(this.underlyingPlayer) { case 'sm2': this.sm2.setPosition('ownCloudSound', percentage * this.duration); break; case 'aurora': this.aurora.seek(percentage * this.duration); break; } } else { console.log('seeking is not supported for this file'); } }; PlayerWrapper.prototype.setVolume = function(percentage) { this.volume = percentage; switch(this.underlyingPlayer) { case 'sm2': this.sm2.setVolume('ownCloudSound', this.volume); break; case 'aurora': this.aurora.volume = this.volume; break; } }; PlayerWrapper.prototype.fromURL = function(typeAndURL) { var self = this; var url = typeAndURL['url']; var type = typeAndURL['type']; if (soundManager.canPlayURL(url)) { this.underlyingPlayer = 'sm2'; } else { this.underlyingPlayer = 'aurora'; } console.log('Using ' + this.underlyingPlayer + ' for type ' + type + ' URL ' + url); switch(this.underlyingPlayer) { case 'sm2': this.sm2 = soundManager.setup({ html5PollingInterval: 200 }); this.sm2.html5Only = true; this.sm2.createSound({ id: 'ownCloudSound', url: url, whileplaying: function() { self.trigger('progress', this.position); }, whileloading: function() { self.duration = this.durationEstimate; self.trigger('duration', this.durationEstimate); // The buffer may contain holes after seeking but just ignore those. // Show the buffering status according the last buffered position. var bufCount = this.buffered.length; var bufEnd = (bufCount > 0) ? this.buffered[bufCount-1].end : 0; self.trigger('buffer', bufEnd / this.durationEstimate * 100); }, onfinish: function() { self.trigger('end'); }, onload: function(success) { if (success) { self.trigger('ready'); } else { console.log('SM2: sound load error'); } } }); break; case 'aurora': this.aurora = AV.Player.fromURL(url); this.aurora.asset.source.chunkSize=524288; this.aurora.on('buffer', function(percent) { self.trigger('buffer', percent); }); this.aurora.on('progress', function(currentTime) {//currentTime is in msec self.trigger('progress', currentTime); }); this.aurora.on('ready', function() { self.trigger('ready'); }); this.aurora.on('end', function() { self.trigger('end'); }); this.aurora.on('duration', function(msecs) { self.duration = msecs; self.trigger('duration', msecs); }); break; } // Set the current volume to the newly created player instance this.setVolume(this.volume); }; PlayerWrapper.prototype.setVolume = function(vol) { console.log("setVolume not implemented");// TODO };
pellaeon/music
js/app/playerwrapper.js
JavaScript
agpl-3.0
4,269
OC.L10N.register( "passman", { "General" : "ទូទៅ", "Done" : "Done", "Sharing" : "ការ​ចែក​រំលែក", "Share link" : "Share link", "Username" : "ឈ្មោះ​អ្នកប្រើ", "File" : "File", "Add" : "បញ្ចូល", "Type" : "Type", "Size" : "ទំហំ", "Expiration date" : "ពេល​ផុត​កំណត់", "Disabled" : "បាន​បិទ", "Export" : "នាំចេញ", "Version" : "កំណែ", "Import" : "នាំយកចូល", "Uploading" : "Uploading", "User" : "User", "Files" : "ឯកសារ", "Pending" : "កំពុង​រង់ចាំ", "Details" : "ព័ត៌មាន​លម្អិត", "by" : "ដោយ", "Save" : "រក្សាទុក", "Cancel" : "បោះបង់", "Settings" : "ការកំណត់", "Unshare" : "លែង​ចែក​រំលែក", "Password" : "ពាក្យសម្ងាត់", "URL" : "URL", "Notes" : "កំណត់​ចំណាំ", "Edit" : "កែប្រែ", "Delete" : "លុប", "Share" : "ចែក​រំលែក", "Date" : "Date", "Tags" : "ស្លាក", "Description" : "ការ​អធិប្បាយ", "You created %1$s" : "អ្នក​បាន​បង្កើត %1$s", "You deleted %1$s" : "អ្នក​បាន​លុប %1$s", "seconds ago" : "វិនាទី​មុន" }, "nplurals=1; plural=0;");
nextcloud/passman
l10n/km.js
JavaScript
agpl-3.0
1,561
export class Toolbar { }
QuantumConcepts/slumber-db-portal
wwwroot/elements/Toolbar.js
JavaScript
agpl-3.0
29
OC.L10N.register( "weather", { "Monday" : "Måndag", "Tuesday" : "Tysdag", "Wednesday" : "Onsdag", "Thursday" : "Torsdag", "Friday" : "Fredag", "Saturday" : "Laurdag", "Sunday" : "Søndag", "Weather" : "Vær", "Save" : "Lagre", "Add a city" : "Legg til ein by", "Add city" : "Legg til by", "City name" : "Bynamn", "Add" : "Legg til", "Cancel" : "Avbryt", "Settings" : "Instillingar", "Pressure" : "Trykk", "Humidity" : "Luftfuktigheit", "Wind" : "Vind", "Sunrise" : "Soloppgang", "Sunset" : "Solnedgang", "Date" : "Date" }, "nplurals=2; plural=(n != 1);");
nerzhul/owncloud-weather
l10n/nn_NO.js
JavaScript
agpl-3.0
649
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Adapter | organization cleanup', function(hooks) { setupTest(hooks); // Replace this with your real tests. test('it exists', function(assert) { let adapter = this.owner.lookup('adapter:organization-cleanup'); assert.ok(adapter); }); });
appknox/irene
tests/unit/adapters/organization-cleanup-test.js
JavaScript
agpl-3.0
349
import React from 'react' import { connect } from 'react-redux' import { VelocityComponent } from 'velocity-react' import TopNav from '../components/TopNav' import NetworkNav from '../components/NetworkNav' import LeftNav, { leftNavWidth, leftNavEasing } from '../components/LeftNav' import { toggleLeftNav, updateCurrentUser } from '../actions' import { getCurrentCommunity } from '../models/community' import { getCurrentNetwork } from '../models/network' import { aggregatedTags } from '../models/hashtag' import { canInvite, canModerate } from '../models/currentUser' import { filter, get } from 'lodash/fp' const { array, bool, func, object, oneOfType, string } = React.PropTypes const makeNavLinks = (currentUser, community) => { const { slug, network } = community || {} const url = slug ? suffix => `/c/${slug}/${suffix}` : suffix => '/' + suffix const rootUrl = slug ? `/c/${slug}` : '/app' return filter('url', [ {url: rootUrl, icon: 'Comment-Alt', label: 'Conversations', index: true}, get('settings.events.enabled', community) && {url: url('events'), icon: 'Calendar', label: 'Events'}, get('settings.projects.enabled', community) && {url: url('projects'), icon: 'ProjectorScreen', label: 'Projects'}, {url: url('people'), icon: 'Users', label: 'Members'}, canInvite(currentUser, community) && {url: url('invite'), icon: 'Mail', label: 'Invite'}, {url: network && `/n/${network.slug}`, icon: 'merkaba', label: 'Network'}, canModerate(currentUser, community) && {url: url('settings'), icon: 'Settings', label: 'Settings'}, {url: slug && url('about'), icon: 'Help', label: 'About'} ]) } const PageWithNav = (props, context) => { const { leftNavIsOpen, community, networkCommunities, network, tags, path, children } = props const { dispatch, currentUser, isMobile } = context const moveWithMenu = {marginLeft: leftNavIsOpen ? leftNavWidth : 0} const toggleLeftNavAndSave = open => { if (leftNavIsOpen !== open) dispatch(toggleLeftNav()) if (!isMobile) { setTimeout(() => { const settings = {leftNavIsOpen: open} dispatch(updateCurrentUser({settings})) }, 5000) } } const openLeftNav = () => toggleLeftNavAndSave(true) const closeLeftNav = () => toggleLeftNavAndSave(false) const links = makeNavLinks(currentUser, community) const showNetworkNav = currentUser && !isMobile && networkCommunities && networkCommunities.length > 1 && !path.startsWith('/t/') const tagNotificationCount = filter(tag => tag.new_post_count > 0, tags).length return <div> {currentUser && <LeftNav opened={leftNavIsOpen} links={links} community={community} network={network} tags={tags} close={closeLeftNav} />} <TopNav currentUser={currentUser} links={links} community={community} network={network} openLeftNav={openLeftNav} leftNavIsOpen={leftNavIsOpen} path={path} opened={leftNavIsOpen} tagNotificationCount={tagNotificationCount} /> <VelocityComponent animation={moveWithMenu} easing={leftNavEasing}> <div id='main'> {showNetworkNav && <NetworkNav communities={networkCommunities} network={network || community.network} />} {children} </div> </VelocityComponent> </div> } PageWithNav.propTypes = { leftNavIsOpen: bool, community: object, network: object, networkCommunities: array, tags: object, path: string, children: oneOfType([array, object]), history: object } PageWithNav.contextTypes = {isMobile: bool, dispatch: func, currentUser: object} export default connect((state, props) => { const { leftNavIsOpen, tagsByCommunity, communitiesForNetworkNav } = state const community = getCurrentCommunity(state) const network = getCurrentNetwork(state) const networkCommunities = communitiesForNetworkNav[network ? network.id : get('network.id', community)] return { leftNavIsOpen, community, networkCommunities, network, tags: get(get('slug', community), tagsByCommunity) || aggregatedTags(state), path: state.routing.locationBeforeTransitions.pathname } })(PageWithNav)
Hylozoic/hylo-redux
src/containers/PageWithNav.js
JavaScript
agpl-3.0
4,170
if(App.namespace) { App.namespace('Action.Sort', function(App) { /** * @namespace App.Action.Sort * @type {*} */ var sort = {}; /** @type {App.Action.Project} Project */ var Project = null; /** * button for sorting columns grid * @type {{}} */ sort.icoSort = {}; /** * button for filter columns grid * @type {{}} */ sort.icoFilter = {}; /** * * @type {{}} */ sort.dataGroupsusers = {}; /** * * @type {{taskGroup: Array, taskName: Array, resGroup: Array, resUsers: Array}} */ sort.dynamic = {taskGroup:[],taskName:[],resGroup:[],resUsers:[]}; sort.clearFilter = true; sort.startFilteringReady = true; /** * * @namespace App.Action.Sort.init */ sort.init = function(){ Project = App.Action.Project; gantt.attachEvent("onColumnResizeEnd", sort.onEventGridResizeEnd); gantt.attachEvent("onGridResizeEnd", sort.onEventGridResizeEnd); gantt.attachEvent("onBeforeTaskDisplay", onBeforeTaskDisplay); sort.dataGroupsusers = App.Module.DataStore.get('groupsusers'); sort.icoSort = { id: App.query('#ganttsort_id'), task: App.query('#ganttsort_task'), start: App.query('#ganttsort_start'), resource: App.query('#ganttsort_resource') }; sort.icoFilter = { task: App.query('#ganttfilter_task'), resource: App.query('#ganttfilter_resource') }; sort.icoSort.id.direction = false; sort.icoSort.id.addEventListener('click', sort.onSortById, false); sort.icoSort.task.direction = false; sort.icoSort.task.addEventListener('click', sort.onSortByTask, false); sort.icoSort.start.direction = false; sort.icoSort.start.addEventListener('click', sort.onSortByStart, false); sort.icoSort.resource.direction = false; sort.icoSort.resource.addEventListener('click', sort.onSortByResource, false); sort.icoFilter.task.addEventListener('click', sort.onFilterForTask, false); sort.icoFilter.resource.addEventListener('click', sort.onFilterForResource, false); sort.applyStyle(); }; sort.applyStyle = function(){ App.node('sortedfilters').style.display = 'block'; sort.icoSort.id.style.left = '5px'; sort.icoSort.task.style.left = '87px'; sort.icoSort.start.style.left = '220px'; sort.icoSort.resource.style.left = '455px'; sort.icoFilter.task.style.left = '107px'; sort.icoFilter.resource.style.left = '475px'; }; /** * change icons position * @namespace App.Action.Sort.onEventGridResizeEnd */ sort.onEventGridResizeEnd = function () { setTimeout(function(){ sort.icoSort.id.style.left = sort.getColumnPosition('id') + 'px'; sort.icoSort.task.style.left = sort.getColumnPosition('text') + 'px'; sort.icoSort.start.style.left = sort.getColumnPosition('start_date') + 'px'; sort.icoSort.resource.style.left = sort.getColumnPosition('users') + 'px'; sort.icoFilter.task.style.left = sort.getColumnPosition('text') + 20 + 'px'; sort.icoFilter.resource.style.left = sort.getColumnPosition('users') + 20 + 'px'; }, 600); }; /** * @namespace App.Action.Sort.getColumnPosition * @param column_id * @returns {*} */ sort.getColumnPosition = function(column_id) { var selector = 'div[column_id='+column_id+']'; return ($(selector).width() / 2 + $(selector).position().left) - 15 }; /** * Sorted Event By Id * @param event */ sort.onSortById = function(event){ sort.icoSort.id.direction = !sort.icoSort.id.direction; gantt.sort(sortById); }; function sortById(task1, task2){ task1 = parseInt(task1.id); task2 = parseInt(task2.id); if (sort.icoSort.id.direction){ return task1 > task2 ? 1 : (task1 < task2 ? -1 : 0); } else { return task1 > task2 ? -1 : (task1 < task2 ? 1 : 0); } } /** * Sorted Event By Task * @param event */ sort.onSortByTask = function(event){ sort.icoSort.task.direction = !sort.icoSort.task.direction; gantt.sort(sortByTask); }; function sortByTask(task1, task2){ task1 = task1.text; task2 = task2.text; if (sort.icoSort.task.direction){ return task1 > task2 ? 1 : (task1 < task2 ? -1 : 0); } else { return task1 > task2 ? -1 : (task1 < task2 ? 1 : 0); } } /** * Sorted Event By Start * @param event */ sort.onSortByStart = function(event){ sort.icoSort.start.direction = !sort.icoSort.start.direction; gantt.sort(sortByStart); }; function sortByStart(task1, task2){ task1 = task1.start_date; task2 = task2.start_date; if (sort.icoSort.start.direction) { return task1 > task2 ? 1 : (task1 < task2 ? -1 : 0); } else { return task1 > task2 ? -1 : (task1 < task2 ? 1 : 0); } } /** * Sorted Event By Resource * @param event */ sort.onSortByResource = function(event){ sort.icoSort.resource.direction = !sort.icoSort.resource.direction; gantt.sort(sortByResource); }; function sortByResource(task1, task2){ task1 = task1.users; task2 = task2.users; if (sort.icoSort.resource.direction){ return task1 > task2 ? 1 : (task1 < task2 ? -1 : 0); } else { return task1 > task2 ? -1 : (task1 < task2 ? 1 : 0); } } sort.createPopup = function(content, specialClass){ var popup = document.createElement('div'), icoClose = document.createElement('i'); icoClose.className = 'icon-close ocb_close_ico'; icoClose.onclick = function(e){ $(popup).remove() }; popup.className = 'ocb_popup' + (specialClass?' '+specialClass:''); if(typeof content === 'object') popup.appendChild(content); else popup.innerHTML = content; popup.appendChild(icoClose); return popup; }; function filterTaskView(){ var wrap = Util.createElement( 'div', null, '<p><b>' +App.t('Filter by task groups or tasks')+ '</b><span class="ico_clear clear_filter"></span></p>'); var inputNameValue = sort.memory('taskname-task'); var inputName = Util.createElement( 'input', { 'id': 'gantt_filter_name', 'type': 'text', 'placeholder': App.t('Enter passphrase to be part of task name'), 'value': '' } ); if(inputNameValue && inputNameValue.length > 0) inputName.value = inputNameValue; inputName.addEventListener('keyup', onFilterClickTask); var inputGroupValue = sort.memory('taskname-group'); var inputGroup = Util.createElement( 'input', { 'id': 'gantt_filter_group', 'type': 'text', 'placeholder': App.t('Enter passphrase to be part of group name'), 'value': '' } ); if(inputGroupValue && inputGroupValue.length > 0) inputGroup.value = inputGroupValue; inputGroup.addEventListener('keyup', onFilterClickTask); var clearBtn, clearFields = Util.createElement( 'div', {'class':'ico_clear'}); wrap.appendChild(inputName); wrap.appendChild(inputGroup); wrap.appendChild(clearFields); if(clearBtn = wrap.querySelector('.clear_filter')) { clearBtn.addEventListener('click',function(event){ inputName.value = inputGroup.value = ''; sort.clearFilter = true; sort.startFilteringReady = true; gantt.render(); }); } return wrap; } function filterGroupView(){ var dataGroupsusers = sort.dataGroupsusers; var clearBtn, inner = Util.createElement('p', {}, '<p><b>' +App.t('Filter by task groups or resource')+ '</b><span class="ico_clear clear_filter"></span></p>'); for(var groupName in dataGroupsusers){ var fragment = createUsersGroup(groupName, dataGroupsusers[groupName]); inner.appendChild(fragment); } if(clearBtn = inner.querySelector('.clear_filter')) { clearBtn.addEventListener('click',function(event){ /*var i, inputs = inner.querySelectorAll('input[type=checkbox]'); if(typeof inputs === 'object' && inputs.length > 0) { for( i = 0; i < inputs.length; i++ ){ if(inputs[i].checked === true) inputs[i].checked = false; } } */ sort.inputCheckedAll(inner, false); sort.clearFilter = true; sort.startFilteringReady = true; gantt.render(); }); } return inner } /** * @namespace App.Action.Sort.createInputWrapper * @type {createInputWrapper} */ sort.createInputWrapper = createInputWrapper; /** * @namespace App.Action.Sort.createUsersGroup * @type {createUsersGroup} */ sort.createUsersGroup = createUsersGroup; function createUsersGroup(group, users){ var deprecatedUsers = ['collab_user']; var usersElements = document.createElement('div'), oneElement = document.createDocumentFragment(); oneElement.appendChild(createInputWrapper(false, group)); for(var i = 0; i < users.length; i ++) { // hide deprecated users if (deprecatedUsers.indexOf(users[i]['uid']) !== -1) continue; usersElements.appendChild(createInputWrapper(users[i]['uid'], group)) } oneElement.appendChild(usersElements); return oneElement } function createInputWrapper(user, group) { var attr_id = user ? 'user_' + group + '_' + user : 'group_' + group; var attr_gid = group; var attr_type = user ? 'user' : 'group'; var attr_name = user ? user : group; var is_checked = sort.memory('resource-' + attr_type + '-' + attr_name) ? true : false; var wrap = Util.createElement( user ? 'span' : 'div' ); var input = Util.createElement( 'input', { 'id': attr_id, 'name': attr_name, 'type': 'checkbox', 'class': '', 'data-gid': attr_gid, 'data-type': attr_type }); if(is_checked) input.checked = true; input.addEventListener('click', onFilterClickResource); var label = Util.createElement( 'label', {'for':attr_id},'<span></span>'+ (attr_type == 'user' ? attr_name : '<b>'+attr_name+'</b>' )); wrap.appendChild(input); wrap.appendChild(label); return wrap; } function onFilterClickResource (event) { var id = this.id.split('_')[1]; var name = this.getAttribute('name'); var type = this.getAttribute('data-type'); var group = this.getAttribute('data-gid'); var checked = this.checked; var uids = sort.getUsersIdsByGroup(name); //console.log(id, name, checked, type, group, uids); sort.memory('resource-' + type + '-' + name, checked); if(type === 'user') { if (checked && sort.dynamic.resUsers.indexOf(name) === -1) { sort.dynamic.resUsers.push(name); //jQuery('input[name="'+name+'"]').checked(true); jQuery('input[name="'+name+'"][data-type="user"]').prop('checked', true); //console.log(); } else if (!checked && sort.dynamic.resUsers.indexOf(name) !== -1) { sort.dynamic.resUsers = Util.rmItArr(name, sort.dynamic.resUsers); } } else { //console.log(group); //console.log(sort.dataGroupsusers); if(checked && sort.dataGroupsusers[group]) { sort.dynamic.resGroup.push(group); //sort.dynamic.resUsers = Util.arrMerge(sort.dynamic.resUsers, uids); } else if(!checked && sort.dynamic.resGroup.indexOf(name) !== -1) { sort.dynamic.resGroup = Util.rmItArr(group, sort.dynamic.resGroup); //sort.dynamic.resUsers = Util.arrDiff(sort.dynamic.resUsers, uids); } // todo: отк/вкл чик юзеров //sort.inputCheckedAll(this.parentNode.nextSibling, checked); /* if(checked && sort.dynamic.resGroup.indexOf(name) === -1) { sort.dynamic.resGroup.push(name); sort.dynamic.resUsers = Util.arrMerge(sort.dynamic.resUsers, uids); } else if(!checked && sort.dynamic.resGroup.indexOf(name) !== -1) { sort.dynamic.resGroup = Util.rmItArr(name, sort.dynamic.resGroup); sort.dynamic.resUsers = Util.arrDiff(sort.dynamic.resUsers, uids); }*/ } // handler for filtering if(sort.startFilteringReady){ sort.startFilteringReady = false; Timer.after(1000, sort.startFiltering); } } function onFilterClickTask(event){ var type = this.id == 'gantt_filter_name' ? 'task' : 'group'; var value = this.value; sort.memory('taskname-' + type, value); if(type === 'task') sort.dynamic.taskName[0] = value; else sort.dynamic.taskGroup[0] = value; // handler for filtering if(sort.startFilteringReady){ sort.startFilteringReady = false; Timer.after(1000, sort.startFiltering); } } sort.onFilterForTask = function(event){ var popup = sort.createPopup(filterTaskView(), 'filter_tasks'); popup.style.width = '350px'; popup.style.left = '110px'; App.node('topbar').appendChild(popup); }; sort.onFilterForResource = function(event){ var popup = sort.createPopup(filterGroupView(), 'filter_resources'); popup.style.width = '500px'; popup.style.left = '480px'; App.node('topbar').appendChild(popup); //console.log(event); }; /** * Apply filtering */ sort.startFiltering = function(){ sort.startFilteringReady = true; if( !!sort.dynamic.taskName[0] || !!sort.dynamic.taskGroup[0] || !Util.isEmpty(sort.dynamic.resUsers) || !Util.isEmpty(sort.dynamic.resGroup) ) { console.log('Filtering enabled'); sort.clearFilter = false; gantt.refreshData(); }else{ console.log('Filtering disabled'); sort.clearFilter = true; gantt.refreshData(); } }; function onBeforeTaskDisplay(id, task) { if(!sort.clearFilter) { var taskName = sort.dynamic.taskName[0] ? sort.dynamic.taskName[0].toLowerCase() : false; var taskGroup = sort.dynamic.taskGroup[0] ? sort.dynamic.taskGroup[0].toLowerCase() : false; var resUsers = Util.uniqueArr(sort.dynamic.resUsers); var resGroup = sort.dynamic.resGroup; var show = false; var resources = false; if(!!taskName && gantt.getChildren(id).length == 0 && task.text.toLowerCase().indexOf(taskName) !== -1 ) { show = true; } if(!!taskGroup && gantt.getChildren(id).length > 0 && task.text.toLowerCase().indexOf(taskGroup) !== -1 ) { show = true; } if(!!resUsers) { for(var iu=0; iu < resUsers.length; iu ++){ resources = App.Action.Chart.getTaskResources(id); if(resources.users.indexOf(resUsers[iu]) !== -1) { show = true; break; } } } if(!!resGroup) { for(var ig=0; ig < resGroup.length; ig ++){ resources = App.Action.Chart.getTaskResources(id); if(resources.groups.indexOf(resGroup[ig]) !== -1) { show = true; break; } } } return show; }else return true; } /** * @namespace App.Action.Sort.getUsersIdsByGroup * @param gid * @returns {Array} */ sort.getUsersIdsByGroup = function(gid){ var ids = []; var groupsusers = Util.isArr(sort.dataGroupsusers[gid]) ? sort.dataGroupsusers[gid] : []; for(var i = 0; i < groupsusers.length; i ++ ){ ids.push(groupsusers[i]['uid']) } return ids; }; sort._memoryStore = {}; /** * @namespace App.Action.Sort.memory * @param key * @param value * @returns {*} */ sort.memory = function(key, value){ if(key === undefined && value === undefined) return sort._memoryStore; if(value === undefined) return sort._memoryStore[key] else return sort._memoryStore[key] = value }; /** * @namespace App.Action.Sort.inputCheckedAll * @param nodeWhere * @param checked */ sort.inputCheckedAll = function(nodeWhere, checked){ var i, inputs = nodeWhere.querySelectorAll('input[type=checkbox]'); if(typeof inputs === 'object' && inputs.length > 0) { for( i = 0; i < inputs.length; i++ ){ inputs[i].checked = !!checked; /*if(!!checked) if(inputs[i].checked !== true) inputs[i].checked = true; else if(inputs[i].checked === true) inputs[i].checked = false;*/ } } }; return sort })}
Werdffelynir/owncollab_chart
js/application/action/sort.js
JavaScript
agpl-3.0
18,828
/* * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting. * * Copyright (C) 2015 John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4. * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ function CustomReportDesignerController($scope, reports, SaveCustomReport, CustomReportFullList){ $scope.r = reports; $scope.reports = _.groupBy( $scope.r, 'category'); $scope.init = function(){ if($scope.sqleditor === undefined){ $scope.sqleditor = ace.edit("sqleditor"); $scope.sqleditor.setTheme("ace/theme/chrome"); $scope.sqleditor.getSession().setMode("ace/mode/pgsql"); $scope.filter = ace.edit("filtereditor"); $scope.filter.setTheme("ace/theme/chrome"); $scope.filter.getSession().setMode("ace/mode/json"); $scope.column = ace.edit("columneditor"); $scope.column.setTheme("ace/theme/chrome"); $scope.column.getSession().setMode("ace/mode/json"); $scope.meta = ace.edit("metaeditor"); $scope.meta.setTheme("ace/theme/chrome"); $scope.meta.getSession().setMode("ace/mode/html"); } $scope.sqleditor.setValue($scope.current.query); $scope.filter.setValue($scope.current.filters); $scope.column.setValue($scope.current.columnoptions); $scope.meta.setValue($scope.current.meta); }; $scope.select = function(report){ // clear previous values and message on screen $scope.columns = $scope.data = []; $scope.message = undefined; $scope.current = report; $scope.init(); }; $scope.New = function(){ $scope.current = {quer:'', filters:'[]',columnoptions:'[]'}; $scope.init(); }; $scope.Save = function(){ $scope.current.query = $scope.sqleditor.getValue(); $scope.current.filters = $scope.filter.getValue(); $scope.current.columnoptions = $scope.column.getValue(); $scope.current.meta = $scope.meta.getValue(); var save = SaveCustomReport.save($scope.current); save.$promise.then(function(){ $scope.message = $scope.current.name + ' saved successfully!'; $scope.current = undefined; $scope.r = CustomReportFullList.get(); $scope.r.$promise.then(function(){ $scope.reports = _.groupBy( $scope.r.reports, 'category'); }); }); }; } CustomReportDesignerController.resolve = { reports: function ($q, $timeout, CustomReportFullList) { var deferred = $q.defer(); $timeout(function () { CustomReportFullList.get(function (data) { deferred.resolve(data.reports); }); }, 100); return deferred.promise; } };
USAID-DELIVER-PROJECT/elmis
modules/openlmis-web/src/main/webapp/public/js/reports/custom/controller/designer-controller.js
JavaScript
agpl-3.0
3,363
(function(global){ var PollXBlockI18N = { init: function() { (function(globals) { var django = globals.django || (globals.django = {}); django.pluralidx = function(count) { return (count == 1) ? 0 : 1; }; /* gettext library */ django.catalog = django.catalog || {}; if (!django.jsi18n_initialized) { django.gettext = function(msgid) { var value = django.catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } }; django.ngettext = function(singular, plural, count) { var value = django.catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value.constructor === Array ? value[django.pluralidx(count)] : value; } }; django.gettext_noop = function(msgid) { return msgid; }; django.pgettext = function(context, msgid) { var value = django.gettext(context + '\x04' + msgid); if (value.indexOf('\x04') != -1) { value = msgid; } return value; }; django.npgettext = function(context, singular, plural, count) { var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count); if (value.indexOf('\x04') != -1) { value = django.ngettext(singular, plural, count); } return value; }; django.interpolate = function(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } }; /* formatting library */ django.formats = { "DATETIME_FORMAT": "j E Y H:i", "DATETIME_INPUT_FORMATS": [ "%d.%m.%Y %H:%M:%S", "%d.%m.%Y %H:%M:%S.%f", "%d.%m.%Y %H:%M", "%d.%m.%Y", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M", "%Y-%m-%d" ], "DATE_FORMAT": "j E Y", "DATE_INPUT_FORMATS": [ "%d.%m.%Y", "%d.%m.%y", "%y-%m-%d", "%Y-%m-%d" ], "DECIMAL_SEPARATOR": ",", "FIRST_DAY_OF_WEEK": 1, "MONTH_DAY_FORMAT": "j E", "NUMBER_GROUPING": 3, "SHORT_DATETIME_FORMAT": "d-m-Y H:i", "SHORT_DATE_FORMAT": "d-m-Y", "THOUSAND_SEPARATOR": "\u00a0", "TIME_FORMAT": "H:i", "TIME_INPUT_FORMATS": [ "%H:%M:%S", "%H:%M:%S.%f", "%H:%M" ], "YEAR_MONTH_FORMAT": "F Y" }; django.get_format = function(format_type) { var value = django.formats[format_type]; if (typeof(value) == 'undefined') { return format_type; } else { return value; } }; /* add to global namespace */ globals.pluralidx = django.pluralidx; globals.gettext = django.gettext; globals.ngettext = django.ngettext; globals.gettext_noop = django.gettext_noop; globals.pgettext = django.pgettext; globals.npgettext = django.npgettext; globals.interpolate = django.interpolate; globals.get_format = django.get_format; django.jsi18n_initialized = true; } }(this)); } }; PollXBlockI18N.init(); global.PollXBlockI18N = PollXBlockI18N; }(this));
open-craft/xblock-poll
poll/public/js/translations/pl/textjs.js
JavaScript
agpl-3.0
3,444
import reducer, { addFlag, fetchAll } from '../reducer' import fetchAllSuccess from './__fixtures__/fetch_all_success' const INITIAL_STATE = reducer(undefined, {}) test('has correct defaults', () => { snapshot(INITIAL_STATE) }) test('fetch all', () => { snapshotReducer(reducer, INITIAL_STATE, fetchAll(fetchAllSuccess)) }) test('add flag', () => { snapshotReducer(reducer, INITIAL_STATE, addFlag(42), addFlag(43), addFlag(44)) })
CaptainFact/captain-fact-frontend
app/state/video_debate/comments/__tests__/reducer.spec.js
JavaScript
agpl-3.0
441
define([ 'collections/credit_provider_collection', 'ecommerce', 'models/course_seats/credit_seat' ], function (CreditProviderCollection, ecommerce, CreditSeat) { 'use strict'; var model, data = { id: 9, url: 'http://ecommerce.local:8002/api/v2/products/9/', structure: 'child', product_class: 'Seat', title: 'Seat in edX Demonstration Course with honor certificate', price: '0.00', expires: null, attribute_values: [ { name: 'certificate_type', value: 'credit' }, { name: 'course_key', value: 'edX/DemoX/Demo_Course' }, { name: 'id_verification_required', value: false } ], is_available_to_buy: true }; beforeEach(function () { model = CreditSeat.findOrCreate(data, {parse: true}); ecommerce.credit.providers = new CreditProviderCollection([{id: 'harvard', display_name: 'Harvard'}]); }); describe('Credit course seat model', function () { describe('credit provider validation', function () { function assertCreditProviderInvalid(credit_provider, expected_msg) { model.set('credit_provider', credit_provider); expect(model.validate().credit_provider).toEqual(expected_msg); expect(model.isValid(true)).toBeFalsy(); } it('should do nothing if the credit provider is valid', function () { model.set('credit_provider', ecommerce.credit.providers.at(0).get('id')); expect(model.validate().credit_provider).toBeUndefined(); }); it('should return a message if the credit provider is not set', function () { var msg = 'All credit seats must have a credit provider.', values = [null, undefined, '']; values.forEach(function (value) { assertCreditProviderInvalid(value, msg); }); }); it('should return a message if the credit provider is not a valid credit provider', function () { var msg = 'Please select a valid credit provider.'; assertCreditProviderInvalid('acme', msg); }); }); }); } );
mferenca/HMS-ecommerce
ecommerce/static/js/test/specs/models/course_seats/credit_seat_spec.js
JavaScript
agpl-3.0
2,777
(function($) { $(document).ready(function() { $('.nsfw').on('click', function() { if($(this).hasClass('show')) { $(this).removeClass('show'); } else { $(this).addClass('show'); } }); $('.snip').on('click', function() { if($(this).hasClass('show')) { $(this).removeClass('show'); $(this).find('.message a').text('Read More'); } else { $(this).addClass('show'); $(this).find('.message a').text('Show Less'); } }); }); })(basic);
wetfish/classic
wiki/src/js/wiki2.js
JavaScript
agpl-3.0
728
/* This file is part of Booktype. Copyright (c) 2012 Aleksandar Erkalovic <aleksandar.erkalovic@sourcefabric.org> Booktype is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Booktype is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Booktype. If not, see <http://www.gnu.org/licenses/>. */ (function (win, jquery, _) { 'use strict'; jquery.namespace('win.booktype.editor'); /* Hold some basic variables and functions that are needed on global level and almost in all situations. */ win.booktype.editor = (function () { // Default settings var DEFAULTS = { panels: { 'edit': 'win.booktype.editor.edit', 'toc' : 'win.booktype.editor.toc', 'media' : 'win.booktype.editor.media' }, styles: { 'style1': '/static/edit/css/style1.css', 'style2': '/static/edit/css/style2.css', 'style3': '/static/edit/css/style3.css' }, tabs: { 'icon_generator': function (tb) { var tl = ''; if (!_.isUndefined(tb.title)) { if (tb.isLeft) { tl = 'rel="tooltip" data-placement="right" data-original-title="' + tb.title + '"'; } else { tl = 'rel="tooltip" data-placement="left" data-original-title="' + tb.title + '"'; } } return '<a href="#" id="' + tb.tabID + '"' + tl + '><i class="' + tb.iconID + '"></i></a>'; } }, config: { 'global': { 'tabs': ['online-users', 'chat'] }, 'edit': { 'tabs': ['chapters', 'attachments', 'notes', 'history', 'style'], 'toolbar': { 'H': ['table-dropdown', 'unorderedList', 'orderedList'], 'TABLE': ['unorderedList', 'orderedList', 'indent-left', 'indent-right'], 'PRE': ['table-dropdown', 'alignLeft', 'alignRight', 'indent-left', 'indent-right', 'alignCenter', 'alignJustify', 'unorderedList', 'orderedList'], 'ALL': ['table-dropdown', 'alignLeft', 'alignRight', 'indent-left', 'indent-right', 'alignCenter', 'alignJustify', 'unorderedList', 'orderedList', 'currentHeading', 'heading-dropdown'] }, 'menu': { 'H': ['insertImage', 'insertLink', 'horizontalline', 'pbreak'], 'TABLE': ['horizontalline', 'pbreak', 'indent-left', 'indent-right'], 'PRE': ['insertImage', 'insertLink', 'horizontalline', 'pbreak', 'indent-left', 'indent-right'], 'ALL': ['insertImage', 'insertLink', 'horizontalline', 'pbreak', 'indent-left', 'indent-right'] } }, 'media': { 'allowUpload': ['.jpe?g$', '.png$'] }, 'toc': { 'tabs': ['hold'], 'sortable': {'is_allowed': function (placeholder, parent, item) { return true; } } } } }; // Our global data var data = { 'chapters': null, 'holdChapters': null, 'statuses': null, 'activeStyle': 'style1', 'activePanel': null, 'panels': null, 'settings': {} }; var EditorRouter = Backbone.Router.extend({ routes: { 'edit/:id': 'edit' }, edit: function (id) { _editChapter(id); } }); var router = new EditorRouter(); // ID of the chapter which is being edited var currentEdit = null; // TABS var tabs = []; var Tab = function (tabID, iconID) { this.tabID = tabID; this.iconID = iconID; this.domID = ''; this.isLeft = false; this.isOnTop = false; this.title = ''; }; Tab.prototype.onActivate = function () {}; Tab.prototype.onDeactivate = function () {}; var hideAllTabs = function () { jquery('.right-tabpane').removeClass('open hold'); jquery('body').removeClass('opentabpane-right'); jquery('.right-tablist li').removeClass('active'); jquery('.left-tabpane').removeClass('open hold'); jquery('body').removeClass('opentabpane-left'); jquery('.left-tablist li').removeClass('active'); }; // Right tab var createRightTab = function (tabID, iconID, title) { var tb = new Tab(tabID, iconID); tb.isLeft = false; tb.domID = '.right-tablist li #' + tabID; if (!_.isUndefined(title)) { tb.title = title; } return tb; }; // Left tab var createLeftTab = function (tabID, iconID, title) { var tb = new Tab(tabID, iconID); tb.isLeft = true; tb.domID = '.left-tablist li #' + tabID; if (!_.isUndefined(title)) { tb.title = title; } return tb; }; // Initialise all tabs var activateTabs = function (tabList) { var _gen = data.settings.tabs['icon_generator']; jquery.each(tabList, function (i, v) { if (!v.isLeft) { if (v.isOnTop && jquery('DIV.right-tablist UL.navigation-tabs li').length > 0) { jquery('DIV.right-tablist UL.navigation-tabs li:eq(0)').before('<li>' + _gen(v) + '</li>'); } else { jquery('DIV.right-tablist UL.navigation-tabs').append('<li>' + _gen(v) + '</li>'); } jquery(v.domID).click(function () { //close left side jquery('.left-tabpane').removeClass('open hold'); jquery('body').removeClass('opentabpane-left'); jquery('.left-tablist li').removeClass('active'); // check if the tab is open if (jquery('#right-tabpane').hasClass('open')) { // if clicked on active tab, close tab if (jquery(this).closest('li').hasClass('active')) { jquery('.right-tabpane').toggleClass('open'); jquery('.right-tabpane').removeClass('hold'); jquery('.right-tabpane section').hide(); jquery('body').toggleClass('opentabpane-right'); jquery(this).closest('li').toggleClass('active'); } else { // open but not active, switching content jquery(this).closest('ul').find('li').removeClass('active'); jquery(this).parent().toggleClass('active'); jquery('.right-tabpane').removeClass('hold'); var target = jquery(this).attr('id'); jquery('.right-tabpane section').hide(); jquery('.right-tabpane section[source_id="' + target + '"]').show(); var isHold = jquery(this).attr('id'); if (isHold === 'hold-tab') { jquery('.right-tabpane').addClass('hold'); } v.onActivate(); } } else { // if closed, open tab jquery('body').toggleClass('opentabpane-right'); jquery(this).parent().toggleClass('active'); jquery('.right-tabpane').toggleClass('open'); var target = jquery(this).attr('id'); jquery('.right-tabpane section').hide(); jquery('.right-tabpane section[source_id="' + target + '"]').show(); var isHold = jquery(this).attr('id'); if (isHold === 'hold-tab') { jquery('.right-tabpane').addClass('hold'); } v.onActivate(); } return false; }); } else { if (v.isOnTop && jquery('DIV.left-tablist UL.navigation-tabs li').length > 0) { jquery('DIV.left-tablist UL.navigation-tabs li:eq(0)').before('<li>' + _gen(v) + '</li>'); } else { jquery('DIV.left-tablist UL.navigation-tabs').append('<li>' + _gen(v) + '</li>'); } jquery(v.domID).click(function () { //close right side jquery('.right-tabpane').removeClass('open hold'); jquery('body').removeClass('opentabpane-right'); jquery('.right-tablist li').removeClass('active'); // check if the tab is open if (jquery('#left-tabpane').hasClass('open')) { // if clicked on active tab, close tab if (jquery(this).closest('li').hasClass('active')) { jquery('.left-tabpane').toggleClass('open'); jquery('.left-tabpane').removeClass('hold'); jquery('.left-tabpane section').hide(); jquery('body').toggleClass('opentabpane-left'); jquery(this).closest('li').toggleClass('active'); } else { // open but not active, switching content jquery(this).closest('ul').find('li').removeClass('active'); jquery(this).parent().toggleClass('active'); jquery('.left-tabpane').removeClass('hold'); var target = jquery(this).attr('id'); jquery('.left-tabpane section').hide(); jquery('.left-tabpane section[source_id="' + target + '"]').show(); var isHold = jquery(this).attr('id'); if (isHold === 'hold-tab') { jquery('.left-tabpane').addClass('hold'); } v.onActivate(); } } else { // if closed, open tab jquery('body').toggleClass('opentabpane-left'); jquery(this).parent().toggleClass('active'); jquery('.left-tabpane').toggleClass('open'); //jquery('.right-tabpane').removeClass('open'); var target = jquery(this).attr('id'); jquery('.left-tabpane section').hide(); jquery('.left-tabpane section[source_id="' + target + '"]').show(); var isHold = jquery(this).attr('id'); if (isHold === 'hold-tab') { jquery('.left-tabpane').addClass('hold'); } v.onActivate(); } return false; }); } }); jquery('DIV.left-tablist [rel=tooltip]').tooltip({container: 'body'}); jquery('DIV.right-tablist [rel=tooltip]').tooltip({container: 'body'}); }; var deactivateTabs = function (tabList) { jquery('DIV.left-tablist [rel=tooltip]').tooltip('destroy'); jquery('DIV.right-tablist [rel=tooltip]').tooltip('destroy'); jquery.each(tabList, function (i, v) { if (v.isLeft) { jquery('DIV.left-tablist UL.navigation-tabs #' + v.tabID).remove(); } else { jquery('DIV.right-tablist UL.navigation-tabs #' + v.tabID).remove(); } }); }; // UTIL FUNCTIONS var _editChapter = function (id) { win.booktype.ui.notify(win.booktype._('loading_chapter', 'Loading chapter.')); win.booktype.sendToCurrentBook({ 'command': 'get_chapter', 'chapterID': id }, function (dta) { currentEdit = id; var activePanel = win.booktype.editor.getActivePanel(); activePanel.hide(function () { data.activePanel = data.panels['edit']; data.activePanel.setChapterID(id); jquery('#contenteditor').html(dta.content); data.activePanel.show(); win.booktype.ui.notify(); // Trigger events var doc = win.booktype.editor.getChapterWithID(id); jquery(document).trigger('booktype-document-loaded', [doc]); }); } ); }; // Init UI var _initUI = function () { win.booktype.ui.notify(); // History Backbone.history.start({pushState: false, root: '/' + win.booktype.currentBookURL + '/_edit/', hashChange: true}); // This is a default route. Instead of doing it from the Router we do it this way so user could easily // change his default route from the booktype events. // This should probably be some kind of default callback. var match = win.location.href.match(/#(.*)$/); if (!match) { data.activePanel = data.panels['toc']; data.activePanel.show(); } // Check configuration for this. Do not show it if it is not enabled. // ONLINE USERS TAB if (isEnabledTab('global', 'online-users')) { var t1 = createLeftTab('online-users-tab', 'big-icon-online-users'); t1.onActivate = function () { }; tabs.push(t1); } // CHAT TAB // Only activate if it is enabled. if (isEnabledTab('global', 'chat')) { var t2 = createLeftTab('chat-tab', 'big-icon-chat'); t2.draw = function () { var $this = this; var $container = jquery('section[source_id=chat-tab]'); var scrollBottom = function () { var scrollHeight = jquery('.content', $container)[0].scrollHeight; jquery('.content', $container).scrollTop(scrollHeight); }; $this.formatString = function (frm, args) { return frm.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) { if (m === '{{') { return '{'; } if (m === '}}') { return '}'; } return win.booktype.utils.escapeJS(args[n]); } ); }; $this.showJoined = function (notice) { var msg = win.booktype.ui.getTemplate('joinMsg'); msg.find('.notice').html(win.booktype.utils.escapeJS(notice)); jquery('.content', $container).append(msg.clone()); scrollBottom(); }; $this.showInfo = function (notice) { var msg = win.booktype.ui.getTemplate('infoMsg'); if (typeof notice['message_id'] !== 'undefined') { msg.find('.notice').html($this.formatString(win.booktype._('message_info_' + notice['message_id'], ''), notice['message_args'])); } jquery('.content', $container).append(msg.clone()); scrollBottom(); }; $this.formatMessage = function (from, message) { return $('<p><b>' + from + '</b>: ' + win.booktype.utils.escapeJS(message) + '</p>'); }; $this.showMessage = function (from, message) { jquery('.content', $container).append($this.formatMessage(from, message)); scrollBottom(); }; jquery('FORM', $container).submit(function () { var msg = jquery.trim(jquery('INPUT[name=message]', $container).val()); if (msg !== '') { $this.showMessage(win.booktype.username, msg); jquery('INPUT', $container).val(''); win.booktype.sendToChannel('/chat/' + win.booktype.currentBookID + '/', { 'command': 'message_send', 'message': msg }, function () { } ); } return false; }); }; t2.onActivate = function () {}; t2.draw(); tabs.push(t2); } activateTabs(tabs); jquery(document).trigger('booktype-ui-finished'); }; var _loadInitialData = function () { win.booktype.ui.notify(win.booktype._('loading_data', 'Loading data.')); win.booktype.sendToCurrentBook({'command': 'init_editor'}, function (dta) { // Put this in the TOC data.chapters.clear(); data.chapters.loadFromArray(dta.chapters); data.holdChapters.clear(); data.holdChapters.loadFromArray(dta.hold); // Attachments are not really needed //attachments = dta.attachments; data.statuses = dta.statuses; // Initislize rest of the interface _initUI(); } ); }; var _reloadEditor = function () { var $d = jquery.Deferred(); win.booktype.ui.notify('Loading data.'); win.booktype.sendToCurrentBook({'command': 'init_editor'}, function (dta) { // Put this in the TOC data.chapters.clear(); data.chapters.loadFromArray(dta.chapters); data.holdChapters.clear(); data.holdChapters.loadFromArray(dta.hold); // Attachments are not really needed //attachments = dta.attachments; data.statuses = dta.statuses; // if activePanel == toc then redraw() if (win.booktype.editor.getActivePanel().name === 'toc') { win.booktype.editor.getActivePanel().redraw(); } else { Backbone.history.navigate('toc', true); } win.booktype.ui.notify(); $d.resolve(); } ); return $d.promise(); }; var _disableUnsaved = function () { jquery(win).bind('beforeunload', function (e) { // CHECK TO SEE IF WE ARE CURRENTLY EDITING SOMETHING return 'not saved'; }); }; var _fillSettings = function (sett, opts) { if (!_.isObject(opts)) { return opts; } _.each(_.pairs(opts), function (item) { var key = item[0], value = item[1]; if (_.isObject(value) && !_.isArray(value)) { if (_.isFunction(value)) { sett[key] = value; } else { sett[key] = _fillSettings(sett[key], value); } } else { sett[key] = value; } }); return sett; }; var _initEditor = function (settings) { // Settings data.settings = _fillSettings(_.clone(DEFAULTS), settings); // Initialize Panels data.panels = {}; _.each(settings.panels, function (pan, name) { data.panels[name] = eval(pan); }); jquery.each(data.panels, function (i, v) { v.init(); }); // initialize chapters data.chapters = new win.booktype.editor.toc.TOC(); data.holdChapters = new win.booktype.editor.toc.TOC(); //_disableUnsaved(); // Subscribe to the book channel win.booktype.subscribeToChannel('/booktype/book/' + win.booktype.currentBookID + '/' + win.booktype.currentVersion + '/', function (message) { var funcs = { 'user_status_changed': function () { jquery('#users .user' + message.from + ' SPAN').html(message.message); jquery('#users .user' + message.from).animate({backgroundColor: 'yellow'}, 'fast', function () { jquery(this).animate({backgroundColor: 'white'}, 3000); }); }, 'user_add': function () { jquery('#users').append('<li class="user' + message.username + '"><div style="width: 24px; height: 24px; float: left; margin-right: 5px;background-image: url(' + jquery.booki.profileThumbnailViewUrlTemplate.replace('XXX', message.username) + ');"></div><b>' + message.username + '</b><br/><span>' + message.mood + '</span></li>'); }, 'user_remove': function () { jquery('#users .user' + message.username).css('background-color', 'yellow').slideUp(1000, function () { jquery(this).remove(); }); } }; if (funcs[message.command]) { funcs[message.command](); } } ); // Do not subscribe to the chat channel if chat is not enabled win.booktype.subscribeToChannel('/chat/' + win.booktype.currentBookID + '/', function (message) { if (message.command === 'user_joined') { if (tabs[1]) { tabs[1].showJoined(message['user_joined']); } } if (message.command === 'message_info') { if (tabs[1]) { tabs[1].showInfo(message); } } if (message.command === 'message_received') { if (tabs[1]) { tabs[1].showMessage(message.from, message.message); } } } ); _loadInitialData(); jquery('#button-toc').parent().addClass('active'); }; var embedActiveStyle = function () { var styleURL = data.settings.styles[data.activeStyle]; jquery('#aloha-embeded-style').attr('href', styleURL); }; var setStyle = function (sid) { data.activeStyle = sid; embedActiveStyle(); jquery(document).trigger('booktype-style-changed', [sid]); }; var isEnabledTab = function (panelName, tabName) { return _.contains(data.settings.config[panelName]['tabs'], tabName); }; return { data: data, editChapter: function (id) { Backbone.history.navigate('edit/' + id, true); }, getCurrentChapterID: function () { return currentEdit; }, getChapterWithID: function (cid) { var d = data.chapters.getChapterWithID(cid); if (_.isUndefined(d)) { d = data.holdChapters.getChapterWithID(cid); } return d; }, setStyle: setStyle, embedActiveStyle: embedActiveStyle, isEnabledTab: isEnabledTab, initEditor: _initEditor, reloadEditor: _reloadEditor, getActivePanel: function () { if (data.activePanel) { return data.activePanel; } return {'name': 'unknown', 'hide': function (c) { c(); }}; }, hideAllTabs: hideAllTabs, activateTabs: activateTabs, deactivateTabs: deactivateTabs, createLeftTab: createLeftTab, createRightTab: createRightTab }; })(); })(window, jQuery, _);
btat/Booktype
lib/booktype/apps/edit/static/edit/js/booktype/editor.js
JavaScript
agpl-3.0
21,929
import * as randomMC from 'random-material-color'; import Localisation from '@js/Classes/Localisation'; import CustomFieldsHelper from '@js/Helper/Import/CustomFieldsHelper'; import ImportMappingHelper from '@js/Helper/Import/ImportMappingHelper'; export default class EnpassConversionHelper { /** * * @param json * @param options * @returns {Promise<{data: {tags: Array, folders: Array, passwords: Array}, errors: Array}>} */ static async processJson(json, options) { let data = JSON.parse(json); if(!data.items) throw new Error('File does not implement Enpass 6 format'); if(!Array.isArray(data.folders)) data.folders = []; let {tags, tagMap} = await this._processTags(data.folders), folders = await this._processFolders(data.items), {passwords, errors} = await this._processPasswords(data.items, tagMap, options); return { data: {tags, folders, passwords}, errors }; } /** * * @param data * @returns {Promise<{tags: Array, tagMap}>} * @private */ static async _processTags(data) { let tags = [], tagMap = {}, labelMap = await ImportMappingHelper.getTagLabelMapping(); for(let i = 0; i < data.length; i++) { let tag = data[i], id = tag.title.toLowerCase(); if(id === '') continue; if(!labelMap.hasOwnProperty(id)) { labelMap[id] = tag.uuid; tagMap[tag.uuid] = tag.uuid; tags.push({id: tag.uuid, label: tag.title, color: randomMC.getColor()}); } else { tagMap[tag.uuid] = labelMap[id]; } } return {tags, tagMap}; } /** * * @param data * @returns {Promise<Array>} * @private */ static async _processFolders(data) { let folders = [], categories = this._getCategoryLabels(), labelMap = await ImportMappingHelper.getFolderLabelMapping(); for(let i = 0; i < data.length; i++) { let folder = data[i].category, label = folder.capitalize(); if(categories.hasOwnProperty(folder)) { label = categories[folder]; } let id = label.toLowerCase(); if(!labelMap.hasOwnProperty(id)) { labelMap[id] = id; folders.push({id, label}); } data[i].category = labelMap[id]; } return folders; } /** * * @param data * @param tagMap * @param options * @returns {Promise<{passwords: Array, errors: Array}>} * @private */ static async _processPasswords(data, tagMap, options) { let passwords = [], errors = [], mapping = await ImportMappingHelper.getPasswordLabelMapping(); for(let i = 0; i < data.length; i++) { let password = this._processPassword(data[i], mapping, tagMap, options.skipEmpty, errors); passwords.push(password); } return {passwords, errors}; } /** * * @param element * @param mapping * @param tagMap * @param skipEmpty * @param errors * @returns {{customFields: Array, password: string, favorite: boolean, folder: string, label: string, notes: string}} * @private */ static _processPassword(element, mapping, tagMap, skipEmpty, errors) { let label = element.title; if(element.hasOwnProperty('subtitle') && element.subtitle.length !== 0 && element.subtitle !== label && (!element.hasOwnProperty('template_type') || element.template_type !== 'login.default')) { label = `${label} – ${element.subtitle}`; } let password = { customFields: [], password : 'password-missing-during-import', favorite : element.favorite === 1, folder : element.category, notes : element.note, label, tags : [] }; ImportMappingHelper.checkPasswordDuplicate(mapping, password); this._processPasswordTags(element, password, tagMap); if(element.hasOwnProperty('fields')) { this._processPasswordFields(element, password, skipEmpty, errors); } if(element.hasOwnProperty('attachments')) { this._logConversionError('"{label}" has files attached which can not be imported.', password, errors); } return password; } /** * * @param element * @param password * @param skipEmpty * @param errors * @private */ static _processPasswordFields(element, password, skipEmpty, errors) { let commonFields = {password: false, username: false, url: false}; for(let i = 0; i < element.fields.length; i++) { let field = element.fields[i]; if(field.type === 'section') continue; if(skipEmpty && field.value === '') continue; if(field.value !== '' && this._processIfCommonField(commonFields, field, password)) continue; this._processCustomField(field, password, errors); } if(password.customFields.length === 0) delete password.customFields; } /** * * @param field * @param errors * @param password * @private */ static _processCustomField(field, password, errors) { let type = field.sensitive ? 'secret':field.type; CustomFieldsHelper.createCustomField(password, errors, field.value, field.label, type); } /** * * @param baseFields * @param field * @param password * @returns {boolean} * @private */ static _processIfCommonField(baseFields, field, password) { if(!baseFields.password && field.type === 'password') { baseFields.password = true; password.password = field.value; password.edited = field.value_updated_at; return true; } else if(!baseFields.username && field.type === 'username') { baseFields.username = true; password.username = field.value; return true; } else if(!baseFields.url && field.type === 'url') { baseFields.url = true; password.url = field.value; return true; } return false; } /** * * @param element * @param password * @param tagMap * @private */ static _processPasswordTags(element, password, tagMap) { if(element.hasOwnProperty('folders')) { for(let i = 0; i < element.folders.length; i++) { let id = element.folders[i].toLowerCase(); if(tagMap.hasOwnProperty(id)) password.tags.push(tagMap[id]); } } } /** * * @returns {{note: string, license: string, password: string, computer: string, identity: string, login: string, travel: string, creditcard: string, finance: string, misc: string}} * @private */ static _getCategoryLabels() { return { login : Localisation.translate('Logins'), creditcard: Localisation.translate('Credit Cards'), identity : Localisation.translate('Identities'), note : Localisation.translate('Notes'), password : Localisation.translate('Passwords'), finance : Localisation.translate('Finances'), license : Localisation.translate('Licenses'), travel : Localisation.translate('Travel'), computer : Localisation.translate('Computers'), misc : Localisation.translate('Miscellaneous') }; } /** * * @param text * @param vars * @param errors * @private */ static _logConversionError(text, vars, errors) { let message = Localisation.translate(text, vars); errors.push(message); console.error(message, vars); } }
marius-wieschollek/passwords
src/js/Helper/Import/EnpassConversionHelper.js
JavaScript
agpl-3.0
8,193
const t = require('tcomb') const Message = require('./message') const Messages = t.list(Message, 'Messages') module.exports = Messages
enspiral-dev-academy/freehold
models/messages.js
JavaScript
agpl-3.0
137
/* Copyright (c) 2016 eyeOS This file is part of Open365. Open365 is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ window.platformSettings = { lang: 'en', theme:'open365', cleanUrlParameters: false, customTitle: false, disableAnalytics: false, forceDomain: true, defaultDomain: "open365.io", publicTenant: "cloud", domainFromUrl: false, domainFromUrlExceptions: "", suggestDomain: true, enableUserRegistration: true, minBrowsersVersion: { "Chrome":30, "Firefox": 30 }, lastSettingsInFile: null // This line is to make sure that all the settings have a trailing coma };
Open365/eyeoslogin
src/js/platformSettings.js
JavaScript
agpl-3.0
1,207
/** * This file is part of taolin project (http://taolin.fbk.eu) * Copyright (C) 2008, 2009 FBK Foundation, (http://www.fbk.eu) * Authors: SoNet Group (see AUTHORS.txt) * * Taolin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation version 3 of the License. * * Taolin is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Taolin. If not, see <http://www.gnu.org/licenses/>. * */ /* Retrieves portal configuration as: * - img path * - contact email * - jabber server and domain */ Ext.onReady(function(){ document.getElementById('loading-msg').innerHTML = 'Loading Interface...'; setPortalConfiguration(application_init); }); Ext.BLANK_IMAGE_URL = 'extjs/resources/images/default/s.gif'; // nsb stands for NOT SUPPORTED BROWSER nsb = (Ext.isIE6 || Ext.isIE7); /* * Themes for Taolin gui */ themes = [ ['tp', 'Tp (default)'], //['access', 'Access'], //['aero', 'Aero'], ['blue', 'Blue'], ['blueen', 'Blueen'], ['gray', 'Gray'], //['galdaka', 'Galdaka'], ['indigo', 'Indigo'], ['midnight', 'Midnight'], ['purple', 'Purple'], ['silverCherry', 'Silver Cherry'], ['slate', 'Slate'], ['slickness', 'Slickness'], ['human', 'Ubuntu'], ['vista', 'Vista'] ]; //Ext.onReady( function application_init(){ if(typeof user.theme == 'string') changeExtTheme(user.theme); Ext.QuickTips.init(); /* * qtip intercepts tooltip */ var qtip = Ext.QuickTips.getQuickTip(); qtip.interceptTitles = true; eventManager = new Ext.ux.fbk.sonet.EventManager({ name: "taolin-event-manager" ,events: { addcomment: true ,removecomment: true ,newtimelineevent: true ,userphotochange: true ,userprofilechange: true } ,listeners:{ addcomment: function(){ this.fireEvent('newtimelineevent'); } ,removecomment: function(){ this.fireEvent('newtimelineevent'); } ,userphotochange: function(){ this.fireEvent('newtimelineevent'); } ,userprofilechange: function(){ Ext.getCmp('user_edit_profile').form.load(); } } }); config.num_columns = user.number_of_columns; var columns = new Array(), width = 1/config.num_columns; for(var i=0; i< config.num_columns; i++){ columns.push({ columnWidth:width ,style:'padding:20px 10px 20px 10px' }); } // preparing text for Did you know messages var aDyk = ['Did you know that you can <span class="right-element" style="float:none;position:relative;padding:0;"><span class="a add_widgets" onclick="openAddWidgetsModalWindow()"><b>Add widgets</b></span></span>? <span class="right-element" style="float:none;position:relative;padding:0;"><span class="a add_widgets" onclick="openAddWidgetsModalWindow()"><b>Add widgets</b></a></span>.', 'Did you know that you can <span class="a" onclick="expandUserEditProfilePanel()">edit your profile</span>? <span class="a" onclick="expandUserEditProfilePanel()">Edit your profile</span>.', 'Did you know that you can <span class="a" onclick="expandSettingsPanel()">customize your widgets\' theme</span>? <span class="a" onclick="expandSettingsPanel()">Edit your settings</span>.', 'Did you know that you can <span class="a" onclick="expandSettingsPanel()">change the number of columns containing your widgets</span>? <span class="a" onclick="expandSettingsPanel()">Edit your settings</span>.', 'Did you know that you can <span class="a" onclick="expandSettingsPanel()">personalize '+config.appname+' background?</span>? <span class="a" onclick="expandSettingsPanel()">Edit your settings</span>.', 'Did you know that you can expand fullscreen widgets clicking on <img width=20px height=1px src="'+Ext.BLANK_IMAGE_URL+'" class="x-tool x-tool-maximize" style="vertical-align:bottom;float:none;cursor:default;"/>? ', 'Did you know that you can configure a widget clicking on <img width=20px height=1px src="'+Ext.BLANK_IMAGE_URL+'" class="x-tool x-tool-gear" style="vertical-align:bottom;float:none;cursor:default;"/>? ', 'Did you know that you can minimize your widget clicking on <img width=20px height=1px src="'+Ext.BLANK_IMAGE_URL+'" class="x-tool x-tool-toggle" style="vertical-align:bottom;float:none;cursor:default;"/>? ', 'Did you know that you can remove a widget clicking on <img width=20px height=1px src="'+Ext.BLANK_IMAGE_URL+'" class="x-tool x-tool-close" style="vertical-align:bottom;float:none;cursor:default;"/>? ', 'Did you know that you can move widgets dragging the title bar?', 'Did you know that you can edit your photos? <span class="a" onclick="openImageChooser()">Edit your photo</span>.', 'Did you know that you can add a new photo? <span class="a" onclick="new PhotoUploader()">Edit your photo</span>.', 'Did you know that you can set taolin as your homepage? Read <a href="./pages/make_homepage_help" target="_blank">the instructions</a>!', 'Did you know that you can view other people photos gallery by clicking on one of their photos?', 'Did you know that there is a <a href="./pages/privacy_policy" target="_blank">privacy policy</a> about how your data are used? <a href="./pages/privacy_policy" target="_blank">Read the privacy policy</a>!', 'Did you know that you can edit your workplace and view other\'s on a map? <span class="a" onclick="(new Ext.ux.fbk.sonet.MapWindow({logparams: {source: \'did you know\', user_id:\'\'}})).show()">Edit!</span>', 'Did you know that you can suggest a colleague of yours as new champion on her/his profile?' ]; var dyk = (nsb ? '<a href="http://getfirefox.com" target="_blank">DOWNLOAD AND USE FIREFOX</a> FOR A BETTER, FASTER USER EXPERIENCE!' : aDyk[Math.floor(Math.random()*aDyk.length)] /* pick a random string out of aDyk */); /* * Main menu: * use .header class only for top-level menu voices */ var main_menu = '' ,admin_menu_item = '<li class="header"><span class="a menu-item">Admin portal</span>' + '<ul>' + '<li><span class="menu-item"><a class="sprited help-icon" href="./admin" target="_blank">Admin main</a></span></li>' + '<li><span class="menu-item"><a class="sprited picture" href="./admin/backgrounds" target="_blank">Background</a></span></li>' + '<li><span class="menu-item"><a class="sprited map" href="./admin/buildings" target="_blank">Building</a></span></li>' + '<li><span class="menu-item"><a class="sprited gears" href="./admin/portals/config" target="_blank">Configuration</a></span></li>' + '<li><span class="menu-item"><a class="sprited image-edit" href="./admin/templates" target="_blank">Templates</a></span></li>' + '<li><span class="menu-item"><a class="sprited groups" href="./admin/users" target="_blank">Users</a></span></li>' + '<li><span class="menu-item"><a class="sprited chart-icon" href="./admin/widgets" target="_blank">Widgets</a></span></li>' + '</ul>' + '</li>' ,simple_admin_menu_item = '<li class="header"><a class="menu-item" href="./admin" target="_blank">Admin portal</a></li>'; if(!nsb) main_menu = '<ul class="dd-menu">' + '<li class="header"><span class="a menu-item">Personal profile</span>' + '<ul>' + '<li><span class="a menu-item" onclick="showUserInfo(null, null, {source: \'logout_div\'})"><span class="sprited user-icon">View your profile</span></span></li>' + '<li><span class="a menu-item" onclick="expandUserEditProfilePanel()"><span class="sprited user-edit">Edit your profile</span></span></li>' + '<li><span class="a menu-item" onclick="expandSettingsPanel()"><span class="sprited settings">Edit your settings</span></span></li>' + '<li><span class="a menu-item" onclick="openImageChooser()"><span class="sprited image-edit">Edit your photos</span></span></li>' + '<li><span class="a menu-item" onclick="new Ext.ux.fbk.sonet.MapWindow().show()"><span class="sprited map-edit">Edit your workplace position</span></span></li>' + '</ul>' + '</li>' + '<li class="header"><span class="a menu-item">Tools</span>' + '<ul>' + '<li><span class="menu-item a add_widgets" onclick="openAddWidgetsModalWindow()"><span class="sprited add-icon">Add widgets</span></span></li>' + '<li><span class="a menu-item" onclick="addOrBounceWidget(\'Ext.ux.fbk.sonet.MetaSearch\',\'string_identifier\',{source: \'logout_div\'})"><span class="sprited search">Search</span></span></li>' + '<li><span class="a menu-item" onclick="new Ext.ux.fbk.sonet.MapWindow().show()"><span class="sprited map">Map of colleagues workplaces</span></span></li>' + '<li><span class="a menu-item" onclick="new PhotoUploader()"><span class="sprited upload-picture">Upload a photo</span></a></li>' + '<li><span class="a menu-item" onclick="new SendToWindow()"><span class="sprited email">Send an email</span></span></li>' + '</ul>' + '</li>' + '<li class="header"><a class="menu-item" href="./wiki" target="_blank">FBK Wiki</a></li>' + '<li class="header"><span class="a menu-item" onclick="showMainTimeline()">Timeline</span></li>' + '<li class="header"><span class="a menu-item">Info</span>' + '<ul>' + '<li><a class="menu-item" href="./pages/help" target="_blank">FAQ - Help</a></li>' + '<li><a class="menu-item" href="./pages/privacy_policy" target="_blank">Privacy policy</a></li>' + '</ul>' + '</li>' + '<li class="header"><span class="a menu-item">' + config.appname + '</span>' + '<ul>' + /* This software is open source released under aGPL. See http://www.fsf.org/licensing/licenses/agpl-3.0.html for more details. According to the license, you must place in every Web page served by Taolin a link where your user can download the source code. So, please, don't remove this link, you can move it in another part of the web page, though. */ '<li><a class="menu-item" href="http://github.com/vad/taolin" target="_blank">Download the code</a></li>' + //'<li><a class="menu-item" href="http://github.com/vad/taolin/issues" target="_blank">Report an issue</a></li>' + '</ul>' + '</li>' + (user.admin ? admin_menu_item : '' ) + '<li class="header last"><a class="menu-item" href="./accounts/logout" onclick="jabber.quit()">Logout</a></li>' + '</ul>'; else // Simplified version for old, stupidunsupported browsers main_menu = '<ul class="dd-menu">' + '<li class="header"><span class="a menu-item" onclick="showUserInfo(null, null, {source: \'logout_div\'})">Personal profile</span></li>' + '<li class="header"><span class="menu-item a add_widgets" onclick="openAddWidgetsModalWindow()">Add widgets</span></li>' + '<li class="header"><a class="menu-item" href="./wiki" target="_blank">FBK Wiki</a></li>' + '<li class="header"><span class="a menu-item" onclick="showMainTimeline()">Timeline</span></li>' + '<li class="header"><a class="menu-item" href="./pages/help" target="_blank">FAQ - Help</a></li>' + '<li class="header"><a class="menu-item" href="./pages/privacy_policy" target="_blank">Privacy policy</a></li>' + /* This software is open source released under aGPL. See http://www.fsf.org/licensing/licenses/agpl-3.0.html for more details. According to the license, you must place in every Web page served by Taolin a link where your user can download the source code. So, please, don't remove this link, you can move it in another part of the web page, though. */ '<li class="header"><a class="menu-item" href="http://github.com/vad/taolin" target="_blank">Download the code</a></li>' + (user.admin ? simple_admin_menu_item : '' ) + '<li class="header last"><a class="menu-item" href="./accounts/logout" onclick="jabber.quit()">Logout</a></li>' + '</ul>'; /** * HTML shown in the northern part of the viewport. * It contains: * - FBK logo * - logout menu * - "Did you know?" questions */ var dyk_style = (nsb ? 'color:darkRed;font-weight:bold;font-size:110%;' : (Math.random() > 0.3 ? 'display:none;':'')); var clear_html = '<div id="logout_div" class="right-element">' + main_menu + '</div>' + '<div class="left-element">' + '<img src="'+config.logo+'" qtip="taolin logo" style="padding-left:10px"/>' + '</div>' + '<div id="didyouknow_div" style="'+dyk_style+'"><span id="didyouknow_span"><table class="border_radius_5px"><tr><td style="padding:0 10px;">'+dyk+' <span class="a" onclick="$(\'#didyouknow_div\').hide();" style="margin-left:10px;font-size:x-small;">[close this message]</span></td></tr></table></span></div>'; viewport = new Ext.Viewport({ layout:'border', items:[{ region:'north', id: 'north-panel', border: false, height: 50, style: 'z-index:1', items:[{ html: clear_html ,border: false }] },{ xtype:'portal', region:'center', id:'portal_central', margins:'5 5 5 0', cls:'desktop', bodyStyle: 'padding:0 10px', style: 'z-index:0;', /* Here we define three different column for our portal. If you change the number of * the column please check the database for any inconsistency */ items: columns, // Setting desktop background listeners:{ afterlayout: function(){ var bg = get(user, 'bg', config.background); changeBg(bg); } } }, westPanel] }); /* These functions are invoked when the page is loaded. * getWidgetsPosition retrieves user's widgets and their position * showUserInfo(null, true) fill western-panel */ getWidgetsPosition(); /* Check if there's a valid session */ var task = { run: function(){ Ext.Ajax.request({ url : 'accounts/issessionup', method: 'GET', success: function ( result, request ) { var valid = Ext.util.JSON.decode(result.responseText); if (!valid){ window.location.reload(false); } } }); }, interval: 300000 //5 minutes }; Ext.TaskMgr.start(task); if(!user.privacy_policy_acceptance) // check if first login wizard should be opened or not openFirstLoginWizard(); /** * Menu */ // Styling: add an image (an arrow) at the end of each menu voice that has a sub-menu //$('.dd-menu .header:has(ul)') $('.dd-menu .header') .each(function(){ $(this) .has('ul') .find('.a:first') .append($('<span>') .addClass('sprited arrow-down')) .end() .find('ul') .css('display', 'none') .hide(); } ) .hover( function(){ $(this) .find('.a:first .sprited') .removeClass('arrow-down') .addClass('arrow-up') .end() .find('ul') .css({visibility: 'visible', display: 'none'}) .show(); },function(){ $(this) .find('.a:first .sprited') .removeClass('arrow-up') .addClass('arrow-down') .end() .find('ul') .css('visibility', 'hidden'); } ); } $(document).ready(function(){ $('#jplayer').jPlayer({ oggSupport:true ,swfPath: 'js/jquery/jplayer' }); });
vad/taolin
webroot/js/portal/application.js
JavaScript
agpl-3.0
17,510
/** * Crypto module for Geierlein. * * @author Stefan Siegl * * Copyright (c) 2012 Stefan Siegl <stesie@brokenpipe.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function() { var geierlein = {}; var gzipjs = {}; var forge = {}; if(typeof(window) !== 'undefined') { geierlein = window.geierlein = window.geierlein || {}; gzipjs = window.gzipjs; forge = window.forge; } // define node.js module else if(typeof(module) !== 'undefined' && module.exports) { geierlein = { }; module.exports = geierlein.crypto = {}; gzipjs = require('../gzip-js/lib/gzip.js'); forge = require('../forge/js/forge.js'); } var crypto = geierlein.crypto = geierlein.crypto || {}; /** * The X.509 certificate with the Elster project's public key. * * The public key is used to encrypt the tax case. */ var elsterPem = '-----BEGIN CERTIFICATE-----\n' + 'MIIDKjCCAhICAQAwDQYJKoZIhvcNAQEEBQAwWTELMAkGA1UEBhMCREUxDzANBgNV\n' + 'BAoTBkVMU1RFUjEMMAoGA1UECxMDRUJBMQ8wDQYDVQQDEwZDb2RpbmcxGjAYBgNV\n' + 'BAUTETIwMDMwOTMwMTQzMzIzeDAwMCIYDzIwMDMwMTAxMDAwMDAwWhgPMjAwOTEy\n' + 'MzEyMzU5NTlaMFkxCzAJBgNVBAYTAkRFMQ8wDQYDVQQKEwZFTFNURVIxDDAKBgNV\n' + 'BAsTA0VCQTEPMA0GA1UEAxMGQ29kaW5nMRowGAYDVQQFExEyMDAzMDkzMDE0MzMy\n' + 'M3gwMDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAIKjQAK3+1WlW6Az\n' + 'bp5C0UISN7+H7KFydsH3xvmvtVHV2XpAlQJxpMt3APH1NzSAmsz7FQlsVPYcTqgd\n' + 'tzwd6s/2bINLm/owNXTjCNRjmf2NLI2cTe9Gq+ovcujFVxVLO1IYjEpj6K09KJc4\n' + 'e9F+LTyJujaRg/W/cSY7aBwPhv/+1o49IoG7nXSwmpMp6CyRZwCVT26RbVAuTJ2R\n' + 'fmDgSmcc5Tostd/gQGSwVcreElrrN2LJM2MP5xDzP5tTQGmB8tMFwEYa7otPuhjF\n' + 'eV5ry3GSlgrFqUdt8JaZ03WQD2dbPZYbNGUvuzb4GebuEdnKCwRrOiGG6bUCx8Qk\n' + 'xXy6sMsCAwEAATANBgkqhkiG9w0BAQQFAAOCAQEABu72l9QUIng2n08p5uzffJA2\n' + 'Zx04ZfKWC+dBJB6an03ax8YqxUPm+e83D341NQtLlgJ4qKn9ShNZW85YoL/I02mU\n' + '/sj50O4NAX72RwzHe/rPi+sS5BU5p4fi8YL+xN00r8R+Mbqctg8QJXleMmvuS/JF\n' + 'qB8F9m72Ud9kmZsV1Letl/qog0El4QHNnU9rSoI+MpchfDaoGvdqoVa+729SEBlc\n' + 'agWaHE8RNF43+aaVZQScvuwQZBrTJq2kqKmPm4Kg7GYuIGMqrm2/g0ldRrm8KfI2\n' + 'vxZIknBdmDknjnQHGMuLXmV3HKZTeN1F6I9BgmBXXqzTJu4gEDpY5n/h7mM+bA==\n' + '-----END CERTIFICATE-----'; /** * The Elster project's X.509 certificate as a Forge PKI instance. */ var elsterCert = forge.pki.certificateFromPem(elsterPem); /** * Perform whole encoding process of one XML piece as required by Elster specs. * * This is, take the provided data, GZIP it, encrypt it with DES3-EDE & RSA, * encode the DER encoding of the resulting PKCS#7 enveloped document with * Base64 and return it. * * @param {string} data The data block to encode. * @param {object} key The key to use to encrypt the data (as a Forge buffer) * @return {string} Base64-encoded result. */ crypto.encryptBlock = function(data, key) { // gzip data var out = gzipjs.zip(data, { level: 9 }); out = gzipjs.charArrayToString(out); out = forge.util.createBuffer(out); // encrypt data var p7 = forge.pkcs7.createEnvelopedData(); p7.addRecipient(elsterCert); p7.content = out; p7.encrypt(key.copy(), forge.pki.oids['des-EDE3-CBC']); // convert to base64 out = forge.asn1.toDer(p7.toAsn1()); return forge.util.encode64(out.getBytes(), 0); }; /** * Decrypt all the encoded parts of a response document from Elster the servers. * * This function performs the full decoding process, i.e. it decrypts the * PKCS#7 encrypted data blocks and unzips them. * * @param {string} data The XML document. * @param {object} key A Forge buffer containing the decryption key. */ crypto.decryptDocument = function(data, key) { function decryptBlock(regex) { var pieces = data.split(regex); if(pieces.length !== 5) { return; } var encBlock = pieces[2].replace(/[\r\n]*/g, ''); if(encBlock === '') { /* On error <DatenTeil> is in some cases returned empty. */ return; } /* Base64-decode block, result is DER-encoded PKCS#7 encrypted data. */ encBlock = forge.util.decode64(encBlock); /* Convert to Forge ASN.1 object. */ encBlock = forge.asn1.fromDer(encBlock); /* Convert to Forge PKCS#7 object. */ var p7 = forge.pkcs7.messageFromAsn1(encBlock); p7.decrypt(key.copy()); /* Covert Forge buffer to gzipJS buffer (array of bytes). */ var gzippedData = []; while(!p7.content.isEmpty()) { gzippedData.push(p7.content.getByte()); } /* Gunzip and replace back into pieces. */ pieces[2] = gzipjs.charArrayToString(gzipjs.unzip(gzippedData)); /* Join pieces together again. */ data = pieces.join(''); } decryptBlock(/(<\/?DatenLieferant>)/); decryptBlock(/(<\/?DatenTeil>)/); return data; }; /** * Generate a key suitable for encryptBlock function. * * @return {object} A new random DES3 key as a Forge buffer. */ crypto.generateKey = function() { return forge.util.createBuffer(forge.random.getBytes(24)); }; })();
vog/geierlein
chrome/content/lib/geierlein/crypto.js
JavaScript
agpl-3.0
5,912
/** * @file tools.js * @brief Used by cutes agent to invoke async actions * @copyright (C) 2014 Jolla Ltd. * @par License: LGPL 2.1 http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html */ var make_system_action = function(name) { return function() { var subprocess = require("subprocess"); subprocess.check_call("sailfish_tools_system_action", [name]); }; }; exports.removeBackups = function(msg, ctx) { var os = require("os"); var home = os.home(); if (!os.path.isDir(home)) error.raise({message: "No home directory " + home}); os.rmtree(os.path(home, ".vault")); }; exports.cleanRpmDb = make_system_action("repair_rpm_db"); exports.cleanTrackerDb = function(msg, ctx) { var os = require("os"); os.system("tracker-control", ["-krs"]); }; exports.restartKeyboard = function(msg, ctx) { var os = require("os"); os.system("systemctl", ["--user", "restart", "maliit-server.service"]); }; exports.isAndroidControlNeeded = function(msg, ctx) { var os = require("os"); var rc = os.system("rpm", ["-q", "aliendalvik"]); return (rc === 0 && os.system("rpm", ["-q", "apkd-android-settings"]) !== 0); }; exports.restartAlien = make_system_action("restart_dalvik"); exports.stopAlien = make_system_action("stop_dalvik"); exports.restartNetwork = make_system_action("restart_network"); exports.restartLipstick = make_system_action("restart_lipstick"); exports.restartDevice = make_system_action("restart_device"); exports.toggleSensors = make_system_action("toggle_sensors");
alinelena/sailfish-utilities
qml/tools.js
JavaScript
lgpl-2.1
1,566
var path = require('path') var utils = require('./utils') var config = require('../config') var vueLoaderConfig = require('./vue-loader.conf') function resolve (dir) { return path.join(__dirname, '..', dir) } module.exports = { entry: { app: './src/main.js' }, output: { path: config.build.assetsRoot, filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath }, resolve: { extensions: ['.js', '.vue', '.json'], alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src') } }, module: { rules: [ { test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', include: [resolve('src'), resolve('test')], options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.vue$/, loader: 'vue-loader', options: vueLoaderConfig }, { test: /\.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test')] }, { test: /\.scss$/, loaders: ["style-loader", "css-loader", "sass-loader"] }, { test: /\.(png|jpe?g|gif|svg)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, // name: utils.assetsPath('img/[name].[hash:7].[ext]') name: utils.assetsPath('img/[name].[ext]') } }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/, loader: 'url-loader', options: { limit: 10000, name: utils.assetsPath('fonts/[name].[hash:7].[ext]') } } ] } }
changxiao/guessTea
build/webpack.base.conf.js
JavaScript
lgpl-2.1
1,709
var slidedelay = $('#bannerslider').attr('data-delay'); var pauseonhover = $('#bannerslider').attr('data-pause'); var fadedelay = 2000; $(document).ready(function() { if ($('#bannerslider').hasClass("slide") && $('#bannerslider').hasClass("carousel")) { $('#bannerslider').carousel({ interval: slidedelay, pause: '"' + pauseonhover + '"' }); } else if ($('#bannerslider').hasClass("slide") && $('#imageContainer').children().length>1) { $('#imageContainer').children(':first-child').addClass("showbanner"); setTimeout(nextSlide, slidedelay); } }); function nextSlide() { var images = $('#imageContainer').children(); $(images).each( function(i) { if ($(this).hasClass("showbanner")) { $(this).fadeOut(fadedelay).removeClass("showbanner"); var nextIndex = (i == (images.length - 1)) ? 0 : i+1; $(images[nextIndex]).fadeIn(fadedelay).addClass("showbanner"); setTimeout(nextSlide, slidedelay); return false } }); }
JojoCMS-Plugins/jojo_bannerimage
js/functions.js
JavaScript
lgpl-2.1
1,098
var searchData= [ ['querybuilder_3034',['QueryBuilder',['../classCqrs_1_1Repositories_1_1Repository_a4447451b7dbcfcd68dfa3fa65a41f357.html#a4447451b7dbcfcd68dfa3fa65a41f357',1,'Cqrs::Repositories::Repository']]], ['querypredicate_3035',['QueryPredicate',['../classCqrs_1_1Azure_1_1BlobStorage_1_1Test_1_1Integration_1_1TestQueryStrategy_ab2a9657b5f1ce73aa3f807dd069c3d30.html#ab2a9657b5f1ce73aa3f807dd069c3d30',1,'Cqrs.Azure.BlobStorage.Test.Integration.TestQueryStrategy.QueryPredicate()'],['../interfaceCqrs_1_1Repositories_1_1Queries_1_1IQueryStrategy_ab36e17425ab9940bfa4f104e7f321b90.html#ab36e17425ab9940bfa4f104e7f321b90',1,'Cqrs.Repositories.Queries.IQueryStrategy.QueryPredicate()'],['../classCqrs_1_1Repositories_1_1Queries_1_1QueryStrategy_a45d9ad6895a7e8c404ea64abab5242ec.html#a45d9ad6895a7e8c404ea64abab5242ec',1,'Cqrs.Repositories.Queries.QueryStrategy.QueryPredicate()']]], ['querystrategy_3036',['QueryStrategy',['../interfaceCqrs_1_1Repositories_1_1Queries_1_1IQueryWithStrategy_a48ee82d7f6ff31e0ce25c09184982e34.html#a48ee82d7f6ff31e0ce25c09184982e34',1,'Cqrs.Repositories.Queries.IQueryWithStrategy.QueryStrategy()'],['../classCqrs_1_1Repositories_1_1Queries_1_1ResultQuery_abad7775345c741c688bab2ec4671ba6b.html#abad7775345c741c688bab2ec4671ba6b',1,'Cqrs.Repositories.Queries.ResultQuery.QueryStrategy()']]], ['queuecount_3037',['QueueCount',['../classCqrs_1_1Azure_1_1ServiceBus_1_1AzureQueuedCommandBusReceiver_a30d135cecfbd6f542a54d50a91448b45.html#a30d135cecfbd6f542a54d50a91448b45',1,'Cqrs.Azure.ServiceBus.AzureQueuedCommandBusReceiver.QueueCount()'],['../classCqrs_1_1Azure_1_1ServiceBus_1_1AzureQueuedEventBusReceiver_a5e71c388c0c0a40f29fc70091d24cc9a.html#a5e71c388c0c0a40f29fc70091d24cc9a',1,'Cqrs.Azure.ServiceBus.AzureQueuedEventBusReceiver.QueueCount()'],['../classCqrs_1_1Bus_1_1QueuedCommandBusReceiver_aefae09fd32d799ac59d35eb706f76654.html#aefae09fd32d799ac59d35eb706f76654',1,'Cqrs.Bus.QueuedCommandBusReceiver.QueueCount()']]], ['queuenames_3038',['QueueNames',['../classCqrs_1_1Azure_1_1ServiceBus_1_1AzureQueuedCommandBusReceiver_a6a91089b303fc630cc6ddc4aba538259.html#a6a91089b303fc630cc6ddc4aba538259',1,'Cqrs.Azure.ServiceBus.AzureQueuedCommandBusReceiver.QueueNames()'],['../classCqrs_1_1Azure_1_1ServiceBus_1_1AzureQueuedEventBusReceiver_ac35217e6991a4f7aacb5b41e16b7f2f7.html#ac35217e6991a4f7aacb5b41e16b7f2f7',1,'Cqrs.Azure.ServiceBus.AzureQueuedEventBusReceiver.QueueNames()'],['../classCqrs_1_1Bus_1_1QueuedCommandBusReceiver_a959facef20063d615b427eafa4290e0f.html#a959facef20063d615b427eafa4290e0f',1,'Cqrs.Bus.QueuedCommandBusReceiver.QueueNames()']]], ['queuetracker_3039',['QueueTracker',['../classCqrs_1_1Azure_1_1ServiceBus_1_1AzureQueuedCommandBusReceiver_ab74357ae0032073a6a006b47b45e8da7.html#ab74357ae0032073a6a006b47b45e8da7',1,'Cqrs.Azure.ServiceBus.AzureQueuedCommandBusReceiver.QueueTracker()'],['../classCqrs_1_1Azure_1_1ServiceBus_1_1AzureQueuedEventBusReceiver_ace1c7e32bb4a637570a7195656333fb6.html#ace1c7e32bb4a637570a7195656333fb6',1,'Cqrs.Azure.ServiceBus.AzureQueuedEventBusReceiver.QueueTracker()'],['../classCqrs_1_1Bus_1_1QueuedCommandBusReceiver_a2fc62989429929acd8ea66808a8c4a78.html#a2fc62989429929acd8ea66808a8c4a78',1,'Cqrs.Bus.QueuedCommandBusReceiver.QueueTracker()']]], ['queuetrackerlock_3040',['QueueTrackerLock',['../classCqrs_1_1Azure_1_1ServiceBus_1_1AzureQueuedCommandBusReceiver_a76aa14e4143c81310c69769267920f7d.html#a76aa14e4143c81310c69769267920f7d',1,'Cqrs.Azure.ServiceBus.AzureQueuedCommandBusReceiver.QueueTrackerLock()'],['../classCqrs_1_1Azure_1_1ServiceBus_1_1AzureQueuedEventBusReceiver_ae08c6646d7e3c064f594c18702e8ebaa.html#ae08c6646d7e3c064f594c18702e8ebaa',1,'Cqrs.Azure.ServiceBus.AzureQueuedEventBusReceiver.QueueTrackerLock()'],['../classCqrs_1_1Bus_1_1QueuedCommandBusReceiver_ac633e2d140fc90fab100acba4afa136b.html#ac633e2d140fc90fab100acba4afa136b',1,'Cqrs.Bus.QueuedCommandBusReceiver.QueueTrackerLock()']]] ];
Chinchilla-Software-Com/CQRS
wiki/docs/4.2/html/search/properties_10.js
JavaScript
lgpl-2.1
3,938
var dir_d5c97c2750cda5d5e748b76e78cc7d4b = [ [ "Masking.cu", "_masking_8cu.html", "_masking_8cu" ] ];
HZDR-FWDF/RISA
docs/dir_d5c97c2750cda5d5e748b76e78cc7d4b.js
JavaScript
lgpl-3.0
105
'use strict'; /** * @ngdoc service * @name ortolangMarketApp.STATIC_WEBSITE_FR * @description * # STATIC_WEBSITE_FR * Constant in the ortolangMarketApp. */ angular.module('ortolangMarketApp') .constant('STATIC_WEBSITE_FR', { STATIC_WEBSITE: { PATH: { LEGAL_NOTICES: 'common/static-website/fr/legal-notices.html' }, ALL_THE_NEWS: 'Toutes les actualités...', USERS: '{{::stat}} utilisateurs', WORKSPACES: '{{::stat}} ressources', DATA: '{{::stat | bytes}} de données', FILES: '{{::stat | numbers:"fr"}} fichiers', LEGAL_NOTICES: { TITLE: 'Mentions Légales', INFO_PUBLICATION: 'Informations de publication', PUBLICATION_DIRECTOR: 'Directeur de la publication', SECONDARY_DIRECTOR: 'Directeurs adjoints', IT_MANAGER: 'Responsable informatique', IT_DEVELOPMENT: 'Développement informatique', PERSONNAL_DATA: 'Données personnelles', PERSONNAL_DATA_CONTENT_1 : 'Conformément à la Loi Informatique et Libertés, nous vous informons que la collecte de données personnelles associée à ce site est en cours de déclaration auprès de la CNIL. A aucun moment ces informations ne sont transmises à un tiers.', PERSONNAL_DATA_CONTENT_2 : 'Vous bénéficiez d\'un droit d\'accès et de rectification aux informations qui vous concernent. Si vous souhaitez exercer ce droit et obtenir communication des informations vous concernant, veuillez adresser un courrier à ATILF, 44, avenue de la libération, 54063 Nancy Cedex - France, en joignant une photocopie de votre carte d\'identité. Afin de répondre à votre demande, merci de nous fournir quelques indications (identifiant ORTOLANG) et d\'indiquer un numéro de téléphone pour vous joindre.', TERMS_OF_USE: 'Conditions générales d’utilisation', USAGE_RULES: 'Règles de bonne conduite', LIABILITY_DISCLAIMER: 'Clause de non-responsabilité', LIABILITY_DISCLAIMER_CONTENT: 'La responsabilité du CNRS et des partenaires ORTOLANG ne peut, en aucune manière, être engagée quant au contenu des informations figurant sur ce site ou aux conséquences pouvant résulter de leur utilisation ou interprétation.', INTELLECTUAL_PROPERTY: 'Propriété intellectuelle', INTELLECTUAL_PROPERTY_CONTENT: 'Le site de ORTOLANG est une oeuvre de création, propriété exclusive du CNRS, protégé par la législation française et internationale sur le droit de la propriété intellectuelle. Aucune reproduction ou représentation ne peut être réalisée en contravention avec les droits du CNRS issus de la législation susvisée.', HYPERLINKS: 'Liens hypertextes', HYPERLINKS_CONTENT: 'La mise en place de liens hypertextes par des tiers vers des pages ou des documents diffusés sur le site de ORTOLANG, est autorisée sous réserve que les liens ne contreviennent pas aux intérêts des partenaires du projet ORTOLANG, et, qu’ils garantissent la possibilité pour l’utilisateur d’identifier l’origine et l’auteur du document.', CONFIDENTIALITY: 'Politique de confidentialité', COOKIES_USE: 'Utilisation des cookies', COOKIES_USE_CONTENT: 'Le site de ORTOLANG utilise des cookies afin de réaliser des statistiques d\'audiences anonymes uniquement destinées à un usage interne. Ces statistiques sont réalisées grâce au logiciel libre et open source de mesure de statistiques web <a href="https://fr.piwik.org/" target="_blank">Piwik</a> hébergé sur nos propres serveur.', DO_NOT_TRACK: 'Ne pas autoriser à suivre mes visites', DO_NOT_TRACK_CONTENT: '<ul><li>Si la fonction "Ne pas me pister" ("Do No Track" en anglais) de votre navigateur est activée, notre outil d\'analyse web n\'enregistrera pas votre activité sur notre site.</li><li>Vous avez également la possibilité de demander à ne pas être suivi ci-dessous :</li></ul>', DO_NOT_TRACK_ACTUAL_CONFIG: 'Configuration actuelle :' } } });
Ortolang/market
src/main/webapp/static/app/common/static-website/i18n/static-website.fr.js
JavaScript
lgpl-3.0
4,289
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import { translate } from '../../../helpers/l10n'; const EmptyOverview = ({ component }) => { return ( <div className="page page-limited"> <div className="alert alert-warning"> {translate('provisioning.no_analysis')} </div> <div className="big-spacer-top"> <h4>{translate('key')}</h4> <code>{component.key}</code> </div> </div> ); }; export default EmptyOverview;
lbndev/sonarqube
server/sonar-web/src/main/js/apps/overview/components/EmptyOverview.js
JavaScript
lgpl-3.0
1,296
/** * Copyright (C) 2005-2016 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ /** * This widget can be used to group menu items within a popup menu such as an [AlfMenuBarPopup]{@link module:alfresco/menus/AlfMenuBarPopup} * or a [AlfCascadingMenu]{@link module:alfresco/menus/AlfCascadingMenu}. When an item is added to any [AlfMenuGroups]{@link module:alfresco/menus/AlfMenuGroups} * popup such as in those widgets then a new instance will automatically be wrapped any child widget that is not in a group. * * @module alfresco/menus/AlfMenuGroup * @extends module:alfresco/menus/AlfDropDownMenu * @mixes module:alfresco/core/Core * @mixes module:alfresco/core/CoreRwd * @author Dave Draper */ define(["dojo/_base/declare", "dojo/text!./templates/AlfMenuGroup.html", "alfresco/core/Core", "alfresco/menus/AlfDropDownMenu", "alfresco/core/CoreRwd", "dojo/_base/event", "dojo/dom-style", "dojo/dom-class", "dojo/keys", "dijit/popup", "dojo/string"], function(declare, template, AlfCore, AlfDropDownMenu, CoreRwd, event, domStyle, domClass, keys, popup, string) { return declare([AlfDropDownMenu, AlfCore, CoreRwd], { // TODO: There's an argument that this should actually extend (rather than wrap) the DropDownMenu to avoid needing to delegate the functions /** * The HTML template to use for the widget. * @instance * @type {string} */ templateString: template, /** * An array of the CSS files to use with this widget. * * @instance * @type {object[]} * @default [{cssFile:"./css/AlfMenuGroup.css"}] */ cssRequirements: [{cssFile:"./css/AlfMenuGroup.css"}], /** * The label for the group. If this is left as the empty string then the group label node will be * hidden completely. The value assigned to label can either be an i18n property key or a value * but an attempt will be made to look up the assigned value in the available i18n keys. * * @instance * @type {string} * @default */ label: "", /** * @instance */ constructor: function alfresco_menus_AlfMenuGroup__constructor(/*jshint unused:false*/args) { this.templateString = string.substitute(template, { ddmTemplateString: AlfDropDownMenu.prototype.templateString}); }, /** * Sets the group label and creates a new alfresco/menus/AlfDropDownMenu to contain the items * in the group. * * @instance */ postCreate: function alfresco_menus_AlfMenuGroup__postCreate() { if (this.label === "") { // If there is no label for the title then hide the title node entirely... domStyle.set(this._groupTitleNode, "display", "none"); } else { // Make sure that an attempt is made to get the localized label... this.label = this.message(this.label); this._groupTitleNode.innerHTML = this.encodeHTML(this.label); } if(this.additionalCssClasses) { domClass.add(this._containerNode, this.additionalCssClasses); } // Setup the Drop down menu as normal... this.inherited(arguments); }, /** * * @instance */ isFocusable: function alfresco_menus_AlfMenuGroup__isFocusable() { return this.hasChildren(); }, /** * Overrides the inherited function in order to address the additional Alfesco object * placed in the chain between the Dojo menu objects. * * @instance * @param {object} evt */ _onRightArrow: function(evt){ if(this.focusedChild && this.focusedChild.popup && !this.focusedChild.disabled) { // This first block is identical to that of the inherited function... this.alfLog("log", "Open cascading menu"); this._moveToPopup(evt); } else { // Find the top menu and focus next in it... this.alfLog("log", "Try and find a menu bar in the stack and move to next"); var menuBarAncestor = this.findMenuBarAncestor(this.getParent()); if (menuBarAncestor) { var next = menuBarAncestor._getNextFocusableChild(menuBarAncestor.focusedChild, 1); if (next) { this.alfLog("log", "Go to next item in menu bar"); menuBarAncestor.focusChild(next); } } } }, /** * Overrides the inherited function in order to address the additional Alfesco object * placed in the chain between the Dojo menu objects. * * @instance * @param {object} evt */ _onLeftArrow: function(evt) { if(this.getParent().parentMenu && !this.getParent().parentMenu._isMenuBar) { this.alfLog("log", "Close cascading menu"); this.getParent().parentMenu.focusChild(this.getParent().parentMenu.focusedChild); popup.close(this.getParent()); } else { var menuBarAncestor = this.findMenuBarAncestor(this.getParent()); if (menuBarAncestor) { var prev = menuBarAncestor._getNextFocusableChild(menuBarAncestor.focusedChild, -1); if (prev) { this.alfLog("log", "Focus previous item in menu bar"); menuBarAncestor.focusChild(prev, true); } } else { evt.stopPropagation(); evt.preventDefault(); } } }, /** * This function will work up the stack of menus to find the first menu bar in the stack. This * is required because of the additional grouping capabilities that have been added to the basic * Dojo menu widgets. In the core Dojo code the "parentMenu" attribute is used to work up the stack * but not all widgets in the Alfresco menu stack have this attribute (and it was not possible to * set it correctly during the widget processing phase). * * @instance * @return Either null if a menu bar cannot be found or a menu bar widget. */ findMenuBarAncestor: function alfresco_menus_AlfMenuGroup__findMenuBarAncestor(currentMenu) { var reachedMenuTop = false; while (!reachedMenuTop && !currentMenu._isMenuBar) { if (currentMenu.parentMenu) { // The current menu item has a parent menu item - assign it as the current menu... currentMenu = currentMenu.parentMenu; } else { // Go up the widget stack until we either run out of ancestors or find another parent menu... var parent = currentMenu.getParent(); while (parent && !parent.parentMenu) { parent = parent.getParent(); } if (parent && parent.parentMenu) { currentMenu = parent.parentMenu; } reachedMenuTop = (parent == null); } } var menuBar = (currentMenu._isMenuBar) ? currentMenu : null; return menuBar; }, /** * Added to support use in context menus * * @instance * @param {boolean} bool */ _setSelected: function alfresco_menus_AlfMenuGroup___setSelected(/*jshint unused:false*/bool) { this._selected = true; } }); });
jphuynh/Aikau
aikau/src/main/resources/alfresco/menus/AlfMenuGroup.js
JavaScript
lgpl-3.0
8,563
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import _ from 'underscore'; import Backbone from 'backbone'; export default Backbone.Model.extend({ idAttribute: 'key', defaults: { _hidden: false, _system: false }, _matchAttribute: function (attr, query) { var value = this.get(attr) || ''; return value.search(new RegExp(query, 'i')) !== -1; }, match: function (query) { return this._matchAttribute('name', query) || this._matchAttribute('category', query) || this._matchAttribute('description', query); }, _action: function (options) { var that = this; var opts = _.extend({}, options, { type: 'POST', data: { key: this.id }, beforeSend: function () { // disable global ajax notifications }, success: function () { options.success(that); }, error: function (jqXHR) { that.set({ _status: 'failed', _errors: jqXHR.responseJSON.errors }); } }); var xhr = Backbone.ajax(opts); this.trigger('request', this, xhr); return xhr; }, install: function () { return this._action({ url: baseUrl + '/api/plugins/install', success: function (model) { model.set({ _status: 'installing' }); } }); }, update: function () { return this._action({ url: baseUrl + '/api/plugins/update', success: function (model) { model.set({ _status: 'installing' }); } }); }, uninstall: function () { return this._action({ url: baseUrl + '/api/plugins/uninstall', success: function (model) { model.set({ _status: 'uninstalling' }); } }); } });
joansmith/sonarqube
server/sonar-web/src/main/js/apps/update-center/plugin.js
JavaScript
lgpl-3.0
2,481
/** * jQuery Selective v0.3.5 * https://github.com/amazingSurge/jquery-selective * * Copyright (c) amazingSurge * Released under the LGPL-3.0 license */ import $$1 from 'jquery'; /*eslint no-empty-function: "off"*/ var DEFAULTS = { namespace: 'selective', buildFromHtml: true, closeOnSelect: false, local: null, selected: null, withSearch: false, searchType: null, //'change' or 'keyup' ajax: { work: false, url: null, quietMills: null, loadMore: false, pageSize: null }, query: function() {}, //function(api, search_text, page) {}, tpl: { frame: function() { return `<div class="${this.namespace}"><div class="${this.namespace}-trigger">${this.options.tpl.triggerButton.call(this)}<div class="${this.namespace}-trigger-dropdown"><div class="${this.namespace}-list-wrap">${this.options.tpl.list.call(this)}</div></div></div>${this.options.tpl.items.call(this)}</div>`; }, search: function() { return `<input class="${this.namespace}-search" type="text" placeholder="Search...">`; }, select: function() { return `<select class="${this.namespace}-select" name="${this.namespace}" multiple="multiple"></select>`; }, optionValue: function(data) { if('name' in data) { return data.name; } return data; }, option: function(content) { return `<option value="${this.options.tpl.optionValue.call(this)}">${content}</option>`; }, items: function() { return `<ul class="${this.namespace}-items"></ul>`; }, item: function(content) { return `<li class="${this.namespace}-item">${content}${this.options.tpl.itemRemove.call(this)}</li>`; }, itemRemove: function() { return `<span class="${this.namespace}-remove">x</span>`; }, triggerButton: function() { return `<div class="${this.namespace}-trigger-button">Add</div>`; }, list: function() { return `<ul class="${this.namespace}-list"></ul>`; }, listItem: function(content) { return `<li class="${this.namespace}-list-item">${content}</li>`; } }, onBeforeShow: null, onAfterShow: null, onBeforeHide: null, onAfterHide: null, onBeforeSearch: null, onAfterSearch: null, onBeforeSelected: null, onAfterSelected: null, onBeforeUnselect: null, onAfterUnselect: null, onBeforeItemRemove: null, onAfterItemRemove: null, onBeforeItemAdd: null, onAfterItemAdd: null }; class Options { constructor(instance) { this.instance = instance; } getOptions() { this.instance.$options = this.instance.$select.find('option'); return this.instance.$options; } select(opt) { $(opt).prop('selected', true); return this.instance; } unselect(opt) { $(opt).prop('selected', false); return this.instance; } add(data) { /*eslint consistent-return: "off"*/ if (this.instance.options.buildFromHtml === false && this.instance.getItem('option', this.instance.$select, this.instance.options.tpl.optionValue(data)) === undefined) { const $option = $(this.instance.options.tpl.option.call(this.instance, data)); this.instance.setIndex($option, data); this.instance.$select.append($option); return $option; } } remove(opt) { $(opt).remove(); return this.instance; } } class List { constructor(instance) { this.instance = instance; } build(data) { const $list = $('<ul></ul>'); const $options = this.instance._options.getOptions(); if (this.instance.options.buildFromHtml === true) { if ($options.length !== 0) { $.each($options, (i, n) => { const $li = $(this.instance.options.tpl.listItem.call(this.instance, n.text)); const $n = $(n); this.instance.setIndex($li, $n); if ($n.attr('selected') !== undefined) { this.instance.select($li); } $list.append($li); }); } } else if (data !== null) { $.each(data, i => { const $li = $(this.instance.options.tpl.listItem.call(this.instance, data[i])); this.instance.setIndex($li, data[i]); $list.append($li); }); if ($options.length !== 0) { $.each($options, (i, n) => { const $n = $(n); const li = this.instance.getItem('li', $list, this.instance.options.tpl.optionValue($n.data('selective_index'))); if (li !== undefined) { this.instance._list.select(li); } }); } } this.instance.$list.append($list.children('li')); return this.instance; } buildSearch() { if (this.instance.options.withSearch === true) { this.instance.$triggerDropdown.prepend(this.instance.options.tpl.search.call(this.instance)); this.instance.$search = this.instance.$triggerDropdown.find(`.${this.instance.namespace}-search`); } return this.instance; } select(obj) { this.instance._trigger("beforeSelected"); $(obj).addClass(`${this.instance.namespace}-selected`); this.instance._trigger("afterSelected"); return this.instance; } unselect(obj) { this.instance._trigger("beforeUnselected"); $(obj).removeClass(`${this.instance.namespace}-selected`); this.instance._trigger("afterUnselected"); return this.instance; } click() { const that = this; this.instance.$list.on('click', 'li', function() { const $this = $(this); if (!$this.hasClass(`${that.instance.namespace}-selected`)) { that.instance.select($this); } }); } filter(val) { $.expr[':'].Contains = (a, i, m) => jQuery(a).text().toUpperCase().includes(m[3].toUpperCase()); if (val) { this.instance.$list.find(`li:not(:Contains(${val}))`).slideUp(); this.instance.$list.find(`li:Contains(${val})`).slideDown(); } else { this.instance.$list.children('li').slideDown(); } return this.instance; } loadMore() { const pageMax = this.instance.options.ajax.pageSize || 9999; this.instance.$listWrap.on('scroll.selective', () => { if (pageMax > this.instance.page) { const listHeight = this.instance.$list.outerHeight(true); const wrapHeight = this.instance.$listWrap.outerHeight(); const wrapScrollTop = this.instance.$listWrap.scrollTop(); const below = listHeight - wrapHeight - wrapScrollTop; if (below === 0) { this.instance.options.query(this.instance, this.instance.$search.val(), ++this.instance.page); } } }); return this.instance; } loadMoreRemove() { this.instance.$listWrap.off('scroll.selective'); return this.instance; } } class Search { constructor(instance) { this.instance = instance; } change() { this.instance.$search.change(() => { this.instance._trigger("beforeSearch"); if (this.instance.options.buildFromHtml === true) { this.instance._list.filter(this.instance.$search.val()); } else if (this.instance.$search.val() !== '') { this.instance.page = 1; this.instance.options.query(this.instance, this.instance.$search.val(), this.instance.page); } else { this.instance.update(this.instance.options.local); } this.instance._trigger("afterSearch"); }); } keyup() { const quietMills = this.instance.options.ajax.quietMills || 1000; let oldValue = ''; let currentValue = ''; let timeout; this.instance.$search.on('keyup', e => { this.instance._trigger("beforeSearch"); currentValue = this.instance.$search.val(); if (this.instance.options.buildFromHtml === true) { if (currentValue !== oldValue) { this.instance._list.filter(currentValue); } } else if (currentValue !== oldValue || e.keyCode === 13) { window.clearTimeout(timeout); timeout = window.setTimeout(() => { if (currentValue !== '') { this.instance.page = 1; this.instance.options.query(this.instance, currentValue, this.instance.page); } else { this.instance.update(this.instance.options.local); } }, quietMills); } oldValue = currentValue; this.instance._trigger("afterSearch"); }); } bind(type) { if (type === 'change') { this.change(); } else if (type === 'keyup') { this.keyup(); } } } class Items { constructor(instance) { this.instance = instance; } withDefaults(data) { if (data !== null) { $.each(data, i => { this.instance._options.add(data[i]); this.instance._options.select(this.instance.getItem('option', this.instance.$select, this.instance.options.tpl.optionValue(data[i]))); this.instance._items.add(data[i]); }); } } add(data, content) { let $item; let fill; if (this.instance.options.buildFromHtml === true) { fill = content; } else { fill = data; } $item = $(this.instance.options.tpl.item.call(this.instance, fill)); this.instance.setIndex($item, data); this.instance.$items.append($item); } remove(obj) { obj = $(obj); let $li; let $option; if (this.instance.options.buildFromHtml === true) { this.instance._list.unselect(obj.data('selective_index')); this.instance._options.unselect(obj.data('selective_index').data('selective_index')); } else { $li = this.instance.getItem('li', this.instance.$list, this.instance.options.tpl.optionValue(obj.data('selective_index'))); if ($li !== undefined) { this.instance._list.unselect($li); } $option = this.instance.getItem('option', this.instance.$select, this.instance.options.tpl.optionValue(obj.data('selective_index'))); this.instance._options.unselect($option)._options.remove($option); } obj.remove(); return this.instance; } click() { const that = this; this.instance.$items.on('click', `.${this.instance.namespace}-remove`, function() { const $this = $(this); const $item = $this.parents('li'); that.instance.itemRemove($item); }); } } const NAMESPACE$1 = 'selective'; /** * Plugin constructor **/ class Selective { constructor(element, options = {}) { this.element = element; this.$element = $$1(element).hide() || $$1('<select></select>'); this.options = $$1.extend(true, {}, DEFAULTS, options); this.namespace = this.options.namespace; const $frame = $$1(this.options.tpl.frame.call(this)); //get the select const _build = () => { this.$element.html(this.options.tpl.select.call(this)); return this.$element.children('select'); }; this.$select = this.$element.is('select') === true ? this.$element : _build(); this.$element.after($frame); this.init(); this.opened = false; } init() { this.$selective = this.$element.next(`.${this.namespace}`); this.$items = this.$selective.find(`.${this.namespace}-items`); this.$trigger = this.$selective.find(`.${this.namespace}-trigger`); this.$triggerButton = this.$selective.find(`.${this.namespace}-trigger-button`); this.$triggerDropdown = this.$selective.find(`.${this.namespace}-trigger-dropdown`); this.$listWrap = this.$selective.find(`.${this.namespace}-list-wrap`); this.$list = this.$selective.find(`.${this.namespace}-list`); this._list = new List(this); this._options = new Options(this); this._search = new Search(this); this._items = new Items(this); this._items.withDefaults(this.options.selected); this.update(this.options.local)._list.buildSearch(); this.$triggerButton.on('click', () => { if (this.opened === false) { this.show(); } else { this.hide(); } }); this._list.click(this); this._items.click(this); if (this.options.withSearch === true) { this._search.bind(this.options.searchType); } this._trigger('ready'); } _trigger(eventType, ...params) { let data = [this].concat(params); // event this.$element.trigger(`${NAMESPACE$1}::${eventType}`, data); // callback eventType = eventType.replace(/\b\w+\b/g, (word) => { return word.substring(0, 1).toUpperCase() + word.substring(1); }); let onFunction = `on${eventType}`; if (typeof this.options[onFunction] === 'function') { this.options[onFunction].apply(this, params); } } _show() { $$1(document).on('click.selective', e => { if (this.options.closeOnSelect === true) { if ($$1(e.target).closest(this.$triggerButton).length === 0 && $$1(e.target).closest(this.$search).length === 0) { this._hide(); } } else if ($$1(e.target).closest(this.$trigger).length === 0) { this._hide(); } }); this.$trigger.addClass(`${this.namespace}-active`); this.opened = true; if (this.options.ajax.loadMore === true) { this._list.loadMore(); } return this; } _hide() { $$1(document).off('click.selective'); this.$trigger.removeClass(`${this.namespace}-active`); this.opened = false; if (this.options.ajax.loadMore === true) { this._list.loadMoreRemove(); } return this; } show() { this._trigger("beforeShow"); this._show(); this._trigger("afterShow"); return this; } hide() { this._trigger("beforeHide"); this._hide(); this._trigger("afterHide"); return this; } select($li) { this._list.select($li); const data = $li.data('selective_index'); if (this.options.buildFromHtml === true) { this._options.select(data); this.itemAdd($li, data.text()); } else { this._options.add(data); this._options.select(this.getItem('option', this.$select, this.options.tpl.optionValue(data))); this.itemAdd(data); } return this; } unselect($li) { this._list.unselect($li); return this; } setIndex(obj, index) { obj.data('selective_index', index); return this; } getItem(type, $list, index) { const $items = $list.children(type); let position = ''; for (let i = 0; i < $items.length; i++) { if (this.options.tpl.optionValue($items.eq(i).data('selective_index')) === index) { position = i; } } return position === '' ? undefined : $items.eq(position); } itemAdd(data, content) { this._trigger("beforeItemAdd"); this._items.add(data, content); this._trigger("afterItemAdd"); return this; } itemRemove($li) { this._trigger("beforeItemRemove"); this._items.remove($li); this._trigger("afterItemRemove"); return this; } optionAdd(data) { this._options.add(data); return this; } optionRemove(opt) { this._options.remove(opt); return this; } update(data) { this.$list.empty(); this.page = 1; if (data !== null) { this._list.build(data); } else { this._list.build(); } return this; } destroy() { this.$selective.remove(); this.$element.show(); $$1(document).off('click.selective'); this._trigger('destroy'); } static setDefaults(options) { $$1.extend(true, DEFAULTS, $$1.isPlainObject(options) && options); } } var info = { version:'0.3.5' }; const NAMESPACE = 'selective'; const OtherSelective = $$1.fn.selective; const jQuerySelective = function(options, ...args) { if (typeof options === 'string') { const method = options; if (/^_/.test(method)) { return false; } else if ((/^(get)/.test(method))) { const instance = this.first().data(NAMESPACE); if (instance && typeof instance[method] === 'function') { return instance[method](...args); } } else { return this.each(function() { const instance = $$1.data(this, NAMESPACE); if (instance && typeof instance[method] === 'function') { instance[method](...args); } }); } } return this.each(function() { if (!$$1(this).data(NAMESPACE)) { $$1(this).data(NAMESPACE, new Selective(this, options)); } }); }; $$1.fn.selective = jQuerySelective; $$1.selective = $$1.extend({ setDefaults: Selective.setDefaults, noConflict: function() { $$1.fn.selective = OtherSelective; return jQuerySelective; } }, info);
amazingSurge/jquery-selective
dist/jquery-selective.es.js
JavaScript
lgpl-3.0
16,420
const keystone = require('keystone'); const Types = keystone.Field.Types; const Gallery = new keystone.List('Gallery', { autokey: { path: 'slug', from: 'title', unique: true }, map: { name: 'title' }, defaultSort: 'order' }); Gallery.add({ title: { type: String, required: true }, state: { type: Types.Select, options: 'draft, published', default: 'draft' }, order: { type: Types.Number, format: false }, items: { type: Types.Relationship, ref: 'Gallery item', many: true }, appearance: { type: Types.Select, options: 'grid, carousel, block', default: 'grid'}, description: { type: Types.Textarea } }); Gallery.defaultColumns = 'title, state|20%, order|20%' module.exports = Gallery;
CopenhagenCityArchives/collections-online
plugins/keystone/models/galleries.js
JavaScript
lgpl-3.0
724
isc.VStack.create({ membersMargin: 30, members: [ isc.VStack.create({ membersMargin: 30, members: [ isc.DynamicForm.create({ ID: "filterForm", width: 300, operator: "and", saveOnEnter: true, dataSource: worldDS, submit: function () { filterGrid.filterData(filterForm.getValuesAsCriteria()); }, fields: [ {name: "countryName", title: "Country Name contains", wrapTitle: false, type: "text" }, {type: "blurb", defaultValue: "<b>AND</b>" }, {name: "population", title: "Population smaller than", wrapTitle: false, type: "number", operator: "lessThan" }, {type: "blurb", defaultValue: "<b>AND</b>" }, {name: "independence", title: "Nationhood later than", wrapTitle: false, type: "date", useTextField: true, operator: "greaterThan" } ] }), isc.IButton.create({ title: "Filter", click: function () { filterForm.submit(); } }) ] }), isc.ListGrid.create({ ID: "filterGrid", width:850, height:300, alternateRecordStyles:true, dataSource: worldDS, autoFetchData: true, useAllDataSourceFields: true, fields: [ {name:"countryCode", width: 50}, {name:"government", title:"Government", width: 95}, {name:"independence", title:"Nationhood", width: 100}, {name:"population", title:"Population", width: 100}, {name:"gdp", title:"GDP ($M)", width: 85} ] }) ] });
kylemwhite/isc
isomorphic_11.1p/system/reference/inlineExamples/grids/filtering/advancedFilter.js
JavaScript
lgpl-3.0
2,434
var vueBody = new coreBody({ el: 'body', data : { user : "leasunhy", selectedTab : 'All Questions', currentOrder : 'vote', orders : ['vote', 'view', 'time'], page : 1, tasks : [], searchTerm : '', ckeInit : false, }, ready: function() { $('#taskhall-index-sticky').sticky({ offset: 60 }); $('#taskhall-index-order-dropdown').dropdown(); this.updateTasks(this, false); this.$watch('page', function() { this.updateTasks(this, false); }); this.$watch('selectedTab', function() { this.updateTasks(this, true); }); this.$watch('currentOrder', function() { this.updateTasks(this, true); }); this.$watch('searchTerm', function() { this.updateTasks(this, true); }); this.$watch('tasks', function() { $('.question.author').popup({ inline: true, position: 'right center', width: '300px', }); }); }, computed : { unansweredOnly : function() { return this.selectedTab === 'Unanswered'; } }, methods: { showAskModal : function() { $('#taskhall-index-ask-modal').modal('show'); if (!this.ckeInit) { this.ckeInit = true; CKEDITOR.replace('askcontent'); } }, updateTasks : function(store, resetPage) { if (resetPage) store.page = 1; var url = '/co-dev/list?page=' + store.page + '&order=' + store.currentOrder + '&keyword=' + store.searchTerm + (store.unansweredOnly ? '&unanswered=True' : ''); $.get(url, function(data) { store.tasks = data.tasks; console.log(data); }); $('.taskhall-index.question.item > .question.main > .detail').ellipsis(); $("html, body").animate({ scrollTop: 0 }, "slow"); }, }, });
igemsoftware/SYSU-Software-2015
server/static/js/taskhall/taskhall_index.js
JavaScript
lgpl-3.0
2,207