<commit_before>#import "assertions.js"
#import "lang-ext.js"

extend(UIATableView.prototype, {
  /**
   * A shortcut for:
   *  this.cells().firstWithName(name)
   */
  cellNamed: function(name) {
    return this.cells().firstWithName(name);
  },

  /**
   * Asserts that this table has a cell with the name (accessibility label)
   * matching the given +name+ argument.
   */
  assertCellNamed: function(name) {
    assertNotNull(this.cellNamed(name), "No table cell found named '" + name + "'");
  }
});

extend(UIAElement.prototype, {
	/**
	 * Poll till the item becomes visible, up to a specified timeout
	 */
	waitUntilVisible: function (timeoutInSeconds) {
        this.waitUntil(function(element) {
            return element;
        }, function(element) {
            return element.isVisible();
        }, timeoutInSeconds, "to become visible");
	},

	/**
	 * Wait until element becomes invisible
	 */
	waitUntilInvisible: function (timeoutInSeconds) {
        this.waitUntil(function(element) {
            return element;
        }, function(element) {
            return !element.isVisible();
        }, timeoutInSeconds, "to become invisible");
    },

    /**
     * Wait until child element with name is added
     */
    waitUntilFoundByName: function (name, timeoutInSeconds) {
        this.waitUntil(function(element) {
            return element.elements().firstWithName(name);
        }, function(element) {
            return element.isValid();
        }, timeoutInSeconds, "to become valid");
    },

    /**
     * Wait until child element with name is removed
     */
    waitUntilNotFoundByName: function (name, timeoutInSeconds) {
        this.waitUntil(function(element) {
            return element.elements().firstWithName(name);
        }, function(element) {
            return !element.isValid();
        }, timeoutInSeconds, "to become invalid");
    },

    /**
     * Wait until element fulfills condition
     */
    waitUntil: function (filterFunction, conditionFunction, timeoutInSeconds, description) {
        timeoutInSeconds = timeoutInSeconds == null ? 5 : timeoutInSeconds;
        var element = this;
        var delay = 0.25;
        retry(function() {
            var filteredElement = filterFunction(element);
            if(!conditionFunction(filteredElement)) {
                throw(["Element", filteredElement, "failed", description, "within", timeoutInSeconds, "seconds."].join(" "));
            }
        }, Math.max(1, timeoutInSeconds/delay), delay);
    },

  /**
   * A shortcut for waiting an element to become visible and tap.
   */
  vtap: function() {
    this.waitUntilVisible(10);
    this.tap();
  },
  /**
   * A shortcut for touching an element and waiting for it to disappear.
   */
  tapAndWaitForInvalid: function() {
    this.tap();
    this.waitForInvalid();
  }
});

extend(UIAApplication.prototype, {
  /**
   * A shortcut for getting the current view controller's title from the
   * navigation bar. If there is no navigation bar, this method returns null
   */
  navigationTitle: function() {
    navBar = this.mainWindow().navigationBar();
    if (navBar) {
      return navBar.name();
    }
    return null;
  },

  /**
   * A shortcut for checking that the interface orientation in either
   * portrait mode
   */
  isPortraitOrientation: function() {
    var orientation = this.interfaceOrientation();
    return orientation == UIA_DEVICE_ORIENTATION_PORTRAIT ||
      orientation == UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN;
  },

  /**
   * A shortcut for checking that the interface orientation in one of the
   * landscape orientations.
   */
  isLandscapeOrientation: function() {
    var orientation = this.interfaceOrientation();
    return orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT ||
      orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;
  }
});

extend(UIANavigationBar.prototype, {
  /**
   * Asserts that the left button's name matches the given +name+ argument
   */
  assertLeftButtonNamed: function(name) {
    assertEquals(name, this.leftButton().name());
  },

  /**
   * Asserts that the right button's name matches the given +name+ argument
   */
  assertRightButtonNamed: function(name) {
    assertEquals(name, this.rightButton().name());
  }
});

extend(UIATarget.prototype, {
  /**
   * A shortcut for checking that the interface orientation in either
   * portrait mode
   */
  isPortraitOrientation: function() {
    var orientation = this.deviceOrientation();
    return orientation == UIA_DEVICE_ORIENTATION_PORTRAIT ||
      orientation == UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN;
   },

  /**
   * A shortcut for checking that the interface orientation in one of the
   * landscape orientations.
   */
  isLandscapeOrientation: function() {
    var orientation = this.deviceOrientation();
    return orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT ||
      orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;
   },

   /**
    * A convenience method for detecting that you're running on an iPad
    */
    isDeviceiPad: function() {
      //model is iPhone Simulator, even when running in iPad mode
      return this.model().match(/^iPad/) !== null ||
        this.name().match(/iPad Simulator/) !== null;
    },

    /**
     * A convenience method for detecting that you're running on an
     * iPhone or iPod touch
     */
    isDeviceiPhone: function() {
      return this.model().match(/^iPad/) === null &&
        this.name().match(/^iPad Simulator$/) === null;
    }
});
extend(UIAKeyboard.prototype,{
  KEYBOARD_TYPE_UNKNOWN :-1,
  KEYBOARD_TYPE_ALPHA : 0,
  KEYBOARD_TYPE_ALPHA_CAPS : 1,
  KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION:2,
  KEYBOARD_TYPE_NUMBER:3,
  keyboardType : function() {
  if (this.keys().length < 12){
    return this.KEYBOARD_TYPE_NUMBER;
  } else if (this.keys().firstWithName("a").toString() != "[object UIAElementNil]") {
    return this.KEYBOARD_TYPE_ALPHA;
  } else if (this.keys().firstWithName("A").toString() != "[object UIAElementNil]") {
    return this.KEYBOARD_TYPE_ALPHA_CAPS;
  } else if (this.keys().firstWithName("1").toString() != "[object UIAElementNil]") {
    return this.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION;
  } else {
    return this.KEYBOARD_TYPE_UNKNOWN;
  }
  }
});

/*
TODO: Character keyboard is super slow.
*/
var typeString = function(pstrString, pbClear) {
  pstrString += ''; // convert number to string
  if (!this.hasKeyboardFocus()){
    this.tap();
  }

  UIATarget.localTarget().delay(0.5);

  if (pbClear || pstrString.length === 0) {
    this.clear();
  }

  if (pstrString.length > 0) {
    var app = UIATarget.localTarget().frontMostApp();
    var keyboard = app.keyboard();
    var keys = app.keyboard().keys();
    var buttons = app.keyboard().buttons();
    for (i = 0; i < pstrString.length; i++) {
      var intKeyboardType = keyboard.keyboardType();
      var bIsAllCaps = (intKeyboardType == keyboard.KEYBOARD_TYPE_ALPHA_CAPS); //Handles autocapitalizationType = UITextAutocapitalizationTypeAllCharacters
      var intNewKeyboardType = intKeyboardType;
      var strChar = pstrString.charAt(i);
      if ((/[a-z]/.test(strChar)) && intKeyboardType == keyboard.KEYBOARD_TYPE_ALPHA_CAPS && !bIsAllCaps) {
        buttons.firstWithName("shift").tap();
        intKeyboardType = keyboard.KEYBOARD_TYPE_ALPHA;
      } else if ((/[A-Z]/.test(strChar)) && intKeyboardType == keyboard.KEYBOARD_TYPE_ALPHA) {
        buttons.firstWithName("shift").tap();
        intKeyboardType = keyboard.KEYBOARD_TYPE_ALPHA_CAPS;
      } else if ((/[A-z]/.test(strChar)) && intKeyboardType == keyboard.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION) {
        buttons.firstWithName("more, letters").tap();
        intKeyboardType = keyboard.KEYBOARD_TYPE_ALPHA;
      } else if ((/[0-9.]/.test(strChar)) && intKeyboardType != keyboard.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION && intKeyboardType != keyboard.KEYBOARD_TYPE_NUMBER) {
        buttons.firstWithName("more, numbers").tap();
        intKeyboardType = keyboard.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION;
      }

      if ((/[a-z]/.test(strChar)) && intKeyboardType == keyboard.KEYBOARD_TYPE_ALPHA_CAPS) {
        strChar = strChar.toUpperCase();
      }
      if (strChar == " ") {
        keys["space"].tap();
      } else if (/[0-9]/.test(strChar)) { // Need to change strChar to the index key of the number because strChar = "0" will tap "1" and strChar = "1" will tap "2"
        if (strChar == "0") {
          if (intKeyboardType == keyboard.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION) {
            strChar = "9";
          } else {
            strChar = "10";
          }
        } else {
          strChar = (parseInt(strChar, 10) - 1).toString();
        }
        keys[strChar].tap();
      } else {
        keys[strChar].tap(); // TODO: this line is super slow when there are many keys
      }
      UIATarget.localTarget().delay(0.5);
    }
  }
};

extend(UIATextField.prototype,{
  typeString: typeString
});
extend(UIATextView.prototype,{
	typeString: typeString
});

extend(UIAPickerWheel.prototype, {

   /*
    * Better implementation than UIAPickerWheel.selectValue
    * Works also for texts
    * Poorly works not for UIDatePickers -> because .values() which get all values of wheel does not work :(
    * I think this is a bug in UIAutomation!
    */
   scrollToValue: function (valueToSelect) {

      var element = this;

      var values = this.values();
      var pickerValue = element.value();

      // convert to string
      valueToSelect = valueToSelect + "";

      // some wheels return for .value()  "17. 128 of 267" ?? don't know why
      // throw away all after "." but be careful lastIndexOf is used because the value can
      // also have "." in it!! e.g.: "1.2. 13 of 27"
      if (pickerValue.lastIndexOf(".") != -1) {
        var currentValue = pickerValue.substr(0, pickerValue.lastIndexOf("."));
      } else {
        var currentValue = element.value();
      }

      var currentValueIndex = values.indexOf(currentValue);
      var valueToSelectIndex = values.indexOf(valueToSelect);

      if (valueToSelectIndex == -1) {
        fail("value: " + valueToSelect + " not found in Wheel!");
      }

      var elementsToScroll = valueToSelectIndex - currentValueIndex;

      UIALogger.logDebug("number of elements to scroll: " + elementsToScroll);
      if (elementsToScroll > 0) {

          for (i=0; i<elementsToScroll; i++) {
            element.tapWithOptions({tapOffset:{x:0.35, y:0.67}});
            target.delay(0.7);
          }

      } else {

          for (i=0; i>elementsToScroll; i--) {
            element.tapWithOptions({tapOffset:{x:0.35, y:0.31}});
            target.delay(0.7);
          }
      }
   },

   /*
    * Wheels filled with values return for .value()  "17. 128 of 267" ?? don't know why -> for comparisons this is unuseful!!
    * If you want to check a value of a wheel this function is very helpful
    */
   realValue: function() {

      // current value of wheel
      var pickerValue = this.value();

      // throw away all after "." but be careful lastIndexOf is used because the value can
      if (pickerValue.lastIndexOf(".") != -1) {
        return pickerValue.substr(0, pickerValue.lastIndexOf("."));
      }

      return this.value();
   }
});
<commit_msg>Added shortcut for detecting iPhone 5<commit_after>#import "assertions.js"
#import "lang-ext.js"

