<commit_before>(function($) {

  var app = $.sammy(function() {
    this.element_selector = '#content';
    this.use(Sammy.Template);

    this.before(function() {
    });

    this.get('#/map', function(context) {
      context.partial('cartmap.template', {id: 1}, function(rendered) {
        context.$element().html(rendered);
        var latlng = new google.maps.LatLng(45.597, -122.644);

        var myOptions = {
          zoom: 12,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
      });
    });

    this.get('#/carts', function(context) {
      context.partial('carts.template', {id: 1}, function(rendered) {
          context.$element().html(rendered);
          $('#cartcount').html('loading cart data ');
          $.couch.app(function(app) {
            app.db.view('webapp/cart', {success: function(cart_results) {
                                          $('#cartcount').html(cart_results.total_rows+" food carts listed.");
                                          $.each(cart_results.rows, function(index,element) {
                                            var carts_element = $('#carts ul');
                                            context.partial('cart.template', {cart: element}, function(rendered) {
                                               carts_element.append(rendered);
                                            });
                                          });
                                       }});
          }, {db : "food_carts", design : "webapp"});
      });
    });

    this.get('#/carts/new', function(context) {
      $.couch.app(function(app) {
        app.db.saveDoc({}, {success: function(res) {
          window.location = "#/carts/edit/"+res.id;
        }});
      }, {db : "food_carts", design : "webapp"});
    });

    this.get('#/carts/edit/:id', function(context) {
      var id = this.params['id'];
      $.couch.app(function(app) {
        app.db.openDoc(id, {success: function(cart_doc) {
          context.partial('carts.edit.template', {cart: cart_doc}, function(rendered) {
            context.$element().html(rendered);
            });
        }});
      }, {db : "food_carts", design : "webapp"});
    });

    $(function() {
      app.run('#/map');
    });
  });
})(jQuery);
<commit_msg>i forget how to amend<commit_after>(function($) {

  var app = $.sammy(function() {
    this.element_selector = '#content';
    this.use(Sammy.Template);

    this.before(function() {
    });

    this.get('#/map', function(context) {
      context.partial('cartmap.template', {id: 1}, function(rendered) {
        context.$element().html(rendered);
        var latlng = new google.maps.LatLng(45.597, -122.644);

        var myOptions = {
          zoom: 12,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
      });
    });

    this.get('#/carts', function(context) {
      context.partial('carts.template', {id: 1}, function(rendered) {
          context.$element().html(rendered);
          $('#cartcount').html('loading cart data ');
          $.couch.app(function(app) {
            app.db.view('webapp/cart', {success: function(cart_results) {
                                          $('#cartcount').html(cart_results.total_rows+" food carts listed.");
                                          $.each(cart_results.rows, function(index,element) {
                                            var carts_element = $('#carts ul');
                                            context.partial('cart.template', {cart: element}, function(rendered) {
                                               carts_element.append(rendered);
                                            });
                                          });
                                       }});
          }, {db : "food_carts", design : "webapp"});
      });
    });

    this.get('#/carts/new', function(context) {
      $.couch.app(function(app) {
        app.db.saveDoc({}, {success: function(res) {
          window.location = "#/carts/edit/"+res.id;
        }});
      }, {db : "food_carts", design : "webapp"});
    });

    this.get('#/carts/edit/:id', function(context) {
      var id = this.params['id'];
      $.couch.app(function(app) {
        app.db.openDoc(id, {success: function(cart_doc) {
          context.partial('cart.edit.template', {cart: cart_doc}, function(rendered) {
            context.$element().html(rendered);
            var cartform = $('#cartform');
            $('#cartform').submit(function() {
              app.db.saveDoc({
                               _id: cart_doc._id,
                               _rev: cart_doc._rev,
                               name: $('#cartform #name').val(),
                               hours: $('#cartform #hours').val(),
                               description: $('#cartform #description').val(),
                               geometry: {coordinates: [],"type":"Point"}
                             }, {success: function(res) {
                                  window.location = "#/carts";
              }});
              return false;
            });
          });
        }});
      }, {db : "food_carts", design : "webapp"});
    });

    $(function() {
      app.run('#/map');
    });
  });
})(jQuery);
<|endoftext|>


<commit_before>var $ = require('jquery');
var m = require('mithril');
var mime = require('js/mime');
var bootbox = require('bootbox');
var $osf = require('js/osfHelpers');
var waterbutler = require('js/waterbutler');

// Local requires
var utils = require('./util.js');
var FileEditor = require('./editor.js');
var FileRevisionsTable = require('./revisions.js');

// Sanity
var Panel = utils.Panel;

var EDITORS = {'text': FileEditor};

var FileViewPage = {
    controller: function(context) {
        var self = this;
        self.context = context;
        self.file = self.context.file;
        self.node = self.context.node;
        self.editorMeta = self.context.editor;
        //Force canEdit into a bool
        self.canEdit = m.prop(!!self.context.currentUser.canEdit);

        $.extend(self.file.urls, {
            delete: waterbutler.buildDeleteUrl(self.file.path, self.file.provider, self.node.id),
            metadata: waterbutler.buildMetadataUrl(self.file.path, self.file.provider, self.node.id),
            revisions: waterbutler.buildRevisionsUrl(self.file.path, self.file.provider, self.node.id),
            content: waterbutler.buildDownloadUrl(self.file.path, self.file.provider, self.node.id, {accept_url: false, mode: 'render'})
        });

        $(document).on('fileviewpage:delete', function() {
            bootbox.confirm({
                title: 'Delete file?',
                message: '
' +
                        'Are you sure you want to delete ' +
                        self.file.safeName + '?' +
                    '
',
                callback: function(confirm) {
                    if (!confirm) {
                        return;
                    }
                    $.ajax({
                        type: 'DELETE',
                        url: self.file.urls.delete,
                        beforeSend: $osf.setXHRAuthorization
                    }).done(function() {
                        window.location = self.node.urls.files;
                    }).fail(function() {
                        $osf.growl('Error', 'Could not delete file.');
                    });
                },
                buttons:{
                    confirm:{
                        label:'Delete',
                        className:'btn-danger'
                    }
                }
            });
        });

        $(document).on('fileviewpage:download', function() {
            window.location = self.file.urls.content;
            return false;
        });

        self.shareJSObservables = {
            activeUsers: m.prop([]),
            status: m.prop('connecting'),
            userId: self.context.currentUser.id
        };

        self.editHeader = function() {
            return m('.row', [
                m('.col-sm-12', m('span[style=display:block;]', [
                    m('h3.panel-title',[m('i.fa.fa-pencil-square-o'), '   Edit ']),
                    m('.pull-right', [
                        m('.progress.no-margin.pointer', {
                            'data-toggle': 'modal',
                            'data-target': '#' + self.shareJSObservables.status() + 'Modal'
                        }, [
                            m('.progress-bar.p-h-sm.progress-bar-success', {
                                connected: {
                                    style: 'width: 100%',
                                    class: 'progress-bar progress-bar-success'
                                },
                                connecting: {
                                    style: 'width: 100%',
                                    class: 'progress-bar progress-bar-warning progress-bar-striped active'
                                },
                                saving: {
                                    style: 'width: 100%',
                                    class: 'progress-bar progress-bar-info progress-bar-striped active'
                                }
                            }[self.shareJSObservables.status()] || {
                                    style: 'width: 100%',
                                    class: 'progress-bar progress-bar-danger'
                                }, [
                                    m('span.progress-bar-content', [
                                        {
                                            connected: 'Live editing mode ',
                                            connecting: 'Attempting to connect ',
                                            unsupported: 'Unsupported browser ',
                                            saving: 'Saving... '
                                        }[self.shareJSObservables.status()] || 'Unavailable: Live editing ',
                                        m('i.fa.fa-question-circle.fa-large')
                                    ])
                                ])
                            ])
                        ])
                    ]))
                ]);
        };

        // Hack to delay creation of the editor
        // until we know this is the current file revsion
        self.enableEditing = function() {
            // Sometimes we can get here twice, check just in case
            if (self.editor || !self.canEdit()) {
                m.redraw(true);
                return;
            }
            var fileType = mime.lookup(self.file.name.toLowerCase());
            // Only allow files < 1MB to be editable
            if (self.file.size < 1048576 && fileType) { //May return false
                var editor = EDITORS[fileType.split('/')[0]];
                if (editor) {
                    self.editor = new Panel('Edit', self.editHeader, editor, [self.file.urls.content, self.file.urls.sharejs, self.editorMeta, self.shareJSObservables], false);
                }
            }
            m.redraw(true);
        };

        //Hack to polyfill the Panel interface
        //Ran into problems with mithrils caching messing up with multiple "Panels"
        self.revisions = m.component(FileRevisionsTable, self.file, self.node, self.enableEditing, self.canEdit);
        self.revisions.selected = false;
        self.revisions.title = 'Revisions';

        // inform the mfr of a change in display size performed via javascript,
        // otherwise the mfr iframe will not update unless the document windows is changed.
        self.triggerResize = $osf.throttle(function () {
            $(document).trigger('fileviewpage:resize');
        }, 1000);

        self.mfrIframeParent = $('#mfrIframeParent');
    },
    view: function(ctrl) {
        //This code was abstracted into a panel toggler at one point
        //it was removed and shoved here due to issues with mithrils caching and interacting
        //With other non-mithril components on the page
        var panels;
        if (ctrl.editor) {
            panels = [ctrl.editor, ctrl.revisions];
        } else {
            panels = [ctrl.revisions];
        }

        var shown = panels.reduce(function(accu, panel) {
            return accu + (panel.selected ? 1 : 0);
        }, 0);

        var panelsShown = shown + (ctrl.mfrIframeParent.is(':visible') ? 1 : 0);
        var mfrIframeParentLayout;
        var fileViewPanelsLayout;

        if (panelsShown === 3) {
            // view | edit | revisions
            mfrIframeParentLayout = 'col-sm-4';
            fileViewPanelsLayout = 'col-sm-8';
        } else if (panelsShown === 2) {
            if (ctrl.mfrIframeParent.is(':visible')) {
                if (ctrl.revisions.selected) {
                    // view | revisions
                    mfrIframeParentLayout = 'col-sm-8';
                    fileViewPanelsLayout = 'col-sm-4';
                } else {
                    // view | edit
                    mfrIframeParentLayout = 'col-sm-6';
                    fileViewPanelsLayout = 'col-sm-6';
                }
            } else {
                // edit | revisions
                mfrIframeParentLayout = '';
                fileViewPanelsLayout = 'col-sm-12';
            }
        } else {
            // view
            if (ctrl.mfrIframeParent.is(':visible')) {
                mfrIframeParentLayout = 'col-sm-12';
                fileViewPanelsLayout = '';
            } else {
                // edit or revisions
                mfrIframeParentLayout = '';
                fileViewPanelsLayout = 'col-sm-12';
            }
        }
        $('#mfrIframeParent').removeClass().addClass(mfrIframeParentLayout);
        $('.file-view-panels').removeClass().addClass('file-view-panels').addClass(fileViewPanelsLayout);

        m.render(document.getElementById('toggleBar'), m('.btn-toolbar.m-t-md', [
            ctrl.canEdit() ? m('.btn-group.m-l-xs.m-t-xs', [
                m('.btn.btn-sm.btn-danger.file-delete', {onclick: $(document).trigger.bind($(document), 'fileviewpage:delete')}, 'Delete')
            ]) : '',
            m('.btn-group.m-t-xs', [
                m('#sharebutton.btn.btn-sm.btn-primary', {config: function(element, isInitialized) {
                    if(!isInitialized){
                        var button = $(element).popover();
                        button.on('show.bs.popover', function(e){
                            button.data()['bs.popover'].$tip.css('max-width', '600px').css('text-align', 'center');
                        });
                        if (!window.contextVars.node.isPublic) {
                            $('#sharebutton').attr('disabled', 'disabled');
                        }
                        else {
                            $('#sharebutton').removeAttr('disabled', 'disabled');
                        }
                        var link = $('iframe').attr('src');
                        var height = $('iframe').attr('height');
                        link = link.substring(0, link.indexOf('download') + 8);
                        var url = link.substring(0, link.indexOf('render'));
                        var style = '\<link href=\"' + url + 'static/css/mfr.css\" media=\"all\" rel=\"stylesheet\" /\>';
                        var data = '\
\
\Share\\
\
\Embed\\
\
\
';
                        data += '\
\
 \<input onclick="this.select()" class="form-control" type="text" value="' + link + '" /\> \
';
                        data += '\
';
                        data += '\
CSS Style, HTML & Script\
\<textarea onclick="this.select()" class="form-control" \>' + style + '\
\
';
                        data += ' \';
                        data += ' \ \</textarea\>';
                        data += '\
\
Direct iFrame\
\<textarea id="directIFrame" onclick="this.select()" class="form-control" \>' + '\' + '\</textarea\> \
';
                        data += '\
 \
 \
 \Width\ \
 \
';
                        data += ' \ Width \ \<input type="text" class="form-control text-center" id="width" placeholder="100%" onchange="updateWidth()"\> \
 \
 \
 \
 \Height\ \
 \
 \Height\ \<input type="text" class="form-control text-center" id="height" placeholder="100%" onchange="updateHeight()"\> \
';
                        data += '\
 \
 \
 \Show More\ \
';
                        data += '\
 \
 \';
                        $(element).attr('data-content', data);
                    }
                }, 'data-toggle': 'popover', 'data-placement': 'bottom', 'data-content': 'Content', 'title': 'Share', 'data-container': 'body', 'data-html': 'true'}, 'Share')
            ].concat(
                m('.btn.btn-sm.btn-primary.file-download', {onclick: $(document).trigger.bind($(document), 'fileviewpage:download')}, 'Download')
            )),
            m('.btn-group.btn-group-sm.m-t-xs', [
                m('.btn.btn-default.disabled', 'Toggle view: ')
            ].concat(
                m('.btn' + (ctrl.mfrIframeParent.is(':visible') ? '.btn-primary' : '.btn-default'), {
                    onclick: function (e) {
                        e.preventDefault();
                        // atleast one button must remain enabled.
                        if (!ctrl.mfrIframeParent.is(':visible') || panelsShown > 1) {
                            ctrl.mfrIframeParent.toggle();
                        }
                    }
                }, 'View')
            ).concat(
                panels.map(function(panel) {
                    return m('.btn' + (panel.selected ? '.btn-primary' : '.btn-default'), {
                        onclick: function(e) {
                            e.preventDefault();
                            // atleast one button must remain enabled.
                            if (!panel.selected || panelsShown > 1) {
                                panel.selected = !panel.selected;
                            }
                        }
                    }, panel.title);
                })
            ))
        ]));

        return m('.file-view-page', m('.panel-toggler', [
            m('.row', panels.map(function(pane, index) {
                ctrl.triggerResize();
                if (!pane.selected) {
                    return m('[style="display:none"]', pane);
                }
                return m('.col-sm-' + Math.floor(12/shown), pane);
            }))
        ]));
    }
};

module.exports = function(context) {
    // Treebeard forces all mithril to load twice, to avoid
    // destroying the page iframe this out side of mithril.
    if (!context.file.urls.render) {
        $('#mfrIframe').html(context.file.error);
    } else {
        var url = context.file.urls.render;
        if (context.accessToken) {
            url += '&token=' + context.accessToken;
        }

        if (window.mfr !== undefined) {
            var mfrRender = new mfr.Render('mfrIframe', url);
            $(document).on('fileviewpage:reload', function() {
                mfrRender.reload();
            });
            $(document).on('fileviewpage:resize', function() {
                mfrRender.resize();
            });
        }

    }

    return m.component(FileViewPage, context);
};
<commit_msg>Organized code, added actual rendered height of iframe to direct iframe opiton<commit_after>var $ = require('jquery');
var m = require('mithril');
var mime = require('js/mime');
var bootbox = require('bootbox');
var $osf = require('js/osfHelpers');
var waterbutler = require('js/waterbutler');

// Local requires
var utils = require('./util.js');
var FileEditor = require('./editor.js');
var FileRevisionsTable = require('./revisions.js');

// Sanity
var Panel = utils.Panel;

var EDITORS = {'text': FileEditor};

var FileViewPage = {
    controller: function(context) {
        var self = this;
        self.context = context;
        self.file = self.context.file;
        self.node = self.context.node;
        self.editorMeta = self.context.editor;
        //Force canEdit into a bool
        self.canEdit = m.prop(!!self.context.currentUser.canEdit);

        $.extend(self.file.urls, {
            delete: waterbutler.buildDeleteUrl(self.file.path, self.file.provider, self.node.id),
            metadata: waterbutler.buildMetadataUrl(self.file.path, self.file.provider, self.node.id),
            revisions: waterbutler.buildRevisionsUrl(self.file.path, self.file.provider, self.node.id),
            content: waterbutler.buildDownloadUrl(self.file.path, self.file.provider, self.node.id, {accept_url: false, mode: 'render'})
        });

        $(document).on('fileviewpage:delete', function() {
            bootbox.confirm({
                title: 'Delete file?',
                message: '
' +
                        'Are you sure you want to delete ' +
                        self.file.safeName + '?' +
                    '
',
                callback: function(confirm) {
                    if (!confirm) {
                        return;
                    }
                    $.ajax({
                        type: 'DELETE',
                        url: self.file.urls.delete,
                        beforeSend: $osf.setXHRAuthorization
                    }).done(function() {
                        window.location = self.node.urls.files;
                    }).fail(function() {
                        $osf.growl('Error', 'Could not delete file.');
                    });
                },
                buttons:{
                    confirm:{
                        label:'Delete',
                        className:'btn-danger'
                    }
                }
            });
        });

        $(document).on('fileviewpage:download', function() {
            window.location = self.file.urls.content;
            return false;
        });

        self.shareJSObservables = {
            activeUsers: m.prop([]),
            status: m.prop('connecting'),
            userId: self.context.currentUser.id
        };

        self.editHeader = function() {
            return m('.row', [
                m('.col-sm-12', m('span[style=display:block;]', [
                    m('h3.panel-title',[m('i.fa.fa-pencil-square-o'), '   Edit ']),
                    m('.pull-right', [
                        m('.progress.no-margin.pointer', {
                            'data-toggle': 'modal',
                            'data-target': '#' + self.shareJSObservables.status() + 'Modal'
                        }, [
                            m('.progress-bar.p-h-sm.progress-bar-success', {
                                connected: {
                                    style: 'width: 100%',
                                    class: 'progress-bar progress-bar-success'
                                },
                                connecting: {
                                    style: 'width: 100%',
                                    class: 'progress-bar progress-bar-warning progress-bar-striped active'
                                },
                                saving: {
                                    style: 'width: 100%',
                                    class: 'progress-bar progress-bar-info progress-bar-striped active'
                                }
                            }[self.shareJSObservables.status()] || {
                                    style: 'width: 100%',
                                    class: 'progress-bar progress-bar-danger'
                                }, [
                                    m('span.progress-bar-content', [
                                        {
                                            connected: 'Live editing mode ',
                                            connecting: 'Attempting to connect ',
                                            unsupported: 'Unsupported browser ',
                                            saving: 'Saving... '
                                        }[self.shareJSObservables.status()] || 'Unavailable: Live editing ',
                                        m('i.fa.fa-question-circle.fa-large')
                                    ])
                                ])
                            ])
                        ])
                    ]))
                ]);
        };

        // Hack to delay creation of the editor
        // until we know this is the current file revsion
        self.enableEditing = function() {
            // Sometimes we can get here twice, check just in case
            if (self.editor || !self.canEdit()) {
                m.redraw(true);
                return;
            }
            var fileType = mime.lookup(self.file.name.toLowerCase());
            // Only allow files < 1MB to be editable
            if (self.file.size < 1048576 && fileType) { //May return false
                var editor = EDITORS[fileType.split('/')[0]];
                if (editor) {
                    self.editor = new Panel('Edit', self.editHeader, editor, [self.file.urls.content, self.file.urls.sharejs, self.editorMeta, self.shareJSObservables], false);
                }
            }
            m.redraw(true);
        };

        //Hack to polyfill the Panel interface
        //Ran into problems with mithrils caching messing up with multiple "Panels"
        self.revisions = m.component(FileRevisionsTable, self.file, self.node, self.enableEditing, self.canEdit);
        self.revisions.selected = false;
        self.revisions.title = 'Revisions';

        // inform the mfr of a change in display size performed via javascript,
        // otherwise the mfr iframe will not update unless the document windows is changed.
        self.triggerResize = $osf.throttle(function () {
            $(document).trigger('fileviewpage:resize');
        }, 1000);

        self.mfrIframeParent = $('#mfrIframeParent');
    },
    view: function(ctrl) {
        //This code was abstracted into a panel toggler at one point
        //it was removed and shoved here due to issues with mithrils caching and interacting
        //With other non-mithril components on the page
        var panels;
        if (ctrl.editor) {
            panels = [ctrl.editor, ctrl.revisions];
        } else {
            panels = [ctrl.revisions];
        }

        var shown = panels.reduce(function(accu, panel) {
            return accu + (panel.selected ? 1 : 0);
        }, 0);

        var panelsShown = shown + (ctrl.mfrIframeParent.is(':visible') ? 1 : 0);
        var mfrIframeParentLayout;
        var fileViewPanelsLayout;

        if (panelsShown === 3) {
            // view | edit | revisions
            mfrIframeParentLayout = 'col-sm-4';
            fileViewPanelsLayout = 'col-sm-8';
        } else if (panelsShown === 2) {
            if (ctrl.mfrIframeParent.is(':visible')) {
                if (ctrl.revisions.selected) {
                    // view | revisions
                    mfrIframeParentLayout = 'col-sm-8';
                    fileViewPanelsLayout = 'col-sm-4';
                } else {
                    // view | edit
                    mfrIframeParentLayout = 'col-sm-6';
                    fileViewPanelsLayout = 'col-sm-6';
                }
            } else {
                // edit | revisions
                mfrIframeParentLayout = '';
                fileViewPanelsLayout = 'col-sm-12';
            }
        } else {
            // view
            if (ctrl.mfrIframeParent.is(':visible')) {
                mfrIframeParentLayout = 'col-sm-12';
                fileViewPanelsLayout = '';
            } else {
                // edit or revisions
                mfrIframeParentLayout = '';
                fileViewPanelsLayout = 'col-sm-12';
            }
        }
        $('#mfrIframeParent').removeClass().addClass(mfrIframeParentLayout);
        $('.file-view-panels').removeClass().addClass('file-view-panels').addClass(fileViewPanelsLayout);

        m.render(document.getElementById('toggleBar'), m('.btn-toolbar.m-t-md', [
            ctrl.canEdit() ? m('.btn-group.m-l-xs.m-t-xs', [
                m('.btn.btn-sm.btn-danger.file-delete', {onclick: $(document).trigger.bind($(document), 'fileviewpage:delete')}, 'Delete')
            ]) : '',
            m('.btn-group.m-t-xs', [
                m('#sharebutton.btn.btn-sm.btn-primary', {onclick: function () {
                    var link = $('iframe').attr('src');
                    var height = $('iframe').attr('height');
                    $('#height').val(height);
                    updateHeight();
                }, config: function(element, isInitialized) {
                    if(!isInitialized){
                        var button = $(element).popover();
                        button.on('show.bs.popover', function(e){
                            button.data()['bs.popover'].$tip.css('max-width', '600px').css('text-align', 'center');
                        });
                        if (!window.contextVars.node.isPublic) {
                            $('#sharebutton').attr('disabled', 'disabled');
                        }
                        else {
                            $('#sharebutton').removeAttr('disabled', 'disabled');
                        }
                        var link = $('iframe').attr('src');
                        var height = $('iframe').attr('height');
                        link = link.substring(0, link.indexOf('download') + 8);
                        var url = link.substring(0, link.indexOf('render'));
                        var style = '\<link href=\"' + url + 'static/css/mfr.css\" media=\"all\" rel=\"stylesheet\" /\>';
                        var data = [
                            '\
',
                            '   \
\Share\\
', '' +
                            '   \
\Embed\\
',
                            '\
\
',
                            '\
',
                            '   \
',
                            '       \<input onclick="this.select()" class="form-control" type="text" value="' + link + '" /\>',
                            '   \
',
                            '   \
',
                            '       \
CSS Style, HTML & Script\
',
                            '       \<textarea onclick="this.select()" class="form-control" \>'
                                        + style + '\n'
                                        + '\
\
 \n',
                                        '\ \n',
                                        '\ ',
                            '       \</textarea\>',
                            '       \
 \
Direct iFrame\
',
                            '           \<textarea id="directIFrame" onclick="this.select()" class="form-control" \>'
                                            + '\',
                            '           \</textarea\> \
',
                            '       \
 \
 \
 ',
                            '           \Width\ \
 \
',
                            '               \ Width \ \<input type="text" class="form-control text-center" id="width" placeholder="100%" onchange="updateWidth()"\> \
 \
 \
 \
 ',
                            '           \Height\ \
 \
 ',
                            '               \Height\ \<input type="text" class="form-control text-center" id="height" placeholder="100%" onchange="updateHeight()"\> \
',
                            '       \
 \
 \
',
                            '       \Show More\ ',
                            '\
 \
 \
 ',
                            '\',
                        ].join('');
                        $(element).attr('data-content', data);
                    }
                }, 'data-toggle': 'popover', 'data-placement': 'bottom', 'data-content': 'Content', 'title': 'Share', 'data-container': 'body', 'data-html': 'true'}, 'Share')
            ].concat(
                m('.btn.btn-sm.btn-primary.file-download', {onclick: $(document).trigger.bind($(document), 'fileviewpage:download')}, 'Download')
            )),
            m('.btn-group.btn-group-sm.m-t-xs', [
                m('.btn.btn-default.disabled', 'Toggle view: ')
            ].concat(
                m('.btn' + (ctrl.mfrIframeParent.is(':visible') ? '.btn-primary' : '.btn-default'), {
                    onclick: function (e) {
                        e.preventDefault();
                        // atleast one button must remain enabled.
                        if (!ctrl.mfrIframeParent.is(':visible') || panelsShown > 1) {
                            ctrl.mfrIframeParent.toggle();
                        }
                    }
                }, 'View')
            ).concat(
                panels.map(function(panel) {
                    return m('.btn' + (panel.selected ? '.btn-primary' : '.btn-default'), {
                        onclick: function(e) {
                            e.preventDefault();
                            // atleast one button must remain enabled.
                            if (!panel.selected || panelsShown > 1) {
                                panel.selected = !panel.selected;
                            }
                        }
                    }, panel.title);
                })
            ))
        ]));

        return m('.file-view-page', m('.panel-toggler', [
            m('.row', panels.map(function(pane, index) {
                ctrl.triggerResize();
                if (!pane.selected) {
                    return m('[style="display:none"]', pane);
                }
                return m('.col-sm-' + Math.floor(12/shown), pane);
            }))
        ]));
    }
};

module.exports = function(context) {
    // Treebeard forces all mithril to load twice, to avoid
    // destroying the page iframe this out side of mithril.
    if (!context.file.urls.render) {
        $('#mfrIframe').html(context.file.error);
    } else {
        var url = context.file.urls.render;
        if (context.accessToken) {
            url += '&token=' + context.accessToken;
        }

        if (window.mfr !== undefined) {
            var mfrRender = new mfr.Render('mfrIframe', url);
            $(document).on('fileviewpage:reload', function() {
                mfrRender.reload();
            });
            $(document).on('fileviewpage:resize', function() {
                mfrRender.resize();
            });
        }

    }

    return m.component(FileViewPage, context);
};
<|endoftext|>


<commit_before>/**
 * Created by jane on 02/04/2017.
 */
import React from 'react'
import {Icon} from 'antd'
import _ from 'lodash'

const lameCSV = (str) => {
  return _.reduce(str.split('\n'), function (table, row) {
    table.push(_.map(row.split(','), function (c) {
      return c.trim()
    }))
    return table
  }, [])
}

const lyricSegment = (n) => {
  return _.chain([])
    .push(n + 'bottles of beer on the wall')
    .push(n + 'bottles of beer')
    .push('Take one down, pass it around')
    .tap(lyrics => {
      if (n > 1)
        lyrics.push((n - 1) + 'bottles of beer on the wall')
      else
        lyrics.push('No more bottles of beer on the wall')
    })
}

// 鬼畜歌词生成器^_^
const song = (start, end, lyricGen) => {
  return _.reduce(_.range(start, end, -1), function (acc, n) {
      return acc.concat(lyricGen(n))
    }, []
  )
}

const str = 'name,age,hair\nMerble,35,red\nBob,64,blonde'
const FP = () =>

string: {str}

   {lameCSV(str)}

    {lameCSV(str).map((tr, i) =>
{tr.map((td, j) => {td}	)}
)}
    {song(99, 0, lyricSegment)}

export default FP
<commit_msg>_.identity<commit_after>/**
 * Created by jane on 02/04/2017.
 */
import React from 'react'
import {Icon} from 'antd'
import _ from 'lodash'

const lameCSV = (str) => {
  return _.reduce(str.split('\n'), function (table, row) {
    table.push(_.map(row.split(','), function (c) {
      return c.trim()
    }))
    return table
  }, [])
}

const lyricSegment = (n) => {
  return _.chain([])
    .push(n + 'bottles of beer on the wall')
    .push(n + 'bottles of beer')
    .push('Take one down, pass it around')
    .tap(lyrics => {
      if (n > 1)
        lyrics.push((n - 1) + 'bottles of beer on the wall')
      else
        lyrics.push('No more bottles of beer on the wall')
    })
}

// 鬼畜歌词生成器^_^
const song = (start, end, lyricGen) => {
  return _.reduce(_.range(start, end, -1), function (acc, n) {
      return acc.concat(lyricGen(n))
    }, []
  )
}

const str = 'name,age,hair\nMerble,35,red\nBob,64,blonde'
const FP = () =>

string: {str}

   {lameCSV(str)}

    {lameCSV(str).map((tr, i) =>
{tr.map((td, j) => {td}	)}
)}
    {song(99, 0, lyricSegment)}

    {_.map({a: 1, b: 2}, _.identity)}

export default FP
<|endoftext|>


<commit_before>var inquirer = require("inquirer"),
    pluralize = require('pluralize'),
    fs = require('fs'),
    grep = require('simple-grep'),
    exec = require('child_process').exec

// file is included here:
eval(fs.readFileSync('src/CRUD.js') + '');
eval(fs.readFileSync('src/CRUD.SqliteAdapter.js') + '');

/**
 * Find a list of all defined CRUD entities so we can use them for hooking up relations
 */
function findEntities() {

    exec("find . -iname '*js' | xargs grep 'CRUD.Entity.call(this);' -isl", {
        timeout: 3000,
        cwd: process.cwd()
    }, function(err, stdout, stdin) {

        // split the results
        var results = stdout.split('\n');
        // remove last element (it’s an empty line)
        results.pop();

        console.log("Search results");
        for (var i = 0; i < results.length; i++) {

            console.log(results[i]);

        }
    });
}

console.log([
    "------------------------------------------------",
    "   Generate a CreateReadUpdateDelete.js Entity",
    "------------------------------------------------"
].join("\n"));

var starterQuestions = [{
    type: "input",
    name: "entityName",
    message: "Please name your entity (singular)",

}];

var propertyQuestions = [{
    type: "input",
    name: "property",
    message: "Add a property"
}, {
    type: "list",
    name: "type",
    message: "What's the type?",
    choices: [
        "RELATION",
        "VARCHAR",
        "INT",
        "TINYINT",
        "SMALLINT",
        "MEDIUMINT",
        "BIGINT",
        "DATE",
        "DATETIME",
        "TEXT",
        "BLOB",
        "DOUBLE",
        "FLOAT",
        "DECIMAL",

    ]
}];

var noLength = ["DATE", "DATETIME", "TEXT", "BLOB"];

var metaQuestions = [{
    type: "confirm",
    name: "createIndex",
    message: "Create an INDEX on this property?",
    default: false
}, {
    type: "confirm",
    name: "autoSerialize",
    message: "Auto-Serialize this property? (Say yes if you plan to put objects or arrays in this property)",
    default: false
}, {
    type: "confirm",
    name: "askAgain",
    message: "Want to add another property? ",
    default: true
}];

var entity = {
    properties: {}
};

var ucFirst = function(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
};

function askMetaQuestions(property) {
    inquirer.prompt(metaQuestions, function(results) {
        entity.properties[property].autoSerialize = results.autoSerialize;
        entity.properties[property].index = results.createIndex;

        if (results.askAgain) {
            addProperty();
        } else {
            console.log("\nEntity info:");
            console.log(JSON.stringify(entity, null, "  "));
        }
    });
}

function askLength(property) {
    inquirer.prompt({
        type: "input",
        name: "length",
        message: "Length",
        default: 1
    }, function(results) {
        entity.properties[property].length = results.length;
        askMetaQuestions(property);
    });
}

function addProperty() {
    inquirer.prompt(propertyQuestions, function(results) {
        entity.properties[results.property] = {
            type: results.type
        };

        if (noLength.indexOf(results.type) == -1) {
            askLength(results.property);
        } else {
            askMetaQuestions(results.property);
        }

    });
}

inquirer.prompt(starterQuestions, function(answers) {
    entity.name = ucFirst(answers.entityName);
    entity.table = ucFirst(pluralize.plural(entity.name));
    entity.primary = 'ID_' + entity.name;
    addProperty();
});<commit_msg>escape from callback hell. Promises ftw <3<commit_after>var inquirer = require("inquirer"),
    pluralize = require('pluralize'),
    fs = require('fs'),
    grep = require('simple-grep'),
    exec = require('child_process').exec,
    Promise = require('es6-promise').Promise;

eval(fs.readFileSync('src/CRUD.js') + '');
eval(fs.readFileSync('src/CRUD.SqliteAdapter.js') + '');

/**
 * Find a list of all defined CRUD entities so we can use them for hooking up relations
 */
function findEntities() {

    exec("find . -iname '*js' | xargs grep 'CRUD.Entity.call(this);' -isl", {
        timeout: 3000,
        cwd: process.cwd()
    }, function(err, stdout, stdin) {

        // split the results
        var results = stdout.split('\n');
        // remove last element (it’s an empty line)
        results.pop();

        console.log("Search results");
        for (var i = 0; i < results.length; i++) {

            console.log(results[i]);

        }
    });
}

console.log([
    "------------------------------------------------",
    "   Generate a CreateReadUpdateDelete.js Entity",
    "------------------------------------------------"
].join("\n"));

var entity = {
    properties: {}
};

var ucFirst = function(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
};

/**
 * Return aything not promise as a promise similar to angular's $q.when
 */
function promiseWrap(something) {
    return new Promise(function(resolve) {
        resolve(something);
    });
}

/**
 * Convert inquirer.prompt to a promise.
 */
function promisePrompt(questions) {
    return new Promise(function(resolve, reject) {
        inquirer.prompt(questions, function(results) {
            resolve(results);
        });
    });
}

function askIndex(property) {
    return promisePrompt({
        type: "confirm",
        name: "createIndex",
        message: "Create an INDEX on this property?",
        default: false
    }).then(function(results) {
        entity.properties[property.property].index = results.createIndex;
        return property;
    });
}

function askLength(property) {
    var noLength = ["DATE", "DATETIME", "TEXT", "BLOB"];

    if (noLength.indexOf(property.type) > -1) {
        return promiseWrap(property);
    } else {
        return promisePrompt({
            type: "input",
            name: "length",
            message: "Length",
            default: 1
        }).then(function(results) {
            entity.properties[property.property].length = results.length;
            return property;
        });
    }
}

function askAutoserialize(property) {
    var canHoldSerializable = ["TEXT", "BLOB"];
    if (canHoldSerializable.indexOf(property.type) == -1) {
        return promiseWrap(property);
    } else {
        return promisePrompt({
            type: "confirm",
            name: "autoSerialize",
            message: "Auto-Serialize this property? (Say yes if you plan to put objects or arrays in this property)",
            default: false
        }).then(function(results) {
            entity.properties[property.property].autoSerialize = results.autoSerialize;
            return property;
        });
    }
}

function askProperty() {
    return promisePrompt([{
        type: "input",
        name: "property",
        message: "Enter the name of a new property to add"
    }, {
        type: "list",
        name: "type",
        message: "What's the type?",
        choices: "RELATION|VARCHAR|INT|TINYINT|SMALLINT|MEDIUMINT|BIGINT|DATE|DATETIME|TEXT|BLOB|DOUBLE|FLOAT|DECIMAL".split("|")
    }]).then(function(results) {
        entity.properties[results.property] = {
            type: results.type
        };
        return results;
    });
}

function askAnotherProperty() {
    return promisePrompt({
        type: "confirm",
        name: "askAgain",
        message: "Want to add another property? ",
        default: true
    }).then(function(results) {
        return (results.askAgain) ? addProperty() : entity;
    });
}

function outputEntity(entity) {
    console.log("\nEntity info:");
    console.log(JSON.stringify(entity, null, "  "));
    return;
}

function addProperty() {
    return askProperty()
        .then(askLength)
        .then(askAutoserialize)
        .then(askIndex)
        .then(askAnotherProperty);
}

promisePrompt({
    type: "input",
    name: "entityName",
    message: "Please name your entity (singular)",
}).then(function(answers) {
    entity.name = ucFirst(answers.entityName);
    entity.table = ucFirst(pluralize.plural(entity.name));
    entity.primary = 'ID_' + entity.name;
    console.log("Creating new CRUD Entity: %s\nTable: %s\nPrimary key: %s", entity.name, entity.table, entity.primary);
    return addProperty().then(outputEntity);
});<|endoftext|>


<commit_before>/*
 * 	Copyright (C) 2012-2013 DFKI GmbH
 * 	Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
 * 	German Research Center for Artificial Intelligence
 * 	http://www.dfki.de
 *
 * 	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.
 */

//define variables/functions in order to avoid errors in jscc.js:
var DEFAULT_DRIVER = '';
var get_arguments = function(){ return [];};
var _quit = function(errors){
	//only print errors if > 0 (or STRING)
	console.log('JS/CC loaded/finished! '+ (errors != null? (typeof errors == 'number'? (errors > 0? 'number of ERRORs ' + errors : ''): 'ERROR ' + errors): ''));
};
function _error( msg ){ console.error('JS/CC ERROR: '+msg); }
function _warning( msg ){ console.warn('JS/CC WARNING: '+msg); }
function _print( msg ){  console.log('JS/CC INFO: '+msg); }<commit_msg>removed un-used file (was directly integrated into jscc-amd)<commit_after><|endoftext|>


<commit_before>'use strict';

// Print the name of an app

const commander = require('commander');
const path = require('path');
const util = require('util');

// Print the name of an app
const runCLI = () => {
  // Parse command line options
  commander
    .arguments('<dir>')
    .action((dir, conf, name) => {
      commander.dir = dir;
    })
    .parse(process.argv);

  // Load the app's package.json and print its name
  const mod = require(path.join(
    path.resolve(process.cwd(), commander.dir), 'package.json'));
  process.stdout.write(util.format('%s\n', mod.name));
};

// Export our CLI
module.exports.runCLI = runCLI;

<commit_msg>Change cfpush to read appname from manifest instead of package.json (#593)<commit_after>'use strict';

// Print the name of an app

const commander = require('commander');
const fs = require('fs');
const yaml = require('js-yaml');
const path = require('path');
const util = require('util');

// Print the name of an app
const runCLI = () => {
  // Parse command line options
  commander
    .arguments('<dir>')
    .action((dir, conf, name) => {
      commander.dir = dir;
    })
    .parse(process.argv);

  // Load the app's manifest and print its name
  const manifestPath = path.join(path.resolve(process.cwd(), commander.dir),
      'manifest.yml');
  const content = fs.readFileSync(manifestPath);
  const manifest = yaml.load(content);
  process.stdout.write(util.format('%s\n', manifest.applications[0].name));
};

// Export our CLI
module.exports.runCLI = runCLI;

<|endoftext|>


<commit_before>const path = require("path");
const fs = require("fs");
const yargs = require("yargs");

// use "npm run build -- --env dev" or "yarn run build --env dev" to pass
const env = yargs.argv.env || null;
const profile = yargs.argv.profile || false;

function resolve(relativePath) {
    return path.resolve(__dirname, `../${relativePath}`);
}

function json(path) {
    return JSON.parse(fs.readFileSync(path));
}

function webpackJSON() {
    if (env === null) return null;
    const path = resolve(`conf/${env}/webpack.json`);
    if (!fs.existsSync(path)) return null;

    return json(path);
}

module.exports = {
    dist: resolve("build/dist"),
    nodeModules: resolve("node_modules"),
    src: resolve("src"),
    static: resolve("static"),
    conf: env == null ? resolve("src/conf") : resolve(`conf/${env}`),
    lib: resolve("lib"),
    tsConfig: resolve("webpack/tsconfig.json"),
    tslintConfig: resolve("webpack/tslint.json"),
    stylelintConfig: resolve("webpack/stylelint.json"),
    webpackJSON: webpackJSON(),
    profile: profile,
};
<commit_msg>simply script<commit_after>const path = require("path");
const fs = require("fs");
const yargs = require("yargs");

// use "npm run build -- --env dev" or "yarn run build --env dev" to pass
const env = yargs.argv.env || null;
const profile = yargs.argv.profile || false;

function resolve(relativePath) {
    return path.resolve(__dirname, `../${relativePath}`);
}

function webpackJSON() {
    if (env === null) return null;
    const path = resolve(`conf/${env}/webpack.json`);
    if (!fs.existsSync(path)) return null;

    return JSON.parse(fs.readFileSync(path));
}

module.exports = {
    dist: resolve("build/dist"),
    nodeModules: resolve("node_modules"),
    src: resolve("src"),
    static: resolve("static"),
    conf: env == null ? resolve("src/conf") : resolve(`conf/${env}`),
    lib: resolve("lib"),
    tsConfig: resolve("webpack/tsconfig.json"),
    tslintConfig: resolve("webpack/tslint.json"),
    stylelintConfig: resolve("webpack/stylelint.json"),
    webpackJSON: webpackJSON(),
    profile: profile,
};
<|endoftext|>


<commit_before>/*
 * Boardfarm Management application
 * Copyright (c) 2016 Heiko Stuebner <heiko@sntech.de>
 *
 * License:
 *   MIT: https://opensource.org/licenses/MIT
 *   See the LICENSE file in the project's top-level directory for details.
 */

var power = require("./Power");
var ipower = require("./IPowerPort");
var exec = require('child_process').exec;

qx.Class.define("sn.boardfarm.backend.power.Ykush",
{
	extend : qx.core.Object,
	implement : [ sn.boardfarm.backend.power.IPowerAdapter ],

	construct : function(serial)
	{
		var pwr = sn.boardfarm.backend.power.Power.getInstance();

		console.log("Power: added Ykush hub " + serial);
		this.setAdapterIdent("ykush:"+serial);
		this.setSerial(serial);
		this.__states = { 0 : -1, 1 : -1, 2 : -1 };

		pwr.addAdapter(this.getAdapterIdent(), this);
	},

	events :
	{
		"adapterPowerChanged" : "qx.event.type.Data",
		"adapterPortStateChanged" : "qx.event.type.Data"
	},

	properties :
	{
		adapterIdent : {},
		serial : {}
	},

	members :
	{
		adapterReadPower : function()
		{
			/* can't read power measurements */
			this.fireDataEvent("adapterPowerChanged", 0);
		},

		__states : {},

		adapterReadState : function()
		{
			var child;
			var serial = this.getSerial();
			var base = this;
			child = exec("ykush -s " + serial + " -g a", function (error, stdout, stderr)
			{
				if (error !== null) {
					console.log("ykush command returned " + error);
					this.__states = { 0 : -1, 1 : -1, 2 : -1 };
					return;
				}

				var data = stdout.split("\n");
				for (var i = 0; i < 3; i++) {
					var state = (data[i].indexOf(": DOWN") != -1) ? 0 : 1;
					base.__states[i] = state;
				}
			});
		},

		__ports : {},

		adapterAddPort : function(port, obj)
		{
			if (this.__ports[port])
				throw "Port "+port+" already set on "+this.getIdent();

			this.__ports[port] = obj;
		},

		adapterGetPortNum : function()
		{
			 return 3;
		},

		adapterGetPort : function(port)
		{
			if (!this.__ports[port])
				throw "Port "+port+" not set on "+this.getIdent();

			return this.__ports[port];
		},

		adapterGetPortState : function(port)
		{
			return this.__states[port];
		},

		adapterSetPortState : function(port, newState)
		{
			var child;
			var serial = this.getSerial();
			var base = this;
			var cmd = newState ? "-u" : "-d";

			child = exec("ykush -s " + serial + " " + cmd + " " + (parseInt(port) + 1), function (error, stdout, stderr)
			{
				if (error !== null) {
					console.log("ykush command returned " + error);
					return;
				}

				base.__states[port] = newState;
				base.fireDataEvent("adapterPortStateChanged", { port : port, state : newState });
				console.log("Power: set port " + parseInt(port) + " of " + base.getAdapterIdent() + " to "+ newState);
			});
		}
	}
});

qx.Class.define("sn.boardfarm.backend.power.YkushPort",
{
	extend : qx.core.Object,
	implement : [ sn.boardfarm.backend.power.IPowerPort ],

	construct : function(serial, port)
	{
		var pwr = sn.boardfarm.backend.power.Power.getInstance();

		try {
			this.__adapter = pwr.getAdapter("ykush:"+serial);
		} catch(ex) {
			this.__adapter = new sn.boardfarm.backend.power.Ykush(serial);
		}

		this.setPort(port);
		this.__adapter.adapterAddPort(port, this);
	},

	properties :
	{
		port : {},
		board : {}
	},

	members :
	{
		__adapter : null,

		portGetAdapter : function()
		{
			return this.__adapter;
		},

		portGetState : function()
		{
			return this.portGetAdapter().adapterGetPortState(this.getPort());
		},

		portSetState : function(newState)
		{
			this.portGetAdapter().adapterSetPortState(this.getPort(), newState);
		}
	}
});
<commit_msg>YKush: use correct property in Exception strings<commit_after>/*
 * Boardfarm Management application
 * Copyright (c) 2016 Heiko Stuebner <heiko@sntech.de>
 *
 * License:
 *   MIT: https://opensource.org/licenses/MIT
 *   See the LICENSE file in the project's top-level directory for details.
 */

var power = require("./Power");
var ipower = require("./IPowerPort");
var exec = require('child_process').exec;

qx.Class.define("sn.boardfarm.backend.power.Ykush",
{
	extend : qx.core.Object,
	implement : [ sn.boardfarm.backend.power.IPowerAdapter ],

	construct : function(serial)
	{
		var pwr = sn.boardfarm.backend.power.Power.getInstance();

		console.log("Power: added Ykush hub " + serial);
		this.setAdapterIdent("ykush:"+serial);
		this.setSerial(serial);
		this.__states = { 0 : -1, 1 : -1, 2 : -1 };

		pwr.addAdapter(this.getAdapterIdent(), this);
	},

	events :
	{
		"adapterPowerChanged" : "qx.event.type.Data",
		"adapterPortStateChanged" : "qx.event.type.Data"
	},

	properties :
	{
		adapterIdent : {},
		serial : {}
	},

	members :
	{
		adapterReadPower : function()
		{
			/* can't read power measurements */
			this.fireDataEvent("adapterPowerChanged", 0);
		},

		__states : {},

		adapterReadState : function()
		{
			var child;
			var serial = this.getSerial();
			var base = this;
			child = exec("ykush -s " + serial + " -g a", function (error, stdout, stderr)
			{
				if (error !== null) {
					console.log("ykush command returned " + error);
					this.__states = { 0 : -1, 1 : -1, 2 : -1 };
					return;
				}

				var data = stdout.split("\n");
				for (var i = 0; i < 3; i++) {
					var state = (data[i].indexOf(": DOWN") != -1) ? 0 : 1;
					base.__states[i] = state;
				}
			});
		},

		__ports : {},

		adapterAddPort : function(port, obj)
		{
			if (this.__ports[port])
				throw "Port "+port+" already set on "+this.getAdapterIdent();

			this.__ports[port] = obj;
		},

		adapterGetPortNum : function()
		{
			 return 3;
		},

		adapterGetPort : function(port)
		{
			if (!this.__ports[port])
				throw "Port "+port+" not set on "+this.getAdapterIdent();

			return this.__ports[port];
		},

		adapterGetPortState : function(port)
		{
			return this.__states[port];
		},

		adapterSetPortState : function(port, newState)
		{
			var child;
			var serial = this.getSerial();
			var base = this;
			var cmd = newState ? "-u" : "-d";

			child = exec("ykush -s " + serial + " " + cmd + " " + (parseInt(port) + 1), function (error, stdout, stderr)
			{
				if (error !== null) {
					console.log("ykush command returned " + error);
					return;
				}

				base.__states[port] = newState;
				base.fireDataEvent("adapterPortStateChanged", { port : port, state : newState });
				console.log("Power: set port " + parseInt(port) + " of " + base.getAdapterIdent() + " to "+ newState);
			});
		}
	}
});

qx.Class.define("sn.boardfarm.backend.power.YkushPort",
{
	extend : qx.core.Object,
	implement : [ sn.boardfarm.backend.power.IPowerPort ],

	construct : function(serial, port)
	{
		var pwr = sn.boardfarm.backend.power.Power.getInstance();

		try {
			this.__adapter = pwr.getAdapter("ykush:"+serial);
		} catch(ex) {
			this.__adapter = new sn.boardfarm.backend.power.Ykush(serial);
		}

		this.setPort(port);
		this.__adapter.adapterAddPort(port, this);
	},

	properties :
	{
		port : {},
		board : {}
	},

	members :
	{
		__adapter : null,

		portGetAdapter : function()
		{
			return this.__adapter;
		},

		portGetState : function()
		{
			return this.portGetAdapter().adapterGetPortState(this.getPort());
		},

		portSetState : function(newState)
		{
			this.portGetAdapter().adapterSetPortState(this.getPort(), newState);
		}
	}
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
import React, { useState, useCallback, useEffect } from "react";
import { MDXProvider } from "@mdx-js/react";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import renderRoutes from "@docusaurus/renderRoutes";
import Layout from "@theme/Layout";
import DocSidebar from "@theme/DocSidebar";
import MDXComponents from "@theme/MDXComponents";
import NotFound from "@theme/NotFound";
import IconArrow from "@theme/IconArrow";
import { matchPath } from "@docusaurus/router";
import clsx from "clsx";
import styles from "./styles.module.css";
import { docVersionSearchTag } from "@docusaurus/theme-common";

function DocPageContent({ currentDocRoute, versionMetadata, children }) {
  const { siteConfig, isClient } = useDocusaurusContext();
  const {
    pluginId,
    permalinkToSidebar,
    docsSidebars,
    version,
  } = versionMetadata;

  const pageId = {
    general : "General",
    apisix : "getting-started",
    apisixDashboard : "dashboard",
    apisixIngressController : "what-is-apisix-ingress-controller",
    apisixHelmChart : "install",
    apisixDocker : "build-an-image-from-source"
  }
  useEffect(() => {
    if(docsSidebars[sidebarName][0].label === pageId.general){
      document.querySelectorAll(".navbar__link--active")[0].text = "General";
    } else if (document.getElementById(pageId.apisix)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX";
    } else if (document.getElementById(pageId.apisixDashboard)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX Dashboard";
    } else if (document.getElementById(pageId.apisixIngressController)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX Ingress Controller";
    } else if (document.getElementById(pageId.apisixHelmChart)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX™ Helm Chart";
    } else if (document.getElementById(pageId.apisixDocker)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX™ Docker";
    }
    return () => {
      console.log('\u{1F680} documentation changed')
    }
  }, []);

  const sidebarName = permalinkToSidebar[currentDocRoute.path];
  const sidebar = docsSidebars[sidebarName];
  const [hiddenSidebarContainer, setHiddenSidebarContainer] = useState(false);
  const [hiddenSidebar, setHiddenSidebar] = useState(false);
  const toggleSidebar = useCallback(() => {
    if (hiddenSidebar) {
      setHiddenSidebar(false);
    }
    setHiddenSidebarContainer(!hiddenSidebarContainer);
  }, [hiddenSidebar]);
  return (
    <Layout
      key={isClient}
      searchMetadatas={{
        version,
        tag: docVersionSearchTag(pluginId, version),
      }}
    >

        {sidebar && (

 {
              if (
                !e.currentTarget.classList.contains(styles.docSidebarContainer)
              ) {
                return;
              }

              if (hiddenSidebarContainer) {
                setHiddenSidebar(true);
              }
            }}
            role="complementary"
          >
            <DocSidebar
              key={
                // Reset sidebar state on sidebar changes
                // See https://github.com/facebook/docusaurus/issues/3414
                sidebarName
              }
              sidebar={sidebar}
              path={currentDocRoute.path}
              sidebarCollapsible={
                siteConfig.themeConfig?.sidebarCollapsible ?? true
              }
              onCollapse={toggleSidebar}
              isHidden={hiddenSidebar}
              docPluginId={pluginId}
            />

            {hiddenSidebar && (

                <IconArrow aria-label="Expand sidebar" />

            )}

        )}

            <MDXProvider components={MDXComponents}>{children}</MDXProvider>

    </Layout>
  );
}

function DocPage(props) {
  const {
    route: { routes: docRoutes },
    versionMetadata,
    location,
  } = props;
  const currentDocRoute = docRoutes.find((docRoute) =>
    matchPath(location.pathname, docRoute)
  );

  if (!currentDocRoute) {
    return <NotFound {...props} />;
  }

  return (
    <DocPageContent
      currentDocRoute={currentDocRoute}
      versionMetadata={versionMetadata}
    >
      {renderRoutes(docRoutes)}
    </DocPageContent>
  );
}

export default DocPage;
<commit_msg>fix: navigation path naming for apisix-java-plugin-runner (#385)<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
import React, { useState, useCallback, useEffect } from "react";
import { MDXProvider } from "@mdx-js/react";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import renderRoutes from "@docusaurus/renderRoutes";
import Layout from "@theme/Layout";
import DocSidebar from "@theme/DocSidebar";
import MDXComponents from "@theme/MDXComponents";
import NotFound from "@theme/NotFound";
import IconArrow from "@theme/IconArrow";
import { matchPath } from "@docusaurus/router";
import clsx from "clsx";
import styles from "./styles.module.css";
import { docVersionSearchTag } from "@docusaurus/theme-common";

function DocPageContent({ currentDocRoute, versionMetadata, children }) {
  const { siteConfig, isClient } = useDocusaurusContext();
  const {
    pluginId,
    permalinkToSidebar,
    docsSidebars,
    version,
  } = versionMetadata;

  const pageId = {
    general : "General",
    apisix : "getting-started",
    apisixDashboard : "dashboard",
    apisixIngressController : "what-is-apisix-ingress-controller",
    apisixHelmChart : "seeking-help",
    apisixDocker : "build-an-image-from-source",
    apisixJavaPluginRunner : "overview"
  }
  useEffect(() => {
    if(docsSidebars[sidebarName][0].label === pageId.general){
      document.querySelectorAll(".navbar__link--active")[0].text = "General";
    } else if (document.getElementById(pageId.apisix)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX";
    } else if (document.getElementById(pageId.apisixDashboard)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX Dashboard";
    } else if (document.getElementById(pageId.apisixIngressController)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX Ingress Controller";
    } else if (document.getElementById(pageId.apisixHelmChart)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX™ Helm Chart";
    } else if (document.getElementById(pageId.apisixDocker)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX™ Docker";
    } else if (document.getElementById(pageId.apisixJavaPluginRunner)) {
      document.querySelectorAll(".navbar__link--active")[0].text = "Apache APISIX™ Java Plugin Runner";
    }
    return () => {
      console.log('\u{1F680} documentation changed')
    }
  }, []);

  const sidebarName = permalinkToSidebar[currentDocRoute.path];
  const sidebar = docsSidebars[sidebarName];
  const [hiddenSidebarContainer, setHiddenSidebarContainer] = useState(false);
  const [hiddenSidebar, setHiddenSidebar] = useState(false);
  const toggleSidebar = useCallback(() => {
    if (hiddenSidebar) {
      setHiddenSidebar(false);
    }
    setHiddenSidebarContainer(!hiddenSidebarContainer);
  }, [hiddenSidebar]);
  return (
    <Layout
      key={isClient}
      searchMetadatas={{
        version,
        tag: docVersionSearchTag(pluginId, version),
      }}
    >

        {sidebar && (

 {
              if (
                !e.currentTarget.classList.contains(styles.docSidebarContainer)
              ) {
                return;
              }

              if (hiddenSidebarContainer) {
                setHiddenSidebar(true);
              }
            }}
            role="complementary"
          >
            <DocSidebar
              key={
                // Reset sidebar state on sidebar changes
                // See https://github.com/facebook/docusaurus/issues/3414
                sidebarName
              }
              sidebar={sidebar}
              path={currentDocRoute.path}
              sidebarCollapsible={
                siteConfig.themeConfig?.sidebarCollapsible ?? true
              }
              onCollapse={toggleSidebar}
              isHidden={hiddenSidebar}
              docPluginId={pluginId}
            />

            {hiddenSidebar && (

                <IconArrow aria-label="Expand sidebar" />

            )}

        )}

            <MDXProvider components={MDXComponents}>{children}</MDXProvider>

    </Layout>
  );
}

function DocPage(props) {
  const {
    route: { routes: docRoutes },
    versionMetadata,
    location,
  } = props;
  const currentDocRoute = docRoutes.find((docRoute) =>
    matchPath(location.pathname, docRoute)
  );

  if (!currentDocRoute) {
    return <NotFound {...props} />;
  }

  return (
    <DocPageContent
      currentDocRoute={currentDocRoute}
      versionMetadata={versionMetadata}
    >
      {renderRoutes(docRoutes)}
    </DocPageContent>
  );
}

export default DocPage;
<|endoftext|>


<commit_before>(function poll() {
  if (typeof ynabToolKit !== 'undefined' && ynabToolKit.actOnChangeInit === true) {
    ynabToolKit.toggleSplits = (function () {
      var calculatingDisplayEnd = false;

      function setDisplayEnd() {
        if (ynabToolKit.toggleSplits.setting === 'show') return;

        calculatingDisplayEnd = true;
        var rowView = ynabToolKit.shared.getEmberViewByContainerKey('view:ynab-grid/rows');
        var accountsController = ynabToolKit.shared.containerLookup('controller:accounts');
        var contentResults = accountsController.get('contentResults');
        var containerView = rowView.get('containerView');
        var gridView = rowView.get('gridView');
        var displayStart = containerView.get('displayStart');
        var recordsPerBody = containerView.get('recordsPerBody');

        // this calculation was taken from YNAB's current codebase
        var wouldBeDisplayEnd = Math.round(Math.min(displayStart + 4 * recordsPerBody, gridView.get('total')));

        var fitOnPage = wouldBeDisplayEnd - displayStart;
        var displayedCount = 0;
        var displayEnd = displayStart;

        for (var i = displayStart; i < contentResults.length; i++) {
          if (displayedCount === fitOnPage) break;

          if (contentResults[i].get('parentEntityId')) {
            if (ynabToolKit.toggleSplits.setting === 'hide') {
              displayEnd++;
              continue;
            } else {
              displayedCount++;
            }
          } else {
            displayedCount++;
            displayEnd++;
          }
        }

        Ember.run.next(function () {
          containerView.set('displayEnd', displayEnd);
          calculatingDisplayEnd = false;
        });
      }

      function addScrollListener() {
        var rowView = ynabToolKit.shared.getEmberViewByContainerKey('view:ynab-grid/rows');
        rowView.get('containerView').addObserver('scrollTop', setDisplayEnd);

        if (rowView.get('containerView').get('scrollTop') === 0) {
          setDisplayEnd();
        }
      }

      function hideSubTransactions() {
        ynabToolKit.toggleSplits.setting = 'hide';
        $('.ynab-grid-body .ynab-grid-body-sub').hide();
        $(".ynab-grid-cell-subCategoryName[title^='Split']").css('font-weight', 700);
        setDisplayEnd();
      }

      function showSubTransactions() {
        ynabToolKit.toggleSplits.setting = 'show';
        $('.ynab-grid-body .ynab-grid-body-sub').show();
        $(".ynab-grid-cell-subCategoryName[title^='Split']").css('font-weight', '');
      }

      return {
        setting: 'init',
        invoke: function invoke() {
          // default the right arrow to hidden
          if (ynabToolKit.toggleSplits.setting === 'init' || ynabToolKit.toggleSplits.setting === 'hide') {
            $('#toggle-splits > .down').hide();
            hideSubTransactions();
          } else {
            showSubTransactions();
          }

          if (!$('#toggle-splits').length) {
            var buttonText = ynabToolKit.l10nData && ynabToolKit.l10nData['toolkit.toggleSplits'] || 'Toggle Splits';

            $('<button>', { id: 'toggle-splits', class: 'ember-view button' })
              .append($('<i>', { class: 'ember-view flaticon stroke right' }))
              .append($('<i>', { class: 'ember-view flaticon stroke down' }))
              .append(' ' + buttonText)
              .insertAfter('.accounts-toolbar .undo-redo-container');

            $('.accounts-toolbar-left').find('#toggle-splits').click(function () {
              if (ynabToolKit.toggleSplits.setting === 'hide') {
                showSubTransactions();
              } else {
                hideSubTransactions();
              }

              $('#toggle-splits > i').toggle();
            });

            addScrollListener();
          }
        },

        observe: function observe(changedNodes) {
          if (changedNodes.has('ynab-grid-body')) {
            ynabToolKit.toggleSplits.invoke();
            if (!calculatingDisplayEnd) {
              setDisplayEnd();
            }
          }
        }
      };
    }());

    ynabToolKit.toggleSplits.invoke();
  } else {
    setTimeout(poll, 250);
  }
}());
<commit_msg>Added exception for rows that are being edited<commit_after>(function poll() {
  if (typeof ynabToolKit !== 'undefined' && ynabToolKit.actOnChangeInit === true) {
    ynabToolKit.toggleSplits = (function () {
      var calculatingDisplayEnd = false;

      function setDisplayEnd() {
        if (ynabToolKit.toggleSplits.setting === 'show') return;

        calculatingDisplayEnd = true;
        var rowView = ynabToolKit.shared.getEmberViewByContainerKey('view:ynab-grid/rows');
        var accountsController = ynabToolKit.shared.containerLookup('controller:accounts');
        var contentResults = accountsController.get('contentResults');
        var containerView = rowView.get('containerView');
        var gridView = rowView.get('gridView');
        var displayStart = containerView.get('displayStart');
        var recordsPerBody = containerView.get('recordsPerBody');

        // this calculation was taken from YNAB's current codebase
        var wouldBeDisplayEnd = Math.round(Math.min(displayStart + 4 * recordsPerBody, gridView.get('total')));

        var fitOnPage = wouldBeDisplayEnd - displayStart;
        var displayedCount = 0;
        var displayEnd = displayStart;

        for (var i = displayStart; i < contentResults.length; i++) {
          if (displayedCount === fitOnPage) break;

          if (contentResults[i].get('parentEntityId')) {
            if (ynabToolKit.toggleSplits.setting === 'hide') {
              displayEnd++;
              continue;
            } else {
              displayedCount++;
            }
          } else {
            displayedCount++;
            displayEnd++;
          }
        }

        Ember.run.next(function () {
          containerView.set('displayEnd', displayEnd);
          calculatingDisplayEnd = false;
        });
      }

      function addScrollListener() {
        var rowView = ynabToolKit.shared.getEmberViewByContainerKey('view:ynab-grid/rows');
        rowView.get('containerView').addObserver('scrollTop', setDisplayEnd);

        if (rowView.get('containerView').get('scrollTop') === 0) {
          setDisplayEnd();
        }
      }

      function hideSubTransactions() {
        ynabToolKit.toggleSplits.setting = 'hide';
        $('.ynab-grid-body .ynab-grid-body-sub:not(.is-editing)').hide();
        $(".ynab-grid-cell-subCategoryName[title^='Split']").css('font-weight', 700);
        setDisplayEnd();
      }

      function showSubTransactions() {
        ynabToolKit.toggleSplits.setting = 'show';
        $('.ynab-grid-body .ynab-grid-body-sub').show();
        $(".ynab-grid-cell-subCategoryName[title^='Split']").css('font-weight', '');
      }

      return {
        setting: 'init',
        invoke: function invoke() {
          // default the right arrow to hidden
          if (ynabToolKit.toggleSplits.setting === 'init' || ynabToolKit.toggleSplits.setting === 'hide') {
            $('#toggle-splits > .down').hide();
            hideSubTransactions();
          } else {
            showSubTransactions();
          }

          if (!$('#toggle-splits').length) {
            var buttonText = ynabToolKit.l10nData && ynabToolKit.l10nData['toolkit.toggleSplits'] || 'Toggle Splits';

            $('<button>', { id: 'toggle-splits', class: 'ember-view button' })
              .append($('<i>', { class: 'ember-view flaticon stroke right' }))
              .append($('<i>', { class: 'ember-view flaticon stroke down' }))
              .append(' ' + buttonText)
              .insertAfter('.accounts-toolbar .undo-redo-container');

            $('.accounts-toolbar-left').find('#toggle-splits').click(function () {
              if (ynabToolKit.toggleSplits.setting === 'hide') {
                showSubTransactions();
              } else {
                hideSubTransactions();
              }

              $('#toggle-splits > i').toggle();
            });

            addScrollListener();
          }
        },

        observe: function observe(changedNodes) {
          if (changedNodes.has('ynab-grid-body')) {
            ynabToolKit.toggleSplits.invoke();
            if (!calculatingDisplayEnd) {
              setDisplayEnd();
            }
          }
        }
      };
    }());

    ynabToolKit.toggleSplits.invoke();
  } else {
    setTimeout(poll, 250);
  }
}());
<|endoftext|>


<commit_before>/**
 * 目标: 为了尽可能的减少模块之间业务逻辑的耦合度, 而开发了这个eventbus, 主要用于业务逻辑的事件传递
 * 使用规范: 每个js模块尽可能通过事件去通信, 减少模块之间的直接调用和依赖(耦合)

 * @return {[type]}
 * @author  theowang
 * $Id: broadcast.js 65871 2012-11-05 01:51:42Z theowang $
 */
MixJS.define('event.broadcast',function($){
    var _cache = {};
    var broadcast = {

        /**
         * 派发
         * @param  {[type]} type 事件类型
         * @param  {[type]} data 回调数据
         * @return {[type]}      [description]
         */
        fire:function(type, data){
            var listeners = _cache[type],len = 0;
            if(!$.isUndefined(listeners)){
                var args = [].slice.call(arguments);
                args = args.length > 2 ? args.splice(2, args.length-1) : [];
                args = [data].concat(args);

                len = listeners.length;
                for(var i = 0; i<len;i++){
                    var listener = listeners[i];
                    if(listener && listener.callback) {
                        args = args.concat(listener.args);
                        listener.callback.apply(listener.scope, args);
                    }
                }
            }
            return this;
        },
        /**
         * 订阅广播事件
         * @param  {[type]}   types     事件类型，支持,分隔符
         * @param  {Function} callback 回调函数
         * @param  {[type]}   scope    回调函数上下文
         * @return {[type]}            this
         */
        subscribe:function(types, callback, scope){
            types = types || [];
            var args = [].slice.call(arguments);

            if($.isString(types)){
                types = types.split(',');
            }
            var len = types.length;
            if(len===0){
                return this;
            }
            args = args.length > 3 ? args.splice(3, args.length-1) : [];
            for(var i = 0;i<len;i++){
                var type = types[i];
                _cache[type] = _cache[type] || [];
                _cache[type].push({callback:callback,scope:scope,args:args});
            }
            return this;
        },
        /**
         * 退订
         * @param  {[type]}   type     [description]
         * @param  {Function} callback 假如传入则移出传入的监控事件，否则移出全部
         * @return {[type]}            [description]
         */
        unsubscribe:function(type, callback, scope){
            var listeners = _cache[type];
            if (!listeners) {
                return this;
            }
            if(callback){
                var len = listeners.length,
                    tmp = [];

                for(var i=0; i<len; i++) {
                    var listener = listeners[i];
                    if(listener.callback == callback && listener.scope == scope) {
                    } else {
                        tmp.push(listener);
                    }
                }
                listeners = tmp;
            }else{
                listeners.length = 0;
            }
            return this;
        },
        /**
         * 订阅别名
         * @return {[type]} [description]
         */
        on:function(){
            return this.subscribe.apply(this,arguments);
        },
        /**
         * 退订别名
         * @return {[type]} [description]
         */
        un:function(){
            return this.unsubscribe.apply(this,arguments);
        },
        dispatch:function(){
            return this.fire.apply(this,arguments);
        },

        removeAll:function(){
            _cache = {};
            return this;
        }
    };
    return broadcast;
});<commit_msg>修改广播事件为0.2规范<commit_after>/**
 * 目标: 为了尽可能的减少模块之间业务逻辑的耦合度, 而开发了这个eventbus, 主要用于业务逻辑的事件传递
 * 使用规范: 每个js模块尽可能通过事件去通信, 减少模块之间的直接调用和依赖(耦合)

 * @return {[type]}
 * @author  theowang
 * $Id: broadcast.js 65871 2012-11-05 01:51:42Z theowang $
 */
MixJS.define('event/broadcast',function($){
    var _cache = {};
    var broadcast = {

        /**
         * 派发
         * @param  {[type]} type 事件类型
         * @param  {[type]} data 回调数据
         * @return {[type]}      [description]
         */
        fire:function(type, data){
            var listeners = _cache[type],len = 0;
            if(!$.isUndefined(listeners)){
                var args = [].slice.call(arguments);
                args = args.length > 2 ? args.splice(2, args.length-1) : [];
                args = [data].concat(args);

                len = listeners.length;
                for(var i = 0; i<len;i++){
                    var listener = listeners[i];
                    if(listener && listener.callback) {
                        args = args.concat(listener.args);
                        listener.callback.apply(listener.scope, args);
                    }
                }
            }
            return this;
        },
        /**
         * 订阅广播事件
         * @param  {[type]}   types     事件类型，支持,分隔符
         * @param  {Function} callback 回调函数
         * @param  {[type]}   scope    回调函数上下文
         * @return {[type]}            this
         */
        subscribe:function(types, callback, scope){
            types = types || [];
            var args = [].slice.call(arguments);

            if($.isString(types)){
                types = types.split(',');
            }
            var len = types.length;
            if(len===0){
                return this;
            }
            args = args.length > 3 ? args.splice(3, args.length-1) : [];
            for(var i = 0;i<len;i++){
                var type = types[i];
                _cache[type] = _cache[type] || [];
                _cache[type].push({callback:callback,scope:scope,args:args});
            }
            return this;
        },
        /**
         * 退订
         * @param  {[type]}   type     [description]
         * @param  {Function} callback 假如传入则移出传入的监控事件，否则移出全部
         * @return {[type]}            [description]
         */
        unsubscribe:function(type, callback, scope){
            var listeners = _cache[type];
            if (!listeners) {
                return this;
            }
            if(callback){
                var len = listeners.length,
                    tmp = [];

                for(var i=0; i<len; i++) {
                    var listener = listeners[i];
                    if(listener.callback == callback && listener.scope == scope) {
                    } else {
                        tmp.push(listener);
                    }
                }
                listeners = tmp;
            }else{
                listeners.length = 0;
            }
            return this;
        },
        /**
         * 订阅别名
         * @return {[type]} [description]
         */
        on:function(){
            return this.subscribe.apply(this,arguments);
        },
        /**
         * 退订别名
         * @return {[type]} [description]
         */
        un:function(){
            return this.unsubscribe.apply(this,arguments);
        },
        dispatch:function(){
            return this.fire.apply(this,arguments);
        },

        removeAll:function(){
            _cache = {};
            return this;
        }
    };
    return broadcast;
});<|endoftext|>