<commit_before>import { render, unmountComponentAtNode, findDOMNode } from "react-dom";

import { getRangeLength } from "ve-range-utils";
import Tether from "tether";

import { getInsertBetweenVals } from "ve-sequence-utils";
import React from "react";
import "./createSequenceInputPopupStyle.css";
import { Hotkey, Hotkeys, HotkeysTarget } from "@blueprintjs/core";

let div;

export default function createSequenceInputPopup(props) {
  // function closeInput() {
  //   sequenceInputBubble.remove();
  // }
  div = document.createElement("div");
  div.id = "sequenceInputBubble";
  document.body.appendChild(div);

  render(<SequenceInput {...props} />, div);
  let caretEl = document.querySelector(".veRowViewCaret");

  // let body = $(document.body);
  // let caretEl = body.find(".veRowViewCaret");
  if (!caretEl === 0) {
    //todo: eventually we should probably jump to the row view caret if it isn't visible
    // caretEl = body.find(".veCaretSVG");
    caretEl = document.querySelector(".veCaretSVG");
  }
  if (!caretEl) {
    return console.error(
      "there must be a caret element present in order to display the insertSequence popup"
    );
  }

  new Tether({
    element: div,
    target: caretEl,
    attachment: "top left",
    targetAttachment: "bottom left",
    offset: "-15px 22px",
    constraints: [
      {
        to: "scrollParent",
        // pin: true,
        attachment: "together"
      }
    ]
  });
}
class SequenceInput extends React.Component {
  state = {
    bpsToInsert: "",
    hasTempError: false
  };
  handleUnmount = () => {
    setTimeout(() => {
      unmountComponentAtNode(findDOMNode(this).parentNode);
      document.getElementById("sequenceInputBubble").outerHTML = "";
    });
  };
  handleInsert() {
    const { handleInsert = () => {} } = this.props;
    const { bpsToInsert } = this.state;
    handleInsert({
      sequence: bpsToInsert
    });
  }
  renderHotkeys() {
    return (
      <Hotkeys>
        <Hotkey
          global={true}
          combo="esc"
          label="Escape"
          onKeyDown={this.handleUnmount}
        />
        <Hotkey combo="enter" label="Enter" onKeyDown={this.handleInsert} />
      </Hotkeys>
    );
  }
  render() {
    const {
      isReplace,
      selectionLayer,
      sequenceLength,
      caretPosition,
      acceptedChars = "atgc",
      maxInsertSize
    } = this.props;
    const { bpsToInsert, hasTempError } = this.state;

    let message;
    if (isReplace) {
      const betweenVals = getInsertBetweenVals(
        -1,
        selectionLayer,
        sequenceLength
      );
      message = (

          Press ENTER to replace{" "}
          {getRangeLength(selectionLayer, sequenceLength)} base pairs between{" "}
          {betweenVals[0]} and {betweenVals[1]}

      );
    } else {
      message = (

          Press ENTER to insert{" "}
          {bpsToInsert.length} base pairs after base {caretPosition}

      );
    }
    return (

        <input
          autoCorrect={"off"}
          onKeyDown={e => {
            if (e.keyCode === 27) {
              this.handleUnmount();
            }
            if (e.keyCode === 13) {
              this.handleInsert();
              this.handleUnmount();
            }
          }}
          className={"pt-input"}
          value={bpsToInsert}
          ref={input => input && input.focus()}
          style={hasTempError ? { borderColor: "red" } : {}}
          onChange={e => {
            let sanitizedVal = "";
            e.target.value.split("").forEach(letter => {
              if (acceptedChars.includes(letter.toLowerCase())) {
                sanitizedVal += letter;
              }
            });
            if (e.target.value.length !== sanitizedVal.length) {
              this.setState({
                hasTempError: true
              });
              setTimeout(() => {
                this.setState({
                  hasTempError: false
                });
              }, 200);
            }
            if (maxInsertSize && sanitizedVal.lenth > maxInsertSize) {
              return window.toastr.error(
                "Sorry, your insert is greater than ",
                maxInsertSize
              );
            }
            e.target.value = sanitizedVal;

            this.setState({ bpsToInsert: sanitizedVal });
          }}
        />

{message}

          Press ESC to cancel

    );
  }
}
HotkeysTarget(SequenceInput);
<commit_msg>making createSequenceInput's zIndex fixed at 4000<commit_after>import { render, unmountComponentAtNode, findDOMNode } from "react-dom";

import { getRangeLength } from "ve-range-utils";
import Tether from "tether";

import { getInsertBetweenVals } from "ve-sequence-utils";
import React from "react";
import "./createSequenceInputPopupStyle.css";
import { Hotkey, Hotkeys, HotkeysTarget } from "@blueprintjs/core";

let div;

export default function createSequenceInputPopup(props) {
  // function closeInput() {
  //   sequenceInputBubble.remove();
  // }
  div = document.createElement("div");
  div.style.zIndex = "4000";
  div.id = "sequenceInputBubble";
  document.body.appendChild(div);

  render(<SequenceInput {...props} />, div);
  let caretEl = document.querySelector(".veRowViewCaret");

  // let body = $(document.body);
  // let caretEl = body.find(".veRowViewCaret");
  if (!caretEl === 0) {
    //todo: eventually we should probably jump to the row view caret if it isn't visible
    // caretEl = body.find(".veCaretSVG");
    caretEl = document.querySelector(".veCaretSVG");
  }
  if (!caretEl) {
    return console.error(
      "there must be a caret element present in order to display the insertSequence popup"
    );
  }

  new Tether({
    element: div,
    target: caretEl,
    attachment: "top left",
    targetAttachment: "bottom left",
    offset: "-15px 22px",
    constraints: [
      {
        to: "scrollParent",
        // pin: true,
        attachment: "together"
      }
    ]
  });
}
class SequenceInput extends React.Component {
  state = {
    bpsToInsert: "",
    hasTempError: false
  };
  handleUnmount = () => {
    setTimeout(() => {
      unmountComponentAtNode(findDOMNode(this).parentNode);
      document.getElementById("sequenceInputBubble").outerHTML = "";
    });
  };
  handleInsert() {
    const { handleInsert = () => {} } = this.props;
    const { bpsToInsert } = this.state;
    handleInsert({
      sequence: bpsToInsert
    });
  }
  renderHotkeys() {
    return (
      <Hotkeys>
        <Hotkey
          global={true}
          combo="esc"
          label="Escape"
          onKeyDown={this.handleUnmount}
        />
        <Hotkey combo="enter" label="Enter" onKeyDown={this.handleInsert} />
      </Hotkeys>
    );
  }
  render() {
    const {
      isReplace,
      selectionLayer,
      sequenceLength,
      caretPosition,
      acceptedChars = "atgc",
      maxInsertSize
    } = this.props;
    const { bpsToInsert, hasTempError } = this.state;

    let message;
    if (isReplace) {
      const betweenVals = getInsertBetweenVals(
        -1,
        selectionLayer,
        sequenceLength
      );
      message = (

          Press ENTER to replace{" "}
          {getRangeLength(selectionLayer, sequenceLength)} base pairs between{" "}
          {betweenVals[0]} and {betweenVals[1]}

      );
    } else {
      message = (

          Press ENTER to insert{" "}
          {bpsToInsert.length} base pairs after base {caretPosition}

      );
    }
    return (

        <input
          autoCorrect={"off"}
          onKeyDown={e => {
            if (e.keyCode === 27) {
              this.handleUnmount();
            }
            if (e.keyCode === 13) {
              this.handleInsert();
              this.handleUnmount();
            }
          }}
          className={"pt-input"}
          value={bpsToInsert}
          ref={input => input && input.focus()}
          style={hasTempError ? { borderColor: "red" } : {}}
          onChange={e => {
            let sanitizedVal = "";
            e.target.value.split("").forEach(letter => {
              if (acceptedChars.includes(letter.toLowerCase())) {
                sanitizedVal += letter;
              }
            });
            if (e.target.value.length !== sanitizedVal.length) {
              this.setState({
                hasTempError: true
              });
              setTimeout(() => {
                this.setState({
                  hasTempError: false
                });
              }, 200);
            }
            if (maxInsertSize && sanitizedVal.lenth > maxInsertSize) {
              return window.toastr.error(
                "Sorry, your insert is greater than ",
                maxInsertSize
              );
            }
            e.target.value = sanitizedVal;

            this.setState({ bpsToInsert: sanitizedVal });
          }}
        />

{message}

          Press ESC to cancel

    );
  }
}
HotkeysTarget(SequenceInput);
<|endoftext|>


<commit_before>"use strict";

