<commit_before>/*
* jQuery Mobile Framework : prototype for "dialog" plugin.
* Copyright (c) jQuery Project
* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
* Note: Code is in draft form and is subject to change
*/
(function ( $ ) {
$.widget( "mobile.dialog", $.mobile.widget, {
	options: {},
	_create: function(){
		var self = this,
			$el = self.element,
			$closeBtn = $('Close');

		$el.delegate("a, submit", "click submit", function(e){
			if( e.type == "click" && ( $(e.target).closest('[data-back]') || $(e.target).closest($closeBtn) ) ){
				self.close();
				return false;
			}
			//otherwise, assume we're headed somewhere new. set activepage to dialog so the transition will work
			$.activePage = this.element;
		});

		this.element
			.bind("pageshow",function(){
				return false;
			})
			//add ARIA role
			.attr("role","dialog")
			.addClass('ui-page ui-dialog ui-body-a')
			.find('[data-role=header]')
			.addClass('ui-corner-top ui-overlay-shadow')
				.prepend( $closeBtn )
			.end()
			.find('.ui-content:not([class*="ui-body-"])')
				.addClass('ui-body-c')
			.end()
			.find('.ui-content,[data-role=footer]')
				.last()
				.addClass('ui-corner-bottom ui-overlay-shadow');

	},
	close: function(){
		$.changePage([this.element, $.activePage], undefined, true );
	}
});
})( jQuery );<commit_msg>fixed support for back button closing of dialogs, utilizing new $.mobile.updateHash method. Fixes #412<commit_after>/*
* jQuery Mobile Framework : prototype for "dialog" plugin.
* Copyright (c) jQuery Project
* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
* Note: Code is in draft form and is subject to change
*/
(function ( $ ) {
$.widget( "mobile.dialog", $.mobile.widget, {
	options: {},
	_create: function(){
		var self = this,
			$el = self.element,
			$prevPage = $.activePage,
			$closeBtn = $('Close');

		$el.delegate("a, submit", "click submit", function(e){
			if( e.type == "click" && ( $(e.target).closest('[data-back]') || $(e.target).closest($closeBtn) ) ){
				self.close();
				return false;
			}
			//otherwise, assume we're headed somewhere new. set activepage to dialog so the transition will work
			$.activePage = this.element;
		});

		this.element
			.bind("pageshow",function(){
				return false;
			})
			//add ARIA role
			.attr("role","dialog")
			.addClass('ui-page ui-dialog ui-body-a')
			.find('[data-role=header]')
			.addClass('ui-corner-top ui-overlay-shadow')
				.prepend( $closeBtn )
			.end()
			.find('.ui-content:not([class*="ui-body-"])')
				.addClass('ui-body-c')
			.end()
			.find('.ui-content,[data-role=footer]')
				.last()
				.addClass('ui-corner-bottom ui-overlay-shadow');

		$(window).bind('hashchange',function(){
			if( $el.is('.ui-page-active') ){
				self.close();
				$el.bind('pagehide',function(){
					$.mobile.updateHash( $prevPage.attr('id'), true);
				});
			}
		});

	},

	close: function(){
		$.changePage([this.element, $.activePage], undefined, true, true );
	}
});
})( jQuery );<|endoftext|>


<commit_before>(function(test){
    var root = (typeof self == 'object' && self.self == self && self) ||
            (typeof global == 'object' && global.global == global && global);

    var isNode = typeof module !== 'undefined' && module.exports;
    var isRequirejs = typeof define === 'function' && define.amd;

    var HA;
    var env;
    var should;
    if(isRequirejs){
        define(['histogram-analyze', 'chai'], function(HA, chai){
            should = chai.should();
            env = 'Requirejs';
            test(HA, should, env);
        })
    } else if(isNode){
        HA = require("../histogram-analyze");
        var should = require("chai").should();
        env = "Node";
        test(HA, should, env);

    }else{
        HA = root.HistogramAnalyze;
        env = "Only Browser"
        test(HA, should, env);
    }

}(function(HA, should, env){
    describe('Open with '+env, function(){
        describe('#histogram module', function(){
            it('is ok', function(){
                HA.should.be.ok;
            })
        })
        describe('#histogram1D()', function(){
            it('is function', function(){
                HA.histogram1D.should.be.a('function');
            })
        })
        describe('#histogram1DCircular()', function(){
            it('is function', function(){
                HA.circularHistogram1D.should.be.a('function');
            })
        })
        describe('#histogram2D()', function(){
            it('is function', function(){
                HA.histogram2D.should.be.a('function');
            })
        })
    })
}))

<commit_msg>add some test<commit_after>(function(test){
    var root = (typeof self == 'object' && self.self == self && self) ||
            (typeof global == 'object' && global.global == global && global);

    var isNode = typeof module !== 'undefined' && module.exports;
    var isRequirejs = typeof define === 'function' && define.amd;

    var HA;
    var env;
    var should;
    if(isRequirejs){
        define(['histogram-analyze', 'chai'], function(HA, chai){
            should = chai.should();
            env = 'Requirejs';
            test(HA, should, env);
        })
    } else if(isNode){
        HA = require("../histogram-analyze");
        var should = require("chai").should();
        env = "Node";
        test(HA, should, env);

    }else{
        HA = root.HistogramAnalyze;
        env = "Only Browser"
        test(HA, should, env);
    }

}(function(HA, should, env){
    describe('Open with '+env, function(){
        describe('#histogram module', function(){
            it('is ok', function(){
                HA.should.be.ok;
            })
        })
        describe('#histogram1D()', function(){
            it('is function', function(){
                HA.histogram1D.should.be.a('function');
            })
        })
        describe('#histogram1DCircular()', function(){
            it('is function', function(){
                HA.circularHistogram1D.should.be.a('function');
            })
        })
        describe('#histogram2D()', function(){
            it('is function', function(){
                HA.histogram2D.should.be.a('function');
            })
        })
    })

    describe('Construct Test', function(){
        describe("# Width : 0 init : 0", function(){
            it('is ok', function(){
                (new HA.histogram1D(0, 0)).should.be.ok;
            })

        })
    })
    describe('Max Test', function(){
        var hist1 = new HA.histogram1D(5);
        hist1[0] = 1;
        hist1[1] = 2;
        hist1[2] = 3;
        hist1[3] = 4;
        hist1[4] = 5;
        var hist2 = new HA.histogram1D(5);
        hist2[0] = 2;
        hist2[1] = 3;
        hist2[2] = 8;
        hist2[3] = 7;
        hist2[4] = 6;
        var hist3 = new HA.histogram1D(5);
        hist3[0] = 6;
        hist3[1] = 6;
        hist3[2] = 6;
        hist3[3] = 6;
        hist3[4] = 6;
        describe(' [1,2,3,4,5] ', function(){
            it('Max is equal to 5', function(){
                hist1.max().should.equal(5);
            })
        })
        describe(' [2,3,8,7,6] ', function(){
            it('Max is equal to 8', function(){
                hist2.max().should.equal(8);
            })
        })
        describe(' [6,6,6,6,6] ', function(){
            it('Max is equal to 6', function(){
                hist3.max().should.equal(6);
            })
        })
        describe(' [1,2,3,4,5] ', function(){
            it('min is equal to 1', function(){
                hist1.min().should.equal(1);
            })
        })
    })
}))

<|endoftext|>