extend(UIATableView.prototype, {
  /**
   * A shortcut for:
   *  this.cells().firstWithName(name)
   */
  cellNamed: function(name) {
    return this.cells().firstWithName(name);
  },

  /**
   * Asserts that this table has a cell with the name (accessibility label)
   * matching the given +name+ argument.
   */
  assertCellNamed: function(name) {
    assertNotNull(this.cellNamed(name), "No table cell found named '" + name + "'");
  }
});

extend(UIAElement.prototype, {
	/**
	 * Poll till the item becomes visible, up to a specified timeout
	 */
	waitUntilVisible: function (timeoutInSeconds) {
        this.waitUntil(function(element) {
            return element;
        }, function(element) {
            return element.isVisible();
        }, timeoutInSeconds, "to become visible");
	},

	/**
	 * Wait until element becomes invisible
	 */
	waitUntilInvisible: function (timeoutInSeconds) {
        this.waitUntil(function(element) {
            return element;
        }, function(element) {
            return !element.isVisible();
        }, timeoutInSeconds, "to become invisible");
    },

    /**
     * Wait until child element with name is added
     */
    waitUntilFoundByName: function (name, timeoutInSeconds) {
        this.waitUntil(function(element) {
            return element.elements().firstWithName(name);
        }, function(element) {
            return element.isValid();
        }, timeoutInSeconds, "to become valid");
    },

    /**
     * Wait until child element with name is removed
     */
    waitUntilNotFoundByName: function (name, timeoutInSeconds) {
        this.waitUntil(function(element) {
            return element.elements().firstWithName(name);
        }, function(element) {
            return !element.isValid();
        }, timeoutInSeconds, "to become invalid");
    },

    /**
     * Wait until element fulfills condition
     */
    waitUntil: function (filterFunction, conditionFunction, timeoutInSeconds, description) {
        timeoutInSeconds = timeoutInSeconds == null ? 5 : timeoutInSeconds;
        var element = this;
        var delay = 0.25;
        retry(function() {
            var filteredElement = filterFunction(element);
            if(!conditionFunction(filteredElement)) {
                throw(["Element", filteredElement, "failed", description, "within", timeoutInSeconds, "seconds."].join(" "));
            }
        }, Math.max(1, timeoutInSeconds/delay), delay);
    },

  /**
   * A shortcut for waiting an element to become visible and tap.
   */
  vtap: function() {
    this.waitUntilVisible(10);
    this.tap();
  },
  /**
   * A shortcut for touching an element and waiting for it to disappear.
   */
  tapAndWaitForInvalid: function() {
    this.tap();
    this.waitForInvalid();
  }
});

extend(UIAApplication.prototype, {
  /**
   * A shortcut for getting the current view controller's title from the
   * navigation bar. If there is no navigation bar, this method returns null
   */
  navigationTitle: function() {
    navBar = this.mainWindow().navigationBar();
    if (navBar) {
      return navBar.name();
    }
    return null;
  },

  /**
   * A shortcut for checking that the interface orientation in either
   * portrait mode
   */
  isPortraitOrientation: function() {
    var orientation = this.interfaceOrientation();
    return orientation == UIA_DEVICE_ORIENTATION_PORTRAIT ||
      orientation == UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN;
  },

  /**
   * A shortcut for checking that the interface orientation in one of the
   * landscape orientations.
   */
  isLandscapeOrientation: function() {
    var orientation = this.interfaceOrientation();
    return orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT ||
      orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;
  }
});

extend(UIANavigationBar.prototype, {
  /**
   * Asserts that the left button's name matches the given +name+ argument
   */
  assertLeftButtonNamed: function(name) {
    assertEquals(name, this.leftButton().name());
  },

  /**
   * Asserts that the right button's name matches the given +name+ argument
   */
  assertRightButtonNamed: function(name) {
    assertEquals(name, this.rightButton().name());
  }
});

extend(UIATarget.prototype, {
  /**
   * A shortcut for checking that the interface orientation in either
   * portrait mode
   */
  isPortraitOrientation: function() {
    var orientation = this.deviceOrientation();
    return orientation == UIA_DEVICE_ORIENTATION_PORTRAIT ||
      orientation == UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN;
   },

  /**
   * A shortcut for checking that the interface orientation in one of the
   * landscape orientations.
   */
  isLandscapeOrientation: function() {
    var orientation = this.deviceOrientation();
    return orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT ||
      orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;
   },

   /**
    * A convenience method for detecting that you're running on an iPad
    */
    isDeviceiPad: function() {
      //model is iPhone Simulator, even when running in iPad mode
      return this.model().match(/^iPad/) !== null ||
        this.name().match(/iPad Simulator/) !== null;
    },

    /**
     * A convenience method for detecting that you're running on an
     * iPhone or iPod touch
     */
    isDeviceiPhone: function() {
      return this.model().match(/^iPad/) === null &&
        this.name().match(/^iPad Simulator$/) === null;
    },

    /**
     * A shortcut for checking if target device is iPhone 5 (or iPod Touch
     * 5th generation)
     */
  	isDeviceiPhone5: function() {
  		var isIphone = this.isDeviceiPhone();
  		var deviceScreen = this.rect();
      	return isIphone && deviceScreen.size.height == 568;
     }
});
extend(UIAKeyboard.prototype,{
  KEYBOARD_TYPE_UNKNOWN :-1,
  KEYBOARD_TYPE_ALPHA : 0,
  KEYBOARD_TYPE_ALPHA_CAPS : 1,
  KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION:2,
  KEYBOARD_TYPE_NUMBER:3,
  keyboardType : function() {
  if (this.keys().length < 12){
    return this.KEYBOARD_TYPE_NUMBER;
  } else if (this.keys().firstWithName("a").toString() != "[object UIAElementNil]") {
    return this.KEYBOARD_TYPE_ALPHA;
  } else if (this.keys().firstWithName("A").toString() != "[object UIAElementNil]") {
    return this.KEYBOARD_TYPE_ALPHA_CAPS;
  } else if (this.keys().firstWithName("1").toString() != "[object UIAElementNil]") {
    return this.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION;
  } else {
    return this.KEYBOARD_TYPE_UNKNOWN;
  }
  }
});

/*
TODO: Character keyboard is super slow.
*/
var typeString = function(pstrString, pbClear) {
  pstrString += ''; // convert number to string
  if (!this.hasKeyboardFocus()){
    this.tap();
  }

  UIATarget.localTarget().delay(0.5);

  if (pbClear || pstrString.length === 0) {
    this.clear();
  }

  if (pstrString.length > 0) {
    var app = UIATarget.localTarget().frontMostApp();
    var keyboard = app.keyboard();
    var keys = app.keyboard().keys();
    var buttons = app.keyboard().buttons();
    for (i = 0; i < pstrString.length; i++) {
      var intKeyboardType = keyboard.keyboardType();
      var bIsAllCaps = (intKeyboardType == keyboard.KEYBOARD_TYPE_ALPHA_CAPS); //Handles autocapitalizationType = UITextAutocapitalizationTypeAllCharacters
      var intNewKeyboardType = intKeyboardType;
      var strChar = pstrString.charAt(i);
      if ((/[a-z]/.test(strChar)) && intKeyboardType == keyboard.KEYBOARD_TYPE_ALPHA_CAPS && !bIsAllCaps) {
        buttons.firstWithName("shift").tap();
        intKeyboardType = keyboard.KEYBOARD_TYPE_ALPHA;
      } else if ((/[A-Z]/.test(strChar)) && intKeyboardType == keyboard.KEYBOARD_TYPE_ALPHA) {
        buttons.firstWithName("shift").tap();
        intKeyboardType = keyboard.KEYBOARD_TYPE_ALPHA_CAPS;
      } else if ((/[A-z]/.test(strChar)) && intKeyboardType == keyboard.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION) {
        buttons.firstWithName("more, letters").tap();
        intKeyboardType = keyboard.KEYBOARD_TYPE_ALPHA;
      } else if ((/[0-9.]/.test(strChar)) && intKeyboardType != keyboard.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION && intKeyboardType != keyboard.KEYBOARD_TYPE_NUMBER) {
        buttons.firstWithName("more, numbers").tap();
        intKeyboardType = keyboard.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION;
      }

      if ((/[a-z]/.test(strChar)) && intKeyboardType == keyboard.KEYBOARD_TYPE_ALPHA_CAPS) {
        strChar = strChar.toUpperCase();
      }
      if (strChar == " ") {
        keys["space"].tap();
      } else if (/[0-9]/.test(strChar)) { // Need to change strChar to the index key of the number because strChar = "0" will tap "1" and strChar = "1" will tap "2"
        if (strChar == "0") {
          if (intKeyboardType == keyboard.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION) {
            strChar = "9";
          } else {
            strChar = "10";
          }
        } else {
          strChar = (parseInt(strChar, 10) - 1).toString();
        }
        keys[strChar].tap();
      } else {
        keys[strChar].tap(); // TODO: this line is super slow when there are many keys
      }
      UIATarget.localTarget().delay(0.5);
    }
  }
};

extend(UIATextField.prototype,{
  typeString: typeString
});
extend(UIATextView.prototype,{
	typeString: typeString
});

