<commit_before>/*
@licstart  The following is the entire license notice for the
JavaScript code in this page.

Copyright (C) 2010  Goteo Foundation

The JavaScript code in this page is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version.  The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.

As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.

@licend  The above is the entire license notice
for the JavaScript code in this page.
*/

$(function(){
  // $('.tabs').click( function() {
  //   $('.tabs').removeClass('slick-current');
  //   $(this).addClass('slick-current');
  // });

  var $slider_program = $('.slider-programs');
  var $slider_post = $('.slider-post');
  var $slider_workshop = $('.slider-workshops');
  var $slider_stories = $('.slider-stories');

  function initSlickSliders() {
    var initial_slide = $slider_program.data('initial-slide');
    $slider_program.slick({
      slidesToShow: 1,
      initialSlide: parseInt(initial_slide),
      slidesToScroll: 1,
      infinite: false,
      arrows: true,
      dots: false,
      variableWidth: true,
      centerMode: false,
      focusOnSelect: true,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
',
      responsive: [
        {
          breakpoint: 992,
          settings: {
            prevArrow: '
Prev
',
            nextArrow: '
Prev
',
          }
        }
      ]
    });

    $slider_post.slick({
      slidesToShow: 3.5,
      infinite: false,
      slidesToScroll: 1,
      arrows: true,
      dots: false,
      focusOnSelect: true,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
',
      responsive: [
        {
          breakpoint: 992,
          settings: {
            slidesToShow: 2.5,
            arrows: false
          }
        },
        {
          breakpoint: 768,
          settings: {
            slidesToShow: 1.2,
            arrows: false
          }
        }]

    });

      var workshop_initial_slide = $slider_workshop.data('initial-slide');
      $slider_workshop.slick({
      slidesToShow: 3.5,
      initialSlide: parseInt(workshop_initial_slide),
      infinite: false,
      slidesToScroll: 1,
      arrows: true,
      dots: false,
      focusOnSelect: true,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
',
      responsive: [
        {
          breakpoint: 992,
          settings: {
            slidesToShow: 2.5,
            arrows: false
          }
        },
        {
          breakpoint: 768,
          settings: {
            slidesToShow: 1.2,
            arrows: false
          }
        }]

    });

    var $container = $('#projects-container');
    var $slider_projects = $container.contents('.slider-projects');

    $slider_projects.slick({
      infinite: false,
      slidesToShow: 3.5,
      slidesToScroll: 1,
      arrows: true,
      dots: false,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
',
      responsive: [
        {
          breakpoint: 769,
          settings: {
            slidesToShow: 2.5,
            arrows:false
          }
        },
        {
          breakpoint: 500,
          settings: {
            slidesToShow: 1.2,
            arrows: false
          }
        }]
    });

    $slider_stories.slick({
      slidesToShow: 1,
      infinite: false,
      slidesToScroll: 1,
      arrows: true,
      dots: false,
      focusOnSelect: true,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
'
    });

  }

  initSlickSliders();
});
<commit_msg>add breakpoints in stories slick<commit_after>/*
@licstart  The following is the entire license notice for the
JavaScript code in this page.

Copyright (C) 2010  Goteo Foundation

The JavaScript code in this page is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version.  The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.

As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.

@licend  The above is the entire license notice
for the JavaScript code in this page.
*/

$(function(){
  // $('.tabs').click( function() {
  //   $('.tabs').removeClass('slick-current');
  //   $(this).addClass('slick-current');
  // });

  var $slider_program = $('.slider-programs');
  var $slider_post = $('.slider-post');
  var $slider_workshop = $('.slider-workshops');
  var $slider_stories = $('.slider-stories');

  function initSlickSliders() {
    var initial_slide = $slider_program.data('initial-slide');
    $slider_program.slick({
      slidesToShow: 1,
      initialSlide: parseInt(initial_slide),
      slidesToScroll: 1,
      infinite: false,
      arrows: true,
      dots: false,
      variableWidth: true,
      centerMode: false,
      focusOnSelect: true,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
',
      responsive: [
        {
          breakpoint: 992,
          settings: {
            prevArrow: '
Prev
',
            nextArrow: '
Prev
',
          }
        }
      ]
    });

    $slider_post.slick({
      slidesToShow: 3.5,
      infinite: false,
      slidesToScroll: 1,
      arrows: true,
      dots: false,
      focusOnSelect: true,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
',
      responsive: [
        {
          breakpoint: 992,
          settings: {
            slidesToShow: 2.5,
            arrows: false
          }
        },
        {
          breakpoint: 768,
          settings: {
            slidesToShow: 1.2,
            arrows: false
          }
        }]

    });

      var workshop_initial_slide = $slider_workshop.data('initial-slide');
      $slider_workshop.slick({
      slidesToShow: 3.5,
      initialSlide: parseInt(workshop_initial_slide),
      infinite: false,
      slidesToScroll: 1,
      arrows: true,
      dots: false,
      focusOnSelect: true,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
',
      responsive: [
        {
          breakpoint: 992,
          settings: {
            slidesToShow: 2.5,
            arrows: false
          }
        },
        {
          breakpoint: 768,
          settings: {
            slidesToShow: 1.2,
            arrows: false
          }
        }]

    });

    var $container = $('#projects-container');
    var $slider_projects = $container.contents('.slider-projects');

    $slider_projects.slick({
      infinite: false,
      slidesToShow: 3.5,
      slidesToScroll: 1,
      arrows: true,
      dots: false,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
',
      responsive: [
        {
          breakpoint: 769,
          settings: {
            slidesToShow: 2.5,
            arrows:false
          }
        },
        {
          breakpoint: 500,
          settings: {
            slidesToShow: 1.2,
            arrows: false
          }
        }]
    });

    $slider_stories.slick({
      slidesToShow: 1,
      infinite: false,
      slidesToScroll: 1,
      arrows: true,
      dots: false,
      focusOnSelect: true,
      prevArrow: '
Prev
',
      nextArrow: '
Prev
',
      responsive: [
        {
          breakpoint: 769,
          settings: {
            slidesToShow: 1,
            arrows:true
          }
        },
        {
          breakpoint: 500,
          settings: {
            slidesToShow: 1,
            arrows: true
          }
        }]

    });

  }

  initSlickSliders();
});
<|endoftext|>


<commit_before>var path = require('path');
var should = require('chai').should();

var month = require(path.join(process.cwd(),'/lib/cal.month'));

describe.only('Month', function() {
  describe('#addLine()', function() {

    it('should print 7 days in a row', function() {
      month.addLine(3,9).should.equal(' 3  4  5  6  7  8  9\n');
    });

    it('should be print the first line in a month', function() {
      month.addLine(1,4,7,2015).should.equal('          1  2  3  4\n');
    });
  });

  describe('#days()', function() {
    it('should start with the first day of the month, and print a list of days', function() {
      var output = [
        '          1  2  3  4\n',
        ' 5  6  7  8  9 10 11\n',
        '12 13 14 15 16 17 18\n',
        '19 20 21 22 23 24 25\n',
        '26 27 28 29 30 31\n'
      ].join('');
      month.days(7,2015).should.equal(output);
    });
  });

  describe('#startIndex()', function() {
    it('should take a week day number and return the start index for that day - e.g., (Th) 4 => 11', function() {
      month.startIndex(1).should.equal(2);
      month.startIndex(4).should.equal(11);
    });
  });

  describe('#title()', function() {
    it('should print an evenly spaced title with year name', function() {
       month.title(7).should.equal('     July 2015\n');
    });
  });

  describe('#wkdys', function() {
    it('should return a list of the names of the days in a row', function() {
      month.wkdys.should.equal('Su Mo Tu We Th Fr Sa\n');
    });
  });

});
<commit_msg>Adding newline character test for the last day of the month<commit_after>var path = require('path');
var should = require('chai').should();

var month = require(path.join(process.cwd(),'/lib/cal.month'));

describe.only('Month', function() {
  describe('#addLine()', function() {

    it('should print 7 days in a row', function() {
      month.addLine(3,9).should.equal(' 3  4  5  6  7  8  9\n');
    });

    it('should be print the first line in a month', function() {
      month.addLine(1,4,7,2015).should.equal('          1  2  3  4\n');
    });

    it('should print a new line after the last day of the month', function() {
      month.addLine(26,31).should.equal('26 27 28 29 30 31\n');
    });
  });

  describe('#days()', function() {
    it('should start with the first day of the month, and print a list of days', function() {
      var output = [
        '          1  2  3  4\n',
        ' 5  6  7  8  9 10 11\n',
        '12 13 14 15 16 17 18\n',
        '19 20 21 22 23 24 25\n',
        '26 27 28 29 30 31\n'
      ].join('');
      month.days(7,2015).should.equal(output);
    });
  });

  describe('#startIndex()', function() {
    it('should take a week day number and return the start index for that day - e.g., (Th) 4 => 11', function() {
      month.startIndex(1).should.equal(2);
      month.startIndex(4).should.equal(11);
    });
  });

  describe('#title()', function() {
    it('should print an evenly spaced title with year name', function() {
       month.title(7).should.equal('     July 2015\n');
    });
  });

  describe('#wkdys', function() {
    it('should return a list of the names of the days in a row', function() {
      month.wkdys.should.equal('Su Mo Tu We Th Fr Sa\n');
    });
  });

});
<|endoftext|>


<commit_before><commit_msg>cell.xsd successfully parsed and loaded<commit_after><|endoftext|>


<commit_before>import {t} from '../../common/utils'
import {StaticText} from '../../models'

export class snippet {
  constructor(renderContext) {
    this.tags = ['snippet']
  }

  parse(parser, nodes, lexer) {
    const tok = parser.nextToken();

    const args = parser.parseSignature(null, true);
    parser.advanceAfterBlockEnd(tok.value);

    let body = parser.parseUntilBlocks('endsnippet');
    parser.advanceAfterBlockEnd();

    return new nodes.CallExtensionAsync(this, 'run', args, [body]);
  }

  run({ctx}, snippetName, options, body, callback) {
    if (typeof options === 'function') {
      callback = body
      body = options
      options = {type: 'html'}
    }
    if (ctx.inspect) {
      return callback(null, null)
    }

    const props = {site: ctx.site._id, key: snippetName, global: true}
    return StaticText.findOne(props)
      .then(text => {
        if (text) {
          var localText = t(text.content, ctx.req.locale)
          if (text.type === 'text') {
            localText = localText.replace(/^\s+/mg, '').replace(/\r?\n/g, '
')
          }
          callback(null, localText)
          return localText
        } else {
          text = new StaticText({...props, content: {en: body()}, type: options.type})
          return text.save().catch(e => console.log(e)).then(() => {
            return callback(null, body())
          })
        }
      })
      .catch(err => callback(err, null))
  }
}<commit_msg>fix default snippet type<commit_after>import {t} from '../../common/utils'
import {StaticText} from '../../models'

export class snippet {
  constructor(renderContext) {
    this.tags = ['snippet']
  }

