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

!function( $ ){

  "use strict"

  var Typeahead = function ( element, options ) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.typeahead.defaults, options)
    this.matcher = this.options.matcher || this.matcher
    this.sorter = this.options.sorter || this.sorter
    this.highlighter = this.options.highlighter || this.highlighter
    this.$menu = $(this.options.menu).appendTo('body')
    this.source = this.options.source
    this.shown = false
    this.listen()
  }

  Typeahead.prototype = {

    constructor: Typeahead

  , select: function () {
      var val = this.$menu.find('.active').attr('data-value')
      this.$element.val(val)
      return this.hide()
    }

  , show: function () {
      var pos = $.extend({}, this.$element.offset(), {
        height: this.$element[0].offsetHeight
      })

      this.$menu.css({
        top: pos.top + pos.height
      , left: pos.left
      })

      this.$menu.show()
      this.shown = true
      return this
    }

  , hide: function () {
      this.$menu.hide()
      this.shown = false
      return this
    }

  , lookup: function (event) {
      var that = this
        , items
        , q

      this.query = this.$element.val()

      if (!this.query) {
        return this.shown ? this.hide() : this
      }

      items = $.grep(this.source, function (item) {
        if (that.matcher(item)) return item
      })

      items = this.sorter(items)

      if (!items.length) {
        return this.shown ? this.hide() : this
      }

      return this.render(items.slice(0, this.options.items)).show()
    }

  , matcher: function (item) {
      return ~item.toLowerCase().indexOf(this.query.toLowerCase())
    }

  , sorter: function (items) {
      var beginswith = []
        , caseSensitive = []
        , caseInsensitive = []
        , item

      while (item = items.shift()) {
        if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
        else if (~item.indexOf(this.query)) caseSensitive.push(item)
        else caseInsensitive.push(item)
      }

      return beginswith.concat(caseSensitive, caseInsensitive)
    }

  , highlighter: function (item) {
      return item.replace(new RegExp('(' + this.query + ')', 'ig'), function ($1, match) {
        return '' + match + ''
      })
    }

  , render: function (items) {
      var that = this

      items = $(items).map(function (i, item) {
        i = $(that.options.item).attr('data-value', item)
        i.find('a').html(that.highlighter(item))
        return i[0]
      })

      items.first().addClass('active')
      this.$menu.html(items)
      return this
    }

  , next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , next = active.next()

      if (!next.length) {
        next = $(this.$menu.find('li')[0])
      }

      next.addClass('active')
    }

  , prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , prev = active.prev()

      if (!prev.length) {
        prev = this.$menu.find('li').last()
      }

      prev.addClass('active')
    }

  , listen: function () {
      this.$element
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))

      if ($.browser.webkit || $.browser.msie) {
        this.$element.on('keydown', $.proxy(this.keypress, this))
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
    }

  , keyup: function (e) {
      e.stopPropagation()
      e.preventDefault()

      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
          break

        case 9: // tab
        case 13: // enter
          if (!this.shown) return
          this.select()
          break

        case 27: // escape
          this.hide()
          break

        default:
          this.lookup()
      }

  }

  , keypress: function (e) {
      e.stopPropagation()
      if (!this.shown) return

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault()
          break

        case 38: // up arrow
          e.preventDefault()
          this.prev()
          break

        case 40: // down arrow
          e.preventDefault()
          this.next()
          break
      }
    }

  , blur: function (e) {
      var that = this
      e.stopPropagation()
      e.preventDefault()
      setTimeout(function () { that.hide() }, 150)
    }

  , click: function (e) {
      e.stopPropagation()
      e.preventDefault()
      this.select()
    }

  , mouseenter: function (e) {
      this.$menu.find('.active').removeClass('active')
      $(e.currentTarget).addClass('active')
    }

  }

  /* TYPEAHEAD PLUGIN DEFINITION
   * =========================== */

  $.fn.typeahead = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.typeahead.defaults = {
    source: []
  , items: 8
  , menu: '

'
  , item: '

'
  }

  $.fn.typeahead.Constructor = Typeahead

 /* TYPEAHEAD DATA-API
  * ================== */

  $(function () {
    $('body').on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
      var $this = $(this)
      if ($this.data('typeahead')) return
      e.preventDefault()
      $this.typeahead($this.data())
    })
  })

}( window.jQuery );<commit_msg>Allow events to propagate / default if not used.  - All key events when the menu is not shown now propagate.  - Blur is also allowed to propagate.<commit_after>/* =============================================================
 * bootstrap-typeahead.js v2.0.1
 * http://twitter.github.com/bootstrap/javascript.html#typeahead
 * =============================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */

!function( $ ){

  "use strict"

  var Typeahead = function ( element, options ) {
    this.$element = $(element)
    this.options = $.extend({}, $.fn.typeahead.defaults, options)
    this.matcher = this.options.matcher || this.matcher
    this.sorter = this.options.sorter || this.sorter
    this.highlighter = this.options.highlighter || this.highlighter
    this.$menu = $(this.options.menu).appendTo('body')
    this.source = this.options.source
    this.shown = false
    this.listen()
  }

  Typeahead.prototype = {

    constructor: Typeahead

  , select: function () {
      var val = this.$menu.find('.active').attr('data-value')
      this.$element.val(val)
      return this.hide()
    }

  , show: function () {
      var pos = $.extend({}, this.$element.offset(), {
        height: this.$element[0].offsetHeight
      })

      this.$menu.css({
        top: pos.top + pos.height
      , left: pos.left
      })

      this.$menu.show()
      this.shown = true
      return this
    }

  , hide: function () {
      this.$menu.hide()
      this.shown = false
      return this
    }

  , lookup: function (event) {
      var that = this
        , items
        , q

      this.query = this.$element.val()

      if (!this.query) {
        return this.shown ? this.hide() : this
      }

      items = $.grep(this.source, function (item) {
        if (that.matcher(item)) return item
      })

      items = this.sorter(items)

      if (!items.length) {
        return this.shown ? this.hide() : this
      }

      return this.render(items.slice(0, this.options.items)).show()
    }

  , matcher: function (item) {
      return ~item.toLowerCase().indexOf(this.query.toLowerCase())
    }

  , sorter: function (items) {
      var beginswith = []
        , caseSensitive = []
        , caseInsensitive = []
        , item

      while (item = items.shift()) {
        if (!item.toLowerCase().indexOf(this.query.toLowerCase())) beginswith.push(item)
        else if (~item.indexOf(this.query)) caseSensitive.push(item)
        else caseInsensitive.push(item)
      }

      return beginswith.concat(caseSensitive, caseInsensitive)
    }

  , highlighter: function (item) {
      return item.replace(new RegExp('(' + this.query + ')', 'ig'), function ($1, match) {
        return '' + match + ''
      })
    }

  , render: function (items) {
      var that = this

      items = $(items).map(function (i, item) {
        i = $(that.options.item).attr('data-value', item)
        i.find('a').html(that.highlighter(item))
        return i[0]
      })

      items.first().addClass('active')
      this.$menu.html(items)
      return this
    }

  , next: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , next = active.next()

      if (!next.length) {
        next = $(this.$menu.find('li')[0])
      }

      next.addClass('active')
    }

  , prev: function (event) {
      var active = this.$menu.find('.active').removeClass('active')
        , prev = active.prev()

      if (!prev.length) {
        prev = this.$menu.find('li').last()
      }

      prev.addClass('active')
    }

  , listen: function () {
      this.$element
        .on('blur',     $.proxy(this.blur, this))
        .on('keypress', $.proxy(this.keypress, this))
        .on('keyup',    $.proxy(this.keyup, this))

      if ($.browser.webkit || $.browser.msie) {
        this.$element.on('keydown', $.proxy(this.keypress, this))
      }

      this.$menu
        .on('click', $.proxy(this.click, this))
        .on('mouseenter', 'li', $.proxy(this.mouseenter, this))
    }

  , keyup: function (e) {
      switch(e.keyCode) {
        case 40: // down arrow
        case 38: // up arrow
          break

        case 9: // tab
        case 13: // enter
          if (!this.shown) return
          this.select()
          break

        case 27: // escape
          this.hide()
          break

        default:
          this.lookup()
      }

      e.stopPropagation()
      e.preventDefault()
  }

  , keypress: function (e) {
      if (!this.shown) return

      switch(e.keyCode) {
        case 9: // tab
        case 13: // enter
        case 27: // escape
          e.preventDefault()
          break

        case 38: // up arrow
          e.preventDefault()
          this.prev()
          break

        case 40: // down arrow
          e.preventDefault()
          this.next()
          break
      }

      e.stopPropagation()
    }

  , blur: function (e) {
      var that = this
      setTimeout(function () { that.hide() }, 150)
    }

  , click: function (e) {
      e.stopPropagation()
      e.preventDefault()
      this.select()
    }

  , mouseenter: function (e) {
      this.$menu.find('.active').removeClass('active')
      $(e.currentTarget).addClass('active')
    }

  }

  /* TYPEAHEAD PLUGIN DEFINITION
   * =========================== */

  $.fn.typeahead = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('typeahead')
        , options = typeof option == 'object' && option
      if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.typeahead.defaults = {
    source: []
  , items: 8
  , menu: '

'
  , item: '

'
  }

  $.fn.typeahead.Constructor = Typeahead

 /* TYPEAHEAD DATA-API
  * ================== */

  $(function () {
    $('body').on('focus.typeahead.data-api', '[data-provide="typeahead"]', function (e) {
      var $this = $(this)
      if ($this.data('typeahead')) return
      e.preventDefault()
      $this.typeahead($this.data())
    })
  })

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


