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
/** * PLEASE DO NOT MODIFY THIS FILE. WORK ON THE ES6 VERSION. * OTHERWISE YOUR CHANGES WILL BE REPLACED ON THE NEXT BUILD. **/ /** * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ ((document, submitForm) => { 'use strict'; // Selectors used by this script const buttonDataSelector = 'data-submit-task'; const formId = 'adminForm'; /** * Submit the task * @param task */ const submitTask = task => { const form = document.getElementById(formId); if (form && task === 'subscriber.batch') { submitForm(task, form); } }; // Register events document.addEventListener('DOMContentLoaded', () => { const button = document.getElementById('batch-submit-button-id'); if (button) { button.addEventListener('click', e => { const task = e.target.getAttribute(buttonDataSelector); submitTask(task); }); } }); })(document, Joomla.submitform);
RomanaBW/BwPostman
src/media/com_bwpostman/js/admin-subscribers-default-batch-footer.es6.js
JavaScript
gpl-3.0
1,041
angular.module('sofa.scrollingShadow', []) .directive('sofaScrollingShadow', function() { 'use strict'; return { restrict: 'A', link: function(scope, $element){ var $topShadow = angular.element('<div class="sofa-scrolling-shadow-top"></div>'), $bottomShadow = angular.element('<div class="sofa-scrolling-shadow-bottom"></div>'), $parent = $element.parent(); $parent .append($topShadow) .append($bottomShadow); var topShadowHeight = $topShadow[0].clientHeight, bottomShadowHeight = $bottomShadow[0].clientHeight; //IE uses scrollTop instead of scrollY var getScrollTop = function(element){ return ('scrollTop' in element) ? element.scrollTop : element.scrollY; }; var updateShadows = function(){ var element = $element[0], scrollTop = getScrollTop(element), clientHeight = element.clientHeight, scrollHeight = element.scrollHeight, scrollBottom = scrollHeight - scrollTop - clientHeight, rollingShadowOffsetTop = 0, rollingShadowOffsetBottom = 0; if (scrollTop < topShadowHeight){ rollingShadowOffsetTop = (topShadowHeight - scrollTop) * -1; } if (scrollBottom < bottomShadowHeight){ rollingShadowOffsetBottom = (bottomShadowHeight - scrollBottom) * -1; } $topShadow.css('top', rollingShadowOffsetTop + 'px'); $bottomShadow.css('bottom', rollingShadowOffsetBottom + 'px'); }; setTimeout(updateShadows, 1); $element.bind('scroll', updateShadows); } }; });
sofa/angular-sofa-scrolling-shadow
src/sofaScrollingShadow.js
JavaScript
gpl-3.0
2,175
/* Copyright 2011 OCAD University Copyright 2010-2011 Lucendo Development Ltd. Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ // Declare dependencies /*global fluid_1_4:true, jQuery*/ // JSLint options /*jslint white: true, funcinvoke: true, continue: true, elsecatch: true, operator: true, jslintok:true, undef: true, newcap: true, regexp: true, bitwise: true, browser: true, forin: true, maxerr: 100, indent: 4 */ var fluid_1_4 = fluid_1_4 || {}; (function ($, fluid) { /** The Fluid "IoC System proper" - resolution of references and * completely automated instantiation of declaratively defined * component trees */ var inCreationMarker = "__CURRENTLY_IN_CREATION__"; // unsupported, non-API function fluid.isFireBreak = function(component) { return component.options && component.options["fluid.visitComponents.fireBreak"]; }; // unsupported, non-API function fluid.visitComponentChildren = function(that, visitor, options, up, down) { options = options || {}; for (var name in that) { var component = that[name]; //Every component *should* have an id, but some clients may not yet be compliant //if (component && component.typeName && !component.id) { // fluid.fail("No id"); //} if (!component || !component.typeName || (component.id && options.visited && options.visited[component.id])) {continue; } if (options.visited) { options.visited[component.id] = true; } if (visitor(component, name, options, up, down)) { return true; } if (!fluid.isFireBreak(component) && !options.flat) { fluid.visitComponentChildren(component, visitor, options, up, down + 1); } } }; // thatStack contains an increasing list of MORE SPECIFIC thats. var visitComponents = function(thatStack, visitor, options) { options = options || { visited: {}, flat: true }; var up = 0; for (var i = thatStack.length - 1; i >= 0; --i) { var that = thatStack[i]; if (fluid.isFireBreak(that)) { return; } if (that.typeName) { options.visited[that.id] = true; if (visitor(that, "", options, 0, 0)) { return; } } if (fluid.visitComponentChildren(that, visitor, options, up, 1)) { return; } ++up; } }; // An EL segment resolver strategy that will attempt to trigger creation of // components that it discovers along the EL path, if they have been defined but not yet // constructed. Spring, eat your heart out! Wot no SPR-2048? function makeGingerStrategy(instantiator, that, thatStack) { return function(component, thisSeg) { var atval = component[thisSeg]; if (atval === undefined) { var parentPath = instantiator.idToPath[component.id]; atval = instantiator.pathToComponent[fluid.composePath(parentPath, thisSeg)]; // if it was not attached to the component, but it is in the instantiator, it MUST be in creation - prepare to fail if (atval) { atval[inCreationMarker] = true; } } if (atval !== undefined) { if (atval[inCreationMarker]) { fluid.fail("Component " + fluid.dumpThat(atval) + " at path \"" + thisSeg + "\" of parent " + fluid.dumpThat(component) + " cannot be used for lookup" + " since it is still in creation. Please reorganise your dependencies so that they no longer contain circular references"); } } else { if (fluid.get(component, fluid.path("options", "components", thisSeg, "type"))) { fluid.initDependent(component, thisSeg); atval = component[thisSeg]; } } return atval; }; } // unsupported, non-API function fluid.dumpThat = function(that, instantiator) { return "{ typeName: \"" + that.typeName + "\" id: " + that.id + "}"; }; // unsupported, non-API function fluid.dumpThatStack = function(thatStack, instantiator) { var togo = fluid.transform(thatStack, function(that) { var path = instantiator.idToPath[that.id]; return fluid.dumpThat(that) + (path? (" - path: " + path) : ""); }); return togo.join("\n"); }; // Return an array of objects describing the current activity // unsupported, non-API function fluid.describeActivity = function() { return fluid.threadLocal().activityStack || []; }; // Execute the supplied function with the specified activity description pushed onto the stack // unsupported, non-API function fluid.pushActivity = function(func, message) { if (!message) { return func(); } var root = fluid.threadLocal(); if (!root.activityStack) { root.activityStack = []; } var frames = fluid.makeArray(message); frames.push("\n"); frames.unshift("\n"); root.activityStack = frames.concat(root.activityStack); return fluid.tryCatch(func, null, function() { root.activityStack = root.activityStack.slice(frames.length); }); }; // Return a function wrapped by the activity of describing its activity // unsupported, non-API function fluid.wrapActivity = function(func, messageSpec) { return function() { var args = fluid.makeArray(arguments); var message = fluid.transform(fluid.makeArray(messageSpec), function(specEl) { if (specEl.indexOf("arguments.") === 0) { var el = specEl.substring("arguments.".length); return fluid.get(args, el); } else { return specEl; } }); return fluid.pushActivity(function() { return func.apply(null, args); }, message); }; }; var localRecordExpected = /arguments|options|container/; function makeStackFetcher(instantiator, parentThat, localRecord, expandOptions) { expandOptions = expandOptions || {}; var thatStack = instantiator.getFullStack(parentThat); var fetchStrategies = [fluid.model.funcResolverStrategy, makeGingerStrategy(instantiator, parentThat, thatStack)]; var fetcher = function(parsed) { var context = parsed.context; if (localRecord && localRecordExpected.test(context)) { var fetched = fluid.get(localRecord[context], parsed.path); return (context === "arguments" || expandOptions.direct)? fetched : { marker: context === "options"? fluid.EXPAND : fluid.EXPAND_NOW, value: fetched }; } var foundComponent; visitComponents(thatStack, function(component, name, options, up, down) { if (context === name || context === component.typeName || context === component.nickName) { foundComponent = component; if (down > 1) { fluid.log("***WARNING: value resolution for context " + context + " found at depth " + down + ": this may not be supported in future"); } return true; // YOUR VISIT IS AT AN END!! } if (fluid.get(component, fluid.path("options", "components", context, "type")) && !component[context]) { foundComponent = fluid.get(component, context, {strategies: fetchStrategies}); return true; } }); if (!foundComponent && parsed.path !== "") { var ref = fluid.renderContextReference(parsed); fluid.log("Failed to resolve reference " + ref + ": thatStack contains\n" + fluid.dumpThatStack(thatStack, instantiator)); fluid.fail("Failed to resolve reference " + ref + " - could not match context with name " + context + " from component root of type " + thatStack[0].typeName, "\ninstantiator contents: ", instantiator); } return fluid.get(foundComponent, parsed.path, fetchStrategies); }; return fetcher; } function makeStackResolverOptions(instantiator, parentThat, localRecord, expandOptions) { return $.extend({}, fluid.defaults("fluid.resolveEnvironment"), { fetcher: makeStackFetcher(instantiator, parentThat, localRecord, expandOptions) }); } // unsupported, non-API function fluid.instantiator = function(freeInstantiator) { // NB: We may not use the options merging framework itself here, since "withInstantiator" below // will blow up, as it tries to resolve the instantiator which we are instantiating *NOW* var preThat = { options: { "fluid.visitComponents.fireBreak": true }, idToPath: {}, pathToComponent: {}, stackCount: 0, nickName: "instantiator" }; var that = fluid.typeTag("fluid.instantiator"); that = $.extend(that, preThat); that.stack = function(count) { return that.stackCount += count; }; that.getThatStack = function(component) { var path = that.idToPath[component.id] || ""; var parsed = fluid.model.parseEL(path); var togo = fluid.transform(parsed, function(value, i) { var parentPath = fluid.model.composeSegments.apply(null, parsed.slice(0, i + 1)); return that.pathToComponent[parentPath]; }); var root = that.pathToComponent[""]; if (root) { togo.unshift(root); } return togo; }; that.getEnvironmentalStack = function() { var togo = [fluid.staticEnvironment]; if (!freeInstantiator) { togo.push(fluid.threadLocal()); } return togo; }; that.getFullStack = function(component) { var thatStack = component? that.getThatStack(component) : []; return that.getEnvironmentalStack().concat(thatStack); }; function recordComponent(component, path) { that.idToPath[component.id] = path; if (that.pathToComponent[path]) { fluid.fail("Error during instantiation - path " + path + " which has just created component " + fluid.dumpThat(component) + " has already been used for component " + fluid.dumpThat(that.pathToComponent[path]) + " - this is a circular instantiation or other oversight." + " Please clear the component using instantiator.clearComponent() before reusing the path."); } that.pathToComponent[path] = component; } that.recordRoot = function(component) { if (component && component.id && !that.pathToComponent[""]) { recordComponent(component, ""); } }; that.pushUpcomingInstantiation = function(parent, name) { that.expectedParent = parent; that.expectedName = name; }; that.recordComponent = function(component) { if (that.expectedName) { that.recordKnownComponent(that.expectedParent, component, that.expectedName); delete that.expectedName; delete that.expectedParent; } else { that.recordRoot(component); } }; that.clearComponent = function(component, name, child, options, noModTree) { options = options || {visited: {}, flat: true}; child = child || component[name]; fluid.visitComponentChildren(child, function(gchild, gchildname) { that.clearComponent(child, gchildname, null, options, noModTree); }, options); var path = that.idToPath[child.id]; delete that.idToPath[child.id]; delete that.pathToComponent[path]; if (!noModTree) { delete component[name]; } }; that.recordKnownComponent = function(parent, component, name) { var parentPath = that.idToPath[parent.id] || ""; var path = fluid.model.composePath(parentPath, name); recordComponent(component, path); }; return that; }; fluid.freeInstantiator = fluid.instantiator(true); // unsupported, non-API function fluid.argMapToDemands = function(argMap) { var togo = []; fluid.each(argMap, function(value, key) { togo[value] = "{" + key + "}"; }); return togo; }; // unsupported, non-API function fluid.makePassArgsSpec = function(initArgs) { return fluid.transform(initArgs, function(arg, index) { return "{arguments}." + index; }); }; function mergeToMergeAll(options) { if (options && options.mergeOptions) { options.mergeAllOptions = ["{options}"].concat(fluid.makeArray(options.mergeOptions)); } } function upgradeMergeOptions(demandspec) { mergeToMergeAll(demandspec); if (demandspec.mergeAllOptions) { if (demandspec.options) { fluid.fail("demandspec ", demandspec, " is invalid - cannot specify literal options together with mergeOptions or mergeAllOptions"); } demandspec.options = { mergeAllOptions: demandspec.mergeAllOptions }; } if (demandspec.options) { delete demandspec.options.mergeOptions; } } /** Given a concrete argument list and/or options, determine the final concrete * "invocation specification" which is coded by the supplied demandspec in the * environment "thatStack" - the return is a package of concrete global function name * and argument list which is suitable to be executed directly by fluid.invokeGlobalFunction. */ // unsupported, non-API function fluid.embodyDemands = function(instantiator, parentThat, demandspec, initArgs, options) { options = options || {}; upgradeMergeOptions(demandspec); var oldOptions = fluid.get(options, "componentRecord.options"); options.componentRecord = $.extend(true, {}, options.componentRecord, fluid.censorKeys(demandspec, ["args", "funcName", "registeredFrom"])); var mergeAllZero = fluid.get(options, "componentRecord.options.mergeAllOptions.0"); if (mergeAllZero === "{options}") { fluid.set(options, "componentRecord.options.mergeAllOptions.0", oldOptions); } var demands = $.makeArray(demandspec.args); var upDefaults = fluid.defaults(demandspec.funcName); // I can SEE into TIME!! var argMap = upDefaults? upDefaults.argumentMap : null; var inferMap = false; if (!argMap && (upDefaults || (options && options.componentRecord)) && !options.passArgs) { inferMap = true; // infer that it must be a little component if we have any reason to believe it is a component if (demands.length < 2) { argMap = fluid.rawDefaults("fluid.littleComponent").argumentMap; } else { argMap = {options: demands.length - 1}; // wild guess in the old style } } options = options || {}; if (demands.length === 0) { if (options.componentRecord && argMap) { demands = fluid.argMapToDemands(argMap); } else if (options.passArgs) { demands = fluid.makePassArgsSpec(initArgs); } } var localRecord = $.extend({"arguments": initArgs}, fluid.censorKeys(options.componentRecord, ["type"])); fluid.each(argMap, function(index, name) { if (initArgs.length > 0) { localRecord[name] = localRecord["arguments"][index]; } if (demandspec[name] !== undefined && localRecord[name] === undefined) { localRecord[name] = demandspec[name]; } }); mergeToMergeAll(localRecord.options); mergeToMergeAll(argMap && demands[argMap.options]); var upstreamLocalRecord = $.extend({}, localRecord); if (options.componentRecord.options !== undefined) { upstreamLocalRecord.options = options.componentRecord.options; } var expandOptions = makeStackResolverOptions(instantiator, parentThat, localRecord); var args = []; if (demands) { for (var i = 0; i < demands.length; ++i) { var arg = demands[i]; // Weak detection since we cannot guarantee this material has not been copied if (fluid.isMarker(arg) && arg.value === fluid.COMPONENT_OPTIONS.value) { arg = "{options}"; // Backwards compatibility for non-users of GRADES - last-ditch chance to correct the inference if (inferMap) { argMap = {options: i}; } } if (typeof(arg) === "string") { if (arg.charAt(0) === "@") { var argpos = arg.substring(1); arg = "{arguments}." + argpos; } } if (!argMap || argMap.options !== i) { // defer expansion required if it is non-pseudoarguments demands and this argument *is* the options args[i] = fluid.expander.expandLight(arg, expandOptions); } else { // It is the component options if (arg && typeof(arg) === "object" && !arg.targetTypeName) { arg.targetTypeName = demandspec.funcName; } // ensure to copy the arg since it is an alias of the demand block material (FLUID-4223) // and will be destructively expanded args[i] = {marker: fluid.EXPAND, value: fluid.copy(arg), localRecord: upstreamLocalRecord}; } if (args[i] && fluid.isMarker(args[i].marker, fluid.EXPAND_NOW)) { args[i] = fluid.expander.expandLight(args[i].value, expandOptions); } } } else { args = initArgs? initArgs : []; } var togo = { args: args, funcName: demandspec.funcName }; return togo; }; var aliasTable = {}; fluid.alias = function(demandingName, aliasName) { if (aliasName) { aliasTable[demandingName] = aliasName; } else { return aliasTable[demandingName]; } }; var dependentStore = {}; function searchDemands(demandingName, contextNames) { var exist = dependentStore[demandingName] || []; outer: for (var i = 0; i < exist.length; ++i) { var rec = exist[i]; for (var j = 0; j < contextNames.length; ++j) { if (rec.contexts[j] !== contextNames[j]) { continue outer; } } return rec.spec; // jslint:ok } } fluid.demands = function(demandingName, contextName, spec) { var contextNames = $.makeArray(contextName).sort(); if (!spec) { return searchDemands(demandingName, contextNames); } else if (spec.length) { spec = {args: spec}; } if (fluid.getCallerInfo) { var callerInfo = fluid.getCallerInfo(5); if (callerInfo) { spec.registeredFrom = callerInfo; } } var exist = dependentStore[demandingName]; if (!exist) { exist = []; dependentStore[demandingName] = exist; } exist.push({contexts: contextNames, spec: spec}); }; // unsupported, non-API function fluid.compareDemands = function(speca, specb) { var p1 = speca.uncess - specb.uncess; return p1 === 0? specb.intersect - speca.intersect : p1; }; // unsupported, non-API function fluid.isDemandLogging = function(demandingNames) { return fluid.isLogging() && demandingNames[0] !== "fluid.threadLocal"; }; // unsupported, non-API function fluid.locateAllDemands = function(instantiator, parentThat, demandingNames) { var demandLogging = fluid.isDemandLogging(demandingNames); if (demandLogging) { fluid.log("Resolving demands for function names ", demandingNames, " in context of " + (parentThat? "component " + parentThat.typeName : "no component")); } var contextNames = {}; var visited = []; var thatStack = instantiator.getFullStack(parentThat); visitComponents(thatStack, function(component, xname, options, up, down) { contextNames[component.typeName] = true; visited.push(component); }); if (demandLogging) { fluid.log("Components in scope for resolution:\n" + fluid.dumpThatStack(visited, instantiator)); } var matches = []; for (var i = 0; i < demandingNames.length; ++i) { var rec = dependentStore[demandingNames[i]] || []; for (var j = 0; j < rec.length; ++j) { var spec = rec[j]; var record = {spec: spec, intersect: 0, uncess: 0}; for (var k = 0; k < spec.contexts.length; ++k) { record[contextNames[spec.contexts[k]]? "intersect" : "uncess"] += 2; } if (spec.contexts.length === 0) { // allow weak priority for contextless matches record.intersect++; } // TODO: Potentially more subtle algorithm here - also ambiguity reports matches.push(record); } } matches.sort(fluid.compareDemands); return matches; }; // unsupported, non-API function fluid.locateDemands = function(instantiator, parentThat, demandingNames) { var matches = fluid.locateAllDemands(instantiator, parentThat, demandingNames); var demandspec = matches.length === 0 || matches[0].intersect === 0? null : matches[0].spec.spec; if (fluid.isDemandLogging(demandingNames)) { if (demandspec) { fluid.log("Located " + matches.length + " potential match" + (matches.length === 1? "" : "es") + ", selected best match with " + matches[0].intersect + " matched context names: ", demandspec); } else { fluid.log("No matches found for demands, using direct implementation"); } } return demandspec; }; /** Determine the appropriate demand specification held in the fluid.demands environment * relative to "thatStack" for the function name(s) funcNames. */ // unsupported, non-API function fluid.determineDemands = function (instantiator, parentThat, funcNames) { funcNames = $.makeArray(funcNames); var newFuncName = funcNames[0]; var demandspec = fluid.locateDemands(instantiator, parentThat, funcNames) || {}; if (demandspec.funcName) { newFuncName = demandspec.funcName; } var aliasTo = fluid.alias(newFuncName); if (aliasTo) { newFuncName = aliasTo; fluid.log("Following redirect from function name " + newFuncName + " to " + aliasTo); var demandspec2 = fluid.locateDemands(instantiator, parentThat, [aliasTo]); if (demandspec2) { fluid.each(demandspec2, function(value, key) { if (localRecordExpected.test(key)) { fluid.fail("Error in demands block ", demandspec2, " - content with key \"" + key + "\" is not supported since this demands block was resolved via an alias from \"" + newFuncName + "\""); } }); if (demandspec2.funcName) { newFuncName = demandspec2.funcName; fluid.log("Followed final inner demands to function name \"" + newFuncName + "\""); } } } return fluid.merge(null, {funcName: newFuncName, args: fluid.makeArray(demandspec.args)}, fluid.censorKeys(demandspec, ["funcName", "args"])); }; // unsupported, non-API function fluid.resolveDemands = function(instantiator, parentThat, funcNames, initArgs, options) { var demandspec = fluid.determineDemands(instantiator, parentThat, funcNames); return fluid.embodyDemands(instantiator, parentThat, demandspec, initArgs, options); }; // TODO: make a *slightly* more performant version of fluid.invoke that perhaps caches the demands // after the first successful invocation fluid.invoke = function(functionName, args, that, environment) { args = fluid.makeArray(args); return fluid.withInstantiator(that, function(instantiator) { var invokeSpec = fluid.resolveDemands(instantiator, that, functionName, args, {passArgs: true}); return fluid.invokeGlobalFunction(invokeSpec.funcName, invokeSpec.args, environment); }); }; fluid.invoke = fluid.wrapActivity(fluid.invoke, [" while invoking function with name \"", "arguments.0", "\" from component", "arguments.2"]); /** Make a function which performs only "static redispatch" of the supplied function name - * that is, taking only account of the contents of the "static environment". Since the static * environment is assumed to be constant, the dispatch of the call will be evaluated at the * time this call is made, as an optimisation. */ fluid.makeFreeInvoker = function(functionName, environment) { var demandSpec = fluid.determineDemands(fluid.freeInstantiator, null, functionName); return function() { var invokeSpec = fluid.embodyDemands(fluid.freeInstantiator, null, demandSpec, arguments, {passArgs: true}); return fluid.invokeGlobalFunction(invokeSpec.funcName, invokeSpec.args, environment); }; }; fluid.makeInvoker = function(instantiator, that, demandspec, functionName, environment) { demandspec = demandspec || fluid.determineDemands(instantiator, that, functionName); return function() { var args = arguments; return fluid.pushActivity(function() { var invokeSpec = fluid.embodyDemands(instantiator, that, demandspec, args, {passArgs: true}); return fluid.invokeGlobalFunction(invokeSpec.funcName, invokeSpec.args, environment); }, [" while invoking invoker with name " + functionName + " on component", that]); }; }; // unsupported, non-API function fluid.event.dispatchListener = function(instantiator, that, listener, eventName, eventSpec) { return function() { var demandspec = fluid.determineDemands(instantiator, that, eventName); if (demandspec.args.length === 0 && eventSpec.args) { demandspec.args = eventSpec.args; } var resolved = fluid.embodyDemands(instantiator, that, demandspec, arguments, {passArgs: true, componentOptions: eventSpec}); listener.apply(null, resolved.args); }; }; // unsupported, non-API function fluid.event.resolveEvent = function(that, eventName, eventSpec) { return fluid.withInstantiator(that, function(instantiator) { if (typeof(eventSpec) === "string") { var firer = fluid.expandOptions(eventSpec, that); if (!firer) { fluid.fail("Error in fluid.event.resolveEvent - context path " + eventSpec + " could not be looked up to a valid event firer"); } return firer; } else { var event = eventSpec.event; var origin; if (!event) { fluid.fail("Event specification for event with name " + eventName + " does not include a base event specification"); } if (event.charAt(0) === "{") { origin = fluid.expandOptions(event, that); } else { origin = that.events[event]; } if (!origin) { fluid.fail("Error in event specification - could not resolve base event reference " + event + " to an event firer"); } var firer = {}; // jslint:ok - already defined fluid.each(["fire", "removeListener"], function(method) { firer[method] = function() {origin[method].apply(null, arguments);}; }); firer.addListener = function(listener, namespace, predicate, priority) { origin.addListener(fluid.event.dispatchListener(instantiator, that, listener, eventName, eventSpec), namespace, predicate, priority); }; return firer; } }); }; fluid.registerNamespace("fluid.expander"); /** rescue that part of a component's options which should not be subject to * options expansion via IoC - this initially consists of "components" and "mergePolicy" * but will be expanded by the set of paths specified as "noexpand" within "mergePolicy" */ // unsupported, non-API function fluid.expander.preserveFromExpansion = function(options) { var preserve = {}; var preserveList = fluid.arrayToHash(["mergePolicy", "mergeAllOptions", "components", "invokers", "events", "listeners", "transformOptions"]); fluid.each(options.mergePolicy, function(value, key) { if (fluid.mergePolicyIs(value, "noexpand")) { preserveList[key] = true; } }); fluid.each(preserveList, function(xvalue, path) { var pen = fluid.model.getPenultimate(options, path); var value = pen.root[pen.last]; delete pen.root[pen.last]; fluid.set(preserve, path, value); }); return { restore: function(target) { fluid.each(preserveList, function(xvalue, path) { var preserved = fluid.get(preserve, path); if (preserved !== undefined) { fluid.set(target, path, preserved); } }); } }; }; /** Expand a set of component options with respect to a set of "expanders" (essentially only * deferredCall) - This substitution is destructive since it is assumed that the options are already "live" as the * result of environmental substitutions. Note that options contained inside "components" will not be expanded * by this call directly to avoid linearly increasing expansion depth if this call is occuring as a result of * "initDependents" */ // TODO: This needs to be integrated with "embodyDemands" above which makes a call to "resolveEnvironment" directly // but with very similarly derived options (makeStackResolverOptions) fluid.expandOptions = function(args, that, localRecord, outerExpandOptions) { if (!args) { return args; } return fluid.withInstantiator(that, function(instantiator) { //fluid.log("expandOptions for " + that.typeName + " executing with instantiator " + instantiator.id); var expandOptions = makeStackResolverOptions(instantiator, that, localRecord, outerExpandOptions); expandOptions.noCopy = true; // It is still possible a model may be fetched even though it is preserved var pres; if (!fluid.isArrayable(args) && !fluid.isPrimitive(args)) { pres = fluid.expander.preserveFromExpansion(args); } var expanded = fluid.expander.expandLight(args, expandOptions); if (pres) { pres.restore(expanded); } return expanded; }); }; // unsupported, non-API function fluid.locateTransformationRecord = function(that) { return fluid.withInstantiator(that, function(instantiator) { var matches = fluid.locateAllDemands(instantiator, that, ["fluid.transformOptions"]); return fluid.find(matches, function(match) { return match.uncess === 0 && fluid.contains(match.spec.contexts, that.typeName)? match.spec.spec : undefined; }); }); }; // fluid.hashToArray = function(hash) { var togo = []; fluid.each(hash, function(value, key) { togo.push(key); }); return togo; }; // unsupported, non-API function fluid.localRecordExpected = ["type", "options", "arguments", "mergeOptions", "mergeAllOptions", "createOnEvent", "priority"]; // unsupported, non-API function fluid.checkComponentRecord = function(defaults, localRecord) { var expected = fluid.arrayToHash(fluid.localRecordExpected); fluid.each(defaults.argumentMap, function(value, key) { expected[key] = true; }); fluid.each(localRecord, function(value, key) { if (!expected[key]) { fluid.fail("Probable error in subcomponent record - key \"" + key + "\" found, where the only legal options are " + fluid.hashToArray(expected).join(", ")); } }); }; // unsupported, non-API function fluid.expandComponentOptions = function(defaults, userOptions, that) { if (userOptions && userOptions.localRecord) { fluid.checkComponentRecord(defaults, userOptions.localRecord); } defaults = fluid.expandOptions(fluid.copy(defaults), that); var localRecord = {}; if (userOptions && userOptions.marker === fluid.EXPAND) { // TODO: Somewhat perplexing... the local record itself, by any route we could get here, consists of unexpanded // material taken from "componentOptions" var localOptions = fluid.get(userOptions, "localRecord.options"); if (localOptions) { if (defaults && defaults.mergePolicy) { localOptions.mergePolicy = defaults.mergePolicy; } localRecord.options = fluid.expandOptions(localOptions, that); } localRecord["arguments"] = fluid.get(userOptions, "localRecord.arguments"); var toExpand = userOptions.value; userOptions = fluid.expandOptions(toExpand, that, localRecord, {direct: true}); } localRecord.directOptions = userOptions; if (!localRecord.options) { // Catch the case where there is no demands block and everything is in the subcomponent record - // in this case, embodyDemands will not construct a localRecord and what the user refers to by "options" // is really what we properly call "directOptions". localRecord.options = userOptions; } var mergeOptions = (userOptions && userOptions.mergeAllOptions) || ["{directOptions}"]; var togo = fluid.transform(mergeOptions, function(path) { // Avoid use of expandOptions in simple case to avoid infinite recursion when constructing instantiator return path === "{directOptions}"? localRecord.directOptions : fluid.expandOptions(path, that, localRecord, {direct: true}); }); var transRec = fluid.locateTransformationRecord(that); if (transRec) { togo[0].transformOptions = transRec.options; } return [defaults].concat(togo); }; fluid.expandComponentOptions = fluid.wrapActivity(fluid.expandComponentOptions, [" while expanding component options ", "arguments.1.value", " with record ", "arguments.1", " for component ", "arguments.2"]); // The case without the instantiator is from the ginger strategy - this logic is still a little ragged fluid.initDependent = function(that, name, userInstantiator, directArgs) { if (!that || that[name]) { return; } fluid.log("Beginning instantiation of component with name \"" + name + "\" as child of " + fluid.dumpThat(that)); directArgs = directArgs || []; var root = fluid.threadLocal(); if (userInstantiator) { var existing = root["fluid.instantiator"]; if (existing && existing !== userInstantiator) { fluid.fail("Error in initDependent: user instantiator supplied with id " + userInstantiator.id + " which differs from that for currently active instantiation with id " + existing.id); } else { root["fluid.instantiator"] = userInstantiator; // fluid.log("*** initDependent for " + that.typeName + " member " + name + " was supplied USER instantiator with id " + userInstantiator.id + " - STORED"); } } var component = that.options.components[name]; fluid.withInstantiator(that, function(instantiator) { if (typeof(component) === "string") { that[name] = fluid.expandOptions([component], that)[0]; // TODO: expose more sensible semantic for expandOptions } else if (component.type) { var invokeSpec = fluid.resolveDemands(instantiator, that, [component.type, name], directArgs, {componentRecord: component}); instantiator.pushUpcomingInstantiation(that, name); fluid.tryCatch(function() { that[inCreationMarker] = true; var instance = fluid.initSubcomponentImpl(that, {type: invokeSpec.funcName}, invokeSpec.args); // The existing instantiator record will be provisional, adjust it to take account of the true return // TODO: Instantiator contents are generally extremely incomplete var path = fluid.composePath(instantiator.idToPath[that.id] || "", name); var existing = instantiator.pathToComponent[path]; if (existing && existing !== instance) { instantiator.clearComponent(that, name, existing, null, true); } if (instance && instance.typeName && instance.id && instance !== existing) { instantiator.recordKnownComponent(that, instance, name); } that[name] = instance; }, null, function() { delete that[inCreationMarker]; instantiator.pushUpcomingInstantiation(); }); } else { that[name] = component; } }, [" while instantiating dependent component with name \"" + name + "\" with record ", component, " as child of ", that]); fluid.log("Finished instantiation of component with name \"" + name + "\" as child of " + fluid.dumpThat(that)); }; // NON-API function // This function is stateful and MUST NOT be called by client code fluid.withInstantiator = function(that, func, message) { var root = fluid.threadLocal(); var instantiator = root["fluid.instantiator"]; if (!instantiator) { instantiator = root["fluid.instantiator"] = fluid.instantiator(); //fluid.log("Created new instantiator with id " + instantiator.id + " in order to operate on component " + typeName); } return fluid.pushActivity(function() { return fluid.tryCatch(function() { if (that) { instantiator.recordComponent(that); } instantiator.stack(1); //fluid.log("Instantiator stack +1 to " + instantiator.stackCount + " for " + typeName); return func(instantiator); }, null, function() { var count = instantiator.stack(-1); //fluid.log("Instantiator stack -1 to " + instantiator.stackCount + " for " + typeName); if (count === 0) { //fluid.log("Clearing instantiator with id " + instantiator.id + " from threadLocal for end of " + typeName); delete root["fluid.instantiator"]; } }); }, message); }; // unsupported, non-API function fluid.bindDeferredComponent = function(that, componentName, component, instantiator) { var events = fluid.makeArray(component.createOnEvent); fluid.each(events, function(eventName) { that.events[eventName].addListener(function() { if (that[componentName]) { instantiator.clearComponent(that, componentName); } fluid.initDependent(that, componentName, instantiator); }, null, null, component.priority); }); }; // unsupported, non-API function fluid.priorityForComponent = function(component) { return component.priority? component.priority : (component.type === "fluid.typeFount" || fluid.hasGrade(fluid.defaults(component.type), "fluid.typeFount"))? "first" : undefined; }; fluid.initDependents = function(that) { var options = that.options; var components = options.components || {}; var componentSort = {}; fluid.withInstantiator(that, function(instantiator) { fluid.each(components, function(component, name) { if (!component.createOnEvent) { var priority = fluid.priorityForComponent(component); componentSort[name] = {key: name, priority: fluid.event.mapPriority(priority, 0)}; } else { fluid.bindDeferredComponent(that, name, component, instantiator); } }); var componentList = fluid.event.sortListeners(componentSort); fluid.each(componentList, function(entry) { fluid.initDependent(that, entry.key); }); var invokers = options.invokers || {}; for (var name in invokers) { var invokerec = invokers[name]; var funcName = typeof(invokerec) === "string"? invokerec : null; that[name] = fluid.withInstantiator(that, function(instantiator) { fluid.log("Beginning instantiation of invoker with name \"" + name + "\" as child of " + fluid.dumpThat(that)); return fluid.makeInvoker(instantiator, that, funcName? null : invokerec, funcName); }, [" while instantiating invoker with name \"" + name + "\" with record ", invokerec, " as child of ", that]); // jslint:ok fluid.log("Finished instantiation of invoker with name \"" + name + "\" as child of " + fluid.dumpThat(that)); } }); }; fluid.staticEnvironment = fluid.typeTag("fluid.staticEnvironment"); fluid.staticEnvironment.environmentClass = fluid.typeTag("fluid.browser"); // fluid.environmentalRoot.environmentClass = fluid.typeTag("fluid.rhino"); fluid.demands("fluid.threadLocal", "fluid.browser", {funcName: "fluid.singleThreadLocal"}); var singleThreadLocal = fluid.typeTag("fluid.dynamicEnvironment"); fluid.singleThreadLocal = function() { return singleThreadLocal; }; fluid.threadLocal = function() { // quick implementation since this is not very dynamic, a hazard to debugging, and used frequently within IoC itself var demands = fluid.locateDemands(fluid.freeInstantiator, null, ["fluid.threadLocal"]); return fluid.invokeGlobalFunction(demands.funcName, arguments); }; function applyLocalChange(applier, type, path, value) { var change = { type: type, path: path, value: value }; applier.fireChangeRequest(change); } // unsupported, non-API function fluid.withEnvironment = function(envAdd, func, prefix) { prefix = prefix || ""; var root = fluid.threadLocal(); var applier = fluid.makeChangeApplier(root, {thin: true}); return fluid.tryCatch(function() { for (var key in envAdd) { applyLocalChange(applier, "ADD", fluid.model.composePath(prefix, key), envAdd[key]); } $.extend(root, envAdd); return func(); }, null, function() { for (var key in envAdd) { // jslint:ok duplicate "value" // TODO: This could be much better through i) refactoring the ChangeApplier so we could naturally use "rollback" semantics // and/or implementing this material using some form of "prototype chain" applyLocalChange(applier, "DELETE", fluid.model.composePath(prefix, key)); } }); }; // unsupported, non-API function fluid.makeEnvironmentFetcher = function(prefix, directModel) { return function(parsed) { var env = fluid.get(fluid.threadLocal(), prefix); return fluid.fetchContextReference(parsed, directModel, env); }; }; // unsupported, non-API function fluid.extractEL = function(string, options) { if (options.ELstyle === "ALL") { return string; } else if (options.ELstyle.length === 1) { if (string.charAt(0) === options.ELstyle) { return string.substring(1); } } else if (options.ELstyle === "${}") { var i1 = string.indexOf("${"); var i2 = string.lastIndexOf("}"); if (i1 === 0 && i2 !== -1) { return string.substring(2, i2); } } }; // unsupported, non-API function fluid.extractELWithContext = function(string, options) { var EL = fluid.extractEL(string, options); if (EL && EL.charAt(0) === "{") { return fluid.parseContextReference(EL, 0); } return EL? {path: EL} : EL; }; fluid.parseContextReference = function(reference, index, delimiter) { var endcpos = reference.indexOf("}", index + 1); if (endcpos === -1) { fluid.fail("Cannot parse context reference \"" + reference + "\": Malformed context reference without }"); } var context = reference.substring(index + 1, endcpos); var endpos = delimiter? reference.indexOf(delimiter, endcpos + 1) : reference.length; var path = reference.substring(endcpos + 1, endpos); if (path.charAt(0) === ".") { path = path.substring(1); } return {context: context, path: path, endpos: endpos}; }; fluid.renderContextReference = function(parsed) { return "{" + parsed.context + "}" + parsed.path; }; fluid.fetchContextReference = function(parsed, directModel, env) { var base = parsed.context? env[parsed.context] : directModel; if (!base) { return base; } return fluid.get(base, parsed.path); }; // unsupported, non-API function fluid.resolveContextValue = function(string, options) { if (options.bareContextRefs && string.charAt(0) === "{") { var parsed = fluid.parseContextReference(string, 0); return options.fetcher(parsed); } else if (options.ELstyle && options.ELstyle !== "${}") { var parsed = fluid.extractELWithContext(string, options); // jslint:ok if (parsed) { return options.fetcher(parsed); } } while (typeof(string) === "string") { var i1 = string.indexOf("${"); var i2 = string.indexOf("}", i1 + 2); if (i1 !== -1 && i2 !== -1) { var parsed; // jslint:ok if (string.charAt(i1 + 2) === "{") { parsed = fluid.parseContextReference(string, i1 + 2, "}"); i2 = parsed.endpos; } else { parsed = {path: string.substring(i1 + 2, i2)}; } var subs = options.fetcher(parsed); var all = (i1 === 0 && i2 === string.length - 1); // TODO: test case for all undefined substitution if (subs === undefined || subs === null) { return subs; } string = all? subs : string.substring(0, i1) + subs + string.substring(i2 + 1); } else { break; } } return string; }; fluid.resolveContextValue = fluid.wrapActivity(fluid.resolveContextValue, [" while resolving context value ", "arguments.0"]); function resolveEnvironmentImpl(obj, options) { fluid.guardCircularity(options.seenIds, obj, "expansion", " - please ensure options are not circularly connected, or protect from expansion using the \"noexpand\" policy or expander"); function recurse(arg) { return resolveEnvironmentImpl(arg, options); } if (typeof(obj) === "string" && !options.noValue) { return fluid.resolveContextValue(obj, options); } else if (fluid.isPrimitive(obj) || obj.nodeType !== undefined || obj.jquery) { return obj; } else if (options.filter) { return options.filter(obj, recurse, options); } else { return (options.noCopy? fluid.each : fluid.transform)(obj, function(value, key) { return resolveEnvironmentImpl(value, options); }); } } fluid.defaults("fluid.resolveEnvironment", { ELstyle: "${}", seenIds: {}, bareContextRefs: true }); fluid.resolveEnvironment = function(obj, options) { // Don't create a component here since this function is itself used in the // component expansion pathway - avoid all expansion in any case to head off FLUID-4301 options = $.extend(true, {}, fluid.rawDefaults("fluid.resolveEnvironment"), options); return resolveEnvironmentImpl(obj, options); }; /** "light" expanders, starting with support functions for the "deferredFetcher" expander **/ fluid.expander.deferredCall = function(target, source, recurse) { var expander = source.expander; var args = (!expander.args || fluid.isArrayable(expander.args))? expander.args : $.makeArray(expander.args); args = recurse(args); return fluid.invokeGlobalFunction(expander.func, args); }; fluid.deferredCall = fluid.expander.deferredCall; // put in top namespace for convenience fluid.deferredInvokeCall = function(target, source, recurse) { var expander = source.expander; var args = (!expander.args || fluid.isArrayable(expander.args))? expander.args : $.makeArray(expander.args); args = recurse(args); return fluid.invoke(expander.func, args); }; // The "noexpand" expander which simply unwraps one level of expansion and ceases. fluid.expander.noexpand = function(target, source) { return $.extend(target, source.expander.tree); }; fluid.noexpand = fluid.expander.noexpand; // TODO: check naming and namespacing // unsupported, non-API function fluid.expander.lightFilter = function (obj, recurse, options) { var togo; if (fluid.isArrayable(obj)) { togo = options.noCopy? obj : []; fluid.each(obj, function(value, key) {togo[key] = recurse(value);}); } else { togo = options.noCopy? obj : {}; for (var key in obj) { var value = obj[key]; var expander; if (key === "expander" && !(options.expandOnly && options.expandOnly[value.type])) { expander = fluid.getGlobalValue(value.type); if (expander) { return expander.call(null, togo, obj, recurse, options); } } if (key !== "expander" || !expander) { togo[key] = recurse(value); } } } return options.noCopy? obj : togo; }; // unsupported, non-API function fluid.expander.expandLight = function (source, expandOptions) { var options = $.extend({}, expandOptions); options.filter = fluid.expander.lightFilter; return fluid.resolveEnvironment(source, options); }; })(jQuery, fluid_1_4);
gregrgay/booking
Web/scripts/infusion/framework/core/js/FluidIoC.js
JavaScript
gpl-3.0
54,696
var searchData= [ ['emails_2ephp',['emails.php',['../emails_8php.html',1,'']]], ['emails_5flinks_2ephp',['emails_links.php',['../emails__links_8php.html',1,'']]] ];
labscoop/xortify
releases/XOOPS 2.6/4.14/docs/html/search/files_65.js
JavaScript
gpl-3.0
169
/* Developed with the contribution of the European Commission - Directorate General for Maritime Affairs and Fisheries © European Union, 2015-2016. This file is part of the Integrated Fisheries Data Management (IFDM) Suite. The IFDM Suite 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 any later version. The IFDM Suite 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 the IFDM Suite. If not, see <http://www.gnu.org/licenses/>. */ describe('AuditconfigurationCtrl', function() { var scope, createController, createSetting; beforeEach(module('unionvmsWeb')); beforeEach(inject(function($rootScope, $controller) { scope = $rootScope.$new(); createController = function() { return $controller('AuditconfigurationCtrl', { '$scope': scope, '$resource': function(url) { if (url === "config/rest/settings/:id") { return singleSettingResource; } else if (url === "config/rest/catalog") { return settingCatalogResource; } } }); }; createSetting = function() { return { id: 123, key: "test.key", value: "some_value", global: false, description: "A setting for testing.", module: "movement", lastModified: 0 }; }; })); it('should only show tabs with at least one non-global setting', function() { var controller = createController(); expect(scope.tabs).toEqual(["systemMonitor", "globalSettings", "reporting","activity", "mobileTerminal"]); }); it('should provide the right partial URLs', function() { var controller = createController(); scope.activeTab = "systemMonitor"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationModule/systemMonitor.html"); scope.activeTab = "globalSettings"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationGeneral/configurationGeneral.html"); scope.activeTab = "reporting"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationReporting/configurationReporting.html"); scope.activeTab = "activity"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationActivity/configurationActivity.html"); scope.activeTab = "any other value"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationModule/configurationModule.html"); }); it('should begin editing a setting by backing up setting value and description', function() { var controller = createController(); var setting = createSetting(); scope.setEditing(setting, true); expect(setting.previousValue).toBe("some_value"); expect(setting.previousDescription).toBe("A setting for testing."); expect(setting.editing).toBe(true); }); it('should stop editing by deleting setting value and description backups', function() { var controller = createController(); var setting = createSetting(); setting.previousValue = "previousValue"; setting.previousDescription = "previousDescription"; scope.setEditing(setting, false); expect(setting.previousValue).not.toBeDefined(); expect(setting.previousDescription).not.toBeDefined(); expect(setting.editing).toBe(false); }); it('should cancel editing by restoring setting value and description from backup', function() { var setting = createSetting(); setting.previousValue = "previousValue"; setting.previousDescription = "previousDescription"; var controller = createController(); spyOn(scope, "setEditing"); scope.cancelEditing(setting); expect(setting.value).toBe("previousValue"); expect(setting.description).toBe("previousDescription"); expect(scope.setEditing).toHaveBeenCalledWith(jasmine.any(Object), false); }); it('should set lastModified when updating a setting, and set editing to false', function() { var controller = createController(); var setting = createSetting(); spyOn(scope, "setEditing"); scope.updateSetting(setting); expect(setting.lastModified).toBe(123); expect(scope.setEditing).toHaveBeenCalledWith(jasmine.any(Object), false); }); it('should filter by replacing periods with underscores', inject(function($filter) { expect($filter('replace')('apa.bepa.cepa')).toBe('apa_bepa_cepa'); expect($filter('replace')('')).toBe(''); })); var catalog = { data: { "vessel": [ { key: "key.1", value: "value.1", description: "A global vessel setting", global: true } ], "mobileTerminal": [ { key: "key.2", value: "value.2", description: "A module-specific setting for mobile terminals", global: false }, { key: "key.3", value: "value.3", description: "A global mobile terminal setting", global: true } ] } }; var response = { data: { id: 123, key: "test.key", value: "some_value", global: false, description: "A setting for testing.", module: "movement", lastModified: 123 } }; var singleSettingResource = { update: function(params, data, callback) { callback(response); } }; var settingCatalogResource = { get: function(callback) { callback(catalog); } }; });
UnionVMS/UVMS-Frontend
app/partial/admin/adminConfiguration/adminConfiguration-spec.js
JavaScript
gpl-3.0
5,549
// ---------------------------------------------------------------------------- // Buzz, a Javascript HTML5 Audio library // v 1.0.x beta // Licensed under the MIT license. // http://buzz.jaysalvat.com/ // ---------------------------------------------------------------------------- // Copyright (C) 2011 Jay Salvat // http://jaysalvat.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. // ---------------------------------------------------------------------------- // // multi-channel support Addition by Alaa-eddine KADDOURI // // // Usage : // var mySound = new buzz.sound( // "music", { // formats: [ "ogg", "mp3" ], // channels : 4 // }); // // mySound.play(); //will use channel 0 // setTimeout(function() { // mySound.play(); //will use channel 1 if channel 0 still playing // }, 3000); // // var buzz = { defaults: { autoplay: false, duration: 5000, formats: [], loop: false, placeholder: '--', preload: 'metadata', volume: 80 }, types: { 'mp3': 'audio/mpeg', 'ogg': 'audio/ogg', 'wav': 'audio/wav', 'aac': 'audio/aac', 'm4a': 'audio/x-m4a' }, sounds: [], el: document.createElement( 'audio' ), sound: function( src, options ) { options = options || {}; var _pool = []; var _instance = this; var pid = 0, events = [], eventsOnce = {}, supported = buzz.isSupported(); // publics this.load = function() { if ( !supported || poolfn( 'load' )) { return this; } this.sound.load(); return this; }; this.play = function() { if ( !supported ) { return this; } //multi-channel support ---------------------// if (this.isPool) { var snd = getChannel(); if (!snd) return; this.sound = snd.sound; } //-------------------------------------------// this.sound.play(); return this; }; this.togglePlay = function() { if ( !supported || poolfn( 'togglePlay' )) { return this; } if ( this.sound.paused ) { this.sound.play(); } else { this.sound.pause(); } return this; }; this.pause = function() { if ( !supported || poolfn( 'pause' )) { return this; } this.sound.pause(); return this; }; this.isPaused = function() { if ( !supported ) { return null; } return this.sound.paused; }; this.stop = function() { if ( !supported || poolfn( 'stop' )) { return this; } this.setTime( 0 ); this.sound.pause(); return this; }; this.isEnded = function() { if ( !supported ) { return null; } return this.sound.ended; }; this.loop = function() { if ( !supported || poolfn( 'loop' )) { return this; } this.sound.loop = 'loop'; this.bind( 'ended.buzzloop', function() { this.currentTime = 0; this.play(); }); return this; }; this.unloop = function() { if ( !supported || poolfn( 'unloop' )) { return this; } this.sound.removeAttribute( 'loop' ); this.unbind( 'ended.buzzloop' ); return this; }; this.mute = function() { if ( !supported || poolfn( 'mute' )) { return this; } this.sound.muted = true; return this; }; this.unmute = function() { if ( !supported || poolfn( 'unmute' )) { return this; } this.sound.muted = false; return this; }; this.toggleMute = function() { if ( !supported || poolfn( 'toggleMute' )) { return this; } this.sound.muted = !this.sound.muted; return this; }; this.isMuted = function() { if ( !supported ) { return null; } return this.sound.muted; }; this.setVolume = function( volume ) { if ( !supported || poolfn( 'setVolume', volume)) { return this; } if ( volume < 0 ) { volume = 0; } if ( volume > 100 ) { volume = 100; } this.volume = volume; this.sound.volume = volume / 100; return this; }; this.getVolume = function() { if ( !supported ) { return this; } return this.volume; }; this.increaseVolume = function( value ) { return this.setVolume( this.volume + ( value || 1 ) ); }; this.decreaseVolume = function( value ) { return this.setVolume( this.volume - ( value || 1 ) ); }; this.setTime = function( time ) { if ( !supported || poolfn( 'setTime', time )) { return this; } this.whenReady( function() { this.sound.currentTime = time; }); return this; }; this.getTime = function(channelIdx) { if ( !supported) { return null; } if (channelIdx !== undefined && this.isPool) { var channel = getChannel(channelIdx); if (channel && channel.sound) { var time = Math.round( channel.sound.currentTime * 100 ) / 100; return isNaN( time ) ? buzz.defaults.placeholder : time; } } var time = Math.round( this.sound.currentTime * 100 ) / 100; return isNaN( time ) ? buzz.defaults.placeholder : time; }; this.setPercent = function( percent ) { if ( !supported ) { return this; } return this.setTime( buzz.fromPercent( percent, this.sound.duration ) ); }; this.getPercent = function() { if ( !supported ) { return null; } var percent = Math.round( buzz.toPercent( this.sound.currentTime, this.sound.duration ) ); return isNaN( percent ) ? buzz.defaults.placeholder : percent; }; this.setSpeed = function( duration ) { if ( !supported ) { return this; } this.sound.playbackRate = duration; }; this.getSpeed = function() { if ( !supported ) { return null; } return this.sound.playbackRate; }; this.getDuration = function() { if ( !supported ) { return null; } var duration = Math.round( this.sound.duration * 100 ) / 100; return isNaN( duration ) ? buzz.defaults.placeholder : duration; }; this.getPlayed = function() { if ( !supported ) { return null; } return timerangeToArray( this.sound.played ); }; this.getBuffered = function() { if ( !supported ) { return null; } return timerangeToArray( this.sound.buffered ); }; this.getSeekable = function() { if ( !supported ) { return null; } return timerangeToArray( this.sound.seekable ); }; this.getErrorCode = function() { if ( supported && this.sound.error ) { return this.sound.error.code; } return 0; }; this.getErrorMessage = function() { if ( !supported ) { return null; } switch( this.getErrorCode() ) { case 1: return 'MEDIA_ERR_ABORTED'; case 2: return 'MEDIA_ERR_NETWORK'; case 3: return 'MEDIA_ERR_DECODE'; case 4: return 'MEDIA_ERR_SRC_NOT_SUPPORTED'; default: return null; } }; this.getStateCode = function() { if ( !supported ) { return null; } return this.sound.readyState; }; this.getStateMessage = function() { if ( !supported ) { return null; } switch( this.getStateCode() ) { case 0: return 'HAVE_NOTHING'; case 1: return 'HAVE_METADATA'; case 2: return 'HAVE_CURRENT_DATA'; case 3: return 'HAVE_FUTURE_DATA'; case 4: return 'HAVE_ENOUGH_DATA'; default: return null; } }; this.getNetworkStateCode = function() { if ( !supported ) { return null; } return this.sound.networkState; }; this.getNetworkStateMessage = function() { if ( !supported ) { return null; } switch( this.getNetworkStateCode() ) { case 0: return 'NETWORK_EMPTY'; case 1: return 'NETWORK_IDLE'; case 2: return 'NETWORK_LOADING'; case 3: return 'NETWORK_NO_SOURCE'; default: return null; } }; this.set = function( key, value ) { if ( !supported || poolfn( 'set', key, value )) { return this; } this.sound[ key ] = value; return this; }; this.get = function( key ) { if ( !supported ) { return null; } return key ? this.sound[ key ] : this.sound; }; this.bind = function( types, func ) { if ( !supported || poolfn( 'bind', types, func )) { return this; } types = types.split( ' ' ); var that = this, efunc = function( e ) { func.call( that, e ); }; for( var t = 0; t < types.length; t++ ) { var type = types[ t ], idx = type; type = idx.split( '.' )[ 0 ]; events.push( { idx: idx, func: efunc } ); this.sound.addEventListener( type, efunc, true ); } return this; }; this.unbind = function( types ) { if ( !supported || poolfn( 'unbind', types )) { return this; } types = types.split( ' ' ); for( var t = 0; t < types.length; t++ ) { var idx = types[ t ], type = idx.split( '.' )[ 0 ]; for( var i = 0; i < events.length; i++ ) { var namespace = events[ i ].idx.split( '.' ); if ( events[ i ].idx == idx || ( namespace[ 1 ] && namespace[ 1 ] == idx.replace( '.', '' ) ) ) { this.sound.removeEventListener( type, events[ i ].func, true ); // remove event events.splice(i, 1); } } } return this; }; this.bindOnce = function( type, func ) { if ( !supported || poolfn( 'bindOnce', type, func )) { return this; } var that = this; eventsOnce[ pid++ ] = false; this.bind( type + '.' + pid, function() { if ( !eventsOnce[ pid ] ) { eventsOnce[ pid ] = true; func.call( that ); } that.unbind( type + '.' + pid ); }); }; this.trigger = function( types ) { if ( !supported || poolfn( 'trigger', types )) { return this; } types = types.split( ' ' ); for( var t = 0; t < types.length; t++ ) { var idx = types[ t ]; for( var i = 0; i < events.length; i++ ) { var eventType = events[ i ].idx.split( '.' ); if ( events[ i ].idx == idx || ( eventType[ 0 ] && eventType[ 0 ] == idx.replace( '.', '' ) ) ) { var evt = document.createEvent('HTMLEvents'); evt.initEvent( eventType[ 0 ], false, true ); this.sound.dispatchEvent( evt ); } } } return this; }; this.fadeTo = function( to, duration, callback ) { if ( !supported ) { return this; } if ( duration instanceof Function ) { callback = duration; duration = buzz.defaults.duration; } else { duration = duration || buzz.defaults.duration; } var from = this.volume, delay = duration / Math.abs( from - to ), that = this; this.play(); function doFade() { setTimeout( function() { if ( from < to && that.volume < to ) { that.setVolume( that.volume += 1 ); doFade(); } else if ( from > to && that.volume > to ) { that.setVolume( that.volume -= 1 ); doFade(); } else if ( callback instanceof Function ) { callback.apply( that ); } }, delay ); } this.whenReady( function() { doFade(); }); return this; }; this.fadeIn = function( duration, callback ) { if ( !supported || poolfn( 'fadeIn', duration, callback )) { return this; } return this.setVolume(0).fadeTo( 100, duration, callback ); }; this.fadeOut = function( duration, callback ) { if ( !supported || poolfn( 'fadeOut', duration, callback )) { return this; } return this.fadeTo( 0, duration, callback ); }; this.fadeWith = function( sound, duration ) { if ( !supported ) { return this; } this.fadeOut( duration, function() { this.stop(); }); sound.play().fadeIn( duration ); return this; }; this.whenReady = function( func ) { if ( !supported ) { return null; } var that = this; if ( this.sound.readyState === 0 ) { this.bind( 'canplay.buzzwhenready', function() { func.call( that ); }); } else { func.call( that ); } }; // privates function timerangeToArray( timeRange ) { var array = [], length = timeRange.length - 1; for( var i = 0; i <= length; i++ ) { array.push({ start: timeRange.start( length ), end: timeRange.end( length ) }); } return array; } function getExt( filename ) { return filename.split('.').pop(); } function addSource( sound, src ) { var source = document.createElement( 'source' ); source.src = src; if ( buzz.types[ getExt( src ) ] ) { source.type = buzz.types[ getExt( src ) ]; } sound.appendChild( source ); } //multi-channel support --------------------------// function poolfn() { if (!_instance.isPool) return false; var args = argsToArray( null, arguments ), func = args.shift(); for( var i = 0; i < _pool.length; i++ ) { _pool[ i ][ func ].apply( _pool[ i ], args ); } return true; } function argsToArray( array, args ) { return ( array instanceof Array ) ? array : Array.prototype.slice.call( args ); } //look for available channel function getChannel(channelIdx) { if (channelIdx !== undefined) return _pool[channelIdx]; for (var i =0; i<_pool.length; i++) { if (_pool[i].isEnded() || _pool[i].isPaused()) return _pool[i]; } return false; } //-----------------------------------------------------// // init if ( supported && src ) { for(var i in buzz.defaults ) { if(buzz.defaults.hasOwnProperty(i)) { options[ i ] = options[ i ] || buzz.defaults[ i ]; } } // multi-channel support -------------------// if (options.channels > 1) //pool or simple sound instance ? { this.isPool = true; var poolsCount = options.channels; for (var i=0; i<poolsCount; i++) { options.channels = 0; _pool.push(new buzz.sound(src, options)); //clone original sound but only initialize one channel per clone } //init first channel this.sound = _pool[0].sound; return; } //-----------------------------------------// this.sound = document.createElement( 'audio' ); if ( src instanceof Array ) { for( var j in src ) { if(src.hasOwnProperty(j)) { addSource( this.sound, src[ j ] ); } } } else if ( options.formats.length ) { for( var k in options.formats ) { if(options.formats.hasOwnProperty(k)) { addSource( this.sound, src + '.' + options.formats[ k ] ); } } } else { addSource( this.sound, src ); } if ( options.loop ) { this.loop(); } if ( options.autoplay ) { this.sound.autoplay = 'autoplay'; } if ( options.preload === true ) { this.sound.preload = 'auto'; } else if ( options.preload === false ) { this.sound.preload = 'none'; } else { this.sound.preload = options.preload; } this.setVolume( options.volume ); buzz.sounds.push( this ); } }, group: function( sounds ) { sounds = argsToArray( sounds, arguments ); // publics this.getSounds = function() { return sounds; }; this.add = function( soundArray ) { soundArray = argsToArray( soundArray, arguments ); for( var a = 0; a < soundArray.length; a++ ) { sounds.push( soundArray[ a ] ); } }; this.remove = function( soundArray ) { soundArray = argsToArray( soundArray, arguments ); for( var a = 0; a < soundArray.length; a++ ) { for( var i = 0; i < sounds.length; i++ ) { if ( sounds[ i ] == soundArray[ a ] ) { sounds.splice(i, 1); break; } } } }; this.load = function() { fn( 'load' ); return this; }; this.play = function() { fn( 'play' ); return this; }; this.togglePlay = function( ) { fn( 'togglePlay' ); return this; }; this.pause = function( time ) { fn( 'pause', time ); return this; }; this.stop = function() { fn( 'stop' ); return this; }; this.mute = function() { fn( 'mute' ); return this; }; this.unmute = function() { fn( 'unmute' ); return this; }; this.toggleMute = function() { fn( 'toggleMute' ); return this; }; this.setVolume = function( volume ) { fn( 'setVolume', volume ); return this; }; this.increaseVolume = function( value ) { fn( 'increaseVolume', value ); return this; }; this.decreaseVolume = function( value ) { fn( 'decreaseVolume', value ); return this; }; this.loop = function() { fn( 'loop' ); return this; }; this.unloop = function() { fn( 'unloop' ); return this; }; this.setTime = function( time ) { fn( 'setTime', time ); return this; }; this.set = function( key, value ) { fn( 'set', key, value ); return this; }; this.bind = function( type, func ) { fn( 'bind', type, func ); return this; }; this.unbind = function( type ) { fn( 'unbind', type ); return this; }; this.bindOnce = function( type, func ) { fn( 'bindOnce', type, func ); return this; }; this.trigger = function( type ) { fn( 'trigger', type ); return this; }; this.fade = function( from, to, duration, callback ) { fn( 'fade', from, to, duration, callback ); return this; }; this.fadeIn = function( duration, callback ) { fn( 'fadeIn', duration, callback ); return this; }; this.fadeOut = function( duration, callback ) { fn( 'fadeOut', duration, callback ); return this; }; // privates function fn() { var args = argsToArray( null, arguments ), func = args.shift(); for( var i = 0; i < sounds.length; i++ ) { sounds[ i ][ func ].apply( sounds[ i ], args ); } } function argsToArray( array, args ) { return ( array instanceof Array ) ? array : Array.prototype.slice.call( args ); } }, all: function() { return new buzz.group( buzz.sounds ); }, isSupported: function() { return !!buzz.el.canPlayType; }, isOGGSupported: function() { return !!buzz.el.canPlayType && buzz.el.canPlayType( 'audio/ogg; codecs="vorbis"' ); }, isWAVSupported: function() { return !!buzz.el.canPlayType && buzz.el.canPlayType( 'audio/wav; codecs="1"' ); }, isMP3Supported: function() { return !!buzz.el.canPlayType && buzz.el.canPlayType( 'audio/mpeg;' ); }, isAACSupported: function() { return !!buzz.el.canPlayType && ( buzz.el.canPlayType( 'audio/x-m4a;' ) || buzz.el.canPlayType( 'audio/aac;' ) ); }, toTimer: function( time, withHours ) { var h, m, s; h = Math.floor( time / 3600 ); h = isNaN( h ) ? '--' : ( h >= 10 ) ? h : '0' + h; m = withHours ? Math.floor( time / 60 % 60 ) : Math.floor( time / 60 ); m = isNaN( m ) ? '--' : ( m >= 10 ) ? m : '0' + m; s = Math.floor( time % 60 ); s = isNaN( s ) ? '--' : ( s >= 10 ) ? s : '0' + s; return withHours ? h + ':' + m + ':' + s : m + ':' + s; }, fromTimer: function( time ) { var splits = time.toString().split( ':' ); if ( splits && splits.length == 3 ) { time = ( parseInt( splits[ 0 ], 10 ) * 3600 ) + ( parseInt(splits[ 1 ], 10 ) * 60 ) + parseInt( splits[ 2 ], 10 ); } if ( splits && splits.length == 2 ) { time = ( parseInt( splits[ 0 ], 10 ) * 60 ) + parseInt( splits[ 1 ], 10 ); } return time; }, toPercent: function( value, total, decimal ) { var r = Math.pow( 10, decimal || 0 ); return Math.round( ( ( value * 100 ) / total ) * r ) / r; }, fromPercent: function( percent, total, decimal ) { var r = Math.pow( 10, decimal || 0 ); return Math.round( ( ( total / 100 ) * percent ) * r ) / r; } };
kushsolitary/Inkpen
public/assets/js/buzz.js
JavaScript
gpl-3.0
26,388
/** * Module dependencies */ var _ = require('@sailshq/lodash'); var getDisplayTypeLabel = require('./get-display-type-label'); /** * getNounPhrase() * * Given an RTTC "display type" string (and some options) * return an appropriate human-readable noun-phrase. * Useful for error messages, user interfaces, etc. * * @required {String} type * Recognizes any of the standard RTTC types: * • string * • number * • boolean * • lamda * • dictionary * • array * • json * • ref * * * @optional {Dictionary} options * * @property {Boolean} plural * If enabled, the returned noun phrase will be plural. * @default false * * @property {Boolean} completeSentence * If enabled, a complete sentence with a capital letter * & ending punctuation (a period) will be returned. * Otherwise (by default), the returned noun phrase will * be a fragment designed for use in an existing sentence. * @default false * * @property {String} determiner * One of: * • "the" (definite article) * • "a" (indefinite article) * • "any" (existential qualifier) * • "" (no determiner) * > Note that if "a" is specified, either "a" or "an" will be used, * > whichever is more appropriate. * > (for more background, see https://en.wikipedia.org/wiki/Article_(grammar) * > and/or https://en.wikipedia.org/wiki/English_determiners) * @default "a" (or "", if plural) * * * @return {String} [noun phrase] */ module.exports = function getNounPhrase(type, options){ if (typeof type !== 'string') { throw new Error('Usage error: rttc.getNounPhrase() expects a string display type such as '+ '`dictionary` or `ref`. If you are trying to get the noun phrase for an exemplar, do '+ '`rttc.getNounPhrase(rttc.inferDisplayType(exemplar))`. If you are trying to get a noun '+ 'phrase to represent voidness (i.e. null exemplar), then you should determine that on a '+ 'case-by-case basis-- there\'s no good sane default.'); } // Set up defaults options = options || {}; options = _.defaults(options, { plural: false, completeSentence: false, determiner: !options.plural ? 'a' : '' }); // Tolerate "an" for "a" if (options.determiner === 'an') { options.determiner = 'a'; } // Validate determiner if (!_.contains(['the', 'a', 'any', ''], options.determiner)) { throw new Error('Usage error: Unrecognized `determiner` option: `'+options.determiner+'`. '+ 'Should be either "the", "a", "any", or "". (defaults to "a", or "" if plural)'); } // Ensure we're not trying to use "a" in a plural noun phrase. if (options.plural && options.determiner === 'a') { throw new Error('Usage error: Cannot use that determiner ("a") to generate a plural noun phrase. '+ 'Trust me, it wouldn\'t sound right.'); } // Compute the display type label that will be used below. var displayTypeLabel = getDisplayTypeLabel(type, { capitalization: 'fragment', plural: options.plural }); // Determine the appropriate naked noun phrase. // (i.e. with determiner, but without ending punctuation or start-sentence capitalization) var nounPhrase; if (type === 'string') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'number') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'boolean') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'lamda') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'dictionary') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'array') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'an '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'json') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } // for future reference, this is where we could do: // > "might be a string, number, boolean, dictionary, array, or even null" } else if (type === 'ref') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else { throw new Error('Unknown type: `'+type+'`'); } // Finally, deal with sentence capitalization and ending punctuation (if relevant). if (options.completeSentence) { nounPhrase = nounPhrase[0].toUpperCase() + nounPhrase.slice(1); nounPhrase += '.'; } // And return our noun phrase. return nounPhrase; };
deshbandhu-renovite/receipt-eCommerce
node_modules/rttc/lib/get-noun-phrase.js
JavaScript
gpl-3.0
6,514
/*jslint browser: true*/ /*global Audio, Drupal*/ /** * @file * Displays Audio viewer. */ (function ($, Drupal) { 'use strict'; /** * If initialized. * @type {boolean} */ var initialized; /** * Unique HTML id. * @type {string} */ var base; function init(context,settings){ if (!initialized){ initialized = true; if ($('audio')[0].textTracks.length > 0) { $('audio')[0].textTracks[0].oncuechange = function() { var currentCue = this.activeCues[0].text; $('#audioTrack').html(currentCue); } } } } Drupal.Audio = Drupal.Audio || {}; /** * Initialize the Audio Viewer. */ Drupal.behaviors.Audio = { attach: function (context, settings) { init(context,settings); }, detach: function () { } }; })(jQuery, Drupal);
nigelgbanks/islandora
modules/islandora_audio/js/audio.js
JavaScript
gpl-3.0
967
(function (window) { const settings = { info: {}, user: {}, currentTime: 0, specificUser: false, init() { // default settings applyed from here const coreSettings = virtualclassSetting.settings; virtualclass.settings.info = virtualclass.settings.parseSettings(coreSettings); const userSetting = localStorage.getItem('userSettings'); if (userSetting) { // console.log('setting ', userSetting); virtualclass.settings.user = JSON.parse(userSetting); } this.recording.init(); // virtualclass.settings.info.trimRecordings = true; }, triggerSettings() { this.qaMarkNotes(virtualclass.settings.info.qaMarkNotes); this.askQuestion(virtualclass.settings.info.askQuestion); this.qaAnswer(virtualclass.settings.info.qaAnswer); this.qaComment(virtualclass.settings.info.qaComment); this.qaUpvote(virtualclass.settings.info.qaUpvote); }, // settings object values assign to array for get a hax code settingsToHex(s) { const localSettings = []; localSettings[0] = +s.allowoverride; localSettings[1] = +s.studentaudio; localSettings[2] = +s.studentvideo; localSettings[3] = +s.studentpc; localSettings[4] = +s.studentgc; localSettings[5] = +s.askQuestion; localSettings[6] = +s.userlist; localSettings[7] = +s.enableRecording; localSettings[8] = +s.recAllowpresentorAVcontrol; localSettings[9] = +s.recShowPresentorRecordingStatus; localSettings[10] = +s.attendeeAV; localSettings[11] = +s.recallowattendeeAVcontrol; localSettings[12] = +s.showAttendeeRecordingStatus; localSettings[13] = +s.trimRecordings; localSettings[14] = +s.attendeerecording; localSettings[15] = +s.qaMarkNotes; localSettings[16] = +s.qaAnswer; localSettings[17] = +s.qaComment; localSettings[18] = +s.qaUpvote; localSettings[19] = +s.upcomingSetting; return virtualclass.settings.binaryToHex(localSettings.join('')); }, // return data into true, false // student side parseSettings(s) { // console.log('====> Settings parse'); const parsedSettings = {}; let localSettings = virtualclass.settings.hexToBinary(s); localSettings = localSettings.split(''); parsedSettings.allowoverride = !!+localSettings[0]; parsedSettings.studentaudio = !!+localSettings[1]; parsedSettings.studentvideo = !!+localSettings[2]; parsedSettings.studentpc = !!+localSettings[3]; parsedSettings.studentgc = !!+localSettings[4]; parsedSettings.askQuestion = !!+localSettings[5]; parsedSettings.userlist = !!+localSettings[6]; parsedSettings.enableRecording = !!+localSettings[7]; parsedSettings.recAllowpresentorAVcontrol = !!+localSettings[8]; parsedSettings.recShowPresentorRecordingStatus = !!+localSettings[9]; parsedSettings.attendeeAV = !!+localSettings[10]; parsedSettings.recallowattendeeAVcontrol = !!+localSettings[11]; parsedSettings.showAttendeeRecordingStatus = !!+localSettings[12]; parsedSettings.trimRecordings = !!+localSettings[13]; parsedSettings.attendeerecording = !!+localSettings[14]; parsedSettings.qaMarkNotes = !!+localSettings[15]; parsedSettings.qaAnswer = !!+localSettings[16]; parsedSettings.qaComment = !!+localSettings[17]; parsedSettings.qaUpvote = !!+localSettings[18]; parsedSettings.upcomingSetting = !!+localSettings[19]; return parsedSettings; }, // Hex convert into binary hexToBinary(s) { let i; let ret = ''; // lookup table for easier conversion. '0' characters are padded for '1' to '7' const lookupTable = { 0: '0000', 1: '0001', 2: '0010', 3: '0011', 4: '0100', 5: '0101', 6: '0110', 7: '0111', 8: '1000', 9: '1001', a: '1010', b: '1011', c: '1100', d: '1101', e: '1110', f: '1111', A: '1010', B: '1011', C: '1100', D: '1101', E: '1110', F: '1111', }; for (i = 0; i < s.length; i += 1) { if (Object.prototype.hasOwnProperty.call(lookupTable, s[i])) { ret += lookupTable[s[i]]; } else { return false; } } return ret; }, // convert binary into Hex binaryToHex(s) { let i; let k; let part; let accum; let ret = ''; for (i = s.length - 1; i >= 3; i -= 4) { // extract out in substrings of 4 and convert to hex part = s.substr(i + 1 - 4, 4); accum = 0; for (k = 0; k < 4; k += 1) { if (part[k] !== '0' && part[k] !== '1') { // invalid character return false; } // compute the length 4 substring accum = accum * 2 + parseInt(part[k], 10); } if (accum >= 10) { // 'A' to 'F' ret = String.fromCharCode(accum - 10 + 'A'.charCodeAt(0)) + ret; } else { // '0' to '9' ret = String(accum) + ret; } } // remaining characters, i = 0, 1, or 2 if (i >= 0) { accum = 0; // convert from front for (k = 0; k <= i; k += 1) { if (s[k] !== '0' && s[k] !== '1') { return false; } accum = accum * 2 + parseInt(s[k], 10); } // 3 bits, value cannot exceed 2^3 - 1 = 7, just convert ret = String(accum) + ret; } return ret; }, // Object's properties value true or false into binary applySettings(value, settingName, userId) { if (roles.hasControls()) { if ((value === true || value === false) && Object.prototype.hasOwnProperty.call(virtualclass.settings.info, settingName)) { if (typeof userId === 'undefined') { virtualclass.settings.applyPresentorGlobalSetting(value, settingName); if (settingName === 'askQuestion' || settingName === 'qaMarkNotes') { this.triggerSettings(value); } // virtualclass.setPrvUser(); } else { virtualclass.settings.applySpecificAttendeeSetting(value, settingName, userId); } return true; } return false; } }, applyPresentorGlobalSetting(value, settingName) { localStorage.removeItem('userSettings'); virtualclass.settings.info[settingName] = value; const str = virtualclass.settings.settingsToHex(virtualclass.settings.info); ioAdapter.mustSend({ cf: 'settings', Hex: str, time: Date.now() }); virtualclassSetting.settings = str; // console.log('====> Settings ', str); for (const propname in virtualclass.settings.user) { virtualclass.user.control.changeAttribute(propname, virtualclass.gObj.testChatDiv.shadowRoot.getElementById(`${propname}contrAudImg`), virtualclass.settings.info.studentaudio, 'audio', 'aud'); virtualclass.user.control.changeAttribute(propname, virtualclass.gObj.testChatDiv.shadowRoot.getElementById(`${propname}contrChatImg`), virtualclass.settings.info.studentpc, 'chat', 'chat'); } virtualclass.settings.user = {}; }, applySpecificAttendeeSetting(value, settingName, userId) { let specificSettings; if (Object.prototype.hasOwnProperty.call(virtualclass.settings.user, userId)) { const user = virtualclass.settings.user[userId]; const setting = virtualclass.settings.parseSettings(user); setting[settingName] = value; specificSettings = virtualclass.settings.settingsToHex(setting); } else { const individualSetting = {}; for (const propname in virtualclass.settings.info) { individualSetting[propname] = virtualclass.settings.info[propname]; } individualSetting[settingName] = value; specificSettings = virtualclass.settings.settingsToHex(individualSetting); } ioAdapter.mustSendUser({ cf: 'settings', Hex: specificSettings, toUser: userId, time: Date.now(), }, userId); virtualclass.settings.user[userId] = specificSettings; localStorage.setItem('userSettings', JSON.stringify(virtualclass.settings.user)); }, applyAttendeeSetting(obj) { // console.log('my setting change ', JSON.stringify(obj)); const rec = ['enableRecording', 'recAllowpresentorAVcontrol', 'recShowPresentorRecordingStatus', 'attendeeAV', 'recallowattendeeAVcontrol', 'showAttendeeRecordingStatus', 'attendeerecording']; for (const propname in obj) { if (virtualclass.settings.info[propname] !== obj[propname]) { if (virtualclass.isPlayMode) { if (propname !== 'qaMarkNotes' && propname !== 'askQuestion' && propname !== 'qaAnswer' && propname !== 'qaUpvote' && propname !== 'qaComment') { virtualclass.settings.info[propname] = obj[propname]; } } else { virtualclass.settings.info[propname] = obj[propname]; } if (propname !== 'trimRecordings') { // avoid trim recordings const recSettings = rec.indexOf(propname); const value = (recSettings !== -1) ? obj : obj[propname]; if (virtualclass.isPlayMode) { if (propname !== 'qaMarkNotes' && propname !== 'askQuestion' && propname !== 'qaAnswer' && propname !== 'qaUpvote' && propname !== 'qaComment') { virtualclass.settings[propname](value); } } else { virtualclass.settings[propname](value); } } } } }, // Apply settings on student side onMessage(msg, userId) { if (roles.hasControls()) { if (typeof msg === 'string' && userId == null) { if (!virtualclass.gObj.refreshSession) { virtualclass.settings.info = virtualclass.settings.parseSettings(msg); } delete virtualclass.gObj.refreshSession; // virtualclass.settings.info = virtualclass.settings.parseSettings(msg); } } else { if (typeof msg === 'string' && roles.isStudent()) { this.specificUser = userId ? true : false; // console.log('====> Settings received ', msg); const stdSettings = virtualclass.settings.parseSettings(msg); this.applyAttendeeSetting(stdSettings); } else { this.recording.triggerSetting(msg); } } }, // Mute or Unmute all student audio or particular student mute or unmute studentaudio(value) { if (roles.isStudent()) { if (value === true) { virtualclass.user.control.audioWidgetEnable(true); virtualclass.gObj.audioEnable = true; } else if (value === false) { const speakerPressOnce = document.querySelector('#speakerPressOnce'); if (speakerPressOnce.dataset.audioPlaying === true || speakerPressOnce.dataset.audioPlaying === 'true') { virtualclass.media.audio.clickOnceSpeaker('speakerPressOnce'); } virtualclass.user.control.audioDisable(); virtualclass.gObj.audioEnable = false; } } }, allowoverride() { // console.log('TO DO'); }, studentpc(value) { // student chat enable/disable if (roles.isStudent()) { if (value === true) { virtualclass.user.control.allChatEnable('pc'); } else if (value === false) { virtualclass.user.control.disbaleAllChatBox(); } } }, studentgc(value) { // student group chat enable/disable if (roles.isStudent()) { if (value === true) { virtualclass.user.control.allChatEnable('gc'); } else { virtualclass.user.control.disableCommonChat(); } } }, studentvideo(value) { // All student video enable, disable if (roles.isStudent()) { const sw = document.querySelector('.videoSwitchCont #videoSwitch'); if (sw.classList.contains('off') && value === false) { // console.log('do nothing'); } else if (sw.classList.contains('on') && value === true) { // console.log('do nothing'); } else if (sw.classList.contains('on') && value === false) { virtualclass.vutil.videoHandler('off'); } const action = (value === false) ? 'disable' : 'enable'; virtualclass.videoHost.toggleVideoMsg(action); } }, askQuestion(value) { const askQuestion = document.querySelector('#congAskQuestion'); const rightSubContainer = document.getElementById('virtualclassAppRightPanel'); if (value === true) { askQuestion.classList.remove('askQuestionDisable'); askQuestion.classList.add('askQuestionEnable'); rightSubContainer.dataset.askQuestion = 'askQuestionEnable'; } else { // document.querySelector('#user_list').click(); askQuestion.classList.remove('askQuestionEnable'); askQuestion.classList.add('askQuestionDisable'); rightSubContainer.dataset.askQuestion = 'askQuestionDisable'; } }, userlist(value) { if (roles.isStudent()) { const userList = document.querySelector('#memlist'); if (userList !== null) { const searchUserInput = document.querySelector('#congchatBarInput #congreaUserSearch'); const vmlist = document.querySelector('#user_list.vmchat_bar_button'); // const askQuestionElem = document.querySelector('#congAskQuestion'); // const notesElem = document.querySelector('#virtualclassnote'); if (value === true) { userList.classList.remove('hideList'); searchUserInput.classList.remove('hideInput'); vmlist.classList.remove('disable'); } else { userList.classList.add('hideList'); searchUserInput.classList.add('hideInput'); vmlist.classList.add('disable'); // TODO remove commented code // if (!askQuestionElem.classList.contains('active') && !notesElem.classList.contains('active')) { // const vmchat = document.querySelector('.vmchat_room_bt .inner_bt'); // vmchat.click(); // } handleCommonChat(); } } } }, attendeerecording(obj) { virtualclass.settings.recordingSettings(obj); }, enableRecording(obj) { virtualclass.settings.recordingSettings(obj); }, recAllowpresentorAVcontrol(obj) { virtualclass.settings.recordingSettings(obj); }, recShowPresentorRecordingStatus(obj) { virtualclass.settings.recordingSettings(obj); }, attendeeAV(obj) { virtualclass.settings.recordingSettings(obj); }, recallowattendeeAVcontrol(obj) { virtualclass.settings.recordingSettings(obj); }, showAttendeeRecordingStatus(obj) { virtualclass.settings.recordingSettings(obj); }, qaMarkNotes(value) { // TODO handle on default settings const notesElem = document.querySelector('#virtualclassnote'); const rightSubContainer = document.getElementById('virtualclassAppRightPanel'); const bookmarkElem = document.querySelector('#bookmark'); if (value === true) { notesElem.classList.remove('notesDisable'); notesElem.classList.add('notesEnable'); bookmarkElem.classList.remove('bookmarkDisable'); bookmarkElem.classList.add('bookmarkEnable'); rightSubContainer.dataset.qaNote = 'enable'; } else { notesElem.classList.remove('notesEnable'); notesElem.classList.add('notesDisable'); bookmarkElem.classList.remove('bookmarkEnable'); bookmarkElem.classList.add('bookmarkDisable'); rightSubContainer.dataset.qaNote = 'disbale'; } }, qaAnswer(value) { if (!virtualclass.vutil.checkUserRole()) { // console.log('setting comp qA ', value); const controlsElem = document.querySelector('#askQuestion'); if (controlsElem) { if (value === true) { document.querySelector('#askQuestion').dataset.answer = 'enable'; } else if (value === false) { document.querySelector('#askQuestion').dataset.answer = 'disable'; } } } }, qaComment(value) { if (!virtualclass.vutil.checkUserRole()) { const controlsElem = document.querySelector('#askQuestion'); if (controlsElem) { if (value === true) { document.querySelector('#askQuestion').dataset.comment = 'enable'; } else if (value === false) { document.querySelector('#askQuestion').dataset.comment = 'disable'; } } } }, qaUpvote(value) { if (!virtualclass.vutil.checkUserRole()) { const controlsElem = document.querySelector('#askQuestion'); if (controlsElem) { if (value === true) { document.querySelector('#askQuestion').dataset.upvote = 'enable'; } else if (value === false) { document.querySelector('#askQuestion').dataset.upvote = 'disable'; } } } }, upcomingSetting() { // nothing to do }, recordingSettings(obj) { const buttonStatus = virtualclass.settings.recording.recordingStatus(obj); virtualclass.settings.recording.showRecordingButton(buttonStatus); }, recording: { recordingButton: 0, // 0 - Do not show button, 1 - show button but no click, 2 - show button and clickable attendeeButtonAction: true, init() { // recording status, button show or hide, override setting const buttonSettings = JSON.parse(localStorage.getItem('recordingButton')); if (buttonSettings === null) { this.recordingButton = this.recordingStatus(); } else { this.recordingButton = buttonSettings; } const atbuttonSettings = JSON.parse(localStorage.getItem('attendeeButtonAction')); if (atbuttonSettings !== null) { this.attendeeButtonAction = atbuttonSettings; } this.showRecordingButton(); }, toggleRecordingButton() { if (this.recordingButton === 21) { this.recordingButton = 11; } else if (this.recordingButton === 11) { this.recordingButton = 21; } ioAdapter.setRecording(); localStorage.setItem('recordingButton', this.recordingButton); this.showRecordingButton(); if (roles.hasControls()) { ioAdapter.mustSend({ ac: this.recordingButton, cf: 'recs' }); } else if (this.recordingButton === 21) { this.attendeeButtonAction = true; localStorage.setItem('attendeeButtonAction', true); } else { this.attendeeButtonAction = false; localStorage.setItem('attendeeButtonAction', false); } }, showRecordingButton(buttonStatus) { // recording button button show or hide if (typeof buttonStatus !== 'undefined') { this.recordingButton = buttonStatus; } const recordingButton = virtualclass.getTemplate('recordingButton'); let context; this.removeButton(); switch (this.recordingButton) { case 10: context = { ten: 'ten' }; break; case 11: context = { eleven: 'eleven' }; break; case 20: context = { twenty: 'twenty' }; break; case 21: context = { twentyone: 'twentyone' }; break; default: return; } const temp = recordingButton(context); const elem = document.querySelector('#virtualclassAppFooterPanel #networkStatusContainer'); // this.removeButton(); elem.insertAdjacentHTML('afterend', temp); const recording = document.getElementById('recording'); if (this.recordingButton === 21 || this.recordingButton === 11) { this.attachHandler(recording); } }, removeButton() { const recording = document.getElementById('recording'); if (recording !== null) { recording.remove(); } }, attachHandler(recording) { recording.addEventListener('click', this.recordingButtonAction.bind(this, recording)); }, recordingButtonAction() { // On recording button action send to student if (this.recordingButton === 21 || this.recordingButton === 11) { this.toggleRecordingButton(); } }, recordingStatus(obj) { let settingsInfo; if (typeof obj !== 'undefined') { settingsInfo = obj; } else { settingsInfo = virtualclass.settings.info; } if (!settingsInfo.enableRecording) { if (roles.hasControls()) { if (settingsInfo.recShowPresentorRecordingStatus) { return 10; } } else if (settingsInfo.showAttendeeRecordingStatus) { return 10; } return 0; } if (roles.hasControls()) { if (settingsInfo.recAllowpresentorAVcontrol) { return 21; } if (settingsInfo.recShowPresentorRecordingStatus) { return 20; } return 22; } if (settingsInfo.attendeerecording) { if (settingsInfo.attendeeAV) { if (settingsInfo.recallowattendeeAVcontrol) { return 21; } if (settingsInfo.showAttendeeRecordingStatus) { return 20; } return 22; } if (settingsInfo.showAttendeeRecordingStatus) { return 10; } return 0; } return 0; }, sendYesOrNo() { if (this.recordingButton === 20 || this.recordingButton === 21 || this.recordingButton === 22) { return 'yes'; } return 'no'; }, triggerSetting(message) { if (roles.isStudent()) { if (!virtualclass.settings.info.attendeeAV) { this.recordingButton = 0; ioAdapter.setRecording(); this.showRecordingButton(); return; } switch (message.ac) { case 11: this.recordingButton = 10; break; case 21: if (virtualclass.settings.info.recallowattendeeAVcontrol) { if (this.attendeeButtonAction) { this.recordingButton = 21; } else { this.recordingButton = 11; } } else { this.recordingButton = 20; } break; default: return; } ioAdapter.setRecording(); localStorage.setItem('recordingButton', this.recordingButton); if (virtualclass.settings.info.showAttendeeRecordingStatus) { this.showRecordingButton(); } } }, }, userAudioIcon() { if ((virtualclass.settings.info.studentaudio === false)) { virtualclass.gObj.audioEnable = false; virtualclass.user.control.audioDisable(true); } else if (virtualclass.settings.info.studentaudio === true) { virtualclass.gObj.audioEnable = true; virtualclass.user.control.audioWidgetEnable(true); } else if (virtualclass.settings.info.studentaudio !== true) { virtualclass.user.control.audioDisable(); } }, userVideoIcon() { if (virtualclass.settings.info.studentvideo === false && roles.isStudent()) { virtualclass.vutil.videoHandler('off'); virtualclass.user.control.videoDisable(); } else { // todo, check it properly on page refresh if (roles.isStudent() && virtualclass.settings.info.studentvideo !== true) { if (virtualclass.settings.info.studentvideo !== undefined) { virtualclass.vutil.videoHandler('off'); virtualclass.videoHost.toggleVideoMsg('disable'); } } else { virtualclass.user.control.videoEnable(); if (roles.isStudent()) { // after refresh video disable when user enable his video etc. virtualclass.vutil.videoHandler('off'); } } if (virtualclass.settings.info.studentvideo === true) { virtualclass.user.control.videoEnable(); } } }, }; window.settings = settings; }(window));
pinky28/virtualclass
src/settings.js
JavaScript
gpl-3.0
24,868
'use strict' import { Github as GithubAPI } from '../utils/github' const Github = new GithubAPI() import Result from '../models/result' import * as utils from '../utils/utils' function _processItems (items, oncomplete, onpromise) { var users_promises = items.map((repo) => { return new Promise((resolve, reject) => { _getContributors(repo['contributors_url'], repo, (res) => { resolve(res) }, (err) => { reject(err) }) onpromise() }) }) Promise.all(users_promises) .then(oncomplete) } function _getContributors (url, repo, oncomplete, onerror) { Github.make_auth_request(url, (contribs) => { repo['total'] = contribs.reduce((memo, user) => { return user['contributions'] + memo }, 0) oncomplete({ contribs, repo }) }, (error) => { onerror(error) }) } function _createUsersData (repos) { let users = new Map() for (let repo of repos) { for (let contrib of repo['contribs']) { if (!users.contains(contrib['login'])) { users.set(contrib['login'], { 'login': contrib['login'], 'url': contrib['url'], 'repos': [] }) } users.get(contrib['login'])['repos'].push({ 'login': contrib['login'], 'url': contrib['url'], 'contributions': contrib['contributions'], 'total': repo['total'], 'repo': repo['repo'], 'author': contrib['login'] === repo['repo']['owner']['login'] }) } } return users } function _getUsersInfo (users, oncomplete) { var user_data_promises = users.vals().map((user) => { return new Promise((resolve, reject) => { Github.make_auth_request(user['url'], (value) => { users.get(user['login'])['data'] = value resolve(value) }) }) }) Promise.all(user_data_promises) .then(oncomplete) } function _getUsersScore (users, oncomplete) { for (let user of users) { user['score'] = user['repos'].reduce((memo, repo) => { let repo_score = (repo['contributions'] / repo['repo']['total']) * (repo['repo']['total'] + repo['repo']['stargazers_count'] + repo['repo']['watchers_count'] + repo['repo']['forks_count'] + repo['repo']['score'] * 2) return memo + repo_score }, user['data']['followers'] * 2) oncomplete() } } function _saveUsers (users, id, oncomplete, onerror) { for (let user of users) { let res = new Result() res.id = utils.guid() res.request = id res.score = user['score'] res.repos_count = user['repos'].length res.contributions_count = user['repos'].reduce((memo, repo) => { return memo + repo['contributions'] }, 0) res.followers = user['data']['followers'] res.object = JSON.stringify(user) res.save((err, res) => { if (err) onerror(err) else oncomplete() }) } } function _search (keywords, langs, req) { Github.search(keywords, langs, (resp) => { req.status = 'got repositories, processing results' req.percent = 0 req.save() let index = 0 _processItems(resp['items'], (res) => { let users = _createUsersData(res) _getUsersInfo(users, () => { const length = users.length req.status = 'got list of users, sorting' req.percent = 0 req.save() let index_scores = 0 _getUsersScore(users, () => { req.percent = (index_scores + 1) * 100.0 / length index_scores += 1 req.save() }) req.status = 'sorted, saving results' req.percent = 0 req.save() let index_users = 0 _saveUsers(users, req.id, () => { req.percent = (index_users + 1) * 100.0 / length index_users += 1 req.save() }, (err) => { req.status = `Error saving, ${err}` req.save() }) req.status = 'done' req.percent = 100 req.save() }) }, () => { req.percent = (index + 1) * 100.0 / resp['items'].length index += 1 req.save() }) }) } export function search (keywords, langs, req, timeout) { if (!timeout) timeout = 100 setTimeout(_search, 100, keywords, langs, req) }
AgustinCB/programmmrs_api
src/app/sources/github.js
JavaScript
gpl-3.0
4,186
/* _____________________________________________________________________________ * | | * | === WARNING: GADGET FILE === | * | Changes to this page affect many users. | * | Please discuss changes on the talk page or on [[MediaWiki_talk:Gadgets-definition]] before editing. | * |_____________________________________________________________________________| * * "join" feature, to be used by the Wikimedia Foundation's Grants Programme, */ //<nowiki> importStylesheet('User:Jeph_paul/join.css'); var joinGadget = function(){ /* Variables */ var dialog = null; //The path to the config file this.joinInterfaceMessages = 'User:Jeph_paul/joinInterfaceMessages'; this.joinConfig = 'User:Jeph_paul/joinconfig'; //The time taken for the page to scroll to the feedback (milliseconds) var feedbackScrollTime = 2000; //The time taken for the feedback to disappear (milliseconds) var feedbackDisappearDelay = 10000; var infobox = ''; var roleDict = {}; var api = new mw.Api(); var that = this; /* Functions */ //To set cookie after feedback/joinment has been added var setFeedbackCookie = function(){ $.cookie('joinFeedback',true); }; //To add the page to the user's watch list var watchPage = function (){ return api.watch(mw.config.get('wgCanonicalNamespace')+':'+mw.config.get('wgTitle')); }; //To display error message in case of an error var errorMessage = function(){ $('.joinError').show(); }; //To detect the type of grant/page type. IEG,PEG etc var grantType = function(joinConfig){ var grant = mw.config.get('wgTitle').split('/')[0]; if (grant in joinConfig){ return joinConfig[grant]; } else{ return joinConfig['default']; } }; //To add the joinment thank you message //remove hardcoding of the joinment/join id in the rendered html this.joinFeedback = function(){ var li = $('#'+$.trim(grantType(joinConfig)['section'])).parent().next().find('li').eq(-1); speechBubble = li.append($('<div class="joinSpeechBubbleContainer"></div>').html('<div class="joinSpeechBubble">\ <span localize="message-feedback">Thank You</span></div><div class="joinArrowDown"></div>')).find('.joinSpeechBubbleContainer'); var width = li.css('display','inline-block').width(); li.css('display',''); li.css('position','relative'); speechBubble.css('left',width/2+'px'); $('[localize=message-feedback]').html(grantType(joinInterfaceMessages)['message-feedback']); $("body, html").animate({ scrollTop : li[0].offsetTop}, feedbackScrollTime); setTimeout(function(){ speechBubble.hide();},feedbackDisappearDelay); }; //To check if feedback has been added & has been set so in the cookie this.checkFeedbackCookie = function(){ if($.cookie('joinFeedback')){ $.cookie('joinFeedback',null); return true; } else{ return false; } }; //To detect the language fo the page this.userLanguage = function(){ return mw.config.get('wgUserLanguage'); }; this.contentLanguage = function(){ return mw.config.get('wgContentLanguage'); }; //To localize the gadget interface messages based on the language detected above var localizeGadget = function (gadgetClass,localizeDict){ $(gadgetClass+' [localize]').each(function(){ var localizeValue = $.trim(localizeDict[$(this).attr('localize')]); if($(this).attr('value')){ $(this).attr('value',localizeValue); } else if($(this).attr('placeholder')){ $(this).attr('placeholder',localizeValue); } else if($(this).attr('data-placeholder')){ $(this).attr('data-placeholder',localizeValue); } else{ $(this).html(localizeValue); } }); }; //To remove extra spaces from the joinment string var cleanupText = function(text){ text = $.trim(text)+' '; var indexOf = text.indexOf('~~~~'); if ( indexOf == -1 ){ return text; } else{ return text.slice(0,indexOf)+text.slice(indexOf+4); } }; //To create the dialog box. It is created once on the time of page load var createDialog = function(){ dialog = $( "<div id='joinDialog'></div>" ) .html( '<select class="roleSelect" localize="placeholder-role" data-placeholder="Select a role">\ <option></option>\ </select>\ <div localize="message-description" class="joinDescription">Tell us how you would like to help</div>\ <div class="error joinHide joinError" localize="message-error">An error occured</div>\ <textarea rows="5" cols="10" placeholder="Add your comment" id="joinComment" class="" localize="placeholder-comment"></textarea>\ <span localize="message-signature" class="gadgetSignature">Your signature will be added automatically</span>\ <div class="gadgetControls">\ <a href="#" localize="button-cancel" class="mw-ui-button cancel mw-ui-quiet">Cancel</a>\ <input type="submit" localize="button-join" class="mw-ui-button mw-ui-constructive add-join" disabled localize="button" value="Join"></input>\ </div>' ).dialog({ dialogClass: 'joinGadget', autoOpen: false, title: 'join Comment', width: '495px', modal: true, closeOnEscape: true, resizable: false, draggable: false, close: function( event, ui ) { $('#joinComment').val(''); } }); $('.add-join').click(function(){ //var joinRole = grantType(joinConfig)['message']+' '+$('.roleSelect').val().replace(/_/,' ')+'.'; //var joinRole = grantType(joinConfig)['message'] + '.'; var joinRole = $('.roleSelect').val().replace(/_/,' '); joinRole=joinRole[0].toUpperCase()+joinRole.slice(1); joinRole = "'''"+ joinRole + "'''" + " "; that.addjoinment(joinRole+cleanupText($('#joinComment').val())); }); $('#joinComment').on('change keyup paste',function(){ $('.joinError').hide(); if($(this).val()){ $('.gadgetSignature').css('visibility','visible'); if($('.roleSelect').val()){ $('.add-join').attr('disabled',false); } } else{ $('.add-join').attr('disabled',true); $('.gadgetSignature').css('visibility','hidden'); } }); $('#ui-dialog-title-joinDialog').attr('localize','title'); $('.joinGadget .cancel').click(function(){ dialog.dialog('close'); }); localizeGadget('.joinGadget',grantType(joinInterfaceMessages)); $('.gadgetSignature').css('visibility','hidden'); //values in dropdown api.get({ 'format':'json', 'action':'parse', 'prop':'wikitext', 'page': mw.config.get('wgPageName'), 'section': 0 }).then(function(result){ var roles = grantType(joinInterfaceMessages)['roles']; //var roles = roleString.split(','); var wikitext = result.parse.wikitext['*']; var infobox = wikitext.slice(wikitext.indexOf('{{Probox'),wikitext.indexOf('}}')+2); that.infobox = infobox; units = infobox.split('|'); //var roleDict = {}; for (unit in units){ var roleParsedWikitext = units[unit].split('=')[0]; var individualParsedWikitext = units[unit].split('=')[1]; var role = units[unit].match(/[a-zA-z]+/)[0]; var count = units[unit].split('=')[0].match(/[0-9]+/)?units[unit].split('=')[0].match(/[0-9]+/)[0]:1; if(role in roles){ roleDict[role]=count; if ($.trim(individualParsedWikitext) == ''){ if(!$('.roleSelect option[value="'+role+'"]').length){ $('.roleSelect').append('<option value='+role+'>'+roles[role]+'</option>'); } } } } if(!$('.roleSelect option[value="volunteer"]').length){ $('.roleSelect').append('<option value="volunteer">'+roles['volunteer']+'</option>'); } $('.roleSelect').chosen({ disable_search: true, placeholder_text_single: 'Select a role', width: '50%', }); $('.roleSelect').on('change',function(){ if($(this).val() && $('#joinComment').val()){ $('.add-join').attr('disabled',false); } else{ $('.add-join').attr('disabled',true); } }); }); }; this.joinDialog = function () { if (dialog === null){ createDialog(); } else{ dialog.dialog('open'); } }; var addToInfobox = function(username){ return '[[User:' + username + '|' + username + ']]'; }; /* * The main function to add the feedback/joinment to the page. It first checks if the page has an joinment section. * If it dosent it creates a new section called joinments and appends the fedback/joinment to that section, * else it appends the feedback/joinment to existing joinments section. */ this.addjoinment = function( text ) { var joinComment = '\n*' + text + '~~~~' + '\n'; //Editing the infobox var roleSelected = $('.roleSelect').val(); var units = that.infobox.split('\n'); var emptyRoleAdded = false; for (unit in units){ if ($.trim(units[unit].split('=')[1]) == ''){ var role = units[unit].match(/[a-zA-z]+/); if (role){ role = role[0]; } if(role == roleSelected){ units[unit] = $.trim(units[unit]) + addToInfobox(mw.config.get('wgUserName')); emptyRoleAdded = true; break; } } } var modifiedInfoBox = units.join("\n"); if(!emptyRoleAdded){ var paramCount = parseInt(roleDict["volunteer"])+1; modifiedInfoBox = modifiedInfoBox.split('}}')[0]+'|volunteer'+paramCount+'='+addToInfobox(mw.config.get('wgUserName'))+'\n}}'; } //end editing the infobox api.post({ 'action' : 'edit', 'title' : mw.config.get('wgPageName'), 'text' : modifiedInfoBox, 'summary' : mw.user.getName() + ' joined the project as a ' + roleSelected, 'section': 0, 'token' : mw.user.tokens.values.editToken }).then(function(){ api.get({ 'format':'json', 'action':'parse', 'prop':'sections', 'page':mw.config.get('wgPageName'), }).then(function(result){ var sections = result.parse.sections; var sectionCount = 1; var sectionFound = false; for (var section in sections ){ if ($.trim(sections[section]['anchor']) == $.trim(grantType(joinConfig)['section']) ){ sectionFound = true; break; } sectionCount++; } if (sectionFound){ api.get({ 'format':'json', 'action':'parse', 'prop':'wikitext', 'page': mw.config.get('wgPageName'), 'section': sectionCount }).then(function(result){ var wikitext = result.parse.wikitext['*']; var joinmentSection = wikitext + joinComment; api.post({ 'action' : 'edit', 'title' : mw.config.get('wgPageName'), 'text' : joinmentSection, 'summary' : 'Joining message from ' + mw.user.getName(), 'section': sectionCount, 'token' : mw.user.tokens.values.editToken }).then(function(){ $.when(watchPage()).then(function(){ window.location.reload(true); setFeedbackCookie(); }); },errorMessage); }); } else{ var sectionHeader = grantType(joinConfig)['section']; api.post({ action: 'edit', title: mw.config.get('wgPageName'), section: 'new', summary: sectionHeader, text: joinComment, token: mw.user.tokens.get('editToken') }).then(function () { location.reload(); feedbackCookie(); }, errorMessage); } },errorMessage); },errorMessage); }; }; /* End of functions */ mw.loader.using( ['jquery.ui.dialog', 'mediawiki.api', 'mediawiki.ui','jquery.chosen'], function() { $(function() { (function(){ var namespace = mw.config.get('wgCanonicalNamespace'); /* * Fix mw.config.get('wgPageContentLanguage') == 'en') checking with a better solution, * either when pages can be tagged with arbitary language or when we set langauge markers later on. * */ if ( namespace == "Grants" ) { if(mw.config.get('wgPageContentLanguage') == 'en'){ var join = new joinGadget(); var api = new mw.Api(); var joinInterfaceMessagesTitle = join.joinInterfaceMessages+'/'+join.userLanguage(); var joinConfigTitle = join.joinConfig+'/'+join.contentLanguage(); //To detect if we have the gadget translations in the language of the page. api.get({'action':'query','titles':joinInterfaceMessagesTitle+'|'+joinConfigTitle,'format':'json'}).then(function(data){ for(id in data.query.pages){ if (data.query.pages[id].title == join.joinInterfaceMessages && id == -1){ joinInterfaceMessagesTitle = join.joinInterfaceMessages+'/en'; } if (data.query.pages[id].title == join.joinConfig && id == -1){ joinConfigTitle = join.joinConfig+'/en'; } } var joinInterfaceMessagesUrl = 'https://meta.wikimedia.org/w/index.php?title='+joinInterfaceMessagesTitle+'&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400'; var joinConfigUrl = 'https://meta.wikimedia.org/w/index.php?title='+joinConfigTitle+'&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400'; //Get the config for the detected language $.when(jQuery.getScript(joinInterfaceMessagesUrl),jQuery.getScript(joinConfigUrl)).then(function(){ join.joinDialog(); $('.wp-join-button').click(function(e){ e.preventDefault(); join.joinDialog(); }); if(join.checkFeedbackCookie()){ join.joinFeedback(); } }); }); } else{ $('.wp-join-button').hide(); } } })(); }); }); //</nowiki>
WMFGrants/joinEndorseGadget
gadget/js/join.js
JavaScript
gpl-3.0
13,692
#! /usr/bin/env node 'use strict'; let SlackClient = require('slack-api-client'); export class SlackAPI { constructor(token) { this.slackToken = token; this.slack = SlackAPI.initSlack(this.slackToken); } static initSlack(token) { return new SlackClient(token); } users() { return new Promise((resolve, reject) => { this.slack.api.users.list((err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } channels() { return new Promise((resolve, reject) => { this.slack.api.channels.list({}, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } channelsHistory(opts) { return new Promise((resolve, reject) => { this.slack.api.channels.history(opts, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } groups() { return new Promise((resolve, reject) => { this.slack.api.groups.list({}, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } groupHistory(opts) { return new Promise((resolve, reject) => { this.slack.api.groups.history(opts, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } im() { return new Promise((resolve, reject) => { this.slack.api.im.list((err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } imHistory(opts) { return new Promise((resolve, reject) => { this.slack.api.im.history(opts, (err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } getSelfData() { return new Promise((resolve, reject) => { this.slack.api.auth.test((err, res) => { if (err) { reject(err); } else { resolve(res); } }); }); } }
SouthPoleTelescope/slacklogging
slack-history-export/src/slack.api.js
JavaScript
gpl-3.0
2,141
const commander = require('commander'); const dnode = require('dnode'); commander .description('returnes the storj status for a given host and port as JSON') .option('--host <hostname>') .option('--port <port>') .parse(process.argv); let sock = dnode.connect(commander.host, commander.port); sock.on('error', () => { sock = null; console.log(JSON.stringify({result: false, error: 'failed to connect to storjshare-daemon', data: null})); }); sock.on('remote', (remote) => { remote.status((err, result) => { sock.end(); sock = null; if (err) { console.log(JSON.stringify({result: false, error: err.toString(), data: null})); return; } console.log(JSON.stringify({result:true, error: null, data: result})); }); });
felixbrucker/storjshare-daemon-proxy
storj-status-json.js
JavaScript
gpl-3.0
764
// Copyright 2014-2021, University of Colorado Boulder /** * Model for the beaker in 'Acid-Base Solutions' sim. * Origin is at bottom center. * * @author Andrey Zelenkov (Mlearner) * @author Chris Malley (PixelZoom, Inc.) */ import Bounds2 from '../../../../dot/js/Bounds2.js'; import Dimension2 from '../../../../dot/js/Dimension2.js'; import Vector2 from '../../../../dot/js/Vector2.js'; import merge from '../../../../phet-core/js/merge.js'; import acidBaseSolutions from '../../acidBaseSolutions.js'; class Beaker { /** * @param {Object} [options] */ constructor( options ) { options = merge( { size: new Dimension2( 360, 270 ), position: new Vector2( 230, 410 ) }, options ); this.size = options.size; // @public this.position = options.position; // @public // @public convenience coordinates this.left = this.position.x - this.size.width / 2; this.right = this.left + this.size.width; this.bottom = this.position.y; this.top = this.bottom - this.size.height; this.bounds = new Bounds2( this.left, this.top, this.right, this.bottom ); // @public } } acidBaseSolutions.register( 'Beaker', Beaker ); export default Beaker;
phetsims/acid-base-solutions
js/common/model/Beaker.js
JavaScript
gpl-3.0
1,204
'use strict'; const expect = require('chai').expect; const Board = require('../src/board'); const Search = require('../src/search'); describe('search', () => { var board; var search; var timePerMove; // ms var maxDepth = 64; beforeEach(() => { board = new Board(); search = new Search(); }); describe('tactics', () => { beforeEach(() => { timePerMove = 200; }); it('should find white checkmate', () => { board.fen = '8/8/8/5K1k/8/8/8/6R1 w - - 0 1'; var correctMove = board.moveStringToMove('g1h1'); var move = search.iterativeDeepening(board, timePerMove, maxDepth); expect(move).to.equal(correctMove); }); it('should find black checkmate', () => { board.fen = '8/8/8/5k1K/8/8/8/6r1 b - - 0 1'; var correctMove = board.moveStringToMove('g1h1'); var move = search.iterativeDeepening(board, timePerMove, maxDepth); expect(move).to.equal(correctMove); }); }); });
joeyrobert/ceruleanjs
test/search.test.js
JavaScript
gpl-3.0
1,071
(function () { define( ['i18next', 'appevents', 'uihandler', 'database', './receivemoney.html!text'], function (i18next, appevents, uihandle, database, template) { function MyReceiveMoney(params) { var viewModel = { // Fields message: ko.observable(), amount: ko.observable(), label: ko.observable(), addressPanel: ko.observable(false), transactions: ko.observableArray([]), address: null, // Errors errMessage: ko.observable(false), errTxtMessage: ko.observable(''), errAmount: ko.observable(false), errTxtAmount: ko.observable(''), errLabel: ko.observable(false), errTxtLabel: ko.observable(''), // QRCode element qrcode_element: '#addr-qrcode', addressClass: '.payment-to', // Validation validateForm: function () { var message = this.message(), amount = this.amount(), label = this.label(); if (message && message.length && !/^[a-z0-9 ,\._!\?#%&\(\)\+\-]{2,100}$/im.test(message)) { this.errMessage(true); this.errTxtMessage(i18next.t('errmsg-wallet-receive-message')); } else { this.errMessage(false); this.errTxtMessage(''); } if (amount && amount.length && (isNaN(+amount) || +amount <= 0)) { this.errAmount(true); this.errTxtAmount(i18next.t('errmsg-wallet-send-amount')); } else { this.errAmount(false); this.errTxtAmount(''); } if (label && label.length && !/^[a-z0-9 _\-]{2,40}$/im.test(label)) { this.errLabel(true); this.errTxtLabel(i18next.t('errmsg-wallet-receive-label')); } else { this.errLabel(false); this.errTxtLabel(''); } if (this.errMessage() === true || this.errAmount() === true || this.errLabel() === true) { return false; } return true; }, clear: function () { this.message(''); this.amount(''); this.label(''); this.errMessage(false); this.errTxtMessage(''); this.errAmount(false); this.errTxtAmount(''); this.errLabel(false); this.errTxtLabel(''); }, closePanel: function () { this.addressPanel(false); $(viewModel.addressClass).text(''); $(viewModel.qrcode_element).html(''); this.clear(); }, copyUri: function () { return this.ctrlc(`streambit:${this.address}`); }, copyAddress: function () { return this.ctrlc(this.address); }, ctrlc: function (txt) { if (!this.address) { return; } uihandle.copyToClipboard(txt); }, saveImg: function () { if (!this.address) { return; } var qrCodeBlock = $('#addr-qrcode'); uihandle.saveImgFromCanvas(qrCodeBlock, this.address); }, generateAddress: function () { if (this.validateForm()) { appevents.dispatch("on-payment-request", {}, this.requestPaymentCallback); } }, updateIndexDB: function (data, callback) { database.update(database.BCPAYMENTREQUESTS, data).then( () => callback(null, data), err => callback(err) ) }, requestPaymentCallback: function(err, address) { if (err) { return streembit.notify.error(err); } if (viewModel.validateForm()) { // protect on direct access viewModel.address = address; var data = { key: address, time: +new Date(), // ms amount: viewModel.amount(), label: viewModel.label(), message: viewModel.message() }; // Async DB update viewModel.updateIndexDB(data, viewModel.reportUpdateDB); // and show modal unrelated(?) to result of DB saving uihandle.qrGenerate(viewModel.qrcode_element, address); $(viewModel.addressClass).text(address); viewModel.addressPanel(true); } }, reportUpdateDB: function (err, data) { if (err) { return streembit.notify.error(err); } viewModel.transactions([ ...viewModel.transactions(), data ]); streembit.notify.success('Address successfully saved in DB'); }, init: function () { // get payment request collections database.getall(database.BCPAYMENTREQUESTS, (err, result) => { if (err) { return streembit.notify.error(err); } this.transactions(result); }); } }; viewModel.init(); return viewModel; } return { viewModel: MyReceiveMoney, template: template }; }); }());
streembit/streembitui
lib/app/views/wallet/receivemoney/receivemoney.js
JavaScript
gpl-3.0
7,037
webpackJsonpjwplayer([1],{ /***/ 41: /*!***********************************!*\ !*** ./src/js/providers/html5.js ***! \***********************************/ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; var _dataNormalizer = __webpack_require__(/*! providers/data-normalizer */ 42); !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! providers/html5-android-hls */ 37), __webpack_require__(/*! utils/css */ 16), __webpack_require__(/*! utils/helpers */ 8), __webpack_require__(/*! utils/dom */ 14), __webpack_require__(/*! utils/underscore */ 6), __webpack_require__(/*! events/events */ 32), __webpack_require__(/*! events/states */ 31), __webpack_require__(/*! providers/default */ 35), __webpack_require__(/*! utils/backbone.events */ 29), __webpack_require__(/*! providers/tracks-mixin */ 43), __webpack_require__(/*! utils/time-ranges */ 51)], __WEBPACK_AMD_DEFINE_RESULT__ = function (getIsAndroidHLS, cssUtils, utils, dom, _, events, states, DefaultProvider, Events, Tracks, timeRangesUtil) { var clearTimeout = window.clearTimeout; var STALL_DELAY = 256; var MIN_DVR_DURATION = 120; var _isIE = utils.isIE(); var _isIE9 = utils.isIE(9); var _isMobile = utils.isMobile(); var _isFirefox = utils.isFF(); var _isAndroid = utils.isAndroidNative(); var _isIOS7 = utils.isIOS(7); var _isIOS8 = utils.isIOS(8); var _name = 'html5'; function _setupListeners(eventsHash, videoTag) { utils.foreach(eventsHash, function (evt, evtCallback) { videoTag.addEventListener(evt, evtCallback, false); }); } function _removeListeners(eventsHash, videoTag) { utils.foreach(eventsHash, function (evt, evtCallback) { videoTag.removeEventListener(evt, evtCallback, false); }); } function VideoProvider(_playerId, _playerConfig) { // Current media state this.state = states.IDLE; // Are we buffering due to seek, or due to playback? this.seeking = false; _.extend(this, Events, Tracks); this.renderNatively = renderNatively(_playerConfig.renderCaptionsNatively); // Always render natively in iOS, Safari and Edge, where HLS is supported. // Otherwise, use native rendering when set in the config for browsers that have adequate support. // FF and IE are excluded due to styling/positioning drawbacks. function renderNatively(configRenderNatively) { if (utils.isIOS() || utils.isSafari() || utils.isEdge()) { return true; } return configRenderNatively && utils.isChrome(); } var _this = this; var _mediaEvents = { click: _clickHandler, durationchange: _durationChangeHandler, ended: _endedHandler, error: _errorHandler, loadstart: _onLoadStart, loadeddata: _onLoadedData, // we have video tracks (text, audio, metadata) loadedmetadata: _loadedMetadataHandler, // we have video dimensions canplay: _canPlayHandler, play: _loading, playing: _playingHandler, progress: _progressHandler, pause: _pauseHandler, seeking: _seekingHandler, seeked: _seekedHandler, timeupdate: _timeUpdateHandler, ratechange: _playbackRateHandler, volumechange: _volumeChangeHandler, webkitbeginfullscreen: _fullscreenBeginHandler, webkitendfullscreen: _fullscreenEndHandler }; var _container; var _duration; var _position; var _canSeek = false; var _bufferFull; var _delayedSeek = 0; var _seekOffset = null; var _playbackTimeout = -1; var _buffered = -1; var _levels; var _currentQuality = -1; var _isAndroidHLS = null; var _isSDK = !!_playerConfig.sdkplatform; var _fullscreenState = false; var _beforeResumeHandler = utils.noop; var _audioTracks = null; var _currentAudioTrackIndex = -1; var _visualQuality = { level: {} }; var _staleStreamDuration = 3 * 10 * 1000; var _staleStreamTimeout = null; var _lastEndOfBuffer = null; var _stale = false; var _edgeOfLiveStream = false; // Find video tag, or create it if it doesn't exist. View may not be built yet. var element = document.getElementById(_playerId); var _videotag = element ? element.querySelector('video, audio') : undefined; function _setAttribute(name, value) { _videotag.setAttribute(name, value || ''); } if (!_videotag) { _videotag = document.createElement('video'); _videotag.load(); if (_isMobile) { _setAttribute('jw-gesture-required'); } } _videotag.className = 'jw-video jw-reset'; this.isSDK = _isSDK; this.video = _videotag; this.supportsPlaybackRate = true; _setupListeners(_mediaEvents, _videotag); _setAttribute('disableRemotePlayback', ''); _setAttribute('webkit-playsinline'); _setAttribute('playsinline'); // Enable tracks support for HLS videos function _onLoadedData() { _setAudioTracks(_videotag.audioTracks); _this.setTextTracks(_videotag.textTracks); _setAttribute('jw-loaded', 'data'); } function _onLoadStart() { _setAttribute('jw-loaded', 'started'); } function _clickHandler(evt) { _this.trigger('click', evt); } function _durationChangeHandler() { if (_isAndroidHLS) { return; } _updateDuration(_getDuration()); _setBuffered(_getBuffer(), _position, _duration); } function _progressHandler() { _setBuffered(_getBuffer(), _position, _duration); } function _timeUpdateHandler() { clearTimeout(_playbackTimeout); _canSeek = true; if (_this.state === states.STALLED) { _this.setState(states.PLAYING); } else if (_this.state === states.PLAYING) { _playbackTimeout = setTimeout(_checkPlaybackStalled, STALL_DELAY); } // When video has not yet started playing for androidHLS, we cannot get the correct duration if (_isAndroidHLS && _videotag.duration === Infinity && _videotag.currentTime === 0) { return; } _updateDuration(_getDuration()); _setPosition(_videotag.currentTime); // buffer ranges change during playback, not just on file progress _setBuffered(_getBuffer(), _position, _duration); // send time events when playing if (_this.state === states.PLAYING) { _this.trigger(events.JWPLAYER_MEDIA_TIME, { position: _position, duration: _duration }); _checkVisualQuality(); } } function _playbackRateHandler() { _this.trigger('ratechange', { playbackRate: _videotag.playbackRate }); } function _checkVisualQuality() { var level = _visualQuality.level; if (level.width !== _videotag.videoWidth || level.height !== _videotag.videoHeight) { level.width = _videotag.videoWidth; level.height = _videotag.videoHeight; _setMediaType(); if (!level.width || !level.height || _currentQuality === -1) { return; } _visualQuality.reason = _visualQuality.reason || 'auto'; _visualQuality.mode = _levels[_currentQuality].type === 'hls' ? 'auto' : 'manual'; _visualQuality.bitrate = 0; level.index = _currentQuality; level.label = _levels[_currentQuality].label; _this.trigger('visualQuality', _visualQuality); _visualQuality.reason = ''; } } function _setBuffered(buffered, currentTime, duration) { if (duration !== 0 && (buffered !== _buffered || duration !== _duration)) { _buffered = buffered; _this.trigger(events.JWPLAYER_MEDIA_BUFFER, { bufferPercent: buffered * 100, position: currentTime, duration: duration }); } checkStaleStream(); } function _setPosition(currentTime) { if (_duration < 0) { currentTime = -(_getSeekableEnd() - currentTime); } _position = currentTime; } function _getDuration() { var duration = _videotag.duration; var end = _getSeekableEnd(); if (duration === Infinity && end) { var seekableDuration = end - _getSeekableStart(); if (seekableDuration !== Infinity && seekableDuration > MIN_DVR_DURATION) { // Player interprets negative duration as DVR duration = -seekableDuration; } } return duration; } function _updateDuration(duration) { _duration = duration; // Don't seek when _delayedSeek is set to -1 in _completeLoad if (_delayedSeek && _delayedSeek !== -1 && duration && duration !== Infinity) { _this.seek(_delayedSeek); } } function _sendMetaEvent() { var duration = _getDuration(); if (_isAndroidHLS && duration === Infinity) { duration = 0; } _this.trigger(events.JWPLAYER_MEDIA_META, { duration: duration, height: _videotag.videoHeight, width: _videotag.videoWidth }); _updateDuration(duration); } function _canPlayHandler() { _canSeek = true; if (!_isAndroidHLS) { _setMediaType(); } if (_isIE9) { // In IE9, set tracks here since they are not ready // on load _this.setTextTracks(_this._textTracks); } _sendBufferFull(); } function _loadedMetadataHandler() { _setAttribute('jw-loaded', 'meta'); _sendMetaEvent(); } function _sendBufferFull() { // Wait until the canplay event on iOS to send the bufferFull event if (!_bufferFull) { _bufferFull = true; _this.trigger(events.JWPLAYER_MEDIA_BUFFER_FULL); } } function _playingHandler() { _this.setState(states.PLAYING); if (!_videotag.hasAttribute('jw-played')) { _setAttribute('jw-played', ''); } if (_videotag.hasAttribute('jw-gesture-required')) { _videotag.removeAttribute('jw-gesture-required'); } _this.trigger(events.JWPLAYER_PROVIDER_FIRST_FRAME, {}); } function _pauseHandler() { clearTimeouts(); // Sometimes the browser will fire "complete" and then a "pause" event if (_this.state === states.COMPLETE) { return; } // If "pause" fires before "complete" or before we've started playback, we still don't want to propagate it if (!_videotag.hasAttribute('jw-played') || _videotag.currentTime === _videotag.duration) { return; } _this.setState(states.PAUSED); } function _stalledHandler() { // Android HLS doesnt update its times correctly so it always falls in here. Do not allow it to stall. if (_isAndroidHLS) { return; } if (_videotag.paused || _videotag.ended) { return; } // A stall after loading/error, should just stay loading/error if (_this.state === states.LOADING || _this.state === states.ERROR) { return; } // During seek we stay in paused state if (_this.seeking) { return; } // Workaround for iOS not completing after midroll with HLS streams if (utils.isIOS() && _videotag.duration - _videotag.currentTime <= 0.1) { _endedHandler(); return; } if (atEdgeOfLiveStream()) { _edgeOfLiveStream = true; if (checkStreamEnded()) { return; } } _this.setState(states.STALLED); } function _errorHandler() { _this.trigger(events.JWPLAYER_MEDIA_ERROR, { message: 'Error loading media: File could not be played' }); } function _getPublicLevels(levels) { var publicLevels; if (utils.typeOf(levels) === 'array' && levels.length > 0) { publicLevels = _.map(levels, function (level, i) { return { label: level.label || i }; }); } return publicLevels; } function _setLevels(levels) { _levels = levels; _currentQuality = _pickInitialQuality(levels); var publicLevels = _getPublicLevels(levels); if (publicLevels) { // _trigger? _this.trigger(events.JWPLAYER_MEDIA_LEVELS, { levels: publicLevels, currentQuality: _currentQuality }); } } function _pickInitialQuality(levels) { var currentQuality = Math.max(0, _currentQuality); var label = _playerConfig.qualityLabel; if (levels) { for (var i = 0; i < levels.length; i++) { if (levels[i].default) { currentQuality = i; } if (label && levels[i].label === label) { return i; } } } _visualQuality.reason = 'initial choice'; _visualQuality.level = {}; return currentQuality; } function _play() { var promise = _videotag.play(); if (promise && promise.catch) { promise.catch(function (err) { if (_videotag.paused) { // Send a time update to update ads UI // `isDurationChange` prevents this from propigating an "adTime" event _this.trigger(events.JWPLAYER_MEDIA_TIME, { position: _position, duration: _duration, isDurationChange: true }); _this.setState(states.PAUSED); } // User gesture required to start playback if (err.name === 'NotAllowedError') { console.warn(err); if (_videotag.hasAttribute('jw-gesture-required')) { _this.trigger('autoplayFailed'); } } }); } else if (_videotag.hasAttribute('jw-gesture-required')) { // Autoplay isn't supported in older versions of Safari (<10) and Chrome (<53) _this.trigger('autoplayFailed'); } } function _completeLoad(startTime, duration) { _delayedSeek = 0; clearTimeouts(); var previousSource = _videotag.src; var sourceElement = document.createElement('source'); sourceElement.src = _levels[_currentQuality].file; var sourceChanged = previousSource !== sourceElement.src; var loadedSrc = _videotag.getAttribute('jw-loaded'); if (sourceChanged || loadedSrc === 'none' || loadedSrc === 'started') { _duration = duration; _setVideotagSource(_levels[_currentQuality]); _this.setupSideloadedTracks(_this._itemTracks); if (previousSource && sourceChanged) { _videotag.load(); } } else { // Load event is from the same video as before if (startTime === 0 && _videotag.currentTime > 0) { // restart video without dispatching seek event _delayedSeek = -1; _this.seek(startTime); } } _position = _videotag.currentTime; if (startTime > 0) { _this.seek(startTime); } _play(); } function _setVideotagSource(source) { _audioTracks = null; _currentAudioTrackIndex = -1; if (!_visualQuality.reason) { _visualQuality.reason = 'initial choice'; _visualQuality.level = {}; } _canSeek = false; _bufferFull = false; _isAndroidHLS = getIsAndroidHLS(source); if (_isAndroidHLS) { // Playback rate is broken on Android HLS _this.supportsPlaybackRate = false; } if (source.preload && source.preload !== 'none' && source.preload !== _videotag.getAttribute('preload')) { _setAttribute('preload', source.preload); } var sourceElement = document.createElement('source'); sourceElement.src = source.file; var sourceChanged = _videotag.src !== sourceElement.src; if (sourceChanged) { _setAttribute('jw-loaded', 'none'); _videotag.src = source.file; } } function _clearVideotagSource() { if (_videotag) { _this.disableTextTrack(); _videotag.removeAttribute('preload'); _videotag.removeAttribute('src'); _videotag.removeAttribute('jw-loaded'); _videotag.removeAttribute('jw-played'); _videotag.pause(); dom.emptyElement(_videotag); cssUtils.style(_videotag, { objectFit: '' }); _currentQuality = -1; } } function _getSeekableStart() { var index = _videotag.seekable ? _videotag.seekable.length : 0; var start = Infinity; while (index--) { start = Math.min(start, _videotag.seekable.start(index)); } return start; } function _getSeekableEnd() { var index = _videotag.seekable ? _videotag.seekable.length : 0; var end = 0; while (index--) { end = Math.max(end, _videotag.seekable.end(index)); } return end; } function _loading() { _this.setState(states.LOADING); } this.stop = function () { clearTimeouts(); _clearVideotagSource(); this.clearTracks(); // IE/Edge continue to play a video after changing video.src and calling video.load() // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/5383483/ (not fixed in Edge 14) if (utils.isIE()) { _videotag.pause(); } this.setState(states.IDLE); }; this.destroy = function () { _beforeResumeHandler = utils.noop; _removeListeners(_mediaEvents, _videotag); this.removeTracksListener(_videotag.audioTracks, 'change', _audioTrackChangeHandler); this.removeTracksListener(_videotag.textTracks, 'change', _this.textTrackChangeHandler); this.remove(); this.off(); }; this.init = function (item) { _levels = item.sources; _currentQuality = _pickInitialQuality(item.sources); // the loadeddata event determines the mediaType for HLS sources if (item.sources.length && item.sources[0].type !== 'hls') { this.sendMediaType(item.sources); } _position = item.starttime || 0; _duration = item.duration || 0; _visualQuality.reason = ''; var source = _levels[_currentQuality]; if (source.preload !== 'none') { _setVideotagSource(source); } this.setupSideloadedTracks(item.tracks); }; this.load = function (item) { _setLevels(item.sources); if (item.sources.length && item.sources[0].type !== 'hls') { this.sendMediaType(item.sources); } if (!_isMobile || _videotag.hasAttribute('jw-played')) { // don't change state on mobile before user initiates playback _loading(); } _completeLoad(item.starttime || 0, item.duration || 0); }; this.play = function () { if (_this.seeking) { _loading(); _this.once(events.JWPLAYER_MEDIA_SEEKED, _this.play); return; } _beforeResumeHandler(); _play(); }; this.pause = function () { clearTimeouts(); _videotag.pause(); _beforeResumeHandler = function _beforeResumeHandler() { var unpausing = _videotag.paused && _videotag.currentTime; if (unpausing && _videotag.duration === Infinity) { var end = _getSeekableEnd(); var seekableDuration = end - _getSeekableStart(); var isLiveNotDvr = seekableDuration < MIN_DVR_DURATION; var behindLiveEdge = end - _videotag.currentTime; if (isLiveNotDvr && end && (behindLiveEdge > 15 || behindLiveEdge < 0)) { // resume playback at edge of live stream _seekOffset = Math.max(end - 10, end - seekableDuration); _setPosition(_videotag.currentTime); _videotag.currentTime = _seekOffset; } } }; this.setState(states.PAUSED); }; this.seek = function (seekPos) { if (seekPos < 0) { seekPos += _getSeekableStart() + _getSeekableEnd(); } if (!_canSeek) { _canSeek = !!_getSeekableEnd(); } if (_canSeek) { _delayedSeek = 0; // setting currentTime can throw an invalid DOM state exception if the video is not ready try { _this.seeking = true; _seekOffset = seekPos; _setPosition(_videotag.currentTime); _videotag.currentTime = seekPos; } catch (e) { _this.seeking = false; _delayedSeek = seekPos; } } else { _delayedSeek = seekPos; // Firefox isn't firing canplay event when in a paused state // https://bugzilla.mozilla.org/show_bug.cgi?id=1194624 if (_isFirefox && _videotag.paused) { _play(); } } }; function _seekingHandler() { var offset = _seekOffset !== null ? _seekOffset : _videotag.currentTime; _seekOffset = null; _delayedSeek = 0; _this.seeking = true; _this.trigger(events.JWPLAYER_MEDIA_SEEK, { position: _position, offset: offset }); } function _seekedHandler() { _this.seeking = false; _this.trigger(events.JWPLAYER_MEDIA_SEEKED); } this.volume = function (vol) { // volume must be 0.0 - 1.0 vol = utils.between(vol / 100, 0, 1); _videotag.volume = vol; }; function _volumeChangeHandler() { _this.trigger('volume', { volume: Math.round(_videotag.volume * 100) }); _this.trigger('mute', { mute: _videotag.muted }); } this.mute = function (state) { _videotag.muted = !!state; }; function _checkPlaybackStalled() { // Browsers, including latest chrome, do not always report Stalled events in a timely fashion if (_videotag.currentTime === _position) { _stalledHandler(); } else { _edgeOfLiveStream = false; } } function _getBuffer() { var buffered = _videotag.buffered; var duration = _videotag.duration; if (!buffered || buffered.length === 0 || duration <= 0 || duration === Infinity) { return 0; } return utils.between(buffered.end(buffered.length - 1) / duration, 0, 1); } function _endedHandler() { if (_this.state !== states.IDLE && _this.state !== states.COMPLETE) { clearTimeouts(); _currentQuality = -1; _this.trigger(events.JWPLAYER_MEDIA_COMPLETE); } } function _fullscreenBeginHandler(e) { _fullscreenState = true; _sendFullscreen(e); // show controls on begin fullscreen so that they are disabled properly at end if (utils.isIOS()) { _videotag.controls = false; } } function _audioTrackChangeHandler() { var _selectedAudioTrackIndex = -1; for (var i = 0; i < _videotag.audioTracks.length; i++) { if (_videotag.audioTracks[i].enabled) { _selectedAudioTrackIndex = i; break; } } _setCurrentAudioTrack(_selectedAudioTrackIndex); } function _fullscreenEndHandler(e) { _fullscreenState = false; _sendFullscreen(e); if (utils.isIOS()) { _videotag.controls = false; } } function _sendFullscreen(e) { _this.trigger('fullscreenchange', { target: e.target, jwstate: _fullscreenState }); } /** * Return the video tag and stop listening to events */ this.detachMedia = function () { clearTimeouts(); _removeListeners(_mediaEvents, _videotag); // Stop listening to track changes so disabling the current track doesn't update the model this.removeTracksListener(_videotag.textTracks, 'change', this.textTrackChangeHandler); // Prevent tracks from showing during ad playback this.disableTextTrack(); return _videotag; }; /** * Begin listening to events again */ this.attachMedia = function () { _setupListeners(_mediaEvents, _videotag); _canSeek = false; // If we were mid-seek when detached, we want to allow it to resume this.seeking = false; // In case the video tag was modified while we shared it _videotag.loop = false; // If there was a showing track, re-enable it this.enableTextTrack(); if (this.renderNatively) { this.setTextTracks(this.video.textTracks); } this.addTracksListener(_videotag.textTracks, 'change', this.textTrackChangeHandler); }; this.setContainer = function (containerElement) { _container = containerElement; containerElement.insertBefore(_videotag, containerElement.firstChild); }; this.getContainer = function () { return _container; }; this.remove = function () { // stop video silently _clearVideotagSource(); clearTimeouts(); // remove if (_container === _videotag.parentNode) { _container.removeChild(_videotag); } }; this.setVisibility = function (state) { state = !!state; if (state || _isAndroid) { // Changing visibility to hidden on Android < 4.2 causes // the pause event to be fired. This causes audio files to // become unplayable. Hence the video tag is always kept // visible on Android devices. cssUtils.style(_container, { visibility: 'visible', opacity: 1 }); } else { cssUtils.style(_container, { visibility: '', opacity: 0 }); } }; this.resize = function (width, height, stretching) { if (!width || !height || !_videotag.videoWidth || !_videotag.videoHeight) { return false; } var style = { objectFit: '', width: '', height: '' }; if (stretching === 'uniform') { // snap video to edges when the difference in aspect ratio is less than 9% var playerAspectRatio = width / height; var videoAspectRatio = _videotag.videoWidth / _videotag.videoHeight; if (Math.abs(playerAspectRatio - videoAspectRatio) < 0.09) { style.objectFit = 'fill'; stretching = 'exactfit'; } } // Prior to iOS 9, object-fit worked poorly // object-fit is not implemented in IE or Android Browser in 4.4 and lower // http://caniuse.com/#feat=object-fit // feature detection may work for IE but not for browsers where object-fit works for images only var fitVideoUsingTransforms = _isIE || _isIOS7 || _isIOS8 || _isAndroid && !_isFirefox; if (fitVideoUsingTransforms) { // Use transforms to center and scale video in container var x = -Math.floor(_videotag.videoWidth / 2 + 1); var y = -Math.floor(_videotag.videoHeight / 2 + 1); var scaleX = Math.ceil(width * 100 / _videotag.videoWidth) / 100; var scaleY = Math.ceil(height * 100 / _videotag.videoHeight) / 100; if (stretching === 'none') { scaleX = scaleY = 1; } else if (stretching === 'fill') { scaleX = scaleY = Math.max(scaleX, scaleY); } else if (stretching === 'uniform') { scaleX = scaleY = Math.min(scaleX, scaleY); } style.width = _videotag.videoWidth; style.height = _videotag.videoHeight; style.top = style.left = '50%'; style.margin = 0; cssUtils.transform(_videotag, 'translate(' + x + 'px, ' + y + 'px) scale(' + scaleX.toFixed(2) + ', ' + scaleY.toFixed(2) + ')'); } cssUtils.style(_videotag, style); return false; }; this.setFullscreen = function (state) { state = !!state; // This implementation is for iOS and Android WebKit only // This won't get called if the player container can go fullscreen if (state) { var status = utils.tryCatch(function () { var enterFullscreen = _videotag.webkitEnterFullscreen || _videotag.webkitEnterFullScreen; if (enterFullscreen) { enterFullscreen.apply(_videotag); } }); if (status instanceof utils.Error) { // object can't go fullscreen return false; } return _this.getFullScreen(); } var exitFullscreen = _videotag.webkitExitFullscreen || _videotag.webkitExitFullScreen; if (exitFullscreen) { exitFullscreen.apply(_videotag); } return state; }; _this.getFullScreen = function () { return _fullscreenState || !!_videotag.webkitDisplayingFullscreen; }; this.setCurrentQuality = function (quality) { if (_currentQuality === quality) { return; } if (quality >= 0) { if (_levels && _levels.length > quality) { _currentQuality = quality; _visualQuality.reason = 'api'; _visualQuality.level = {}; this.trigger(events.JWPLAYER_MEDIA_LEVEL_CHANGED, { currentQuality: quality, levels: _getPublicLevels(_levels) }); // The playerConfig is not updated automatically, because it is a clone // from when the provider was first initialized _playerConfig.qualityLabel = _levels[quality].label; var time = _videotag.currentTime || 0; var duration = _videotag.duration || 0; if (duration <= 0) { duration = _duration; } _loading(); _completeLoad(time, duration); } } }; this.setPlaybackRate = function (playbackRate) { // Set defaultPlaybackRate so that we do not send ratechange events when setting src _videotag.playbackRate = _videotag.defaultPlaybackRate = playbackRate; }; this.getPlaybackRate = function () { return _videotag.playbackRate; }; this.getCurrentQuality = function () { return _currentQuality; }; this.getQualityLevels = function () { return _.map(_levels, function (level) { return (0, _dataNormalizer.qualityLevel)(level); }); }; this.getName = function () { return { name: _name }; }; this.setCurrentAudioTrack = _setCurrentAudioTrack; this.getAudioTracks = _getAudioTracks; this.getCurrentAudioTrack = _getCurrentAudioTrack; function _setAudioTracks(tracks) { _audioTracks = null; if (!tracks) { return; } if (tracks.length) { for (var i = 0; i < tracks.length; i++) { if (tracks[i].enabled) { _currentAudioTrackIndex = i; break; } } if (_currentAudioTrackIndex === -1) { _currentAudioTrackIndex = 0; tracks[_currentAudioTrackIndex].enabled = true; } _audioTracks = _.map(tracks, function (track) { var _track = { name: track.label || track.language, language: track.language }; return _track; }); } _this.addTracksListener(tracks, 'change', _audioTrackChangeHandler); if (_audioTracks) { _this.trigger('audioTracks', { currentTrack: _currentAudioTrackIndex, tracks: _audioTracks }); } } function _setCurrentAudioTrack(index) { if (_videotag && _videotag.audioTracks && _audioTracks && index > -1 && index < _videotag.audioTracks.length && index !== _currentAudioTrackIndex) { _videotag.audioTracks[_currentAudioTrackIndex].enabled = false; _currentAudioTrackIndex = index; _videotag.audioTracks[_currentAudioTrackIndex].enabled = true; _this.trigger('audioTrackChanged', { currentTrack: _currentAudioTrackIndex, tracks: _audioTracks }); } } function _getAudioTracks() { return _audioTracks || []; } function _getCurrentAudioTrack() { return _currentAudioTrackIndex; } function _setMediaType() { // Send mediaType when format is HLS. Other types are handled earlier by default.js. if (_levels[0].type === 'hls') { var mediaType = 'video'; if (_videotag.videoHeight === 0) { mediaType = 'audio'; } _this.trigger('mediaType', { mediaType: mediaType }); } } // If we're live and the buffer end has remained the same for some time, mark the stream as stale and check if the stream is over function checkStaleStream() { var endOfBuffer = timeRangesUtil.endOfRange(_videotag.buffered); var live = _videotag.duration === Infinity; if (live && _lastEndOfBuffer === endOfBuffer) { if (!_staleStreamTimeout) { _staleStreamTimeout = setTimeout(function () { _stale = true; checkStreamEnded(); }, _staleStreamDuration); } } else { clearTimeout(_staleStreamTimeout); _staleStreamTimeout = null; _stale = false; } _lastEndOfBuffer = endOfBuffer; } function checkStreamEnded() { if (_stale && _edgeOfLiveStream) { _this.trigger(events.JWPLAYER_MEDIA_ERROR, { message: 'The live stream is either down or has ended' }); return true; } return false; } function atEdgeOfLiveStream() { if (_videotag.duration !== Infinity) { return false; } // currentTime doesn't always get to the end of the buffered range var timeFudge = 2; return timeRangesUtil.endOfRange(_videotag.buffered) - _videotag.currentTime <= timeFudge; } function clearTimeouts() { clearTimeout(_playbackTimeout); clearTimeout(_staleStreamTimeout); _staleStreamTimeout = null; } } // Register provider var F = function F() {}; F.prototype = DefaultProvider; VideoProvider.prototype = new F(); VideoProvider.getName = function () { return { name: 'html5' }; }; return VideoProvider; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }, /***/ 42: /*!*********************************************!*\ !*** ./src/js/providers/data-normalizer.js ***! \*********************************************/ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.qualityLevel = qualityLevel; function qualityLevel(level) { return { bitrate: level.bitrate, label: level.label, width: level.width, height: level.height }; } /***/ }, /***/ 43: /*!******************************************!*\ !*** ./src/js/providers/tracks-mixin.js ***! \******************************************/ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! utils/underscore */ 6), __webpack_require__(/*! utils/id3Parser */ 18), __webpack_require__(/*! utils/helpers */ 8), __webpack_require__(/*! controller/tracks-loader */ 44), __webpack_require__(/*! controller/tracks-helper */ 50)], __WEBPACK_AMD_DEFINE_RESULT__ = function (_, ID3Parser, utils, tracksLoader, tracksHelper) { /** * Used across all providers for loading tracks and handling browser track-related events */ var Tracks = { _itemTracks: null, _textTracks: null, _tracksById: null, _cuesByTrackId: null, _cachedVTTCues: null, _metaCuesByTextTime: null, _currentTextTrackIndex: -1, _unknownCount: 0, _activeCuePosition: null, _initTextTracks: _initTextTracks, addTracksListener: addTracksListener, clearTracks: clearTracks, clearCueData: clearCueData, disableTextTrack: disableTextTrack, enableTextTrack: enableTextTrack, getSubtitlesTrack: getSubtitlesTrack, removeTracksListener: removeTracksListener, addTextTracks: addTextTracks, setTextTracks: setTextTracks, setupSideloadedTracks: setupSideloadedTracks, setSubtitlesTrack: setSubtitlesTrack, textTrackChangeHandler: null, addTrackHandler: null, addCuesToTrack: addCuesToTrack, addCaptionsCue: addCaptionsCue, addVTTCue: addVTTCue, addVTTCuesToTrack: addVTTCuesToTrack, renderNatively: false }; function setTextTracks(tracks) { this._currentTextTrackIndex = -1; if (!tracks) { return; } if (!this._textTracks) { this._initTextTracks(); } else { // Remove the 608 captions track that was mutated by the browser this._textTracks = _.reject(this._textTracks, function (track) { if (this.renderNatively && track._id === 'nativecaptions') { delete this._tracksById[track._id]; return true; } }, this); // Remove the ID3 track from the cache delete this._tracksById.nativemetadata; } // filter for 'subtitles' or 'captions' tracks if (tracks.length) { var i = 0; var len = tracks.length; for (i; i < len; i++) { var track = tracks[i]; if (!track._id) { if (track.kind === 'captions' || track.kind === 'metadata') { track._id = 'native' + track.kind; if (!track.label && track.kind === 'captions') { // track label is read only in Safari // 'captions' tracks without a label need a name in order for the cc menu to work var labelInfo = tracksHelper.createLabel(track, this._unknownCount); track.name = labelInfo.label; this._unknownCount = labelInfo.unknownCount; } } else { track._id = tracksHelper.createId(track, this._textTracks.length); } if (this._tracksById[track._id]) { // tracks without unique ids must not be marked as "inuse" continue; } track.inuse = true; } if (!track.inuse || this._tracksById[track._id]) { continue; } // setup TextTrack if (track.kind === 'metadata') { // track mode needs to be "hidden", not "showing", so that cues don't display as captions in Firefox track.mode = 'hidden'; track.oncuechange = _cueChangeHandler.bind(this); this._tracksById[track._id] = track; } else if (_kindSupported(track.kind)) { var mode = track.mode; var cue; // By setting the track mode to 'hidden', we can determine if the track has cues track.mode = 'hidden'; if (!track.cues.length && track.embedded) { // There's no method to remove tracks added via: video.addTextTrack. // This ensures the 608 captions track isn't added to the CC menu until it has cues continue; } track.mode = mode; // Parsed cues may not have been added to this track yet if (this._cuesByTrackId[track._id] && !this._cuesByTrackId[track._id].loaded) { var cues = this._cuesByTrackId[track._id].cues; while (cue = cues.shift()) { _addCueToTrack(this.renderNatively, track, cue); } track.mode = mode; this._cuesByTrackId[track._id].loaded = true; } _addTrackToList.call(this, track); } } } if (this.renderNatively) { // Only bind and set this.textTrackChangeHandler once so that removeEventListener works this.textTrackChangeHandler = this.textTrackChangeHandler || textTrackChangeHandler.bind(this); this.addTracksListener(this.video.textTracks, 'change', this.textTrackChangeHandler); if (utils.isEdge() || utils.isFF() || utils.isSafari()) { // Listen for TextTracks added to the videotag after the onloadeddata event in Edge and Firefox this.addTrackHandler = this.addTrackHandler || addTrackHandler.bind(this); this.addTracksListener(this.video.textTracks, 'addtrack', this.addTrackHandler); } } if (this._textTracks.length) { this.trigger('subtitlesTracks', { tracks: this._textTracks }); } } function setupSideloadedTracks(itemTracks) { // Add tracks if we're starting playback or resuming after a midroll if (!this.renderNatively) { return; } // Determine if the tracks are the same and the embedded + sideloaded count = # of tracks in the controlbar var alreadyLoaded = itemTracks === this._itemTracks; if (!alreadyLoaded) { tracksLoader.cancelXhr(this._itemTracks); } this._itemTracks = itemTracks; if (!itemTracks) { return; } if (!alreadyLoaded) { this.disableTextTrack(); _clearSideloadedTextTracks.call(this); this.addTextTracks(itemTracks); } } function getSubtitlesTrack() { return this._currentTextTrackIndex; } function setSubtitlesTrack(menuIndex) { if (!this.renderNatively) { if (this.setCurrentSubtitleTrack) { this.setCurrentSubtitleTrack(menuIndex - 1); } return; } if (!this._textTracks) { return; } // 0 = 'Off' if (menuIndex === 0) { _.each(this._textTracks, function (track) { track.mode = track.embedded ? 'hidden' : 'disabled'; }); } // Track index is 1 less than controlbar index to account for 'Off' = 0. // Prevent unnecessary track change events if (this._currentTextTrackIndex === menuIndex - 1) { return; } // Turn off current track this.disableTextTrack(); // Set the provider's index to the model's index, then show the selected track if it exists this._currentTextTrackIndex = menuIndex - 1; if (this._textTracks[this._currentTextTrackIndex]) { this._textTracks[this._currentTextTrackIndex].mode = 'showing'; } // Update the model index since the track change may have come from a browser event this.trigger('subtitlesTrackChanged', { currentTrack: this._currentTextTrackIndex + 1, tracks: this._textTracks }); } function addCaptionsCue(cueData) { if (!cueData.text || !cueData.begin || !cueData.end) { return; } var trackId = cueData.trackid.toString(); var track = this._tracksById && this._tracksById[trackId]; if (!track) { track = { kind: 'captions', _id: trackId, data: [] }; this.addTextTracks([track]); this.trigger('subtitlesTracks', { tracks: this._textTracks }); } var cueId; if (cueData.useDTS) { // There may not be any 608 captions when the track is first created // Need to set the source so position is determined from metadata if (!track.source) { track.source = cueData.source || 'mpegts'; } } cueId = cueData.begin + '_' + cueData.text; var cue = this._metaCuesByTextTime[cueId]; if (!cue) { cue = { begin: cueData.begin, end: cueData.end, text: cueData.text }; this._metaCuesByTextTime[cueId] = cue; var vttCue = tracksLoader.convertToVTTCues([cue])[0]; track.data.push(vttCue); } } function addVTTCue(cueData) { if (!this._tracksById) { this._initTextTracks(); } var trackId = cueData.track ? cueData.track : 'native' + cueData.type; var track = this._tracksById[trackId]; var label = cueData.type === 'captions' ? 'Unknown CC' : 'ID3 Metadata'; var vttCue = cueData.cue; if (!track) { var itemTrack = { kind: cueData.type, _id: trackId, label: label, embedded: true }; track = _createTrack.call(this, itemTrack); if (this.renderNatively || track.kind === 'metadata') { this.setTextTracks(this.video.textTracks); } else { addTextTracks.call(this, [track]); } } if (_cacheVTTCue.call(this, track, vttCue)) { if (this.renderNatively || track.kind === 'metadata') { _addCueToTrack(this.renderNatively, track, vttCue); } else { track.data.push(vttCue); } } } function addCuesToTrack(cueData) { // convert cues coming from the flash provider into VTTCues, then append them to track var track = this._tracksById[cueData.name]; if (!track) { return; } track.source = cueData.source; var cues = cueData.captions || []; var cuesToConvert = []; var sort = false; for (var i = 0; i < cues.length; i++) { var cue = cues[i]; var cueId = cueData.name + '_' + cue.begin + '_' + cue.end; if (!this._metaCuesByTextTime[cueId]) { this._metaCuesByTextTime[cueId] = cue; cuesToConvert.push(cue); sort = true; } } if (sort) { cuesToConvert.sort(function (a, b) { return a.begin - b.begin; }); } var vttCues = tracksLoader.convertToVTTCues(cuesToConvert); Array.prototype.push.apply(track.data, vttCues); } function addTracksListener(tracks, eventType, handler) { if (!tracks) { return; } // Always remove existing listener removeTracksListener(tracks, eventType, handler); if (this.instreamMode) { return; } if (tracks.addEventListener) { tracks.addEventListener(eventType, handler); } else { tracks['on' + eventType] = handler; } } function removeTracksListener(tracks, eventType, handler) { if (!tracks) { return; } if (tracks.removeEventListener) { tracks.removeEventListener(eventType, handler); } else { tracks['on' + eventType] = null; } } function clearTracks() { tracksLoader.cancelXhr(this._itemTracks); var metadataTrack = this._tracksById && this._tracksById.nativemetadata; if (this.renderNatively || metadataTrack) { _removeCues(this.renderNatively, this.video.textTracks); if (metadataTrack) { metadataTrack.oncuechange = null; } } this._itemTracks = null; this._textTracks = null; this._tracksById = null; this._cuesByTrackId = null; this._metaCuesByTextTime = null; this._unknownCount = 0; this._activeCuePosition = null; if (this.renderNatively) { // Removing listener first to ensure that removing cues does not trigger it unnecessarily this.removeTracksListener(this.video.textTracks, 'change', this.textTrackChangeHandler); _removeCues(this.renderNatively, this.video.textTracks); } } // Clear track cues to prevent duplicates function clearCueData(trackId) { if (this._cachedVTTCues[trackId]) { this._cachedVTTCues[trackId] = {}; this._tracksById[trackId].data = []; } } function disableTextTrack() { if (this._textTracks) { var track = this._textTracks[this._currentTextTrackIndex]; if (track) { // FF does not remove the active cue from the dom when the track is hidden, so we must disable it track.mode = 'disabled'; if (track.embedded || track._id === 'nativecaptions') { track.mode = 'hidden'; } } } } function enableTextTrack() { if (this._textTracks) { var track = this._textTracks[this._currentTextTrackIndex]; if (track) { track.mode = 'showing'; } } } function textTrackChangeHandler() { var textTracks = this.video.textTracks; var inUseTracks = _.filter(textTracks, function (track) { return (track.inuse || !track._id) && _kindSupported(track.kind); }); if (!this._textTracks || _tracksModified.call(this, inUseTracks)) { this.setTextTracks(textTracks); return; } // If a caption/subtitle track is showing, find its index var selectedTextTrackIndex = -1; for (var i = 0; i < this._textTracks.length; i++) { if (this._textTracks[i].mode === 'showing') { selectedTextTrackIndex = i; break; } } // Notifying the model when the index changes keeps the current index in sync in iOS Fullscreen mode if (selectedTextTrackIndex !== this._currentTextTrackIndex) { this.setSubtitlesTrack(selectedTextTrackIndex + 1); } } // Used in MS Edge to get tracks from the videotag as they're added function addTrackHandler() { this.setTextTracks(this.video.textTracks); } function addTextTracks(tracksArray) { if (!tracksArray) { return; } if (!this._textTracks) { this._initTextTracks(); } for (var i = 0; i < tracksArray.length; i++) { var itemTrack = tracksArray[i]; // only add valid and supported kinds https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track if (itemTrack.kind && !_kindSupported(itemTrack.kind)) { continue; } var textTrackAny = _createTrack.call(this, itemTrack); _addTrackToList.call(this, textTrackAny); if (itemTrack.file) { itemTrack.data = []; tracksLoader.loadFile(itemTrack, this.addVTTCuesToTrack.bind(this, textTrackAny), _errorHandler); } } if (this._textTracks && this._textTracks.length) { this.trigger('subtitlesTracks', { tracks: this._textTracks }); } } function addVTTCuesToTrack(track, vttCues) { if (!this.renderNatively) { return; } var textTrack = this._tracksById[track._id]; // the track may not be on the video tag yet if (!textTrack) { if (!this._cuesByTrackId) { this._cuesByTrackId = {}; } this._cuesByTrackId[track._id] = { cues: vttCues, loaded: false }; return; } // Cues already added if (this._cuesByTrackId[track._id] && this._cuesByTrackId[track._id].loaded) { return; } var cue; this._cuesByTrackId[track._id] = { cues: vttCues, loaded: true }; while (cue = vttCues.shift()) { _addCueToTrack(this.renderNatively, textTrack, cue); } } // //////////////////// // //// PRIVATE METHODS // //////////////////// function _addCueToTrack(renderNatively, track, vttCue) { if (!(utils.isIE() && renderNatively) || !window.TextTrackCue) { track.addCue(vttCue); return; } // There's no support for the VTTCue interface in IE/Edge. // We need to convert VTTCue to TextTrackCue before adding them to the TextTrack // This unfortunately removes positioning properties from the cues var textTrackCue = new window.TextTrackCue(vttCue.startTime, vttCue.endTime, vttCue.text); track.addCue(textTrackCue); } function _removeCues(renderNatively, tracks) { if (tracks && tracks.length) { _.each(tracks, function (track) { // Let IE & Edge handle cleanup of non-sideloaded text tracks for native rendering if (utils.isIE() && renderNatively && /^(native|subtitle|cc)/.test(track._id)) { return; } // Cues are inaccessible if the track is disabled. While hidden, // we can remove cues while the track is in a non-visible state // Set to disabled before hidden to ensure active cues disappear track.mode = 'disabled'; track.mode = 'hidden'; for (var i = track.cues.length; i--;) { track.removeCue(track.cues[i]); } if (!track.embedded) { track.mode = 'disabled'; } track.inuse = false; }); } } function _kindSupported(kind) { return kind === 'subtitles' || kind === 'captions'; } function _initTextTracks() { this._textTracks = []; this._tracksById = {}; this._metaCuesByTextTime = {}; this._cuesByTrackId = {}; this._cachedVTTCues = {}; this._unknownCount = 0; } function _createTrack(itemTrack) { var track; var labelInfo = tracksHelper.createLabel(itemTrack, this._unknownCount); var label = labelInfo.label; this._unknownCount = labelInfo.unknownCount; if (this.renderNatively || itemTrack.kind === 'metadata') { var tracks = this.video.textTracks; // TextTrack label is read only, so we'll need to create a new track if we don't // already have one with the same label track = _.findWhere(tracks, { label: label }); if (track) { track.kind = itemTrack.kind; track.language = itemTrack.language || ''; } else { track = this.video.addTextTrack(itemTrack.kind, label, itemTrack.language || ''); } track.default = itemTrack.default; track.mode = 'disabled'; track.inuse = true; } else { track = itemTrack; track.data = track.data || []; } if (!track._id) { track._id = tracksHelper.createId(itemTrack, this._textTracks.length); } return track; } function _addTrackToList(track) { this._textTracks.push(track); this._tracksById[track._id] = track; } function _clearSideloadedTextTracks() { // Clear VTT textTracks if (!this._textTracks) { return; } var nonSideloadedTracks = _.filter(this._textTracks, function (track) { return track.embedded || track.groupid === 'subs'; }); this._initTextTracks(); _.each(nonSideloadedTracks, function (track) { this._tracksById[track._id] = track; }); this._textTracks = nonSideloadedTracks; } function _cueChangeHandler(e) { var activeCues = e.currentTarget.activeCues; if (!activeCues || !activeCues.length) { return; } // Get the most recent start time. Cues are sorted by start time in ascending order by the browser var startTime = activeCues[activeCues.length - 1].startTime; // Prevent duplicate meta events for the same list of cues since the cue change handler fires once // for each activeCue in Safari if (this._activeCuePosition === startTime) { return; } var dataCues = []; _.each(activeCues, function (cue) { if (cue.startTime < startTime) { return; } if (cue.data || cue.value) { dataCues.push(cue); } else if (cue.text) { this.trigger('meta', { metadataTime: startTime, metadata: JSON.parse(cue.text) }); } }, this); if (dataCues.length) { var id3Data = ID3Parser.parseID3(dataCues); this.trigger('meta', { metadataTime: startTime, metadata: id3Data }); } this._activeCuePosition = startTime; } function _cacheVTTCue(track, vttCue) { var trackKind = track.kind; if (!this._cachedVTTCues[track._id]) { this._cachedVTTCues[track._id] = {}; } var cachedCues = this._cachedVTTCues[track._id]; var cacheKeyTime; switch (trackKind) { case 'captions': case 'subtitles': // VTTCues should have unique start and end times, even in cases where there are multiple // active cues. This is safer than ensuring text is unique, which may be violated on seek. // Captions within .05s of each other are treated as unique to account for // quality switches where start/end times are slightly different. cacheKeyTime = Math.floor(vttCue.startTime * 20); var cacheLine = '_' + vttCue.line; var cacheValue = Math.floor(vttCue.endTime * 20); var cueExists = cachedCues[cacheKeyTime + cacheLine] || cachedCues[cacheKeyTime + 1 + cacheLine] || cachedCues[cacheKeyTime - 1 + cacheLine]; if (cueExists && Math.abs(cueExists - cacheValue) <= 1) { return false; } cachedCues[cacheKeyTime + cacheLine] = cacheValue; return true; case 'metadata': var text = vttCue.data ? new Uint8Array(vttCue.data).join('') : vttCue.text; cacheKeyTime = vttCue.startTime + text; if (cachedCues[cacheKeyTime]) { return false; } cachedCues[cacheKeyTime] = vttCue.endTime; return true; default: return false; } } function _tracksModified(inUseTracks) { // Need to add new textTracks coming from the video tag if (inUseTracks.length > this._textTracks.length) { return true; } // Tracks may have changed in Safari after an ad for (var i = 0; i < inUseTracks.length; i++) { var track = inUseTracks[i]; if (!track._id || !this._tracksById[track._id]) { return true; } } return false; } function _errorHandler(error) { utils.log('CAPTIONS(' + error + ')'); } return Tracks; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ }, /***/ 51: /*!*************************************!*\ !*** ./src/js/utils/time-ranges.js ***! \*************************************/ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;"use strict"; !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { function endOfRange(timeRanges) { if (!timeRanges || !timeRanges.length) { return 0; } return timeRanges.end(timeRanges.length - 1); } return { endOfRange: endOfRange }; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); /***/ } }); //# sourceMappingURL=provider.html5.a8bf8f3cb1a82cfe5f6e.map
vfremaux/moodle-mod_mplayer
extralib/players/jw/7.12/bin-debug/provider.html5.js
JavaScript
gpl-3.0
68,286
/* * Copyright (c) 2011 Vinay Pulim <[email protected]> * MIT Licensed * */ /*jshint proto:true*/ "use strict"; var sax = require('sax'); var inherits = require('util').inherits; var HttpClient = require('./http'); var NamespaceContext = require('./nscontext'); var fs = require('fs'); var url = require('url'); var path = require('path'); var assert = require('assert').ok; var stripBom = require('strip-bom'); var debug = require('debug')('node-soap'); var _ = require('lodash'); var selectn = require('selectn'); var utils = require('./utils'); var TNS_PREFIX = utils.TNS_PREFIX; var findPrefix = utils.findPrefix; var Primitives = { string: 1, boolean: 1, decimal: 1, float: 1, double: 1, anyType: 1, byte: 1, int: 1, long: 1, short: 1, negativeInteger: 1, nonNegativeInteger: 1, positiveInteger: 1, nonPositiveInteger:1, unsignedByte: 1, unsignedInt: 1, unsignedLong: 1, unsignedShort: 1, duration: 0, dateTime: 0, time: 0, date: 0, gYearMonth: 0, gYear: 0, gMonthDay: 0, gDay: 0, gMonth: 0, hexBinary: 0, base64Binary: 0, anyURI: 0, QName: 0, NOTATION: 0 }; function splitQName(nsName) { var i = typeof nsName === 'string' ? nsName.indexOf(':') : -1; return i < 0 ? {prefix: TNS_PREFIX, name: nsName} : {prefix: nsName.substring(0, i), name: nsName.substring(i + 1)}; } function xmlEscape(obj) { if (typeof (obj) === 'string') { return obj .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&apos;'); } return obj; } var trimLeft = /^[\s\xA0]+/; var trimRight = /[\s\xA0]+$/; function trim(text) { return text.replace(trimLeft, '').replace(trimRight, ''); } /** * What we want is to copy properties from one object to another one and avoid * properties overriding. This way we ensure the 'inheritance' of * <xsd:extension base=...> usage. * * NB: 'Element' (and subtypes) don't have any prototyped properties: there's * no need to process a 'hasOwnProperties' call, we should just iterate over the * keys. */ function extend(base, obj) { if(base !== null && typeof base === "object" && obj !== null && typeof obj === "object"){ Object.keys(obj).forEach(function(key) { if(!base.hasOwnProperty(key)) base[key] = obj[key]; }); } return base; } function deepMerge(destination, source) { return _.merge(destination || {}, source, function(a, b) { return _.isArray(a) ? a.concat(b) : undefined; }); } var Element = function(nsName, attrs, options) { var parts = splitQName(nsName); this.nsName = nsName; this.prefix = parts.prefix; this.name = parts.name; this.children = []; this.xmlns = {}; this._initializeOptions(options); for (var key in attrs) { var match = /^xmlns:?(.*)$/.exec(key); if (match) { this.xmlns[match[1] ? match[1] : TNS_PREFIX] = attrs[key]; } else { if(key === 'value') { this[this.valueKey] = attrs[key]; } else { this['$' + key] = attrs[key]; } } } if (this.$targetNamespace !== undefined) { // Add targetNamespace to the mapping this.xmlns[TNS_PREFIX] = this.$targetNamespace; } }; Element.prototype._initializeOptions = function (options) { if(options) { this.valueKey = options.valueKey || '$value'; this.xmlKey = options.xmlKey || '$xml'; this.ignoredNamespaces = options.ignoredNamespaces || []; } else { this.valueKey = '$value'; this.xmlKey = '$xml'; this.ignoredNamespaces = []; } }; Element.prototype.deleteFixedAttrs = function() { this.children && this.children.length === 0 && delete this.children; this.xmlns && Object.keys(this.xmlns).length === 0 && delete this.xmlns; delete this.nsName; delete this.prefix; delete this.name; }; Element.prototype.allowedChildren = []; Element.prototype.startElement = function(stack, nsName, attrs, options) { if (!this.allowedChildren) return; var ChildClass = this.allowedChildren[splitQName(nsName).name], element = null; if (ChildClass) { stack.push(new ChildClass(nsName, attrs, options)); } else { this.unexpected(nsName); } }; Element.prototype.endElement = function(stack, nsName) { if (this.nsName === nsName) { if (stack.length < 2) return; var parent = stack[stack.length - 2]; if (this !== stack[0]) { extend(stack[0].xmlns, this.xmlns); // delete this.xmlns; parent.children.push(this); parent.addChild(this); } stack.pop(); } }; Element.prototype.addChild = function(child) { return; }; Element.prototype.unexpected = function(name) { throw new Error('Found unexpected element (' + name + ') inside ' + this.nsName); }; Element.prototype.description = function(definitions) { return this.$name || this.name; }; Element.prototype.init = function() { }; Element.createSubClass = function() { var root = this; var subElement = function() { root.apply(this, arguments); this.init(); }; // inherits(subElement, root); subElement.prototype.__proto__ = root.prototype; return subElement; }; var ElementElement = Element.createSubClass(); var AnyElement = Element.createSubClass(); var InputElement = Element.createSubClass(); var OutputElement = Element.createSubClass(); var SimpleTypeElement = Element.createSubClass(); var RestrictionElement = Element.createSubClass(); var ExtensionElement = Element.createSubClass(); var ChoiceElement = Element.createSubClass(); var EnumerationElement = Element.createSubClass(); var ComplexTypeElement = Element.createSubClass(); var ComplexContentElement = Element.createSubClass(); var SimpleContentElement = Element.createSubClass(); var SequenceElement = Element.createSubClass(); var AllElement = Element.createSubClass(); var MessageElement = Element.createSubClass(); var DocumentationElement = Element.createSubClass(); var SchemaElement = Element.createSubClass(); var TypesElement = Element.createSubClass(); var OperationElement = Element.createSubClass(); var PortTypeElement = Element.createSubClass(); var BindingElement = Element.createSubClass(); var PortElement = Element.createSubClass(); var ServiceElement = Element.createSubClass(); var DefinitionsElement = Element.createSubClass(); var ElementTypeMap = { types: [TypesElement, 'schema documentation'], schema: [SchemaElement, 'element complexType simpleType include import'], element: [ElementElement, 'annotation complexType'], any: [AnyElement, ''], simpleType: [SimpleTypeElement, 'restriction'], restriction: [RestrictionElement, 'enumeration all choice sequence'], extension: [ExtensionElement, 'all sequence choice'], choice: [ChoiceElement, 'element sequence choice any'], // group: [GroupElement, 'element group'], enumeration: [EnumerationElement, ''], complexType: [ComplexTypeElement, 'annotation sequence all complexContent simpleContent choice'], complexContent: [ComplexContentElement, 'extension'], simpleContent: [SimpleContentElement, 'extension'], sequence: [SequenceElement, 'element sequence choice any'], all: [AllElement, 'element choice'], service: [ServiceElement, 'port documentation'], port: [PortElement, 'address documentation'], binding: [BindingElement, '_binding SecuritySpec operation documentation'], portType: [PortTypeElement, 'operation documentation'], message: [MessageElement, 'part documentation'], operation: [OperationElement, 'documentation input output fault _operation'], input: [InputElement, 'body SecuritySpecRef documentation header'], output: [OutputElement, 'body SecuritySpecRef documentation header'], fault: [Element, '_fault documentation'], definitions: [DefinitionsElement, 'types message portType binding service import documentation'], documentation: [DocumentationElement, ''] }; function mapElementTypes(types) { var rtn = {}; types = types.split(' '); types.forEach(function(type) { rtn[type.replace(/^_/, '')] = (ElementTypeMap[type] || [Element]) [0]; }); return rtn; } for (var n in ElementTypeMap) { var v = ElementTypeMap[n]; v[0].prototype.allowedChildren = mapElementTypes(v[1]); } MessageElement.prototype.init = function() { this.element = null; this.parts = null; }; SchemaElement.prototype.init = function() { this.complexTypes = {}; this.types = {}; this.elements = {}; this.includes = []; }; TypesElement.prototype.init = function() { this.schemas = {}; }; OperationElement.prototype.init = function() { this.input = null; this.output = null; this.inputSoap = null; this.outputSoap = null; this.style = ''; this.soapAction = ''; }; PortTypeElement.prototype.init = function() { this.methods = {}; }; BindingElement.prototype.init = function() { this.transport = ''; this.style = ''; this.methods = {}; }; PortElement.prototype.init = function() { this.location = null; }; ServiceElement.prototype.init = function() { this.ports = {}; }; DefinitionsElement.prototype.init = function() { if (this.name !== 'definitions')this.unexpected(this.nsName); this.messages = {}; this.portTypes = {}; this.bindings = {}; this.services = {}; this.schemas = {}; }; DocumentationElement.prototype.init = function() { }; SchemaElement.prototype.merge = function(source) { assert(source instanceof SchemaElement); if (this.$targetNamespace === source.$targetNamespace) { _.merge(this.complexTypes, source.complexTypes); _.merge(this.types, source.types); _.merge(this.elements, source.elements); _.merge(this.xmlns, source.xmlns); } return this; }; SchemaElement.prototype.addChild = function(child) { if (child.$name in Primitives) return; if (child.name === 'include' || child.name === 'import') { var location = child.$schemaLocation || child.$location; if (location) { this.includes.push({ namespace: child.$namespace || child.$targetNamespace || this.$targetNamespace, location: location }); } } else if (child.name === 'complexType') { this.complexTypes[child.$name] = child; } else if (child.name === 'element') { this.elements[child.$name] = child; } else if (child.$name) { this.types[child.$name] = child; } this.children.pop(); // child.deleteFixedAttrs(); }; //fix#325 TypesElement.prototype.addChild = function (child) { assert(child instanceof SchemaElement); var targetNamespace = child.$targetNamespace; if(!this.schemas.hasOwnProperty(targetNamespace)) { this.schemas[targetNamespace] = child; } else { console.error('Target-Namespace "'+ targetNamespace +'" already in use by another Schema!'); } }; InputElement.prototype.addChild = function(child) { if (child.name === 'body') { this.use = child.$use; if (this.use === 'encoded') { this.encodingStyle = child.$encodingStyle; } this.children.pop(); } }; OutputElement.prototype.addChild = function(child) { if (child.name === 'body') { this.use = child.$use; if (this.use === 'encoded') { this.encodingStyle = child.$encodingStyle; } this.children.pop(); } }; OperationElement.prototype.addChild = function(child) { if (child.name === 'operation') { this.soapAction = child.$soapAction || ''; this.style = child.$style || ''; this.children.pop(); } }; BindingElement.prototype.addChild = function(child) { if (child.name === 'binding') { this.transport = child.$transport; this.style = child.$style; this.children.pop(); } }; PortElement.prototype.addChild = function(child) { if (child.name === 'address' && typeof (child.$location) !== 'undefined') { this.location = child.$location; } }; DefinitionsElement.prototype.addChild = function(child) { var self = this; if (child instanceof TypesElement) { // Merge types.schemas into definitions.schemas _.merge(self.schemas, child.schemas); } else if (child instanceof MessageElement) { self.messages[child.$name] = child; } else if (child.name === 'import') { self.schemas[child.$namespace] = new SchemaElement(child.$namespace, {}); self.schemas[child.$namespace].addChild(child); } else if (child instanceof PortTypeElement) { self.portTypes[child.$name] = child; } else if (child instanceof BindingElement) { if (child.transport === 'http://schemas.xmlsoap.org/soap/http' || child.transport === 'http://www.w3.org/2003/05/soap/bindings/HTTP/') self.bindings[child.$name] = child; } else if (child instanceof ServiceElement) { self.services[child.$name] = child; } else if (child instanceof DocumentationElement) { } this.children.pop(); }; MessageElement.prototype.postProcess = function(definitions) { var part = null; var child; var children = this.children || []; var ns; var nsName; var i; var type; for (i in children) { if ((child = children[i]).name === 'part') { part = child; break; } } if (!part) { return; } if (part.$element) { var lookupTypes = [], elementChildren ; delete this.parts; nsName = splitQName(part.$element); ns = nsName.prefix; var schema = definitions.schemas[definitions.xmlns[ns]]; this.element = schema.elements[nsName.name]; if(!this.element) { debug(nsName.name + " is not present in wsdl and cannot be processed correctly."); return; } this.element.targetNSAlias = ns; this.element.targetNamespace = definitions.xmlns[ns]; // set the optional $lookupType to be used within `client#_invoke()` when // calling `wsdl#objectToDocumentXML() this.element.$lookupType = part.$name; elementChildren = this.element.children; // get all nested lookup types (only complex types are followed) if (elementChildren.length > 0) { for (i = 0; i < elementChildren.length; i++) { lookupTypes.push(this._getNestedLookupTypeString(elementChildren[i])); } } // if nested lookup types where found, prepare them for furter usage if (lookupTypes.length > 0) { lookupTypes = lookupTypes. join('_'). split('_'). filter(function removeEmptyLookupTypes (type) { return type !== '^'; }); var schemaXmlns = definitions.schemas[this.element.targetNamespace].xmlns; for (i = 0; i < lookupTypes.length; i++) { lookupTypes[i] = this._createLookupTypeObject(lookupTypes[i], schemaXmlns); } } this.element.$lookupTypes = lookupTypes; if (this.element.$type) { type = splitQName(this.element.$type); var typeNs = schema.xmlns && schema.xmlns[type.prefix] || definitions.xmlns[type.prefix]; if (typeNs) { if (type.name in Primitives) { // this.element = this.element.$type; } else { // first check local mapping of ns alias to namespace schema = definitions.schemas[typeNs]; var ctype = schema.complexTypes[type.name] || schema.types[type.name] || schema.elements[type.name]; if (ctype) { this.parts = ctype.description(definitions, schema.xmlns); } } } } else { var method = this.element.description(definitions, schema.xmlns); this.parts = method[nsName.name]; } this.children.splice(0, 1); } else { // rpc encoding this.parts = {}; delete this.element; for (i = 0; part = this.children[i]; i++) { if (part.name === 'documentation') { // <wsdl:documentation can be present under <wsdl:message> continue; } assert(part.name === 'part', 'Expected part element'); nsName = splitQName(part.$type); ns = definitions.xmlns[nsName.prefix]; type = nsName.name; var schemaDefinition = definitions.schemas[ns]; if (typeof schemaDefinition !== 'undefined') { this.parts[part.$name] = definitions.schemas[ns].types[type] || definitions.schemas[ns].complexTypes[type]; } else { this.parts[part.$name] = part.$type; } if (typeof this.parts[part.$name] === 'object') { this.parts[part.$name].prefix = nsName.prefix; this.parts[part.$name].xmlns = ns; } this.children.splice(i--, 1); } } this.deleteFixedAttrs(); }; /** * Takes a given namespaced String(for example: 'alias:property') and creates a lookupType * object for further use in as first (lookup) `parameterTypeObj` within the `objectToXML` * method and provides an entry point for the already existing code in `findChildSchemaObject`. * * @method _createLookupTypeObject * @param {String} nsString The NS String (for example "alias:type"). * @param {Object} xmlns The fully parsed `wsdl` definitions object (including all schemas). * @returns {Object} * @private */ MessageElement.prototype._createLookupTypeObject = function (nsString, xmlns) { var splittedNSString = splitQName(nsString), nsAlias = splittedNSString.prefix, splittedName = splittedNSString.name.split('#'), type = splittedName[0], name = splittedName[1], lookupTypeObj = {}; lookupTypeObj.$namespace = xmlns[nsAlias]; lookupTypeObj.$type = nsAlias + ':' + type; lookupTypeObj.$name = name; return lookupTypeObj; }; /** * Iterates through the element and every nested child to find any defined `$type` * property and returns it in a underscore ('_') separated String (using '^' as default * value if no `$type` property was found). * * @method _getNestedLookupTypeString * @param {Object} element The element which (probably) contains nested `$type` values. * @returns {String} * @private */ MessageElement.prototype._getNestedLookupTypeString = function (element) { var resolvedType = '^', excluded = this.ignoredNamespaces.concat('xs'); // do not process $type values wich start with if (element.hasOwnProperty('$type') && typeof element.$type === 'string') { if (excluded.indexOf(element.$type.split(':')[0]) === -1) { resolvedType += ('_' + element.$type + '#' + element.$name); } } if (element.children.length > 0) { var self = this; element.children.forEach(function (child) { var resolvedChildType = self._getNestedLookupTypeString(child).replace(/\^_/, ''); if (resolvedChildType && typeof resolvedChildType === 'string') { resolvedType += ('_' + resolvedChildType); } }); } return resolvedType; }; OperationElement.prototype.postProcess = function(definitions, tag) { var children = this.children; for (var i = 0, child; child = children[i]; i++) { if (child.name !== 'input' && child.name !== 'output') continue; if (tag === 'binding') { this[child.name] = child; children.splice(i--, 1); continue; } var messageName = splitQName(child.$message).name; var message = definitions.messages[messageName]; message.postProcess(definitions); if (message.element) { definitions.messages[message.element.$name] = message; this[child.name] = message.element; } else { this[child.name] = message; } children.splice(i--, 1); } this.deleteFixedAttrs(); }; PortTypeElement.prototype.postProcess = function(definitions) { var children = this.children; if (typeof children === 'undefined') return; for (var i = 0, child; child = children[i]; i++) { if (child.name !== 'operation') continue; child.postProcess(definitions, 'portType'); this.methods[child.$name] = child; children.splice(i--, 1); } delete this.$name; this.deleteFixedAttrs(); }; BindingElement.prototype.postProcess = function(definitions) { var type = splitQName(this.$type).name, portType = definitions.portTypes[type], style = this.style, children = this.children; if (portType){ portType.postProcess(definitions); this.methods = portType.methods; for (var i = 0, child; child = children[i]; i++) { if (child.name !== 'operation') continue; child.postProcess(definitions, 'binding'); children.splice(i--, 1); child.style || (child.style = style); var method = this.methods[child.$name]; if (method) { method.style = child.style; method.soapAction = child.soapAction; method.inputSoap = child.input || null; method.outputSoap = child.output || null; method.inputSoap && method.inputSoap.deleteFixedAttrs(); method.outputSoap && method.outputSoap.deleteFixedAttrs(); } } } delete this.$name; delete this.$type; this.deleteFixedAttrs(); }; ServiceElement.prototype.postProcess = function(definitions) { var children = this.children, bindings = definitions.bindings; if (children && children.length > 0) { for (var i = 0, child; child = children[i]; i++) { if (child.name !== 'port') continue; var bindingName = splitQName(child.$binding).name; var binding = bindings[bindingName]; if (binding) { binding.postProcess(definitions); this.ports[child.$name] = { location: child.location, binding: binding }; children.splice(i--, 1); } } } delete this.$name; this.deleteFixedAttrs(); }; SimpleTypeElement.prototype.description = function(definitions) { var children = this.children; for (var i = 0, child; child = children[i]; i++) { if (child instanceof RestrictionElement) return this.$name + "|" + child.description(); } return {}; }; RestrictionElement.prototype.description = function(definitions, xmlns) { var children = this.children; var desc; for (var i=0, child; child=children[i]; i++) { if (child instanceof SequenceElement || child instanceof ChoiceElement) { desc = child.description(definitions, xmlns); break; } } if (desc && this.$base) { var type = splitQName(this.$base), typeName = type.name, ns = xmlns && xmlns[type.prefix] || definitions.xmlns[type.prefix], schema = definitions.schemas[ns], typeElement = schema && ( schema.complexTypes[typeName] || schema.types[typeName] || schema.elements[typeName] ); desc.getBase = function() { return typeElement.description(definitions, schema.xmlns); }; return desc; } // then simple element var base = this.$base ? this.$base + "|" : ""; return base + this.children.map(function(child) { return child.description(); }).join(","); }; ExtensionElement.prototype.description = function(definitions, xmlns) { var children = this.children; var desc = {}; for (var i=0, child; child=children[i]; i++) { if (child instanceof SequenceElement || child instanceof ChoiceElement) { desc = child.description(definitions, xmlns); } } if (this.$base) { var type = splitQName(this.$base), typeName = type.name, ns = xmlns && xmlns[type.prefix] || definitions.xmlns[type.prefix], schema = definitions.schemas[ns]; if (typeName in Primitives) { return this.$base; } else { var typeElement = schema && ( schema.complexTypes[typeName] || schema.types[typeName] || schema.elements[typeName] ); if (typeElement) { var base = typeElement.description(definitions, schema.xmlns); extend(desc, base); } } } return desc; }; EnumerationElement.prototype.description = function() { return this[this.valueKey]; }; ComplexTypeElement.prototype.description = function(definitions, xmlns) { var children = this.children || []; for (var i=0, child; child=children[i]; i++) { if (child instanceof ChoiceElement || child instanceof SequenceElement || child instanceof AllElement || child instanceof SimpleContentElement || child instanceof ComplexContentElement) { return child.description(definitions, xmlns); } } return {}; }; ComplexContentElement.prototype.description = function(definitions, xmlns) { var children = this.children; for (var i = 0, child; child = children[i]; i++) { if (child instanceof ExtensionElement) { return child.description(definitions, xmlns); } } return {}; }; SimpleContentElement.prototype.description = function(definitions, xmlns) { var children = this.children; for (var i = 0, child; child = children[i]; i++) { if (child instanceof ExtensionElement) { return child.description(definitions, xmlns); } } return {}; }; ElementElement.prototype.description = function(definitions, xmlns) { var element = {}, name = this.$name; var isMany = !this.$maxOccurs ? false : (isNaN(this.$maxOccurs) ? (this.$maxOccurs === 'unbounded') : (this.$maxOccurs > 1)); if (this.$minOccurs !== this.$maxOccurs && isMany) { name += '[]'; } if (xmlns && xmlns[TNS_PREFIX]) { this.$targetNamespace = xmlns[TNS_PREFIX]; } var type = this.$type || this.$ref; if (type) { type = splitQName(type); var typeName = type.name, ns = xmlns && xmlns[type.prefix] || definitions.xmlns[type.prefix], schema = definitions.schemas[ns], typeElement = schema && ( this.$type? schema.complexTypes[typeName] || schema.types[typeName] : schema.elements[typeName] ); if (ns && definitions.schemas[ns]) { xmlns = definitions.schemas[ns].xmlns; } if (typeElement && !(typeName in Primitives)) { if (!(typeName in definitions.descriptions.types)) { var elem = {}; definitions.descriptions.types[typeName] = elem; var description = typeElement.description(definitions, xmlns); if (typeof description === 'string') { elem = description; } else { Object.keys(description).forEach(function (key) { elem[key] = description[key]; }); } if (this.$ref) { element = elem; } else { element[name] = elem; } if (typeof elem === 'object') { elem.targetNSAlias = type.prefix; elem.targetNamespace = ns; } definitions.descriptions.types[typeName] = elem; } else { if (this.$ref) { element = definitions.descriptions.types[typeName]; } else { element[name] = definitions.descriptions.types[typeName]; } } } else { element[name] = this.$type; } } else { var children = this.children; element[name] = {}; for (var i = 0, child; child = children[i]; i++) { if (child instanceof ComplexTypeElement) { element[name] = child.description(definitions, xmlns); } } } return element; }; AllElement.prototype.description = SequenceElement.prototype.description = function(definitions, xmlns) { var children = this.children; var sequence = {}; for (var i = 0, child; child = children[i]; i++) { if (child instanceof AnyElement) { continue; } var description = child.description(definitions, xmlns); for (var key in description) { sequence[key] = description[key]; } } return sequence; }; ChoiceElement.prototype.description = function(definitions, xmlns) { var children = this.children; var choice = {}; for (var i=0, child; child=children[i]; i++) { var description = child.description(definitions, xmlns); for (var key in description) { choice[key] = description[key]; } } return choice; }; MessageElement.prototype.description = function(definitions) { if (this.element) { return this.element && this.element.description(definitions); } var desc = {}; desc[this.$name] = this.parts; return desc; }; PortTypeElement.prototype.description = function(definitions) { var methods = {}; for (var name in this.methods) { var method = this.methods[name]; methods[name] = method.description(definitions); } return methods; }; OperationElement.prototype.description = function(definitions) { var inputDesc = this.input ? this.input.description(definitions) : null; var outputDesc = this.output ? this.output.description(definitions) : null; return { input: inputDesc && inputDesc[Object.keys(inputDesc)[0]], output: outputDesc && outputDesc[Object.keys(outputDesc)[0]] }; }; BindingElement.prototype.description = function(definitions) { var methods = {}; for (var name in this.methods) { var method = this.methods[name]; methods[name] = method.description(definitions); } return methods; }; ServiceElement.prototype.description = function(definitions) { var ports = {}; for (var name in this.ports) { var port = this.ports[name]; ports[name] = port.binding.description(definitions); } return ports; }; var WSDL = function(definition, uri, options) { var self = this, fromFunc; this.uri = uri; this.callback = function() { }; this._includesWsdl = []; // initialize WSDL cache this.WSDL_CACHE = (options || {}).WSDL_CACHE || {}; this._initializeOptions(options); if (typeof definition === 'string') { definition = stripBom(definition); fromFunc = this._fromXML; } else if (typeof definition === 'object') { fromFunc = this._fromServices; } else { throw new Error('WSDL constructor takes either an XML string or service definition'); } process.nextTick(function() { try { fromFunc.call(self, definition); } catch (e) { return self.callback(e.message); } self.processIncludes(function(err) { var name; if (err) { return self.callback(err); } self.definitions.deleteFixedAttrs(); var services = self.services = self.definitions.services; if (services) { for (name in services) { services[name].postProcess(self.definitions); } } var complexTypes = self.definitions.complexTypes; if (complexTypes) { for (name in complexTypes) { complexTypes[name].deleteFixedAttrs(); } } // for document style, for every binding, prepare input message element name to (methodName, output message element name) mapping var bindings = self.definitions.bindings; for (var bindingName in bindings) { var binding = bindings[bindingName]; if (typeof binding.style === 'undefined') { binding.style = 'document'; } if (binding.style !== 'document') continue; var methods = binding.methods; var topEls = binding.topElements = {}; for (var methodName in methods) { if (methods[methodName].input) { var inputName = methods[methodName].input.$name; var outputName=""; if(methods[methodName].output ) outputName = methods[methodName].output.$name; topEls[inputName] = {"methodName": methodName, "outputName": outputName}; } } } // prepare soap envelope xmlns definition string self.xmlnsInEnvelope = self._xmlnsMap(); self.callback(err, self); }); }); }; WSDL.prototype.ignoredNamespaces = ['tns', 'targetNamespace', 'typedNamespace']; WSDL.prototype.ignoreBaseNameSpaces = false; WSDL.prototype.valueKey = '$value'; WSDL.prototype.xmlKey = '$xml'; WSDL.prototype._initializeOptions = function (options) { this._originalIgnoredNamespaces = (options || {}).ignoredNamespaces; this.options = {}; var ignoredNamespaces = options ? options.ignoredNamespaces : null; if (ignoredNamespaces && (Array.isArray(ignoredNamespaces.namespaces) || typeof ignoredNamespaces.namespaces === 'string')) { if (ignoredNamespaces.override) { this.options.ignoredNamespaces = ignoredNamespaces.namespaces; } else { this.options.ignoredNamespaces = this.ignoredNamespaces.concat(ignoredNamespaces.namespaces); } } else { this.options.ignoredNamespaces = this.ignoredNamespaces; } this.options.valueKey = options.valueKey || this.valueKey; this.options.xmlKey = options.xmlKey || this.xmlKey; // Allow any request headers to keep passing through this.options.wsdl_headers = options.wsdl_headers; this.options.wsdl_options = options.wsdl_options; var ignoreBaseNameSpaces = options ? options.ignoreBaseNameSpaces : null; if(ignoreBaseNameSpaces !== null && typeof ignoreBaseNameSpaces !== 'undefined' ) this.options.ignoreBaseNameSpaces = ignoreBaseNameSpaces; else this.options.ignoreBaseNameSpaces = this.ignoreBaseNameSpaces; // Works only in client this.options.forceSoap12Headers = options.forceSoap12Headers; if(options.overrideRootElement !== undefined) { this.options.overrideRootElement = options.overrideRootElement; } }; WSDL.prototype.onReady = function(callback) { if (callback) this.callback = callback; }; WSDL.prototype._processNextInclude = function(includes, callback) { var self = this, include = includes.shift(), options; if (!include) return callback(); var includePath; if (!/^https?:/.test(self.uri) && !/^https?:/.test(include.location)) { includePath = path.resolve(path.dirname(self.uri), include.location); } else { includePath = url.resolve(self.uri, include.location); } options = _.assign({}, this.options); // follow supplied ignoredNamespaces option options.ignoredNamespaces = this._originalIgnoredNamespaces || this.options.ignoredNamespaces; options.WSDL_CACHE = this.WSDL_CACHE; open_wsdl_recursive(includePath, options, function(err, wsdl) { if (err) { return callback(err); } self._includesWsdl.push(wsdl); if(wsdl.definitions instanceof DefinitionsElement){ _.merge(self.definitions, wsdl.definitions, function(a,b) { return (a instanceof SchemaElement) ? a.merge(b) : undefined; }); }else{ self.definitions.schemas[include.namespace || wsdl.definitions.$targetNamespace] = deepMerge(self.definitions.schemas[include.namespace || wsdl.definitions.$targetNamespace], wsdl.definitions); } self._processNextInclude(includes, function(err) { callback(err); }); }); }; WSDL.prototype.processIncludes = function(callback) { var schemas = this.definitions.schemas, includes = []; for (var ns in schemas) { var schema = schemas[ns]; includes = includes.concat(schema.includes || []); } this._processNextInclude(includes, callback); }; WSDL.prototype.describeServices = function() { var services = {}; for (var name in this.services) { var service = this.services[name]; services[name] = service.description(this.definitions); } return services; }; WSDL.prototype.toXML = function() { return this.xml || ''; }; WSDL.prototype.xmlToObject = function(xml) { var self = this; var p = sax.parser(true); var objectName = null; var root = {}; var schema = { Envelope: { Header: { Security: { UsernameToken: { Username: 'string', Password: 'string' } } }, Body: { Fault: { faultcode: 'string', faultstring: 'string', detail: 'string' } } } }; var stack = [{name: null, object: root, schema: schema}]; var xmlns = {}; var refs = {}, id; // {id:{hrefs:[],obj:}, ...} p.onopentag = function(node) { var nsName = node.name; var attrs = node.attributes; var name = splitQName(nsName).name, attributeName, top = stack[stack.length - 1], topSchema = top.schema, elementAttributes = {}, hasNonXmlnsAttribute = false, hasNilAttribute = false, obj = {}; var originalName = name; if (!objectName && top.name === 'Body' && name !== 'Fault') { var message = self.definitions.messages[name]; // Support RPC/literal messages where response body contains one element named // after the operation + 'Response'. See http://www.w3.org/TR/wsdl#_names if (!message) { // Determine if this is request or response var isInput = false; var isOutput = false; if ((/Response$/).test(name)) { isOutput = true; name = name.replace(/Response$/, ''); } else if ((/Request$/).test(name)) { isInput = true; name = name.replace(/Request$/, ''); } else if ((/Solicit$/).test(name)) { isInput = true; name = name.replace(/Solicit$/, ''); } // Look up the appropriate message as given in the portType's operations var portTypes = self.definitions.portTypes; var portTypeNames = Object.keys(portTypes); // Currently this supports only one portType definition. var portType = portTypes[portTypeNames[0]]; if (isInput) name = portType.methods[name].input.$name; else name = portType.methods[name].output.$name; message = self.definitions.messages[name]; // 'cache' this alias to speed future lookups self.definitions.messages[originalName] = self.definitions.messages[name]; } topSchema = message.description(self.definitions); objectName = originalName; } if (attrs.href) { id = attrs.href.substr(1); if (!refs[id]) refs[id] = {hrefs: [], obj: null}; refs[id].hrefs.push({par: top.object, key: name, obj: obj}); } if (id = attrs.id) { if (!refs[id]) refs[id] = {hrefs: [], obj: null}; } //Handle element attributes for(attributeName in attrs){ if(/^xmlns:|^xmlns$/.test(attributeName)){ xmlns[splitQName(attributeName).name] = attrs[attributeName]; continue; } hasNonXmlnsAttribute = true; elementAttributes[attributeName] = attrs[attributeName]; } for(attributeName in elementAttributes){ var res = splitQName(attributeName); if(res.name === 'nil' && xmlns[res.prefix] === 'http://www.w3.org/2001/XMLSchema-instance'){ hasNilAttribute = true; break; } } if(hasNonXmlnsAttribute)obj[self.options.attributesKey] = elementAttributes; // Pick up the schema for the type specified in element's xsi:type attribute. var xsiTypeSchema; var xsiType = elementAttributes['xsi:type']; if (xsiType) { var type = splitQName(xsiType); var typeURI; if (type.prefix === TNS_PREFIX) { // In case of xsi:type = "MyType" typeURI = xmlns[type.prefix] || xmlns.xmlns; } else { typeURI = xmlns[type.prefix]; } var typeDef = self.findSchemaObject(typeURI, type.name); if (typeDef) { xsiTypeSchema = typeDef.description(self.definitions); } } if (topSchema && topSchema[name + '[]']) name = name + '[]'; stack.push({name: originalName, object: obj, schema: (xsiTypeSchema || (topSchema && topSchema[name])), id: attrs.id, nil: hasNilAttribute}); }; p.onclosetag = function(nsName) { var cur = stack.pop(), obj = cur.object, top = stack[stack.length - 1], topObject = top.object, topSchema = top.schema, name = splitQName(nsName).name; if (typeof cur.schema === 'string' && (cur.schema === 'string' || cur.schema.split(':')[1] === 'string')) { if (typeof obj === 'object' && Object.keys(obj).length === 0) obj = cur.object = ''; } if(cur.nil === true) { return; } if (_.isPlainObject(obj) && !Object.keys(obj).length) { obj = null; } if (topSchema && topSchema[name + '[]']) { if (!topObject[name]) topObject[name] = []; topObject[name].push(obj); } else if (name in topObject) { if (!Array.isArray(topObject[name])) { topObject[name] = [topObject[name]]; } topObject[name].push(obj); } else { topObject[name] = obj; } if (cur.id) { refs[cur.id].obj = obj; } }; p.oncdata = function (text) { text = trim(text); if (!text.length) return; if (/<\?xml[\s\S]+\?>/.test(text)) { var top = stack[stack.length - 1]; var value = self.xmlToObject(text); if (top.object[self.options.attributesKey]) { top.object[self.options.valueKey] = value; } else { top.object = value; } } else { p.ontext(text); } }; p.ontext = function(text) { text = trim(text); if (!text.length) return; var top = stack[stack.length - 1]; var name = splitQName(top.schema).name, value; if (name === 'int' || name === 'integer') { value = parseInt(text, 10); } else if (name === 'bool' || name === 'boolean') { value = text.toLowerCase() === 'true' || text === '1'; } else if (name === 'dateTime' || name === 'date') { value = new Date(text); } else { // handle string or other types if (typeof top.object !== 'string') { value = text; } else { value = top.object + text; } } if(top.object[self.options.attributesKey]) { top.object[self.options.valueKey] = value; } else { top.object = value; } }; p.write(xml).close(); // merge obj with href var merge = function(href, obj) { for (var j in obj) { if (obj.hasOwnProperty(j)) { href.obj[j] = obj[j]; } } }; // MultiRef support: merge objects instead of replacing for (var n in refs) { var ref = refs[n]; for (var i = 0; i < ref.hrefs.length; i++) { merge(ref.hrefs[i], ref.obj); } } if (root.Envelope) { var body = root.Envelope.Body; if (body.Fault) { var code = selectn('faultcode.$value', body.Fault) || selectn('faultcode', body.Fault); var string = selectn('faultstring.$value', body.Fault) || selectn('faultstring', body.Fault); var detail = selectn('detail.$value', body.Fault) || selectn('detail.message', body.Fault); var error = new Error(code + ': ' + string + (detail ? ': ' + detail : '')); error.root = root; throw error; } return root.Envelope; } return root; }; /** * Look up a XSD type or element by namespace URI and name * @param {String} nsURI Namespace URI * @param {String} qname Local or qualified name * @returns {*} The XSD type/element definition */ WSDL.prototype.findSchemaObject = function(nsURI, qname) { if (!nsURI || !qname) { return null; } var def = null; if (this.definitions.schemas) { var schema = this.definitions.schemas[nsURI]; if (schema) { if (qname.indexOf(':') !== -1) { qname = qname.substring(qname.indexOf(':') + 1, qname.length); } // if the client passed an input element which has a `$lookupType` property instead of `$type` // the `def` is found in `schema.elements`. def = schema.complexTypes[qname] || schema.types[qname] || schema.elements[qname]; } } return def; }; /** * Create document style xml string from the parameters * @param {String} name * @param {*} params * @param {String} nsPrefix * @param {String} nsURI * @param {String} type */ WSDL.prototype.objectToDocumentXML = function(name, params, nsPrefix, nsURI, type) { var args = {}; args[name] = params; var parameterTypeObj = type ? this.findSchemaObject(nsURI, type) : null; return this.objectToXML(args, null, nsPrefix, nsURI, true, null, parameterTypeObj); }; /** * Create RPC style xml string from the parameters * @param {String} name * @param {*} params * @param {String} nsPrefix * @param {String} nsURI * @returns {string} */ WSDL.prototype.objectToRpcXML = function(name, params, nsPrefix, nsURI) { var parts = []; var defs = this.definitions; var nsAttrName = '_xmlns'; nsPrefix = nsPrefix || findPrefix(defs.xmlns, nsURI); nsURI = nsURI || defs.xmlns[nsPrefix]; nsPrefix = nsPrefix === TNS_PREFIX ? '' : (nsPrefix + ':'); parts.push(['<', nsPrefix, name, '>'].join('')); for (var key in params) { if (!params.hasOwnProperty(key)) continue; if (key !== nsAttrName) { var value = params[key]; parts.push(['<', key, '>'].join('')); parts.push((typeof value === 'object') ? this.objectToXML(value, key, nsPrefix, nsURI) : xmlEscape(value)); parts.push(['</', key, '>'].join('')); } } parts.push(['</', nsPrefix, name, '>'].join('')); return parts.join(''); }; /** * Convert an object to XML. This is a recursive method as it calls itself. * * @param {Object} obj the object to convert. * @param {String} name the name of the element (if the object being traversed is * an element). * @param {String} nsPrefix the namespace prefix of the object I.E. xsd. * @param {String} nsURI the full namespace of the object I.E. http://w3.org/schema. * @param {Boolean} isFirst whether or not this is the first item being traversed. * @param {?} xmlnsAttr * @param {?} parameterTypeObject * @param {NamespaceContext} nsContext Namespace context */ WSDL.prototype.objectToXML = function(obj, name, nsPrefix, nsURI, isFirst, xmlnsAttr, schemaObject, nsContext) { var self = this; var schema = this.definitions.schemas[nsURI]; var parentNsPrefix = nsPrefix ? nsPrefix.parent : undefined; if(typeof parentNsPrefix !== 'undefined') { //we got the parentNsPrefix for our array. setting the namespace-variable back to the current namespace string nsPrefix = nsPrefix.current; } var soapHeader = !schema; var qualified = schema && schema.$elementFormDefault === 'qualified'; var parts = []; var prefixNamespace = (nsPrefix || qualified) && nsPrefix !== TNS_PREFIX; var xmlnsAttrib = ''; if (nsURI && isFirst) { if(self.options.overrideRootElement && self.options.overrideRootElement.xmlnsAttributes) { self.options.overrideRootElement.xmlnsAttributes.forEach(function(attribute) { xmlnsAttrib += ' ' + attribute.name + '="' + attribute.value + '"'; }); } else { if (prefixNamespace && this.options.ignoredNamespaces.indexOf(nsPrefix) === -1) { // resolve the prefix namespace xmlnsAttrib += ' xmlns:' + nsPrefix + '="' + nsURI + '"'; } // only add default namespace if the schema elementFormDefault is qualified if (qualified || soapHeader) xmlnsAttrib += ' xmlns="' + nsURI + '"'; } } if (!nsContext) { nsContext = new NamespaceContext(); nsContext.declareNamespace(nsPrefix, nsURI); } else { nsContext.pushContext(); } // explicitly use xmlns attribute if available if (xmlnsAttr && !(self.options.overrideRootElement && self.options.overrideRootElement.xmlnsAttributes)) { xmlnsAttrib = xmlnsAttr; } var ns = ''; if(self.options.overrideRootElement && isFirst) { ns = self.options.overrideRootElement.namespace + ':'; } else if (prefixNamespace && ((qualified || isFirst) || soapHeader) && this.options.ignoredNamespaces.indexOf(nsPrefix) === -1) { // prefix element ns = nsPrefix.indexOf(":") === -1 ? nsPrefix + ':' : nsPrefix; } var i, n; // start building out XML string. if (Array.isArray(obj)) { for (i = 0, n = obj.length; i < n; i++) { var item = obj[i]; var arrayAttr = self.processAttributes(item, nsContext), correctOuterNsPrefix = parentNsPrefix || ns; //using the parent namespace prefix if given parts.push(['<', correctOuterNsPrefix, name, arrayAttr, xmlnsAttrib, '>'].join('')); parts.push(self.objectToXML(item, name, nsPrefix, nsURI, false, null, schemaObject, nsContext)); parts.push(['</', correctOuterNsPrefix, name, '>'].join('')); } } else if (typeof obj === 'object') { for (name in obj) { if (!obj.hasOwnProperty(name)) continue; //don't process attributes as element if (name === self.options.attributesKey) { continue; } //Its the value of a xml object. Return it directly. if (name === self.options.xmlKey){ nsContext.popContext(); return obj[name]; } //Its the value of an item. Return it directly. if (name === self.options.valueKey) { nsContext.popContext(); return xmlEscape(obj[name]); } var child = obj[name]; if (typeof child === 'undefined') continue; var attr = self.processAttributes(child, nsContext); var value = ''; var nonSubNameSpace = ''; var emptyNonSubNameSpace = false; var nameWithNsRegex = /^([^:]+):([^:]+)$/.exec(name); if (nameWithNsRegex) { nonSubNameSpace = nameWithNsRegex[1] + ':'; name = nameWithNsRegex[2]; } else if(name[0] === ':'){ emptyNonSubNameSpace = true; name = name.substr(1); } if (isFirst) { value = self.objectToXML(child, name, nsPrefix, nsURI, false, null, schemaObject, nsContext); } else { if (self.definitions.schemas) { if (schema) { var childSchemaObject = self.findChildSchemaObject(schemaObject, name); //find sub namespace if not a primitive if (childSchemaObject && ((childSchemaObject.$type && (childSchemaObject.$type.indexOf('xsd:') === -1)) || childSchemaObject.$ref || childSchemaObject.$name)) { /*if the base name space of the children is not in the ingoredSchemaNamspaces we use it. This is because in some services the child nodes do not need the baseNameSpace. */ var childNsPrefix = ''; var childName = ''; var childNsURI; var childXmlnsAttrib = ''; var elementQName = childSchemaObject.$ref || childSchemaObject.$name; if (elementQName) { elementQName = splitQName(elementQName); childName = elementQName.name; if (elementQName.prefix === TNS_PREFIX) { // Local element childNsURI = childSchemaObject.$targetNamespace; childNsPrefix = nsContext.registerNamespace(childNsURI); for (i = 0, n = this.ignoredNamespaces.length; i < n; i++) { if (this.ignoredNamespaces[i] === childNsPrefix) { childNsPrefix = nsPrefix; break; } } } else { childNsPrefix = elementQName.prefix; for (i = 0, n = this.ignoredNamespaces.length; i < n; i++) { if (this.ignoredNamespaces[i] === childNsPrefix) { childNsPrefix = nsPrefix; break; } } childNsURI = schema.xmlns[childNsPrefix] || self.definitions.xmlns[childNsPrefix]; } var unqualified = false; // Check qualification form for local elements if (childSchemaObject.$name && childSchemaObject.targetNamespace === undefined) { if (childSchemaObject.$form === 'unqualified') { unqualified = true; } else if (childSchemaObject.$form === 'qualified') { unqualified = false; } else { unqualified = schema.$elementFormDefault === 'unqualified'; } } if (unqualified) { childNsPrefix = ''; } if (childNsURI && childNsPrefix) { if (nsContext.declareNamespace(childNsPrefix, childNsURI)) { childXmlnsAttrib = ' xmlns:' + childNsPrefix + '="' + childNsURI + '"'; xmlnsAttrib += childXmlnsAttrib; } } } var resolvedChildSchemaObject; if (childSchemaObject.$type) { var typeQName = splitQName(childSchemaObject.$type); var typePrefix = typeQName.prefix; var typeURI = schema.xmlns[typePrefix] || self.definitions.xmlns[typePrefix]; childNsURI = typeURI; if (typeURI !== 'http://www.w3.org/2001/XMLSchema') { // Add the prefix/namespace mapping, but not declare it nsContext.addNamespace(typeQName.prefix, typeURI); } resolvedChildSchemaObject = self.findSchemaType(typeQName.name, typeURI) || childSchemaObject; } else { resolvedChildSchemaObject = self.findSchemaObject(childNsURI, childName) || childSchemaObject; } if (childSchemaObject.$baseNameSpace && this.options.ignoreBaseNameSpaces) { childNsPrefix = nsPrefix; childNsURI = nsURI; } if (this.options.ignoreBaseNameSpaces) { childNsPrefix = ''; childNsURI = ''; } ns = childNsPrefix ? childNsPrefix + ':' : ''; if(Array.isArray(child)) { //for arrays, we need to remember the current namespace childNsPrefix = { current: childNsPrefix, parent: ns }; } value = self.objectToXML(child, name, childNsPrefix, childNsURI, false, null, resolvedChildSchemaObject, nsContext); } else if (obj[self.options.attributesKey] && obj[self.options.attributesKey].xsi_type) { //if parent object has complex type defined and child not found in parent var completeChildParamTypeObject = self.findChildSchemaObject( obj[self.options.attributesKey].xsi_type.type, obj[self.options.attributesKey].xsi_type.xmlns); nonSubNameSpace = obj[self.options.attributesKey].xsi_type.prefix + ':'; nsContext.addNamespace(obj[self.options.attributesKey].xsi_type.prefix, obj[self.options.attributesKey].xsi_type.xmlns); value = self.objectToXML(child, name, obj[self.options.attributesKey].xsi_type.prefix, obj[self.options.attributesKey].xsi_type.xmlns, false, null, null, nsContext); } else { if(Array.isArray(child)) { name = nonSubNameSpace + name; } value = self.objectToXML(child, name, nsPrefix, nsURI, false, null, null, nsContext); } } else { value = self.objectToXML(child, name, nsPrefix, nsURI, false, null, null, nsContext); } } } if (!Array.isArray(child)) { parts.push(['<', emptyNonSubNameSpace ? '' : nonSubNameSpace || ns, name, attr, xmlnsAttrib, (child === null ? ' xsi:nil="true"' : ''), '>'].join('')); } parts.push(value); if (!Array.isArray(child)) { parts.push(['</', emptyNonSubNameSpace ? '' : nonSubNameSpace || ns, name, '>'].join('')); } } } else if (obj !== undefined) { parts.push(xmlEscape(obj)); } nsContext.popContext(); return parts.join(''); }; WSDL.prototype.processAttributes = function(child, nsContext) { var attr = ''; if(child === null) { child = []; } var attrObj = child[this.options.attributesKey]; if (attrObj && attrObj.xsi_type) { var xsiType = attrObj.xsi_type; var prefix = xsiType.prefix || xsiType.namespace; // Generate a new namespace for complex extension if one not provided if (!prefix) { prefix = nsContext.registerNamespace(xsiType.xmlns); } else { nsContext.declareNamespace(prefix, xsiType.xmlns); } xsiType.prefix = prefix; } if (attrObj) { for (var attrKey in attrObj) { //handle complex extension separately if (attrKey === 'xsi_type') { var attrValue = attrObj[attrKey]; attr += ' xsi:type="' + attrValue.prefix + ':' + attrValue.type + '"'; attr += ' xmlns:' + attrValue.prefix + '="' + attrValue.xmlns + '"'; continue; } else { attr += ' ' + attrKey + '="' + xmlEscape(attrObj[attrKey]) + '"'; } } } return attr; }; /** * Look up a schema type definition * @param name * @param nsURI * @returns {*} */ WSDL.prototype.findSchemaType = function(name, nsURI) { if (!this.definitions.schemas || !name || !nsURI) { return null; } var schema = this.definitions.schemas[nsURI]; if (!schema || !schema.complexTypes) { return null; } return schema.complexTypes[name]; }; WSDL.prototype.findChildSchemaObject = function(parameterTypeObj, childName) { if (!parameterTypeObj || !childName) { return null; } var found = null, i = 0, child, ref; if(Array.isArray(parameterTypeObj.$lookupTypes) && parameterTypeObj.$lookupTypes.length) { var types = parameterTypeObj.$lookupTypes; for(i = 0; i < types.length; i++) { var typeObj = types[i]; if(typeObj.$name === childName) { found = typeObj; break; } } } var object = parameterTypeObj; if (object.$name === childName && object.name === 'element') { return object; } if (object.$ref) { ref = splitQName(object.$ref); if (ref.name === childName) { return object; } } var childNsURI; if (object.$type) { var typeInfo = splitQName(object.$type); if (typeInfo.prefix === TNS_PREFIX) { childNsURI = parameterTypeObj.$targetNamespace; } else { childNsURI = this.definitions.xmlns[typeInfo.prefix]; } var typeDef = this.findSchemaType(typeInfo.name, childNsURI); if (typeDef) { return this.findChildSchemaObject(typeDef, childName); } } if (object.children) { for (i = 0, child; child = object.children[i]; i++) { found = this.findChildSchemaObject(child, childName); if (found) { break; } if (child.$base) { var baseQName = splitQName(child.$base); var childNameSpace = baseQName.prefix === TNS_PREFIX ? '' : baseQName.prefix; childNsURI = this.definitions.xmlns[baseQName.prefix]; var foundBase = this.findSchemaType(baseQName.name, childNsURI); if (foundBase) { found = this.findChildSchemaObject(foundBase, childName); if (found) { found.$baseNameSpace = childNameSpace; found.$type = childNameSpace + ':' + childName; break; } } } } } if (!found && object.$name === childName) { return object; } return found; }; WSDL.prototype._parse = function(xml) { var self = this, p = sax.parser(true), stack = [], root = null, types = null, schema = null, options = self.options; p.onopentag = function(node) { var nsName = node.name; var attrs = node.attributes; var top = stack[stack.length - 1]; var name; if (top) { try { top.startElement(stack, nsName, attrs, options); } catch (e) { if (self.options.strict) { throw e; } else { stack.push(new Element(nsName, attrs, options)); } } } else { name = splitQName(nsName).name; if (name === 'definitions') { root = new DefinitionsElement(nsName, attrs, options); stack.push(root); } else if (name === 'schema') { // Shim a structure in here to allow the proper objects to be created when merging back. root = new DefinitionsElement('definitions', {}, {}); types = new TypesElement('types', {}, {}); schema = new SchemaElement(nsName, attrs, options); types.addChild(schema); root.addChild(types); stack.push(schema); } else { throw new Error('Unexpected root element of WSDL or include'); } } }; p.onclosetag = function(name) { var top = stack[stack.length - 1]; assert(top, 'Unmatched close tag: ' + name); top.endElement(stack, name); }; p.write(xml).close(); return root; }; WSDL.prototype._fromXML = function(xml) { this.definitions = this._parse(xml); this.definitions.descriptions = { types:{} }; this.xml = xml; }; WSDL.prototype._fromServices = function(services) { }; WSDL.prototype._xmlnsMap = function() { var xmlns = this.definitions.xmlns; var str = ''; for (var alias in xmlns) { if (alias === '' || alias === TNS_PREFIX) continue; var ns = xmlns[alias]; switch (ns) { case "http://xml.apache.org/xml-soap" : // apachesoap case "http://schemas.xmlsoap.org/wsdl/" : // wsdl case "http://schemas.xmlsoap.org/wsdl/soap/" : // wsdlsoap case "http://schemas.xmlsoap.org/wsdl/soap12/": // wsdlsoap12 case "http://schemas.xmlsoap.org/soap/encoding/" : // soapenc case "http://www.w3.org/2001/XMLSchema" : // xsd continue; } if (~ns.indexOf('http://schemas.xmlsoap.org/')) continue; if (~ns.indexOf('http://www.w3.org/')) continue; if (~ns.indexOf('http://xml.apache.org/')) continue; str += ' xmlns:' + alias + '="' + ns + '"'; } return str; }; /* * Have another function to load previous WSDLs as we * don't want this to be invoked externally (expect for tests) * This will attempt to fix circular dependencies with XSD files, * Given * - file.wsdl * - xs:import namespace="A" schemaLocation: A.xsd * - A.xsd * - xs:import namespace="B" schemaLocation: B.xsd * - B.xsd * - xs:import namespace="A" schemaLocation: A.xsd * file.wsdl will start loading, import A, then A will import B, which will then import A * Because A has already started to load previously it will be returned right away and * have an internal circular reference * B would then complete loading, then A, then file.wsdl * By the time file A starts processing its includes its definitions will be already loaded, * this is the only thing that B will depend on when "opening" A */ function open_wsdl_recursive(uri, options, callback) { var fromCache, WSDL_CACHE; if (typeof options === 'function') { callback = options; options = {}; } WSDL_CACHE = options.WSDL_CACHE; if (fromCache = WSDL_CACHE[ uri ]) { return callback.call(fromCache, null, fromCache); } return open_wsdl(uri, options, callback); } function open_wsdl(uri, options, callback) { if (typeof options === 'function') { callback = options; options = {}; } // initialize cache when calling open_wsdl directly var WSDL_CACHE = options.WSDL_CACHE || {}; var request_headers = options.wsdl_headers; var request_options = options.wsdl_options; var wsdl; if (!/^https?:/.test(uri)) { debug('Reading file: %s', uri); fs.readFile(uri, 'utf8', function(err, definition) { if (err) { callback(err); } else { wsdl = new WSDL(definition, uri, options); WSDL_CACHE[ uri ] = wsdl; wsdl.WSDL_CACHE = WSDL_CACHE; wsdl.onReady(callback); } }); } else { debug('Reading url: %s', uri); var httpClient = options.httpClient || new HttpClient(options); httpClient.request(uri, null /* options */, function(err, response, definition) { if (err) { callback(err); } else if (response && response.statusCode === 200) { wsdl = new WSDL(definition, uri, options); WSDL_CACHE[ uri ] = wsdl; wsdl.WSDL_CACHE = WSDL_CACHE; wsdl.onReady(callback); } else { callback(new Error('Invalid WSDL URL: ' + uri + "\n\n\r Code: " + response.statusCode + "\n\n\r Response Body: " + response.body)); } }, request_headers, request_options); } return wsdl; } exports.open_wsdl = open_wsdl; exports.WSDL = WSDL;
momchil-anachkov/su-translation-app
src/node/node_modules/soap/lib/wsdl.js
JavaScript
gpl-3.0
63,995
/* * Copyright (C) 2019 Nethesis S.r.l. * http://www.nethesis.it - [email protected] * * This script is part of NethServer. * * NethServer 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 any later version. * * NethServer 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 NethServer. If not, see COPYING. */ import Vue from "vue"; import VueI18n from "vue-i18n"; import Router from "vue-router"; import VueToggleButton from "vue-js-toggle-button"; import DocInfo from "./directives/DocInfo.vue"; import VueGoodTable from "vue-good-table"; import LiquorTree from "liquor-tree"; import App from "./App.vue"; import Dashboard from "./views/Dashboard.vue"; import Restore from "./views/Restore.vue"; import About from "./views/About.vue"; import UtilService from "./services/util"; Vue.mixin(UtilService); import "./filters"; Vue.config.productionTip = false; Vue.use(VueToggleButton); Vue.component("doc-info", DocInfo); Vue.use(VueGoodTable); Vue.use(LiquorTree); Vue.use(VueI18n); const i18n = new VueI18n(); Vue.use(Router); const router = new Router({ mode: "hash", base: process.env.BASE_URL, routes: [ { path: "/", redirect: "/dashboard" }, { path: "/dashboard", component: Dashboard }, { path: "/restore", component: Restore }, { path: "/about", name: "about", component: About } ] }); router.replace("/dashboard"); var app = new Vue({ i18n, router, render: h => h(App) }); nethserver.fetchTranslatedStrings(function(data) { i18n.setLocaleMessage("cockpit", data); i18n.locale = "cockpit"; app.$mount("#app"); // Start VueJS application });
NethServer/nethserver-restore-data
ui/src/main.js
JavaScript
gpl-3.0
2,022
Point.sJSLogin.connect(pointSlotLogin); Point.sJSUpdateVertifyCode.connect(pointUpdateVertifyCode); var spliterBtwData = "#..#"; var spliterEnd = "#.^_^.#"; var pointLoginCheckInterval; var pointVertifyChangeIntervalId; // login frame $p_lf = $("#loginIframe").contents(); function pointSlotLogin(userName, pwd, vertifyCode) { $p_lf.find("#al_c").val(vertifyCode); $p_lf.find("#al_u").val(userName); $p_lf.find("#al_p").val(pwd); $p_lf.find("#al_c").val(vertifyCode); setTimeout( function() { // debug Point.justForJSTest("login"); $p_lf.find("#al_submit").get(0).click(); }, 500 ); } var pointLoginCheckValid = true; // whether login check valid flag pointLoginCheckInterval = setInterval("pointLoginCheckSlot()", 500); // check login even (pwd incorrect, username not exist ...) function pointLoginCheckSlot() { if($p_lf.find("#al_warn").css("display") === "block") { if(pointLoginCheckValid) { Point.loginError(1, $p_lf.find("#al_warn").html()); } pointLoginCheckValid = false; } else { pointLoginCheckValid = true; } } pointVertifyChangeIntervalId = setInterval("pointVertifyCodeCheckSlot()", 200); var lastVc = "" function pointVertifyCodeCheckSlot() { var vc = $p_lf.find("#al_c_img").attr("src") if(vc !== lastVc) { Point.justForJSTest("pointVertifyCodeCheckSlot: " + vc) Point.loginError(2, vc); lastVc = vc; } } function pointUpdateVertifyCode() { $p_lf.find("#al_c_img").click(); }
PointTeam/PointDownload
PointDownload/resources/xware/xware_login.js
JavaScript
gpl-3.0
1,587
/* MOBILE SELECT MENU */ (function($){ //variable for storing the menu count when no ID is present var menuCount = 0; //plugin code $.fn.mobileMenu = function(options){ //plugin's default options var settings = { switchWidth: 767, topOptionText: 'Filter by category', indentString: '&nbsp;&nbsp;&nbsp;' }; //function to check if selector matches a list function isList($this){ return $this.is('ul, ol'); } //function to decide if mobile or not function isMobile(){ return ($(window).width() < settings.switchWidth); } //check if dropdown exists for the current element function menuExists($this){ //if the list has an ID, use it to give the menu an ID if($this.attr('id')){ return ($('#mobileMenu_'+$this.attr('id')).length > 0); } //otherwise, give the list and select elements a generated ID else { menuCount++; $this.attr('id', 'mm'+menuCount); return ($('#mobileMenu_mm'+menuCount).length > 0); } } //change page on mobile menu selection function goToPage($this){ if($this.val() !== null){document.location.href = $this.val()} } //show the mobile menu function showMenu($this){ $this.css('display', 'none'); $('#mobileMenu_'+$this.attr('id')).show(); } //hide the mobile menu function hideMenu($this){ $this.css('display', ''); $('#mobileMenu_'+$this.attr('id')).hide(); } //create the mobile menu function createMenu($this){ if(isList($this)){ //generate select element as a string to append via jQuery //var selectString = '<div class="styled-select-cat"><select id="mobileMenu_'+$this.attr('id')+'" class="mobileMenu">'; var selectString = ''; //create first option (no value) //selectString += '<option value="">'+settings.topOptionText+'</option>'; //loop through list items $this.find('li').each(function(){ //when sub-item, indent var levelStr = ''; var len = $(this).parents('ul, ol').length; for(i=1;i<len;i++){levelStr += settings.indentString;} //get url and text for option var link = $(this).find('a:first-child').attr('href'); var text = levelStr + $(this).clone().children('ul, ol').remove().end().text(); //add option //selectString += '<option value="'+link+'">'+text+'</option>'; }); //selectString += '</select></div>'; //append select element to ul/ol's container $this.parent().append(selectString); //add change event handler for mobile menu $('#mobileMenu_'+$this.attr('id')).change(function(){ goToPage($(this)); }); //hide current menu, show mobile menu showMenu($this); } else { alert('mobileMenu will only work with UL or OL elements!'); } } //plugin functionality function run($this){ //menu doesn't exist if(isMobile() && !menuExists($this)){ createMenu($this); } //menu already exists else if(isMobile() && menuExists($this)){ showMenu($this); } //not mobile browser else if(!isMobile() && menuExists($this)){ hideMenu($this); } } //run plugin on each matched ul/ol //maintain chainability by returning "this" return this.each(function() { //override the default settings if user provides some if(options){$.extend(settings, options);} //cache "this" var $this = $(this); //bind event to browser resize $(window).resize(function(){run($this);}); //run plugin run($this); }); }; })(jQuery);
thepetronics/PetroFDS
Web/media/themes/local/menufiles/cat_nav_mobile.js
JavaScript
gpl-3.0
4,018
var assert = require('assert'); var expect = require('chai').expect; var usersMfaEnabled = require('./usersMfaEnabled') const createCache = (users) => { return { iam: { generateCredentialReport: { 'us-east-1': { data: users } } } } } describe('usersMfaEnabled', function () { describe('run', function () { it('should FAIL when user has password and does not have MFA enabled', function (done) { const cache = createCache( [{ user: '<root_account>', password_enabled: true, mfa_active: false }, { user: 'UserAccount', password_enabled: true, mfa_active: false }] ) const callback = (err, results) => { expect(results.length).to.equal(1) expect(results[0].status).to.equal(2) done() } usersMfaEnabled.run(cache, {}, callback) }) it('should PASS when user has password and does not have MFA enabled', function (done) { const cache = createCache( [{ user: '<root_account>', password_enabled: true, mfa_active: false }, { user: 'UserAccount', password_enabled: true, mfa_active: true }] ) const callback = (err, results) => { expect(results.length).to.equal(1) expect(results[0].status).to.equal(0) done() } usersMfaEnabled.run(cache, {}, callback) }) }) })
cloudsploit/scans
plugins/aws/iam/usersMfaEnabled.spec.js
JavaScript
gpl-3.0
1,884
// Note: I had to change the name from [Aa]utocomplete to [Ss]elfcomplete // in order to get this to work at the same time as JQuery-UI /** * Ajax Selfcomplete for jQuery, version 1.4.4 * (c) 2017 Tomas Kirda * * Ajax Selfcomplete for jQuery is freely distributable under the terms of an MIT-style license. * For details, see the web site: https://github.com/devbridge/jQuery-Selfcomplete */ /*jslint browser: true, white: true, single: true, this: true, multivar: true */ /*global define, window, document, jQuery, exports, require */ // Expose plugin as an AMD module if AMD loader is present: (function (factory) { "use strict"; if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object' && typeof require === 'function') { // Browserify factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function ($) { 'use strict'; var utils = (function () { return { escapeRegExChars: function (value) { return value.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&"); }, createNode: function (containerClass) { var div = document.createElement('div'); div.className = containerClass; div.style.position = 'absolute'; div.style.display = 'none'; return div; } }; }()), keys = { ESC: 27, TAB: 9, RETURN: 13, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40 }, noop = $.noop; function Selfcomplete(el, options) { var that = this; // Shared variables: that.element = el; that.el = $(el); that.suggestions = []; that.badQueries = []; that.selectedIndex = -1; that.currentValue = that.element.value; that.timeoutId = null; that.cachedResponse = {}; that.onChangeTimeout = null; that.onChange = null; that.isLocal = false; that.suggestionsContainer = null; that.noSuggestionsContainer = null; that.options = $.extend({}, Selfcomplete.defaults, options); that.classes = { selected: 'selfcomplete-selected', suggestion: 'selfcomplete-suggestion' }; that.hint = null; that.hintValue = ''; that.selection = null; // Initialize and set options: that.initialize(); that.setOptions(options); } Selfcomplete.utils = utils; $.Selfcomplete = Selfcomplete; Selfcomplete.defaults = { ajaxSettings: {}, autoSelectFirst: false, appendTo: 'body', serviceUrl: null, lookup: null, onSelect: null, width: 'auto', minChars: 1, maxHeight: 300, deferRequestBy: 0, params: {}, formatResult: _formatResult, formatGroup: _formatGroup, delimiter: null, zIndex: 9999, type: 'GET', noCache: false, onSearchStart: noop, onSearchComplete: noop, onSearchError: noop, preserveInput: false, containerClass: 'selfcomplete-suggestions', tabDisabled: false, dataType: 'text', currentRequest: null, triggerSelectOnValidInput: true, preventBadQueries: true, lookupFilter: _lookupFilter, paramName: 'query', transformResult: _transformResult, showNoSuggestionNotice: false, noSuggestionNotice: 'No results', orientation: 'bottom', forceFixPosition: false }; function _lookupFilter(suggestion, originalQuery, queryLowerCase) { return suggestion.value.toLowerCase().startsWith(queryLowerCase) !== false; }; function _transformResult(response) { return typeof response === 'string' ? $.parseJSON(response) : response; }; function _formatResult(suggestion, currentValue) { // Do not replace anything if the current value is empty if (!currentValue) { return suggestion.value; } var pattern = '(' + utils.escapeRegExChars(currentValue) + ')'; return suggestion.value .replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>') .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/&lt;(\/?strong)&gt;/g, '<$1>'); }; function _formatGroup(suggestion, category) { return '<div class="selfcomplete-group">' + category + '</div>'; }; Selfcomplete.prototype = { initialize: function () { var that = this, suggestionSelector = '.' + that.classes.suggestion, selected = that.classes.selected, options = that.options, container; // Remove selfcomplete attribute to prevent native suggestions: that.element.setAttribute('selfcomplete', 'off'); // html() deals with many types: htmlString or Element or Array or jQuery that.noSuggestionsContainer = $('<div class="selfcomplete-no-suggestion"></div>') .html(this.options.noSuggestionNotice).get(0); that.suggestionsContainer = Selfcomplete.utils.createNode(options.containerClass); container = $(that.suggestionsContainer); container.appendTo(options.appendTo || 'body'); // Only set width if it was provided: if (options.width !== 'auto') { container.css('width', options.width); } // Listen for mouse over event on suggestions list: container.on('mouseover.selfcomplete', suggestionSelector, function () { that.activate($(this).data('index')); }); // Deselect active element when mouse leaves suggestions container: container.on('mouseout.selfcomplete', function () { that.selectedIndex = -1; container.children('.' + selected).removeClass(selected); }); // Listen for click event on suggestions list: container.on('click.selfcomplete', suggestionSelector, function () { that.select($(this).data('index')); }); container.on('click.selfcomplete', function () { clearTimeout(that.blurTimeoutId); }) that.fixPositionCapture = function () { if (that.visible) { that.fixPosition(); } }; $(window).on('resize.selfcomplete', that.fixPositionCapture); that.el.on('keydown.selfcomplete', function (e) { that.onKeyPress(e); }); that.el.on('keyup.selfcomplete', function (e) { that.onKeyUp(e); }); that.el.on('blur.selfcomplete', function () { that.onBlur(); }); that.el.on('focus.selfcomplete', function () { that.onFocus(); }); that.el.on('change.selfcomplete', function (e) { that.onKeyUp(e); }); that.el.on('input.selfcomplete', function (e) { that.onKeyUp(e); }); }, onFocus: function () { var that = this; that.fixPosition(); if (that.el.val().length >= that.options.minChars) { that.onValueChange(); } }, onBlur: function () { var that = this; // If user clicked on a suggestion, hide() will // be canceled, otherwise close suggestions that.blurTimeoutId = setTimeout(function () { that.hide(); }, 200); }, abortAjax: function () { var that = this; if (that.currentRequest) { that.currentRequest.abort(); that.currentRequest = null; } }, setOptions: function (suppliedOptions) { var that = this, options = $.extend({}, that.options, suppliedOptions); that.isLocal = Array.isArray(options.lookup); if (that.isLocal) { options.lookup = that.verifySuggestionsFormat(options.lookup); } options.orientation = that.validateOrientation(options.orientation, 'bottom'); // Adjust height, width and z-index: $(that.suggestionsContainer).css({ 'max-height': options.maxHeight + 'px', 'width': options.width + 'px', 'z-index': options.zIndex }); this.options = options; }, clearCache: function () { this.cachedResponse = {}; this.badQueries = []; }, clear: function () { this.clearCache(); this.currentValue = ''; this.suggestions = []; }, disable: function () { var that = this; that.disabled = true; clearTimeout(that.onChangeTimeout); that.abortAjax(); }, enable: function () { this.disabled = false; }, fixPosition: function () { // Use only when container has already its content var that = this, $container = $(that.suggestionsContainer), containerParent = $container.parent().get(0); // Fix position automatically when appended to body. // In other cases force parameter must be given. if (containerParent !== document.body && !that.options.forceFixPosition) { return; } // Choose orientation var orientation = that.options.orientation, containerHeight = $container.outerHeight(), height = that.el.outerHeight(), offset = that.el.offset(), styles = { 'top': offset.top, 'left': offset.left }; if (orientation === 'auto') { var viewPortHeight = $(window).height(), scrollTop = $(window).scrollTop(), topOverflow = -scrollTop + offset.top - containerHeight, bottomOverflow = scrollTop + viewPortHeight - (offset.top + height + containerHeight); orientation = (Math.max(topOverflow, bottomOverflow) === topOverflow) ? 'top' : 'bottom'; } if (orientation === 'top') { styles.top += -containerHeight; } else { styles.top += height; } // If container is not positioned to body, // correct its position using offset parent offset if(containerParent !== document.body) { var opacity = $container.css('opacity'), parentOffsetDiff; if (!that.visible){ $container.css('opacity', 0).show(); } parentOffsetDiff = $container.offsetParent().offset(); styles.top -= parentOffsetDiff.top; styles.left -= parentOffsetDiff.left; if (!that.visible){ $container.css('opacity', opacity).hide(); } } if (that.options.width === 'auto') { styles.width = that.el.outerWidth() + 'px'; } $container.css(styles); }, isCursorAtEnd: function () { var that = this, valLength = that.el.val().length, selectionStart = that.element.selectionStart, range; if (typeof selectionStart === 'number') { return selectionStart === valLength; } if (document.selection) { range = document.selection.createRange(); range.moveStart('character', -valLength); return valLength === range.text.length; } return true; }, onKeyPress: function (e) { var that = this; // If suggestions are hidden and user presses arrow down, display suggestions: if (!that.disabled && !that.visible && e.which === keys.DOWN && that.currentValue) { that.suggest(); return; } if (that.disabled || !that.visible) { return; } switch (e.which) { case keys.ESC: that.el.val(that.currentValue); that.hide(); break; case keys.RIGHT: if (that.hint && that.options.onHint && that.isCursorAtEnd()) { that.selectHint(); break; } return; case keys.TAB: if (that.hint && that.options.onHint) { that.selectHint(); return; } if (that.selectedIndex === -1) { that.hide(); return; } that.select(that.selectedIndex); if (that.options.tabDisabled === false) { return; } break; case keys.RETURN: if (that.selectedIndex === -1) { that.hide(); return; } that.select(that.selectedIndex); break; case keys.UP: that.moveUp(); break; case keys.DOWN: that.moveDown(); break; default: return; } // Cancel event if function did not return: e.stopImmediatePropagation(); e.preventDefault(); }, onKeyUp: function (e) { var that = this; if (that.disabled) { return; } switch (e.which) { case keys.UP: case keys.DOWN: return; } clearTimeout(that.onChangeTimeout); if (that.currentValue !== that.el.val()) { that.findBestHint(); if (that.options.deferRequestBy > 0) { // Defer lookup in case when value changes very quickly: that.onChangeTimeout = setTimeout(function () { that.onValueChange(); }, that.options.deferRequestBy); } else { that.onValueChange(); } } }, onValueChange: function () { if (this.ignoreValueChange) { this.ignoreValueChange = false; return; } var that = this, options = that.options, value = that.el.val(), query = that.getQuery(value); if (that.selection && that.currentValue !== query) { that.selection = null; (options.onInvalidateSelection || $.noop).call(that.element); } clearTimeout(that.onChangeTimeout); that.currentValue = value; that.selectedIndex = -1; // Check existing suggestion for the match before proceeding: if (options.triggerSelectOnValidInput && that.isExactMatch(query)) { that.select(0); return; } if (query.length < options.minChars) { that.hide(); } else { that.getSuggestions(query); } }, isExactMatch: function (query) { var suggestions = this.suggestions; return (suggestions.length === 1 && suggestions[0].value.toLowerCase() === query.toLowerCase()); }, getQuery: function (value) { var delimiter = this.options.delimiter, parts; if (!delimiter) { return value; } parts = value.split(delimiter); return $.trim(parts[parts.length - 1]); }, getSuggestionsLocal: function (query) { var that = this, options = that.options, queryLowerCase = query.toLowerCase(), filter = options.lookupFilter, limit = parseInt(options.lookupLimit, 10), data; data = { suggestions: $.grep(options.lookup, function (suggestion) { return filter(suggestion, query, queryLowerCase); }) }; if (limit && data.suggestions.length > limit) { data.suggestions = data.suggestions.slice(0, limit); } return data; }, getSuggestions: function (q) { var response, that = this, options = that.options, serviceUrl = options.serviceUrl, params, cacheKey, ajaxSettings; options.params[options.paramName] = q; if (options.onSearchStart.call(that.element, options.params) === false) { return; } params = options.ignoreParams ? null : options.params; if ($.isFunction(options.lookup)){ options.lookup(q, function (data) { that.suggestions = data.suggestions; that.suggest(); options.onSearchComplete.call(that.element, q, data.suggestions); }); return; } if (that.isLocal) { response = that.getSuggestionsLocal(q); } else { if ($.isFunction(serviceUrl)) { serviceUrl = serviceUrl.call(that.element, q); } cacheKey = serviceUrl + '?' + $.param(params || {}); response = that.cachedResponse[cacheKey]; } if (response && Array.isArray(response.suggestions)) { that.suggestions = response.suggestions; that.suggest(); options.onSearchComplete.call(that.element, q, response.suggestions); } else if (!that.isBadQuery(q)) { that.abortAjax(); ajaxSettings = { url: serviceUrl, data: params, type: options.type, dataType: options.dataType }; $.extend(ajaxSettings, options.ajaxSettings); that.currentRequest = $.ajax(ajaxSettings).done(function (data) { var result; that.currentRequest = null; result = options.transformResult(data, q); that.processResponse(result, q, cacheKey); options.onSearchComplete.call(that.element, q, result.suggestions); }).fail(function (jqXHR, textStatus, errorThrown) { options.onSearchError.call(that.element, q, jqXHR, textStatus, errorThrown); }); } else { options.onSearchComplete.call(that.element, q, []); } }, isBadQuery: function (q) { if (!this.options.preventBadQueries){ return false; } var badQueries = this.badQueries, i = badQueries.length; while (i--) { if (q.indexOf(badQueries[i]) === 0) { return true; } } return false; }, hide: function () { var that = this, container = $(that.suggestionsContainer); if ($.isFunction(that.options.onHide) && that.visible) { that.options.onHide.call(that.element, container); } that.visible = false; that.selectedIndex = -1; clearTimeout(that.onChangeTimeout); $(that.suggestionsContainer).hide(); that.signalHint(null); }, suggest: function () { if (!this.suggestions.length) { if (this.options.showNoSuggestionNotice) { this.noSuggestions(); } else { this.hide(); } return; } var that = this, options = that.options, groupBy = options.groupBy, formatResult = options.formatResult, value = that.getQuery(that.currentValue), className = that.classes.suggestion, classSelected = that.classes.selected, container = $(that.suggestionsContainer), noSuggestionsContainer = $(that.noSuggestionsContainer), beforeRender = options.beforeRender, html = '', category, formatGroup = function (suggestion, index) { var currentCategory = suggestion.data[groupBy]; if (category === currentCategory){ return ''; } category = currentCategory; return options.formatGroup(suggestion, category); }; if (options.triggerSelectOnValidInput && that.isExactMatch(value)) { that.select(0); return; } // Build suggestions inner HTML: $.each(that.suggestions, function (i, suggestion) { if (groupBy){ html += formatGroup(suggestion, value, i); } html += '<div class="' + className + '" data-index="' + i + '">' + formatResult(suggestion, value, i) + '</div>'; }); this.adjustContainerWidth(); noSuggestionsContainer.detach(); container.html(html); if ($.isFunction(beforeRender)) { beforeRender.call(that.element, container, that.suggestions); } that.fixPosition(); container.show(); // Select first value by default: if (options.autoSelectFirst) { that.selectedIndex = 0; container.scrollTop(0); container.children('.' + className).first().addClass(classSelected); } that.visible = true; that.findBestHint(); }, noSuggestions: function() { var that = this, beforeRender = that.options.beforeRender, container = $(that.suggestionsContainer), noSuggestionsContainer = $(that.noSuggestionsContainer); this.adjustContainerWidth(); // Some explicit steps. Be careful here as it easy to get // noSuggestionsContainer removed from DOM if not detached properly. noSuggestionsContainer.detach(); // clean suggestions if any container.empty(); container.append(noSuggestionsContainer); if ($.isFunction(beforeRender)) { beforeRender.call(that.element, container, that.suggestions); } that.fixPosition(); container.show(); that.visible = true; }, adjustContainerWidth: function() { var that = this, options = that.options, width, container = $(that.suggestionsContainer); // If width is auto, adjust width before displaying suggestions, // because if instance was created before input had width, it will be zero. // Also it adjusts if input width has changed. if (options.width === 'auto') { width = that.el.outerWidth(); container.css('width', width > 0 ? width : 300); } else if(options.width === 'flex') { // Trust the source! Unset the width property so it will be the max length // the containing elements. container.css('width', ''); } }, findBestHint: function () { var that = this, value = that.el.val().toLowerCase(), bestMatch = null; if (!value) { return; } $.each(that.suggestions, function (i, suggestion) { var foundMatch = suggestion.value.toLowerCase().indexOf(value) === 0; if (foundMatch) { bestMatch = suggestion; } return !foundMatch; }); that.signalHint(bestMatch); }, signalHint: function (suggestion) { var hintValue = '', that = this; if (suggestion) { hintValue = that.currentValue + suggestion.value.substr(that.currentValue.length); } if (that.hintValue !== hintValue) { that.hintValue = hintValue; that.hint = suggestion; (this.options.onHint || $.noop)(hintValue); } }, verifySuggestionsFormat: function (suggestions) { // If suggestions is string array, convert them to supported format: if (suggestions.length && typeof suggestions[0] === 'string') { return $.map(suggestions, function (value) { return { value: value, data: null }; }); } return suggestions; }, validateOrientation: function(orientation, fallback) { orientation = $.trim(orientation || '').toLowerCase(); if($.inArray(orientation, ['auto', 'bottom', 'top']) === -1){ orientation = fallback; } return orientation; }, processResponse: function (result, originalQuery, cacheKey) { var that = this, options = that.options; result.suggestions = that.verifySuggestionsFormat(result.suggestions); // Cache results if cache is not disabled: if (!options.noCache) { that.cachedResponse[cacheKey] = result; if (options.preventBadQueries && !result.suggestions.length) { that.badQueries.push(originalQuery); } } // Return if originalQuery is not matching current query: if (originalQuery !== that.getQuery(that.currentValue)) { return; } that.suggestions = result.suggestions; that.suggest(); }, activate: function (index) { var that = this, activeItem, selected = that.classes.selected, container = $(that.suggestionsContainer), children = container.find('.' + that.classes.suggestion); container.find('.' + selected).removeClass(selected); that.selectedIndex = index; if (that.selectedIndex !== -1 && children.length > that.selectedIndex) { activeItem = children.get(that.selectedIndex); $(activeItem).addClass(selected); return activeItem; } return null; }, selectHint: function () { var that = this, i = $.inArray(that.hint, that.suggestions); that.select(i); }, select: function (i) { var that = this; that.hide(); that.onSelect(i); }, moveUp: function () { var that = this; if (that.selectedIndex === -1) { return; } if (that.selectedIndex === 0) { $(that.suggestionsContainer).children().first().removeClass(that.classes.selected); that.selectedIndex = -1; that.ignoreValueChange = false; that.el.val(that.currentValue); that.findBestHint(); return; } that.adjustScroll(that.selectedIndex - 1); }, moveDown: function () { var that = this; if (that.selectedIndex === (that.suggestions.length - 1)) { return; } that.adjustScroll(that.selectedIndex + 1); }, adjustScroll: function (index) { var that = this, activeItem = that.activate(index); if (!activeItem) { return; } var offsetTop, upperBound, lowerBound, heightDelta = $(activeItem).outerHeight(); offsetTop = activeItem.offsetTop; upperBound = $(that.suggestionsContainer).scrollTop(); lowerBound = upperBound + that.options.maxHeight - heightDelta; if (offsetTop < upperBound) { $(that.suggestionsContainer).scrollTop(offsetTop); } else if (offsetTop > lowerBound) { $(that.suggestionsContainer).scrollTop(offsetTop - that.options.maxHeight + heightDelta); } if (!that.options.preserveInput) { // During onBlur event, browser will trigger "change" event, // because value has changed, to avoid side effect ignore, // that event, so that correct suggestion can be selected // when clicking on suggestion with a mouse that.ignoreValueChange = true; that.el.val(that.getValue(that.suggestions[index].value)); } that.signalHint(null); }, onSelect: function (index) { var that = this, onSelectCallback = that.options.onSelect, suggestion = that.suggestions[index]; that.currentValue = that.getValue(suggestion.value); if (that.currentValue !== that.el.val() && !that.options.preserveInput) { that.el.val(that.currentValue); } that.signalHint(null); that.suggestions = []; that.selection = suggestion; if ($.isFunction(onSelectCallback)) { onSelectCallback.call(that.element, suggestion); } }, getValue: function (value) { var that = this, delimiter = that.options.delimiter, currentValue, parts; if (!delimiter) { return value; } currentValue = that.currentValue; parts = currentValue.split(delimiter); if (parts.length === 1) { return value; } return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value; }, dispose: function () { var that = this; that.el.off('.selfcomplete').removeData('selfcomplete'); $(window).off('resize.selfcomplete', that.fixPositionCapture); $(that.suggestionsContainer).remove(); } }; // Create chainable jQuery plugin: $.fn.devbridgeSelfcomplete = function (options, args) { var dataKey = 'selfcomplete'; // If function invoked without argument return // instance of the first matched element: if (!arguments.length) { return this.first().data(dataKey); } return this.each(function () { var inputElement = $(this), instance = inputElement.data(dataKey); if (typeof options === 'string') { if (instance && typeof instance[options] === 'function') { instance[options](args); } } else { // If instance already exists, destroy it: if (instance && instance.dispose) { instance.dispose(); } instance = new Selfcomplete(this, options); inputElement.data(dataKey, instance); } }); }; // Don't overwrite if it already exists if (!$.fn.selfcomplete) { $.fn.selfcomplete = $.fn.devbridgeSelfcomplete; } }));
maryszmary/ud-annotatrix
standalone/lib/ext/jquery.autocomplete.js
JavaScript
gpl-3.0
33,367
// Doctor personal info edit section functions $(function() { retrievePersonalInfo(); // Retrieves personal info var passFields = $('#third_step input[type=password]'); passFields.each(function() { // Erases password values $(this).val(""); }); ////// First form ////// $('form').submit(function(){ return false; }); $('#submit_edit_first').click(function() { $('#submit_edit_first').removeClass('error').removeClass('valid'); // Removes submit error class and adds valid class var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; // E-mail pattern will be used to check mail validity var fields = $('#first_step input[type=text]'); var error = 0; fields.each(function() // Loop passes through all text input fields of the first form { var value = $(this).val(); var phone = $('#phone').val(); var cellPhone = $('#cellPhone').val(); var value = $(this).val(); var field_id = $(this).attr('id'); if( field_id !='phone' && field_id !='cellPhone' && // If current input is NOT phone, cell phone or postcode field_id !='postCode' && value=="" ) // and the input value is the same as the default value { apply_error_events(this,'formError5'); // Error classes messages and animations error++; // (msg: Invalid value) } else if (value.length<3 &&value!= '') // If input is smaller than 3 characters { apply_error_events(this,'formError8'); // Error classes messages and animations error++; // (msg: Enter value with more than 3 characters) } else if((field_id =='phone'|| field_id =='cellPhone') // If no phone number has inserted && phone=="" && cellPhone=="" ) { apply_error_events(this,'formError10'); // Error classes messages and animations error++; // (msg: Insert at least 1 phone number) } else if((value!="" && field_id =='postCode' && // Cases of non-numeric input where numeric (isNaN( $('#postCode').val() ) ) ) || ( value!="" && // is required field_id =='phone' && (isNaN( $('#phone').val()))) || ( value!="" && field_id =='cellPhone' && (isNaN( $('#cellPhone').val() ) ) ) ) { apply_error_events(this,'formError11'); // Error classes messages and animations error++; // (msg: Invalid value) } else if( field_id =='email' && !emailPattern.test(value) ) // Checks e-mail validity { apply_error_events(this,'formError11'); // Error classes messages and animations error++; // (msg: Invalid value) } else { $(this).addClass('valid'); // If none of the above occurs, adds class "valid" $("label[for='"+field_id+"']").fadeTo('slow', 0); // Removes all error messages) if appeared before } }); if(!error) // If all inputs are valid { $('.error_p').fadeTo('fast', 0); // Remove error messages if exist $('#form_msg1 h1').fadeTo('fast', 0); // Remove regular labels $('#form_loading_p_doc').fadeTo('slow', 1); // Visualize waiting animation during the delay.. sendData(1); // Procceed to the data registration } }); ////// Second form ////// $('#submit_edit_second').click(function() { $('#second_step input').removeClass('error').removeClass('valid'); // Removes submit error class and adds valid class var fields = $('#second_step input[type=text]'); var error = 0; if(!error) // If all inputs are valid { $('.error_p').fadeTo('fast', 0); // Remove error messages if exist $('#form_msg2 h1').fadeTo('fast', 0); // Remove regular labels $('#form_loading_p2_doc').fadeTo('slow', 1); // Visualize waiting animation during the delay.. sendData(2); // Procceed to the data registration } }); ////// Third form ////// $('#submit_edit_third').click(function() { $('#third_step input').removeClass('error').removeClass('valid'); // Removes submit error class and adds valid class //ckeck if inputs aren't empty var fields = $('#third_step input[type=password]'); var error = 0; fields.each(function() { var value = $(this).val(); var field_id = $(this).attr('id'); if( value=="" ) { apply_error_events(this,'formError5'); // Error classes messages and animations error++; } else if ( (field_id =='oldPassword' && value.length<5) || (field_id =='newPassword' && value.length<5) || (field_id =='passwordConf' && value.length<5) ) { apply_error_events(this,'formError3'); // Error classes messages and animations error++; } else if ($('#newPassword').val() != $('#passwordConf').val()) { apply_error_events(this,'formError14'); // Error classes messages and animations error++; } else { $(this).addClass('valid'); // If none of the above occurs, adds class "valid" $("label[for='"+field_id+"']").fadeTo('slow', 0); // Removes all error messages) if appeared before } }); if(!error) // If all inputs are valid { $('.error_p').fadeTo('fast', 0); // Remove error messages if exist $('#form_msg3 h1, #form_msg3 p').fadeTo('fast', 0); // Remove regular labels $('#form_loading_p3_doc').fadeTo('slow', 1); // Visualize waiting animation during the delay.. sendData(3); // Procceed to the data registration } }); //////Switch buttons ////// $('.choice_buttons tr #communication_upd').click(function() { $('.content').animate({ height: 840 }, 800, function(){ $('#first_step').slideDown(); // Switches the form contents $('#second_step').slideUp(); $('#third_step').slideUp(); } ); }); $('.choice_buttons tr #biog_upd').click(function() { $('#first_step').slideUp(); $('#third_step').slideUp(); $('.content').animate({ height: 475 }, 800, function(){ // Switches the form contents $('#first_step').slideUp(); $('#second_step').slideDown(); $('#third_step').slideUp(); } ); }); $('.choice_buttons tr #password_upd').click(function() { $('.content').animate({ height: 535 }, 800, function(){ // Switches the form contents $('#first_step').slideUp(); $('#second_step').slideUp(); $('#third_step').slideDown(); } ); }); ////// Retrieves patients data and puts them to the input fields ////// function retrievePersonalInfo() { $.ajax({ type: "POST", url: "server_processes/doctor_functions/staff_data.php", dataType: "json", success: function(response) { $('#address').val(response.Address); $('#city').val(response.City); $('#postCode').val(response.Postal_code); $('#phone').val(response.Home_phone); $('#cellPhone').val(response.Mobile_phone); $('#email').val(response.Email); $('#biog').val(response.Resume); } }); } ////// Sends data to server ////// function sendData(step) { $.ajax({ type: "POST", url: "server_processes/doctor_functions/edit_staff.php", data:{ step: step, address: $('#address').val(), city: $('#city').val(), postCode: $('#postCode').val(), phone: $('#phone').val(), cellPhone: $('#cellPhone').val(), email: $('#email').val(), biog: $('#biog').val(), password: $('#newPassword').val(), oldpass: $('#oldPassword').val() }, success: function(response) { if(response == "EXPIRED") // If the server respons that session has expired { session_expired(); // Calls function to alert the user and logout } else if(response == "DONE") // If all data is succesfully inserted { if(step == 1) // If data is from the first form { $('#form_loading_p_doc').fadeTo('slow', 0); // Hide loading animation $('h1.succ').html(langPack['editSuccess']).fadeTo('slow', 1); // Show success message } else if(step == 2) // If data is from the second form { $('#form_loading_p2_doc').fadeTo('slow', 0); // Hide loading animation $('h1.succ2').html(langPack['editSuccess']).fadeTo('slow', 1); // Show success message } else if(step == 3) // If data is from the third form { $('#form_loading_p3_doc').fadeTo('slow', 0); // Hide loading animation $('h1.succ3').html(langPack['editSuccess']).fadeTo('slow', 1); // Show success message $('p.succ3').html(langPack['editSuccess']).fadeTo('slow', 1); } } else if(response =="WRONG PASS") // If password is invalid { $('#form_loading_p3_doc').fadeTo('slow', 0); // Hide loading animation $('#form_msg3 h1.error_p').html(langPack['wrongPass']).fadeTo('slow', 1); // Show error message $('#form_msg3 p.error_p').html(langPack['wrongPass']).fadeTo('slow', 1); } else{ // Else (if something went wrong) if(step == 1) // If data is from the first form { $('#form_loading_p_doc').fadeTo('slow', 0); // Hide loading animation $('#form_msg1 h1.error_p').html(langPack['regFailed']).fadeTo('slow', 1); // Show error message $('#form_msg1 p.error_p').html(langPack['regSubFaied']).fadeTo('slow', 1); } else if(step == 2) // If data is from the second form { $('#form_loading_p2_doc').fadeTo('slow', 0); // Hide loading animation $('#form_msg2 h1.error_p').html(langPack['regFailed']).fadeTo('slow', 1); // Show error message $('#form_msg2 p.error_p').html(langPack['regSubFaied']).fadeTo('slow', 1); } else if(step == 3) // If data is from the t form { $('#form_loading_p3_doc').fadeTo('slow', 0); // Hide loading animation $('#form_msg3 h1.error_p').html(langPack['regFailed']).fadeTo('slow', 1); // Show error message $('#form_msg3 p.error_p').html(langPack['regSubFaied']).fadeTo('slow', 1); } } } }); } });
labrosb/Hospital-Management-System
client_processes/doctor_functions/edit_staff_profile.js
JavaScript
gpl-3.0
10,568
// Navigation active state on click or section scrolled var sections = $('section'), nav = $('.desktop-navigation'), nav_height = nav.outerHeight(); $(window).on('scroll', function () { var cur_pos = $(this).scrollTop(); sections.each(function() { var top = $(this).offset().top - nav_height -1, bottom = top + $(this).outerHeight(); if (cur_pos >= top && cur_pos <= bottom) { nav.find('a').removeClass('active'); sections.removeClass('active'); $(this).addClass('active'); nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active'); } }); }); nav.find('a').on('click', function () { var $el = $(this), id = $el.attr('href'); // $(this).addClass('active'); $('html, body').animate({ scrollTop: $(id).offset().top - nav_height }, 500); return false; });
blueocto/code-snippets
jquery-javascript/sticky-nav-active-state-while-scrolling.js
JavaScript
gpl-3.0
823
/** * Copyright 2020 The Pennsylvania State University * @license Apache-2.0, see License.md for full text. */ import{LitElement as e,html as t,css as r}from"../../../lit/index.js";import{FutureTerminalTextLiteSuper as a}from"./FutureTerminalTextSuper.js";class FutureTerminalTextLite extends(a(e)){static get styles(){let e=r``;return super.styles&&(e=super.styles),[e,r` :host { font-weight: bold; display: inline-flex; --flicker-easing: cubic-bezier(0.32, 0.32, 0, 0.92); --flicker-duration: 300ms; --fade-in-duration: 500ms; } span { color: #5fa4a5; text-shadow: 0 0 4px #5fa4a5; animation: flicker var(--flicker-duration) var(--flicker-easing); } :host([red]) span { color: #b35b5a; text-shadow: 0 0 4px #b35b5a; } :host([fadein]) span { animation: fade-in var(--fade-in-duration), flicker 300ms var(--flicker-easing) calc(var(--fade-in-duration) * 0.8); transform: translate(0, 0); opacity: 1; } @keyframes flicker { 0% { opacity: 0.75; } 50% { opacity: 0.45; } 100% { opacity: 1; } } @keyframes fade-in { from { transform: translate(-30px, 0px); opacity: 0; } } `]}updated(e){super.updated&&super.updated(e),e.forEach(((e,t)=>{"glitch"===t&&this[t]&&this._doGlitch()}))}render(){return t`<span><slot></slot></span>`}static get properties(){return{...super.properties,glitch:{type:Boolean},red:{type:Boolean,reflect:!0},fadein:{type:Boolean,reflect:!0},glitchMax:{type:Number,attribute:"glitch-max"},glitchDuration:{type:Number,attribute:"glitch-duration"}}}static get tag(){return"future-terminal-text-lite"}}customElements.define(FutureTerminalTextLite.tag,FutureTerminalTextLite);export{FutureTerminalTextLite};
elmsln/elmsln
core/dslmcode/cores/haxcms-1/build/es6/node_modules/@lrnwebcomponents/future-terminal-text/lib/future-terminal-text-lite.js
JavaScript
gpl-3.0
2,021
/* bender-tags: clipboard,pastefromword */ /* jshint ignore:start */ /* bender-ckeditor-plugins: pastefromword,ajax,basicstyles,bidi,font,link,toolbar,colorbutton,image */ /* bender-ckeditor-plugins: list,liststyle,sourcearea,format,justify,table,tableresize,tabletools,indent,indentblock,div,dialog */ /* jshint ignore:end */ /* bender-include: _lib/q.js,_helpers/promisePasteEvent.js,_lib/q.js,_helpers/assertWordFilter.js,_helpers/createTestCase.js,_helpers/pfwTools.js */ /* global createTestCase,pfwTools */ ( function() { 'use strict'; pfwTools.defaultConfig.disallowedContent = 'span[lang,dir]'; bender.editor = { config: pfwTools.defaultConfig }; var browsers = [ 'chrome', 'firefox', 'ie8', 'ie11' ], wordVersion = 'word2013', ticketTests = { '7661Multilevel_lists': [ 'word2013' ], '7696empty_table': [ 'word2013' ], '7797fonts': [ 'word2013' ], '7843Multi_level_Numbered_list': [ 'word2013' ], '7857pasting_RTL_lists_from_word_defect': [ 'word2013' ], '7872lists': [ 'word2013' ], '7918Numbering': [ 'word2013' ], '7950Sample_word_doc': [ 'word2013' ], '8437WORD_ABC': [ 'word2013' ], '8501FromWord': [ 'word2013' ], '8665Tartalom': [ 'word2013' ], '8734list_test2': [ 'word2013' ], '8734list_test': [ 'word2013' ], '8780ckeditor_tablebug_document': [ 'word2013' ], '9144test': [ 'word2013' ], '9274CKEditor_formating_issue': [ 'word2013' ], '9330Sample_Anchor_Document': [ 'word2013' ], '9331ckBugWord1': [ 'word2013' ], '9340test_ckeditor': [ 'word2013' ], '9422for_cke': [ 'word2013' ], '9426CK_Sample_word_document': [ 'word2013' ], '9456Stuff_to_get': [ 'word2013' ], '9456text-with-bullet-list-example': [ 'word2013' ], '9475list2003': [ 'word2013' ], '9475List2010': [ 'word2013' ], '9616word_table': [ 'word2013' ], '9685ckeditor_tablebug_document': [ 'word2013' ], '9685testResumeTest': [ 'word2013' ] }, testData = { _should: { ignore: {} } }, ticketKeys = CKEDITOR.tools.objectKeys( ticketTests ), i, k; for ( i = 0; i < ticketKeys.length; i++ ) { for ( k = 0; k < browsers.length; k++ ) { if ( ticketTests[ ticketKeys[ i ] ] === true || CKEDITOR.tools.indexOf( ticketTests[ ticketKeys[ i ] ], wordVersion ) !== -1 ) { var testName = [ 'test', ticketKeys[ i ], wordVersion, browsers[ k ] ].join( ' ' ); if ( CKEDITOR.env.ie && CKEDITOR.env.version <= 11 ) { testData._should.ignore[ testName ] = true; } testData[ testName ] = createTestCase( ticketKeys[ i ], wordVersion, browsers[ k ], true ); } } } bender.test( testData ); } )();
Mediawiki-wysiwyg/WYSIWYG-CKeditor
WYSIWYG/ckeditor_source/tests/plugins/pastefromword/generated/tickets4.js
JavaScript
gpl-3.0
2,627
Ext.define('Surveyportal.view.reportui.datachart.chart.ChartController', { extend : 'Ext.app.ViewController', alias : 'controller.chartController', reportView : null, reportViewController : null, reportJSON : null, defaultIncHeight:100, init : function() { this.control({ "button": { click:this.filterdaterangedata, }, }); }, initObject : function() { this.reportViewController = this.reportView.controller; this.reportJSON = this.reportView.reportJSON; var clayout=this.getView().down("#chartcolumnlayout"); if(this.reportJSON != undefined && this.reportJSON.defaultCColumn!=undefined && this.reportJSON.defaultCColumn.toString().length>0){ clayout.value=this.reportJSON.defaultCColumn; clayout.minLength=this.reportJSON.defaultCColumn; } }, afterRender:function(){ if(this.numberofcharts <= 1){ if(this.getView().down("#chartcolumnlayout")!= null){ this.getView().down("#chartcolumnlayout").hide(); } } }, loadCharts : function(charts) { this.initObject(); this.getView().removeAll(); this.numberofcharts=charts.length; if(charts.length <= 1){ if(this.getView().down("#chartcolumnlayout")!= null){ this.getView().down("#chartcolumnlayout").hide(); } } var fusionchart; // var charts= this.chartDatas if(charts.length > 0) { for (var x = 0; x < charts.length; x++) { if(charts[x].hasOwnProperty("group") && charts[x].group == true){ this.loadGroupCharts(charts[x].groupCharts,charts[x]); }else{ panel = this.getView().add({ xtype : "panel", title:charts[x].chartTitle, height : charts[x].height * 1 +this.defaultIncHeight, group:false, margin : '5 5 0 0', chartJSON : charts[x], listeners : { afterrender : 'loadfusionchart' } }); } } } else { this.getView().hide(); } this.getView().doLayout(); this.resizeCharts(this.getView().down("#chartcolumnlayout")); }, loadGroupCharts:function(groupcharts,chart){ var charts=[] for (var x = 0; x < groupcharts.length; x++) { charts.push({ xtype : "panel", height : groupcharts[x].height * 1, scope:this, margin : '5 5 0 0', chartwidth:this.getView().getWidth()/groupcharts.length, chartJSON : groupcharts[x], listeners : { afterrender :function(panel){ panel.chartJSON.width=panel.chartwidth; var fusionchart = new FusionCharts(panel.chartJSON); fusionchart.render(panel.body.id); } } }); } this.getView().add({ xtype : "panel", margin : '5 5 0 0', title:chart.chartTitle, bodyStyle : 'background:#D8D8D8', group:true, scope:this, width:"100%", layout:{ type : 'table', columns : charts.length }, items : charts }); this.resizeCharts(this.getView().down("#chartcolumnlayout")); }, loadfusionchart : function(panel) { var clayout=this.getView().down("#chartcolumnlayout"); var newColumns =clayout==null?1:parseInt(clayout.value); var chartwidth=this.getView().getWidth()/newColumns; panel.chartJSON.width=chartwidth; var fusionchart = new FusionCharts(panel.chartJSON); fusionchart.render(panel.body.id); // this.resizeCharts(this.getView().down("#chartcolumnlayout")); }, resizeCharts : function(comp, newValue, oldValue, eOpts) { var Value = comp.value; mainPanel = comp.up().up(); mainPanel.getLayout().columns = parseInt(Value); newColumns = parseInt(Value); totalWidth = (mainPanel.getWidth()) for (var i = 0; i < mainPanel.items.length; i++) { var currentPanel = mainPanel.items.items[i]; if(currentPanel.hasOwnProperty("group") && currentPanel.group == false){ currentPanel.setWidth(((totalWidth - 2) / newColumns)); } } for ( var k in FusionCharts.items) { debugger; fusionObj = FusionCharts.items[k]; if(fusionObj.args.hasOwnProperty("group") && fusionObj.args.group == true){ }else{ var panelbodyId = fusionObj.options.containerElementId; if (this.getView().down( '#' + panelbodyId.substring(0, panelbodyId .indexOf('-body'))) != null) { fusionObj.resizeTo(((totalWidth) / newColumns)); } } } mainPanel.setWidth(totalWidth); }, filterdaterangedata:function(btn){ debugger; if(btn.hasOwnProperty("daterangevalue") ){ var defaultDate=this.reportView.down("#defaultsDate"); if(defaultDate!=null){ defaultDate.setValue(btn.daterangevalue); this.reportView.controller.datachart.controller.filterData(); } } }, onPanelResize:function(me, width, height, oldWidth, oldHeight, eOpts ) { debugger; newColumns=parseInt(me.down("ratingField").value); for (var i = 0; i < me.items.length; i++) { var currentPanel = me.items.items[i]; if(currentPanel.hasOwnProperty("group") && currentPanel.group == false){ currentPanel.setWidth(((width - 2) / newColumns)); } } for ( var k in FusionCharts.items) { debugger; fusionObj = FusionCharts.items[k]; if(fusionObj.args.hasOwnProperty("group") && fusionObj.args.group == true){ }else{ var panelbodyId = fusionObj.options.containerElementId; if (me.down( '#' + panelbodyId.substring(0, panelbodyId .indexOf('-body'))) != null) { fusionObj.resizeTo(((width) / newColumns)); } } } //alert("Panel Resize Called>>>>>>>>>"); } });
applifireAlgo/appDemoApps201115
surveyportal/src/main/webapp/app/view/reportui/datachart/chart/ChartController.js
JavaScript
gpl-3.0
5,406
angular.module('CarpentryApp.Index', ['CarpentryApp.Common']).controller( 'IndexController', function ($rootScope, $scope, $state, $http, $cookies, hotkeys, notify) { var limit = 720; var counter = 0; $rootScope.resetPollers(); $rootScope.indexPoller = setInterval(function(){ counter++; if (counter > 720) { clearInterval($rootScope.indexPoller); } $rootScope.refresh(); }, 1000); $rootScope.refresh(); });
gabrielfalcao/carpentry
carpentry/static/js/app.2.index.js
JavaScript
gpl-3.0
529
// ChaosUPS - a universal points system. // Copyright (C) 2015 Jay Baker var mongoose = require('mongoose'), async = require('async'), util = require('util') module.exports = function(app) { app.factory.bids = {} app.factory.bids.getAll = function(fn) { var Item = mongoose.model('Item', app.models.item) var User = mongoose.model('User', app.models.user) var Bid = mongoose.model('Bid', app.models.bid) Bid.find({ state: 0 }) .populate('item') .populate('user') .exec(function(err, docs) { if (err) { console.log('app.factory.bids.getAll ERROR: ' + err) } fn(docs) }) } app.factory.bids.getAllByUserId = function(userId, fn) { var Item = mongoose.model('Item', app.models.item) var User = mongoose.model('User', app.models.user) var Bid = mongoose.model('Bid', app.models.bid) Bid.find({ user: userId, state: 0 }) .populate('item') .populate('user') .exec(function(err, docs) { if (err) { console.log('app.factory.bids.getAllByUserId ERROR: ' + err) } fn(docs) }) } app.factory.bids.getAllFinishedByUserId = function(userId, fn) { var Item = mongoose.model('Item', app.models.item) var User = mongoose.model('User', app.models.user) var Bid = mongoose.model('Bid', app.models.bid) Bid.find({ user: userId, state: 1 }) .populate('item') .populate('user') .exec(function(err, docs) { if (err) { console.log('app.factory.bids.getAllFinishedByUserId ERROR: ' + err) } fn(docs) }) } app.factory.bids.getByItem = function(itemId, fn) { var Item = mongoose.model('Item', app.models.item) var User = mongoose.model('User', app.models.user) var Bid = mongoose.model('Bid', app.models.bid) Bid.find({ item: itemId, state: 0 }) .populate('item') .populate('user') .populate('item.previousBids') .exec(function(err, docs) { if (err) { console.log('app.factory.bids.getByItem ERROR: ' + err) } fn(docs) }) } app.factory.bids.place = function(item, userId, value, fn) { var Item = mongoose.model('Item', app.models.item) var User = mongoose.model('User', app.models.user) var Bid = mongoose.model('Bid', app.models.bid) var moment = app.locals.moment // get the current user app.factory.users.getById(userId, function(user) { // check if there is currently a bid if (item.currentBid) { // change the old bid state to 1 so its not a current bid var oldBid = item.currentBid oldBid.state = 1 oldBid.save(function(err) { // add the old bid to the item's previous bids item.previousBids.push(oldBid) // check if someone is bidding in the last 12 hours var endDate = oldBid.endDate var secondsRemaining = moment(endDate).format('x') - moment().format('x') if (secondsRemaining < 60 * 60 * 12) { endDate = moment().add('1', 'd') } // create a new bid var newBid = new Bid({ previous: [], item: item, user: user, amount: value, zone: item.zone, state: 0, endDate: endDate }) // save the bid newBid.save(function(err) { if (err) { console.log('app.factory.bids.place new bid ERROR: ' + err) } item.currentBid = newBid item.minimumBid = Math.ceil(Number(value) * 1.1) // save the item item.save(function(err) { if (err) { console.log('app.factory.bids.place save item ERROR: ' + err) } app.factory.items.getById(item.id, function(newItem) { fn(newItem) }) }) }) }) } else { var endDate = app.locals.moment().add(3, 'd') if (item.date <= app.locals.moment().subtract('3', 'd')) { endDate = app.locals.moment().add(1, 'd') } // create a new bid var newBid = new Bid({ item: item, user: user, amount: value, zone: item.zone, state: 0, endDate: endDate }) newBid.save(function(err) { if (err) { console.log('app.factory.bids.place new bid ERROR: ' + err) } item.minimumBid = Math.ceil(Number(value) * 1.1) item.currentBid = newBid item.save(function(err) { if (err) { console.log('app.factory.bids.place item save ERROR: ' + err) } app.factory.items.getById(item.id, function(newItem) { fn(newItem) }) }) }) } }) } }
logikaljay/chaosups
factory/bids.js
JavaScript
gpl-3.0
4,945
const Command = require('../../structures/Command'); const { MessageEmbed } = require('discord.js'); const { stripIndents } = require('common-tags'); module.exports = class PokedexCommand extends Command { constructor(client) { super(client, { name: 'pokedex', aliases: ['pokemon', 'pokémon', 'pokédex'], group: 'search', memberName: 'pokedex', description: 'Searches the Pokédex for a Pokémon.', clientPermissions: ['EMBED_LINKS'], credit: [ { name: 'Pokémon', url: 'https://www.pokemon.com/us/' }, { name: 'PokéAPI', url: 'https://pokeapi.co/' }, { name: 'Serebii.net', url: 'https://www.serebii.net/index2.shtml' } ], args: [ { key: 'pokemon', prompt: 'What Pokémon would you like to get information on?', type: 'string' } ] }); } async run(msg, { pokemon }) { try { const data = await this.client.pokemon.fetch(pokemon); const embed = new MessageEmbed() .setColor(0xED1C24) .setAuthor(`#${data.displayID} - ${data.name}`, data.boxImageURL, data.serebiiURL) .setDescription(stripIndents` **${data.genus}** ${data.entries[Math.floor(Math.random() * data.entries.length)]} `) .setThumbnail(data.spriteImageURL); return msg.embed(embed); } catch (err) { if (err.status === 404) return msg.say('Could not find any results.'); return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); } } };
dragonfire535/xiaobot
commands/search/pokedex.js
JavaScript
gpl-3.0
1,491
import { createCanvas, loadImage } from 'canvas' class Util { static createCanvas (size, image, fillType = 'fill') { var canvas = createCanvas() canvas.width = size canvas.height = size if (image) { switch (fillType) { case 'fill' : canvas.getContext('2d').drawImage(image, 0, 0, size, size) break case 'scale_to_fit': var wrh = image.width / image.height var newWidth = canvas.width var newHeight = newWidth / wrh if (newHeight > canvas.height) { newHeight = canvas.height newWidth = newHeight * wrh } var x = (canvas.width - newWidth) * 0.5 var y = (canvas.height - newHeight) * 0.5 canvas.getContext('2d').drawImage(image, x, y, newWidth, newHeight) break } } return canvas } static threshold (r, g, b, value) { return (0.2126 * r + 0.7152 * g + 0.0722 * b >= value) ? 255 : 0 } } export default Util
kciter/qart.js
src/util.js
JavaScript
gpl-3.0
1,005
import { RESET_PROGRESS_SUCCESS } from '../actions/progressActions' import { GET_INBOX_SUCCESS } from '../actions/inboxActions' import { GET_TASK_SUCCESS, GET_TASKS_SUCCESS, TASK_UPDATE_PROGRESS_SUCCESS, TASK_REVERT_PROGRESS_SUCCESS } from '../actions/taskActions' export default function tasksReducer(state = null, action) { switch (action.type) { case GET_TASKS_SUCCESS: case GET_INBOX_SUCCESS: case GET_TASK_SUCCESS: case TASK_UPDATE_PROGRESS_SUCCESS: case TASK_REVERT_PROGRESS_SUCCESS: case RESET_PROGRESS_SUCCESS: return Object.assign({}, state, action.tasks ) default: return state || null } }
DemocracyGuardians/DGTeam
client/src/reducers/tasksReducer.js
JavaScript
gpl-3.0
658
yagpa.factory('playerService', function() { var player_selected = {}; var players_list = []; var loadlist = function() {}; });
YAGPATeam/YAGPA
YAGPA/static/scripts/services.js
JavaScript
gpl-3.0
131
'use strict'; import gulp from 'gulp'; import del from 'del'; import sass from 'gulp-sass'; import globbing from 'node-sass-globbing'; import browserSync from 'browser-sync'; import eslint from 'gulp-eslint'; import autoprefixer from 'autoprefixer'; import postcss from 'gulp-postcss'; const rootDir = process.cwd(); const paths = { theme: `${rootDir}/themes/uhsg_theme`, modules: `${rootDir}/modules` }; const browserSyncProxyTarget = 'https://local.studies-qa.it.helsinki.fi'; const styleguidePath = `${rootDir}/node_modules/uh-living-styleguide`; const sass_config = { importer: globbing, outputStyle: 'expanded', includePaths: [ `${rootDir}/node_modules/normalize.css/`, `${rootDir}/node_modules/breakpoint-sass/stylesheets/` ] }; // Compile sass. gulp.task('sass', (done) => { process.chdir(paths.theme); gulp.src('sass/**/*.scss') .pipe(sass(sass_config).on('error', sass.logError)) .pipe(postcss([ autoprefixer() ])) .pipe(gulp.dest('css')); browserSync.reload(); done(); }); gulp.task('watch', gulp.series('sass', () => { process.chdir(paths.theme); gulp.watch('sass/**/*.scss', gulp.series('sass')); })); // Clean styleguide assets gulp.task('styleguide-clean', () => { process.chdir(paths.theme); return del([ 'fonts/**/*', 'sass/styleguide' ]); }); // Updates styleguide with bower and moves relevant assets to correct path gulp.task('styleguide-update', gulp.series('styleguide-clean', (done) => { process.chdir(paths.theme); gulp.src(`${styleguidePath}/fonts/**/*`) .pipe(gulp.dest('./fonts')); gulp.src([`${styleguidePath}/sass/**/*`, `!${styleguidePath}/sass/styles.scss`], { base: `${styleguidePath}/sass` }) .pipe(gulp.dest('./sass/styleguide')); done(); })); // Live reload css changes gulp.task('browsersync', gulp.series('watch', (done) => { process.chdir(paths.theme); browserSync.init({ proxy: browserSyncProxyTarget, reloadDelay: 1000 }); done(); })); // Linting gulp.task('lint', () => { return gulp.src([`${paths.theme}/**/*.js`, `${paths.modules}/**/*.js`, '!**/node_modules/**']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); });
UH-StudentServices/student_guide
gulpfile.babel.js
JavaScript
gpl-3.0
2,210
import React from 'react'; import Button from '../base/Button'; import T from '../base/T'; import withPermisisons, {ORDER_CONTEXT} from '../hoc/Permissions'; const OrderAllButton = props => ( <Button size="medium" type="quaternary" className="orderAllBtn" data-cy="orderAllButton" {...props} > <T component="shortlist" name="shortlistOrder" /> </Button> ); export default withPermisisons(OrderAllButton, ORDER_CONTEXT);
DBCDK/content-first
src/client/components/order/OrderAllButton.component.js
JavaScript
gpl-3.0
452
import React from 'react' import { Provider } from 'react-redux' import routes from '../routes' import { Router } from 'react-router' const Root = ({ store, history }) => ( <Provider store={store}> <Router history={history} routes={routes} /> </Provider> ) export default Root
reimertz/anolog
src/containers/Root.prod.js
JavaScript
gpl-3.0
288
/** * @author Attila Barna */ var DefaultModalComponent = easejs.Class('DefaultModalComponent').extend(ModalComponent,{ /** * The value of the current element */ 'private value' : null, /** * Required property * Input cannot be created without name */ 'private inputName' : null, /** * Optional property * The component does not check if the ID exists on the page, it must be handle by the developer. */ 'private inputID' : null, 'override virtual __construct' : function () { this.__super(); }, 'public static create' : function() { return new DefaultModalComponent(); }, 'public virtual setLabel' : function(text) { this.label = jQuery("<div></div>",{class : 'label-dialog-column-1', html: text}) return this; }, 'public override virtual getLabel' : function() { return this.label; }, 'public override virtual getElement' : function() { return this.element; }, 'public virtual setInput' : function(_type,_name,_id,options) { if ( _id == undefined ) { _id = ""; } else { this.inputID = _id; } if ( options == undefined ) options = {}; this.inputName = _name; this.element = jQuery("<div></div>",{class : 'label-dialog-column-2'}) .append( jQuery("<input></input>", jQuery.extend({type:_type,name:_name,id:_id},options)) .val(this.value) ); return this; }, 'public virtual getValue' : function() { var ob = this.element.find('input'); if ( ob.length == 1 ) { return ob.val(); } ob = this.element.find('textarea'); if ( ob.length == 1 ) { return ob.val(); } return null; }, 'public virtual getInputName' : function() { return this.inputName; }, 'public virtual getInputID' : function() { return this.inputID; }, 'public virtual setValue' : function(val) { this.element.find('input').val(val); this.element.find('textarea').val(val); return this; }, 'public virtual setTextarea' : function(_name,_id,options) { if ( _id == undefined ) { _id = ""; } else { this.inputID = _id; } if ( options == undefined ) options = {}; this.inputName = _name; this.element = jQuery("<div></div>",{class : 'label-dialog-column-2'}) .append( jQuery("<textarea></textarea>", jQuery.extend({name:_name,id:_id},options)) .val(this.value) ); return this; }, }); //# sourceURL=/resources/js/core/modal/DefaultModalComponent.js
emraxxor/infovip
infovip-web/src/main/webapp/WEB-INF/resources/js/core/dialog/modal/DefaultModalComponent.js
JavaScript
gpl-3.0
2,423
var app = angular.module("ngApp", ["ngGrid"]); app.controller("ngCtrl", function($scope) { $scope.ngData = data; $scope.gridOptions = { data: "ngData", plugins: [new ngGridCsvExportPlugin()], showFooter: true, showGroupPanel: true, enableColumnReordering: true, enableColumnResize: true, showColumnMenu: true, showFilter: true }; });
FH-Complete/FHC-AddOn-Reports
include/js/nggrid.js
JavaScript
gpl-3.0
368
$(document).ready(init); function init() { /* Declaring Events */ attachEvents(); } function attachEvents() { $('.addSlo').on('click', addIdo); $('.addIndicator').on('click', addIndicator); $('.addTargets').on('click', addTargets); $('.addCrossCuttingIssue').on('click', addCrossCuttingIssue); $('.remove-element').on('click', removeElement); $('.blockTitle.closed').on('click', function() { if($(this).hasClass('closed')) { $('.blockContent').slideUp(); $('.blockTitle').removeClass('opened').addClass('closed'); $(this).removeClass('closed').addClass('opened'); } else { $(this).removeClass('opened').addClass('closed'); } $(this).next().slideToggle('slow', function() { $(this).find('textarea').autoGrow(); }); }); } function addIdo() { console.log("add ido"); var $itemsList = $(this).parent().find('.slos-list'); var $item = $("#srfSlo-template").clone(true).removeAttr("id"); $item.find('.blockTitle').trigger('click'); $itemsList.append($item); $item.slideDown('slow'); updateIndexes(); $item.trigger('addComponent'); } function addIndicator() { console.log("addIndicator"); var $itemsList = $(this).parent().parent().find('.srfIndicators-list'); var $item = $("#srfSloIndicator-template").clone(true).removeAttr("id"); $itemsList.append($item); $item.slideDown('slow'); updateIndexes(); $item.trigger('addComponent'); } function addTargets() { console.log("addTargets"); var $itemsList = $(this).parent().parent().find('.targetsList'); var $item = $("#targetIndicator-template").clone(true).removeAttr("id"); $itemsList.append($item); $item.show('slow'); updateIndexes(); $item.trigger('addComponent'); } function addCrossCuttingIssue() { console.log("addCrossCuttingIssue"); var $itemsList = $(this).parent().find('.issues-list'); var $item = $("#srfCCIssue-template").clone(true).removeAttr("id"); $itemsList.append($item); $item.slideDown('slow'); updateIndexes(); $item.trigger('addComponent'); } function removeElement() { $item = $(this).parent(); $item.hide('slow', function() { $item.remove(); updateIndexes(); $(document).trigger('removeComponent'); }); } function updateIndexes() { $('.slos-list .srfSlo').each(function(i,slo) { // Updating indexes $(slo).setNameIndexes(1, i); $(slo).find('.srfSloIndicator').each(function(subIdoIndex,subIdo) { // Updating indexes $(subIdo).setNameIndexes(2, subIdoIndex); }); }); $('.issues-list .srfCCIssue').each(function(i,crossCutting) { // Updating indexes $(crossCutting).setNameIndexes(1, i); }); }
CCAFS/MARLO
marlo-web/src/main/webapp/global/js/superadmin/marloSLOs.js
JavaScript
gpl-3.0
2,668
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'undo', 'az', { redo: 'Təkrar et', undo: 'İmtina et' } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/undo/lang/az.js
JavaScript
gpl-3.0
251
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'embedbase', 'es', { pathName: 'objeto media', title: 'Media incrustado', button: 'Insertar Media incrustado', unsupportedUrlGiven: 'La URL especificada no está soportada.', unsupportedUrl: 'La URL {url} no está soportada por Medio Inscrustado.', fetchingFailedGiven: 'Fallo al recuperar el contenido de la URL dada.', fetchingFailed: 'Fallo al recuperar contenido de {url}.', fetchingOne: 'Recuperando respuesta oEmbed...', fetchingMany: 'Recuperando respuestas oEmbed, {current} de {max} hecho...' } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/embedbase/lang/es.js
JavaScript
gpl-3.0
705
"use strict" const spawn = require('child_process').spawn; const INTERVAL_UPDATE = 24*60*60*1000; const INTERVAL_SYSTEM_UPDATE = 7*24*60*60*1000; let program_configs = [ { 'name': 'Core', 'child': null, 'executable': 'node', 'parameters': ['../Core/index.js'], 'root_dir': '../Core', 'version': null }, { 'name': 'Toggles', 'child': null, 'executable': 'node', 'parameters': ['../Toggles/index.js'], 'root_dir': '../Toggles', 'version': null }, { 'name': 'Front', 'child': null, 'executable': 'node', 'parameters': ['../Front/index.js'], 'root_dir': '../Front', 'version': null } ]; let numberOfRunningChildren = 0; program_configs.forEach(function (program_config) { startProcess(program_config); program_config.version = getVersion(program_config); }); setInterval(checkForAllUpdates, INTERVAL_UPDATE); setInterval(updateOS, INTERVAL_SYSTEM_UPDATE); function checkForAllUpdates() { program_configs.forEach(function (program_config) { checkForUpdate(program_config); }); } function checkForUpdate(program_config) { let oldVersion = program_config.version; spawn('git', 'pull', {'cwd': __dirname+'/'+program_config.root_dir}); spawn.on('close', function () { let newVersion = getVersion(program_config); if (newVersion === null) return; if (oldVersion === newVersion) return; program_config.version = newVersion; killProcess(program_config); }); } function getVersion(program_config) { try { return require(program_config.root_dir+'/package.json').version; } catch (e) { log("Failed to get local_config for "+program_config.name+". Error: "+e); return null; } } function startProcess(program_config) { if (program_config.child) { log(program_config.name+" is already running."); return; } log("Starting process "+program_config.name); numberOfRunningChildren++; program_config.child = spawn(program_config.executable, program_config.parameters); program_config.child.stdout.setEncoding('utf8'); program_config.child.on('close', function (code, signal) { log(program_config.name + " exited with code "+code+", from signal "+ signal); program_config.child = null; numberOfRunningChildren--; if (code === 0 || code === '0' || code === null) return; // Don't restart if the program opted to close setTimeout(function() { startProcess(program_config); }, 2000); }); program_config.child.stdout.on('data', function (data) { log(data); }); program_config.child.stderr.on('data', function (data) { log(data); }); } function killProcess(program_config) { if (!program_config.child) return; program_config.child.kill('SIGINT'); program_config.child = null; } function updateOS() { let update = spawn('apt-get', ['update']); update.on('close', function (code) { if (code == 0) { let upgrade = spawn('apt-get', ['upgrade', '-y']); } }); } function log(message) { console.log(Date.now(), "Process Manager:", message); } process.on('SIGINT', shutdownProgram); process.on('uncaughtException', shutdownProgram); function shutdownProgram() { program_configs.forEach(function (program_config) { killProcess(program_config); }); setInterval(function() { if (numberOfRunningChildren < 1) { process.exit(); } log("There are "+numberOfRunningChildren+" still running"); }, 1000); }
smwa/opensource-spa
Controller/src/Updater/index.js
JavaScript
gpl-3.0
3,447
var searchData= [ ['end_5ftest',['END_TEST',['../group___calls_malloc.html#gaefcd1ca1799d2395f7bbe3c50bcc8ff8',1,'unit_test.h']]], ['endgame',['endGame',['../game__state_8h.html#aeda119595fcc834db9cfec532a90cf79',1,'game_state.c']]], ['endtrial',['endTrial',['../profile_8h.html#a8aae37a7e7fa5f85958ca30807cae136',1,'profile.c']]], ['err_5f1',['ERR_1',['../error_8h.html#abe0e0e5d41bcdf7365b58faf284d55b1',1,'error.h']]], ['err_5f10',['ERR_10',['../error_8h.html#a805aa89fa27b9a21ddafc999bba0bb68',1,'error.h']]], ['err_5f11',['ERR_11',['../error_8h.html#a7b8665db5362fa1e49816b7e5a839863',1,'error.h']]], ['err_5f12',['ERR_12',['../error_8h.html#ab6d13d5316dd231c323cf18998c7195e',1,'error.h']]], ['err_5f13',['ERR_13',['../error_8h.html#a57027f9c748ff6708774addce1746539',1,'error.h']]], ['err_5f14',['ERR_14',['../error_8h.html#a80b4f190b67f53f3c2dea7b01d966b6f',1,'error.h']]], ['err_5f15',['ERR_15',['../error_8h.html#aae5dc676babeb0e2b4702f59835382f4',1,'error.h']]], ['err_5f16',['ERR_16',['../error_8h.html#a1842caea0771e65e3219bb0278a181a4',1,'error.h']]], ['err_5f17',['ERR_17',['../error_8h.html#a28dcf048ee64c2f1a38f80f71d28fc2a',1,'error.h']]], ['err_5f18',['ERR_18',['../error_8h.html#ac9d7613d1c0680c3a6aa46c219fcb283',1,'error.h']]], ['err_5f19',['ERR_19',['../error_8h.html#acc63f7ea363c63c45e8efa026c6024b9',1,'error.h']]], ['err_5f2',['ERR_2',['../error_8h.html#a012097e952ead190cc831d35441d1828',1,'error.h']]], ['err_5f20',['ERR_20',['../error_8h.html#a62c46bd16d82b73650b04cf33d88b85e',1,'error.h']]], ['err_5f21',['ERR_21',['../error_8h.html#a7f36ca4ee7ec8e6b036463cdfb4f8e37',1,'error.h']]], ['err_5f22',['ERR_22',['../error_8h.html#a765e766c66b052360a0f0ef2b108d418',1,'error.h']]], ['err_5f23',['ERR_23',['../error_8h.html#afe7dc0131b0e477c85ce6f1ae81e583e',1,'error.h']]], ['err_5f24',['ERR_24',['../error_8h.html#a89111005bd52f88a676e395c2dc5b595',1,'error.h']]], ['err_5f25',['ERR_25',['../error_8h.html#acb0053735b7712b0f7fe1b568879826e',1,'error.h']]], ['err_5f26',['ERR_26',['../error_8h.html#a402e8f8ce9e0d5f50415d6e7f9234f89',1,'error.h']]], ['err_5f27',['ERR_27',['../error_8h.html#a779a2cfcbc19b315d894998e3806f38a',1,'error.h']]], ['err_5f28',['ERR_28',['../error_8h.html#aa4698896e1be73384ab032d4f6e5dd56',1,'error.h']]], ['err_5f29',['ERR_29',['../error_8h.html#a0ae86bfa2a5b1023325ab803195e26f1',1,'error.h']]], ['err_5f3',['ERR_3',['../error_8h.html#ab90bfbd2a8eb7519c0d0dc5098b9a281',1,'error.h']]], ['err_5f30',['ERR_30',['../error_8h.html#a9ad2467e024cf16be24d8571cea85092',1,'error.h']]], ['err_5f31',['ERR_31',['../error_8h.html#aee8ef3aac4cae8198c2a81433b536966',1,'error.h']]], ['err_5f32',['ERR_32',['../error_8h.html#aad40aa9441ad40db7654ad648667113b',1,'error.h']]], ['err_5f4',['ERR_4',['../error_8h.html#a76e4c62cff81f41c203a1055c05f224d',1,'error.h']]], ['err_5f5',['ERR_5',['../error_8h.html#a8d7a9415f9f39dcab0fd998d1b6abd32',1,'error.h']]], ['err_5f6',['ERR_6',['../error_8h.html#a787a962fcf3e7d2fe874c605cf0b97d7',1,'error.h']]], ['err_5f7',['ERR_7',['../error_8h.html#a8bba8a97454ca8c09e04e8a9c88ba6e6',1,'error.h']]], ['err_5f8',['ERR_8',['../error_8h.html#a45f5fb50712d5336e0b90ecb11b51383',1,'error.h']]], ['err_5f9',['ERR_9',['../error_8h.html#a1c2d6b2d90865a8010ddb14268662072',1,'error.h']]], ['error',['error',['../group___calls_malloc.html#ga600ac89163a3ee4d9e17288546b1ceed',1,'error(const char *errMessage):&#160;print.c'],['../group___calls_malloc.html#ga600ac89163a3ee4d9e17288546b1ceed',1,'error(const char *errMessage):&#160;print.c']]], ['error_2eh',['error.h',['../error_8h.html',1,'']]], ['error_5fmsg',['ERROR_MSG',['../group___calls_malloc.html#ga53cf0ce013d4c7336b4ff71a360cf89a',1,'error.h']]], ['error_5fstate',['ERROR_STATE',['../error_8h.html#a60db3d3e5c5fb314c0d698922d0b7124',1,'error.h']]], ['error_5fthrown',['ERROR_THROWN',['../error_8h.html#a0099faec25b2b4649490d7f562ade34e',1,'error.h']]], ['exp',['exp',['../math_8h.html#a9b5b75b78eff58c7f376e3ce51e9fdfd',1,'math.h']]], ['exp_5ffptr',['EXP_FPTR',['../native__functions__102_8h.html#aee9ec78d07d65bcaddf62698b64ea774',1,'native_functions_102.h']]] ];
sherman5/MeleeModdingLibrary
docs/search/all_5.js
JavaScript
gpl-3.0
4,177
import { registerReducer } from 'foremanReact/common/MountingService'; import { addGlobalFill } from 'foremanReact/components/common/Fill/GlobalFill'; import { registerRoutes } from 'foremanReact/routes/RoutingService'; import Routes from './src/Router/routes' import reducers from './src/reducers'; // register reducers Object.entries(reducers).forEach(([key, reducer]) => registerReducer(key, reducer) ); // register client routes registerRoutes('PluginTemplate', Routes); // register fills for extending foreman core // http://foreman.surge.sh/?path=/docs/introduction-slot-and-fill--page addGlobalFill('<slotId>', '<fillId>', <div key='plugin-template-example' />, 300);
theforeman/foreman_plugin_template
webpack/global_index.js
JavaScript
gpl-3.0
682
import {NavElement} from 'helpers/nav-element'; export class Navigation { constructor() { this.home = new NavElement("Home"); this.about = new NavElement("About"); this.form = new NavElement("Upload"); this._active = this.home; } changeActive(navElement) { this._active.deactivate(); navElement.activate(); this._active = navElement; return true; } }
pbujok/workoutcombiner
src/FrontEnd/src/navigation.js
JavaScript
gpl-3.0
435
/** * Copyright (C) 2017 Order of the Bee * * This file is part of Community Support Tools * * Community Support Tools 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. * * Community Support Tools 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 Community Support Tools. If not, see <http://www.gnu.org/licenses/>. */ /* * Linked to Alfresco * Copyright (C) 2005-2017 Alfresco Software Limited. */ function getSitesCount() { var list = monitorJobSearchService.getJobsHistory("1", "SITES_COUNT","FINISHED"); if (list) { var node = search.findNode(list.get(0).nodeRef); model.node = jsonUtils.toObject(node.content); } else { model.node = {'sitesCount': "UNKNOWN"}; } }
Vitezslav-Sliz/tieto-alfresco-repository_monitor
health-monitor-repo/src/main/resources/alfresco/extension/templates/webscripts/com/tieto/healthy-addon/admin/healthy-repo-addon/sites.lib.js
JavaScript
gpl-3.0
1,177
// // Vivado(TM) // rundef.js: a Vivado-generated Runs Script for WSH 5.1/5.6 // Copyright 1986-2017 Xilinx, Inc. All Rights Reserved. // var WshShell = new ActiveXObject( "WScript.Shell" ); var ProcEnv = WshShell.Environment( "Process" ); var PathVal = ProcEnv("PATH"); if ( PathVal.length == 0 ) { PathVal = "C:/Xilinx/Vivado/2017.2/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2017.2/ids_lite/ISE/lib/nt64;C:/Xilinx/Vivado/2017.2/bin;"; } else { PathVal = "C:/Xilinx/Vivado/2017.2/ids_lite/ISE/bin/nt64;C:/Xilinx/Vivado/2017.2/ids_lite/ISE/lib/nt64;C:/Xilinx/Vivado/2017.2/bin;" + PathVal; } ProcEnv("PATH") = PathVal; var RDScrFP = WScript.ScriptFullName; var RDScrN = WScript.ScriptName; var RDScrDir = RDScrFP.substr( 0, RDScrFP.length - RDScrN.length - 1 ); var ISEJScriptLib = RDScrDir + "/ISEWrap.js"; eval( EAInclude(ISEJScriptLib) ); ISEStep( "vivado", "-log board_top.vds -m64 -product Vivado -mode batch -messageDb vivado.pb -notrace -source board_top.tcl" ); function EAInclude( EAInclFilename ) { var EAFso = new ActiveXObject( "Scripting.FileSystemObject" ); var EAInclFile = EAFso.OpenTextFile( EAInclFilename ); var EAIFContents = EAInclFile.ReadAll(); EAInclFile.Close(); return EAIFContents; }
rongcuid/lots-of-subleq-cpus
Subleq V2/SubLEQV2Viv/SubLEQV2Viv.runs/synth_1/rundef.js
JavaScript
gpl-3.0
1,239
// Renders area for students in the classroom and their status App.StudentsInClassroomView = Backbone.View.extend({ el: "#studentsInClassList", initialize: function() { this.render(); }, // Todo: Will need add functionality to set status state defcon1 - 3 render: function() { this.$el.empty(); console.log("rendering all students status"); this.collection.each(function(model) { App.studentInClassroomView = new App.StudentInClassroomView({ model: model }); }); } }); // Renders each square for students in the classroom and their status App.StudentInClassroomView = Backbone.View.extend({ el: "#studentsInClassList", tagName: 'li', initialize: function() { this.render(); }, // Todo: Will need add functionality to set status state defcon1 - 3 render: function() { console.log("rendering one student's status"); var source = $("#studentInClassroom").html(); var template = Handlebars.compile(source); var html = template(this.model.toJSON()); this.$el.append(html); } }); // Teacher // Renders area for students in the classroom and their status App.StudentsInClassroomViewT = Backbone.View.extend({ el: "#studentsInClassList", initialize: function() { this.render(); }, // Todo: Will need add functionality to set status state defcon1 - 3 render: function() { this.$el.empty(); console.log("rendering all students status"); this.collection.each(function(model) { App.studentInClassroomViewT = new App.StudentInClassroomViewT({ model: model }); }); } }); // Renders each square for students in the classroom and their status App.StudentInClassroomViewT = Backbone.View.extend({ el: "#studentsInClassList", tagName: 'li', initialize: function() { this.render(); }, // Todo: Will need add functionality to set status state defcon1 - 3 render: function() { console.log("rendering one student's status"); var source = $("#studentInClassroom-t").html(); var template = Handlebars.compile(source); var html = template(this.model.toJSON()); this.$el.append(html); } });
RKJuve/class-barometer
js/view/studentInClassroomView.js
JavaScript
gpl-3.0
2,166
/* * Copyright 2017 Anton Tananaev ([email protected]) * Copyright 2017 Andrey Kunitsyn ([email protected]) * * 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/>. */ Ext.define('Traccar.view.dialog.SendCommand', { extend: 'Traccar.view.dialog.Base', requires: [ 'Traccar.view.dialog.SendCommandController' ], controller: 'sendCommand', title: Strings.commandTitle, items: [{ xtype: 'combobox', reference: 'commandsComboBox', fieldLabel: Strings.deviceCommand, displayField: 'description', valueField: 'id', store: 'DeviceCommands', queryMode: 'local', editable: false, allowBlank: false, listeners: { select: 'onCommandSelect' } }, { xtype: 'form', listeners: { validitychange: 'onValidityChange' }, items: [{ xtype: 'fieldset', reference: 'newCommandFields', disabled: true, items: [{ xtype: 'checkboxfield', name: 'textChannel', reference: 'textChannelCheckBox', inputValue: true, uncheckedValue: false, fieldLabel: Strings.commandSendSms, listeners: { change: 'onTextChannelChange' } }, { xtype: 'combobox', name: 'type', reference: 'commandType', fieldLabel: Strings.sharedType, store: 'CommandTypes', displayField: 'name', valueField: 'type', editable: false, allowBlank: false, listeners: { change: 'onTypeChange' } }, { xtype: 'fieldcontainer', reference: 'parameters' }] }] }], buttons: [{ xtype: 'tbfill' }, { glyph: 'xf093@FontAwesome', tooltip: Strings.sharedSend, tooltipType: 'title', minWidth: 0, disabled: true, reference: 'sendButton', handler: 'onSendClick' }, { glyph: 'xf00d@FontAwesome', tooltip: Strings.sharedCancel, tooltipType: 'title', minWidth: 0, handler: 'closeView' }] });
tananaev/traccar-web
web/app/view/dialog/SendCommand.js
JavaScript
gpl-3.0
2,976
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), SchoolClass = mongoose.model('SchoolClass'), Student = mongoose.model('Student'), ClassRegistry = mongoose.model('ClassRegistry'), ObjectId = mongoose.Types.ObjectId, async = require('async'), _ = require('lodash'); /** * Find school class by id */ exports.schoolClass = function(req, res, next) { SchoolClass.findOne({ _id: new ObjectId(req.params.schoolClassId), academicYear: new ObjectId(req.params.academicYearId), complex: new ObjectId(req.params.complexId), school: new ObjectId(req.params.schoolId) }, function(err, schoolClass) { if (err) return next(err); if (!schoolClass) return next(new Error('Failed to load school class ' + req.params.schoolClassId)); req.schoolClass = schoolClass; next(); }); }; /** * Create an school class */ exports.create = function(req, res) { var schoolClass = new SchoolClass(req.body); schoolClass.save(function(err) { if (err) { res.jsonp(400, err); } else { res.jsonp(schoolClass); } }); }; /** * Update an school class */ exports.update = function(req, res) { var schoolClass = req.schoolClass; schoolClass = _.extend(schoolClass, req.body); schoolClass.save(function(err) { if (err) { res.jsonp(400, err); } else { res.jsonp(schoolClass); } }); }; /** * Delete an school class */ exports.destroy = function(req, res) { var schoolClass = req.schoolClass; schoolClass.remove(function(err) { if (err) { res.jsonp(400, err); } else { res.jsonp(schoolClass); } }); }; /** * Show an school class */ exports.show = function(req, res) { res.jsonp(req.schoolClass); }; /** * List of school classes */ exports.all = function(req, res) { SchoolClass.find({ academicYear: new ObjectId(req.params.academicYearId), complex: new ObjectId(req.params.complexId), school: new ObjectId(req.params.schoolId) }, function(err, schoolClass) { if (err) { res.jsonp(400, err); } else { res.jsonp(schoolClass); } }); }; exports.allStudents = function (req, res) { async.waterfall([ function (callback) { SchoolClass.findById(req.params.schoolClassId, callback); }, function (schoolClass, callback) { Student.find({'_id': { $in: schoolClass.students} }).populate('user', 'email').exec(callback); } ], function (err, result) { if (err) { res.jsonp(400, err); } else { res.jsonp(result); } }); }; exports.studentStats = function (req, res){ var student = new ObjectId(req.params.studentId); ClassRegistry.aggregate() .match({ school: new ObjectId(req.params.schoolId), complex: new ObjectId(req.params.complexId), academicYear: new ObjectId(req.params.academicYearId), schoolClass: new ObjectId(req.params.schoolClassId), absences: student }) .group({ _id: null, absences: {$addToSet: '$date'} }) .exec(function (err, result){ if(err) { res.jsonp(400, err); } else { res.jsonp(result[0]); } }); };
apuliasoft/aurea
app/controllers/schoolClasses.js
JavaScript
gpl-3.0
3,519
var gAutoRender = true var gMirrorEntities = false var gNamedStyle = null var gLanguage = 'mscgen' var gDebug = false var gLinkToInterpreter = false var gVerticalLabelAlignment = 'middle' var gIncludeSource = true module.exports = { getAutoRender: function () { return gAutoRender }, setAutoRender: function (pBool) { gAutoRender = pBool }, getMirrorEntities: function () { return gMirrorEntities }, setMirrorEntities: function (pBool) { gMirrorEntities = pBool }, getIncludeSource: function () { return gIncludeSource }, setIncludeSource: function (pBool) { gIncludeSource = pBool }, getVerticalLabelAlignment: function () { return gVerticalLabelAlignment }, setVerticalLabelAlignment: function (pVerticalLabelAlignment) { gVerticalLabelAlignment = pVerticalLabelAlignment }, getNamedStyle: function () { return gNamedStyle }, setNamedStyle: function (pStyle) { gNamedStyle = pStyle }, getLanguage: function () { return gLanguage }, setLanguage: function (pLanguage) { gLanguage = pLanguage }, getDebug: function () { return gDebug }, setDebug: function (pDebug) { gDebug = pDebug }, getLinkToInterpreter: function () { return gLinkToInterpreter }, setLinkToInterpreter: function (pBool) { gLinkToInterpreter = pBool } } /* This file is part of mscgen_js. mscgen_js 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. mscgen_js 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 mscgen_js. If not, see <http://www.gnu.org/licenses/>. */
sverweij/mscgen_js
src/script/interpreter/state.js
JavaScript
gpl-3.0
1,921
var winston = require("winston"); var chalk = require("chalk"); var fs = require('fs'); var moment = require('moment'); try { fs.mkdirSync('logs') } catch (err) { if (err.code !== 'EEXIST') throw err } const TERM_COLORS = { error: "red", warn: "yellow", info: "blue", verbose: "white", silly: "grey", }; function winstonColorFormatter(options) { options.level = chalk[TERM_COLORS[options.level]](options.level); return winstonFormatter(options); } function winstonFormatter(options) { return options.timestamp() + ' ' + options.level + ' ' + (options.message ? options.message : '') + (options.meta && Object.keys(options.meta).length ? '\n\t' + JSON.stringify(options.meta) : '' ); } function getTimestamp() { return moment().format('MMM-D-YYYY HH:mm:ss.SSS Z'); } var log = null; function doLog(level, module, messageOrObject) { if (typeof(messageOrObject) === 'object' && !(messageOrObject instanceof Error)) messageOrObject = JSON.stringify(messageOrObject); var message = "[" + module + "] " + messageOrObject; if (!log) { console.log("[preinit] " + getTimestamp() + " - " + level + " - " + message); } else log.log(level, message); } class LogService { static info(module, message) { doLog('info', module, message); } static warn(module, message) { doLog('warn', module, message); } static error(module, message) { doLog('error', module, message); } static verbose(module, message) { doLog('verbose', module, message); } static silly(module, message) { doLog('silly', module, message); } static init(config) { var transports = []; transports.push(new (winston.transports.File)({ json: false, name: "file", filename: config.logging.file, timestamp: getTimestamp, formatter: winstonFormatter, level: config.logging.fileLevel, maxsize: config.logging.rotate.size, maxFiles: config.logging.rotate.count, zippedArchive: false })); if (config.logging.console) { transports.push(new (winston.transports.Console)({ json: false, name: "console", timestamp: getTimestamp, formatter: winstonColorFormatter, level: config.logging.consoleLevel })); } log = new winston.Logger({ transports: transports, levels: { error: 0, warn: 1, info: 2, verbose: 3, silly: 4 } }); } } module.exports = LogService;
turt2live/matrix-appservice-instagram
src/util/LogService.js
JavaScript
gpl-3.0
2,765
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'save', 'nb', { toolbar: 'Lagre' } );
ernestbuffington/PHP-Nuke-Titanium
includes/wysiwyg/ckeditor/plugins/save/lang/nb.js
JavaScript
gpl-3.0
228
import Form from 'cerebral-module-forms/Form'; import {TOX_MAX_FRIEND_REQUEST_LENGTH} from './../../../../shared/tox'; export default function sendMessage () { return Form({ message: { value: '', isRequired: true, validations: [{ maxBytes: TOX_MAX_FRIEND_REQUEST_LENGTH }], errorMessages: ['invalidMessage'] } }); }
toxzilla/app
src/app/modules/Chat/forms/sendMessage.js
JavaScript
gpl-3.0
368
/* * Palantír Pocket * http://mynameisrienk.com/?palantir * https://github.com/MyNameIsRienk/PalantírPocket **/ /* * IMPORTANT! * Temporarily added ?[Date.now] params to all urls to easily bypass * caching. This needs to be remove prior to commit for production! * * PROBLEM! * The window does not deal well with zoomed out (i.e. non-responsive) * web pages on iOS. Possible solutions are (1) setting body overflow * to hidden and dimensions equel to device window size, (2) a more * responsive version using FlameViewportScale.js^, (3) resetting * the viewport meta attributes. * ^http://menacingcloud.com/source/js/FlameViewportScale.js **/ var PP_JSON = PP_JSON || '//mynameisrienk.github.io/palantirpocket/data.json?' + Date.now(); var PP_CSS = PP_CSS || '//mynameisrienk.github.io/palantirpocket/stylesheet.css?' + Date.now(); var PP_ICON = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAArklEQVR4XqWQQQqDQAxFf1zY21k3XsAeoHgYu7NasV5QqM5mUlACw5RMWvrh7T6Pn2TMjH/IEGSaJtYgIoRIQsFurKrqg2VZMI4jI04s8P7obJsTICmKM4bhIRJ9QSplWaLvB04s8ADiW4975/m5s64vdN2df1pQ15cQ6SkLojjnQqSnC4hgYAiOUAJbYCA9/YkW9hOJdOwFIOT5SQWg1AJG295MvFcETXOlbxHBG8Vy2fHIq9l6AAAAAElFTkSuQmCC"; /* Insert DOM Elements ============================================================================ */ function palantirCallback(data) { // Stringify & parse as a precaution; reverse data to keep with JSON file window.list = JSON.parse(JSON.stringify(data)) || data; var palantir = document.createDocumentFragment(); var div = document.createElement('div'); div.id = 'PALANTIR'; var box = document.createElement('div'); box.id = 'palantir-search-box'; var field = document.createElement('div'); field.id = 'palantir-search-field'; var search = document.createElement('input'); search.id = 'palantir-search'; search.type = 'search'; search.placeholder = 'Search' var ul = document.createElement('ul'); ul.id = 'palantir-results'; // Loop through the JSONP provided object for (var i = 0; i < list.length; i++) { var li = document.createElement('li'); // Add favicons (if available) if(list[i].icon != null) { var icon = list[i].icon; } else { var domain = list[i].url.match(/(https?:\/\/)([\da-z\.-]+)\.([a-z\.]{2,6})\/?/); var icon = (domain) ? 'http://' + domain[2].replace('www.','').substr(0,1) + '.getfavicon.appspot.com/' + domain[0] + '?defaulticon=lightpng': PP_ICON; } var a = document.createElement('a'); a.href = list[i].url; var desc = (list[i].description != null) ? list[i].description : list[i].url; var txt = "<span>" + list[i].title + "</span>" + desc; a.innerHTML = txt; li.appendChild(a); li.style.backgroundImage = "url(" + icon + ")"; ul.appendChild(li); }; // Append window to screen field.appendChild(search); box.appendChild(field); div.appendChild(box); div.appendChild(ul); palantir.appendChild(div); document.getElementsByTagName('body')[0].appendChild(palantir); // Add an open/close button var btn = document.createElement('a'); btn.href = 'javascript:void(0);' btn.id = 'palantir-close'; btn.addEventListener('click', function(e) { var el = document.getElementById('PALANTIR'); el.className = (el.className != 'open' ? 'open' : ''); }); document.getElementsByTagName('body')[0].appendChild(btn); // Calling clientHeight forces layout on element, req. for animation var reset = div.clientHeight; div.className = 'open'; // Add search function document.getElementById('palantir-search').addEventListener('keyup', palantirSearch ); document.getElementById('palantir-search').addEventListener('click', palantirSearch ); document.getElementById('palantir-search').addEventListener('blur', palantirSearch ); } function palantirSearch() { var items = document.getElementById('palantir-results').getElementsByTagName('li'); var val = document.getElementById('palantir-search').value; if( val ) { for (var i = items.length - 1; i >= 0; i--) { items[i].style.display="none"; }; // Escape Regex specials and split query words var input = val.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); input = input.split(/\s/); // Create a regex for query words in any order var regex = '^'; for( i = 0; i < input.length; i++ ) { regex += '(?=.*' + input[i] + ')'; } var query = new RegExp( regex, 'i' ); // Query the list of items list.filter( function( value, index, list ) { if( (value.title + value.description).search( query ) !== -1 ) { items[index].style.display="block"; } }, query ); } else { for (var i = items.length - 1; i >= 0; i--) { items[i].style.display="block"; }; } } /* Insert JSONP & CSS ============================================================================ */ var css = document.createElement('style'); css.type = 'text/css'; css.innerHTML = '@import "' + PP_CSS + '";'; document.getElementsByTagName('body')[0].appendChild(css); var head = document.getElementsByTagName('head')[0]; var palantirFile = document.createElement('script'); palantirFile.type = 'text/javascript'; palantirFile.src = PP_JSON; head.appendChild(palantirFile);
mynameisrienk/Palantir-Pocket
src/script.js
JavaScript
gpl-3.0
5,311
"use strict"; /* global global: false */ var ko = require("knockout"); var $ = require("jquery"); var console = require("console"); var tinymce = require("tinymce"); var timeout; var render = function() { timeout = undefined; if (typeof tinymce.activeEditor !== 'undefined' && tinymce.activeEditor !== null && typeof tinymce.activeEditor.theme !== 'undefined' && tinymce.activeEditor.theme !== null && typeof tinymce.activeEditor.theme.panel !== 'undefined' && tinymce.activeEditor.theme.panel !== null && typeof tinymce.activeEditor.theme.panel.visible !== 'undefined') { // @see FloatPanel.js function repositionPanel(panel) // First condition group is for Tinymce 4.0/4.1 // Second condition group is for Tinymce 4.2/4.3 where "._property" are now available as ".state.get('property')". if ((typeof tinymce.activeEditor.theme.panel._visible !== 'undefined' && tinymce.activeEditor.theme.panel._visible && tinymce.activeEditor.theme.panel._fixed) || (typeof tinymce.activeEditor.theme.panel.state !== 'undefined' && tinymce.activeEditor.theme.panel.state.get('visible') && tinymce.activeEditor.theme.panel.state.get('fixed'))) { tinymce.activeEditor.theme.panel.fixed(false); } tinymce.activeEditor.nodeChanged(); // Don't force tinymce to be visible on scrolls // If setteed, This will show the tinymce controls event when non are selected // https://github.com/goodenough/mosaico/issues/7#issuecomment-236853305 // tinymce.activeEditor.theme.panel.visible(true); if (tinymce.activeEditor.theme.panel.layoutRect().y <= 40) tinymce.activeEditor.theme.panel.moveBy(0, 40 - tinymce.activeEditor.theme.panel.layoutRect().y); } }; ko.bindingHandlers.wysiwygScrollfix = { 'scroll': function(event) { if (timeout) global.clearTimeout(timeout); timeout = global.setTimeout(render, 50); }, 'init': function(element) { ko.utils.domNodeDisposal.addDisposeCallback(element, function() { $(element).off("scroll", ko.bindingHandlers.wysiwygScrollfix.scroll); }); $(element).on("scroll", ko.bindingHandlers.wysiwygScrollfix.scroll); } };
goodenough/mosaico
src/js/bindings/scrollfix.js
JavaScript
gpl-3.0
2,159
function geojsonToPath( geojson ) { var points = []; var features; if (geojson.type === "FeatureCollection") features = geojson.features; else if (geojson.type === "Feature") features = [geojson]; else features = [{type:"Feature", properties: {}, geometry: geojson}]; features.forEach(function mapFeature(f) { switch (f.geometry.type) { // POIs // LineStrings case "LineString": case "MultiLineString": var coords = f.geometry.coordinates; if (f.geometry.type == "LineString") coords = [coords]; coords.forEach(function(coordinates) { coordinates.forEach(function(c) { points.push("" + c[1] + "," + c[0]); }); }); break; default: console.log("warning: unsupported geometry type: "+f.geometry.type); } }); gpx_str = points.join(':'); return gpx_str; } module.exports = geojsonToPath;
Wilkins/geojson-to-path
index.js
JavaScript
gpl-3.0
903
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); /** * This module contains code for State Parameters. * * See [[ParamDeclaration]] * * @packageDocumentation @preferred */ __exportStar(require("./interface"), exports); __exportStar(require("./param"), exports); __exportStar(require("./paramTypes"), exports); __exportStar(require("./stateParams"), exports); __exportStar(require("./paramType"), exports); //# sourceMappingURL=index.js.map
statusengine/interface
public/node_modules/@uirouter/core/lib/params/index.js
JavaScript
gpl-3.0
962
var class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu = [ [ "GUIVehiclePopupMenu", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a73018020f9f05d195dae7150d7d05f67", null ], [ "~GUIVehiclePopupMenu", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#adb26386f308440afa1524afdc297a855", null ], [ "GUIVehiclePopupMenu", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a19c8bd91fbe5bec3058d99905ccbf3fc", null ], [ "getParentView", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a7636e249e43445e500207ac5a38df9c5", null ], [ "onCmdAddSelected", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a3bd8d959ee49ded6699b440378f571cd", null ], [ "onCmdCenter", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a9ba9190cfcdbdf7ac7d15d8df3e6eff0", null ], [ "onCmdCopyCursorGeoPosition", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a38bf05cc7af3a4627e538b9c9d91c4bb", null ], [ "onCmdCopyCursorPosition", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a34aff5c5881cafb9ed118b5d8aa756ad", null ], [ "onCmdCopyName", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a27185a4f7b78f6820dd109afa7947799", null ], [ "onCmdCopyTypedName", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#aeaf6c23905d5e7b8f877101c0abe4a3e", null ], [ "onCmdHideAllRoutes", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a8319aa3a0ab6d86c858b54d02fa2f74f", null ], [ "onCmdHideBestLanes", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a22e96fb1eab350af224cbd01c1d3508e", null ], [ "onCmdHideCurrentRoute", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a9ff2c75f891caa53908d6f8f9d1b5a09", null ], [ "onCmdHideLFLinkItems", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a0c32ab11aadc2e07aeca6f9af9a69fed", null ], [ "onCmdRemoveSelected", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#ab5ac05701ab7a3bd79b23e6c1e5cdbf1", null ], [ "onCmdShowAllRoutes", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a3177b067a40a81ea429153764c9f7cd9", null ], [ "onCmdShowBestLanes", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a8c17df1522be85eb51e561887549473a", null ], [ "onCmdShowCurrentRoute", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a3c3d80caa43d1bb59ebc57453e19fe71", null ], [ "onCmdShowFoes", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a711381145f2dc84b2650642c70318657", null ], [ "onCmdShowLFLinkItems", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a0b2345f09be6e44b2934fa5b23401563", null ], [ "onCmdShowPars", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a5118a7bb2c2e6a7c6fb928872dd77db1", null ], [ "onCmdStartTrack", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a8339783a43238e108431fa3160693956", null ], [ "onCmdStopTrack", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#ab4e2668ac25eff359f6b8d61bb968e33", null ], [ "dummy", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a3739a963992d7b28aa876d0dd814fafa", null ], [ "myApplication", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a612a7a648bf10fa293c70f80f8d18573", null ], [ "myNetworkPosition", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#aaa196610b3d120719f5d4a958ebb386a", null ], [ "myObject", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a0c5104d23cce18ac2afd4b758f444516", null ], [ "myParent", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a32927bb7e5465b8e8c01c6f9a289528c", null ], [ "myVehiclesAdditionalVisualizations", "db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.html#a6b012f516393eaddfc97723ae846e2c1", null ] ];
cathyyul/sumo-0.18
docs/doxygen/db/d5b/class_g_u_i_vehicle_1_1_g_u_i_vehicle_popup_menu.js
JavaScript
gpl-3.0
3,913
console.log('Hello world!') require('./src')
VevoxDigital/Iota
index.js
JavaScript
gpl-3.0
45
/** * team-popup-links.js * Foxtrick show Team Popup * @author bummerland, convinced, ryanli */ 'use strict'; Foxtrick.modules['TeamPopupLinks'] = { MODULE_CATEGORY: Foxtrick.moduleCategories.SHORTCUTS_AND_TWEAKS, OUTSIDE_MAINBODY: true, PAGES: ['all'], NICE: 10, // after anythings that works on team/manager links // but before staff-marker CSS: Foxtrick.InternalPath + 'resources/css/popup-links.css', OPTIONS: ['TeamHighlight', 'TeamLinks', 'UserLinks', 'CustomLink'], OPTION_TEXTS: true, OPTION_TEXTS_DISABLED_LIST: [true, true, true, false], LINKS: { Team: { linkByUser: '/Club/Manager/?userId=[userid]&redir_to_team=true', }, Manager: { linkByTeam: '/Club/Manager/?teamId=[teamid]', }, Matches: { ownLink: '/Club/Matches/', linkByTeam: '/Club/Matches/?teamId=[teamid]', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_matches=true', }, Players: { ownLink: '/Club/Players/', linkByTeam: '/Club/Players/?teamId=[teamid]', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_players=true', }, Series: { linkByTeam: '/Club/Manager/?teamId=[teamid]&redir_to_series=true', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_series=true', }, last_5_ips: { linkByTeam: '/Club/Manager/?teamId=[teamid]&ShowOldConnections=true', linkByUser: '/Club/Manager/?userId=[userid]&ShowOldConnections=true', }, Guestbook: { linkByTeam: '/Club/Manager/Guestbook.aspx?teamId=[teamid]', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_guestbook=true', }, SendMessage: { linkByTeam: '/Club/?teamId=[teamid]&redir_to_mail=true', linkByUser: '/MyHattrick/Inbox/?actionType=newMail&userId=[userid]', }, Challenge: { linkByTeam: '/Club/?teamId=[teamid]&make_challenge', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_challenge=true', }, Achievements: { linkByTeam: '/Club/Manager/?teamId=[teamid]&redir_to_achievements=true', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_achievements=true', }, Coach: { ownLink: '/Club/Training/?redir_to_coach=true', linkByTeam: '/Club/Players/?teamId=[teamid]&redir_to_coach=true', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_coach=true', }, TeamAnalysis: { ownLink: '/Club/TacticsRoom/', linkByTeam: '/Club/TacticsRoom/?teamId=[teamid]', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_analysis=true', }, TransferHistory: { linkByTeam: '/Club/Transfers/transfersTeam.aspx?teamId=[teamid]', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_transferhistory=true', }, TeamHistory: { linkByTeam: '/Club/History/?teamId=[teamid]', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_teamhistory=true', }, FlagCollection: { linkByTeam: '/Club/Flags/?teamId=[teamid]', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_flags=true', }, LastLineup: { linkByTeam: '/Club/Matches/MatchLineup.aspx?teamId=[teamid]' + '&useArchive=True&redir_to_newlineup=true', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_lastlineup=true', }, NextMatch: { linkByTeam: '/Club/Matches/?teamId=[teamid]&redir_to_nextmatch=true', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_nextmatch=true', }, AddNextMatch: { linkByTeam: '/Club/Matches/?teamId=[teamid]&redir_to_addnextmatch=true', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_addnextmatch=true', }, YouthMatches: { linkByTeam: '/Club/Matches/?teamId=[teamid]&redir_to_youthmatches=true', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_youthmatches=true', }, Tournaments: { linkByTeam: '/Community/Tournaments/?teamId=[teamid]', linkByUser: '/Club/Manager/?userId=[userid]&redir_to_tournaments=true', }, }, OPTION_FUNC: function(doc) { var table = doc.createElement('table'); table.className = 'bordered center'; var caption = doc.createElement('caption'); caption.setAttribute('data-text', 'TeamPopupLinks.prefsCaption'); table.appendChild(caption); var headerRow = doc.createElement('tr'); table.appendChild(headerRow); var placeHolder = doc.createElement('th'); headerRow.appendChild(placeHolder); var enableDefault = doc.createElement('th'); enableDefault.setAttribute('data-text', 'TeamPopupLinks.ShowByDefault'); headerRow.appendChild(enableDefault); var enableMore = doc.createElement('th'); enableMore.setAttribute('data-text', 'TeamPopupLinks.ShowOnMore'); headerRow.appendChild(enableMore); var enableNewTab = doc.createElement('th'); enableNewTab.setAttribute('data-text', 'TeamPopupLinks.OpenNewTab'); headerRow.appendChild(enableNewTab); var i; for (i in this.LINKS) { var row = doc.createElement('tr'); table.appendChild(row); var title = doc.createElement('th'); title.textContent = Foxtrick.Prefs.getModuleElementDescription('TeamPopupLinks', i); row.appendChild(title); var defaultCell = doc.createElement('td'); row.appendChild(defaultCell); var defaultCheck = doc.createElement('input'); defaultCheck.type = 'checkbox'; defaultCheck.setAttribute('pref', 'module.TeamPopupLinks.' + i + '.default'); defaultCell.appendChild(defaultCheck); var moreCell = doc.createElement('td'); row.appendChild(moreCell); var moreCheck = doc.createElement('input'); moreCheck.type = 'checkbox'; moreCheck.setAttribute('pref', 'module.TeamPopupLinks.' + i + '.more'); moreCell.appendChild(moreCheck); var newTab = doc.createElement('td'); row.appendChild(newTab); var newTabCheck = doc.createElement('input'); newTabCheck.type = 'checkbox'; newTabCheck.setAttribute('pref', 'module.TeamPopupLinks.' + i + '.newTab'); newTab.appendChild(newTabCheck); } return table; }, run: function(doc) { const module = this; // show last 5 logins if (/ShowOldConnections=true/i.test(doc.URL)) { let a = Foxtrick.getMBElement(doc, 'lnkShowLogins'); a && a.click(); } module.addPopupLinks(doc); }, /* eslint-disable complexity */ addPopupLinks: function(doc) { const module = this; const MODULE_NAME = module.MODULE_NAME; const TEAM_RE = /Club\/(Default\.aspx)?\?TeamID=/i; const MANAGER_RE = /Club\/Manager\/(Default\.aspx)?\?UserID=/i; const FORUM_RE = /Forum\/(Default\.aspx)?\?/i; const TEAM_ID_TAG = /\[teamid\]/i; const USER_ID_TAG = /\[userid\]/i; const USER_NAME_TAG = /\[username\]/i; const REDIR_RE = /redir_to/i; var teamEnabled = Foxtrick.Prefs.isModuleOptionEnabled(module, 'TeamLinks'); var userEnabled = Foxtrick.Prefs.isModuleOptionEnabled(module, 'UserLinks'); var highlightEnabled = Foxtrick.Prefs.isModuleOptionEnabled(module, 'TeamHighlight'); var customEnabled = Foxtrick.Prefs.isModuleOptionEnabled(module, 'CustomLink'); var mainBody = doc.getElementById('mainBody'); var sUrl = doc.URL; var ownTeamId = Foxtrick.util.id.getOwnTeamId(); var curTeamId = Foxtrick.Pages.All.getTeamId(doc); var hasScroll = Foxtrick.util.layout.mainBodyHasScroll(doc); var links = this.LINKS; var addSpan = function(aLink) { if (Foxtrick.hasClass(aLink, 'ft-tpl') || Foxtrick.hasClass(aLink, 'ft-popup-list-link')) return; var url = aLink.href; var parent = aLink.parentNode; var grandParent = parent.parentNode; if (TEAM_RE.test(url) && !REDIR_RE.test(url) && teamEnabled || MANAGER_RE.test(url) && userEnabled) { var span = Foxtrick.createFeaturedElement(doc, module, 'span'); span.className = 'ft-popup-span'; if (highlightEnabled && TEAM_RE.test(url) && curTeamId == parseInt(Foxtrick.getUrlParam(url, 'TeamID'), 10)) { if (parent.nodeName == 'TD') Foxtrick.addClass(grandParent, 'ftTeamHighlight'); else if (grandParent.nodeName == 'TD') Foxtrick.addClass(grandParent.parentNode, 'ftTeamHighlight'); } const pages = ['forumViewThread', 'forumWritePost', 'forumModWritePost', 'region']; if (!Foxtrick.isPage(doc, pages) && (Foxtrick.util.layout.isStandard(doc) || parent.nodeName != 'TD')) { // Foxtrick.addClass(aLink, 'ft-nowrap'); Foxtrick.addClass(aLink, 'ft-tpl'); } else { Foxtrick.addClass(aLink, 'ft-tpl'); } parent.insertBefore(span, aLink); // to show a pop-up! var showPopup = function(ev) { var findLink = function(node) { if (node.nodeName == 'A' && !Foxtrick.hasClass(node, 'ft-no-popup')) return node; if (!node.parentNode) return null; return findLink(node.parentNode); }; // need to find <a> recursively as <a> may have children // like <bdo> var orgLink = findLink(ev.target); if (orgLink == null) return; // no link found var showMore = false; if (orgLink.getAttribute('more')) { if (orgLink.getAttribute('more') == 'true') showMore = true; orgLink = orgLink.parentNode.parentNode.previousSibling; } var teamId = Foxtrick.util.id.getTeamIdFromUrl(orgLink.href); if (teamId) { // eslint-disable-next-line no-unused-vars let teamName = orgLink.textContent; // lgtm[js/unused-local-variable] } var userName; var userId = Foxtrick.util.id.getUserIdFromUrl(orgLink.href); if (userId) { let linkName = orgLink.textContent.trim(); let titleName = orgLink.title.trim(); if (titleName.slice(0, linkName.length) === linkName) { // link name seems to be shortened for long user names // using titleName instead if it's a superstring userName = titleName; } else { userName = linkName; } } var ownTopTeamLinks = orgLink.parentNode.parentNode.nodeName == 'DIV' && orgLink.parentNode.parentNode.id == 'teamLinks'; var list = Foxtrick.createFeaturedElement(doc, module, 'ul'); list.className = 'ft-popup-list'; var addItem = function(key, isOwnTeam, teamId, userId, userName, ownLink, linkByTeam, linkByUser, linkByUserName) { var item = doc.createElement('li'); var link = doc.createElement('a'); link.className = 'ft-popup-list-link'; var user = userName; if (user && userId && userId == user.match(/\d+/)) user = ''; if (isOwnTeam && ownLink) link.href = ownLink; else if (teamId && linkByTeam) link.href = linkByTeam.replace(TEAM_ID_TAG, teamId); else if (user && linkByUserName) link.href = linkByUserName.replace(USER_NAME_TAG, user); else if (userId && linkByUser) link.href = linkByUser.replace(USER_ID_TAG, userId); else return; var openInNewTab = function(option) { let key = `module.${MODULE_NAME}.${option}.newTab`; return Foxtrick.Prefs.getBool(key); }; if (openInNewTab(key)) link.target = '_blank'; link.textContent = Foxtrick.L10n.getString(key); item.appendChild(link); list.appendChild(item); }; var isEnabledWithinContext = function(option, more) { let key = `module.${MODULE_NAME}.${option}.${more ? 'more' : 'default'}`; return Foxtrick.Prefs.getBool(key); }; var showLessMore = false; if (ownTopTeamLinks) { // own team's link at the top of the page for (let link of ['Matches', 'Players']) { let def = links[link]; if (!def) continue; let ownLink = def.ownLink; addItem(link, true, null, null, null, ownLink, null, null, null); } } else { for (let link in links) { if (isEnabledWithinContext(link, showMore)) { let def = links[link]; let own = teamId == ownTeamId; addItem(link, own, teamId, userId, userName, def.ownLink, def.linkByTeam, def.linkByUser, def.linkByUserName); } else if (isEnabledWithinContext(link, !showMore)) { showLessMore = true; } } if (customEnabled) { let customLinkText = Foxtrick.Prefs.getString(`module.${MODULE_NAME}.CustomLink_text`); if (typeof customLinkText === 'string') { let ownLinks = customLinkText.split(/\n/); for (let ownLink of ownLinks.map(l => l.trim()).filter(Boolean)) { try { let redirToCustom = false; let json = JSON.parse(ownLink); if (showMore != json.more) { showLessMore = true; continue; } let item = doc.createElement('li'); let link = doc.createElement('a'); link.href = Foxtrick.util.sanitize.parseUrl(json.link); link.title = json.title; link.textContent = json.title; if (TEAM_ID_TAG.test(link.href)) { if (teamId) link.href = link.href.replace(TEAM_ID_TAG, teamId); else redirToCustom = true; } if (USER_ID_TAG.test(link.href)) { if (userId) link.href = link.href.replace(USER_ID_TAG, userId); else redirToCustom = true; } if (redirToCustom) { if (teamId == null) { link.href = '/Club/Manager/?userId=' + userId + '&redir_to_custom=true&redir_to=' + link.href; } else { link.href = '/Club/Manager/?teamId=' + teamId + '&redir_to_custom=true&redir_to=' + link.href; } } if (json.newTab) link.target = '_blank'; item.appendChild(link); list.appendChild(item); } catch (e) { Foxtrick.log('custom teampopup error:', e); } } } } if (showLessMore) { let item = doc.createElement('li'); let link = doc.createElement('a'); if (showMore) { link.setAttribute('more', 'false'); link.textContent = Foxtrick.L10n.getString('less'); } else { link.setAttribute('more', 'true'); link.textContent = Foxtrick.L10n.getString('more'); } Foxtrick.onClick(link, showPopup); item.appendChild(link); list.appendChild(item); } } var down = false; let pos = Foxtrick.getElementPosition(orgLink, mainBody); var pT = pos.top; if (hasScroll && pT - mainBody.scrollTop < mainBody.offsetHeight / 2 || pT - doc.body.scrollTop < 300 || !mainBody) { // = popdown if (list.lastChild) { let more = list.removeChild(list.lastChild); list.insertBefore(more, list.firstChild); } down = true; } Foxtrick.addClass(list, 'ft-popup-list-' + (down ? 'down' : 'up')); let parentTPL = orgLink.parentNode.querySelector('.ft-popup-list'); if (parentTPL) parentTPL.remove(); Foxtrick.insertAfter(list, orgLink); }; Foxtrick.listen(aLink, 'mouseover', showPopup, false); span.appendChild(aLink); } }; // team links var link = doc.querySelector('#teamLinks a'); if (link) addSpan(link); // all in mainWrapper (ie. not left boxes) if (FORUM_RE.test(sUrl)) return; // not in forum overview if (mainBody) { let aLinks = mainBody.querySelectorAll('a'); for (let aLink of aLinks) { if (!aLink.hasAttribute('href') || Foxtrick.hasClass(aLink, 'ft-no-popup') || aLink.parentNode.className == 'liveTabText' || aLink.querySelector('img:not(.ft-staff-icon)') !== null) continue; // don't add to buttons, and htlive tabs addSpan(aLink); } } var sidebar = doc.getElementById('sidebar'); if (sidebar) { let aLinks = sidebar.querySelectorAll('a'); for (let aLink of aLinks) { if (!aLink.hasAttribute('href') || aLink.querySelector('img:not(.ft-staff-icon)') !== null) continue; // don't add to buttons addSpan(aLink); } } }, change: function(doc) { this.addPopupLinks(doc); }, };
minj/foxtrick
content/shortcuts-and-tweaks/team-popup-links.js
JavaScript
gpl-3.0
15,863
var sqlite3 = require('sqlite3').verbose(); /*Live database*/ var db = new sqlite3.Database(__dirname + '/database.db'); /*Testing database*/ module.exports.useTestDatabase = function(){ var path = __dirname + '/testDatabase.db' db = new sqlite3.Database(__dirname + '/testDatabase.db'); } /*Test or Live depending on caller*/ module.exports.database = function(){ return db; };
TantalizingThyroids/Event.ly
server/db/db.js
JavaScript
gpl-3.0
388
import { Component, Directive, ElementRef, EventEmitter, forwardRef, HostListener, Input, NgZone, Renderer, Inject, Optional, Output } from '@angular/core'; import { Content } from '../content/content'; import { CSS, zoneRafFrames } from '../../util/dom'; import { Item } from './item'; import { ItemReorderGesture } from '../item/item-reorder-gesture'; import { isTrueProperty } from '../../util/util'; export class ItemReorder { constructor(elementRef, _rendered, _zone, _content) { this._rendered = _rendered; this._zone = _zone; this._content = _content; this._enableReorder = false; this._visibleReorder = false; this._lastToIndex = -1; this.ionItemReorder = new EventEmitter(); this._element = elementRef.nativeElement; } ngOnDestroy() { this._element = null; this._reorderGesture && this._reorderGesture.destroy(); } get reorder() { return this._enableReorder; } set reorder(val) { let enabled = isTrueProperty(val); if (!enabled && this._reorderGesture) { this._reorderGesture.destroy(); this._reorderGesture = null; this._visibleReorder = false; setTimeout(() => this._enableReorder = false, 400); } else if (enabled && !this._reorderGesture) { // console.debug('enableReorderItems'); this._reorderGesture = new ItemReorderGesture(this); this._enableReorder = true; zoneRafFrames(2, () => this._visibleReorder = true); } } reorderPrepare() { let ele = this._element; let children = ele.children; for (let i = 0, ilen = children.length; i < ilen; i++) { var child = children[i]; child.$ionIndex = i; child.$ionReorderList = ele; } } reorderStart() { this.setElementClass('reorder-list-active', true); } reorderEmit(fromIndex, toIndex) { this.reorderReset(); if (fromIndex !== toIndex) { this._zone.run(() => { this.ionItemReorder.emit({ from: fromIndex, to: toIndex, }); }); } } scrollContent(scroll) { let scrollTop = this._content.getScrollTop() + scroll; if (scroll !== 0) { this._content.scrollTo(0, scrollTop, 0); } return scrollTop; } reorderReset() { let children = this._element.children; let len = children.length; this.setElementClass('reorder-list-active', false); let transform = CSS.transform; for (let i = 0; i < len; i++) { children[i].style[transform] = ''; } this._lastToIndex = -1; } reorderMove(fromIndex, toIndex, itemHeight) { if (this._lastToIndex === -1) { this._lastToIndex = fromIndex; } let lastToIndex = this._lastToIndex; this._lastToIndex = toIndex; let children = this._element.children; let transform = CSS.transform; if (toIndex >= lastToIndex) { for (var i = lastToIndex; i <= toIndex; i++) { if (i !== fromIndex) { children[i].style[transform] = (i > fromIndex) ? `translateY(${-itemHeight}px)` : ''; } } } if (toIndex <= lastToIndex) { for (var i = toIndex; i <= lastToIndex; i++) { if (i !== fromIndex) { children[i].style[transform] = (i < fromIndex) ? `translateY(${itemHeight}px)` : ''; } } } } setElementClass(classname, add) { this._rendered.setElementClass(this._element, classname, add); } getNativeElement() { return this._element; } } ItemReorder.decorators = [ { type: Directive, args: [{ selector: 'ion-list[reorder],ion-item-group[reorder]', host: { '[class.reorder-enabled]': '_enableReorder', '[class.reorder-visible]': '_visibleReorder', } },] }, ]; ItemReorder.ctorParameters = [ { type: ElementRef, }, { type: Renderer, }, { type: NgZone, }, { type: Content, decorators: [{ type: Optional },] }, ]; ItemReorder.propDecorators = { 'ionItemReorder': [{ type: Output },], 'reorder': [{ type: Input },], }; export class Reorder { constructor(item, elementRef) { this.item = item; this.elementRef = elementRef; elementRef.nativeElement['$ionComponent'] = this; } getReorderNode() { let node = this.item.getNativeElement(); return findReorderItem(node, null); } onClick(ev) { ev.preventDefault(); ev.stopPropagation(); } } Reorder.decorators = [ { type: Component, args: [{ selector: 'ion-reorder', template: `<ion-icon name="reorder"></ion-icon>` },] }, ]; Reorder.ctorParameters = [ { type: ItemReorder, decorators: [{ type: Inject, args: [forwardRef(() => Item),] },] }, { type: ElementRef, }, ]; Reorder.propDecorators = { 'onClick': [{ type: HostListener, args: ['click', ['$event'],] },], }; export function findReorderItem(node, listNode) { let nested = 0; while (node && nested < 4) { if (indexForItem(node) !== undefined) { if (listNode && node.parentNode !== listNode) { return null; } return node; } node = node.parentNode; nested++; } return null; } export function indexForItem(element) { return element['$ionIndex']; } export function reorderListForItem(element) { return element['$ionReorderList']; }
shdevops/JAF-Dice-Roller
node_modules/ionic-angular/es2015/components/item/item-reorder.js
JavaScript
gpl-3.0
5,883
/** * This module removes the need to know which implementation of has we are using. * @module * @todo Make a decision and remove this! */ define(["lib/dojo/has"], /** @param {Object?} [has] @ignore */function(has) { "use strict"; var global = window; return global.has || has; });
Joshua-Barclay/wcomponents
wcomponents-theme/src/main/js/wc/has.js
JavaScript
gpl-3.0
289
cloudStreetMarketApp.factory("indicesGraphFactory", function (httpAuth) { return { getGraph: function (index) { var xmlHTTP = new XMLHttpRequest(); xmlHTTP.open('GET',"/api/charts/indices/"+index+".png",true); httpAuth.setHeaders(xmlHTTP); // Must include this line - specifies the response type we want xmlHTTP.responseType = 'arraybuffer'; xmlHTTP.onload = function(e){ var arr = new Uint8Array(this.response); var raw = String.fromCharCode.apply(null,arr); if($("#homeChart")[0]){ $("#homeChart")[0].src = "data:image/png;base64,"+btoa(raw); } }; xmlHTTP.send(); }, getIndices: function (market) { return httpAuth.get("/api/indices.json?size=6"); } } }); cloudStreetMarketApp.controller('homeFinancialGraphController', function ($scope, indicesGraphFactory){ $scope.init = function () { var indicesPromise = indicesGraphFactory.getIndices($scope.preferedMarket); indicesPromise.success(function(dataIndices, status, headers, config) { $scope.indicesForGraph = dataIndices.content; if($scope.indicesForGraph){ indicesGraphFactory.getGraph($scope.currentIndex); } }) $('.form-control').on('change', function (){ $scope.currentIndex = this.value; indicesGraphFactory.getGraph($scope.currentIndex); }); } $scope.preferedMarket="EUROPE"; $scope.currentIndex="^GDAXI"; $scope.indices = null; $scope.init(); });
alex-bretet/cloudstreetmarket.com
cloudstreetmarket-parent/cloudstreetmarket-webapp/src/main/webapp/js/home/home_financial_graph.js
JavaScript
gpl-3.0
1,575
Template.addAction.actionCreationCancelled=function() { var context=EditContext.getContext(); if(context!=null) { context.keepEditContextOnNextRoute(); var route=context.getReturnRoute(); route.onCancel(); } else { Router.go('actions'); } return false; } Template.addAction.events({ 'click .cancel' :Template.addAction.actionCreationCancelled, 'click .goBack' : Template.addAction.actionCreationCancelled }); Router.route('action-create', function () { this.render('addAction'); }, { name: 'addAction'}); Template.addAction.helpers({ collection: function() { return Collections.Actions; }, editContext : function() { return EditContext.getContext(); }, schema: Schemas.Action }); AutoForm.hooks({ addActionForm: { after: { 'method-update': function(err,result) { //Router.go('actions'); var context=EditContext.getContext(); console.log('save action!'); if(context!=undefined) { context.keepEditContextOnNextRoute(); } Router.go('render.action',{_id: result}); } } } });
dubsky/robolos
src/client/html/actions/addAction.js
JavaScript
gpl-3.0
1,248
function zeroFill( number, width ) { width -= number.toString().length; if ( width > 0 ) { return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number; } return number + ""; // always return a string } function populateEndtime() { var startVal = parseInt($('started').value,10); var hrsVal = parseInt($('workhours').value,10); var finVal = startVal + hrsVal; finVal = zeroFill(finVal,2); $('ended').value = finVal + ":00"; } function populateHours() { var startVal = parseInt($('started').value,10); var endVal = parseInt($('ended').value,10); var hrsVal = parseInt($('workhours').value,10); var finVal = endVal - startVal; if(hrsVal != finVal && finVal >= 0) { $('workhours').value = finVal; } }
cosycode/collabtive2
include/js/timetracker_widget.js
JavaScript
gpl-3.0
745
(function() { "use strict"; pwf.reg_class('ui.list.team.member', { 'parents':['ui.link'], 'storage':{ 'opts':{ 'path':'user' } }, 'proto':{ 'prefix':'member', 'els':[ 'avatar', { 'name':'data', 'els':['name', 'roles'] }, { 'name':'cleaner', 'prefix':null } ], 'create_link':function(p) { p('fill'); }, 'fill':function() { var el = this.get_el(), item = this.get('item'), user = item.get('user'); this.set('params', {'user':this.get('user').get('id')}); el.data.name.html(pwf.site.get_user_name(user)); pwf.thumb.fit(user.get('avatar'), el.avatar); pwf.create('ui.intra.team.member.role.list', { 'parent':el.data.roles, 'roles':item.get('roles') }); } } }); })();
just-paja/improliga
share/scripts/ui/list/team/member.js
JavaScript
gpl-3.0
819
var spa = "spa/scripts/"; require.config({ jsx: { fileExtension: '.jsx' }, paths: { 'spa': "spa/scripts", 'underscore': "spa/scripts/vendor/underscore", 'jquery': "spa/scripts/vendor/jquery", 'Q': 'spa/scripts/vendor/q', 'marked': 'spa/scripts/vendor/marked', 'backbone': 'spa/scripts/vendor/backbone', 'react': "spa/scripts/vendor/react-dev", 'immutable': "spa/scripts/vendor/immutable", 'JSXTransformer': "spa/scripts/vendor/JSXTransformer", 'PDFJS': "spa/scripts/vendor/pdfjs/pdf" }, shim: { 'PDFJS': { exports: 'PDFJS', deps: ['spa/vendor/pdfjs/generic/web/compatibility', 'spa/vendor/ui_utils'] } } }); define(function (require) { window.React = require('react'); // for pref tools require("app"); });
vortext/vortext-demo
resources/public/scripts/main.js
JavaScript
gpl-3.0
804
'use strict'; angular.module('risevision.editorApp.directives') .directive('resolutionSelector', [ function () { return { restrict: 'E', scope: false, templateUrl: 'partials/resolution-selector.html', link: function (scope) { // view will show resolutions on the same order from this object declaration scope.resolutionOptions = { '1024x768': '1024 x 768', '1280x1024': '1280 x 1024', '1600x1200': '1600 x 1200', '1280x720': '1280 x 720 Wide', '1280x768': '1280 x 768 Wide', '1360x768': '1360 x 768 Wide', '1366x768': '1366 x 768 Wide', '1440x900': '1440 x 900 Wide', '1680x1050': '1680 x 1050 Wide', '1920x1080': '1920 x 1080 Wide', '720x1280': '720 x 1280 Portrait', '768x1280': '768 x 1280 Portrait', '768x1360': '768 x 1360 Portrait', '768x1366': '768 x 1366 Portrait', '1080x1920': '1080 x 1920 Portrait', 'custom': 'Custom' }; if (scope.presentationProperties.width && scope.presentationProperties .height) { scope.resolutionOption = scope.presentationProperties.width + 'x' + scope.presentationProperties.height; if (!(scope.resolutionOption in scope.resolutionOptions)) { scope.resolutionOption = 'custom'; } } scope.updateResolution = function () { if (scope.resolutionOption !== 'custom') { var sizes = scope.resolutionOption.split('x'); scope.presentationProperties.width = parseInt(sizes[0]); scope.presentationProperties.height = parseInt(sizes[1]); } }; scope.objectKeys = function (obj) { return Object.keys(obj); }; } //link() }; } ]);
Rise-Vision/editor-app
js/directives/dtv-resolution-selector.js
JavaScript
gpl-3.0
2,034
import React from 'react'; import Select from 'react-select'; import axios from 'axios'; export default class RuleTypeSelector extends React.Component { constructor() { super(); this.state = { ruleTypes: [] }; } componentDidMount() { axios.get('/rule-types').then((response) => { this.setState({ruleTypes: response.data.map((ruleType) => { return { typeName: ruleType } })}); }); } render() { return ( <Select options={this.state.ruleTypes} value={this.props.value} onChange={this.props.onChange} labelKey="typeName" valueKey="typeName" /> ); } }
kfirprods/tpp
client/src/components/atomic/RuleTypeSelector.js
JavaScript
gpl-3.0
776
var assert = require('assert'); var expect = require('chai').expect; var rds = require('./rdsEncryptionEnabled'); const listKeys = [ { KeyId: '60c4f21b-e271-4e97-86ae-6403618a9467', KeyArn: 'arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467' } ]; const describeKey = [ { "KeyMetadata": { "AWSAccountId": "112233445566", "KeyId": "60c4f21b-e271-4e97-86ae-6403618a9467", "Arn": "arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467", "CreationDate": "2020-03-25T14:05:09.299Z", "Enabled": true, "Description": "Used for S3 encryption", "KeyUsage": "ENCRYPT_DECRYPT", "KeyState": "Enabled", "Origin": "AWS_KMS", "KeyManager": "CUSTOMER", "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT", "EncryptionAlgorithms": [ "SYMMETRIC_DEFAULT" ] } } ]; const createCache = (rdsData, kmsData, listKeys, describeKey) => { var keyId = (listKeys && listKeys.length) ? listKeys[0].KeyId : null; return { rds: { describeDBInstances: { 'us-east-1': { err: null, data: rdsData } } }, kms: { listAliases: { 'us-east-1': { err: null, data: kmsData } }, listKeys: { 'us-east-1': { data: listKeys } }, describeKey: { 'us-east-1': { [keyId]: { data: describeKey } } } } } }; describe('rdsEncryptionEnabled', function () { describe('run', function () { it('should give passing result if no RDS instances are found', function (done) { const callback = (err, results) => { expect(results.length).to.equal(1) expect(results[0].status).to.equal(0) expect(results[0].message).to.include('No RDS instances found') done() }; const cache = createCache( [], [] ); rds.run(cache, {}, callback); }) it('should give passing result if encrypted RDS instance is found', function (done) { const callback = (err, results) => { expect(results.length).to.equal(1) expect(results[0].status).to.equal(0) expect(results[0].message).to.include('Encryption at rest is enabled via KMS key') done() }; const cache = createCache( [ { Engine: 'mysql', StorageEncrypted: true, KmsKeyId: "arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467", } ], [], listKeys, describeKey[0] ); rds.run(cache, {}, callback); }) it('should give failing result if non-encrypted RDS instance is found', function (done) { const callback = (err, results) => { expect(results.length).to.equal(1) expect(results[0].status).to.equal(2) expect(results[0].message).to.include('Encryption at rest is not enabled') done() }; const cache = createCache( [ { Engine: 'mysql', StorageEncrypted: false } ], [] ); rds.run(cache, {}, callback); }) it('should give failing result if encrypted RDS instance is found with no KMS aliases', function (done) { const callback = (err, results) => { expect(results.length).to.equal(1) expect(results[0].status).to.equal(2) expect(results[0].message).to.include('RDS KMS alias setting is configured but there are no KMS aliases') done() }; const cache = createCache( [ { Engine: 'mysql', StorageEncrypted: true, KmsKeyId: "arn:aws:kms:us-east-1:112233445566:key/abcdef10-1517-49d8-b085-77c50b904149", } ], [], listKeys, describeKey[0] ); rds.run(cache, { rds_encryption_kms_alias: 'alias/example1' }, callback); }) it('should give failing result if encrypted RDS instance is found with wrong KMS aliases', function (done) { const callback = (err, results) => { expect(results.length).to.equal(1) expect(results[0].status).to.equal(2) expect(results[0].message).to.include('Encryption at rest is enabled, but is not using expected KMS key') done() }; const cache = createCache( [ { Engine: 'mysql', StorageEncrypted: true, KmsKeyId: "arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467", } ], [ { AliasArn: "arn:aws:kms:us-east-1:112233445566:alias/example1", AliasName: "alias/example1", TargetKeyId: "def1234a-62d0-46c5-a7c0-5f3a3d2f8046" } ], listKeys, describeKey[0] ); rds.run(cache, { rds_encryption_kms_alias: 'alias/example1' }, callback); }) it('should give passing result if encrypted RDS instance is found with correct KMS aliases', function (done) { const callback = (err, results) => { expect(results.length).to.equal(1) expect(results[0].status).to.equal(0) expect(results[0].message).to.include('Encryption at rest is enabled via expected KMS key') done() }; const cache = createCache( [ { Engine: 'mysql', StorageEncrypted: true, KmsKeyId: "arn:aws:kms:us-east-1:112233445566:key/60c4f21b-e271-4e97-86ae-6403618a9467", } ], [ { AliasArn: "arn:aws:kms:us-east-1:112233445566:alias/example1", AliasName: "alias/example1", TargetKeyId: "60c4f21b-e271-4e97-86ae-6403618a9467" } ], listKeys, describeKey[0] ); rds.run(cache, { rds_encryption_kms_alias: 'alias/example1' }, callback); }) }) })
cloudsploit/scans
plugins/aws/rds/rdsEncryptionEnabled.spec.js
JavaScript
gpl-3.0
7,430
iris.ui(function (self) { self.settings({ col: null , row: null , color: null }); // var resource = iris.resource(iris.path.resource); self.create = function() { self.tmplMode(self.APPEND); self.tmpl(iris.path.ui.king.html); }; self.moves = function(p_squareTo) { var colIndex = chess.board.COLS.indexOf(self.setting("col")) , cols = self.setting("col") === "a" ? ["a", "b"] : self.setting("col") === "h" ? ["g", "h"] : [chess.board.COLS[colIndex-1], chess.board.COLS[colIndex], chess.board.COLS[colIndex+1]] , rows = self.setting("row") === 1 ? [1, 2] : self.setting("row") === 8 ? [7, 8] : [self.setting("row")-1, self.setting("row"), self.setting("row")+1] , squares = [] , square ; for (var i=0, I=cols.length; i<I; i++) { for (var j=0, J=rows.length; j<J; j++) { if (cols[i] !== self.setting("col") || rows[j] !== self.setting("row")) { square = iris.model( iris.path.model.square.js , { row: rows[j] , col: cols[i] } ); if (!p_squareTo) { squares.push({ row: rows[j] , col: cols[i] }); } else if (p_squareTo.col === cols[i] && p_squareTo.row === rows[j]) { squares.push({ row: rows[j] , col: cols[i] }); break; } } } } return p_squareTo ? squares.length > 0 : squares ; }; // self.awake = function () { // }; // self.sleep = function () { // }; // self.destroy = function () { // }; },iris.path.ui.king.js);
IGZOscarArce/chess-challenges
src/iris-front/iris/ui/king.js
JavaScript
gpl-3.0
1,575
'use strict'; define( [ 'lodash', 'forge/object/base' ], function( lodash, Base ) { /** * BBCode parser * * @param {Object} codes * @param {Object} options */ function BBCode(codes, options) { this.codes = {}; Base.call(this, options); this.setCodes(codes); } // prototype BBCode.prototype = Object.create(Base.prototype, { /** * all codes in structure. * * @var {Object} */ codes: { value: null, enumerable: false, configurable: false, writable: true } }); /** * set bb codes * * @param {Object} codes * @returns {BBCode} */ BBCode.prototype.setCodes = function(codes) { this.codes = lodash.map(codes, function(replacement, regex) { return { regexp: new RegExp(regex.slice(1, regex.lastIndexOf('#')), 'igm'), replacement: replacement }; }); return this; }; /** * parse * * @param {String} text * @returns {String} */ BBCode.prototype.parse = function(text) { return lodash.reduce(this.codes, function(text, code) { return text.replace(code.regexp, code.replacement); }, text); }; return BBCode; });
DasRed/forge
bbCode.js
JavaScript
gpl-3.0
1,128
var util = require('util'); var Publisher = require('clickberry-nsq-publisher'); var Q = require('q'); var publishAsync; function Bus(options) { Publisher.call(this, options); publishAsync = Q.nbind(this.publish, this); } util.inherits(Bus, Publisher); Bus.prototype.publishVideoUpload = function (video, storageSpace, callback) { Q.all([ publishAsync('video-creates', video), publishAsync('video-storage-updates', storageSpace) ]).then(function () { callback(); }).catch(function (err) { callback(err); }); }; Bus.prototype.publishVideoRemove = function (video, storageSpace, callback) { Q.all([ publishAsync('video-deletes', video), publishAsync('video-storage-updates', storageSpace) ]).then(function(){ callback(); }).catch(function(err){ callback(err); }); }; module.exports = Bus;
clickberry/videos-api-nodejs
lib/bus-service.js
JavaScript
gpl-3.0
895
/** * @file: greyhead_customisations.js * * Little JS nips and tucks go in here. */ var Drupal = Drupal || {}; (function($, Drupal){ "use strict"; /** * If we're on a node edit page and the URL slug field is present, copy the * menu title into the URL slug field converted to lowercase alphanumeric- * only. */ Drupal.behaviors.greyheadAutoPopulateURLSlugField = { attach: function (context, settings) { // Are we on a node edit/add page? var nodeFormSelector = 'form.node-form'; var nodeForm = $(nodeFormSelector); if (nodeForm.length) { // Do we have a URL slug field? var urlSlugField = $(nodeFormSelector + ' #edit-field-parapg-url-slug-und-0-value'); if (urlSlugField.length) { // Yes, we are Go. Add a watcher to add a data-manuallyEdited=yes // attribute if the field is changed. urlSlugField.data('manuallyEdited', 'no').blur(function() { $(this).data('manuallyEdited', 'yes'); }); // Get the node title field. var nodeTitleField = $(nodeFormSelector + ' #edit-title'); nodeTitleField.blur(function() { greyheadCopyNodeTitleToURLSlugField($(this).val(), urlSlugField); }); } } /** * Copy the node title to the menu title if the menu title field doesn't * have a data-manuallyEdited attribute. * * @param nodeTitle * @param menuTitleField */ function greyheadCopyNodeTitleToURLSlugField(nodeTitle, urlSlugField) { // Is the URL slug field empty? if (urlSlugField.data('manuallyEdited') !== 'yes') { var nodeTitleConverted = nodeTitle.replace(/\W/g, '').toLowerCase(); urlSlugField.val(nodeTitleConverted); } } } }; /** * If we're on an admin page, get the height of the admin toolbar and set the * body's top margin accordingly. */ Drupal.behaviors.greyheadCorrectBodyMarginForAdminMenu = { attach: function(context, settings) { if ($('body', context).hasClass('admin-menu')) { var height = $('#admin-menu').height(); if (!(height === null) && (height > 0)) { console.log('Setting body top-margin to ' + height + 'px.'); $('body', context).attr('style', 'margin-top: ' + $('#admin-menu').height() + 'px !important'); } } } }; })(jQuery, Drupal);
alexharries/greyhead_customisations
js/greyhead_customisations.js
JavaScript
gpl-3.0
2,442
/** * The main application class. An instance of this class is created by app.js when it * calls Ext.application(). This is the ideal place to handle application launch and * initialization details. */ Ext.define('Demo.Application', { extend: 'Ext.app.Application', name: 'Demo', stores: [ // TODO: add global / shared stores here ], launch: function () { // TODO - Launch the application }, onAppUpdate: function () { Ext.Msg.confirm('Application Update', 'This application has an update, reload?', function (choice) { if (choice === 'yes') { window.location.reload(); } } ); } });
chihchungyu/Demo
public/app/Application.js
JavaScript
gpl-3.0
739
/* YUI 3.4.1pr1 (build 4097) Copyright 2011 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('io-queue', function(Y) { /** Extends IO to implement Queue for synchronous transaction processing. @module io-base @submodule io-queue @for IO **/ var io = Y.io._map['io:0'] || new Y.IO(); Y.mix(Y.IO.prototype, { /** * Array of transactions queued for processing * * @property _q * @private * @static * @type {Object} */ _q: new Y.Queue(), _qActiveId: null, _qInit: false, /** * Property to determine whether the queue is set to * 1 (active) or 0 (inactive). When inactive, transactions * will be stored in the queue until the queue is set to active. * * @property _qState * @private * @static * @type {Number} */ _qState: 1, /** * Method Process the first transaction from the * queue in FIFO order. * * @method _qShift * @private * @static */ _qShift: function() { var io = this, o = io._q.next(); io._qActiveId = o.id; io._qState = 0; io.send(o.uri, o.cfg, o.id); }, /** * Method for queueing a transaction before the request is sent to the * resource, to ensure sequential processing. * * @method queue * @static * @return {Object} */ queue: function(uri, c) { var io = this, o = { uri: uri, cfg:c, id: this._id++ }; if(!io._qInit) { Y.on('io:complete', function(id, o) { io._qNext(id); }, io); io._qInit = true; } io._q.add(o); if (io._qState === 1) { io._qShift(); } Y.log('Object queued. Transaction id is' + o.id, 'info', 'io'); return o; }, _qNext: function(id) { var io = this; io._qState = 1; if (io._qActiveId === id && io._q.size() > 0) { io._qShift(); } }, /** * Method for promoting a transaction to the top of the queue. * * @method promote * @static */ qPromote: function(o) { this._q.promote(o); }, /** * Method for removing a specific, pending transaction from * the queue. * * @method remove * @private * @static */ qRemove: function(o) { this._q.remove(o); }, qStart: function() { var io = this; io._qState = 1; if (io._q.size() > 0) { io._qShift(); } Y.log('Queue started.', 'info', 'io'); }, /** * Method for setting queue processing to inactive. * Transaction requests to YUI.io.queue() will be stored in the queue, but * not processed until the queue is reset to "active". * * @method _stop * @private * @static */ qStop: function() { this._qState = 0; Y.log('Queue stopped.', 'info', 'io'); }, /** * Method to query the current size of the queue. * * @method _size * @private * @static * @return {Number} */ qSize: function() { return this._q.size(); } }, true); function _queue(u, c) { return io.queue.apply(io, [u, c]); } _queue.start = function () { io.qStart(); }; _queue.stop = function () { io.qStop(); }; _queue.promote = function (o) { io.qPromote(o); }; _queue.remove = function (o) { io.qRemove(o); }; _queue.size = function () { io.qSize(); }; Y.io.queue = _queue; }, '3.4.1pr1' ,{requires:['io-base','queue-promote']});
uhoreg/moodle
lib/yui/3.4.1pr1/build/io-queue/io-queue-debug.js
JavaScript
gpl-3.0
3,560
let weightDependency = new Tracker.Dependency; Template.productSettings.helpers({ hasSelectedProducts() { return this.products.length > 0; }, itemWeightActive: function (weight) { weightDependency.depend(); for (let product of this.products) { let position = product.position || {}; let currentWeight = position.weight || 0; if (currentWeight === weight) { return "active"; } } return ""; } }); Template.productSettingsGridItem.helpers({ displayPrice: function () { if (this._id) { return ReactionProduct.getProductPriceRange(this._id).range; } }, media: function () { const media = ReactionCore.Collections.Media.findOne({ "metadata.productId": this._id, "metadata.priority": 0, "metadata.toGrid": 1 }, { sort: { uploadedAt: 1 } }); return media instanceof FS.File ? media : false; }, additionalMedia: function () { const mediaArray = ReactionCore.Collections.Media.find({ "metadata.productId": this._id, "metadata.priority": { $gt: 0 }, "metadata.toGrid": 1 }, { limit: 3 }); if (mediaArray.count() > 1) { return mediaArray; } return false; }, weightClass: function () { weightDependency.depend(); let position = this.position || {}; let weight = position.weight || 0; switch (weight) { case 1: return "product-medium"; case 2: return "product-large"; default: return "product-small"; } }, isMediumWeight: function () { weightDependency.depend(); let position = this.position || {}; let weight = position.weight || 0; return weight === 1; }, isLargeWeight: function () { weightDependency.depend(); let position = this.position || {}; let weight = position.weight || 0; return weight === 3; }, shouldShowAdditionalImages: function () { weightDependency.depend(); if (this.isMediumWeight && this.mediaArray) { return true; } return false; } }); Template.productSettingsListItem.inheritsHelpersFrom("productSettingsGridItem"); /** * productExtendedControls events */ Template.productSettings.events({ "click [data-event-action=publishProduct]": function () { ReactionProduct.publishProduct(this.products); }, "click [data-event-action=cloneProduct]": function () { ReactionProduct.cloneProduct(this.products); }, "click [data-event-action=deleteProduct]": function () { ReactionProduct.maybeDeleteProduct(this.products); }, "click [data-event-action=changeProductWeight]": function (event) { event.preventDefault(); for (product of this.products) { let weight = $(event.currentTarget).data("event-data") || 0; let position = { tag: ReactionCore.getCurrentTag(), weight: weight, updatedAt: new Date() }; product.position = position; Meteor.call("products/updateProductPosition", product._id, position, function () { weightDependency.changed(); }); } } });
ScyDev/reaction
packages/reaction-product-variant/client/templates/products/productSettings/productSettings.js
JavaScript
gpl-3.0
3,087
import { curry, split, indexBy, path, prop, } from 'ramda'; import fetchUserInstallations from './fetchUserInstallations'; import fetchInstallationRepositories from './fetchInstallationRepositories'; export default curry((accessToken, repository) => { const [installationName] = split('/', repository); return fetchUserInstallations(accessToken) .then((installations) => { const byName = indexBy(path(['account', 'login']), installations); if (!byName[installationName]) { throw new Error('Not Found'); } return fetchInstallationRepositories(accessToken, byName[installationName].id); }) .then(repositories => { const byName = indexBy(prop(['full_name']), repositories); if (!byName[repository]) { throw new Error('Not Found'); } return byName[repository]; }); });
branch-bookkeeper/pina
src/lib/fetchRepository.js
JavaScript
gpl-3.0
959
import * as actions from '../../actions' import AppBar from 'material-ui/AppBar' import { connect } from 'react-redux' import Menu from 'material-ui/Menu' import MenuItem from 'material-ui/MenuItem' import MUIDrawer from 'material-ui/Drawer' import React, { PropTypes } from 'react' import { reset } from 'redux-form' import { toggleDrawer } from '../../actions' import { Link } from 'react-router' class Drawer extends React.Component { render() { return ( <MUIDrawer open={ this.props.isOpen } docked={ false } onRequestChange={ this.props.onDrawerToggle }> <AppBar title="Math4Kids" onLeftIconButtonTouchTap={ this.props.onDrawerToggle }/> <Menu onItemTouchTap={this.props.onItemTouchTap}> <MenuItem value="add" containerElement={<Link to='/'/>}>Dodawanie</MenuItem> <MenuItem value="substract" containerElement={<Link to='substract'/>}>Odejmowanie</MenuItem> <MenuItem value="multiply" containerElement={<Link to='multiply'/>}>Mnożenie</MenuItem> </Menu> </MUIDrawer> ); } } const mapStateToProps = (state) => { return { isOpen: state.drawer.open } } const mapDispatchToProps = (dispatch) => { return { onDrawerToggle: () => { dispatch(toggleDrawer()) }, onItemTouchTap: (event, menuItem, index) => { dispatch(reset('AddForm')); dispatch(reset('SubstractForm')); dispatch(reset('MultiplyForm')); dispatch(toggleDrawer()) switch (menuItem.props.value) { case "add" : return dispatch(actions.newAdd()) case "substract" : return dispatch(actions.newSubstract()) case "multiply" : return dispatch(actions.newMultiply()) default: return null } } } } Drawer.propTypes = { isOpen: PropTypes.bool.isRequired, onDrawerToggle: PropTypes.func.isRequired } export default connect(mapStateToProps, mapDispatchToProps)(Drawer)
gom3s/math4Kids
src/components/app/Drawer.js
JavaScript
gpl-3.0
2,173
"use strict"; const serversdb = require("../servers"); const hands = [":ok_hand::skin-tone-1:", ":ok_hand::skin-tone-2:", ":ok_hand::skin-tone-3:", ":ok_hand::skin-tone-4:", ":ok_hand::skin-tone-5:", ":ok_hand:"]; const hand = hands[Math.floor(Math.random() * hands.length)]; module.exports = { // eslint-disable-next-line no-unused-vars main: async function(bot, m, args, prefix) { var data = await serversdb.load(); var guild = m.channel.guild; if (!data[guild.id]) { data[guild.id] = {}; data[guild.id].name = guild.name; data[guild.id].owner = guild.ownerID; bot.createMessage(m.channel.id, `Server: ${guild.name} added to database. Populating information ${hand}`).then(function(msg) { return setTimeout(function() { bot.deleteMessage(m.channel.id, m.id, "Timeout"); bot.deleteMessage(m.channel.id, msg.id, "Timeout"); }, 5000); }); await serversdb.save(data); } if (!data[guild.id].art) { bot.createMessage(m.channel.id, `An art channel has not been set up for this server. Please have a mod add one using the command: \`${prefix}edit art add #channel\``).then(function(msg) { return setTimeout(function() { bot.deleteMessage(m.channel.id, msg.id, "Timeout"); bot.deleteMessage(m.channel.id, m.id, "Timeout"); }, 10000); }); return; } var index = 5000; if (args) { if (!isNaN(+args)) { index = args; } } var channel = data[guild.id].art; channel = bot.getChannel(channel); if (data[guild.id].art && !channel) { bot.createMessage(m.channel.id, `The selected art channel, <#${data[guild.id].art}>, has either been deleted, or I no longer have access to it. Please set the art channel to an existing channel that I have access to.`).then(function(msg) { return setTimeout(function() { bot.deleteMessage(m.channel.id, msg.id, "Timeout"); bot.deleteMessage(m.channel.id, m.id, "Timeout"); }, 15000); }); return; } var cName = channel.name; var gName = channel.guild.name; var icon = channel.guild.iconURL || null; if (channel.nsfw && !m.channel.nsfw) { bot.createMessage(m.channel.id, `The selected art channel, <#${channel.id}>, is an nsfw channel, and this channel is not. Please either use this command in an nsfw channel, or set the art channel to a non-nsfw channel`).then(function(msg) { return setTimeout(function() { bot.deleteMessage(m.channel.id, msg.id, "Timeout"); bot.deleteMessage(m.channel.id, m.id, "Timeout"); }, 10000); }); return; } channel = channel.id; if (index > 7000) { bot.createMessage(m.channel.id, "I can't grab more than 7000 messages in any channel. Setting limit to 7000").then(function(msg) { return setTimeout(function() { bot.deleteMessage(m.channel.id, msg.id, "Timeout"); }, 5000); }); index = 7000; } await bot.sendChannelTyping(m.channel.id); var msgs = await bot.getMessages(channel, parseInt(index, 10)); var art = {}; for (var msg of msgs) { if (msg.content.includes("pastebin.com")) { art[msg.content] = [msg.author.id, msg.timestamp]; } if (msg.attachments[0]) { art[msg.attachments[0].url] = [msg.author.id, msg.timestamp]; } if (msg.embeds[0]) { if (msg.embeds[0].image) { art[msg.embeds[0].image.url] = [msg.author.id, msg.timestamp]; } if (!msg.embeds[0].image) { art[msg.embeds[0].url] = [msg.author.id, msg.timestamp]; } } } var number = Math.floor(Math.random() * Object.entries(art).length); var list = Object.entries(art); var chosen = list[number]; console.log(chosen); if (!chosen) { bot.createMessage(m.channel.id, `No art was found within the last \`${index}\` messages. Please try again using more messages`).then(function(msg) { return setTimeout(function() { bot.deleteMessage(m.channel.id, msg.id, "Timeout"); bot.deleteMessage(m.channel.id, m.id, "Timeout"); }, 5000); }); return; } var author = m.channel.guild.members.get(chosen[1][0]) || m.channel.guild.members.get(chosen[1][0]) || bot.users.get(chosen[1][0]); var url = author.avatarURL || undefined; author = author.nick || author.username; var time = new Date(chosen[1][1]).toISOString(); if (chosen[0].includes("pastebin.com")) { const data = { "embed": { "color": 0xA260F6, "title": chosen[0], "description": `A random piece from <#${channel}>~`, "url": chosen[0], "timestamp": time, "author": { "name": author, "icon_url": url }, "footer": { "icon_url": icon, "text": `${cName} | ${gName}` } } }; bot.createMessage(m.channel.id, data); return; } else { const data = { "embed": { "color": 0xA260F6, "timestamp": time, "description": `A random piece from <#${channel}>~`, "image": { "url": chosen[0] }, "author": { "name": author, "icon_url": url }, "footer": { "icon_url": icon, "text": `${cName} | ${gName}` } } }; bot.createMessage(m.channel.id, data); } return; }, help: "Show art from the set art channel" // add description };
LaChocola/Mei
commands/art.js
JavaScript
gpl-3.0
6,637
var ALLOWED_VARIANCE = 0.05; /* Nested model forms BEGIN */ function inspect (obj) { var str; for(var i in obj) str+=i+";\n" //str+=i+"="+obj[i]+";\n" alert(str); } function remove_fields(link) { $(link).prev("input[type=hidden]").val("1"); $(link).closest(".fields").hide(); //$(link).parent().next().hide(); if ($(link).hasClass('totals_callback')) { updateTotalValuesCallback(link); } }; function add_fields(link, association, content) { // before callback before_add_fields_callback(association); var new_id = new Date().getTime(); var regexp = new RegExp("new_" + association, "g") if (association === 'in_flows' || association === 'implementer_splits' ) { $(link).parents('tr:first').before(content.replace(regexp, new_id)); } else { $(link).parent().before(content.replace(regexp, new_id)); } after_add_fields_callback(association); }; //prevents non-numeric characters to be entered in the input field var numericInputField = function (input) { $(input).keydown(function(event) { // Allow backspace and delete, enter and tab var bksp = 46; var del = 8; var enter = 13; var tab = 9; if ( event.keyCode == bksp || event.keyCode == del || event.keyCode == enter || event.keyCode == tab ) { // let it happen, don't do anything } else { // Ensure that it is a number or a '.' and stop the keypress var period = 190; if ((event.keyCode >= 48 && event.keyCode <= 57 ) || event.keyCode == period || event.keyCode >= 37 && event.keyCode <= 40) { // let it happen } else { event.preventDefault(); }; }; }); } var observeFormChanges = function (form) { var catcher = function () { var changed = false; if ($(form).data('initialForm') != $(form).serialize()) { changed = true; } if (changed) { return 'You have unsaved changes!'; } }; if ($(form).length) { //# dont bind unless you find the form element on the page $('input[type=submit]').click(function (e) { $(form).data('initialForm', $(form).serialize()); }); $(form).data('initialForm', $(form).serialize()); $(window).bind('beforeunload', catcher); }; } var build_activity_funding_source_row = function (edit_block) { var organization = edit_block.find('.ff_organization option:selected').text(); var spend = ''; var budget = ''; spend = $('<li/>').append( $('<span/>').text('Expenditure'), edit_block.find('.ff_spend').val() || 'N/A' ) budget = $('<li/>').append( $('<span/>').text('Current Budget'), edit_block.find('.ff_budget').val() || 'N/A' ) return $('<ul/>').append( $('<li/>').append( $('<span/>').text('Funder'), organization || 'N/A' ), spend, budget ) }; var close_activity_funding_sources_fields = function (fields) { $.each(fields, function () { var element = $(this); var edit_block = element.find('.edit_block'); var preview_block = element.find('.preview_block'); var manage_block = element.find('.manage_block'); edit_block.hide(); preview_block.html(''); preview_block.append(build_activity_funding_source_row(edit_block)) preview_block.show(); manage_block.find('.edit_button').remove(); manage_block.prepend( $('<a/>').attr({'class': 'edit_button', 'href': '#'}).text('Edit') ) }); }; var before_add_fields_callback = function (association) { if (association === 'funding_sources') { close_activity_funding_sources_fields($('.funding_sources .fields')); } }; var after_add_fields_callback = function (association) { // show the jquery autocomplete combobox instead of // standard dropdowns $( ".js_combobox" ).combobox(); }; /* Nested model forms END */ /* Ajax CRUD BEGIN */ var getRowId = function (element) { return element.parents('tr').attr('id'); }; var getResourceId = function (element) { return Number(getRowId(element).match(/\d+/)[0]); }; var getResourceName = function (element) { return element.parents('.resources').attr("data-resource"); }; var getForm = function (element) { return element.parents('form'); }; var addNewForm = function (resources, data) { resources.find('.placer').html(data); }; var addEditForm = function (rowId, data) { $('#' + rowId).html('<td colspan="100">' + data + '</td>').addClass("edit_row"); }; var updateCount = function (resources) { var count = resources.find('tbody tr').length; resources.find('.count').html(count); } var addNewRow = function (resources, data) { resources.find('tbody').prepend(data); enableElement(resources.find('.new_btn')); updateCount(resources); var newRow = $(resources.find('tbody tr')[0]); newRow.find(".rest_in_place").rest_in_place(); // inplace edit }; var addExistingRow = function (rowId, data) { var row = $('#' + rowId); row.replaceWith(data) var newRow = $('#' + rowId); newRow.find(".rest_in_place").rest_in_place(); // inplace edit }; var addSearchForm = function (element) { if (element.hasClass('enabled')) { disableElement(element); var resourceName = getResourceName(element); $.get(resourceName + '/search.js', function (data) { $('#placer').prepend(data); }); } } var closeForm = function (element) { element.parents('.form_box').remove(); }; var disableElement = function (element) { element.removeClass('enabled').addClass('disabled'); }; var enableElement = function (element) { element.removeClass('disabled').addClass('enabled'); }; var buildUrl = function (url) { var parts = url.split('?'); if (parts.length > 1) { return parts.join('.js?'); } else { return parts[0] + '.js'; } }; var buildJsonUrl = function (url) { var parts = url.split('?'); if (parts.length > 1) { return parts.join('.json?'); } else { return parts[0] + '.json'; } }; var getResources = function (element) { return element.parents('.resources'); } var newResource = function (element) { if (element.hasClass('enabled')) { var resources = getResources(element); disableElement(element); $.get(buildUrl(element.attr('href')), function (data) { addNewForm(resources, data); }); } }; var replaceTable = function (data) { $("#main_table").replaceWith(data); $("#main_table").find(".rest_in_place").rest_in_place(); // inplace edit }; var searchResources = function (element, type) { var resourceName = getResourceName(element); var form = getForm(element); var q = (type === "reset") ? '' : form.find("#s_q").val(); $.get(resourceName + '.js?q=' + q, function (data) { replaceTable(data); if (type === "reset") { closeForm(element); enableElement($(".search_btn")); } }); }; var editResource = function (element) { var rowId = getRowId(element); $.get(buildUrl(element.attr('href')), function (data) { addEditForm(rowId, data); }); }; var updateResource = function (element) { var rowId = getRowId(element); var form = getForm(element); $.post(buildUrl(form.attr('action')), form.serialize(), function (data, status, response) { closeForm(element); response.status === 206 ? addEditForm(rowId, data) : addExistingRow(rowId, data); }); }; var createResource = function (element) { var form = getForm(element); var resources = getResources(element); $.post(buildUrl(form.attr('action')), form.serialize(), function (data, status, response) { closeForm(element); response.status === 206 ? addNewForm(resources, data) : addNewRow(resources, data); }); }; var showResource = function (element) { var rowId = getRowId(element); var resourceId = getResourceId(element) $.get(element.attr('href') + '/' + resourceId + '.js', function (data) { closeForm(element); addExistingRow(rowId, data); }); }; var destroyResource = function (element) { var rowId = getRowId(element); var resources = getResources(element); $.post(element.attr('href').replace('/delete', '') + '.js', {'_method': 'delete'}, function (data) { removeRow(resources, rowId); }); }; var sortResources = function (element) { var link = element.find('a'); var resourceName = getResourceName(element); var url = resourceName + '.js?' + link.attr('href').replace(/.*\?/, ''); $.get(url, function (data) { replaceTable(data); }); } var getFormType = function (element) { // new_form => new; edit_form => edit return element.parents('.form_box').attr('class').replace(/form_box /, '').split('_')[0]; } var ajaxifyResources = function (resources) { var block = $(".resources[data-resources='" + resources + "']"); var newBtn = block.find(".new_btn"); var editBtn = block.find(".edit_btn"); var cancelBtn = block.find(".cancel_btn"); var searchBtn = block.find(".search_btn"); var submitBtn = block.find(".js_submit_comment_btn"); var destroyBtn = block.find(".destroy_btn"); // new newBtn.live('click', function (e) { e.preventDefault(); var element = $(this); newResource(element); }); // edit editBtn.live('click', function (e) { e.preventDefault(); var element = $(this); editResource(element); }); // cancel cancelBtn.live('click', function (e) { e.preventDefault(); var element = $(this); var formType = getFormType(element); if (formType === "new") { closeForm(element); enableElement(newBtn); } else if (formType === "edit") { showResource(element); } else if (formType === "search") { closeForm(element); enableElement(searchBtn); } else { throw "Unknown form type:" + formType; } }); // submit submitBtn.live('click', function (e) { e.preventDefault(); var element = $(this); var formType = getFormType(element); if (formType === "new") { createResource(element); } else if (formType === "edit") { updateResource(element); } else if (formType === "search") { searchResources(element); } else { throw "Unknown form type: " + formType; } }); // destroy destroyBtn.live('click', function (e) { e.preventDefault(); var element = $(this); if (confirm('Are you sure?')) { destroyResource(element); } }); }; /* Ajax CRUD END */ var collapse_expand = function (e, element, type) { // if target element is link or the user is selecting text, skip collapsing if (e.target.nodeName === 'A' || window.getSelection().toString() !== "") { return; } var next_element = element.next('.' + type + '.entry_main'); var next_element_visible = next_element.is(':visible'); $('.' + type + '.entry_main').hide(); $('.' + type + '.entry_header').removeClass('active'); if (next_element_visible) { next_element.hide(); } else { element.addClass('active'); next_element.show(); } }; var getRowId = function (element) { return element.parents('tr').attr('id'); }; var getResourceName = function (element) { return element.parents('.resources').attr("data-resources"); }; var getResourceId = function (element) { return Number(getRowId(element).match(/\d+/)[0]); }; var removeRow = function (resources, rowId) { resources.find("#" + rowId).remove(); updateCount(resources); }; var updateTotalValuesCallback = function (el) { updateTotalValue($(el).parents('tr').find('.js_spend')); updateTotalValue($(el).parents('tr').find('.js_budget')); }; var getFieldsTotal = function (fields) { var total = 0; for (var i = 0; i < fields.length; i++) { if (!isNaN(fields[i].value)) { total += Number(fields[i].value); } } return total; } var updateTotalValue = function (el) { if ($(el).hasClass('js_spend')) { if ($(el).parents('table').length) { // table totals var table = $(el).parents('table'); var input_fields = table.find('input.js_spend:visible'); var total_field = table.find('.js_total_spend .amount'); } else { // classifications tree totals var input_fields = $(el).parents('.activity_tree').find('> li > div input.js_spend'); var total_field = $('.js_total_spend .amount'); } } else if ($(el).hasClass('js_budget')) { if ($(el).parents('table').length) { // table totals var table = $(el).parents('table'); var input_fields = table.find('input.js_budget:visible'); var total_field = table.find('.js_total_budget .amount'); } else { // classifications tree totals var input_fields = $(el).parents('.activity_tree').find('> li > div input.js_budget'); var total_field = $('.js_total_budget .amount'); } } else { throw "Element class not valid"; } var fieldsTotal = getFieldsTotal(input_fields); total_field.html(fieldsTotal.toFixed(2)); }; var dynamicUpdateTotalsInit = function () { $('.js_spend, .js_budget').live('keyup', function () { updateTotalValue(this); }); }; var admin_responses_index = { run: function () { // destroy $(".destroy_btn").live('click', function (e) { e.preventDefault(); var element = $(this); if (confirm('Are you sure?')) { destroyResource(element); } }); } }; var admin_responses_empty = { run: function () { // destroy $(".destroy_btn").live('click', function (e) { e.preventDefault(); var element = $(this); if (confirm('Are you sure?')) { destroyResource(element); } }); } }; var getOrganizationInfo = function (organization_id, box) { if (organization_id) { $.get(organization_id + '.js', function (data) { box.find('.placer').html(data); }); } }; var displayFlashForReplaceOrganization = function (type, message) { $('#content .wrapper').prepend( $('<div/>').attr({id: 'flashes'}).append( $('<div/>').attr({id: type}).text(message) ) ); // fade out flash message $("#" + type).delay(5000).fadeOut(3000, function () { $("#flashes").remove(); }); } var removeOrganizationFromLists = function (duplicate_id, box_type) { $.each(['duplicate', 'target'], function (i, name) { var select_element = $("#" + name + "_organization_id"); var current_option = select_element.find("option[value='" + duplicate_id + "']"); // remove element from page if (name === box_type) { var next_option = current_option.next().val(); if (next_option) { select_element.val(next_option); // update info block getOrganizationInfo(select_element.val(), $('#' + name)); } else { $('#' + name).html('') } } current_option.remove(); }); } var ReplaceOrganizationSuccessCallback = function (message, duplicate_id) { removeOrganizationFromLists(duplicate_id, 'duplicate'); displayFlashForReplaceOrganization('notice', message); }; var ReplaceOrganizationErrorCallback = function (message) { displayFlashForReplaceOrganization('error', message) } var replaceOrganization = function (form) { var duplicate_id = $("#duplicate_organization_id").val(); $.post(buildUrl(form.attr('action')), form.serialize(), function (data, status, response) { var data = $.parseJSON(data) response.status === 206 ? ReplaceOrganizationErrorCallback(data.message) : ReplaceOrganizationSuccessCallback(data.message, duplicate_id); }); }; var admin_organizations_duplicate = { run: function () { $("#duplicate_organization_id, #target_organization_id").change(function() { var organization_id = $(this).val(); var type = $(this).parents('.box').attr('data-type'); var box = $('#' + type); // type = duplicate; target getOrganizationInfo(organization_id, box); }); getOrganizationInfo($("#duplicate_organization_id").val(), $('#duplicate')); getOrganizationInfo($("#target_organization_id").val(), $('#target')); $("#replace_organization").click(function (e) { e.preventDefault(); var element = $(this); var form = element.parents('form') if (confirm('Are you sure?')) { replaceOrganization(form); } }); } }; var admin_responses_show = { run: function (){ build_data_response_review_screen(); ajaxifyResources('comments'); } }; var reports_index = { run: function () { ajaxifyResources('comments'); drawPieChart('code_spent', _code_spent_values, 450, 300); drawPieChart('code_budget', _code_budget_values, 450, 300); } }; var responses_review = { run: function () { build_data_response_review_screen(); ajaxifyResources('comments'); } }; var activity_classification = function () { /* * Adds collapsible checkbox tree functionality for a tab and validates classification tree * @param {String} tab * */ var addCollabsibleButtons = function (tab) { $('.' + tab + ' ul.activity_tree').collapsibleCheckboxTree({tab: tab}); $('.' + tab + ' ul.activity_tree').validateClassificationTree(); }; //collapsible checkboxes for tab1 var mode = document.location.search.split("=")[1] if (mode != 'locations') { addCollabsibleButtons('tab1'); } checkRootNodes('budget'); checkRootNodes('spend'); checkAllChildren(); showSubtotalIcons(); $('.js_upload_btn').click(function (e) { e.preventDefault(); $(this).parents('.upload').find('.upload_box').toggle(); }); $('.js_submit_btn').click(function (e) { var ajaxLoader = $(this).closest('ol').find('.ajax-loader'); ajaxLoader.show(); checkRootNodes('spend'); checkRootNodes('budget'); if ($('.invalid_node').size() > 0){ e.preventDefault(); alert('The classification tree could not be saved. Please correct all errors and try again') ajaxLoader.hide(); }; }); $('#js_budget_to_spend').click(function (e) { e.preventDefault(); if ($(this).find('img').hasClass('approved')) { alert('Classifications for an approved activity cannot be changed'); } else if (confirm('This will overwrite all Past Expenditure percentages with the Current Budget percentages. Are you sure?')) { $('.js_budget input').each(function () { var element = $(this); element.parents('.js_values').find('.js_spend input').val(element.val()); }); checkRootNodes('spend'); checkAllChildren(); }; }); $('#js_spend_to_budget').click(function (e) { e.preventDefault(); if ($(this).find('img').hasClass('approved')) { alert('Classifications for an approved activity cannot be changed'); } else if (confirm('This will overwrite all Current Budget percentages with the Past Expenditure percentages. Are you sure?')) { $('.js_spend input').each(function () { var element = $(this); element.parents('.js_values').find('.js_budget input').val(element.val()); }); checkRootNodes('budget'); checkAllChildren(); }; }); $(".percentage_box").keyup(function(event) { var element = $(this); var isSpend = element.parents('div:first').hasClass('spend') var type = (isSpend) ? 'spend' : 'budget'; var childLi = element.parents('li:first').children('ul:first').children('li'); updateSubTotal(element); updateTotalValue(element); if (element.val().length == 0 && childLi.size() > 0) { clearChildNodes(element, event, type); } var period = 190; var bksp = 46; var del = 8; //update parent nodes if: numeric keys, backspace/delete, period or undefined (i.e. called from another function) if (typeof event.keyCode == 'undefined' || (event.keyCode >= 48 && event.keyCode <= 57 ) || event.keyCode == period || event.keyCode == del || event.keyCode == bksp || event.keyCode >= 37 && event.keyCode <= 40){ updateParentNodes(element, type) } //check whether children (1 level deep) are equal to my total if (childLi.size() > 0){ compareChildrenToParent(element, type); }; //check whether root nodes are = 100% checkRootNodes(type); }); numericInputField(".percentage_box, .js_spend, .js_budget"); var updateParentNodes = function(element, type){ type = '.' + type + ':first' var parentElement = element.parents('ul:first').prev('div:first').find(type).find('input'); var siblingLi = element.parents('ul:first').children('li'); var siblingValue = 0; var siblingTotal = 0; siblingLi.each(function (){ siblingValue = parseFloat($(this).find(type).find('input:first').val()); if ( !isNaN(siblingValue) ) { siblingTotal = siblingTotal + siblingValue; };  }); if ( siblingTotal !== 0 ) { parentElement.val(siblingTotal); parentElement.trigger('keyup'); } } var clearChildNodes = function(element, event, type){ var bksp = 46; var del = 8; type = '.' + type + ':first' if ( (event.keyCode == bksp || event.keyCode == del) ){ childNodes = element.parents('li:first').children('ul:first').find('li').find(type).find('input'); var childTotal = 0; childNodes.each(function (){ childValue = parseFloat($(this).val()) if (!isNaN(childValue)) { childTotal = childTotal + childValue }; }); if ( childTotal > 0 && confirm('Would you like to clear the value of all child nodes?') ){ childNodes.each(function(){ if ( $(this).val !== '' ){ $(this).val(' '); updateSubTotal($(this)); } }); } } } var updateSubTotal = function(element){ var activity_budget = parseFloat(element.parents('ul:last').attr('activity_budget')); var activity_spend = parseFloat(element.parents('ul:last').attr('activity_spend')); var activity_currency = element.parents('ul:last').attr('activity_currency'); var elementValue = parseFloat(element.val()); var subtotal = element.siblings('.subtotal_icon'); var isSpend = element.parents('div:first').hasClass('spend') if ( elementValue > 0 ){ subtotal.removeClass('hidden') subtotal.attr('title', (isSpend ? activity_spend : activity_budget * (elementValue/100)).toFixed(2) + ' ' + activity_currency); } else { subtotal.attr('title',''); subtotal.addClass('hidden'); } }; } var checkAllChildren = function(){ var inputs = $('.percentage_box') inputs.each(function(){ if ( $(this).val !== '' ){ var type = $(this).hasClass('js_spend') ? 'spend' : 'budget' compareChildrenToParent($(this), type); } }); } var compareChildrenToParent = function(parentElement, type){ var childValue = 0; var childTotal = 0; var childLi = parentElement.parents('li:first').children('ul:first').children('li'); type = '.' + type + ':first' childLi.each(function (){ childValue = parseFloat($(this).find(type).find('input:first').val()) if (!isNaN(childValue)) { childTotal = childTotal + childValue }; }); var parentValue = parseFloat(parentElement.val()).toFixed(2) childTotal = childTotal.toFixed(2) if ( (Math.abs(childTotal - parentValue) > ALLOWED_VARIANCE) && childTotal > 0){ parentElement.addClass('invalid_node tooltip') var message = "This amount is not the same as the sum of the amounts underneath (" ; message += parentValue + "% - " + childTotal + "% = " + (parentValue - childTotal) + "%)"; parentElement.attr('original-title', message) ; } else { parentElement.removeClass('invalid_node tooltip') }; }; var checkRootNodes = function(type){ var topNodes = $('.activity_tree').find('li:first').siblings().andSelf(); var total = 0; var value = 0; type = '.' + type + ':first' topNodes.each(function(){ value = $(this).find(type).find('input').val(); if (!isNaN(parseFloat(value))){ total += parseFloat($(this).find(type).find('input').val()); }; }); $('.totals').find(type).find('.amount').html(total); if ( (Math.abs(total - 100.00) > ALLOWED_VARIANCE) && total > 0){ topNodes.each(function(){ rootNode = $(this).find(type).find('input'); if (rootNode.val().length > 0 && (!(rootNode.hasClass('invalid_node tooltip')))){ rootNode.addClass('invalid_node tooltip'); } var message = "The root nodes do not add up to 100%"; rootNode.attr('original-title', message) ; }); } else { topNodes.each(function(){ rootNode = $(this).find(type).find('input'); if (rootNode.attr('original-title') != undefined && rootNode.attr('original-title') == "The root nodes do not add up to 100%"){ rootNode.removeClass('invalid_node tooltip'); rootNode.attr('original-title', '') } }); }; }; var showSubtotalIcons = function(){ $('.tab1').find('.percentage_box').each(function(){ if ($(this).val().length > 0) { $(this).siblings('.subtotal_icon').removeClass('hidden') } }); } var update_use_budget_codings_for_spend = function (e, activity_id, checked) { if (!checked || checked && confirm('All your expenditure codings will be deleted and replaced with copies of your budget codings, adjusted for the difference between your budget and spend. Your expenditure codings will also automatically update if you change your budget codings. Are you sure?')) { $.post( "/activities/" + activity_id + "/use_budget_codings_for_spend", { checked: checked, "_method": "put" }); } else { e.preventDefault(); } }; var data_responses_review = { run: function () { $(".use_budget_codings_for_spend").click(function (e) { var checked = $(this).is(':checked'); activity_id = Number($(this).attr('id').match(/\d+/)[0], 10); update_use_budget_codings_for_spend(e, activity_id, checked); }) } } var responses_submit = { run: function () { $(".collapse").click(function(e){ e.preventDefault(); var row_id = $(this).attr('id'); $("." + row_id).slideToggle("fast"); var row = row_id.split("_", 3); var img = $(this).attr('img'); var image = row_id + "_image"; var source = $('.'+image).attr('src'); var split = source.split("?", 1); if (split == "/images/icon_expand.png") { $('.' + image).attr('src', "/images/icon_collapse.png"); } else { $('.' + image).attr('src', "/images/icon_expand.png"); } }); } } function drawPieChart(id, data_rows, width, height) { if (typeof(data_rows) === "undefined") { return; } var data = new google.visualization.DataTable(); data.addColumn('string', data_rows.names.column1); data.addColumn('number', data_rows.names.column2); data.addRows(data_rows.values.length); for (var i = 0; i < data_rows.values.length; i++) { var value = data_rows.values[i]; data.setValue(i, 0, value[0]); data.setValue(i, 1, value[1]); }; var chart = new google.visualization.PieChart(document.getElementById(id)); chart.draw(data, {width: width, height: height, chartArea: {width: 360, height: 220}}); }; var reports_districts_show = reports_countries_show = { run: function () { drawPieChart('budget_i_pie', _budget_i_values, 400, 250); drawPieChart('spend_i_pie', _spend_i_values, 400, 250); } }; var reports_districts_classifications = reports_countries_classifications = { run: function () { if (_pie) { drawPieChart('code_spent', _code_spent_values, 450, 300); drawPieChart('code_budget', _code_budget_values, 450, 300); } else { drawTreemapChart('code_spent', _code_spent_values, 'w'); drawTreemapChart('code_budget', _code_budget_values, 'e'); } } } var reports_districts_activities_show = { run: function () { drawPieChart('spent_pie', _spent_pie_values, 450, 300); drawPieChart('budget_pie', _budget_pie_values, 450, 300); drawPieChart('code_spent', _code_spent_values, 450, 300); drawPieChart('code_budget', _code_budget_values, 450, 300); } }; var admin_currencies_index = { run: function () { $(".currency_label").live("click", function () { var element = $(this); var id = element.attr('id'); element.hide(); element.parent('td').append($("<input id=\'" + id + "\' class=\'currency\' />")); }); $(".currency").live('focusout', function () { element = $(this); var input_rate = element.val(); var url = "/admin/currencies/" + element.attr('id'); $.post(url, { "rate" : input_rate, "_method" : "put" }, function(data){ var data = $.parseJSON(data); if (data.status == 'success'){ element.parent('td').children('span').show(); element.parent('td').children('span').text(data.new_rate); element.hide(); } }); }); } } var reports_districts_activities_index = { run: function () { drawPieChart('spent_pie', _spent_pie_values, 450, 300); drawPieChart('budget_pie', _budget_pie_values, 450, 300); } }; var reports_districts_organizations_index = { run: function () { drawPieChart('spent_pie', _spent_pie_values, 450, 300); drawPieChart('budget_pie', _budget_pie_values, 450, 300); } }; var reports_districts_organizations_show = { run: function () { drawPieChart('code_spent', _code_spent_values, 450, 300); drawPieChart('code_budget', _code_budget_values, 450, 300); } }; var reports_countries_organizations_index = { run: function () { drawPieChart('spent_pie', _spent_pie_values, 450, 300); drawPieChart('budget_pie', _budget_pie_values, 450, 300); } }; var reports_countries_organizations_show = { run: function () { drawPieChart('code_spent', _code_spent_values, 450, 300); drawPieChart('code_budget', _code_budget_values, 450, 300); } }; var reports_countries_activities_index = { run: function () { drawPieChart('spent_pie', _spent_pie_values, 450, 300); drawPieChart('budget_pie', _budget_pie_values, 450, 300); } }; var reports_countries_activities_show = { run: function () { drawPieChart('code_spent', _code_spent_values, 450, 300); drawPieChart('code_budget', _code_budget_values, 450, 300); } }; var validateDates = function (startDate, endDate) { var checkDates = function (e) { var element = $(e.target); var d1 = new Date(startDate.val()); var d2 = new Date(endDate.val()); // remove old errors startDate.parent('li').find('.inline-errors').remove(); endDate.parent('li').find('.inline-errors').remove(); if (startDate.length && endDate.length && d1 >= d2) { if (startDate.attr('id') == element.attr('id')) { message = "Start date must come before End date."; } else { message = "End date must come after Start date."; } element.parent('li').append( $('<p/>').attr({"class": "inline-errors"}).text(message) ); } }; startDate.live('change', checkDates); endDate.live('change', checkDates); }; var commentsInit = function () { initDemoText($('*[data-hint]')); focusDemoText($('*[data-hint]')); blurDemoText($('*[data-hint]')); var removeInlineErrors = function (form) { form.find('.inline-errors').remove(); // remove inline error if present } $('.js_reply').live('click', function (e) { e.preventDefault(); var element = $(this); element.parents('li:first').find('.js_reply_box:first').show(); }) $('.js_cancel_reply').live('click', function (e) { e.preventDefault(); var element = $(this); element.parents('.js_reply_box:first').hide(); removeInlineErrors(element.parents('form')); }) // remove demo text when submiting comment $('.js_submit_comment_btn').live('click', function (e) { e.preventDefault(); removeDemoText($('*[data-hint]')); var element = $(this); if (element.hasClass('disabled')) { return; } var form = element.parents('form'); var block; var ajaxLoader = element.parent('li').nextAll('.ajax-loader'); element.addClass('disabled'); ajaxLoader.show(); $.post(buildJsonUrl(form.attr('action')), form.serialize(), function (data, status, response) { ajaxLoader.hide(); element.removeClass('disabled'); if (response.status === 206) { form.replaceWith(data.html) } else { if (form.find('#comment_parent_id').length) { // comment reply block = element.parents('li.comment_item:first'); if (block.find('ul').length) { block.find('ul').prepend(data.html); } else { block.append($('<ul/>').prepend(data.html)); } } else { // root comment block = $('ul.js_comments_list'); block.prepend(data.html) } } initDemoText(form.find('*[data-hint]')); removeInlineErrors(form); form.find('textarea').val(''); // reset comment value to blank form.find('.js_cancel_reply').trigger('click'); // close comment block }); }); } var dropdown = { // find the dropdown menu relative to the current element menu: function(element){ return element.parents('.js_dropdown_menu'); }, toggle_on: function (menu_element) { menu_element.find('.menu_items').slideDown(100); menu_element.addClass('persist'); }, toggle_off: function (menu_element) { menu_element.find('.menu_items').slideUp(100); menu_element.removeClass('persist'); } }; var projects_index = { run: function () { // use click() not toggle() here, as toggle() doesnt // work when menu items are also toggling it $('.js_project_row').hover( function(e){ $(this).find('.js_am_approve').show(); }, function(e){ $(this).find('.js_am_approve').fadeOut(300); } ); $('.js_dropdown_trigger').click(function (e){ e.preventDefault(); menu = dropdown.menu($(this)); if (!menu.is('.persist')) { dropdown.toggle_on(menu); } else { dropdown.toggle_off(menu); }; }); $('.js_dropdown_menu .menu_items a').click(function (e){ menu = dropdown.menu($(this)); dropdown.toggle_off(menu); $(this).click; // continue with desired click action }); $('.js_upload_btn').click(function (e) { e.preventDefault(); $(this).parents('tbody').find('.upload_box').slideToggle(); }); $('#import_export').click(function (e) { e.preventDefault(); $('#import_export_box .upload_box').slideToggle(); }); $('.tooltip_projects').tipsy({gravity: $.fn.tipsy.autoWE, live: true, html: true}); commentsInit(); approveBudget(); $('.js_address').address(function() { return 'new_' + $(this).html().toLowerCase(); }); $.address.externalChange(function() { var hash = $.address.path(); if (hash == '/'){ if (!($('#projects_listing').is(":visible"))){ $('.js_toggle_projects_listing').click(); } } else { if (hash == '/new_project'){ hideAll(); $('#new_project_form').fadeIn(); validateDates($('.start_date'), $('.end_date')); }else if (hash == '/new_activity'){ hideAll(); $('#new_activity_form').fadeIn(); activity_form(); } else if (hash == '/new_other cost'){ hideAll(); $('#new_other_cost_form').fadeIn(); } }; }); $('.js_toggle_project_form').click(function (e) { e.preventDefault(); hideAll(); $('#new_project_form').fadeIn(); $('#new_project_form #project_name').focus(); }); $('.js_toggle_activity_form').click(function (e) { e.preventDefault(); hideAll(); $('#new_activity_form').fadeIn(); $('#new_activity_form #activity_name').focus(); activity_form(); }); $('.js_toggle_other_cost_form').click(function (e) { e.preventDefault(); hideAll(); $('#new_other_cost_form').fadeIn(); $('#new_other_cost_form #other_cost_name').focus(); }); $('.js_toggle_projects_listing').click(function (e) { e.preventDefault(); hideAll(); $.address.path('/'); $( "form" )[ 0 ].reset() $('#projects_listing').fadeIn(); $("html, body").animate({ scrollTop: 0 }, 0); }); dynamicUpdateTotalsInit(); numericInputField(".js_spend, .js_budget"); } }; var hideAll = function() { $('#projects_listing').hide(); $('#new_project_form').hide(); $('#new_activity_form').hide(); $('#new_other_cost_form').hide(); $('.js_total_budget .amount, .js_total_spend .amount').html(0); }; var initDemoText = function (elements) { elements.each(function(){ var element = $(this); var demo_text = element.attr('data-hint'); if (demo_text != null) { element.attr('title', demo_text); if (element.val() == '' || element.val() == demo_text) { element.val( demo_text ); element.addClass('input_hint'); } } }); }; var focusDemoText = function (elements) { elements.live('focus', function(){ var element = $(this); var demo_text = element.attr('data-hint'); if (demo_text != null) { if (element.val() == demo_text) { element.val(''); element.removeClass('input_hint'); } } }); }; var removeDemoText = function (elements) { elements.each(function () { var element = $(this); var demo_text = element.attr('data-hint'); if (demo_text != null) { if (element.val() == demo_text) { element.val(''); } } }); }; var blurDemoText = function (elements) { elements.live('blur', function(){ var element = $(this); var demo_text = element.attr('data-hint'); if (demo_text != null) { if (element.val() == '') { element.val( demo_text ); element.addClass('input_hint'); } } }); }; var toggle_collapsed = function (elem, indicator) { var is_visible = elem.is(':visible'); if (is_visible) { indicator.removeClass('collapsed'); } else { indicator.addClass('collapsed'); }; }; var unsaved_warning = function () { return 'You have projects that have not been saved. Saved projects show a green checkmark next to them. Are you sure you want to leave this page?' }; var projects_import = { run: function () { $('.activity_box .header').live('click', function (e) { e.preventDefault(); var activity_box = $(this).parents('.activity_box'); //collapse the others, in an accordion style $.each($.merge(activity_box.prevAll('.activity_box'), activity_box.nextAll('.activity_box')), function () { $(this).find('.main').hide(); toggle_collapsed($(this).find('.main'), $(this).find('.header span')); }); activity_box.find('.main').toggle(); toggle_collapsed(activity_box.find('.main'), activity_box.find('.header span')); }); $('.header:first').trigger('click'); // expand the first one on page load $(window).bind('beforeunload',function (e) { if ($('.js_unsaved').length > 0) { return unsaved_warning(); } }); $('.save_btn').live('click', function (e) { e.preventDefault(); var element = $(this); var form = element.parents('form'); var ajaxLoader = element.next('.ajax-loader'); var activity_box = element.parents('.activity_box'); ajaxLoader.show(); $.post(buildUrl(form.attr('action')), form.serialize(), function (data) { activity_box.html(data.html); activity_box.find(".js_combobox").combobox(); ajaxLoader.hide(); if (data.status == 'success') { activity_box.find('.saved_tick').show(); activity_box.find('.saved_tick').removeClass('js_unsaved'); activity_box.find('.saved_tick').addClass('js_saved'); activity_box.find('.main').toggle(); toggle_collapsed(activity_box.find('.main'), activity_box.find('.header span')); $('.js_unsaved:first').parents('.activity_box').find('.main').toggle(); toggle_collapsed($('.js_unsaved:first').parents('.activity_box').find('.main'), $('.js_unsaved:first').parents('.activity_box').find('.header span')); } }); }); } } // Post approval for an activity // // approval types; // 'activity_manager_approve' // 'sysadmin_approve' // success text // // var approveBudget = function() { $(".js_am_approve").click(function (e) { e.preventDefault(); approveActivity($(this), 'activity_manager_approve', 'Budget Approved'); }) }; var approveAsAdmin = function() { $(".js_sysadmin_approve").click(function (e) { e.preventDefault(); approveActivity($(this), 'sysadmin_approve', 'Admin Approved'); }) }; var approveActivity = function (element, approval_type, success_text) { var activity_id = element.attr('activity-id'); var response_id = element.attr('response-id'); element.parent('li').find(".ajax-loader").show(); var url = "/responses/" + response_id + "/activities/" + activity_id + "/" + approval_type $.post(url, {approve: true, "_method": "put"}, function (data) { element.parent('li').find(".ajax-loader").hide(); if (data.status == 'success') { element.parent('li').html('<span>' + success_text + '</span>'); } }) }; var activities_new = activities_create = activities_edit = activities_update = other_costs_edit = other_costs_new = other_costs_create = other_costs_update = { run: function () { var mode = document.location.search.split("=")[1] activity_classification(); activity_form(); if ($('.js_target_field').size() == 0) { $(document).find('.js_add_nested').trigger('click'); } numericInputField(".js_implementer_spend, .js_implementer_budget"); $('.ui-autocomplete-input').live('focusin', function () { var element = $(this).siblings('select'); if(element.children('option').length < 2) { // because there is already one in to show default element.append(selectOptions); } }); } }; var activity_form = function () { $('#activity_project_id').change(function () { update_funding_source_selects(); }); $('#activity_name').live('keyup', function() { var parent = $(this).parent('li') var remaining = $(this).attr('data-maxlength') - $(this).val().length; $('.remaining_characters').html("(?) <span class=\"red\">" + remaining + " Characters Remaining</span>") }); $('.js_implementer_select').live('change', function(e) { e.preventDefault(); var element = $(this); if (element.val() == "-1") { $('.js_implementer_container').hide(); $('.add_organization').show(); } }); $('.cancel_organization_link').live('click', function(e) { e.preventDefault(); $('.organization_name').attr('value', ''); $('.add_organization').hide(); $('.js_implementer_container').show(); $('.js_implementer_select').val(null); }); $('.add_organization_link').live('click', function(e) { e.preventDefault(); var name = $('.organization_name').val(); $.post("/organizations.js", { "name" : name }, function(data){ var data = $.parseJSON(data); $('.js_implementer_container').show(); $('.add_organization').hide(); if (isNaN(data.organization.id)) { $('.js_implementer_select').val(null); } else { $('.js_implementer_select').prepend("<option value=\'"+ data.organization.id + "\'>" + data.organization.name + "</option>"); $('.js_implementer_select').val(data.organization.id); } }); $('.organization_name').attr('value', ''); $('.add_organization').slideToggle(); }); $('.js_target_field').live('keydown', function (e) { var block = $(this).parents('.js_targets'); if (e.keyCode === 13) { e.preventDefault(); block.find('.js_add_nested').trigger('click'); block.find('.js_target_field:last').focus() } }); $('.edit_button').live('click', function (e) { e.preventDefault(); var element = $(this).parents('.fields'); var fields = $.merge(element.prevAll('.fields'), element.nextAll('.fields')); element.find('.edit_block').show(); element.find('.preview_block').hide(); close_activity_funding_sources_fields(fields); }); $('.js_implementer_spend').live('keyup', function(e) { var page_spend = parseFloat($('body').attr('page_spend')); var current_spend = implementer_page_total('spend'); var difference = page_spend - current_spend; var total = parseFloat($('body').attr('total_spend')); $('.js_total_spend').find('.amount').html((total - difference).toFixed(2)) }); $('.js_implementer_budget').live('keyup', function(e) { var page_budget = parseFloat($('body').attr('page_budget')); var current_budget = implementer_page_total('budget'); var difference = page_budget - current_budget; var total = parseFloat($('body').attr('total_budget')); $('.js_total_budget').find('.amount').html((total - difference).toFixed(2)) }); approveBudget(); approveAsAdmin(); commentsInit(); dynamicUpdateTotalsInit(); close_activity_funding_sources_fields($('.funding_sources .fields')); store_implementer_page_total(); }; var store_implementer_page_total = function(){ $('body').attr('total_spend', $('.js_total_spend').find('.amount').html() ) $('body').attr('total_budget', $('.js_total_budget').find('.amount').html() ) if( $('.js_implementer_budget').length > 0 ){ page_budget = implementer_page_total('budget') $('body').attr('page_budget',page_budget); } if( $('.js_implementer_spend').length > 0 ){ page_spend = implementer_page_total('spend') $('body').attr('page_spend',page_spend); } }; var implementer_page_total = function(type){ var page_total = 0; inputs = (type == 'budget') ? $('.js_implementer_budget') : $('.js_implementer_spend'); inputs.each(function(){ float_val = parseFloat($(this).val()); if( !(isNaN(float_val)) ){ page_total += parseFloat($(this).val()); } }); return page_total } var admin_activities_new = admin_activities_create = admin_activities_edit = admin_activities_update = { run: function () { activity_form(); } }; var admin_users_new = admin_users_create = admin_users_edit = admin_users_update = { run: function () { var toggleMultiselect = function (element) { var ac_selected = $('#user_roles option[value="activity_manager"]:selected').length > 0; var dm_selected = $('#user_roles option[value="district_manager"]:selected').length > 0; if (element.val() && ac_selected) { $(".organizations").show().css('visibility', 'visible'); $(".js_manage_orgs").slideDown(); } else { $(".js_manage_orgs").slideUp(); $(".organizations").hide().css('visibility', 'hidden'); } if (element.val() && dm_selected) { $(".locations").show().css('visibility', 'visible'); $(".js_manage_districts").slideDown(); } else { $(".locations").hide().css('visibility', 'hidden'); $(".js_manage_districts").slideUp(); } }; // choose either the full version $(".multiselect").multiselect({sortable: false}); // or disable some features //$(".multiselect").multiselect({sortable: false, searchable: false}); toggleMultiselect($('#user_roles')); $('#user_roles').change(function () { toggleMultiselect($(this)); }); } } var dashboard_index = { run: function () { $('.dropdown_trigger').click(function (e) {e.preventDefault()}); if (typeof(_code_spent_values) !== 'undefined' || typeof(_code_budget_values) !== 'undefined') { drawPieChart('code_spent', _code_spent_values, 450, 300); drawPieChart('code_budget', _code_budget_values, 450, 300); } $('.dropdown_menu').hover(function (e){ e.preventDefault(); $('ul', this).slideDown(100); $('.dropdown_trigger').addClass('persist'); }, function(e) { e.preventDefault(); $('ul', this).slideUp(100); $('.dropdown_trigger').removeClass('persist'); }); } }; var admin_organizations_create = admin_organizations_edit = { run: function () { $(".js_combobox" ).combobox(); jsAutoTab(); } }; var projects_new = projects_create = projects_edit = projects_update = { run: function () { commentsInit(); validateDates($('.start_date'), $('.end_date')); dynamicUpdateTotalsInit(); numericInputField(".js_spend, .js_budget"); } } // Autotabs a page using javascript var jsAutoTab = function () { var tabindex = 1; $('input, select, textarea, checkbox').each(function() { if (this.type != "hidden") { var $input = $(this); $input.attr("tabindex", tabindex); tabindex++; } }); } // DOM LOAD $(function () { // prevent going to top when tooltip clicked $('.tooltip').live('click', function (e) { if ($(this).attr('href') === '#') { e.preventDefault(); } }); //combobox everywhere! $( ".js_combobox" ).combobox(); // keep below combobox jsAutoTab(); // tipsy tooltips everywhere! $('.tooltip').tipsy({gravity: $.fn.tipsy.autoWE, fade: true, live: true, html: true}); //jquery tools overlays $(".overlay").overlay(); var id = $('body').attr("id"); if (id) { controller_action = id; if (typeof(window[controller_action]) !== 'undefined' && typeof(window[controller_action]['run']) === 'function') { window[controller_action]['run'](); } } //observe form changes and alert user if form has unsaved data observeFormChanges($('.js_form')); $(".closeFlash").click(function (e) { e.preventDefault(); $(this).parents('div:first').fadeOut("slow", function() { $(this).show().css({display: "none"}); }); }); $('#page_tips_open').click(function (e) { e.preventDefault(); $('#page_tips .desc').toggle(); $('#page_tips .nav').toggle(); }); $('#page_tips_close').click(function (e) { e.preventDefault(); $('#page_tips .desc').toggle(); $('#page_tips .nav').toggle(); $("#page_tips_open_link").effect("highlight", {}, 1500); }); // Date picker $('.date_picker').live('click', function () { $(this).datepicker('destroy').datepicker({ changeMonth: true, changeYear: true, yearRange: '2000:2025', dateFormat: 'dd-mm-yy' }).focus(); }); // Inplace edit $(".rest_in_place").rest_in_place(); // clickable table rows $('.clickable tbody tr').click(function (e) { e.preventDefault(); var element = $(e.target); if (element.attr('href')) { var href = element.attr('href'); } else { var href = $(this).find("a").attr("href"); } if (href) { window.location = href; } }); // CSV file upload $("#csv_file").click( function(e) { e.preventDefault(); $("#import").slideToggle(); }); // Show/hide getting started tips $('.js_tips_hide').click(function (e) { e.preventDefault(); $('.js_tips_container').fadeOut(); $.post('/profile/disable_tips', { "_method": "put" }); }); });
siyelo/hrtv1
public/javascripts/application.js
JavaScript
gpl-3.0
51,126
"use strict"; const ConnectionState = Object.freeze({ Disconnected: "disconnected", Connected: "connected", Reconnecting: "reconnecting", Connecting: "connecting" }); exports.ConnectionState = ConnectionState;
Firebottle/Firebot
shared/connection-constants.js
JavaScript
gpl-3.0
227
/** * Cloud9 Language Foundation * * @copyright 2011, Ajax.org B.V. * @license GPLv3 <http://www.gnu.org/licenses/gpl.txt> */ define(function(require, exports, module) { var Range = require("ace/range").Range; var Anchor = require('ace/anchor').Anchor; var tooltip = require('ext/language/tooltip'); var Editors = require("ext/editors/editors"); module.exports = { disabledMarkerTypes: {}, hook: function(ext, worker) { var _self = this; this.ext = ext; worker.on("markers", function(event) { if(ext.disabled) return; _self.addMarkers(event, ext.editor); }); worker.on("hint", function(event) { _self.onHint(event); }); }, onHint: function(event) { var message = event.data.message; var pos = event.data.pos; var cursorPos = ceEditor.$editor.getCursorPosition(); if(cursorPos.column === pos.column && cursorPos.row === pos.row && message) tooltip.show(cursorPos.row, cursorPos.column, message); else tooltip.hide(); }, removeMarkers: function(session) { var markers = session.getMarkers(false); for (var id in markers) { // All language analysis' markers are prefixed with language_highlight if (markers[id].clazz.indexOf('language_highlight_') === 0) { session.removeMarker(id); } } for (var i = 0; i < session.markerAnchors.length; i++) { session.markerAnchors[i].detach(); } session.markerAnchors = []; }, addMarkers: function(event, editor) { var _self = this; var annos = event.data; var mySession = editor.session; if (!mySession.markerAnchors) mySession.markerAnchors = []; this.removeMarkers(editor.session); mySession.languageAnnos = []; annos.forEach(function(anno) { // Certain annotations can temporarily be disabled if (_self.disabledMarkerTypes[anno.type]) return; // Multi-line markers are not supported, and typically are a result from a bad error recover, ignore if(anno.pos.el && anno.pos.sl !== anno.pos.el) return; // Using anchors here, to automaticaly move markers as text around the marker is updated var anchor = new Anchor(mySession.getDocument(), anno.pos.sl, anno.pos.sc || 0); mySession.markerAnchors.push(anchor); var markerId; var colDiff = anno.pos.ec - anno.pos.sc; var rowDiff = anno.pos.el - anno.pos.sl; var gutterAnno = { guttertext: anno.message, type: anno.level || "warning", text: anno.message // row will be filled in updateFloat() }; function updateFloat(single) { if (markerId) mySession.removeMarker(markerId); gutterAnno.row = anchor.row; if (anno.pos.sc !== undefined && anno.pos.ec !== undefined) { var range = Range.fromPoints(anchor.getPosition(), { row: anchor.row + rowDiff, column: anchor.column + colDiff }); markerId = mySession.addMarker(range, "language_highlight_" + (anno.type ? anno.type : "default")); } if (single) mySession.setAnnotations(mySession.languageAnnos); } updateFloat(); anchor.on("change", function() { updateFloat(true); }); if (anno.message) mySession.languageAnnos.push(gutterAnno); }); mySession.setAnnotations(mySession.languageAnnos); }, /** * Temporarily disable certain types of markers (e.g. when refactoring) */ disableMarkerType: function(type) { this.disabledMarkerTypes[type] = true; var session = Editors.currentEditor.amlEditor.$editor.session; var markers = session.getMarkers(false); for (var id in markers) { // All language analysis' markers are prefixed with language_highlight if (markers[id].clazz === 'language_highlight_' + type) session.removeMarker(id); } }, enableMarkerType: function(type) { this.disabledMarkerTypes[type] = false; }, /** * Called when text in editor is updated * This attempts to predict how the worker is going to adapt markers based on the given edit * it does so instanteously, rather than with a 500ms delay, thereby avoid ugly box bouncing etc. */ onChange: function(session, event) { if(this.ext.disabled) return; var range = event.data.range; var isInserting = event.data.action.substring(0, 6) !== "remove"; var text = event.data.text; var adaptingId = text && text.search(/[^a-zA-Z0-9\$_]/) === -1; if (!isInserting) { // Removing some text var markers = session.getMarkers(false); // Run through markers var foundOne = false; for (var id in markers) { var marker = markers[id]; if (marker.clazz.indexOf('language_highlight_') === 0) { if (range.contains(marker.range.start.row, marker.range.start.column)) { session.removeMarker(id); foundOne = true; } else if (adaptingId && marker.range.contains(range.start.row, range.start.column)) { foundOne = true; var deltaLength = text.length; marker.range.end.column -= deltaLength; } } } if (!foundOne) { // Didn't find any markers, therefore there will not be any anchors or annotations either return; } // Run through anchors for (var i = 0; i < session.markerAnchors.length; i++) { var anchor = session.markerAnchors[i]; if (range.contains(anchor.row, anchor.column)) { anchor.detach(); } } // Run through annotations for (var i = 0; i < session.languageAnnos.length; i++) { var anno = session.languageAnnos[i]; if (range.contains(anno.row, 1)) { session.languageAnnos.splice(i, 1); i--; } } session.setAnnotations(session.languageAnnos); } else { // Inserting some text var markers = session.getMarkers(false); // Only if inserting an identifier if (!adaptingId) return; // Run through markers var foundOne = false; for (var id in markers) { var marker = markers[id]; if (marker.clazz.indexOf('language_highlight_') === 0) { if (marker.range.contains(range.start.row, range.start.column)) { foundOne = true; var deltaLength = text.length; marker.range.end.column += deltaLength; } } } } if (foundOne) session._dispatchEvent("changeBackMarker"); }, destroy : function(){ } }; });
Phara0h/cloud9
plugins-client/ext.language/marker.js
JavaScript
gpl-3.0
7,580
/** * selectbox-utils for jQuery * For Virtual-Office Company * Copyright (c) 2007 Yoshiomi KURISU * Licensed under the MIT (MIT-LICENSE.txt) licenses. * * @example $('#year1').numericOptions({from:2007,to:2011}); * @example $('#month1').numericOptions({from:1,to:12}); * @example $('#date1').numericOptions().datePulldown({year:$('#year1'),month:$('#month1')}); * */ (function() { //obj is Array // Array : [[label,value],[label,value],....] //set options to select node //obj is null or obj is number //get options from select node $.fn.options = function(obj){ if(obj || obj == 0){ if(obj instanceof Array){ this.each(function(){ this.options.length = 0; for(var i = 0,len = obj.length;i<len;i++){ var tmp = obj[i]; if(tmp.length && tmp.length == 2){ this.options[this.options.length] = new Option(tmp[0],tmp[1]); } } }); return this; }else if(typeof obj == 'number'){ return $('option:eq('+obj+')',this); }else if(obj == 'selected'){ return this.val(); } }else{ return $('option',this) } return $([]); } $.fn.numericOptions = function(settings){ settings = jQuery.extend({ remove:true ,from:1 ,to:31 ,selectedIndex:0 ,valuePadding:0 ,namePadding:0 ,labels:[] ,exclude:null ,startLabel:null },settings); //error check if(!(settings.from+'').match(/^\d+$/)||!(settings.to+'').match(/^\d+$/)||!(settings.selectedIndex+'').match(/^\d+$/)||!(settings.valuePadding+'').match(/^\d+$/)||!(settings.namePadding+'').match(/^\d+$/)) return; if(settings.from > settings.to) return; if(settings.to - settings.from < settings.selectedIndex) return; //add options if(settings.remove) this.children().remove(); var padfunc = function(v,p){ if((''+v).length < p){ for(var i = 0,l = p - (v+'').length;i < l ;i++){ v = '0' + v; } } return v; } var exclude_strings = (settings.exclude && settings.exclude instanceof Array && settings.exclude.length > 0)?' '+settings.exclude.join(' ')+' ':''; this.each(function(){ this.options.length = 0 //set startLabel var sl = settings.startLabel; if(sl && sl.length && sl.length == 2){ this.options[0] = new Option(sl[0],sl[1]); } }); for(var i=settings.from,j=0;i<=settings.to;i++){ this.each(function(){ var val = padfunc(i,settings.valuePadding); if(exclude_strings.indexOf(' '+val+' ') < 0){ var lab = (settings.labels[j])?settings.labels[j]:padfunc(i,settings.namePadding); this.options[this.options.length] = new Option(lab,val); j++; } }); } this.each(function(){ if(jQuery.browser.opera){ this.options[settings.selectedIndex].defaultSelected = true; }else{ this.selectedIndex = settings.selectedIndex; } }); return this; }; // $.fn.datePulldown = function(settings){ if(!settings.year || !settings.month) return ; var y = settings.year; var m = settings.month; if(!y.val() || !m.val()) return; if(!y.val().match(/^\d{1,4}$/)) return; if(!m.val().match(/^[0][1-9]$|^[1][1,2]$|^[0-9]$/)) return; var self = this; var fnc = function(){ var tmp = new Date(new Date(y.val(),m.val()).getTime() - 1000); var lastDay = tmp.getDate() - 0; self.each(function(){ var ind = (this.selectedIndex<lastDay-1)?this.selectedIndex:lastDay-1; this.selectedIndex = ind; $(this).numericOptions({to:lastDay,selectedIndex:ind}); }); } y.change(fnc); m.change(fnc); return this; }; })(jQuery);
ulinke/phpb2b
static/scripts/jquery/selectbox.js
JavaScript
gpl-3.0
3,526
var searchData= [ ['gpio_2ec',['gpio.c',['../gpio_8c.html',1,'']]], ['gpio_2ed',['gpio.d',['../gpio_8d.html',1,'']]], ['gpio_2eh',['gpio.h',['../gpio_8h.html',1,'']]], ['gpio0',['GPIO0',['../group__gpio__pin__id.html#ga20f88dbc839eb32b5fec903474befdd7',1,'gpio_common_all.h']]], ['gpio1',['GPIO1',['../group__gpio__pin__id.html#gabe59d3a7ce7a18e9440bd54cae1f3fc8',1,'gpio_common_all.h']]], ['gpio10',['GPIO10',['../group__gpio__pin__id.html#gae285b2475841ecb1ac23d8511b360d0e',1,'gpio_common_all.h']]], ['gpio11',['GPIO11',['../group__gpio__pin__id.html#gac376b1c124378935df7b3c171b2bef35',1,'gpio_common_all.h']]], ['gpio12',['GPIO12',['../group__gpio__pin__id.html#ga1dfa6e5489489f2797d3d80c718716ce',1,'gpio_common_all.h']]], ['gpio13',['GPIO13',['../group__gpio__pin__id.html#ga4b7d9a3961712ddd2a58532f4dcedc1d',1,'gpio_common_all.h']]], ['gpio14',['GPIO14',['../group__gpio__pin__id.html#gad42a78782c6bb99ad7e7c1ec975b5b96',1,'gpio_common_all.h']]], ['gpio15',['GPIO15',['../group__gpio__pin__id.html#gaabc2f003b1495cd03eef1fae31e6847a',1,'gpio_common_all.h']]], ['gpio2',['GPIO2',['../group__gpio__pin__id.html#ga88a95401ea8409c83cbda42f31450cd0',1,'gpio_common_all.h']]], ['gpio3',['GPIO3',['../group__gpio__pin__id.html#gaf3cc04d651b622d5323d74dc2f0999a0',1,'gpio_common_all.h']]], ['gpio4',['GPIO4',['../group__gpio__pin__id.html#ga98aeff9c8b3bbdfd119e4ec4d3f615c8',1,'gpio_common_all.h']]], ['gpio5',['GPIO5',['../group__gpio__pin__id.html#ga1a96368c99d63b0e715b7e0421f4a209',1,'gpio_common_all.h']]], ['gpio6',['GPIO6',['../group__gpio__pin__id.html#ga46027cd97ff756e5ddadcc10811b5699',1,'gpio_common_all.h']]], ['gpio7',['GPIO7',['../group__gpio__pin__id.html#ga3820cacb614277004870fc37b33ad084',1,'gpio_common_all.h']]], ['gpio8',['GPIO8',['../group__gpio__pin__id.html#gaa951be0ce26f788049a86e407a70ae20',1,'gpio_common_all.h']]], ['gpio9',['GPIO9',['../group__gpio__pin__id.html#gae2a4c4d28729daf18e1923a1878e7352',1,'gpio_common_all.h']]], ['gpio_5fall',['GPIO_ALL',['../group__gpio__pin__id.html#ga9f4da19f41fda0a3ec6d017e0bedfa4a',1,'gpio_common_all.h']]], ['gpio_5fbrr',['GPIO_BRR',['../gpio_8h.html#a790c77e8320ce9c7dc9132862cdc4a59',1,'gpio.h']]], ['gpio_5fclear',['gpio_clear',['../group__gpio__defines.html#ga8970f778a63c9d78ffd8d4d36628c7e1',1,'gpio_clear(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c'],['../group__gpio__file.html#ga8970f778a63c9d78ffd8d4d36628c7e1',1,'gpio_clear(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c']]], ['gpio_5fcommon_5fall_2ec',['gpio_common_all.c',['../gpio__common__all_8c.html',1,'']]], ['gpio_5fcommon_5fall_2ed',['gpio_common_all.d',['../gpio__common__all_8d.html',1,'']]], ['gpio_5fcommon_5fall_2eh',['gpio_common_all.h',['../gpio__common__all_8h.html',1,'']]], ['gpio_5fcommon_5ff0234_2ec',['gpio_common_f0234.c',['../gpio__common__f0234_8c.html',1,'']]], ['gpio_5fcommon_5ff0234_2ed',['gpio_common_f0234.d',['../gpio__common__f0234_8d.html',1,'']]], ['gpio_20defines',['GPIO Defines',['../group__gpio__defines.html',1,'']]], ['gpio',['GPIO',['../group__gpio__file.html',1,'']]], ['gpio_5fget',['gpio_get',['../group__gpio__defines.html#ga5fee90e8e5af7de567890ffae5ed50c8',1,'gpio_get(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c'],['../group__gpio__file.html#ga5fee90e8e5af7de567890ffae5ed50c8',1,'gpio_get(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c']]], ['gpio_5flckk',['GPIO_LCKK',['../group__gpio__defines.html#gabb9a59447b681234fadf66bd3f0fdd57',1,'gpio_common_all.h']]], ['gpio_5fmode_5fsetup',['gpio_mode_setup',['../group__gpio__file.html#ga733d745a0b6840f22b516979ce7a92c9',1,'gpio_common_f0234.c']]], ['gpio_5fospeed_5fhigh',['GPIO_OSPEED_HIGH',['../group__gpio__speed.html#ga680deeabdb12a634cdb3aeb08244cc1e',1,'gpio.h']]], ['gpio_5fospeed_5flow',['GPIO_OSPEED_LOW',['../group__gpio__speed.html#ga947fdffc33c7628758f40ccb72688217',1,'gpio.h']]], ['gpio_5fospeed_5fmed',['GPIO_OSPEED_MED',['../group__gpio__speed.html#ga9e215e655afc1576bbaeed0ae3545de6',1,'gpio.h']]], ['gpio_20pin_20identifiers',['GPIO Pin Identifiers',['../group__gpio__pin__id.html',1,'']]], ['gpio_5fport_5fa_5fbase',['GPIO_PORT_A_BASE',['../memorymap_8h.html#aadfedde7941fa484de08872551516cd9',1,'memorymap.h']]], ['gpio_5fport_5fb_5fbase',['GPIO_PORT_B_BASE',['../memorymap_8h.html#a76f2426fde990408388cc7e23d63444e',1,'memorymap.h']]], ['gpio_5fport_5fc_5fbase',['GPIO_PORT_C_BASE',['../memorymap_8h.html#ac3754540649792975085507caf98b70f',1,'memorymap.h']]], ['gpio_5fport_5fconfig_5flock',['gpio_port_config_lock',['../group__gpio__defines.html#ga749adc86df621552b5a0908ecf5b2ebe',1,'gpio_port_config_lock(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c'],['../group__gpio__file.html#ga749adc86df621552b5a0908ecf5b2ebe',1,'gpio_port_config_lock(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c']]], ['gpio_5fport_5fd_5fbase',['GPIO_PORT_D_BASE',['../memorymap_8h.html#afc8d20f5f6ce85201a9682a37036445d',1,'memorymap.h']]], ['gpio_5fport_5fe_5fbase',['GPIO_PORT_E_BASE',['../memorymap_8h.html#a512bc9a47ce4bccdcbcaa9a80620d559',1,'memorymap.h']]], ['gpio_5fport_5ff_5fbase',['GPIO_PORT_F_BASE',['../memorymap_8h.html#aeb59b5ce54ec229dc4697a0d3b387401',1,'memorymap.h']]], ['gpio_5fport_5fread',['gpio_port_read',['../group__gpio__defines.html#gac7a671c0d057a8db484357b344d66b23',1,'gpio_port_read(uint32_t gpioport):&#160;gpio_common_all.c'],['../group__gpio__file.html#gac7a671c0d057a8db484357b344d66b23',1,'gpio_port_read(uint32_t gpioport):&#160;gpio_common_all.c']]], ['gpio_5fport_5fwrite',['gpio_port_write',['../group__gpio__defines.html#gaeb877f5252652d6a574a08b085ef14f5',1,'gpio_port_write(uint32_t gpioport, uint16_t data):&#160;gpio_common_all.c'],['../group__gpio__file.html#gaeb877f5252652d6a574a08b085ef14f5',1,'gpio_port_write(uint32_t gpioport, uint16_t data):&#160;gpio_common_all.c']]], ['gpio_5fset',['gpio_set',['../group__gpio__defines.html#ga7fb65a68e4fc7175660f396395f6b44e',1,'gpio_set(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c'],['../group__gpio__file.html#ga7fb65a68e4fc7175660f396395f6b44e',1,'gpio_set(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c']]], ['gpio_5fset_5faf',['gpio_set_af',['../group__gpio__file.html#ga2937f803468b3440302fae213c4c3c14',1,'gpio_common_f0234.c']]], ['gpio_5fset_5foutput_5foptions',['gpio_set_output_options',['../group__gpio__file.html#gab05e7f5b963f49c7442a69e5999f9319',1,'gpio_common_f0234.c']]], ['gpio_20output_20pin_20speed',['GPIO Output Pin Speed',['../group__gpio__speed.html',1,'']]], ['gpio_5ftoggle',['gpio_toggle',['../group__gpio__defines.html#ga5ce25ff1552b12093b009978322fcb5c',1,'gpio_toggle(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c'],['../group__gpio__file.html#ga5ce25ff1552b12093b009978322fcb5c',1,'gpio_toggle(uint32_t gpioport, uint16_t gpios):&#160;gpio_common_all.c']]], ['gpioa_5fbrr',['GPIOA_BRR',['../gpio_8h.html#a9c111ddc85e66775e6d3e6ed2e44eb4f',1,'gpio.h']]], ['gpiob_5fbrr',['GPIOB_BRR',['../gpio_8h.html#a0c7c0db6bb2dc88162cec23b7d90700f',1,'gpio.h']]], ['gpioc_5fbrr',['GPIOC_BRR',['../gpio_8h.html#ac6a4510b46cf898d3c3a2f56c84386b7',1,'gpio.h']]], ['gpiod_5fbrr',['GPIOD_BRR',['../gpio_8h.html#ac7dec0235cd22aa5c0bc17fe8f1b723c',1,'gpio.h']]], ['gpiof_5fbrr',['GPIOF_BRR',['../gpio_8h.html#a35e53847bccba5ae1e79b28748ee9aac',1,'gpio.h']]] ];
Aghosh993/TARS_codebase
libopencm3/doc/stm32f0/html/search/all_7.js
JavaScript
gpl-3.0
7,420
ig.module( 'game.weapons.beam' ) .requires( 'impact.entity' ) .defines(function() { WeaponBeam = ig.Class.extend({ name: 'WeaponBeam', displayName: 'Lasers', playerAnimOffset: 0, hudImage: new ig.Image( 'media/hud-bullet.png' ), shootSFX: new ig.Sound('media/sounds/eyebeams.*'), fire: function() { var player = ig.game.player; var pos = player.getProjectileStartPosition(); ig.game.spawnEntity( EntityBeamParticle, pos.x, pos.y, { flip: player.flip }); this.shootSFX.play(); } }); EntityBeamParticle = WeaponBase.extend({ size: { x: 20, y: 4 }, offset: { x: 0, y: 0 }, animSheet: new ig.AnimationSheet( 'media/laser-beam.png', 20, 4 ), type: ig.Entity.TYPE.NONE, checkAgainst: ig.Entity.TYPE.B, collides: ig.Entity.COLLIDES.PASSIVE, maxVel: { x: 500, y: 0 }, friction: {x: 0, y: 0}, damage: 15, init: function( x, y, settings ) { this.parent( x + (settings.flip ? -20 : 0), y, settings); this.vel.x = (settings.flip ? -this.maxVel.x : this.maxVel.x); this.addAnim( 'idle', 0.2, [0], true); this.addAnim( 'hit', 0.03, [1,2,3,4], true); }, update: function() { this.parent(); if( this.currentAnim === this.anims.hit && this.currentAnim.loopCount > 0 ) { this.kill(); } }, handleMovementTrace: function( res ) { this.parent(res); if( res.collision.x || res.collision.y || res.collision.slope ) { this.vel.x = 0; this.currentAnim = this.anims.hit.rewind(); } }, check: function(other) { if( this.currentAnim !== this.anims.hit ) { other.receiveDamage(this.damage, this); this.kill(); } }, collideWith: function( other, axis ) { if( this.currentAnim !== this.anims.hit && other ) { this.kill(); } } }); });
gamebytes/rock-kickass
lib/game/weapons/beam.js
JavaScript
gpl-3.0
1,887
turingApp.controller('TurConverseTrainingListCtrl', [ "$scope", "$filter", "turConverseTrainingResource", function ($scope, $filter, turConverseTrainingResource) { $scope.conversations = turConverseTrainingResource.query( function() { $scope.conversations = $filter('orderBy')($scope.conversations, '-date'); }); }]);
openviglet/turing
src/main/resources/public/js/build/extract/feature/converse/training/TurConverseTrainingListCtrl.js
JavaScript
gpl-3.0
373
/*! * @copyright &copy; Kartik Visweswaran, Krajee.com, 2013 - 2016 * @version 4.0.1 * * A simple yet powerful JQuery star rating plugin that allows rendering fractional star ratings and supports * Right to Left (RTL) input. * * For more JQuery plugins visit http://plugins.krajee.com * For more Yii related demos visit http://demos.krajee.com */ (function (factory) { "use strict"; if (typeof define === 'function' && define.amd) { // jshint ignore:line // AMD. Register as an anonymous module. define(['jquery'], factory); // jshint ignore:line } else { // noinspection JSUnresolvedVariable if (typeof module === 'object' && module.exports) { // jshint ignore:line // Node/CommonJS // noinspection JSUnresolvedVariable module.exports = factory(require('jquery')); // jshint ignore:line } else { // Browser globals factory(window.jQuery); } } }(function ($) { "use strict"; $.fn.ratingLocales = {}; var NAMESPACE, DEFAULT_MIN, DEFAULT_MAX, DEFAULT_STEP, isEmpty, getCss, addCss, getDecimalPlaces, applyPrecision, handler, Rating; NAMESPACE = '.rating'; DEFAULT_MIN = 0; DEFAULT_MAX = 5; DEFAULT_STEP = 0.5; isEmpty = function (value, trim) { return value === null || value === undefined || value.length === 0 || (trim && $.trim(value) === ''); }; getCss = function (condition, css) { return condition ? ' ' + css : ''; }; addCss = function ($el, css) { $el.removeClass(css).addClass(css); }; getDecimalPlaces = function (num) { var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/); return !match ? 0 : Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0)); }; applyPrecision = function (val, precision) { return parseFloat(val.toFixed(precision)); }; handler = function ($el, event, callback, skipNS) { var ev = skipNS ? event : event.split(' ').join(NAMESPACE + ' ') + NAMESPACE; $el.off(ev).on(ev, callback); }; Rating = function (element, options) { var self = this; self.$element = $(element); self._init(options); }; Rating.prototype = { constructor: Rating, _parseAttr: function (vattr, options) { var self = this, $el = self.$element, elType = $el.attr('type'), finalVal, val, chk, out; if (elType === 'range' || elType === 'number') { val = options[vattr] || $el.data(vattr) || $el.attr(vattr); switch (vattr) { case 'min': chk = DEFAULT_MIN; break; case 'max': chk = DEFAULT_MAX; break; default: chk = DEFAULT_STEP; } finalVal = isEmpty(val) ? chk : val; out = parseFloat(finalVal); } else { out = parseFloat(options[vattr]); } return isNaN(out) ? chk : out; }, _setDefault: function (key, val) { var self = this; if (isEmpty(self[key])) { self[key] = val; } }, _listenClick: function (e, callback) { e.stopPropagation(); e.preventDefault(); if (e.handled !== true) { callback(e); e.handled = true; } else { return false; } }, _starClick: function (e) { var self = this, pos; self._listenClick(e, function (ev) { if (self.inactive) { return false; } pos = self._getTouchPosition(ev); self._setStars(pos); self.$element.trigger('change').trigger('rating.change', [self.$element.val(), self._getCaption()]); self.starClicked = true; }); }, _starMouseMove: function (e) { var self = this, pos, out; if (!self.hoverEnabled || self.inactive || (e && e.isDefaultPrevented())) { return; } self.starClicked = false; pos = self._getTouchPosition(e); out = self.calculate(pos); self._toggleHover(out); self.$element.trigger('rating.hover', [out.val, out.caption, 'stars']); }, _starMouseLeave: function (e) { var self = this, out; if (!self.hoverEnabled || self.inactive || self.starClicked || (e && e.isDefaultPrevented())) { return; } out = self.cache; self._toggleHover(out); self.$element.trigger('rating.hoverleave', ['stars']); }, _clearClick: function (e) { var self = this; self._listenClick(e, function () { if (!self.inactive) { self.clear(); self.clearClicked = true; } }); }, _clearMouseMove: function (e) { var self = this, caption, val, width, out; if (!self.hoverEnabled || self.inactive || !self.hoverOnClear || (e && e.isDefaultPrevented())) { return; } self.clearClicked = false; caption = '<span class="' + self.clearCaptionClass + '">' + self.clearCaption + '</span>'; val = self.clearValue; width = self.getWidthFromValue(val) || 0; out = {caption: caption, width: width, val: val}; self._toggleHover(out); self.$element.trigger('rating.hover', [val, caption, 'clear']); }, _clearMouseLeave: function (e) { var self = this, out; if (!self.hoverEnabled || self.inactive || self.clearClicked || !self.hoverOnClear || (e && e.isDefaultPrevented())) { return; } out = self.cache; self._toggleHover(out); self.$element.trigger('rating.hoverleave', ['clear']); }, _resetForm: function (e) { var self = this; if (e && e.isDefaultPrevented()) { return; } if (!self.inactive) { self.reset(); } }, _setTouch: function (e, flag) { //noinspection JSUnresolvedVariable var self = this, ev, touches, pos, out, caption, w, width, isTouchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch); if (!isTouchCapable || self.inactive) { return; } ev = e.originalEvent; //noinspection JSUnresolvedVariable touches = !isEmpty(ev.touches) ? ev.touches : ev.changedTouches; pos = self._getTouchPosition(touches[0]); if (flag) { self._setStars(pos); self.$element.trigger('change').trigger('rating.change', [self.$element.val(), self._getCaption()]); self.starClicked = true; } else { out = self.calculate(pos); caption = out.val <= self.clearValue ? self.fetchCaption(self.clearValue) : out.caption; w = self.getWidthFromValue(self.clearValue); width = out.val <= self.clearValue ? w + '%' : out.width; self._setCaption(caption); self.$filledStars.css('width', width); } }, _initTouch: function (e) { var self = this, flag = (e.type === "touchend"); self._setTouch(e, flag); }, _initSlider: function (options) { var self = this; if (isEmpty(self.$element.val())) { self.$element.val(0); } self.initialValue = self.$element.val(); self._setDefault('min', self._parseAttr('min', options)); self._setDefault('max', self._parseAttr('max', options)); self._setDefault('step', self._parseAttr('step', options)); if (isNaN(self.min) || isEmpty(self.min)) { self.min = DEFAULT_MIN; } if (isNaN(self.max) || isEmpty(self.max)) { self.max = DEFAULT_MAX; } if (isNaN(self.step) || isEmpty(self.step) || self.step === 0) { self.step = DEFAULT_STEP; } self.diff = self.max - self.min; }, _initHighlight: function (v) { var self = this, w, cap = self._getCaption(); if (!v) { v = self.$element.val(); } w = self.getWidthFromValue(v) + '%'; self.$filledStars.width(w); self.cache = {caption: cap, width: w, val: v}; }, _getContainerCss: function () { var self = this; return 'rating-container' + getCss(self.theme, 'theme-' + self.theme) + getCss(self.rtl, 'rating-rtl') + getCss(self.size, 'rating-' + self.size) + getCss(self.animate, 'rating-animate') + getCss(self.disabled || self.readonly, 'rating-disabled') + getCss(self.containerClass, self.containerClass); }, _checkDisabled: function () { var self = this, $el = self.$element, opts = self.options; self.disabled = opts.disabled === undefined ? $el.attr('disabled') || false : opts.disabled; self.readonly = opts.readonly === undefined ? $el.attr('readonly') || false : opts.readonly; self.inactive = (self.disabled || self.readonly); $el.attr({disabled: self.disabled, readonly: self.readonly}); }, _addContent: function (type, content) { var self = this, $container = self.$container, isClear = type === 'clear'; if (self.rtl) { return isClear ? $container.append(content) : $container.prepend(content); } else { return isClear ? $container.prepend(content) : $container.append(content); } }, _generateRating: function () { var self = this, $el = self.$element, $rating, $container, w; $container = self.$container = $(document.createElement("div")).insertBefore($el); addCss($container, self._getContainerCss()); self.$rating = $rating = $(document.createElement("div")).attr('class', 'rating').appendTo($container) .append(self._getStars('empty')).append(self._getStars('filled')); self.$emptyStars = $rating.find('.empty-stars'); self.$filledStars = $rating.find('.filled-stars'); self._renderCaption(); self._renderClear(); self._initHighlight(); $container.append($el); if (self.rtl) { w = Math.max(self.$emptyStars.outerWidth(), self.$filledStars.outerWidth()); self.$emptyStars.width(w); } }, _getCaption: function () { var self = this; return self.$caption && self.$caption.length ? self.$caption.html() : self.defaultCaption; }, _setCaption: function (content) { var self = this; if (self.$caption && self.$caption.length) { self.$caption.html(content); } }, _renderCaption: function () { var self = this, val = self.$element.val(), html, $cap = self.captionElement ? $(self.captionElement) : ''; if (!self.showCaption) { return; } html = self.fetchCaption(val); if ($cap && $cap.length) { addCss($cap, 'caption'); $cap.html(html); self.$caption = $cap; return; } self._addContent('caption', '<div class="caption">' + html + '</div>'); self.$caption = self.$container.find(".caption"); }, _renderClear: function () { var self = this, css, $clr = self.clearElement ? $(self.clearElement) : ''; if (!self.showClear) { return; } css = self._getClearClass(); if ($clr.length) { addCss($clr, css); $clr.attr({"title": self.clearButtonTitle}).html(self.clearButton); self.$clear = $clr; return; } self._addContent('clear', '<div class="' + css + '" title="' + self.clearButtonTitle + '">' + self.clearButton + '</div>'); self.$clear = self.$container.find('.' + self.clearButtonBaseClass); }, _getClearClass: function () { return this.clearButtonBaseClass + ' ' + ((this.inactive) ? '' : this.clearButtonActiveClass); }, _getTouchPosition: function (e) { var pageX = isEmpty(e.pageX) ? e.originalEvent.touches[0].pageX : e.pageX; return pageX - this.$rating.offset().left; }, _toggleHover: function (out) { var self = this, w, width, caption; if (!out) { return; } if (self.hoverChangeStars) { w = self.getWidthFromValue(self.clearValue); width = out.val <= self.clearValue ? w + '%' : out.width; self.$filledStars.css('width', width); } if (self.hoverChangeCaption) { caption = out.val <= self.clearValue ? self.fetchCaption(self.clearValue) : out.caption; if (caption) { self._setCaption(caption + ''); } } }, _init: function (options) { var self = this, $el = self.$element.addClass('hide'); self.options = options; $.each(options, function (key, value) { self[key] = value; }); if (self.rtl || $el.attr('dir') === 'rtl') { self.rtl = true; $el.attr('dir', 'rtl'); } self.starClicked = false; self.clearClicked = false; self._initSlider(options); self._checkDisabled(); if (self.displayOnly) { self.inactive = true; self.showClear = false; self.showCaption = false; } self._generateRating(); self._listen(); return $el.removeClass('rating-loading'); }, _listen: function () { var self = this, $el = self.$element, $form = $el.closest('form'), $rating = self.$rating, $clear = self.$clear; handler($rating, 'touchstart touchmove touchend', $.proxy(self._initTouch, self)); handler($rating, 'click touchstart', $.proxy(self._starClick, self)); handler($rating, 'mousemove', $.proxy(self._starMouseMove, self)); handler($rating, 'mouseleave', $.proxy(self._starMouseLeave, self)); if (self.showClear && $clear.length) { handler($clear, 'click touchstart', $.proxy(self._clearClick, self)); handler($clear, 'mousemove', $.proxy(self._clearMouseMove, self)); handler($clear, 'mouseleave', $.proxy(self._clearMouseLeave, self)); } if ($form.length) { handler($form, 'reset', $.proxy(self._resetForm, self)); } return $el; }, _getStars: function (type) { var self = this, stars = '<span class="' + type + '-stars">', i; for (i = 1; i <= self.stars; i++) { stars += '<span class="star">' + self[type + 'Star'] + '</span>'; } return stars + '</span>'; }, _setStars: function (pos) { var self = this, out = arguments.length ? self.calculate(pos) : self.calculate(), $el = self.$element; $el.val(out.val); self.$filledStars.css('width', out.width); self._setCaption(out.caption); self.cache = out; return $el; }, showStars: function (val) { var self = this, v = parseFloat(val); self.$element.val(isNaN(v) ? self.clearValue : v); return self._setStars(); }, calculate: function (pos) { var self = this, defaultVal = isEmpty(self.$element.val()) ? 0 : self.$element.val(), val = arguments.length ? self.getValueFromPosition(pos) : defaultVal, caption = self.fetchCaption(val), width = self.getWidthFromValue(val); width += '%'; return {caption: caption, width: width, val: val}; }, getValueFromPosition: function (pos) { var self = this, precision = getDecimalPlaces(self.step), val, factor, maxWidth = self.$rating.width(); factor = (self.diff * pos) / (maxWidth * self.step); factor = self.rtl ? Math.floor(factor) : Math.ceil(factor); val = applyPrecision(parseFloat(self.min + factor * self.step), precision); val = Math.max(Math.min(val, self.max), self.min); return self.rtl ? (self.max - val) : val; }, getWidthFromValue: function (val) { var self = this, min = self.min, max = self.max, factor, $r = self.$emptyStars, w; if (!val || val <= min || min === max) { return 0; } w = $r.outerWidth(); factor = w ? $r.width() / w : 1; if (val >= max) { return 100; } return (val - min) * factor * 100 / (max - min); }, fetchCaption: function (rating) { var self = this, val = parseFloat(rating) || self.clearValue, css, cap, capVal, cssVal, caption, vCap = self.starCaptions, vCss = self.starCaptionClasses; if (val && val !== self.clearValue) { val = applyPrecision(val, getDecimalPlaces(self.step)); } cssVal = typeof vCss === "function" ? vCss(val) : vCss[val]; capVal = typeof vCap === "function" ? vCap(val) : vCap[val]; cap = isEmpty(capVal) ? self.defaultCaption.replace(/\{rating}/g, val) : capVal; css = isEmpty(cssVal) ? self.clearCaptionClass : cssVal; caption = (val === self.clearValue) ? self.clearCaption : cap; return '<span class="' + css + '">' + caption + '</span>'; }, destroy: function () { var self = this, $el = self.$element; if (!isEmpty(self.$container)) { self.$container.before($el).remove(); } $.removeData($el.get(0)); return $el.off('rating').removeClass('hide'); }, create: function (options) { var self = this, opts = options || self.options || {}; return self.destroy().rating(opts); }, clear: function () { var self = this, title = '<span class="' + self.clearCaptionClass + '">' + self.clearCaption + '</span>'; if (!self.inactive) { self._setCaption(title); } return self.showStars(self.clearValue).trigger('change').trigger('rating.clear'); }, reset: function () { var self = this; return self.showStars(self.initialValue).trigger('rating.reset'); }, update: function (val) { var self = this; return arguments.length ? self.showStars(val) : self.$element; }, refresh: function (options) { var self = this, $el = self.$element; if (!options) { return $el; } return self.destroy().rating($.extend(true, self.options, options)).trigger('rating.refresh'); } }; $.fn.rating = function (option) { var args = Array.apply(null, arguments), retvals = []; args.shift(); this.each(function () { var self = $(this), data = self.data('rating'), options = typeof option === 'object' && option, lang = options.language || self.data('language') || 'en', loc = {}, opts; if (!data) { if (lang !== 'en' && !isEmpty($.fn.ratingLocales[lang])) { loc = $.fn.ratingLocales[lang]; } opts = $.extend(true, {}, $.fn.rating.defaults, $.fn.ratingLocales.en, loc, options, self.data()); data = new Rating(this, opts); self.data('rating', data); } if (typeof option === 'string') { retvals.push(data[option].apply(data, args)); } }); switch (retvals.length) { case 0: return this; case 1: return retvals[0] === undefined ? this : retvals[0]; default: return retvals; } }; $.fn.rating.defaults = { theme: '', language: 'en', stars: 5, filledStar: '<i class="glyphicon glyphicon-star"></i>', emptyStar: '<i class="glyphicon glyphicon-star-empty"></i>', containerClass: '', size: 'md', animate: true, displayOnly: false, rtl: false, showClear: false, showCaption: false, starCaptionClasses: { 0.5: 'label label-danger', 1: 'label label-danger', 1.5: 'label label-warning', 2: 'label label-warning', 2.5: 'label label-info', 3: 'label label-info', 3.5: 'label label-primary', 4: 'label label-primary', 4.5: 'label label-success', 5: 'label label-success' }, clearButton: '<i class="glyphicon glyphicon-minus-sign"></i>', clearButtonBaseClass: 'clear-rating', clearButtonActiveClass: 'clear-rating-active', clearCaptionClass: 'label label-default', clearValue: null, captionElement: null, clearElement: null, hoverEnabled: true, hoverChangeCaption: true, hoverChangeStars: true, hoverOnClear: true }; $.fn.ratingLocales.en = { defaultCaption: '{rating} Stars', starCaptions: { 0.5: 'Half Star', 1: 'One Star', 1.5: 'One & Half Star', 2: 'Two Stars', 2.5: 'Two & Half Stars', 3: 'Three Stars', 3.5: 'Three & Half Stars', 4: 'Four Stars', 4.5: 'Four & Half Stars', 5: 'Five Stars' }, clearButtonTitle: 'Clear', clearCaption: 'Not Rated' }; $.fn.rating.Constructor = Rating; /** * Convert automatically inputs with class 'rating' into Krajee's star rating control. */ $(document).ready(function () { var $input = $('input.rating'); if ($input.length) { $input.removeClass('rating-loading').addClass('rating-loading').rating(); } }); }));
uc-web/CHAMBING
resources/plugins/ratingbar/star-rating.js
JavaScript
gpl-3.0
23,526
import config from './config'; import webpackConfig from './webpack.config'; import path from 'path'; import _ from 'lodash'; import gulp from 'gulp'; import webpack from 'webpack'; import rimraf from 'rimraf-promise'; import sequence from 'run-sequence'; import $plumber from 'gulp-plumber'; import $sass from 'gulp-sass'; import $sourcemaps from 'gulp-sourcemaps'; import $pug from 'gulp-pug'; import $util from 'gulp-util'; import $rev from 'gulp-rev'; import $replace from 'gulp-replace'; import $prefixer from 'gulp-autoprefixer'; import $size from 'gulp-size'; import $imagemin from 'gulp-imagemin'; import $changed from 'gulp-changed'; // Set environment variable. process.env.NODE_ENV = config.env.debug ? 'development' : 'production'; // Create browserSync. const browserSync = require('browser-sync').create(); // Rewrite gulp.src for better error handling. let gulpSrc = gulp.src; gulp.src = function () { return gulpSrc(...arguments) .pipe($plumber((error) => { const { plugin, message } = error; $util.log($util.colors.red(`Error (${plugin}): ${message}`)); this.emit('end'); })); }; // Create server. gulp.task('server', () => { browserSync.init({ notify: false, server: { baseDir: config.buildDir } }); }); // Compiles and deploys images. gulp.task('images', () => { return gulp.src(config.images.entry) .pipe($changed(config.images.output)) .pipe($imagemin()) .pipe($size({ title: '[images]', gzip: true })) .pipe(gulp.dest(config.images.output)); }); gulp.task('files', () => { return gulp.src(config.files.entry) .pipe($changed(config.files.output)) .pipe($size({ title: '[files]', gzip: true })) .pipe(gulp.dest(config.files.output)); }); // Compiles and deploys stylesheets. gulp.task('stylesheets', () => { if (config.env.debug) { return gulp.src(config.stylesheets.entry) .pipe($sourcemaps.init()) .pipe($sass(config.stylesheets.sass).on('error', $sass.logError)) .pipe($prefixer(config.stylesheets.autoprefixer)) .pipe($sourcemaps.write('/')) .pipe(gulp.dest(config.stylesheets.output)) .pipe($size({ title: '[stylesheets]', gzip: true })) .pipe(browserSync.stream({ match: '**/*.css' })); } else { return gulp.src(config.stylesheets.entry) .pipe($sass(config.stylesheets.sass).on('error', $sass.logError)) .pipe($prefixer(config.stylesheets.autoprefixer)) .pipe(gulp.dest(config.stylesheets.output)) .pipe($size({ title: '[stylesheets]', gzip: true })); } }); // Compiles and deploys javascript files. gulp.task('javascripts', (callback) => { let guard = false; if (config.env.debug) { webpack(webpackConfig).watch(100, build(callback)); } else { webpack(webpackConfig).run(build(callback)); } function build (done) { return (err, stats) => { if (err) { throw new $util.PluginError('webpack', err); } else { $util.log($util.colors.green('[webpack]'), stats.toString()); } if (!guard && done) { guard = true; done(); } }; } }); // Compiles and deploys HTML files. gulp.task('html', () => { return gulp.src(config.html.entry) .pipe($pug()) .pipe(gulp.dest(config.html.output)); }); // Files revision. gulp.task('rev', (callback) => { gulp.src(config.rev.entry) .pipe($rev()) .pipe(gulp.dest(config.rev.output)) .pipe($rev.manifest(config.rev.manifestFile)) .pipe(gulp.dest(config.rev.output)) .on('end', () => { const manifestFile = path.join(config.rev.output, config.rev.manifestFile); const manifest = require(manifestFile); let removables = []; let pattern = (_.keys(manifest)).join('|'); for (let v in manifest) { if (v !== manifest[v]) { removables.push(path.join(config.rev.output, v)); } } removables.push(manifestFile); rimraf(`{${removables.join(',')}}`) .then(() => { if (!_.isEmpty(config.cdn)) { gulp.src(config.rev.replace) .pipe($replace(new RegExp(`((?:\\.?\\.\\/?)+)?([\\/\\da-z\\.-]+)(${pattern})`, 'gi'), (m) => { let k = m.match(new RegExp(pattern, 'i'))[0]; let v = manifest[k]; return m.replace(k, v).replace(/^((?:\.?\.?\/?)+)?/, _.endsWith(config.cdn, '/') ? config.cdn : `${config.cdn}/`); })) .pipe(gulp.dest(config.rev.output)) .on('end', callback) .on('error', callback); } else { gulp.src(config.rev.replace) .pipe($replace(new RegExp(`${pattern}`, 'gi'), (m) => (manifest[m]))) .pipe(gulp.dest(config.rev.output)) .on('end', callback) .on('error', callback); } }); }) .on('error', callback); }); // Watch for file changes. gulp.task('watch', () => { config.watch.entries.map((entry) => { gulp.watch(entry.files, { cwd: config.sourceDir }, entry.tasks); }); gulp.watch([ 'public/**/*.html', 'public/**/*.js' ]).on('change', () => { browserSync.reload(); }); }); gulp.task('default', () => { let seq = [ 'images', 'files', 'javascripts', 'stylesheets', 'html' ]; if (config.env.debug) { seq.push('server'); seq.push('watch'); } rimraf(config.buildDir) .then(() => { sequence(...seq); }) .catch((error) => { throw error; }); });
Genert/bsp-viewer
gulpfile.babel.js
JavaScript
gpl-3.0
5,487
/*****************************************************************************/ /* _QnA: Event Handlers and Helpers .js*/ /*****************************************************************************/ Template._QnA.events({ "submit #newQuestion": function (e, tmpl) { e.preventDefault(); var question = Utils.forms.sArrayToObject($(e.currentTarget).serializeArray()) , chatter = tmpl.data && tmpl.data.chatter; if (!chatter) { Growl.error("Could not find chatter."); return; } if (question.message) { question.chatterId = chatter._id; Meteor.call("/app/chatters/add/question", question, function (err, result) { if (err) { Growl.error(err); } else { $(e.currentTarget)[0].reset(); } }); } else { Growl.error("Please add some text and try again.", { title: "Doh?!" }); } return false; } , "click a[href=#voteUp]": function (e) { e.preventDefault(); Meteor.call("/app/questions/vote", { "count": 1, "questionId": this._id }, function (err, result) { if (err) { Growl.error(err); } }); } , "click a[href=#voteDown]": function (e) { e.preventDefault(); Meteor.call("/app/questions/vote", { "count": -1, "questionId": this._id }, function (err, result) { if (err) { Growl.error(err); } }); } }); Template._QnA.helpers({ replyCount: function () { var _count = parseInt(this.replyCount) || 0; return { "num": _count, "label": (_count === 1) ? "reply" : "replies" }; } , questionActions: function () { var loggedInUser = Meteor.user() , actions = [] , editPath = Router.routes["questions.edit"].path({ "chatterId": this.chatterId, "_id": this._id }) , deletePath = Router.routes["questions.delete"].path({ "chatterId": this.chatterId, "_id": this._id }); if (this.created.by === loggedInUser._id || Roles.userIsInRole(loggedInUser, ["admin-role"])) { actions.push({ "actionPath": editPath, "actionLabel": "Edit" }); actions.push({ "actionPath": deletePath, "actionLabel": "Delete" }); } return actions; } }); /*****************************************************************************/ /* _QnA: Lifecycle Hooks */ /*****************************************************************************/ Template._QnA.created = function () { }; Template._QnA.rendered = function () { }; Template._QnA.destroyed = function () { };
fletchtj/BackRowChatter
client/views/chatters/chatters_qna/chatters_qna.js
JavaScript
gpl-3.0
2,484
(function($){ /* * VGA, SVGA, QVGA */ libDraw.ns('risc.hw.vga'); // Text mode... // /* CGA 16 colors pallete: */ var _CGA_PALLETE = [ '#000000', '#0000AA', '#00AA00', '#00AAAA', '#AA0000', '#AA00AA', '#AA5500', '#AAAAAA', '#555555', '#5555FF', '#55FF55', '#55FFFF', '#FF5555', '#FF55FF', '#FFFF55', '#FFFFFF' ]; var _RESOLUTION_MODES = { 'CGA_80_25': { width: 640, height: 200, cols: 80, rows: 25, charWidth: 8, charHeight: 8, font: '8px monospace', fontHeight: 8 }, 'VGA_80_25': { width: 720, height: 400, cols:80, rows: 25, charWidth: 9, charHeight: 16, font: '12px monospace', fontHeight: 12 } }; var VGA = function(config){ libDraw.ext(this, config); this.mode = _RESOLUTION_MODES[config.mode || 'VGA_80_25']; if(!this.mode){ throw new Error('Mode [' + config.mode + '] is not valid VGA mode.'); } if(!this.memory){ throw new Error('Not attached to memory!'); } this.origin = this.origin || 0xB8000; if(this.memory.length < this.origin+(this.mode.rows*this.mode.cols*2)){ throw new Error("Not enough memory. Unable to map physical memory at 0x" + risc.utils.wToHex(this.origin)); } this.cache = new Int32Array(this.mode.cols*this.mode.rows/2); if(!this.runtime){ var canvas = $('<canvas class="vga-canvas"></canvas>')[0]; this.runtime = new libDraw.pkg.runtime.Runtime({ spec: { width: this.mode.width, height: this.mode.height, canvas: canvas }, clock:{ interval: 100, // 10 FPS mode: 'interval' } }); $(this.appendTo || document.body).append(canvas); } var self = this; this.runtime.register(function(g, frame, rt){ self.draw(g, rt); }); }; libDraw.ext(VGA,{ turnOn: function(){ this.runtime.clock.start(); // for now }, turnOff: function(){ this.runtime.clock.stop(); // for now }, draw: function(g,rt){ var total = this.mode.rows*this.mode.cols/2; if(!this.bgset){ this.bgset = true; g.background('#000'); } g.setFont(this.mode.font); var l = 0; var row = 0; var col = 0; var originW = this.origin>>2; // div by 4 for(var i = 0; i < total; i++){ if(this.cache[i] != this.memory[originW+i]){ this.cache[i] = this.memory[originW+i]; l = i*2; row = Math.floor(l/this.mode.cols); col = l%this.mode.cols; this.__printCharacter(row,col, this.cache[i], g); col++; if(col >= this.mode.cols){ col = 0; row++; } this.__printCharacter(row,col, this.cache[i]>>16, g); } } }, __printCharacter: function(row, col, char, graphics){ graphics.fill('#000'); graphics.rect(col*this.mode.charWidth, row*this.mode.charHeight, this.mode.charWidth, this.mode.charHeight); graphics.fill(_CGA_PALLETE[(char>>12)&0xF]); graphics.rect(col*this.mode.charWidth, row*this.mode.charHeight, this.mode.charWidth, this.mode.charHeight); graphics.fill(_CGA_PALLETE[(char>>8)&0xF]); graphics.stroke(_CGA_PALLETE[(char>>8)&0xF]); graphics.text(String.fromCharCode(char&0xFF), col*this.mode.charWidth, row*this.mode.charHeight+this.mode.fontHeight); }, writeText: function(row, col, text, fgColor, bgColor){ for(var i = 0; i < text.length; i++){ col++; if(col>=this.mode.cols){ col=0; row++; } if(row>=this.mode.rows) break; this.__writeChar(row,col,text[i],fgColor,bgColor); } }, __writeChar: function(row, col, char, fgColor, bgColor){ var origin = this.origin>>2; var halfWord = row*this.mode.cols+col; var word = Math.floor(halfWord/2) + origin; var sh = (halfWord%2)*16; var int32 = char.charCodeAt(0) | ((fgColor&0xF)<<12) | ((bgColor&0xF)<<8); this.memory[word] = this.memory[word]&(~(0xFFFF<<sh)) | int32<<sh; //console.log('PRINTED CHAR IN WORD: ', word, ' -> ', risc.utils.wToHex(this.memory[word])); } }); risc.hw.vga.VGA = VGA; })(jQuery);
natemago/primer
src/hw/vga.js
JavaScript
gpl-3.0
5,034
isc.defineClass("BrewClubs", "myWindow").addProperties({ initWidget: function(initData){ this.Super("initWidget", arguments); this.BrewClubsDS = isc.myDataSource.create({ cacheAllData: false, dataURL: serverPath + "BrewClubs.php", showFilterEditor: true, fields:[ {name: "clubID", primaryKey: true, type: "sequence", detail: true, canEdit: false}, {name: "LastYear", width: 75, prompt: "The last year this club as invited.", canEdit: false}, {name: "clubName", width: "*"}, {name: "clubAbbr", width: 75}, {name: "distance", type: "integer", width: 65}, {name: "city", width: 150}, {name: "state", width: 50}, {name: "active", type: "text", width: 50, editorType: "selectItem", defaultValue: "Y", optionDataSource: isc.Clients.yesNoDS, displayField: "displayLOV", valueField: "valueLOV"}, {name: "lastChangeDate", type: "date", detail: true, canEdit: false} ] }); this.BrewClubsLG = isc.myListGrid.create({ dataSource: this.BrewClubsDS, name: "Brew Clubs", parent: this, showFilterEditor: true, sortField: "clubName" }); this.localContextMenu = isc.myClubMenu.create({ callingListGrid: this.BrewClubsLG, parent: this }); this.addItem(isc.myVLayout.create({members: [this.BrewClubsLG]})); this.BrewClubsLG.canEdit = checkPerms(this.getClassName() + ".js"); this.BrewClubsLG.filterData({active: "Y"}); } });
braddoro/cabrew
bluehost/smart/client/BrewClubs.js
JavaScript
gpl-3.0
1,399
/* eslint-disable react/prop-types */ /* eslint-disable react/destructuring-assignment */ /* eslint-disable react/prefer-stateless-function */ import React, { Component } from 'react'; import IconButton from '@material-ui/core/IconButton'; import CloseIcon from '@material-ui/icons/Close'; import { withStyles } from '@material-ui/core/styles'; const styles = { btnIco: { float: 'right', }, }; class CloseModal extends Component { render() { return ( <IconButton style={styles.btnIco} edge="start" color="inherit" onClick={() => { this.props.callbackParent(); }} aria-label="close" > <CloseIcon /> </IconButton> ); } } export default withStyles(styles)(CloseModal);
linea-it/dri
frontend/landing_page/src/pages/Home/partials/ModalInterfaces/CloseModal.js
JavaScript
gpl-3.0
772
module.exports = function (grunt) { var exec = require('child_process').exec; var rimraf = require('rimraf'); var fs = require('fs'); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), connect: { server: { options: { port: 1841, base: __dirname, open: 'http://localhost:1841', keepalive: true, middleware: function (connect, options) { var middlewares = []; var directory = options.directory || options.base[options.base.length - 1]; if (!Array.isArray(options.base)) { options.base = [options.base]; } options.base.forEach(function(base) { // Serve static files. middlewares.push(connect.static(base)); }); // Make directory browse-able. middlewares.push(connect.directory(directory)); middlewares.push(function (req, res, next) { if (req.url == '/cordova.js') { res.writeHead(200, { 'Content-Type': 'text/javascript' }); res.end('console.warn("当前处于网页调试状态,所有设备功能将不可用")'); return; } next(); }); return middlewares; } } } } }); grunt.loadNpmTasks('grunt-contrib-connect'); var registry = grunt.file.readJSON('registry.json'); var readApp = function (method) { var filename = 'app.json' var app = grunt.file.readJSON(filename); method(app); }; var editApp = function (method) { var filename = 'app.json'; readApp(function (app) { method(app); fs.writeFileSync(filename, JSON.stringify(app, null, 4)); }); }; grunt.registerTask('init', function () { var log = grunt.log.write('Installing touch library ...'); var done = this.async(); exec('git submodule update --init', function (err, stdout, stderr) { if (err) { log.error(stderr); done(false); return; } log.ok(); done(); }); }); grunt.registerTask('register', function (packageName) { var log = grunt.log.write('add ' + packageName + ' to app.json...'); editApp(function (app) { if (app.requires.indexOf(packageName) < 0) { app.requires.push(packageName); } }); log.ok(); }); grunt.registerTask('unregister', function (packageName) { var log = grunt.log.write('remove ' + packageName + ' from app.json...'); editApp(function (app) { var index = app.requires.indexOf(packageName); if (!(index < 0)) { app.requires.splice(index, 1); }; }); log.ok(); }); grunt.registerTask('refresh', function () { var log = grunt.log.write('refreshing sencha app...'); var done = this.async(); exec('sencha app refresh', function (err, stdout, stderr) { if (err) { done(false); return; } log.ok(); done(); }); }); grunt.registerTask('download', function (packageName) { var log = grunt.log.write('download ' + packageName + '...'); var done = this.async(); exec('git clone ' + registry[packageName] + ' packages/' + packageName, function (err, stdout, stderr) { if (err) { done(false); return; } log.ok(); done(); }); }); grunt.registerTask('delete', function (packageName) { var log = grunt.log.write('delete ' + packageName + '...'); var done = this.async(); rimraf('packages/' + packageName, function (err) { if (err) { done(false); return; } log.ok(); done(); }); }); grunt.registerTask('ls', function () { var log = grunt.log.writeln('listing installed packages'); readApp(function (app) { console.log(app.requires); }); log.ok(); }); grunt.registerTask('remove', function (packageName) { grunt.task.run('delete:' + packageName, 'unregister:' + packageName, 'refresh'); }); grunt.registerTask('install', function (packageName) { grunt.task.run('delete:' + packageName, 'download:' + packageName, 'register:' + packageName, 'refresh'); }); grunt.registerTask('default', ['connect']); };
gengen1988/bootplate
Gruntfile.js
JavaScript
gpl-3.0
5,163
var class_undoable = [ [ "Undoable", "class_undoable.html#a9b5187143377380164baa7bda8756b30", null ], [ "execute", "class_undoable.html#a8ce5a456598a27152d873ebaeb063e00", null ], [ "isClearingUndoRedo", "class_undoable.html#a58b3ab47ca3687f314542ef72497b858", null ], [ "isExecutable", "class_undoable.html#a98cbf0431ce4ec8a1131f27e965afdcd", null ], [ "isUndoable", "class_undoable.html#a55ea467c2c1006a7cdec39605a9d4348", null ], [ "redo", "class_undoable.html#acf782d879f8241b0ddf3655bb69e30e8", null ], [ "undo", "class_undoable.html#a19f85257c6403dbf4eeb62689f446b48", null ] ];
Ryoga-Unryu/pidgirl-engine
doc/html/class_undoable.js
JavaScript
gpl-3.0
612
'use strict'; angular.module('risevision.common.header') .controller('CompanySettingsModalCtrl', ['$scope', '$modalInstance', 'updateCompany', 'companyId', 'countries', 'REGIONS_CA', 'REGIONS_US', 'TIMEZONES', 'getCompany', 'regenerateCompanyField', '$loading', 'humanReadableError', 'userState', 'userAuthFactory', 'deleteCompany', 'companyTracker', 'confirmModal', '$modal', '$templateCache', 'COMPANY_INDUSTRY_FIELDS', 'COMPANY_SIZE_FIELDS', 'addressFactory', function ($scope, $modalInstance, updateCompany, companyId, countries, REGIONS_CA, REGIONS_US, TIMEZONES, getCompany, regenerateCompanyField, $loading, humanReadableError, userState, userAuthFactory, deleteCompany, companyTracker, confirmModal, $modal, $templateCache, COMPANY_INDUSTRY_FIELDS, COMPANY_SIZE_FIELDS, addressFactory) { $scope.company = { id: companyId }; $scope.countries = countries; $scope.regionsCA = REGIONS_CA; $scope.regionsUS = REGIONS_US; $scope.timezones = TIMEZONES; $scope.COMPANY_INDUSTRY_FIELDS = COMPANY_INDUSTRY_FIELDS; $scope.COMPANY_SIZE_FIELDS = COMPANY_SIZE_FIELDS; $scope.isRiseStoreAdmin = userState.isRiseStoreAdmin(); _clearErrorMessages(); $scope.$watch('loading', function (loading) { if (loading) { $loading.start('company-settings-modal'); } else { $loading.stop('company-settings-modal'); } }); $scope.loading = false; $scope.forms = {}; if (companyId) { $scope.loading = true; getCompany(companyId).then( function (company) { $scope.company = company; $scope.company.isSeller = company && company.sellerId ? true : false; $scope.company.isChargebee = company && company.origin === 'Chargebee'; }, function (resp) { _showErrorMessage('load', resp); }).finally(function () { $scope.loading = false; }); } $scope.closeModal = function () { $modalInstance.dismiss('cancel'); }; $scope.save = function () { _clearErrorMessages(); if (!$scope.forms.companyForm.$valid) { console.info('form not valid: ', $scope.forms.companyForm.$error); } else { $scope.loading = true; addressFactory.isValidOrEmptyAddress($scope.company).then(function () { var company = angular.copy($scope.company); verifyAdmin(company); return updateCompany($scope.company.id, company) .then( function () { companyTracker('Company Updated', userState.getSelectedCompanyId(), userState.getSelectedCompanyName(), !userState.isSubcompanySelected()); userState.updateCompanySettings($scope.company); $modalInstance.close('success'); }).catch(function (error) { _showErrorMessage('update', error); }); }) .catch(function (error) { $scope.formError = 'We couldn\'t update your address.'; $scope.apiError = humanReadableError(error); $scope.isAddressError = true; }) .finally(function () { $scope.loading = false; }); } }; $scope.deleteCompany = function () { _clearErrorMessages(); var instance = $modal.open({ template: $templateCache.get('partials/common-header/safe-delete-modal.html'), controller: 'SafeDeleteModalCtrl' }); instance.result.then(function () { $scope.loading = true; deleteCompany($scope.company.id) .then( function () { companyTracker('Company Deleted', userState.getSelectedCompanyId(), userState.getSelectedCompanyName(), !userState.isSubcompanySelected()); if (userState.getUserCompanyId() === $scope.company.id) { userAuthFactory.signOut(); } else if (userState.getSelectedCompanyId() === $scope.company .id) { userState.resetCompany(); } $modalInstance.close('success'); }) .catch( function (error) { _showErrorMessage('delete', error); }) .finally(function () { $scope.loading = false; }); }); }; var _resetCompanyField = function (type, title, message) { _clearErrorMessages(); return confirmModal(title, message) .then(function () { $loading.start('company-settings-modal'); return regenerateCompanyField($scope.company.id, type) .catch(function (error) { _showErrorMessage('update', error); }) .finally(function () { $loading.stop('company-settings-modal'); }); }); }; $scope.resetAuthKey = function () { var type = 'authKey'; var title = 'Reset Authentication Key', message = 'Resetting the Company Authentication Key will cause existing Data Gadgets ' + 'to no longer report data until they are updated with the new Key.'; _resetCompanyField(type, title, message) .then(function (resp) { $scope.company.authKey = resp.item; }); }; $scope.resetClaimId = function () { var type = 'claimId'; var title = 'Reset Claim Id', message = 'Resetting the Company Claim Id will cause existing installations to no ' + 'longer be associated with your Company.'; _resetCompanyField(type, title, message) .then(function (resp) { $scope.company.claimId = resp.item; }); }; function verifyAdmin(company) { if ($scope.isRiseStoreAdmin) { company.sellerId = company.isSeller ? 'yes' : null; } else { //exclude fields from API call delete company.sellerId; delete company.isTest; delete company.shareCompanyPlan; } } function _clearErrorMessages() { $scope.formError = null; $scope.apiError = null; $scope.isAddressError = false; } function _showErrorMessage(action, error) { $scope.formError = 'Failed to ' + action + ' Company.'; $scope.apiError = humanReadableError(error); } } ]);
Rise-Vision/rise-vision-app-launcher
web/scripts/common-header/controllers/ctr-company-settings-modal.js
JavaScript
gpl-3.0
6,693
var Main = require('../src/Main.purs'); var initialState = require('../src/Types.purs').init; var debug = process.env.NODE_ENV === 'development' if (module.hot) { var app = Main[debug ? 'debug' : 'main'](window.puxLastState || initialState)(); app.state.subscribe(function (state) { window.puxLastState = state; }); module.hot.accept(); } else { Main[debug ? 'debug' : 'main'](initialState)(); }
input-output-hk/rscoin-haskell
block-explorer/support/index.js
JavaScript
gpl-3.0
404