var eon = eon || {};
eon.subsub = eon.subsub || subsub;
eon.c = {
  create: function(options) {

    var self = this;
    var error = false;

    self.chart = false;

    self.pubnub = options.pubnub || PUBNUB || false;

    if(!self.pubnub) {
      error = "PubNub not found. See http://www.pubnub.com/docs/javascript/javascript-sdk.html#_where_do_i_get_the_code";
    }

    options.transform = options.transform || function(m){return m};
    options.channel = options.channel || false;
    options.generate = options.generate || {};
    if(!options.generate.data) {
      options.generate.data = {
        columns: null
      };
    }
    options.flow = options.flow || false;
    if(options.flow) {
      if(typeof(options.flow) == "boolean") {
        options.flow = {};
      }
      options.flow.length = options.flow.length || 0;
    }
    options.limit = options.limit || 10;
    options.history = options.history || false;

    options.rate = options.rate || 1000;

    options.message = options.message || function(){};
    options.connect = options.connect || function(){};

    options.xcolumn = options.xcolumn || false;

    if(options.xcolumn) {

      if(!options.generate.axis) {
        options.generate.axis = {}
      }

      // assume js date
      if(!options.generate.axis.x) {

        options.generate.axis.x = {
          type: 'timeseries',
          tick: {
              format: '%Y-%m-%d %H:%M:%S'
          }
        }

      }

    }

    if(!options.channel) {
      error = "No channel supplied.";
    }

    var all_messages = [];
    var page = function() {

      all_messages = [];
      var i = 0;

      var getAllMessages = function(timetoken) {
         self.pubnub.history({
          count: options.limit,
          channel: options.channel,
          start: timetoken,
           callback: function(payload) {

             var msgs = payload[0];
             var start = payload[1];
             var end = payload[2];

             if (msgs !== undefined && msgs.length) {

               msgs.reverse();

              i = 0;
               while(i < msgs.length) {
                 all_messages.push(msgs[[i]]);
                 i++;
               }

             }

             if (msgs.length && all_messages.length < options.limit) {
               getAllMessages(start);
             } else {

              var data = [];

               i = 0;
               while(i < all_messages.length) {

                var columns = all_messages[i].columns;

                 for(var j in columns) {

                    if(i === 0) {
                      data[j] = [];
                      data[j].push(columns[j][0]);
                    }

                    data[j].push(columns[j][1]);

                 }

                 i++;

               }

               // ready to go
               data.reverse();
               self.chart.load({columns: data});

             }

           }
         });
       };

       getAllMessages();

    };

    var buffer = [];
    var needsTrim = function() {

      buffer = self.chart.data();

      var i = 0;

      while(i < buffer.length) {

        if(buffer[i].values.length > options.limit) {
          var trimLength = buffer[i].values.length - 1 - options.limit;
          return trimLength;
        }
        i++;

      }

      return false;

    };

    var lastData = [];
    var lastX = null;
    var dataStore = [];

    var mapMessage = function(message) {

      var i = 0;

      // if we have data already
      if(lastData.length) {

        // loop through the new message
        while(i < message.columns.length) {

          var j = 0;
          var found = false;

          // and compare it against the old message
          while(j < lastData.length) {

            // if it's x, then see if the new one is larger
            if(
              message.columns[i][0] == options.xcolumn &&
              lastData[j][0] == options.xcolumn
            ) {

              if(message.columns[i][1] > lastData[j][1]) {
                lastData[j][1] = message.columns[i][1];
              }

              // if they have the same key, overwrite the buffer              }
            }

            if(lastData[j][0] == message.columns[i][0]) {
              lastData[j][1] = message.columns[i][1];
              found = true;
            }

            j++;

          }

          if(!found) {
            lastData[j] = message.columns[i];
          }

          i++;

        }

      } else {
        lastData = message.columns;
      }

    };

    var updateInterval = false;

    var kill = function() {

      if(['donut', 'pie', 'gauge'].indexOf(options.generate.data.type) == -1) {
        self.chart.destroy();
      }

      delete self.chart;

    };

    var boot = function() {

      if(options.xcolumn) {
        options.generate.data.x = options.xcolumn;
      }

      options.generate.data.columns = dataStore;

      if(dataStore.length && dataStore[0].length - 1 > options.limit) {
        dataStore = [];
      }

      self.chart = c3.generate(options.generate);

    };

    var reboot = function() {
      kill();
      boot();
    };

    Visibility.change(function (e, state) {
      reboot();
    });

    var init = function() {

      if(options.history) {
        page();
      }

      subsub.subscribe(self.pubnub, options.channel, options.connect, function(message, env, channel) {

        var message = options.transform(message);

        options.message(message, env, channel);
        mapMessage(message);

      });

      var recursive = function(){

        var newx = false;
        var i = 0;

        if(!dataStore.length || !options.xcolumn) {
          newx = true;
        }

        // find out if this x value is different from the last plotted
        while(i < lastData.length) {

          if(lastData[i][0] == options.xcolumn) {

            var j = 0;

            while(j < dataStore.length) {

              if(dataStore[j][0] == options.xcolumn &&
                dataStore[j][dataStore[j].length - 1] !== lastData[i][1]) {
                newx = true;
              }

              j++;
            }

          }

          i++;
        }

        if(newx && lastData.length) {

          if(options.flow) {

            var trimLength = needsTrim();

            if((buffer.length && !buffer[0].values.length) || trimLength > 1) {
              reboot();
            } else {

              if(trimLength)  {
                options.flow.length = 1;
              }

              options.flow.columns = lastData;
              self.chart.flow(options.flow);

            }

          } else {

            self.chart.load({
              columns: lastData
            });

          }

          var i = 0;
          if(!dataStore.length) {
            dataStore = JSON.parse(JSON.stringify(lastData));
          } else {

            while(i < lastData.length) {

              // if this is a new key, add the id
              if(typeof dataStore[i] == "undefined") {
                dataStore[i] = [lastData[i][0]];
              }

              dataStore[i].push(lastData[i][1]);

              if(dataStore[i].length > options.limit) {
                dataStore[i].splice(1,1);
              }

              i++;
            }

          }

        }

        setTimeout(function(){
          recursive();
        }, options.rate);

      };
      recursive();

      return self;

    };

    if(error) {
      console.error("EON: " + error);
    } else {
      init();
      boot();

    }

    return self.chart;

  },
  flatten: function(ob) {

    var toReturn = {};

    for (var i in ob) {
      if (!ob.hasOwnProperty(i)) continue;

      if ((typeof ob[i]) == 'object') {
        var flatObject = eon.c.flatten(ob[i]);
        for (var x in flatObject) {
          if (!flatObject.hasOwnProperty(x)) continue;

          toReturn[i + '.' + x] = flatObject[x];
        }
      } else {
        toReturn[i] = ob[i];
      }
    }

    return toReturn;

  }
};
eon.chart = function(o) {
  return new eon.c.create(o);
};
<commit_msg>kill on change focus<commit_after>"use strict";

var eon = eon || {};
eon.subsub = eon.subsub || subsub;
eon.c = {
  create: function(options) {

    var self = this;
    var error = false;

    self.chart = false;
    self.killed = false;
    self.recursive = false;

    self.pubnub = options.pubnub || PUBNUB || false;

    if(!self.pubnub) {
      error = "PubNub not found. See http://www.pubnub.com/docs/javascript/javascript-sdk.html#_where_do_i_get_the_code";
    }

    options.transform = options.transform || function(m){return m};
    options.channel = options.channel || false;
    options.generate = options.generate || {};
    if(!options.generate.data) {
      options.generate.data = {
        columns: null
      };
    }
    options.flow = options.flow || false;
    if(options.flow) {
      if(typeof(options.flow) == "boolean") {
        options.flow = {};
      }
      options.flow.length = options.flow.length || 0;
    }
    options.limit = options.limit || 10;
    options.history = options.history || false;

    options.rate = options.rate || 1000;

    options.message = options.message || function(){};
    options.connect = options.connect || function(){};

    options.xcolumn = options.xcolumn || false;

    if(options.xcolumn) {

      if(!options.generate.axis) {
        options.generate.axis = {}
      }

      // assume js date
      if(!options.generate.axis.x) {

        options.generate.axis.x = {
          type: 'timeseries',
          tick: {
              format: '%Y-%m-%d %H:%M:%S'
          }
        }

      }

    }

    if(!options.channel) {
      error = "No channel supplied.";
    }

    var all_messages = [];
    var page = function() {

      all_messages = [];
      var i = 0;

      var getAllMessages = function(timetoken) {
         self.pubnub.history({
          count: options.limit,
          channel: options.channel,
          start: timetoken,
           callback: function(payload) {

             var msgs = payload[0];
             var start = payload[1];
             var end = payload[2];

             if (msgs !== undefined && msgs.length) {

               msgs.reverse();

              i = 0;
               while(i < msgs.length) {
                 all_messages.push(msgs[[i]]);
                 i++;
               }

             }

             if (msgs.length && all_messages.length < options.limit) {
               getAllMessages(start);
             } else {

              var data = [];

               i = 0;
               while(i < all_messages.length) {

                var columns = all_messages[i].columns;

                 for(var j in columns) {

                    if(i === 0) {
                      data[j] = [];
                      data[j].push(columns[j][0]);
                    }

                    data[j].push(columns[j][1]);

                 }

                 i++;

               }

               // ready to go
               data.reverse();
               self.chart.load({columns: data});

             }

           }
         });
       };

       getAllMessages();

    };

    var buffer = [];
    var needsTrim = function() {

      buffer = self.chart.data();

      var i = 0;

      while(i < buffer.length) {

        if(buffer[i].values.length > options.limit) {
          var trimLength = buffer[i].values.length - 1 - options.limit;
          return trimLength;
        }
        i++;

      }

      return false;

    };

    var lastData = [];
    var lastX = null;
    var dataStore = [];

    var mapMessage = function(message) {

      var i = 0;

      // if we have data already
      if(lastData.length) {

        // loop through the new message
        while(i < message.columns.length) {

          var j = 0;
          var found = false;

          // and compare it against the old message
          while(j < lastData.length) {

            // if it's x, then see if the new one is larger
            if(
              message.columns[i][0] == options.xcolumn &&
              lastData[j][0] == options.xcolumn
            ) {

              if(message.columns[i][1] > lastData[j][1]) {
                lastData[j][1] = message.columns[i][1];
              }

              // if they have the same key, overwrite the buffer              }
            }

            if(lastData[j][0] == message.columns[i][0]) {
              lastData[j][1] = message.columns[i][1];
              found = true;
            }

            j++;

          }

          if(!found) {
            lastData[j] = message.columns[i];
          }

          i++;

        }

      } else {
        lastData = message.columns;
      }

    };

    var updateInterval = false;

    var kill = function() {
      self.killed = true;
    };

    self.destroy = function() {

      if(['donut', 'pie', 'gauge'].indexOf(options.generate.data.type) == -1) {
        self.chart.destroy();
      }

      delete self.chart;

    }

    var boot = function() {

      self.killed = false;

      if(options.xcolumn) {
        options.generate.data.x = options.xcolumn;
      }

      options.generate.data.columns = dataStore;

      if(dataStore.length && dataStore[0].length - 1 > options.limit) {
        dataStore = [];
      }

      self.chart = c3.generate(options.generate);

      self.recursive();

    };

    var reboot = function() {
      kill();
      boot();
    };

    Visibility.change(function (e, state) {

      if (Visibility.hidden()) {
        kill();
      } else {
        boot();
      }

    });

    var init = function() {

      if(options.history) {
        page();
      }

      subsub.subscribe(self.pubnub, options.channel, options.connect, function(message, env, channel) {

        var message = options.transform(message);

        options.message(message, env, channel);
        mapMessage(message);

      });

      self.recursive = function(){

        var newx = false;
        var i = 0;

        if(!dataStore.length || !options.xcolumn) {
          newx = true;
        }

        // find out if this x value is different from the last plotted
        while(i < lastData.length) {

          if(lastData[i][0] == options.xcolumn) {

            var j = 0;

            while(j < dataStore.length) {

              if(dataStore[j][0] == options.xcolumn &&
                dataStore[j][dataStore[j].length - 1] !== lastData[i][1]) {
                newx = true;
              }

              j++;
            }

          }

          i++;
        }

        if(newx && lastData.length) {

          if(options.flow) {

            var trimLength = needsTrim();

            if((buffer.length && !buffer[0].values.length) || trimLength > 1) {
              reboot();
            } else {

              if(trimLength)  {
                options.flow.length = 1;
              }

              options.flow.columns = lastData;
              self.chart.flow(options.flow);

            }

          } else {

            self.chart.load({
              columns: lastData
            });

          }

          var i = 0;
          if(!dataStore.length) {
            dataStore = JSON.parse(JSON.stringify(lastData));
          } else {

            while(i < lastData.length) {

              // if this is a new key, add the id
              if(typeof dataStore[i] == "undefined") {
                dataStore[i] = [lastData[i][0]];
              }

              dataStore[i].push(lastData[i][1]);

              if(dataStore[i].length > options.limit) {
                dataStore[i].splice(1,1);
              }

              i++;
            }

          }

        }

        if(self.killed) {
          self.destroy();
        } else {
          setTimeout(function(){
            self.recursive();
          }, options.rate);

        }

      };

      return self;

    };

    if(error) {
      console.error("EON: " + error);
    } else {
      init();
      boot();

    }

    return self.chart;

  },
  flatten: function(ob) {

    var toReturn = {};

    for (var i in ob) {
      if (!ob.hasOwnProperty(i)) continue;

      if ((typeof ob[i]) == 'object') {
        var flatObject = eon.c.flatten(ob[i]);
        for (var x in flatObject) {
          if (!flatObject.hasOwnProperty(x)) continue;

          toReturn[i + '.' + x] = flatObject[x];
        }
      } else {
        toReturn[i] = ob[i];
      }
    }

    return toReturn;

  }
};
eon.chart = function(o) {
  return new eon.c.create(o);
};
<|endoftext|>