<commit_before>// query selector vs jquery
// http://jsperf.com/jquery-vs-queryselectorall-to-array
//
// get element by id vs query selector
// http://jsperf.com/getelementbyid-v-s-queryselector
define(["jquery","cs!umobi.core"],function($,umobi) {
    var dom = {  };
    dom.supportClassList = (typeof document.documentElement.classList !== 'undefined');

    dom.query = function(q,c) {
        c = c || document;
        return c.querySelector(q);
    };

    dom.queryAll = function(q,c) {
        c = c || document;
        // querySelectorAll is available in IE8, Chrome, Firefox and Safari
        // in this library we don't consider IE7
        return c.querySelectorAll(q);
    };

    // get element by id, which is faster than querySelectorAll
    dom.get = function(d,c) {
        c = c || document;
        return c.getElementById(d);
    };

    // convert element collection to array
    // which is needed when iterating huge collection.
    dom.collectionToArray = function(c) {
        var i = 0, len = c.length;
        var list = [];
        for (; i < len ; i++ ) {
            list.push(c[i]);
        }
        return list;
    };

    // get by tagname
    dom.byTagName = function(n,c) {
        c = c || document;
        return c.getElementsByTagName(n);
    };
    dom.byClassName = function(n,c) {
            c = c || document;
            return c.getElementsByClassName(n);
    };

    // http://jsperf.com/jquery-addclass-vs-dom-classlist/2
    dom.addClass = function(e,cls) {
        if(typeof e.classList !== 'undefined')
            e.classList.add(cls);
        // jquery fallback
        else $(e).addClass(cls);
    };
    dom.removeClass = function(e,cls) {
        if(this.supportClassList)
            e.classList.remove(cls);
        else $(e).removeClass(cls);
    };
    dom.toggleClass = function(e,cls) {
        if(this.supportClassList)
            e.classList.toggle(cls)
        else $(e).toggleClass(cls);
    };
    dom.bind = function(el,n,cb) {
        el.addEventListener(n,cb);
    };
    umobi.dom = dom;
    return dom;
});
<commit_msg>Remove js code<commit_after><|endoftext|>


<commit_before>/* eslint-env mocha */

import React from 'react';
import expect from 'expect';
import sinon from 'sinon';
import jsdom from 'mocha-jsdom';

import expectJSX from 'expect-jsx';
expect.extend(expectJSX);

import indexSelector from '../index-selector';
import IndexSelector from '../../../components/IndexSelector';

describe('indexSelector()', () => {
  jsdom({useEach: true});

  var ReactDOM;
  var container;
  var indices;
  var cssClasses;
  var widget;
  var props;
  var helper;
  var results;
  var autoHideContainer;

  beforeEach(() => {
    autoHideContainer = sinon.stub().returns(IndexSelector);

    ReactDOM = {render: sinon.spy()};
    indexSelector.__Rewire__('ReactDOM', ReactDOM);
    indexSelector.__Rewire__('autoHideContainer', autoHideContainer);

    container = document.createElement('div');
    indices = ['index-a', 'index-b'];
    cssClasses = {
      root: 'custom-root',
      item: 'custom-item'
    };
    widget = indexSelector({container, indices, cssClasses});
    helper = {
      getIndex: sinon.stub().returns('index-a'),
      setIndex: sinon.spy(),
      search: sinon.spy()
    };
    results = {
      hits: []
    };
  });

  it('doesn\'t configure anything', () => {
    expect(widget.getConfiguration).toEqual(undefined);
  });

  it('calls ReactDOM.render(<IndexSelector props />, container)', () => {
    widget.render({helper, results});
    props = {
      cssClasses: {
        root: 'ais-index-selector custom-root',
        item: 'ais-index-selector--item custom-item'
      },
      currentIndex: 'index-a',
      hasResults: false,
      hideContainerWhenNoResults: false,
      indices: ['index-a', 'index-b'],
      setIndex: () => {}
    };
    expect(ReactDOM.render.calledOnce).toBe(true, 'ReactDOM.render called once');
    expect(ReactDOM.render.firstCall.args[0]).toEqualJSX(<IndexSelector {...props} />);
    expect(ReactDOM.render.firstCall.args[1]).toEqual(container);
  });

  it('sets the underlying index', () => {
    widget.setIndex(helper, 'index-b');
    expect(helper.setIndex.calledOnce).toBe(true, 'setIndex called once');
    expect(helper.search.calledOnce).toBe(true, 'search called once');
  });

  it('must include the current index at initialization time', () => {
    helper.getIndex = sinon.stub().returns('non-existing-index');
    expect(() => {
      widget.init(null, helper);
    }).toThrow(/Index non-existing-index not present/);
  });

  afterEach(() => {
    indexSelector.__ResetDependency__('ReactDOM');
    indexSelector.__ResetDependency__('autoHideContainer');
  });
});
<commit_msg>fix(index-selector): Fix tests passing with incorrect parameters<commit_after>/* eslint-env mocha */

import React from 'react';
import expect from 'expect';
import sinon from 'sinon';
import jsdom from 'mocha-jsdom';

import expectJSX from 'expect-jsx';
expect.extend(expectJSX);

import indexSelector from '../index-selector';
import IndexSelector from '../../../components/IndexSelector';

describe('indexSelector()', () => {
  jsdom({useEach: true});

  var ReactDOM;
  var container;
  var indices;
  var cssClasses;
  var widget;
  var props;
  var helper;
  var results;
  var autoHideContainer;

  beforeEach(() => {
    autoHideContainer = sinon.stub().returns(IndexSelector);

    ReactDOM = {render: sinon.spy()};
    indexSelector.__Rewire__('ReactDOM', ReactDOM);
    indexSelector.__Rewire__('autoHideContainer', autoHideContainer);

    container = document.createElement('div');
    indices = [
      {name: 'index-a', label: 'Index A'},
      {name: 'index-b', label: 'Index B'}
    ];
    cssClasses = {
      root: 'custom-root',
      item: 'custom-item'
    };
    widget = indexSelector({container, indices, cssClasses});
    helper = {
      getIndex: sinon.stub().returns('index-a'),
      setIndex: sinon.spy(),
      search: sinon.spy()
    };
    results = {
      hits: []
    };
  });

  it('doesn\'t configure anything', () => {
    expect(widget.getConfiguration).toEqual(undefined);
  });

  it('calls ReactDOM.render(<IndexSelector props />, container)', () => {
    widget.render({helper, results});
    props = {
      cssClasses: {
        root: 'ais-index-selector custom-root',
        item: 'ais-index-selector--item custom-item'
      },
      currentIndex: 'index-a',
      hasResults: false,
      hideContainerWhenNoResults: false,
      indices: [
        {name: 'index-a', label: 'Index A'},
        {name: 'index-b', label: 'Index B'}
      ],
      setIndex: () => {}
    };
    expect(ReactDOM.render.calledOnce).toBe(true, 'ReactDOM.render called once');
    expect(ReactDOM.render.firstCall.args[0]).toEqualJSX(<IndexSelector {...props} />);
    expect(ReactDOM.render.firstCall.args[1]).toEqual(container);
  });

  it('sets the underlying index', () => {
    widget.setIndex(helper, 'index-b');
    expect(helper.setIndex.calledOnce).toBe(true, 'setIndex called once');
    expect(helper.search.calledOnce).toBe(true, 'search called once');
  });

  it('must include the current index at initialization time', () => {
    helper.getIndex = sinon.stub().returns('non-existing-index');
    expect(() => {
      widget.init(null, helper);
    }).toThrow(/Index non-existing-index not present/);
  });

  afterEach(() => {
    indexSelector.__ResetDependency__('ReactDOM');
    indexSelector.__ResetDependency__('autoHideContainer');
  });
});
<|endoftext|>


