<commit_before>import {first, uniq, compact, startsWith} from 'lodash'

import cheerio from 'cheerio'
import urijs from 'urijs'

import {flattenDeepCheerioElements} from 'utils'

export function getRelevantTags(htmlText, urlToFetch){
  return new Promise((resolve, reject) => {
    const doc = cheerio.load(htmlText, {
      ignoreWhitespace: true,
      decodeEntities: true,
      lowerCaseTags: true,
      lowerCaseAttributeNames: true,
      recognizeCDATA: true,
      recognizeSelfClosing: true
    })

    resolve({
      title: extractTitle(doc),
      description: extractDescription(doc),
      imageUrls: extractImages(doc, urlToFetch)
    })
  })
}

function extractDescription(doc){
  return first(compact([
    doc("meta[name='description']").attr('content'),
    doc("meta[property='og:description']").attr('content')
  ]))
}

function extractTitle(doc) {
  return first(compact([
    doc("meta[name='title']").attr('content'),
    doc("meta[property='og:title']").attr('content'),
    doc('title').text(),
  ]))
}

function extractImages(doc, urlToFetch) {
  const imageUrls = flattenDeepCheerioElements([
    doc("meta[name='image']").attr("content"),
    doc("meta[property='og:image']").attr("content"),
    doc("img").map((i, imgNode) => doc(imgNode).attr("src"))
  ])

  return uniq(imageUrls.map(imageUrl => {
    const imageProtocol = urijs(imageUrl).protocol()
    if(imageProtocol){
      return imageUrl
    }

    if(startsWith(imageUrl, '//')){
      const urlToFetchProtocol = urijs(urlToFetch).protocol()
      return urijs(imageUrl).protocol(urlToFetchProtocol).toString()
    }

    return urijs.joinPaths(urlToFetch, imageUrl).toString()
  }))
}<commit_msg>fixed image resolving bug<commit_after>import {first, uniq, compact, startsWith} from 'lodash'

import cheerio from 'cheerio'
import urijs from 'urijs'

import {flattenDeepCheerioElements} from 'utils'

export function getRelevantTags(htmlText, urlToFetch){
  return new Promise((resolve, reject) => {
    const doc = cheerio.load(htmlText, {
      ignoreWhitespace: true,
      decodeEntities: true,
      lowerCaseTags: true,
      lowerCaseAttributeNames: true,
      recognizeCDATA: true,
      recognizeSelfClosing: true
    })

    resolve({
      title: extractTitle(doc),
      description: extractDescription(doc),
      imageUrls: extractImages(doc, urlToFetch)
    })
  })
}

function extractDescription(doc){
  return first(compact([
    doc("meta[name='description']").attr('content'),
    doc("meta[property='og:description']").attr('content')
  ]))
}

function extractTitle(doc) {
  return first(compact([
    doc("meta[name='title']").attr('content'),
    doc("meta[property='og:title']").attr('content'),
    doc('title').text(),
  ]))
}

function extractImages(doc, urlToFetch) {
  const imageUrls = flattenDeepCheerioElements([
    doc("meta[name='image']").attr("content"),
    doc("meta[property='og:image']").attr("content"),
    doc("img").map((i, imgNode) => doc(imgNode).attr("src"))
  ])

  return uniq(imageUrls.map(imageUrl => {
    const imageProtocol = urijs(imageUrl).protocol()
    if(imageProtocol){
      return imageUrl
    }

    if(startsWith(imageUrl, '//')){
      const urlToFetchProtocol = urijs(urlToFetch).protocol()
      return urijs(imageUrl).protocol(urlToFetchProtocol).toString()
    }

    return urijs(imageUrl).absoluteTo(urlToFetch).toString()
  }))
}<|endoftext|>


<commit_before>/**
 * Start the girder backbone app.
 */
$(function () {
    girder.events.trigger('g:appload.before');
    var app = new girder.App({
        el: 'body',
        parentView: null
    });
    girder.events.trigger('g:appload.after');
});

function _setProgress(test, duration) {
    /* Set or update a current progress notification.
     *
     * :param test: test parameter to send to the webclienttest/progress
     *     endpoint
     * :param duration: duration to send to the endpoint
     */
    girder.restRequest({path: 'webclienttest/progress', type: 'GET',
                        data: {test: test, duration: duration}});
}

describe('Test widgets that are not covered elsewhere', function () {
    it('register a user',
        girderTest.createUser('admin',
                              'admin@email.com',
                              'Admin',
                              'Admin',
                              'adminpassword!'));

    it('test task progress widget', function () {
        var errorCalled=0, onMessageError=0;

        runs(function () {
            expect($('#g-app-progress-container:visible').length).toBe(0);
            _setProgress('success', 0);
        });
        waitsFor(function () {
            return $('.g-task-progress-title').text() == 'Progress Test';
        }, 'progress to be shown');
        waitsFor(function () {
            return $('.g-task-progress-message').text() == 'Done';
        }, 'progress to be complete');

        runs(function () {
            _setProgress('error', 0);
        });
        waitsFor(function () {
            return $('.g-task-progress-title:last').text() == 'Progress Test';
        }, 'progress to be shown');
        waitsFor(function () {
            return $('.g-task-progress-message:last').text() == 'Error: Progress error test.';
        }, 'progress to report an error');

        runs(function () {
            var origOnMessage = girder.eventStream._eventSource.onmessage;
            girder.eventStream._eventSource.onmessage = function (e) {
                try {
                    origOnMessage(e);
                } catch (err) {
                    onMessageError += 1;
                }
            };
            var stream = girder.events._events['g:navigateTo'][0].ctx.progressListView.eventStream;
            stream.on('g:error', function () { errorCalled += 1; });
            stream.on('g:event.progress', function () {
                throw 'intentional error';
            });
            _setProgress('success', 0);
        });
        waitsFor(function () {
            return onMessageError == 1;
        }, 'bad progress callbcak to be tried');
        runs(function () {
            _setProgress('error', 0);
        });
        waitsFor(function () {
            return onMessageError == 2;
        }, 'bad progress callbcak to be tried again');
        runs(function () {
            expect(errorCalled).toBe(0);
        });

        runs(function () {
            /* Ask for a long test, so that on slow machines we can still
             * detect a partial progress. */
            _setProgress('success', 100);
        });
        waitsFor(function () {
            return $('.g-task-progress-message:last').text() == 'Progress Message';
        }, 'progress to be shown');
        runs(function () {
            expect($('.g-progress-widget-container').length > 0);
        });
        waitsFor(function () {
            /* Wait until at least 4% has progressed, as it makes our
             * subsequent test not require an explicit wait */
            return parseFloat($('.progress-status .progress-percent:last').
                   text()) >= 4 && /left$/.test($(
                   '.progress-status .progress-left:last').text());
        }, 'progress to show estimated time');

        /* There is a five second timeout for fading out the success message.
         * Because we waiting for 4% of the progress of the previous task,
         * there should be less than a second left to wait for the first test
         * to vanish. */
        waitsFor(function () {
            return $('.g-progress-widget-container').length < 3;
        }, 'at least the first progress to be hidden');

        runs(function () {
            girder.restRequest({path: 'webclienttest/progress/stop',
                                type: 'PUT', async: false});
        });
    });
});
<commit_msg>Fix a typo.<commit_after>/**
 * Start the girder backbone app.
 */
$(function () {
    girder.events.trigger('g:appload.before');
    var app = new girder.App({
        el: 'body',
        parentView: null
    });
    girder.events.trigger('g:appload.after');
});

function _setProgress(test, duration) {
    /* Set or update a current progress notification.
     *
     * :param test: test parameter to send to the webclienttest/progress
     *     endpoint
     * :param duration: duration to send to the endpoint
     */
    girder.restRequest({path: 'webclienttest/progress', type: 'GET',
                        data: {test: test, duration: duration}});
}

describe('Test widgets that are not covered elsewhere', function () {
    it('register a user',
        girderTest.createUser('admin',
                              'admin@email.com',
                              'Admin',
                              'Admin',
                              'adminpassword!'));

    it('test task progress widget', function () {
        var errorCalled=0, onMessageError=0;

        runs(function () {
            expect($('#g-app-progress-container:visible').length).toBe(0);
            _setProgress('success', 0);
        });
        waitsFor(function () {
            return $('.g-task-progress-title').text() == 'Progress Test';
        }, 'progress to be shown');
        waitsFor(function () {
            return $('.g-task-progress-message').text() == 'Done';
        }, 'progress to be complete');

        runs(function () {
            _setProgress('error', 0);
        });
        waitsFor(function () {
            return $('.g-task-progress-title:last').text() == 'Progress Test';
        }, 'progress to be shown');
        waitsFor(function () {
            return $('.g-task-progress-message:last').text() == 'Error: Progress error test.';
        }, 'progress to report an error');

        runs(function () {
            var origOnMessage = girder.eventStream._eventSource.onmessage;
            girder.eventStream._eventSource.onmessage = function (e) {
                try {
                    origOnMessage(e);
                } catch (err) {
                    onMessageError += 1;
                }
            };
            var stream = girder.events._events['g:navigateTo'][0].ctx.progressListView.eventStream;
            stream.on('g:error', function () { errorCalled += 1; });
            stream.on('g:event.progress', function () {
                throw 'intentional error';
            });
            _setProgress('success', 0);
        });
        waitsFor(function () {
            return onMessageError == 1;
        }, 'bad progress callback to be tried');
        runs(function () {
            _setProgress('error', 0);
        });
        waitsFor(function () {
            return onMessageError == 2;
        }, 'bad progress callback to be tried again');
        runs(function () {
            expect(errorCalled).toBe(0);
        });

        runs(function () {
            /* Ask for a long test, so that on slow machines we can still
             * detect a partial progress. */
            _setProgress('success', 100);
        });
        waitsFor(function () {
            return $('.g-task-progress-message:last').text() == 'Progress Message';
        }, 'progress to be shown');
        runs(function () {
            expect($('.g-progress-widget-container').length > 0);
        });
        waitsFor(function () {
            /* Wait until at least 4% has progressed, as it makes our
             * subsequent test not require an explicit wait */
            return parseFloat($('.progress-status .progress-percent:last').
                   text()) >= 4 && /left$/.test($(
                   '.progress-status .progress-left:last').text());
        }, 'progress to show estimated time');

        /* There is a five second timeout for fading out the success message.
         * Because we waiting for 4% of the progress of the previous task,
         * there should be less than a second left to wait for the first test
         * to vanish. */
        waitsFor(function () {
            return $('.g-progress-widget-container').length < 3;
        }, 'at least the first progress to be hidden');

        runs(function () {
            girder.restRequest({path: 'webclienttest/progress/stop',
                                type: 'PUT', async: false});
        });
    });
});
<|endoftext|>


<commit_before>// $Revision$

Ensembl.LayoutManager = new Base();

