<commit_before>/*global au:true $:true codes:true UIATarget:true UIA_DEVICE_ORIENTATION_UNKNOWN: true UIA_DEVICE_ORIENTATION_FACEUP:true UIA_DEVICE_ORIENTATION_FACEDOWN:true UIA_DEVICE_ORIENTATION_PORTRAIT:true UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN:true UIA_DEVICE_ORIENTATION_LANDSCAPELEFT:true UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT:true UIA_DEVICE_ORIENTATION_LANDSCAPELEFT:true UIA_DEVICE_ORIENTATION_PORTRAIT:true */
"use strict";
var au;

if (typeof au === "undefined") {
  au = {};
}

$.extend(au, {
  cache: []
  , identifier: 0
  , target: UIATarget.localTarget()
  , mainWindow: UIATarget.localTarget().frontMostApp().mainWindow()
  , mainApp: UIATarget.localTarget().frontMostApp()
  , keyboard: UIATarget.localTarget().frontMostApp().keyboard()

  // Screen orientation functions

  , getScreenOrientation: function () {
      var orientation = $.orientation()
        , value = null;
      switch (orientation) {
        case UIA_DEVICE_ORIENTATION_UNKNOWN ||
             UIA_DEVICE_ORIENTATION_FACEUP ||
             UIA_DEVICE_ORIENTATION_FACEDOWN:
            value = "UNKNOWN"; break;
        case UIA_DEVICE_ORIENTATION_PORTRAIT ||
             UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN:
            value = "PORTRAIT"; break;
        case UIA_DEVICE_ORIENTATION_LANDSCAPELEFT ||
             UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT:
            value = "LANDSCAPE"; break;
      }
      if (value !== null) {
        return {
          status: codes.Success.code,
          value: value
        };
      } else {
        return {
          status: codes.UnknownError.code,
          value: 'Unsupported Orientation: ' + orientation
        };
      }
    }

  , setScreenOrientation: function(orientation) {
      if (orientation === "LANDSCAPE") {
        $.orientation(UIA_DEVICE_ORIENTATION_LANDSCAPELEFT);
      } else if (orientation === "PORTRAIT") {
        $.orientation(UIA_DEVICE_ORIENTATION_PORTRAIT);
      } else {
        return {
          status: codes.UnknownError.code,
          value: 'Unsupported orientation: ' + orientation
        };
      }
      var newOrientation = au.getScreenOrientation();
      if (newOrientation == orientation) {
        return {
          status: codes.Success.code
          , value: newOrientation
        };
      } else {
        console.log("returning error");
        return {
          status: codes.UnknownError.code
          , value: "Orientation change did not take effect"
        };
      }
    }

  // Element lookup functions

  , lookup: function(selector, ctx) {
      if (typeof selector === 'string') {
        var _ctx = this.web ? this.web : this.mainWindow;

        if (typeof ctx === 'string') {
          _ctx = this.cache[ctx];
        } else if (typeof ctx !== 'undefined') {
          _ctx = ctx;
        }

        this.target.pushTimeout(0);
        var elems = $(selector, _ctx);
        this.target.popTimeout();

        return elems;
      }

      return null;
    }

  , getElement: function(name) {
      if (typeof this.cache[name] !== 'undefined') {
        return this.cache[name];
      }

      return null;
    }

  , getId: function(el) {
      var id = (this.identifier++).toString();
      if (el.name() !== null) {
        console.log('Lookup returned ' + el + ' with the name "' + el.name() + '" (id: ' + id + ').');
      }
      this.cache[id] = el;
      return id;
    }

  , getElementByName: function(name) {
      var selector = ['#', name].join('');
      var elems = this.lookup(selector);

      if (elems.length > 0) {
        var el = elems[0];
        var elid = this.getId(el);

        return {
          status: codes.Success.code,
          value: {'ELEMENT': elid }
        };
      } else {
        return {
          status: codes.NoSuchElement.code,
          value: codes.NoSuchElement.summary
        };
      }
    }

  , getElementsByType: function(type, ctx) {
      var selector = type;

      // some legacy: be backwards compatible, mechanic.js
      switch (type) {
        case 'tableView':
        case 'textField':
          selector = type.toLowerCase();
          break;
        case 'staticText':
          selector = 'text';
          break;
        case 'tableCell':
          selector = 'cell';
      }

      var elems = [];

      if (typeof ctx !== 'undefined') {
        elems = this.lookup(selector, ctx);
      } else {
        elems = this.lookup(selector);
      }

      var results = []
        , me = this;

      elems.each(function(e, el) {
        var elid = me.getId(el);
        results.push({ 'ELEMENT': elid });
      });

      return {
        status: codes.Success.code,
        value: results
      };
    }

  , getElementByType: function(type, ctx) {
      var results = [];

      if (typeof ctx !== 'undefined') {
        results = this.getElementsByType(type, ctx);
      } else {
        results = this.getElementsByType(type);
      }

      if (results.value.length < 1) {
        return {
          status: codes.NoSuchElement.code,
          value: null
        };
      } else {
        return {
          status: codes.Success.code,
          value: results.value[0]
        };
      }
    }

  , getActiveElement: function() {
      return $(this.mainWindow).getActiveElement();
    }

  // Gesture functions

  , complexTap: function(opts) {
      return this.mainApp.tapWithOptions(opts);
    }

 // Gesture emulation functions (i.e., making Selenium work)

    // does a flick in the middle of the screen of size 1/4 of screen
    // using the direction corresponding to xSpeed/ySpeed
  , touchFlickFromSpeed: function(xSpeed, ySpeed) {
      // get x, y of vector that provides the direction given by xSpeed/ySpeed and
      // has length .25
      var mult = Math.sqrt((0.25 * 0.25) / (xSpeed * xSpeed + ySpeed * ySpeed));
      var x = mult * xSpeed;
      var y = mult * ySpeed;

      // translate to flick in the middle of the screen
      var options = {
        startOffset : {
          x : 0.5 - 0.5 * x,
          y : 0.5 - 0.5 * y
        },
        endOffset : {
          x : 0.5 + 0.5 * x,
          y : 0.5 + 0.5 * y
        }
      };

      this.mainWindow.flickInsideWithOptions(options);
      return {
        status: codes.Success.code,
        value: null
      };
    }

    // similar to flick but does a longer movement in the direction of the swipe
    // does a swipe in the middle of the screen of size 1/2 of screen
    // using the direction corresponding to xSpeed/ySpeed
  , touchSwipeFromSpeed: function(xSpeed, ySpeed) {
      // get x, y of vector that provides the direction given by xSpeed/ySpeed and
      // has length .50
      var mult = Math.sqrt((0.5 * 0.5) / (xSpeed * xSpeed + ySpeed * ySpeed));
      var x = mult * xSpeed;
      var y = mult * ySpeed;

      // translate to swipe in the middle of the screen
      var options = {
        startOffset : {
          x : 0.5 - 0.25 * x,
          y : 0.5 - 0.25 * y
        },
        endOffset : {
          x : 0.5 + 0.75 * x,
          y : 0.5 + 0.75 * y
        },
        duration : 0.2
      };

      this.mainWindow.dragInsideWithOptions(options);
      return {
        status: codes.Success.code,
        value: null
      };
    }

  // Keyboard functions

  , sendKeysToActiveElement: function(keys) {
      if (this.hasSpecialKeys(keys)) {
        return this.sendKeysToActiveElementSpecial(keys);
      } else {
        this.keyboard.typeString(keys);
      }
      return {
        status: codes.Success.code,
        value: null
      };
    }

  , hasSpecialKeys: function(keys) {
      var numChars = keys.length;
      for (var i = 0; i < numChars; i++)
        if (this.isSpecialKey(keys.charAt(i)))
          return true;
      return false;
    }

  , sendKeysToActiveElementSpecial: function(keys) {
      var numChars = keys.length;
      for (var i = 0; i < numChars; i++)
        this.typeKey(keys.charAt(i));
      return {
        status: codes.Success.code,
        value: null
      };
    }

    // handles some of the special keys in org.openqa.selenium.Keys
  , isSpecialKey: function(k) {
      if (k === '\uE003') // DELETE
        return true;
      else if (k === '\uE006' || k === '\uE007') // RETURN ENTER
        return true;
      return false;
    }

 , typeKey: function(k) {
    if (k === '\uE003') { // DELETE
      this.keyboard.keys().Delete.tap();
    } else if (k === '\uE006' || k === '\uE007') {// RETURN ENTER
      this.keyboard.buttons().Go.tap();
    } else {
      this.keyboard.typeString(String(k)); // regular key
    }
  }

  // Alert-related functions

  , getAlertText: function() {
      return {
        status: codes.Success.code,
        value: this.mainApp.alert().name()
      };
    }

  , acceptAlert: function() {
      this.mainApp.alert().defaultButton().tap();
      return {
        status: codes.Success.code,
        value: null
      };
    }

  , dismissAlert: function() {
      this.mainApp.alert().cancelButton().tap();
      return {
        status: codes.Success.code,
        value: null
      };
    }
});
<commit_msg>keyboard is a dynamic thing, need to re-get every time<commit_after>/*global au:true $:true codes:true UIATarget:true UIA_DEVICE_ORIENTATION_UNKNOWN: true UIA_DEVICE_ORIENTATION_FACEUP:true UIA_DEVICE_ORIENTATION_FACEDOWN:true UIA_DEVICE_ORIENTATION_PORTRAIT:true UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN:true UIA_DEVICE_ORIENTATION_LANDSCAPELEFT:true UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT:true UIA_DEVICE_ORIENTATION_LANDSCAPELEFT:true UIA_DEVICE_ORIENTATION_PORTRAIT:true */
"use strict";
var au;

if (typeof au === "undefined") {
  au = {};
}

