<commit_before>// Amara, universalsubtitles.org
//
// Copyright (C) 2012 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

var AmaraDFXPParser = function(AmaraDFXPParser) {
    /*
     * A utility for working with DFXP subs.
     */

    var that = this;
    var $ = window.jQuery.noConflict();

    this.init = function(xml) {

        // Store the original XML for comparison later.
        this.$originalXml = $(xml.documentElement).clone();

        // Store the working XML for local edits.
        this.$xml = $(xml.documentElement).clone();

    };

    // Helper methods.
    this.utils = {

        xmlToString: function(xml) {
            /*
             * Convert an XML document to a string.
             * Accepts: document object (XML tree)
             * Returns: string
             */

            var xmlString;

            // For Internet Explorer.
            if (window.ActiveXObject) {
                xmlString = xml.xml;

            // Everyone else.
            } else {
                xmlString = (new XMLSerializer()).serializeToString(xml);
            }

            return xmlString;
        }

    };

    this.addSubtitle = function(after, newAttrs, content) {
        /*
         * For adding a new subtitle to this set.
         *
         * If `after` is provided, we'll place the new subtitle directly
         * after that one. Otherwise, we'll place the new subtitle at the
         * end.
         *
         * `newAttrs` is an optional JSON object specifying the attributes to
         * be applied to the new element.
         *
         * `content` is an optional string to set the initial content.
         *
         * Returns: new subtitle element
         */

        if (typeof after != 'number') {
            after = this.getLastSubtitle();
        }

        // Create the new element manually. If you create with jQuery, it'll use
        // the document's namespace as the default namespace, which is ugly.
        var newSubtitle = document.createElementNS('', 'p');

        // Init the default attrs and combine them with the defined newAttrs if
        // required.
        newAttrs = $.extend({
            'begin': '',
            'end': ''
        }, newAttrs);

        var $newSubtitle = $(newSubtitle).attr(newAttrs);

        if (typeof content !== 'undefined') {
            this.content($newSubtitle, content);
        }

        // Finally, place the new subtitle.
        //
        // If after is -1, we need to place the subtitle at the beginning.
        if (after === -1) {

            // Get the very first subtitle.
            var $firstSubtitle = this.getSubtitle(0);

            // Place this new subtitle before the first subtitle.
            $firstSubtitle.before($newSubtitle);

        // Otherwise, place it after the designated subtitle.
        } else {

            // First just make sure that the previous subtitle exists.
            var $previousSubtitle = this.getSubtitle(after);

            // Then place it.
            $previousSubtitle.after($newSubtitle);
        }

        return $newSubtitle.get(0);
    };
    this.changesMade = function() {
        /*
         * Check to see if any changes have been made to the working XML.
         *
         * Returns: true || false
         */

        var originalString = that.utils.xmlToString(that.$originalXml.get(0));
        var xmlString = that.utils.xmlToString(that.$xml.get(0));

        return originalString != xmlString;
    };
    this.content = function(indexOrElement, content) {
        /*
         * Either get or set the HTML content for the subtitle.
         *
         * Returns: current content (string)
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        if (typeof content !== 'undefined') {
            $subtitle.text(content);
        }

        // OK. So, when parsing an XML node, you can't just get the HTML content.
        // We need to retrieve the total contents of the node by using "contents()",
        // but that returns an array of objects, like ['', 'hi', '', '
'],
        // etc. So we create a temporary div, and append the array to it, and retrieve
        // the rendered HTML that way. Then remove the temporary div.
        //
        // Reference: http://bit.ly/SwbPeR
        return $('
').append($subtitle.contents().clone()).remove().html();

    };
    this.endTime = function(indexOrElement, endTime) {
        /*
         * Either get or set the end time for the subtitle.
         *
         * Returns: current end time (string)
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        if (typeof endTime !== 'undefined') {
            $subtitle.attr('end', endTime);
        }

        return $subtitle.attr('end');
    };
    this.getFirstSubtitle = function() {
        /*
         * Retrieve the first subtitle in this set.
         *
         * Returns: first subtitle element
         */

        return this.getSubtitle(0).get(0);
    };
    this.getLastSubtitle = function() {
        /*
         * Retrieve the last subtitle in this set.
         *
         * Returns: last subtitle element
         */

        // Cache the selection.
        var $subtitles = this.getSubtitles();

        return this.getSubtitle($subtitles.length - 1).get(0);
    };
    this.getSubtitle = function(indexOrElement) {
        /*
         * Returns: jQuery selection of element
         */

        // If an index or an object is not provided, throw an error.
        if (typeof indexOrElement !== 'number' && typeof indexOrElement !== 'object') {
            throw new Error('DFXP: You must supply either an index or an element.');
        }

        var subtitle;

        // If indexOrElement is a number, we'll need to query the DOM to
        // get the element.
        //
        // Note: you should only use this approach for checking one-off
        // subtitles. If you're checking more than one subtitle, it's much
        // faster to pass along pre-selected elements instead.
        if (typeof indexOrElement === 'number') {
            subtitle = this.getSubtitles().get(indexOrElement);

        // Otherwise, just use the element.
        } else {
            subtitle = indexOrElement;
        }

        if (!subtitle) {
            throw new Error('DFXP: No subtitle exists with that index.');
        }

        return $(subtitle);
    };
    this.getSubtitles = function() {
        /*
         * Retrieve the current set of subtitles.
         *
         * Returns: jQuery selection of nodes
         */

        return $('div > p', this.$xml);
    };
    this.needsAnySynced = function() {
        /*
         * Determine whether any of the subtitles in the set need
         * to be synced.
         *
         * Returns: true || false
         */

        var needsAnySynced = false;

        // Caching the current subtitle set drastically cuts down on processing
        // time for iterating through large subtitle sets.
        var $subtitles = this.getSubtitles();

        for (var i = 0; i < $subtitles.length; i++) {

            // We're going to pass the actual element instead of an integer. This
            // means needsSyncing doesn't need to hit the DOM to find the element.
            if (this.needsSyncing($subtitles.get(i))) {
                needsAnySynced = true;
            }
        }

        return needsAnySynced;
    };
    this.needsSyncing = function(indexOrElement) {
        /*
         * Given the zero-index or the element of the subtitle to be
         * checked, determine whether the subtitle needs to be synced.
         *
         * In most cases, if a subtitle has either no start time,
         * or no end time, it needs to be synced. However, if the
         * subtitle is the last in the list, the end time may be
         * omitted.
         *
         * Returns: true || false
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        var startTime = $subtitle.attr('begin');
        var endTime = $subtitle.attr('end');

        // If start time is empty, it always needs to be synced.
        if (startTime === '') {
            return true;
        }

        // If the end time is empty and this is not the last subtitle,
        // it needs to be synced.
        if (endTime === '' && (subtitle !== this.getLastSubtitle())) {
            return true;
        }

        // Otherwise, we're good.
        return false;
    };
    this.removeSubtitle = function(indexOrElement) {
        /*
         * Given the zero-index of the subtitle to be removed,
         * remove it from the node tree.
         *
         * Returns: true
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        $subtitle.remove();

        return true;
    };
    this.startTime = function(indexOrElement, startTime) {
        /*
         * Either get or set the start time for the subtitle.
         *
         * Returns: current start time (string)
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        if (typeof startTime !== 'undefined') {
            $subtitle.attr('begin', startTime);
        }

        return $subtitle.attr('begin');
    };
    this.subtitlesCount = function() {
        /*
         * Retrieve the current number of subtitles.
         *
         * Returns: integer
         */

        return this.getSubtitles().length;
    };
};
<commit_msg>Helper functions for getting XML strings for DFXP parser.<commit_after>// Amara, universalsubtitles.org
//
// Copyright (C) 2012 Participatory Culture Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see
// http://www.gnu.org/licenses/agpl-3.0.html.