extend(UIAPickerWheel.prototype, {

   /*
    * Better implementation than UIAPickerWheel.selectValue
    * Works also for texts
    * Poorly works not for UIDatePickers -> because .values() which get all values of wheel does not work :(
    * I think this is a bug in UIAutomation!
    */
   scrollToValue: function (valueToSelect) {

      var element = this;

      var values = this.values();
      var pickerValue = element.value();

      // convert to string
      valueToSelect = valueToSelect + "";

      // some wheels return for .value()  "17. 128 of 267" ?? don't know why
      // throw away all after "." but be careful lastIndexOf is used because the value can
      // also have "." in it!! e.g.: "1.2. 13 of 27"
      if (pickerValue.lastIndexOf(".") != -1) {
        var currentValue = pickerValue.substr(0, pickerValue.lastIndexOf("."));
      } else {
        var currentValue = element.value();
      }

      var currentValueIndex = values.indexOf(currentValue);
      var valueToSelectIndex = values.indexOf(valueToSelect);

      if (valueToSelectIndex == -1) {
        fail("value: " + valueToSelect + " not found in Wheel!");
      }

      var elementsToScroll = valueToSelectIndex - currentValueIndex;

      UIALogger.logDebug("number of elements to scroll: " + elementsToScroll);
      if (elementsToScroll > 0) {

          for (i=0; i<elementsToScroll; i++) {
            element.tapWithOptions({tapOffset:{x:0.35, y:0.67}});
            target.delay(0.7);
          }

      } else {

          for (i=0; i>elementsToScroll; i--) {
            element.tapWithOptions({tapOffset:{x:0.35, y:0.31}});
            target.delay(0.7);
          }
      }
   },

   /*
    * Wheels filled with values return for .value()  "17. 128 of 267" ?? don't know why -> for comparisons this is unuseful!!
    * If you want to check a value of a wheel this function is very helpful
    */
   realValue: function() {

      // current value of wheel
      var pickerValue = this.value();

      // throw away all after "." but be careful lastIndexOf is used because the value can
      if (pickerValue.lastIndexOf(".") != -1) {
        return pickerValue.substr(0, pickerValue.lastIndexOf("."));
      }

      return this.value();
   }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import WebsocketProxy from '../helpers/websocket-proxy';
import { normalizeURL, cleanURL } from '../helpers';

const { Service, get, set } = Ember;

export default Service.extend({
  /*
    A hash of open websocket connections. This
    allows multiple components to share the same connection.

    {
      'websocket-url': WebSocket Proxy object
    }
  */
  sockets: Ember.computed(function() {
    return {};
  }),

  /*
    socketFor returns a websocket proxy object. On this object there is a property `socket`
    which contains the actual websocket object. This websocket object is cached based off of the url meaning
    multiple requests for the same socket will return the same object.
  */
  socketFor(url, protocols = []) {
    /*
      Websockets allows either a string or array of strings to be passed as the second argument.
      Normalize both cases into an array of strings so we can just deal with arrays.
    */
    if (typeof protocols === 'string') { protocols = [protocols]; }

    /*
      Normalize the url as native websockets add a / to the end of the url:
      http://example.com:8000 becomes: http://example.com:8000/

      Since the url will be used as a key will need to make sure that it does not
      contain '.' as it will throw ember off
    */
    const normalizedUrl = normalizeURL(url);
    const cleanedUrl = cleanURL(normalizedUrl);

    /*

    */
    const existingProxy = get(this, `sockets.${cleanedUrl}`);

    if (existingProxy && this.isWebSocketOpen(existingProxy.socket)) {
      return existingProxy;
    }

    /*
      we can get to this place if the websocket has been closed and we are trying to reopen
      or we are creating a proxy for the first time
    */
    const newWebSocket = this.createSocket(normalizedUrl, protocols);

    if (existingProxy) {
      /*
        If there is an existing socket in place we simply update the websocket object and not
        the whole proxy as we dont want to destroy the previous listeners.
      */
      existingProxy.socket = newWebSocket;
      return existingProxy;
    }

    const newProxy = this.createProxy(newWebSocket, protocols);

    set(this, `sockets.${cleanedUrl}`, newProxy);

    return newProxy;
  },

  closeSocketFor(url) {
    const cleanedUrl = cleanURL(normalizeURL(url));
    get(this, `sockets.${cleanedUrl}`).socket.close();
  },

  isWebSocketOpen(websocket) {
    return websocket.readyState !== WebSocket.CLOSED;
  },

  createSocket(url, options) {
    return new WebSocket(url, options);
  },

  createProxy(socket, protocols) {
    return WebsocketProxy.create({ content: this, protocols, socket });
  }
});
<commit_msg>Fix websocket proxy object is not removed from cache<commit_after>import Ember from 'ember';
import WebsocketProxy from '../helpers/websocket-proxy';
import { normalizeURL, cleanURL } from '../helpers';

const { Service, get, set } = Ember;

export default Service.extend({
  /*
    A hash of open websocket connections. This
    allows multiple components to share the same connection.

    {
      'websocket-url': WebSocket Proxy object
    }
  */
  sockets: Ember.computed(function() {
    return {};
  }),

  /*
    socketFor returns a websocket proxy object. On this object there is a property `socket`
    which contains the actual websocket object. This websocket object is cached based off of the url meaning
    multiple requests for the same socket will return the same object.
  */
  socketFor(url, protocols = []) {
    /*
      Websockets allows either a string or array of strings to be passed as the second argument.
      Normalize both cases into an array of strings so we can just deal with arrays.
    */
    if (typeof protocols === 'string') { protocols = [protocols]; }

    /*
      Normalize the url as native websockets add a / to the end of the url:
      http://example.com:8000 becomes: http://example.com:8000/

      Since the url will be used as a key will need to make sure that it does not
      contain '.' as it will throw ember off
    */
    const normalizedUrl = normalizeURL(url);
    const cleanedUrl = cleanURL(normalizedUrl);

    /*

    */
    const existingProxy = get(this, `sockets.${cleanedUrl}`);

    if (existingProxy && this.isWebSocketOpen(existingProxy.socket)) {
      return existingProxy;
    }

    /*
      we can get to this place if the websocket has been closed and we are trying to reopen
      or we are creating a proxy for the first time
    */
    const newWebSocket = this.createSocket(normalizedUrl, protocols);

    if (existingProxy) {
      /*
        If there is an existing socket in place we simply update the websocket object and not
        the whole proxy as we dont want to destroy the previous listeners.
      */
      existingProxy.socket = newWebSocket;
      return existingProxy;
    }

    const newProxy = this.createProxy(newWebSocket, protocols);

    set(this, `sockets.${cleanedUrl}`, newProxy);

    return newProxy;
  },

  closeSocketFor(url) {
    const cleanedUrl = cleanURL(normalizeURL(url));
    get(this, `sockets.${cleanedUrl}`).socket.close();
    delete get(this, 'sockets')[cleanedUrl];
  },

  isWebSocketOpen(websocket) {
    return websocket.readyState !== WebSocket.CLOSED;
  },

  createSocket(url, options) {
    return new WebSocket(url, options);
  },

  createProxy(socket, protocols) {
    return WebsocketProxy.create({ content: this, protocols, socket });
  }
});
<|endoftext|>


<commit_before>"use strict";
var JsonLoader_1 = require("jsontyped/dist/JsonLoader");
exports.Config = JsonLoader_1.JsonLoader.loadFile(".", "proton.json");
//# sourceMappingURL=Config.js.map<commit_msg>Update jsontyped version<commit_after>"use strict";
var jsontyped_1 = require("jsontyped");
exports.Config = jsontyped_1.JsonLoader.loadFile(".", "proton.json");
//# sourceMappingURL=Config.js.map<|endoftext|>


<commit_before>(function () {
		function config($stateProvider, $locationProvider, $authProvider, RestangularProvider) {
    window.slug = location.hostname.substring(0,location.hostname.indexOf("."));
		RestangularProvider.setBaseUrl('https://rescue-site-api.herokuapp.com/api');

		$authProvider.configure({
			apiUrl: 'https://rescue-site-api.herokuapp.com/api'
		});

// https://rescue-site-api.herokuapp.com/api

		$locationProvider
			.html5Mode({
				enabled: true,
				requireBase: false
		});

		$stateProvider
			.state('landing', {
				url: '/',
				controller: 'landingController as landing',
				templateUrl: '/templates/landing.html'
			})

			.state('animals', {
				url: '/animals',
				controller: 'listingController as listing',
				templateUrl: '/templates/listing.html'
			})

			.state('profile', {
				url: '/animals/:slug',
				controller: 'profileController as profile',
				templateUrl: '/templates/profile.html'
			})

			.state('adoption', {
				url: '/animals/:slug/adoption',
				controller: 'adoptionFormController as adoptionForm',
				templateUrl: '/templates/adoption.html'
			})

			.state('adoption-show', {
				url: '/adoption-forms',
				controller: 'adoptionShowController as adoptionShow',
				templateUrl: '/templates/adoption-show.html'
			})

			.state('adoption-print', {
				url: '/adoption-forms/:id',
				controller: 'adoptionPrintController as adoptionPrint',
				templateUrl: '/templates/adoption-print.html'
			})

			.state('contact', {
				url: '/contact',
				controller: 'contactController as contact',
				templateUrl: '/templates/contact.html'
			})

			.state('admin', {
				url: '/admin',
				controller: 'adminController as admin',
				templateUrl: '/templates/admin.html'
			});
	}

	angular
		.module('rescueSite', ['ui.router', 'ui.bootstrap', 'restangular', 'ngFileUpload', 'ngAnimate', 'ngTouch', 'ng-token-auth', 'ipCookie'])
		.config(config)
		.run(function($auth) {
			$auth.validateUser();
		});
})();
<commit_msg>dist url change<commit_after>(function () {
		function config($stateProvider, $locationProvider, $authProvider, RestangularProvider) {
    window.slug = location.hostname.substring(0,location.hostname.indexOf("."));
		RestangularProvider.setBaseUrl('https://rescue-site-api.herokuapp.com/api');

		$authProvider.configure({
			apiUrl: 'https://rescue-site-api.herokuapp.com/api'
		});

// https://rescue-site-api.herokuapp.com/api

		$locationProvider
			.html5Mode({
				enabled: true,
				requireBase: false
		});

		$stateProvider
			.state('landing', {
				url: '/',
				controller: 'landingController as landing',
				templateUrl: '/templates/landing.html'
			})

			.state('animals', {
				url: '/animals',
				controller: 'listingController as listing',
				templateUrl: '/templates/listing.html'
			})

			.state('profile', {
				url: '/animals/:slug',
				controller: 'profileController as profile',
				templateUrl: '/templates/profile.html'
			})

			.state('adoption', {
				url: '/animals/:slug/adoption',
				controller: 'adoptionFormController as adoptionForm',
				templateUrl: '/templates/adoption.html'
			})

			.state('adoption-show', {
				url: '/adoption-forms',
				controller: 'adoptionShowController as adoptionShow',
				templateUrl: '/templates/adoption-show.html'
			})

			.state('adoption-print', {
				url: '/adoption-forms/:id',
				controller: 'adoptionPrintController as adoptionPrint',
				templateUrl: '/templates/adoption-print.html'
			})

			.state('contact', {
				url: '/contact',
				controller: 'contactController as contact',
				templateUrl: '/templates/contact.html'
			})

			.state('admin', {
				url: '/admin',
				controller: 'adminController as admin',
				templateUrl: '/templates/admin.html'
			});
	}

	angular
		.module('rescueSite', ['ui.router', 'ui.bootstrap', 'restangular', 'ngFileUpload', 'ngAnimate', 'ngTouch', 'ng-token-auth', 'ipCookie'])
		.config(config)
		.run(function($auth) {
			$auth.validateUser();
		});
})();
<|endoftext|>


<commit_before>ace.define("ace/mode/json_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var JsonHighlightRules = function() {
    this.$rules = {
        "start" : [
            {
                token : "variable", // single line
                regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]\\s*(?=:)'
            }, {
                token : "string", // single line
                regex : '"',
                next  : "string"
            }, {
                token : "constant.numeric", // hex
                regex : "0[xX][0-9a-fA-F]+\\b"
            }, {
                token : "constant.numeric", // float
                regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
            }, {
                token : "constant.language.boolean",
                regex : "(?:true|false)\\b"
            }, {
                token : "invalid.illegal", // single quoted strings are not allowed
                regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
            }, {
                token : "invalid.illegal", // comments are not allowed
                regex : "\\/\\/.*$"
            }, {
                token : "paren.lparen",
                regex : "[[({]"
            }, {
                token : "paren.rparen",
                regex : "[\\])}]"
            }, {
                token : "text",
                regex : "\\s+"
            }
        ],
        "string" : [
            {
                token : "constant.language.escape",
                regex : /\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|["\\\/bfnrt])/
            }, {
                token : "string",
                regex : '[^"\\\\]+'
            }, {
                token : "string",
                regex : '"',
                next  : "start"
            }, {
                token : "string",
                regex : "",
                next  : "start"
            }
        ]
    };

};

oop.inherits(JsonHighlightRules, TextHighlightRules);

exports.JsonHighlightRules = JsonHighlightRules;
});

ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) {
"use strict";

var Range = require("../range").Range;

var MatchingBraceOutdent = function() {};

(function() {

    this.checkOutdent = function(line, input) {
        if (! /^\s+$/.test(line))
            return false;

        return /^\s*\}/.test(input);
    };

    this.autoOutdent = function(doc, row) {
        var line = doc.getLine(row);
        var match = line.match(/^(\s*\})/);

        if (!match) return 0;

        var column = match[1].length;
        var openBracePos = doc.findMatchingBracket({row: row, column: column});

        if (!openBracePos || openBracePos.row == row) return 0;

        var indent = this.$getIndent(doc.getLine(openBracePos.row));
        doc.replace(new Range(row, 0, row, column-1), indent);
    };

    this.$getIndent = function(line) {
        return line.match(/^\s*/)[0];
    };

}).call(MatchingBraceOutdent.prototype);

