<commit_before>/**
  * LaszloEvents.lzs
  *
  * @copyright Copyright 2001-2007 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.
  *
  * @affects lzevent lzdelegate
  */

/** A delegate is essentially a closure.
  */
class LzDelegate {

/**
  * @param Object context: reference to object which will be called
  * @param String functionName: name of the method to call (a string)
  * @param Object eventSender: optional; the sender of the event to register the
  * new delegate for.
  * @param String eventName: Optional, but required if eventSender is used; The name
  * of the event to register the new delegate for.
*/
function initialize (context, functionName, eventSender, eventName) {
  super.initialize.apply(this, arguments);
  // too expensive to leave on all the time
//     if ($debug) {
//         this._dbg_created = Debug.backtrace();
//     }
//@field Object c: The context in which to call the method
  this.c = context;
  if ( $debug ){
    if (typeof(functionName) != "string")
      Debug.warn('LzDelegate functionName must be a string in %w', arguments.caller);
  }
  //@field String f: The name of the method to call
  this.f = functionName;
  if ( eventSender != null ){
    if ( $debug ) {
      if (typeof(eventName) != "string") {
        Debug.warn('LzDelegate eventName must be a string in %w', arguments.caller);
      }
    }
    this.register( eventSender , eventName );
  }

  this.__delegateID = LzDelegate.__nextID++;
}

static var __nextID = 1;

var lastevent = 0;
var enabled = true;
var event_called = false;

/**
  * Executes the named method in the given context with the given data. Returns
  * the result of the call.
  *
  * @param sd: The data with which to call the method.
  * @return Object: The value returned by the method call.
  */
function execute (sd){
    // Don't execute if context has been deleted, as that could
    // 'resurrect' the deleted view, causing a memory leak
    // Usually this is because a deleted view has idle or timer events
    // still registered.
    var context = this.c;
    if (context) {
        if (context['__LZdeleted']) {
            return;
        }
        return context[this.f]( sd );
    }
}

/**
  * Registers the delegate for the named event in the given context. NB:
  * This is the primary way in which events are created. Published events do
  * not generally exist as objects (with some exceptions) until delegates are
  * created for them.
  *
  * @param Object eventSender: The object which publishes the event.
  * @param String eventName: The name (string) of the event to register for.
  */
function register ( eventSender , eventName){
    if (! eventSender) {
        Debug.error('No eventSender (%w) for %s', eventSender, eventName);
        return;
    }

    var anEvent = eventSender[ eventName ];

    if ( anEvent == LzDeclaredEvent || !anEvent ){
        // The call used to be unrolled here for swf. I removed it since it
        // was done during the swf5 days
        anEvent = new LzEvent( eventSender, eventName , this );
    } else {
        anEvent.addDelegate( this );
    }

    this[ this.lastevent++ ] = anEvent;

    // If debugging, add an informative name
    if ($debug) {
        var anEvent = eventSender[ eventName ];
        if (! anEvent.hasOwnProperty('_dbg_eventSender')) {
            anEvent._dbg_eventSender = eventSender;
            anEvent._dbg_eventName = eventName;
            // too expensive to leave on all the time
//             anEvent._dbg_created = Debug.backtrace();
        }
    }
    if ($profile) {
        var anEvent = eventSender[ eventName ];
        if (! anEvent.hasOwnProperty('_dbg_profileName')) {
            anEvent._dbg_profileName = eventName;
        }
    }
}

/**
  * Unregisters the delegate for all of the events it is registered for.
  */
function unregisterAll ( ){
    for (var i = 0; i< this.lastevent ; i++){
        this[ i ].removeDelegate( this );
        this[ i ] = null;
    }
    this.lastevent = 0;
}

/**
  * Unregisters the delegate for the given event
  * @param LzEvent event: The event to unregister the delegate from.
  *                      (e.g.  myview.onmouseup)
  */
function unregisterFrom ( event ){
    var keep = [];
    for (var i = 0; i< this.lastevent ; i++){
        var ev = this[ i ];
        if ( ev == event ){
            ev.removeDelegate( this );
        } else {
            keep.push( ev );
        }
        this[ i ] = null;
    }
    //now fix it
    this.lastevent = 0;
    for ( var i = 0; i < keep.length; i++ ){
        this[ this.lastevent++ ] = keep[ i ];
    }
}

/**
  * Disables the delegate until enable method is called.
  */
function disable (){
    this.enabled = false;
}

/**
  * Enables a delegate that has been disabled
  */
function enable (){
    this.enabled = true;
}

/**
  * @keywords private
  */
function toString (){
    return ("Delegate for " + this.c + " calls " + this.f + " " + this.__delegateID );
}

if ($debug) {
/**
  * If debugging, add an informative name
  * @keywords private
  */
function _dbg_name (){
    return (Debug.formatToString("%0.48w.%s()", this.c, this.f));
}
}

} // End of LzDelegate

class LzEvent {

/** An event is an object which stores delegates. When it is called, it
  * calls all of its delegates in turn. Due to the dynamic (and lazy) nature
  * of event instantiation, events store themselves in their containing object
  * in two ways: first, in slot equivalent to their name (view[eventName]
  * = event) and second, in an array in the containing object (which it will
  *  create if it doesn't exist) called _events
  *
  *
  * @param Object eventSender: The owner of this event
  * @param String eventName: The name of this event.
  */
function initialize ( eventSender , eventName , d ){
    super.initialize.apply(this, arguments);

    var _evs = eventSender._events;
    if (_evs == null ){
        eventSender._events = [ this ];
    } else {
        _evs.push ( this );
    }
    eventSender[ eventName ] = this;
    if ( d ){
        this.delegateList = [d];
    }else{
        this.delegateList = [];
    }

    // If debugging, add an informative name
    if ($debug) {
        var anEvent = eventSender[ eventName ];
        if (! anEvent.hasOwnProperty('_dbg_eventSender')) {
            anEvent._dbg_eventSender = eventSender;
            anEvent._dbg_eventName = eventName;
        }
    }
    if ($profile) {
        var anEvent = eventSender[ eventName ];
        if (! anEvent.hasOwnProperty('_dbg_profileName')) {
            anEvent._dbg_profileName = eventName;
        }
    }

}

// Because this is not created with Class
//prototype.classname = "LzEvent";
var locked = false;

/**
  * Adds the given delegate to the event's delegate list. Although this listed
  * as a public function it should rarely be called explicitly -- it is used
  * exclusively by LzDelegate.register
  *
  * @param LzDelegate d: The delegate to add to the list of delegates called by the event.
  */
function addDelegate (d){
    this.delegateList.push(d);
}

/**
  * Sends the event, passing its argument as the data to all the called
  * delegates
  *
  * @param sd: The data to send with the event.
  */
function sendEvent ( sd ){
    //@field locked: Bool which is true when event is being sent.
    if ( this.locked ) { return; } //don't allow for multiple calls

    var dll = this.delegateList.length;
    if (dll == 0) { return; }

    if ($profile) {
        var nm = this._dbg_profileName;

        if (nm) {
            Profiler.event(nm, 'calls');
        }
    }

    this.locked = true;

    var calledDelegates = new Array;

    var d;
    for (var i = dll; i >= 0; i--){
        d = this.delegateList[ i ];
        //pointer may be bad due to deletions
        if ( d && ! d.event_called){
            d.event_called = true; //this delegate has been called
            calledDelegates.push( d );
            // d.execute( sd ); inlined
            // We don't worry about deleted contexts here, because
            // we assume that delegates registered on events are
            // properly managed
            if (d.enabled && d.c) {
                d.c[d.f]( sd );
            }
        }
    }

    while (d = calledDelegates.pop() ){
        d.event_called = false;
    }

    if ($profile) {
        var nm = this._dbg_profileName;
        if (nm) {
            Profiler.event(nm, 'returns');
        }
    }

    this.locked = false;
}

/**
  * Removes the delegate from the delegate list. In practice, this is rarely
  * called explicitly, since it does not update the delegate's list of stored
  * events. Right now, this is called only by LzDelegate.
  * unregisterAll Delegates should support a simple unregister command, that
  * unregisters them for a single event, but to date, that has not proven
  * necessary
  *
  * @param LzDelegate d: The delegate to remove from the delegateList.
  */
function removeDelegate ( d ){
    var dll = this.delegateList.length;
    for (var i = 0; i < dll; i++){
        if (this.delegateList[i] == d){
            this.delegateList.splice(i, 1);
            break;
        }
    }
    if ( this.delegateList.length == 0 ){
        this.hasNoDelegates = true;
    }
}

/**
  * Removes all delegates from call list
  */
function clearDelegates (){
    while (this.delegateList.length ){
        this.delegateList[ 0 ].unregisterFrom( this );
    }
    //this.delegateList = [];
    this.hasNoDelegates = true;
}

/**
  * Returns the number of delegates registered for the event
  * @return Number: The number of delegates registered for the event.
  */
function getDelegateCount ( ){
    return this.delegateList.length;
}

function toString (){
    return ( "LzEvent");
}

if ($debug) {
/**
  * If debugging, add an informative name
  * @keywords private
  */
function _dbg_name (){
    return Debug.formatToString("%0.48w.%s", this._dbg_eventSender, this._dbg_eventName);
}
}

} // End of LzEvent
<commit_msg>Change 20080504-dda-P by dda@lester.local on 2008-05-04 18:47:16 EDT     in /Users/dda/laszlo/src/svn/openlaszlo/trunk-doc     for http://svn.openlaszlo.org/openlaszlo/trunk<commit_after>/**
  * LaszloEvents.lzs
  *
  * @copyright Copyright 2001-2008 Laszlo Systems, Inc.  All Rights Reserved.
  *            Use is subject to license terms.
  *
  * @affects lzevent lzdelegate
  */

/** A delegate is essentially a closure.
  */