$.extend(au, {
  cache: []
  , identifier: 0
  , target: UIATarget.localTarget()
  , mainWindow: UIATarget.localTarget().frontMostApp().mainWindow()
  , mainApp: UIATarget.localTarget().frontMostApp()
  , keyboard: function() { return UIATarget.localTarget().frontMostApp().keyboard(); }

  // Screen orientation functions

  , getScreenOrientation: function () {
      var orientation = $.orientation()
        , value = null;
      switch (orientation) {
        case UIA_DEVICE_ORIENTATION_UNKNOWN ||
             UIA_DEVICE_ORIENTATION_FACEUP ||
             UIA_DEVICE_ORIENTATION_FACEDOWN:
            value = "UNKNOWN"; break;
        case UIA_DEVICE_ORIENTATION_PORTRAIT ||
             UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN:
            value = "PORTRAIT"; break;
        case UIA_DEVICE_ORIENTATION_LANDSCAPELEFT ||
             UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT:
            value = "LANDSCAPE"; break;
      }
      if (value !== null) {
        return {
          status: codes.Success.code,
          value: value
        };
      } else {
        return {
          status: codes.UnknownError.code,
          value: 'Unsupported Orientation: ' + orientation
        };
      }
    }

  , setScreenOrientation: function(orientation) {
      if (orientation === "LANDSCAPE") {
        $.orientation(UIA_DEVICE_ORIENTATION_LANDSCAPELEFT);
      } else if (orientation === "PORTRAIT") {
        $.orientation(UIA_DEVICE_ORIENTATION_PORTRAIT);
      } else {
        return {
          status: codes.UnknownError.code,
          value: 'Unsupported orientation: ' + orientation
        };
      }
      var newOrientation = au.getScreenOrientation();
      if (newOrientation == orientation) {
        return {
          status: codes.Success.code
          , value: newOrientation
        };
      } else {
        console.log("returning error");
        return {
          status: codes.UnknownError.code
          , value: "Orientation change did not take effect"
        };
      }
    }

  // Element lookup functions

  , lookup: function(selector, ctx) {
      if (typeof selector === 'string') {
        var _ctx = this.web ? this.web : this.mainWindow;

        if (typeof ctx === 'string') {
          _ctx = this.cache[ctx];
        } else if (typeof ctx !== 'undefined') {
          _ctx = ctx;
        }

        this.target.pushTimeout(0);
        var elems = $(selector, _ctx);
        this.target.popTimeout();

        return elems;
      }

      return null;
    }

  , getElement: function(name) {
      if (typeof this.cache[name] !== 'undefined') {
        return this.cache[name];
      }

      return null;
    }

  , getId: function(el) {
      var id = (this.identifier++).toString();
      if (el.name() !== null) {
        console.log('Lookup returned ' + el + ' with the name "' + el.name() + '" (id: ' + id + ').');
      }
      this.cache[id] = el;
      return id;
    }

  , getElementByName: function(name) {
      var selector = ['#', name].join('');
      var elems = this.lookup(selector);

      if (elems.length > 0) {
        var el = elems[0];
        var elid = this.getId(el);

        return {
          status: codes.Success.code,
          value: {'ELEMENT': elid }
        };
      } else {
        return {
          status: codes.NoSuchElement.code,
          value: codes.NoSuchElement.summary
        };
      }
    }

  , getElementsByType: function(type, ctx) {
      var selector = type;

      // some legacy: be backwards compatible, mechanic.js
      switch (type) {
        case 'tableView':
        case 'textField':
          selector = type.toLowerCase();
          break;
        case 'staticText':
          selector = 'text';
          break;
        case 'tableCell':
          selector = 'cell';
      }

      var elems = [];

      if (typeof ctx !== 'undefined') {
        elems = this.lookup(selector, ctx);
      } else {
        elems = this.lookup(selector);
      }

      var results = []
        , me = this;

      elems.each(function(e, el) {
        var elid = me.getId(el);
        results.push({ 'ELEMENT': elid });
      });

      return {
        status: codes.Success.code,
        value: results
      };
    }

  , getElementByType: function(type, ctx) {
      var results = [];

      if (typeof ctx !== 'undefined') {
        results = this.getElementsByType(type, ctx);
      } else {
        results = this.getElementsByType(type);
      }

      if (results.value.length < 1) {
        return {
          status: codes.NoSuchElement.code,
          value: null
        };
      } else {
        return {
          status: codes.Success.code,
          value: results.value[0]
        };
      }
    }

  , getActiveElement: function() {
      return $(this.mainWindow).getActiveElement();
    }

  // Gesture functions

  , complexTap: function(opts) {
      return this.mainApp.tapWithOptions(opts);
    }

 // Gesture emulation functions (i.e., making Selenium work)

    // does a flick in the middle of the screen of size 1/4 of screen
    // using the direction corresponding to xSpeed/ySpeed
  , touchFlickFromSpeed: function(xSpeed, ySpeed) {
      // get x, y of vector that provides the direction given by xSpeed/ySpeed and
      // has length .25
      var mult = Math.sqrt((0.25 * 0.25) / (xSpeed * xSpeed + ySpeed * ySpeed));
      var x = mult * xSpeed;
      var y = mult * ySpeed;

      // translate to flick in the middle of the screen
      var options = {
        startOffset : {
          x : 0.5 - 0.5 * x,
          y : 0.5 - 0.5 * y
        },
        endOffset : {
          x : 0.5 + 0.5 * x,
          y : 0.5 + 0.5 * y
        }
      };

      this.mainWindow.flickInsideWithOptions(options);
      return {
        status: codes.Success.code,
        value: null
      };
    }

    // similar to flick but does a longer movement in the direction of the swipe
    // does a swipe in the middle of the screen of size 1/2 of screen
    // using the direction corresponding to xSpeed/ySpeed
  , touchSwipeFromSpeed: function(xSpeed, ySpeed) {
      // get x, y of vector that provides the direction given by xSpeed/ySpeed and
      // has length .50
      var mult = Math.sqrt((0.5 * 0.5) / (xSpeed * xSpeed + ySpeed * ySpeed));
      var x = mult * xSpeed;
      var y = mult * ySpeed;

      // translate to swipe in the middle of the screen
      var options = {
        startOffset : {
          x : 0.5 - 0.25 * x,
          y : 0.5 - 0.25 * y
        },
        endOffset : {
          x : 0.5 + 0.75 * x,
          y : 0.5 + 0.75 * y
        },
        duration : 0.2
      };

      this.mainWindow.dragInsideWithOptions(options);
      return {
        status: codes.Success.code,
        value: null
      };
    }

  // Keyboard functions

  , sendKeysToActiveElement: function(keys) {
      if (this.hasSpecialKeys(keys)) {
        return this.sendKeysToActiveElementSpecial(keys);
      } else {
        this.keyboard().typeString(keys);
      }
      return {
        status: codes.Success.code,
        value: null
      };
    }

  , hasSpecialKeys: function(keys) {
      var numChars = keys.length;
      for (var i = 0; i < numChars; i++)
        if (this.isSpecialKey(keys.charAt(i)))
          return true;
      return false;
    }

  , sendKeysToActiveElementSpecial: function(keys) {
      var numChars = keys.length;
      for (var i = 0; i < numChars; i++)
        this.typeKey(keys.charAt(i));
      return {
        status: codes.Success.code,
        value: null
      };
    }

    // handles some of the special keys in org.openqa.selenium.Keys
  , isSpecialKey: function(k) {
      if (k === '\uE003') // DELETE
        return true;
      else if (k === '\uE006' || k === '\uE007') // RETURN ENTER
        return true;
      return false;
    }

 , typeKey: function(k) {
    if (k === '\uE003') { // DELETE
      this.keyboard().keys().Delete.tap();
    } else if (k === '\uE006' || k === '\uE007') {// RETURN ENTER
      this.keyboard().buttons().Go.tap();
    } else {
      this.keyboard().typeString(String(k)); // regular key
    }
  }

  // Alert-related functions

  , getAlertText: function() {
      return {
        status: codes.Success.code,
        value: this.mainApp.alert().name()
      };
    }

  , acceptAlert: function() {
      this.mainApp.alert().defaultButton().tap();
      return {
        status: codes.Success.code,
        value: null
      };
    }

  , dismissAlert: function() {
      this.mainApp.alert().cancelButton().tap();
      return {
        status: codes.Success.code,
        value: null
      };
    }
});
<|endoftext|>


<commit_before>import {
  GraphQLBoolean,
  GraphQLEnumType,
  GraphQLFloat,
  GraphQLInt,
  GraphQLList,
  GraphQLObjectType,
  GraphQLString,
} from 'graphql';

import models from '../models';
import status from '../constants/response_status';

export const ResponseStatusType = new GraphQLEnumType({
  name: 'Responses',
  values: {
    PENDING: { value: status.PENDING },
    INTERESTED: { value: status.INTERESTED },
    YES: { value: status.YES },
  }
});

export const UserType = new GraphQLObjectType({
  name: 'User',
  description: 'This represents a User',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve(user) {
          return user.id;
        }
      },
      firstName: {
        type: GraphQLString,
        resolve(user) {
          return user.firstName;
        }
      },
      lastName: {
        type: GraphQLString,
        resolve(user) {
          return user.lastName;
        }
      },
      name: {
        type: GraphQLString,
        resolve(user) {
          return user.name;
        }
      },
      avatar: {
        type: GraphQLString,
        resolve(user) {
          return user.avatar;
        }
      },
      username: {
        type: GraphQLString,
        resolve(user) {
          return user.username;
        }
      },
      email: {
        type: GraphQLString,
        resolve(user) {
          return user.email;
        }
      },
      description: {
        type: GraphQLString,
        resolve(user) {
          return user.description
        }
      },
      isOrganization: {
        type: GraphQLBoolean,
        resolve(user) {
          return user.isOrganization;
        }
      },
      twitterHandle: {
        type: GraphQLString,
        resolve(user) {
          return user.twitterHandle;
        }
      },
      billingAddress: {
        type: GraphQLString,
        resolve(user) {
          return user.billingAddress;
        }
      },
      website: {
        type: GraphQLString,
        resolve(user) {
          return user.website;
        }
      },
      paypalEmail: {
        type: GraphQLString,
        resolve(user) {
          return user.paypalEmail;
        }
      }
    }
  }
});

export const CollectiveType = new GraphQLObjectType({
  name: 'Collective',
  description: 'This represents a Collective',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve(collective) {
          return collective.id;
        }
      },
      name: {
        type: GraphQLString,
        resolve(collective) {
          return collective.name;
        }
      },
      description: {
        type: GraphQLString,
        resolve(collective) {
          return collective.description;
        }
      },
      longDescription: {
        type: GraphQLString,
        resolve(collective) {
          return collective.longDescription;
        }
      },
      mission: {
        type: GraphQLString,
        resolve(collective) {
          return collective.mission;
        }
      },
      currency: {
        type: GraphQLString,
        resolve(collective) {
          return collective.currency;
        }
      },
      logo: {
        type: GraphQLString,
        resolve(collective) {
          return collective.logo;
        }
      },
      backgroundImage: {
        type: GraphQLString,
        resolve(collective) {
          return collective.backgroundImage;
        }
      },
      slug: {
        type: GraphQLString,
        resolve(collective) {
          return collective.slug;
        }
      },
      events: {
        type: new GraphQLList(EventType),
        resolve(collective) {
          return collective.getEvents();
        }
      },
      stripePublishableKey: {
        type: GraphQLString,
        resolve(collective) {
          return collective.getStripeAccount()
          .then(stripeAccount => stripeAccount && stripeAccount.stripePublishablekey)
        }
      }
    }
  }
});