<commit_before>app.directive('slackSlackbox', [
  "settings",
  "ChatService",
  "User",
  "SessionService",
  "Course",
  "Channel",
  "$location",
  "$interval",
  function(
    settings,
    ChatService,
    User,
    SessionService,
    Course,
    Channel,
    $location,
    $interval
  ) {

    return {
      templateUrl: settings.widgets + 'slack/slackbox.html',
      link: function(scope, element, attrs) {

        var savedUser;

        var sendMessage = function(channelName, text, UserIdentifier, callback){

          var name = channelName;
          var obj = savedUser.courses.filter(function ( obj ) {
            return obj.code === name;
          })[0];

          ChatService.sendMessage(obj.slack_channels[0].channelId, text, UserIdentifier).success(function(response){
            console.log("Response", response);
            ChatService.getMessages(obj.slack_channels[0].channelId, UserIdentifier).success(function(response){
              console.log("Response", response);
              callback(response.messages);
              });
          });
        }

        //Get messages with callback
        var getMessages = function(channelName, UserIdentifier, callback){
          scope.messages = [];

          var name = channelName;
          var obj = savedUser.courses.filter(function ( obj ) {
            return obj.code === name;
          })[0];

           ChatService.getMessages(obj.slack_channels[0].channelId, UserIdentifier).success(function(response){
              console.log("Response", response);
              callback(response.messages);
            });
        }

        /* scope.toggleCreateSlackBar = function(){
          $interval.cancel(gmPromise);
        } */

        var courseGlobal;
        var gmPromise;
        scope.showChatBox = function(course) {

          courseGlobal = course;
          if(scope.course != undefined) {

            if (scope.course.messages != undefined)
              {
                scope.course.messages = undefined;
                }
                scope.course = undefined;
          }

            //slack connection depending on course
            scope.course = "";
            scope.course = course;
            scope.courseSelected = true;
            $interval.cancel(gmPromise);
            gmPromise = $interval(gm, 1000);

        }

        var gm = function(){
          getMessages(courseGlobal.code, savedUser.email, function(messages){
            scope.course.messages = "";
            scope.course.messages = messages;
          });
        }

        scope.sendM = function(){
          sendMessage(scope.course.code, scope.input, savedUser.email,function(messages){
            scope.course.messages = "";
            scope.course.messages = messages;
          });
          scope.input = "";
        }

        SessionService.getSession().success(function(response) {
          User.get({_id: response.user._id, _populate: "courses"}, function(user){

            var coursesWithToken = [];

            for (var i = 0; i < user[0].courses.length; i++) {
              if(user[0].courses[i].slack_channels != 0)
              {
                coursesWithToken.push(user[0].courses[i]);

                console.log(user[0].courses[i]);
              }
            }

            scope.courselist = coursesWithToken;
            savedUser = user[0];
          });
        });

        scope.toggleCreateSlackBar = function() {
          $interval.cancel(gmPromise);
          scope.isToolbarPersonalOpen = false;
          scope.isToolbarCreateSlackOpen = scope.isToolbarCreateSlackOpen === true ? false: true;
          scope.courseSelected = false;
        }
      }
    }
  }
]);
<commit_msg>Reversed chat<commit_after>app.directive('slackSlackbox', [
  "settings",
  "ChatService",
  "User",
  "SessionService",
  "Course",
  "Channel",
  "$location",
  "$interval",
  function(
    settings,
    ChatService,
    User,
    SessionService,
    Course,
    Channel,
    $location,
    $interval
  ) {

    return {
      templateUrl: settings.widgets + 'slack/slackbox.html',
      link: function(scope, element, attrs) {

        var savedUser;

        var sendMessage = function(channelName, text, UserIdentifier, callback){

          var name = channelName;
          var obj = savedUser.courses.filter(function ( obj ) {
            return obj.code === name;
          })[0];

          ChatService.sendMessage(obj.slack_channels[0].channelId, text, UserIdentifier).success(function(response){
            console.log("Response", response);
            ChatService.getMessages(obj.slack_channels[0].channelId, UserIdentifier).success(function(response){
              console.log("Response", response);
              callback(response.messages.reverse());
              });
          });
        }

        //Get messages with callback
        var getMessages = function(channelName, UserIdentifier, callback){
          scope.messages = [];

          var name = channelName;
          var obj = savedUser.courses.filter(function ( obj ) {
            return obj.code === name;
          })[0];

           ChatService.getMessages(obj.slack_channels[0].channelId, UserIdentifier).success(function(response){
              console.log("Response", response);
              callback(response.messages.reverse());
            });
        }

        /* scope.toggleCreateSlackBar = function(){
          $interval.cancel(gmPromise);
        } */

        var courseGlobal;
        var gmPromise;
        scope.showChatBox = function(course) {

          courseGlobal = course;
          if(scope.course != undefined) {

            if (scope.course.messages != undefined)
              {
                scope.course.messages = undefined;
                }
                scope.course = undefined;
          }

            //slack connection depending on course
            scope.course = "";
            scope.course = course;
            scope.courseSelected = true;
            $interval.cancel(gmPromise);
            gmPromise = $interval(gm, 1000);

        }

        var gm = function(){
          getMessages(courseGlobal.code, savedUser.email, function(messages){
            scope.course.messages = "";
            scope.course.messages = messages;
          });
        }

        scope.sendM = function(){
          sendMessage(scope.course.code, scope.input, savedUser.email,function(messages){
            scope.course.messages = "";
            scope.course.messages = messages;
          });
          scope.input = "";
        }

        SessionService.getSession().success(function(response) {
          User.get({_id: response.user._id, _populate: "courses"}, function(user){

            var coursesWithToken = [];

            for (var i = 0; i < user[0].courses.length; i++) {
              if(user[0].courses[i].slack_channels != 0)
              {
                coursesWithToken.push(user[0].courses[i]);

                console.log(user[0].courses[i]);
              }
            }

            scope.courselist = coursesWithToken;
            savedUser = user[0];
          });
        });

        scope.toggleCreateSlackBar = function() {
          $interval.cancel(gmPromise);
          scope.isToolbarPersonalOpen = false;
          scope.isToolbarCreateSlackOpen = scope.isToolbarCreateSlackOpen === true ? false: true;
          scope.courseSelected = false;
        }
      }
    }
  }
]);
<|endoftext|>


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

import {LitElement, html, nothing} from "lit";
import UtilsNew from "../../core/utilsNew.js";
import "./opencga-facet-result-view.js";
import "./opencga-active-filters.js";
import "./forms/select-field-filter.js";
import "./opencb-facet-results.js";
import "./facet-filter.js";
import "../loading-spinner.js";
import "./tool-header.js";