class LzDelegate {

/**
  * @param Object context: reference to object which will be called
  * @param String functionName: name of the method to call (a string)
  * @param Object eventSender: optional; the sender of the event to register the
  * new delegate for.
  * @param String eventName: Optional, but required if eventSender is used; The name
  * of the event to register the new delegate for.
*/
function initialize (context, functionName, eventSender, eventName) {
  super.initialize.apply(this, arguments);
  // too expensive to leave on all the time
//     if ($debug) {
//         this._dbg_created = Debug.backtrace();
//     }
//@field Object c: The context in which to call the method
  this.c = context;
  if ( $debug ){
    if (typeof(functionName) != "string")
      Debug.warn('LzDelegate functionName must be a string in %w', arguments.caller);
  }
  //@field String f: The name of the method to call
  this.f = functionName;
  if ( eventSender != null ){
    if ( $debug ) {
      if (typeof(eventName) != "string") {
        Debug.warn('LzDelegate eventName must be a string in %w', arguments.caller);
      }
    }
    this.register( eventSender , eventName );
  }

  this.__delegateID = LzDelegate.__nextID++;
}

static var __nextID = 1;

var lastevent = 0;
var enabled = true;
var event_called = false;

/**
  * Executes the named method in the given context with the given data. Returns
  * the result of the call.
  *
  * @param sd: The data with which to call the method.
  * @return Object: The value returned by the method call.
  */
function execute (sd){
    // Don't execute if context has been deleted, as that could
    // 'resurrect' the deleted view, causing a memory leak
    // Usually this is because a deleted view has idle or timer events
    // still registered.
    var context = this.c;
    if (context) {
        if (context['__LZdeleted']) {
            return;
        }
        return context[this.f]( sd );
    }
}

/**
  * Registers the delegate for the named event in the given context. NB:
  * This is the primary way in which events are created. Published events do
  * not generally exist as objects (with some exceptions) until delegates are
  * created for them.
  *
  * @param Object eventSender: The object which publishes the event.
  * @param String eventName: The name (string) of the event to register for.
  */
function register ( eventSender , eventName){
    if (! eventSender) {
        Debug.error('No eventSender (%w) for %s', eventSender, eventName);
        return;
    }

    var anEvent = eventSender[ eventName ];

    if ( anEvent == LzDeclaredEvent || !anEvent ){
        // The call used to be unrolled here for swf. I removed it since it
        // was done during the swf5 days
        anEvent = new LzEvent( eventSender, eventName , this );
    } else {
        anEvent.addDelegate( this );
    }

    this[ this.lastevent++ ] = anEvent;

    // If debugging, add an informative name
    if ($debug) {
        var anEvent = eventSender[ eventName ];
        if (! anEvent.hasOwnProperty('_dbg_eventSender')) {
            anEvent._dbg_eventSender = eventSender;
            anEvent._dbg_eventName = eventName;
            // too expensive to leave on all the time
//             anEvent._dbg_created = Debug.backtrace();
        }
    }
    if ($profile) {
        var anEvent = eventSender[ eventName ];
        if (! anEvent.hasOwnProperty('_dbg_profileName')) {
            anEvent._dbg_profileName = eventName;
        }
    }
}

/**
  * Unregisters the delegate for all of the events it is registered for.
  */
function unregisterAll ( ){
    for (var i = 0; i< this.lastevent ; i++){
        this[ i ].removeDelegate( this );
        this[ i ] = null;
    }
    this.lastevent = 0;
}

/**
  * Unregisters the delegate for the given event
  * @param LzEvent event: The event to unregister the delegate from.
  *                      (e.g.  myview.onmouseup)
  */
function unregisterFrom ( event ){
    var keep = [];
    for (var i = 0; i< this.lastevent ; i++){
        var ev = this[ i ];
        if ( ev == event ){
            ev.removeDelegate( this );
        } else {
            keep.push( ev );
        }
        this[ i ] = null;
    }
    //now fix it
    this.lastevent = 0;
    for ( var i = 0; i < keep.length; i++ ){
        this[ this.lastevent++ ] = keep[ i ];
    }
}

/**
  * Disables the delegate until enable method is called.
  */
function disable (){
    this.enabled = false;
}

/**
  * Enables a delegate that has been disabled
  */
function enable (){
    this.enabled = true;
}

/**
  * @keywords private
  */
function toString (){
    return ("Delegate for " + this.c + " calls " + this.f + " " + this.__delegateID );
}

if ($debug) {
/**
  * If debugging, add an informative name
  * @keywords private
  */
function _dbg_name (){
    return (Debug.formatToString("%0.48w.%s()", this.c, this.f));
}
}

} // End of LzDelegate

class LzEvent {

/** An event is an object which stores delegates. When it is called, it
  * calls all of its delegates in turn. Due to the dynamic (and lazy) nature
  * of event instantiation, events store themselves in their containing object
  * in two ways: first, in slot equivalent to their name (view[eventName]
  * = event) and second, in an array in the containing object (which it will
  *  create if it doesn't exist) called _events
  *
  *
  * @param Object eventSender: The owner of this event
  * @param String eventName: The name of this event.
  */
function initialize ( eventSender , eventName , d ){
    super.initialize.apply(this, arguments);

    var _evs = eventSender._events;
    if (_evs == null ){
        eventSender._events = [ this ];
    } else {
        _evs.push ( this );
    }
    eventSender[ eventName ] = this;
    if ( d ){
        this.delegateList = [d];
    }else{
        this.delegateList = [];
    }

    // If debugging, add an informative name
    if ($debug) {
        var anEvent = eventSender[ eventName ];
        if (! anEvent.hasOwnProperty('_dbg_eventSender')) {
            anEvent._dbg_eventSender = eventSender;
            anEvent._dbg_eventName = eventName;
        }
    }
    if ($profile) {
        var anEvent = eventSender[ eventName ];
        if (! anEvent.hasOwnProperty('_dbg_profileName')) {
            anEvent._dbg_profileName = eventName;
        }
    }

}

// Because this is not created with Class
//prototype.classname = "LzEvent";
var locked = false;

/**
  * Adds the given delegate to the event's delegate list. Although this listed
  * as a public function it should rarely be called explicitly -- it is used
  * exclusively by LzDelegate.register
  *
  * @param LzDelegate d: The delegate to add to the list of delegates called by the event.
  */
function addDelegate (d){
    this.delegateList.push(d);
}

/**
  * Sends the event, passing its argument as the data to all the called
  * delegates
  *
  * @param sd: The data to send with the event.
  */
function sendEvent ( sd ){
    //@field locked: Bool which is true when event is being sent.
    if ( this.locked ) { return; } //don't allow for multiple calls

    var dll = this.delegateList.length;
    if (dll == 0) { return; }

    if ($profile) {
        var nm = this._dbg_profileName;

        if (nm) {
            Profiler.event(nm, 'calls');
        }
    }

    this.locked = true;

    var calledDelegates = new Array;

    var d;
    for (var i = dll; i >= 0; i--){
        d = this.delegateList[ i ];
        //pointer may be bad due to deletions
        if ( d && ! d.event_called){
            d.event_called = true; //this delegate has been called
            calledDelegates.push( d );
            // d.execute( sd ); inlined
            // We don't worry about deleted contexts here, because
            // we assume that delegates registered on events are
            // properly managed
            if (d.enabled && d.c) {
                d.c[d.f]( sd );
            }
        }
    }

    while (d = calledDelegates.pop() ){
        d.event_called = false;
    }

    if ($profile) {
        var nm = this._dbg_profileName;
        if (nm) {
            Profiler.event(nm, 'returns');
        }
    }

    this.locked = false;
}

/**
  * Removes the delegate from the delegate list. In practice, this is rarely
  * called explicitly, since it does not update the delegate's list of stored
  * events. Right now, this is called only by LzDelegate.
  * unregisterAll Delegates should support a simple unregister command, that
  * unregisters them for a single event, but to date, that has not proven
  * necessary
  *
  * @param LzDelegate d: The delegate to remove from the delegateList.
  */
function removeDelegate ( d ){
    var dll = this.delegateList.length;
    for (var i = 0; i < dll; i++){
        if (this.delegateList[i] == d){
            this.delegateList.splice(i, 1);
            break;
        }
    }
    if ( this.delegateList.length == 0 ){
        this.hasNoDelegates = true;
    }
}

/**
  * Removes all delegates from call list
  */
function clearDelegates (){
    while (this.delegateList.length ){
        this.delegateList[ 0 ].unregisterFrom( this );
    }
    //this.delegateList = [];
    this.hasNoDelegates = true;
}

/**
  * Returns the number of delegates registered for the event
  * @return Number: The number of delegates registered for the event.
  */
function getDelegateCount ( ){
    return this.delegateList.length;
}

function toString (){
    return ( "LzEvent");
}

if ($debug) {
/**
  * If debugging, add an informative name
  * @keywords private
  */
function _dbg_name (){
    return Debug.formatToString("%0.48w.%s", this._dbg_eventSender, this._dbg_eventName);
}
}

} // End of LzEvent
<|endoftext|>