<commit_before>var Request = require('../lib/request'),
    should = require('should');

describe('Request unit tests', function () {
  describe("matching", function () {

    it('should work with defined headers in the incoming request', function () {
      var request = new Request(new Object(), {
        method: 'GET',
        url: '/lowercasetest',
        headers: { 'foo-type': 'artischocke' }
      });

      request.isMatch({
        method: 'GET',
        url: '/lowercasetest',
        headers: { 'foo-type': 'artischocke' }
      }).should.equal(true);
    });

    it('should work with defined headers in the incoming request', function () {
      var request = new Request(new Object(), {
        method: 'GET',
        url: '/lowercasetest',
        headers: { 'foo-type': 'artischocke' }
      });

      request.isMatch({
        method: 'GET',
        url: '/lowercasetest',
        headers: {}
      }).should.equal(false);
    });
  });
});
<commit_msg>Test that `Request#isMatch` accepts any order of query strings<commit_after>var Request = require('../lib/request'),
    should = require('should');

describe('Request unit tests', function () {
  describe("matching", function () {

    it('should work with defined headers in the incoming request', function () {
      var request = new Request(new Object(), {
        method: 'GET',
        url: '/lowercasetest',
        headers: { 'foo-type': 'artischocke' }
      });

      request.isMatch({
        method: 'GET',
        url: '/lowercasetest',
        headers: { 'foo-type': 'artischocke' }
      }).should.equal(true);
    });

    it('should work with defined headers in the incoming request', function () {
      var request = new Request(new Object(), {
        method: 'GET',
        url: '/lowercasetest',
        headers: { 'foo-type': 'artischocke' }
      });

      request.isMatch({
        method: 'GET',
        url: '/lowercasetest',
        headers: {}
      }).should.equal(false);
    });

    it('should accept any order of query strings', function () {
      var request = new Request(new Object(), {
        method: 'GET',
        url: '/?foo=bar&bar=foo'
      });

      request.isMatch({
        method: 'GET',
        url: '/?bar=foo&foo=bar'
      }).should.equal(true);
    });
  });
});
<|endoftext|>