export default class OpencgaBrowser extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            resource: {
                type: String
            },
            opencgaSession: {
                type: Object
            },
            cellbaseClient: {
                type: Object
            },
            query: {
                type: Object
            },
            // query object sent to Opencga client (includes this.selectedFacet serialised)
            facetQuery: {
                type: Object
            },
            // complex object that keeps track of the values of all facets
            selectedFacet: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = "facet" + UtilsNew.randomString(6);

        this.query = {};
        this.preparedQuery = {};
        this.executedQuery = {};

        this.checkProjects = false;

        this.activeFilterAlias = {
        };

        this.selectedFacet = {};
        this.preparedFacetQueryFormatted = {};
        this.activeTab = {};
        this.detail = {};
    }

    connectedCallback() {
        super.connectedCallback();
        // we don't need _config here
    }

    firstUpdated(_changedProperties) {
        $(".bootstrap-select", this).selectpicker();
        UtilsNew.initTooltip(this);
    }

    update(changedProperties) {
        if (changedProperties.has("opencgaSession")) {
            this.opencgaSessionObserver();
        }
        if (changedProperties.has("query")) {
            this.queryObserver();
        }
        if (changedProperties.has("selectedFacet")) {
            this.facetQueryBuilder();
        }
        super.update(changedProperties);
    }

    opencgaSessionObserver() {
        if (this?.opencgaSession?.study?.fqn) {
            this.checkProjects = true;
            this.query = {study: this.opencgaSession.study.fqn};

            this.preparedQuery = {study: this.opencgaSession.study.fqn};
            this.facetQuery = null;
            this.preparedFacetQueryFormatted = null;
            // this.requestUpdate();
            // this.onRun();

            // this.requestUpdate().then(() => $(".bootstrap-select", this).selectpicker());
        } else {
            this.checkProjects = false;
        }
    }

    queryObserver() {
        if (this?.opencgaSession?.study?.fqn) {
            // NOTE UtilsNew.objectCompare avoid repeating remote requests.
            if (!UtilsNew.objectCompare(this.query, this._query)) {
                this._query = this.query;
                if (this.query) {
                    this.preparedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
                    this.executedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
                } else {
                    this.preparedQuery = {study: this.opencgaSession.study.fqn};
                    this.executedQuery = {study: this.opencgaSession.study.fqn};
                }
                // onServerFilterChange() in opencga-active-filters fires an activeFilterChange event when the Filter dropdown is used
                this.dispatchEvent(new CustomEvent("queryChange", {
                    detail: this.preparedQuery
                }));
                this.detail = {};
            } else {
                // console.error("same queries")
            }
            // this.requestUpdate();
        }
    }

    facetQueryBuilder() {
        if (Object.keys(this.selectedFacet).length) {
            this.executedFacetQueryFormatted = {...this.preparedFacetQueryFormatted};

            this.facetQuery = {
                ...this.preparedQuery,
                study: this.opencgaSession.study.fqn,
                // timeout: 60000,
                field: Object.values(this.preparedFacetQueryFormatted).map(v => v.formatted).join(";")
            };
            this._changeView("facet-tab");
        } else {
            this.facetQuery = null;
        }
    }

    notifySearch(query) {
        this.dispatchEvent(new CustomEvent("querySearch", {
            detail: {
                query: query
            },
            bubbles: true,
            composed: true
        }));
    }

    async onRun() {
        // NOTE notifySearch() triggers this chain: notifySearch -> onQueryFilterSearch() on iva-app.js -> this.queries updated -> queryObserver() in opencga-browser
        // queryObserver() here stops the repetition of the remote request by checking if it has changed
        // TODO do the same with facetQuery
        this.query = {...this.preparedQuery};
        // updates this.queries in iva-app
        this.notifySearch(this.preparedQuery);

        this.facetQueryBuilder();
        // this.requestUpdate();

        /* if (Object.keys(this.selectedFacet).length) {
            this.facetQuery = {
                ...this.preparedQuery,
                study: this.opencgaSession.study.fqn,
                // timeout: 60000,
                field: Object.values(this.preparedFacetQueryFormatted).map(v => v.formatted).join(";")
            };
            this._changeView("facet-tab");
        } else {
            this.facetQuery = null;
        }*/
    }

    onFilterChange(e) {
        this.query = e.detail;
    }

    onClickPill(e) {
        this._changeView(e.currentTarget.dataset.id);
    }

    _changeView(tabId) {
        $(".content-pills", this).removeClass("active");
        $(".content-tab", this).removeClass("active");
        Object.keys(this.activeTab).forEach(tab => {
            this.activeTab[tab] = false;
        });
        $(`button.content-pills[data-id=${tabId}]`, this).addClass("active");
        $("#" + tabId, this).addClass("active");
        this.activeTab[tabId] = true;
        this.requestUpdate();
    }

    onQueryFilterChange(e) {
        // console.log("onQueryFilterChange")
        this.preparedQuery = e.detail.query;
        this.requestUpdate();
    }

    // TODO review
    // this is used only in case of Search button inside filter component. Only in Clinical Analysis Browser.
    onQueryFilterSearch(e) {
        this.dispatchEvent(new CustomEvent("querySearch", {
            detail: {
                query: e.detail.query
            }
        }));
    }

    onActiveFilterChange(e) {
        // console.log("onActiveFilterChange");
        this.preparedQuery = {study: this.opencgaSession.study.fqn, ...e.detail};
        this.query = {study: this.opencgaSession.study.fqn, ...e.detail};
        this.facetQueryBuilder();
    }

    onActiveFilterClear() {
        // console.log("onActiveFilterClear");
        this.query = {study: this.opencgaSession.study.fqn};
        this.preparedQuery = {...this.query};
        this.facetQueryBuilder();
    }

    onFacetQueryChange(e) {
        // console.log("onFacetQueryChange");
        this.preparedFacetQueryFormatted = e.detail.value;
        // this.facetQueryBuilder();
        this.requestUpdate();
    }

    onActiveFacetChange(e) {
        this.selectedFacet = {...e.detail};
        this.preparedFacetQueryFormatted = {...e.detail};
        // this.onRun(); // TODO the query should be repeated every action on active-filter (delete, clear, load from Saved filter)
        this.facetQueryBuilder();
        this.requestUpdate();
    }

    onActiveFacetClear(e) {
        this.selectedFacet = {};
        this.onRun();
        this.requestUpdate();
    }

    onClickRow(e, resource) {
        this.detail = {...this.detail, [resource]: e.detail.row};
        this.requestUpdate();
    }

    renderView() {

        if (!this.config.views) {
            return html`No view has been configured`;
        }

        const params = {
            opencgaSession: this.opencgaSession,
            config: this.config,
            executedQuery: this.executedQuery,
            detail: this.detail,
            resource: this.resource,
            facetQuery: this.facetQuery,
            facetResults: this.facetResults,
            eventNotifyName: this.eventNotifyName,
            activeTab: name => this.activeTab[name],
            onClickRow: (e, eventName) => this.onClickRow(e, eventName),
        };

        return this.config.views.map(view =>
            html`

                    ${view.render(params)}

            `);
    }

    renderfilter() {

        if (!this.config?.filter) {
            return html`${nothing}`;
        }

        const params = {
            opencgaSession: this.opencgaSession,
            config: this.config,
            query: this.query,
            onQueryFilterChange: this.onQueryFilterChange,
            onQueryFilterSearch: this.onQueryFilterSearch
        };

        return html`

                ${this.config.filter.render(params)}

`;
    }

    renderAggregation() {

        if (!this.config?.aggregation) {
            return html`${nothing}`;
        }

        const params = {
            config: this.config,
            selectedFacet: this.selectedFacet,
            onFacetQueryChange: this.onFacetQueryChange
        };

        return html `

                ${this.config.aggregation.render(params)}

`;
    }

    renderButtonViews() {

        if (!this.config.views) {
            return html`No view has been configured`;
        }

        return html `

                    ${this.config.views.map(tab => html`
                        <button
                            type="button"
                            class="btn btn-success content-pills ${tab.active ? "active" : ""}"
                            ?disabled=${tab.disabled}
                            @click="${this.onClickPill}"
                            data-id="${tab.id}">
                             ${tab.name}
                        </button>`
                    )}

        `;
    }

    render() {
        if (!this.opencgaSession?.study?.fqn) {
            return html`

No public projects available to browse. Please login to continue

            `;
        }

        return html`
            <tool-header
                .title="${this.config.title}"
                .icon="${this.config.icon}">
            </tool-header>

                        <button type="button" class="btn btn-primary ripple" @click="${this.onRun}">

                            ${this.config.searchButtonText || "Search"}
                        </button>

                            Filters

                        ${this.config.aggregation ? html`

                                Aggregation

                        ` : null}

                        ${this.renderfilter()}
                        ${this.renderAggregation()}

                    ${this.renderButtonViews()}

                        <opencga-active-filters
                            facetActive
                            .resource="${this.resource}"
                            .opencgaSession="${this.opencgaSession}"
                            .defaultStudy="${this.opencgaSession?.study?.fqn}"
                            .query="${this.preparedQuery}"
                            .executedQuery="${this.executedQuery}"
                            .facetQuery="${this.preparedFacetQueryFormatted}"
                            .executedFacetQuery="${this.executedFacetQueryFormatted}"
                            .alias="${this.activeFilterAlias}"
                            .config="${this.config.activeFilters}"
                            .filters="${this.config.filter.examples}"
                            @activeFilterChange="${this.onActiveFilterChange}"
                            @activeFilterClear="${this.onActiveFilterClear}"
                            @activeFacetChange="${this.onActiveFacetChange}"
                            @activeFacetClear="${this.onActiveFacetClear}">
                        </opencga-active-filters>

                            ${this.renderView()}

        `;
    }

}

customElements.define("opencga-browser", OpencgaBrowser);
<commit_msg>wc: style fixes in opencga-browser #TASK-468<commit_after>/*
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html, nothing} from "lit";
import UtilsNew from "../../core/utilsNew.js";
import "./opencga-facet-result-view.js";
import "./opencga-active-filters.js";
import "./forms/select-field-filter.js";
import "./opencb-facet-results.js";
import "./facet-filter.js";
import "../loading-spinner.js";
import "./tool-header.js";

export default class OpencgaBrowser extends LitElement {

    constructor() {
        super();
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            resource: {
                type: String
            },
            opencgaSession: {
                type: Object
            },
            cellbaseClient: {
                type: Object
            },
            query: {
                type: Object
            },
            // query object sent to Opencga client (includes this.selectedFacet serialised)
            facetQuery: {
                type: Object
            },
            // complex object that keeps track of the values of all facets
            selectedFacet: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = "facet" + UtilsNew.randomString(6);

        this.query = {};
        this.preparedQuery = {};
        this.executedQuery = {};

        this.checkProjects = false;

        this.activeFilterAlias = {};

        this.selectedFacet = {};
        this.preparedFacetQueryFormatted = {};
        this.activeTab = {};
        this.detail = {};
    }

    firstUpdated() {
        $(".bootstrap-select", this).selectpicker();
        UtilsNew.initTooltip(this);
    }

    update(changedProperties) {
        if (changedProperties.has("opencgaSession")) {
            this.opencgaSessionObserver();
        }

        if (changedProperties.has("query")) {
            this.queryObserver();
        }

        if (changedProperties.has("selectedFacet")) {
            this.facetQueryBuilder();
        }

        super.update(changedProperties);
    }

    opencgaSessionObserver() {
        if (this?.opencgaSession?.study?.fqn) {
            this.checkProjects = true;
            this.query = {study: this.opencgaSession.study.fqn};

            this.preparedQuery = {study: this.opencgaSession.study.fqn};
            this.facetQuery = null;
            this.preparedFacetQueryFormatted = null;
            // this.requestUpdate();
            // this.onRun();

            // this.requestUpdate().then(() => $(".bootstrap-select", this).selectpicker());
        } else {
            this.checkProjects = false;
        }
    }

    queryObserver() {
        if (this?.opencgaSession?.study?.fqn) {
            // NOTE UtilsNew.objectCompare avoid repeating remote requests.
            if (!UtilsNew.objectCompare(this.query, this._query)) {
                this._query = this.query;
                if (this.query) {
                    this.preparedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
                    this.executedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
                } else {
                    this.preparedQuery = {study: this.opencgaSession.study.fqn};
                    this.executedQuery = {study: this.opencgaSession.study.fqn};
                }
                // onServerFilterChange() in opencga-active-filters fires an activeFilterChange event when the Filter dropdown is used
                this.dispatchEvent(new CustomEvent("queryChange", {
                    detail: this.preparedQuery
                }));
                this.detail = {};
            } else {
                // console.error("same queries")
            }
            // this.requestUpdate();
        }
    }

    facetQueryBuilder() {
        if (Object.keys(this.selectedFacet).length) {
            this.executedFacetQueryFormatted = {...this.preparedFacetQueryFormatted};

            this.facetQuery = {
                ...this.preparedQuery,
                study: this.opencgaSession.study.fqn,
                // timeout: 60000,
                field: Object.values(this.preparedFacetQueryFormatted).map(v => v.formatted).join(";")
            };
            this._changeView("facet-tab");
        } else {
            this.facetQuery = null;
        }
    }

    notifySearch(query) {
        this.dispatchEvent(new CustomEvent("querySearch", {
            detail: {
                query: query
            },
            bubbles: true,
            composed: true
        }));
    }