<commit_before>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.StartQueryBuilderView = Backbone.View.extend({
    el: "#developer-playground",

    template: _.template($('#playground-template').html()),

    events: {
        'change .form-control#entity': 'changeParam',
        'change .form-control#parameter': 'changeFilter',
        'click .btn#san-francisco': 'changeMapSF',
        'click .btn#new-york': 'changeMapNY',
        'click .btn#run-query-btn' : 'submit'
    },

    initialize: function () {
        this.operators = new DeveloperPlayground.Operators();
        this.stops = new DeveloperPlayground.Stops();
        this.routes = new DeveloperPlayground.Routes();
        this.render();
    },

    render: function() {
        this.$el.html(this.template());
        $(".form-control#name").hide();
        $(".btn#new-york").hide();
        $(".btn#san-francisco").hide();

        if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");
        this.mapview = new DeveloperPlayground.MapView();
        this.mapview.render();
        this.downloadview = new DeveloperPlayground.DownloadView();
        this.downloadview.render();
        return this;
    },

    changeMapSF: function(){
        if($(".btn#new-york").hasClass("selected")) $(".btn#new-york").removeClass("selected");
        $(".btn#san-francisco").addClass("selected");
        this.mapview.setMapviewSF();
    },

    changeMapNY: function(){
        if($(".btn#san-francisco").hasClass("selected")) $(".btn#san-francisco").removeClass("selected");
        $(".btn#new-york").addClass("selected");
        this.mapview.setMapviewNY();
    },

    changeParam: function() {

        $(".form-control#name").hide();
        $(".btn#new-york").hide();
        $(".btn#san-francisco").hide();

        if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");

        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var selectValues = {
            "base": {
                " ": "",
            },
            "stops": {
                " ": "",
                "map view": "",
                "operator": "",
            },
            "operators": {
                " ": "",
                "map view": "",
                "name": "",
                // "mode": "",
            },
            "routes": {
                " ": "",
                "map view": "",
                "operator": "",
                // "route number": "",
            }
        };

        $parameterSelect.empty().append(function() {
            var output = '';
            $.each(selectValues[$entitySelect.val()], function(key, value) {
                output += '<option>' + key + '</option>';
            });
            return output;
        });

        return this;
    },

    changeFilter: function() {
        var $parameterSelect = $('select.form-control#parameter');

        if($parameterSelect.val() == "name" || $parameterSelect.val() == "operator") {
            collection = this.operators;
            $(".form-control#name").show();
            $(".btn#new-york").hide();
            $(".btn#san-francisco").hide();

            if(!$("#nameMenu").hasClass("dropdown")) $("#nameMenu").addClass("dropdown");
            if ('undefined' !== typeof this.nameListView) {
                this.nameListView.close();
                this.nameListView = new DeveloperPlayground.NameListView({collection: collection});
            } else {
                this.nameListView = new DeveloperPlayground.NameListView({collection: collection});
            }
            this.operators.setQueryParameters({
                    url: API_HOST+'/api/v1/operators.json?per_page=5000'
                });
            collection.fetch();
            return this;

        } else {
            $(".form-control#name").hide();
            this.changeMapSF();
            $(".btn#new-york").show();
            $(".btn#san-francisco").show();

            if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");

        }
    },

    submit: function() {
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var $nameSelect = $('select.form-control#name');
        var bounds = this.mapview.getBounds();
        var identifier = $nameSelect.val();

        var shouldFetchAndResetCollection = true;

        // FOR STOP QUERIES

        if ($entitySelect.val() == "stops") {
            // for search by map view
            if($parameterSelect.val() == "map view") {
            collection = this.stops;
            this.stops.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            // for search by operator name
            } else if($parameterSelect.val() == "operator") {
                collection = this.stops;
                this.stops.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?servedBy='+identifier+'&per_page=5000',
                });
            }

        // FOR OPERATOR QUERIES

        } else if ($entitySelect.val() == "operators") {

            if($parameterSelect.val() == "map view") {
                collection = this.operators;
                this.operators.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            } else if($parameterSelect.val() == "name") {
                this.operators.hideAll();
                this.operators.get(identifier).set({ display: true });
                shouldFetchAndResetCollection = false;
            } else {
                alert("Please select either map view or name.");
            }

        //  FOR ROUTE QUERIES

        } else if ($entitySelect.val() == "routes") {
            if($parameterSelect.val() == "map view") {
                collection = this.routes;
                this.routes.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            } else if($parameterSelect.val() == "operator") {
                collection = this.routes;
                this.routes.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?operatedBy='+identifier+'&per_page=5000',
                });
            } else if($parameterSelect.val() == "route number") {
                collection = this.routes;
                alert("routes by route number not yet functional");
            }
        } else {
            alert("Please select a parameter.");
        }

        if (shouldFetchAndResetCollection) {
            collection.reset();
        }

        $("#download-bar").show();
        this.mapview.markerclustergroup.clearLayers();
        this.mapview.clearCollection();
        this.mapview.setCollection({collection: collection});
        this.mapview.initialize({collection: collection});
        this.downloadview.setCollection({collection: collection});

        if ('undefined' !== typeof this.gridview) this.gridview.close();
        this.gridview = new DeveloperPlayground.GridView({collection: collection});

        if (shouldFetchAndResetCollection) {
            collection.fetch();
        }

    },
});<commit_msg>remove listener<commit_after>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.StartQueryBuilderView = Backbone.View.extend({
    el: "#developer-playground",

    template: _.template($('#playground-template').html()),

    events: {
        'change .form-control#entity': 'changeParam',
        'change .form-control#parameter': 'changeFilter',
        'click .btn#san-francisco': 'changeMapSF',
        'click .btn#new-york': 'changeMapNY',
        'click .btn#run-query-btn' : 'submit'
    },

    initialize: function () {
        this.operators = new DeveloperPlayground.Operators();
        this.stops = new DeveloperPlayground.Stops();
        this.routes = new DeveloperPlayground.Routes();
        this.render();
    },

    render: function() {
        this.$el.html(this.template());
        $(".form-control#name").hide();
        $(".btn#new-york").hide();
        $(".btn#san-francisco").hide();

        if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");
        this.mapview = new DeveloperPlayground.MapView();
        this.mapview.render();
        this.downloadview = new DeveloperPlayground.DownloadView();
        this.downloadview.render();
        return this;
    },

    changeMapSF: function(){
        if($(".btn#new-york").hasClass("selected")) $(".btn#new-york").removeClass("selected");
        $(".btn#san-francisco").addClass("selected");
        this.mapview.setMapviewSF();
    },

    changeMapNY: function(){
        if($(".btn#san-francisco").hasClass("selected")) $(".btn#san-francisco").removeClass("selected");
        $(".btn#new-york").addClass("selected");
        this.mapview.setMapviewNY();
    },

    changeParam: function() {

        $(".form-control#name").hide();
        $(".btn#new-york").hide();
        $(".btn#san-francisco").hide();

        if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");

        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var selectValues = {
            "base": {
                " ": "",
            },
            "stops": {
                " ": "",
                "map view": "",
                "operator": "",
            },
            "operators": {
                " ": "",
                "map view": "",
                "name": "",
                // "mode": "",
            },
            "routes": {
                " ": "",
                "map view": "",
                "operator": "",
                // "route number": "",
            }
        };

        $parameterSelect.empty().append(function() {
            var output = '';
            $.each(selectValues[$entitySelect.val()], function(key, value) {
                output += '<option>' + key + '</option>';
            });
            return output;
        });

        return this;
    },

    changeFilter: function() {
        var $parameterSelect = $('select.form-control#parameter');

        if($parameterSelect.val() == "name" || $parameterSelect.val() == "operator") {
            collection = this.operators;
            $(".form-control#name").show();
            $(".btn#new-york").hide();
            $(".btn#san-francisco").hide();

            if(!$("#nameMenu").hasClass("dropdown")) $("#nameMenu").addClass("dropdown");
            if ('undefined' !== typeof this.nameListView) {
                this.nameListView.close();
                this.nameListView = new DeveloperPlayground.NameListView({collection: collection});
            } else {
                this.nameListView = new DeveloperPlayground.NameListView({collection: collection});
            }
            this.operators.setQueryParameters({
                    url: API_HOST+'/api/v1/operators.json?per_page=5000'
                });
            collection.fetch();
            return this;

        } else {
            $(".form-control#name").hide();
            this.changeMapSF();
            $(".btn#new-york").show();
            $(".btn#san-francisco").show();

            if($("#nameMenu").hasClass("dropdown")) $("#nameMenu").removeClass("dropdown");

        }
    },

    submit: function() {
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        var $nameSelect = $('select.form-control#name');
        var bounds = this.mapview.getBounds();
        var identifier = $nameSelect.val();

        var shouldFetchAndResetCollection = true;

        // FOR STOP QUERIES

        if ($entitySelect.val() == "stops") {
            // for search by map view
            if($parameterSelect.val() == "map view") {
            collection = this.stops;
            this.stops.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            // for search by operator name
            } else if($parameterSelect.val() == "operator") {
                collection = this.stops;
                this.stops.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?servedBy='+identifier+'&per_page=5000',
                });
            }

        // FOR OPERATOR QUERIES

        } else if ($entitySelect.val() == "operators") {

            if($parameterSelect.val() == "map view") {
                collection = this.operators;
                this.operators.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            } else if($parameterSelect.val() == "name") {
                this.operators.hideAll();
                this.operators.get(identifier).set({ display: true });
                shouldFetchAndResetCollection = false;
            } else {
                alert("Please select either map view or name.");
            }

        //  FOR ROUTE QUERIES

        } else if ($entitySelect.val() == "routes") {
            if($parameterSelect.val() == "map view") {
                collection = this.routes;
                this.routes.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?bbox='+bounds+'&per_page=5000'
                });
            } else if($parameterSelect.val() == "operator") {
                collection = this.routes;
                this.routes.setQueryParameters({
                    url: API_HOST+'/api/v1/'+$entitySelect.val()+'.json?operatedBy='+identifier+'&per_page=5000',
                });
            } else if($parameterSelect.val() == "route number") {
                collection = this.routes;
                alert("routes by route number not yet functional");
            }
        } else {
            alert("Please select a parameter.");
        }

        if (shouldFetchAndResetCollection) {
            collection.reset();
        }

        $("#download-bar").show();
        this.mapview.markerclustergroup.clearLayers();
        this.mapview.clearCollection();
        this.mapview.setCollection({collection: collection});
        this.mapview.initialize({collection: collection});
        this.downloadview.setCollection({collection: collection});

        if ('undefined' !== typeof this.gridview) this.gridview.close();
        this.gridview = new DeveloperPlayground.GridView({collection: collection});

        if (shouldFetchAndResetCollection) {
            collection.fetch();
        }

        ga('send', 'event', 'button', 'click', 'run-query-btn');

        // $('#run-query-btn').on('click', function() {
        //     ga('send', 'event', 'button', 'click', 'run-query-btn');
        // });

    },
});<|endoftext|>