<commit_before>(function() {
    function createTable(columns, d3Selection, data) {
        var table = d3Selection.append("table")
                .attr("class", "columns"),
            thead = table.append("thead"),
            tbody = table.append("tbody");

        // append the header row
        thead.append("tr")
            .selectAll("th")
            .data(columns)
            .enter()
            .append("th")
            .text(function(column) { return column.text; });

        // create a row for each object in the data
        var rows = tbody.selectAll("tr")
            .data(data)
            .enter()
            .append("tr");

        // create a cell in each row for each column
        var cells = rows.selectAll("td")
            .data(function(row) {
                return columns.map(function(column) {
                    return {column: column, value: row[column.property]};
                });
            })
            .enter()
            .append("td")
            .attr("style", "font-family: Courier")
            .html(function(d) { return d.value; });

        return table;
    }

    function downloadFile(fileType, fileContent, fileName) {
        $("<a>")
            .attr("href", encodeURI(fileType + fileContent))
            .attr("download", fileName)
            .get(0)
            .click();
    }

    function createCSV(columns, data) {
        var csvRows = [columns.map(function(item) {
                return ['"',
                        item.text.replace('"', '""'),
                        '"'].join("");
            }).join(",")];

        csvRows = csvRows.concat(data.map(function(item) {
            return columns.map(function(column) {
                return item[column.property];
            }).join(",");
        }));

        return csvRows.join("\n");
    }

    function parseActivity(activity) {
        function isOutside(endpoint) {
            return activity.Endpoints.indexOf(endpoint) < 0;
        }

        function createEndpoint(endpoint) {
            return {
                activity: activity.Label,
                endpoint: endpoint,
                totalConnections: 0,
                outsideConnections: 0,
                external: NCI.isExternal(endpoint)
            }
        }

        function getEndpoint(endpoint) {
            return endpoints[endpoint];
        }

        var endpoints = {};

        activity.Endpoints.forEach(function(endpoint) {
            endpoints[endpoint] = createEndpoint(endpoint);
        });

        activity.Interactions.forEach(
            function(interaction) {
                var outsideInteraction = false,
                    ep = null;

                interaction.forEach(function(endpoint) {
                    if (isOutside(endpoint)) {
                        outsideInteraction = true
                    } else {
                        ep = getEndpoint(endpoint);
                        ep.totalConnections += 1;
                    }
                });

                if (ep && outsideInteraction) {
                    ep.outsideConnections += 1;
                }

            }
        );

        return Object.keys(endpoints).map(function(endpoint) {return endpoints[endpoint]});
    }

    function parseActivities(activities) {
        return Array.prototype.concat.apply([], activities.map(parseActivity));
    }

    function getCommunitiesColumns(communities) {
        return communities.length > 1 ? activitiesColumns : activityColumns;
    }

    function getActivityName(communities) {
        return communities.length > 1 ? "activities" : (communities[0].Label);
    }

    var activityColumns = [
            {text: "Endpoint", property: "endpoint"},
            {text: "Connections", property: "totalConnections"},
            {text: "Outside Connections", property: "outsideConnections"},
            {text: "External", property: "external"}
        ],
        activitiesColumns = [
            {text: "Activity", property: "activity"},
            {text: "Endpoint", property: "endpoint"},
            {text: "Connections", property: "totalConnections"},
            {text: "Outside Connections", property: "outsideConnections"},
            {text: "External", property: "external"}
        ],
        downloadCSV = downloadFile.bind(null, "data:text/csv;charset=utf-8,");

    function ListBuilder(communities) {
        this.columns = getCommunitiesColumns(communities);
        this.activityName = getActivityName(communities);
        this.activities = parseActivities(communities);
    }

    ListBuilder.prototype.downloadCSV = function() {
        var columns = this.columns,
            csvName = this.activityName + ".csv",
            activities = this.activities,
            csvContent = createCSV(columns, activities);

        return downloadCSV(csvContent, csvName);
    }

    ListBuilder.prototype.createTable = function (d3Selection) {
        var columns = this.columns,
            activities = this.activities;

        return createTable(columns, d3Selection, activities);
    }

    NCI.list = {
        createListBuilder: function(communities) {
            return new ListBuilder(communities);
        }
    };

})();
<commit_msg>Data sorted in list view<commit_after>(function() {
    function createTable(columns, d3Selection, data) {
        var table = d3Selection.append("table")
                .attr("class", "columns"),
            thead = table.append("thead"),
            tbody = table.append("tbody");

        // append the header row
        thead.append("tr")
            .selectAll("th")
            .data(columns)
            .enter()
            .append("th")
            .text(function(column) { return column.text; });

        // create a row for each object in the data
        var rows = tbody.selectAll("tr")
            .data(data)
            .enter()
            .append("tr");

        // create a cell in each row for each column
        var cells = rows.selectAll("td")
            .data(function(row) {
                return columns.map(function(column) {
                    return {column: column, value: row[column.property]};
                });
            })
            .enter()
            .append("td")
            .attr("style", "font-family: Courier")
            .html(function(d) { return d.value; });

        return table;
    }

    function downloadFile(fileType, fileContent, fileName) {
        $("<a>")
            .attr("href", encodeURI(fileType + fileContent))
            .attr("download", fileName)
            .get(0)
            .click();
    }

    function createCSV(columns, data) {
        var csvRows = [columns.map(function(item) {
                return ['"',
                        item.text.replace('"', '""'),
                        '"'].join("");
            }).join(",")];

        csvRows = csvRows.concat(data.map(function(item) {
            return columns.map(function(column) {
                return item[column.property];
            }).join(",");
        }));

        return csvRows.join("\n");
    }

    function parseActivity(activity) {
        function isOutside(endpoint) {
            return activity.Endpoints.indexOf(endpoint) < 0;
        }

        function createEndpoint(endpoint) {
            return {
                activity: activity.Label,
                endpoint: endpoint,
                totalConnections: 0,
                outsideConnections: 0,
                external: NCI.isExternal(endpoint)
            }
        }

        function getEndpoint(endpoint) {
            return endpoints[endpoint];
        }

        var endpoints = {};

        activity.Endpoints.forEach(function(endpoint) {
            endpoints[endpoint] = createEndpoint(endpoint);
        });

        activity.Interactions.forEach(
            function(interaction) {
                var outsideInteraction = false,
                    ep = null;

                interaction.forEach(function(endpoint) {
                    if (isOutside(endpoint)) {
                        outsideInteraction = true
                    } else {
                        ep = getEndpoint(endpoint);
                        ep.totalConnections += 1;
                    }
                });

                if (ep && outsideInteraction) {
                    ep.outsideConnections += 1;
                }

            }
        );

        return Object.keys(endpoints).map(function(endpoint) {return endpoints[endpoint]});
    }

    function parseActivities(activities) {
        return Array.prototype.concat.apply([], activities.map(parseActivity));
    }

    function sortActivities(activities) {
        return activities.sort(function(a1, a2) {
            if (a1.activity < a2.activity) {
                return -1;
            }
            if (a1.activity > a2.activity)
                return 1;
            return a2.totalConnections - a1.totalConnections;
        })
    }

    function getCommunitiesColumns(communities) {
        return communities.length > 1 ? activitiesColumns : activityColumns;
    }

    function getActivityName(communities) {
        return communities.length > 1 ? "activities" : (communities[0].Label);
    }

    var activityColumns = [
            {text: "Endpoint", property: "endpoint"},
            {text: "Connections", property: "totalConnections"},
            {text: "Outside Connections", property: "outsideConnections"},
            {text: "External", property: "external"}
        ],
        activitiesColumns = [
            {text: "Activity", property: "activity"},
            {text: "Endpoint", property: "endpoint"},
            {text: "Connections", property: "totalConnections"},
            {text: "Outside Connections", property: "outsideConnections"},
            {text: "External", property: "external"}
        ],
        downloadCSV = downloadFile.bind(null, "data:text/csv;charset=utf-8,");

    function ListBuilder(communities) {
        this.columns = getCommunitiesColumns(communities);
        this.activityName = getActivityName(communities);
        this.activities = sortActivities(parseActivities(communities));
    }

    ListBuilder.prototype.downloadCSV = function() {
        var columns = this.columns,
            csvName = this.activityName + ".csv",
            activities = this.activities,
            csvContent = createCSV(columns, activities);

        return downloadCSV(csvContent, csvName);
    }

    ListBuilder.prototype.createTable = function (d3Selection) {
        var columns = this.columns,
            activities = this.activities;

        return createTable(columns, d3Selection, activities);
    }

    NCI.list = {
        createListBuilder: function(communities) {
            return new ListBuilder(communities);
        }
    };

})();
<|endoftext|>


<commit_before>import React from 'react';
import { Table, TableHeader, TableBody } from '@patternfly/react-table';
import { ExclamationCircleIcon } from '@patternfly/react-icons';

const renderType = prop => {
  if (prop.type) {
    // JS prop
    return prop.type.name;
  } else if (prop.tsType) {
    // TS Prop
    if (prop.tsType.raw) {
      // Raw is like 'h1' | 'h2' | 'h3'
      return prop.tsType.raw;
    }
    return prop.tsType.name;
  }

  return '';
};

export const PropsTable = props => {
  const columns = [
    { title: 'Name' },
    { title: 'Type' },
    { title: 'Required' },
    { title: 'Default' },
    { title: 'Description' }
  ];

  return (

 ({
        cells: [
          row.name,
          renderType(row),

            {row.required && <ExclamationCircleIcon />}

,
          row.defaultValue && row.defaultValue.value,
          row.description
        ]
      }))}
    >
      <TableHeader />
      <TableBody />

  );
}
<commit_msg>fix: for required field. We now will display if the property is required or not using 'Yes || No' (#1637)<commit_after>import React from 'react';
import { Table, TableHeader, TableBody } from '@patternfly/react-table';

const renderType = prop => {
  if (prop.type) {
    // JS prop
    return prop.type.name;
  } else if (prop.tsType) {
    // TS Prop
    if (prop.tsType.raw) {
      // Raw is like 'h1' | 'h2' | 'h3'
      return prop.tsType.raw;
    }
    return prop.tsType.name;
  }

  return '';
};

export const PropsTable = props => {
  const columns = [
    { title: 'Name' },
    { title: 'Type' },
    { title: 'Required' },
    { title: 'Default' },
    { title: 'Description' }
  ];

  return (

 ({
        cells: [
          row.name,
          renderType(row),

            {row.required ? 'Yes' : 'No'}

,
          row.defaultValue && row.defaultValue.value,
          row.description
        ]
      }))}
    >
      <TableHeader />
      <TableBody />

  );
}
<|endoftext|>


<commit_before>/* global describe, it, before, expect */
const Remit = require('../')

describe('Request', function () {
  let remit

  before(function () {
    remit = Remit()
  })

  describe('#object', function () {
    it('should be a function')
    it('should expose "on" global function')
    it('should return a Request')
    it('should be runnable (#send)')
    it('should expose an "on" function')
    it('should expose a "fallback" function')
    it('should expose an "options" function')
    it('should expose a "ready" function')
    it('should expose a "send" function')
  })
})
<commit_msg>✅ Pad out request testing<commit_after>/* global describe, it, before, expect */
const Remit = require('../')

describe('Request', function () {
  let remit

  before(function () {
    remit = Remit()
  })

  describe('#object', function () {
    it('should be a function', function () {
      expect(remit.request).to.be.a('function')
    })
    it('should expose "on" global function', function () {
      expect(remit.endpoint.on).to.be.a('function')
    })
  })

  describe('#return', function () {
    let remit, request

    before(function () {
      remit = Remit()
      request = remit.request('request-test')
    })

    it('should throw if no event given', function () {
      expect(remit.request).to.throw('No/invalid event specified when creating a request')
    })

    it('should throw if given no event in options object', function () {
      expect(remit.request.bind(remit, {})).to.throw('No/invalid event specified when creating a request')
    })

    it('should allow options to be set on first run', function () {
      const req = remit.request({
        event: 'tester-123',
        timeout: 2000
      })

      expect(req._options).to.have.property('event', 'tester-123')
      expect(req._options).to.have.property('timeout', 2000)
    })

    it('should return a Request', function () {
      expect(request).to.be.an.instanceof(remit.request.Type)
    })

    it('should be runnable (#send)', function () {
      expect(request).to.be.a('function')
    })

    it('should expose an "on" function', function () {
      expect(request.on).to.be.a('function')
    })
    it('should expose a "fallback" function', function () {
      expect(request.fallback).to.be.a('function')
    })
    it('should expose an "options" function', function () {
      expect(request.options).to.be.a('function')
    })
    it('should expose a "ready" function', function () {
      expect(request.ready).to.be.a('function')
    })
    it('should expose a "send" function', function () {
      expect(request.send).to.be.a('function')
    })
  })

  describe('#usage', function () {
    let remit

    before(function () {
      remit = Remit({name: 'requestRemit'})
    })

    it('should assign new options over old ones', function () {
      const request = remit.request('options-test')
      expect(request._options).to.have.property('event', 'options-test')
      request.options({event: 'options-queue'})
      expect(request._options).to.have.property('event', 'options-queue')
    })

    it('should return \'ready\' promise when request is ready to be used', function () {
      this.slow(200)

      const request = remit.request('on-start')
      const ret = request.ready()
      expect(ret).to.be.a('promise')

      return ret
    })

    it('should allow a fallback to be set', function () {
      const request = remit.request('fallback-test')
      expect(request).to.not.have.property('_fallback')
      request.fallback(123)
      expect(request).to.have.property('_fallback', 123)
    })

    it('should allow a falsy fallback to be set', function () {
      const request = remit.request('fallback-test-falsy')
      expect(request).to.not.have.property('_fallback')
      request.fallback(null)
      expect(request).to.have.property('_fallback', null)
    })

    it('should allow a fallback to be unset', function () {
      const request = remit.request('fallback-test-unset')
      expect(request).to.not.have.property('_fallback')
      request.fallback('testfallback')
      expect(request).to.have.property('_fallback', 'testfallback')
      request.fallback()
      expect(request).to.not.have.property('_fallback')
    })

    it('should throw if sent with invalid priority', async function () {
      const request = remit.request('invalid-priority')
      request.options({priority: 11})

      try {
        await request()
        throw new Error('Should have failed with invalid priority')
      } catch (e) {
        expect(e.message).to.equal('Invalid priority "11" when making request')
      }
    })

    it('should timeout in configurable times', async function () {
      this.slow(2000)

      const request = remit.request('timeout-test')
      request.options({timeout: 1000})

      try {
        await request()
        throw new Error('Request should not have succeeded')
      } catch (e) {
        expect(e.message).to.equal('Request timed out after no response for 1000ms')
      }
    })

    it('should return fallback if timing out and fallback set')
    it('should send NULL if given unparsable data')
  })
})
<|endoftext|>