Ensembl.LayoutManager.extend({
  constructor: null,

  /**
   * Creates events on elements outside of the domain of panels
   */
  initialize: function () {
    this.id = 'LayoutManager';

    Ensembl.EventManager.register('reloadPage',    this, this.reloadPage);
    Ensembl.EventManager.register('validateForms', this, this.validateForms);
    Ensembl.EventManager.register('makeZMenu',     this, this.makeZMenu);
    Ensembl.EventManager.register('relocateTools', this, this.relocateTools);
    Ensembl.EventManager.register('hashChange',    this, this.hashChange);
    Ensembl.EventManager.register('toggleContent', this, this.toggleContent);
    Ensembl.EventManager.register('changeWidth',   this, this.changeWidth);

    $('#page_nav .tool_buttons > p').show();

    $('#header a:not(#tabs a)').addClass('constant');

    if (window.location.hash.match(Ensembl.locationMatch)) {
      $('.ajax_load').val(function (i, val) {
        return Ensembl.urlFromHash(val);
      });

      this.hashChange(Ensembl.urlFromHash(window.location.href, true));
    }

    $(document).on('click', '.modal_link', function () {
      if (Ensembl.EventManager.trigger('modalOpen', this)) {
        return false;
      }
    }).on('click', '.popup', function () {
      if (window.name.match(/^popup_/)) {
        return true;
      }

      window.open(this.href, 'popup_' + window.name, 'width=950,height=500,resizable,scrollbars');
      return false;
    }).on('click', 'a[rel="external"]', function () {
      this.target = '_blank';
    }).on('click', 'a.update_panel', function () {
      var panelId = this.rel;
      var url     = Ensembl.updateURL({ update_panel: 1 }, this.href);

      if (Ensembl.PanelManager.panels[panelId] && this.href.split('?')[0].match(Ensembl.PanelManager.panels[panelId].params.updateURL.split('?')[0])) {
        var params = {};

        if (!$('.update_url', this).each(function () { params[this.name] = this.value; }).length) {
          params = undefined;
        }

        Ensembl.EventManager.triggerSpecific('updatePanel', panelId, url, null, { updateURL: this.href }, params);
      } else {
        $.ajax({
          url: url,
          success: function () {
            Ensembl.EventManager.triggerSpecific('updatePanel', panelId);
          }
        });
      }

      return false;
    }).on({
      'keyup.ensembl': function (event) {
        if (event.keyCode === 27) {
          Ensembl.EventManager.trigger('modalClose', true); // Close modal window if the escape key is pressed
        }
      },
      'mouseup.ensembl': function (e) {
        // only fired on left click
        if (!e.which || e.which === 1) {
          Ensembl.EventManager.trigger('mouseUp', e);
        }
      }
    });

    $('.modal_link').show();

    this.validateForms(document);

    $(window).on({
      'resize.ensembl': function (e) {
        if (window.name.match(/^popup_/)) {
          return false;
        }

        // jquery ui resizable events cause window.resize to fire (all events bubble to window)
        // if target has no tagName it is window or document. Don't resize unless this is the case
        if (!e.target.tagName) {
          var width = Ensembl.width;

          if (Ensembl.dynamicWidth) {
            Ensembl.setWidth(undefined, true);
          }

          Ensembl.EventManager.trigger('windowResize');

          if (Ensembl.dynamicWidth && Ensembl.width !== width) {
            Ensembl.LayoutManager.changeWidth();
            Ensembl.EventManager.trigger('imageResize');
          }
        }
      },
      'hashchange.ensembl': $.proxy(this.popState, this),
      'popstate.ensembl'  : $.proxy(this.popState, this)
    });

    var userMessage = unescape(Ensembl.cookie.get('user_message'));

    if (userMessage) {
      userMessage = userMessage.split('\n');

      $([
        '
',
        '
', userMessage[0], '
',
        '
', userMessage[1], '
',
        '
'
      ].join('')).prependTo('#main').find('h3 img, a').on('click', function () {
        $(this).parents('div.hint').remove();
        Ensembl.cookie.set('user_message', '');
      });
    }
  },

  reloadPage: function (args, url) {
    if (typeof args === 'string') {
      Ensembl.EventManager.triggerSpecific('updatePanel', args);
    } else if (typeof args === 'object') {
      for (var i in args) {
        Ensembl.EventManager.triggerSpecific('updatePanel', i);
      }
    } else {
      return Ensembl.redirect(url);
    }

    $('#messages').hide();
  },

  validateForms: function (context) {
    $('form._check', context).validate().on('submit', function () {
      var form = $(this);

      if (form.parents('#modal_panel').length) {
        var panels = form.parents('.js_panel').map(function () { return this.id; }).toArray();
        var rtn;

        while (panels.length && typeof rtn === 'undefined') {
          rtn = Ensembl.EventManager.triggerSpecific('modalFormSubmit', panels.shift(), form);
        }

        return rtn;
      }
    });
  },

  makeZMenu: function (id, params) {
    if (!$('#' + id).length) {
      $([
        '
',
        ' ',
        '
',
        '
',
        '

',
        '
',
        '
',
        '

',
        '
',
        '

',
        '
',
        '
'
      ].join('')).draggable({ handle: 'thead' }).appendTo('body');
    }

    Ensembl.EventManager.trigger('addPanel', id, 'ZMenu', undefined, undefined, params, 'showExistingZMenu');
  },

  relocateTools: function (tools) {
    var toolButtons = $('#page_nav .tool_buttons');

    tools.each(function () {
      var a        = $(this).find('a');
      var existing = $('.additional .' + a[0].className.replace(' ', '.'), toolButtons);

      if (existing.length) {
        existing.replaceWith(a);
      } else {
        $(this).children().addClass('additional').appendTo(toolButtons).not('.hidden').show();
      }

      a = existing = null;
    }).remove();

    $('a.seq_blast', toolButtons).on('click', function () {
      $('form.seq_blast', toolButtons).submit();
      return false;
    });
  },

  popState: function () {
    if (
      Ensembl.historyReady && // stops popState executing on initial page load in Chrome. This value is set to true in Ensembl.updateLocation
      // there is an r param in the hash/search EXCEPT WHEN the browser supports history API, and there is a hash which doesn't have an r param (ajax added content)
      ((window.location[Ensembl.locationURL].match(Ensembl.locationMatch) && !(Ensembl.locationURL === 'search' && window.location.hash && !window.location.hash.match(Ensembl.locationMatch))) ||
      (!window.location.hash && Ensembl.hash.match(Ensembl.locationMatch))) // there is no location.hash, but Ensembl.hash (previous hash value) had an r param (going back from no hash url to hash url)
    ) {
      Ensembl.setCoreParams();
      Ensembl.EventManager.trigger('hashChange', Ensembl.urlFromHash(window.location.href, true));
    }
  },

  hashChange: function (r) {
    if (!r) {
      return;
    }

    r = decodeURIComponent(r);

    var text = r.split(/\W/);
        text = text[0] + ': ' + Ensembl.thousandify(text[1]) + '-' + Ensembl.thousandify(text[2]);

    $('a:not(.constant)').attr('href', function () {
      var r;

      if (this.title === 'UCSC') {
        this.href = this.href.replace(/(&?position=)[^&]+(.?)/, '$1chr' + Ensembl.urlFromHash(this.href, true) + '$2');
      } else if (this.title === 'NCBI') {
        r = Ensembl.urlFromHash(this.href, true).split(/[:\-]/);
        this.href = this.href.replace(/(&?CHR=).+&BEG=.+&END=[^&]+(.?)/, '$1' + r[0] + '&BEG=' + r[1] + '&END=' + r[2] + '$2');
      } else {
        return Ensembl.urlFromHash(this.href);
      }
    });

    $('input[name=r]', 'form:not(#core_params)').val(r);

    $('h1.summary-heading').html(function (i, html) {
      return html.replace(/^(Chromosome ).+/, '$1' + text);
    });

    document.title = document.title.replace(/(Chromosome ).+/, '$1' + text);
  },

  toggleContent: function (rel) {
    if (rel) {
      $('a.toggle[rel="' + rel + '"]').toggleClass('open closed');
    }
  },

  changeWidth: function () {
    $('.navbar, div.info, div.hint, div.warning, div.error').not('.fixed_width, :parent(#modal_panel)').width(Ensembl.width);
  }
});

<commit_msg>fix selector for changeWidth<commit_after>// $Revision$

Ensembl.LayoutManager = new Base();