<commit_before>/* eslint import/no-unresolved: 0 */

import React, { Fragment, Component } from "react";

import Loading from "../Loading";
import TimeParser from "../utils/time_parser.js";
import honeybadger from "../utils/honeybadger";

class BikeSearch extends Component {
  // loading states :
  // null before querying
  // true when loading
  // false when query complete

  state = {
    loading: null,
    results: [],
  };

  componentDidMount() {
    this.resultsBeingFetched();
    this.props
      .fetchBikes(this.props.interpretedParams)
      .then(this.resultsFetched)
      .catch(this.handleError);
  }

  componentDidUpdate() {
    if (!window.timeParser) {
      window.timeParser = new TimeParser();
    }
    window.timeParser.localize();
  }

  resultsBeingFetched = () => {
    this.setState({ loading: true });
  };

  resultsFetched = ({ bikes, error }) => {
    const results = bikes || [];
    const loading = !results.length ? null : false;
    this.setState({ results, loading });
    if (error) {
      this.handleError(error);
    }
  };

  handleError = (error) => {
    honeybadger.notify(error, { component: this.props.searchName });
  };

  render() {
    const { serial } = this.props.interpretedParams;

    if (this.state.loading === null) {
      return (

              {this.props.t("no_matches_found_html", { serial })}

      );
    }

    if (this.state.loading) {
      return (

              {this.props.t("searching_html", { serial })}

            <Loading />

      );
    }

    const Result = this.props.resultComponent;
    const stolenness = {
      non: "abandoned",
      all: "all",
      stolen: "stolen",
    }[this.props.interpretedParams.stolenness];

    return (

            {this.props.t("matches_found_html", { serial, stolenness })}

            {this.state.results.map((bike) => (
              <Result key={bike.id} bike={bike} />
            ))}

    );
  }
}

export default BikeSearch;
<commit_msg>Fix stolenness js translation bug (#1899)<commit_after>/* eslint import/no-unresolved: 0 */

import React, { Fragment, Component } from "react";

import Loading from "../Loading";
import TimeParser from "../utils/time_parser.js";
import honeybadger from "../utils/honeybadger";

class BikeSearch extends Component {
  // loading states :
  // null before querying
  // true when loading
  // false when query complete

  state = {
    loading: null,
    results: [],
  };

  componentDidMount() {
    this.resultsBeingFetched();
    this.props
      .fetchBikes(this.props.interpretedParams)
      .then(this.resultsFetched)
      .catch(this.handleError);
  }

  componentDidUpdate() {
    if (!window.timeParser) {
      window.timeParser = new TimeParser();
    }
    window.timeParser.localize();
  }

  resultsBeingFetched = () => {
    this.setState({ loading: true });
  };

  resultsFetched = ({ bikes, error }) => {
    const results = bikes || [];
    const loading = !results.length ? null : false;
    this.setState({ results, loading });
    if (error) {
      this.handleError(error);
    }
  };

  handleError = (error) => {
    honeybadger.notify(error, { component: this.props.searchName });
  };

  render() {
    const { serial } = this.props.interpretedParams;

    if (this.state.loading === null) {
      return (

              {this.props.t("no_matches_found_html", { serial })}

      );
    }

    if (this.state.loading) {
      return (

              {this.props.t("searching_html", { serial })}

            <Loading />

      );
    }

    const Result = this.props.resultComponent;
    // external registry search doesn't care about proximity, and for translation
    const stolenness = {
      non: "abandoned",
      all: "all",
      stolen: "stolen",
      proximity: "stolen",
    }[this.props.interpretedParams.stolenness];

    return (

            {this.props.t("matches_found_html", { serial, stolenness })}

            {this.state.results.map((bike) => (
              <Result key={bike.id} bike={bike} />
            ))}

    );
  }
}

export default BikeSearch;
<|endoftext|>


<commit_before>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello, je suis Harry ! Est ce que tu as un peu de temps de disponible ? =) %[Oui !](postback:yes) %[Pas maintenant :/)](postback:no)')
                .then(() => bot.say('Yop!'));
        }
    },

    askForTime: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then((payload) => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});
<commit_msg>'Test2'<commit_after>'use strict';

const Script = require('smooch-bot').Script;

module.exports = new Script({
    processing: {
        prompt: (bot) => bot.say('Beep boop...'),
        receive: () => 'processing'
    },

    start: {
        receive: (bot) => {
            return bot.say('Hello, je suis Harry ! Est ce que tu as un peu de temps de disponible ? =) %[Oui !](postback:yes) %[Pas maintenant :/)](postback:no)')
                .then(() => 'askForTime');
        }
    },

    askForTime: {
        prompt: (bot) => bot.say('What\'s your name?'),
        receive: (bot, message) => {
            const name = message.text;
            return bot.setProp('name', name)
                .then(() => bot.say(`Great! I'll call you ${name}
Is that OK? %[Yes](postback:yes) %[No](postback:no)`))
                .then((payload) => 'finish');
        }
    },

    finish: {
        receive: (bot, message) => {
            return bot.getProp('name')
                .then((name) => bot.say(`Sorry ${name}, my creator didn't ` +
                        'teach me how to do anything else!'))
                .then(() => 'finish');
        }
    }
});
<|endoftext|>


<commit_before>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //localStorage.numGroupe = nbDePersonnes;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

   //localStorage.duree = 'longue_adult';
    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
   $("#inputnb").change(function(e){
     var numpers = $("#inputnb").val();
     localStorage.numGroupe = numpers;
   });

  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
     localStorage.dataset = "deux";
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      localStorage.dataset = "un";
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function generer() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);
groupe = 1;
    var logo = new Image();

    var numPErs =  (parseInt(localStorage.numGroupe));

          if(localStorage.duree == "longue_adult"){
            if(localStorage.dataset == "un"){

              var logo = new Image();
      //       for (groupe = 1; groupe < 5; groupe++) {

                 logo.src = "/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";

                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);

                 groupe = groupe +1;
             pdf.addPage();
     /*       var logo2 = new Image();
                 logo2.src = "/pdf_images/long/Long_adults/long_adults_dataset1_2.PNG";

                    pdf.addImage(logo2, 'PNG', 2, 2, 590,850);

                 groupe = groupe +1;
             pdf.addPage();*/

             /*var logo3 = new Image();
                 logo3.src = "/pdf_images/long/Long_adults/long_adults_dataset1_3.PNG";
                 logo3.onload = function(){
                    pdf.addImage(logo3, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo4 = new Image();
                 logo4.src = "/pdf_images/long/Long_adults/long_adults_dataset1_4.PNG";
                 logo4.onload = function(){
                    pdf.addImage(logo4, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }*/
           //  }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }
          }
          else if(localStorage.duree == "longue_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }

      }
      else if(localStorage.duree == "courte_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                }
              }
            }

          }
          else {
            if(localStorage.dataset == "un"){
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".PNG";
                logo.onload = function(){
                  pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }

             }
            }else{
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }
             }
            }
          // var uno= 1;
          }