<commit_before>import React from 'react'
import CourseTitle from './courseTitle'
import CourseIdentBlock from './courseIdentBlock'
import map from 'lodash/collection/map'

class CollapsedCourse extends React.Component {
	shouldComponentUpdate(nextProps) {
		return this.props.info.clbid !== nextProps.info.clbid
	}

	render() {
		console.log('CollapsedCourse#render')
		let {info: course} = this.props

		let gereqs = null
		if (course.gereqs) {
			gereqs =

				{map(course.gereqs, (ge, idx) =>

{ge}

				)}

		}

		return

				<CourseTitle {...course} onClick={this.props.onClick} />
				{this.props.children}

					<CourseIdentBlock {...course} />
					{course.type}
					{gereqs}

			<button className='show-info' onClick={this.props.onClick} />

	}
}

CollapsedCourse.propTypes = {
	info: React.PropTypes.object.isRequired,
	onClick: React.PropTypes.func.isRequired,
}
CollapsedCourse.defaultProps = {
	onClick() {}
}

export default CollapsedCourse
<commit_msg>Show course times in collapsedCourse<commit_after>import React from 'react'
import CourseTitle from './courseTitle'
import CourseIdentBlock from './courseIdentBlock'
import map from 'lodash/collection/map'

class CollapsedCourse extends React.Component {
	shouldComponentUpdate(nextProps) {
		return this.props.info.clbid !== nextProps.info.clbid
	}

	render() {
		console.log('CollapsedCourse#render')
		let {info: course} = this.props

		let gereqs = null
		if (course.gereqs) {
			gereqs =

				{map(course.gereqs, (ge, idx) =>

{ge}

				)}

		}

		return

				<CourseTitle {...course} onClick={this.props.onClick} />
				{this.props.children}

					<CourseIdentBlock {...course} />
					{course.type}
					{gereqs}

					{course.times}

			<button className='show-info' onClick={this.props.onClick} />

	}
}

CollapsedCourse.propTypes = {
	info: React.PropTypes.object.isRequired,
	onClick: React.PropTypes.func.isRequired,
}
CollapsedCourse.defaultProps = {
	onClick() {}
}

export default CollapsedCourse
<|endoftext|>


<commit_before>import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { Text } from '@buffetjs/core';

const NotificationWrapper = styled.div`
  height: 14px;
  margin-top: 4px;
  padding: 0px 4px;
  background-color: #383d49;
  border-radius: 2px;
  font-size: 11px;
`;

const NotificationCount = ({ count }) => (
  <NotificationWrapper>
    <Text fontWeight="bold" fontSize="xs" lineHeight="14px" color="#919bae">
      {count}
    </Text>
  </NotificationWrapper>
);

NotificationCount.defaultProps = {
  count: 0,
};

NotificationCount.propTypes = {
  count: PropTypes.number,
};

export default NotificationCount;
<commit_msg>Fix margin in notification count<commit_after>import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import { Text } from '@buffetjs/core';

const NotificationWrapper = styled.div`
  height: 14px;
  margin-top: 4px;
  margin-right: 20px;
  padding: 0px 4px;
  background-color: #383d49;
  border-radius: 2px;
  font-size: 11px;
`;

const NotificationCount = ({ count }) => (
  <NotificationWrapper>
    <Text fontWeight="bold" fontSize="xs" lineHeight="14px" color="#919bae">
      {count}
    </Text>
  </NotificationWrapper>
);

NotificationCount.defaultProps = {
  count: 0,
};

NotificationCount.propTypes = {
  count: PropTypes.number,
};

export default NotificationCount;
<|endoftext|>


<commit_before>
var express = require('../')
  , request = require('./support/http');