  parse(parser, nodes, lexer) {
    const tok = parser.nextToken();

    const args = parser.parseSignature(null, true);
    parser.advanceAfterBlockEnd(tok.value);

    let body = parser.parseUntilBlocks('endsnippet');
    parser.advanceAfterBlockEnd();

    return new nodes.CallExtensionAsync(this, 'run', args, [body]);
  }

  run({ctx}, snippetName, options, body, callback) {
    if (typeof options === 'function') {
      callback = body
      body = options
      options = {type: 'html'}
    }
    if (ctx.inspect) {
      return callback(null, null)
    }

    const props = {site: ctx.site._id, key: snippetName, global: true}
    return StaticText.findOne(props)
      .then(text => {
        if (text) {
          var localText = t(text.content, ctx.req.locale)
          if (text.type === 'text') {
            localText = localText.replace(/^\s+/mg, '').replace(/\r?\n/g, '
')
          }
          callback(null, localText)
          return localText
        } else {
          text = new StaticText({...props, content: {en: body()}, type: (options.type || 'text')})
          return text.save().catch(e => console.log(e)).then(() => {
            return callback(null, body())
          })
        }
      })
      .catch(err => callback(err, null))
  }
}<|endoftext|>


<commit_before>/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

'use strict';

/**
 * A disk access SAS uri.
 *
 */
class AccessUri {
  /**
   * Create a AccessUri.
   * @member {string} [accessSAS] A SAS uri for accessing a disk.
   */
  constructor() {
  }

  /**
   * Defines the metadata of AccessUri
   *
   * @returns {object} metadata of AccessUri
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'AccessUri',
      type: {
        name: 'Composite',
        className: 'AccessUri',
        modelProperties: {
          accessSAS: {
            required: false,
            readOnly: true,
            serializedName: 'accessSAS',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = AccessUri;
<commit_msg>Generated from b59db77683f3a9c65d0edec17b5f05e458a68897 (#3187)<commit_after>/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

'use strict';

/**
 * A disk access SAS uri.
 *
 */
class AccessUri {
  /**
   * Create a AccessUri.
   * @member {string} [accessSAS] A SAS uri for accessing a disk.
   */
  constructor() {
  }