export const EventType = new GraphQLObjectType({
  name: 'Event',
  description: 'This represents an Event',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve(event) {
          return event.id;
        }
      },
      name: {
        type: GraphQLString,
        resolve(event) {
          return event.name
        }
      },
      description: {
        type: GraphQLString,
        resolve(event) {
          return event.description
        }
      },
      backgroundImage: {
        type: GraphQLString,
        resolve(event) {
          return event.backgroundImage;
        }
      },
      createdByUser: {
        type: UserType,
        resolve(event) {
          return models.User.findById(event.createdByUserId)
        }
      },
      collective: {
        type: CollectiveType,
        resolve(event) {
          return event.getGroup();
        }
      },
      slug: {
        type: GraphQLString,
        resolve(event) {
          return event.slug;
        }
      },
      location: {
        type: GraphQLString,
        description: 'Name of the location. Ex: Puck Fair restaurant',
        resolve(event) {
          return event.locationName;
        }
      },
      address: {
        type: GraphQLString,
        description: 'Ex: 525 Broadway, NY 10012',
        resolve(event) {
          return event.address;
        }
      },
      lat: {
        type: GraphQLFloat,
        resolve(event) {
          return event.geoLocationLatLong ? event.geoLocationLatLong.coordinates[0] : null;
        }
      },
      long: {
        type: GraphQLFloat,
        resolve(event) {
          return event.geoLocationLatLong ? event.geoLocationLatLong.coordinates[1] : null;
        }
      },
      startsAt: {
        type: GraphQLString,
        resolve(event) {
          return event.startsAt
        }
      },
      endsAt: {
        type: GraphQLString,
        resolve(event) {
          return event.startsAt
        }
      },
      maxAmount: {
        type: GraphQLInt,
        resolve(event) {
          return event.maxAmount;
        }
      },
      currency: {
        type: GraphQLString,
        resolve(event) {
          return event.currency;
        }
      },
      maxQuantity: {
        type: GraphQLInt,
        resolve(event) {
          return event.maxQuantity;
        }
      },
      tiers: {
        type: new GraphQLList(TierType),
        resolve(event) {
          return event.getTiers();
        }
      },
      responses: {
        type: new GraphQLList(ResponseType),
        resolve(event) {
          return event.getResponses({
            where: {
              confirmedAt: { $ne: null }
            }
          });
        }
      }

    }
  }
});

export const TierType = new GraphQLObjectType({
  name: 'Tier',
  description: 'This represents an Tier',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve(tier) {
          return tier.id;
        }
      },
      name: {
        type: GraphQLString,
        resolve(tier) {
          return tier.name
        }
      },
      description: {
        type: GraphQLString,
        resolve(tier) {
          return tier.description
        }
      },
      amount: {
        type: GraphQLInt,
        resolve(tier) {
          return tier.amount;
        }
      },
      currency: {
        type: GraphQLString,
        resolve(tier) {
          return tier.currency;
        }
      },
      maxQuantity: {
        type: GraphQLInt,
        resolve(tier) {
          return tier.maxQuantity;
        }
      },
      availableQuantity: {
        type: GraphQLInt,
        resolve(tier) {
          return tier.availableQuantity()
          // graphql doesn't like infinity value
          .then(availableQuantity => availableQuantity === Infinity ? 10000000 : availableQuantity);
        }
      },
      password: {
        type: GraphQLString,
        resolve(tier) {
          return tier.password
        }
      },
      startsAt: {
        type: GraphQLString,
        resolve(tier) {
          return tier.startsAt
        }
      },
      endsAt: {
        type: GraphQLString,
        resolve(tier) {
          return tier.startsAt
        }
      },
      event: {
        type: EventType,
        resolve(tier) {
          return tier.getEvent();
        }
      },
      responses: {
        type: new GraphQLList(ResponseType),
        resolve(tier) {
          return tier.getResponses({
            where: {
              confirmedAt: { $ne: null }
            }
          });
        }
      }
    }
  }
});

export const ResponseType = new GraphQLObjectType({
  name: 'Response',
  description: 'This is a Response',
  fields: () => {
    return {
       id: {
        type: GraphQLInt,
        resolve(response) {
          return response.id;
        }
      },
      quantity: {
        type: GraphQLInt,
        resolve(response) {
          return response.quantity;
        }
      },
      user: {
        type: UserType,
        resolve(response) {
          return response.getUser();
        }
      },
      description: {
        type: GraphQLString,
        resolve(response) {
          return response.description;
        }
      },
      collective: {
        type: CollectiveType,
        resolve(response) {
          return response.getGroup();
        }
      },
      tier: {
        type: TierType,
        resolve(response) {
          return response.getTier();
        }
      },
      event: {
        type: EventType,
        resolve(response) {
          return response.getEvent();
        }
      },
      confirmedAt: {
        type: GraphQLString,
        resolve(response) {
          return response.confirmedAt;
        }
      },
      status: {
        type: ResponseStatusType,
        resolve(response) {
          return response.status;
        }
      }
    }
  }
});

<commit_msg>fix for returning stripePublishableKey<commit_after>import {
  GraphQLBoolean,
  GraphQLEnumType,
  GraphQLFloat,
  GraphQLInt,
  GraphQLList,
  GraphQLObjectType,
  GraphQLString,
} from 'graphql';

import models from '../models';
import status from '../constants/response_status';

export const ResponseStatusType = new GraphQLEnumType({
  name: 'Responses',
  values: {
    PENDING: { value: status.PENDING },
    INTERESTED: { value: status.INTERESTED },
    YES: { value: status.YES },
  }
});

export const UserType = new GraphQLObjectType({
  name: 'User',
  description: 'This represents a User',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve(user) {
          return user.id;
        }
      },
      firstName: {
        type: GraphQLString,
        resolve(user) {
          return user.firstName;
        }
      },
      lastName: {
        type: GraphQLString,
        resolve(user) {
          return user.lastName;
        }
      },
      name: {
        type: GraphQLString,
        resolve(user) {
          return user.name;
        }
      },
      avatar: {
        type: GraphQLString,
        resolve(user) {
          return user.avatar;
        }
      },
      username: {
        type: GraphQLString,
        resolve(user) {
          return user.username;
        }
      },
      email: {
        type: GraphQLString,
        resolve(user) {
          return user.email;
        }
      },
      description: {
        type: GraphQLString,
        resolve(user) {
          return user.description
        }
      },
      isOrganization: {
        type: GraphQLBoolean,
        resolve(user) {
          return user.isOrganization;
        }
      },
      twitterHandle: {
        type: GraphQLString,
        resolve(user) {
          return user.twitterHandle;
        }
      },
      billingAddress: {
        type: GraphQLString,
        resolve(user) {
          return user.billingAddress;
        }
      },
      website: {
        type: GraphQLString,
        resolve(user) {
          return user.website;
        }
      },
      paypalEmail: {
        type: GraphQLString,
        resolve(user) {
          return user.paypalEmail;
        }
      }
    }
  }
});

export const CollectiveType = new GraphQLObjectType({
  name: 'Collective',
  description: 'This represents a Collective',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve(collective) {
          return collective.id;
        }
      },
      name: {
        type: GraphQLString,
        resolve(collective) {
          return collective.name;
        }
      },
      description: {
        type: GraphQLString,
        resolve(collective) {
          return collective.description;
        }
      },
      longDescription: {
        type: GraphQLString,
        resolve(collective) {
          return collective.longDescription;
        }
      },
      mission: {
        type: GraphQLString,
        resolve(collective) {
          return collective.mission;
        }
      },
      currency: {
        type: GraphQLString,
        resolve(collective) {
          return collective.currency;
        }
      },
      logo: {
        type: GraphQLString,
        resolve(collective) {
          return collective.logo;
        }
      },
      backgroundImage: {
        type: GraphQLString,
        resolve(collective) {
          return collective.backgroundImage;
        }
      },
      slug: {
        type: GraphQLString,
        resolve(collective) {
          return collective.slug;
        }
      },
      events: {
        type: new GraphQLList(EventType),
        resolve(collective) {
          return collective.getEvents();
        }
      },
      stripePublishableKey: {
        type: GraphQLString,
        resolve(collective) {
          return collective.getStripeAccount()
          .then(stripeAccount => stripeAccount && stripeAccount.stripePublishableKey)
        }
      }
    }
  }
});

export const EventType = new GraphQLObjectType({
  name: 'Event',
  description: 'This represents an Event',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve(event) {
          return event.id;
        }
      },
      name: {
        type: GraphQLString,
        resolve(event) {
          return event.name
        }
      },
      description: {
        type: GraphQLString,
        resolve(event) {
          return event.description
        }
      },
      backgroundImage: {
        type: GraphQLString,
        resolve(event) {
          return event.backgroundImage;
        }
      },
      createdByUser: {
        type: UserType,
        resolve(event) {
          return models.User.findById(event.createdByUserId)
        }
      },
      collective: {
        type: CollectiveType,
        resolve(event) {
          return event.getGroup();
        }
      },
      slug: {
        type: GraphQLString,
        resolve(event) {
          return event.slug;
        }
      },
      location: {
        type: GraphQLString,
        description: 'Name of the location. Ex: Puck Fair restaurant',
        resolve(event) {
          return event.locationName;
        }
      },
      address: {
        type: GraphQLString,
        description: 'Ex: 525 Broadway, NY 10012',
        resolve(event) {
          return event.address;
        }
      },
      lat: {
        type: GraphQLFloat,
        resolve(event) {
          return event.geoLocationLatLong ? event.geoLocationLatLong.coordinates[0] : null;
        }
      },
      long: {
        type: GraphQLFloat,
        resolve(event) {
          return event.geoLocationLatLong ? event.geoLocationLatLong.coordinates[1] : null;
        }
      },
      startsAt: {
        type: GraphQLString,
        resolve(event) {
          return event.startsAt
        }
      },
      endsAt: {
        type: GraphQLString,
        resolve(event) {
          return event.startsAt
        }
      },
      maxAmount: {
        type: GraphQLInt,
        resolve(event) {
          return event.maxAmount;
        }
      },
      currency: {
        type: GraphQLString,
        resolve(event) {
          return event.currency;
        }
      },
      maxQuantity: {
        type: GraphQLInt,
        resolve(event) {
          return event.maxQuantity;
        }
      },
      tiers: {
        type: new GraphQLList(TierType),
        resolve(event) {
          return event.getTiers();
        }
      },
      responses: {
        type: new GraphQLList(ResponseType),
        resolve(event) {
          return event.getResponses({
            where: {
              confirmedAt: { $ne: null }
            }
          });
        }
      }

    }
  }
});