pdf.output("dataurlnewwindow");
}
function visualiser() {

}
<commit_msg>Update dynamic_carousel.js<commit_after>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;
  //localStorage.numGroupe = nbDePersonnes;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

   //localStorage.duree = 'longue_adult';
    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
   $("#inputnb").change(function(e){
     var numpers = $("#inputnb").val();
     localStorage.numGroupe = numpers;
   });

  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
//       alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
     localStorage.dataset = "deux";
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      localStorage.dataset = "un";
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

  });

function generer() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);
groupe = 1;
    var logo = new Image();

    var numPErs =  (parseInt(localStorage.numGroupe));

          if(localStorage.duree == "longue_adult"){
            if(localStorage.dataset == "un"){

              var logo = new Image();
      //       for (groupe = 1; groupe < 5; groupe++) {

                 logo.src = "/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";

                 pdf.addImage(logo, 'PNG', 2, 2, 590,850);

                 groupe = groupe +1;
             pdf.addPage();
            var logo2 = new Image();
                 logo2.src = "/pdf_images/long/Long_adults/long_adults_dataset1_2.PNG";

                    pdf.addImage(logo2, 'PNG', 2, 2, 590,850);

                 groupe = groupe +1;
             pdf.addPage();

             /*var logo3 = new Image();
                 logo3.src = "/pdf_images/long/Long_adults/long_adults_dataset1_3.PNG";
                 logo3.onload = function(){
                    pdf.addImage(logo3, 'PNG', 2, 2, 590,850);
                 };
                 groupe = groupe +1;
             pdf.addPage();
             var logo4 = new Image();
                 logo4.src = "/pdf_images/long/Long_adults/long_adults_dataset1_4.PNG";
                 logo4.onload = function(){
                    pdf.addImage(logo4, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }*/
           //  }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }
          }
          else if(localStorage.duree == "longue_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 };
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset2_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }

      }
      else if(localStorage.duree == "courte_enfant"){
            if(localStorage.dataset == "un"){
              for (groupe = 1; groupe < 5; groupe++) {
                 var logo = new Image();
                 logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_"+groupe+".PNG";
                 logo.onload = function(){
                    pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                 }
                 if(groupe < numPErs){
                   pdf.addPage();
                 }
              }
            }else{
              for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                }
              }
            }

          }
          else {
            if(localStorage.dataset == "un"){
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset1_"+groupe+".PNG";
                logo.onload = function(){
                  pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }

             }
            }else{
             for (groupe = 1; groupe < 5; groupe++) {
                var logo = new Image();
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_adults/court_adults_dataset2_"+groupe+".PNG";
                logo.onload = function(){
                   pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                }
                if(groupe < numPErs){
                   pdf.addPage();
                 }
             }
            }
          // var uno= 1;
          }

pdf.output("dataurlnewwindow");
}
function visualiser() {

}
<|endoftext|>


<commit_before>function ARRAYDAMNIT(someArrayLikeObject) {
    return [].slice.call(someArrayLikeObject);
}

// extract data from everything in table form. Verified to work for headers in thead.
function extractTabularData() {
    return ARRAYDAMNIT(document.getElementsByTagName("table")).map(extractTable);
}

function extractTable(table) {
    return ARRAYDAMNIT(table.rows).map(extractRows);
}

function extractRows(row) {
    return ARRAYDAMNIT(row.cells).map(extractContent);
}

function extractContent(cell) {
    return cell.innerText;
}

// gather all the data and send it somewhere
allData = {"tabular": extractTabularData(), "html": document.documentElement.innerHTML, "text": document.documentElement.innerText};

console.log(JSON.stringify(allData));
<commit_msg>map all the things<commit_after>var ARRAYDAMNIT = function(someArrayLikeObject) {
    return [].slice.call(someArrayLikeObject);
}

Object.prototype.map = function(f) {
    return ARRAYDAMNIT(this).map(f);
}

// extract data from everything in table form. Verified to work for headers in thead.
function extractTabularData() {
    return document.getElementsByTagName("table").map(extractTable);
}

function extractTable(table) {
    return table.rows.map(extractRows);
}

function extractRows(row) {
    return row.cells.map(extractContent);
}

function extractContent(cell) {
    return cell.innerText;
}

// gather all the data and send it somewhere
allData = {"tabular": extractTabularData(), "html": document.documentElement.innerHTML, "text": document.documentElement.innerText};

console.log(JSON.stringify(allData));
<|endoftext|>


<commit_before>var Latexdown={
  delay: 50,        // delay after keystroke before updating

  previewid: null,
  bufferbid: null,
  eventtabid: null,
  preview: null,     // filled in by Init below
  buffer: null,

  timeout: null,     // store setTimout id
  mjRunning: false,  // true when MathJax is processing
  oldText: null,     // used to check if an update is needed

  Init: function (pid,bid,eid) {
    this.previewid=pid;
    this.bufferid=bid;
    this.eventtabid=eid;
    this.preview=document.getElementById(this.previewid);
    this.buffer=document.getElementById(this.bufferid);
  },
  SwapBuffers: function () {
    var buffer = this.preview, preview = this.buffer;
    this.buffer = buffer; this.preview = preview;
    buffer.style.display = "none";
    buffer.style.position = "absolute";
    preview.style.position = "";
    preview.style.display = "";
  },
  Update: function () {
    if (this.timeout) {clearTimeout(this.timeout)}
    this.timeout = setTimeout(this.callback,this.delay);
  },
  PreviewHtml: function () {
    this.mjRunning = false;
    this.SwapBuffers();
  },
  PreviewMark: function () {
    this.mjRunning = false;
    text = this.buffer.innerHTML;
    //text = text.replace(/</mg, '<');
    //text = text.replace(/>/mg, '>');
    this.buffer.innerHTML = marked (text);
    this.SwapBuffers();

  },
  IsMarkdown: function(url){
    if( url== null) return false;
    ext = url.split('.').pop().toLowerCase();
    if ($.inArray(ext, ['md', 'markdown', 'mdown', 'mkdn', 'mkd', 'mdtxt', 'mdtext']) == -1) {
        return false;
    }
    else{
        return true;
    }
  },
  UpdateTab: function(url , pane){
    var _this=this;
    $.get(url, function(data) {
        this.timeout = null;
        if (_this.mjRunning) return;
        var text = data;
        if (text === _this.oldtext) return;
        text = _this.Escape(text);
        _this.buffer.innerHTML = _this.oldtext = text;
        _this.mjRunning = true;
        if(_this.IsMarkdown(url)  ){
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,_this.buffer],["PreviewMark",_this]);
        }
        else{
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,_this.buffer],["PreviewHTML",_this]);
        }
        makerbutton();
        pane.tab('show');
    });
  },
  Escape: function (html, encode) {
    return html
      .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
      //.replace(/</g, '<')
      //.replace(/>/g, '>')
      .replace(/"/g, '"')
      .replace(/'/g, ''');
  }
};
Latexdown.callback=MathJax.Callback(["UpdateTab",Latexdown]);
Latexdown.callback.autoReset = true;
<commit_msg>Update updatetab.js<commit_after>var Latexdown={
  delay: 50,        // delay after keystroke before updating

  previewid: null,
  bufferbid: null,
  eventtabid: null,
  preview: null,     // filled in by Init below
  buffer: null,

  timeout: null,     // store setTimout id
  mjRunning: false,  // true when MathJax is processing
  oldText: null,     // used to check if an update is needed

  Init: function (pid,bid,eid) {
    this.previewid=pid;
    this.bufferid=bid;
    this.eventtabid=eid;
    this.preview=document.getElementById(this.previewid);
    this.buffer=document.getElementById(this.bufferid);
  },
  SwapBuffers: function () {
    var buffer = this.preview, preview = this.buffer;
    this.buffer = buffer; this.preview = preview;
    buffer.style.display = "none";
    buffer.style.position = "absolute";
    preview.style.position = "";
    preview.style.display = "";
  },
  Update: function () {
    if (this.timeout) {clearTimeout(this.timeout)}
    this.timeout = setTimeout(this.callback,this.delay);
  },
  PreviewHtml: function () {
    this.mjRunning = false;
    this.SwapBuffers();
  },
  PreviewMark: function () {
    this.mjRunning = false;
    text = this.buffer.innerHTML;
    //text = text.replace(/</mg, '<');
    //text = text.replace(/>/mg, '>');
    this.buffer.innerHTML = marked (text);
    this.SwapBuffers();

  },
  IsMarkdown: function(url){
    if( url== null) return false;
    ext = url.split('.').pop().toLowerCase();
    if ($.inArray(ext, ['md', 'markdown', 'mdown', 'mkdn', 'mkd', 'mdtxt', 'mdtext']) == -1) {
        return false;
    }
    else{
        return true;
    }
  },
  UpdateTab: function(url , pane){
    var _this=this;
    $.get(url, function(data) {
        this.timeout = null;
        if (_this.mjRunning) return;
        var text = data;
        if (text === _this.oldtext) return;
        text = _this.Escape(text);
        _this.buffer.innerHTML = _this.oldtext = text;
        _this.mjRunning = true;
        if(_this.IsMarkdown(url)  ){
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,_this.buffer],["PreviewMark",_this]);
        }
        else{
            MathJax.Hub.Queue(["Typeset",MathJax.Hub,_this.buffer],["PreviewHTML",_this]);
        }
        makerbutton();
        pane.tab('show');
    });
  },
  Escape: function (html, encode) {
    return html
      .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
      .replace(/</g, '<')
      .replace(/>/g, '>')
      .replace(/"/g, '"')
      .replace(/'/g, ''');
  }
};
Latexdown.callback=MathJax.Callback(["UpdateTab",Latexdown]);
Latexdown.callback.autoReset = true;
<|endoftext|>