Ensembl.LayoutManager.extend({
  constructor: null,

  /**
   * Creates events on elements outside of the domain of panels
   */
  initialize: function () {
    this.id = 'LayoutManager';

    Ensembl.EventManager.register('reloadPage',    this, this.reloadPage);
    Ensembl.EventManager.register('validateForms', this, this.validateForms);
    Ensembl.EventManager.register('makeZMenu',     this, this.makeZMenu);
    Ensembl.EventManager.register('relocateTools', this, this.relocateTools);
    Ensembl.EventManager.register('hashChange',    this, this.hashChange);
    Ensembl.EventManager.register('toggleContent', this, this.toggleContent);
    Ensembl.EventManager.register('changeWidth',   this, this.changeWidth);

    $('#page_nav .tool_buttons > p').show();

    $('#header a:not(#tabs a)').addClass('constant');

    if (window.location.hash.match(Ensembl.locationMatch)) {
      $('.ajax_load').val(function (i, val) {
        return Ensembl.urlFromHash(val);
      });

      this.hashChange(Ensembl.urlFromHash(window.location.href, true));
    }

    $(document).on('click', '.modal_link', function () {
      if (Ensembl.EventManager.trigger('modalOpen', this)) {
        return false;
      }
    }).on('click', '.popup', function () {
      if (window.name.match(/^popup_/)) {
        return true;
      }

      window.open(this.href, 'popup_' + window.name, 'width=950,height=500,resizable,scrollbars');
      return false;
    }).on('click', 'a[rel="external"]', function () {
      this.target = '_blank';
    }).on('click', 'a.update_panel', function () {
      var panelId = this.rel;
      var url     = Ensembl.updateURL({ update_panel: 1 }, this.href);

      if (Ensembl.PanelManager.panels[panelId] && this.href.split('?')[0].match(Ensembl.PanelManager.panels[panelId].params.updateURL.split('?')[0])) {
        var params = {};

        if (!$('.update_url', this).each(function () { params[this.name] = this.value; }).length) {
          params = undefined;
        }

        Ensembl.EventManager.triggerSpecific('updatePanel', panelId, url, null, { updateURL: this.href }, params);
      } else {
        $.ajax({
          url: url,
          success: function () {
            Ensembl.EventManager.triggerSpecific('updatePanel', panelId);
          }
        });
      }

      return false;
    }).on({
      'keyup.ensembl': function (event) {
        if (event.keyCode === 27) {
          Ensembl.EventManager.trigger('modalClose', true); // Close modal window if the escape key is pressed
        }
      },
      'mouseup.ensembl': function (e) {
        // only fired on left click
        if (!e.which || e.which === 1) {
          Ensembl.EventManager.trigger('mouseUp', e);
        }
      }
    });

    $('.modal_link').show();

    this.validateForms(document);

    $(window).on({
      'resize.ensembl': function (e) {
        if (window.name.match(/^popup_/)) {
          return false;
        }

        // jquery ui resizable events cause window.resize to fire (all events bubble to window)
        // if target has no tagName it is window or document. Don't resize unless this is the case
        if (!e.target.tagName) {
          var width = Ensembl.width;

          if (Ensembl.dynamicWidth) {
            Ensembl.setWidth(undefined, true);
          }

          Ensembl.EventManager.trigger('windowResize');

          if (Ensembl.dynamicWidth && Ensembl.width !== width) {
            Ensembl.LayoutManager.changeWidth();
            Ensembl.EventManager.trigger('imageResize');
          }
        }
      },
      'hashchange.ensembl': $.proxy(this.popState, this),
      'popstate.ensembl'  : $.proxy(this.popState, this)
    });

    var userMessage = unescape(Ensembl.cookie.get('user_message'));

    if (userMessage) {
      userMessage = userMessage.split('\n');

      $([
        '
',
        '
', userMessage[0], '
',
        '
', userMessage[1], '
',
        '
'
      ].join('')).prependTo('#main').find('h3 img, a').on('click', function () {
        $(this).parents('div.hint').remove();
        Ensembl.cookie.set('user_message', '');
      });
    }
  },

  reloadPage: function (args, url) {
    if (typeof args === 'string') {
      Ensembl.EventManager.triggerSpecific('updatePanel', args);
    } else if (typeof args === 'object') {
      for (var i in args) {
        Ensembl.EventManager.triggerSpecific('updatePanel', i);
      }
    } else {
      return Ensembl.redirect(url);
    }

    $('#messages').hide();
  },

  validateForms: function (context) {
    $('form._check', context).validate().on('submit', function () {
      var form = $(this);

      if (form.parents('#modal_panel').length) {
        var panels = form.parents('.js_panel').map(function () { return this.id; }).toArray();
        var rtn;

        while (panels.length && typeof rtn === 'undefined') {
          rtn = Ensembl.EventManager.triggerSpecific('modalFormSubmit', panels.shift(), form);
        }

        return rtn;
      }
    });
  },

  makeZMenu: function (id, params) {
    if (!$('#' + id).length) {
      $([
        '
',
        ' ',
        '
',
        '
',
        '

',
        '
',
        '
',
        '

',
        '
',
        '

',
        '
',
        '
'
      ].join('')).draggable({ handle: 'thead' }).appendTo('body');
    }

    Ensembl.EventManager.trigger('addPanel', id, 'ZMenu', undefined, undefined, params, 'showExistingZMenu');
  },

  relocateTools: function (tools) {
    var toolButtons = $('#page_nav .tool_buttons');

    tools.each(function () {
      var a        = $(this).find('a');
      var existing = $('.additional .' + a[0].className.replace(' ', '.'), toolButtons);

      if (existing.length) {
        existing.replaceWith(a);
      } else {
        $(this).children().addClass('additional').appendTo(toolButtons).not('.hidden').show();
      }

      a = existing = null;
    }).remove();

    $('a.seq_blast', toolButtons).on('click', function () {
      $('form.seq_blast', toolButtons).submit();
      return false;
    });
  },

  popState: function () {
    if (
      Ensembl.historyReady && // stops popState executing on initial page load in Chrome. This value is set to true in Ensembl.updateLocation
      // there is an r param in the hash/search EXCEPT WHEN the browser supports history API, and there is a hash which doesn't have an r param (ajax added content)
      ((window.location[Ensembl.locationURL].match(Ensembl.locationMatch) && !(Ensembl.locationURL === 'search' && window.location.hash && !window.location.hash.match(Ensembl.locationMatch))) ||
      (!window.location.hash && Ensembl.hash.match(Ensembl.locationMatch))) // there is no location.hash, but Ensembl.hash (previous hash value) had an r param (going back from no hash url to hash url)
    ) {
      Ensembl.setCoreParams();
      Ensembl.EventManager.trigger('hashChange', Ensembl.urlFromHash(window.location.href, true));
    }
  },

  hashChange: function (r) {
    if (!r) {
      return;
    }

    r = decodeURIComponent(r);

    var text = r.split(/\W/);
        text = text[0] + ': ' + Ensembl.thousandify(text[1]) + '-' + Ensembl.thousandify(text[2]);

    $('a:not(.constant)').attr('href', function () {
      var r;

      if (this.title === 'UCSC') {
        this.href = this.href.replace(/(&?position=)[^&]+(.?)/, '$1chr' + Ensembl.urlFromHash(this.href, true) + '$2');
      } else if (this.title === 'NCBI') {
        r = Ensembl.urlFromHash(this.href, true).split(/[:\-]/);
        this.href = this.href.replace(/(&?CHR=).+&BEG=.+&END=[^&]+(.?)/, '$1' + r[0] + '&BEG=' + r[1] + '&END=' + r[2] + '$2');
      } else {
        return Ensembl.urlFromHash(this.href);
      }
    });

    $('input[name=r]', 'form:not(#core_params)').val(r);

    $('h1.summary-heading').html(function (i, html) {
      return html.replace(/^(Chromosome ).+/, '$1' + text);
    });

    document.title = document.title.replace(/(Chromosome ).+/, '$1' + text);
  },

  toggleContent: function (rel) {
    if (rel) {
      $('a.toggle[rel="' + rel + '"]').toggleClass('open closed');
    }
  },

  changeWidth: function () {
    var modal = $('#modal_panel');
    $('.navbar, div.info, div.hint, div.warning, div.error').not('.fixed_width').not(function () { return modal.find(this).length; }).width(Ensembl.width);
    modal = null;
  }
});

<|endoftext|>


