<commit_before>require('source-map-support').install()

var Concat = require('concat-stream')
var Fs = require('fs')
var Through2 = require('through2')
var Assert = require('assert')
var Stream = require('stream')
var path = require('path')
var credentials = require(path.join(process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'], 'credentials.json'))
var Minio = require('../../..')

describe('minio', () => {
    var client = new Minio({
      url: 'https://s3-us-west-2.amazonaws.com',
      accessKey: credentials.accesskey,
      secretKey: credentials.secretkey
        // url: 'https://play.minio.io:9000'
    })
    var bucket = 'goroutine-js-integration'
    describe('bucket integration', () => {
      it('should clean up old buckets', (done) => {
        client.bucketExists(bucket, (e) => {
          if (e) {
            return done()
          }
          client.removeBucket(bucket, (e) => {
            done(e)
          })
        })
      })
      it('should create a new bucket', (done) => {
        client.makeBucket(bucket, (done))
      })
      it('should fail to cretae an existing', (done) => {
        client.makeBucket(bucket, (e) => {
          done()
        })
      })
      it('should list buckets', (done) => {
        var bucketStream = client.listBuckets()
        var found = false
        var foundError = null
        bucketStream.pipe(Through2.obj(function(chunk, enc, end) {
          if (chunk.name === bucket) {
            found = true
          }
          end()
        }, function(end) {
          end()
          if (foundError) {
            return done(foundError)
          } else if (found === false) {
            return done('bucket not found')
          }
          done()
        }))
        bucketStream.on('error', (e) => {
          foundError = e
        })
      })
      it('should head bucket', (done) => {
        client.bucketExists(bucket, done)
      })
      it('should get acl private', (done) => {
        client.getBucketACL(bucket, (e, r) => {
          Assert.equal(r, 'private')
          done(e)
        })
      })
      it('should set acl authenticated read', (done) => {
        client.setBucketACL(bucket, 'authenticated-read', done)
      })
      it('should get acl authenticated read', (done) => {
        client.getBucketACL(bucket, (e, r) => {
          Assert.equal(r, 'authenticated-read')
          done(e)
        })
      })
      it('should set acl private', (done) => {
        client.setBucketACL(bucket, 'private', done)
      })
      it('should get acl', (done) => {
        client.getBucketACL(bucket, (e, r) => {
          Assert.equal(r, 'private')
          done(e)
        })
      })
    })
    describe('object integration', () => {
      it('get object should return an error on no object', (done) => {
        client.getObject(bucket, 'noobject', (e, r) => {
          if (!e) {
            done('expecting error')
          }
          done()
        })
      })
      it('should put an object', (done) => {
        var stream = new Stream.Readable()
        stream._read = () => {}
        stream.push('hello')
        stream.push(' ')
        stream.push('world')
        stream.push(null)
        client.putObject(bucket, 'hello/world', '', 11, stream, done)
      })
      it('should get an object', (done) => {
        client.getObject(bucket, 'hello/world', (e, r) => {
          if (e) {
            return done(e)
          }
          r.pipe(Concat((data) => {
            Assert.equal(data, 'hello world')
            done()
          }))
        })
      })
      it('should put a large object', function(done) {
        var file = '11mb'
        var size = 0
        this.timeout(10000)
        Fs.stat(file, function(e, stat) {
          var fileStream = Fs.createReadStream(file)
          var r = fileStream.pipe(Through2(function(chunk, enc, end) {
            size += chunk.length
            end(null, chunk)
          }, function(end) {
            console.log('amount sent: ' + size)
            end()
          }))
          client.putObject(bucket, 'hello/world2', '', 11 * 1024 * 1024, r, (e) => {
            done(e)
          })
        })
      })
      it('should drop multipart uploads', (done) => {
        client.dropAllIncompleteUploads(bucket, done)
      })
      it('should delete objects', (done) => {
        var objects = client.listObjects(bucket)
        objects.pipe(Through2.obj(function(chunk, enc, end) {
          console.log(chunk)
          client.removeObject(bucket, chunk.name, end)
        }, function(end) {
          end()
          done()
        }))
      })
    })
  })
<commit_msg>Beautifying integration.js<commit_after>require('source-map-support').install()

var Concat = require('concat-stream')
var Fs = require('fs')
var Through2 = require('through2')
var Assert = require('assert')
var Stream = require('stream')
var path = require('path')
var credentials = require(path.join(process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'], 'credentials.json'))
var Minio = require('../../..')

describe('minio', () => {
  var client = new Minio({
    url: 'https://s3-us-west-2.amazonaws.com',
    accessKey: credentials.accesskey,
    secretKey: credentials.secretkey
      // url: 'https://play.minio.io:9000'
  })
  var bucket = 'goroutine-js-integration'
  describe('bucket integration', () => {
    it('should clean up old buckets', (done) => {
      client.bucketExists(bucket, (e) => {
        if (e) {
          return done()
        }
        client.removeBucket(bucket, (e) => {
          done(e)
        })
      })
    })
    it('should create a new bucket', (done) => {
      client.makeBucket(bucket, (done))
    })
    it('should fail to cretae an existing', (done) => {
      client.makeBucket(bucket, (e) => {
        done()
      })
    })
    it('should list buckets', (done) => {
      var bucketStream = client.listBuckets()
      var found = false
      var foundError = null
      bucketStream.pipe(Through2.obj(function(chunk, enc, end) {
        if (chunk.name === bucket) {
          found = true
        }
        end()
      }, function(end) {
        end()
        if (foundError) {
          return done(foundError)
        } else if (found === false) {
          return done('bucket not found')
        }
        done()
      }))
      bucketStream.on('error', (e) => {
        foundError = e
      })
    })
    it('should head bucket', (done) => {
      client.bucketExists(bucket, done)
    })
    it('should get acl private', (done) => {
      client.getBucketACL(bucket, (e, r) => {
        Assert.equal(r, 'private')
        done(e)
      })
    })
    it('should set acl authenticated read', (done) => {
      client.setBucketACL(bucket, 'authenticated-read', done)
    })
    it('should get acl authenticated read', (done) => {
      client.getBucketACL(bucket, (e, r) => {
        Assert.equal(r, 'authenticated-read')
        done(e)
      })
    })
    it('should set acl private', (done) => {
      client.setBucketACL(bucket, 'private', done)
    })
    it('should get acl', (done) => {
      client.getBucketACL(bucket, (e, r) => {
        Assert.equal(r, 'private')
        done(e)
      })
    })
  })
  describe('object integration', () => {
    it('get object should return an error on no object', (done) => {
      client.getObject(bucket, 'noobject', (e, r) => {
        if (!e) {
          done('expecting error')
        }
        done()
      })
    })
    it('should put an object', (done) => {
      var stream = new Stream.Readable()
      stream._read = () => {}
      stream.push('hello')
      stream.push(' ')
      stream.push('world')
      stream.push(null)
      client.putObject(bucket, 'hello/world', '', 11, stream, done)
    })
    it('should get an object', (done) => {
      client.getObject(bucket, 'hello/world', (e, r) => {
        if (e) {
          return done(e)
        }
        r.pipe(Concat((data) => {
          Assert.equal(data, 'hello world')
          done()
        }))
      })
    })
    it('should put a large object', function(done) {
      var file = '11mb'
      var size = 0
      this.timeout(10000)
      Fs.stat(file, function(e, stat) {
        var fileStream = Fs.createReadStream(file)
        var r = fileStream.pipe(Through2(function(chunk, enc, end) {
          size += chunk.length
          end(null, chunk)
        }, function(end) {
          console.log('amount sent: ' + size)
          end()
        }))
        client.putObject(bucket, 'hello/world2', '', 11 * 1024 * 1024, r, (e) => {
          done(e)
        })
      })
    })
    it('should drop multipart uploads', (done) => {
      client.dropAllIncompleteUploads(bucket, done)
    })
    it('should delete objects', (done) => {
      var objects = client.listObjects(bucket)
      objects.pipe(Through2.obj(function(chunk, enc, end) {
        console.log(chunk)
        client.removeObject(bucket, chunk.name, end)
      }, function(end) {
        end()
        done()
      }))
    })
  })
})
<|endoftext|>


<commit_before>import $ from "jquery";
import chroma from "chroma-js";
import {
  createItemLink,
  generateColumnOrderInfo,
  tableConfig
} from "../../../utilities/datatables-utilities";
import { formatDate } from "../../../utilities/date-utilities";
import "./../../../vendor/datatables/datatables";
import "./../../../vendor/datatables/datatables-buttons";
import "./../../../vendor/datatables/datatables-rowSelection";
import { CART } from "../../../utilities/events-utilities";
import SampleDropdownButton from "./SampleDropdownButton";

/*
 Initialize the sample tools menu.
 */
const SAMPLE_TOOL_ACTIONS = {
  "cart-add-btn"() {
    const selected = $dt.select.selected()[0];
    /*
    Selected data needs to be formatted into an object: {projectId => [sampleIds]}
     */
    const projects = {};
    selected.forEach(item => {
      projects[item.project] = projects[item.project] || [];
      projects[item.project].push(item.sample);
    });

    /*
    Update the cart with the new samples.
     */
    const event = new CustomEvent(CART.ADD, { detail: { projects } });
    document.dispatchEvent(event);
  }
};

const POPOVER_OPTIONS = {
  container: "body",
  trigger: "hover",
  placement: "right",
  html: true,
  template: $("#popover-template").clone()
};

const sampleToolsNodes = document.querySelectorAll(".sample-tool-btn");
const SAMPLE_TOOL_BUTTONS = [...sampleToolsNodes].map(
  elm => new SampleDropdownButton(elm, SAMPLE_TOOL_ACTIONS[elm.id])
);

/**
 * Reference to the currently selected associated projects.
 * @type {Map}
 */
const ASSOCIATED_PROJECTS = new Map();

/**
 * Reference to the colour for a specific project.
 * @type {Map}
 */
const PROJECT_COLOURS = (function() {
  const colours = new Map();
  $(".associated-cb input").each((i, elm) => {
    const input = $(elm);
    const colour = chroma.random();
    /*
    Add some colour to the checkbox so it can easily be
    associated with the name in the table
     */
    $(
      `<div class="label-bar-color" style="margin: 0; background-color: ${colour}"> </div>`
    ).insertAfter(input);

    colours.set(Number(input.val()), colour);
  });
  return colours;
})();

/**
 *  Get the names and order of the table columns
 * @type {Object}
 */
const COLUMNS = generateColumnOrderInfo();

/**
 * Get a handle on the table
 * @type {*|jQuery|HTMLElement}
 */
const $table = $("#samplesTable");

/**
 * Get access the the url for the tables data.
 * @type {string}
 */
const url = $table.data("url");

const config = Object.assign({}, tableConfig, {
  ajax: {
    url,
    data(d) {
      /*
      Add any extra parameters that need to be passed to the server
      here.
       */
      if (ASSOCIATED_PROJECTS.size > 0) {
        // Add a list of ids for currently visible associated projects
        d.associated = Array.from(ASSOCIATED_PROJECTS.keys());
      }
    }
  },
  stateSave: true,
  deferRender: true,
  select: {
    allUrl: window.PAGE.urls.samples.sampleIds,
    allPostDataFn() {
      return {
        associated: [...ASSOCIATED_PROJECTS.keys()]
      };
    },
    formatSelectAllResponseFn(response) {
      // This is a callback function used by datatables-select
      // to format the server response when selectAll is clicked.
      // It puts the response into the format of the `data-info` attribute
      // set on the row itself ({row_id: {projectId, sampleId}}
      const projectIds = Object.keys(response);
      const complete = new Map();
      for (const pId of projectIds) {
        for (const sId of response[pId]) {
          complete.set(`row_${sId}`, {
            project: pId,
            sample: sId
          });
        }
      }
      return complete;
    }
  },
  order: [[COLUMNS.MODIFIED_DATE, "desc"]],
  rowId: "DT_RowId",
  buttons: ["selectAll", "selectNone"],
  language: {
    select: window.PAGE.i18n.select,
    buttons: {
      selectAll: window.PAGE.i18n.buttons.selectAll,
      selectNone: window.PAGE.i18n.buttons.selectNone
    }
  },
  columnDefs: [
    // Add an empty checkbox to the first column in each row
    // This will handle row selection.
    {
      orderable: false,
      data: null,
      render() {
        return `<input type="checkbox"/>`;
      },
      targets: 0
    },
    {
      targets: [COLUMNS.SAMPLE_NAME],
      render(data, type, full) {
        return createItemLink({
          url: `${window.TL
            .BASE_URL}projects/${full.projectId}/samples/${full.id}`,
          label: full.sampleName
        });
      }
    },
    {
      targets: [COLUMNS.PROJECT_NAME],
      render(data, type, full) {
        return createItemLink({
          url: `${window.TL.BASE_URL}projects/${full.projectId}`,
          label: `

${data}`,
          classes: ["project-link"]
        });
      }
    },
    {
      targets: [COLUMNS.CREATED_DATE, COLUMNS.MODIFIED_DATE],
      render(data) {
        return `<time>${formatDate({ date: data })}</time>`;
      }
    }
  ],
  drawCallback() {
    $('[data-toggle="popover"]').popover(POPOVER_OPTIONS);
  },
  createdRow(row, data) {
    row.dataset.info = JSON.stringify({
      project: data.projectId,
      sample: data.id
    });

    /*
    Check if this sample has any quality control issues.
    If there are they will be displayed in a popover.
     */
    if (data.qcEntries.length) {
      const $row = $(row);
      $row.addClass("row-warning");

      const icon = $(".qc-warning-wrapper").clone();
      /*
      Generate the content for the popover
       */
      const content = `

          ${data.qcEntries.map(qc => `<li class="error">${qc}</li>`)}

`;
      icon.data("content", content);
      const td = $row.find(`td:nth-of-type(${COLUMNS.SAMPLE_NAME + 1})`);
      td.css("position", "relative");
      icon.appendTo(td);
    }
  }
});

const $dt = $table.DataTable(config);

// This allows for the use of checkboxes in the dropdown without
// it closing on every click.
const ASSOCIATED_INPUTS = $(".associated-cb input");
$(".associated-dd .dropdown-menu a").on("click", function(event) {
  /*
  Find the input element.
   */
  const $inp = $(event.currentTarget).find("input");
  const id = $inp.val();

  /*
  This is a little finicky.  If the user clicked the actual input element,
  then get the checked property of the input.  Else the input has not yet changed
  so get its opposite.
   */
  const checked =
    event.target instanceof HTMLInputElement
      ? $inp.prop("checked")
      : !$inp.prop("checked");

  if (id === "ALL") {
    // Need to get all the ids and select all the checkboxes
    ASSOCIATED_INPUTS.each((index, elm) => {
      const $elm = $(elm);
      $elm.prop("checked", checked);

      if (checked) {
        ASSOCIATED_PROJECTS.set($elm.val(), true);
      } else {
        ASSOCIATED_PROJECTS.delete($elm.val());
      }
    });
  } else {
    if (ASSOCIATED_PROJECTS.has(id)) {
      ASSOCIATED_PROJECTS.delete(id);
    } else {
      ASSOCIATED_PROJECTS.set(id, true);
    }
  }

  setTimeout(function() {
    // Update the current checkbox
    $inp.prop("checked", checked);
    // Update the select all checkbox
    $("#select-all-cb").prop(
      "checked",
      ASSOCIATED_PROJECTS.size === ASSOCIATED_INPUTS.size()
    );
    // Update the DataTable
    $dt.ajax.reload(null, false);
  }, 0);

  $(event.target).blur();
  return false;
});

/*
TABLE EVENT HANDLERS
 */

// Row selection events.
$dt.on("selection-count.dt", function(e, count) {
  /*
  Update the state of the buttons in the navbar.
   */
  for (const btn of SAMPLE_TOOL_BUTTONS) {
    btn.checkState(count);
  }
});

/*
Store reference to handle different modals.
 */
const MODALS = {
  /**
   * Hanle opening the merge modal.
   * @param {string} url for the content of the modal
   * @param {string} src url for the javascript needed for modal.
   * @param {list} sampleIds list of sample ids to merge.
   */
  merge({ url, src, sampleIds }) {
    const modal = $(this);

    /*
    Load the content for the dialogue based on the server response.
     */
    modal.load(`${url}?${$.param({ sampleIds })}`, function() {
      if (typeof src !== "undefined") {
        const script = document.createElement("script");
        script.type = "text/javascript";
        script.src = src;
        document.getElementsByTagName("head")[0].appendChild(script);
      }
    });

    /*
    Handle the closing the modal
     */
    modal.on("samples:merged", function(e) {
      $(this).modal("hide");
      $dt.select.selectNone();
      $dt.ajax.reload();
    });
  }
};

/*
Handle MERGE through the modal window.
 */
$("#modal-wrapper").on("show.bs.modal", function(event) {
  const wrapper = this;
  /*
  Determine which modal to open
   */
  const btn = $(event.relatedTarget);
  const whichModal = btn.data("modal");
  const url = btn.data("url");
  const script = btn.data("script");

  /*
  Find the ids for the currently selected samples.
   */
  const selected = $dt.select.selected()[0];
  const sampleIds = [];
  for (let [key, value] of selected) {
    sampleIds.push(value.sample);
  }

  MODALS[whichModal].call(wrapper, { url, src: script, sampleIds });
});
<commit_msg>Fixed issue with coma appearing in QC list<commit_after>import $ from "jquery";
import chroma from "chroma-js";
import {
  createItemLink,
  generateColumnOrderInfo,
  tableConfig
} from "../../../utilities/datatables-utilities";
import { formatDate } from "../../../utilities/date-utilities";
import "./../../../vendor/datatables/datatables";
import "./../../../vendor/datatables/datatables-buttons";
import "./../../../vendor/datatables/datatables-rowSelection";
import { CART } from "../../../utilities/events-utilities";
import SampleDropdownButton from "./SampleDropdownButton";

/*
 Initialize the sample tools menu.
 */
const SAMPLE_TOOL_ACTIONS = {
  "cart-add-btn"() {
    const selected = $dt.select.selected()[0];
    /*
    Selected data needs to be formatted into an object: {projectId => [sampleIds]}
     */
    const projects = {};
    selected.forEach(item => {
      projects[item.project] = projects[item.project] || [];
      projects[item.project].push(item.sample);
    });

    /*
    Update the cart with the new samples.
     */
    const event = new CustomEvent(CART.ADD, { detail: { projects } });
    document.dispatchEvent(event);
  }
};

const POPOVER_OPTIONS = {
  container: "body",
  trigger: "hover",
  placement: "right",
  html: true,
  template: $("#popover-template").clone()
};

const sampleToolsNodes = document.querySelectorAll(".sample-tool-btn");
const SAMPLE_TOOL_BUTTONS = [...sampleToolsNodes].map(
  elm => new SampleDropdownButton(elm, SAMPLE_TOOL_ACTIONS[elm.id])
);

/**
 * Reference to the currently selected associated projects.
 * @type {Map}
 */
const ASSOCIATED_PROJECTS = new Map();

/**
 * Reference to the colour for a specific project.
 * @type {Map}
 */
const PROJECT_COLOURS = (function() {
  const colours = new Map();
  $(".associated-cb input").each((i, elm) => {
    const input = $(elm);
    const colour = chroma.random();
    /*
    Add some colour to the checkbox so it can easily be
    associated with the name in the table
     */
    $(
      `<div class="label-bar-color" style="margin: 0; background-color: ${colour}"> </div>`
    ).insertAfter(input);

    colours.set(Number(input.val()), colour);
  });
  return colours;
})();

/**
 *  Get the names and order of the table columns
 * @type {Object}
 */
const COLUMNS = generateColumnOrderInfo();

/**
 * Get a handle on the table
 * @type {*|jQuery|HTMLElement}
 */
const $table = $("#samplesTable");

/**
 * Get access the the url for the tables data.
 * @type {string}
 */
const url = $table.data("url");

const config = Object.assign({}, tableConfig, {
  ajax: {
    url,
    data(d) {
      /*
      Add any extra parameters that need to be passed to the server
      here.
       */
      if (ASSOCIATED_PROJECTS.size > 0) {
        // Add a list of ids for currently visible associated projects
        d.associated = Array.from(ASSOCIATED_PROJECTS.keys());
      }
    }
  },
  stateSave: true,
  deferRender: true,
  select: {
    allUrl: window.PAGE.urls.samples.sampleIds,
    allPostDataFn() {
      return {
        associated: [...ASSOCIATED_PROJECTS.keys()]
      };
    },
    formatSelectAllResponseFn(response) {
      // This is a callback function used by datatables-select
      // to format the server response when selectAll is clicked.
      // It puts the response into the format of the `data-info` attribute
      // set on the row itself ({row_id: {projectId, sampleId}}
      const projectIds = Object.keys(response);
      const complete = new Map();
      for (const pId of projectIds) {
        for (const sId of response[pId]) {
          complete.set(`row_${sId}`, {
            project: pId,
            sample: sId
          });
        }
      }
      return complete;
    }
  },
  order: [[COLUMNS.MODIFIED_DATE, "desc"]],
  rowId: "DT_RowId",
  buttons: ["selectAll", "selectNone"],
  language: {
    select: window.PAGE.i18n.select,
    buttons: {
      selectAll: window.PAGE.i18n.buttons.selectAll,
      selectNone: window.PAGE.i18n.buttons.selectNone
    }
  },
  columnDefs: [
    // Add an empty checkbox to the first column in each row
    // This will handle row selection.
    {
      orderable: false,
      data: null,
      render() {
        return `<input type="checkbox"/>`;
      },
      targets: 0
    },
    {
      targets: [COLUMNS.SAMPLE_NAME],
      render(data, type, full) {
        return createItemLink({
          url: `${window.TL
            .BASE_URL}projects/${full.projectId}/samples/${full.id}`,
          label: full.sampleName
        });
      }
    },
    {
      targets: [COLUMNS.PROJECT_NAME],
      render(data, type, full) {
        return createItemLink({
          url: `${window.TL.BASE_URL}projects/${full.projectId}`,
          label: `

${data}`,
          classes: ["project-link"]
        });
      }
    },
    {
      targets: [COLUMNS.CREATED_DATE, COLUMNS.MODIFIED_DATE],
      render(data) {
        return `<time>${formatDate({ date: data })}</time>`;
      }
    }
  ],
  drawCallback() {
    $('[data-toggle="popover"]').popover(POPOVER_OPTIONS);
  },
  createdRow(row, data) {
    row.dataset.info = JSON.stringify({
      project: data.projectId,
      sample: data.id
    });

    /*
    Check if this sample has any quality control issues.
    If there are they will be displayed in a popover.
     */
    if (data.qcEntries.length) {
      const $row = $(row);
      $row.addClass("row-warning");

      const icon = $(".qc-warning-wrapper").clone();
      /*
      Generate the content for the popover
       */
      debugger;
      const content = `

          ${data.qcEntries.map(qc => `<li class="error">${qc}</li>`).join("")}

`;
      icon.data("content", content);
      const td = $row.find(`td:nth-of-type(${COLUMNS.SAMPLE_NAME + 1})`);
      td.css("position", "relative");
      icon.appendTo(td);
    }
  }
});

const $dt = $table.DataTable(config);

// This allows for the use of checkboxes in the dropdown without
// it closing on every click.
const ASSOCIATED_INPUTS = $(".associated-cb input");
$(".associated-dd .dropdown-menu a").on("click", function(event) {
  /*
  Find the input element.
   */
  const $inp = $(event.currentTarget).find("input");
  const id = $inp.val();

  /*
  This is a little finicky.  If the user clicked the actual input element,
  then get the checked property of the input.  Else the input has not yet changed
  so get its opposite.
   */
  const checked =
    event.target instanceof HTMLInputElement
      ? $inp.prop("checked")
      : !$inp.prop("checked");

  if (id === "ALL") {
    // Need to get all the ids and select all the checkboxes
    ASSOCIATED_INPUTS.each((index, elm) => {
      const $elm = $(elm);
      $elm.prop("checked", checked);

      if (checked) {
        ASSOCIATED_PROJECTS.set($elm.val(), true);
      } else {
        ASSOCIATED_PROJECTS.delete($elm.val());
      }
    });
  } else {
    if (ASSOCIATED_PROJECTS.has(id)) {
      ASSOCIATED_PROJECTS.delete(id);
    } else {
      ASSOCIATED_PROJECTS.set(id, true);
    }
  }

  setTimeout(function() {
    // Update the current checkbox
    $inp.prop("checked", checked);
    // Update the select all checkbox
    $("#select-all-cb").prop(
      "checked",
      ASSOCIATED_PROJECTS.size === ASSOCIATED_INPUTS.size()
    );
    // Update the DataTable
    $dt.ajax.reload(null, false);
  }, 0);

  $(event.target).blur();
  return false;
});

/*
TABLE EVENT HANDLERS
 */

// Row selection events.
$dt.on("selection-count.dt", function(e, count) {
  /*
  Update the state of the buttons in the navbar.
   */
  for (const btn of SAMPLE_TOOL_BUTTONS) {
    btn.checkState(count);
  }
});

/*
Store reference to handle different modals.
 */
const MODALS = {
  /**
   * Hanle opening the merge modal.
   * @param {string} url for the content of the modal
   * @param {string} src url for the javascript needed for modal.
   * @param {list} sampleIds list of sample ids to merge.
   */
  merge({ url, src, sampleIds }) {
    const modal = $(this);

    /*
    Load the content for the dialogue based on the server response.
     */
    modal.load(`${url}?${$.param({ sampleIds })}`, function() {
      if (typeof src !== "undefined") {
        const script = document.createElement("script");
        script.type = "text/javascript";
        script.src = src;
        document.getElementsByTagName("head")[0].appendChild(script);
      }
    });

    /*
    Handle the closing the modal
     */
    modal.on("samples:merged", function(e) {
      $(this).modal("hide");
      $dt.select.selectNone();
      $dt.ajax.reload();
    });
  }
};

/*
Handle MERGE through the modal window.
 */
$("#modal-wrapper").on("show.bs.modal", function(event) {
  const wrapper = this;
  /*
  Determine which modal to open
   */
  const btn = $(event.relatedTarget);
  const whichModal = btn.data("modal");
  const url = btn.data("url");
  const script = btn.data("script");

  /*
  Find the ids for the currently selected samples.
   */
  const selected = $dt.select.selected()[0];
  const sampleIds = [];
  for (let [key, value] of selected) {
    sampleIds.push(value.sample);
  }

  MODALS[whichModal].call(wrapper, { url, src: script, sampleIds });
});
<|endoftext|>


<commit_before>export default 42;
export default {};
export default [];
export default foo;
export default function () {};
export default class {};
export default function foo() {}
export default class Foo {}
export * from "foo";
export { foo } from "foo";
export { foo, bar } from "foo";
export { foo as bar } from "foo";
export { foo as default } from "foo";
export { foo as default, bar } from "foo";
export { foo };
export { foo, bar };
export { foo as bar };
export { foo as default };
export { foo as default, bar };
export var foo = 1;
export var foo2 = function () {};
export var foo3;
export let foo4 = 2;
export let foo5;
export const foo6 = 3;
export function foo7() {}
export class foo8 {}
<commit_msg>remove redundant semicolons from export declarations<commit_after>export default 42;
export default {};
export default [];
export default foo;
export default function () {}
export default class {}
export default function foo() {}
export default class Foo {}
export * from "foo";
export { foo } from "foo";
export { foo, bar } from "foo";
export { foo as bar } from "foo";
export { foo as default } from "foo";
export { foo as default, bar } from "foo";
export { foo };
export { foo, bar };
export { foo as bar };
export { foo as default };
export { foo as default, bar };
export var foo = 1;
export var foo2 = function () {};
export var foo3;
export let foo4 = 2;
export let foo5;
export const foo6 = 3;
export function foo7() {}
export class foo8 {}
<|endoftext|>


<commit_before>function append(){
$('#routine').append(`
      Quanity (reps or seconds)<input class="quantity" type="text" name="quantity">
      Exercise: <input class="description" type="text" name="description">`);
}

function setupHandlers() {
  $('#plus').on('click', append);
}

$(document).ready(setupHandlers);
<commit_msg>added missing colon before routine form quantity<commit_after>function append(){
$('#routine').append(`
      Quanity (reps or seconds): <input class="quantity" type="text" name="quantity">
      Exercise: <input class="description" type="text" name="description">`);
}

function setupHandlers() {
  $('#plus').on('click', append);
}

$(document).ready(setupHandlers);
<|endoftext|>


<commit_before>"use strict"

var f = require('util').format;

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful reconnect when driver looses touch with entire replicaset'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    },
    // ignore: { travis:true }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];
    var die = false;

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(primary[0]);
            } else if(doc.insert) {
              request.reply({ "ok" : 1, "n" : 1 });
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(firstSecondary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(arbiter[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 2000,
        socketTimeout: 2000,
        haInterval: 500,
        size: 500
    });

    server.on('connect', function(_server) {
      // server.__connected = true;
      // console.log("------------------------------- step 0 ")
      // console.dir(_server)

      for(var i = 0; i < 100000; i++) {
        // console.log("------------------------------- step 0 : 1 ")
        // console.log(server.insert)
        // Execute the write
        _server.insert(f("%s.inserts", configuration.db), [{a:1}], {
          writeConcern: {w:1}, ordered:true
        }, function(err, results) {
          // if(results) console.log("insert success")
          // console.log("!!!!!!!!! RESULt")
          // if(results)console.dir(results.result)
        });
        // console.log("------------------------------- step 0 : 2 ")
      }
      // console.log("------------------------------- step 0 : 1")

      setTimeout(function() {
        // console.log("------------------------------- step 1 ")
        die = true;

        setTimeout(function() {
          // console.log("------------------------------- step 2 ")
          die = false;

          setTimeout(function() {
            // console.log("------------------------------- step 5 : 0")
            // console.dir(server.s.replicaSetState.primary)
            // console.log("------------------------------- step 6 : 0")
            // console.dir(server.s.replicaSetState.secondaries)
            // console.log("------------------------------- step 7 : 0")
            // console.dir(server.s.replicaSetState.arbiters)

            // console.log("------------------------------- step 3 ")
            _server.command('admin.$cmd', {ismaster:true}, function(err, r) {
              // console.log("------------------------------- step 4 : 1")
              // console.dir(err)
              // console.log("------------------------------- step 5 : 1")
              // console.dir(server.s.replicaSetState.primary)
              // console.log("------------------------------- step 6 : 1")
              // console.dir(server.s.replicaSetState.secondaries)
              // console.log("------------------------------- step 7 : 1")
              // console.dir(server.s.replicaSetState.arbiters)
              console.log("============================================= 0")
              console.dir(err)
              if(r)console.dir(r.result)
              console.log("_server.s.replicaSetState.primary != null = " + (_server.s.replicaSetState.primary != null))
              console.log("_server.s.replicaSetState.secondaries.length = " + _server.s.replicaSetState.secondaries.length)
              console.log("_server.s.replicaSetState.arbiters.length = " + _server.s.replicaSetState.arbiters.length)
              // test.equal(null, err);
              // test.ok(_server.s.replicaSetState.primary != null);
              // test.equal(1, _server.s.replicaSetState.secondaries.length);
              // test.equal(1, _server.s.replicaSetState.arbiters.length);

              setTimeout(function() {
                console.log("============================================= 1")
                if(r)console.dir(r.result)
                console.log("_server.s.replicaSetState.primary != null = " + (_server.s.replicaSetState.primary != null))
                console.log("_server.s.replicaSetState.secondaries.length = " + _server.s.replicaSetState.secondaries.length)
                console.log("_server.s.replicaSetState.arbiters.length = " + _server.s.replicaSetState.arbiters.length)

                primaryServer.destroy();
                firstSecondaryServer.destroy();
                arbiterServer.destroy();
                server.destroy();
                running = false;

                test.done();
              }, 10000)
            });
          }, 10000);
        }, 2500);
      }, 2500);
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

// exports['Successfully come back from a dead replicaset that has been unavailable for a long time'] = {
//   metadata: {
//     requires: {
//       generators: true,
//       topology: "single"
//     }
//   },
//
//   test: function(configuration, test) {
//     var ReplSet = configuration.require.ReplSet,
//       ObjectId = configuration.require.BSON.ObjectId,
//       ReadPreference = configuration.require.ReadPreference,
//       Long = configuration.require.BSON.Long,
//       co = require('co'),
//       mockupdb = require('../../../mock');
//
//     // Contain mock server
//     var primaryServer = null;
//     var firstSecondaryServer = null;
//     var arbiterServer = null;
//     var running = true;
//     var electionIds = [new ObjectId(), new ObjectId()];
//     var die = false;
//
//     // Default message fields
//     var defaultFields = {
//       "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
//       "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
//       "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
//       "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
//     }
//
//     // Primary server states
//     var primary = [extend(defaultFields, {
//       "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
//     })];
//
//     // Primary server states
//     var firstSecondary = [extend(defaultFields, {
//       "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
//     })];
//
//     // Primary server states
//     var arbiter = [extend(defaultFields, {
//       "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
//     })];
//
//     // Boot the mock
//     co(function*() {
//       primaryServer = yield mockupdb.createServer(32000, 'localhost');
//       firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
//       arbiterServer = yield mockupdb.createServer(32002, 'localhost');
//
//       // Primary state machine
//       co(function*() {
//         while(running) {
//           var request = yield primaryServer.receive();
//           if(die) {
//             // console.log("------------------ die 1")
//             request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(primary[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//
//       // First secondary state machine
//       co(function*() {
//         while(running) {
//           var request = yield firstSecondaryServer.receive();
//           if(die) {
//             // console.log("------------------ die 2")
//             request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(firstSecondary[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//
//       // Second secondary state machine
//       co(function*() {
//         while(running) {
//           var request = yield arbiterServer.receive();
//           if(die) {
//             // console.log("------------------ die 3")
//             request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(arbiter[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//     });
//
//     // Attempt to connect
//     var server = new ReplSet([
//       { host: 'localhost', port: 32000 },
//       { host: 'localhost', port: 32001 },
//       { host: 'localhost', port: 32002 }], {
//         setName: 'rs',
//         connectionTimeout: 5000,
//         socketTimeout: 5000,
//         haInterval: 1000,
//         size: 1
//     });
//
//     server.on('connect', function(e) {
//       // console.log("================================== 0")
//       setTimeout(function() {
//         // console.log("================================== 1")
//         die = true;
//
//         var intervalId = setInterval(function() {
//           // console.log("--------------- interval 0")
//           server.command('admin.$cmd', {ismaster:true}, function(err, r) {
//             // console.log("--------------- interval 1")
//             // console.log(err)
//             // test.ok(err != null);
//           });
//         }, 2000);
//
//         setTimeout(function() {
//           // console.log("================================== 2")
//           die = false;
//           // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ALIVE")
//
//           setTimeout(function() {
//             // console.log("================================== 3")
//             clearInterval(intervalId);
//
//             server.command('admin.$cmd', {ismaster:true}, function(err, r) {
//               // console.log("---------------------------------------------------------------")
//               // console.dir(err)
//               // console.log("server.s.replicaSetState.secondaries = " + server.s.replicaSetState.secondaries.length)
//               // console.log("server.s.replicaSetState.arbiters = " + server.s.replicaSetState.arbiters.length)
//               // console.log("server.s.replicaSetState.primary = " + (server.s.replicaSetState.primary != null))
//               // console.dir(err)
//               // console.dir(r.result)
//
//               test.equal(null, err);
//               test.ok(server.s.replicaSetState.primary != null);
//               test.equal(1, server.s.replicaSetState.secondaries.length);
//               test.equal(1, server.s.replicaSetState.arbiters.length);
//
//               primaryServer.destroy();
//               firstSecondaryServer.destroy();
//               arbiterServer.destroy();
//               server.destroy();
//               running = false;
//
//               test.done();
//             });
//           }, 5000);
//         }, 25000);
//       }, 2500);
//     });
//
//     // Add event listeners
//     server.on('fullsetup', function(_server) {});
//     // Gives proxies a chance to boot up
//     setTimeout(function() {
//       server.connect();
//     }, 100)
//   }
// }
<commit_msg>do not remove servers if they are actually connected (avoid timeout connections causing a messed up server state)<commit_after>"use strict"

var f = require('util').format;

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful reconnect when driver looses touch with entire replicaset'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    },
    // ignore: { travis:true }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];
    var die = false;

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(primary[0]);
            } else if(doc.insert) {
              request.reply({ "ok" : 1, "n" : 1 });
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(firstSecondary[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          if(die) {
            request.connection.destroy();
          } else {
            var doc = request.document;

            if(doc.ismaster) {
              request.reply(arbiter[0]);
            }
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 2000,
        socketTimeout: 2000,
        haInterval: 500,
        size: 500
    });

    server.on('connect', function(_server) {
      // server.__connected = true;
      // console.log("------------------------------- step 0 ")
      // console.dir(_server)

      for(var i = 0; i < 100000; i++) {
        // console.log("------------------------------- step 0 : 1 ")
        // console.log(server.insert)
        // Execute the write
        _server.insert(f("%s.inserts", configuration.db), [{a:1}], {
          writeConcern: {w:1}, ordered:true
        }, function(err, results) {
          // if(results) console.log("insert success")
          // console.log("!!!!!!!!! RESULt")
          // if(results)console.dir(results.result)
        });
        // console.log("------------------------------- step 0 : 2 ")
      }
      // console.log("------------------------------- step 0 : 1")

      setTimeout(function() {
        // console.log("------------------------------- step 1 ")
        die = true;

        setTimeout(function() {
          // console.log("------------------------------- step 2 ")
          die = false;

          setTimeout(function() {
            // console.log("------------------------------- step 5 : 0")
            // console.dir(server.s.replicaSetState.primary)
            // console.log("------------------------------- step 6 : 0")
            // console.dir(server.s.replicaSetState.secondaries)
            // console.log("------------------------------- step 7 : 0")
            // console.dir(server.s.replicaSetState.arbiters)

            // console.log("------------------------------- step 3 ")
            _server.command('admin.$cmd', {ismaster:true}, function(err, r) {
              // console.log("------------------------------- step 4 : 1")
              // console.dir(err)
              // console.log("------------------------------- step 5 : 1")
              // console.dir(server.s.replicaSetState.primary)
              // console.log("------------------------------- step 6 : 1")
              // console.dir(server.s.replicaSetState.secondaries)
              // console.log("------------------------------- step 7 : 1")
              // console.dir(server.s.replicaSetState.arbiters)
              console.log("============================================= 0")
              console.dir(err)
              if(r)console.dir(r.result)
              console.log("_server.s.replicaSetState.primary != null = " + (_server.s.replicaSetState.primary != null))
              console.log("_server.s.replicaSetState.secondaries.length = " + _server.s.replicaSetState.secondaries.length)
              console.log("_server.s.replicaSetState.arbiters.length = " + _server.s.replicaSetState.arbiters.length)
              // test.equal(null, err);
              // test.ok(_server.s.replicaSetState.primary != null);
              // test.equal(1, _server.s.replicaSetState.secondaries.length);
              // test.equal(1, _server.s.replicaSetState.arbiters.length);

              // setTimeout(function() {
              //   console.log("============================================= 1")
              //   if(r)console.dir(r.result)
              //   console.log("_server.s.replicaSetState.primary != null = " + (_server.s.replicaSetState.primary != null))
              //   console.log("_server.s.replicaSetState.secondaries.length = " + _server.s.replicaSetState.secondaries.length)
              //   console.log("_server.s.replicaSetState.arbiters.length = " + _server.s.replicaSetState.arbiters.length)

                primaryServer.destroy();
                firstSecondaryServer.destroy();
                arbiterServer.destroy();
                server.destroy();
                running = false;

                test.done();
              // }, 10000)
            });
          }, 10000);
        }, 2500);
      }, 2500);
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

// exports['Successfully come back from a dead replicaset that has been unavailable for a long time'] = {
//   metadata: {
//     requires: {
//       generators: true,
//       topology: "single"
//     }
//   },
//
//   test: function(configuration, test) {
//     var ReplSet = configuration.require.ReplSet,
//       ObjectId = configuration.require.BSON.ObjectId,
//       ReadPreference = configuration.require.ReadPreference,
//       Long = configuration.require.BSON.Long,
//       co = require('co'),
//       mockupdb = require('../../../mock');
//
//     // Contain mock server
//     var primaryServer = null;
//     var firstSecondaryServer = null;
//     var arbiterServer = null;
//     var running = true;
//     var electionIds = [new ObjectId(), new ObjectId()];
//     var die = false;
//
//     // Default message fields
//     var defaultFields = {
//       "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
//       "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
//       "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
//       "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
//     }
//
//     // Primary server states
//     var primary = [extend(defaultFields, {
//       "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
//     })];
//
//     // Primary server states
//     var firstSecondary = [extend(defaultFields, {
//       "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
//     })];
//
//     // Primary server states
//     var arbiter = [extend(defaultFields, {
//       "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
//     })];
//
//     // Boot the mock
//     co(function*() {
//       primaryServer = yield mockupdb.createServer(32000, 'localhost');
//       firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
//       arbiterServer = yield mockupdb.createServer(32002, 'localhost');
//
//       // Primary state machine
//       co(function*() {
//         while(running) {
//           var request = yield primaryServer.receive();
//           if(die) {
//             // console.log("------------------ die 1")
//             request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(primary[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//
//       // First secondary state machine
//       co(function*() {
//         while(running) {
//           var request = yield firstSecondaryServer.receive();
//           if(die) {
//             // console.log("------------------ die 2")
//             request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(firstSecondary[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//
//       // Second secondary state machine
//       co(function*() {
//         while(running) {
//           var request = yield arbiterServer.receive();
//           if(die) {
//             // console.log("------------------ die 3")
//             request.connection.destroy();
//           } else {
//             var doc = request.document;
//
//             if(doc.ismaster) {
//               request.reply(arbiter[0]);
//             }
//           }
//         }
//       }).catch(function(err) {
//         console.log(err.stack);
//       });
//     });
//
//     // Attempt to connect
//     var server = new ReplSet([
//       { host: 'localhost', port: 32000 },
//       { host: 'localhost', port: 32001 },
//       { host: 'localhost', port: 32002 }], {
//         setName: 'rs',
//         connectionTimeout: 5000,
//         socketTimeout: 5000,
//         haInterval: 1000,
//         size: 1
//     });
//
//     server.on('connect', function(e) {
//       // console.log("================================== 0")
//       setTimeout(function() {
//         // console.log("================================== 1")
//         die = true;
//
//         var intervalId = setInterval(function() {
//           // console.log("--------------- interval 0")
//           server.command('admin.$cmd', {ismaster:true}, function(err, r) {
//             // console.log("--------------- interval 1")
//             // console.log(err)
//             // test.ok(err != null);
//           });
//         }, 2000);
//
//         setTimeout(function() {
//           // console.log("================================== 2")
//           die = false;
//           // console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ALIVE")
//
//           setTimeout(function() {
//             // console.log("================================== 3")
//             clearInterval(intervalId);
//
//             server.command('admin.$cmd', {ismaster:true}, function(err, r) {
//               // console.log("---------------------------------------------------------------")
//               // console.dir(err)
//               // console.log("server.s.replicaSetState.secondaries = " + server.s.replicaSetState.secondaries.length)
//               // console.log("server.s.replicaSetState.arbiters = " + server.s.replicaSetState.arbiters.length)
//               // console.log("server.s.replicaSetState.primary = " + (server.s.replicaSetState.primary != null))
//               // console.dir(err)
//               // console.dir(r.result)
//
//               test.equal(null, err);
//               test.ok(server.s.replicaSetState.primary != null);
//               test.equal(1, server.s.replicaSetState.secondaries.length);
//               test.equal(1, server.s.replicaSetState.arbiters.length);
//
//               primaryServer.destroy();
//               firstSecondaryServer.destroy();
//               arbiterServer.destroy();
//               server.destroy();
//               running = false;
//
//               test.done();
//             });
//           }, 5000);
//         }, 25000);
//       }, 2500);
//     });
//
//     // Add event listeners
//     server.on('fullsetup', function(_server) {});
//     // Gives proxies a chance to boot up
//     setTimeout(function() {
//       server.connect();
//     }, 100)
//   }
// }
<|endoftext|>


<commit_before>var projects = new ProjectCollection();
var all_projects = new ProjectCollection();

var users = new UserCollection();
var all_users = new UserCollection();

var project_hours = new ProjectHoursCollection();

function showError(msg) {
    var html = '
' + msg +
        '×
';

    $('#alerts').append(html);
    $('.alert').alert();
}

function processData(data) {
    var projects = data.projects,
        project_hours = data.project_hours,
        all_projects = data.all_projects,
        all_users = data.all_users,
        dataTable = [['']];

    if(typeof ajax_url === 'undefined') {
        ajax_url = data.ajax_url;
    }

    // Store all projects for autocomplete
    for(var i = 0; i < all_projects.length; i++) {
        var p = all_projects[i];

        this.all_projects.add(new Project(p.id, p.name));
    }

    // Store all users for autocomplete
    for(i = 0; i < all_users.length; i++) {
        var u = all_users[i],
            name = u.first_name + ' ' + u.last_name,
            display_name = u.first_name + ' ' + u.last_name[0] + '.';

        this.all_users.add(new User(u.id, name, display_name));
    }

    // Process all project hours to add to the table
    for(i = 0; i < project_hours.length; i++) {
        var ph = project_hours[i],
            project = this.all_projects.get_by_id(ph.project);

        project.row = project.row || dataTable.length;

        // Add project to table if it doesnt already exist
        if(this.projects.add(project)) {
            dataTable.push([project.name]);
        }

        var hours = new ProjectHours(ph.id, ph.hours, project, ph.published);
        hours.row = project.row;

        // Get from global users and add to datatable and adjust column
        // if the user isnt already in the table
        var user = this.all_users.get_by_id(ph.user);
        if(users.add(user)) {
            dataTable[0].push(user.display_name);
            user.col = dataTable[0].length - 1;
        } else {
            user = users.get_by_id(user.id);
        }

        hours.user = user;
        hours.col = user.col;

        if(!dataTable[hours.row]) {
            dataTable[hours.row] = [];
        }

        dataTable[hours.row][hours.col] = hours.hours;

        this.project_hours.add(hours);
    }

    // Populate the totals row after weve gone through all the data
    var totals = ['Totals'], j;

    for(i = 1; i < dataTable.length; i++) {
        var row = dataTable[i];

        for(j = 1; j < row.length; j++) {
            if(!totals[j]) {
                totals[j] = 0;
            }

            if(row[j]) {
                totals[j] += row[j];
            }
        }
    }

    dataTable.push([], [], totals);

    $('.dataTable').handsontable('loadData', dataTable);
}

// Helper for updating totals after any change
function updateTotals(col, data) {
    var dataTable = $('.dataTable').handsontable('getData'),
        row = dataTable.length - 2,
        totals = dataTable[row];

    if(data !== '') {
        var current = parseInt(totals[col], 10);

        if(current) {
            current += data;
        } else {
            current = data;
        }

        $('.dataTable').handsontable('setDataAtCell', row, col, current);
    }
}

// Entry point to load all data into the table
function getData(week_start) {
    if(!week_start) {
        var d = new Date();
        week_start = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
    }

    $.getJSON(ajax_url, { week_start: week_start }, function(data, status, xhr) {
        processData(data);
    });
}

function ajax(url, data, success, error, type) {
    $.ajax({
        type: type,
        url: url,
        data: data,
        success: success,
        error: error
    });
}

// Override post to take an error callback
$.post = function(url, data, success, error) {
    ajax(url, data, success, error, 'POST');
};

// Add wrappers for put and delete
$.put = function(url, data, success, error) {
    ajax(url, data, success, error, 'PUT');
};

$.del = function(url, success, error) {
    ajax(url, { }, success, error, 'DELETE');
};

$(function() {
    var table = $('.dataTable').handsontable({
        rows: 3,

        fillHandle: false,

        minSpareRows: 1,
        minSpareCols: 1,

        minWidth: $('div#content').width() - 20, // -20 is to account for padding

        enterBeginsEditing: true,

        legend: [
            {   // Match the first row and bold it
                match: function(row, col, data) {
                    return (row === 0);
                },
                style: {
                    fontWeight: 'bold'
                }
            },
            {   // Match the cells with content
                match: function(row, col, data) {
                    var ph = project_hours.get_by_row_col(row, col);

                    if(ph && ph.published) {
                        return (row > 0 && col > 0 && data()[row][col] !== '');
                    }

                    return false;
                },
                style: {
                    color: 'white',
                    backgroundColor: 'green'
                }
            }
        ],

        autoComplete: [
            {
                match: function(row, col, data) {
                    return (col === 0);
                },
                source: function() {
                    return all_projects.collection;
                }
            },
            {
                match: function(row, col, data) {
                    return (row === 0 && col !== 0);
                },
                source: function() {
                    return all_users.collection;
                }
            }
        ],

        onBeforeChange: function(changes) {
            if(changes.length > 4) { return; }

            var row = changes[0],
                col = changes[1],
                before = changes[2],
                after = changes[3],
                project, user, hours;

            if(row === 0) {
                if(!users.get_by_display_name(after)) {
                    // Adding a user
                    user = all_users.get_by_display_name(after);

                    user.col = col;
                    users.add(user);
                } else {
                    showError('User already listed');
                    return false;
                }
            } else if(col === 0) {
                if(!projects.get_by_name(after)) {
                    // Adding project
                    project = all_projects.get_by_name(after);

                    project.row = row;
                    projects.add(project);

                    // Keep rows in between projects and totals
                    $('.dataTable').handsontable('alter', 'insert_row', row + 1);
                } else {
                    showError('Project already listed');
                    return false;
                }
            } else if(row >= 1 && col >= 1) {
                var time = parseInt(after, 10);
                hours = project_hours.get_by_row_col(row, col);

                if(time && hours) {
                    // If we have times and hours in the row/col, then update the current hours
                    $.post(ajax_url, {
                        'project': hours.project.id,
                        'user': hours.user.id,
                        'hours': time,
                        'week_start': $('h2[data-date]').data('date')
                    }, function(data, status, xhr) {
                        var diff = time - hours.hours;
                        updateTotals(col, diff);

                        hours.hours = time;
                        hours.published = false;
                        $('.dataTable').handsontable('setDataAtCell', row, col, time);
                    }, function(xhr, status, error) {
                        $('.dataTable').handsontable('setDataAtCell', row, col, before);
                        showError('Could not save the project hours. Please notify an administrator.');
                    });
                } else if(time && !hours) {
                    // If the user entered a valid time, but the hours do not exist
                    // in a row/col, create them
                    project = projects.get_by_row(row);
                    user = users.get_by_col(col);

                    if(project && user && before === '') {
                        $.post(ajax_url, {
                            'user': user.id,
                            'project': project.id,
                            'hours': time,
                            'week_start': $('h2[data-date]').data('date')
                        }, function(data, status, xhr) {
                            hours = new ProjectHours(parseInt(data, 10), time, project, false);
                            hours.user = user;
                            hours.row = project.row;
                            hours.col = user.col;
                            project_hours.add(hours);

                            updateTotals(col, time);
                        }, function(xhr, status, error) {
                            $('.dataTable').handsontable('setDataAtCell', row, col, '');
                            showError('Could not save the project hours. Please notify an administrator.');
                        });
                    } else {
                        showError('Project hours must be associated with a project and user');
                        return false;
                    }
                } else {
                    if(after !== '' && !hours) {
                        showError('Project hours must be integers greater than zero');
                        return false;
                    }
                }
            } else {
                return;
            }
        },

        onChange: function(changes) {
            if(changes.length > 1) { return; }

            var row = changes[0][0],
                col = changes[0][1],
                before = changes[0][2],
                after = changes[0][3],
                project, user, hours, i;

            if(row === 0) {
                user = users.get_by_name(before);

                if(user && after === '') {
                    users.remove(user);

                    hours = project_hours.get_by_key('user', user);

                    for(i = 0; i < hours.length; i++) {
                        project_hours.remove(hours[i]);
                    }

                    $('.dataTable').handsontable('alter', 'remove_col', user.col);
                }
            } else if(col === 0) {
                project = projects.get_by_name(before);

                if(project && after === '') {
                    projects.remove(project);

                    hours = project_hours.get_by_key('project', project);

                    for(i = 0; i < hours.length; i++) {
                        project_hours.remove(hours[i]);
                    }

                    $('.dataTable').handsontable('alter', 'remove_row', project.row);
                }
            } else if(row >= 1 && col >= 1) {
                function deleteHours() {
                    $.del(ajax_url + hours.id + '/', function(data, status, xhr) {
                        updateTotals(col, -hours.hours);

                        project_hours.remove(hours);
                        $('.dataTable').handsontable('setDataAtCell', row, col, '');
                    }, function(xhr, status, error) {
                        $('.dataTable').handsontable('setDataAtCell', row, col, before);
                        showError('Could not delete the project hours. Please notify an administrator.');
                    });
                }

                hours = project_hours.get_by_row_col(row, col);

                if(hours && after === '') {
                    // If the hours have been removed from the table, delete from
                    // the database
                    deleteHours();
                } else if(hours && after == '0') {
                    // If the hours have been zeroed out in the table, delete from
                    // the database
                    deleteHours();
                }
            } else {
                return;
            }
        }
    });

    // Load initial data
    getData($('h2[data-date]').data('date'));

    // Make sure the datepicker uses the correct format we expect
    $('.hasDatepicker').datepicker('setDate', $('h2[data-date]').data('date'));

    // Make sure they really want to copy project hours
    $('#copy').click(function(e) {
        var copy = confirm('This will overwrite a person\'s project hours if they exist. Are you sure you want to do this?');

        if(copy) {
            return true;
        }

        return false;
    });
});<commit_msg>Make sure a user cannot enter a negative number<commit_after>var projects = new ProjectCollection();
var all_projects = new ProjectCollection();

var users = new UserCollection();
var all_users = new UserCollection();

var project_hours = new ProjectHoursCollection();

function showError(msg) {
    var html = '
' + msg +
        '×
';

    $('#alerts').append(html);
    $('.alert').alert();
}

function processData(data) {
    var projects = data.projects,
        project_hours = data.project_hours,
        all_projects = data.all_projects,
        all_users = data.all_users,
        dataTable = [['']];

    if(typeof ajax_url === 'undefined') {
        ajax_url = data.ajax_url;
    }

    // Store all projects for autocomplete
    for(var i = 0; i < all_projects.length; i++) {
        var p = all_projects[i];

        this.all_projects.add(new Project(p.id, p.name));
    }

    // Store all users for autocomplete
    for(i = 0; i < all_users.length; i++) {
        var u = all_users[i],
            name = u.first_name + ' ' + u.last_name,
            display_name = u.first_name + ' ' + u.last_name[0] + '.';

        this.all_users.add(new User(u.id, name, display_name));
    }

    // Process all project hours to add to the table
    for(i = 0; i < project_hours.length; i++) {
        var ph = project_hours[i],
            project = this.all_projects.get_by_id(ph.project);

        project.row = project.row || dataTable.length;

        // Add project to table if it doesnt already exist
        if(this.projects.add(project)) {
            dataTable.push([project.name]);
        }

        var hours = new ProjectHours(ph.id, ph.hours, project, ph.published);
        hours.row = project.row;

        // Get from global users and add to datatable and adjust column
        // if the user isnt already in the table
        var user = this.all_users.get_by_id(ph.user);
        if(users.add(user)) {
            dataTable[0].push(user.display_name);
            user.col = dataTable[0].length - 1;
        } else {
            user = users.get_by_id(user.id);
        }

        hours.user = user;
        hours.col = user.col;

        if(!dataTable[hours.row]) {
            dataTable[hours.row] = [];
        }

        dataTable[hours.row][hours.col] = hours.hours;

        this.project_hours.add(hours);
    }

    // Populate the totals row after weve gone through all the data
    var totals = ['Totals'], j;

    for(i = 1; i < dataTable.length; i++) {
        var row = dataTable[i];

        for(j = 1; j < row.length; j++) {
            if(!totals[j]) {
                totals[j] = 0;
            }

            if(row[j]) {
                totals[j] += row[j];
            }
        }
    }

    dataTable.push([], [], totals);

    $('.dataTable').handsontable('loadData', dataTable);
}

// Helper for updating totals after any change
function updateTotals(col, data) {
    var dataTable = $('.dataTable').handsontable('getData'),
        row = dataTable.length - 2,
        totals = dataTable[row];

    if(data !== '') {
        var current = parseInt(totals[col], 10);

        if(current) {
            current += data;
        } else {
            current = data;
        }

        $('.dataTable').handsontable('setDataAtCell', row, col, current);
    }
}

// Entry point to load all data into the table
function getData(week_start) {
    if(!week_start) {
        var d = new Date();
        week_start = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
    }

    $.getJSON(ajax_url, { week_start: week_start }, function(data, status, xhr) {
        processData(data);
    });
}

function ajax(url, data, success, error, type) {
    $.ajax({
        type: type,
        url: url,
        data: data,
        success: success,
        error: error
    });
}

// Override post to take an error callback
$.post = function(url, data, success, error) {
    ajax(url, data, success, error, 'POST');
};

// Add wrappers for put and delete
$.put = function(url, data, success, error) {
    ajax(url, data, success, error, 'PUT');
};

$.del = function(url, success, error) {
    ajax(url, { }, success, error, 'DELETE');
};

$(function() {
    var table = $('.dataTable').handsontable({
        rows: 3,

        fillHandle: false,

        minSpareRows: 1,
        minSpareCols: 1,

        minWidth: $('div#content').width() - 20, // -20 is to account for padding

        enterBeginsEditing: true,

        legend: [
            {   // Match the first row and bold it
                match: function(row, col, data) {
                    return (row === 0);
                },
                style: {
                    fontWeight: 'bold'
                }
            },
            {   // Match the cells with content
                match: function(row, col, data) {
                    var ph = project_hours.get_by_row_col(row, col);

                    if(ph && ph.published) {
                        return (row > 0 && col > 0 && data()[row][col] !== '');
                    }

                    return false;
                },
                style: {
                    color: 'white',
                    backgroundColor: 'green'
                }
            }
        ],

        autoComplete: [
            {
                match: function(row, col, data) {
                    return (col === 0);
                },
                source: function() {
                    return all_projects.collection;
                }
            },
            {
                match: function(row, col, data) {
                    return (row === 0 && col !== 0);
                },
                source: function() {
                    return all_users.collection;
                }
            }
        ],

        onBeforeChange: function(changes) {
            if(changes.length > 4) { return; }

            var row = changes[0],
                col = changes[1],
                before = changes[2],
                after = changes[3],
                project, user, hours;

            if(row === 0) {
                if(!users.get_by_display_name(after)) {
                    // Adding a user
                    user = all_users.get_by_display_name(after);

                    user.col = col;
                    users.add(user);
                } else {
                    showError('User already listed');
                    return false;
                }
            } else if(col === 0) {
                if(!projects.get_by_name(after)) {
                    // Adding project
                    project = all_projects.get_by_name(after);

                    project.row = row;
                    projects.add(project);

                    // Keep rows in between projects and totals
                    $('.dataTable').handsontable('alter', 'insert_row', row + 1);
                } else {
                    showError('Project already listed');
                    return false;
                }
            } else if(row >= 1 && col >= 1) {
                var time = parseInt(after, 10);
                hours = project_hours.get_by_row_col(row, col);

                if(time && hours && time > 0) {
                    // If we have times and hours in the row/col, then update the current hours
                    $.post(ajax_url, {
                        'project': hours.project.id,
                        'user': hours.user.id,
                        'hours': time,
                        'week_start': $('h2[data-date]').data('date')
                    }, function(data, status, xhr) {
                        var diff = time - hours.hours;
                        updateTotals(col, diff);

                        hours.hours = time;
                        hours.published = false;
                        $('.dataTable').handsontable('setDataAtCell', row, col, time);
                    }, function(xhr, status, error) {
                        $('.dataTable').handsontable('setDataAtCell', row, col, before);
                        showError('Could not save the project hours. Please notify an administrator.');
                    });
                } else if(time && !hours && time > 0) {
                    // If the user entered a valid time, but the hours do not exist
                    // in a row/col, create them
                    project = projects.get_by_row(row);
                    user = users.get_by_col(col);

                    if(project && user && before === '') {
                        $.post(ajax_url, {
                            'user': user.id,
                            'project': project.id,
                            'hours': time,
                            'week_start': $('h2[data-date]').data('date')
                        }, function(data, status, xhr) {
                            hours = new ProjectHours(parseInt(data, 10), time, project, false);
                            hours.user = user;
                            hours.row = project.row;
                            hours.col = user.col;
                            project_hours.add(hours);

                            updateTotals(col, time);
                        }, function(xhr, status, error) {
                            $('.dataTable').handsontable('setDataAtCell', row, col, '');
                            showError('Could not save the project hours. Please notify an administrator.');
                        });
                    } else {
                        showError('Project hours must be associated with a project and user');
                        return false;
                    }
                } else {
                    if(after !== '' && !hours || time <= 0) {
                        showError('Project hours must be integers greater than zero');
                        return false;
                    }
                }
            } else {
                return;
            }
        },

        onChange: function(changes) {
            if(changes.length > 1) { return; }

            var row = changes[0][0],
                col = changes[0][1],
                before = changes[0][2],
                after = changes[0][3],
                project, user, hours, i;

            if(row === 0) {
                user = users.get_by_name(before);

                if(user && after === '') {
                    users.remove(user);

                    hours = project_hours.get_by_key('user', user);

                    for(i = 0; i < hours.length; i++) {
                        project_hours.remove(hours[i]);
                    }

                    $('.dataTable').handsontable('alter', 'remove_col', user.col);
                }
            } else if(col === 0) {
                project = projects.get_by_name(before);

                if(project && after === '') {
                    projects.remove(project);

                    hours = project_hours.get_by_key('project', project);

                    for(i = 0; i < hours.length; i++) {
                        project_hours.remove(hours[i]);
                    }

                    $('.dataTable').handsontable('alter', 'remove_row', project.row);
                }
            } else if(row >= 1 && col >= 1) {
                function deleteHours() {
                    $.del(ajax_url + hours.id + '/', function(data, status, xhr) {
                        updateTotals(col, -hours.hours);

                        project_hours.remove(hours);
                        $('.dataTable').handsontable('setDataAtCell', row, col, '');
                    }, function(xhr, status, error) {
                        $('.dataTable').handsontable('setDataAtCell', row, col, before);
                        showError('Could not delete the project hours. Please notify an administrator.');
                    });
                }

                hours = project_hours.get_by_row_col(row, col);

                if(hours && after === '') {
                    // If the hours have been removed from the table, delete from
                    // the database
                    deleteHours();
                } else if(hours && after == '0') {
                    // If the hours have been zeroed out in the table, delete from
                    // the database
                    deleteHours();
                }
            } else {
                return;
            }
        }
    });

    // Load initial data
    getData($('h2[data-date]').data('date'));

    // Make sure the datepicker uses the correct format we expect
    $('.hasDatepicker').datepicker('setDate', $('h2[data-date]').data('date'));

    // Make sure they really want to copy project hours
    $('#copy').click(function(e) {
        var copy = confirm('This will overwrite a person\'s project hours if they exist. Are you sure you want to do this?');

        if(copy) {
            return true;
        }

        return false;
    });
});<|endoftext|>


<commit_before>(function($, window, _, undefined){

	$(function() {
		jQuery.extend(jQuery.validator.messages, {
			required : "Това поле е задължително",
			minlength : jQuery.validator.format("Моля, въведете поне {0} символа"),
			maxlength : jQuery.validator.format("Моля, въведете по-малко от {0} символа")
		});
	});

	var getHostLocation = function() {
		if (getHostLocation.hostLocation === undefined) {
			var loc = window.location;
			getHostLocation.hostLocation = loc.protocol + "//" + loc.hostname + ((loc.port !== undefined) ? ':' + loc.port : '');
		}
		return getHostLocation.hostLocation;
	};

	var appConfig = {
		projectName : "Diaphanum",
		textAreaValidationReq : {
			required: true,
			minlength: 140
		},
		nameSearchUrl : getHostLocation() + "/search/"
	};

	window.Diaphanum = {
		appConfig : appConfig,
		utils : {}
	};

	window.Diaphanum.utils.validationRequirementsFromAttributes = function(inputNameValue) {
		var
			inputObject = $("input[name=" + inputNameValue + "]"),
			resultObject = {},
			NONE_VALUE = "None";

		// if no match is found, return an empty object
		if(inputObject.length === 0) {
			return resultObject;
		}

		if ( inputObject.is('[maxlength]') && inputObject.attr("maxlength") !== NONE_VALUE ) {
			resultObject.maxlength = parseInt(inputObject.attr('maxlength'), 10);
		}

		if ( inputObject.is('[minlength]') && inputObject.attr("minlength") !== NONE_VALUE ) {
			resultObject.minlength = parseInt(inputObject.attr('minlength'), 10);
		}

		if ( inputObject.is('[required]') ) {
			resultObject.required = true;
		}

		if ( inputObject.is("input[type=email]") ) {
			resultObject.email = true;
		}

		if ( inputObject.is("input[type=url]") ) {
			resultObject.url = true;
		}

		if ( inputObject.is("input[type=date]") ) {
			resultObject.date = true;
		}

		if ( inputObject.is("input[type=number]") ) {
			resultObject.number = true;
		}

		return resultObject;
	};
})($, window, _);
<commit_msg>Changing the route for members name autocomplete<commit_after>(function($, window, _, undefined){

	$(function() {
		jQuery.extend(jQuery.validator.messages, {
			required : "Това поле е задължително",
			minlength : jQuery.validator.format("Моля, въведете поне {0} символа"),
			maxlength : jQuery.validator.format("Моля, въведете по-малко от {0} символа")
		});
	});

	var getHostLocation = function() {
		if (getHostLocation.hostLocation === undefined) {
			var loc = window.location;
			getHostLocation.hostLocation = loc.protocol + "//" + loc.hostname + ((loc.port !== undefined) ? ':' + loc.port : '');
		}
		return getHostLocation.hostLocation;
	};

	var appConfig = {
		projectName : "Diaphanum",
		textAreaValidationReq : {
			required: true,
			minlength: 140
		},
		nameSearchUrl : getHostLocation() + "/members/search/"
	};

	window.Diaphanum = {
		appConfig : appConfig,
		utils : {}
	};

	window.Diaphanum.utils.validationRequirementsFromAttributes = function(inputNameValue) {
		var
			inputObject = $("input[name=" + inputNameValue + "]"),
			resultObject = {},
			NONE_VALUE = "None";

		// if no match is found, return an empty object
		if(inputObject.length === 0) {
			return resultObject;
		}

		if ( inputObject.is('[maxlength]') && inputObject.attr("maxlength") !== NONE_VALUE ) {
			resultObject.maxlength = parseInt(inputObject.attr('maxlength'), 10);
		}

		if ( inputObject.is('[minlength]') && inputObject.attr("minlength") !== NONE_VALUE ) {
			resultObject.minlength = parseInt(inputObject.attr('minlength'), 10);
		}

		if ( inputObject.is('[required]') ) {
			resultObject.required = true;
		}

		if ( inputObject.is("input[type=email]") ) {
			resultObject.email = true;
		}

		if ( inputObject.is("input[type=url]") ) {
			resultObject.url = true;
		}

		if ( inputObject.is("input[type=date]") ) {
			resultObject.date = true;
		}

		if ( inputObject.is("input[type=number]") ) {
			resultObject.number = true;
		}

		return resultObject;
	};
})($, window, _);
<|endoftext|>


<commit_before>import { Iterable, fromJS } from 'immutable';

export const asImmutable = (obj) => (Iterable.isIterable(obj) ? obj : fromJS(obj));
<commit_msg>Add asJS to immutableHelper<commit_after>import { Iterable, fromJS } from 'immutable';

export const asImmutable = (obj) => (
  Iterable.isIterable(obj) ? obj : fromJS(obj)
);

export const asJS = (obj) => (
  obj && Iterable.isIterable(obj) ? obj.toJS() : obj
);
<|endoftext|>


<commit_before>// Debug settings
define('lyria/debug', function() {
  return true;
});

// General constants
define('lyria/constants', {
  animSpeed: 300
});

define('lyria/language', ['detectr'], function(detectr) {
  // Fallback language
  var defaultLanguage = 'en';

  return detectr.Browser.language() || defaultLanguage;
});
<commit_msg>Updated constants<commit_after>// Debug settings
define('lyria/debug', function() {
  return true;
});

// General constants
define('lyria/constants', function() {
  return {
    animSpeed: 300
  };
});

define('lyria/language', ['detectr'], function(detectr) {
  // Fallback language
  var defaultLanguage = 'en';

  return detectr.Browser.language() || defaultLanguage;
});
<|endoftext|>


<commit_before>var raf = requestAnimationFrame || setTimeout;
var nextFrame = function(fn) { raf(function() { raf(fn); }); };

function setNextFrame(obj, prop, val) {
  nextFrame(function() { obj[prop] = val; });
}

function updateStyle(oldVnode, vnode) {
  var cur, name, elm = vnode.elm,
      oldStyle = oldVnode.data.style || {},
      style = vnode.data.style || {};
  for (name in style) {
    cur = style[name];
    if ((name[0] !== 'r' || name[0] !== '-') &&
        cur !== oldStyle[name]) {
      if (name[0] === 'd' && name[1] === '-') {
        setNextFrame(elm.style, name.slice(2), cur);
      } else {
        elm.style[name] = cur;
      }
    }
  }
}

function applyRemoveStyle(vnode, rm) {
  var cur, name, elm = vnode.elm, idx, i = 0, maxDur = 0,
      compStyle, style = vnode.data.style || {};
  var applied = [];
  for (name in style) {
    cur = style[name];
    if (name[0] === 'r' && name[1] === '-') {
      name = name.slice(2);
      applied.push(name);
      setNextFrame(elm.style, name, cur);
    }
  }
  if (applied.length > 0) {
    compStyle = getComputedStyle(elm);
    var dels = compStyle['transition-delay'].split(', ');
    var durs = compStyle['transition-duration'].split(', ');
    var props = compStyle['transition-property'].split(', ');
    for (; i < applied.length; ++i) {
      idx = props.indexOf(applied[i]);
      if (idx !== -1) maxDur = Math.max(maxDur, parseFloat(dels[idx]) + parseFloat(durs[idx]));
    }
    setTimeout(rm, maxDur * 1000); // s to ms
  } else {
    rm();
  }
}

module.exports = {create: updateStyle, update: updateStyle, remove: applyRemoveStyle};
<commit_msg>Update syntax for style on removal<commit_after>var raf = requestAnimationFrame || setTimeout;
var nextFrame = function(fn) { raf(function() { raf(fn); }); };

function setNextFrame(obj, prop, val) {
  nextFrame(function() { obj[prop] = val; });
}

function updateStyle(oldVnode, vnode) {
  var cur, name, elm = vnode.elm,
      oldStyle = oldVnode.data.style || {},
      style = vnode.data.style || {};
  for (name in style) {
    cur = style[name];
    if (name !== 'remove' &&
        cur !== oldStyle[name]) {
      if (name[0] === 'd' && name[1] === '-') {
        setNextFrame(elm.style, name.slice(2), cur);
      } else {
        elm.style[name] = cur;
      }
    }
  }
}

function applyRemoveStyle(vnode, rm) {
  var s = vnode.data.style;
  if (!s || !s.remove) return;
  var cur, name, elm = vnode.elm, idx, i = 0, maxDur = 0,
      compStyle, style = s.remove;
  var applied = [];
  for (name in style) {
    applied.push(name);
    elm.style[name] = style[name];
  }
  if (applied.length > 0) {
    compStyle = getComputedStyle(elm);
    var dels = compStyle['transition-delay'].split(', ');
    var durs = compStyle['transition-duration'].split(', ');
    var props = compStyle['transition-property'].split(', ');
    for (; i < applied.length; ++i) {
      idx = props.indexOf(applied[i]);
      if (idx !== -1) maxDur = Math.max(maxDur, parseFloat(dels[idx]) + parseFloat(durs[idx]));
    }
    setTimeout(rm, maxDur * 1000); // s to ms
  } else {
    rm();
  }
}

module.exports = {create: updateStyle, update: updateStyle, remove: applyRemoveStyle};
<|endoftext|>


<commit_before>define(
	'ace/mode/wizard_diary_highlight_rules',
	[
		'require',
		'exports',
		'module',
		'ace/lib/oop',
		'ace/mode/text_highlight_rules'
	],
	function(require, exports, module) {
		var oop = require('../lib/oop');
		var text_highlight_rules =
			require('./text_highlight_rules')
			.TextHighlightRules;

		var highlight_rules = function() {
			this.$rules = {
				start: [
					{
						// first and second hierarchy levels
						token: [
							'keyword.control.wizard-diary',
							'variable.language.wizard-diary'
						],
						regex: '^([^,]+,|\\s{4})([^,]+,)'
					},
					{
						// only first hierarchy level
						token: 'keyword.control.wizard-diary',
						regex: '^[^,]+,'
					},
					{
						// identifiers
						token: 'comment.line.wizard-diary',
						regex: '[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*(?:\\(\\))?'
					},
					{
						// double-quoted string
						token: 'string.quoted.double.wizard-diary',
						regex: '"(?:\\\\.|[^"])*"'
					},
					{
						// operators `-` and `->`
						token: 'keyword.operator.wizard-diary',
						regex: '\\s->?\\s'
					},
					{
						// operator `(key Key)`
						token: [
							'keyword.operator.wizard-diary',
							'constant.language.wizard-diary',
							'keyword.operator.wizard-diary'
						],
						regex: '(\\(key\\s)([^\\)]+)(\\))'
					}
				]
			};

			this.normalizeRules();
		};
		oop.inherits(highlight_rules, text_highlight_rules);

		exports.WizardDiaryHighlightRules = highlight_rules;
	}
);
<commit_msg>Issue #196: extend identifiers highlighting.<commit_after>define(
	'ace/mode/wizard_diary_highlight_rules',
	[
		'require',
		'exports',
		'module',
		'ace/lib/oop',
		'ace/mode/text_highlight_rules'
	],
	function(require, exports, module) {
		var oop = require('../lib/oop');
		var text_highlight_rules =
			require('./text_highlight_rules')
			.TextHighlightRules;

		var highlight_rules = function() {
			this.$rules = {
				start: [
					{
						// first and second hierarchy levels
						token: [
							'keyword.control.wizard-diary',
							'variable.language.wizard-diary'
						],
						regex: '^([^,]+,|\\s{4})([^,]+,)'
					},
					{
						// only first hierarchy level
						token: 'keyword.control.wizard-diary',
						regex: '^[^,]+,'
					},
					{
						// identifiers
						token: 'comment.line.wizard-diary',
						regex: '\\.?\\w+(?:(?:\\.|::)\\w+)*(?:\\(\\)|\\+\\+|#)?'
					},
					{
						// double-quoted string
						token: 'string.quoted.double.wizard-diary',
						regex: '"(?:\\\\.|[^"])*"'
					},
					{
						// operators `-` and `->`
						token: 'keyword.operator.wizard-diary',
						regex: '\\s->?\\s'
					},
					{
						// operator `(key Key)`
						token: [
							'keyword.operator.wizard-diary',
							'constant.language.wizard-diary',
							'keyword.operator.wizard-diary'
						],
						regex: '(\\(key\\s)([^\\)]+)(\\))'
					}
				]
			};

			this.normalizeRules();
		};
		oop.inherits(highlight_rules, text_highlight_rules);

		exports.WizardDiaryHighlightRules = highlight_rules;
	}
);
<|endoftext|>