  /**
   * Defines the metadata of AccessUri
   *
   * @returns {object} metadata of AccessUri
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'AccessUri',
      type: {
        name: 'Composite',
        className: 'AccessUri',
        modelProperties: {
          accessSAS: {
            required: false,
            readOnly: true,
            serializedName: 'properties.output.accessSAS',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = AccessUri;
<|endoftext|>


<commit_before>const test = require('tap').test;
const Runtime = require('../../src/engine/runtime');
const MonitorRecord = require('../../src/engine/records');
const {Map} = require('immutable');

test('spec', t => {
    const r = new Runtime();

    t.type(Runtime, 'function');
    t.type(r, 'object');
    t.ok(r instanceof Runtime);

    t.end();
});

test('monitorStateEquals', t => {
    const r = new Runtime();
    const id = 'xklj4#!';
    const prevMonitorState = MonitorRecord({
        id,
        opcode: 'turtle whereabouts',
        value: '25'
    });
    const newMonitorDelta = Map({
        id,
        value: String(25)
    });
    r.requestAddMonitor(prevMonitorState);
    r.requestUpdateMonitor(newMonitorDelta);

    t.equals(true, prevMonitorState === r._monitorState.get(id));
    t.equals(String(25), r._monitorState.get(id).get('value'));
    t.end();
});

test('monitorStateDoesNotEqual', t => {
    const r = new Runtime();
    const id = 'xklj4#!';
    const params = {seven: 7};
    const prevMonitorState = MonitorRecord({
        id,
        opcode: 'turtle whereabouts',
        value: '25'
    });

    // Value change
    let newMonitorDelta = Map({
        id,
        value: String(24)
    });
    r.requestAddMonitor(prevMonitorState);
    r.requestUpdateMonitor(newMonitorDelta);

    t.equals(false, prevMonitorState.equals(r._monitorState.get(id)));
    t.equals(String(24), r._monitorState.get(id).get('value'));

    // Prop change
    newMonitorDelta = Map({
        id: 'xklj4#!',
        params: params
    });
    r.requestUpdateMonitor(newMonitorDelta);

    t.equals(false, prevMonitorState.equals(r._monitorState.get(id)));
    t.equals(String(24), r._monitorState.get(id).value);
    t.equals(params, r._monitorState.get(id).params);

    t.end();
});
<commit_msg>fix file name in test<commit_after>const test = require('tap').test;
const Runtime = require('../../src/engine/runtime');
const MonitorRecord = require('../../src/engine/monitor-record');
const {Map} = require('immutable');

test('spec', t => {
    const r = new Runtime();

    t.type(Runtime, 'function');
    t.type(r, 'object');
    t.ok(r instanceof Runtime);

    t.end();
});

test('monitorStateEquals', t => {
    const r = new Runtime();
    const id = 'xklj4#!';
    const prevMonitorState = MonitorRecord({
        id,
        opcode: 'turtle whereabouts',
        value: '25'
    });
    const newMonitorDelta = Map({
        id,
        value: String(25)
    });
    r.requestAddMonitor(prevMonitorState);
    r.requestUpdateMonitor(newMonitorDelta);

    t.equals(true, prevMonitorState === r._monitorState.get(id));
    t.equals(String(25), r._monitorState.get(id).get('value'));
    t.end();
});

test('monitorStateDoesNotEqual', t => {
    const r = new Runtime();
    const id = 'xklj4#!';
    const params = {seven: 7};
    const prevMonitorState = MonitorRecord({
        id,
        opcode: 'turtle whereabouts',
        value: '25'
    });

    // Value change
    let newMonitorDelta = Map({
        id,
        value: String(24)
    });
    r.requestAddMonitor(prevMonitorState);
    r.requestUpdateMonitor(newMonitorDelta);

    t.equals(false, prevMonitorState.equals(r._monitorState.get(id)));
    t.equals(String(24), r._monitorState.get(id).get('value'));

    // Prop change
    newMonitorDelta = Map({
        id: 'xklj4#!',
        params: params
    });
    r.requestUpdateMonitor(newMonitorDelta);

    t.equals(false, prevMonitorState.equals(r._monitorState.get(id)));
    t.equals(String(24), r._monitorState.get(id).value);
    t.equals(params, r._monitorState.get(id).params);

    t.end();
});
<|endoftext|>


<commit_before>function changeCipherBasic() {
  var cipherText = document.getElementById("ciphertext").value;
  document.getElementById("reverse").value = reverse(cipherText);
  document.getElementById("atbash").value = atbash(cipherText);
  document.getElementById("odd").value = extractAlternatingChars(cipherText, 0);
  document.getElementById("even").value = extractAlternatingChars(cipherText, 1);
  document.getElementById("filter-uppercase").value = removeCharRange(cipherText, "uppercase");
  document.getElementById("filter-lowercase").value = removeCharRange(cipherText, "lowercase");
  document.getElementById("filter-numbers").value = removeCharRange(cipherText, "numbers");
}
/**
 * Converts the input text to its reverse.
 * @param {string} the string to be reversed.
 * @return {string} returns the reversed string.
 */
function reverse(text) {
  return reversedString = text.split("").reverse().join("");
}
/**
 * Extracts even/odd characters from input text
 * @param {string} text - text to be extracted from.
 * @param {integer} parity - shift for parity. use 0 to extract odd characters and 1 for even.
 * @return {string} - returns extracted text.
 * @author - Cyan
 */
function extractAlternatingChars(text, parity) {
  var i = 0;
  var outputtext = "";
  if (parity==1 || parity==0) {
    i = parity;
  } else {
    return "WTF is this? Wrong args!!";
  }
  for (i; i < text.length; i=i+2) {
    outputtext = outputtext + text.charAt(i);
  }
  return outputtext;
}

/**
 * Removes a range of characters from input text
 * @param {string} text - text to be extracted from.
 * @param {integer} range - shift for for the character range to be removed. valid values are "uppercase", "lowercase", and "numbers".
 * @return {string} - returns extracted text.
 * @author - Cyan
 */
function removeCharRange(text, range) {
  var outputtext = "";

  function createOutput(cipherText, minLimit, maxLimit) {
    for (i = 0; i < cipherText.length; i++) {
      character = text.charCodeAt(i);
      if (character < minLimit || character > maxLimit) {
        outputtext = outputtext + cipherText.charAt(i);
      }
    }
  }

  switch (range) {
    case "uppercase":
      createOutput(text, 65, 90) //remove uppercase characters
      break;
    case "lowercase":
      createOutput(text, 97, 122) //remove lowercase characters
      break;
    case "numbers":
      createOutput(text, 48, 57) //remove number characters (0-9)
      break;
    default:
      outputtext = "This shit is not implemented yet!";
  }

  return outputtext;
}
/**
 * Converts the input text in to an atbash cipher using an alphabet [a-z] and [A-Z].
 * Numbers and all other characters are left as they are.
 * @param {string} text - text to be atbashed.
 * @return {string} - returns atbash converted string of the input.
 * @todo - Currently this function uses a pure a-z alphabet and uses the ASCII offset
 * to find the atbash. Will not work with anything outside the a-z alphabet OR numbers.
 * @author - KJ <kulendra@gmail.com>
 */
function atbash(text) {

  var i = 0;
  var character = "";
  var outputchar = "";
  var outputtext = "";
  for (i = 0; i < text.length; i++) {
    character = text.charCodeAt(i);
    if (character >= 65 && character <= 90) {
      outputchar = String.fromCharCode(155 - character);
    } else if (character >= 97 && character <= 122) {
      outputchar = String.fromCharCode(219 - character);
    } else {
      outputchar = String.fromCharCode(character);
    }
    outputtext = outputtext + outputchar;
  }
  return outputtext;
}
/**
 * Converts the input text using caesar cipher using an alphabet [a-z] and [A-Z].
 * @param {string} text - text to be encrypted/decrypted.
 * @param {integer} n - shift for caesar.
 * @param {integer} flag - 0: for encrypt 1: for decrypt
 * @return {string} - returns caesar encrypted/decrypted text.
 */
function caesar(text, n, flag) {

  var i = 0;
  var character = "";
  var outputchar = "";
  var outputtext = "";
  for (i = 0; i < text.length; i++) {
    character = text.charCodeAt(i);
    if (character >= 65 && character <= 90) {
      outputchar = String.fromCharCode(65 + ((character + n) % 91)%65);
    } else if (character >= 97 && character <= 122) {
      outputchar = String.fromCharCode(97 + ((character + n) % 123)%97);
    } else {
      outputchar = String.fromCharCode(character);
    }
    outputtext = outputtext + outputchar;
  }
  return outputtext;
}

/**
 * Converts the input text using a columnar transposition.
 * @param {string} text - text to be encrypted/decrypted.
 * @param {integer} n - number of columns.
 * @param {integer} flag - 0: top-bottom LR 1: top-bottom RL 2:bottom-top LR 3:bottom-top RL
 * @param {integer} type - 1: snake algorithm 0/ommitted/null: regular
 * @return {string} - returns columnar encrypted/decrypted text.
 * @author - KJ <kulendra@gmail.com>
 */
function columnar_transposition(text, n, flag, type) {
  var character = "";
  var outputchar = "";
  var outputtext = "";
  var rowtext = "";
  var dir = 1;

  var i = 0;
  var j = i;
  var maxrow = Math.ceil(text.length/n);
  var maxcol = n;

  // read columnwise left-right
  if(flag == 0){
	  for(j=0;j<maxcol;j++){
	  	rowtext = "";
	  	for(i=0;i<maxrow;i++){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read columnwise right-left
  if (flag == 1){
	  for(j=maxcol-1;j>=0;j--){
	  	rowtext="";
	  	for(i=0;i<maxrow;i++){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read columnwise bottom-top left-right
  if (flag == 2){
	  for(j=0;j<maxcol;j++){
	  	rowtext="";
	  	for(i=maxrow-1;i>=0;i--){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read columnwise bottom-up right-left
  if (flag == 3){
	  for(j=maxcol-1;j>=0;j--){
	  	rowtext="";
	  	for(i=maxrow-1;i>=0;i--){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read rowwise right-left top-bottom
  if (flag == 4){
	  for(i=0;i<maxrow;i++){
	  	rowtext="";
	  	for(j=maxcol-1;j>=0;j--){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read rowwise right-left bottom-up
  if (flag == 5){
	  for(i=maxrow-1;i>=0;i--){
	  	rowtext="";
	  	for(j=maxcol-1;j>=0;j--){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read rowwise left-right top-bottom
  if(flag==6){
	  for(i=0;i<maxrow;i++){
		rowtext="";
	  	for(j=0;j<maxcol;j++){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }
  //read rowwise left-right bottom-top
  if(flag==7){
	  for(i=maxrow-1;i>=0;i--){
	  	rowtext="";
	  	for(j=0;j<maxcol;j++){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }
}

/**
 * Converts the input text into their Ascii values
 * @param {string} text - text to be encrypted/decrypted.
 * @param {integer} flag - 0: number to letter 1: letter to number 2: Ascii to characters 3: char to Ascii
 *                         4: hex to char 5: char to hex 6: b64 to char 7:char to b64
 * @return {string} - returns the converted text.
 * @todo - The ASCII and Hex conversions assume that it will be all doublets. I can't think of a better alternative.
 * @author - KJ <kulendra@gmail.com>
 */
function numText(text,flag){
  var character="";
  var output="";
  var i=0;
  for(i=0;i<text.length;i++){
  	if(flag==0){
		// 0->a
		if(!isNaN(parseInt(text.charAt(i)))){
			output = output + String.fromCharCode(97+parseInt(text.charAt(i)));
		}
		else{
			output = output + text.charAt(i);
		}

  	}
  	else if(flag==1){
		// a->0
  		text = text.toLowerCase();
		if(isNaN(parseInt(text.charAt(i)))){
			output = output + (parseInt(text.charCodeAt(i)) - 97);
		}
		else{
			output = output + text.charAt(i);
		}

  	}
  	else if(flag==2){
		// ASC -> A
  		// Assumes that the characters will be in lower case range and a two character code.
  		output = output + String.fromCharCode(text.charAt(i)+text.charAt(i+1));
  		i++;
  	}
  	else if(flag==3){
		// A->ASC
  		output = output + text.charCodeAt(i);
  	}
  	else if(flag==4){
		// Hex->A
  		character = text.charAt(i)+text.charAt(i+1);
  		output = output + String.fromCharCode(parseInt(character,16));
  		i++;
  	}
  	else if(flag==5){
		// A->Hex
  		output = output + text.charCodeAt(i).toString(16);
  	}
  }
  if(flag==6){
  	// B64->A
  	output = atob(text);
  }
  else if(flag==7){
  	// A->B64
  	output = btoa(text);
  }

  return output;
}

/**
 * Converts the input text using caesar cipher using an alphabet [a-z] and [A-Z].
 * @param {string} text - text to be encrypted/decrypted.
 * @param {integer} a - shift for a.
 * @param {integer} b - shift for b.
 * @param {integer} flag - 0: for encrypt 1: for decrypt
 * @return {string} - returns caesar encrypted/decrypted text.
 */
function affine(text, a, b, flag){
	var output_text = "";
	for (i=0;i<text.length;i++){
		char = text.charCodeAt(i);
		if(char>=65 && char <= 90){
			c = 65 + ((char + 91 - b)%91 )/a % 26;
		}
		if(char>=97 && char <= 122){
			c = 97 + ((char + 123 - b)%123 )/a % 26);
		}
		output_text = output_text + c;
	}
	return output_text;
}

/**
 * Converts the case of the text. Leaves non alphabetic characters as it is.
 * @param {string} text - text to be converted.
 * @return {string} - returns the converted text.
 * @author - KJ <kulendra@gmail.com>
 */
function caseSwitch(text){
	var output = "";
	for(i=0;i<text.length;i++){
		c = text.CharAt(i);
		if(c==c.toUpperCase()){
			output = output+c.toLowerCase();
		}
		else if(c==c.toLowerCase()){
			output = output+c.toUpperCase();
		}
		else{
			output = output + c;
		}
	}
}
<commit_msg>Update affine()<commit_after>function changeCipherBasic() {
  var cipherText = document.getElementById("ciphertext").value;
  document.getElementById("reverse").value = reverse(cipherText);
  document.getElementById("atbash").value = atbash(cipherText);
  document.getElementById("odd").value = extractAlternatingChars(cipherText, 0);
  document.getElementById("even").value = extractAlternatingChars(cipherText, 1);
  document.getElementById("filter-uppercase").value = removeCharRange(cipherText, "uppercase");
  document.getElementById("filter-lowercase").value = removeCharRange(cipherText, "lowercase");
  document.getElementById("filter-numbers").value = removeCharRange(cipherText, "numbers");
}
/**
 * Converts the input text to its reverse.
 * @param {string} the string to be reversed.
 * @return {string} returns the reversed string.
 */
function reverse(text) {
  return reversedString = text.split("").reverse().join("");
}
/**
 * Extracts even/odd characters from input text
 * @param {string} text - text to be extracted from.
 * @param {integer} parity - shift for parity. use 0 to extract odd characters and 1 for even.
 * @return {string} - returns extracted text.
 * @author - Cyan
 */
function extractAlternatingChars(text, parity) {
  var i = 0;
  var outputtext = "";
  if (parity==1 || parity==0) {
    i = parity;
  } else {
    return "WTF is this? Wrong args!!";
  }
  for (i; i < text.length; i=i+2) {
    outputtext = outputtext + text.charAt(i);
  }
  return outputtext;
}

/**
 * Removes a range of characters from input text
 * @param {string} text - text to be extracted from.
 * @param {integer} range - shift for for the character range to be removed. valid values are "uppercase", "lowercase", and "numbers".
 * @return {string} - returns extracted text.
 * @author - Cyan
 */
function removeCharRange(text, range) {
  var outputtext = "";

  function createOutput(cipherText, minLimit, maxLimit) {
    for (i = 0; i < cipherText.length; i++) {
      character = text.charCodeAt(i);
      if (character < minLimit || character > maxLimit) {
        outputtext = outputtext + cipherText.charAt(i);
      }
    }
  }

  switch (range) {
    case "uppercase":
      createOutput(text, 65, 90) //remove uppercase characters
      break;
    case "lowercase":
      createOutput(text, 97, 122) //remove lowercase characters
      break;
    case "numbers":
      createOutput(text, 48, 57) //remove number characters (0-9)
      break;
    default:
      outputtext = "This shit is not implemented yet!";
  }

  return outputtext;
}
/**
 * Converts the input text in to an atbash cipher using an alphabet [a-z] and [A-Z].
 * Numbers and all other characters are left as they are.
 * @param {string} text - text to be atbashed.
 * @return {string} - returns atbash converted string of the input.
 * @todo - Currently this function uses a pure a-z alphabet and uses the ASCII offset
 * to find the atbash. Will not work with anything outside the a-z alphabet OR numbers.
 * @author - KJ <kulendra@gmail.com>
 */
function atbash(text) {

  var i = 0;
  var character = "";
  var outputchar = "";
  var outputtext = "";
  for (i = 0; i < text.length; i++) {
    character = text.charCodeAt(i);
    if (character >= 65 && character <= 90) {
      outputchar = String.fromCharCode(155 - character);
    } else if (character >= 97 && character <= 122) {
      outputchar = String.fromCharCode(219 - character);
    } else {
      outputchar = String.fromCharCode(character);
    }
    outputtext = outputtext + outputchar;
  }
  return outputtext;
}
/**
 * Converts the input text using caesar cipher using an alphabet [a-z] and [A-Z].
 * @param {string} text - text to be encrypted/decrypted.
 * @param {integer} n - shift for caesar.
 * @param {integer} flag - 0: for encrypt 1: for decrypt
 * @return {string} - returns caesar encrypted/decrypted text.
 */
function caesar(text, n, flag) {

  var i = 0;
  var character = "";
  var outputchar = "";
  var outputtext = "";
  for (i = 0; i < text.length; i++) {
    character = text.charCodeAt(i);
    if (character >= 65 && character <= 90) {
      outputchar = String.fromCharCode(65 + ((character + n) % 91)%65);
    } else if (character >= 97 && character <= 122) {
      outputchar = String.fromCharCode(97 + ((character + n) % 123)%97);
    } else {
      outputchar = String.fromCharCode(character);
    }
    outputtext = outputtext + outputchar;
  }
  return outputtext;
}

/**
 * Converts the input text using a columnar transposition.
 * @param {string} text - text to be encrypted/decrypted.
 * @param {integer} n - number of columns.
 * @param {integer} flag - 0: top-bottom LR 1: top-bottom RL 2:bottom-top LR 3:bottom-top RL
 * @param {integer} type - 1: snake algorithm 0/ommitted/null: regular
 * @return {string} - returns columnar encrypted/decrypted text.
 * @author - KJ <kulendra@gmail.com>
 */
function columnar_transposition(text, n, flag, type) {
  var character = "";
  var outputchar = "";
  var outputtext = "";
  var rowtext = "";
  var dir = 1;

  var i = 0;
  var j = i;
  var maxrow = Math.ceil(text.length/n);
  var maxcol = n;

  // read columnwise left-right
  if(flag == 0){
	  for(j=0;j<maxcol;j++){
	  	rowtext = "";
	  	for(i=0;i<maxrow;i++){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read columnwise right-left
  if (flag == 1){
	  for(j=maxcol-1;j>=0;j--){
	  	rowtext="";
	  	for(i=0;i<maxrow;i++){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read columnwise bottom-top left-right
  if (flag == 2){
	  for(j=0;j<maxcol;j++){
	  	rowtext="";
	  	for(i=maxrow-1;i>=0;i--){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read columnwise bottom-up right-left
  if (flag == 3){
	  for(j=maxcol-1;j>=0;j--){
	  	rowtext="";
	  	for(i=maxrow-1;i>=0;i--){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read rowwise right-left top-bottom
  if (flag == 4){
	  for(i=0;i<maxrow;i++){
	  	rowtext="";
	  	for(j=maxcol-1;j>=0;j--){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read rowwise right-left bottom-up
  if (flag == 5){
	  for(i=maxrow-1;i>=0;i--){
	  	rowtext="";
	  	for(j=maxcol-1;j>=0;j--){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }

  //read rowwise left-right top-bottom
  if(flag==6){
	  for(i=0;i<maxrow;i++){
		rowtext="";
	  	for(j=0;j<maxcol;j++){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }
  //read rowwise left-right bottom-top
  if(flag==7){
	  for(i=maxrow-1;i>=0;i--){
	  	rowtext="";
	  	for(j=0;j<maxcol;j++){
			outputchar = text.charAt(i*n+j);
			rowtext = rowtext+outputchar;
		}
		if(dir == -1 && type==1){
			rowtext = reverse(rowtext);
		}
		dir=dir*(-1);
		outputtext = outputtext+rowtext;
	  }
	  return outputtext;
  }
}

/**
 * Converts the input text into their Ascii values
 * @param {string} text - text to be encrypted/decrypted.
 * @param {integer} flag - 0: number to letter 1: letter to number 2: Ascii to characters 3: char to Ascii
 *                         4: hex to char 5: char to hex 6: b64 to char 7:char to b64
 * @return {string} - returns the converted text.
 * @todo - The ASCII and Hex conversions assume that it will be all doublets. I can't think of a better alternative.
 * @author - KJ <kulendra@gmail.com>
 */
function numText(text,flag){
  var character="";
  var output="";
  var i=0;
  for(i=0;i<text.length;i++){
  	if(flag==0){
		// 0->a
		if(!isNaN(parseInt(text.charAt(i)))){
			output = output + String.fromCharCode(97+parseInt(text.charAt(i)));
		}
		else{
			output = output + text.charAt(i);
		}

  	}
  	else if(flag==1){
		// a->0
  		text = text.toLowerCase();
		if(isNaN(parseInt(text.charAt(i)))){
			output = output + (parseInt(text.charCodeAt(i)) - 97);
		}
		else{
			output = output + text.charAt(i);
		}

  	}
  	else if(flag==2){
		// ASC -> A
  		// Assumes that the characters will be in lower case range and a two character code.
  		output = output + String.fromCharCode(text.charAt(i)+text.charAt(i+1));
  		i++;
  	}
  	else if(flag==3){
		// A->ASC
  		output = output + text.charCodeAt(i);
  	}
  	else if(flag==4){
		// Hex->A
  		character = text.charAt(i)+text.charAt(i+1);
  		output = output + String.fromCharCode(parseInt(character,16));
  		i++;
  	}
  	else if(flag==5){
		// A->Hex
  		output = output + text.charCodeAt(i).toString(16);
  	}
  }
  if(flag==6){
  	// B64->A
  	output = atob(text);
  }
  else if(flag==7){
  	// A->B64
  	output = btoa(text);
  }

  return output;
}

/**
 * Converts the input text using caesar cipher using an alphabet [a-z] and [A-Z].
 * @param {string} text - text to be encrypted/decrypted.
 * @param {integer} a - shift for a.
 * @param {integer} b - shift for b.
 * @param {integer} flag - 0: for encrypt 1: for decrypt
 * @return {string} - returns caesar encrypted/decrypted text.
 */
function affine(text, a, b, flag){
	var output_text = "";
	for (i=0;i<text.length;i++){
		char = text.charCodeAt(i);
		if(char>=65 && char <= 90){
			c = 65 + ((char + 91 - b)%91 )/a % 26;
		}
		if(char>=97 && char <= 122){
			c = 97 + ((char + 123 - b)%123 )/a % 26;
		}
		output_text = output_text + c;
	}
	return output_text;
}

/**
 * Converts the case of the text. Leaves non alphabetic characters as it is.
 * @param {string} text - text to be converted.
 * @return {string} - returns the converted text.
 * @author - KJ <kulendra@gmail.com>
 */
function caseSwitch(text){
	var output = "";
	for(i=0;i<text.length;i++){
		c = text.CharAt(i);
		if(c==c.toUpperCase()){
			output = output+c.toLowerCase();
		}
		else if(c==c.toLowerCase()){
			output = output+c.toUpperCase();
		}
		else{
			output = output + c;
		}
	}
}
<|endoftext|>


<commit_before>const bot = require('./bot');

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

bot.on('message', message => {
    var channel = message.channel;

    if (channel.name.indexOf('help')<0 ) {
        return;
    }
    if(message.author.bot)return;
    var user = message.author;
    message = message.content.toLowerCase();
    //Error updating
    if (message.includes('updating') && message.includes('forever')) {
        channel.sendMessage('Follow this article \n http://battlelog.co/wiki.php?article=27');
    }
    //Error debugging
else if (message.includes('unknown dynamicoption')) {
        channel.sendMessage('Follow the second part of this article. \n http://battlelog.co/post.php?id=9744');
    }
    //Mouse stuck after launch ingame
else if (message.includes('mouse') && message.includes('stuck')) {
        channel.sendMessage('follow this article\nhttp://battlelog.co/wiki.php?article=7');
    }
    //Invalid CD key Fix
else if (message.includes('invalid') && message.includes('cdkey')) {
        channel.sendMessage('follow these articles\nhttps://battlelog.co/post.php?id=16014&page=1\nhttp://battlelog.co/wiki.php?article=28');
    }
    //Installation Errors
else if (message.includes('installation') && message.includes('failed')) {
        channel.sendMessage('follow this article\nhttp://battlelog.co/post.php?id=17435#p57246');
    }
    //Black screen after launch
else if (message.includes('black screen') && message.includes('help')) {
        channel.sendMessage('Follow this article \nhttp://battlelog.co/post.php?id=9744');
    }
    //Login Errors
else if (message.includes('error') && message.includes('api')) {
        channel.sendMessage('Follow this article \n https://battlelog.co/post.php?id=17435#p93129');
    }
    //DirectX9 errors after launhcer
else if (message.includes('directx9') && message.includes('error')) {
        channel.sendMessage('Follow this article \n https://battlelog.co/wiki.php?article=14');
    }
    //Server Rules Battlelog
else if (message.includes('server') && message.includes('rules')) {
        channel.sendMessage('Follow this article \n https://battlelog.co/post.php?id=19581');
    }
    //Howto Report players
else if (message.includes('howto') && message.includes('report')) {
        channel.sendMessage('Follow this article \n https://battlelog.co/post.php?id=15931');
    }
});
<commit_msg>dont break help.js on dm<commit_after>const bot = require('./bot');

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

bot.on('message', message => {
    var channel = message.channel;
    if(message.author.bot)return;
    if(!message.channel.name)return;//it is a dm
    if (channel.name.indexOf('help')<0 ) {
        return;
    }
    var user = message.author;
    message = message.content.toLowerCase();
    //Error updating
    if (message.includes('updating') && message.includes('forever')) {
        channel.sendMessage('Follow this article \n http://battlelog.co/wiki.php?article=27');
    }
    //Error debugging
else if (message.includes('unknown dynamicoption')) {
        channel.sendMessage('Follow the second part of this article. \n http://battlelog.co/post.php?id=9744');
    }
    //Mouse stuck after launch ingame
else if (message.includes('mouse') && message.includes('stuck')) {
        channel.sendMessage('follow this article\nhttp://battlelog.co/wiki.php?article=7');
    }
    //Invalid CD key Fix
else if (message.includes('invalid') && message.includes('cdkey')) {
        channel.sendMessage('follow these articles\nhttps://battlelog.co/post.php?id=16014&page=1\nhttp://battlelog.co/wiki.php?article=28');
    }
    //Installation Errors
else if (message.includes('installation') && message.includes('failed')) {
        channel.sendMessage('follow this article\nhttp://battlelog.co/post.php?id=17435#p57246');
    }
    //Black screen after launch
else if (message.includes('black screen') && message.includes('help')) {
        channel.sendMessage('Follow this article \nhttp://battlelog.co/post.php?id=9744');
    }
    //Login Errors
else if (message.includes('error') && message.includes('api')) {
        channel.sendMessage('Follow this article \n https://battlelog.co/post.php?id=17435#p93129');
    }
    //DirectX9 errors after launhcer
else if (message.includes('directx9') && message.includes('error')) {
        channel.sendMessage('Follow this article \n https://battlelog.co/wiki.php?article=14');
    }
    //Server Rules Battlelog
else if (message.includes('server') && message.includes('rules')) {
        channel.sendMessage('Follow this article \n https://battlelog.co/post.php?id=19581');
    }
    //Howto Report players
else if (message.includes('howto') && message.includes('report')) {
        channel.sendMessage('Follow this article \n https://battlelog.co/post.php?id=15931');
    }
});
<|endoftext|>


<commit_before>/* eslint-env mocha */
/* eslint no-unused-expressions:0 */

import sinon from 'sinon'
import * as tcpAdapter from '../../src/tcpAdapter'
import { ChannelModel } from '../../src/model/channels'

xdescribe('TCP adapter tests', () => {
  const testChannel = new ChannelModel({
    name: 'test',
    urlPattern: '/test',
    allow: '*',
    type: 'tcp',
    tcpPort: 4000,
    tcpHost: 'localhost'
  })

  const disabledChannel = new ChannelModel({
    name: 'disabled',
    urlPattern: '/disabled',
    allow: '*',
    type: 'tcp',
    tcpPort: 4001,
    tcpHost: 'localhost',
    status: 'disabled'
  })

  before(done => testChannel.save(() => disabledChannel.save(() => done())))

  after(done => tcpAdapter.stopServers(() => ChannelModel.remove({}, done)))

  return xdescribe('.startupServers', () =>
    it('should startup all enabled channels', (done) => {
      const spy = sinon.spy(tcpAdapter, 'startupTCPServer')
      return tcpAdapter.startupServers(() => {
        try {
          spy.calledOnce.should.be.true
          spy.calledWith(testChannel._id)
        } catch (err) {
          return done(err)
        }
        return done()
      })
    })
  )
})
<commit_msg>Updated tcpAdapterTest<commit_after>/* eslint-env mocha */
/* eslint no-unused-expressions:0 */

import sinon from 'sinon'
import * as tcpAdapter from '../../src/tcpAdapter'
import { ChannelModel } from '../../src/model/channels'
import * as constants from '../constants'
import { promisify } from 'util'

describe('TCP adapter tests', () => {
  const testChannel = new ChannelModel({
    name: 'test',
    urlPattern: '/test',
    allow: '*',
    type: 'tcp',
    tcpPort: constants.PORT_START - 1,
    tcpHost: 'localhost'
  })

  const disabledChannel = new ChannelModel({
    name: 'disabled',
    urlPattern: '/disabled',
    allow: '*',
    type: 'tcp',
    tcpPort: constants.PORT_START - 2,
    tcpHost: 'localhost',
    status: 'disabled'
  })

  before(async () => {
    await Promise.all([
      testChannel.save(),
      disabledChannel.save()
    ])
  })

  after(async () => {
    await Promise.all([
      promisify(tcpAdapter.stopServers)(),
      ChannelModel.remove({})
    ])
  })

  describe('.startupServers', () =>
    it('should startup all enabled channels', async () => {
      const spy = sinon.spy(tcpAdapter, 'startupTCPServer')
      await promisify(tcpAdapter.startupServers)()
      spy.calledOnce.should.be.true
      spy.calledWith(testChannel._id)
    })
  )
})
<|endoftext|>


<commit_before>var app = angular.module('timecrunch', ['ui.router']);

app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: '/templates/home.html',
      controller: 'DashCtrl'
    })
    .state('food', {
      url: '/food',
      templateUrl: '/templates/food.html',
      controller: 'ListCtrl',
      resolve: {
        foodPromise: ['foods', function(foods) {
            return foods.getFood();
        }]
      }
    })
    .state('recipes', {
      url: '/recipes',
      templateUrl: '/templates/recipes.html',
      controller: 'ListCtrl',
      resolve: {
        recipePromise: ['recipes', function(recipes) {
            return recipes.getAll();
        }]
      }
    })
    .state('recipeform', {
      url: '/recipes/form',
      templateUrl: '/templates/recipeform.html',
      controller: 'ListCtrl'
    })
    .state('recipe', {
      url: '/recipes/{id}',
      templateUrl: '/templates/recipe.html',
      controller: 'RecipesCtrl',
      resolve: {
        recipe: ['$stateParams', 'recipes', function($stateParams, recipes) {
          return recipes.get($stateParams.id);
        }]
      }
    })
    .state('editRecipe', {
      url: '/recipes/{id}/edit',
      templateUrl: '/templates/recipeeditform.html',
      controller: 'RecipesCtrl',
      resolve: {
        recipe: ['$stateParams', 'recipes', function($stateParams, recipes) {
          return recipes.get($stateParams.id);
        }]
      }
    })
    .state('login', {
      url: '/login',
      templateUrl: '/templates/login.html',
      controller: 'AuthCtrl',
      onEnter: ['$state', 'auth', function($state, auth) {
        if(auth.isLoggedIn()) {
          $state.go('home');
        }
      }]
    })
    .state('register', {
      url: '/register',
      templateUrl: '/templates/register.html',
      controller: 'AuthCtrl',
      onEnter: ['$state', 'auth', function($state, auth) {
        if(auth.isLoggedIn()) {
          $state.go('home');
        }
      }]
    });

  $urlRouterProvider.otherwise('home');
}]);

// Factory for auth handling all authorization and
// user id related functions
app.factory('auth', ['$http', '$window', function($http, $window) {
  var auth = {};

  // save given token
  auth.saveToken = function(token) {
    $window.localStorage['time-crunch-token'] = token;
  };

  // get token from localStorage
  auth.getToken = function() {
    return $window.localStorage['time-crunch-token'];
  };

  // register user
  auth.register = function(user) {
    return $http.post('/register', user).then(function(data) {
      auth.saveToken(data.data.token);
    });
  };

  // login user save token
  auth.logIn = function(user) {
    return $http.post('/login', user).then(function(data) {
      auth.saveToken(data.data.token);
    });
  };

  // logout a user and delete token
  auth.logOut = function() {
    $window.localStorage.removeItem('time-crunch-token');
  };

  // check if user is logged in
  auth.isLoggedIn = function() {
    var token = auth.getToken();

    if(token) {
      var payload = JSON.parse($window.atob(token.split('.')[1]));

      return payload.exp > Date.now() / 1000;
    } else {
      return false;
    }
  };

  // returns currently logged in username
  auth.currentUser = function() {
    if(auth.isLoggedIn()) {
      var token = auth.getToken();
      var payload = JSON.parse($window.atob(token.split('.')[1]));

      return payload.username;
      }
    };

  return auth;
}]);

// Factory for foods handling all related functions
app.factory('foods', ['$http', '$state', 'auth', function($http, $state, auth) {
  var o = {
    foods: []
  };

  // Load food list for the current user
  o.getFood = function() {
    if(auth.isLoggedIn()) {
      return $http.get('/food', {
        headers: {Authorization: 'Bearer ' + auth.getToken()}
      }).then(function(data) {
        angular.copy(data.data, o.foods);
      });
    }
    $state.go('login');
  };

  // Add a food to a user's food list
  o.create = function(food) {
    return $http.post('/food', food, {
      headers: {Authorization: 'Bearer ' + auth.getToken()}
    }).then(function(data) {
      o.getFood();
    });
  };

  // Remove a food from a user's food list
  o.delete = function(food) {
    return $http.delete('/food/' + food._id).then(function(data) {
      o.getFood();
    });
  };

  return o;
}]);

// Factory for recipes handling related functions
app.factory('recipes', ['$http', 'auth', function($http, auth) {
  var o = {
    recipes: []
  };

  // Get all recipes
  o.getAll = function() {
    return $http.get('/recipes').then(function(data) {
      angular.copy(data.data, o.recipes);
    });
  };

  // Get a specific recipe
  o.get = function(id) {
    for(i = 0; i < o.recipes.length; ++i) {
      if(o.recipes[i]._id == id) {
        return o.recipes[i];
      }
    }
  };

  // Create a new recipe
  o.create = function(recipe) {
    return $http.post('/recipes', recipe, {
      headers: {Authorization: 'Bearer ' + auth.getToken()}
    }).then(function(data) {
      o.getAll();
      return data.data._id;
    });
  };

  // Update a recipe
  o.update = function(recipe) {
    return $http.put('/recipes/' + recipe._id, recipe, {
      headers: {Authorization: 'Bearer ' + auth.getToken()}
    }).then(function(data) {
      o.getAll();
    });
  };

  // Delete a recipe
  o.delete = function(recipe) {
    return $http.delete('/recipes/' + recipe._id).then(function(data) {
      o.getAll();
    });
  };

  return o;
}]);

// Factory for ingredients handling related functions
app.factory('ingredients', ['$http', function($http){
  var o = {};

  // Create a new ingredient
  o.create = function(recipeID, ingredient) {
    return $http.post('/recipes/' + recipeID + '/ingredients',
      ingredient).then(function(data) {
        return data.data;
    });
  };

  // Delete an ingredient
  o.delete = function(recipeID, ingredient) {
    return $http.delete('/recipes/' + recipeID + 'ingredients/' + ingredient._id);
  };

  return o;
}]);

// Controller for dashboard on home/index
app.controller('DashCtrl', [
  '$scope',
  'foods',
  function($scope, foods){
    $scope.foods = foods.foods;
}]);

// Controller for recipe and food lists
app.controller('ListCtrl', [
  '$scope',
  '$state',
  'auth',
  'ingredients',
  'foods',
  'recipes',
  function($scope, $state, auth, ingredients, foods, recipes) {

    $scope.foods = foods.foods;
    $scope.recipes = recipes.recipes;
    $scope.ingredients = [];
    $scope.isLoggedIn = auth.isLoggedIn;

    $scope.categories = [
      "Baking",
      "Dairy",
      "Fruit",
      "Herb/Spice",
      "Meat",
      "Sauce",
      "Vegetable",
      "Other-Ingredient",
      "Other-Food",
      "Other-Produce"
    ];

    $scope.sortBy = ["sellBy", "name"];
    $scope.filterCat = "";

    $scope.filter = function() {
      return function(item) {
        if($scope.filterCat == "" || !$scope.filterCat
          || $scope.filterCat == item.category) {
          return true;
        }
        return false;
      };
    };

    // Add a new food
    $scope.addFood = function() {
      // Make sure food name is valid
      if(!$scope.name || $scope.name == '') {
        alert("Please fill in the name field");
        return;
      }
      // If sell by was left blank, set it to 2 years from now
      if(!$scope.sellBy) {
        $scope.sellBy = new Date();
        $scope.sellBy.setDate($scope.sellBy.getDate() + 730);
      }
      foods.create({
        name: $scope.name,
        sellBy: $scope.sellBy,
        amount: $scope.amount,
        units: $scope.units,
        category: $scope.category
      });
    };

    // Remove a food
    $scope.removeFood = function(food) {
      foods.delete(food);
    };

    // Add a new recipe
    $scope.addRecipe = function() {
      //Check that the recipe has a name, ingredients, and instructions
      if(!$scope.name || $scope.name == '' || !$scope.ingredients) {
        alert("Please make sure all fields are filled out");
        return;
      }

      if(!$scope.instructions && !$scope.link) {
        alert("Please provide either instructions or a link to the full recipe");
        return;
      }

      recipes.create({
        name: $scope.name,
        prepTime: $scope.prepTime,
        link: $scope.link,
        instructions: $scope.instructions
      }).then(function success(id) {
        // Return to the recipe list
        for(i = 0; i < $scope.instructions.length; i++) {
          ingredients.create(id, $scope.instructions[i]);
        }
        $state.go('recipes');
      }, function failure(error) {
        // Show error message
        $scope.error = error.data;
      });
    };

    // Add an ingredient to a recipe
    $scope.addIngredient = function() {
      if($scope.ing_name) {
        ($scope.ingredients).push({
          name: $scope.ing_name,
          amount: $scope.ing_amount,
          unit: $scope.ing_unit
        });
      }
      else {
        $scope.error = {
          message: "Missing ingredient name"
        };
      }
    };

    // Remove an ingredient from a recipe
    $scope.removeIngredient = function(ingredient) {
      if($scope.ingredients.length == 1) {
        $scope.ingredients = [];
      }
      else {
        for(i = 0; i < $scope.ingredients.length; i++) {
          if($scope.ingredients[i].name === ingredient.name &&
            $scope.ingredients[i].amount === ingredient.amount &&
            $scope.ingredients[i].unit === ingredient.unit) {
            $scope.ingredients.splice(i, 1);
            break;
          }
        }
      }
    };
}]);

// Controller for recipe details page
app.controller('RecipesCtrl', [
  '$scope',
  '$state',
  'recipe',
  'recipes',
  'auth',
  function($scope, $state, recipe, recipes, auth){
    $scope.recipe = recipe;

    // Determines if a user is allowed to edit this
    // recipe
    $scope.canEdit = function() {
      return recipe.author == auth.currentUser();
    };

    // Remove an ingredient from a recipe
    $scope.removeIngredient = function(ingredient) {
      if($scope.recipe.ingredients.length == 1) {
        $scope.recipe.ingredients = [];
      }
      else {
        var i = $scope.recipe.ingredients.indexOf(ingredient);
        $scope.recipe.ingredients.splice(i, 1);
      }
    };

    // Add an ingredient to a recipe
    $scope.addIngredient = function() {
      // Build the ingredient string
      var ing = $scope.ing_name.concat(" - " + $scope.ing_amount);
      if($scope.ing_unit) {
        ing = ing.concat(" " + $scope.ing_unit);
      }

      // Check if the ingredient is a duplicate
      if($scope.recipe.ingredients.indexOf(ing) > -1) {
        alert("Duplicate ingredients! Please change your entry.");
      }
      else {
        ($scope.recipe.ingredients).push(ing);
      }
    };

    // Edit an existing recipe
    $scope.editRecipe = function() {
      recipes.update($scope.recipe).then(function success() {
        // Return to the recipe list
        $state.go('recipe', {id: recipe._id});
      }, function failure(error) {
        // Show error message
        $scope.error = error.data;
      });
    }

    // Deletes the recipe
    $scope.deleteRecipe = function() {
      // Make sure user is authorized
      if($scope.canEdit()) {
        recipes.delete(recipe);
        $state.go('recipes');
      }
      else {
        // If not allowed show an alert
        alert('You cannot delete this recipe!');
      }
    };

}]);

// Controller for logging in and registering
app.controller('AuthCtrl', [
  '$scope',
  '$state',
  'auth',
  function($scope, $state, auth) {
    $scope.user = {};

    // Registers a new user
    $scope.register = function() {
      auth.register($scope.user).then(function success() {
        // Go to dashboard once logged in
        $state.go('home');
      }, function failure(error) {
        // Show error message
        $scope.error = error.data;
      });
    };

    // Starts a new login session
    $scope.logIn = function() {
      auth.logIn($scope.user).then(function success() {
        // Go to dashboard once logged in
        $state.go('home');
      }, function failure(error) {
        // Show error message
        $scope.error = error.data;
      });
    };
}]);

// Controller for dashboard on home/index
app.controller('NavCtrl', [
  '$scope',
  'auth',
  function($scope, auth){

    $scope.isLoggedIn = auth.isLoggedIn;
    $scope.currentUser = auth.currentUser;
    $scope.logOut = auth.logOut;
}]);<commit_msg>Add ingredient bug fixed in ListCtrl<commit_after>var app = angular.module('timecrunch', ['ui.router']);

app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: '/templates/home.html',
      controller: 'DashCtrl'
    })
    .state('food', {
      url: '/food',
      templateUrl: '/templates/food.html',
      controller: 'ListCtrl',
      resolve: {
        foodPromise: ['foods', function(foods) {
            return foods.getFood();
        }]
      }
    })
    .state('recipes', {
      url: '/recipes',
      templateUrl: '/templates/recipes.html',
      controller: 'ListCtrl',
      resolve: {
        recipePromise: ['recipes', function(recipes) {
            return recipes.getAll();
        }]
      }
    })
    .state('recipeform', {
      url: '/recipes/form',
      templateUrl: '/templates/recipeform.html',
      controller: 'ListCtrl'
    })
    .state('recipe', {
      url: '/recipes/{id}',
      templateUrl: '/templates/recipe.html',
      controller: 'RecipesCtrl',
      resolve: {
        recipe: ['$stateParams', 'recipes', function($stateParams, recipes) {
          return recipes.get($stateParams.id);
        }]
      }
    })
    .state('editRecipe', {
      url: '/recipes/{id}/edit',
      templateUrl: '/templates/recipeeditform.html',
      controller: 'RecipesCtrl',
      resolve: {
        recipe: ['$stateParams', 'recipes', function($stateParams, recipes) {
          return recipes.get($stateParams.id);
        }]
      }
    })
    .state('login', {
      url: '/login',
      templateUrl: '/templates/login.html',
      controller: 'AuthCtrl',
      onEnter: ['$state', 'auth', function($state, auth) {
        if(auth.isLoggedIn()) {
          $state.go('home');
        }
      }]
    })
    .state('register', {
      url: '/register',
      templateUrl: '/templates/register.html',
      controller: 'AuthCtrl',
      onEnter: ['$state', 'auth', function($state, auth) {
        if(auth.isLoggedIn()) {
          $state.go('home');
        }
      }]
    });

  $urlRouterProvider.otherwise('home');
}]);

// Factory for auth handling all authorization and
// user id related functions
app.factory('auth', ['$http', '$window', function($http, $window) {
  var auth = {};

  // save given token
  auth.saveToken = function(token) {
    $window.localStorage['time-crunch-token'] = token;
  };

  // get token from localStorage
  auth.getToken = function() {
    return $window.localStorage['time-crunch-token'];
  };

  // register user
  auth.register = function(user) {
    return $http.post('/register', user).then(function(data) {
      auth.saveToken(data.data.token);
    });
  };

  // login user save token
  auth.logIn = function(user) {
    return $http.post('/login', user).then(function(data) {
      auth.saveToken(data.data.token);
    });
  };

  // logout a user and delete token
  auth.logOut = function() {
    $window.localStorage.removeItem('time-crunch-token');
  };

  // check if user is logged in
  auth.isLoggedIn = function() {
    var token = auth.getToken();

    if(token) {
      var payload = JSON.parse($window.atob(token.split('.')[1]));

      return payload.exp > Date.now() / 1000;
    } else {
      return false;
    }
  };

  // returns currently logged in username
  auth.currentUser = function() {
    if(auth.isLoggedIn()) {
      var token = auth.getToken();
      var payload = JSON.parse($window.atob(token.split('.')[1]));

      return payload.username;
      }
    };

  return auth;
}]);

// Factory for foods handling all related functions
app.factory('foods', ['$http', '$state', 'auth', function($http, $state, auth) {
  var o = {
    foods: []
  };

  // Load food list for the current user
  o.getFood = function() {
    if(auth.isLoggedIn()) {
      return $http.get('/food', {
        headers: {Authorization: 'Bearer ' + auth.getToken()}
      }).then(function(data) {
        angular.copy(data.data, o.foods);
      });
    }
    $state.go('login');
  };

  // Add a food to a user's food list
  o.create = function(food) {
    return $http.post('/food', food, {
      headers: {Authorization: 'Bearer ' + auth.getToken()}
    }).then(function(data) {
      o.getFood();
    });
  };

  // Remove a food from a user's food list
  o.delete = function(food) {
    return $http.delete('/food/' + food._id).then(function(data) {
      o.getFood();
    });
  };

  return o;
}]);

// Factory for recipes handling related functions
app.factory('recipes', ['$http', 'auth', function($http, auth) {
  var o = {
    recipes: []
  };

  // Get all recipes
  o.getAll = function() {
    return $http.get('/recipes').then(function(data) {
      angular.copy(data.data, o.recipes);
    });
  };

  // Get a specific recipe
  o.get = function(id) {
    for(i = 0; i < o.recipes.length; ++i) {
      if(o.recipes[i]._id == id) {
        return o.recipes[i];
      }
    }
  };

  // Create a new recipe
  o.create = function(recipe) {
    return $http.post('/recipes', recipe, {
      headers: {Authorization: 'Bearer ' + auth.getToken()}
    }).then(function(data) {
      o.getAll();
      return data.data._id;
    });
  };

  // Update a recipe
  o.update = function(recipe) {
    return $http.put('/recipes/' + recipe._id, recipe, {
      headers: {Authorization: 'Bearer ' + auth.getToken()}
    }).then(function(data) {
      o.getAll();
    });
  };

  // Delete a recipe
  o.delete = function(recipe) {
    return $http.delete('/recipes/' + recipe._id).then(function(data) {
      o.getAll();
    });
  };

  return o;
}]);

// Factory for ingredients handling related functions
app.factory('ingredients', ['$http', function($http){
  var o = {};

  // Create a new ingredient
  o.create = function(recipeID, ingredient) {
    return $http.post('/recipes/' + recipeID + '/ingredients',
      ingredient).then(function(data) {
        return data.data;
    });
  };

  // Delete an ingredient
  o.delete = function(recipeID, ingredient) {
    return $http.delete('/recipes/' + recipeID + 'ingredients/' + ingredient._id);
  };

  return o;
}]);

// Controller for dashboard on home/index
app.controller('DashCtrl', [
  '$scope',
  'foods',
  function($scope, foods){
    $scope.foods = foods.foods;
}]);

// Controller for recipe and food lists
app.controller('ListCtrl', [
  '$scope',
  '$state',
  'auth',
  'ingredients',
  'foods',
  'recipes',
  function($scope, $state, auth, ingredients, foods, recipes) {

    $scope.foods = foods.foods;
    $scope.recipes = recipes.recipes;
    $scope.ingredients = [];
    $scope.isLoggedIn = auth.isLoggedIn;

    $scope.categories = [
      "Baking",
      "Dairy",
      "Fruit",
      "Herb/Spice",
      "Meat",
      "Sauce",
      "Vegetable",
      "Other-Ingredient",
      "Other-Food",
      "Other-Produce"
    ];

    $scope.sortBy = ["sellBy", "name"];
    $scope.filterCat = "";

    $scope.filter = function() {
      return function(item) {
        if($scope.filterCat == "" || !$scope.filterCat
          || $scope.filterCat == item.category) {
          return true;
        }
        return false;
      };
    };

    // Add a new food
    $scope.addFood = function() {
      // Make sure food name is valid
      if(!$scope.name || $scope.name == '') {
        alert("Please fill in the name field");
        return;
      }
      // If sell by was left blank, set it to 2 years from now
      if(!$scope.sellBy) {
        $scope.sellBy = new Date();
        $scope.sellBy.setDate($scope.sellBy.getDate() + 730);
      }
      foods.create({
        name: $scope.name,
        sellBy: $scope.sellBy,
        amount: $scope.amount,
        units: $scope.units,
        category: $scope.category
      });
    };

    // Remove a food
    $scope.removeFood = function(food) {
      foods.delete(food);
    };

    // Add a new recipe
    $scope.addRecipe = function() {
      //Check that the recipe has a name, ingredients, and instructions
      if(!$scope.name || $scope.name == '' || !$scope.ingredients) {
        alert("Please make sure all fields are filled out");
        return;
      }

      if(!$scope.instructions && !$scope.link) {
        alert("Please provide either instructions or a link to the full recipe");
        return;
      }

      recipes.create({
        name: $scope.name,
        prepTime: $scope.prepTime,
        link: $scope.link,
        instructions: $scope.instructions
      }).then(function success(id) {
        // Return to the recipe list
        for(i = 0; i < $scope.ingredients.length; i++) {
          ingredients.create(id, $scope.ingredients[i]);
        }
        $state.go('recipes');
      }, function failure(error) {
        // Show error message
        $scope.error = error.data;
      });
    };

    // Add an ingredient to a recipe
    $scope.addIngredient = function() {
      if($scope.ing_name) {
        ($scope.ingredients).push({
          name: $scope.ing_name,
          amount: $scope.ing_amount,
          unit: $scope.ing_unit
        });
      }
      else {
        $scope.error = {
          message: "Missing ingredient name"
        };
      }
    };

    // Remove an ingredient from a recipe
    $scope.removeIngredient = function(ingredient) {
      if($scope.ingredients.length == 1) {
        $scope.ingredients = [];
      }
      else {
        for(i = 0; i < $scope.ingredients.length; i++) {
          if($scope.ingredients[i].name === ingredient.name &&
            $scope.ingredients[i].amount === ingredient.amount &&
            $scope.ingredients[i].unit === ingredient.unit) {
            $scope.ingredients.splice(i, 1);
            break;
          }
        }
      }
    };
}]);

// Controller for recipe details page
app.controller('RecipesCtrl', [
  '$scope',
  '$state',
  'recipe',
  'recipes',
  'auth',
  function($scope, $state, recipe, recipes, auth){
    $scope.recipe = recipe;

    // Determines if a user is allowed to edit this
    // recipe
    $scope.canEdit = function() {
      return recipe.author == auth.currentUser();
    };

    // Remove an ingredient from a recipe
    $scope.removeIngredient = function(ingredient) {
      if($scope.recipe.ingredients.length == 1) {
        $scope.recipe.ingredients = [];
      }
      else {
        var i = $scope.recipe.ingredients.indexOf(ingredient);
        $scope.recipe.ingredients.splice(i, 1);
      }
    };

    // Add an ingredient to a recipe
    $scope.addIngredient = function() {
      // Build the ingredient string
      var ing = $scope.ing_name.concat(" - " + $scope.ing_amount);
      if($scope.ing_unit) {
        ing = ing.concat(" " + $scope.ing_unit);
      }

      // Check if the ingredient is a duplicate
      if($scope.recipe.ingredients.indexOf(ing) > -1) {
        alert("Duplicate ingredients! Please change your entry.");
      }
      else {
        ($scope.recipe.ingredients).push(ing);
      }
    };

    // Edit an existing recipe
    $scope.editRecipe = function() {
      recipes.update($scope.recipe).then(function success() {
        // Return to the recipe list
        $state.go('recipe', {id: recipe._id});
      }, function failure(error) {
        // Show error message
        $scope.error = error.data;
      });
    }

    // Deletes the recipe
    $scope.deleteRecipe = function() {
      // Make sure user is authorized
      if($scope.canEdit()) {
        recipes.delete(recipe);
        $state.go('recipes');
      }
      else {
        // If not allowed show an alert
        alert('You cannot delete this recipe!');
      }
    };

}]);

// Controller for logging in and registering
app.controller('AuthCtrl', [
  '$scope',
  '$state',
  'auth',
  function($scope, $state, auth) {
    $scope.user = {};

    // Registers a new user
    $scope.register = function() {
      auth.register($scope.user).then(function success() {
        // Go to dashboard once logged in
        $state.go('home');
      }, function failure(error) {
        // Show error message
        $scope.error = error.data;
      });
    };

    // Starts a new login session
    $scope.logIn = function() {
      auth.logIn($scope.user).then(function success() {
        // Go to dashboard once logged in
        $state.go('home');
      }, function failure(error) {
        // Show error message
        $scope.error = error.data;
      });
    };
}]);

// Controller for dashboard on home/index
app.controller('NavCtrl', [
  '$scope',
  'auth',
  function($scope, auth){

    $scope.isLoggedIn = auth.isLoggedIn;
    $scope.currentUser = auth.currentUser;
    $scope.logOut = auth.logOut;
}]);<|endoftext|>


<commit_before>function Dispatcher (tree_id, map_id) {
  self           = this,
  this.tree      = null,
  this.map       = null,
  this.markers   = {},
  this._data     = null,
  this._infoWindow = new google.maps.InfoWindow({ content : "" }),
  this._tree_elem  = $("#" + tree_id),
  this._map_elem = $("#" + map_id),

  this.init = function(map_id){
    $(window).resize(self.adjustMapHeight).resize();

    self.map = new google.maps.Map( document.getElementById(map_id), {
      zoom      : 11,
      mapTypeId : google.maps.MapTypeId.ROADMAP,
      center    : new google.maps.LatLng(45.5234515, -122.6762071)
    });

    google.maps.event.addListener(self.map, "click", function(){
      self._infoWindow.close();
    });

    self.initTree();
  },

  this.adjustMapHeight = function() {
    self._map_elem.css("height", function(){
      return $(window).height() -
      $("#header").outerHeight() -
      $("#crossbar").outerHeight() -
      ( $("#main").outerHeight() - $("#main").height() ) -
      $("#page-header").outerHeight() - 21 + "px"
    });
  },

  this.initTree = function(){
    self.tree = self._tree_elem.jstree({
      core      : { html_titles : true },
      plugins   : [ "json_data", "themes", "checkbox", "ui" ],
      themes    : { theme : "apple" },
      json_data : { ajax : {
        url : window.location.pathname,
        dataType : "json",
        success : function(data) {
          self._data = data;

          self.positionMarkers();
          self.createNodeListeners();

          window.setTimeout(function(){
            self._tree_elem.jstree("open_all", -1);
            self._tree_elem.jstree("check_all");
          }, 1);
        }
      } },
      checkbox  : { override_ui : true }
    });
  },

  this.positionMarkers = function() {
    if ( self.markers.length < 1 ) self.initMarkers();
    else self.updateMarkers();
  },

  this.initMarkers = function(){
    $.each(self._data, function(){
      $.each(this.children, function(){
        var device_pool = this;
        $.each(device_pool.children, function(){
          self.createMarker(device_pool, this);
        })
      })
    });
  },

  this.updateMarkers = function() {
    $.each(self._data, function(){
      $.each(this.children, function(){
        var device_pool = this;
        $.each(device_pool.children, function(){
          var marker = self.markers[this.metadata.id];
          if (marker) {
            marker.setPosition( new google.maps.LatLng( this.metadata.lat, this.metadata.lng ) );
            marker.html = self._marker_html(device.metadata);
          } else self.createMarker(device_pool, this);
        });
      });
    });
  },

  this.createMarker = function(device_pool, device) {
    var marker = new StyledMarker({
      styleIcon : new StyledIcon( StyledIconTypes.MARKER, { color : device_pool.attr["data-color"] } ),
      position  : new google.maps.LatLng( device.metadata.lat, device.metadata.lng ),
      map       : self.map
    });

    marker.html = self._marker_html(device.metadata);

    self.markers[device.metadata.id] = marker;
    google.maps.event.addListener(marker,"click",function(){
      self._infoWindow.setContent(marker.html);
      self._infoWindow.open(self.map, marker);
    });

    return marker;
  },

  this._marker_html = function(device) {
    return '
\

' + device.name + '
\

' + device.status + '
\

Updated: ' + device.posted_at + '
\

';
  },

  this.refresh = function() {
    self._tree_elem.jstree("refresh");
  },

  this.uncheckNode = function(node){
    self._tree_elem.jstree("uncheck_node", node );
  },

  this.checkNode = function(node){
    self._tree_elem.jstree("check_node", node );
  },

  this.createNodeListeners = function(){
    self._tree_elem.delegate("a","click", function(e) {
      var node = $(this).parent("li");

      if (node.data().lat) // it's a marker
        return self.toggleVisibility( [self.markers[node.data().id.toString()]] );
      else {
        $.each( node.find("[rel=device]"), function(){
          return self.toggleVisibility( [self.markers[$(this).data().id.toString()]] );
        });
      }
    });
  },

  this.toggleVisibility = function(markers){
    $.each(markers, function(){
      var marker = this;
      if (!marker.getMap()) marker.setMap(self.map);
      else marker.setMap(null);
    })
  };

  this.init(map_id);
}<commit_msg>Closing infoWindow on refresh; Fixing typo.<commit_after>function Dispatcher (tree_id, map_id) {
  self           = this,
  this.tree      = null,
  this.map       = null,
  this.markers   = {},
  this._data     = null,
  this._infoWindow = new google.maps.InfoWindow({ content : "" }),
  this._tree_elem  = $("#" + tree_id),
  this._map_elem = $("#" + map_id),

  this.init = function(map_id){
    $(window).resize(self.adjustMapHeight).resize();

    self.map = new google.maps.Map( document.getElementById(map_id), {
      zoom      : 11,
      mapTypeId : google.maps.MapTypeId.ROADMAP,
      center    : new google.maps.LatLng(45.5234515, -122.6762071)
    });

    google.maps.event.addListener(self.map, "click", function(){
      self._infoWindow.close();
    });

    self.initTree();
  },

  this.adjustMapHeight = function() {
    self._map_elem.css("height", function(){
      return $(window).height() -
      $("#header").outerHeight() -
      $("#crossbar").outerHeight() -
      ( $("#main").outerHeight() - $("#main").height() ) -
      $("#page-header").outerHeight() - 21 + "px"
    });
  },

  this.initTree = function(){
    self.tree = self._tree_elem.jstree({
      core      : { html_titles : true },
      plugins   : [ "json_data", "themes", "checkbox", "ui" ],
      themes    : { theme : "apple" },
      json_data : { ajax : {
        url : window.location.pathname,
        dataType : "json",
        success : function(data) {
          self._data = data;

          self.positionMarkers();
          self.createNodeListeners();

          window.setTimeout(function(){
            self._tree_elem.jstree("open_all", -1);
            self._tree_elem.jstree("check_all");
          }, 1);
        }
      } },
      checkbox  : { override_ui : true }
    });
  },

  this.positionMarkers = function() {
    if ( self.markers.length < 1 ) self.initMarkers();
    else self.updateMarkers();
  },

  this.initMarkers = function(){
    $.each(self._data, function(){
      $.each(this.children, function(){
        var device_pool = this;
        $.each(device_pool.children, function(){
          self.createMarker(device_pool, this);
        })
      })
    });
  },

  this.updateMarkers = function() {
    $.each(self._data, function(){
      $.each(this.children, function(){
        var device_pool = this;
        $.each(device_pool.children, function(){
          var marker = self.markers[this.metadata.id];
          if (marker) {
            marker.setPosition( new google.maps.LatLng( this.metadata.lat, this.metadata.lng ) );
            marker.html = self._marker_html(this.metadata);
          } else self.createMarker(device_pool, this);
        });
      });
    });
  },

  this.createMarker = function(device_pool, device) {
    var marker = new StyledMarker({
      styleIcon : new StyledIcon( StyledIconTypes.MARKER, { color : device_pool.attr["data-color"] } ),
      position  : new google.maps.LatLng( device.metadata.lat, device.metadata.lng ),
      map       : self.map
    });

    marker.html = self._marker_html(device.metadata);

    self.markers[device.metadata.id] = marker;
    google.maps.event.addListener(marker,"click",function(){
      self._infoWindow.setContent(marker.html);
      self._infoWindow.open(self.map, marker);
    });

    return marker;
  },

  this._marker_html = function(device) {
    return '
\

' + device.name + '
\

' + device.status + '
\

Updated: ' + device.posted_at + '
\

';
  },

  this.refresh = function() {
    self._infoWindow.close();
    self._tree_elem.jstree("refresh");
  },

  this.uncheckNode = function(node){
    self._tree_elem.jstree("uncheck_node", node );
  },

  this.checkNode = function(node){
    self._tree_elem.jstree("check_node", node );
  },

  this.createNodeListeners = function(){
    self._tree_elem.delegate("a","click", function(e) {
      var node = $(this).parent("li");

      if (node.data().lat) // it's a marker
        return self.toggleVisibility( [self.markers[node.data().id.toString()]] );
      else {
        $.each( node.find("[rel=device]"), function(){
          return self.toggleVisibility( [self.markers[$(this).data().id.toString()]] );
        });
      }
    });
  },

  this.toggleVisibility = function(markers){
    $.each(markers, function(){
      var marker = this;
      if (!marker.getMap()) marker.setMap(self.map);
      else marker.setMap(null);
    })
  };

  this.init(map_id);
}<|endoftext|>


<commit_before>'use strict';

angular.module('eMarketApp').directive('sellItem', function(Category, SellItem) {
  return {
    templateUrl: 'views/sellItem.html',
    restrict: 'E',
    scope: true,
    replace: true,
    controller: function($scope) {
      $scope.setPreviewItemInfo = SellItem.setItemPreview
    },
    link: function(scope, elem) {

      var page = $(elem[0]);
      var freeShippingCheckbox = page.find('#checkbox-free-shipping');
      var shippingPriceInput = page.find('#shipping-price');

      var newCheckBox = page.find('#radio-choice-new');
      var UsedCheckBox = page.find('#radio-choice-used');
      var RefurbishedCheckBox = page.find('#radio-choice-refurbished');

      page.on('pagebeforeshow', function() {

        if(!SellItem.isDraft) {
          scope.item = {};
          SellItem.setDraft({});
        }

        // Get Draft if it is a a draft, if not set an empty object
        scope.item = SellItem.getDraft();

        scope.disableShipping = function() {
          shippingPriceInput.prop('disabled', freeShippingCheckbox.prop('checked'));
          scope.item.shippingPrice = 0;
        };

        Category.getList({flat: true}).then(function(categoryList) {
          scope.categories = categoryList;
        });

        if(SellItem.isDraft && scope.item.condition === 'New') {
          setTimeout(function() {
            newCheckBox.prop('checked', true).checkboxradio('refresh');
            UsedCheckBox.prop('checked', false).checkboxradio('refresh');
            RefurbishedCheckBox.prop('checked', false).checkboxradio('refresh');
          });
        } else if(SellItem.isDraft && scope.item.condition === 'Used') {
          setTimeout(function() {
            newCheckBox.prop('checked', false).checkboxradio('refresh');
            UsedCheckBox.prop('checked', true).checkboxradio('refresh');
            RefurbishedCheckBox.prop('checked', false).checkboxradio('refresh');
          });
        } else if(SellItem.isDraft && scope.item.condition === 'Refurbished') {
          setTimeout(function() {
            newCheckBox.prop('checked', false).checkboxradio('refresh');
            UsedCheckBox.prop('checked', false).checkboxradio('refresh');
            RefurbishedCheckBox.prop('checked', true).checkboxradio('refresh');
          });
        } else {
          setTimeout(function() {
            newCheckBox.prop('checked', false).checkboxradio('refresh');
            UsedCheckBox.prop('checked', false).checkboxradio('refresh');
            RefurbishedCheckBox.prop('checked', false).checkboxradio('refresh');
          });
        }

        if(SellItem.isDraft && scope.item.shippingPrice === 0) {
          setTimeout(function() {
            freeShippingCheckbox.prop('checked', true).checkboxradio('refresh');
          });
        } else {
          setTimeout(function() {
            freeShippingCheckbox.prop('checked', false).checkboxradio('refresh');
          });
        }

      });

    }
  };
});
<commit_msg>Making sellItem Category Scrollable to custom heights<commit_after>'use strict';

angular.module('eMarketApp').directive('sellItem', function(Category, SellItem) {
  return {
    templateUrl: 'views/sellItem.html',
    restrict: 'E',
    scope: true,
    replace: true,
    controller: function($scope) {
      $scope.setPreviewItemInfo = SellItem.setItemPreview;
    },
    link: function(scope, elem) {

      var page = $(elem[0]);
      var freeShippingCheckbox = page.find('#checkbox-free-shipping');
      var shippingPriceInput = page.find('#shipping-price');

      var newCheckBox = page.find('#radio-choice-new');
      var UsedCheckBox = page.find('#radio-choice-used');
      var RefurbishedCheckBox = page.find('#radio-choice-refurbished');

      var categoryPopup = page.find('#popupCategory');

      page.on('pagebeforeshow', function() {

        categoryPopup.on({
          popupbeforeposition: function() {
            var maxHeight = $.mobile.window.innerHeight() / 1.75;
            categoryPopup.css('overflow-y', 'scroll');
            categoryPopup.height(maxHeight);
          }
        });

        if(!SellItem.isDraft) {
          scope.item = {};
          SellItem.setDraft({});
        }

        // Get Draft if it is a a draft, if not set an empty object
        scope.item = SellItem.getDraft();

        scope.disableShipping = function() {
          shippingPriceInput.prop('disabled', freeShippingCheckbox.prop('checked'));
          scope.item.shippingPrice = 0;
        };

        Category.getList({flat: true}).then(function(categoryList) {
          scope.categories = categoryList;
        });

        if(SellItem.isDraft && scope.item.condition === 'New') {
          setTimeout(function() {
            newCheckBox.prop('checked', true).checkboxradio('refresh');
            UsedCheckBox.prop('checked', false).checkboxradio('refresh');
            RefurbishedCheckBox.prop('checked', false).checkboxradio('refresh');
          });
        } else if(SellItem.isDraft && scope.item.condition === 'Used') {
          setTimeout(function() {
            newCheckBox.prop('checked', false).checkboxradio('refresh');
            UsedCheckBox.prop('checked', true).checkboxradio('refresh');
            RefurbishedCheckBox.prop('checked', false).checkboxradio('refresh');
          });
        } else if(SellItem.isDraft && scope.item.condition === 'Refurbished') {
          setTimeout(function() {
            newCheckBox.prop('checked', false).checkboxradio('refresh');
            UsedCheckBox.prop('checked', false).checkboxradio('refresh');
            RefurbishedCheckBox.prop('checked', true).checkboxradio('refresh');
          });
        } else {
          setTimeout(function() {
            newCheckBox.prop('checked', false).checkboxradio('refresh');
            UsedCheckBox.prop('checked', false).checkboxradio('refresh');
            RefurbishedCheckBox.prop('checked', false).checkboxradio('refresh');
          });
        }

        if(SellItem.isDraft && scope.item.shippingPrice === 0) {
          setTimeout(function() {
            freeShippingCheckbox.prop('checked', true).checkboxradio('refresh');
          });
        } else {
          setTimeout(function() {
            freeShippingCheckbox.prop('checked', false).checkboxradio('refresh');
          });
        }

      });

    }
  };
});
<|endoftext|>