describe('res', function(){
  describe('.sendfile(path)', function(){
    it('should transfer the file', function(done){
      var app = express();

      app.use(function(req, res){
        res.sendfile(__dirname + '/fixtures/user.html');
      });

      request(app)
      .get('/')
      .end(function(res){
        res.body.should.equal('
{{user.name}}
');
        res.headers.should.have.property('content-type', 'text/html; charset=UTF-8');
        done();
      });
    })
  })
})
<commit_msg>added failing res.sendfile() test on 404<commit_after>
var express = require('../')
  , request = require('./support/http')
  , assert = require('assert');

describe('res', function(){
  describe('.sendfile(path)', function(){
    describe('with an absolute path', function(){
      it('should transfer the file', function(done){
        var app = express();

        app.use(function(req, res){
          res.sendfile(__dirname + '/fixtures/user.html');
        });

        request(app)
        .get('/')
        .end(function(res){
          res.body.should.equal('
{{user.name}}
');
          res.headers.should.have.property('content-type', 'text/html; charset=UTF-8');
          done();
        });
      })
    })

    describe('with a relative path', function(){
      it('should transfer the file', function(done){
        var app = express();

        app.use(function(req, res){
          res.sendfile('test/fixtures/user.html');
        });

        request(app)
        .get('/')
        .end(function(res){
          res.body.should.equal('
{{user.name}}
');
          res.headers.should.have.property('content-type', 'text/html; charset=UTF-8');
          done();
        });
      })

      it('should next(404) when not found', function(done){
        var app = express()
          , calls = 0;

        app.use(function(req, res){
          res.sendfile('user.html');
        });

        app.use(function(req, res){
          assert(0, 'this should not be called');
        });

        app.use(function(err, req, res, next){
          ++calls;
          next(err);
        });

        request(app)
        .get('/')
        .end(function(res){
          res.statusCode.should.equal(404);
          calls.should.equal(1);
          done();
        });
      })
    })
  })
})
<|endoftext|>


<commit_before>;(function($, undefined){

    Hyphen.view = {}

	// Generic quantities
	$(document).on( "/webentities", function(event, eventData){
        switch(eventData.what){
            case "updated":

            var l = Hyphen.model.webEntities.getAll().length
            $('.content_webEntityCount').text(l)
            $('.content_webEntityCount_text').text((l>1)?('web entities'):('web entity'))

            break
        }
    })

    $(document).on( "/crawls", function(event, eventData){
        switch(eventData.what){
            case "updated":

            var l = Hyphen.model.crawlJobs.getAll().length
            $('.content_crawlJobsCount').text(l)
            $('.content_crawlJobsCount_text').text((l>1)?('crawl jobs'):('crawl job'))

            break
        }
    })

    // Web entities proxies
    $(document).on( "/webentities", function(event, eventData){
        switch(eventData.what){
            case "updated":
            Hyphen.view.webEntities.proxiesUpdate()
            break
        }
    })
    Hyphen.view.webEntities = {}
    Hyphen.view.webEntities.proxiesUpdate = function(onlyOutdated){
        $('.webEntity_proxy').each(function(i,proxy){
            Hyphen.view.webEntities.replaceProxyElement($(proxy), onlyOutdated)

        })
    }
    Hyphen.view.webEntities.replaceProxyElement = function(proxyElement, onlyOutdated){
        var we_id = proxyElement.attr('webEntity_id')
            ,we = Hyphen.model.webEntities.get(we_id)
        if(!(onlyOutdated && proxyElement.hasClass('webEntity_proxy_updated'))){
            var creationDate = new Date()
                ,lastModificationDate = new Date()
            creationDate.setTime(we.creation_date)
            lastModificationDate.setTime(we.last_modification_date)
            proxyElement.html('')
            proxyElement.addClass('webEntity_proxy_updated')
            proxyElement.append(
                $('').text(we.name)
                    .addClass('info_tooltip')
                    .popover({
                        trigger:'hover'
                        ,title: $('').after($('').text(' '+we.name))
                        ,content:
                            $('
').append(
                                $('
').append(
                                    we.lru_prefixes.map(function(lru){
                                        return $('
').append($('').text(Hyphen.utils.URL_simplify(Hyphen.utils.LRU_to_URL(lru))))
                                        // return $('
').append($('').attr('href', Hyphen.utils.LRU_to_URL(lru)).text(Hyphen.utils.URL_simplify(Hyphen.utils.LRU_to_URL(lru))))
                                    })
                                )
                            ).css('padding-bottom', '10px')
                            .after(
                                $('
').append(
                                    $('').text('Status: ')
                                ).append(
                                    $('').text(we.status)
                                        .addClass(Hyphen.view.webEntities_status_getLabelColor(we.status))
                                )
                            )/*.after($('
').append(
                                    $('').text('Last crawl: ')
                                ).append(
                                    $('
')
                                ).append(
                                    $('').text('Harvesting: '+we.crawling_status.replace('_', ' ').toLowerCase())
                                        .addClass(Hyphen.view.crawlJobs_crawling_getLabelColor(we.crawling_status))
                                ).append(
                                    $('').text(' ')
                                ).append(
                                    $('').text('Indexing: '+we.indexing_status.replace('_', ' ').toLowerCase())
                                        .addClass(Hyphen.view.crawlJobs_indexing_getLabelColor(we.indexing_status))
                                ).append(
                                    $('').text(' ')
                                )
                            )*/.after($('
').append(
                                    $('').text('Modified: ')
                                ).append(
                                    $('').text(Hyphen.utils.prettyDate(lastModificationDate))
                                        .attr('title', lastModificationDate)
                                )
                            )
                    })
            )
        }
        return proxyElement
    }

    Hyphen.view.updateInfoTooltips = function(){
        // Glossary & Tooltip informations
        $('.info_start_pages').attr('title', 'The start pages define where the crawler starts. They are used to compute the depth of other pages.')
        $('.info_start_pages_explanations').attr('title', 'Browse the start pages and check that they are working and not redirected')
        $('.info_prefixes_explanations').attr('title', 'The prefixes define which URLs belong to a web entity. Different prefixes for the same web entity represent its aliases.')
        $(".info_tooltip").tooltip()
    }

	$(document).ready(function () {
	    Hyphen.view.updateInfoTooltips()
  	})

    // Color codes
    Hyphen.view.crawlJobs_crawling_getLabelColor = function(status){
        var crawling_colorClass
        if(status.toLowerCase() == "finished")
            crawling_colorClass = 'label-success'
        else if(status.toLowerCase().indexOf("crashed") >= 0)
            crawling_colorClass = 'label-important'
        else if(status.toLowerCase() == "pending")
            crawling_colorClass = 'label-warning'
        else if(status.toLowerCase() == "canceled")
            crawling_colorClass = 'label-inverse'
        else
            crawling_colorClass = ''
        return crawling_colorClass
    }
    Hyphen.view.crawlJobs_indexing_getLabelColor = function(status){
        var indexing_colorClass
        if(status.toLowerCase() == "finished")
            indexing_colorClass = 'label-success'
        else if(status.toLowerCase().indexOf("crashed") >= 0)
            indexing_colorClass = 'label-important'
        else if(status.toLowerCase() == "pending")
            indexing_colorClass = 'label-warning'
        else
            indexing_colorClass = ''
        return indexing_colorClass
    }
    Hyphen.view.webEntities_status_getLabelColor = function(status){
        return (status=='DISCOVERED')?('label-warning'):(
                (status=='UNDECIDED')?('label-info'):(
                    (status=='OUT')?('label-important'):(
                        (status=='IN')?('label-success'):('')
                    )
                )
            )
    }

})(jQuery)
<commit_msg>fix display following entities in crawl list when an entity's crawl was canceled<commit_after>;(function($, undefined){

    Hyphen.view = {}

	// Generic quantities
	$(document).on( "/webentities", function(event, eventData){
        switch(eventData.what){
            case "updated":

            var l = Hyphen.model.webEntities.getAll().length
            $('.content_webEntityCount').text(l)
            $('.content_webEntityCount_text').text((l>1)?('web entities'):('web entity'))

            break
        }
    })

    $(document).on( "/crawls", function(event, eventData){
        switch(eventData.what){
            case "updated":

            var l = Hyphen.model.crawlJobs.getAll().length
            $('.content_crawlJobsCount').text(l)
            $('.content_crawlJobsCount_text').text((l>1)?('crawl jobs'):('crawl job'))

            break
        }
    })

    // Web entities proxies
    $(document).on( "/webentities", function(event, eventData){
        switch(eventData.what){
            case "updated":
            Hyphen.view.webEntities.proxiesUpdate()
            break
        }
    })
    Hyphen.view.webEntities = {}
    Hyphen.view.webEntities.proxiesUpdate = function(onlyOutdated){
        $('.webEntity_proxy').each(function(i,proxy){
            Hyphen.view.webEntities.replaceProxyElement($(proxy), onlyOutdated)

        })
    }
    Hyphen.view.webEntities.replaceProxyElement = function(proxyElement, onlyOutdated){
        var we_id = proxyElement.attr('webEntity_id')
            ,we = Hyphen.model.webEntities.get(we_id)
        if(we && !(onlyOutdated && proxyElement.hasClass('webEntity_proxy_updated'))){
            var creationDate = new Date()
                ,lastModificationDate = new Date()
            creationDate.setTime(we.creation_date)
            lastModificationDate.setTime(we.last_modification_date)
            proxyElement.html('')
            proxyElement.addClass('webEntity_proxy_updated')
            proxyElement.append(
                $('').text(we.name)
                    .addClass('info_tooltip')
                    .popover({
                        trigger:'hover'
                        ,title: $('').after($('').text(' '+we.name))
                        ,content:
                            $('
').append(
                                $('
').append(
                                    we.lru_prefixes.map(function(lru){
                                        return $('
').append($('').text(Hyphen.utils.URL_simplify(Hyphen.utils.LRU_to_URL(lru))))
                                        // return $('
').append($('').attr('href', Hyphen.utils.LRU_to_URL(lru)).text(Hyphen.utils.URL_simplify(Hyphen.utils.LRU_to_URL(lru))))
                                    })
                                )
                            ).css('padding-bottom', '10px')
                            .after(
                                $('
').append(
                                    $('').text('Status: ')
                                ).append(
                                    $('').text(we.status)
                                        .addClass(Hyphen.view.webEntities_status_getLabelColor(we.status))
                                )
                            )/*.after($('
').append(
                                    $('').text('Last crawl: ')
                                ).append(
                                    $('
')
                                ).append(
                                    $('').text('Harvesting: '+we.crawling_status.replace('_', ' ').toLowerCase())
                                        .addClass(Hyphen.view.crawlJobs_crawling_getLabelColor(we.crawling_status))
                                ).append(
                                    $('').text(' ')
                                ).append(
                                    $('').text('Indexing: '+we.indexing_status.replace('_', ' ').toLowerCase())
                                        .addClass(Hyphen.view.crawlJobs_indexing_getLabelColor(we.indexing_status))
                                ).append(
                                    $('').text(' ')
                                )
                            )*/.after($('
').append(
                                    $('').text('Modified: ')
                                ).append(
                                    $('').text(Hyphen.utils.prettyDate(lastModificationDate))
                                        .attr('title', lastModificationDate)
                                )
                            )
                    })
            )
        }
        return proxyElement
    }

    Hyphen.view.updateInfoTooltips = function(){
        // Glossary & Tooltip informations
        $('.info_start_pages').attr('title', 'The start pages define where the crawler starts. They are used to compute the depth of other pages.')
        $('.info_start_pages_explanations').attr('title', 'Browse the start pages and check that they are working and not redirected')
        $('.info_prefixes_explanations').attr('title', 'The prefixes define which URLs belong to a web entity. Different prefixes for the same web entity represent its aliases.')
        $(".info_tooltip").tooltip()
    }

	$(document).ready(function () {
	    Hyphen.view.updateInfoTooltips()
  	})

    // Color codes
    Hyphen.view.crawlJobs_crawling_getLabelColor = function(status){
        var crawling_colorClass
        if(status.toLowerCase() == "finished")
            crawling_colorClass = 'label-success'
        else if(status.toLowerCase().indexOf("crashed") >= 0)
            crawling_colorClass = 'label-important'
        else if(status.toLowerCase() == "pending")
            crawling_colorClass = 'label-warning'
        else if(status.toLowerCase() == "canceled")
            crawling_colorClass = 'label-inverse'
        else
            crawling_colorClass = ''
        return crawling_colorClass
    }
    Hyphen.view.crawlJobs_indexing_getLabelColor = function(status){
        var indexing_colorClass
        if(status.toLowerCase() == "finished")
            indexing_colorClass = 'label-success'
        else if(status.toLowerCase().indexOf("crashed") >= 0)
            indexing_colorClass = 'label-important'
        else if(status.toLowerCase() == "pending")
            indexing_colorClass = 'label-warning'
        else
            indexing_colorClass = ''
        return indexing_colorClass
    }
    Hyphen.view.webEntities_status_getLabelColor = function(status){
        return (status=='DISCOVERED')?('label-warning'):(
                (status=='UNDECIDED')?('label-info'):(
                    (status=='OUT')?('label-important'):(
                        (status=='IN')?('label-success'):('')
                    )
                )
            )
    }

})(jQuery)
<|endoftext|>


<commit_before>'use strict';
var questions = [],
    fs = require('fs'),
	JSON5 = require('json5'),
    correctNameEnding,
    jsonData;

var originCountries = ['Україна', 'Англія', 'Франція', 'Іспанія', 'Німеччина', 'Чехія', 'Молдова', 'Уельс', 'Китай', 'Азербайджан', 'Чилі'];

//fs.readFile('./public/freebase_countries.json', 'utf8', function(err, data){
//    jsonData = JSON5.parse(data);
//    getDataFromJson(jsonData, questions);
//    console.log(questionsJS.questions);
//});

for(var i in originCountries) {
    correctNameEnding = changeCountryNameEnding(originCountries[i]);
    questions.push(correctNameEnding);
}

function changeCountryNameEnding(country) {
    var countryLength = country.length,
        endings = country[countryLength-1],
        nameWithoutEnding = country.slice(0, countryLength-1),
        correctName;

    switch(endings) {
        case 'а':
            correctName = nameWithoutEnding+'и';
            break;
        case 'я':
            correctName = nameWithoutEnding+'ї';
            break;
        case 'й':
            correctName = nameWithoutEnding+'я';
            break;
        case 'н':
            correctName = nameWithoutEnding+'на';
            break;
        case 'р':
            correctName = nameWithoutEnding+'ра';
            break;
        case 'с':
            correctName = nameWithoutEnding+'са';
            break;
        case 'ь':
            correctName = nameWithoutEnding+'і';
            break;
        case 'м':
            correctName = nameWithoutEnding+'ма';
            break;
        case 'и':
            correctName = nameWithoutEnding;
            break;
        default:
            correctName = country;
    }

    return correctName;
}

//function getDataFromJson(json, question) {
//	for(var i in json){
//		if(json[i].capital !== null) {
//			question.push({"name": json[i].name, "capital": json[i].capital});
//		}
//		else {
//			question.push({"name": json[i].name, "capital": json[i].name});
//		}
//	}
//}

exports.correctQuestions = function() {
    return questions;
}
<commit_msg>added consonantals and vowels<commit_after>'use strict';
var questions = [],
    fs = require('fs'),
	JSON5 = require('json5'),
    correctNameEnding,
    jsonData,
    consonantals = ["б", "в", "г", "ґ", "д", "ж", "з", "к", "л", "м", "н", "п", "р", "с", "т", "ф", "х", "ц", "ч", "ш", "щ", "й"],
    vowels = ["а", "е", "и", "і", "о", "у", "є", "ю", "я", "ї"];

var originCountries = ['Україна', 'Англія', 'Франція', 'Іспанія', 'Німеччина', 'Чехія', 'Молдова', 'Уельс', 'Китай', 'Азербайджан', 'Чилі'];

//fs.readFile('./public/freebase_countries.json', 'utf8', function(err, data){
//    jsonData = JSON5.parse(data);
//    getDataFromJson(jsonData, questions);
//    console.log(questionsJS.questions);
//});

for(var i in originCountries) {
    correctNameEnding = changeCountryNameEnding(originCountries[i]);
    questions.push(correctNameEnding);
}

function changeCountryNameEnding(country) {
    var countryLength = country.length,
        endings = country[countryLength-1],
        nameWithoutEnding = country.slice(0, countryLength-1),
        correctName;

    switch(endings) {
        case 'а':
            correctName = nameWithoutEnding+'и';
            break;
        case 'я':
            correctName = nameWithoutEnding+'ї';
            break;
        case 'й':
            correctName = nameWithoutEnding+'я';
            break;
        case 'н':
            correctName = nameWithoutEnding+'на';
            break;
        case 'р':
            correctName = nameWithoutEnding+'ра';
            break;
        case 'с':
            correctName = nameWithoutEnding+'са';
            break;
        case 'ь':
            correctName = nameWithoutEnding+'і';
            break;
        case 'м':
            correctName = nameWithoutEnding+'ма';
            break;
        case 'и':
            correctName = nameWithoutEnding;
            break;
        default:
            correctName = country;
    }

    return correctName;
}

//function getDataFromJson(json, question) {
//	for(var i in json){
//		if(json[i].capital !== null) {
//			question.push({"name": json[i].name, "capital": json[i].capital});
//		}
//		else {
//			question.push({"name": json[i].name, "capital": json[i].name});
//		}
//	}
//}

exports.correctQuestions = function() {
    return questions;
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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.
 */

/**
 * @fileoverview Caja is a whitelisting javascript sanitizing rewriter.
 * This file tames the APIs that are exposed to a gadget
 */

var caja___ = (function() {
    // URI policy: Rewrites all uris in a cajoled gadget
  var uriCallback = {
    rewrite: function rewrite(uri, mimeTypes) {
      uri = String(uri);
      // By default, only allow references to anchors.
      if (/^#/.test(uri)) {
        return '#' + encodeURIComponent(decodeURIComponent(uri.substring(1)));
        // and files on the same host
      } else if (/^\/(?:[^\/][^?#]*)?$/.test(uri)) {
        return encodeURI(decodeURI(uri));
      }
      // This callback can be replaced with one that passes the URL through
      // a proxy that checks the mimetype.
      return null;
    }
  };

  var fire = function(globalScope) {
    for (var tamer in tamings___) {
      if (tamings___.hasOwnProperty(tamer)) {
        // This is just tamings___[tamer](globalScope)
        // but in a way that does not leak a potent "this"
        // to the taming functions
        (1, tamings___[tamer])(globalScope);
      }
    }
  }
  function whitelistCtors(schemas) {
    var length = schemas.length;
    for (var i=0; i < length; i++) {
      var schema = schemas[i];
      if (typeof schema[0][schema[1]] === 'function') {
        ___.markCtor(schema[0][schema[1]] /* func */, schema[2] /* parent */, schema[1] /* name */);
      } else {
        gadgets.warn("Error taming constructor: " + schema[0] + "." + schema[1]);
      }
    }
  }
  function whitelistFuncs(schemas) {
    var length = schemas.length;
    for (var i=0; i < length; i++) {
      var schema = schemas[i];
      if (typeof schema[0][schema[1]] === 'function') {
        ___.markInnocent(schema[0][schema[1]], schema[1]);
      } else {
        gadgets.warn("Error taming function: " + schema[0] + "." + schema[1]);
      }
    }
  }
  function whitelistMeths(schemas) {
    var length = schemas.length;
    for (var i=0; i < length; i++) {
      var schema = schemas[i];
      if (typeof schema[0][schema[1]] == 'function') {
        ___.grantInnocentMethod(schema[0].prototype, schema[1]);
      } else {
        gadgets.warn("Error taming method: " + schema[0] + "." + schema[1]);
      }
    }
  }

  function enable() {
    var imports = ___.copy(___.sharedImports);
    imports.outers = imports;

    var gadgetRoot = document.getElementById('cajoled-output');
    gadgetRoot.className = 'g___';
    document.body.appendChild(gadgetRoot);

    imports.htmlEmitter___ = new HtmlEmitter(gadgetRoot);
    attachDocumentStub('-g___', uriCallback, imports, gadgetRoot);

    imports.$v = valijaMaker.CALL___(imports.outers);

    ___.getNewModuleHandler().setImports(imports);

    fire(imports);

    imports.outers.gadgets = ___.tame(window.gadgets);
    imports.outers.opensocial = ___.tame(window.opensocial);
    ___.grantRead(imports.outers, 'gadgets');
    ___.grantRead(imports.outers, 'opensocial');
  }
  return {
    enable: enable,
    whitelistCtors: whitelistCtors,
    whitelistFuncs: whitelistFuncs,
    whitelistMeths: whitelistMeths
  };
})();

// Expose alert and console.log to cajoled programs
var tamings___ = tamings___ || [];
tamings___.push(function(imports) {
  imports.outers.alert = function(msg) { alert(msg); };
  ___.grantFunc(imports.outers, 'alert');
});
<commit_msg>Oops - trivial change missed from my last patch without which taming will not work<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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.
 */

/**
 * @fileoverview Caja is a whitelisting javascript sanitizing rewriter.
 * This file tames the APIs that are exposed to a gadget
 */

var caja___ = (function() {
    // URI policy: Rewrites all uris in a cajoled gadget
  var uriCallback = {
    rewrite: function rewrite(uri, mimeTypes) {
      uri = String(uri);
      // By default, only allow references to anchors.
      if (/^#/.test(uri)) {
        return '#' + encodeURIComponent(decodeURIComponent(uri.substring(1)));
        // and files on the same host
      } else if (/^\/(?:[^\/][^?#]*)?$/.test(uri)) {
        return encodeURI(decodeURI(uri));
      }
      // This callback can be replaced with one that passes the URL through
      // a proxy that checks the mimetype.
      return null;
    }
  };

  var fire = function(globalScope) {
    for (var tamer in tamings___) {
      if (tamings___.hasOwnProperty(tamer)) {
        // This is just tamings___[tamer](globalScope)
        // but in a way that does not leak a potent "this"
        // to the taming functions
        (1, tamings___[tamer])(globalScope);
      }
    }
  }
  function whitelistCtors(schemas) {
    var length = schemas.length;
    for (var i=0; i < length; i++) {
      var schema = schemas[i];
      if (typeof schema[0][schema[1]] === 'function') {
        ___.markCtor(schema[0][schema[1]] /* func */, schema[2] /* parent */, schema[1] /* name */);
      } else {
        gadgets.warn("Error taming constructor: " + schema[0] + "." + schema[1]);
      }
    }
  }
  function whitelistFuncs(schemas) {
    var length = schemas.length;
    for (var i=0; i < length; i++) {
      var schema = schemas[i];
      if (typeof schema[0][schema[1]] === 'function') {
        ___.markInnocent(schema[0][schema[1]], schema[1]);
      } else {
        gadgets.warn("Error taming function: " + schema[0] + "." + schema[1]);
      }
    }
  }
  function whitelistMeths(schemas) {
    var length = schemas.length;
    for (var i=0; i < length; i++) {
      var schema = schemas[i];
      if (typeof schema[0].prototype[schema[1]] == 'function') {
        ___.grantInnocentMethod(schema[0].prototype, schema[1]);
      } else {
        gadgets.warn("Error taming method: " + schema[0] + "." + schema[1]);
      }
    }
  }

  function enable() {
    var imports = ___.copy(___.sharedImports);
    imports.outers = imports;

    var gadgetRoot = document.getElementById('cajoled-output');
    gadgetRoot.className = 'g___';
    document.body.appendChild(gadgetRoot);

    imports.htmlEmitter___ = new HtmlEmitter(gadgetRoot);
    attachDocumentStub('-g___', uriCallback, imports, gadgetRoot);

    imports.$v = valijaMaker.CALL___(imports.outers);

    ___.getNewModuleHandler().setImports(imports);

    fire(imports);

    imports.outers.gadgets = ___.tame(window.gadgets);
    imports.outers.opensocial = ___.tame(window.opensocial);
    ___.grantRead(imports.outers, 'gadgets');
    ___.grantRead(imports.outers, 'opensocial');
  }
  return {
    enable: enable,
    whitelistCtors: whitelistCtors,
    whitelistFuncs: whitelistFuncs,
    whitelistMeths: whitelistMeths
  };
})();

// Expose alert and console.log to cajoled programs
var tamings___ = tamings___ || [];
tamings___.push(function(imports) {
  imports.outers.alert = function(msg) { alert(msg); };
  ___.grantFunc(imports.outers, 'alert');
});
<|endoftext|>


<commit_before>/* eslint-disable global-require */
import $ from 'jquery';

const utils = require('./modules/utils');

$(document).ready(function () {
  $(':checkbox[data-checkbox-api-prefix]').change(function () {
    const $this = $(this);
    const prefix = $this.data('checkbox-api-prefix');
    const id = $this.attr('id');
    utils.toggleCheckbox(prefix, '#' + id);
  });
});

export function appSetup() {
  // A set of hacks to allow apps to run within a FAB template
  // this allows for the server side generated menus to function
  window.$ = $;
  window.jQuery = $;
  require('bootstrap');
}
<commit_msg>Update common.js<commit_after>/* eslint-disable global-require */
//this is a comment//
import $ from 'jquery';

const utils = require('./modules/utils');

$(document).ready(function () {
  $(':checkbox[data-checkbox-api-prefix]').change(function () {
    const $this = $(this);
    const prefix = $this.data('checkbox-api-prefix');
    const id = $this.attr('id');
    utils.toggleCheckbox(prefix, '#' + id);
  });
});

export function appSetup() {
  // A set of hacks to allow apps to run within a FAB template
  // this allows for the server side generated menus to function
  window.$ = $;
  window.jQuery = $;
  require('bootstrap');
}
<|endoftext|>


<commit_before>if("undefined"==typeof OGX)var OGX=function(){};OGX.prototype.MobileChatBox=function(e){"use strict";function o(){v.empty();for(var e=0;e<w.messages.length;e++)t(w.messages[e])}function t(e){var o=r(e),t=l(e,o);v.append(t),setTimeout(function(){v.children('.ogx_mobile_chat_box_message[data-user="'+e.user+'"]').addClass("ogx_mobile_chat_box_message_anim")},100)}function n(e){E[e]=!0;var o='
.

';v.append(o),i(!0)}function a(e){E[e]=!1,v.find('.ogx_mobile_chat_box_typing[data-user="'+e+'"]').remove(),0===v.find(".ogx_mobile_chat_box_typing").length&&i(!1)}function i(e){e?M||(M=setInterval(s,w.dot_speed)):(clearInterval(M),M=null)}function s(){S+=".",S.length>3?S=".":null,v.find(".ogx_mobile_chat_box_typing_body").html(S)}function r(e){return e.user.toString()===w.users.current?w.template_right:w.template_left}function l(e,o){var t=o;for(var n in e)reg=new RegExp("\\$"+n,"g"),t=t.replace(reg,e[n]);return t}function _(){var e=O.find("textarea:first").val(),o=new Date;if(e.length>0){var n={from:"appraiser",msg:e,date:o.toISOString().split("T").shift()};t(n),O.find("textarea:first").val(""),C.el.trigger(OGX.MobileChatBox.SEND_MSG,n)}}function c(e){var o=u.height()-O.height()-e.keyboardHeight;O.css({transform:"translate3D(0px, "+o+"px, 0px)"})}function d(){O.css({transform:"translate3D(0px, "+(u.height()-O.height())+"px, 0px)"}),_()}function g(e){e?(window.addEventListener("native.keyboardshow",c),window.addEventListener("native.keyboardhide",d)):(window.removeEventListener("native.keyboardshow",c),window.removeEventListener("native.keyboardhide",d))}function b(e){e?O.on("click",".ogx_mobile_chat_box_composer_send",function(){d()}):O.off("click",".ogx_mobile_chat_box_composer_send")}function h(){var e=$(window).height(),o='
<textarea placeholder="'+w.placeholder+'">';o+='</textarea>
',u.prepend(o),O=u.find(".ogx_mobile_chat_box_composer:first"),e=O.height(),O.css("transform","translateY("+-e+"px)")}function p(){y=new OGX.MobileScrollContainer({container:C.el[0],initDelay:100,autoScroll:!0}),C.el.on(OGX.MobileScrollContainer.READY,function(){C.el.off(OGX.MobileScrollContainer.READY),v=y.getInner(),v=$(v),v.addClass("ogx_mobile_chat_box"),o()})}function x(){for(var e in w.users)E[e]=!1}function m(){for(var e in G)w.hasOwnProperty(e)||(w[e]=G[e]);C.el=u=$(w.container)}function f(){return"undefined"==typeof OGX.MobileScrollContainer?void console.log("%c CRITICAL ERROR - OGX.MobileScrollContainer not found! ","background:#222; color: #FF0000"):(m(),h(),x(),p(),g(!0),void b(!0))}var u,v,y,O,M,C=this,w=e,G={placeholder:"Type a message",dot_speed:600,messages:[],mode:OGX.MobileChatBox.MODE_DESKTOP,template_left:'
M$msg
',template_right:'
$msg
'},E={},S=".";this.el=null,this.addMessage=function(e){t(e)},this.userTyping=function(e,o){e&&!E[o]?n(o):!e&&E[o]&&a(o)},f()},OGX.MobileChatBox=function(e){"use strict";return new OGX.prototype.MobileChatBox(e)},OGX.MobileChatBox.MODE_DESKTOP="desktop",OGX.MobileChatBox.MODE_MOBILE="mobile",OGX.MobileChatBox.SEND_MSG="MobileChatBoxSend";<commit_msg>composer y<commit_after>if("undefined"==typeof OGX)var OGX=function(){};OGX.prototype.MobileChatBox=function(e){"use strict";function o(){v.empty();for(var e=0;e<w.messages.length;e++)t(w.messages[e])}function t(e){var o=r(e),t=l(e,o);v.append(t),setTimeout(function(){v.children('.ogx_mobile_chat_box_message[data-user="'+e.user+'"]').addClass("ogx_mobile_chat_box_message_anim")},100)}function n(e){E[e]=!0;var o='
.

';v.append(o),i(!0)}function a(e){E[e]=!1,v.find('.ogx_mobile_chat_box_typing[data-user="'+e+'"]').remove(),0===v.find(".ogx_mobile_chat_box_typing").length&&i(!1)}function i(e){e?M||(M=setInterval(s,w.dot_speed)):(clearInterval(M),M=null)}function s(){S+=".",S.length>3?S=".":null,v.find(".ogx_mobile_chat_box_typing_body").html(S)}function r(e){return e.user.toString()===w.users.current?w.template_right:w.template_left}function l(e,o){var t=o;for(var n in e)reg=new RegExp("\\$"+n,"g"),t=t.replace(reg,e[n]);return t}function _(){var e=O.find("textarea:first").val(),o=new Date;if(e.length>0){var n={from:"appraiser",msg:e,date:o.toISOString().split("T").shift()};t(n),O.find("textarea:first").val(""),C.el.trigger(OGX.MobileChatBox.SEND_MSG,n)}}function c(e){var o=u.height()-u.position.top()-O.height()-e.keyboardHeight;O.css({transform:"translate3D(0px, "+o+"px, 0px)"})}function d(){O.css({transform:"translate3D(0px, "+(u.height()-u.position.top()-O.height())+"px, 0px)"}),_()}function g(e){e?(window.addEventListener("native.keyboardshow",c),window.addEventListener("native.keyboardhide",d)):(window.removeEventListener("native.keyboardshow",c),window.removeEventListener("native.keyboardhide",d))}function p(e){e?O.on("click",".ogx_mobile_chat_box_composer_send",function(){d()}):O.off("click",".ogx_mobile_chat_box_composer_send")}function b(){var e=$(window).height(),o='
<textarea placeholder="'+w.placeholder+'">';o+='</textarea>
',u.prepend(o),O=u.find(".ogx_mobile_chat_box_composer:first"),e=O.height(),O.css("transform","translateY("+-e+"px)")}function h(){y=new OGX.MobileScrollContainer({container:C.el[0],initDelay:100,autoScroll:!0}),C.el.on(OGX.MobileScrollContainer.READY,function(){C.el.off(OGX.MobileScrollContainer.READY),v=y.getInner(),v=$(v),v.addClass("ogx_mobile_chat_box"),o()})}function x(){for(var e in w.users)E[e]=!1}function m(){for(var e in G)w.hasOwnProperty(e)||(w[e]=G[e]);C.el=u=$(w.container)}function f(){return"undefined"==typeof OGX.MobileScrollContainer?void console.log("%c CRITICAL ERROR - OGX.MobileScrollContainer not found! ","background:#222; color: #FF0000"):(m(),b(),x(),h(),g(!0),void p(!0))}var u,v,y,O,M,C=this,w=e,G={placeholder:"Type a message",dot_speed:600,messages:[],mode:OGX.MobileChatBox.MODE_DESKTOP,template_left:'
M$msg
',template_right:'
$msg
'},E={},S=".";this.el=null,this.addMessage=function(e){t(e)},this.userTyping=function(e,o){e&&!E[o]?n(o):!e&&E[o]&&a(o)},f()},OGX.MobileChatBox=function(e){"use strict";return new OGX.prototype.MobileChatBox(e)},OGX.MobileChatBox.MODE_DESKTOP="desktop",OGX.MobileChatBox.MODE_MOBILE="mobile",OGX.MobileChatBox.SEND_MSG="MobileChatBoxSend";<|endoftext|>