exports.MatchingBraceOutdent = MatchingBraceOutdent;
});

ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var TokenIterator = require("../../token_iterator").TokenIterator;
var lang = require("../../lib/lang");

var SAFE_INSERT_IN_TOKENS =
    ["text", "paren.rparen", "punctuation.operator"];
var SAFE_INSERT_BEFORE_TOKENS =
    ["text", "paren.rparen", "punctuation.operator", "comment"];

var context;
var contextCache = {};
var initContext = function(editor) {
    var id = -1;
    if (editor.multiSelect) {
        id = editor.selection.index;
        if (contextCache.rangeCount != editor.multiSelect.rangeCount)
            contextCache = {rangeCount: editor.multiSelect.rangeCount};
    }
    if (contextCache[id])
        return context = contextCache[id];
    context = contextCache[id] = {
        autoInsertedBrackets: 0,
        autoInsertedRow: -1,
        autoInsertedLineEnd: "",
        maybeInsertedBrackets: 0,
        maybeInsertedRow: -1,
        maybeInsertedLineStart: "",
        maybeInsertedLineEnd: ""
    };
};

var getWrapped = function(selection, selected, opening, closing) {
    var rowDiff = selection.end.row - selection.start.row;
    return {
        text: opening + selected + closing,
        selection: [
                0,
                selection.start.column + 1,
                rowDiff,
                selection.end.column + (rowDiff ? 0 : 1)
            ]
    };
};

var CstyleBehaviour = function() {
    this.add("braces", "insertion", function(state, action, editor, session, text) {
        var cursor = editor.getCursorPosition();
        var line = session.doc.getLine(cursor.row);
        if (text == '{') {
            initContext(editor);
            var selection = editor.getSelectionRange();
            var selected = session.doc.getTextRange(selection);
            if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
                return getWrapped(selection, selected, '{', '}');
            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
                if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
                    CstyleBehaviour.recordAutoInsert(editor, session, "}");
                    return {
                        text: '{}',
                        selection: [1, 1]
                    };
                } else {
                    CstyleBehaviour.recordMaybeInsert(editor, session, "{");
                    return {
                        text: '{',
                        selection: [1, 1]
                    };
                }
            }
        } else if (text == '}') {
            initContext(editor);
            var rightChar = line.substring(cursor.column, cursor.column + 1);
            if (rightChar == '}') {
                var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
                    CstyleBehaviour.popAutoInsertedClosing();
                    return {
                        text: '',
                        selection: [1, 1]
                    };
                }
            }
        } else if (text == "\n" || text == "\r\n") {
            initContext(editor);
            var closing = "";
            if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
                closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
                CstyleBehaviour.clearMaybeInsertedClosing();
            }
            var rightChar = line.substring(cursor.column, cursor.column + 1);
            if (rightChar === '}') {
                var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
                if (!openBracePos)
                     return null;
                var next_indent = this.$getIndent(session.getLine(openBracePos.row));
            } else if (closing) {
                var next_indent = this.$getIndent(line);
            } else {
                CstyleBehaviour.clearMaybeInsertedClosing();
                return;
            }
            var indent = next_indent + session.getTabString();

            return {
                text: '\n' + indent + '\n' + next_indent + closing,
                selection: [1, indent.length, 1, indent.length]
            };
        } else {
            CstyleBehaviour.clearMaybeInsertedClosing();
        }
    });

    this.add("braces", "deletion", function(state, action, editor, session, range) {
        var selected = session.doc.getTextRange(range);
        if (!range.isMultiLine() && selected == '{') {
            initContext(editor);
            var line = session.doc.getLine(range.start.row);
            var rightChar = line.substring(range.end.column, range.end.column + 1);
            if (rightChar == '}') {
                range.end.column++;
                return range;
            } else {
                context.maybeInsertedBrackets--;
            }
        }
    });

    this.add("parens", "insertion", function(state, action, editor, session, text) {
        if (text == '(') {
            initContext(editor);
            var selection = editor.getSelectionRange();
            var selected = session.doc.getTextRange(selection);
            if (selected !== "" && editor.getWrapBehavioursEnabled()) {
                return getWrapped(selection, selected, '(', ')');
            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
                CstyleBehaviour.recordAutoInsert(editor, session, ")");
                return {
                    text: '()',
                    selection: [1, 1]
                };
            }
        } else if (text == ')') {
            initContext(editor);
            var cursor = editor.getCursorPosition();
            var line = session.doc.getLine(cursor.row);
            var rightChar = line.substring(cursor.column, cursor.column + 1);
            if (rightChar == ')') {
                var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
                    CstyleBehaviour.popAutoInsertedClosing();
                    return {
                        text: '',
                        selection: [1, 1]
                    };
                }
            }
        }
    });

    this.add("parens", "deletion", function(state, action, editor, session, range) {
        var selected = session.doc.getTextRange(range);
        if (!range.isMultiLine() && selected == '(') {
            initContext(editor);
            var line = session.doc.getLine(range.start.row);
            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
            if (rightChar == ')') {
                range.end.column++;
                return range;
            }
        }
    });

    this.add("brackets", "insertion", function(state, action, editor, session, text) {
        if (text == '[') {
            initContext(editor);
            var selection = editor.getSelectionRange();
            var selected = session.doc.getTextRange(selection);
            if (selected !== "" && editor.getWrapBehavioursEnabled()) {
                return getWrapped(selection, selected, '[', ']');
            } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
                CstyleBehaviour.recordAutoInsert(editor, session, "]");
                return {
                    text: '[]',
                    selection: [1, 1]
                };
            }
        } else if (text == ']') {
            initContext(editor);
            var cursor = editor.getCursorPosition();
            var line = session.doc.getLine(cursor.row);
            var rightChar = line.substring(cursor.column, cursor.column + 1);
            if (rightChar == ']') {
                var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
                if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
                    CstyleBehaviour.popAutoInsertedClosing();
                    return {
                        text: '',
                        selection: [1, 1]
                    };
                }
            }
        }
    });

    this.add("brackets", "deletion", function(state, action, editor, session, range) {
        var selected = session.doc.getTextRange(range);
        if (!range.isMultiLine() && selected == '[') {
            initContext(editor);
            var line = session.doc.getLine(range.start.row);
            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
            if (rightChar == ']') {
                range.end.column++;
                return range;
            }
        }
    });

    this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
        if (text == '"' || text == "'") {
            initContext(editor);
            var quote = text;
            var selection = editor.getSelectionRange();
            var selected = session.doc.getTextRange(selection);
            if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
                return getWrapped(selection, selected, quote, quote);
            } else if (!selected) {
                var cursor = editor.getCursorPosition();
                var line = session.doc.getLine(cursor.row);
                var leftChar = line.substring(cursor.column-1, cursor.column);
                var rightChar = line.substring(cursor.column, cursor.column + 1);

                var token = session.getTokenAt(cursor.row, cursor.column);
                var rightToken = session.getTokenAt(cursor.row, cursor.column + 1);
                if (leftChar == "\\" && token && /escape/.test(token.type))
                    return null;

                var stringBefore = token && /string|escape/.test(token.type);
                var stringAfter = !rightToken || /string|escape/.test(rightToken.type);

                var pair;
                if (rightChar == quote) {
                    pair = stringBefore !== stringAfter;
                } else {
                    if (stringBefore && !stringAfter)
                        return null; // wrap string with different quote
                    if (stringBefore && stringAfter)
                        return null; // do not pair quotes inside strings
                    var wordRe = session.$mode.tokenRe;
                    wordRe.lastIndex = 0;
                    var isWordBefore = wordRe.test(leftChar);
                    wordRe.lastIndex = 0;
                    var isWordAfter = wordRe.test(leftChar);
                    if (isWordBefore || isWordAfter)
                        return null; // before or after alphanumeric
                    if (rightChar && !/[\s;,.})\]\\]/.test(rightChar))
                        return null; // there is rightChar and it isn't closing
                    pair = true;
                }
                return {
                    text: pair ? quote + quote : "",
                    selection: [1,1]
                };
            }
        }
    });

    this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
        var selected = session.doc.getTextRange(range);
        if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
            initContext(editor);
            var line = session.doc.getLine(range.start.row);
            var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
            if (rightChar == selected) {
                range.end.column++;
                return range;
            }
        }
    });

};

CstyleBehaviour.isSaneInsertion = function(editor, session) {
    var cursor = editor.getCursorPosition();
    var iterator = new TokenIterator(session, cursor.row, cursor.column);
    if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
        var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
        if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
            return false;
    }
    iterator.stepForward();
    return iterator.getCurrentTokenRow() !== cursor.row ||
        this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
};

CstyleBehaviour.$matchTokenType = function(token, types) {
    return types.indexOf(token.type || token) > -1;
};

CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
    var cursor = editor.getCursorPosition();
    var line = session.doc.getLine(cursor.row);
    if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
        context.autoInsertedBrackets = 0;
    context.autoInsertedRow = cursor.row;
    context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
    context.autoInsertedBrackets++;
};

CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
    var cursor = editor.getCursorPosition();
    var line = session.doc.getLine(cursor.row);
    if (!this.isMaybeInsertedClosing(cursor, line))
        context.maybeInsertedBrackets = 0;
    context.maybeInsertedRow = cursor.row;
    context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
    context.maybeInsertedLineEnd = line.substr(cursor.column);
    context.maybeInsertedBrackets++;
};

CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
    return context.autoInsertedBrackets > 0 &&
        cursor.row === context.autoInsertedRow &&
        bracket === context.autoInsertedLineEnd[0] &&
        line.substr(cursor.column) === context.autoInsertedLineEnd;
};

CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
    return context.maybeInsertedBrackets > 0 &&
        cursor.row === context.maybeInsertedRow &&
        line.substr(cursor.column) === context.maybeInsertedLineEnd &&
        line.substr(0, cursor.column) == context.maybeInsertedLineStart;
};

CstyleBehaviour.popAutoInsertedClosing = function() {
    context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
    context.autoInsertedBrackets--;
};

CstyleBehaviour.clearMaybeInsertedClosing = function() {
    if (context) {
        context.maybeInsertedBrackets = 0;
        context.maybeInsertedRow = -1;
    }
};

oop.inherits(CstyleBehaviour, Behaviour);

exports.CstyleBehaviour = CstyleBehaviour;
});

ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";

var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;