export const TierType = new GraphQLObjectType({
  name: 'Tier',
  description: 'This represents an Tier',
  fields: () => {
    return {
      id: {
        type: GraphQLInt,
        resolve(tier) {
          return tier.id;
        }
      },
      name: {
        type: GraphQLString,
        resolve(tier) {
          return tier.name
        }
      },
      description: {
        type: GraphQLString,
        resolve(tier) {
          return tier.description
        }
      },
      amount: {
        type: GraphQLInt,
        resolve(tier) {
          return tier.amount;
        }
      },
      currency: {
        type: GraphQLString,
        resolve(tier) {
          return tier.currency;
        }
      },
      maxQuantity: {
        type: GraphQLInt,
        resolve(tier) {
          return tier.maxQuantity;
        }
      },
      availableQuantity: {
        type: GraphQLInt,
        resolve(tier) {
          return tier.availableQuantity()
          // graphql doesn't like infinity value
          .then(availableQuantity => availableQuantity === Infinity ? 10000000 : availableQuantity);
        }
      },
      password: {
        type: GraphQLString,
        resolve(tier) {
          return tier.password
        }
      },
      startsAt: {
        type: GraphQLString,
        resolve(tier) {
          return tier.startsAt
        }
      },
      endsAt: {
        type: GraphQLString,
        resolve(tier) {
          return tier.startsAt
        }
      },
      event: {
        type: EventType,
        resolve(tier) {
          return tier.getEvent();
        }
      },
      responses: {
        type: new GraphQLList(ResponseType),
        resolve(tier) {
          return tier.getResponses({
            where: {
              confirmedAt: { $ne: null }
            }
          });
        }
      }
    }
  }
});

export const ResponseType = new GraphQLObjectType({
  name: 'Response',
  description: 'This is a Response',
  fields: () => {
    return {
       id: {
        type: GraphQLInt,
        resolve(response) {
          return response.id;
        }
      },
      quantity: {
        type: GraphQLInt,
        resolve(response) {
          return response.quantity;
        }
      },
      user: {
        type: UserType,
        resolve(response) {
          return response.getUser();
        }
      },
      description: {
        type: GraphQLString,
        resolve(response) {
          return response.description;
        }
      },
      collective: {
        type: CollectiveType,
        resolve(response) {
          return response.getGroup();
        }
      },
      tier: {
        type: TierType,
        resolve(response) {
          return response.getTier();
        }
      },
      event: {
        type: EventType,
        resolve(response) {
          return response.getEvent();
        }
      },
      confirmedAt: {
        type: GraphQLString,
        resolve(response) {
          return response.confirmedAt;
        }
      },
      status: {
        type: ResponseStatusType,
        resolve(response) {
          return response.status;
        }
      }
    }
  }
});

<|endoftext|>


<commit_before>var toString = Object.prototype.toString;
var dateTag = "[object Date]";
var regExpTag = "[object RegExp]";
var setTag = "[object Set]";
var mapTag = "[object Map]";

var arson = require("./index.js");

arson.registerType("Buffer", {
  deconstruct: function (buf) {
    return Buffer.isBuffer(buf) && [buf.toString("base64"), "base64"];
  },

  // The reconstruct function will be called twice: once with no
  // arguments, which allows it to return a placeholder object reference;
  // and once with one argument, a copy of the array returned by the
  // deconstruct function. For immutable types like Buffer, Date, and
  // RegExp, the reconstruct function should return a falsy value when it
  // receives no arguments, since there is no way to create an empty
  // Buffer or Date and later fill in its contents.  For container types
  // like Map and Set, the reconstruct function must return an empty
  // instance of the container when it receives no arguments, so that we
  // can fill in that empty container later. This two-phased strategy is
  // essential for decoding containers that contain themselves.
  reconstruct: function (args) {
    return args && new Buffer(args[0], args[1]);
  }
});

arson.registerType("Date", {
  deconstruct: function (date) {
    return toString.call(date) === dateTag && [date.toJSON()];
  },

  reconstruct: function (args) {
    return args && new Date(args[0]);
  }
});

arson.registerType("RegExp", {
  deconstruct: function (exp) {
    if (toString.call(exp) === regExpTag) {
      var args = [exp.source];
      var flags = "";

      if (exp.ignoreCase) flags += "i";
      if (exp.multiline) flags += "m";
      if (exp.global) flags += "g";

      if (flags) {
        args.push(flags);
      }

      return args;
    }
  },

  reconstruct: function (args) {
    return args && new RegExp(args[0], args[1]);
  }
});

typeof Set === "function" &&
typeof Array.from === "function" &&
arson.registerType("Set", {
  deconstruct: function (set) {
    if (toString.call(set) === setTag) {
      return Array.from(set);
    }
  },

  reconstruct: function (values) {
    if (values) {
      values.forEach(this.add, this);
    } else {
      return new Set;
    }
  }
});

typeof Map === "function" &&
typeof Array.from === "function" &&
arson.registerType("Map", {
  deconstruct: function (map) {
    if (toString.call(map) === mapTag) {
      return Array.from(map);
    }
  },

  reconstruct: function (entries) {
    if (entries) {
      entries.forEach(function (entry) {
        this.set(entry[0], entry[1]);
      }, this);
    } else {
      return new Map;
    }
  }
});
<commit_msg>Only arson.registerType("Buffer", ...) when Buffer defined.<commit_after>var toString = Object.prototype.toString;
var dateTag = "[object Date]";
var regExpTag = "[object RegExp]";
var setTag = "[object Set]";
var mapTag = "[object Map]";

var arson = require("./index.js");

typeof Buffer === "function" &&
typeof Buffer.isBuffer === "function" &&
arson.registerType("Buffer", {
  deconstruct: function (buf) {
    return Buffer.isBuffer(buf) && [buf.toString("base64"), "base64"];
  },

  // The reconstruct function will be called twice: once with no
  // arguments, which allows it to return a placeholder object reference;
  // and once with one argument, a copy of the array returned by the
  // deconstruct function. For immutable types like Buffer, Date, and
  // RegExp, the reconstruct function should return a falsy value when it
  // receives no arguments, since there is no way to create an empty
  // Buffer or Date and later fill in its contents.  For container types
  // like Map and Set, the reconstruct function must return an empty
  // instance of the container when it receives no arguments, so that we
  // can fill in that empty container later. This two-phased strategy is
  // essential for decoding containers that contain themselves.
  reconstruct: function (args) {
    return args && new Buffer(args[0], args[1]);
  }
});

arson.registerType("Date", {
  deconstruct: function (date) {
    return toString.call(date) === dateTag && [date.toJSON()];
  },

  reconstruct: function (args) {
    return args && new Date(args[0]);
  }
});

arson.registerType("RegExp", {
  deconstruct: function (exp) {
    if (toString.call(exp) === regExpTag) {
      var args = [exp.source];
      var flags = "";

      if (exp.ignoreCase) flags += "i";
      if (exp.multiline) flags += "m";
      if (exp.global) flags += "g";

      if (flags) {
        args.push(flags);
      }

      return args;
    }
  },

  reconstruct: function (args) {
    return args && new RegExp(args[0], args[1]);
  }
});

typeof Set === "function" &&
typeof Array.from === "function" &&
arson.registerType("Set", {
  deconstruct: function (set) {
    if (toString.call(set) === setTag) {
      return Array.from(set);
    }
  },

  reconstruct: function (values) {
    if (values) {
      values.forEach(this.add, this);
    } else {
      return new Set;
    }
  }
});

typeof Map === "function" &&
typeof Array.from === "function" &&
arson.registerType("Map", {
  deconstruct: function (map) {
    if (toString.call(map) === mapTag) {
      return Array.from(map);
    }
  },

  reconstruct: function (entries) {
    if (entries) {
      entries.forEach(function (entry) {
        this.set(entry[0], entry[1]);
      }, this);
    } else {
      return new Map;
    }
  }
});
<|endoftext|>