<commit_before>// Tests for the javascript API.
// IMPORTANT: These tests are not isolated because we rely on an external
// tornado server which has state. To have them isolated, we would have to
// start and stop the server from javascript at every test, something that
// is rather hard to achieve from the browser.
define([
    "jsapi/v1/resources"
], function (resources) {
    "use strict";

    QUnit.module("Resources");

    QUnit.test("items", function (assert) {
        var done = assert.async();
        resources.Student.items().done(function(item_ids) {
            assert.equal(item_ids.length, 0);
            done();
        });
    });

    QUnit.test("create", function (assert) {
        var done = assert.async();
        resources.Student.create(
            {name: "Student", surname: "McStudentface"}
        ).done(function(id) {
            assert.equal(id, "0");
            done();
        });
    });

    QUnit.test("items after create", function (assert) {
        var done = assert.async();
        resources.Student.items().done(function(item_ids) {
            assert.equal(item_ids.length, 1);
            assert.equal(item_ids[0], "0");
            done();
        });
    });

    QUnit.test("retrieve", function (assert) {
        var done = assert.async();
        resources.Student.retrieve("0").done(function(student) {
            assert.equal(student.name, "Student");
            assert.equal(student.surname, "McStudentface");
            done();
        });
    });

    QUnit.test("update", function (assert) {
        var done = assert.async();
        resources.Student.update("0", {name: "Whatever", surname: "McWhateverface"})
            .done(function() {
                resources.Student.retrieve("0").done(
                    function(student) {
                        assert.equal(student.name, "Whatever");
                        assert.equal(student.surname, "McWhateverface");
                        done();
                    }
                );
        });
    });

    QUnit.test("update unexistent", function (assert) {
        var done = assert.async();
        resources.Student.update("1", {name: "Whatever", surname: "McWhateverface"})
            .fail(function(error) {
                assert.equal(error.code, 404);
                done();
            });
    });

    QUnit.test("retrieve unexistent", function (assert) {
        var done = assert.async();
        resources.Student.retrieve("1").fail(function(error) {
            assert.equal(error.code, 404);
            done();
        });
    });

    QUnit.test("delete", function (assert) {
        var done = assert.async();
        resources.Student.delete("0")
            .done(function() {
                resources.Student.retrieve("0")
                    .fail(function (error) {
                        assert.equal(error.code, 404);
                        done();
                    });
            });
    });

    QUnit.test("delete unexistent", function (assert) {
        var done = assert.async();
        resources.Student.delete("0")
            .fail(function (error) {
                assert.equal(error.code, 404);
                done();
            });
    });
});
<commit_msg>Fixed js tests<commit_after>// Tests for the javascript API.
// IMPORTANT: These tests are not isolated because we rely on an external
// tornado server which has state. To have them isolated, we would have to
// start and stop the server from javascript at every test, something that
// is rather hard to achieve from the browser.
define([
    "jsapi/v1/resources"
], function (resources) {
    "use strict";

    QUnit.module("Resources");

    QUnit.test("items", function (assert) {
        var done = assert.async();
        resources.Student.items().done(function(item_ids) {
            assert.equal(item_ids.length, 0);
            done();
        });
    });

    QUnit.test("create", function (assert) {
        var done = assert.async();
        resources.Student.create(
            {name: "john wick", age: 19}
        ).done(function(id) {
            assert.equal(id, "0");
            done();
        });
    });

    QUnit.test("items after create", function (assert) {
        var done = assert.async();
        resources.Student.items().done(function(item_ids) {
            assert.equal(item_ids.length, 1);
            assert.equal(item_ids[0], "0");
            done();
        });
    });

    QUnit.test("retrieve", function (assert) {
        var done = assert.async();
        resources.Student.retrieve("0").done(function(student) {
            assert.equal(student.name, "john wick");
            assert.equal(student.age, 19);
            done();
        });
    });

    QUnit.test("update", function (assert) {
        var done = assert.async();
        resources.Student.update("0", {name: "Whatever", age: 24})
            .done(function() {
                resources.Student.retrieve("0").done(
                    function(student) {
                        assert.equal(student.name, "Whatever");
                        assert.equal(student.age, 24);
                        done();
                    }
                );
        });
    });

    QUnit.test("update unexistent", function (assert) {
        var done = assert.async();
        resources.Student.update("1", {name: "Whatever", age: 19})
            .fail(function(error) {
                assert.equal(error.code, 404);
                done();
            });
    });

    QUnit.test("retrieve unexistent", function (assert) {
        var done = assert.async();
        resources.Student.retrieve("1").fail(function(error) {
            assert.equal(error.code, 404);
            done();
        });
    });

    QUnit.test("delete", function (assert) {
        var done = assert.async();
        resources.Student.delete("0")
            .done(function() {
                resources.Student.retrieve("0")
                    .fail(function (error) {
                        assert.equal(error.code, 404);
                        done();
                    });
            });
    });

    QUnit.test("delete unexistent", function (assert) {
        var done = assert.async();
        resources.Student.delete("0")
            .fail(function (error) {
                assert.equal(error.code, 404);
                done();
            });
    });
});
<|endoftext|>