var FoldMode = exports.FoldMode = function(commentRegex) {
    if (commentRegex) {
        this.foldingStartMarker = new RegExp(
            this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
        );
        this.foldingStopMarker = new RegExp(
            this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
        );
    }
};
oop.inherits(FoldMode, BaseFoldMode);

(function() {

    this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
    this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
    this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
    this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
    this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
    this._getFoldWidgetBase = this.getFoldWidget;
    this.getFoldWidget = function(session, foldStyle, row) {
        var line = session.getLine(row);

        if (this.singleLineBlockCommentRe.test(line)) {
            if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
                return "";
        }

        var fw = this._getFoldWidgetBase(session, foldStyle, row);

        if (!fw && this.startRegionRe.test(line))
            return "start"; // lineCommentRegionStart

        return fw;
    };

    this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
        var line = session.getLine(row);

        if (this.startRegionRe.test(line))
            return this.getCommentRegionBlock(session, line, row);

        var match = line.match(this.foldingStartMarker);
        if (match) {
            var i = match.index;

            if (match[1])
                return this.openingBracketBlock(session, match[1], row, i);

            var range = session.getCommentFoldRange(row, i + match[0].length, 1);

            if (range && !range.isMultiLine()) {
                if (forceMultiline) {
                    range = this.getSectionRange(session, row);
                } else if (foldStyle != "all")
                    range = null;
            }

            return range;
        }

        if (foldStyle === "markbegin")
            return;

        var match = line.match(this.foldingStopMarker);
        if (match) {
            var i = match.index + match[0].length;

            if (match[1])
                return this.closingBracketBlock(session, match[1], row, i);

            return session.getCommentFoldRange(row, i, -1);
        }
    };

    this.getSectionRange = function(session, row) {
        var line = session.getLine(row);
        var startIndent = line.search(/\S/);
        var startRow = row;
        var startColumn = line.length;
        row = row + 1;
        var endRow = row;
        var maxRow = session.getLength();
        while (++row < maxRow) {
            line = session.getLine(row);
            var indent = line.search(/\S/);
            if (indent === -1)
                continue;
            if  (startIndent > indent)
                break;
            var subRange = this.getFoldWidgetRange(session, "all", row);

            if (subRange) {
                if (subRange.start.row <= startRow) {
                    break;
                } else if (subRange.isMultiLine()) {
                    row = subRange.end.row;
                } else if (startIndent == indent) {
                    break;
                }
            }
            endRow = row;
        }

        return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
    };
    this.getCommentRegionBlock = function(session, line, row) {
        var startColumn = line.search(/\s*$/);
        var maxRow = session.getLength();
        var startRow = row;

        var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
        var depth = 1;
        while (++row < maxRow) {
            line = session.getLine(row);
            var m = re.exec(line);
            if (!m) continue;
            if (m[1]) depth--;
            else depth++;

            if (!depth) break;
        }

        var endRow = row;
        if (endRow > startRow) {
            return new Range(startRow, startColumn, endRow, line.length);
        }
    };

}).call(FoldMode.prototype);

});