<commit_before>/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';

/* the first selector is required for youtrack-5 and the second for youtrack-6 */
togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) {

  var link, description,
    numElem = $('a.issueId'),
    titleElem = $(".issue-summary"),
    projectElem = $('.fsi-properties .disabled.bold');

  description = titleElem.textContent;
  description = numElem.firstChild.textContent.trim() + " " + description.trim();

  link = togglbutton.createTimerLink({
    className: 'youtrack',
    description: description,
    projectName: projectElem ? projectElem.textContent : ''
  });

  elem.insertBefore(link, titleElem);
});

// Agile board
togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) {
  var link,
    container = $('.sb-task-title', elem),
    description = $('.sb-task-summary', elem).textContent,
    projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim();

  link = togglbutton.createTimerLink({
    className: 'youtrack',
    description: description,
    projectName: projectName
  });

  container.appendChild(link);
});<commit_msg>[YouTrack] Fix project name fetch regression<commit_after>/*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';

/* the first selector is required for youtrack-5 and the second for youtrack-6 */
togglbutton.render('.fsi-toolbar-content:not(.toggl), .toolbar_fsi:not(.toggl)', {observe: true}, function (elem) {

  var link, description,
    numElem = $('a.issueId'),
    titleElem = $(".issue-summary"),
    projectElem = $('.fsi-properties a[title^="Project"], .fsi-properties .disabled.bold');

  description = titleElem.textContent;
  description = numElem.firstChild.textContent.trim() + " " + description.trim();

  link = togglbutton.createTimerLink({
    className: 'youtrack',
    description: description,
    projectName: projectElem ? projectElem.textContent : ''
  });

  elem.insertBefore(link, titleElem);
});

// Agile board
togglbutton.render('#board .sb-task:not(.toggl)', {observe: true}, function (elem) {
  var link,
    container = $('.sb-task-title', elem),
    description = $('.sb-task-summary', elem).textContent,
    projectName = $('#selectAgile').value.split("(")[1].replace(")", "").trim();

  link = togglbutton.createTimerLink({
    className: 'youtrack',
    description: description,
    projectName: projectName
  });

  container.appendChild(link);
});
<|endoftext|>


<commit_before>change_buttons = function(check_node = 0) {
  var button, buttons, item, num_checked, text, _i, _j, _k, _l, _len, _len2, _len3, _len4, _results, _results2;
  buttons = ["#add", "#remove"];

  num_checked = 0
  table_api = $('#trait_table').DataTable();
  check_cells = table_api.column(0).nodes().to$();
  for (let i = 0; i < check_cells.length; i++) {
    if (check_cells[i].childNodes[check_node].checked){
      num_checked += 1
    }
  }

  if (num_checked === 0) {
    for (_i = 0, _len = buttons.length; _i < _len; _i++) {
      button = buttons[_i];
      $(button).prop("disabled", true);
    }
  } else {
    for (_j = 0, _len2 = buttons.length; _j < _len2; _j++) {
      button = buttons[_j];
      $(button).prop("disabled", false);
    }
  }
};