    async onRun() {
        // NOTE notifySearch() triggers this chain: notifySearch -> onQueryFilterSearch() on iva-app.js -> this.queries updated -> queryObserver() in opencga-browser
        // queryObserver() here stops the repetition of the remote request by checking if it has changed
        // TODO do the same with facetQuery
        this.query = {...this.preparedQuery};
        // updates this.queries in iva-app
        this.notifySearch(this.preparedQuery);

        this.facetQueryBuilder();
        // this.requestUpdate();

        /* if (Object.keys(this.selectedFacet).length) {
            this.facetQuery = {
                ...this.preparedQuery,
                study: this.opencgaSession.study.fqn,
                // timeout: 60000,
                field: Object.values(this.preparedFacetQueryFormatted).map(v => v.formatted).join(";")
            };
            this._changeView("facet-tab");
        } else {
            this.facetQuery = null;
        }*/
    }

    onFilterChange(e) {
        this.query = e.detail;
    }

    onClickPill(e) {
        this._changeView(e.currentTarget.dataset.id);
    }

    _changeView(tabId) {
        $(".content-pills", this).removeClass("active");
        $(".content-tab", this).removeClass("active");
        Object.keys(this.activeTab).forEach(tab => {
            this.activeTab[tab] = false;
        });
        $(`button.content-pills[data-id=${tabId}]`, this).addClass("active");
        $("#" + tabId, this).addClass("active");
        this.activeTab[tabId] = true;
        this.requestUpdate();
    }

    onQueryFilterChange(e) {
        // console.log("onQueryFilterChange")
        this.preparedQuery = e.detail.query;
        this.requestUpdate();
    }

    // TODO review
    // this is used only in case of Search button inside filter component. Only in Clinical Analysis Browser.
    onQueryFilterSearch(e) {
        this.dispatchEvent(new CustomEvent("querySearch", {
            detail: {
                query: e.detail.query
            }
        }));
    }

    onActiveFilterChange(e) {
        // console.log("onActiveFilterChange");
        this.preparedQuery = {study: this.opencgaSession.study.fqn, ...e.detail};
        this.query = {study: this.opencgaSession.study.fqn, ...e.detail};
        this.facetQueryBuilder();
    }

    onActiveFilterClear() {
        // console.log("onActiveFilterClear");
        this.query = {study: this.opencgaSession.study.fqn};
        this.preparedQuery = {...this.query};
        this.facetQueryBuilder();
    }

    onFacetQueryChange(e) {
        // console.log("onFacetQueryChange");
        this.preparedFacetQueryFormatted = e.detail.value;
        // this.facetQueryBuilder();
        this.requestUpdate();
    }

    onActiveFacetChange(e) {
        this.selectedFacet = {...e.detail};
        this.preparedFacetQueryFormatted = {...e.detail};
        // this.onRun(); // TODO the query should be repeated every action on active-filter (delete, clear, load from Saved filter)
        this.facetQueryBuilder();
        this.requestUpdate();
    }

    onActiveFacetClear() {
        this.selectedFacet = {};
        this.onRun();
        this.requestUpdate();
    }

    onClickRow(e, resource) {
        this.detail = {
            ...this.detail,
            [resource]: e.detail.row,
        };
        this.requestUpdate();
    }

    renderView() {
        if (!this.config.views) {
            return html`No view has been configured`;
        }

        const params = {
            opencgaSession: this.opencgaSession,
            config: this.config,
            executedQuery: this.executedQuery,
            detail: this.detail,
            resource: this.resource,
            facetQuery: this.facetQuery,
            facetResults: this.facetResults,
            eventNotifyName: this.eventNotifyName,
            activeTab: name => this.activeTab[name],
            onClickRow: (e, eventName) => this.onClickRow(e, eventName),
        };

        return this.config.views.map(view => html`

                ${view.render(params)}

        `);
    }

    renderfilter() {
        if (!this.config?.filter) {
            return html`${nothing}`;
        }

        const params = {
            opencgaSession: this.opencgaSession,
            config: this.config,
            query: this.query,
            onQueryFilterChange: this.onQueryFilterChange,
            onQueryFilterSearch: this.onQueryFilterSearch
        };

        return html`

                ${this.config.filter.render(params)}

        `;
    }

    renderAggregation() {
        if (!this.config?.aggregation) {
            return html`${nothing}`;
        }

        const params = {
            config: this.config,
            selectedFacet: this.selectedFacet,
            onFacetQueryChange: this.onFacetQueryChange
        };

        return html `

                ${this.config.aggregation.render(params)}

        `;
    }

    renderButtonViews() {
        if (!this.config.views) {
            return html`No view has been configured`;
        }

        return html `

                    ${this.config.views.map(tab => html`
                        <button
                            type="button"
                            class="btn btn-success content-pills ${tab.active ? "active" : ""}"
                            ?disabled=${tab.disabled}
                            @click="${this.onClickPill}"
                            data-id="${tab.id}">
                             ${tab.name}
                        </button>
                    `)}

        `;
    }

    render() {
        if (!this.opencgaSession?.study?.fqn) {
            return html`

No public projects available to browse. Please login to continue

            `;
        }

        return html`
            <tool-header
                .title="${this.config.title}"
                .icon="${this.config.icon}">
            </tool-header>

                        <button type="button" class="btn btn-primary ripple" @click="${this.onRun}">

                            ${this.config.searchButtonText || "Search"}
                        </button>

                            Filters

                        ${this.config.aggregation ? html`

                                Aggregation

                        ` : null}

                        ${this.renderfilter()}
                        ${this.renderAggregation()}

                    ${this.renderButtonViews()}

                        <opencga-active-filters
                            facetActive
                            .resource="${this.resource}"
                            .opencgaSession="${this.opencgaSession}"
                            .defaultStudy="${this.opencgaSession?.study?.fqn}"
                            .query="${this.preparedQuery}"
                            .executedQuery="${this.executedQuery}"
                            .facetQuery="${this.preparedFacetQueryFormatted}"
                            .executedFacetQuery="${this.executedFacetQueryFormatted}"
                            .alias="${this.activeFilterAlias}"
                            .config="${this.config.activeFilters}"
                            .filters="${this.config.filter.examples}"
                            @activeFilterChange="${this.onActiveFilterChange}"
                            @activeFilterClear="${this.onActiveFilterClear}"
                            @activeFacetChange="${this.onActiveFacetChange}"
                            @activeFacetClear="${this.onActiveFacetClear}">
                        </opencga-active-filters>

                            ${this.renderView()}

        `;
    }

}

customElements.define("opencga-browser", OpencgaBrowser);
<|endoftext|>