ace.define("ace/mode/json",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/json_highlight_rules","ace/mode/matching_brace_outdent","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/worker/worker_client"], function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var HighlightRules = require("./json_highlight_rules").JsonHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var WorkerClient = require("../worker/worker_client").WorkerClient;

var Mode = function() {
    this.HighlightRules = HighlightRules;
    this.$outdent = new MatchingBraceOutdent();
    this.$behaviour = new CstyleBehaviour();
    this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);

(function() {

    this.getNextLineIndent = function(state, line, tab) {
        var indent = this.$getIndent(line);

        if (state == "start") {
            var match = line.match(/^.*[\{\(\[]\s*$/);
            if (match) {
                indent += tab;
            }
        }

        return indent;
    };

    this.checkOutdent = function(state, line, input) {
        return this.$outdent.checkOutdent(line, input);
    };

    this.autoOutdent = function(state, doc, row) {
        this.$outdent.autoOutdent(doc, row);
    };

    this.createWorker = function(session) {
        var worker = new WorkerClient(["ace"], "ace/mode/json_worker", "JsonWorker");
        worker.attachToDocument(session.getDocument());

        worker.on("annotate", function(e) {
            session.setAnnotations(e.data);
        });

        worker.on("terminate", function() {
            session.clearAnnotations();
        });

        return worker;
    };

    this.$id = "ace/mode/json";
}).call(Mode.prototype);

exports.Mode = Mode;
});
<commit_msg>Update public/libs/bower_components/ace-builds/src-noconflict/mode-json.js<commit_after><|endoftext|>


<commit_before>'use strict';

/**
* @ngdoc controller
* @name groupbuys.controller:GroupbuysController
*
* @requires $cope
* @requires $stateParams
* @requires $location
* @requires $translate
* @requires users.service:Authentication
* @requires users.service:Groupbuys
*
* @description
* Controlador encargado de la gestión de las Compras en Grupo.
*/

// Groupbuys controller
angular.module('groupbuys').controller('GroupbuysController', ['$scope','Restangular', '$stateParams', '$location', '$translate', 'Authentication', 'Groupbuys',
function($scope, Restangular, $stateParams, $location, $translate, Authentication, Groupbuys) {
	$scope.authentication = Authentication;

	//$locationProvider.html5Mode(true); // Mode HTML5

	// Configuration of tinyMCE
	$scope.tinymceOptions = {
		resize: false,
		menubar: false,
		statusbar: false,
		plugins: 'textcolor image table',
		toolbar1: 'bold italic underline strikethrough | forecolor backcolor fontsizeselect | removeformat',
		toolbar2: 'alignleft aligncenter alignright | bullist numlist outdent indent | table image'
	};

	// ----------------------
	$scope.loadList = function(){
		var serverData = Restangular.all('groupbuys').getList();

		serverData.then(function(data) {

			// Add the real URL to the elements
			for (var i=0; i<data.length; i++) {
				data[i].restangularUrl = data[i].getRequestedUrl();
			}

			$scope.groupbuys = data;

		}, function errorCallback() {
	// TODO translate this key and don't use alert
			alert("Error getting data from server");
		});
	};

	// ----------------------

	/**
	* @ngdoc method
	* @name groupbuys.controller:GroupbuysController.$scope.create
	* @methodOf groupbuys.controller:GroupbuysController
	*
	* @description
	* Create new Groupbuy and redirects to the manage page
	*/
	$scope.create = function(isValid) {
		if (isValid) {
			console.log('create-begin');

			var newGroupbuy = {};
			newGroupbuy.title = $scope.groupbuy.title;
			newGroupbuy.description = $scope.groupbuy.description;

			Restangular.all('groupbuys').post(newGroupbuy).then(function(serverResponse) {

			// Redirect after save
			// TODO parse and get Id
			//	$location.path('groupbuys/' + response._id + '/manage');

			}, function(serverResponse) {
				// TODO parse and show errors
				console.log("Error sending data to server");
			});
		}
	};

	// ----------------------
// from the top of the file
}
]);
<commit_msg>Documented function<commit_after>'use strict';

/**
* @ngdoc controller
* @name groupbuys.controller:GroupbuysController
*
* @requires $cope
* @requires $stateParams
* @requires $location
* @requires $translate
* @requires users.service:Authentication
* @requires users.service:Groupbuys
*
* @description
* Controlador encargado de la gestión de las Compras en Grupo.
*/

// Groupbuys controller
angular.module('groupbuys').controller('GroupbuysController', ['$scope','Restangular', '$stateParams', '$location', '$translate', 'Authentication', 'Groupbuys',
function($scope, Restangular, $stateParams, $location, $translate, Authentication, Groupbuys) {
	$scope.authentication = Authentication;

	//$locationProvider.html5Mode(true); // Mode HTML5

	// Configuration of tinyMCE
	$scope.tinymceOptions = {
		resize: false,
		menubar: false,
		statusbar: false,
		plugins: 'textcolor image table',
		toolbar1: 'bold italic underline strikethrough | forecolor backcolor fontsizeselect | removeformat',
		toolbar2: 'alignleft aligncenter alignright | bullist numlist outdent indent | table image'
	};

	// ----------------------

	/**
	* @ngdoc method
	* @name groupbuys.controller:GroupbuysController.$scope.loadList
	* @methodOf groupbuys.controller:GroupbuysController
	*
	* @description
	* Gets the list of Groupbuys from the server and processes it.
	*/
	$scope.loadList = function(){
		var serverData = Restangular.all('groupbuys').getList();

		serverData.then(function(data) {

			// Add the real URL to the elements
			for (var i=0; i<data.length; i++) {
				data[i].restangularUrl = data[i].getRequestedUrl();
			}

			$scope.groupbuys = data;

		}, function errorCallback() {
	// TODO translate this key and don't use alert
			alert('Error getting data from server');
		});
	};

	// ----------------------

	/**
	* @ngdoc method
	* @name groupbuys.controller:GroupbuysController.$scope.create
	* @methodOf groupbuys.controller:GroupbuysController
	*
	* @description
	* Create new Groupbuy and redirects to the manage page
	*/
	$scope.create = function(isValid) {
		if (isValid) {
			console.log('create-begin');

			var newGroupbuy = {};
			newGroupbuy.title = $scope.groupbuy.title;
			newGroupbuy.description = $scope.groupbuy.description;

			Restangular.all('groupbuys').post(newGroupbuy).then(function(serverResponse) {

			// Redirect after save
			// TODO parse and get Id
			//	$location.path('groupbuys/' + response._id + '/manage');

			}, function(serverResponse) {
				// TODO parse and show errors
				console.log("Error sending data to server");
			});
		}
	};

	// ----------------------
// from the top of the file
}
]);
<|endoftext|>


<commit_before>'use strict';

// Schedules controller
angular.module('schedules').controller('SchedulesController', ['$scope', '$stateParams', '$location', 'Authentication','Committees', 'Schedules', '$log',
	function($scope, $stateParams, $location, Authentication,Committees, Schedules, $log ) {
		$scope.authentication = Authentication;

		// Create new Schedule
		$scope.create = function() {
			// Create new Schedule object
			var schedule = new Schedules.Schedules ({
				name: 'TestZachary'
			});
			$scope.schedule =schedule;
			// Redirect after save
			schedule.$save(function(response) {
				//$location.path('schedules/' + response._id);

				// Clear form fields
        console.log('schedule: '+schedule._id);
        console.log('schedule: '+$scope.committee._id);
       // $scope.addSchedule(schedule);

       $scope.addSchedule(schedule);

				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Schedule
		$scope.remove = function( schedule ) {
			if ( schedule ) { schedule.$remove();

				for (var i in $scope.schedules ) {
					if ($scope.schedules [i] === schedule ) {
						$scope.schedules.splice(i, 1);
					}
				}
			} else {
				$scope.schedule.$remove(function() {
					$location.path('schedules');
				});
			}
		};

		// Update existing Schedule
		$scope.update = function() {
			var schedule = $scope.schedule ;

			schedule.$update(function() {
				$location.path('schedules/' + schedule._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Schedules
		$scope.find = function() {
			$scope.schedules = Schedules.Schedules.query();
		};

		// Find existing Schedule
		$scope.findOne = function() {
			$scope.schedule = Schedules.Schedules.get({
				scheduleId: $stateParams.scheduleId
			});
		};

    $scope.addNewEvent = function(){
      // var schedule = $scope.schedule;
      // $scope.schedule.eventToAdd = schedule.events[index];

      $log.debug('Entered addEvent');

      var tempEventObject = {
          'title' : $scope.newEvent.name,
          'start' : new Date($scope.newEvent.startY,$scope.newEvent.startM,$scope.newEvent.startD),
          'end'   : new Date($scope.newEvent.endY,$scope.newEvent.endM,$scope.newEvent.endD)
      };

      $log.debug('tempEventObject:');
      $log.debug(tempEventObject);

      $scope.events.push(tempEventObject);

      $log.debug('Events Array:');
      $log.debug($scope.events);

      $log.debug('Schedule:');
      $log.debug($scope.schedule);

      var index = $scope.events.length-1;
      $scope.schedule.eventToAdd = $scope.events[index];

      $log.debug('Event to Add:');
      $log.debug($scope.schedule.eventToAdd);

      Schedules.Event.put({scheduleId: schedule._id}).$promise.then(function(data) {
        $log.debug('Data from Sucessful Added Event:');
        $log.debug(data);
        $scope.schedule = data;
      });
    };

      $scope.removeEvent = function(index){
      var schedule = $scope.schedule;
      var eventToRemove = schedule.events[index];
      Schedules.Event.delete({scheduleId: schedule._id}).$promise.then(function(data) {
        // $log.debug(data);
        $scope.schedule = data;
      });
    };

      $scope.getEvents = function(){
      var schedule = $scope.schedule;
      Schedules.Event.query({scheduleId: schedule._id}).$promise.then(function(data) {
        // $log.debug(data);
        $scope.schedule = data;
      });
    };

		 var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    /* event source that contains custom events on the scope */
    $scope.events = [
      {title: 'All Day Event',start: new Date(y, m, 1)},
      {title: 'Long Event',start: new Date(y, m, d - 5),end: new Date(y, m, d - 2)},
      {id: 999,title: 'Repeating Event',start: new Date(y, m, d - 3, 16, 0),allDay: false},
      {id: 999,title: 'Repeating Event',start: new Date(y, m, d + 4, 16, 0),allDay: false},
      {title: 'Birthday Party',start: new Date(y, m, d + 1, 19, 0),end: new Date(y, m, d + 1, 22, 30),allDay: false},
      {title: 'Click for Google',start: new Date(y, m, 28),end: new Date(y, m, 29),url: 'http://google.com/'}
    ];
    /* event source that calls a function on every view switch */
    $scope.eventsF = function (start, end, callback) {
      var s = new Date(start).getTime() / 1000;
      var e = new Date(end).getTime() / 1000;
      var m = new Date(start).getMonth();
      var events = [{title: 'Feed Me ' + m,start: s + (50000),end: s + (100000),allDay: false, className: ['customFeed']}];
      callback(events);
    };

    $scope.calEventsExt = {
       color: '#f00',
       textColor: 'yellow',
       events: [
          {type:'party',title: 'Lunch',start: new Date(y, m, d, 12, 0),end: new Date(y, m, d, 14, 0),allDay: false},
          {type:'party',title: 'Lunch 2',start: new Date(y, m, d, 12, 0),end: new Date(y, m, d, 14, 0),allDay: false},
          {type:'party',title: 'Click for Google',start: new Date(y, m, 28),end: new Date(y, m, 29),url: 'http://google.com/'}
        ]
    };
    /* alert on eventClick */
    $scope.alertOnEventClick = function( event, allDay, jsEvent, view ){
        $scope.alertMessage = (event.title + ' was clicked ');
		  console.log(event.title);
    };
    /* alert on Drop */
     $scope.alertOnDrop = function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view){
       $scope.alertMessage = ('Event Droped to make dayDelta ' + dayDelta);
    };
    /* alert on Resize */
    $scope.alertOnResize = function(event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ){
       $scope.alertMessage = ('Event Resized to make dayDelta ' + minuteDelta);
    };
    /* add and removes an event source of choice */
    $scope.addRemoveEventSource = function(sources,source) {
      var canAdd = 0;
      angular.forEach(sources,function(value, key){
        if(sources[key] === source){
          sources.splice(key,1);
          canAdd = 1;
        }
      });
      if(canAdd === 0){
        sources.push(source);
      }
    };
    /* add custom event*/
    $scope.addEvent = function() {
      $scope.events.push({
        title: 'Open Sesame',
        start: new Date(y, m, 28),
        end: new Date(y, m, 29),
        className: ['openSesame']
      });
    };
    /* remove event */
    $scope.remove = function(index) {
      $scope.events.splice(index,1);
    };
    /* Change View */
    $scope.changeView = function(view,calendar) {
      calendar.fullCalendar('changeView',view);
    };
    /* Change View */
    $scope.renderCalender = function(calendar) {
      calendar.fullCalendar('render');
    };
    /* config object */
    $scope.uiConfig = {
      calendar:{
        height: 450,
        editable: true,
        header:{
          left: 'title',
          center: '',
          right: 'today prev,next'
        },
        eventClick: $scope.alertOnEventClick,
        eventDrop: $scope.alertOnDrop,
        eventResize: $scope.alertOnResize
      }
    };
    /* event sources array*/
    $scope.eventSources = [$scope.events];

	}
]);<commit_msg>changed findOne() in schedule controller to find a certain id and set the schedule scope.<commit_after>'use strict';

// Schedules controller
angular.module('schedules').controller('SchedulesController', ['$scope', '$stateParams', '$location', 'Authentication','Committees', 'Schedules', '$log',
	function($scope, $stateParams, $location, Authentication,Committees, Schedules, $log ) {
		$scope.authentication = Authentication;

		// Create new Schedule
		$scope.create = function() {
			// Create new Schedule object
			var schedule = new Schedules.Schedules ({
				name: 'TestZachary'
			});
			$scope.schedule =schedule;
			// Redirect after save
			schedule.$save(function(response) {
				//$location.path('schedules/' + response._id);

				// Clear form fields
        console.log('schedule: '+schedule._id);
        console.log('schedule: '+$scope.committee._id);
       // $scope.addSchedule(schedule);

       $scope.addSchedule(schedule);

				$scope.name = '';
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Remove existing Schedule
		$scope.remove = function( schedule ) {
			if ( schedule ) { schedule.$remove();

				for (var i in $scope.schedules ) {
					if ($scope.schedules [i] === schedule ) {
						$scope.schedules.splice(i, 1);
					}
				}
			} else {
				$scope.schedule.$remove(function() {
					$location.path('schedules');
				});
			}
		};

		// Update existing Schedule
		$scope.update = function() {
			var schedule = $scope.schedule ;

			schedule.$update(function() {
				$location.path('schedules/' + schedule._id);
			}, function(errorResponse) {
				$scope.error = errorResponse.data.message;
			});
		};

		// Find a list of Schedules
		$scope.find = function() {
			$scope.schedules = Schedules.Schedules.query();
		};

		// Find existing Schedule
		// Find existing Schedule
		$scope.findOne = function(id) {
			$scope.schedule = Schedules.Schedules.get({
				scheduleId: id
			});
			console.log($scope.schedule);
		};

    $scope.addNewEvent = function(){
      // var schedule = $scope.schedule;
      // $scope.schedule.eventToAdd = schedule.events[index];

      $log.debug('Entered addEvent');

      var tempEventObject = {
          'title' : $scope.newEvent.name,
          'start' : new Date($scope.newEvent.startY,$scope.newEvent.startM,$scope.newEvent.startD),
          'end'   : new Date($scope.newEvent.endY,$scope.newEvent.endM,$scope.newEvent.endD)
      };

      $log.debug('tempEventObject:');
      $log.debug(tempEventObject);

      $scope.events.push(tempEventObject);

      $log.debug('Events Array:');
      $log.debug($scope.events);

      $log.debug('Schedule:');
      $log.debug($scope.schedule);

      var index = $scope.events.length-1;
      $scope.schedule.eventToAdd = $scope.events[index];

      $log.debug('Event to Add:');
      $log.debug($scope.schedule.eventToAdd);

      Schedules.Event.put({scheduleId: schedule._id}).$promise.then(function(data) {
        $log.debug('Data from Sucessful Added Event:');
        $log.debug(data);
        $scope.schedule = data;
      });
    };

      $scope.removeEvent = function(index){
      var schedule = $scope.schedule;
      var eventToRemove = schedule.events[index];
      Schedules.Event.delete({scheduleId: schedule._id}).$promise.then(function(data) {
        // $log.debug(data);
        $scope.schedule = data;
      });
    };

      $scope.getEvents = function(){
      var schedule = $scope.schedule;
      Schedules.Event.query({scheduleId: schedule._id}).$promise.then(function(data) {
        // $log.debug(data);
        $scope.schedule = data;
      });
    };

		 var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();

    /* event source that contains custom events on the scope */
    $scope.events = [
      {title: 'All Day Event',start: new Date(y, m, 1)},
      {title: 'Long Event',start: new Date(y, m, d - 5),end: new Date(y, m, d - 2)},
      {id: 999,title: 'Repeating Event',start: new Date(y, m, d - 3, 16, 0),allDay: false},
      {id: 999,title: 'Repeating Event',start: new Date(y, m, d + 4, 16, 0),allDay: false},
      {title: 'Birthday Party',start: new Date(y, m, d + 1, 19, 0),end: new Date(y, m, d + 1, 22, 30),allDay: false},
      {title: 'Click for Google',start: new Date(y, m, 28),end: new Date(y, m, 29),url: 'http://google.com/'}
    ];
    /* event source that calls a function on every view switch */
    $scope.eventsF = function (start, end, callback) {
      var s = new Date(start).getTime() / 1000;
      var e = new Date(end).getTime() / 1000;
      var m = new Date(start).getMonth();
      var events = [{title: 'Feed Me ' + m,start: s + (50000),end: s + (100000),allDay: false, className: ['customFeed']}];
      callback(events);
    };

    $scope.calEventsExt = {
       color: '#f00',
       textColor: 'yellow',
       events: [
          {type:'party',title: 'Lunch',start: new Date(y, m, d, 12, 0),end: new Date(y, m, d, 14, 0),allDay: false},
          {type:'party',title: 'Lunch 2',start: new Date(y, m, d, 12, 0),end: new Date(y, m, d, 14, 0),allDay: false},
          {type:'party',title: 'Click for Google',start: new Date(y, m, 28),end: new Date(y, m, 29),url: 'http://google.com/'}
        ]
    };
    /* alert on eventClick */
    $scope.alertOnEventClick = function( event, allDay, jsEvent, view ){
        $scope.alertMessage = (event.title + ' was clicked ');
		  console.log(event.title);
    };
    /* alert on Drop */
     $scope.alertOnDrop = function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view){
       $scope.alertMessage = ('Event Droped to make dayDelta ' + dayDelta);
    };
    /* alert on Resize */
    $scope.alertOnResize = function(event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view ){
       $scope.alertMessage = ('Event Resized to make dayDelta ' + minuteDelta);
    };
    /* add and removes an event source of choice */
    $scope.addRemoveEventSource = function(sources,source) {
      var canAdd = 0;
      angular.forEach(sources,function(value, key){
        if(sources[key] === source){
          sources.splice(key,1);
          canAdd = 1;
        }
      });
      if(canAdd === 0){
        sources.push(source);
      }
    };
    /* add custom event*/
    $scope.addEvent = function() {
      $scope.events.push({
        title: 'Open Sesame',
        start: new Date(y, m, 28),
        end: new Date(y, m, 29),
        className: ['openSesame']
      });
    };
    /* remove event */
    $scope.remove = function(index) {
      $scope.events.splice(index,1);
    };
    /* Change View */
    $scope.changeView = function(view,calendar) {
      calendar.fullCalendar('changeView',view);
    };
    /* Change View */
    $scope.renderCalender = function(calendar) {
      calendar.fullCalendar('render');
    };
    /* config object */
    $scope.uiConfig = {
      calendar:{
        height: 450,
        editable: true,
        header:{
          left: 'title',
          center: '',
          right: 'today prev,next'
        },
        eventClick: $scope.alertOnEventClick,
        eventDrop: $scope.alertOnDrop,
        eventResize: $scope.alertOnResize
      }
    };
    /* event sources array*/
    $scope.eventSources = [$scope.events];

	}
]);<|endoftext|>


<commit_before>var meta = <><![CDATA[
// ==UserScript==
// @name           豆瓣电台dbscrobbler
// @namespace      http://whosemind.net
// @description    记录 douban.fm 到last.fm
// @include        http://douban.fm/
// @include        http://douban.fm/?*
// @require        https://github.com/justan/gmscrobber/raw/master/simple_scrobbler_user.js
// @version        0.1.1
// @changelog      新增过滤广告功能
// @uso:script     98833
// ==/UserScript==
]]></>.toString();

meta = uso.metaParse(meta);
uso.check(meta.version, meta.uso.script);

(function(){
var douban = function(){
	var ready = function(){
		var ex = unsafeWindow.extStatusHandler,
			cmds = {start:"start", end:"e", next:"s", like: "r", unlike: "u"};

		if(!sc.sk){
			return;
		}
		unsafeWindow.extStatusHandler = function(o){
			var song, album;
			log(o);
			o = JSON.parse(o);
			song = o.song;

			song.album = song.albumtitle;
			song.duration = song.len || 180;

			setTimeout(function(){
				if(song.ssid == null || song.subtype == "T"){
					log("广告, 略过...");
					return;
				}else if(/\.{3}$/.test(song.album)){
					log("一个省略的专辑名...");
					if(o.type == cmds.start){
						song.album = "";
						getAlbum(song.aid, function(at){
							sc.song.album = at;
							log("新的专辑名是: " + at);
						});
					}
				}
				switch(o.type){
				case cmds.start:
					sc.nowPlaying(song);
					sc.getInfo(song, function(p){
						log(JSON.stringify(p));
						if(song.like != p.islove){
							if(song.like){
								log("love " + song.title + "in last.fm");
								sc.love();
							}else{
								log("love " + song.title + "in douban.fm");
								o.type = cmds.like;
								ex(JSON.stringify(o));
								o.type = cmds.start;
							}
						}
						document.getElementById("radioplayer").parentNode.title = "在last.fm中记录 " + p.len + " 次";
					});
					break;
				case cmds.end:
					sc.scrobble();
					break;
				case cmds.like:
					sc.love();
					break;
				case cmds.unlike:
					sc.unlove();
					break;
				default:
					break;
				}

			}, 0);

			return ex.apply(this, arguments);
			//ex(o);
		};
	},
	sc = new Scrobbler({name: "豆瓣电台", type: 1, ready: ready}),
	getAlbum = function(id, cb){
		var url = "http://api.douban.com/music/subject/" + id + "?alt=json";
		xhr({
			method: "GET",
			url: url,
			onload: function(d){
				cb(JSON.parse(d.responseText)["title"]["$t"]);
			},
			onerror: function(e){
				log("专辑信息获取失败.. \n" + JSON.stringify(e));
			}
		});
	};
};

unsafeWindow.Do('douban', 'counter', 'coverflow', function() {
	setTimeout(function(){
		unsafeWindow.extStatusHandler ? douban() : log("init error");
	}, 0);
});
})();<commit_msg>修复多歌手记录问题<commit_after>var meta = <><![CDATA[
// ==UserScript==
// @name           豆瓣电台dbscrobbler
// @namespace      http://whosemind.net
// @description    记录 douban.fm 到last.fm
// @include        http://douban.fm/
// @include        http://douban.fm/?*
// @require        https://github.com/justan/gmscrobber/raw/master/simple_scrobbler_user.js
// @version        0.1.2
// @changelog      修复多歌手记录问题
// @uso:script     98833
// ==/UserScript==
]]></>.toString();

meta = uso.metaParse(meta);
uso.check(meta.version, meta.uso.script);

(function(){
var douban = function(){
	var ready = function(){
		var ex = unsafeWindow.extStatusHandler,
			cmds = {start:"start", end:"e", next:"s", like: "r", unlike: "u"};

		if(!sc.sk){
			return;
		}
		unsafeWindow.extStatusHandler = function(o){
			var song, album;
			log(o);
			o = JSON.parse(o);
			song = o.song;

			song.album = song.albumtitle;
			song.duration = song.len || 180;//如果没有时间，就3分钟吧

			setTimeout(function(){
				if(song.ssid == null || song.subtype == "T"){
					log("广告, 略过...");
					return;
				}
				switch(o.type){
				case cmds.start:
					if(/\.{3}$/.test(song.album)){
						if(o.type == cmds.start){
							song.album = "";
							getAlbum(song.aid, function(at){
								sc.song.album = at;
								log("一个省略的专辑名...新的专辑名是: " + at);
							});
						}
					}
					song.artist = song.artist.replace(/\s+\/\s+.+$/,"");//多个歌手，就保留第一个
					sc.nowPlaying(song);
					sc.getInfo(song, function(p){
						log(JSON.stringify(p));
						if(song.like != p.islove){
							if(song.like){
								log("love " + song.title + "in last.fm");
								sc.love();
							}else{
								log("love " + song.title + "in douban.fm");
								o.type = cmds.like;
								ex(JSON.stringify(o));
								o.type = cmds.start;
							}
						}
						document.getElementById("radioplayer").parentNode.title = "在last.fm中记录 " + p.len + " 次";
					});
					break;
				case cmds.end:
					sc.scrobble();
					break;
				case cmds.like:
					sc.love();
					break;
				case cmds.unlike:
					sc.unlove();
					break;
				default:
					break;
				}

			}, 0);

			return ex.apply(this, arguments);
			//ex(o);
		};
	},
	sc = new Scrobbler({name: "豆瓣电台", type: 1, ready: ready}),
	getAlbum = function(id, cb){
		var url = "http://api.douban.com/music/subject/" + id + "?alt=json";
		xhr({
			method: "GET",
			url: url,
			onload: function(d){
				cb(JSON.parse(d.responseText)["title"]["$t"]);
			},
			onerror: function(e){
				log("专辑信息获取失败.. \n" + JSON.stringify(e));
			}
		});
	};
};

unsafeWindow.Do('douban', 'counter', 'coverflow', function() {
	setTimeout(function(){
		unsafeWindow.extStatusHandler ? douban() : log("init error");
	}, 0);
});
})();
<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const helpers = require('./helpers');

const createDeal = (req, res) => {
  const attributes = {
    ethereumId: req.body.ethereumId,
    lenderId : req.body.lenderId,
    borrowerId : req.body.borrowerId,
    status : req.body.status,
    txIds : req.body.txId
  };

  helpers.createDeal(attributes, (err, deal) => {
    if (err) {
      console.error(err);
      return res.status(err.status || 500).json(err);
    }
    res.status(201).json(deal);
  });
};

const deleteDeal = (req, res) => {

  const where = {
    _id: req.params.id
  };

  helpers.deleteDeal(where, (err, deal) => {
    if (err) {
      console.error(err);
      return res.status(err.status || 500).json(err);
    }
    res.status(200).json(deal);
  });
};

const getAllDeals = (req, res) => {

  const query = req.query;
  const where = {};
  let limit = 10;

  // get all deals where user is either lender or borrower
  if (query.hasOwnProperty('ethAccount') && _.isString(query.ethAccount)) { // find all deals a person is part of
    let condition = {};
    let dealsUserIsPartOf = null;
    let ethAccount = null;

    ethAccount = query.ethAccount;

    condition = {
      lenderId: ethAccount
    };

    helpers.searchDeals(limit, condition, (err, dealsWhereUserIsLender) => {
      if (err) {
        console.error(err);
        return res.status(err.status || 500).json(err);
      }

      condition = {
        borrowerId: ethAccount
      };

      helpers.searchDeals(limit, condition, (err, dealsWhereUserIsBorrower) => {
        if (err) {
          console.error(err);
          return res.status(err.status || 500).json(err);
        }
        dealsUserIsPartOf = dealsWhereUserIsLender.concat(dealsWhereUserIsBorrower);

        return res.status(200).json(dealsUserIsPartOf);
      });
    });
  };

  // filter based on params
  if (query.hasOwnProperty('borrowerId') && _.isString(query.borrowerId)) {
    where.borrowerId = query.borrowerId;
  };
  if (query.hasOwnProperty('ethereumId') && _.isString(query.ethereumId)) {
    where.ethereumId = query.ethereumId;
  };
  if (query.hasOwnProperty('lenderId') && _.isString(query.lenderId)) {
    where.lenderId = query.lenderId;
  };
  if (query.hasOwnProperty('limit') && _.isInteger(query.limit)) {
    limit = query.limit;
  };

  helpers.searchDeals(limit, where, (err, deals) => {
    if (err) {
      console.error(err);
      return res.status(err.status || 500).json(err);
    }
    res.status(200).json(deals);
  });
};

const getDealById = (req, res) => {
  const where = {
    _id: req.params.id
  };

  helpers.findDeal(where, (err, deal) => {
    if (err) {
      console.error(err);
      return res.status(err.status || 500).json(err);
    }
    res.status(200).json(deal);
  });
};

const updateDeal = (req, res) => {
  const where = {
    _id: req.params.id
  };

  const attributes = {
    status : req.body.status,
    txIds: req.body.txId
  };

  helpers.updateDeal(where, attributes, (err, deal) => {
    if (err) {
      console.error(err);
      return res.status(err.status || 500).json(err);
    }
    res.status(202).json(deal);
  });
};

module.exports = {
  createDeal,
  deleteDeal,
  getAllDeals,
  getDealById,
  updateDeal
};
<commit_msg>Added Else statement to fix bug<commit_after>'use strict';

const _ = require('lodash');
const helpers = require('./helpers');

const createDeal = (req, res) => {
  const attributes = {
    ethereumId: req.body.ethereumId,
    lenderId : req.body.lenderId,
    borrowerId : req.body.borrowerId,
    status : req.body.status,
    txIds : req.body.txId
  };

  helpers.createDeal(attributes, (err, deal) => {
    if (err) {
      console.error(err);
      return res.status(err.status || 500).json(err);
    }
    res.status(201).json(deal);
  });
};

const deleteDeal = (req, res) => {

  const where = {
    _id: req.params.id
  };

  helpers.deleteDeal(where, (err, deal) => {
    if (err) {
      console.error(err);
      return res.status(err.status || 500).json(err);
    }
    res.status(200).json(deal);
  });
};

const getAllDeals = (req, res) => {

  const query = req.query;
  const where = {};
  let limit = 10;

  // get all deals where user is either lender or borrower
  if (query.hasOwnProperty('ethAccount') && _.isString(query.ethAccount)) { // find all deals a person is part of
    let condition = {};
    let dealsUserIsPartOf = null;
    let ethAccount = null;

    ethAccount = query.ethAccount;

    condition = {
      lenderId: ethAccount
    };

    helpers.searchDeals(limit, condition, (err, dealsWhereUserIsLender) => {
      if (err) {
        console.error(err);
        return res.status(err.status || 500).json(err);
      }

      condition = {
        borrowerId: ethAccount
      };

      helpers.searchDeals(limit, condition, (err, dealsWhereUserIsBorrower) => {
        if (err) {
          console.error(err);
          return res.status(err.status || 500).json(err);
        }
        dealsUserIsPartOf = dealsWhereUserIsLender.concat(dealsWhereUserIsBorrower);

        return res.status(200).json(dealsUserIsPartOf);
      });
    });
  } else {
    // filter based on params
    if (query.hasOwnProperty('borrowerId') && _.isString(query.borrowerId)) {
      where.borrowerId = query.borrowerId;
    };
    if (query.hasOwnProperty('ethereumId') && _.isString(query.ethereumId)) {
      where.ethereumId = query.ethereumId;
    };
    if (query.hasOwnProperty('lenderId') && _.isString(query.lenderId)) {
      where.lenderId = query.lenderId;
    };
    if (query.hasOwnProperty('limit') && _.isInteger(query.limit)) {
      limit = query.limit;
    };

    helpers.searchDeals(limit, where, (err, deals) => {
      if (err) {
        console.error(err);
        return res.status(err.status || 500).json(err);
      }
      res.status(200).json(deals);
    });
  };
};

const getDealById = (req, res) => {
  const where = {
    _id: req.params.id
  };

  helpers.findDeal(where, (err, deal) => {
    if (err) {
      console.error(err);
      return res.status(err.status || 500).json(err);
    }
    res.status(200).json(deal);
  });
};

const updateDeal = (req, res) => {
  const where = {
    _id: req.params.id
  };

  const attributes = {
    status : req.body.status,
    txIds: req.body.txId
  };

  helpers.updateDeal(where, attributes, (err, deal) => {
    if (err) {
      console.error(err);
      return res.status(err.status || 500).json(err);
    }
    res.status(202).json(deal);
  });
};

module.exports = {
  createDeal,
  deleteDeal,
  getAllDeals,
  getDealById,
  updateDeal
};
<|endoftext|>


<commit_before>/**
 * Interface to the User model.
 */

// Support output of objects
var util = require('util');

/**
 * Constructor to the UserImportSummary object.
 *
 * @param model
 *   The model of the userImportSummary document.
 */
function UserImportSummary(model) {
  this.docModel = model;
}

/**
 * Converts a timestamp in seconds to a Date object.
 *
 * @param timestamp
 *   Timestamp in seconds.
 */
var convertToDate = function(timestamp) {
  return new Date(timestamp * 1000);
};

/**
 * Create a log document from the supplied values
 *
 * @param req
 *  The request object in a POST callback.
 * @param res
 *  The response object in a POST callback.
 */
UserImportSummary.prototype.post = function(req, res) {
  this.request = req;
  this.response = res;
  var addArgs = {};

  if (this.request.body.logging_timestamp !== undefined) {
    // Convert timestamp string to Date object
    var timestamp = parseInt(this.request.body.logging_timestamp);
    addArgs.logged_date = convertToDate(timestamp);
  }
  if (this.request.body.target_CSV_file !== undefined) {
    addArgs.target_CSV_file = this.request.body.target_CSV_file;
  }
  if (this.request.body.signup_count !== undefined) {
    addArgs.signup_count = this.request.body.signup_count;
  }
  if (this.request.body.skipped !== undefined) {
    addArgs.skipped = this.request.body.skipped;
  }
  if (this.request.query.source !== undefined) {
    addArgs.source = this.request.query.source;
  }
  if (this.request.query.type !== undefined) {
    addArgs.log_type = this.request.query.type;
  }

  var logEntry = new this.docModel(addArgs);
  logEntry.save(function(err) {
    if (err) {
      res.status(500).json(err);
      console.log("500 Error: POST to  /v1/imports/summaries. err response: " + util.inspect(err, false, null));
      return;
    }
    // Added log entry to db
    res.status(201).json("OK");
  });
};

/**
 * Retrieve summary log documents. Example request:
 * /api/v1/imports/summary/2014-09-01/2014-10-01?type=user&exists=1&source=niche.com
 *
 * @param req
 *   The request object in the GET callback.
 * @param res
 *   The response object in the GET callback.
 */
UserImportSummary.prototype.get = function(req, res) {

  if (req.params.start_processed_date === undefined) {
    var targetStartDate = new Date('2014-08-01');
  }
  else {
    var targetStartDate = new Date(req.params.start_processed_date);
  }
  if (req.params.end_processed_date === undefined) {
    var targetEndDate = new Date();
  }
  else {
    var targetEndDate = new Date(req.params.start_processed_date);
  }

  var data = {
    request: req,
    response: res
  };
  this.docModel.find( {
    $and : [
      { 'logged_date' : {$gte : targetStartDate, $lte : targetEndDate} },
      { 'source' : req.query.source }
    ]},
    function (err, docs) {
      if (err) {
        data.response.send(500, err);
        return;
      }

      if (docs.length == 0) {
        res.status(404).json('OK - No match found for source ' + req.query.source + ' logged_date: gte: ' + targetStartDate + ' lte ' + targetEndDate);
      }
      else {
        res.status(200).json(docs);
      }

  }).sort({ target_CSV_file : -1 })
};

/**
 * Delete existing user import summary log documents.
 *
 * @param req
 *   The request object in the DELETE callback.
 * @param res
 *   The response object in the DELETE callback.
 */
UserImportSummary.prototype.delete = function(req, res) {

  this.request = req;
  this.response = res;
  var deleteArgs = {};

  deleteArgs.source = this.request.query.source;

  if (this.request.query.origin !== undefined) {
    deleteArgs.target_CSV_file = this.request.query.origin;
  }

  this.docModel.remove(deleteArgs,
    function(err, num) {

      if (err) {
        console.log('ERROR delete: ' + err);
        res.status(500).json(err);
        return;
      }

      if (num == 0) {
        var message = 'OK - No documents found to delete for target_CSV_file: ' + targetOrigin;
        res.status(404).json(message);
      }
      else {
        var message = 'OK - Deleted ' + num + ' document(s) for origin: ' + targetOrigin;
        res.status(200).json(message);
      }
    }
  );
};

module.exports = UserImportSummary;
<commit_msg>Fixed scope issue with error message variable<commit_after>/**
 * Interface to the User model.
 */

// Support output of objects
var util = require('util');

/**
 * Constructor to the UserImportSummary object.
 *
 * @param model
 *   The model of the userImportSummary document.
 */
function UserImportSummary(model) {
  this.docModel = model;
}

/**
 * Converts a timestamp in seconds to a Date object.
 *
 * @param timestamp
 *   Timestamp in seconds.
 */
var convertToDate = function(timestamp) {
  return new Date(timestamp * 1000);
};

/**
 * Create a log document from the supplied values
 *
 * @param req
 *  The request object in a POST callback.
 * @param res
 *  The response object in a POST callback.
 */
UserImportSummary.prototype.post = function(req, res) {
  this.request = req;
  this.response = res;
  var addArgs = {};

  if (this.request.body.logging_timestamp !== undefined) {
    // Convert timestamp string to Date object
    var timestamp = parseInt(this.request.body.logging_timestamp);
    addArgs.logged_date = convertToDate(timestamp);
  }
  if (this.request.body.target_CSV_file !== undefined) {
    addArgs.target_CSV_file = this.request.body.target_CSV_file;
  }
  if (this.request.body.signup_count !== undefined) {
    addArgs.signup_count = this.request.body.signup_count;
  }
  if (this.request.body.skipped !== undefined) {
    addArgs.skipped = this.request.body.skipped;
  }
  if (this.request.query.source !== undefined) {
    addArgs.source = this.request.query.source;
  }
  if (this.request.query.type !== undefined) {
    addArgs.log_type = this.request.query.type;
  }

  var logEntry = new this.docModel(addArgs);
  logEntry.save(function(err) {
    if (err) {
      res.status(500).json(err);
      console.log("500 Error: POST to  /v1/imports/summaries. err response: " + util.inspect(err, false, null));
      return;
    }
    // Added log entry to db
    res.status(201).json("OK");
  });
};

/**
 * Retrieve summary log documents. Example request:
 * /api/v1/imports/summary/2014-09-01/2014-10-01?type=user&exists=1&source=niche.com
 *
 * @param req
 *   The request object in the GET callback.
 * @param res
 *   The response object in the GET callback.
 */
UserImportSummary.prototype.get = function(req, res) {

  if (req.params.start_processed_date === undefined) {
    var targetStartDate = new Date('2014-08-01');
  }
  else {
    var targetStartDate = new Date(req.params.start_processed_date);
  }
  if (req.params.end_processed_date === undefined) {
    var targetEndDate = new Date();
  }
  else {
    var targetEndDate = new Date(req.params.start_processed_date);
  }

  var data = {
    request: req,
    response: res
  };
  this.docModel.find( {
    $and : [
      { 'logged_date' : {$gte : targetStartDate, $lte : targetEndDate} },
      { 'source' : req.query.source }
    ]},
    function (err, docs) {
      if (err) {
        data.response.send(500, err);
        return;
      }

      if (docs.length == 0) {
        res.status(404).json('OK - No match found for source ' + req.query.source + ' logged_date: gte: ' + targetStartDate + ' lte ' + targetEndDate);
      }
      else {
        res.status(200).json(docs);
      }

  }).sort({ target_CSV_file : -1 })
};

/**
 * Delete existing user import summary log documents.
 *
 * @param req
 *   The request object in the DELETE callback.
 * @param res
 *   The response object in the DELETE callback.
 */
UserImportSummary.prototype.delete = function(req, res) {

  this.request = req;
  this.response = res;
  var targetOrigin = this.request.query.origin;
  var deleteArgs = {};

  deleteArgs.source = this.request.query.source;

  if (targetOrigin !== undefined) {
    deleteArgs.target_CSV_file = targetOrigin;
  }

  this.docModel.remove(deleteArgs,
    function(err, num) {

      if (err) {
        console.log('ERROR delete: ' + err);
        res.status(500).json(err);
        return;
      }

      if (num == 0) {
        var message = 'OK - No documents found to delete for target_CSV_file: ' + targetOrigin;
        res.status(404).json(message);
      }
      else {
        var message = 'OK - Deleted ' + num + ' document(s) for origin: ' + targetOrigin;
        res.status(200).json(message);
      }
    }
  );
};

module.exports = UserImportSummary;
<|endoftext|>