<commit_before>!(function () {
    /* =================================================================== */

    function UUID() {
        var uuid = localStorage.getItem('__jsinspector_uuid__');
        if (uuid) return uuid;
        else {
            uuid = UUID.generate();
            localStorage.setItem('__jsinspector_uuid__', uuid);
            return uuid;
        }
    }

    UUID.generate = function () {
        return 'xxxx-yxxyx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        }).toUpperCase();
    }

    function createScript () {
        var script = '',
            $scriptContainer = document.querySelector('#script'),
            code = script.replace('{{host}}', window.location.origin)
                        .replace('{{inspectId}}', UUID())
                        .replace(/</g, '<')
                        .replace(/>/g, '>')
                        .replace(/"/g, '"')
                        .replace(/\s+([a-zA-Z\-]+?)\="/g, '  $1="')
                        .replace(/="(.+?)"/g, '="$1"')
                        .replace(/<([a-zA-Z]+?)\s/g, '<$1 ')
                        .replace(/\/([a-zA-Z]+?)>/g, '/$1>')
                        .replace(/</g, '<')
                        .replace(/>/g, '>')
                         // inspector highligt
                        .replace(/\?([a-zA-Z0-9]+)\-([a-zA-Z0-9]+)/g, '?$1-$2')

        $scriptContainer.innerHTML = code;
    }

    createScript();

    var $devtoolsButton = document.querySelector('#devtoolsButton');
    function updateDevtoolsLink () {
        $devtoolsButton.href = window.location.origin + '/devtools?' + UUID();
    }

    document.querySelector('#createButton').onclick = function () {
        localStorage.removeItem('__jsinspector_uuid__')
        createScript();
        updateDevtoolsLink();
    }

})();
<commit_msg>init update devtools link<commit_after>!(function () {
    /* =================================================================== */

    function UUID() {
        var uuid = localStorage.getItem('__jsinspector_uuid__');
        if (uuid) return uuid;
        else {
            uuid = UUID.generate();
            localStorage.setItem('__jsinspector_uuid__', uuid);
            return uuid;
        }
    }

    UUID.generate = function () {
        return 'xxxx-yxxyx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        }).toUpperCase();
    }

    function createScript () {
        var script = '',
            $scriptContainer = document.querySelector('#script'),
            code = script.replace('{{host}}', window.location.origin)
                        .replace('{{inspectId}}', UUID())
                        .replace(/</g, '<')
                        .replace(/>/g, '>')
                        .replace(/"/g, '"')
                        .replace(/\s+([a-zA-Z\-]+?)\="/g, '  $1="')
                        .replace(/="(.+?)"/g, '="$1"')
                        .replace(/<([a-zA-Z]+?)\s/g, '<$1 ')
                        .replace(/\/([a-zA-Z]+?)>/g, '/$1>')
                        .replace(/</g, '<')
                        .replace(/>/g, '>')
                         // inspector highligt
                        .replace(/\?([a-zA-Z0-9]+)\-([a-zA-Z0-9]+)/g, '?$1-$2')

        $scriptContainer.innerHTML = code;
    }

    createScript();

    function updateDevtoolsLink () {
        var $devtoolsButton = document.querySelector('#devtoolsButton');
        $devtoolsButton.href = window.location.origin + '/devtools?' + UUID();
    }

    document.querySelector('#createButton').onclick = function () {
        localStorage.removeItem('__jsinspector_uuid__')
        createScript();
        updateDevtoolsLink();
    }
    // initialize update
    updateDevtoolsLink();

})();
<|endoftext|>


<commit_before>var datepicker = $('#date').pickadate({
        container: '#outlet', onSet: function(item) {
            if ( 'select' in item ) setTimeout( timepicker.open, 0 )
        }

    }).pickadate('picker');

var timepicker = $('#time').pickatime({
        container: '#outlet',
        // onRender: function() {
        //     $('<button>back to date</button>').
        //         on('click', function() {
        //             timepicker.close()
        //             datepicker.open()
        //         }).prependTo( this.$root.find('.picker__box') )
        // },
        onSet: function(item) {
            if ( 'select' in item ) setTimeout( function() {
                $datetime.
                    off('focus').
                    val( datepicker.get() + ' @ ' + timepicker.get() ).
                    focus().
                    on('focus', datepicker.open)
            }, 0 )
        }
    }).pickatime('picker');

var $datetime = $('#datetime').
    on('focus', datepicker.open).
    on('click', function(event) { event.stopPropagation(); datepicker.open() });

// $('.datetime').pickadate({
//     // Escape any “rule” characters with an exclamation mark (!).
//     format: 'dddd, dd mmm, yyyy',
//     formatSubmit: 'yyyy/mm/dd',
//     hiddenPrefix: 'prefix__',
//     hiddenSuffix: '__suffix'
// // });

// $('.date').pickadate({
//     min: true,
//     max: false
// })<commit_msg>when page, times are fixed again haha<commit_after>
var datepicker = $('#date').pickadate({
        container: '#outlet', onSet: function(item) {
            if ( 'select' in item ) setTimeout( timepicker.open, 0 )
        }

    }).pickadate('picker');

var timepicker = $('#time').pickatime({
        container: '#outlet',
        onOpen: function() {
            var selectedDate = datepicker.get('select', 'yyyy/m/d');
            console.log(selectedDate);
            var splitDate = selectedDate.split("/");
            console.log(splitDate);
            var current = new Date();
            var currentYear = current.getFullYear();
            var currentMonth = current.getMonth() + 1;
            var currentDate = current.getDate();
            if (currentYear.toString() == splitDate[0] && currentMonth.toString() == splitDate[1]
                && currentDate.toString() == splitDate[2]) {
                console.log("user chose today");
           timepicker.set({min:true, max:false});} else {
            timepicker.set({min:false, max:false, view: [current.getHours().toString(), current.getMinutes().toString()]});}
        },
        onSet: function(item) {
            if ( 'select' in item ) setTimeout( function() {
                $datetime.
                    off('focus').
                    val( datepicker.get() + ' @ ' + timepicker.get() ).
                    focus().
                    on('focus', datepicker.open)
            }, 0 )
        }
    }).pickatime('picker');

var $datetime = $('#datetime').
    on('focus', datepicker.open).
    on('click', function(event) { event.stopPropagation(); datepicker.open() });
<|endoftext|>


<commit_before>var canvas = new fabric.Canvas('draughts-canvas');
canvas.setBackgroundColor("#ffffff");
//TODO manage all properties in proper files +REFACTOR
var board;
var Color = net.brehaut.Color;
var hoverAnimationTime = 100;
var colorAnimationTime = 300;
var manAnimationTime = 700;

var socketURL = document.location.origin;

//TODO will 'window.requestAnimationFrame(draw)' ever be needed? +RETHINK
//TODO make clear where's the entire application's entry point +STD_FEATURE
var websocket = new Websocket(socketURL);

function initializeGame(status, tiles) {
  if (status === "OK") {
    board = new Board(tiles);
    $(".game-not-found-tr").hide();
    $(".game-tr").show();
  } else {
    $(".game-tr").hide();
    $(".game-not-found-tr").show();
  }
}

function showModalUsername() {
  $('#joinGameModal').modal('show');
}

function showModal() {
  $('#waitingForOtherPlayerModal').modal('show');
}

//TODO rename methods, @object +REFACTOR
$("#joinGameButton").click(function() {
  websocket.connect($("#usernameInput").val());
  $('#joinGameModal').modal('hide');
  showModal();
});
// setTimeout(showPlayerJoinedOnModal, 2000);

function showPlayerJoinedOnModal(username, color) {
  var fadeTime = 500;
  var msgTime = 2500;

  $("#opponentUsername").html(username);
  $("#yourColor").html(color).addClass("color-" + color);

  $('#modalWait').fadeOut(fadeTime, function() {
    $('#modalEnjoy').fadeIn(fadeTime, function() {
      setTimeout(function() {
        $('#waitingForOtherPlayerModal').modal('hide');
      }, msgTime);
    });
  });
}

//TODO don't show when game doesn't exist +STD_FEATURE
$(document).ready(function() {
  $("#usernameInput").keypress(function(e) {
    if (e.which == 13) {
      e.preventDefault();
      websocket.connect($("#usernameInput").val());
      $('#joinGameModal').modal('hide');
      showModal();
    }
  });
  var waitTillMsgTime = 0;
  setTimeout(showModalUsername, waitTillMsgTime);
});

//TODO DRY +REFACTOR
canvas.on('mouse:over', function(e) {
  if (e.target.obj.onMouseOver) {
    e.target.obj.onMouseOver();
    canvas.renderAll();
  }
});

canvas.on('mouse:out', function(e) {
  if (e.target.obj.onMouseOut) {
    e.target.obj.onMouseOut();
    canvas.renderAll();
  }
});

canvas.on('mouse:down', function(e) {
  if (e.target.obj.onMouseDown) {
    e.target.obj.onMouseDown();
    canvas.renderAll();
  }
});

canvas.on('mouse:up', function(e) {
  if (e.target.obj.select) {
    e.target.obj.select();
    canvas.renderAll();
  }
});
<commit_msg>Apply focus on username input at start<commit_after>var canvas = new fabric.Canvas('draughts-canvas');
canvas.setBackgroundColor("#ffffff");
//TODO manage all properties in proper files +REFACTOR
var board;
var Color = net.brehaut.Color;
var hoverAnimationTime = 100;
var colorAnimationTime = 300;
var manAnimationTime = 700;

var socketURL = document.location.origin;

//TODO will 'window.requestAnimationFrame(draw)' ever be needed? +RETHINK
//TODO make clear where's the entire application's entry point +STD_FEATURE
var websocket = new Websocket(socketURL);

function initializeGame(status, tiles) {
  if (status === "OK") {
    board = new Board(tiles);
    $(".game-not-found-tr").hide();
    $(".game-tr").show();
  } else {
    $(".game-tr").hide();
    $(".game-not-found-tr").show();
  }
}

function showModalUsername() {
  $('#joinGameModal').modal('show');
  setTimeout(function() {
    $("#usernameInput").focus();
  }, 500);
}

function showModal() {
  $('#waitingForOtherPlayerModal').modal('show');
}

//TODO rename methods, \@object +REFACTOR
$("#joinGameButton").click(function() {
  websocket.connect($("#usernameInput").val());
  $('#joinGameModal').modal('hide');
  showModal();
});
// setTimeout(showPlayerJoinedOnModal, 2000);

function showPlayerJoinedOnModal(username, color) {
  var fadeTime = 500;
  var msgTime = 2500;

  $("#opponentUsername").html(username);
  $("#yourColor").html(color).addClass("color-" + color);

  $('#modalWait').fadeOut(fadeTime, function() {
    $('#modalEnjoy').fadeIn(fadeTime, function() {
      setTimeout(function() {
        $('#waitingForOtherPlayerModal').modal('hide');
      }, msgTime);
    });
  });
}

//TODO don't show when game doesn't exist +STD_FEATURE
$(document).ready(function() {
  $("#usernameInput").keypress(function(e) {
    if (e.which == 13) {
      e.preventDefault();
      websocket.connect($("#usernameInput").val());
      $('#joinGameModal').modal('hide');
      showModal();
    }
  });
  var waitTillMsgTime = 0;
  setTimeout(showModalUsername, waitTillMsgTime);
});

//TODO DRY +REFACTOR
canvas.on('mouse:over', function(e) {
  if (e.target.obj.onMouseOver) {
    e.target.obj.onMouseOver();
    canvas.renderAll();
  }
});

canvas.on('mouse:out', function(e) {
  if (e.target.obj.onMouseOut) {
    e.target.obj.onMouseOut();
    canvas.renderAll();
  }
});

canvas.on('mouse:down', function(e) {
  if (e.target.obj.onMouseDown) {
    e.target.obj.onMouseDown();
    canvas.renderAll();
  }
});

canvas.on('mouse:up', function(e) {
  if (e.target.obj.select) {
    e.target.obj.select();
    canvas.renderAll();
  }
});
<|endoftext|>


<commit_before>window.overview = {};

var tomorrow = window.utils.formatDate_api(moment().add(1, "days").toDate())

$(document).ready(function() {
	$("#overview").on("tabOpened", function() {
		$(".overview-date").text(window.utils.formatDate_english(new Date()));
		window.api.get('overview/announcements/get/', function(data) {
			$("#announcementList").text("");
			var response = data.feedback.reverse();
			for (var feed in response) {
				if (moment(response[feed].time).add(response[feed].days, "days").isAfter(moment())) {
					var $feedLi = $("

");
						$feedLi.append(response[feed].msg);
					$("#announcementList").append($feedLi);
				}
			}
			if ($("#announcementList").children().size() > 0) {
				$("#announcementAlert").css("display", "block");
			} else {
				$("#announcementAlert").css("display", "none");
			}
		});
		HWphrase(tomorrow, window.api.get("HWphrase",'/planner/events/getDay/' + day, function(result) {console.log(result.events.length)}));
	});
});

function getHwPerDay(){
	var date = window.utils.formatDate_api(moment().add(1, day).toDate();
	var hwPerDay = [];
	for (i = 0; i < 10; i++) {
		date1 = date + i;
		window.api.get('/overview/events/getDay/', {date: date1}, function(res) {
			alert(res);
			hwPerDay.push(res);
		});
		alert(hwPerDay);
	}
}

function HWphrase(date, hw)
	if(hw < 1){
		document.getElementById(id).innerHTML = ' Looks like tonight will be an easy night! You have no homework due tomorrow!';
	} else if (hw < 3) {
		document.getElementById(id).innerHTML = ' It seems like you will have some free time tonight! You have ' + hw + ' assignments due tomorrow.';
	} else if (hw < 5)
		document.getElementById(id).innerHTML = ' Tonight might be rough. You have ' + hw + ' assignments due tomorrow.';
	} else {
		document.getElementById(id).innerHTML = ' You might be up late doing homework tonight. You have ' + hw + ' assignments due tomorrow.';
	}
}

function hello(){
	alert("Hi!");
}
<commit_msg>fixex<commit_after>window.overview = {};

var tomorrow = window.utils.formatDate_api(moment().add(1, "days").toDate())

$(document).ready(function() {
	$("#overview").on("tabOpened", function() {
		$(".overview-date").text(window.utils.formatDate_english(new Date()));
		window.api.get('overview/announcements/get/', function(data) {
			$("#announcementList").text("");
			var response = data.feedback.reverse();
			for (var feed in response) {
				if (moment(response[feed].time).add(response[feed].days, "days").isAfter(moment())) {
					var $feedLi = $("

");
						$feedLi.append(response[feed].msg);
					$("#announcementList").append($feedLi);
				}
			}
			if ($("#announcementList").children().size() > 0) {
				$("#announcementAlert").css("display", "block");
			} else {
				$("#announcementAlert").css("display", "none");
			}
		});
		window.api.get("HWphrase",'/planner/events/getDay/' + day, function(result) {
			HWphrase(tomorrow, result.events.length);
		});
	});
});

function getHwPerDay(){
	var date = window.utils.formatDate_api(moment().add(1, day).toDate();
	var hwPerDay = [];
	for (i = 0; i < 10; i++) {
		date1 = date + i;
		window.api.get('/overview/events/getDay/', {date: date1}, function(res) {
			alert(res);
			hwPerDay.push(res);
		});
		alert(hwPerDay);
	}
}

function HWphrase(date, hw)
	if(hw < 1){
		document.getElementById(id).innerHTML = ' Looks like tonight will be an easy night! You have no homework due tomorrow!';
	} else if (hw < 3) {
		document.getElementById(id).innerHTML = ' It seems like you will have some free time tonight! You have ' + hw + ' assignments due tomorrow.';
	} else if (hw < 5)
		document.getElementById(id).innerHTML = ' Tonight might be rough. You have ' + hw + ' assignments due tomorrow.';
	} else {
		document.getElementById(id).innerHTML = ' You might be up late doing homework tonight. You have ' + hw + ' assignments due tomorrow.';
	}
}

function hello(){
	alert("Hi!");
}
<|endoftext|>


<commit_before>/*
* @constructor
* @this {RulesSet}
*/
//function RulesSet(game) {
function RulesSet(game) {
    this.movesMade = 0;
    this.totalMoves = 0;

    // Zoli: this is needed to figure out when the game has ended. See RulesSet.controlPointCapturable
    this.game = game
};

/*
 * @return {grid}
 */
RulesSet.prototype.newBoard = function(board, players) {

    this.movesMade = 0;
    this.totalMoves = board.width * board.height;

    var grid = new Array(board.width);
    for (var i = 0; i < board.width; i++) {
        grid[i] = new Array(board.height);
        for (var j = 0; j < board.height; j++) {
            grid[i][j] = -1;
        }
    }

    for (var s in board.nonrendered) {
        var space = board.nonrendered[s];
        grid[space[0]][space[1]] = -2;
        this.totalMoves--;
    }

    for (var s in board.nonjumpable) {
        var space = board.nonjumpable[s];
        grid[space[0]][space[1]] = -3;
        this.totalMoves--;
    }

    if (board.gametype === "pointcontrol") {
        for (var s in board.controlpoints) {
            var space = board.controlpoints[s];
            grid[space[0]][space[1]] = -1;
        }
    }

    this.setInitialPositions(grid, board, players);

    return grid;
}
/*
 * @param {grid} grid
 * @param {list: players} players
 */
RulesSet.prototype.setInitialPositions = function(grid, board, players) {
    if (players && players.length === 3) {
        for (var i = 0; i < 3; i++) {
            var id = players[i].id;
            for (var s in board.starting[i]) {
                var space = board.starting[i][s];
                grid[space[0]][space[1]] = id;
                this.totalMoves--;
            }
        }
    }
}

/*
 * @param {Position} space
 * return {boolean}
 */
RulesSet.prototype.isControlPoint = function(pos, board) {
    if (board.gametype === "pointcontrol") {
        for (var s in board.controlpoints) {
            var point = board.controlpoints[s];
            // var space = {i:point[0], j:point[1]};
            if (point[0] === pos.i && point[1] === pos.j) {
                return true;
            }
        }
    }

    return false;
}
/*
 * @param {BoardDiff} boardDiff
 * return {ScoreDiff}
 */
RulesSet.prototype.getScoreDiff = function(boardDiff, board) {
    /*
     * BoardDiff = {
     *     gained: {
     *         id: [{Position}, ...],
     *         id: ...
     *     },
     *     lost: {
     *         id: [{Position}, ...],
     *         id: ...
     *     }
     * }
     */

    var scoreDiff = {};
    for (var id in boardDiff.gained) {
        var spaces = boardDiff.gained[id];

        for (var s in spaces) {
            var space = spaces[s];

            if (board.gametype === "classic") {
                if (scoreDiff[id]) {
                    scoreDiff[id]++;
                } else {
                    scoreDiff[id] = 1;
                }
            } else if (board.gametype === "pointcontrol") {
                if (this.isControlPoint(space, board)) {
                    if (scoreDiff[id]) {
                        scoreDiff[id]++;
                    } else {
                        scoreDiff[id] = 1;
                    }
                }
            }
        }
    }

    for (var id in boardDiff.lost) {
        var spaces = boardDiff.lost[id];

        for (var s in spaces) {
            var space = spaces[s];
            if (board.gametype === "classic") {
                if (scoreDiff[id]) {
                    scoreDiff[id]--;
                } else {
                    scoreDiff[id] = -1;
                }
            } else if (board.gametype === "pointcontrol") {
                if (this.isControlPoint(space, board)) {
                    if (scoreDiff[id]) {
                        scoreDiff[id]--;
                    } else {
                        scoreDiff[id] = -1;
                    }
                }
            }
        }
    }

    return scoreDiff;
}
/*
 * returns {} when not 3 players
 * @return {dict} scores {id: score}
 */
RulesSet.prototype.getScores = function(grid, board, forceClassic) {

    var scores = {};
    var gametype;

    if (forceClassic) {
        gametype = "classic";
    } else {
        gametype = board.gametype;
    }

    for (var i = 0; i < board.width; i++) {
        for (var j = 0; j < board.height; j++) {
            var id = grid[i][j];
            if (id < 0) {
                continue;
            }
            if (!scores[id]) {
                scores[id] = 0;
            }

            if (gametype === "classic") {
                scores[id]++;
            } else if (gametype === "pointcontrol") {
                var s = {
                    i : i,
                    j : j
                };
                if (this.isControlPoint(s, board)) {
                    scores[id]++;
                }
            }
        }
    }

    return scores;
}

RulesSet.prototype.getPlayerScore = function(grid, board, playerId) {

    var scores = this.getScores(grid, board);
    if (scores[playerId]) {
        return scores[playerId];
    }

    return 0;
}

/*
 * @param {grid} grid
 * @param {board} board
 */
RulesSet.prototype.gameEnded = function(grid, board) {

    if (this.movesMade >= this.totalMoves) {
        return true;
    }

    if (board.gametype === "pointcontrol") {
        for (var s in board.controlpoints) {
            var point = board.controlpoints[s];

            if (this.controlPointCapturable(grid, board, {i : point[0], j : point[1]})) {
                return false;
            }
        }

        return true;
    }

    return false;
}

RulesSet.prototype.controlPointCapturable = function(grid, board, controlPoint) {
    // Generate data
    var playersInDirection = {}
    var playersInDirectionCount = {}
    var endsEmpty = {}
    var captorId = grid[controlPoint.i][controlPoint.j] + "";

    if (captorId == -1) {
        return true;
    }

    for (var direction = 0; direction < 6; direction++) {
        playersInDirection[direction] = {};
        playersInDirectionCount[direction] = 0;

        var space = controlPoint;
        while (true) {
            space = this.game.spaceInDirection(space, direction);

            if (space === undefined) {
                endsEmpty[direction] = false;
                break;
            }

            var id = grid[space.i][space.j];

            if (id === -1) {
                endsEmpty[direction] = true;
                // continue;
                break;
            } else if (id === -2 || id === -3) {
                endsEmpty[direction] = false;
                // continue;
                break;
            }

            if (playersInDirection[direction][id] === undefined) {
                playersInDirection[direction][id] = true;
                playersInDirectionCount[direction]++;
            }
        }
    }

    // Check whether capturable
    var canBeCaptured = false;
    for (var direction = 0; direction < 6; direction++) {

        var oppositeDirection = (direction + 3) % 6;

        if (!endsEmpty[direction]) {
            continue;
        }

        if (endsEmpty[oppositeDirection]) {
            canBeCaptured = true;
            // break;
        }

        for (var player in playersInDirection[oppositeDirection]) {
            if (playersInDirection[direction][player] === undefined) {
                canBeCaptured = true;
                break;
            }
            // if (playersInDirectionCount[oppositeDirection] === 1 && player === captorId) {
            if (playersInDirectionCount[oppositeDirection] === 1) {
                canBeCaptured = false;
                break;
            }
        }

        if (canBeCaptured) {
            break;
        }
    }

    return canBeCaptured;
}

if ( typeof module === "undefined")
    module = {}

module.exports = RulesSet;

<commit_msg>Removed some silly comments.<commit_after>/*
* @constructor
* @this {RulesSet}
*/
//function RulesSet(game) {
function RulesSet(game) {
    this.movesMade = 0;
    this.totalMoves = 0;

    // Zoli: this is needed to figure out when the game has ended. See RulesSet.controlPointCapturable
    this.game = game
};

/*
 * @return {grid}
 */
RulesSet.prototype.newBoard = function(board, players) {

    this.movesMade = 0;
    this.totalMoves = board.width * board.height;

    var grid = new Array(board.width);
    for (var i = 0; i < board.width; i++) {
        grid[i] = new Array(board.height);
        for (var j = 0; j < board.height; j++) {
            grid[i][j] = -1;
        }
    }

    for (var s in board.nonrendered) {
        var space = board.nonrendered[s];
        grid[space[0]][space[1]] = -2;
        this.totalMoves--;
    }

    for (var s in board.nonjumpable) {
        var space = board.nonjumpable[s];
        grid[space[0]][space[1]] = -3;
        this.totalMoves--;
    }

    if (board.gametype === "pointcontrol") {
        for (var s in board.controlpoints) {
            var space = board.controlpoints[s];
            grid[space[0]][space[1]] = -1;
        }
    }

    this.setInitialPositions(grid, board, players);

    return grid;
}
/*
 * @param {grid} grid
 * @param {list: players} players
 */
RulesSet.prototype.setInitialPositions = function(grid, board, players) {
    if (players && players.length === 3) {
        for (var i = 0; i < 3; i++) {
            var id = players[i].id;
            for (var s in board.starting[i]) {
                var space = board.starting[i][s];
                grid[space[0]][space[1]] = id;
                this.totalMoves--;
            }
        }
    }
}

/*
 * @param {Position} space
 * return {boolean}
 */
RulesSet.prototype.isControlPoint = function(pos, board) {
    if (board.gametype === "pointcontrol") {
        for (var s in board.controlpoints) {
            var point = board.controlpoints[s];
            // var space = {i:point[0], j:point[1]};
            if (point[0] === pos.i && point[1] === pos.j) {
                return true;
            }
        }
    }

    return false;
}
/*
 * @param {BoardDiff} boardDiff
 * return {ScoreDiff}
 */
RulesSet.prototype.getScoreDiff = function(boardDiff, board) {
    /*
     * BoardDiff = {
     *     gained: {
     *         id: [{Position}, ...],
     *         id: ...
     *     },
     *     lost: {
     *         id: [{Position}, ...],
     *         id: ...
     *     }
     * }
     */

    var scoreDiff = {};
    for (var id in boardDiff.gained) {
        var spaces = boardDiff.gained[id];

        for (var s in spaces) {
            var space = spaces[s];

            if (board.gametype === "classic") {
                if (scoreDiff[id]) {
                    scoreDiff[id]++;
                } else {
                    scoreDiff[id] = 1;
                }
            } else if (board.gametype === "pointcontrol") {
                if (this.isControlPoint(space, board)) {
                    if (scoreDiff[id]) {
                        scoreDiff[id]++;
                    } else {
                        scoreDiff[id] = 1;
                    }
                }
            }
        }
    }

    for (var id in boardDiff.lost) {
        var spaces = boardDiff.lost[id];

        for (var s in spaces) {
            var space = spaces[s];
            if (board.gametype === "classic") {
                if (scoreDiff[id]) {
                    scoreDiff[id]--;
                } else {
                    scoreDiff[id] = -1;
                }
            } else if (board.gametype === "pointcontrol") {
                if (this.isControlPoint(space, board)) {
                    if (scoreDiff[id]) {
                        scoreDiff[id]--;
                    } else {
                        scoreDiff[id] = -1;
                    }
                }
            }
        }
    }

    return scoreDiff;
}
/*
 * returns {} when not 3 players
 * @return {dict} scores {id: score}
 */
RulesSet.prototype.getScores = function(grid, board, forceClassic) {

    var scores = {};
    var gametype;

    if (forceClassic) {
        gametype = "classic";
    } else {
        gametype = board.gametype;
    }

    for (var i = 0; i < board.width; i++) {
        for (var j = 0; j < board.height; j++) {
            var id = grid[i][j];
            if (id < 0) {
                continue;
            }
            if (!scores[id]) {
                scores[id] = 0;
            }

            if (gametype === "classic") {
                scores[id]++;
            } else if (gametype === "pointcontrol") {
                var s = {
                    i : i,
                    j : j
                };
                if (this.isControlPoint(s, board)) {
                    scores[id]++;
                }
            }
        }
    }

    return scores;
}

RulesSet.prototype.getPlayerScore = function(grid, board, playerId) {

    var scores = this.getScores(grid, board);
    if (scores[playerId]) {
        return scores[playerId];
    }

    return 0;
}

/*
 * @param {grid} grid
 * @param {board} board
 */
RulesSet.prototype.gameEnded = function(grid, board) {

    if (this.movesMade >= this.totalMoves) {
        return true;
    }

    if (board.gametype === "pointcontrol") {
        for (var s in board.controlpoints) {
            var point = board.controlpoints[s];

            if (this.controlPointCapturable(grid, board, {i : point[0], j : point[1]})) {
                return false;
            }
        }

        return true;
    }

    return false;
}

RulesSet.prototype.controlPointCapturable = function(grid, board, controlPoint) {
    // Generate data
    var playersInDirection = {}
    var playersInDirectionCount = {}
    var endsEmpty = {}
    var captorId = grid[controlPoint.i][controlPoint.j] + "";

    if (captorId == -1) {
        return true;
    }

    for (var direction = 0; direction < 6; direction++) {
        playersInDirection[direction] = {};
        playersInDirectionCount[direction] = 0;

        var space = controlPoint;
        while (true) {
            space = this.game.spaceInDirection(space, direction);

            if (space === undefined) {
                endsEmpty[direction] = false;
                break;
            }

            var id = grid[space.i][space.j];

            if (id === -1) {
                endsEmpty[direction] = true;
                break;
            } else if (id === -2 || id === -3) {
                endsEmpty[direction] = false;
                break;
            }

            if (playersInDirection[direction][id] === undefined) {
                playersInDirection[direction][id] = true;
                playersInDirectionCount[direction]++;
            }
        }
    }

    // Check whether capturable
    var canBeCaptured = false;
    for (var direction = 0; direction < 6; direction++) {

        var oppositeDirection = (direction + 3) % 6;

        if (!endsEmpty[direction]) {
            continue;
        }

        if (endsEmpty[oppositeDirection]) {
            canBeCaptured = true;
        }

        for (var player in playersInDirection[oppositeDirection]) {
            if (playersInDirection[direction][player] === undefined) {
                canBeCaptured = true;
                break;
            }
            if (playersInDirectionCount[oppositeDirection] === 1) {
                canBeCaptured = false;
                break;
            }
        }

        if (canBeCaptured) {
            break;
        }
    }

    return canBeCaptured;
}

if ( typeof module === "undefined")
    module = {}

module.exports = RulesSet;

<|endoftext|>


<commit_before>'use strict';

/* Services */

var samtServices = angular.module('samtServices', ['ngResource']);

samtServices.factory('Phone',
		['$resource',
		 function($resource){
			return $resource('phones/:phoneId.json', {}, {
				query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
			});
		}]);

samtServices.factory('Noticia',
		['$resource',
		 function($resource){
			return $resource('http://localhost/api/noticias', {}, {
				//query: {method:'GET', params:{noticiaId:'noticias'}, isArray:true}
			});
		}]);

samtServices.factory('Parceiro',
		['$resource',
		 function($resource){
			return $resource('http://localhost/api/parceiros', {}, {
				//query: {method:'GET', params:{parceiroId:'parceiros'}, isArray:true}
			});
		}]);
<commit_msg>Bla Bla<commit_after>'use strict';

/* Services */

var samtServices = angular.module('samtServices', ['ngResource']);

samtServices.factory('Phone',
		['$resource',
		 function($resource){
			return $resource('phones/:phoneId.json', {}, {
				query: {method:'GET', params:{phoneId:'phones'}, isArray:true}
			});
		}]);

samtServices.factory('Noticia',
		['$resource',
		 function($resource){
			return $resource('http://54.191.191.173/api/noticias', {}, {
				//query: {method:'GET', params:{noticiaId:'noticias'}, isArray:true}
			});
		}]);

samtServices.factory('Parceiro',
		['$resource',
		 function($resource){
			return $resource('http://54.191.191.173/api/parceiros', {}, {
				//query: {method:'GET', params:{parceiroId:'parceiros'}, isArray:true}
			});
		}]);
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var request = require('request');
var slackBot = require('slack-bot')(process.env.URL);

router.get('/', function(req, res) {
  if (req.query.secret !== process.env.SECRET) {
    res.sendStatus(404).end();
  } else {
    request({
      url: 'https://status.heroku.com/api/v3/current-status',
      method: 'GET'
    }, function(error, response, body) {
      var result = JSON.parse(body);
      var color;
      var issues = [];

      if (result.status.Production === 'green' && result.status.Development === 'green') {
        color = 'good';
      } else {
        color = 'danger';

        result.issues.forEach(function(issue) {
          issues.push(issue.title);
        });
      }

      slackBot.send({
        text: undefined,
        channel: '#hackers',
        username: 'Heroku',
        icon_emoji: ':heroku:',
        attachments: [{
          fallback: 'Heroku Status',
          color: color,
          title: 'Heroku Status',
          title_link: 'https://status.heroku.com/',
          fields: [{
            title: 'Production',
            value: result.status.Production === 'green' ? 'Operational' : 'Experiencing issues',
            short: 'true'
          }, {
            title: 'Issues',
            value: issues ? issues.join(', ') : 'No issues',
            short: 'true'
          }, {
            title: 'Development',
            value: result.status.Development === 'green' ? 'Operational' : 'Experiencing issues',
            short: 'true'
          }]
        }]
      }, function() {
        res.end();
      });
    });
  }
});

module.exports = router;
<commit_msg>Remove text property.<commit_after>var express = require('express');
var router = express.Router();
var request = require('request');
var slackBot = require('slack-bot')(process.env.URL);

router.get('/', function(req, res) {
  if (req.query.secret !== process.env.SECRET) {
    res.sendStatus(404).end();
  } else {
    request({
      url: 'https://status.heroku.com/api/v3/current-status',
      method: 'GET'
    }, function(error, response, body) {
      var result = JSON.parse(body);
      var color;
      var issues = [];

      if (result.status.Production === 'green' && result.status.Development === 'green') {
        color = 'good';
      } else {
        color = 'danger';

        result.issues.forEach(function(issue) {
          issues.push(issue.title);
        });
      }

      slackBot.send({
        channel: '#hackers',
        username: 'Heroku',
        icon_emoji: ':heroku:',
        attachments: [{
          fallback: 'Heroku Status',
          color: color,
          title: 'Heroku Status',
          title_link: 'https://status.heroku.com/',
          fields: [{
            title: 'Production',
            value: result.status.Production === 'green' ? 'Operational' : 'Experiencing issues',
            short: 'true'
          }, {
            title: 'Issues',
            value: issues ? issues.join(', ') : 'No issues',
            short: 'true'
          }, {
            title: 'Development',
            value: result.status.Development === 'green' ? 'Operational' : 'Experiencing issues',
            short: 'true'
          }]
        }]
      }, function() {
        res.end();
      });
    });
  }
});

module.exports = router;
<|endoftext|>


<commit_before>    var prompt = 0;
    $('.changeButton2').click(function () {
      $('#alert').addClass('in'); // shows alert with Bootstrap CSS3 implem
    });

    $('.close').click(function () {
        prompt = 0;
      $(this).parent().removeClass('in'); // hides alert with Bootstrap CSS3 implem
    });

    var words = new Array();
        words[0] = "Contemplate";
        words[1] = "Brandish";
        words[2] = "Zip";
        words[3] = "Vanish";
        words[4] = "Itch";
        words[5] = "dangle";
        words[6] = "Resemble";
        words[7] = "Terrorize";
        words[8] = "Escape";
        words[9] = "Fix";
        words[10] = "Vortex";
        words[11] = "Meaning";
        words[12] = "Moonlight";
        words[13] = "Event";
        words[14] = "Music";
        words[15] = "Cobweb";
        words[16] = "Hook";
        words[17] = "Feather";
        words[18] = "Wilderness";
        words[19] = "Volcano";
        words[20] = "Futile";
        words[21] = "Remarkable";
        words[22] = "Ridiculous";
        words[23] = "Fundamental";
        words[24] = "Scary";
        words[25] = "Skeptical";
        words[26] = "Sneaky";
        words[27] = "Idyllic";
        words[28] = "Transparent";
        words[29] = "Uncomfortable";
        words[30] = "Dramatically";
        words[31] = "Randomly";
        words[32] = "Metaphorically";
        words[33] = "Blindly";
        words[34] = "Frantically";
        words[35] = "Naughtily";
        words[36] = "Shamelessly";
        words[37] = "Studiously";
        words[38] = "Wildly";
        words[39] = "Vaguely";

    var quotes = new Array();
        quotes[0] = "You must be the change you wish to see in the world.
-Mahatma Gandhi";
        quotes[1] = "I'm so happy because today I found my friends - they're in my head.
-Kurt Cobain";
        quotes[2] = "I'd rather be hated for who I am, than loved for who I am not.
-Kurt Cobain";
        quotes[3] = "If you change the way you look at things, the things you look at change.
-Wayne Dyer";
        quotes[4] = "Everyone thinks of changing the world, but no one thinks of changing himself.
-Leo Tolstoy";
        quotes[5] = "Think of all the beauty still left around you and be happy.
-Anne Frank";
        quotes[6] = "Do not go where the path may lead, go instead where there is no path and leave a trail.
-Ralph Waldo Emerson";
        quotes[7] = "Experience is not what happens to you; it's what you do with what happens to you.
-Aldous Huxley";
        quotes[8] = "To win, you must risk losing.
-Francesco Moser";
        quotes[9] = "I can accept failure, everyone fails at something. But I can't accept not trying.
-Michael Jordon";

    $('.changeButton').click(function () {
    $('#alert2').addClass('in'); // shows alert with Bootstrap CSS3 implem
    });

    $('.close').click(function () {
        prompt = 0;
      $(this).parent().removeClass('in'); // hides alert with Bootstrap CSS3 implem
    });

    $('#the-thing-that-opens-your-alert').click(function(){
        if (prompt == 0){
            var num = Math.ceil(Math.random() * 2);
            if ( num == 1) {
                alert1();
                prompt = 2;
            }
            else if (num == 2) {
                alert2();
                prompt = 1;
            }
        }
        else {
            if ( prompt == 1) {
                alert1();
            }
            else if (prompt == 2) {
                alert2();
            }
        }
    });

    function alert1 () {
        $('#alert').addClass('in');
    }

    function alert2 () {
        $('#alert2').addClass('in');
    }

    $(function(){
        //Prompts modal dialog
        $('.publishButton').click(function(){
                $('.publish-modal').modal();
            }); //cancel-signup click

        $('.btn-abandon').click(function(){
            window.location = 'http://mynarrative.co/narratives';
        }); //Redirects to Google

    });

	function ChangeIt() {
    	var totalCount = 18;
        var num =  Math.ceil( Math.random() * totalCount );
        document.body.background = 'https://s3.amazonaws.com/narrativeBlob/images/00'+num+'.jpg';
        document.body.style.backgroundColor = "black";
    }

    ChangeIt();<commit_msg>removed random image<commit_after>    var prompt = 0;
    $('.changeButton2').click(function () {
      $('#alert').addClass('in'); // shows alert with Bootstrap CSS3 implem
    });

    $('.close').click(function () {
        prompt = 0;
      $(this).parent().removeClass('in'); // hides alert with Bootstrap CSS3 implem
    });

    var words = new Array();
        words[0] = "Contemplate";
        words[1] = "Brandish";
        words[2] = "Zip";
        words[3] = "Vanish";
        words[4] = "Itch";
        words[5] = "dangle";
        words[6] = "Resemble";
        words[7] = "Terrorize";
        words[8] = "Escape";
        words[9] = "Fix";
        words[10] = "Vortex";
        words[11] = "Meaning";
        words[12] = "Moonlight";
        words[13] = "Event";
        words[14] = "Music";
        words[15] = "Cobweb";
        words[16] = "Hook";
        words[17] = "Feather";
        words[18] = "Wilderness";
        words[19] = "Volcano";
        words[20] = "Futile";
        words[21] = "Remarkable";
        words[22] = "Ridiculous";
        words[23] = "Fundamental";
        words[24] = "Scary";
        words[25] = "Skeptical";
        words[26] = "Sneaky";
        words[27] = "Idyllic";
        words[28] = "Transparent";
        words[29] = "Uncomfortable";
        words[30] = "Dramatically";
        words[31] = "Randomly";
        words[32] = "Metaphorically";
        words[33] = "Blindly";
        words[34] = "Frantically";
        words[35] = "Naughtily";
        words[36] = "Shamelessly";
        words[37] = "Studiously";
        words[38] = "Wildly";
        words[39] = "Vaguely";

    var quotes = new Array();
        quotes[0] = "You must be the change you wish to see in the world.
-Mahatma Gandhi";
        quotes[1] = "I'm so happy because today I found my friends - they're in my head.
-Kurt Cobain";
        quotes[2] = "I'd rather be hated for who I am, than loved for who I am not.
-Kurt Cobain";
        quotes[3] = "If you change the way you look at things, the things you look at change.
-Wayne Dyer";
        quotes[4] = "Everyone thinks of changing the world, but no one thinks of changing himself.
-Leo Tolstoy";
        quotes[5] = "Think of all the beauty still left around you and be happy.
-Anne Frank";
        quotes[6] = "Do not go where the path may lead, go instead where there is no path and leave a trail.
-Ralph Waldo Emerson";
        quotes[7] = "Experience is not what happens to you; it's what you do with what happens to you.
-Aldous Huxley";
        quotes[8] = "To win, you must risk losing.
-Francesco Moser";
        quotes[9] = "I can accept failure, everyone fails at something. But I can't accept not trying.
-Michael Jordon";

    $('.changeButton').click(function () {
    $('#alert2').addClass('in'); // shows alert with Bootstrap CSS3 implem
    });

    $('.close').click(function () {
        prompt = 0;
      $(this).parent().removeClass('in'); // hides alert with Bootstrap CSS3 implem
    });

    $('#the-thing-that-opens-your-alert').click(function(){
        if (prompt == 0){
            var num = Math.ceil(Math.random() * 2);
            if ( num == 1) {
                alert1();
                prompt = 2;
            }
            else if (num == 2) {
                alert2();
                prompt = 1;
            }
        }
        else {
            if ( prompt == 1) {
                alert1();
            }
            else if (prompt == 2) {
                alert2();
            }
        }
    });

    function alert1 () {
        $('#alert').addClass('in');
        $('.helpfulquotes')
    }

    function alert2 () {
        $('#alert2').addClass('in');
    }

    $(function(){
        //Prompts modal dialog
        $('.publishButton').click(function(){
                $('.publish-modal').modal();
            }); //cancel-signup click

        $('.btn-abandon').click(function(){
            window.location = 'http://mynarrative.co/narratives';
        }); //Redirects to Google

    });

	function ChangeIt() {
    	var totalCount = 18;
        var num =  Math.ceil( Math.random() * totalCount );
        document.body.background = 'https://s3.amazonaws.com/narrativeBlob/images/00'+num+'.jpg';
        document.body.style.backgroundColor = "black";
    }
<|endoftext|>