var AmaraDFXPParser = function(AmaraDFXPParser) {
    /*
     * A utility for working with DFXP subs.
     */

    var that = this;
    var $ = window.jQuery.noConflict();

    this.init = function(xml) {

        // Store the original XML for comparison later.
        this.$originalXml = $(xml.documentElement).clone();

        // Store the working XML for local edits.
        this.$xml = $(xml.documentElement).clone();

    };

    // Helper methods.
    this.utils = {

        xmlToString: function(xml) {
            /*
             * Convert an XML document to a string.
             * Accepts: document object (XML tree)
             * Returns: string
             */

            var xmlString;

            // For Internet Explorer.
            if (window.ActiveXObject) {
                xmlString = xml.xml;

            // Everyone else.
            } else {
                xmlString = (new XMLSerializer()).serializeToString(xml);
            }

            return xmlString;
        }

    };

    this.addSubtitle = function(after, newAttrs, content) {
        /*
         * For adding a new subtitle to this set.
         *
         * If `after` is provided, we'll place the new subtitle directly
         * after that one. Otherwise, we'll place the new subtitle at the
         * end.
         *
         * `newAttrs` is an optional JSON object specifying the attributes to
         * be applied to the new element.
         *
         * `content` is an optional string to set the initial content.
         *
         * Returns: new subtitle element
         */

        if (typeof after != 'number') {
            after = this.getLastSubtitle();
        }

        // Create the new element manually. If you create with jQuery, it'll use
        // the document's namespace as the default namespace, which is ugly.
        var newSubtitle = document.createElementNS('', 'p');

        // Init the default attrs and combine them with the defined newAttrs if
        // required.
        newAttrs = $.extend({
            'begin': '',
            'end': ''
        }, newAttrs);

        var $newSubtitle = $(newSubtitle).attr(newAttrs);

        if (typeof content !== 'undefined') {
            this.content($newSubtitle, content);
        }

        // Finally, place the new subtitle.
        //
        // If after is -1, we need to place the subtitle at the beginning.
        if (after === -1) {

            // Get the very first subtitle.
            var $firstSubtitle = this.getSubtitle(0);

            // Place this new subtitle before the first subtitle.
            $firstSubtitle.before($newSubtitle);

        // Otherwise, place it after the designated subtitle.
        } else {

            // First just make sure that the previous subtitle exists.
            var $previousSubtitle = this.getSubtitle(after);

            // Then place it.
            $previousSubtitle.after($newSubtitle);
        }

        return $newSubtitle.get(0);
    };
    this.changesMade = function() {
        /*
         * Check to see if any changes have been made to the working XML.
         *
         * Returns: true || false
         */

        var originalString = that.utils.xmlToString(that.$originalXml.get(0));
        var xmlString = that.utils.xmlToString(that.$xml.get(0));

        return originalString != xmlString;
    };
    this.content = function(indexOrElement, content) {
        /*
         * Either get or set the HTML content for the subtitle.
         *
         * Returns: current content (string)
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        if (typeof content !== 'undefined') {
            $subtitle.text(content);
        }

        // OK. So, when parsing an XML node, you can't just get the HTML content.
        // We need to retrieve the total contents of the node by using "contents()",
        // but that returns an array of objects, like ['', 'hi', '', '
'],
        // etc. So we create a temporary div, and append the array to it, and retrieve
        // the rendered HTML that way. Then remove the temporary div.
        //
        // Reference: http://bit.ly/SwbPeR
        return $('
').append($subtitle.contents().clone()).remove().html();

    };
    this.endTime = function(indexOrElement, endTime) {
        /*
         * Either get or set the end time for the subtitle.
         *
         * Returns: current end time (string)
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        if (typeof endTime !== 'undefined') {
            $subtitle.attr('end', endTime);
        }

        return $subtitle.attr('end');
    };
    this.getFirstSubtitle = function() {
        /*
         * Retrieve the first subtitle in this set.
         *
         * Returns: first subtitle element
         */

        return this.getSubtitle(0).get(0);
    };
    this.getLastSubtitle = function() {
        /*
         * Retrieve the last subtitle in this set.
         *
         * Returns: last subtitle element
         */

        // Cache the selection.
        var $subtitles = this.getSubtitles();

        return this.getSubtitle($subtitles.length - 1).get(0);
    };
    this.getSubtitle = function(indexOrElement) {
        /*
         * Returns: jQuery selection of element
         */

        // If an index or an object is not provided, throw an error.
        if (typeof indexOrElement !== 'number' && typeof indexOrElement !== 'object') {
            throw new Error('DFXP: You must supply either an index or an element.');
        }

        var subtitle;

        // If indexOrElement is a number, we'll need to query the DOM to
        // get the element.
        //
        // Note: you should only use this approach for checking one-off
        // subtitles. If you're checking more than one subtitle, it's much
        // faster to pass along pre-selected elements instead.
        if (typeof indexOrElement === 'number') {
            subtitle = this.getSubtitles().get(indexOrElement);

        // Otherwise, just use the element.
        } else {
            subtitle = indexOrElement;
        }

        if (!subtitle) {
            throw new Error('DFXP: No subtitle exists with that index.');
        }

        return $(subtitle);
    };
    this.getSubtitles = function() {
        /*
         * Retrieve the current set of subtitles.
         *
         * Returns: jQuery selection of nodes
         */

        return $('div > p', this.$xml);
    };
    this.needsAnySynced = function() {
        /*
         * Determine whether any of the subtitles in the set need
         * to be synced.
         *
         * Returns: true || false
         */

        var needsAnySynced = false;

        // Caching the current subtitle set drastically cuts down on processing
        // time for iterating through large subtitle sets.
        var $subtitles = this.getSubtitles();

        for (var i = 0; i < $subtitles.length; i++) {

            // We're going to pass the actual element instead of an integer. This
            // means needsSyncing doesn't need to hit the DOM to find the element.
            if (this.needsSyncing($subtitles.get(i))) {
                needsAnySynced = true;
            }
        }

        return needsAnySynced;
    };
    this.needsSyncing = function(indexOrElement) {
        /*
         * Given the zero-index or the element of the subtitle to be
         * checked, determine whether the subtitle needs to be synced.
         *
         * In most cases, if a subtitle has either no start time,
         * or no end time, it needs to be synced. However, if the
         * subtitle is the last in the list, the end time may be
         * omitted.
         *
         * Returns: true || false
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        var startTime = $subtitle.attr('begin');
        var endTime = $subtitle.attr('end');

        // If start time is empty, it always needs to be synced.
        if (startTime === '') {
            return true;
        }

        // If the end time is empty and this is not the last subtitle,
        // it needs to be synced.
        if (endTime === '' && (subtitle !== this.getLastSubtitle())) {
            return true;
        }

        // Otherwise, we're good.
        return false;
    };
    this.originalXmlToString = function() {
        return this.utils.xmlToString(this.$originalXml.get(0));
    };
    this.removeSubtitle = function(indexOrElement) {
        /*
         * Given the zero-index of the subtitle to be removed,
         * remove it from the node tree.
         *
         * Returns: true
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        $subtitle.remove();

        return true;
    };
    this.startTime = function(indexOrElement, startTime) {
        /*
         * Either get or set the start time for the subtitle.
         *
         * Returns: current start time (string)
         */

        var $subtitle = this.getSubtitle(indexOrElement);

        if (typeof startTime !== 'undefined') {
            $subtitle.attr('begin', startTime);
        }

        return $subtitle.attr('begin');
    };
    this.subtitlesCount = function() {
        /*
         * Retrieve the current number of subtitles.
         *
         * Returns: integer
         */

        return this.getSubtitles().length;
    };
    this.xmlToString = function() {
        return this.utils.xmlToString(this.$xml.get(0));
    };
};
<|endoftext|>


<commit_before>async function postgres_sql(args) {
/*
description("Postgres function")
base_component_id("postgres_server")
load_once_from_file(true)
only_run_on_server(true)
*/
    var config = {
      user:              args.user,
      database:          args.database,
      password:          args.password,
      host:              args.host,
      port:              args.port
    };

    console.log("postgres_server: " + JSON.stringify(args,null,2));

    var promise = new Promise(async function(returnFn) {

        var dbconnection = new postgresdb.Client(config);
        dbconnection.connect(function (err) {
          if (err) {
              console.log({error: '' + err});
              returnFn({failed: err})
          } else {
              dbconnection.query(args.sql, [], function (err, result) {
                if (err) {
                    console.log({failed: '' + err});
                } else {
                    console.log("row count: " + result.rows.length); // outputs: { name: 'brianc' }
                    if (args.limit) {
                        result.rows = result.rows.slice(0, args.limit);
                    }
                    returnFn({value: result.rows})
                };
              })

          }
        });

    })
    var ret = await promise

    return ret
}
<commit_msg>Allow Postgres DB driver to return the list of tables<commit_after>async function postgres_sql(args) {
/*
description("Postgres function")
base_component_id("postgres_server")
load_once_from_file(true)
only_run_on_server(true)
*/
    var config = {
      user:              args.user,
      database:          args.database,
      password:          args.password,
      host:              args.host,
      port:              args.port
    };

    console.log("postgres_server: " + JSON.stringify(args,null,2));

    var promise = new Promise(async function(returnFn) {

        var dbconnection = new postgresdb.Client(config);
        dbconnection.connect(function (err) {
          if (err) {
              console.log({error: '' + err});
              returnFn({failed: err})
          } else {
              var useSql = args.sql
              if (args.get_tables) {
                  useSql = "SELECT tablename as name FROM pg_catalog.pg_tables where schemaname = 'public';"
              }
              dbconnection.query(useSql, [], function (err, result) {
                if (err) {
                    console.log({failed: '' + err});
                } else {
                    console.log("row count: " + result.rows.length); // outputs: { name: 'brianc' }
                    if (args.limit) {
                        result.rows = result.rows.slice(0, args.limit);
                    }
                    returnFn({value: result.rows})
                };
              })

          }
        });

    })
    var ret = await promise

    return ret
}
<|endoftext|>


<commit_before>/*
 * Copyright 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview JavaScript Built-Ins for windows properties.
 *
 * @externs
 */

// Window properties
// Only common properties are here.  Others such as open()
// should be used with an explicit Window object.

/**
 * @type {!Window}
 * @see https://developer.mozilla.org/en/DOM/window.top
 * @const
 */
var top;

/**
 * @type {Navigator}
 * @see https://developer.mozilla.org/en/DOM/window.navigator
 * @const
 */
var navigator;

/**
 * @type {!HTMLDocument}
 * @see https://developer.mozilla.org/en/DOM/window.document
 * @const
 */
var document;

/**
 * @type {Location}
 * @see https://developer.mozilla.org/en/DOM/window.location
 * @const
 * @suppress {duplicate}
 */
var location;

/**
 * @see https://developer.mozilla.org/En/DOM/Window.screen
 * @const
 */
var screen;

/**
 * @type {!Window}
 * @see https://developer.mozilla.org/En/DOM/Window.self
 * @const
 */
var self;

// Magic functions for Firefox's LiveConnect.
// We'll probably never use these in practice. But redefining them
// will fire up the JVM, so we want to reserve the symbol names.

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/JavaArray
 */
var JavaArray;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/JavaClass
 */
var JavaClass;

// We just ripped this from the FF source; it doesn't appear to be
// publicly documented.
var JavaMember;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/JavaObject
 */
var JavaObject;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/JavaPackage
 */
var JavaPackage;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Packages
 */
var Packages;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/java
 */
var java;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/netscape
 */
var netscape;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/sun
 */
var sun;

// Magic variable for Norton Identity Protection's Chrome extension.  This
// program will overwrite whatever's stored in the variable 'o' with random
// values, so we want to avoid it.
// NOTE(user): Added 8-30-2012.  We may want to remove this once Norton
// Identity Protection has been fixed and pushed to most people.
var o;

/**
 * @see https://developer.mozilla.org/en/DOM/window.alert
 */
function alert(x) {}

/**
 * @param {number|undefined?} intervalID
 * @see https://developer.mozilla.org/en/DOM/window.clearInterval
 */
function clearInterval(intervalID) {}

/**
 * @param {number|undefined?} timeoutID
 * @see https://developer.mozilla.org/en/DOM/window.clearTimeout
 */
function clearTimeout(timeoutID) {}

/**
 * @see https://developer.mozilla.org/en/DOM/window.confirm
 */
function confirm(x) {}

/**
 * @see https://developer.mozilla.org/en/DOM/window.dump
 */
function dump(x) {}

/**
 * @param {string} message
 * @param {string=} opt_value
 * @return {?string}
 * @see https://developer.mozilla.org/en/DOM/window.prompt
 */
function prompt(message, opt_value) {}

/**
 * @param {Function|string} callback
 * @param {number} delay
 * @return {number}
 * @see https://developer.mozilla.org/en/DOM/window.setInterval
 * @see https://msdn.microsoft.com/en-us/library/ms536749(v=VS.85).aspx
 */
function setInterval(callback, delay) {}

/**
 * @param {Function|string} callback
 * @param {number} delay
 * @return {number}
 * @see https://developer.mozilla.org/en/DOM/window.setTimeout
 * @see https://msdn.microsoft.com/en-us/library/ms536753(VS.85).aspx
 */
function setTimeout(callback, delay) {}

/**
 * window.i is overwritten by the Silk Browser on
 * Kindle HD 7.1.5 firmware.
 * Remove this once they have pushed out the fix for this.
 * @suppress {duplicate}
 */
var i;
<commit_msg><commit_after>/*
 * Copyright 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview JavaScript Built-Ins for windows properties.
 *
 * @externs
 */