<commit_before>(function($){

  //Utils functions
  function setActivities(){
    var activities = activityList.find(".notification li");
    activities.removeClass("chidden");
    if(!activityList.hasClass("fullList")){
      for(var i = 7; i<activities.length; i++){
        $(activities.get(i)).addClass("chidden");
      }
      $("#activity-list-full-btn").addClass("chidden");
      $("#activity-list-expand-btn a").text("Tout afficher");
    } else {
      $("#activity-list-full-btn").removeClass("chidden");
      $("#activity-list-expand-btn a").text("Cacher");
    }
  }

  String.prototype.hashCode = function() {
    var hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
      chr   = this.charCodeAt(i);
      hash  = ((hash << 5) - hash) + chr;
      hash |= 0; // Convert to 32bit integer
    }
    return hash;
  };

  function getActivityHash(activity){
    var title = activity.find(".resume strong a").text();
    var author = activity.find(".auteur").text();
    var date = activity.find(".date").text();
    return (title+author+date).hashCode().toString().replace(/-/g,"k");
  }

  //Events and iterators functions

  function onEachActivity(){
    var $this = $(this);
    var hash = getActivityHash($this);
    $this.attr("id","activity-"+hash);
    $this.attr("data-hash",hash);
    $this.prepend('')
  }

  function initOnEachActivityBroadcast(el){
      var $this = $(broadcastsActivity.get(el));
      var $title = $this.find(".titre");
      var title = $title.text();
      $title.text("Annonce");
      $this.find(".vignette_deco2").prepend("
"+title+"
");
      $this.find(".vignette_deco2 .auteur").text("Annonce d'administration")
  }

  function onClickActivity(e){
    if($(e.target).is("a") || $(e.target).is("a *"))
      return;
    var link = $(this).find("strong a").attr('href');
    if(link)
     window.location = link;
  }

  function onClickPinActivity(e){
    e.preventDefault();
    var activity = $(this).parent();
    if(activity.hasClass("pinned")){
      activity.removeClass("pinned");
    } else {
      activity.addClass("pinned");
      activity.prependTo(activity.parent());
    }
  }

  function onClickExpandActivity(e){
    e.preventDefault();
    activityList.toggleClass("fullList");
    setActivities();
  }

  //INIT

  $(".layout__slot:nth-child(1)").attr("id","calendar-list");
  $(".layout__slot:nth-child(2)").attr("id","app-list");
  $(".layout__slot:nth-child(3)").attr("id","activity-list");
  $(".layout__slot:nth-child(4)").attr("id","tweets-list");
  $(".layout__slot:nth-child(5)").attr("id","campus-post-list");
  $(".layout__slot:nth-child(6)").attr("id","school-post-list");

  var appList = $("#app-list")
  appList.prependTo(appList.parent())
  appList.removeClass();

  var tweetsList = $("#tweets-list")
  tweetsList.appendTo(tweetsList.parent())
  tweetsList.removeClass();

  var activityList = $("#activity-list");
  var broadcastsActivity = activityList.find(".notification li .vignette_deco .icon-chat").parent().parent();
  broadcastsActivity.each(initOnEachActivityBroadcast);

  var activities = activityList.find(".notification li");
  activities.on("click",onClickActivity)
  activities.each(onEachActivity)
  activities.find(".activity-pin").on("click",onClickPinActivity)

  var oldActivityBox = activityList.find(".card__lien");
  oldActivityBox.attr("id","activity-list-full-btn");
  activityList.find(".carte-activite").append("
Tout afficher
");

  $("#activity-list-expand-btn").on("click",onClickExpandActivity)

  setActivities();

})(jQuery);
<commit_msg>Update page-manipulation.js<commit_after>(function($){

  //Storages
  var pinnedActivities = []

  //Utils functions
  function setActivities(){
    var activities = activityList.find(".notification li");
    activities.removeClass("chidden");
    if(!activityList.hasClass("fullList")){
      for(var i = 7; i<activities.length; i++){
        $(activities.get(i)).addClass("chidden");
      }
      $("#activity-list-full-btn").addClass("chidden");
      $("#activity-list-expand-btn a").text("Tout afficher");
    } else {
      $("#activity-list-full-btn").removeClass("chidden");
      $("#activity-list-expand-btn a").text("Cacher");
    }
  }

  function setPinnedActivities(){
  }

  String.prototype.hashCode = function() {
    var hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
      chr   = this.charCodeAt(i);
      hash  = ((hash << 5) - hash) + chr;
      hash |= 0; // Convert to 32bit integer
    }
    return hash;
  };

  function getActivityHash(activity){
    var title = activity.find(".resume strong a").text();
    var author = activity.find(".auteur").text();
    var date = activity.find(".date").text();
    return (title+author+date).hashCode().toString().replace(/-/g,"k");
  }

  //Events and iterators functions

  function onEachActivity(){
    var $this = $(this);
    var hash = getActivityHash($this);
    $this.attr("id","activity-"+hash);
    $this.attr("data-hash",hash);
    $this.prepend('')
  }

  function initOnEachActivityBroadcast(el){
      var $this = $(broadcastsActivity.get(el));
      var $title = $this.find(".titre");
      var title = $title.text();
      $title.text("Annonce");
      $this.find(".vignette_deco2").prepend("
"+title+"
");
      $this.find(".vignette_deco2 .auteur").text("Annonce d'administration")
  }

  function onClickActivity(e){
    if($(e.target).is("a") || $(e.target).is("a *"))
      return;
    var link = $(this).find("strong a").attr('href');
    if(link)
     window.location = link;
  }

  function onClickPinActivity(e){
    e.preventDefault();
    var activity = $(this).parent();
    var pinned = pinnedActivities.find(function(el){return el.hash == activity.attr("data-hash")})
    if(pinned){
      activity.removeClass("pinned");
      if(pinned.before){
        activity.insertBefore($("#activity-"+pinned.before));
      } else {
        activity.appendTo(activity.parent());
      }
      pinnedActivities.splice(pinnedActivities.indexOf(pinned),1)
    } else {
      pinnedActivities.unshift({
        hash: activity.attr("data-hash"),
        before: activity.next().attr("data-hash")
      });
      activity.addClass("pinned");
      activity.prependTo(activity.parent());
    }
    console.log(pinnedActivities);
  }

  function onClickExpandActivity(e){
    e.preventDefault();
    activityList.toggleClass("fullList");
    setActivities();
  }

  //INIT

  $(".layout__slot:nth-child(1)").attr("id","calendar-list");
  $(".layout__slot:nth-child(2)").attr("id","app-list");
  $(".layout__slot:nth-child(3)").attr("id","activity-list");
  $(".layout__slot:nth-child(4)").attr("id","tweets-list");
  $(".layout__slot:nth-child(5)").attr("id","campus-post-list");
  $(".layout__slot:nth-child(6)").attr("id","school-post-list");

  var appList = $("#app-list")
  appList.prependTo(appList.parent())
  appList.removeClass();

  var tweetsList = $("#tweets-list")
  tweetsList.appendTo(tweetsList.parent())
  tweetsList.removeClass();

  var activityList = $("#activity-list");
  var broadcastsActivity = activityList.find(".notification li .vignette_deco .icon-chat").parent().parent();
  broadcastsActivity.each(initOnEachActivityBroadcast);

  var activities = activityList.find(".notification li");
  activities.on("click",onClickActivity)
  activities.each(onEachActivity)
  activities.find(".activity-pin").on("click",onClickPinActivity)

  var oldActivityBox = activityList.find(".card__lien");
  oldActivityBox.attr("id","activity-list-full-btn");
  activityList.find(".carte-activite").append("
Tout afficher
");

  $("#activity-list-expand-btn").on("click",onClickExpandActivity)

  setActivities();

})(jQuery);
<|endoftext|>


<commit_before>//jshint strict: false
module.exports = function(config) {
  config.set({

    basePath: './app',
	frameworks: ['jasmine'],
    files: [
    'lib/loader.js',
	  'lib/jquery.min.js',
      'lib/angular.min.js',
      'lib/angular-route.min.js',
      'lib/angular-mocks.js',
      'lib/angular-cookies.min.js',
	  'lib/firebase.js',
	  'lib/angularfire.min.js',
    'zwangbm/js/*.js',
    'jzhangbs/*.js',
    'TXR/*.js',
    'search/*.js',
      'unit_tests/*.js',

    ],
	exclude: [
	],
	preprocessors: {
		 'zwangbm/js/btnclick.js' : ['coverage'],
		 'jzhangbs/*.js' : ['coverage'],
		 'TXR/*.js': ['coverage'],
      	 'search/*.js' : ['coverage']

	},
	reporters: ['progress', 'coverage'],
	coverageReporter: {
			type: 'html',
			dir: 'coverage/',
			subdir: '.'
	},
	port: 8080,
	colors: true,
    browsers: ['Chrome'],
	singleRun: true,
    plugins: [
      'karma-chrome-launcher',
      'karma-jasmine',
	  'karma-coverage'
    ]

  });
};
<commit_msg>edit karma<commit_after>//jshint strict: false
module.exports = function(config) {
  config.set({

    basePath: './app',
	frameworks: ['jasmine'],
    files: [
    'lib/loader.js',
	  'lib/jquery.min.js',
      'lib/angular.min.js',
      'lib/angular-route.min.js',
      'lib/angular-mocks.js',
      'lib/angular-cookies.min.js',
	  'lib/firebase.js',
	  'lib/angularfire.min.js',
    'zwangbm/js/*.js',
    'jzhangbs/*.js',
    'TXR/*.js',
    'search/*.js',
      'unit_tests/*.js',

    ],
	exclude: [
	],
	preprocessors: {
		 'zwangbm/js/angular_invite.js' : ['coverage'],
		 'jzhangbs/*.js' : ['coverage'],
		 'TXR/*.js': ['coverage'],
      	 'search/*.js' : ['coverage']

	},
	reporters: ['progress', 'coverage'],
	coverageReporter: {
			type: 'html',
			dir: 'coverage/',
			subdir: '.'
	},
	port: 8080,
	colors: true,
    browsers: ['Chrome'],
	singleRun: true,
    plugins: [
      'karma-chrome-launcher',
      'karma-jasmine',
	  'karma-coverage'
    ]

  });
};
<|endoftext|>


<commit_before>/*
 * grunt-lazyload
 * https://github.com/raphaeleidus/grunt-lazyload
 *
 * Copyright (c) 2013 Raphael Eidus
 * Licensed under the MIT license.
 */

'use strict';

var util = require('util');

module.exports = function(grunt) {
  grunt.lazyLoadNpmTasks = function lazyload(NpmPackage, tasks) {
    if(!util.isArray(tasks)) {
      tasks = [tasks];
    }
    tasks.forEach(function(task) {
      //register the task aliases
      grunt.task.registerTask(task, task, function(){
        //pass along any arguments passed in
        var runName = Array.prototype.concat.apply([task], arguments).join(':');
        tasks.forEach(function(t) {
          //rename all the aliases (grunt doesn't have a task.delete ... yet)
          grunt.task.renameTask(t, '_'+t+'_');
        });
        //register the true tasks
        grunt.loadNpmTasks(NpmPackage);
        //run the task
        grunt.task.run(runName);
      });
    });
  }
};
<commit_msg>when --help is passed eagerload everything<commit_after>/*
 * grunt-lazyload
 * https://github.com/raphaeleidus/grunt-lazyload
 *
 * Copyright (c) 2013 Raphael Eidus
 * Licensed under the MIT license.
 */

'use strict';

var util = require('util');
var argv = process.argv;

module.exports = function(grunt) {
  grunt.lazyLoadNpmTasks = function lazyload(NpmPackage, tasks) {
    //when displaying the grunt help eager load everything
    if(argv.indexOf('--help') !== -1) {
      grunt.loadNpmTasks(NpmPackage);
    }
    if(!util.isArray(tasks)) {
      tasks = [tasks];
    }
    tasks.forEach(function(task) {
      //register the task aliases
      grunt.task.registerTask(task, task, function(){
        //pass along any arguments passed in
        var runName = Array.prototype.concat.apply([task], arguments).join(':');
        tasks.forEach(function(t) {
          //rename all the aliases (grunt doesn't have a task.delete ... yet)
          grunt.task.renameTask(t, '_'+t+'_');
        });
        //register the true tasks
        grunt.loadNpmTasks(NpmPackage);
        //run the task
        grunt.task.run(runName);
      });
    });
  }
};
<|endoftext|>


<commit_before>var Raf = require("raf");

function Animato(from, to, time, step, complete) {

    if (arguments.length === 1 && from && typeof from.from === "object" && typeof from.to === "object") {
        return new Animato(from.from, from.to, from.duration, from.step, from.complete);
    }
    if (this.constructor !== Animato) {
        return new Animato(from, to, time, step, complete);
    }
    this._from = from;
    this._inter = {};
    this._to = to || null;
    this._duration = time || 200;
    this._step = step || function () {};
    this._complete = function () {};
    if (typeof complete === "function") {
        this.run(complete);
    }
}

Animato.prototype.to = function (to) {
    this._to = to;
    return this;
};

Animato.prototype.duration = function (duration) {
    this._duration = duration;
    return this;
};

Animato.prototype.step = function (fn) {
    this._step = fn;
    return this;
};

Animato.prototype.complete = function (fn) {
    this._complete = fn;
    return this;
};

Animato.prototype.run = function (fn) {

    var self = this;

    self.deltas = {};
    for (var k in self._from) {
        if (!self._from.hasOwnProperty(k)) continue;
        self.deltas[k] = self._to[k] - self._from[k];
    }

    if (typeof fn === "function") {
        this._complete = fn;
    }

    return Raf(function tick (delta) {
        var proc = delta / self._duration
          , k
          ;

        for (k in self._from) {
            if (!self._from.hasOwnProperty(k)) continue;
            self._inter[k] = self._from[k] + self.deltas[k] * proc;
        }

        if (proc >= 1) {
            self._step(self._to);
            return self._complete();
        }

        self._step(self._inter);

        Raf(tick);
    });
};

Animato.Frames = function (from, to, count) {

    if (this.constructor !== Animato.Frames) {
        return new Animato.Frames(from, to, count);
    }

    this._from = from;
    this._to = to;
    this._count = count;
    this._step = function () {};
    this._complete = function () {};
    this._duration = 200;
};

Animato.Frames.prototype.toArray = function () {
    debugger
    var frames = []
      , deltas = {}
      , steps = {}
      , inter = {}
      , k = null
      ;

    for (k in this._from) {
        if (!this._from.hasOwnProperty(k)) continue;
        steps[k] = (deltas[k] = this._to[k] - this._from[k]) / this._count;
    }

    for (var i = 1; i < this._count; ++i) {
        inter = {};
        for (k in this._from) {
            if (!this._from.hasOwnProperty(k)) continue;
            inter[k] = this._from[k] + steps[k] * i;
        }
        frames.push(inter);
    }

    frames.push(this._to);
    return frames;
};

Animato.Frames.prototype.step = function (fn) {
    this._step = fn || this._step;
    return this;
};

Animato.Frames.prototype.duration = function (duration) {
    this._duration = duration;
    return this;
};

Animato.Frames.prototype.run = function (fn) {
    var self = this
      , frames = this.toArray()
      ;

    self._complete = fn || self._complete;
    return Raf(function tick (delta) {
        var proc = delta / self._duration
          , index = Math.round(proc * frames.length)
          , frame = frames[index]
          ;

        if (!frame) {
            return self._complete();
        }

        self._step(frame);

        Raf(tick);
    });
};

module.exports = Animato;
<commit_msg>JSDoc comments<commit_after>// Dependencies
var Raf = require("raf");

/**
 * Animato
 * Creates a new `Animato` instance.
 *
 * Usage:
 *
 * ```js
 * Animato({...}).to({...}).duration(1000).step(function (c) {
 *  ...
 * }).run(function () {
 *  ...
 * });
 *
 * Animato({
 *    from: {...}
 *  , to: {...}
 *  , duration: 1000
 *  , step: function () {...}
 *  , complete: function () {...}
 * })
 * ```
 *
 * @name Animato
 * @function
 * @param {Object} from The source object.
 * @param {Object} to The target object.
 * @param {Number} time The animation duration (milliseconds).
 * @param {Function} step The step function.
 * @param {Function} complete The complete function.
 * @return {Animato} The `Animato` instance.
 */
function Animato(from, to, time, step, complete) {

    if (arguments.length === 1 && from && typeof from.from === "object" && typeof from.to === "object") {
        return new Animato(from.from, from.to, from.duration, from.step, from.complete);
    }
    if (this.constructor !== Animato) {
        return new Animato(from, to, time, step, complete);
    }
    this._from = from;
    this._inter = {};
    this._to = to || null;
    this._duration = time || 200;
    this._step = step || function () {};
    this._complete = function () {};
    if (typeof complete === "function") {
        this.run(complete);
    }
}

/**
 * to
 * Sets the target object.
 *
 * @name to
 * @function
 * @param {Object} to The target object.
 * @return {Animato} The `Animato` instance.
 */
Animato.prototype.to = function (to) {
    this._to = to;
    return this;
};

/**
 * duration
 * Sets the animation duration.
 *
 * @name duration
 * @function
 * @param {Number} duration The animation duration (milliseconds).
 * @return {Animato} The `Animato` instance.
 */
Animato.prototype.duration = function (duration) {
    this._duration = duration;
    return this;
};

/**
 * step
 * Sets the step function. This function will be called every time when the animation changes.
 *
 * @name step
 * @function
 * @param {Function} fn The step function.
 * @return {Animato} The `Animato` instance.
 */
Animato.prototype.step = function (fn) {
    this._step = fn;
    return this;
};

/**
 * complete
 * Sets the complete function. This function will be called when the animation is done.
 *
 * @name complete
 * @function
 * @param {Function} fn The complete function.
 * @return {Animato} The `Animato` instance.
 */
Animato.prototype.complete = function (fn) {
    this._complete = fn;
    return this;
};

/**
 * run
 * Starts the animation.
 *
 * @name run
 * @function
 * @param {Function} fn The complete function.
 * @return {Raf} The `Raf` instance.
 */
Animato.prototype.run = function (fn) {

    var self = this;

    self.deltas = {};
    for (var k in self._from) {
        if (!self._from.hasOwnProperty(k)) continue;
        self.deltas[k] = self._to[k] - self._from[k];
    }

    if (typeof fn === "function") {
        this._complete = fn;
    }

    return Raf(function tick (delta) {
        var proc = delta / self._duration
          , k
          ;

        for (k in self._from) {
            if (!self._from.hasOwnProperty(k)) continue;
            self._inter[k] = self._from[k] + self.deltas[k] * proc;
        }

        if (proc >= 1) {
            self._step(self._to);
            return self._complete();
        }

        self._step(self._inter);

        Raf(tick);
    });
};

/**
 * Frames
 * Generate frames for two given objects (source and target).
 *
 * @name Frames
 * @function
 * @param {Object} from The source object.
 * @param {Object} to The target object.
 * @param {Number} count How many frames to generate.
 * @return {Frames} The `Animato.Frames` instance.
 */
Animato.Frames = function (from, to, count) {

    if (this.constructor !== Animato.Frames) {
        return new Animato.Frames(from, to, count);
    }

    this._from = from;
    this._to = to;
    this._count = count;
    this._step = function () {};
    this._complete = function () {};
    this._duration = 200;
};

/**
 * toArray
 * Builts the array of frames.
 *
 * @name toArray
 * @function
 * @return {Array} The frames array.
 */
Animato.Frames.prototype.toArray = function () {
    var frames = []
      , deltas = {}
      , steps = {}
      , inter = {}
      , k = null
      ;

    for (k in this._from) {
        if (!this._from.hasOwnProperty(k)) continue;
        steps[k] = (deltas[k] = this._to[k] - this._from[k]) / this._count;
    }

    for (var i = 1; i < this._count; ++i) {
        inter = {};
        for (k in this._from) {
            if (!this._from.hasOwnProperty(k)) continue;
            inter[k] = this._from[k] + steps[k] * i;
        }
        frames.push(inter);
    }

    frames.push(this._to);
    return frames;
};

/**
 * step
 * Sets the step function. This function will be called every time when the animation changes.
 *
 * @name step
 * @function
 * @param {Function} fn The step function.
 * @return {Animato} The `Animato` instance.
 */
Animato.Frames.prototype.step = function (fn) {
    this._step = fn || this._step;
    return this;
};

/**
 * duration
 * Sets the animation duration.
 *
 * @name duration
 * @function
 * @param {Number} duration The animation duration (milliseconds).
 * @return {Animato} The `Animato` instance.
 */
Animato.Frames.prototype.duration = function (duration) {
    this._duration = duration;
    return this;
};

/**
 * run
 * Starts the animation.
 *
 * @name run
 * @function
 * @param {Function} fn The complete function.
 * @return {Raf} The `Raf` instance.
 */
Animato.Frames.prototype.run = function (fn) {
    var self = this
      , frames = this.toArray()
      ;

    self._complete = fn || self._complete;
    return Raf(function tick (delta) {
        var proc = delta / self._duration
          , index = Math.round(proc * frames.length)
          , frame = frames[index]
          ;

        if (!frame) {
            return self._complete();
        }

        self._step(frame);

        Raf(tick);
    });
};

module.exports = Animato;
<|endoftext|>


<commit_before>/*
program.js
Used for setting up user parameters from CLI and returning streaming IO objects
*/

var program = require('commander'),
    fs = require('fs'),
    colors = require('colors');
//var cli = {};
var app = {};

module.exports = {}

program
  .version('0.0.1')
  .usage('[options]')
  .option('-i, --input [source]', "REQ: Input source. Takes file location or stream with '-i -'")
  .option ('-o --output [dest]', "OPTIONAL: Output destination. Defaults to stream. Takes file location or stream with '-o -'")
  .parse(process.argv);

sensemake(program)

// Display help if nothing displayed
if (!process.argv.slice(2).length) {
  program.outputHelp(make_red);
  process.exit(1);
}

function make_red(txt) {
  return colors.red(txt); //display the help text in red on the console
}

// Actual paramater sensemaking starts here

function sensemake(program){
  input(program.input)
  output(program.output)
}

function input(val){
  /*
    Builds input stream
    No default assumed
    '-': STDIN
    all other: assumed to be file location; writes over file
  */
  if (val === '-'){app.input=process.stdin}
  else{app.input = fs.createReadStream(val)}
}

function output(val){
  /*
    Builds output stream
    Default: STDOUT
    '-': STDOUT
    all other: Assumed to be file location
  */
  if(val === '-') // IS IT A DASH (STDOUT)
    { app.output=process.stdout}
  else if (typeof(val) === 'string'){ // IF ITS NOT A DASH, BUT ITS A STRING, ITS A FILE
    app.output = fs.createWriteStream(val)}
  else{ // OR WERE STDOUT AGAIN
      app.output=process.stdout
  }

}

module.exports.cli = program; // Original CLI params
module.exports.app = app; // Usable functions / data
<commit_msg>program prints help & quits when no inputs<commit_after>/*
program.js
Used for setting up user parameters from CLI and returning streaming IO objects
*/

var program = require('commander'),
    fs = require('fs'),
    colors = require('colors');
//var cli = {};
var app = {};

module.exports = {}

program
  .version('0.0.1')
  .usage('[options]')
  .option('-i, --input [source]', "REQ: Input source. Takes file location or stream with '-i -'")
  .option ('-o --output [dest]', "OPTIONAL: Output destination. Defaults to stream. Takes file location or stream with '-o -'")
  .parse(process.argv);

sensemake(program)

function make_red(txt) {
  return colors.red(txt); //display the help text in red on the console
}

// Actual paramater sensemaking starts here

function sensemake(program){
  // Display help if nothing displayed
  if (!process.argv.slice(2).length) {
    program.outputHelp(make_red);
    process.exit(1);
  }
  input(program.input)
  output(program.output)
}

function input(val){
  /*
    Builds input stream
    No default assumed
    '-': STDIN
    all other: assumed to be file location; writes over file
  */
  if (val === '-'){app.input=process.stdin}
  else{app.input = fs.createReadStream(val)}
}

function output(val){
  /*
    Builds output stream
    Default: STDOUT
    '-': STDOUT
    all other: Assumed to be file location
  */
  if(val === '-') // IS IT A DASH (STDOUT)
    { app.output=process.stdout}
  else if (typeof(val) === 'string'){ // IF ITS NOT A DASH, BUT ITS A STRING, ITS A FILE
    app.output = fs.createWriteStream(val)}
  else{ // OR WERE STDOUT AGAIN
      app.output=process.stdout
  }

}

module.exports.cli = program; // Original CLI params
module.exports.app = app; // Usable functions / data
<|endoftext|>


<commit_before>/*

The MIT License (MIT)

Copyright (c) 2013 Rémi Arnaud - Advanced Micro Devices, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

setViewer6Upload=function(upload){
    var header;
    var index;
    var buttonToReplace;
    upload.callOnClick(function(){
        header = upload.header();
        index=0;
    });
    var url = '/rest3d/upload',
        uploadButton = $('<button/>')
            .addClass('btn')
            .prop('disabled', true)
            .text('Upload')
            .on('click', function (){
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('Abort')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                data.submit();
                buttonToReplace=$(this);
                //.always(function () {
                //     $this.remove();
                // });
        }),
        // show the name of the file nicely
        formatName = function(data,file){
            var i = file.name.lastIndexOf('/');
            return file.name.substring(i+1);
        },
        convertButton = $('<button/>')
            .addClass('btn')
            .prop('disabled', true)
            .text('Convert')
            .on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('Convert')
                    .prop('disabled',true)
                // user rest to convert dae into glTF
                var callback = function(data) {
                    $this.prop('disabled',true);
                    if(data.result.output){console.debug(data.result.output);}
                    if(data.result.code){console.debug("Exit code: "+data.result.code);}
                    if (data.error){
                        var span = $('
Error code='+data.error.code+' :: '+data.error.message+'
');
                        data.context.append(span);
                    } else {
                        // ennumerate all resulting files
                        var $conve = upload.header(data.file.name);
                        $.each(data.result.files, function (index, file) {
                            var $download = $("<button>Downl..</button>").on("click",function(){
                                var gitHtml = $('');
                                gitPanel = $('body').append(gitHtml);
                            });

                        var url = decodeURIComponent(file.url);
                        var ext = url.match(/\.[^.]+$/);
                        console.debug(ext);
                        if(ext==".json"){
                            var $dialog = $("<button>Launch</button>").on("click",function(){
                                glTF.load(url, viewer.parse_gltf);
                                notif(url);
                            });
                                // function(parent,link,button1,button2,button3){
                                upload.convert($conve,formatName(data,file),$dialog,$download);
                        }
                        else{
                            upload.upload($conve,formatName(data,file),$dialog)
                        }
                            // var span = '

'+formatName(data,file)+'';
                            // // endsWith
                            // if (file.url.indexOf('.json', file.url.length - '.json'.length) !== -1) {
                            //     var url='/viewer/viewer4.html?file=/rest3d/upload/'+decodeURIComponent(file.name);
                            //     span += ' ->  View '+formatName(data,file)+'';
                            // }
                            // span += '
';
                            // data.context.append($(span));
                        });
                    }
                }

                rest3d.convert(data,callback);
            });

    upload.object.on('fileuploadadd', function (e, data) {
        upload.object=$(this);
        data.context = header;
        $.each(data.files, function (index, file) {
            if (!index) {
                upload.upload(header,file.name,uploadButton.clone(true).data(data));
            }
            else{this.upload(header,file.name);}
        });
    }).on('fileuploadprocessalways', function (e, data) {
            var indexI = data.index,
            file = data.files[indexI],
             node = $(data.context.children('div')[index+1]);
        if (file.preview) {
            node
                .prepend('
')
                .prepend(file.preview);
        }
        if (file.error) {
          GUI.addTooltip({
                    parent: node.find('button'),
                    content: file.error,
                });
        }
        if (indexI + 1 === data.files.length) {
            node.find('button')
                .text('Upload')
                .prop('disabled', !!data.files.error);
        }
        index++;
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        upload.progress.setValue(progress);
    }).on('fileuploaddone', function (e, data) {
        $.each(data.result.files, function (index, file) {
            file.assetName = data.result.files[index].name;
            var $node = convertButton.clone(true).data({file: file, context: data.context})
                .text('Convert')
                .prop('disabled', !/dae$/i.test(file.url));
            buttonToReplace
                .replaceWith($node);
        });
    }).on('fileuploadfail', function (e, data) {
        if (!data.result) {
            $(data.context.children()[0])
                .append('
')
                .append('error communicating with server')
                .find('button').remove();
        } else
        $.each(data.result.files, function (index, file) {
            var error = $('').text(file.error);
            $(data.context.children()[index])
                .append('
')
                .append(error)
                .find('button').remove();
        });
    });
}
<commit_msg>ad GLTF for upload assets workaround<commit_after>/*

The MIT License (MIT)

Copyright (c) 2013 Rémi Arnaud - Advanced Micro Devices, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

setViewer6Upload=function(upload){
    var header;
    var index;
    var buttonToReplace;
    upload.callOnClick(function(){
        header = upload.header();
        index=0;
    });
    var url = '/rest3d/upload',
        uploadButton = $('<button/>')
            .addClass('btn')
            .prop('disabled', true)
            .text('Upload')
            .on('click', function (){
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('Abort')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                data.submit();
                buttonToReplace=$(this);
                //.always(function () {
                //     $this.remove();
                // });
        }),
        // show the name of the file nicely
        formatName = function(data,file){
            var i = file.name.lastIndexOf('/');
            return file.name.substring(i+1);
        },
        convertButton = $('<button/>')
            .addClass('btn')
            .prop('disabled', true)
            .text('Convert')
            .on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('Convert')
                    .prop('disabled',true)
                // user rest to convert dae into glTF
                var callback = function(data) {
                    $this.prop('disabled',true);
                    if(data.result.output){console.debug(data.result.output);}
                    if(data.result.code){console.debug("Exit code: "+data.result.code);}
                    if (data.error){
                        var span = $('
Error code='+data.error.code+' :: '+data.error.message+'
');
                        data.context.append(span);
                    } else {
                        // ennumerate all resulting files
                        var $conve = upload.header(data.file.name);
                        $.each(data.result.files, function (index, file) {
                            var $download = $("<button>Downl..</button>").on("click",function(){
                                var gitHtml = $('');
                                gitPanel = $('body').append(gitHtml);
                            });

                        var url = decodeURIComponent(file.url);
                        var ext = url.match(/\.[^.]+$/);
                        console.debug(ext);
                        if(ext==".json"){
                            var $dialog = $("<button>Launch</button>").on("click",function(){
                                glTF.load(url, viewer.parse_gltf);
                                notif(url);
                            });
                                upload.convert($conve,formatName(data,file),$dialog,$download);
                        }
                        else{
                            upload.upload($conve,formatName(data,file),$dialog)
                        }
                        });
                    }
                }

                rest3d.convert(data,callback);
            });

    upload.object.on('fileuploadadd', function (e, data) {
        upload.object=$(this);
        data.context = header;
        $.each(data.files, function (index, file) {
            if (!index) {
                upload.upload(header,file.name,uploadButton.clone(true).data(data));
            }
            else{this.upload(header,file.name);}
        });
    }).on('fileuploadprocessalways', function (e, data) {
            var indexI = data.index,
            file = data.files[indexI],
             node = $(data.context.children('div')[index+1]);
        if (file.preview) {
            node
                .prepend('
')
                .prepend(file.preview);
        }
        if (file.error) {
          GUI.addTooltip({
                    parent: node.find('button'),
                    content: file.error,
                });
        }
        if (indexI + 1 === data.files.length) {
            node.find('button')
                .text('Upload')
                .prop('disabled', !!data.files.error);
        }
        index++;
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        upload.progress.setValue(progress);
    }).on('fileuploaddone', function (e, data) {
        $.each(data.result.files, function (index, file) {
            file.assetName = data.result.files[index].name;
            var $node = convertButton.clone(true).data({file: file, context: data.context})
                .text('Convert')
                .prop('disabled', !/dae$/i.test(file.url));
            buttonToReplace
                .replaceWith($node);
        });
    }).on('fileuploadfail', function (e, data) {
        if (!data.result) {
            $(data.context.children()[0])
                .append('
')
                .append('error communicating with server')
                .find('button').remove();
        } else
        $.each(data.result.files, function (index, file) {
            var error = $('').text(file.error);
            $(data.context.children()[index])
                .append('
')
                .append(error)
                .find('button').remove();
        });
    });
}
<|endoftext|>


<commit_before>new function() {

	function getCurrentPath(compoundPath) {
		if (compoundPath.children.length) {
			return compoundPath.children[compoundPath.children.length - 1];
		} else {
			throw Error('Use a moveTo() command first');
		}
	}

	CompoundPath = PathItem.extend({
		initialize: function(items) {
			this.base();
			this.children = [];
			if (items) {
				for (var i = 0, l = items.length; i < l; i++) {
					this.appendTop(items[i]);
				}
			}
		},

		draw: function(ctx) {
			if (this.children.length) {
				var firstChild = this.children[0];
				// if (!child.visible) return;
				ctx.beginPath();
				for (var i = 0, l = this.children.length; i < l; i++) {
					var child = this.children[i];
					child.draw(ctx, true);
				}
				firstChild.setCtxStyles(ctx);
				if (firstChild.fillColor) ctx.fill();
				if (firstChild.strokeColor) ctx.stroke();
			}
		},

		/**
		 * If this is a compound path with only one path inside,
		 * the path is moved outside and the compound path is erased.
		 * Otherwise, the compound path is returned unmodified.
		 *
		 * @return the simplified compound path.
		 */
		simplify: function() {
			if(this.children.length == 1) {
				var child = this.children[0];
				child.moveAbove(this);
				this.remove();
				return child;
			}
			return this;
		},

		smooth: function() {
			for (var i = 0, l = this.children.length; i < l; i++) {
				this.children[i].smooth();
			}
		},

		moveTo: function() {
			var path = new Path();
			this.appendTop(path);
			path.moveTo.apply(path, arguments);
		},

		moveBy: function() {
			if (!arguments.length) {
				this.moveTo(0, 0);
			} else {
				var point = Point.read(arguments);
				var curPath = this.getCurrentPath(this);
				var current = curPath.segments[curPath.segments.length - 1].point;
				this.moveTo(current.add(point));
			}
		}
	});

	var keys = ['lineTo', 'cubicCurveTo', 'curveTo', 'quadraticCurveTo',
	'arcTo', 'lineBy', 'curveBy', 'arcBy'];
	var props = {};

	function addProp(key) {
		props[key] = function() {
			var curPath = getCurrentPath(this);
			curPath[key].apply(curPath, arguments);
		};
	}

	for (var i = 0, l = keys.length; i < l; i++) {
		addProp(keys[i]);
	}
	CompoundPath.inject(props);
};<commit_msg>Optimise and simplfy CompoundPath code, by moving scope into extend() call, and only compiling one fields object inside it that is return at the end.<commit_after>CompoundPath = PathItem.extend(new function() {

	function getCurrentPath(compoundPath) {
		if (compoundPath.children.length) {
			return compoundPath.children[compoundPath.children.length - 1];
		} else {
			throw Error('Use a moveTo() command first');
		}
	}

	var fields = {
		initialize: function(items) {
			this.base();
			this.children = [];
			if (items) {
				for (var i = 0, l = items.length; i < l; i++) {
					this.appendTop(items[i]);
				}
			}
		},

		draw: function(ctx) {
			if (this.children.length) {
				var firstChild = this.children[0];
				// if (!child.visible) return;
				ctx.beginPath();
				for (var i = 0, l = this.children.length; i < l; i++) {
					var child = this.children[i];
					child.draw(ctx, true);
				}
				firstChild.setCtxStyles(ctx);
				if (firstChild.fillColor) ctx.fill();
				if (firstChild.strokeColor) ctx.stroke();
			}
		},

		/**
		 * If this is a compound path with only one path inside,
		 * the path is moved outside and the compound path is erased.
		 * Otherwise, the compound path is returned unmodified.
		 *
		 * @return the simplified compound path.
		 */
		simplify: function() {
			if(this.children.length == 1) {
				var child = this.children[0];
				child.moveAbove(this);
				this.remove();
				return child;
			}
			return this;
		},

		smooth: function() {
			for (var i = 0, l = this.children.length; i < l; i++) {
				this.children[i].smooth();
			}
		},

		moveTo: function() {
			var path = new Path();
			this.appendTop(path);
			path.moveTo.apply(path, arguments);
		},

		moveBy: function() {
			if (!arguments.length) {
				// TODO: Shouldn't this be relative to the previous position
				// in lack of an argument? This should then be corrected in
				// Scriptographer too.
				this.moveTo(0, 0);
			} else {
				var point = Point.read(arguments);
				var curPath = getCurrentPath(this);
				var current = curPath.segments[curPath.segments.length - 1].point;
				this.moveTo(current.add(point));
			}
		}
	};

	var keys = ['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo',
			'arcTo', 'lineBy', 'curveBy', 'arcBy'];
	for (var i = 0, l = keys.length; i < l; i++) {
		fields[keys[i]] = function() {
			var path = getCurrentPath(this);
			path[keys[i]].apply(path, arguments);
		};
	}

	return fields;
};<|endoftext|>


<commit_before>var mapOptions = {
    center: new google.maps.LatLng(29.650793, -82.326780),
    zoom: 14,
    mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map (document.getElementById("map"), mapOptions);

google.maps.event.addDomListener(window, 'load', initialize);

var marker=new google.maps.Marker({
  position:myCenter,
  });

var mapProp = {
  center:myCenter,
  zoom:5,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };
 //   new google.maps.Map(HTMLElement,MAPOPTIONS)
 //    mapvariable.fitBounds();

 <commit_msg>built a secondary map app to fool with called mapking hopefully merging the map to this app once completed<commit_after>var mapOptions = {
    center: new google.maps.LatLng(29.650793, -82.326780),
    zoom: 14,
    mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map (document.getElementById("map"), mapOptions);

google.maps.event.addDomListener(window, 'load', initialize);

var marker=new google.maps.Marker({
  position:myCenter,
  });

var mapProp = {
  center:myCenter,
  zoom:5,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };
 //   new google.maps.Map(HTMLElement,MAPOPTIONS)
 //    mapvariable.fitBounds();

<|endoftext|>