$(function() {
  var add, checked_traits, deselectAll, invert, selectAll;

  checked_traits = null;
  selectAll = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      check_cells[i].childNodes[0].checked = true;
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      check_rows[i].classList.add("selected");
    }

    change_buttons();
  };

  deselectAll = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      check_cells[i].childNodes[0].checked = false;
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      check_rows[i].classList.remove("selected")
    }

    change_buttons();
  };

  invert = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      if (check_cells[i].childNodes[0].checked){
        check_cells[i].childNodes[0].checked = false;
      } else {
        check_cells[i].childNodes[0].checked = true;
      }
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      if (check_rows[i].classList.contains("selected")){
        check_rows[i].classList.remove("selected")
      } else {
        check_rows[i].classList.add("selected")
      }
    }

    change_buttons();
  };

  $('#searchbox').keyup(function(){
      if ($(this).val() != ""){
        $('#filter_term').val($(this).val());
      } else {
        $('#filter_term').val("None");
      }
      $('#trait_table').DataTable().search($(this).val()).draw();
  });

  /**
   * parseIndexString takes a string consisting of integers,
   * hyphens, and/or commas to indicate range(s) of indices
   * to select a rows and returns the corresponding set of indices
   * For example - "1, 5-10, 15" would return a set of 8 rows
   * @return {Set} The list of indices as a Set
   */
  parseIndexString = function(idx_string) {
    index_list = [];

    _ref = idx_string.split(",");
    for (_i = 0; _i < _ref.length; _i++) {
      index_set = _ref[_i];
      if (!/^ *([0-9]+$) *| *([0-9]+ *- *[0-9]+$) *|(^$)$/.test(index_set)) {
        $('#select_samples_invalid').show();
        break
      } else {
        $('#select_samples_invalid').hide();
      }
      if (index_set.indexOf('-') !== -1) {
          start_index = parseInt(index_set.split("-")[0]);
          end_index = parseInt(index_set.split("-")[1]);

          // If start index is higher than end index (for example is the string "10-5" exists) swap values so it'll be interpreted as "5-10" instead
          if (start_index > end_index) {
            [start_index, end_index] = [end_index, start_index]
          }

          for (index = start_index; index <= end_index; index++) {
            index_list.push(index);
          }
      } else {
        index = parseInt(index_set);
        index_list.push(index);
      }
    }
    return new Set(index_list)
  }

  filterByIndex = function() {
    index_string = $('#select_top').val()
    index_set = parseIndexString(index_string)

    table_api = $('#trait_table').DataTable();
    check_nodes = table_api.column(0).nodes().to$();
    check_nodes.each(function(index) {
      if (index_set.has(index + 1)){
        $(this)[0].childNodes[0].checked = true
      }
    })
  }

  $(window).keydown(function(event){
    if((event.keyCode == 13)) {
      event.preventDefault();
      return false;
    }
  });

  $('#select_top').keyup(function(event){
    if (event.keyCode === 13) {
      filterByIndex()
    }
  });

  $('#select_top').blur(function() {
    filterByIndex()
  });

  addToCollection = function() {
    var traits;
    table_api = $('#trait_table').DataTable();
    check_nodes = table_api.column(0).nodes().to$();
    traits = Array.from(check_nodes.map(function() {
      if ($(this)[0].childNodes[0].checked){
        return $(this)[0].childNodes[0].value
      }
    }))

    var traits_hash = md5(traits.toString());

    $.ajax({
          type: "POST",
          url: "/collections/store_trait_list",
          data: {
            hash: traits_hash,
            traits: traits.toString()
          }
    });

    return $.colorbox({
      href: "/collections/add?hash=" + traits_hash
    });

  };

  removedTraits = function() {
    return checked_traits.closest("tr").fadeOut();
  };

  submitBnw = function() {
    trait_data = submitTraitsToExportOrBnw("trait_table", "submit_bnw")
  }

  exportTraits = function() {
    trait_data = submitTraitsToExportOrBnw("trait_table", "export_csv")
  };

  submitTraitsToExportOrBnw = function(table_name, destination) {
    trait_table = $('#'+table_name);
    table_dict = {};

    headers = [];
    trait_table.find('th').each(function () {
      if ($(this).data('export')){
        headers.push($(this).data('export'))
      }
    });
    table_dict['headers'] = headers;

    selected_rows = [];
    all_rows = []; //ZS: If no rows are checked, export all
    table_api = $('#' + table_name).DataTable();
    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      this_node = check_cells[i].childNodes[0];
      all_rows.push(this_node.value)
      if (this_node.checked){
        selected_rows.push(this_node.value)
      }
    }

    if (selected_rows.length > 0){
      table_dict['rows'] = selected_rows;
    } else {
      table_dict['rows'] = all_rows;
    }

    json_table_dict = JSON.stringify(table_dict);
    $('input[name=export_data]').val(json_table_dict);

    if (destination == "export_csv"){
        $('#export_form').attr('action', '/export_traits_csv');
    } else{
        $('#export_form').attr('action', '/submit_bnw');
    }
    $('#export_form').submit();
  };

  getTraitsFromTable = function(){
    traits = $("#trait_table input:checked").map(function() {
      return $(this).val();
    }).get();
    if (traits.length == 0){
      num_traits = $("#trait_table input").length
      if (num_traits <= 100){
        traits = $("#trait_table input").map(function() {
          return $(this).val();
        }).get();
      }
    }
    return traits
  }

  $("#corr_matrix").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Correlation Matrix")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#network_graph").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Network Graph")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#wgcna_setup").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("WGCNA Setup")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#ctl_setup").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("CTL Setup")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#heatmap").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Heatmap")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#comp_bar_chart").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Comparison Bar Chart")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });

  $("#send_to_webgestalt, #send_to_bnw, #send_to_geneweaver").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      url = $(this).data("url")
      return submit_special(url)
  });

  $("#select_all").click(selectAll);
  $("#deselect_all").click(deselectAll);
  $("#invert").click(invert);
  $("#add").click(addToCollection);
  $("#submit_bnw").click(submitBnw);
  $("#export_traits").click(exportTraits);

  let naturalAsc = $.fn.dataTableExt.oSort["natural-ci-asc"]
  let naturalDesc = $.fn.dataTableExt.oSort["natural-ci-desc"]

  let na_equivalent_vals = ["N/A", "--", ""]; //ZS: Since there are multiple values that should be treated the same as N/A

  function extractInnerText(the_string){
    var span = document.createElement('span');
    span.innerHTML = the_string;
    return span.textContent || span.innerText;
  }

  function sortNAs(a, b, sort_function){
    if ( na_equivalent_vals.includes(a) && na_equivalent_vals.includes(b)) {
      return 0;
    }
    if (na_equivalent_vals.includes(a)){
      return 1
    }
    if (na_equivalent_vals.includes(b)) {
      return -1;
    }
    return sort_function(a, b)
  }

  $.extend( $.fn.dataTableExt.oSort, {
    "natural-minus-na-asc": function (a, b) {
      return sortNAs(extractInnerText(a), extractInnerText(b), naturalAsc)
    },
    "natural-minus-na-desc": function (a, b) {
      return sortNAs(extractInnerText(a), extractInnerText(b), naturalDesc)
    }
  });

  $.fn.dataTable.ext.order['dom-checkbox'] = function  ( settings, col )
  {
      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
          return $('input', td).prop('checked') ? '1' : '0';
      } );
  };

  $.fn.dataTable.ext.order['dom-inner-text'] = function  ( settings, col )
  {
      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
          return $(td).text();
      } );
  }

  applyDefault = function() {
    let default_collection_id = $.cookie('default_collection');
    if (default_collection_id) {
      let the_option = $('[name=existing_collection] option').filter(function() {
        return ($(this).text().split(":")[0] == default_collection_id);
      })
      the_option.prop('selected', true);
    }
  }
  applyDefault();

});
<commit_msg>Removed unused variables code<commit_after>change_buttons = function(check_node = 0) {
  var button, buttons, item, num_checked, text, _i, _j, _k, _l, _len, _len2, _len3, _len4, _results, _results2;
  buttons = ["#add", "#remove"];

  num_checked = 0
  table_api = $('#trait_table').DataTable();
  check_cells = table_api.column(0).nodes().to$();
  for (let i = 0; i < check_cells.length; i++) {
    if (check_cells[i].childNodes[check_node].checked){
      num_checked += 1
    }
  }

  if (num_checked === 0) {
    for (_i = 0, _len = buttons.length; _i < _len; _i++) {
      button = buttons[_i];
      $(button).prop("disabled", true);
    }
  } else {
    for (_j = 0, _len2 = buttons.length; _j < _len2; _j++) {
      button = buttons[_j];
      $(button).prop("disabled", false);
    }
  }
};