// Window properties
// Only common properties are here.  Others such as open()
// should be used with an explicit Window object.

/**
 * @type {!Window}
 * @see https://developer.mozilla.org/en/DOM/window.top
 * @const
 */
var top;

/**
 * @type {Navigator}
 * @see https://developer.mozilla.org/en/DOM/window.navigator
 * @const
 */
var navigator;

/**
 * @type {!HTMLDocument}
 * @see https://developer.mozilla.org/en/DOM/window.document
 * @const
 */
var document;

/**
 * @type {Location}
 * @see https://developer.mozilla.org/en/DOM/window.location
 * @const
 * @suppress {duplicate}
 */
var location;

/**
 * @see https://developer.mozilla.org/En/DOM/Window.screen
 * @const
 */
var screen;

/**
 * @type {!Window}
 * @see https://developer.mozilla.org/En/DOM/Window.self
 * @const
 */
var self;

// Magic functions for Firefox's LiveConnect.
// We'll probably never use these in practice. But redefining them
// will fire up the JVM, so we want to reserve the symbol names.

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/JavaArray
 */
var JavaArray;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/JavaClass
 */
var JavaClass;

// We just ripped this from the FF source; it doesn't appear to be
// publicly documented.
var JavaMember;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/JavaObject
 */
var JavaObject;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/JavaPackage
 */
var JavaPackage;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Packages
 */
var Packages;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/java
 */
var java;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/netscape
 */
var netscape;

/**
 * @see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/sun
 */
var sun;

// Magic variable for Norton Identity Protection's Chrome extension.  This
// program will overwrite whatever's stored in the variable 'o' with random
// values, so we want to avoid it.
// NOTE(user): Added 8-30-2012.  We may want to remove this once Norton
// Identity Protection has been fixed and pushed to most people.
var o;

/**
 * @see https://developer.mozilla.org/en/DOM/window.alert
 */
function alert(x) {}

/**
 * @param {number|undefined?} intervalID
 * @see https://developer.mozilla.org/en/DOM/window.clearInterval
 */
function clearInterval(intervalID) {}

/**
 * @param {number|undefined?} timeoutID
 * @see https://developer.mozilla.org/en/DOM/window.clearTimeout
 */
function clearTimeout(timeoutID) {}

/**
 * @see https://developer.mozilla.org/en/DOM/window.confirm
 */
function confirm(x) {}

/**
 * @see https://developer.mozilla.org/en/DOM/window.dump
 */
function dump(x) {}

/**
 * @param {string} message
 * @param {string=} opt_value
 * @return {?string}
 * @see https://developer.mozilla.org/en/DOM/window.prompt
 */
function prompt(message, opt_value) {}

/**
 * @param {Function|string} callback
 * @param {number} delay
 * @return {number}
 * @see https://developer.mozilla.org/en/DOM/window.setInterval
 * @see https://msdn.microsoft.com/en-us/library/ms536749(v=VS.85).aspx
 */
function setInterval(callback, delay) {}

/**
 * @param {Function|string} callback
 * @param {number} delay
 * @return {number}
 * @see https://developer.mozilla.org/en/DOM/window.setTimeout
 * @see https://msdn.microsoft.com/en-us/library/ms536753(VS.85).aspx
 */
function setTimeout(callback, delay) {}
<|endoftext|>


<commit_before>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: dispatch_module.js
 */

module.exports = {
    malloc: function (fibre_val) {
        return new DispatchObject(fibre_val);
    },
};

function DispatchObject(fibre_val) {
    "use strict";
    this.theFibreObject = fibre_val;

    this.linkModuleMalloc = function (my_name_val, link_id_val) {
        var link_module = require("./link_module.js");
        return link_module.malloc(this, my_name_val, link_id_val);
    };

    this.objectName = function () {
        return "DispatchObject";
    };

    this.fibreObject = function () {
        return this.theFibreObject;
    };

    this.rootObject = function () {
        return this.fibreObject().rootObject();
    };

    this.utilObject = function () {
        return this.rootObject().utilObject();
    };

    this.linkMgrObject = function () {
        return this.fibreObject().linkMgrObject();
    };

    this.sessionMgrObject = function () {
        return this.fibreObject().sessionMgrObject();
    };

    this.dispatchRequest = function (go_request) {
        this.debug(false, "dispatchRequest", "command=" + go_request.command);

        if (go_request.command === "setup_link") {
            return this.setupLink(go_request);
        }

        if (go_request.command === "keep_alive") {
            this.abend("dispatchRequest", "keep_alive gorequest=");
            return this.keepAlive(go_request);
        }

        if (go_request.command === "get_link_data") {
            return this.getLinkData(go_request);
        }

        if (go_request.command === "put_link_data") {
            this.abend("dispatchRequest", "put_link_data");
            return this.putLinkData(go_request);
        }

        if (go_request.command === "get_name_list") {
            return this.getNameList(go_request);
        }

        if (go_request.command === "setup_session") {
            return this.setupSession(go_request);
        }

        if (go_request.command === "get_session_data") {
            return this.getSessionData(go_request);
        }

        if (go_request.command === "put_session_data") {
            return this.putSessionData(go_request);
        }

         this.abend("dispatchRequest", "command=" + go_request.command);
    }

    this.setupLink = function (go_request) {
        if (!go_request) {
            this.abend("setupLink", "null go_request");
            return null;
        }

        var link = this.linkMgrObject().searchAndCreate(go_request.my_name, 0);
        if (!link) {
            res.send(this.jsonStingifyData(req.headers.command, go_request.ajax_id, null));
            this.abend("setupLink", "null link");
            return null;
        } else {
            link.resetKeepAliveTimer();
        }

        var link_id_str = "" + link.linkId();
        this.logit("setupLink", "name=" + go_request.my_name + " link_id=" + link.linkId());
        return link_id_str;
    };

    this.getLinkData = function (go_request) {
        this.debug(false, "getLinkData", "link_id=" + go_request.link_id + " my_name=" + go_request.my_name + " ajax_id=" + go_request.ajax_id);

        var link = this.getLink(go_request);
        if (!link) {
            return null;
        }
        link.resetKeepAliveTimer();

        var data = link.receiveQueue().deQueue();
        if (data) {
            this.logit("getLinkData", "link_id=" + go_request.link_id + " my_name="  + go_request.my_name + " data={" + data + "}");
        }
        return data;
    };

    this.getLink = function (go_request) {
        var link_id = Number(go_request.link_id);
        var link = this.linkMgrObject().searchLink(go_request.my_name, link_id);
        if (!link) {
            //res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            this.abend("getLink", "null link" + "link_id=" + link_id + " my_name=" + go_request.my_name);
            return null;
        }
        if (link.link_id === 0) {
            //res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            this.abend("getLink", "link_id = 0");
            return null;
        }
        return link;
    };

    this.putLinkData111111111 = function (res, go_request) {
        this.debug(true, "putLinkData", "link_id=" + go_request.link_id + " my_name=" + go_request.my_name + " data=" + go_request.data);

        var my_link = this.getLink(res, go_request);
        if (!my_link) {
            return null;
        }
        my_link.resetKeepAliveTimer();

        if (data.order === "setup_session_reply") {
            var data_str = this.sessionMgrObject().preSessionQueue().unQueue(function(data_val, param_val1) {
                return (data_val === param_val1);
            }, go_request.data);
            if (data_str) {
                var data = JSON.parse(go_request.data);
            }

        }
        return data;
    };

    this.getNameList = function (go_request) {
        var link = this.getLink(go_request);
        if (!link) {
            return null;
        }
        link.resetKeepAliveTimer();

        var name_array = this.linkMgrObject().getNameList();
        var name_array_str = JSON.stringify(name_array);
        this.debug(true, "getNameList", "(" + link.linkId() + ",0) " + go_request.my_name + "=>server " + name_array_str);
        return name_array_str;
    };

    this.setupSession = function (go_request) {
        var session = this.sessionMgrObject().searchIt(go_request.my_name, go_request.his_name, Number(go_request.link_id));
        if (!session){
            session = this.sessionMgrObject().searchAndCreate(go_request.my_name, go_request.his_name, 0);
            if (!session) {
                res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
                this.abend("setupSession", "null session");
                return null;
            }
        }

        var his_link = this.linkMgrObject().searchLink(go_request.his_name, 0);
        if (!his_link) {
            res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            return null;
        }

        this.debug(true, "setupSession", "(" + go_request.link_id + "," + session.sessionId() + "," + session.hisSession().sessionId() + ") " + go_request.my_name + "=>" + go_request.his_name + " data=" + go_request.data);

        if (go_request.data !== null) {
            session.clusterObject().processSetupLinkData(go_request.data);
        }

        var session_id_str = "" + session.hisSession().sessionId();
        var data = JSON.stringify({
                        order: "setup_session",
                        session_id: session_id_str,
                        his_name: go_request.my_name,
                        my_name: go_request.his_name,
                        extra_data: go_request.data,
                    });
        his_link.receiveQueue().enQueue(data);
        this.sessionMgrObject().preSessionQueue().enQueue(data)
        return this.setupSessionReply(session, go_request);
    }

    this.setupSessionReply = function (session_val, go_request) {
        var session_id_str = "" + session_val.sessionId();
        var data = JSON.stringify({
                        session_id: session_id_str,
                        extra_data: go_request.data,
                    });
        this.logit("setupSessionReply", "(" + go_request.link_id + "," + session_val.sessionId() + "," + session_val.hisSession().sessionId() + ") " + go_request.my_name + "=>" + go_request.his_name);
        return data;
    };

    this.getSessionData = function (go_request) {
        this.debug(false, "getSessionData", "(" + go_request.link_id + "," + go_request.session_id + ") my_name=" + go_request.my_name + "=>" + go_request.his_name);
        var link = this.getLink(go_request);
        if (!link) {
            return null;
        }
        link.resetKeepAliveTimer();

        var session = this.sessionMgrObject().searchIt(go_request.my_name, go_request.his_name, Number(go_request.session_id));
        if (!session) {
            //res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            this.abend("getSessionData", "null session" + " session_id=" + go_request.session_id);
            return null;
        }

        var res_data = session.dequeueTransmitData();
        if (!res_data) {
            this.debug(false, "getSessionData", "no data");
            //res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            return null;
        }
        this.logit("getSessionData", "res_data=" + res_data);

        this.debug(false, "getSessionData", "ajax_id=" + go_request.ajax_id);
        this.logit("getSessionData", "(" + go_request.link_id + "," + go_request.session_id + ") "  + go_request.his_name + "=>" + go_request.my_name + " {" + res_data + "}");
        return res_data;
    };

    this.putSessionData = function (go_request) {
        //console.log(req.headers);
        this.debug(true, "putSessionData ", "ajax_id=" + go_request.ajax_id);
        this.debug(true, "putSessionData ", "(" + go_request.link_id + "," + go_request.session_id + ") "  + go_request.his_name + "=>" + go_request.my_name + " {" + go_request.data + "}");

        var session_id = Number(go_request.session_id);
        var xmt_seq = Number(go_request.xmt_seq);

        var link = this.getLink(go_request);
        if (!link) {
            return null;
        }
        link.resetKeepAliveTimer();

        var my_session = this.sessionMgrObject().searchIt(go_request.my_name, go_request.his_name, Number(go_request.session_id));
        if (!my_session) {
            res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            this.abend("putSessionData", "null my_session" + " session_id=" + go_request.session_id + " my_name=" + go_request.my_name + " his_name=" + go_request.his_name);
            return null;
        }

        this.debug(true, "putSessionData", "(" + go_request.link_id + "," + go_request.session_id + ") "  + go_request.my_name + "=>" + go_request.his_name + " {" + go_request.data + "} " + go_request.xmt_seq + "=>" + my_session.up_seq);

        if (xmt_seq === my_session.up_seq) {
            my_session.clusterObject().enqueAndPocessReceiveData(go_request.data);
            my_session.up_seq += 1;
        } else if (xmt_seq < my_session.up_seq) {
            if (xmt_seq === 0) {
                my_session.clusterObject().enqueAndPocessReceiveData(go_request.data);
                my_session.up_seq = 1;
                this.logit("putSessionData", go_request.data + " post " + xmt_seq + " reset");
            } else {
                this.logit("putSessionData", "(" + link_id + "," + session_id + ") "  + go_request.my_name + "=>" + go_request.his_name + " {" + go_request.data + "} " + xmt_seq + " dropped");
            }
        } else {
            this.logit("***abend: putSessionData", go_request.data + " post seq=" + xmt_seq + " dropped");
        }

        this.debug(true, "putSessionData", "queue_size=" + my_session.receiveQueue().size());
        return null;
    };

    this.keepAlive1111111111111111 = function (go_request) {
        var my_link_id = Number(go_request.link_id);
        this.debug(false, "keepAlive", "link_id=" + my_link_id + " my_name=" + go_request.my_name);
        var link = this.linkMgrObject().searchLink(go_request.my_name, my_link_id);
        if (!link) {
            res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            this.abend("keepAlive", "***null link***" + "link_id=" + my_link_id + " my_name=" + go_request.my_name);
            return null;
        }
        link.resetKeepAliveTimer();
        return null;
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, "==" + str2_val);
        }
    };

    this.logit = function (str1_val, str2_val) {
        this.utilObject().utilLogit(this.objectName() + "." + str1_val, str2_val);
    };

    this.abend = function (str1_val, str2_val) {
        this.utilObject().utilAbend(this.objectName() + "." + str1_val, str2_val);
    };
}
<commit_msg>number<commit_after>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: dispatch_module.js
 */