<commit_before>var TradingTimesWS = (function() {
    "use strict";

    var $date      = $('#trading-date');
    var $container = $('#trading-times');
    var columns    = ['Asset', 'Opens', 'Closes', 'Settles', 'UpcomingEvents'];
    var activeSymbols,
        tradingTimes;

    var init = function() {
        showLoadingImage($container);
        BinarySocket.send({"active_symbols": "brief"});
        sendRequest('today');

        $date.val(moment.utc(new Date()).format('YYYY-MM-DD'));
        $date.datepicker({minDate: 0, maxDate: '+1y', dateFormat: 'yy-mm-dd', autoSize: true});
        $date.change(function() {
            $container.empty();
            showLoadingImage($container);
            sendRequest();
        });
    };

    var sendRequest = function(date) {
        tradingTimes = null;
        BinarySocket.send({"trading_times": (date ? date : $date.val())});
    };

    var getActiveSymbols = function(response) {
        activeSymbols = response.active_symbols;
        if(tradingTimes) {
            populateTable();
        }
    };

    var getTradingTimes = function(response) {
        tradingTimes = response.trading_times;
        if(activeSymbols) {
            populateTable();
        }
    };

    var populateTable = function() {
        $('#errorMsg').addClass('hidden');

        var isJapan = page.language().toLowerCase() === 'ja';

        var markets = tradingTimes.markets;

        var $ul = $('
', {class: isJapan ? 'hidden' : ''});
        var $contents = $('
');

        for(var m = 0; m < markets.length; m++) {
            var tabID = 'tradingtimes-' + markets[m].name.toLowerCase();

            // tabs
            if(!isJapan) {
                $ul.append($('
').append($('', {href: '#' + tabID, text: markets[m].name, id: 'outline'})));
            }

            // contents
            var $market = $('
', {id: tabID});
            $market.append(createMarketTables(markets[m], isJapan));
            $contents.append($market);
        }

        $container
            .empty()
            .append($ul)
            .append($('
', {class: 'grd-row-padding'}))
            .append($contents.children());

        $container.tabs('destroy').tabs();
    };

    var createMarketTables = function(market, isJapan) {
        var $marketTables = $('
');

        // submarkets of this market
        var submarkets = market.submarkets;
        for(var s = 0; s < submarkets.length; s++) {
            // just show "Major Pairs" when the language is JA
            if(isJapan) {
                var symbolInfo = symbolSearch(submarkets[s].name);
                if(symbolInfo.length > 0 && symbolInfo[0].submarket !== 'major_pairs') {
                    continue;
                }
            }

            // submarket table
            var $submarketTable = createEmptyTable(market.name + '-' + s);

            // submarket name
            $submarketTable.find('thead').prepend(createSubmarketHeader(submarkets[s].name));

            // symbols of this submarket
            var symbols = submarkets[s].symbols;
            for(var sy = 0; sy < symbols.length; sy++) {
                $submarketTable.find('tbody').append(createSubmarketTableRow(market.name, submarkets[s].name, symbols[sy]));
            }

            $marketTables.append($submarketTable);
        }

        return $marketTables;
    };

    var createSubmarketHeader = function(submarketName) {
        return $('
', {class: 'flex-tr'})
            .append($('', {class: 'flex-tr-child submarket-name', colspan: columns.length, text: submarketName}));
    };

    var createSubmarketTableRow = function(marketName, submarketName, symbol) {
        var $tableRow = Table.createFlexTableRow(
            [
                symbol.name,
                '', // Opens
                '', // Closes
                symbol.times.settlement,
                ''  // UpcomingEvents
            ],
            columns,
            "data"
        );

        $tableRow.children('.opens').html(symbol.times.open.join('
'));
        $tableRow.children('.closes').html(symbol.times.close.join('
'));
        $tableRow.children('.upcomingevents').html(createEventsText(symbol.events));

        return $tableRow;
    };

    var symbolSearch = function(submarketname) {
        return activeSymbols.filter(function(sy) {
            return sy.submarket_display_name === submarketname;
        });
    };

    var createEventsText = function(events) {
        var result = '';
        for(var i = 0; i < events.length; i++) {
            result += (i > 0 ? '
' : '') + events[i].descrip + ': ' + events[i].dates;
        }
        return result;
    };

    var createEmptyTable = function(tableID) {
        var header = [
            Content.localize().textAsset,
            Content.localize().textOpens,
            Content.localize().textCloses,
            Content.localize().textSettles,
            Content.localize().textUpcomingEvents
        ];

        var metadata = {
            id: tableID,
            cols: columns
        };

        return Table.createFlexTable([], metadata, header);
    };

    return {
        init: init,
        getTradingTimes : getTradingTimes,
        getActiveSymbols: getActiveSymbols
    };
}());

pjax_config_page("trading_timesws", function() {
    return {
        onLoad: function() {
            BinarySocket.init({
                onmessage: function(msg) {
                    var response = JSON.parse(msg.data);
                    if (response) {
                        if (response.msg_type === "trading_times") {
                            TradingTimesWS.getTradingTimes(response);
                        }
                        else if (response.msg_type === "active_symbols") {
                            TradingTimesWS.getActiveSymbols(response);
                        }
                    }
                }
            });

            Content.populate();
            TradingTimesWS.init();
        }
    };
});
<commit_msg>fix trading times ws on pjax menu change<commit_after>var TradingTimesWS = (function() {
    "use strict";

    var $date,
        $container;

    var columns,
        activeSymbols,
        tradingTimes;

    var init = function() {
        $date      = $('#trading-date');
        $container = $('#trading-times');
        columns    = ['Asset', 'Opens', 'Closes', 'Settles', 'UpcomingEvents'];
        showLoadingImage($container);
        BinarySocket.send({"active_symbols": "brief"});
        sendRequest('today');

        $date.val(moment.utc(new Date()).format('YYYY-MM-DD'));
        $date.datepicker({minDate: 0, maxDate: '+1y', dateFormat: 'yy-mm-dd', autoSize: true});
        $date.change(function() {
            $container.empty();
            showLoadingImage($container);
            sendRequest();
        });
    };

    var sendRequest = function(date) {
        tradingTimes = null;
        BinarySocket.send({"trading_times": (date ? date : $date.val())});
    };

    var getActiveSymbols = function(response) {
        activeSymbols = response.active_symbols;
        if(tradingTimes) {
            populateTable();
        }
    };

    var getTradingTimes = function(response) {
        tradingTimes = response.trading_times;
        if(activeSymbols) {
            populateTable();
        }
    };

    var populateTable = function() {
        $('#errorMsg').addClass('hidden');

        var isJapan = page.language().toLowerCase() === 'ja';

        var markets = tradingTimes.markets;

        var $ul = $('
', {class: isJapan ? 'hidden' : ''});
        var $contents = $('
');

        for(var m = 0; m < markets.length; m++) {
            var tabID = 'tradingtimes-' + markets[m].name.toLowerCase();

            // tabs
            if(!isJapan) {
                $ul.append($('
').append($('', {href: '#' + tabID, text: markets[m].name, id: 'outline'})));
            }

            // contents
            var $market = $('
', {id: tabID});
            $market.append(createMarketTables(markets[m], isJapan));
            $contents.append($market);
        }

        $container
            .empty()
            .append($ul)
            .append($('
', {class: 'grd-row-padding'}))
            .append($contents.children());

        $container.tabs('destroy').tabs();
    };

    var createMarketTables = function(market, isJapan) {
        var $marketTables = $('
');

        // submarkets of this market
        var submarkets = market.submarkets;
        for(var s = 0; s < submarkets.length; s++) {
            // just show "Major Pairs" when the language is JA
            if(isJapan) {
                var symbolInfo = symbolSearch(submarkets[s].name);
                if(symbolInfo.length > 0 && symbolInfo[0].submarket !== 'major_pairs') {
                    continue;
                }
            }

            // submarket table
            var $submarketTable = createEmptyTable(market.name + '-' + s);

            // submarket name
            $submarketTable.find('thead').prepend(createSubmarketHeader(submarkets[s].name));

            // symbols of this submarket
            var symbols = submarkets[s].symbols;
            for(var sy = 0; sy < symbols.length; sy++) {
                $submarketTable.find('tbody').append(createSubmarketTableRow(market.name, submarkets[s].name, symbols[sy]));
            }

            $marketTables.append($submarketTable);
        }

        return $marketTables;
    };

    var createSubmarketHeader = function(submarketName) {
        return $('
', {class: 'flex-tr'})
            .append($('', {class: 'flex-tr-child submarket-name', colspan: columns.length, text: submarketName}));
    };

    var createSubmarketTableRow = function(marketName, submarketName, symbol) {
        var $tableRow = Table.createFlexTableRow(
            [
                symbol.name,
                '', // Opens
                '', // Closes
                symbol.times.settlement,
                ''  // UpcomingEvents
            ],
            columns,
            "data"
        );

        $tableRow.children('.opens').html(symbol.times.open.join('
'));
        $tableRow.children('.closes').html(symbol.times.close.join('
'));
        $tableRow.children('.upcomingevents').html(createEventsText(symbol.events));

        return $tableRow;
    };

    var symbolSearch = function(submarketname) {
        return activeSymbols.filter(function(sy) {
            return sy.submarket_display_name === submarketname;
        });
    };

    var createEventsText = function(events) {
        var result = '';
        for(var i = 0; i < events.length; i++) {
            result += (i > 0 ? '
' : '') + events[i].descrip + ': ' + events[i].dates;
        }
        return result;
    };

    var createEmptyTable = function(tableID) {
        var header = [
            Content.localize().textAsset,
            Content.localize().textOpens,
            Content.localize().textCloses,
            Content.localize().textSettles,
            Content.localize().textUpcomingEvents
        ];

        var metadata = {
            id: tableID,
            cols: columns
        };

        return Table.createFlexTable([], metadata, header);
    };

    return {
        init: init,
        getTradingTimes : getTradingTimes,
        getActiveSymbols: getActiveSymbols
    };
}());

pjax_config_page("trading_timesws", function() {
    return {
        onLoad: function() {
            BinarySocket.init({
                onmessage: function(msg) {
                    var response = JSON.parse(msg.data);
                    if (response) {
                        if (response.msg_type === "trading_times") {
                            TradingTimesWS.getTradingTimes(response);
                        }
                        else if (response.msg_type === "active_symbols") {
                            TradingTimesWS.getActiveSymbols(response);
                        }
                    }
                }
            });

            Content.populate();
            TradingTimesWS.init();
        }
    };
});
<|endoftext|>


<commit_before>import Vue from 'vue'
import '../../dist/clair.css'
import Clair from '../../'

import Header from '../layouts/includes/header.vue'
import Footer from '../layouts/includes/footer.vue'

import RunOnline from '../assets/vue/run-online.vue'

Vue.use(Clair)
Vue.component('c-header', Header)
Vue.component('c-footer', Footer)
Vue.component('c-run-online', RunOnline)

<commit_msg>doc(style): remove extra line<commit_after>import Vue from 'vue'
import '../../dist/clair.css'
import Clair from '../../'

import Header from '../layouts/includes/header.vue'
import Footer from '../layouts/includes/footer.vue'

import RunOnline from '../assets/vue/run-online.vue'

Vue.use(Clair)
Vue.component('c-header', Header)
Vue.component('c-footer', Footer)
Vue.component('c-run-online', RunOnline)
<|endoftext|>


<commit_before>angular.module('app').
config(['$stateProvider', function ($stateProvider) {
	$stateProvider
			.state('accountSession', {
				abstract: true,
				data: {
					permissions: {
						only: ['SUPER']
					}
				},
				url: '/accountSession',
				templateUrl: 'view/common/parent.html'
			})
			.state('accountSession.list', {
				url: "/",
				templateUrl: 'view/common/grid/grid.html',
				controller: 'accountSessionCtrl'
			});
}]).
factory('accountSessionService', ['$resource', function ($resource) {
	return $resource(apiBaseUrl + '/account/session', {}, serviceCommonConfig);
}]).
controller('accountSessionCtrl', ['$scope', 'accountSessionService', 'uiGridConstants', 'gridHelper', 'dateTimePickerFilterTemplate', '$state', 'principal', function ($scope, service, uiGridConstants, gridHelper, filterTemplate, $state, principal) {
	$scope.filterModel = {};

	var paginationOptions = {
		pageNumber: 1,
		pageSize: 25,
		sort: ["loginAt,DESC"]
	};

	gridHelper($scope, service, paginationOptions, {
		columnDefs: [
			{
				field: 'id',
			},
			{field: 'accountUsername', enableFiltering: true},
			{
				field: 'loginAt',
				sort: {direction: uiGridConstants.DESC, priority: 0},
				filterHeaderTemplate: filterTemplate(),
				filters: [{placeholder: 'from'}, {placeholder: 'to'}],
				filterTermMapper: function(value) {
					return moment(value).format('YYYY-MM-DD[T]HH:mm:ss.SSSZ');
				}
			},
			{field: 'loginAs', enableFiltering: false},
			{field: 'sessionId'},
			//todo Скрыть по дефолту
			{field: 'details'},
			{
				field: 'logoutAt',
				filterHeaderTemplate: filterTemplate(),
				filters: [{placeholder: 'from'}, {placeholder: 'to'}],
				filterTermMapper: function(value) {
					return moment(value).format('YYYY-MM-DD[T]HH:mm:ss.SSSZ');
				}
			},
			{field: 'logoutAs', enableFiltering: false},
			{
				field: 'duration',
				enableFiltering: false,
				cellFilter: 'secondToPeriod'
			},
		],
	});

	$scope.loadPage();
}])
;<commit_msg>Сеансы работы пользователей (клиент): скрыто поле с расширенными данными<commit_after>angular.module('app').
config(['$stateProvider', function ($stateProvider) {
	$stateProvider
			.state('accountSession', {
				abstract: true,
				data: {
					permissions: {
						only: ['SUPER']
					}
				},
				url: '/accountSession',
				templateUrl: 'view/common/parent.html'
			})
			.state('accountSession.list', {
				url: "/",
				templateUrl: 'view/common/grid/grid.html',
				controller: 'accountSessionCtrl'
			});
}]).
factory('accountSessionService', ['$resource', function ($resource) {
	return $resource(apiBaseUrl + '/account/session', {}, serviceCommonConfig);
}]).
controller('accountSessionCtrl', ['$scope', 'accountSessionService', 'uiGridConstants', 'gridHelper', 'dateTimePickerFilterTemplate', '$state', 'principal', function ($scope, service, uiGridConstants, gridHelper, filterTemplate, $state, principal) {
	$scope.filterModel = {};

	var paginationOptions = {
		pageNumber: 1,
		pageSize: 25,
		sort: ["loginAt,DESC"]
	};

	gridHelper($scope, service, paginationOptions, {
		columnDefs: [
			{
				field: 'id',
			},
			{field: 'accountUsername', enableFiltering: true},
			{
				field: 'loginAt',
				sort: {direction: uiGridConstants.DESC, priority: 0},
				filterHeaderTemplate: filterTemplate(),
				filters: [{placeholder: 'from'}, {placeholder: 'to'}],
				filterTermMapper: function(value) {
					return moment(value).format('YYYY-MM-DD[T]HH:mm:ss.SSSZ');
				}
			},
			{field: 'loginAs', enableFiltering: false},
			{field: 'sessionId'},
			{field: 'details', visible: false},
			{
				field: 'logoutAt',
				filterHeaderTemplate: filterTemplate(),
				filters: [{placeholder: 'from'}, {placeholder: 'to'}],
				filterTermMapper: function(value) {
					return moment(value).format('YYYY-MM-DD[T]HH:mm:ss.SSSZ');
				}
			},
			{field: 'logoutAs', enableFiltering: false},
			{
				field: 'duration',
				enableFiltering: false,
				cellFilter: 'secondToPeriod'
			},
		],
	});

	$scope.loadPage();
}])
;<|endoftext|>


<commit_before>var Promise = require('es6-promise').Promise;
var deferred =  require('../src/lib/deferred');
var path = require('path');
var spawn = require('child_process').spawn;
var fs = require('fs');

/**
 * Provides two tasks for setup and tear down of integration tests. For instance
 * processes like wspr can be spawned & then killed in setup and teardown
 * @param {object} grunt the Grunt module
 */
module.exports = function(grunt) {
  // List of processes we have spawned so we can kill them on teardown
  var runningChildProcesses = [];
  var cleaningUp;
  var addListeners = function(runningProcess, resolve, reject) {
    var stderr = '';
    if (resolve) {
      runningProcess.stderr.once('data', function() {
        resolve();
      });
    }
    runningProcess.stderr.on('data', function(d) {
      stderr += d;
      grunt.log.debug(d);
    });
    runningProcess.on('exit', function (code) {
      if (!cleaningUp) {
        reject(runningProcess.title +
          ' crashed before tests finish with code: ' + code +
          ' here is the stderr:\n' + stderr);
      }
    });
  };

  // Constants
  // Binary location of wspr and other processes to run
  var VEYRON_ROOT = process.env.VEYRON_ROOT;

  if (! VEYRON_ROOT) {
    grunt.fail.fatal('Please export $VEYRON_ROOT to proceed');
  }

  var VEYRON_BIN_DIR = path.join(VEYRON_ROOT, 'veyron/go/bin');

  var VEYRON_PROXY_BIN = path.join(VEYRON_BIN_DIR, 'proxyd');
  var MOUNTTABLE_BIN = path.join(VEYRON_BIN_DIR, 'mounttabled')
  var WSPR_BIN = path.join(VEYRON_BIN_DIR, 'wsprd')
  var IDENTITYD_BIN = path.join(VEYRON_BIN_DIR, 'identityd')
  var SAMPLE_GO_SERVICE_BIN = path.join(VEYRON_BIN_DIR, 'sampled')

  var BINARIES = [VEYRON_PROXY_BIN, MOUNTTABLE_BIN, WSPR_BIN, IDENTITYD_BIN,
   SAMPLE_GO_SERVICE_BIN];

  var WSPR_PORT = 3224; // The port for WSPR.
  var IDENTITYD_PORT = 8125; // The port for the identityd server.

  var LOGS_DIR = path.resolve('logs');
  // TODO(bprosnitz) Currently we generate a *.ERROR sym link when there is an
  // error. However this is not removed when the most recent logged version has
  // no errors so it points to stale data.

  /**
   * Starts a process that depends on the mounttable root and returns
   * a handle the process.
   * @param {string} mounttableRoot the veyron endpoint of the mounttable.
   * @param {string} bin the path to the binary.
   * @param {array} extraArgs an array of args that are binary specific. The
   * logging flags will already be set.
   * @return {Process} the process handle for the command.
   */
  var startProcessWithMounttableRoot = function(mounttableRoot, bin, name,
   extraArgs) {
    var envWithMount = {
      VEYRON_IDENTITY: process.env.IDENTITY_FILE,
      NAMESPACE_ROOT: mounttableRoot,
    };
    var args = ['-v=3', '-vv=3', '-log_dir=' + LOGS_DIR];
    args = args.concat(extraArgs);
    // Run process
    var runningProcess = spawn(bin, args, { env: envWithMount});
    runningProcess.title = name;
    runningChildProcesses.push(runningProcess);
    return runningProcess;
  };

  /**
   * Starts a process that depends on the mounttable root and returns
   * a promise that will be resolved when the process has started.
   * @param {string} mounttableRoot the veyron endpoint of the mounttable.
   * @param {string} bin the path to the binary.
   * @param {array} extraArgs an array of args that are binary specific. The
   * logging flags will already be set.
   * @return {Promise} a promise that will be resolved when the process has
   * been started.
   */
  var startProcessWithMounttableAndAddHandlers = function(mounttableRoot, bin,
   name, extraArgs) {
    var process = startProcessWithMounttableRoot(mounttableRoot, bin, name,
     extraArgs);
    var def = new deferred();
    addListeners(process, def.resolve, def.reject);
    return def.promise;
  };

  // Starts WSPR taking in the mounttable root and returns a promise that
  // will be resolved when WSPR is ready to accept requests.
  var startWSPR = function(mounttable) {
    grunt.testConfigs['WSPR_SERVER_URL'] = 'http://localhost:' +
        WSPR_PORT;
    return startProcessWithMounttableAndAddHandlers(
      mounttable, WSPR_BIN,
      'WSPR', ['-port=' + WSPR_PORT, '-vproxy=test/proxy', '-identd=test/identd']);
  };

  // Starts the Veyron Proxy taking in the mounttable root and returns
  // a promise that will be resolved when the proxy. is ready to accept requests.
  var startProxy = function(mounttable) {
    return startProcessWithMounttableAndAddHandlers(
      mounttable, VEYRON_PROXY_BIN, 'Veyron Proxy',
      ['-address=127.0.0.1:0', '-name=test/proxy']);
  };

  // Starts sampled taking in the mounttable root and returns a ppromise
  // that will resolved when sampled is up and running.
  var startSampled = function(mounttable) {
    var process =  startProcessWithMounttableRoot(
      mounttable, SAMPLE_GO_SERVICE_BIN, 'Sampled', []);
    var def = new deferred();
    addListeners(process, null, def.reject);
    // Wait until we get the sample service endpoint from the process stdout
    process.stdout.on('data', function(data) {
      var endpoint = data.toString().replace('Listening at: ', '').trim();
      if (!endpoint.match(/^@.*@$/)) {
        var errorMessage = SAMPLE_GO_SERVICE_BIN + ' did not print the ' +
          'endpoint address on stdout. Expected stdout: ' +
          'Listening at: <VeyronEndPointAddress> but got ' +
          data;

        fail(errorMessage);
      }

      // Success, set the config vars that tests rely on and return
      grunt.testConfigs['SAMPLE_VEYRON_GO_SERVICE_ENDPOINT'] = endpoint;
      def.resolve();
    });
    return def.promise;
  };

  var startMounttable = function() {
    var mounttableDef = new deferred();
    var mounttablePromise = mounttableDef.promise;

    var mounttable_process = spawn(MOUNTTABLE_BIN,
      ['-log_dir=' + LOGS_DIR, '-address=127.0.0.1:0'], {
        env: {
          VEYRON_IDENTITY: process.env.IDENTITY_FILE
        }
      });
    mounttable_process.title = 'MountTable';
    var endpointRe = /@.*@@\S*/;
    var mounttableEndpoint = '';
    mounttable_process.stderr.on('data', function(data) {
      var string = data.toString();
      if (mounttableEndpoint !== '') {
        return;
      }
      var match = string.match(endpointRe);
      if (!match) {
	console.log('Did not find a match');
        return
      }
      mounttableEndpoint = match[0];
      mounttableDef.resolve('/' + mounttableEndpoint);
    });

    runningChildProcesses.push(mounttable_process);
    addListeners(mounttable_process, null, mounttableDef.reject);
    return mounttablePromise;
  };

  var startIdentityd = function() {
    var identityd_process = spawn(IDENTITYD_BIN, ['-httpaddr=localhost:' + IDENTITYD_PORT], {
      env: {
          VEYRON_IDENTITY: process.env.IDENTITY_FILE
        }
    });
    identityd_process.title = 'Identity Server';
    runningChildProcesses.push(identityd_process);
    var identityDef = new deferred();
    addListeners(identityd_process, identityDef.resolve, identityDef.reject);
    grunt.testConfigs['IDENTITY_SERVER_URL'] = 'http://localhost:' +
        IDENTITYD_PORT + '/random/';
    return identityDef.promise;
  };
  /**
   * Setups the required environment for integration testing such as
   * running wspr and sample Veyron services written in Go that are
   * expected in the integration tests.
   */
  grunt.registerTask('subtask_setupIntegrationTestEnvironment', function() {
    // Indicate this is a async grunt task
    var done = this.async();

    // Reset state
    runningChildProcesses = [];
    cleaningUp = false;

    // Ensure binaries exist
    BINARIES.forEach(function(bin) {
      if (!fs.existsSync(bin)) {
        var errorMessage = 'Veyron binaries not found. Ensure "veyron" and ' +
        '"veyron2" are built and installed in ' + VEYRON_BIN_DIR + ' by ' +
        'running go-amd64 install\n The following binaries are needed:\n' +
        BINARIES.join('\n');
        fail(errorMessage);
      }
    });

    var basicEnv = {
      VEYRON_IDENTITY: process.env.IDENTITY_FILE
    };

    var servicePromises = [];
    var mounttablePromise = startMounttable();
    servicePromises.push(mounttablePromise);

    servicePromises.push(startIdentityd());

    servicePromises.push(mounttablePromise.then(startWSPR));

    servicePromises.push(mounttablePromise.then(startProxy));

    servicePromises.push(mounttablePromise.then(startSampled));

    Promise.all(servicePromises).then(function() {
      if (BINARIES.length != runningChildProcesses.length) {
        fail('Not all binaries were started');
        done(false);
      } else {
        done(true);
      }
    }).catch(function(err) {
      fail(err);
      done(false);
    });
  });

  // Kills any running process we started and calls done when all finish
  var cleanUp = function(done) {
    cleaningUp = true;
    var numExited = 0;
    for(var i = 0; i < runningChildProcesses.length; i++) {
      runningChildProcesses[i].kill('SIGTERM');
      // wait until all exit
      runningChildProcesses[i].on('exit', function (code) {
        numExited++;
        if (done !== undefined && numExited == runningChildProcesses.length) {
          done(true);
        }
      });
    }
  };

  // Fails the task after cleaning up
  var fail = function(message) {
    cleanUp();
    grunt.fail.fatal(message);
  };

  // Cleanup in case Grunt fails or is forced to exit
  process.on('exit', function() {
    cleanUp();
  });

  /**
   * Tears down anything setup in subtask_setupIntegrationTestEnvironment
   * such as killing wspr and other services spawned for testing
   */
  grunt.registerTask('subtask_teardownIntegrationTestEnvironment', function() {
    // Indicate this is a async grunt task
    var done = this.async();
    cleanUp(done);
  });
};
<commit_msg>sampled moved to roadmap respository<commit_after>var Promise = require('es6-promise').Promise;
var deferred =  require('../src/lib/deferred');
var path = require('path');
var spawn = require('child_process').spawn;
var fs = require('fs');

/**
 * Provides two tasks for setup and tear down of integration tests. For instance
 * processes like wspr can be spawned & then killed in setup and teardown
 * @param {object} grunt the Grunt module
 */
module.exports = function(grunt) {
  // List of processes we have spawned so we can kill them on teardown
  var runningChildProcesses = [];
  var cleaningUp;
  var addListeners = function(runningProcess, resolve, reject) {
    var stderr = '';
    if (resolve) {
      runningProcess.stderr.once('data', function() {
        resolve();
      });
    }
    runningProcess.stderr.on('data', function(d) {
      stderr += d;
      grunt.log.debug(d);
    });
    runningProcess.on('exit', function (code) {
      if (!cleaningUp) {
        reject(runningProcess.title +
          ' crashed before tests finish with code: ' + code +
          ' here is the stderr:\n' + stderr);
      }
    });
  };

  // Constants
  // Binary location of wspr and other processes to run
  var VEYRON_ROOT = process.env.VEYRON_ROOT;

  if (! VEYRON_ROOT) {
    grunt.fail.fatal('Please export $VEYRON_ROOT to proceed');
  }

  var VEYRON_BIN_DIR = path.join(VEYRON_ROOT, 'veyron/go/bin');
  var ROADMAP_BIN_DIR = path.join(VEYRON_ROOT, 'roadmap/go/bin');

  var VEYRON_PROXY_BIN = path.join(VEYRON_BIN_DIR, 'proxyd');
  var MOUNTTABLE_BIN = path.join(VEYRON_BIN_DIR, 'mounttabled')
  var WSPR_BIN = path.join(VEYRON_BIN_DIR, 'wsprd')
  var IDENTITYD_BIN = path.join(VEYRON_BIN_DIR, 'identityd')
  var SAMPLE_GO_SERVICE_BIN = path.join(ROADMAP_BIN_DIR, 'sampled')

  var BINARIES = [VEYRON_PROXY_BIN, MOUNTTABLE_BIN, WSPR_BIN, IDENTITYD_BIN,
   SAMPLE_GO_SERVICE_BIN];

  var WSPR_PORT = 3224; // The port for WSPR.
  var IDENTITYD_PORT = 8125; // The port for the identityd server.

  var LOGS_DIR = path.resolve('logs');
  // TODO(bprosnitz) Currently we generate a *.ERROR sym link when there is an
  // error. However this is not removed when the most recent logged version has
  // no errors so it points to stale data.

  /**
   * Starts a process that depends on the mounttable root and returns
   * a handle the process.
   * @param {string} mounttableRoot the veyron endpoint of the mounttable.
   * @param {string} bin the path to the binary.
   * @param {array} extraArgs an array of args that are binary specific. The
   * logging flags will already be set.
   * @return {Process} the process handle for the command.
   */
  var startProcessWithMounttableRoot = function(mounttableRoot, bin, name,
   extraArgs) {
    var envWithMount = {
      VEYRON_IDENTITY: process.env.IDENTITY_FILE,
      NAMESPACE_ROOT: mounttableRoot,
    };
    var args = ['-v=3', '-vv=3', '-log_dir=' + LOGS_DIR];
    args = args.concat(extraArgs);
    // Run process
    var runningProcess = spawn(bin, args, { env: envWithMount});
    runningProcess.title = name;
    runningChildProcesses.push(runningProcess);
    return runningProcess;
  };

  /**
   * Starts a process that depends on the mounttable root and returns
   * a promise that will be resolved when the process has started.
   * @param {string} mounttableRoot the veyron endpoint of the mounttable.
   * @param {string} bin the path to the binary.
   * @param {array} extraArgs an array of args that are binary specific. The
   * logging flags will already be set.
   * @return {Promise} a promise that will be resolved when the process has
   * been started.
   */
  var startProcessWithMounttableAndAddHandlers = function(mounttableRoot, bin,
   name, extraArgs) {
    var process = startProcessWithMounttableRoot(mounttableRoot, bin, name,
     extraArgs);
    var def = new deferred();
    addListeners(process, def.resolve, def.reject);
    return def.promise;
  };

  // Starts WSPR taking in the mounttable root and returns a promise that
  // will be resolved when WSPR is ready to accept requests.
  var startWSPR = function(mounttable) {
    grunt.testConfigs['WSPR_SERVER_URL'] = 'http://localhost:' +
        WSPR_PORT;
    return startProcessWithMounttableAndAddHandlers(
      mounttable, WSPR_BIN,
      'WSPR', ['-port=' + WSPR_PORT, '-vproxy=test/proxy', '-identd=test/identd']);
  };

  // Starts the Veyron Proxy taking in the mounttable root and returns
  // a promise that will be resolved when the proxy. is ready to accept requests.
  var startProxy = function(mounttable) {
    return startProcessWithMounttableAndAddHandlers(
      mounttable, VEYRON_PROXY_BIN, 'Veyron Proxy',
      ['-address=127.0.0.1:0', '-name=test/proxy']);
  };

  // Starts sampled taking in the mounttable root and returns a ppromise
  // that will resolved when sampled is up and running.
  var startSampled = function(mounttable) {
    var process =  startProcessWithMounttableRoot(
      mounttable, SAMPLE_GO_SERVICE_BIN, 'Sampled', []);
    var def = new deferred();
    addListeners(process, null, def.reject);
    // Wait until we get the sample service endpoint from the process stdout
    process.stdout.on('data', function(data) {
      var endpoint = data.toString().replace('Listening at: ', '').trim();
      if (!endpoint.match(/^@.*@$/)) {
        var errorMessage = SAMPLE_GO_SERVICE_BIN + ' did not print the ' +
          'endpoint address on stdout. Expected stdout: ' +
          'Listening at: <VeyronEndPointAddress> but got ' +
          data;

        fail(errorMessage);
      }

      // Success, set the config vars that tests rely on and return
      grunt.testConfigs['SAMPLE_VEYRON_GO_SERVICE_ENDPOINT'] = endpoint;
      def.resolve();
    });
    return def.promise;
  };

  var startMounttable = function() {
    var mounttableDef = new deferred();
    var mounttablePromise = mounttableDef.promise;

    var mounttable_process = spawn(MOUNTTABLE_BIN,
      ['-log_dir=' + LOGS_DIR, '-address=127.0.0.1:0'], {
        env: {
          VEYRON_IDENTITY: process.env.IDENTITY_FILE
        }
      });
    mounttable_process.title = 'MountTable';
    var endpointRe = /@.*@@\S*/;
    var mounttableEndpoint = '';
    mounttable_process.stderr.on('data', function(data) {
      var string = data.toString();
      if (mounttableEndpoint !== '') {
        return;
      }
      var match = string.match(endpointRe);
      if (!match) {
	console.log('Did not find a match');
        return
      }
      mounttableEndpoint = match[0];
      mounttableDef.resolve('/' + mounttableEndpoint);
    });

    runningChildProcesses.push(mounttable_process);
    addListeners(mounttable_process, null, mounttableDef.reject);
    return mounttablePromise;
  };

  var startIdentityd = function() {
    var identityd_process = spawn(IDENTITYD_BIN, ['-httpaddr=localhost:' + IDENTITYD_PORT], {
      env: {
          VEYRON_IDENTITY: process.env.IDENTITY_FILE
        }
    });
    identityd_process.title = 'Identity Server';
    runningChildProcesses.push(identityd_process);
    var identityDef = new deferred();
    addListeners(identityd_process, identityDef.resolve, identityDef.reject);
    grunt.testConfigs['IDENTITY_SERVER_URL'] = 'http://localhost:' +
        IDENTITYD_PORT + '/random/';
    return identityDef.promise;
  };
  /**
   * Setups the required environment for integration testing such as
   * running wspr and sample Veyron services written in Go that are
   * expected in the integration tests.
   */
  grunt.registerTask('subtask_setupIntegrationTestEnvironment', function() {
    // Indicate this is a async grunt task
    var done = this.async();

    // Reset state
    runningChildProcesses = [];
    cleaningUp = false;

    // Ensure binaries exist
    BINARIES.forEach(function(bin) {
      if (!fs.existsSync(bin)) {
        var errorMessage = 'Veyron binaries not found. Ensure "veyron" and ' +
        '"veyron2" are built and installed in ' + VEYRON_BIN_DIR + ' by ' +
        'running go-amd64 install\n The following binaries are needed:\n' +
        BINARIES.join('\n');
        fail(errorMessage);
      }
    });

    var basicEnv = {
      VEYRON_IDENTITY: process.env.IDENTITY_FILE
    };

    var servicePromises = [];
    var mounttablePromise = startMounttable();
    servicePromises.push(mounttablePromise);

    servicePromises.push(startIdentityd());

    servicePromises.push(mounttablePromise.then(startWSPR));

    servicePromises.push(mounttablePromise.then(startProxy));

    servicePromises.push(mounttablePromise.then(startSampled));

    Promise.all(servicePromises).then(function() {
      if (BINARIES.length != runningChildProcesses.length) {
        fail('Not all binaries were started');
        done(false);
      } else {
        done(true);
      }
    }).catch(function(err) {
      fail(err);
      done(false);
    });
  });

  // Kills any running process we started and calls done when all finish
  var cleanUp = function(done) {
    cleaningUp = true;
    var numExited = 0;
    for(var i = 0; i < runningChildProcesses.length; i++) {
      runningChildProcesses[i].kill('SIGTERM');
      // wait until all exit
      runningChildProcesses[i].on('exit', function (code) {
        numExited++;
        if (done !== undefined && numExited == runningChildProcesses.length) {
          done(true);
        }
      });
    }
  };

  // Fails the task after cleaning up
  var fail = function(message) {
    cleanUp();
    grunt.fail.fatal(message);
  };

  // Cleanup in case Grunt fails or is forced to exit
  process.on('exit', function() {
    cleanUp();
  });

  /**
   * Tears down anything setup in subtask_setupIntegrationTestEnvironment
   * such as killing wspr and other services spawned for testing
   */
  grunt.registerTask('subtask_teardownIntegrationTestEnvironment', function() {
    // Indicate this is a async grunt task
    var done = this.async();
    cleanUp(done);
  });
};
<|endoftext|>


<commit_before>// The graph used for the visualization. added to own file
// to separate code for visualizing and keeping track of graph

var nodes = [];
var edges = [];
var graph;

var color = d3.scale.linear()
    .domain([10000,0,-400])
    .range(colorbrewer.RdYlBu[3]);
    //.range(["yellow", "white", "blue"]);

function Graph(cy){
    this.addNode = function(n){

        if(typeof findNode(n.id) != 'undefined') {
            return
        }

        n.graphics.name = n.graphics.name.split(" ")
        if(n.name === "\"bg\"") {
            console.log(n.graphics.name[0])
            var a = n.graphics.name[0].split("/")
            var b = a[a.length-1]
            var url = "http://localhost:8080/public/pathways/"+b
            n.graphics.bgimage = url
            n.graphics.bgcolor = "#fff"
            n.graphics.name = ""
        }
        else{
            n.graphics.bgimage = "";
        }

//        n.background-image = "http://www.genome.jp/kegg/pathway/hsa/hsa04915.png"
        /*
        // Fetch coloring if node is a gene
        if(n.graphics.shape == "rectangle"){
            // gene name but strip away any colon
            gene = n.name
            id = JSON.parse(n.name)
            ids = JSON.parse(n.name).split(" ")

            // If more than gene is present in the node. Fetch all of them
            // and do some clever stuff

            avg = AvgDiff(ids[0])

            if(avg === "0") {
                n.graphics.bgcolor = "#ffffff"
            } else  {
                n.graphics.bgcolor = color(avg)
            }
        }

        */

        n.graphics.name = n.graphics.name.toString().replace(/,/g, " ")

        n.graphics.valign = "center"
        if(n.graphics.name.substr(0,2) == "C0"){
            n.graphics.valign = "bottom"
        }

        var no = {
            group: 'nodes',
            data: {
                id: ''+ n.id,
                name: JSON.parse(n.name),
                graphics: n.graphics,
                //background-image: "test.png",
            },
            position: {
                x: n.graphics.x,
                y: n.graphics.y
            },
            //grabbable: false,
            locked: true,
        };
        nodes.push(no);
        cy.add(no);

    };

    this.addEdge = function(e){
        var s = findNode(e.source);
        var t = findNode(e.target);

        if(typeof s == 'undefined' || typeof t == 'undefined'){
            return
        }

        var ed = {
            group: "edges",
            data: {
                source: ''+e.source,
                target: ''+e.target,
            },
        };

        edges.push(ed);
        //cy.add(ed);

    }

    var findNode = function (id) {
        for (var i in nodes) {
            if (nodes[i]["data"]["id"] === ''+id) {
                return nodes[i];
            }
        };
    };

    var update = function() {
        //cy.layout();
    }
}

<commit_msg>no more numbers<commit_after>// The graph used for the visualization. added to own file
// to separate code for visualizing and keeping track of graph

var nodes = [];
var edges = [];
var graph;

var color = d3.scale.linear()
    .domain([colmax,0,colmin])
    .range(colorbrewer.RdYlBu[3]);
    //.range(["yellow", "white", "blue"]);

function Graph(cy){
    this.addNode = function(n){

        if(typeof findNode(n.id) != 'undefined') {
            return
        }

        n.graphics.name = n.graphics.name.split(" ")
        if(n.name === "\"bg\"") {
            console.log(n.graphics.name[0])
            var a = n.graphics.name[0].split("/")
            var b = a[a.length-1]
            var url = "http://localhost:8080/public/pathways/"+b
            n.graphics.bgimage = url
            n.graphics.bgcolor = "#fff"
            n.graphics.name = ""
        }
        else{
            n.graphics.bgimage = "";
        }

//        n.background-image = "http://www.genome.jp/kegg/pathway/hsa/hsa04915.png"
        /*
        // Fetch coloring if node is a gene
        if(n.graphics.shape == "rectangle"){
            // gene name but strip away any colon
            gene = n.name
            id = JSON.parse(n.name)
            ids = JSON.parse(n.name).split(" ")

            // If more than gene is present in the node. Fetch all of them
            // and do some clever stuff

            avg = AvgDiff(ids[0])

            if(avg === "0") {
                n.graphics.bgcolor = "#ffffff"
            } else  {
                n.graphics.bgcolor = color(avg)
            }
        }

        */

        n.graphics.name = n.graphics.name.toString().replace(/,/g, " ")

        n.graphics.valign = "center"
        if(n.graphics.name.substr(0,2) == "C0"){
            n.graphics.valign = "bottom"
        }

        var no = {
            group: 'nodes',
            data: {
                id: ''+ n.id,
                name: JSON.parse(n.name),
                graphics: n.graphics,
                //background-image: "test.png",
            },
            position: {
                x: n.graphics.x,
                y: n.graphics.y
            },
            //grabbable: false,
            locked: true,
        };
        nodes.push(no);
        cy.add(no);

    };

    this.addEdge = function(e){
        var s = findNode(e.source);
        var t = findNode(e.target);

        if(typeof s == 'undefined' || typeof t == 'undefined'){
            return
        }

        var ed = {
            group: "edges",
            data: {
                source: ''+e.source,
                target: ''+e.target,
            },
        };

        edges.push(ed);
        //cy.add(ed);

    }

    var findNode = function (id) {
        for (var i in nodes) {
            if (nodes[i]["data"]["id"] === ''+id) {
                return nodes[i];
            }
        };
    };

    var update = function() {
        //cy.layout();
    }
}

<|endoftext|>


<commit_before><commit_msg>update: example angular parser<commit_after>const fs = require('fs')
      path = require('path'),
      Templatefy = require('../..');

Templatefy.parse({
    angular: {
        module: {
            name: 'testName'
        }
    },
}'./template-element.html', './template-element.js');
<|endoftext|>


<commit_before>/* @flow */

import React, { Component } from 'react';

type Hairs = {
  length: number,
}

type Fur = {
  color: string,
  density: number,
  hairs: Hairs,
}

type Props = {
  isDangerous: boolean,
  age?: number,
  description?: string,
  fur?: Fur,
  teeth?: Array<number>,
  teethOfTeeth?: Array<Array<number>>,
  toe?: number | string,
}

type DefaultProps = {
  isDangerous: boolean,
}

export default class Ghidorah extends Component<DefaultProps, Props, void> {

  static defaultProps: DefaultProps = {
    isDangerous: false,
  };

  props: Props;

  render() {
    return (

{ this.props.isDangerous ? 'Dangerous' : 'Not Dangerous'}

description: { this.props.description }

Age: { this.props.age }

        {(this.props.fur) ? (

Fur: Density: { this.props.fur.density }

        ) : null}

array: { this.props.teeth }

array of arrays: { this.props.teethOfTeeth }

toe: { this.props.toe }

    );
  }
}
<commit_msg>simplify-flow-example<commit_after>/* @flow */

import React, { Component } from 'react';

type Hairs = {
  length: number,
}

type Fur = {
  color: string,
  density: number,
  hairs: Hairs,
}

type Props = {
  isDangerous: boolean,
  age?: number,
  description?: string,
  fur?: Fur,
  teeth?: Array<number>,
  teethOfTeeth?: Array<Array<number>>,
  toe?: number | string,
}

type DefaultProps = {
  isDangerous: boolean,
}

export default class Ghidorah extends Component {

  static defaultProps: DefaultProps = {
    isDangerous: false,
  };

  props: Props;

  render() {
    return (

{ this.props.isDangerous ? 'Dangerous' : 'Not Dangerous'}

description: { this.props.description }

Age: { this.props.age }

        {(this.props.fur) ? (

Fur: Density: { this.props.fur.density }

        ) : null}

array: { this.props.teeth }

array of arrays: { this.props.teethOfTeeth }

toe: { this.props.toe }

    );
  }
}
<|endoftext|>


<commit_before>const path = require('path');
module.exports = {
	module: {
		rules: [
			{
				test: /\.scss$/,
				loaders: ["style-loader", "css-loader", "sass-loader"],
				include: path.resolve(__dirname, '../')
			},
			{
				test: /\.css/,
				loaders: ["style-loader", "css-loader"],
				include: path.resolve(__dirname, '../')
			},
			{
				enforce: 'pre',
				test: /\.js$/,
				loader: "source-map-loader",
				exclude: [
					/node_modules\//
				]
			},
			{
				test: /\.tsx?$/,
				loader: 'awesome-typescript-loader',
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf|svg)$/,
				loader: "file-loader"
			}
		]
	},
	resolve: {
		extensions: [".tsx", ".ts", ".js"]
	}
};
<commit_msg>storybook should use typescript loader<commit_after>const path = require('path');
module.exports = {
	module: {
		rules: [
			{
				test: /\.scss$/,
				loaders: ["style-loader", "css-loader", "sass-loader"],
				include: path.resolve(__dirname, '../')
			},
			{
				test: /\.css/,
				loaders: ["style-loader", "css-loader"],
				include: path.resolve(__dirname, '../')
			},
			{
				enforce: 'pre',
				test: /\.js$/,
				loader: "source-map-loader",
				exclude: [
					/node_modules\//
				]
			},
			{
				test: /\.tsx?$/,
				loader: 'ts-loader',
			},
			{
				test: /\.(woff|woff2|eot|ttf|otf|svg)$/,
				loader: "file-loader"
			}
		]
	},
	resolve: {
		extensions: [".tsx", ".ts", ".js"]
	}
};
<|endoftext|>