$(function() {
  var selectAll, deselectAll, invert;

  selectAll = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      check_cells[i].childNodes[0].checked = true;
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      check_rows[i].classList.add("selected");
    }

    change_buttons();
  };

  deselectAll = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      check_cells[i].childNodes[0].checked = false;
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      check_rows[i].classList.remove("selected")
    }

    change_buttons();
  };

  invert = function() {
    table_api = $('#trait_table').DataTable();

    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      if (check_cells[i].childNodes[0].checked){
        check_cells[i].childNodes[0].checked = false;
      } else {
        check_cells[i].childNodes[0].checked = true;
      }
    }

    check_rows = table_api.rows().nodes();
    for (let i =0; i < check_rows.length; i++) {
      if (check_rows[i].classList.contains("selected")){
        check_rows[i].classList.remove("selected")
      } else {
        check_rows[i].classList.add("selected")
      }
    }

    change_buttons();
  };

  $('#searchbox').keyup(function(){
      if ($(this).val() != ""){
        $('#filter_term').val($(this).val());
      } else {
        $('#filter_term').val("None");
      }
      $('#trait_table').DataTable().search($(this).val()).draw();
  });

  /**
   * parseIndexString takes a string consisting of integers,
   * hyphens, and/or commas to indicate range(s) of indices
   * to select a rows and returns the corresponding set of indices
   * For example - "1, 5-10, 15" would return a set of 8 rows
   * @return {Set} The list of indices as a Set
   */
  parseIndexString = function(idx_string) {
    index_list = [];

    _ref = idx_string.split(",");
    for (_i = 0; _i < _ref.length; _i++) {
      index_set = _ref[_i];
      if (!/^ *([0-9]+$) *| *([0-9]+ *- *[0-9]+$) *|(^$)$/.test(index_set)) {
        $('#select_samples_invalid').show();
        break
      } else {
        $('#select_samples_invalid').hide();
      }
      if (index_set.indexOf('-') !== -1) {
          start_index = parseInt(index_set.split("-")[0]);
          end_index = parseInt(index_set.split("-")[1]);

          // If start index is higher than end index (for example is the string "10-5" exists) swap values so it'll be interpreted as "5-10" instead
          if (start_index > end_index) {
            [start_index, end_index] = [end_index, start_index]
          }

          for (index = start_index; index <= end_index; index++) {
            index_list.push(index);
          }
      } else {
        index = parseInt(index_set);
        index_list.push(index);
      }
    }
    return new Set(index_list)
  }

  filterByIndex = function() {
    index_string = $('#select_top').val()
    index_set = parseIndexString(index_string)

    table_api = $('#trait_table').DataTable();
    check_nodes = table_api.column(0).nodes().to$();
    check_nodes.each(function(index) {
      if (index_set.has(index + 1)){
        $(this)[0].childNodes[0].checked = true
      }
    })
  }

  $(window).keydown(function(event){
    if((event.keyCode == 13)) {
      event.preventDefault();
      return false;
    }
  });

  $('#select_top').keyup(function(event){
    if (event.keyCode === 13) {
      filterByIndex()
    }
  });

  $('#select_top').blur(function() {
    filterByIndex()
  });

  addToCollection = function() {
    var traits;
    table_api = $('#trait_table').DataTable();
    check_nodes = table_api.column(0).nodes().to$();
    traits = Array.from(check_nodes.map(function() {
      if ($(this)[0].childNodes[0].checked){
        return $(this)[0].childNodes[0].value
      }
    }))

    var traits_hash = md5(traits.toString());

    $.ajax({
          type: "POST",
          url: "/collections/store_trait_list",
          data: {
            hash: traits_hash,
            traits: traits.toString()
          }
    });

    return $.colorbox({
      href: "/collections/add?hash=" + traits_hash
    });

  };

  submitBnw = function() {
    trait_data = submitTraitsToExportOrBnw("trait_table", "submit_bnw")
  }

  exportTraits = function() {
    trait_data = submitTraitsToExportOrBnw("trait_table", "export_csv")
  };

  submitTraitsToExportOrBnw = function(table_name, destination) {
    trait_table = $('#'+table_name);
    table_dict = {};

    headers = [];
    trait_table.find('th').each(function () {
      if ($(this).data('export')){
        headers.push($(this).data('export'))
      }
    });
    table_dict['headers'] = headers;

    selected_rows = [];
    all_rows = []; //ZS: If no rows are checked, export all
    table_api = $('#' + table_name).DataTable();
    check_cells = table_api.column(0).nodes().to$();
    for (let i = 0; i < check_cells.length; i++) {
      this_node = check_cells[i].childNodes[0];
      all_rows.push(this_node.value)
      if (this_node.checked){
        selected_rows.push(this_node.value)
      }
    }

    if (selected_rows.length > 0){
      table_dict['rows'] = selected_rows;
    } else {
      table_dict['rows'] = all_rows;
    }

    json_table_dict = JSON.stringify(table_dict);
    $('input[name=export_data]').val(json_table_dict);

    if (destination == "export_csv"){
        $('#export_form').attr('action', '/export_traits_csv');
    } else{
        $('#export_form').attr('action', '/submit_bnw');
    }
    $('#export_form').submit();
  };

  getTraitsFromTable = function(){
    traits = $("#trait_table input:checked").map(function() {
      return $(this).val();
    }).get();
    if (traits.length == 0){
      num_traits = $("#trait_table input").length
      if (num_traits <= 100){
        traits = $("#trait_table input").map(function() {
          return $(this).val();
        }).get();
      }
    }
    return traits
  }

  $("#corr_matrix").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Correlation Matrix")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#network_graph").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Network Graph")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#wgcna_setup").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("WGCNA Setup")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#ctl_setup").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("CTL Setup")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#heatmap").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Heatmap")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });
  $("#comp_bar_chart").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      $("input[name=tool_used]").val("Comparison Bar Chart")
      $("input[name=form_url]").val($(this).data("url"))
      return submit_special("/loading")
  });

  $("#send_to_webgestalt, #send_to_bnw, #send_to_geneweaver").on("click", function() {
      traits = getTraitsFromTable()
      $("#trait_list").val(traits)
      url = $(this).data("url")
      return submit_special(url)
  });

  $("#select_all").click(selectAll);
  $("#deselect_all").click(deselectAll);
  $("#invert").click(invert);
  $("#add").click(addToCollection);
  $("#submit_bnw").click(submitBnw);
  $("#export_traits").click(exportTraits);

  let naturalAsc = $.fn.dataTableExt.oSort["natural-ci-asc"]
  let naturalDesc = $.fn.dataTableExt.oSort["natural-ci-desc"]

  let na_equivalent_vals = ["N/A", "--", ""]; //ZS: Since there are multiple values that should be treated the same as N/A

  function extractInnerText(the_string){
    var span = document.createElement('span');
    span.innerHTML = the_string;
    return span.textContent || span.innerText;
  }

  function sortNAs(a, b, sort_function){
    if ( na_equivalent_vals.includes(a) && na_equivalent_vals.includes(b)) {
      return 0;
    }
    if (na_equivalent_vals.includes(a)){
      return 1
    }
    if (na_equivalent_vals.includes(b)) {
      return -1;
    }
    return sort_function(a, b)
  }

  $.extend( $.fn.dataTableExt.oSort, {
    "natural-minus-na-asc": function (a, b) {
      return sortNAs(extractInnerText(a), extractInnerText(b), naturalAsc)
    },
    "natural-minus-na-desc": function (a, b) {
      return sortNAs(extractInnerText(a), extractInnerText(b), naturalDesc)
    }
  });

  $.fn.dataTable.ext.order['dom-checkbox'] = function  ( settings, col )
  {
      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
          return $('input', td).prop('checked') ? '1' : '0';
      } );
  };

  $.fn.dataTable.ext.order['dom-inner-text'] = function  ( settings, col )
  {
      return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
          return $(td).text();
      } );
  }

  applyDefault = function() {
    let default_collection_id = $.cookie('default_collection');
    if (default_collection_id) {
      let the_option = $('[name=existing_collection] option').filter(function() {
        return ($(this).text().split(":")[0] == default_collection_id);
      })
      the_option.prop('selected', true);
    }
  }
  applyDefault();

});
<|endoftext|>