module.exports = {
    malloc: function (fibre_val) {
        return new DispatchObject(fibre_val);
    },
};

function DispatchObject(fibre_val) {
    "use strict";
    this.theFibreObject = fibre_val;

    this.linkModuleMalloc = function (my_name_val, link_id_val) {
        var link_module = require("./link_module.js");
        return link_module.malloc(this, my_name_val, link_id_val);
    };

    this.objectName = function () {
        return "DispatchObject";
    };

    this.fibreObject = function () {
        return this.theFibreObject;
    };

    this.rootObject = function () {
        return this.fibreObject().rootObject();
    };

    this.utilObject = function () {
        return this.rootObject().utilObject();
    };

    this.linkMgrObject = function () {
        return this.fibreObject().linkMgrObject();
    };

    this.sessionMgrObject = function () {
        return this.fibreObject().sessionMgrObject();
    };

    this.dispatchRequest = function (go_request) {
        this.debug(false, "dispatchRequest", "command=" + go_request.command);

        if (go_request.command === "setup_link") {
            return this.setupLink(go_request);
        }

        if (go_request.command === "keep_alive") {
            this.abend("dispatchRequest", "keep_alive gorequest=");
            return this.keepAlive(go_request);
        }

        if (go_request.command === "get_link_data") {
            return this.getLinkData(go_request);
        }

        if (go_request.command === "put_link_data") {
            this.abend("dispatchRequest", "put_link_data");
            return this.putLinkData(go_request);
        }

        if (go_request.command === "get_name_list") {
            return this.getNameList(go_request);
        }

        if (go_request.command === "setup_session") {
            return this.setupSession(go_request);
        }

        if (go_request.command === "get_session_data") {
            return this.getSessionData(go_request);
        }

        if (go_request.command === "put_session_data") {
            return this.putSessionData(go_request);
        }

         this.abend("dispatchRequest", "command=" + go_request.command);
    }

    this.setupLink = function (go_request) {
        if (!go_request) {
            this.abend("setupLink", "null go_request");
            return null;
        }

        var link = this.linkMgrObject().searchAndCreate(go_request.my_name, 0);
        if (!link) {
            this.abend("setupLink", "null link");
            return null;
        } else {
            link.resetKeepAliveTimer();
        }

        var link_id_str = "" + link.linkId();
        this.logit("setupLink", "name=" + go_request.my_name + " link_id=" + link.linkId());
        return link_id_str;
    };

    this.getLinkData = function (go_request) {
        this.debug(false, "getLinkData", "link_id=" + go_request.link_id + " my_name=" + go_request.my_name + " ajax_id=" + go_request.ajax_id);

        var link = this.getLink(go_request);
        if (!link) {
            return null;
        }
        link.resetKeepAliveTimer();

        var data = link.receiveQueue().deQueue();
        if (data) {
            this.logit("getLinkData", "link_id=" + go_request.link_id + " my_name="  + go_request.my_name + " data={" + data + "}");
        }
        return data;
    };

    this.getLink = function (go_request) {
        var link = this.linkMgrObject().searchLink(go_request.my_name, go_request.link_id);
        if (!link) {
            this.abend("getLink", "null link" + "link_id=" + go_request.link_id + " my_name=" + go_request.my_name);
            return null;
        }
        if (link.link_id === 0) {
            this.abend("getLink", "link_id = 0");
            return null;
        }
        return link;
    };

    this.getNameList = function (go_request) {
        var link = this.getLink(go_request);
        if (!link) {
            return null;
        }
        link.resetKeepAliveTimer();

        var name_array = this.linkMgrObject().getNameList();
        var name_array_str = JSON.stringify(name_array);
        this.debug(true, "getNameList", "(" + link.linkId() + ",0) " + go_request.my_name + "=>server " + name_array_str);
        return name_array_str;
    };

    this.setupSession = function (go_request) {
        var session = this.sessionMgrObject().searchIt(go_request.my_name, go_request.his_name, go_request.link_id);
        if (!session){
            session = this.sessionMgrObject().searchAndCreate(go_request.my_name, go_request.his_name, 0);
            if (!session) {
                res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
                this.abend("setupSession", "null session");
                return null;
            }
        }

        var his_link = this.linkMgrObject().searchLink(go_request.his_name, 0);
        if (!his_link) {
            res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            return null;
        }

        this.debug(true, "setupSession", "(" + go_request.link_id + "," + session.sessionId() + "," + session.hisSession().sessionId() + ") " + go_request.my_name + "=>" + go_request.his_name + " data=" + go_request.data);

        if (go_request.data !== null) {
            session.clusterObject().processSetupLinkData(go_request.data);
        }

        var session_id_str = "" + session.hisSession().sessionId();
        var data = JSON.stringify({
                        order: "setup_session",
                        session_id: session_id_str,
                        his_name: go_request.my_name,
                        my_name: go_request.his_name,
                        extra_data: go_request.data,
                    });
        his_link.receiveQueue().enQueue(data);
        this.sessionMgrObject().preSessionQueue().enQueue(data)
        return this.setupSessionReply(session, go_request);
    }

    this.setupSessionReply = function (session_val, go_request) {
        var session_id_str = "" + session_val.sessionId();
        var data = JSON.stringify({
                        session_id: session_id_str,
                        extra_data: go_request.data,
                    });
        this.logit("setupSessionReply", "(" + go_request.link_id + "," + session_val.sessionId() + "," + session_val.hisSession().sessionId() + ") " + go_request.my_name + "=>" + go_request.his_name);
        return data;
    };

    this.getSessionData = function (go_request) {
        this.debug(false, "getSessionData", "(" + go_request.link_id + "," + go_request.session_id + ") my_name=" + go_request.my_name + "=>" + go_request.his_name);
        var link = this.getLink(go_request);
        if (!link) {
            return null;
        }
        link.resetKeepAliveTimer();

        var session = this.sessionMgrObject().searchIt(go_request.my_name, go_request.his_name, go_request.session_id);
        if (!session) {
            //res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            this.abend("getSessionData", "null session" + " session_id=" + go_request.session_id);
            return null;
        }

        var res_data = session.dequeueTransmitData();
        if (!res_data) {
            this.debug(false, "getSessionData", "no data");
            //res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            return null;
        }
        this.logit("getSessionData", "res_data=" + res_data);

        this.debug(false, "getSessionData", "ajax_id=" + go_request.ajax_id);
        this.logit("getSessionData", "(" + go_request.link_id + "," + go_request.session_id + ") "  + go_request.his_name + "=>" + go_request.my_name + " {" + res_data + "}");
        return res_data;
    };

    this.putSessionData = function (go_request) {
        //console.log(req.headers);
        this.debug(true, "putSessionData ", "ajax_id=" + go_request.ajax_id);
        this.debug(true, "putSessionData ", "(" + go_request.link_id + "," + go_request.session_id + ") "  + go_request.his_name + "=>" + go_request.my_name + " {" + go_request.data + "}");

        var link = this.getLink(go_request);
        if (!link) {
            return null;
        }
        link.resetKeepAliveTimer();

        var my_session = this.sessionMgrObject().searchIt(go_request.my_name, go_request.his_name, go_request.session_id);
        if (!my_session) {
            res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            this.abend("putSessionData", "null my_session" + " session_id=" + go_request.session_id + " my_name=" + go_request.my_name + " his_name=" + go_request.his_name);
            return null;
        }

        this.debug(true, "putSessionData", "(" + go_request.link_id + "," + go_request.session_id + ") "  + go_request.my_name + "=>" + go_request.his_name + " {" + go_request.data + "} " + go_request.xmt_seq + "=>" + my_session.up_seq);

        if (go_request.xmt_seq === my_session.up_seq) {
            my_session.clusterObject().enqueAndPocessReceiveData(go_request.data);
            my_session.up_seq += 1;
        } else if (go_request.xmt_seq < my_session.up_seq) {
            if (xmt_seq === 0) {
                my_session.clusterObject().enqueAndPocessReceiveData(go_request.data);
                my_session.up_seq = 1;
                this.logit("putSessionData", go_request.data + " post " + xmt_seq + " reset");
            } else {
                this.logit("putSessionData", "(" + link_id + "," + session_id + ") "  + go_request.my_name + "=>" + go_request.his_name + " {" + go_request.data + "} " + xmt_seq + " dropped");
            }
        } else {
            this.logit("***abend: putSessionData", go_request.data + " post seq=" + xmt_seq + " dropped");
        }

        this.debug(true, "putSessionData", "queue_size=" + my_session.receiveQueue().size());
        return null;
    };

    this.keepAlive1111111111111111 = function (go_request) {
        var my_link_id = go_request.link_id;
        this.debug(false, "keepAlive", "link_id=" + my_link_id + " my_name=" + go_request.my_name);
        var link = this.linkMgrObject().searchLink(go_request.my_name, my_link_id);
        if (!link) {
            res.send(this.jsonStingifyData(go_request.command, go_request.ajax_id, null));
            this.abend("keepAlive", "***null link***" + "link_id=" + my_link_id + " my_name=" + go_request.my_name);
            return null;
        }
        link.resetKeepAliveTimer();
        return null;
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, "==" + str2_val);
        }
    };

    this.logit = function (str1_val, str2_val) {
        this.utilObject().utilLogit(this.objectName() + "." + str1_val, str2_val);
    };

    this.abend = function (str1_val, str2_val) {
        this.utilObject().utilAbend(this.objectName() + "." + str1_val, str2_val);
    };
}
<|endoftext|>