<commit_before>context('Data Control', () => {
	before(() => {
		cy.login();
		cy.visit('/app/doctype');
		return cy.window().its('frappe').then(frappe => {
			return frappe.xcall('frappe.tests.ui_test_helpers.create_doctype', {
				name: 'Test Data Control',
				fields: [
					{
						"label": "Name",
						"fieldname": "name1",
						"fieldtype": "Data",
						"options":"Name",
						"in_list_view": 1,
					},
					{
						"label": "Email-ID",
						"fieldname": "email",
						"fieldtype": "Data",
						"options":"Email",
						"in_list_view": 1,
					},
					{
						"label": "Phone No.",
						"fieldname": "phone",
						"fieldtype": "Data",
						"options":"Phone",
						"in_list_view": 1,
					},
				]
			});
		});
	});
	it('Verifying data control by inputting different patterns', () => {
		cy.new_form('Test Data Control');

		//Checking the URL for the new form of the doctype
		cy.location("pathname").should('eq', '/app/test-data-control/new-test-data-control-1');
		cy.get('.title-text').should('have.text', 'New Test Data Control');

		//Checking if the status is "Not Saved" initially
		cy.get('.indicator-pill').should('have.text', 'Not Saved');

		//Inputting data in the field
		cy.fill_field('name1', '@@###', 'Data');

		//Checking if the border color of the field changes to red
		cy.get_field('name1', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();

		//Checking for the error message
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', '@@### is not a valid Name');
		cy.reload();

		cy.fill_field('name1', 'Komal{}/!', 'Data');
		cy.get_field('name1', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', 'Komal{}/! is not a valid Name');
		cy.reload();

		cy.fill_field('name1', 'Komal', 'Data');
		cy.get_field('name1', 'Data').should('have.css', 'border', '0px none rgb(152, 161, 169)');
		cy.fill_field('email', 'komal', 'Data');
		cy.get_field('email', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', 'komal is not a valid Email Address');
		cy.reload();

		cy.fill_field('email', 'komal@test', 'Data');
		cy.get_field('email', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', 'komal@test is not a valid Email Address');
		cy.reload();

		cy.fill_field('email', 'komal@test.com', 'Data');
		cy.get_field('email', 'Data').should('have.css', 'border', '0px none rgb(152, 161, 169)');

		cy.fill_field('phone', 'komal', 'Data');
		cy.get_field('phone', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', 'komal is not a valid Phone Number');
		cy.reload();

		//Inputting the data as expected and saving the document
		cy.fill_field('name1', 'Komal', 'Data');
		cy.fill_field('email', 'komal@test.com', 'Data');
		cy.fill_field('phone', '9432380001', 'Data');
		cy.get_field('phone', 'Data').should('have.css', 'border', '0px none rgb(152, 161, 169)');
		cy.findByRole('button', {name: 'Save'}).click();

		//Checking if the fields contains the data which has been filled in
		cy.location("pathname").should('not.be', '/app/test-data-control/new-test-data-control-1');
		cy.get_field('name1').should('have.value', 'Komal');
		cy.get_field('email').should('have.value', 'komal@test.com');
		cy.get_field('phone').should('have.value', '9432380001');

		//Deleting the inserted document
		cy.visit('/app/test-data-control');
		cy.get('.list-row-checkbox').eq(0).click();
		cy.get('.actions-btn-group > .btn').contains('Actions').click();
		cy.get('.actions-btn-group > .dropdown-menu [data-label="Delete"]').click();
		cy.click_modal_primary_button('Yes');
		cy.get('.btn-modal-close').click();
	});
});<commit_msg>test: Fixed sider issues<commit_after>context('Data Control', () => {
	before(() => {
		cy.login();
		cy.visit('/app/doctype');
		return cy.window().its('frappe').then(frappe => {
			return frappe.xcall('frappe.tests.ui_test_helpers.create_doctype', {
				name: 'Test Data Control',
				fields: [
					{
						"label": "Name",
						"fieldname": "name1",
						"fieldtype": "Data",
						"options": "Name",
						"in_list_view": 1,
					},
					{
						"label": "Email-ID",
						"fieldname": "email",
						"fieldtype": "Data",
						"options": "Email",
						"in_list_view": 1,
					},
					{
						"label": "Phone No.",
						"fieldname": "phone",
						"fieldtype": "Data",
						"options": "Phone",
						"in_list_view": 1,
					},
				]
			});
		});
	});
	it('Verifying data control by inputting different patterns', () => {
		cy.new_form('Test Data Control');

		//Checking the URL for the new form of the doctype
		cy.location("pathname").should('eq', '/app/test-data-control/new-test-data-control-1');
		cy.get('.title-text').should('have.text', 'New Test Data Control');

		//Checking if the status is "Not Saved" initially
		cy.get('.indicator-pill').should('have.text', 'Not Saved');

		//Inputting data in the field
		cy.fill_field('name1', '@@###', 'Data');

		//Checking if the border color of the field changes to red
		cy.get_field('name1', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();

		//Checking for the error message
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', '@@### is not a valid Name');
		cy.reload();

		cy.fill_field('name1', 'Komal{}/!', 'Data');
		cy.get_field('name1', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', 'Komal{}/! is not a valid Name');
		cy.reload();

		cy.fill_field('name1', 'Komal', 'Data');
		cy.get_field('name1', 'Data').should('have.css', 'border', '0px none rgb(152, 161, 169)');
		cy.fill_field('email', 'komal', 'Data');
		cy.get_field('email', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', 'komal is not a valid Email Address');
		cy.reload();

		cy.fill_field('email', 'komal@test', 'Data');
		cy.get_field('email', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', 'komal@test is not a valid Email Address');
		cy.reload();

		cy.fill_field('email', 'komal@test.com', 'Data');
		cy.get_field('email', 'Data').should('have.css', 'border', '0px none rgb(152, 161, 169)');

		cy.fill_field('phone', 'komal', 'Data');
		cy.get_field('phone', 'Data').should('have.css', 'border', '1px solid rgb(236, 100, 94)');
		cy.findByRole('button', {name: 'Save'}).click();
		cy.get('.modal-title').should('have.text', 'Message');
		cy.get('.msgprint').should('have.text', 'komal is not a valid Phone Number');
		cy.reload();

		//Inputting the data as expected and saving the document
		cy.fill_field('name1', 'Komal', 'Data');
		cy.fill_field('email', 'komal@test.com', 'Data');
		cy.fill_field('phone', '9432380001', 'Data');
		cy.get_field('phone', 'Data').should('have.css', 'border', '0px none rgb(152, 161, 169)');
		cy.findByRole('button', {name: 'Save'}).click();

		//Checking if the fields contains the data which has been filled in
		cy.location("pathname").should('not.be', '/app/test-data-control/new-test-data-control-1');
		cy.get_field('name1').should('have.value', 'Komal');
		cy.get_field('email').should('have.value', 'komal@test.com');
		cy.get_field('phone').should('have.value', '9432380001');

		//Deleting the inserted document
		cy.visit('/app/test-data-control');
		cy.get('.list-row-checkbox').eq(0).click();
		cy.get('.actions-btn-group > .btn').contains('Actions').click();
		cy.get('.actions-btn-group > .dropdown-menu [data-label="Delete"]').click();
		cy.click_modal_primary_button('Yes');
		cy.get('.btn-modal-close').click();
	});
});<|endoftext|>


<commit_before>describe("editor", function() {
  beforeEach(() => {
    cy.visit("");
  });

  it(`should be able to delete data around the origin correctly
  - the cursor should be place at the origin`, () => {
    cy.selectRange(5297, 3);
    cy.deleteSelection();
    cy.contains("Caret Between Bases 5293 and 1");
    cy.contains(".ve-row-item-sequence", /^gtcttatga/);
  });
  it(`should be able to insert data around the origin correctly
  - new sequence should be inserted after the origin`, () => {
    cy.selectRange(5297, 3);
    cy.replaceSelection("aaaaaa");
    cy.contains("Selecting 6 bps from 1 to 6");
    cy.contains(".ve-row-item-sequence", /^aaaaaagtcttatga/);
    cy.selectRange(3, 5);
    cy.replaceSelection("tt");
    cy.contains("Selecting 2 bps from 3 to 4");
  });
  it(`should be able to revComp, comp selections that wrap the origin correctly
  - new sequence should be inserted after the origin`, () => {
    cy.selectRange(5297, 3);
    cy.contains("button", "Edit").click();
    cy.contains(".bp3-menu-item", /Complement Selection/).click();
    cy.contains(".ve-row-item-sequence", /gattag$/);

    cy.contains("button", "Edit").click();
    cy.contains(".bp3-menu-item", "Reverse Complement Selection").click();

    cy.contains("Selecting 6 bps from 5297 to 3");
    cy.contains(".ve-row-item-sequence", /gatcag$/);
  });
});
<commit_msg>fixing breaking test in editing spec<commit_after>describe("editor", function() {
  beforeEach(() => {
    cy.visit("");
  });

  it(`should be able to delete data around the origin correctly
  - the cursor should be place at the origin`, () => {
    cy.selectRange(5297, 3);
    cy.deleteSelection();
    cy.contains("Caret Between Bases 5293 and 1");
    cy.contains(".ve-row-item-sequence", /^gtcttatga/);
  });
  it(`should be able to insert data around the origin correctly
  - new sequence should be inserted after the origin`, () => {
    cy.selectRange(5297, 3);
    cy.replaceSelection("aaaaaa");
    cy.contains("Selecting 6 bps from 1 to 6");
    cy.contains(".ve-row-item-sequence", /^aaaaaagtcttatga/);
    cy.selectRange(3, 5);
    cy.replaceSelection("tt");
    cy.contains("Selecting 2 bps from 3 to 4");
  });
  it(`should be able to revComp, comp selections that wrap the origin correctly
  - new sequence should be inserted after the origin`, () => {
    cy.selectRange(5297, 3);
    cy.contains("button", "Edit").click();
    cy.contains(".bp3-menu-item", /Complement Selection/).click();
    cy.contains(".ve-row-item-sequence", /^ctggtcttat/);

    cy.contains("button", "Edit").click();
    cy.contains(".bp3-menu-item", "Reverse Complement Selection").click();

    cy.contains("Selecting 6 bps from 5297 to 3");
    cy.contains(".ve-row-item-sequence", /^ctagtcttatg/);
  });
});
<|endoftext|>


<commit_before>(function(jQuery) {
"use strict";

if (Echo.AppServer.Dashboard.isDefined("Echo.Apps.TopicRadar.Dashboard.InstanceList.Instance")) return;

var instance = Echo.AppServer.Dashboard.manifest("Echo.Apps.TopicRadar.Dashboard.InstanceList.Instance");

instance.inherits = Echo.Utils.getComponent("Echo.Apps.TopicRadar.Dashboard.Item");

instance.labels = {
	"removePopupHint": "Delete this application"
};

instance.config = {
	"ecl": [{
		"component": "Echo.Apps.TopicRadar.Dashboard.DashboardAdapter",
		"type": "object",
		"name": "config",
		"config": {}
	}]
};

instance.init = function() {
	this.parent();
};

instance.destroy = function() {
	this.events.publish({
		"topic": "onDestroy",
		"inherited": true,
		"data": {
			"item": this
		}
	});
};

instance.methods.getECL = function() {
	var ecl = this.config.get("ecl");
	var dashboard = this.get("data.app.dashboard");
	var rootDashboard = $.extend(true, {}, this.config.get("dashboard"), {});

	// TODO display message if dashboard is not defined
	if (!dashboard) {
		return [];
	}
	$.each({
		"data.instance.config": this.get("data.config", {}),
		"data.app": this.get("data.app", {}),
		"data.instance.name": Echo.Utils.get(rootDashboard, "data.instance.name") + "-" + this.get("data.id"),
		"meta": {}
	}, function(key, value) {
		Echo.Utils.set(rootDashboard, key, value);
	});
	// TODO get rid of this (use placeholders)
	ecl[0].config = {
		"component": dashboard.component,
		"url": this.substitute({"template": dashboard.script}),
		"dashboard": {
			"component": dashboard.component,
			"url": this.substitute({"template": dashboard.script}),
			"config": $.extend(true, {}, rootDashboard, dashboard.config)
		}
	};
	return ecl;
};

instance.methods.value = function() {
	return {
		"id": this.get("data.id"),
		"component": this.get("data.app.clientWidget.component"),
		"script": this.get("data.app.clientWidget.script"),
		"scripts": this.get("data.app.clientWidget.scripts"),
		"config": this.get("data.config")
	};
};

Echo.AppServer.Dashboard.create(instance);

})(Echo.jQuery);
<commit_msg>Support for placeholders in dashboard config (BC code)<commit_after>(function(jQuery) {
"use strict";

if (Echo.AppServer.Dashboard.isDefined("Echo.Apps.TopicRadar.Dashboard.InstanceList.Instance")) return;

var instance = Echo.AppServer.Dashboard.manifest("Echo.Apps.TopicRadar.Dashboard.InstanceList.Instance");

instance.inherits = Echo.Utils.getComponent("Echo.Apps.TopicRadar.Dashboard.Item");

instance.labels = {
	"removePopupHint": "Delete this application"
};

instance.config = {
	"ecl": [{
		"component": "Echo.Apps.TopicRadar.Dashboard.DashboardAdapter",
		"type": "object",
		"name": "config",
		"config": {}
	}]
};

instance.init = function() {
	this._normalizeDashboardConfig($.proxy(this.parent, this));
};

instance.destroy = function() {
	this.events.publish({
		"topic": "onDestroy",
		"inherited": true,
		"data": {
			"item": this
		}
	});
};

instance.methods.getECL = function() {
	var ecl = this.config.get("ecl");
	var dashboard = this.get("data.app.dashboard");
	var rootDashboard = $.extend(true, {}, this.config.get("dashboard"), {});

	// TODO display message if dashboard is not defined
	if (!dashboard) {
		return [];
	}
	$.each({
		"data.instance.config": this.get("data.config", {}),
		"data.app": this.get("data.app", {}),
		"data.instance.name": Echo.Utils.get(rootDashboard, "data.instance.name") + "-" + this.get("data.id"),
		"meta": {}
	}, function(key, value) {
		Echo.Utils.set(rootDashboard, key, value);
	});
	// TODO get rid of this (use placeholders)
	ecl[0].config = {
		"component": dashboard.component,
		"url": this.substitute({"template": dashboard.script}),
		"dashboard": {
			"component": dashboard.component,
			"url": this.substitute({"template": dashboard.script}),
			"config": $.extend(true, {}, rootDashboard, dashboard.config)
		}
	};
	return ecl;
};

instance.methods.value = function() {
	return {
		"id": this.get("data.id"),
		"component": this.get("data.app.clientWidget.component"),
		"script": this.get("data.app.clientWidget.script"),
		"scripts": this.get("data.app.clientWidget.scripts"),
		"config": this.get("data.config")
	};
};

// TODO this method takes dashboard config from database & replace placeholders with the data.
// This method was added for backward compatible (for 'live-qa' app in particular)
// and should be removed in the future (apps should use dashboard contract instead of config placeholders).
instance.methods._normalizeDashboardConfig = function(callback) {
	var self = this;
	var dashboardConfig = $.extend(true, {}, this.get("data.app.dashboard.config"), {
		"customerId": this.config.get("dashboard.data.customer.id")
	});
	Echo.AppServer.Dashboard.normalizeConfig(dashboardConfig, function(normalizedConfig) {

		var prepareConfig = function(config, data) {
			var subs = {
				"{data:instance}": function() {
					return data.instance;
				}
			};
			return $.extend(true, {}, config, Echo.AppServer.Utils.traverse(config, {}, function(value, acc, key) {
				if (subs[value]) {
					Echo.Utils.set(acc, key, subs[value]());
				}
			}));
		};

		var instance = self.config.get("dashboard.data.instance", {});
		self.set("data.app.dashboard.config", prepareConfig(normalizedConfig, {
			"instance": $.extend(true, {}, instance, {
				"name": instance.name + self.get("data.id")
			})
		}));
		callback && callback();
	});
};

Echo.AppServer.Dashboard.create(instance);

})(Echo.jQuery);
<|endoftext|>


<commit_before>#! /usr/bin/env node

'use strict'

const minimist = require('minimist')
const fs = require('fs')
const path = require('path')
const help = fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf8')
const run = require('./lib/run')
const track = require('./lib/progressTracker')

module.exports = run
module.exports.track = track

module.exports.start = start
module.exports.parseArguments = parseArguments

function parseArguments (argvs) {
  const argv = minimist(argvs, {
    boolean: ['json', 'n', 'help', 'renderLatencyTable', 'renderProgressBar', 'forever', 'idReplacement'],
    alias: {
      connections: 'c',
      pipelining: 'p',
      timeout: 't',
      duration: 'd',
      amount: 'a',
      json: 'j',
      renderLatencyTable: ['l', 'latency'],
      method: 'm',
      headers: ['H', 'header'],
      body: 'b',
      bailout: 'B',
      input: 'i',
      maxConnectionRequests: 'M',
      maxOverallRequests: 'O',
      connectionRate: 'r',
      overallRate: 'R',
      reconnectRate: 'D',
      renderProgressBar: 'progress',
      title: 'T',
      version: 'v',
      forever: 'f',
      idReplacement: 'I',
      help: 'h'
    },
    default: {
      connections: 10,
      timeout: 10,
      pipelining: 1,
      duration: 10,
      reconnectRate: 0,
      renderLatencyTable: false,
      renderProgressBar: true,
      json: false,
      forever: false,
      method: 'GET',
      idReplacement: false
    }
  })

  argv.url = argv._[0]

  // support -n to disable the progress bar and results table
  if (argv.n) {
    argv.renderProgressBar = false
    argv.renderResultsTable = false
  }

  if (argv.version) {
    console.log('autocannon', 'v' + require('./package').version)
    console.log('node', process.version)
    return
  }

  if (!argv.url || argv.help) {
    console.error(help)
    return
  }

  if (argv.input) {
    argv.body = fs.readFileSync(argv.input)
  }

  if (argv.headers) {
    if (!Array.isArray(argv.headers)) {
      argv.headers = [argv.headers]
    }

    argv.headers = argv.headers.reduce((obj, header) => {
      const index = header.indexOf('=')
      obj[header.slice(0, index)] = header.slice(index + 1)
      return obj
    }, {})
  }

  return argv
}

function start (argv) {
  const tracker = run(argv)

  tracker.on('done', (result) => {
    if (argv.json) {
      console.log(JSON.stringify(result))
    }
  })

  tracker.on('error', (err) => {
    if (err) {
      throw err
    }
  })

  // if not rendering json, or if std isn't a tty, track progress
  if (!argv.json || !process.stdout.isTTY) track(tracker, argv)

  process.once('SIGINT', () => {
    tracker.stop()
  })
}

if (require.main === module) {
  start(parseArguments(process.argv.slice(2)))
}
<commit_msg>Fixes #105.<commit_after>#! /usr/bin/env node

'use strict'

const minimist = require('minimist')
const fs = require('fs')
const path = require('path')
const help = fs.readFileSync(path.join(__dirname, 'help.txt'), 'utf8')
const run = require('./lib/run')
const track = require('./lib/progressTracker')

module.exports = run
module.exports.track = track

module.exports.start = start
module.exports.parseArguments = parseArguments

function parseArguments (argvs) {
  const argv = minimist(argvs, {
    boolean: ['json', 'n', 'help', 'renderLatencyTable', 'renderProgressBar', 'forever', 'idReplacement'],
    alias: {
      connections: 'c',
      pipelining: 'p',
      timeout: 't',
      duration: 'd',
      amount: 'a',
      json: 'j',
      renderLatencyTable: ['l', 'latency'],
      method: 'm',
      headers: ['H', 'header'],
      body: 'b',
      bailout: 'B',
      input: 'i',
      maxConnectionRequests: 'M',
      maxOverallRequests: 'O',
      connectionRate: 'r',
      overallRate: 'R',
      reconnectRate: 'D',
      renderProgressBar: 'progress',
      title: 'T',
      version: 'v',
      forever: 'f',
      idReplacement: 'I',
      help: 'h'
    },
    default: {
      connections: 10,
      timeout: 10,
      pipelining: 1,
      duration: 10,
      reconnectRate: 0,
      renderLatencyTable: false,
      renderProgressBar: true,
      json: false,
      forever: false,
      method: 'GET',
      idReplacement: false
    }
  })

  argv.url = argv._[0]

  // support -n to disable the progress bar and results table
  if (argv.n) {
    argv.renderProgressBar = false
    argv.renderResultsTable = false
  }

  if (argv.version) {
    console.log('autocannon', 'v' + require('./package').version)
    console.log('node', process.version)
    return
  }

  if (!argv.url || argv.help) {
    console.error(help)
    return
  }

  if (argv.input) {
    argv.body = fs.readFileSync(argv.input)
  }

  if (argv.headers) {
    if (!Array.isArray(argv.headers)) {
      argv.headers = [argv.headers]
    }

    argv.headers = argv.headers.reduce((obj, header) => {
      const index = header.indexOf('=')
      obj[header.slice(0, index)] = header.slice(index + 1)
      return obj
    }, {})
  }

  return argv
}

function start (argv) {
  if (!argv) {
    // we are printing the help
    return
  }

  const tracker = run(argv)

  tracker.on('done', (result) => {
    if (argv.json) {
      console.log(JSON.stringify(result))
    }
  })

  tracker.on('error', (err) => {
    if (err) {
      throw err
    }
  })

  // if not rendering json, or if std isn't a tty, track progress
  if (!argv.json || !process.stdout.isTTY) track(tracker, argv)

  process.once('SIGINT', () => {
    tracker.stop()
  })
}

if (require.main === module) {
  start(parseArguments(process.argv.slice(2)))
}
<|endoftext|>


<commit_before>var chai = require("chai");
chai.Should();
chai.use(require('chai-things'));

describe('127250 Heading', function () {
  it('Magnetic sentence converts', function () {
    var tree = require("../n2kMapper.js").toNested(
      JSON.parse('{"timestamp":"2013-10-08-15:47:28.263","prio":"2","src":"204","dst":"255","pgn":"127250","description":"Vessel Heading","fields":{"Heading":"129.7","Reference":"Magnetic"}}'));
    tree.should.have.with.deep.property('navigation.headingMagnetic.value', 129.7);
  });

  it('Variation sentence converts', function () {
    var tree = require("../n2kMapper.js").toNested(
      JSON.parse('{"timestamp":"2013-10-08-15:47:28.264","prio":"2","src":"1","dst":"255","pgn":"127250","description":"Vessel Heading","fields":{"SID":"68","Variation":"8.0","Reference":"True"}}'));
    tree.should.have.with.deep.property('navigation.magneticVariation.value', 8);
  });
});

<commit_msg>Add test for 27250 Heading<commit_after>var chai = require("chai");
chai.Should();
chai.use(require('chai-things'));
chai.use(require('signalk-schema').chaiModule);

describe('127250 Heading', function () {
  it('Magnetic sentence converts', function () {
    var tree = require("../n2kMapper.js").toNested(
      JSON.parse('{"timestamp":"2013-10-08-15:47:28.263","prio":"2","src":"204","dst":"255","pgn":"127250","description":"Vessel Heading","fields":{"Heading":"129.7","Reference":"Magnetic"}}'));
    tree.should.have.with.deep.property('navigation.headingMagnetic.value', 129.7);
    tree.should.be.validSignalK;
  });

  it('Variation sentence converts', function () {
    var tree = require("../n2kMapper.js").toNested(
      JSON.parse('{"timestamp":"2013-10-08-15:47:28.264","prio":"2","src":"1","dst":"255","pgn":"127250","description":"Vessel Heading","fields":{"SID":"68","Variation":"8.0","Reference":"True"}}'));
    tree.should.have.with.deep.property('navigation.magneticVariation.value', 8);
    tree.should.be.validSignalK;
  });
});

<|endoftext|>


<commit_before>/**
    For conditions of distribution and use, see copyright notice in LICENSE

    MenuBar.js - Implements basic menu bar for accessing common Tundra functionality and UIs.

    NOTE: Clears any existing menus in the menu bar so make sure that this script
    is loaded first, or replace with another implementation*/

// Widget for showing instructions if user starts Tundra without any scene.
var sceneInstructions = null;

function SizeOf(obj)
{
    var size = 0, key;
    for(key in obj)
        if (obj.hasOwnProperty(key))
            ++size;
    return size;
};

// Applicable only in headful mode.
if (!framework.IsHeadless())
{
    engine.ImportExtension("qt.core");
    engine.ImportExtension("qt.gui");

    // Use absolute paths for rel image files so they always work!
    var installDir = QDir.fromNativeSeparators(application.installationDirectory);

    // Get the menubar
    var menu = ui.MainWindow().menuBar();
    menu.clear();

    // File menu
    var fileMenu = menu.addMenu("&File");
    fileMenu.addAction("New Scene...").triggered.connect(NewScene);
    fileMenu.addAction("Open Scene...").triggered.connect(OpenScene);
    fileMenu.addSeparator();

    var screenshotAct = fileMenu.addAction("Take Screenshot");
    screenshotAct.triggered.connect(TakeScreenshot);
    screenshotAct.enabled = false;

    fileMenu.addSeparator();
    fileMenu.addAction("Clear Asset Cache").triggered.connect(ClearAssetCache);
    fileMenu.addSeparator();

    // Reconnect menu items for client only
    if (!server.IsAboutToStart())
    {
        var disconnectAction = fileMenu.addAction(new QIcon(installDir + "data/ui/images/icon/disconnect.ico"), "Disconnect");
        disconnectAction.triggered.connect(Disconnect);
        client.Connected.connect(Connected);
        client.Disconnected.connect(Disconnected);
        disconnectAction.enabled = false;
    }
    fileMenu.addAction(new QIcon(installDir + "data/ui/images/icon/system-shutdown.ico"), "Quit").triggered.connect(Quit);

    // View menu
    var viewMenu = menu.addMenu("&View");
    // Set unique object name so that other scripts can query this menu.
    toolsMenu.objectName = "ViewMenu";

    if (framework.ModuleByName("SceneStructure"))
    {
        viewMenu.addAction("Assets").triggered.connect(OpenAssetsWindow);
        viewMenu.addAction("Scene").triggered.connect(OpenSceneWindow);
        viewMenu.addAction("Key Bindings").triggered.connect(OpenKeyBindingsWindow);
    }

    var ecEditor = framework.ModuleByName("ECEditor");
    if (ecEditor)
        viewMenu.addAction("EC Editor").triggered.connect(OpenEcEditorWindow);

    // TODO: Avatar Editor menu action disabled for now, as it's not fully ready for end-users
//    if (framework.ModuleByName("Avatar"))

    if (framework.ModuleByName("DebugStats"))
        viewMenu.addAction("Profiler").triggered.connect(OpenProfilerWindow);

    toolsMenu.addAction("Show Console").triggered.connect(OpenConsoleWindow);

    // Settings menu
    if (framework.ModuleByName("MumbleVoip") || ecEditor)
    {
        var settingsMenu = menu.addMenu("&Settings");
        // Set unique object name so that other scripts can query this menu.
        settingsMenu.objectName = "SettingsMenu";

        settingsMenu.addAction("Open Config Folder").triggered.connect(OpenConfigFolder);

        if (framework.ModuleByName("MumbleVoip"))
            settingsMenu.addAction("Voice Settings").triggered.connect(OpenVoiceSettings);

        if (ecEditor)
        {
            // Gizmo
            var showGizmoAction = settingsMenu.addAction("Show Editing Gizmo");
            showGizmoAction.checkable = true;
            showGizmoAction.checked = ecEditor.gizmoEnabled;
            showGizmoAction.triggered.connect(ShowEditingGizmo);

            // Highlighting of selected entities
            var showHighlightAction = settingsMenu.addAction("Highlight Selected Entities");
            showHighlightAction.checkable = true;
            showHighlightAction.checked = ecEditor.highlightingEnabled;
            showHighlightAction.triggered.connect(HighlightSelectedEntities);
        }
    }

    // Help menu
    var helpMenu = menu.addMenu("&Help");
    var browserIcon = new QIcon(installDir + "data/ui/images/icon/browser.ico");
    helpMenu.addAction(browserIcon, "realXtend Home Page").triggered.connect(OpenHomePageUrl);
    helpMenu.addAction(browserIcon, "Developer Mailing List").triggered.connect(OpenDevMailingListUrl);
    helpMenu.addAction(browserIcon, "User Mailing List").triggered.connect(OpenMailingListUrl);
    helpMenu.addAction(browserIcon, "GitHub").triggered.connect(OpenGitHubUrl);
    // TODO Doxygen documentation not hosted anywhere currently!
//    helpMenu.addAction(browserIcon, "Developer Documentation").triggered.connect(OpenDoxygenUrl);

    function NewScene()
    {
        if (framework.Scene().MainCameraScene() != null)
        {
            var result = QMessageBox.warning(ui.MainWindow(), "New Scene", "Making a new scene will discard any changes you made to the current scene. Do you want to continue?", QMessageBox.Yes, QMessageBox.No);
            if (result == QMessageBox.No)
                return;
        }

        var fileName = QFileDialog.getSaveFileName(ui.MainWindow(), "Save New Scene As", application.currentWorkingDirectory, "Tundra TXML file (*.txml)");
        if (fileName == "")
            return;

        var sceneNumber = Math.floor(Math.random() * 10000000 + 1);
        var newScene = framework.Scene().CreateScene("Scene" + sceneNumber, true, true);
        if (newScene == null)
            return;

        var storage = asset.DeserializeAssetStorageFromString(fileName, false);
        if (!storage)
        {
            console.LogError("Failed to create asset storage for file " + fileName);
            return;
        }

        asset.SetDefaultAssetStorage(storage);

        // Give some sort of feedback (f.ex. make a skybox)
        var environment = newScene.CreateEntity(newScene.NextFreeId(), ["Name", "Sky"]);
        environment.name = "Environment";
        environment.sky.enabled = true;
    }

    function OpenScene() {
        var fileName = QFileDialog.getOpenFileName(ui.MainWindow(), "Open Scene", application.currentWorkingDirectory, "Tundra TXML file (*.txml)");
        if (fileName == "")
            return;

        if (framework.Scene().MainCameraScene() != null)
        {
            var result = QMessageBox.warning(ui.MainWindow(), "Open Scene", "Opening a new scene will discard any changes you made to the current scene. Do you want to continue?", QMessageBox.Yes, QMessageBox.No);
            if (result == QMessageBox.No)
                return;
        }

        var sceneNumber = Math.floor(Math.random() * 10000000 + 1);
        var openedScene = framework.Scene().CreateScene("Scene" + sceneNumber, true, true);
        if (openedScene == null)
            return;
        var openedStorage = asset.DeserializeAssetStorageFromString(fileName, false);
        if (openedStorage != null)
            asset.SetDefaultAssetStorage(openedStorage);

        openedScene.LoadSceneXML(fileName, true, false, 0);

    }

    function Reconnect() {
        client.Reconnect();
    }

    function Disconnect() {
        client.Logout();
    }

    function Connected() {
        disconnectAction.enabled = true;
        screenshotAct.enabled = true;
    }

    function Disconnected() {
        disconnectAction.enabled = false;
        screenshotAct.enabled = false;
    }

    function Quit() {
        framework.Exit();
    }

    function TakeScreenshot() {
        var mainCamera = renderer.MainCameraComponent();
        var imgPath = mainCamera.SaveScreenshot();
        QDesktopServices.openUrl(new QUrl(imgPath));
    }

    function ClearAssetCache() {
        // Show some additional info: count and size of removed files
        var cachePath = asset.Cache().CacheDirectory();
        if (cachePath != "" && cachePath != null)
        {
            var count = 0;
            var size = 0;

            var cacheDir = new QDir(cachePath);
            var cacheFiles = cacheDir.entryInfoList();  // Using flags here would be nice but does not seem to work
            for(var i=0; i<cacheFiles.length; ++i)
            {
                try
                {
                    if (cacheFiles[i].isFile() && cacheFiles[i].exists())
                    {
                        count++;
                        size += cacheFiles[i].size();
                    }
                }
                catch(e)
                {
                    console.LogError("Failed to iterate files in cache: " + e);
                    count = null;
                    size = null;
                    break;
                }
            }

            // Clear the cache. If we happen to throw here we wont show false log/ui information.
            asset.Cache().ClearAssetCache();

            // Log to console
            var msg = "";
            if (count != null && size != null)
            {
                // Round to two decimals
                var roundedSize = Math.round(((size/1024)/1024) * Math.pow(10,2)) / Math.pow(10,2);
                msg = "Cleared " + count + " files with total size of " + roundedSize + " mb from asset cache."
            }
            else
                msg = "Errors occurred while calculating cache file information. Cache cleared.";
            console.LogInfo(msg);

            // Show information box for user. Note: this will block so not the most convenient.
            if (ui.MainWindow() != null)
                QMessageBox.information(ui.MainWindow(), "Cache Cleared", msg);
        }
    }

    function OpenDevMailingListUrl()
    {
        QDesktopServices.openUrl(new QUrl("http://groups.google.com/group/realxtend-dev/"));
    }

    function OpenMailingListUrl()
    {
        QDesktopServices.openUrl(new QUrl("http://groups.google.com/group/realxtend/"));
    }

    function OpenHomePageUrl() {
        QDesktopServices.openUrl(new QUrl("http://realxtend.org/"));
    }

    function OpenGitHubUrl() {
        QDesktopServices.openUrl(new QUrl("https://github.com/realxtend/naali/"));
    }

    function OpenDoxygenUrl()
    {
        // TODO host doxygen-generated documentation somewhere!
        QDesktopServices.openUrl(new QUrl("http://www.realxtend.org/doxygen/"));
    }

    function OpenSceneWindow() {
        framework.ModuleByName("SceneStructure").ToggleSceneStructureWindow();
    }

    function OpenAssetsWindow() {
        framework.ModuleByName("SceneStructure").ToggleAssetsWindow();
    }

    function OpenKeyBindingsWindow() {
        framework.ModuleByName("SceneStructure").ToggleKeyBindingsWindow();
    }

    function OpenProfilerWindow() {
        framework.ModuleByName("DebugStats").ShowProfilerWindow();
    }

    function OpenVoiceSettings() {
        framework.ModuleByName("MumbleVoip").ToggleSettingsWidget();
    }

    function OpenConsoleWindow() {
        framework.GetModuleByName("Console").ToggleConsole();
    }

    function OpenEcEditorWindow() {
        framework.ModuleByName("ECEditor").ShowEditorWindow();
    }

    function OpenAvatarEditorWindow() {
        framework.ModuleByName("Avatar").ToggleAvatarEditorWindow();
        if (client.IsConnected())
           framework.ModuleByName("Avatar").EditAvatar("Avatar" + client.connectionId)
   }

    function ShowEditingGizmo(show) {
        framework.ModuleByName("ECEditor").gizmoEnabled = show;
    }

    function HighlightSelectedEntities(show) {
        framework.ModuleByName("ECEditor").highlightingEnabled = show;
    }

    function OpenConfigFolder() {
        QDesktopServices.openUrl(new QUrl(config.ConfigFolder()));
    }
}
<commit_msg>MenuBar.js: create asset storage when OpenScene is used. This was already done in the rex repo (https://github.com/realXtend/naali/commit/76de3bef5f17c919f39d07c3d2cf8a28b2ef5c49), but apparently lost in the merge.<commit_after>/**
    For conditions of distribution and use, see copyright notice in LICENSE

    MenuBar.js - Implements basic menu bar for accessing common Tundra functionality and UIs.

    NOTE: Clears any existing menus in the menu bar so make sure that this script
    is loaded first, or replace with another implementation*/

// Widget for showing instructions if user starts Tundra without any scene.
var sceneInstructions = null;

function SizeOf(obj)
{
    var size = 0, key;
    for(key in obj)
        if (obj.hasOwnProperty(key))
            ++size;
    return size;
};

// Applicable only in headful mode.
if (!framework.IsHeadless())
{
    engine.ImportExtension("qt.core");
    engine.ImportExtension("qt.gui");

    // Use absolute paths for rel image files so they always work!
    var installDir = QDir.fromNativeSeparators(application.installationDirectory);

    // Get the menubar
    var menu = ui.MainWindow().menuBar();
    menu.clear();

    // File menu
    var fileMenu = menu.addMenu("&File");
    fileMenu.addAction("New Scene...").triggered.connect(NewScene);
    fileMenu.addAction("Open Scene...").triggered.connect(OpenScene);
    fileMenu.addSeparator();

    var screenshotAct = fileMenu.addAction("Take Screenshot");
    screenshotAct.triggered.connect(TakeScreenshot);
    screenshotAct.enabled = false;

    fileMenu.addSeparator();
    fileMenu.addAction("Clear Asset Cache").triggered.connect(ClearAssetCache);
    fileMenu.addSeparator();

    // Reconnect menu items for client only
    if (!server.IsAboutToStart())
    {
        var disconnectAction = fileMenu.addAction(new QIcon(installDir + "data/ui/images/icon/disconnect.ico"), "Disconnect");
        disconnectAction.triggered.connect(Disconnect);
        client.Connected.connect(Connected);
        client.Disconnected.connect(Disconnected);
        disconnectAction.enabled = false;
    }
    fileMenu.addAction(new QIcon(installDir + "data/ui/images/icon/system-shutdown.ico"), "Quit").triggered.connect(Quit);

    // View menu
    var viewMenu = menu.addMenu("&View");
    // Set unique object name so that other scripts can query this menu.
    toolsMenu.objectName = "ViewMenu";

    if (framework.ModuleByName("SceneStructure"))
    {
        viewMenu.addAction("Assets").triggered.connect(OpenAssetsWindow);
        viewMenu.addAction("Scene").triggered.connect(OpenSceneWindow);
        viewMenu.addAction("Key Bindings").triggered.connect(OpenKeyBindingsWindow);
    }

    var ecEditor = framework.ModuleByName("ECEditor");
    if (ecEditor)
        viewMenu.addAction("EC Editor").triggered.connect(OpenEcEditorWindow);

    // TODO: Avatar Editor menu action disabled for now, as it's not fully ready for end-users
//    if (framework.ModuleByName("Avatar"))

    if (framework.ModuleByName("DebugStats"))
        viewMenu.addAction("Profiler").triggered.connect(OpenProfilerWindow);

    toolsMenu.addAction("Show Console").triggered.connect(OpenConsoleWindow);

    // Settings menu
    if (framework.ModuleByName("MumbleVoip") || ecEditor)
    {
        var settingsMenu = menu.addMenu("&Settings");
        // Set unique object name so that other scripts can query this menu.
        settingsMenu.objectName = "SettingsMenu";

        settingsMenu.addAction("Open Config Folder").triggered.connect(OpenConfigFolder);

        if (framework.ModuleByName("MumbleVoip"))
            settingsMenu.addAction("Voice Settings").triggered.connect(OpenVoiceSettings);

        if (ecEditor)
        {
            // Gizmo
            var showGizmoAction = settingsMenu.addAction("Show Editing Gizmo");
            showGizmoAction.checkable = true;
            showGizmoAction.checked = ecEditor.gizmoEnabled;
            showGizmoAction.triggered.connect(ShowEditingGizmo);

            // Highlighting of selected entities
            var showHighlightAction = settingsMenu.addAction("Highlight Selected Entities");
            showHighlightAction.checkable = true;
            showHighlightAction.checked = ecEditor.highlightingEnabled;
            showHighlightAction.triggered.connect(HighlightSelectedEntities);
        }
    }

    // Help menu
    var helpMenu = menu.addMenu("&Help");
    var browserIcon = new QIcon(installDir + "data/ui/images/icon/browser.ico");
    helpMenu.addAction(browserIcon, "realXtend Home Page").triggered.connect(OpenHomePageUrl);
    helpMenu.addAction(browserIcon, "Developer Mailing List").triggered.connect(OpenDevMailingListUrl);
    helpMenu.addAction(browserIcon, "User Mailing List").triggered.connect(OpenMailingListUrl);
    helpMenu.addAction(browserIcon, "GitHub").triggered.connect(OpenGitHubUrl);
    // TODO Doxygen documentation not hosted anywhere currently!
//    helpMenu.addAction(browserIcon, "Developer Documentation").triggered.connect(OpenDoxygenUrl);

    function NewScene()
    {
        if (framework.Scene().MainCameraScene() != null)
        {
            var result = QMessageBox.warning(ui.MainWindow(), "New Scene", "Making a new scene will discard any changes you made to the current scene. Do you want to continue?", QMessageBox.Yes, QMessageBox.No);
            if (result == QMessageBox.No)
                return;
        }

        var fileName = QFileDialog.getSaveFileName(ui.MainWindow(), "Save New Scene As", application.currentWorkingDirectory, "Tundra TXML file (*.txml)");
        if (fileName == "")
            return;

        var sceneNumber = Math.floor(Math.random() * 10000000 + 1);
        var newScene = framework.Scene().CreateScene("Scene" + sceneNumber, true, true);
        if (newScene == null)
            return;

        var storage = asset.DeserializeAssetStorageFromString(fileName, false);
        if (!storage)
        {
            console.LogError("Failed to create asset storage for file " + fileName);
            return;
        }

        asset.SetDefaultAssetStorage(storage);

        // Give some sort of feedback (f.ex. make a skybox)
        var environment = newScene.CreateEntity(newScene.NextFreeId(), ["Name", "Sky"]);
        environment.name = "Environment";
        environment.sky.enabled = true;
    }

    function OpenScene()
    {
        var fileName = QFileDialog.getOpenFileName(ui.MainWindow(), "Open Scene", application.currentWorkingDirectory, "Tundra TXML file (*.txml)");
        if (fileName == "")
            return;

        if (framework.Scene().MainCameraScene() != null)
        {
            var result = QMessageBox.warning(ui.MainWindow(), "Open Scene", "Opening a new scene will discard any changes you made to the current scene. Do you want to continue?", QMessageBox.Yes, QMessageBox.No);
            if (result == QMessageBox.No)
                return;
        }

        var sceneNumber = Math.floor(Math.random() * 10000000 + 1);
        var openedScene = framework.Scene().CreateScene("Scene" + sceneNumber, true, true);
        if (openedScene == null)
            return;
        var openedStorage = asset.DeserializeAssetStorageFromString(fileName, false);
        if (openedStorage != null)
            asset.SetDefaultAssetStorage(openedStorage);

        var storage = asset.DeserializeAssetStorageFromString(fileName, false);
        if (!storage)
        {
            console.LogError("Failed to create asset storage for file " + fileName);
            return;
        }

        asset.SetDefaultAssetStorage(storage);

        openedScene.LoadSceneXML(fileName, true, false, 0);

    }

    function Reconnect() {
        client.Reconnect();
    }

    function Disconnect() {
        client.Logout();
    }

    function Connected() {
        disconnectAction.enabled = true;
        screenshotAct.enabled = true;
    }

    function Disconnected() {
        disconnectAction.enabled = false;
        screenshotAct.enabled = false;
    }

    function Quit() {
        framework.Exit();
    }

    function TakeScreenshot() {
        var mainCamera = renderer.MainCameraComponent();
        var imgPath = mainCamera.SaveScreenshot();
        QDesktopServices.openUrl(new QUrl(imgPath));
    }

    function ClearAssetCache() {
        // Show some additional info: count and size of removed files
        var cachePath = asset.Cache().CacheDirectory();
        if (cachePath != "" && cachePath != null)
        {
            var count = 0;
            var size = 0;

            var cacheDir = new QDir(cachePath);
            var cacheFiles = cacheDir.entryInfoList();  // Using flags here would be nice but does not seem to work
            for(var i=0; i<cacheFiles.length; ++i)
            {
                try
                {
                    if (cacheFiles[i].isFile() && cacheFiles[i].exists())
                    {
                        count++;
                        size += cacheFiles[i].size();
                    }
                }
                catch(e)
                {
                    console.LogError("Failed to iterate files in cache: " + e);
                    count = null;
                    size = null;
                    break;
                }
            }

            // Clear the cache. If we happen to throw here we wont show false log/ui information.
            asset.Cache().ClearAssetCache();

            // Log to console
            var msg = "";
            if (count != null && size != null)
            {
                // Round to two decimals
                var roundedSize = Math.round(((size/1024)/1024) * Math.pow(10,2)) / Math.pow(10,2);
                msg = "Cleared " + count + " files with total size of " + roundedSize + " mb from asset cache."
            }
            else
                msg = "Errors occurred while calculating cache file information. Cache cleared.";
            console.LogInfo(msg);

            // Show information box for user. Note: this will block so not the most convenient.
            if (ui.MainWindow() != null)
                QMessageBox.information(ui.MainWindow(), "Cache Cleared", msg);
        }
    }

    function OpenDevMailingListUrl()
    {
        QDesktopServices.openUrl(new QUrl("http://groups.google.com/group/realxtend-dev/"));
    }

    function OpenMailingListUrl()
    {
        QDesktopServices.openUrl(new QUrl("http://groups.google.com/group/realxtend/"));
    }

    function OpenHomePageUrl() {
        QDesktopServices.openUrl(new QUrl("http://realxtend.org/"));
    }

    function OpenGitHubUrl() {
        QDesktopServices.openUrl(new QUrl("https://github.com/realxtend/naali/"));
    }

    function OpenDoxygenUrl()
    {
        // TODO host doxygen-generated documentation somewhere!
        QDesktopServices.openUrl(new QUrl("http://www.realxtend.org/doxygen/"));
    }

    function OpenSceneWindow() {
        framework.ModuleByName("SceneStructure").ToggleSceneStructureWindow();
    }

    function OpenAssetsWindow() {
        framework.ModuleByName("SceneStructure").ToggleAssetsWindow();
    }

    function OpenKeyBindingsWindow() {
        framework.ModuleByName("SceneStructure").ToggleKeyBindingsWindow();
    }

    function OpenProfilerWindow() {
        framework.ModuleByName("DebugStats").ShowProfilerWindow();
    }

    function OpenVoiceSettings() {
        framework.ModuleByName("MumbleVoip").ToggleSettingsWidget();
    }

    function OpenConsoleWindow() {
        framework.GetModuleByName("Console").ToggleConsole();
    }

    function OpenEcEditorWindow() {
        framework.ModuleByName("ECEditor").ShowEditorWindow();
    }

    function OpenAvatarEditorWindow() {
        framework.ModuleByName("Avatar").ToggleAvatarEditorWindow();
        if (client.IsConnected())
           framework.ModuleByName("Avatar").EditAvatar("Avatar" + client.connectionId)
   }

    function ShowEditingGizmo(show) {
        framework.ModuleByName("ECEditor").gizmoEnabled = show;
    }

    function HighlightSelectedEntities(show) {
        framework.ModuleByName("ECEditor").highlightingEnabled = show;
    }

    function OpenConfigFolder() {
        QDesktopServices.openUrl(new QUrl(config.ConfigFolder()));
    }
}
<|endoftext|>


<commit_before>var mysql = require('mysql');
var moQuery = require('mongo-sql');
var Promise = require("bluebird");
var using = Promise.using;

Promise.promisifyAll(mysql);
Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);

var conf = require('./conf');

var pools = {};
pools.db = mysql.createPool(conf.mysql);

function prepQuery(spec) {
  var query = moQuery.sql(spec);

  return {
    stmt: query.toString().replace(/\$\d+/g, '?').replace(/"/g, ''),
    values: query.values
  };
};
<commit_msg>mysql db connect and rollback code<commit_after>var mysql = require('mysql');
var moQuery = require('mongo-sql');
var Promise = require("bluebird");
var using = Promise.using;

Promise.promisifyAll(mysql);
Promise.promisifyAll(require("mysql/lib/Connection").prototype);
Promise.promisifyAll(require("mysql/lib/Pool").prototype);

var conf = require('./conf');

var pools = {};
pools.db = mysql.createPool(conf.mysql);

function buildQuery(spec) {
  var query = moQuery.sql(spec);

  return {
    stmt: query.toString().replace(/\$\d+/g, '?').replace(/"/g, ''),
    values: query.values
  };
};

function getDisposableConn(poolId) {
  return pools[poolId]
  .getConnectionAsync()
  .disposer(function(conn) {
    conn.release();
  });
};

function getTranscation(poolId) {
  return new Promise(function(resolve, reject) {
    pools[poolId || 'vrm'].getConnection(function(err, conn) {
      if(err) return reject(err);
      conn.beginTransaction(function(err) {
        return err ? reject(err) : resolve(conn);
      });
    });
  })
  .disposer(function(conn, promise) {
    if(promise.isFulfilled()) {
      return conn.commitAsync().finally(release);
    }
    else {
      return conn.rollbackAsync().finally(release);
    }

    function release() {
      conn.release();
    }
  });
};

function execute(spec, conn) {
  var query = buildQuery(spec);

  function _queryWithConn(cn) {
    return cn.queryAsync(query.stmt, query.values);
  }
  return conn && 'string' !== typeof conn
    ? _queryWithConn(conn)
    : using(getDisposableConn(conn), _queryWithConn);
}

module.exports = {
  execute: execute,
  getDisposableConn: getDisposableConn,
  getTranscation: getTranscation
};<|endoftext|>


<commit_before>/* global alert:true, confirm:true */

define([
  'jquery',
  'underscore',
  'mockup-ui-url/views/base',
  'mockup-patterns-texteditor',
  'mockup-utils',
  'mockup-patterns-select2'
], function($, _, BaseView, TextEditor, utils, Select2) {
  'use strict';

  var OverridesView = BaseView.extend({
    tagName: 'div',
    className: 'tab-pane overrides',
    editing: null,
    canSave: false,

    template: _.template(
      '<form class="row">' +
        '
' +
          '<input class="select" type="hidden" placeholder="Search..." style="width: 100%" />' +
        '
' +
      '</form>' +
      '
' +
        '
' +
          '<% if(view.editing){ %>' +
            '
<%- view.editing %>
 ' +
            '
' +
              '<button class="plone-btn plone-btn-primary plone-btn-xs disabled">Save</button> ' +
              '<button class="plone-btn plone-btn-default plone-btn-xs disabled">Cancel</button>' +
              '<button class="plone-btn plone-btn-danger plone-btn-xs">Delete customizations</button>' +
            '
' +
          '<% } %>' +
          '
' +
        '
' +
      '
'),
    events: {
      'click button.plone-btn-danger': 'itemDeleted',
      'click button.plone-btn-primary': 'itemSaved',
      'click button.plone-btn-default': 'itemCancel'
    },

    initialize: function(options){
      BaseView.prototype.initialize.apply(this, [options]);
      this.tabView = options.tabView;
    },

    serializedModel: function(){
      return $.extend({}, { view: this }, this.options);
    },

    itemSaved: function(e){
      e.preventDefault();
      var that = this;
      that.tabView.saveData('save-file', {
        filepath: that.editing,
        data: that.editor.editor.getValue()
      }, function(){
        that.$el.find('.plone-btn-primary,.plone-btn-default').addClass('disabled');
      });
    },

    itemDeleted: function(e){
      e.preventDefault();
      var that = this;
      if(confirm('Are you sure you want to delete this override?')){
        that.options.data.overrides.splice(
          that.options.data.overrides.indexOf(that.editing), 1);
        that.tabView.saveData('delete-file', {
          filepath: that.editing
        }, function(){
          that.editing = null;
          that.render();
        });
      }
    },

    itemCancel: function(e){
      e.preventDefault();
      this.editing = null;
      this.render();
    },

    customizeResource: function(resource){
      if(this.options.data.overrides.indexOf(resource) === -1){
        this.options.data.overrides.push(resource);
      }
      this.editing = resource;
      this.render();
    },

    afterRender: function(){
      var that = this;
      var $select = that.$el.find('.select');
      var overrides = _.map(that.options.data.overrides, function(override){
        return {
          id: override,
          text: override,
          override: true
        };
      });
      var resources = _.flatten(_.map(that.options.data.resources, function(resource){
        var base = resource.url || '';
        if(base){
          base += '/';
        }
        var items = [];
        var url;
        if(resource.js){
          url = base + resource.js;
          if(overrides.indexOf(url) === -1){
            items.push({id: url, text: url});
          }
        }
        for(var i=0; i<resource.css.length; i=i+1){
          url = base + resource.css[i];
          if(overrides.indexOf(url) === -1){
            items.push({id: url, text: url});
          }
        }
        return items;
      }));

      var format = function(data){
        if(data.override){
          return '' + data.text + ' - customized';
        }
        return data.text;
      };
      that.select2 = new Select2($select, {
        data: overrides.concat(_.sortBy(resources, function(d){ return d.id; })),
        formatResult: format,
        formatSelection: format
      });

      $select.on('change', function(){
        that.customizeResource($select.select2('val'));
      });

      that.$editorContainer = that.$('.editor');
      if(that.editing !== null){
        var url = that.options.data.baseUrl;
        if(url[url.length - 1] !== '/'){
          url += '/';
        }
        that.tabView.loading.show();
        $.ajax({
          // cache busting url
          url: url + that.editing + '?' + utils.generateId(),
          dataType: 'text'
        }).done(function(data){
          var $pre = $('
');
          $pre.text(data);
          that.$editorContainer.empty().append($pre);
          that.editor = new TextEditor($pre, {
            width: $('.editor').width(),
            height: 500
          });
          that.editor.setSyntax(that.editing);
          that.tabView.loading.hide();
          that.editor.editor.on('change', function(){
            that.$el.find('.plone-btn-primary,.plone-btn-default').removeClass('disabled');
          });
        }).fail(function(){
          alert('error loading resource for editing');
          that.tabView.loading.hide();
        });
      }
    }
  });

  return OverridesView;
});
<commit_msg>update text<commit_after>/* global alert:true, confirm:true */

define([
  'jquery',
  'underscore',
  'mockup-ui-url/views/base',
  'mockup-patterns-texteditor',
  'mockup-utils',
  'mockup-patterns-select2'
], function($, _, BaseView, TextEditor, utils, Select2) {
  'use strict';

  var OverridesView = BaseView.extend({
    tagName: 'div',
    className: 'tab-pane overrides',
    editing: null,
    canSave: false,

    template: _.template(
      '<form class="row">' +
        '
' +
          '<input class="select" type="hidden" placeholder="Select resource to override..." style="width: 100%" />' +
        '
' +
      '</form>' +
      '
' +
        '
' +
          '<% if(view.editing){ %>' +
            '
<%- view.editing %>
 ' +
            '
' +
              '<button class="plone-btn plone-btn-primary plone-btn-xs disabled">Save</button> ' +
              '<button class="plone-btn plone-btn-default plone-btn-xs disabled">Cancel</button>' +
              '<button class="plone-btn plone-btn-danger plone-btn-xs">Delete customizations</button>' +
            '
' +
          '<% } %>' +
          '
' +
        '
' +
      '
'),
    events: {
      'click button.plone-btn-danger': 'itemDeleted',
      'click button.plone-btn-primary': 'itemSaved',
      'click button.plone-btn-default': 'itemCancel'
    },

    initialize: function(options){
      BaseView.prototype.initialize.apply(this, [options]);
      this.tabView = options.tabView;
    },

    serializedModel: function(){
      return $.extend({}, { view: this }, this.options);
    },

    itemSaved: function(e){
      e.preventDefault();
      var that = this;
      that.tabView.saveData('save-file', {
        filepath: that.editing,
        data: that.editor.editor.getValue()
      }, function(){
        that.$el.find('.plone-btn-primary,.plone-btn-default').addClass('disabled');
      });
    },

    itemDeleted: function(e){
      e.preventDefault();
      var that = this;
      if(confirm('Are you sure you want to delete this override?')){
        that.options.data.overrides.splice(
          that.options.data.overrides.indexOf(that.editing), 1);
        that.tabView.saveData('delete-file', {
          filepath: that.editing
        }, function(){
          that.editing = null;
          that.render();
        });
      }
    },

    itemCancel: function(e){
      e.preventDefault();
      this.editing = null;
      this.render();
    },

    customizeResource: function(resource){
      if(this.options.data.overrides.indexOf(resource) === -1){
        this.options.data.overrides.push(resource);
      }
      this.editing = resource;
      this.render();
    },

    afterRender: function(){
      var that = this;
      var $select = that.$el.find('.select');
      var overrides = _.map(that.options.data.overrides, function(override){
        return {
          id: override,
          text: override,
          override: true
        };
      });
      var resources = _.flatten(_.map(that.options.data.resources, function(resource){
        var base = resource.url || '';
        if(base){
          base += '/';
        }
        var items = [];
        var url;
        if(resource.js){
          url = base + resource.js;
          if(overrides.indexOf(url) === -1){
            items.push({id: url, text: url});
          }
        }
        for(var i=0; i<resource.css.length; i=i+1){
          url = base + resource.css[i];
          if(overrides.indexOf(url) === -1){
            items.push({id: url, text: url});
          }
        }
        return items;
      }));

      var format = function(data){
        if(data.override){
          return '' + data.text + ' - customized';
        }
        return data.text;
      };
      that.select2 = new Select2($select, {
        data: overrides.concat(_.sortBy(resources, function(d){ return d.id; })),
        formatResult: format,
        formatSelection: format
      });

      $select.on('change', function(){
        that.customizeResource($select.select2('val'));
      });

      that.$editorContainer = that.$('.editor');
      if(that.editing !== null){
        var url = that.options.data.baseUrl;
        if(url[url.length - 1] !== '/'){
          url += '/';
        }
        that.tabView.loading.show();
        $.ajax({
          // cache busting url
          url: url + that.editing + '?' + utils.generateId(),
          dataType: 'text'
        }).done(function(data){
          var $pre = $('
');
          $pre.text(data);
          that.$editorContainer.empty().append($pre);
          that.editor = new TextEditor($pre, {
            width: $('.editor').width(),
            height: 500
          });
          that.editor.setSyntax(that.editing);
          that.tabView.loading.hide();
          that.editor.editor.on('change', function(){
            that.$el.find('.plone-btn-primary,.plone-btn-default').removeClass('disabled');
          });
        }).fail(function(){
          alert('error loading resource for editing');
          that.tabView.loading.hide();
        });
      }
    }
  });

  return OverridesView;
});
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010-2012, Contrail consortium.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms,
 * with or without modification, are permitted provided
 * that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the
 *     above copyright notice, this list of conditions
 *     and the following disclaimer.
 *  2. Redistributions in binary form must reproduce
 *     the above copyright notice, this list of
 *     conditions and the following disclaimer in the
 *     documentation and/or other materials provided
 *     with the distribution.
 *  3. Neither the name of the Contrail consortium nor the
 *     names of its contributors may be used to endorse
 *     or promote products derived from this software
 *     without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

manifest = [];

manifest['owncloud'] = '{ "Application" : "Owncloud", "Services" : [ { "Type" : "php", "FrontendName" : "Php backend", "Archive" : "http://download.owncloud.org/community/owncloud-5.0.6.tar.bz2" }, { "Type" : "mysql", "FrontendName" : "Mysql backend" } ] }';
manifest['wordpress'] = '{ "Application" : "Wordpress", "Services" : [ { "Type" : "php", "FrontendName" : "Php backend", "Archive" : "http://wordpress.org/wordpress-3.5.1.tar.gz" }, { "Type" : "mysql", "FrontendName" : "Mysql backend" } ] }';

$(document).ready(function() {
	$('#fileForm').ajaxForm({
		dataType: 'json',
		success: function(response) {
			if (typeof response.error != 'undefined' && response.error != null) {
				alert('Error: ' + response.error);
				$('#file').val('');
				return;
			}
			alert("Manifest uploaded correctly, now it can take a while to startup everything")
			window.location = 'index.php';
		},
		error: function(response) {
			alert('#fileForm.ajaxForm() error: ' + response.error);
		}
	});

	$('input:file').change(function() {
		$('#fileForm').submit();
	});

	$('#deploy').click(function() {
		type = $('input[name=type]:checked').val();
		if (manifest[type] == '') {
			alert("There is no manifest for such an application");
			return;
		}

		$.ajax({
			type: "POST",
			url: "ajax/uploadManifest.php",
			data: { json: manifest[type] },
			dataType: 'json'
		}).done(function(response) {
			if (typeof response.error != 'undefined' && response.error != null) {
				alert('Error: ' + response.error);
				$('#file').val('');
				return;
			}
			alert("Manifest uploaded correctly, now it can take a while to startup everything")
			window.location = 'index.php';
		});

	});
});
<commit_msg>conpaas-frontend: allow to logout from manifest page<commit_after>/*
 * Copyright (c) 2010-2012, Contrail consortium.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms,
 * with or without modification, are permitted provided
 * that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the
 *     above copyright notice, this list of conditions
 *     and the following disclaimer.
 *  2. Redistributions in binary form must reproduce
 *     the above copyright notice, this list of
 *     conditions and the following disclaimer in the
 *     documentation and/or other materials provided
 *     with the distribution.
 *  3. Neither the name of the Contrail consortium nor the
 *     names of its contributors may be used to endorse
 *     or promote products derived from this software
 *     without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

manifest = [];

manifest['owncloud'] = '{ "Application" : "Owncloud", "Services" : [ { "Type" : "php", "FrontendName" : "Php backend", "Archive" : "http://download.owncloud.org/community/owncloud-5.0.6.tar.bz2" }, { "Type" : "mysql", "FrontendName" : "Mysql backend" } ] }';
manifest['wordpress'] = '{ "Application" : "Wordpress", "Services" : [ { "Type" : "php", "FrontendName" : "Php backend", "Archive" : "http://wordpress.org/wordpress-3.5.1.tar.gz" }, { "Type" : "mysql", "FrontendName" : "Mysql backend" } ] }';

$(document).ready(function() {
	$('#fileForm').ajaxForm({
		dataType: 'json',
		success: function(response) {
			if (typeof response.error != 'undefined' && response.error != null) {
				alert('Error: ' + response.error);
				$('#file').val('');
				return;
			}
			alert("Manifest uploaded correctly, now it can take a while to startup everything")
			window.location = 'index.php';
		},
		error: function(response) {
			alert('#fileForm.ajaxForm() error: ' + response.error);
		}
	});

	$('input:file').change(function() {
		$('#fileForm').submit();
	});

    $('#logout').click(function () {
        $.ajax({
                type: 'POST',
                url: 'ajax/logout.php',
                data: {}
        }).done(function () {
            window.location = 'index.php';
        });
    });

	$('#deploy').click(function() {
		type = $('input[name=type]:checked').val();
		if (manifest[type] == '') {
			alert("There is no manifest for such an application");
			return;
		}

		$.ajax({
			type: "POST",
			url: "ajax/uploadManifest.php",
			data: { json: manifest[type] },
			dataType: 'json'
		}).done(function(response) {
			if (typeof response.error != 'undefined' && response.error != null) {
				alert('Error: ' + response.error);
				$('#file').val('');
				return;
			}
			alert("Manifest uploaded correctly, now it can take a while to startup everything")
			window.location = 'index.php';
		});

	});
});
<|endoftext|>