<commit_before>angular.module('galleryApp', [])
  .controller('galleryController', function() {
    var gallery = this;
    gallery.language = "en";

    gallery.title = {
      en: "Projects",
      ro: "Proiecte"
    };

    gallery.description = {
      en: "a list of projects in which I participate or participated",
      ro: "o listă de proiecte la care particip sau am participat"
    };

    gallery.complete = {
      ro: "Realizat",
      en: "Complete"
    };

    gallery.credits = {
      title: {
        ro: "Contact",
        en: "Contact"
      },
      text: {
        ro: "ghita_bizau@yahoo.com",
        en: "ghita_bizau@yahoo.com"
      }
    };

    gallery.languages = [
      {
        short: "ro",
        text: "Română"
      },
      {
        short: "en",
        text: "English"
      }
    ];

    gallery.change_language = function(language) {
      gallery.language = language;
      console.log(language);
    };

    gallery.get_progress = function(done) {
      if(done <= 10) {
        return "danger"
      } else {
        if(done > 80) {
          return "success"
        } else {
          if(done <= 50) {
            return "warning"
          } else {
            return "info"
          }
        }
      }
    };

    // EDIT HERE
    gallery.items = [
      {
        id: '20.05.2016 - present',
        img: 'http://ghitab.github.io/jonah-illustrated-book/Latest/01.png',
        done: 50,
        title: {
          ro: "Iona",
          en: "Jonah"
        },
        text: {
          ro: "carte ilustrată pentru copii",
          en: "illustrated book for kids"
        },
        url: "http://ghitab.github.io/jonah-illustrated-book/"
      },
      {
        id: '12.02.2017 - present',
        img: 'https://ghitab.github.io/miracles-of-jesus/Latest/00.png',
        done: 95,
        title: {
          ro: "Minunile lui Isus",
          en: "Miracles of Jesus"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "https://ghitab.github.io/miracles-of-jesus/"
      },
      {
        id: '2014',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Colorat-Moise-353x516.jpg',
        done: 100,
        title: {
          ro: "Moise, copilul de pe Nil",
          en: "Moses"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/moise-copilul-de-pe-nil/"
      },
      {
        id: '2013-2014',
        img: 'https://images-na.ssl-images-amazon.com/images/I/51zcXMjkIoL._SX258_BO1,204,203,200_.jpg',
        done: 100,
        title: {
          ro: "Balada unui greier mic",
          en: "Balada unui greier mic"
        },
        text: {
          ro: "ilustrații color, pictură digitală",
          en: "illustrations, digital painting"
        },
        url: "https://www.amazon.co.uk/BALADA-UNUI-GREIER-GEORGE-TOPIRCEANU/dp/6068500039"
      },
      {
        id: '2013',
        img: 'Latest/condeiul.jpg',
        done: 100,
        title: {
          ro: "Condeiul fermecat",
          en: "Condeiul fermecat"
        },
        text: {
          ro: "caiet de caligrafie (desene și text caligrafic pentru exerciții)",
          en: "calligraphy notebook (drawings and calligraphic text for exercises)"
        },
        url: "#"
      },
      {
        id: '2010-2013',
        img: 'Latest/desenez-net.png',
        done: 100,
        title: {
          ro: "www.desenez.net",
          en: "www.desenez.net"
        },
        text: {
          ro: "PHP, MySQL, programare web",
          en: "PHP, MySQL, web development"
        },
        url: "http://www.desenez.net"
      },
      {
        id: '2013',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Desen-Isaac-2013-363x516.jpg',
        done: 100,
        title: {
          ro: "Isaac",
          en: "Isaac"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/isaac/"
      },
      {
        id: '2013',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Cop_Babel-355x516.jpg',
        done: 100,
        title: {
          ro: "Turnul Babel",
          en: "Tower of Babel"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/turnul-babel/"
      },
      {
        id: '2011',
        img: 'Latest/drumul.jpg',
        done: 100,
        title: {
          ro: "Pe drumul înțelepților",
          en: "Pe drumul înțelepților"
        },
        text: {
          ro: "ilustrații",
          en: "illustrations"
        },
        url: "#"
      },
      {
        id: '2010',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Rebeca-358x516.jpg',
        done: 100,
        title: {
          ro: "Rebeca",
          en: "Rebecca"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/carte-de-colorat-rebeca/"
      },
      {
        id: '2010',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Potopul-356x516.jpg',
        done: 100,
        title: {
          ro: "Potopul lui Noe",
          en: "Noah"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/potopul-lui-noe/"
      },
      {
        id: '2009-2010',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Proverbe-356x516.jpg',
        done: 100,
        title: {
          ro: "Cartea Proverbelor",
          en: "Proverbs"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/cartea-proverbelor/"
      },
      {
        id: '2009',
        img: 'Latest/ZZ.png',
        done: 100,
        title: {
          ro: "Dor de țară",
          en: "Dor de țară"
        },
        text: {
          ro: "muzică creștină, CD",
          en: "christian music, CD"
        },
        url: "http://ghitab.blogspot.com"
      }
    ];

  });
<commit_msg>Add Puzzle.<commit_after>angular.module('galleryApp', [])
  .controller('galleryController', function() {
    var gallery = this;
    gallery.language = "en";

    gallery.title = {
      en: "Projects",
      ro: "Proiecte"
    };

    gallery.description = {
      en: "a list of projects in which I participate or participated",
      ro: "o listă de proiecte la care particip sau am participat"
    };

    gallery.complete = {
      ro: "Realizat",
      en: "Complete"
    };

    gallery.credits = {
      title: {
        ro: "Contact",
        en: "Contact"
      },
      text: {
        ro: "ghita_bizau@yahoo.com",
        en: "ghita_bizau@yahoo.com"
      }
    };

    gallery.languages = [
      {
        short: "ro",
        text: "Română"
      },
      {
        short: "en",
        text: "English"
      }
    ];

    gallery.change_language = function(language) {
      gallery.language = language;
      console.log(language);
    };

    gallery.get_progress = function(done) {
      if(done <= 10) {
        return "danger"
      } else {
        if(done > 80) {
          return "success"
        } else {
          if(done <= 50) {
            return "warning"
          } else {
            return "info"
          }
        }
      }
    };

    // EDIT HERE
    gallery.items = [
      {
        id: '20.05.2016 - present',
        img: 'http://ghitab.github.io/jonah-illustrated-book/Latest/01.png',
        done: 50,
        title: {
          ro: "Iona",
          en: "Jonah"
        },
        text: {
          ro: "carte ilustrată pentru copii",
          en: "illustrated book for kids"
        },
        url: "http://ghitab.github.io/jonah-illustrated-book/"
      },
      {
        id: '12.02.2017 - present',
        img: 'https://ghitab.github.io/miracles-of-jesus/Latest/00.png',
        done: 95,
        title: {
          ro: "Minunile lui Isus",
          en: "Miracles of Jesus"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "https://ghitab.github.io/miracles-of-jesus/"
      },
      {
        id: '2014',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Colorat-Moise-353x516.jpg',
        done: 100,
        title: {
          ro: "Moise, copilul de pe Nil",
          en: "Moses"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/moise-copilul-de-pe-nil/"
      },
      {
        id: '2013-2014',
        img: 'https://images-na.ssl-images-amazon.com/images/I/51zcXMjkIoL._SX258_BO1,204,203,200_.jpg',
        done: 100,
        title: {
          ro: "Balada unui greier mic",
          en: "Balada unui greier mic"
        },
        text: {
          ro: "ilustrații color, pictură digitală",
          en: "illustrations, digital painting"
        },
        url: "https://www.amazon.co.uk/BALADA-UNUI-GREIER-GEORGE-TOPIRCEANU/dp/6068500039"
      },
      {
        id: '2013',
        img: 'Latest/condeiul.jpg',
        done: 100,
        title: {
          ro: "Condeiul fermecat",
          en: "Condeiul fermecat"
        },
        text: {
          ro: "caiet de caligrafie (desene și text caligrafic pentru exerciții)",
          en: "calligraphy notebook (drawings and calligraphic text for exercises)"
        },
        url: "#"
      },
      {
        id: '2010-2013',
        img: 'Latest/desenez-net.png',
        done: 100,
        title: {
          ro: "www.desenez.net",
          en: "www.desenez.net"
        },
        text: {
          ro: "PHP, MySQL, programare web",
          en: "PHP, MySQL, web development"
        },
        url: "http://www.desenez.net"
      },
      {
        id: '2013',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Desen-Isaac-2013-363x516.jpg',
        done: 100,
        title: {
          ro: "Isaac",
          en: "Isaac"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/isaac/"
      },
      {
        id: '2013',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Cop_Babel-355x516.jpg',
        done: 100,
        title: {
          ro: "Turnul Babel",
          en: "Tower of Babel"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/turnul-babel/"
      },
      {
        id: '2013',
        img: 'http://i.imgur.com/wP4x0W3.png',
        done: 100,
        title: {
          ro: "Puzzle (joc)",
          en: "Puzzle (game)"
        },
        text: {
          ro: "Joc cu numere, javascript",
          en: "Game with numbers, javascript"
        },
        url: "http://ghitab.github.io/Puzzle/"
      },
      {
        id: '2011',
        img: 'Latest/drumul.jpg',
        done: 100,
        title: {
          ro: "Pe drumul înțelepților",
          en: "Pe drumul înțelepților"
        },
        text: {
          ro: "ilustrații",
          en: "illustrations"
        },
        url: "#"
      },
      {
        id: '2010',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Rebeca-358x516.jpg',
        done: 100,
        title: {
          ro: "Rebeca",
          en: "Rebecca"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/carte-de-colorat-rebeca/"
      },
      {
        id: '2010',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Potopul-356x516.jpg',
        done: 100,
        title: {
          ro: "Potopul lui Noe",
          en: "Noah"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/potopul-lui-noe/"
      },
      {
        id: '2009-2010',
        img: 'http://www.farulsperantei.ro/wp-content/uploads/Proverbe-356x516.jpg',
        done: 100,
        title: {
          ro: "Cartea Proverbelor",
          en: "Proverbs"
        },
        text: {
          ro: "carte de colorat",
          en: "coloring book"
        },
        url: "http://www.farulsperantei.ro/produs/cartea-proverbelor/"
      },
      {
        id: '2009',
        img: 'Latest/ZZ.png',
        done: 100,
        title: {
          ro: "Dor de țară",
          en: "Dor de țară"
        },
        text: {
          ro: "muzică creștină, CD",
          en: "christian music, CD"
        },
        url: "http://ghitab.blogspot.com"
      }
    ];

  });
<|endoftext|>