<commit_before>app.controller("TrailController", ["$scope", "$routeParams", "$uibModal", "TrailService", function($scope, $routeParams, $uibModal, TrailService) {
	// get the trail from the api
	// come back to add other
	// make doc blocks way better
	$scope.currentTrailId = $routeParams.trailId;
	$scope.currentTrail = null;
	$scope.newTrail = {
		trailId: null,
		userId: null,
		browser: null,
		createDate: null,
		ipAddress: null,
		submitTrailId: null,
		trailAmenities: null,
		trailCondition: null,
		trailDescription: null,
		trailDifficulty: null,
		trailDistance: null,
		trailName: null,
		trailSubmissionType: null,
		trailTerrain: null,
		trailTraffic: null,
		trailUse: null,
		trailUuid: null
	};
	$scope.isEditing = false;
	$scope.points = [];
	$scope.trails = [];
	$scope.alerts = [];
	$scope.trailToSubmit = {};

	$scope.openTrailAlertModal = function() {
		var TrailAlertModalInstance = $uibModal.open({
			templateUrl: "../angular/views/trail-alert-modal.php",
			controller: "TrailAlertModal",
			resolve: {
				trails: function() {
					return ($scope.trailCondition);
				}
			}
		});
		TrailAlertModalInstance.result.then(function(trailCondition) {
			$scope.trailToSubmit = $scope.currentTrail;
			$scope.trailToSubmit.trailCondition = trailCondition;
			$scope.trailToSubmit.submitTrailId = $scope.trailToSubmit.trailId;
			$scope.trailToSubmit.trailId = null;
			TrailService.create($scope.trailToSubmit).then(function(result) {
				if(result.data.status === 200) {
					$scope.alerts[0] = {type: "success", msg: result.data.message};
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			});
		});
	};

	$scope.getTrailId = function(trailId, validated) {
		if(validated === true) {
			TrailService.fetchId(trailId)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data;
						$scope.currentTrail = result.data.data;
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};
	$scope.getTrailUser = function(userId, validated) {
		if(validated === true) {
			TrailService.fetchUserId(userId)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};
	$scope.getSubmitId = function(TrailSubmitId, validated) {
		if(validated === true) {
			TrailService.fetchSubmitId(TrailSubmitId)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getTrailDifficulty = function(trailDifficulty, validated) {
		if(validated === true) {
			TrailService.fetchDifficulty(trailDifficulty)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};
	$scope.getTrailDistance = function(trailDistance, validated) {
		if(validated === true) {
			TrailService.fetchDistance(trailDistance)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getTrailName = function(TrailName, validated) {
		if(validated === true) {
			TrailService.fetchName(TrailName)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getTrailSubmission = function(trailSubmissionType, validated) {
		if(validated === true) {
			TrailService.fetchSubmission(trailSubmissionType)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.createTrail = function(trail, validated) {
		if(validated === true) {
			// do i need to add the date
			TrailService.createTrail(trail)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};

	$scope.updateTrail = function(trail, validated) {
		if(validated === true) {
			// do i need to add date.
			TrailService.update(trail.trailId, trail)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
					$scope.cancelEditing();
					$scope.getTrails();
				});
		}
	};

	$scope.getPoints = function(
			trailId, validated) {
		if(validated === true) {

			TrailService.fetchPoints(trailId)
				.then(function(result) {
					if(result.data.status === 200) {
						//console.log(result.data);
						$scope.points = result.data.points;
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	console.log($routeParams);
	if($scope.currentTrail === null && $scope.currentTrailId !== null) {
		$scope.getTrailId($scope.currentTrailId, true);
	}
}]);<commit_msg>Edited the<commit_after>app.controller("TrailController", ["$scope", "$routeParams", "$uibModal", "TrailService", function($scope, $routeParams, $uibModal, TrailService) {
	// get the trail from the api
	// come back to add other
	// make doc blocks way better
	$scope.currentTrailId = $routeParams.trailId;
	$scope.currentTrail = null;
	$scope.newTrail = {
		trailId: null,
		userId: null,
		browser: null,
		createDate: null,
		ipAddress: null,
		submitTrailId: null,
		trailAmenities: null,
		trailCondition: null,
		trailDescription: null,
		trailDifficulty: null,
		trailDistance: null,
		trailName: null,
		trailSubmissionType: null,
		trailTerrain: null,
		trailTraffic: null,
		trailUse: null,
		trailUuid: null
	};
	$scope.isEditing = false;
	$scope.points = [];
	$scope.trails = [];
	$scope.alerts = [];
	$scope.trailToSubmit = {};

	$scope.openTrailAlertModal = function() {
		var TrailAlertModalInstance = $uibModal.open({
			templateUrl: "../angular/views/trail-alert-modal.php",
			controller: "TrailAlertModal",
			resolve: {
				trails: function() {
					return ($scope.trailCondition);
				}
			}
		});
		TrailAlertModalInstance.result.then(function(trailCondition) {
			$scope.trailToSubmit = $scope.currentTrail;
			$scope.trailToSubmit.trailCondition = trailCondition;
			$scope.trailToSubmit.submitTrailId = $scope.trailToSubmit.trailId;
			$scope.trailToSubmit.trailId = null;
			TrailService.create($scope.trailToSubmit).then(function(result) {
				if(result.data.status === 200) {
					$scope.alerts[0] = {type: "success", msg: result.data.message};
				} else {
					$scope.alerts[0] = {type: "danger", msg: result.data.message};
				}
			});
		});
	};

	$scope.getTrailId = function(trailId, validated) {
		if(validated === true) {
			TrailService.fetchId(trailId)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data;
						$scope.currentTrail = result.data.data;
						$scope.getPoints(result.data.data.trailId, true); // TODO: Check this
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};
	$scope.getTrailUser = function(userId, validated) {
		if(validated === true) {
			TrailService.fetchUserId(userId)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};
	$scope.getSubmitId = function(TrailSubmitId, validated) {
		if(validated === true) {
			TrailService.fetchSubmitId(TrailSubmitId)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getTrailDifficulty = function(trailDifficulty, validated) {
		if(validated === true) {
			TrailService.fetchDifficulty(trailDifficulty)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};
	$scope.getTrailDistance = function(trailDistance, validated) {
		if(validated === true) {
			TrailService.fetchDistance(trailDistance)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getTrailName = function(TrailName, validated) {
		if(validated === true) {
			TrailService.fetchName(TrailName)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.getTrailSubmission = function(trailSubmissionType, validated) {
		if(validated === true) {
			TrailService.fetchSubmission(trailSubmissionType)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.trails = result.data.data
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	$scope.createTrail = function(trail, validated) {
		if(validated === true) {
			// do i need to add the date
			TrailService.createTrail(trail)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
				});
		}
	};

	$scope.updateTrail = function(trail, validated) {
		if(validated === true) {
			// do i need to add date.
			TrailService.update(trail.trailId, trail)
				.then(function(result) {
					if(result.data.status === 200) {
						$scope.alerts[0] = {type: "success", msg: result.data.message};
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message};
					}
					$scope.cancelEditing();
					$scope.getTrails();
				});
		}
	};

	$scope.getPoints = function(trailId, validated) {
		if(validated === true) {

			TrailService.fetchPoints(trailId)
				.then(function(result) {
					if(result.data.status === 200) {
						//console.log(result.data);
						$scope.points = result.data.points;
					} else {
						$scope.alerts[0] = {type: "danger", msg: result.data.message}
					}
				});
		}
	};

	console.log($routeParams);
	if($scope.currentTrail === null && $scope.currentTrailId !== null) {
		$scope.getTrailId($scope.currentTrailId, true);
	}
}]);<|endoftext|>


<commit_before>/*
 * jQuery Tools 1.2.5 - The missing UI library for the Web
 *
 * [tooltip, tooltip.slide, tooltip.dynamic]
 *
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 *
 * http://flowplayer.org/tools/
 *
 * File generated: Thu Nov 25 23:31:10 GMT 2010
 */
(function(f){function p(a,b,c){var h=c.relative?a.position().top:a.offset().top,d=c.relative?a.position().left:a.offset().left,i=c.position[0];h-=b.outerHeight()-c.offset[0];d+=a.outerWidth()+c.offset[1];if(/iPad/i.test(navigator.userAgent))h-=f(window).scrollTop();var j=b.outerHeight()+a.outerHeight();if(i=="center")h+=j/2;if(i=="bottom")h+=j;i=c.position[1];a=b.outerWidth()+a.outerWidth();if(i=="center")d-=a/2;if(i=="left")d-=a;return{top:h,left:d}}function u(a,b){var c=this,h=a.add(c),d,i=0,j=
0,m=a.attr("title"),q=a.attr("data-tooltip"),r=o[b.effect],l,s=a.is(":input"),v=s&&a.is(":checkbox, :radio, select, :button, :submit"),t=a.attr("type"),k=b.events[t]||b.events[s?v?"widget":"input":"def"];if(!r)throw'Nonexistent effect "'+b.effect+'"';k=k.split(/,\s*/);if(k.length!=2)throw"Tooltip: bad events configuration for "+t;a.bind(k[0],function(e){clearTimeout(i);if(b.predelay)j=setTimeout(function(){c.show(e)},b.predelay);else c.show(e)}).bind(k[1],function(e){clearTimeout(j);if(b.delay)i=
setTimeout(function(){c.hide(e)},b.delay);else c.hide(e)});if(m&&b.cancelDefault){a.removeAttr("title");a.data("title",m)}f.extend(c,{show:function(e){if(!d){if(q)d=f(q);else if(b.tip)d=f(b.tip).eq(0);else if(m)d=f(b.layout).addClass(b.tipClass).appendTo(document.body).hide().append(m);else{d=a.next();d.length||(d=a.parent().next())}if(!d.length)throw"Cannot find tooltip for "+a;}if(c.isShown())return c;d.stop(true,true);var g=p(a,d,b);b.tip&&d.html(a.data("title"));e=e||f.Event();e.type="onBeforeShow";
h.trigger(e,[g]);if(e.isDefaultPrevented())return c;g=p(a,d,b);d.css({position:"absolute",top:g.top,left:g.left});l=true;r[0].call(c,function(){e.type="onShow";l="full";h.trigger(e)});g=b.events.tooltip.split(/,\s*/);if(!d.data("__set")){d.bind(g[0],function(){clearTimeout(i);clearTimeout(j)});g[1]&&!a.is("input:not(:checkbox, :radio), textarea")&&d.bind(g[1],function(n){n.relatedTarget!=a[0]&&a.trigger(k[1].split(" ")[0])});d.data("__set",true)}return c},hide:function(e){if(!d||!c.isShown())return c;
e=e||f.Event();e.type="onBeforeHide";h.trigger(e);if(!e.isDefaultPrevented()){l=false;o[b.effect][1].call(c,function(){e.type="onHide";h.trigger(e)});return c}},isShown:function(e){return e?l=="full":l},getConf:function(){return b},getTip:function(){return d},getTrigger:function(){return a}});f.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(e,g){f.isFunction(b[g])&&f(c).bind(g,b[g]);c[g]=function(n){n&&f(c).bind(g,n);return c}})}f.tools=f.tools||{version:"1.2.5"};f.tools.tooltip=
{conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,position:["top","center"],offset:[0,0],relative:false,cancelDefault:true,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,b,c){o[a]=[b,c]}};var o={toggle:[function(a){var b=this.getConf(),c=this.getTip();b=b.opacity;b<1&&c.css({opacity:b});c.show();a.call()},function(a){this.getTip().hide();
a.call()}],fade:[function(a){var b=this.getConf();this.getTip().fadeTo(b.fadeInSpeed,b.opacity,a)},function(a){this.getTip().fadeOut(this.getConf().fadeOutSpeed,a)}]};f.fn.tooltip=function(a){var b=this.data("tooltip");if(b)return b;a=f.extend(true,{},f.tools.tooltip.conf,a);if(typeof a.position=="string")a.position=a.position.split(/,?\s/);this.each(function(){b=new u(f(this),a);f(this).data("tooltip",b)});return a.api?b:this}})(jQuery);
(function(d){var i=d.tools.tooltip;d.extend(i.conf,{direction:"up",bounce:false,slideOffset:10,slideInSpeed:200,slideOutSpeed:200,slideFade:!d.browser.msie});var e={up:["-","top"],down:["+","top"],left:["-","left"],right:["+","left"]};i.addEffect("slide",function(g){var a=this.getConf(),f=this.getTip(),b=a.slideFade?{opacity:a.opacity}:{},c=e[a.direction]||e.up;b[c[1]]=c[0]+"="+a.slideOffset;a.slideFade&&f.css({opacity:0});f.show().animate(b,a.slideInSpeed,g)},function(g){var a=this.getConf(),f=a.slideOffset,
b=a.slideFade?{opacity:0}:{},c=e[a.direction]||e.up,h=""+c[0];if(a.bounce)h=h=="+"?"-":"+";b[c[1]]=h+"="+f;this.getTip().animate(b,a.slideOutSpeed,function(){d(this).hide();g.call()})})})(jQuery);
(function(g){function j(a){var c=g(window),d=c.width()+c.scrollLeft(),h=c.height()+c.scrollTop();return[a.offset().top<=c.scrollTop(),d<=a.offset().left+a.width(),h<=a.offset().top+a.height(),c.scrollLeft()>=a.offset().left]}function k(a){for(var c=a.length;c--;)if(a[c])return false;return true}var i=g.tools.tooltip;i.dynamic={conf:{classNames:"top right bottom left"}};g.fn.dynamic=function(a){if(typeof a=="number")a={speed:a};a=g.extend({},i.dynamic.conf,a);var c=a.classNames.split(/\s/),d;this.each(function(){var h=
g(this).tooltip().onBeforeShow(function(e,f){e=this.getTip();var b=this.getConf();d||(d=[b.position[0],b.position[1],b.offset[0],b.offset[1],g.extend({},b)]);g.extend(b,d[4]);b.position=[d[0],d[1]];b.offset=[d[2],d[3]];e.css({visibility:"hidden",position:"absolute",top:f.top,left:f.left}).show();f=j(e);if(!k(f)){if(f[2]){g.extend(b,a.top);b.position[0]="top";e.addClass(c[0])}if(f[3]){g.extend(b,a.right);b.position[1]="right";e.addClass(c[1])}if(f[0]){g.extend(b,a.bottom);b.position[0]="bottom";e.addClass(c[2])}if(f[1]){g.extend(b,
a.left);b.position[1]="left";e.addClass(c[3])}if(f[0]||f[2])b.offset[0]*=-1;if(f[1]||f[3])b.offset[1]*=-1}e.css({visibility:"visible"}).hide()});h.onBeforeShow(function(){var e=this.getConf();this.getTip();setTimeout(function(){e.position=[d[0],d[1]];e.offset=[d[2],d[3]]},0)});h.onHide(function(){var e=this.getTip();e.removeClass(a.classNames)});ret=h});return a.api?ret:this}})(jQuery);
<commit_msg>Beter version of jQuery tools<commit_after>/*!
 * jQuery Tools v1.2.5 - The missing UI library for the Web
 *
 * tooltip/tooltip.js
 * tooltip/tooltip.dynamic.js
 * tooltip/tooltip.slide.js
 *
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 *
 * http://flowplayer.org/tools/
 *
 */
(function(a){a.tools=a.tools||{version:"v1.2.5"},a.tools.tooltip={conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,position:["top","center"],offset:[0,0],relative:!1,cancelDefault:!0,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,c,d){b[a]=[c,d]}};var b={toggle:[function(a){var b=this.getConf(),c=this.getTip(),d=b.opacity;d<1&&c.css({opacity:d}),c.show(),a.call()},function(a){this.getTip().hide(),a.call()}],fade:[function(a){var b=this.getConf();this.getTip().fadeTo(b.fadeInSpeed,b.opacity,a)},function(a){this.getTip().fadeOut(this.getConf().fadeOutSpeed,a)}]};function c(b,c,d){var e=d.relative?b.position().top:b.offset().top,f=d.relative?b.position().left:b.offset().left,g=d.position[0];e-=c.outerHeight()-d.offset[0],f+=b.outerWidth()+d.offset[1],/iPad/i.test(navigator.userAgent)&&(e-=a(window).scrollTop());var h=c.outerHeight()+b.outerHeight();g=="center"&&(e+=h/2),g=="bottom"&&(e+=h),g=d.position[1];var i=c.outerWidth()+b.outerWidth();g=="center"&&(f-=i/2),g=="left"&&(f-=i);return{top:e,left:f}}function d(d,e){var f=this,g=d.add(f),h,i=0,j=0,k=d.attr("title"),l=d.attr("data-tooltip"),m=b[e.effect],n,o=d.is(":input"),p=o&&d.is(":checkbox, :radio, select, :button, :submit"),q=d.attr("type"),r=e.events[q]||e.events[o?p?"widget":"input":"def"];if(!m)throw"Nonexistent effect \""+e.effect+"\"";r=r.split(/,\s*/);if(r.length!=2)throw"Tooltip: bad events configuration for "+q;d.bind(r[0],function(a){clearTimeout(i),e.predelay?j=setTimeout(function(){f.show(a)},e.predelay):f.show(a)}).bind(r[1],function(a){clearTimeout(j),e.delay?i=setTimeout(function(){f.hide(a)},e.delay):f.hide(a)}),k&&e.cancelDefault&&(d.removeAttr("title"),d.data("title",k)),a.extend(f,{show:function(b){if(!h){l?h=a(l):e.tip?h=a(e.tip).eq(0):k?h=a(e.layout).addClass(e.tipClass).appendTo(document.body).hide().append(k):(h=d.next(),h.length||(h=d.parent().next()));if(!h.length)throw"Cannot find tooltip for "+d}if(f.isShown())return f;h.stop(!0,!0);var o=c(d,h,e);e.tip&&h.html(d.data("title")),b=b||a.Event(),b.type="onBeforeShow",g.trigger(b,[o]);if(b.isDefaultPrevented())return f;o=c(d,h,e),h.css({position:"absolute",top:o.top,left:o.left}),n=!0,m[0].call(f,function(){b.type="onShow",n="full",g.trigger(b)});var p=e.events.tooltip.split(/,\s*/);h.data("__set")||(h.bind(p[0],function(){clearTimeout(i),clearTimeout(j)}),p[1]&&!d.is("input:not(:checkbox, :radio), textarea")&&h.bind(p[1],function(a){a.relatedTarget!=d[0]&&d.trigger(r[1].split(" ")[0])}),h.data("__set",!0));return f},hide:function(c){if(!h||!f.isShown())return f;c=c||a.Event(),c.type="onBeforeHide",g.trigger(c);if(!c.isDefaultPrevented()){n=!1,b[e.effect][1].call(f,function(){c.type="onHide",g.trigger(c)});return f}},isShown:function(a){return a?n=="full":n},getConf:function(){return e},getTip:function(){return h},getTrigger:function(){return d}}),a.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}})}a.fn.tooltip=function(b){var c=this.data("tooltip");if(c)return c;b=a.extend(!0,{},a.tools.tooltip.conf,b),typeof b.position=="string"&&(b.position=b.position.split(/,?\s/)),this.each(function(){c=new d(a(this),b),a(this).data("tooltip",c)});return b.api?c:this}})(jQuery);
(function(a){var b=a.tools.tooltip;b.dynamic={conf:{classNames:"top right bottom left"}};function c(b){var c=a(window),d=c.width()+c.scrollLeft(),e=c.height()+c.scrollTop();return[b.offset().top<=c.scrollTop(),d<=b.offset().left+b.width(),e<=b.offset().top+b.height(),c.scrollLeft()>=b.offset().left]}function d(a){var b=a.length;while(b--)if(a[b])return!1;return!0}a.fn.dynamic=function(e){typeof e=="number"&&(e={speed:e}),e=a.extend({},b.dynamic.conf,e);var f=e.classNames.split(/\s/),g;this.each(function(){var b=a(this).tooltip().onBeforeShow(function(b,h){var i=this.getTip(),j=this.getConf();g||(g=[j.position[0],j.position[1],j.offset[0],j.offset[1],a.extend({},j)]),a.extend(j,g[4]),j.position=[g[0],g[1]],j.offset=[g[2],g[3]],i.css({visibility:"hidden",position:"absolute",top:h.top,left:h.left}).show();var k=c(i);if(!d(k)){k[2]&&(a.extend(j,e.top),j.position[0]="top",i.addClass(f[0])),k[3]&&(a.extend(j,e.right),j.position[1]="right",i.addClass(f[1])),k[0]&&(a.extend(j,e.bottom),j.position[0]="bottom",i.addClass(f[2])),k[1]&&(a.extend(j,e.left),j.position[1]="left",i.addClass(f[3]));if(k[0]||k[2])j.offset[0]*=-1;if(k[1]||k[3])j.offset[1]*=-1}i.css({visibility:"visible"}).hide()});b.onBeforeShow(function(){var a=this.getConf(),b=this.getTip();setTimeout(function(){a.position=[g[0],g[1]],a.offset=[g[2],g[3]]},0)}),b.onHide(function(){var a=this.getTip();a.removeClass(e.classNames)}),ret=b});return e.api?ret:this}})(jQuery);
(function(a){var b=a.tools.tooltip;a.extend(b.conf,{direction:"up",bounce:!1,slideOffset:10,slideInSpeed:200,slideOutSpeed:200,slideFade:!a.browser.msie});var c={up:["-","top"],down:["+","top"],left:["-","left"],right:["+","left"]};b.addEffect("slide",function(a){var b=this.getConf(),d=this.getTip(),e=b.slideFade?{opacity:b.opacity}:{},f=c[b.direction]||c.up;e[f[1]]=f[0]+"="+b.slideOffset,b.slideFade&&d.css({opacity:0}),d.show().animate(e,b.slideInSpeed,a)},function(b){var d=this.getConf(),e=d.slideOffset,f=d.slideFade?{opacity:0}:{},g=c[d.direction]||c.up,h=""+g[0];d.bounce&&(h=h=="+"?"-":"+"),f[g[1]]=h+"="+e,this.getTip().animate(f,d.slideOutSpeed,function(){a(this).hide(),b.call()})})})(jQuery);
<|endoftext|>


<commit_before>function showLoading() {
    // remove existing loaders
    $('.loading-container').remove();
    $('

').appendTo("body");

    componentHandler.upgradeElements($('.mdl-spinner').get());
    setTimeout(function () {
        $('#orrsLoader').css({opacity: 1});
    }, 1);
}

function hideLoading() {
    $('#orrsLoader').css({opacity: 0});
    setTimeout(function () {
        $('#orrsLoader').remove();
    }, 400);
}

function showDialog(options) {
    options = $.extend({
        id: 'orrsDiag',
        title: null,
        text: null,
        negative: false,
        positive: false,
        cancelable: true,
        contentStyle: null,
        onLoaded: false
    }, options);

    // remove existing dialogs
    $('.dialog-container').remove();
    $(document).unbind("keyup.dialog");

    $('

').appendTo("body");
    var dialog = $('#' + options.id);
    var content = dialog.find('.mdl-card');
    if (options.contentStyle != null) content.css(options.contentStyle);
    if (options.title != null) {
        $('
' + options.title + '
').appendTo(content);
    }
    if (options.text != null) {
        $('
' + options.text + '
').appendTo(content);
    }
    if (options.negative || options.positive) {
        var buttonBar = $('

');
        if (options.negative) {
            options.negative = $.extend({
                id: 'negative',
                title: 'Cancel',
                onClick: function () {
                    return false;
                }
            }, options.negative);
            var negButton = $('<button class="mdl-button mdl-js-button mdl-js-ripple-effect" id="' + options.negative.id + '">' + options.negative.title + '</button>');
            negButton.click(function (e) {
                e.preventDefault();
                if (!options.negative.onClick(e))
                    hideDialog(dialog)
            });
            negButton.appendTo(buttonBar);
        }
        if (options.positive) {
            options.positive = $.extend({
                id: 'positive',
                title: 'OK',
                onClick: function () {
                    return false;
                }
            }, options.positive);
            var posButton = $('<button class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" id="' + options.positive.id + '">' + options.positive.title + '</button>');
            posButton.click(function (e) {
                e.preventDefault();
                if (!options.positive.onClick(e))
                    hideDialog(dialog)
            });
            posButton.appendTo(buttonBar);
        }
        buttonBar.appendTo(content);
    }
    componentHandler.upgradeDom();
    if (options.cancelable) {
        dialog.click(function () {
            hideDialog(dialog);
        });
        $(document).bind("keyup.dialog", function (e) {
            if (e.which == 27)
                hideDialog(dialog);
        });
        content.click(function (e) {
            e.stopPropagation();
        });
    }
    setTimeout(function () {
        dialog.css({opacity: 1});
        if (options.onLoaded)
            options.onLoaded();
    }, 1);
}

function hideDialog(dialog) {
    $(document).unbind("keyup.dialog");
    dialog.css({opacity: 0});
    setTimeout(function () {
        dialog.remove();
    }, 400);
}<commit_msg>Added option to disable hiding of other open dialogs to allow nesting<commit_after>function showLoading() {
    // remove existing loaders
    $('.loading-container').remove();
    $('

').appendTo("body");

    componentHandler.upgradeElements($('.mdl-spinner').get());
    setTimeout(function () {
        $('#orrsLoader').css({opacity: 1});
    }, 1);
}

function hideLoading() {
    $('#orrsLoader').css({opacity: 0});
    setTimeout(function () {
        $('#orrsLoader').remove();
    }, 400);
}

function showDialog(options) {
    options = $.extend({
        id: 'orrsDiag',
        title: null,
        text: null,
        negative: false,
        positive: false,
        cancelable: true,
        contentStyle: null,
        onLoaded: false,
        hideOther: true
    }, options);

    if (options.hideOther) {
        // remove existing dialogs
        $('.dialog-container').remove();
        $(document).unbind("keyup.dialog");
    }

    $('

').appendTo("body");
    var dialog = $('#' + options.id);
    var content = dialog.find('.mdl-card');
    if (options.contentStyle != null) content.css(options.contentStyle);
    if (options.title != null) {
        $('
' + options.title + '
').appendTo(content);
    }
    if (options.text != null) {
        $('
' + options.text + '
').appendTo(content);
    }
    if (options.negative || options.positive) {
        var buttonBar = $('

');
        if (options.negative) {
            options.negative = $.extend({
                id: 'negative',
                title: 'Cancel',
                onClick: function () {
                    return false;
                }
            }, options.negative);
            var negButton = $('<button class="mdl-button mdl-js-button mdl-js-ripple-effect" id="' + options.negative.id + '">' + options.negative.title + '</button>');
            negButton.click(function (e) {
                e.preventDefault();
                if (!options.negative.onClick(e))
                    hideDialog(dialog)
            });
            negButton.appendTo(buttonBar);
        }
        if (options.positive) {
            options.positive = $.extend({
                id: 'positive',
                title: 'OK',
                onClick: function () {
                    return false;
                }
            }, options.positive);
            var posButton = $('<button class="mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect" id="' + options.positive.id + '">' + options.positive.title + '</button>');
            posButton.click(function (e) {
                e.preventDefault();
                if (!options.positive.onClick(e))
                    hideDialog(dialog)
            });
            posButton.appendTo(buttonBar);
        }
        buttonBar.appendTo(content);
    }
    componentHandler.upgradeDom();
    if (options.cancelable) {
        dialog.click(function () {
            hideDialog(dialog);
        });
        $(document).bind("keyup.dialog", function (e) {
            if (e.which == 27)
                hideDialog(dialog);
        });
        content.click(function (e) {
            e.stopPropagation();
        });
    }
    setTimeout(function () {
        dialog.css({opacity: 1});
        if (options.onLoaded)
            options.onLoaded();
    }, 1);
}

function hideDialog(dialog) {
    $(document).unbind("keyup.dialog");
    dialog.css({opacity: 0});
    setTimeout(function () {
        dialog.remove();
    }, 400);
}<|endoftext|>


<commit_before>/*
 * @name 正弦波
 * @description Render 是一个简单的正弦波。
 * 作者：Daniel Shiffman
 */

let xspacing = 16; // 每个水平位置的距离
let w; // 波的宽度
let theta = 0.0; // 初始角度为 0
let amplitude = 75.0; // 波的高度
let period = 500.0; // 波在重复前的像素个数
let dx; // x 的增量
let yvalues; // 保存波的高度的数组

function setup() {
  createCanvas(710, 400);
  w = width + 16;
  dx = (TWO_PI / period) * xspacing;
  yvalues = new Array(floor(w / xspacing));
}

function draw() {
  background(0);
  calcWave();
  renderWave();
}

function calcWave() {
  // theta 增量（尝试赋予 ‘角速度’ 不同的数值）
  // 对于每一个 x 值，使用正弦函数计算 y 值
  let x = theta;
  for (let i = 0; i < yvalues.length; i++) {
    yvalues[i] = sin(x) * amplitude;
    x += dx;
  }
}

function renderWave() {
  noStroke();
  fill(255);
  // 在波上的每个位置画椭圆
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 + yvalues[x], 16, 16);
  }
}
<commit_msg>Update src/data/examples/zh-Hans/08_Math/06_sinewave.js<commit_after>/*
 * @name 正弦波
 * @description Render 是一个简单的正弦波。
 * 作者：Daniel Shiffman
 */

let xspacing = 16; // 每个水平位置的距离
let w; // 波的宽度
let theta = 0.0; // 初始角度为 0
let amplitude = 75.0; // 波的高度
let period = 500.0; // 波在重复前的像素个数
let dx; // x 的增量
let yvalues; // 保存波的高度的数组

function setup() {
  createCanvas(710, 400);
  w = width + 16;
  dx = (TWO_PI / period) * xspacing;
  yvalues = new Array(floor(w / xspacing));
}

function draw() {
  background(0);
  calcWave();
  renderWave();
}

function calcWave() {
  // theta 增量（尝试赋予 ‘角速度’ 不同的数值）
  theta += 0.02;

  // 对于每一个 x 值，使用正弦函数计算 y 值
  let x = theta;
  for (let i = 0; i < yvalues.length; i++) {
    yvalues[i] = sin(x) * amplitude;
    x += dx;
  }
}

function renderWave() {
  noStroke();
  fill(255);
  // 在波上的每个位置画椭圆
  for (let x = 0; x < yvalues.length; x++) {
    ellipse(x * xspacing, height / 2 + yvalues[x], 16, 16);
  }
}
<|endoftext|>


<commit_before>import * as chai from 'chai';
const expect = chai.expect;
const chaiAsPromised = require('chai-as-promised');
import * as sinon from 'sinon';
import * as sinonAsPromised from 'sinon-as-promised';
import { SentEmail } from '../src/models/sent_email';

chai.use(chaiAsPromised);

describe('SentEmail', () => {
  const tableName = 'SentEmails-table';
  const messageId = 'some-message-id';
  const recipientId = 'thatUserId';
  const sentEmailHashKey = 'messageId';
  const listId = 'some-list-id';
  const status = 'sent';
  const params = {recipientId, messageId, listId, status}
  let tNameStub;

  before(() => {
    sinon.stub(SentEmail, '_client').resolves(true);
    tNameStub = sinon.stub(SentEmail, 'tableName', { get: () => tableName});
  });

  describe('#hashKey', () => {
    it('returns the hash key name', () => {
      expect(SentEmail.hashKey).to.equal(sentEmailHashKey);
    });
  });

  describe('#rangeKey', () => {
    it('returns the range key name', () => {
      expect(SentEmail.rangeKey).to.be.null;
    });
  });

  after(() => {
    SentEmail._client.restore();
    tNameStub.restore();
  });
});
<commit_msg>Adding email template model<commit_after>import * as chai from 'chai';
const expect = chai.expect;
const chaiAsPromised = require('chai-as-promised');
import * as sinon from 'sinon';
import * as sinonAsPromised from 'sinon-as-promised';
import { EmailTemplate } from '../src/models/email_template';

chai.use(chaiAsPromised);

describe('EmailTemplate', () => {
  const tableName = 'emailTemplates-table';
  const emailTemplateHashKey = 'userId';
  const rangeKey = 'id';
  let tNameStub;

  before(() => {
    sinon.stub(EmailTemplate, '_client').resolves(true);
    tNameStub = sinon.stub(EmailTemplate, 'tableName', { get: () => tableName});
  });

  describe('#hashKey', () => {
    it('returns the hash key name', () => {
      expect(EmailTemplate.hashKey).to.equal(emailTemplateHashKey);
    });
  });

  describe('#rangeKey', () => {
    it('returns the range key name', () => {
      expect(EmailTemplate.rangeKey).to.equal(rangeKey);
    });
  });

  after(() => {
    EmailTemplate._client.restore();
    tNameStub.restore();
  });
});
<|endoftext|>


<commit_before>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// @ts-nocheck
// TODO(crbug.com/1011811): Enable TypeScript compiler checks

import * as Common from '../common/common.js';
import * as TextUtils from '../text_utils/text_utils.js';  // eslint-disable-line no-unused-vars

import {AnchorBehavior} from './GlassPane.js';  // eslint-disable-line no-unused-vars
import {Suggestions} from './SuggestBox.js';    // eslint-disable-line no-unused-vars
import {Widget} from './Widget.js';  // eslint-disable-line no-unused-vars

/**
 * @interface
 */
export class TextEditorFactory {
  /**
   * @param {!Options} options
   * @return {!TextEditor}
   */
  createEditor(options) {}
}

/**
 * @interface
 */
export class TextEditor extends Common.EventTarget.EventTarget {
  /**
   * @return {!Widget}
   */
  widget() {
  }

  /**
   * @return {!TextUtils.TextRange.TextRange}
   */
  fullRange() {
  }

  /**
   * @return {!TextUtils.TextRange.TextRange}
   */
  selection() {
  }

  /**
   * @param {!TextUtils.TextRange.TextRange} selection
   */
  setSelection(selection) {
  }

  /**
   * @param {!TextUtils.TextRange.TextRange=} textRange
   * @return {string}
   */
  text(textRange) {
  }

  /**
   * @return {string}
   */
  textWithCurrentSuggestion() {
  }

  /**
   * @param {string} text
   */
  setText(text) {
  }

  /**
   * @param {number} lineNumber
   * @return {string}
   */
  line(lineNumber) {
  }

  newlineAndIndent() {
  }

  /**
   * @param {function(!KeyboardEvent):void} handler
   */
  addKeyDownHandler(handler) {
  }

  /**
   * @param {?AutocompleteConfig} config
   */
  configureAutocomplete(config) {
  }

  clearAutocomplete() {
  }

  /**
   * @param {number} lineNumber
   * @param {number} columnNumber
   * @return {!{x: number, y: number}}
   */
  visualCoordinates(lineNumber, columnNumber) {
  }

  /**
   * @param {number} lineNumber
   * @param {number} columnNumber
   * @return {?{startColumn: number, endColumn: number, type: string}}
   */
  tokenAtTextPosition(lineNumber, columnNumber) {
  }

  /**
   * @param {string} placeholder
   */
  setPlaceholder(placeholder) {}
}

/** @enum {symbol} */
export const Events = {
  CursorChanged: Symbol('CursorChanged'),
  TextChanged: Symbol('TextChanged'),
  SuggestionChanged: Symbol('SuggestionChanged')
};

/**
 * @typedef {{
  *  bracketMatchingSetting: (!Common.Settings.Setting<*>|undefined),
  *  devtoolsAccessibleName: (string|undefined),
  *  lineNumbers: boolean,
  *  lineWrapping: boolean,
  *  mimeType: (string|undefined),
  *  autoHeight: (boolean|undefined),
  *  padBottom: (boolean|undefined),
  *  maxHighlightLength: (number|undefined),
  *  placeholder: (string|undefined),
  *  lineWiseCopyCut: (boolean|undefined)
  * }}
  */
export let Options;

/**
  * @typedef {{
  *     substituteRangeCallback: ((function(number, number):?TextUtils.TextRange.TextRange)|undefined),
  *     tooltipCallback: ((function(number, number):!Promise<?Element>)|undefined),
  *     suggestionsCallback: ((function(!TextUtils.TextRange.TextRange, !TextUtils.TextRange.TextRange, boolean=):?Promise.<!Suggestions>)|undefined),
  *     isWordChar: ((function(string):boolean)|undefined),
  *     anchorBehavior: (AnchorBehavior|undefined)
  * }}
  */
export let AutocompleteConfig;
<commit_msg>[ts] Type-check ui/TextEditor.js with TypeScript<commit_after>// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import * as Common from '../common/common.js';
import * as TextUtils from '../text_utils/text_utils.js';  // eslint-disable-line no-unused-vars

import {AnchorBehavior} from './GlassPane.js';  // eslint-disable-line no-unused-vars
import {Suggestions} from './SuggestBox.js';    // eslint-disable-line no-unused-vars
import {Widget} from './Widget.js';  // eslint-disable-line no-unused-vars

/**
 * @interface
 */
export class TextEditorFactory {
  /**
   * @param {!Options} options
   * @return {!TextEditor}
   */
  createEditor(options) {
    throw new Error('not implemented');
  }
}

/**
 * @interface
 */
export class TextEditor extends Common.EventTarget.EventTarget {
  /**
   * @return {!Widget}
   */
  widget() {
    throw new Error('not implemented');
  }

  /**
   * @return {!TextUtils.TextRange.TextRange}
   */
  fullRange() {
    throw new Error('not implemented');
  }

  /**
   * @return {!TextUtils.TextRange.TextRange}
   */
  selection() {
    throw new Error('not implemented');
  }

  /**
   * @param {!TextUtils.TextRange.TextRange} selection
   */
  setSelection(selection) {
  }

  /**
   * @param {!TextUtils.TextRange.TextRange=} textRange
   * @return {string}
   */
  text(textRange) {
    throw new Error('not implemented');
  }

  /**
   * @return {string}
   */
  textWithCurrentSuggestion() {
    throw new Error('not implemented');
  }

  /**
   * @param {string} text
   */
  setText(text) {
  }

  /**
   * @param {number} lineNumber
   * @return {string}
   */
  line(lineNumber) {
    throw new Error('not implemented');
  }

  newlineAndIndent() {
  }

  /**
   * @param {function(!KeyboardEvent):void} handler
   */
  addKeyDownHandler(handler) {
  }

  /**
   * @param {?AutocompleteConfig} config
   */
  configureAutocomplete(config) {
  }

  clearAutocomplete() {
  }

  /**
   * @param {number} lineNumber
   * @param {number} columnNumber
   * @return {!{x: number, y: number}}
   */
  visualCoordinates(lineNumber, columnNumber) {
    throw new Error('not implemented');
  }

  /**
   * @param {number} lineNumber
   * @param {number} columnNumber
   * @return {?{startColumn: number, endColumn: number, type: string}}
   */
  tokenAtTextPosition(lineNumber, columnNumber) {
    throw new Error('not implemented');
  }

  /**
   * @param {string} placeholder
   */
  setPlaceholder(placeholder) {}
}

/** @enum {symbol} */
export const Events = {
  CursorChanged: Symbol('CursorChanged'),
  TextChanged: Symbol('TextChanged'),
  SuggestionChanged: Symbol('SuggestionChanged')
};

/**
 * @typedef {{
  *  bracketMatchingSetting: (!Common.Settings.Setting<*>|undefined),
  *  devtoolsAccessibleName: (string|undefined),
  *  lineNumbers: boolean,
  *  lineWrapping: boolean,
  *  mimeType: (string|undefined),
  *  autoHeight: (boolean|undefined),
  *  padBottom: (boolean|undefined),
  *  maxHighlightLength: (number|undefined),
  *  placeholder: (string|undefined),
  *  lineWiseCopyCut: (boolean|undefined)
  * }}
  */
// @ts-ignore typedef
export let Options;

/**
  * @typedef {{
  *     substituteRangeCallback: ((function(number, number):?TextUtils.TextRange.TextRange)|undefined),
  *     tooltipCallback: ((function(number, number):!Promise<?Element>)|undefined),
  *     suggestionsCallback: ((function(!TextUtils.TextRange.TextRange, !TextUtils.TextRange.TextRange, boolean=):?Promise.<!Suggestions>)|undefined),
  *     isWordChar: ((function(string):boolean)|undefined),
  *     anchorBehavior: (AnchorBehavior|undefined)
  * }}
  */
// @ts-ignore typedef
export let AutocompleteConfig;
<|endoftext|>