<commit_before>// @flow
import React from 'react'
import {ScrollView, Text, StyleSheet} from 'react-native'
import moment from 'moment'
import {HtmlView} from '../components/html-view'
import {Cell} from 'react-native-tableview-simple'
import {Card} from '../components/card'
import * as c from '../components/colors'
import type {StudentOrgType} from './types'

const styles = StyleSheet.create({
  name: {
    textAlign: 'center',
    marginTop: 20,
    marginBottom: 15,
    paddingHorizontal: 5,
    color: c.black,
    fontSize: 32,
    fontWeight: '300',
  },
  card: {
    marginBottom: 20,
  },
  cardBody: {
    color: c.black,
    paddingTop: 13,
    paddingBottom: 13,
    paddingLeft: 16,
    paddingRight: 16,
    fontSize: 16,
  },
  description: {
    paddingTop: 13,
    paddingBottom: 13,
    paddingLeft: 16,
    paddingRight: 16,
    backgroundColor: c.white,
    height: 200,
  },
  footer: {
    fontSize: 10,
    color: c.iosDisabledText,
    textAlign: 'center',
  },
  lastUpdated: {
    paddingBottom: 10,
  },
  poweredBy: {
    paddingBottom: 20,
  },
})

export class StudentOrgsDetailRenderView extends React.Component {
  props: {
    org: StudentOrgType,
  }

  render() {
    const data = this.props.org
    const name = data.name.trim()
    let {
      category,
      meetings,
      contacts,
      description,
      advisors,
      lastUpdated,
      website,
    } = data

    advisors = advisors.filter(c => c.name.trim().length)

    return (
      <ScrollView>
        <Text style={styles.name}>{name}</Text>

        {category.trim()
          ? <Card header="Category" style={styles.card}>
              <Text style={styles.cardBody}>{category}</Text>
            </Card>
          : null}

        {meetings.trim()
          ? <Card header="Meetings" style={styles.card}>
              <Cell cellStyle="Basic" title={meetings} />
            </Card>
          : null}

        {website.trim()
          ? <Card header="Website" style={styles.card}>
              <Text style={styles.cardBody}>
                {/^https?:\/\//.test(website) ? website : `http://${website}`}
              </Text>
            </Card>
          : null}

        <Card header="Contact" style={styles.card}>
          {contacts.map((c, i) => (
            <Text key={i} selectable={true} style={styles.cardBody}>
              {c.title}: {c.firstName} {c.lastName} ({c.email})
            </Text>
          ))}
        </Card>

        {advisors.length
          ? <Card
              header={advisors.length === 1 ? 'Advisor' : 'Advisors'}
              style={styles.card}
            >
              {advisors.map((c, i) => (
                <Text key={i} selectable={true} style={styles.cardBody}>
                  {c.name} ({c.email})
                </Text>
              ))}
            </Card>
          : null}

        {description.trim()
          ? <Card header="Description" style={styles.card}>
              <HtmlView
                scrollEnabled={true}
                style={styles.description}
                html={`
                  <style>
                    body {
                      margin: 10px 15px 10px;
                      font-family: -apple-system;
                    }
                    * {
                      max-width: 100%;
                    }
                  </style>
                  ${description.trim()}
                `}
              />
            </Card>
          : null}

        <Text selectable={true} style={[styles.footer, styles.lastUpdated]}>
          Last updated:
          {' '}
          {moment(lastUpdated, 'MMMM, DD YYYY HH:mm:ss').calendar()}
        </Text>

        <Text selectable={true} style={[styles.footer, styles.poweredBy]}>
          Powered by the St. Olaf Student Orgs Database
        </Text>
      </ScrollView>
    )
  }
}
<commit_msg>* Link android contacts and advisors to an email method * Link anroid org websites to tab browser * Remove blank ':' when no title for org head<commit_after>// @flow
import React from 'react'
import {ScrollView, Text, StyleSheet, Linking} from 'react-native'
import moment from 'moment'
import {HtmlView} from '../components/html-view'
import {Cell} from 'react-native-tableview-simple'
import {Card} from '../components/card'
import * as c from '../components/colors'
import type {StudentOrgType} from './types'
import Communications from 'react-native-communications'
import openUrl from '../components/open-url'

const styles = StyleSheet.create({
  name: {
    textAlign: 'center',
    marginTop: 20,
    marginBottom: 15,
    paddingHorizontal: 5,
    color: c.black,
    fontSize: 32,
    fontWeight: '300',
  },
  card: {
    marginBottom: 20,
  },
  cardBody: {
    color: c.black,
    paddingTop: 13,
    paddingBottom: 13,
    paddingLeft: 16,
    paddingRight: 16,
    fontSize: 16,
  },
  description: {
    paddingTop: 13,
    paddingBottom: 13,
    paddingLeft: 16,
    paddingRight: 16,
    backgroundColor: c.white,
    height: 200,
  },
  footer: {
    fontSize: 10,
    color: c.iosDisabledText,
    textAlign: 'center',
  },
  lastUpdated: {
    paddingBottom: 10,
  },
  poweredBy: {
    paddingBottom: 20,
  },
})

export class StudentOrgsDetailRenderView extends React.Component {
  props: {
    org: StudentOrgType,
  }

  // Using Communications because `mailTo` complains about
  // the lack of an available Activity...
  openEmail = (email: string, org: string) => {
    Communications.email([email], null, null, org, '')
  }

  render() {
    const data = this.props.org
    const name = data.name.trim()
    let {
      category,
      meetings,
      contacts,
      description,
      advisors,
      lastUpdated,
      website,
    } = data

    advisors = advisors.filter(c => c.name.trim().length)

    return (
      <ScrollView>
        <Text style={styles.name}>{name}</Text>

        {category.trim()
          ? <Card header="Category" style={styles.card}>
              <Text style={styles.cardBody}>{category}</Text>
            </Card>
          : null}

        {meetings.trim()
          ? <Card header="Meetings" style={styles.card}>
              <Cell cellStyle="Basic" title={meetings.trim()} />
            </Card>
          : null}

        {website.trim()
          ? <Card header="Website" style={styles.card}>
              <Text
                onPress={() =>
                  openUrl(
                    /^https?:\/\//.test(website.trim())
                      ? website
                      : `http://${website.trim()}`,
                  )}
                style={styles.cardBody}
              >
                {/^https?:\/\//.test(website.trim())
                  ? website.trim()
                  : `http://${website.trim()}`}
              </Text>
            </Card>
          : null}

        <Card header="Contact" style={styles.card}>
          {contacts.map((c, i) => (
            <Text
              key={i}
              selectable={true}
              style={styles.cardBody}
              onPress={() => this.openEmail(c.email.trim(), name)}
            >
              {c.title.trim() ? c.title.trim() + ': ' : ''}
              {c.firstName.trim()} {c.lastName.trim()} ({c.email.trim()})
            </Text>
          ))}
        </Card>

        {advisors.length
          ? <Card
              header={advisors.length === 1 ? 'Advisor' : 'Advisors'}
              style={styles.card}
            >
              {advisors.map((c, i) => (
                <Text
                  key={i}
                  selectable={true}
                  style={styles.cardBody}
                  onPress={() => this.openEmail(c.email.trim(), name)}
                >
                  {c.name.trim()} ({c.email.trim()})
                </Text>
              ))}
            </Card>
          : null}

        {description.trim()
          ? <Card header="Description" style={styles.card}>
              <HtmlView
                scrollEnabled={true}
                style={styles.description}
                html={`
                  <style>
                    body {
                      margin: 10px 15px 10px;
                      font-family: -apple-system;
                    }
                    * {
                      max-width: 100%;
                    }
                  </style>
                  ${description.trim()}
                `}
              />
            </Card>
          : null}

        <Text selectable={true} style={[styles.footer, styles.lastUpdated]}>
          Last updated:
          {' '}
          {moment(lastUpdated, 'MMMM, DD YYYY HH:mm:ss').calendar()}
        </Text>

        <Text selectable={true} style={[styles.footer, styles.poweredBy]}>
          Powered by the St. Olaf Student Orgs Database
        </Text>
      </ScrollView>
    )
  }
}
<|endoftext|>


<commit_before>(function () {
  'use strict';

  angular.module('app.session', [
      'angular-filters',
      'angular-rickshaw',
      'ui.router',

      'exceptionless',
      'exceptionless.duration',
      'exceptionless.events',
      'exceptionless.filter',
      'exceptionless.link',
      'exceptionless.notification',
      'exceptionless.pagination',
      'exceptionless.refresh',
      'exceptionless.organization',
      'exceptionless.organization-notifications',
      'exceptionless.project',
      'exceptionless.stat',
      'exceptionless.summary',
      'exceptionless.timeago',
      'exceptionless.users'
    ])
    .config(['$stateProvider', function ($stateProvider) {
      var onEnterSetTypeFilter = ['filterService', function (filterService) {
        filterService.setEventType('session', true);
      }];

      var onExitRemoveTypeFilter = ['filterService', function (filterService) {
        filterService.setEventType(null, true);
      }];

      $stateProvider.state('app.session', {
        abstract: true,
        url: '/session',
        template: '<ui-view autoscroll="true" />'
      });

      $stateProvider.state('app.session.dashboard', {
        url: '/dashboard',
        controller: 'session.Dashboard',
        controllerAs: 'vm',
        templateUrl: 'app/session/dashboard.tpl.html',
        onEnter: onEnterSetTypeFilter,
        onExit: onExitRemoveTypeFilter
      });

      $stateProvider.state('app.session-dashboard', {
        url: '/session/dashboard',
        controller: 'session.Dashboard',
        controllerAs: 'vm',
        templateUrl: 'app/session/dashboard.tpl.html',
        onEnter: onEnterSetTypeFilter,
        onExit: onExitRemoveTypeFilter
      });

      $stateProvider.state('app.session-project-dashboard', {
        url: '/project/{projectId:[0-9a-fA-F]{24}}/session/dashboard',
        controller: 'session.Dashboard',
        controllerAs: 'vm',
        templateUrl: 'app/session/dashboard.tpl.html',
        onEnter: ['$stateParams', 'filterService', function ($stateParams, filterService) {
          filterService.setProjectId($stateParams.projectId, true);
          filterService.setEventType('session', true);
        }],
        onExit: onExitRemoveTypeFilter,
        resolve: {
          project: ['$stateParams', 'projectService', function($stateParams, projectService) {
            return projectService.getById($stateParams.projectId, true);
          }]
        }
      });

      $stateProvider.state('app.session-organization-dashboard', {
        url: '/organization/{organizationId:[0-9a-fA-F]{24}}/session/dashboard',
        controller: 'session.Dashboard',
        controllerAs: 'vm',
        templateUrl: 'app/session/dashboard.tpl.html',
        onEnter: ['$stateParams', 'filterService', function ($stateParams, filterService) {
          filterService.setOrganizationId($stateParams.organizationId, true);
          filterService.setEventType('session', true);
        }],
        onExit: onExitRemoveTypeFilter,
        resolve: {
          project: ['$stateParams', 'organizationService', function($stateParams, organizationService) {
            return organizationService.getById($stateParams.organizationId, true);
          }]
        }
      });

      $stateProvider.state('app.session.list', {
        url: '/{id:[0-9a-zA-Z\-]{8,100}}',
        controller: 'session.List',
        controllerAs: 'vm',
        templateUrl: 'app/session/list.tpl.html',
        onEnter: onEnterSetTypeFilter,
        onExit: onExitRemoveTypeFilter
      });
    }]);
}());
<commit_msg>Fixed an issue with sessions sidebar not clearing existing filters<commit_after>(function () {
  'use strict';

  angular.module('app.session', [
      'angular-filters',
      'angular-rickshaw',
      'ui.router',

      'exceptionless',
      'exceptionless.duration',
      'exceptionless.events',
      'exceptionless.filter',
      'exceptionless.link',
      'exceptionless.notification',
      'exceptionless.pagination',
      'exceptionless.refresh',
      'exceptionless.organization',
      'exceptionless.organization-notifications',
      'exceptionless.project',
      'exceptionless.stat',
      'exceptionless.summary',
      'exceptionless.timeago',
      'exceptionless.users'
    ])
    .config(['$stateProvider', function ($stateProvider) {
      var onEnterSetTypeFilter = ['filterService', function (filterService) {
        filterService.setOrganizationId(null, true);
        filterService.setProjectId(null, true);
        filterService.setEventType('session', true);
      }];

      var onExitRemoveTypeFilter = ['filterService', function (filterService) {
        filterService.setEventType(null, true);
      }];

      $stateProvider.state('app.session', {
        abstract: true,
        url: '/session',
        template: '<ui-view autoscroll="true" />'
      });

      $stateProvider.state('app.session.dashboard', {
        url: '/dashboard',
        controller: 'session.Dashboard',
        controllerAs: 'vm',
        templateUrl: 'app/session/dashboard.tpl.html',
        onEnter: onEnterSetTypeFilter,
        onExit: onExitRemoveTypeFilter
      });

      $stateProvider.state('app.session-dashboard', {
        url: '/session/dashboard',
        controller: 'session.Dashboard',
        controllerAs: 'vm',
        templateUrl: 'app/session/dashboard.tpl.html',
        onEnter: onEnterSetTypeFilter,
        onExit: onExitRemoveTypeFilter
      });

      $stateProvider.state('app.session-project-dashboard', {
        url: '/project/{projectId:[0-9a-fA-F]{24}}/session/dashboard',
        controller: 'session.Dashboard',
        controllerAs: 'vm',
        templateUrl: 'app/session/dashboard.tpl.html',
        onEnter: ['$stateParams', 'filterService', function ($stateParams, filterService) {
          filterService.setProjectId($stateParams.projectId, true);
          filterService.setEventType('session', true);
        }],
        onExit: onExitRemoveTypeFilter,
        resolve: {
          project: ['$stateParams', 'projectService', function($stateParams, projectService) {
            return projectService.getById($stateParams.projectId, true);
          }]
        }
      });

      $stateProvider.state('app.session-organization-dashboard', {
        url: '/organization/{organizationId:[0-9a-fA-F]{24}}/session/dashboard',
        controller: 'session.Dashboard',
        controllerAs: 'vm',
        templateUrl: 'app/session/dashboard.tpl.html',
        onEnter: ['$stateParams', 'filterService', function ($stateParams, filterService) {
          filterService.setOrganizationId($stateParams.organizationId, true);
          filterService.setEventType('session', true);
        }],
        onExit: onExitRemoveTypeFilter,
        resolve: {
          project: ['$stateParams', 'organizationService', function($stateParams, organizationService) {
            return organizationService.getById($stateParams.organizationId, true);
          }]
        }
      });

      $stateProvider.state('app.session.list', {
        url: '/{id:[0-9a-zA-Z\-]{8,100}}',
        controller: 'session.List',
        controllerAs: 'vm',
        templateUrl: 'app/session/list.tpl.html',
        onEnter: onEnterSetTypeFilter,
        onExit: onExitRemoveTypeFilter
      });
    }]);
}());
<|endoftext|>


<commit_before>/**
 * XadillaX created at 2015-03-24 12:33:42
 *
 * Copyright (c) 2015 Souche.com, all rights
 * reserved
 */
var field = require("../lib/fieldType");
require("should");

describe("Field",function () {
    describe("float type", function () {
        var float = field.Float;
        describe("#restore", function () {
            it("arg float", function () {
                (float.restore(1.14412)).should.equal(1.14412);
                (float.restore(-1.1)).should.equal(-1.1);
            });
            it("arg string", function () {
                (float.restore("1.441")).should.equal(1.441);
                (float.restore("-1.1")).should.equal(-1.1);
            });
        });
        describe("#parse", function () {
            it("arg float", function () {
                (float.parse(1.14412)).should.equal(1.14412);
                (float.parse(-1.1)).should.equal(-1.1);
            });
            it("arg string", function () {
                (float.parse("1.441")).should.equal(1.441);
                (float.parse("-1.1")).should.equal(-1.1);
            });
        });
        describe("#equal", function () {
            it("should return true", function () {
                (float.equal("123.1", 123.1)).should.be.true;
                (float.equal(123.1, 123.1)).should.be.true;
                (float.equal(0, 0)).should.be.true;
                (float.equal("-1", -1)).should.be.true;
                (float.equal(-1.1, -1.1)).should.be.true;
            });
            it("should return false", function () {
                (float.equal("123.1", 123.11)).should.not.be.true;
                (float.equal(123.1, 123.11)).should.not.be.true;
                (float.equal(0, 0.111)).should.not.be.true;
                (float.equal("-1", -1.1)).should.not.be.true;
                (float.equal(-1.1, -1.11)).should.not.be.true;
                (float.equal(-1.1, NaN)).should.not.be.true;
            });
        });
    });
    describe("Integer type", function () {
        var Integer = field.Integer;
        describe("#restore", function () {
            it("arg Integer", function () {
                (Integer.restore(1)).should.equal(1);
                (Integer.restore(-1)).should.equal(-1);
            });
            it("arg Float", function () {
                (Integer.restore(1.1)).should.equal(1);
                (Integer.restore(-1.1)).should.equal(-1);
            });
            it("arg string", function () {
                (Integer.restore("1.441")).should.equal(1);
                (Integer.restore("-1.1")).should.equal(-1);
                (Integer.restore("-1")).should.equal(-1);
                (Integer.restore("1")).should.equal(1);
            });
        });
        describe("#parse", function () {
            it("arg Integer", function () {
                (Integer.parse(1)).should.equal(1);
                (Integer.parse(-1)).should.equal(-1);
            });
            it("arg Float", function () {
                (Integer.parse(1.1)).should.equal(1);
                (Integer.parse(-1.1)).should.equal(-1);
            });
            it("arg string", function () {
                (Integer.parse("1.441")).should.equal(1);
                (Integer.parse("-1.1")).should.equal(-1);
                (Integer.parse("-1")).should.equal(-1);
            });
        });
        describe("#equal", function () {
            it("should return true", function () {
                (Integer.equal("123.1", 123)).should.be.true;
                (Integer.equal(123.1, 123)).should.be.true;
                (Integer.equal(0, 0)).should.be.true;
                (Integer.equal("-1", -1)).should.be.true;
                (Integer.equal(-1.1, -1)).should.be.true;
            });
            it("should return false", function () {
                (Integer.equal("124.1", 123.1)).should.not.be.true;
                (Integer.equal(124.1, 123.1)).should.not.be.true;
                (Integer.equal(3, 0.111)).should.not.be.true;
                (Integer.equal("-2", -1.1)).should.not.be.true;
                (Integer.equal(-2.1, -1)).should.not.be.true;
                (Integer.equal(-2.1, NaN)).should.not.be.true;
            });
        });
    });
    describe("String tpye", function () {
        var String = field.String;
        describe("#restore", function () {
            it("should return \"\"", function () {
                String.restore().should.eql("");
                String.restore("").should.eql("");
                String.restore(null).should.eql("");
                String.restore(undefined).should.eql("");
            });
            it("should return as String", function () {
                String.restore(123).should.eql("123");
                String.restore("x123").should.eql("x123");
                String.restore(123.1).should.eql("123.1");
                String.restore(" ").should.eql(" ");
            });
        });
        describe("#parse", function () {
            it("should return \"\"", function () {
                String.parse().should.eql("");
                String.parse("").should.eql("");
                String.parse(null).should.eql("");
                String.parse(undefined).should.eql("");
            });
            it("should return as String", function () {
                String.parse(123).should.eql("123");
                String.parse("x123").should.eql("x123");
                String.parse(123.1).should.eql("123.1");
                String.parse(" ").should.eql(" ");
            });
        });
        describe("#equal", function () {
            it("should return true" , function () {
                String.equal(123,"123").should.be.true;
                String.equal("123","123").should.be.true;
                String.equal("123",123).should.be.true;
            });
            it("should return false", function () {
                String.equal("123",null).should.be.false;
                String.equal("123",undefined).should.be.false;
                String.equal(NaN,"123").should.be.false;
                String.equal("123","1234").should.be.false;
            });
        });

        describe("#zero", function() {
            it("should be \"0\"", function() {
                String.restore(0).should.be.eql("0");
                String.parse(0).should.be.eql("0");
            });
        });
    });
    describe("Json type", function () {
        var json  = field.Json;
        describe("#restore", function () {
            it("Json to String", function () {
                json.restore({a:1}).should.eql("{\"a\":1}");
            });
        });
        describe("#parse", function () {
            it("return {}", function () {
                json.parse("{\"a\":").should.eql({});
            });
            it("String to Json", function () {
                json.parse("{\"a\":1}").should.eql({a:1});
            });
        });
        describe("#equal", function () {
            it("return true", function () {
                json.equal({a:1},{a:1}).should.be.true;
            });
            it("return false", function () {
                json.equal({a:"1"},{a:1}).should.be.false;
                json.equal("{xxx",{a:1}).should.be.false;
            });
        });
    });
});
<commit_msg>add test case for boolean<commit_after>/**
 * XadillaX created at 2015-03-24 12:33:42
 *
 * Copyright (c) 2015 Souche.com, all rights
 * reserved
 */
var field = require("../lib/fieldType");
require("should");

describe("Field",function () {
    describe("float type", function () {
        var float = field.Float;
        describe("#restore", function () {
            it("arg float", function () {
                (float.restore(1.14412)).should.equal(1.14412);
                (float.restore(-1.1)).should.equal(-1.1);
            });
            it("arg string", function () {
                (float.restore("1.441")).should.equal(1.441);
                (float.restore("-1.1")).should.equal(-1.1);
            });
        });
        describe("#parse", function () {
            it("arg float", function () {
                (float.parse(1.14412)).should.equal(1.14412);
                (float.parse(-1.1)).should.equal(-1.1);
            });
            it("arg string", function () {
                (float.parse("1.441")).should.equal(1.441);
                (float.parse("-1.1")).should.equal(-1.1);
            });
        });
        describe("#equal", function () {
            it("should return true", function () {
                (float.equal("123.1", 123.1)).should.be.true;
                (float.equal(123.1, 123.1)).should.be.true;
                (float.equal(0, 0)).should.be.true;
                (float.equal("-1", -1)).should.be.true;
                (float.equal(-1.1, -1.1)).should.be.true;
            });
            it("should return false", function () {
                (float.equal("123.1", 123.11)).should.not.be.true;
                (float.equal(123.1, 123.11)).should.not.be.true;
                (float.equal(0, 0.111)).should.not.be.true;
                (float.equal("-1", -1.1)).should.not.be.true;
                (float.equal(-1.1, -1.11)).should.not.be.true;
                (float.equal(-1.1, NaN)).should.not.be.true;
            });
        });
    });

    describe("Boolean type", function () {
        var _Boolean = field.Boolean;
        describe("#restore", function () {
            it("arg Integer", function () {
                (_Boolean.restore(1)).should.equal(1);
                (_Boolean.restore(-1)).should.equal(1);
            });
            it("arg Float", function () {
                (_Boolean.restore(1.1)).should.equal(1);
                (_Boolean.restore(-1.1)).should.equal(1);
            });
            it("arg string", function () {
                (_Boolean.restore("1.441")).should.equal(1);
                (_Boolean.restore("-1.1")).should.equal(1);
                (_Boolean.restore("-1")).should.equal(1);
                (_Boolean.restore("1")).should.equal(1);
            });
            it("arg boolean", function() {
                (_Boolean.restore(true)).should.equal(1);
                (_Boolean.restore(false)).should.equal(0);
            });
        });
        describe("#parse", function () {
            it("arg Integer", function () {
                (_Boolean.parse(1)).should.equal(true);
                (_Boolean.parse(-1)).should.equal(true);
                (_Boolean.parse(0)).should.equal(false);
            });
            it("arg Float", function () {
                (_Boolean.parse(1.1)).should.equal(true);
                (_Boolean.parse(-1.1)).should.equal(true);
            });
            it("arg string", function () {
                (_Boolean.parse("1.441")).should.equal(true);
                (_Boolean.parse("-1.1")).should.equal(true);
                (_Boolean.parse("-1")).should.equal(true);
            });
        });
        describe("#equal", function () {
            it("should return true", function () {
                (_Boolean.equal("123.1", 123)).should.be.true;
                (_Boolean.equal(123.1, 123)).should.be.true;
                (_Boolean.equal(0, 0)).should.be.true;
                (_Boolean.equal("-1", -1)).should.be.true;
                (_Boolean.equal(-1.1, -1)).should.be.true;
            });
            it("should return false", function () {
                (_Boolean.equal("124.1", false)).should.not.be.true;
                (_Boolean.equal(124.1, "")).should.not.be.true;
                (_Boolean.equal(3, 0)).should.not.be.true;
                (_Boolean.equal(true, false)).should.not.be.true;
                (_Boolean.equal(true, 0)).should.not.be.true;
            });
        });
    });

    describe("Integer type", function () {
        var Integer = field.Integer;
        describe("#restore", function () {
            it("arg Integer", function () {
                (Integer.restore(1)).should.equal(1);
                (Integer.restore(-1)).should.equal(-1);
            });
            it("arg Float", function () {
                (Integer.restore(1.1)).should.equal(1);
                (Integer.restore(-1.1)).should.equal(-1);
            });
            it("arg string", function () {
                (Integer.restore("1.441")).should.equal(1);
                (Integer.restore("-1.1")).should.equal(-1);
                (Integer.restore("-1")).should.equal(-1);
                (Integer.restore("1")).should.equal(1);
            });
        });
        describe("#parse", function () {
            it("arg Integer", function () {
                (Integer.parse(1)).should.equal(1);
                (Integer.parse(-1)).should.equal(-1);
            });
            it("arg Float", function () {
                (Integer.parse(1.1)).should.equal(1);
                (Integer.parse(-1.1)).should.equal(-1);
            });
            it("arg string", function () {
                (Integer.parse("1.441")).should.equal(1);
                (Integer.parse("-1.1")).should.equal(-1);
                (Integer.parse("-1")).should.equal(-1);
            });
        });
        describe("#equal", function () {
            it("should return true", function () {
                (Integer.equal("123.1", 123)).should.be.true;
                (Integer.equal(123.1, 123)).should.be.true;
                (Integer.equal(0, 0)).should.be.true;
                (Integer.equal("-1", -1)).should.be.true;
                (Integer.equal(-1.1, -1)).should.be.true;
            });
            it("should return false", function () {
                (Integer.equal("124.1", 123.1)).should.not.be.true;
                (Integer.equal(124.1, 123.1)).should.not.be.true;
                (Integer.equal(3, 0.111)).should.not.be.true;
                (Integer.equal("-2", -1.1)).should.not.be.true;
                (Integer.equal(-2.1, -1)).should.not.be.true;
                (Integer.equal(-2.1, NaN)).should.not.be.true;
            });
        });
    });
    describe("String tpye", function () {
        var String = field.String;
        describe("#restore", function () {
            it("should return \"\"", function () {
                String.restore().should.eql("");
                String.restore("").should.eql("");
                String.restore(null).should.eql("");
                String.restore(undefined).should.eql("");
            });
            it("should return as String", function () {
                String.restore(123).should.eql("123");
                String.restore("x123").should.eql("x123");
                String.restore(123.1).should.eql("123.1");
                String.restore(" ").should.eql(" ");
            });
        });
        describe("#parse", function () {
            it("should return \"\"", function () {
                String.parse().should.eql("");
                String.parse("").should.eql("");
                String.parse(null).should.eql("");
                String.parse(undefined).should.eql("");
            });
            it("should return as String", function () {
                String.parse(123).should.eql("123");
                String.parse("x123").should.eql("x123");
                String.parse(123.1).should.eql("123.1");
                String.parse(" ").should.eql(" ");
            });
        });
        describe("#equal", function () {
            it("should return true" , function () {
                String.equal(123,"123").should.be.true;
                String.equal("123","123").should.be.true;
                String.equal("123",123).should.be.true;
            });
            it("should return false", function () {
                String.equal("123",null).should.be.false;
                String.equal("123",undefined).should.be.false;
                String.equal(NaN,"123").should.be.false;
                String.equal("123","1234").should.be.false;
            });
        });

        describe("#zero", function() {
            it("should be \"0\"", function() {
                String.restore(0).should.be.eql("0");
                String.parse(0).should.be.eql("0");
            });
        });
    });
    describe("Json type", function () {
        var json  = field.Json;
        describe("#restore", function () {
            it("Json to String", function () {
                json.restore({a:1}).should.eql("{\"a\":1}");
            });
        });
        describe("#parse", function () {
            it("return {}", function () {
                json.parse("{\"a\":").should.eql({});
            });
            it("String to Json", function () {
                json.parse("{\"a\":1}").should.eql({a:1});
            });
        });
        describe("#equal", function () {
            it("return true", function () {
                json.equal({a:1},{a:1}).should.be.true;
            });
            it("return false", function () {
                json.equal({a:"1"},{a:1}).should.be.false;
                json.equal("{xxx",{a:1}).should.be.false;
            });
        });
    });
});
<|endoftext|>


<commit_before>import {
  drawBackground,
  drawWalls,
  openingSort,
  throttle,
  drawArrow,
  drawRect
} from "./renderingFunctions"

import {DefaultWidthEnemy, DefaultHeightEnemy} from "./constants";
import Hud from "./hud";
import AssetsLoader from "./assetsLoader";
import AssetsManager from "./assetsManager";
import Texture from "./texture";
import TextureAtlas from "./textureAtlas";
import Bitmap from "./bitmap";

/* eslint-disable */
function app() {
  'use strict';

  let socket = io.connect();
  let assetsManager = new AssetsManager();
  let assetsLoader = new AssetsLoader();
  let characterSprite = null;
  let enemySprite = [];
  const hudCanvas = document.getElementById("hud");
  let hud = new Hud(hudCanvas);
  window.addEventListener('resize', resizeHudCanvas, false);

  swip.init({ socket: socket, container: document.getElementById('root') }, function (client) {
    assetsLoader.getInstance().onComplete = onComplete;
    assetsLoader.getInstance().addFile("character.png","character");
    assetsLoader.getInstance().addFile("atari400.png","enemy");
    assetsLoader.getInstance().load();
    let converter = client.converter;
    let stage = client.stage;
    let ctx = stage.getContext('2d');

    let state = null;
    let dragPosition = null;
    let dragging = false;

    client.onClick(function (evt) {
      //var hole = { x: evt.position.x, y: evt.position.y };
      //client.emit('shoot', hole);
    });

    client.onDragStart(function (evt) {
      if (state) {
        var distanceX = evt.position[0].x - state.cluster.data.character.x;
        var distanceY = evt.position[0].y - state.cluster.data.character.y;
        var distance = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));

        if (distance < (3 * state.cluster.data.character.radius)) {
          dragging = true;
          dragPosition = evt.position[0];
        }
      }
    });

    client.onDragMove(function (evt) {
      var distanceX = evt.position[0].x - state.cluster.data.character.x;
      var distanceY = evt.position[0].y - state.cluster.data.character.y;
      var distance = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));

      if (dragging) {
        if (distance > 150) {
          dragPosition = {
            x: state.cluster.data.character.x + (distanceX / distance) * 150,
            y: state.cluster.data.character.y + (distanceY / distance) * 150
          }
          const { character } = state.cluster.data;
          client.emit('move', {
             speedX: (evt.position[0].x - character.x) / 100,
             speedY: (evt.position[0].y - character.y) / 100
          });
          dragPosition = evt.position[0];
        }
      }
    });

    client.onDragEnd(function (evt) {
      if (dragging) {
        dragging = false;
        client.emit('move', {
          speedX: 0,
          speedY: 0
        });
      }
    });

    swip.sensor.onChangeOrientation(throttle(function (evt) {
      client.emit('updateOrientation', {
        rotationX: evt.rotation.x,
        rotationY: evt.rotation.y
      });
    }, 200));

    client.onUpdate(function (evt) {
      state = evt;
      var client = state.client;
      const { currentScreenId, character, currentRoomConstraint, hasStarted, maze, enemies } = state.cluster.data;
      ctx.save();
      applyTransform(ctx, converter, client.transform);
      drawBackground(ctx, client, currentRoomConstraint.bgColor);
      //if(hasStarted) {
        drawWalls(ctx, client);
        if(characterSprite && character.life > 0) {
          characterSprite.x = character.x - characterSprite.width/2;
          characterSprite.y = character.y - characterSprite.height/2;
          characterSprite.render(ctx)
          if (dragging) {
            drawArrow(ctx, character, dragPosition);
          }
        }
        enemies.forEach((enemy, index) => {
          enemySprite[index].x = enemy.x;
          enemySprite[index].y = enemy.y;
          enemySprite[index].render(ctx);
          drawRect(ctx, enemy);
        });
      //}
      ctx.restore();
      hud.draw(hasStarted, currentRoomConstraint, maze);
    });
  });

  function applyTransform (ctx, converter, transform) {
    ctx.translate(-converter.toDevicePixel(transform.x), -converter.toDevicePixel(transform.y));
    ctx.scale(converter.toDevicePixel(1), converter.toDevicePixel(1));

  }

  function onComplete() {
    const data = assetsLoader.getInstance().getData();
    for( const alias in data ){
        assetsManager.getInstance().addImage(data[alias],alias);
    }
    let atlas = new TextureAtlas();
    atlas.data = assetsManager.getInstance().getImageByAlias("character");
    atlas.createTexture("character_tex", 0,0,136,130);
    let texture = atlas.getTextureByName("character_tex");
    let characterBmp = new Bitmap();
    characterBmp.texture = texture;
    characterBmp.width = 136;
    characterBmp.height = 130;
    characterBmp.x = 0;
    characterBmp.y = 0;
    characterSprite = characterBmp;

    atlas.data = assetsManager.getInstance().getImageByAlias("enemy");
    atlas.createTexture("particle_tex", 0,0,256,156);
    texture = atlas.getTextureByName("particle_tex");
    for(let i = 0; i < 2; ++i) {
      let bmp = new Bitmap();
      bmp.texture = texture;
      bmp.width = DefaultWidthEnemy;
      bmp.height = DefaultHeightEnemy;
      bmp.x = 0;
      bmp.y = 0;
      enemySprite[i] = bmp;
    }
  }

  function resizeHudCanvas() {
     const rootCanvas = document.getElementById("root").childNodes[0];
      hud.resize(
       rootCanvas.width,
       rootCanvas.height);
  }

  window.onload = resizeHudCanvas();

};

export default app;<commit_msg>disable debug rendering function<commit_after>import {
  drawBackground,
  drawWalls,
  openingSort,
  throttle,
  drawArrow,
  drawRect
} from "./renderingFunctions"

import {DefaultWidthEnemy, DefaultHeightEnemy} from "./constants";
import Hud from "./hud";
import AssetsLoader from "./assetsLoader";
import AssetsManager from "./assetsManager";
import Texture from "./texture";
import TextureAtlas from "./textureAtlas";
import Bitmap from "./bitmap";

/* eslint-disable */
function app() {
  'use strict';

  let socket = io.connect();
  let assetsManager = new AssetsManager();
  let assetsLoader = new AssetsLoader();
  let characterSprite = null;
  let enemySprite = [];
  const hudCanvas = document.getElementById("hud");
  let hud = new Hud(hudCanvas);
  window.addEventListener('resize', resizeHudCanvas, false);

  swip.init({ socket: socket, container: document.getElementById('root') }, function (client) {
    assetsLoader.getInstance().onComplete = onComplete;
    assetsLoader.getInstance().addFile("character.png","character");
    assetsLoader.getInstance().addFile("atari400.png","enemy");
    assetsLoader.getInstance().load();
    let converter = client.converter;
    let stage = client.stage;
    let ctx = stage.getContext('2d');

    let state = null;
    let dragPosition = null;
    let dragging = false;

    client.onClick(function (evt) {
      //var hole = { x: evt.position.x, y: evt.position.y };
      //client.emit('shoot', hole);
    });

    client.onDragStart(function (evt) {
      if (state) {
        var distanceX = evt.position[0].x - state.cluster.data.character.x;
        var distanceY = evt.position[0].y - state.cluster.data.character.y;
        var distance = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));

        if (distance < (3 * state.cluster.data.character.radius)) {
          dragging = true;
          dragPosition = evt.position[0];
        }
      }
    });

    client.onDragMove(function (evt) {
      var distanceX = evt.position[0].x - state.cluster.data.character.x;
      var distanceY = evt.position[0].y - state.cluster.data.character.y;
      var distance = Math.sqrt(Math.pow(distanceX, 2) + Math.pow(distanceY, 2));

      if (dragging) {
        if (distance > 150) {
          dragPosition = {
            x: state.cluster.data.character.x + (distanceX / distance) * 150,
            y: state.cluster.data.character.y + (distanceY / distance) * 150
          }
          const { character } = state.cluster.data;
          client.emit('move', {
             speedX: (evt.position[0].x - character.x) / 100,
             speedY: (evt.position[0].y - character.y) / 100
          });
          dragPosition = evt.position[0];
        }
      }
    });

    client.onDragEnd(function (evt) {
      if (dragging) {
        dragging = false;
        client.emit('move', {
          speedX: 0,
          speedY: 0
        });
      }
    });

    swip.sensor.onChangeOrientation(throttle(function (evt) {
      client.emit('updateOrientation', {
        rotationX: evt.rotation.x,
        rotationY: evt.rotation.y
      });
    }, 200));

    client.onUpdate(function (evt) {
      state = evt;
      var client = state.client;
      const { currentScreenId, character, currentRoomConstraint, hasStarted, maze, enemies } = state.cluster.data;
      ctx.save();
      applyTransform(ctx, converter, client.transform);
      drawBackground(ctx, client, currentRoomConstraint.bgColor);
      //if(hasStarted) {
        drawWalls(ctx, client);
        if(characterSprite && character.life > 0) {
          characterSprite.x = character.x - characterSprite.width/2;
          characterSprite.y = character.y - characterSprite.height/2;
          characterSprite.render(ctx)
          if (dragging) {
            drawArrow(ctx, character, dragPosition);
          }
        }
        enemies.forEach((enemy, index) => {
          enemySprite[index].x = enemy.x;
          enemySprite[index].y = enemy.y;
          enemySprite[index].render(ctx);
          //drawRect(ctx, enemy);
        });
      //}
      ctx.restore();
      hud.draw(hasStarted, currentRoomConstraint, maze);
    });
  });

  function applyTransform (ctx, converter, transform) {
    ctx.translate(-converter.toDevicePixel(transform.x), -converter.toDevicePixel(transform.y));
    ctx.scale(converter.toDevicePixel(1), converter.toDevicePixel(1));

  }

  function onComplete() {
    const data = assetsLoader.getInstance().getData();
    for( const alias in data ){
        assetsManager.getInstance().addImage(data[alias],alias);
    }
    let atlas = new TextureAtlas();
    atlas.data = assetsManager.getInstance().getImageByAlias("character");
    atlas.createTexture("character_tex", 0,0,136,130);
    let texture = atlas.getTextureByName("character_tex");
    let characterBmp = new Bitmap();
    characterBmp.texture = texture;
    characterBmp.width = 136;
    characterBmp.height = 130;
    characterBmp.x = 0;
    characterBmp.y = 0;
    characterSprite = characterBmp;

    atlas.data = assetsManager.getInstance().getImageByAlias("enemy");
    atlas.createTexture("particle_tex", 0,0,256,156);
    texture = atlas.getTextureByName("particle_tex");
    for(let i = 0; i < 2; ++i) {
      let bmp = new Bitmap();
      bmp.texture = texture;
      bmp.width = DefaultWidthEnemy;
      bmp.height = DefaultHeightEnemy;
      bmp.x = 0;
      bmp.y = 0;
      enemySprite[i] = bmp;
    }
  }

  function resizeHudCanvas() {
     const rootCanvas = document.getElementById("root").childNodes[0];
      hud.resize(
       rootCanvas.width,
       rootCanvas.height);
  }

  window.onload = resizeHudCanvas();

};

export default app;<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if ((playerMove === 'rock' && computerMove === 'scissors') || (playerMove === 'scissors' && computerMove === 'paper') || (playerMove === 'paper' && computerMove === 'rock')) {
        winner = 'player';
    } else if  ((computerMove === 'rock' && playerMove === 'scissors') || (computerMove === 'scissors' && playerMove === 'paper') || (computerMove === 'paper' && playerMove === 'rock')) {
        winner = 'computer';
    } else {
        winner = 'tie';
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>homework 5<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if ((playerMove === 'rock' && computerMove === 'scissors') || (playerMove === 'scissors' && computerMove === 'paper') || (playerMove === 'paper' && computerMove === 'rock')) {
        winner = 'player';
    } else if  ((computerMove === 'rock' && playerMove === 'scissors') || (computerMove === 'scissors' && playerMove === 'paper') || (computerMove === 'paper' && playerMove === 'rock')) {
        winner = 'computer';
    } else {
        winner = 'tie';
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    while (playerWins <= 5 && computerWins <= 5) {
            if (playerWins === 5) {
        console.log('Player Won!');
        break;
    } else if (computerWins === 5) {
        console.log('Computer Won!');
        break;
    } else {
    var playerMove = getPlayerMove();
    var computerMove = getComputerMove();
	var winner = getWinner(playerMove, computerMove);
    	console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
    		if (winner === 'player') {
    	    playerWins++;
    	    console.log(winner + ' won this round.')
    	} else if (winner === 'computer') {
    	    computerWins++;
    	    console.log(winner + ' won this round.')
    	} else {
    	    console.log('Round was a tie.');
    	}
    	console.log('The score is currently ' + playerWins + ' to ' + computerWins + '\n');

    }
}
    return [playerWins, computerWins];

}

<|endoftext|>


<commit_before>// External dependencies
var assert = require('assert'),
    should = require('should'),
    fs     = require('fs');

describe('The build/fonts directory...', function() {

    it('Should include the right font files', function(done) {
        fs.readdir('build/fonts/', function(err, files) {
            files.should.containEql('fontawesome-webfont.eot');
            files.should.containEql('fontawesome-webfont.svg');
            files.should.containEql('fontawesome-webfont.ttf');
            files.should.containEql('fontawesome-webfont.woff');
            done();
        });
    });

    it('Should include Merriweather font files', function(done) {
        fs.readdir('build/fonts/', function(err, files) {
            files.should.containEql('Merriweather.eot');
            files.should.containEql('Merriweather.svg');
            files.should.containEql('Merriweather.ttf');
            files.should.containEql('Merriweather.woff');
            done();
        });
    });

    it('Should include Open-Sans font files', function(done) {
        fs.readdir('build/fonts/', function(err, files) {
            files.should.containEql('Open-Sans.eot');
            files.should.containEql('Open-Sans.svg');
            files.should.containEql('Open-Sans.ttf');
            files.should.containEql('Open-Sans.woff');
            done();
        });
    });

    it('Should include SourceCodePro font files', function(done) {
        fs.readdir('build/fonts/', function(err, files) {
            files.should.containEql('SourceCodePro.eot');
            files.should.containEql('SourceCodePro.svg');
            files.should.containEql('SourceCodePro.ttf');
            files.should.containEql('SourceCodePro.woff');
            done();
        });
    });

});<commit_msg>Removing assert<commit_after>// External dependencies
var should = require('should'),
    fs     = require('fs');

describe('The build/fonts directory...', function() {

    it('Should include the right font files', function(done) {
        fs.readdir('build/fonts/', function(err, files) {
            files.should.containEql('fontawesome-webfont.eot');
            files.should.containEql('fontawesome-webfont.svg');
            files.should.containEql('fontawesome-webfont.ttf');
            files.should.containEql('fontawesome-webfont.woff');
            done();
        });
    });

    it('Should include Merriweather font files', function(done) {
        fs.readdir('build/fonts/', function(err, files) {
            files.should.containEql('Merriweather.eot');
            files.should.containEql('Merriweather.svg');
            files.should.containEql('Merriweather.ttf');
            files.should.containEql('Merriweather.woff');
            done();
        });
    });

    it('Should include Open-Sans font files', function(done) {
        fs.readdir('build/fonts/', function(err, files) {
            files.should.containEql('Open-Sans.eot');
            files.should.containEql('Open-Sans.svg');
            files.should.containEql('Open-Sans.ttf');
            files.should.containEql('Open-Sans.woff');
            done();
        });
    });

    it('Should include SourceCodePro font files', function(done) {
        fs.readdir('build/fonts/', function(err, files) {
            files.should.containEql('SourceCodePro.eot');
            files.should.containEql('SourceCodePro.svg');
            files.should.containEql('SourceCodePro.ttf');
            files.should.containEql('SourceCodePro.woff');
            done();
        });
    });

});<|endoftext|>


<commit_before>import {parse} from 'cookie';
module.exports = (router) => {
  // router is props.history from a component served by react router
  let cookies = parse(document.cookie);
  console.log(cookies);
  if (!cookies.fridgrSesh) {
    router.push('/login');
    return;
  }

  let fridgrSesh = JSON.parse(cookies.fridgrSesh.slice(2));
  console.log(fridgrSesh);
  if (!(fridgrSesh.userId && fridgrSesh.houseId)) {
    router.push('/login');
  }

};
<commit_msg>Remove console logs from auth<commit_after>import {parse} from 'cookie';
module.exports = (router) => {
  // router is props.history from a component served by react router
  let cookies = parse(document.cookie);
  if (!cookies.fridgrSesh) {
    router.push('/login');
    return;
  }

  let fridgrSesh = JSON.parse(cookies.fridgrSesh.slice(2));
  if (!(fridgrSesh.userId && fridgrSesh.houseId)) {
    router.push('/login');
  }

};
<|endoftext|>


<commit_before>function NineSlice(image) {
    var img = image;
    return {
        topLeft:undefined, top:undefined, topRight:undefined,
        right:undefined, bottomRight:undefined, bottom:undefined,
        bottomLeft:undefined, left:undefined, center:undefined,

        copyDimensions: function(slices) {
            this.topLeft = slice.topLeft;
            this.top = slice.top;
            this.topRight = slice.topRight;
            this.right = slice.right;
            this.bottomRight = slice.bottomRight;
            this.bottom = slice.bottom;
            this.bottomLeft = slice.bottomLeft;
            this.left = slice.left;
            this.center = slice.center;
        },

        render: function(gc, x, y, width, height) {
            gc.drawImage(img, this.left.x, this.left.y, this.left.width, this.left.height, x, y+this.topLeft.height, this.left.width, height-this.topLeft.height); //Left
            gc.drawImage(img, this.top.x, this.top.y, this.top.width, this.top.height, x+this.topLeft.width, y, width-this.topLeft.width, this.top.height); //Top
            gc.drawImage(img, this.right.x, this.right.y, this.right.width, this.right.height, x+width, y+this.topRight.height, this.right.width, height-this.topRight.height); //Right
            gc.drawImage(img, this.bottom.x, this.bottom.y, this.bottom.width, this.bottom.height, x+this.bottomLeft.width, y+height, width-this.bottomLeft.width, this.bottom.height); //Bottom
            gc.drawImage(img, this.topLeft.x, this.topLeft.y, this.topLeft.width, this.topLeft.height, x, y, this.topLeft.width, this.topLeft.height); //TopLeft
            gc.drawImage(img, this.topRight.x, this.topRight.y, this.topRight.width, this.topRight.height, x+width, y, this.topRight.width, this.topRight.height); //TopRight
            gc.drawImage(img, this.bottomRight.x, this.bottomRight.y, this.bottomRight.width, this.bottomRight.height, x+width, y+height, this.bottomRight.width, this.bottomRight.height); //BottomRight
            gc.drawImage(img, this.bottomLeft.x, this.bottomLeft.y, this.bottomLeft.width, this.bottomLeft.height, x, y+height, this.bottomRight.width, this.bottomRight.height); //BottomLeft
            if (this.center) gc.drawImage(img, this.center.x, this.center.y, this.center.width, this.center.height, x+this.left.width, y+this.top.height, width-this.left.width, height-this.top.height); //Center
        },
    }
}

function Graphic(image) {
    var img = image;
    return {
        x: 0,
        y: 0,
        scaleX: 1,
        scaleY: 1,
        originX: 0,
        originY: 0,
        angle: 0,
        render: function(gc) {
            gc.save();
            gc.translate(this.x, this.y);
            gc.rotate(this.angle*(Math.PI/180));
            gc.drawImage(img, -this.originX, -this.originY, img.width * this.scaleX, img.height * this.scaleY);
            gc.rotate(0);
            gc.restore();
        },

        getImage: function() {
            return img;
        },

        getWidth: function() {
            return img.width;
        },

        getHeight: function() {
            return img.height;
        },
    }
}

function Animation(image, _cellWidth, _cellHeight) {
    'use strict';
    var base = Graphic(image),
    cellWidth = _cellWidth,
    cellHeight = _cellHeight,
    cells,
    cell = 0,
    timer = 0,
    speed = 1;

    base.onComplete = undefined;

    base.update = function(delta) {
        if (timer >= delta) {
            if (cell < cells) {
                cell++;
            } else {
                if (base.onComplete) {
                    base.onComplete();
                }
                cell = 0;
            }
            timer = 0;
        } else {
            timer += delta * speed;
        }
    };

    base.render = function(gc) {
        var img = base.getImage();
        cells = img.width / cellWidth - 1; //For some reason base.img won't work in the constructor.

        gc.save();
        gc.translate(base.x, base.y);
        gc.rotate(base.angle*(Math.PI/180));
        gc.drawImage(img, cell*cellWidth, 0, cellWidth, cellHeight, -base.originX, -base.originY, cellWidth * base.scaleX, cellHeight * base.scaleY);
        gc.rotate(0);
        gc.restore();
    };

    base.getWidth = function() {
        return cellWidth;
    };

    base.getHeight = function() {
        return cellHeight;
    };

    base.getSpeed = function() {
        return speed;
    };

    base.setSpeed = function(value) {
        speed = value;
    };

    return base;
}
<commit_msg>Fixed a typo.<commit_after>function NineSlice(image) {
    var img = image;
    return {
        topLeft:undefined, top:undefined, topRight:undefined,
        right:undefined, bottomRight:undefined, bottom:undefined,
        bottomLeft:undefined, left:undefined, center:undefined,

        copyDimensions: function(slice) {
            this.topLeft = slice.topLeft;
            this.top = slice.top;
            this.topRight = slice.topRight;
            this.right = slice.right;
            this.bottomRight = slice.bottomRight;
            this.bottom = slice.bottom;
            this.bottomLeft = slice.bottomLeft;
            this.left = slice.left;
            this.center = slice.center;
        },

        render: function(gc, x, y, width, height) {
            gc.drawImage(img, this.left.x, this.left.y, this.left.width, this.left.height, x, y+this.topLeft.height, this.left.width, height-this.topLeft.height); //Left
            gc.drawImage(img, this.top.x, this.top.y, this.top.width, this.top.height, x+this.topLeft.width, y, width-this.topLeft.width, this.top.height); //Top
            gc.drawImage(img, this.right.x, this.right.y, this.right.width, this.right.height, x+width, y+this.topRight.height, this.right.width, height-this.topRight.height); //Right
            gc.drawImage(img, this.bottom.x, this.bottom.y, this.bottom.width, this.bottom.height, x+this.bottomLeft.width, y+height, width-this.bottomLeft.width, this.bottom.height); //Bottom
            gc.drawImage(img, this.topLeft.x, this.topLeft.y, this.topLeft.width, this.topLeft.height, x, y, this.topLeft.width, this.topLeft.height); //TopLeft
            gc.drawImage(img, this.topRight.x, this.topRight.y, this.topRight.width, this.topRight.height, x+width, y, this.topRight.width, this.topRight.height); //TopRight
            gc.drawImage(img, this.bottomRight.x, this.bottomRight.y, this.bottomRight.width, this.bottomRight.height, x+width, y+height, this.bottomRight.width, this.bottomRight.height); //BottomRight
            gc.drawImage(img, this.bottomLeft.x, this.bottomLeft.y, this.bottomLeft.width, this.bottomLeft.height, x, y+height, this.bottomRight.width, this.bottomRight.height); //BottomLeft
            if (this.center) gc.drawImage(img, this.center.x, this.center.y, this.center.width, this.center.height, x+this.left.width, y+this.top.height, width-this.left.width, height-this.top.height); //Center
        },
    }
}

function Graphic(image) {
    var img = image;
    return {
        x: 0,
        y: 0,
        scaleX: 1,
        scaleY: 1,
        originX: 0,
        originY: 0,
        angle: 0,
        render: function(gc) {
            gc.save();
            gc.translate(this.x, this.y);
            gc.rotate(this.angle*(Math.PI/180));
            gc.drawImage(img, -this.originX, -this.originY, img.width * this.scaleX, img.height * this.scaleY);
            gc.rotate(0);
            gc.restore();
        },

        getImage: function() {
            return img;
        },

        getWidth: function() {
            return img.width;
        },

        getHeight: function() {
            return img.height;
        },
    }
}

function Animation(image, _cellWidth, _cellHeight) {
    'use strict';
    var base = Graphic(image),
    cellWidth = _cellWidth,
    cellHeight = _cellHeight,
    cells,
    cell = 0,
    timer = 0,
    speed = 1;

    base.onComplete = undefined;

    base.update = function(delta) {
        if (timer >= delta) {
            if (cell < cells) {
                cell++;
            } else {
                if (base.onComplete) {
                    base.onComplete();
                }
                cell = 0;
            }
            timer = 0;
        } else {
            timer += delta * speed;
        }
    };

    base.render = function(gc) {
        var img = base.getImage();
        cells = img.width / cellWidth - 1; //For some reason base.img won't work in the constructor.

        gc.save();
        gc.translate(base.x, base.y);
        gc.rotate(base.angle*(Math.PI/180));
        gc.drawImage(img, cell*cellWidth, 0, cellWidth, cellHeight, -base.originX, -base.originY, cellWidth * base.scaleX, cellHeight * base.scaleY);
        gc.rotate(0);
        gc.restore();
    };

    base.getWidth = function() {
        return cellWidth;
    };

    base.getHeight = function() {
        return cellHeight;
    };

    base.getSpeed = function() {
        return speed;
    };

    base.setSpeed = function(value) {
        speed = value;
    };

    return base;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    if (playerMove === computerMove) {
        winner = 'tie';
    } else if (playerMove === 'rock' && computerMove === 'scissors') {
        winner = 'player';
    } else if (playerMove === 'paper' && computerMove === 'rock') {
        winner = 'player';
    } else if (playerMove === 'scissors' && computerMove === 'paper') {
        winner = 'player';
    } else {
        winner = 'computer';
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Unit 5 homework<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move || getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move || randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    if (playerMove === computerMove) {
        winner = 'tie';
    } else if (playerMove === 'rock' && computerMove === 'scissors') {
        winner = 'player';
    } else if (playerMove === 'paper' && computerMove === 'rock') {
        winner = 'player';
    } else if (playerMove === 'scissors' && computerMove === 'paper') {
        winner = 'player';
    } else {
        winner = 'computer';
    }
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    var score = '';
    while (playerWins + computerWins < 5) {
        var gameWinner = getWinner(getPlayerMove(),getComputerMove());
        if (gameWinner === 'player') {
            console.log('Player wins this round!');
            playerWins ++;
            score = 'Score is ' + playerWins + ':' + computerWins;
            console.log(score);
        } else if (gameWinner === 'computer') {
            console.log('Computer wins this round!');
            computerWins ++;
            score = 'Score is ' + playerWins + ':' + computerWins;
            console.log(score);

        } else {
            console.log('This round was tied');
            score = 'Score is ' + playerWins + ':' + computerWins;
            console.log(score);

        }
    }
    return [playerWins, computerWins];
}

function playTo(x) {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    var score = '';
    while (playerWins + computerWins < x) {
        var gameWinner = getWinner(getPlayerMove(),getComputerMove());
        if (gameWinner === 'player') {
            console.log('Player wins this round!');
            playerWins ++;
            score = 'Score is ' + playerWins + ':' + computerWins;
            console.log(score);
        } else if (gameWinner === 'computer') {
            console.log('Computer wins this round!');
            computerWins ++;
            score = 'Score is ' + playerWins + ':' + computerWins;
            console.log(score);

        } else {
            console.log('This round was tied');
            score = 'Score is ' + playerWins + ':' + computerWins;
            console.log(score);

        }
    }
    return [playerWins, computerWins];
}<|endoftext|>


<commit_before>(function () {
    'use strict';

    const app = angular.module('pitonApp',
        [
            'app',
            'ui.router',
            'ui.bootstrap',
            'ui.calendar',
            'ngAria',
            'ngMaterial',
            'ngMessages',
            'ngSanitize',
            'auth0',
            'angular-storage',
            'angular-jwt',
            'auth0.lock',

            // Nossos modulos
            'modalModule',
            'login',
            'authModule',
            'userModule',
            'toolbarModulo',
            'toastModule',
            'sidebarModulo',
            'buscaModulo',
            'aboutModule',
            'footerModule',
            'materialCalendar',
            'calendarioModulo',
            'agendamentoModulo',
            'autenticacaoModulo',
            'localModulo'
        ]);

    app.constant('_', window._)
    /**
     * Auth config
     */
        .config(['$urlRouterProvider', '$provide', '$httpProvider',
            function ($urlRouterProvider, $provide, $httpProvider) {

                /**
                 * Adds watchers for requests open and close. While there's an
                 * open request the loading indicator keeps shown.
                 */
                function loadingInterceptor($rootScope, $q) {
                    var _openRequests_ = 0;

                    return {
                        request: function (config) {
                            _openRequests_++;
                            $rootScope.$broadcast('loading_show');
                            return config || $q.when(config);
                        },
                        response: function (response) {
                            if (!(--_openRequests_)) {
                                $rootScope.$broadcast('loading_hide');
                            }
                            return response || $q.when(response);
                        },
                        responseError: function (response) {
                            if (!(--_openRequests_)) {
                                $rootScope.$broadcast('loading_hide');
                            }
                            return $q.reject(response);
                        }
                    };
                }

                $provide.factory('loadingInterceptor', ['$rootScope', '$q', loadingInterceptor]);

                $urlRouterProvider.otherwise('/app/');

                $httpProvider.interceptors.push('loadingInterceptor');
            }])
        /**
         * State config
         */
        .config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) {
            const view = './view/';
            $stateProvider
                .state('app', {
                    abstract: true,
                    url: '/app',
                    templateUrl: view + 'app.html',
                    controller: 'AppController'
                })
                .state('app.login', {
                    url: '/',
                    templateUrl: view + 'login.html',
                    controller: 'LoginController as loginCtrl'
                })
                .state('app.home', {
                    url: '/home',
                    templateUrl: view + 'home.html',
                    controller: 'CalendarioController as calendarioCtrl'
                })
                .state('app.dia', {
                    url: '/dia?numeroDia&numeroMes&ano',
                    templateUrl: view + 'detalhesDia.html',
                    controller: 'DetalhesDiaController as detalhesCtrl',
                    resolve: {
                        data: $stateParams => {
                            const dia = $stateParams.numeroDia;
                            const mes = $stateParams.numeroMes;
                            const ano = $stateParams.ano;
                            return new Date(ano, mes, dia);
                        }
                    }
                });
            $locationProvider.html5Mode(true);
        }])
        .config(['$mdThemingProvider', function ($mdThemingProvider) {
            $mdThemingProvider.setNonce();
            $mdThemingProvider.theme('default')
                .primaryPalette('indigo', {default: 'A200'})
                .accentPalette('blue', {default: '500'});
        }]);
    app.run(['$rootScope', 'ModalService', function ($rootScope, ModalService) {
        $rootScope._ = window._;
        $rootScope.apiRoot = '/api';

        $rootScope.appPrimaryColor = 'teal';
        $rootScope.appSecondaryColor = 'teal';

        const _modalResp_ = ModalService.loadingIndicatorModal();
        _modalResp_.attach().then(function () {
            $rootScope.$on('loading_show', function () {
                _modalResp_.show();
            });

            $rootScope.$on('loading_hide', function () {
                if (_modalResp_) {
                    _modalResp_.hide();
                }
            });
        });
    }]);
}());
<commit_msg>Adicionando os eventos do calendário como uma propriedade 'resolve' para o state da home<commit_after>(function () {
    'use strict';

    const app = angular.module('pitonApp',
        [
            'app',
            'ui.router',
            'ui.bootstrap',
            'ui.calendar',
            'ngAria',
            'ngMaterial',
            'ngMessages',
            'ngSanitize',
            'auth0',
            'angular-storage',
            'angular-jwt',
            'auth0.lock',

            // Nossos modulos
            'modalModule',
            'login',
            'authModule',
            'userModule',
            'toolbarModulo',
            'toastModule',
            'sidebarModulo',
            'buscaModulo',
            'aboutModule',
            'footerModule',
            'materialCalendar',
            'calendarioModulo',
            'agendamentoModulo',
            'autenticacaoModulo',
            'localModulo'
        ]);

    app.constant('_', window._)
    /**
     * Auth config
     */
        .config(['$urlRouterProvider', '$provide', '$httpProvider',
            function ($urlRouterProvider, $provide, $httpProvider) {

                /**
                 * Adds watchers for requests open and close. While there's an
                 * open request the loading indicator keeps shown.
                 */
                function loadingInterceptor($rootScope, $q) {
                    var _openRequests_ = 0;

                    return {
                        request: function (config) {
                            _openRequests_++;
                            $rootScope.$broadcast('loading_show');
                            return config || $q.when(config);
                        },
                        response: function (response) {
                            if (!(--_openRequests_)) {
                                $rootScope.$broadcast('loading_hide');
                            }
                            return response || $q.when(response);
                        },
                        responseError: function (response) {
                            if (!(--_openRequests_)) {
                                $rootScope.$broadcast('loading_hide');
                            }
                            return $q.reject(response);
                        }
                    };
                }

                $provide.factory('loadingInterceptor', ['$rootScope', '$q', loadingInterceptor]);

                $urlRouterProvider.otherwise('/app/');

                $httpProvider.interceptors.push('loadingInterceptor');
            }])
        /**
         * State config
         */
        .config(['$stateProvider', '$locationProvider', function ($stateProvider, $locationProvider) {
            const view = './view/';
            $stateProvider
                .state('app', {
                    abstract: true,
                    url: '/app',
                    templateUrl: view + 'app.html',
                    controller: 'AppController'
                })
                .state('app.login', {
                    url: '/',
                    templateUrl: view + 'login.html',
                    controller: 'LoginController as loginCtrl'
                })
                .state('app.home', {
                    url: '/home',
                    templateUrl: view + 'home.html',
                    controller: 'CalendarioController as calendarioCtrl',
                    resolve: {
                        eventos: function (AgendamentoService) {
                            return AgendamentoService.loadReservasFuturas();
                        }
                    }
                })
                .state('app.dia', {
                    url: '/dia?numeroDia&numeroMes&ano',
                    templateUrl: view + 'detalhesDia.html',
                    controller: 'DetalhesDiaController as detalhesCtrl',
                    resolve: {
                        data: $stateParams => {
                            const dia = $stateParams.numeroDia;
                            const mes = $stateParams.numeroMes;
                            const ano = $stateParams.ano;
                            return new Date(ano, mes, dia);
                        }
                    }
                });
            $locationProvider.html5Mode(true);
        }])
        .config(['$mdThemingProvider', function ($mdThemingProvider) {
            $mdThemingProvider.setNonce();
            $mdThemingProvider.theme('default')
                .primaryPalette('indigo', {default: 'A200'})
                .accentPalette('blue', {default: '500'});
        }]);
    app.run(['$rootScope', 'ModalService', function ($rootScope, ModalService) {
        $rootScope._ = window._;
        $rootScope.apiRoot = '/api';

        $rootScope.appPrimaryColor = 'teal';
        $rootScope.appSecondaryColor = 'teal';

        const _modalResp_ = ModalService.loadingIndicatorModal();
        _modalResp_.attach().then(function () {
            $rootScope.$on('loading_show', function () {
                _modalResp_.show();
            });

            $rootScope.$on('loading_hide', function () {
                if (_modalResp_) {
                    _modalResp_.hide();
                }
            });
        });
    }]);
}());
<|endoftext|>


<commit_before>/* global describe, it, beforeEach */

var expect = require('chai').expect

var dtype = require('dynatype')
var graph = require('../lib/graph')

describe('Translator Graph', function () {
  it('Creates a graph for a list of translators', function () {
  })
})
<commit_msg>(test) Add test sketch for a translator graph.<commit_after>/* global describe, it, beforeEach */

var expect = require('chai').expect

var dtypeGraph = require('../lib/graph')

describe('Translator Graph', function () {
  it('Creates a graph for a list of translators', function () {
    var dynatypes = {
      descriptors: [{name: 'A'}, {name: 'B'}, {name: 'C'}],
      translators: [{from: 'A', to: 'B'}, {from: 'C', to: 'B'}]
    }
    var graph = dtypeGraph(dynatypes)
    expect(graph).to.be.an('object')
    expect(graph.nodes).to.have.length(3)
    expect(graph.edges).to.have.length(2)
  })
})
<|endoftext|>


<commit_before>/*global d3 $ */

function GroupedBarChart(opts, getDataCallback, updateCallback){
    this.getDataCallback=getDataCallback;
    this.updateCallback=updateCallback;

    var name=opts.name;
    var id = "#"+name.replace(/\./g,'\\.');
    var margin = {top: 20, right: 20, bottom: 30, left: 40};

    //Add CSS to the div
    d3.select(id).style({
        "overflow-y":"auto",
        "overflow-x":"hidden"
    });

    //set param
    this.selection = {global:[]};
    if(opts.args){ // set selection from arguments
        this._decodeArgs(opts.args);
    }

    var widget = this;
    //Make draggable and resizable
    d3.select(id).attr("class","resize-drag");

    d3.select(id).on("divresize",function(){
        widget.update();
    });

    //Collapse on dbl click
    d3.select(id).on('dblclick',function(d){
        var currentheight = d3.select(id).style("height");
        if ( currentheight != "20px"){
            widget.restoreHeight =currentheight ;
            d3.select(id).style('height','20px');
        }
        else{
            d3.select(id).style("height",widget.restoreHeight);
        }
    });

    //SVG container
    var svg = d3.select(id).append("svg").append("g");

    //Title
    svg.append("text").attr('y',-5).text(name);

    //Axes
    svg.append("g").attr("class", "y axis")
        .attr("transform", "translate(-3,0)");
    svg.append("g").attr("class", "x axis");

    //Scales
    var y0 = d3.scale.ordinal();
    var y1 = d3.scale.ordinal();
    var x = d3.scale.linear();
    if (opts.logaxis){
        x = d3.scale.log();
    }

    //Axis
    var xAxis = d3.svg.axis();
    var yAxis = d3.svg.axis();

    xAxis.orient("bottom").ticks(3,",.1s");
    yAxis.orient("left");

    //Save vars to "this"
    this.margin = margin;
    this.svg=svg;
    this.y0=y0;
    this.y1=y1;
    this.x=x;
    this.xAxis = xAxis;
    this.yAxis = yAxis;

    this._datasrc = opts.datasrc;
    this._opts = opts;
    this._logaxis = opts.logaxis;
}

GroupedBarChart.prototype = {
    getSelection: function(){
        return this.selection;
    },

    _encodeArgs: function(){
        return JSON.stringify(this.getSelection());
    },

    _decodeArgs: function(s){
        this.selection = JSON.parse(s);
    },

    update: function(){
        var widget = this;
        var promises = {};

        //generate promise for each expr
        for (var d in widget._datasrc){
            if (widget._datasrc[d].disabled){
                continue;
            }
            var p = this.getDataCallback(d);
            for (var k in p){
                promises[k] = p[k];
            }
        }

        var promarray = Object.keys(promises).map(function(k){
            return promises[k];
        });

        var promkeys = Object.keys(promises);
        $.when.apply($,promarray).done(function(){
            var results = arguments;
            var res = {};
            promkeys.forEach(function(d,i){
                res[d] = results[i];
            });

            widget.redraw(res);
        });
    },

    flattenData: function(res){
        var widget = this;
        return Object.keys(res).reduce(function(prev,curr){
            var label = curr.split('-');
            var colormap = widget._datasrc[label[1]].colormap;
            var cidx = Math.floor(colormap.length/2);
            var c = colormap[cidx];

            //Add color
            var row = res[curr].data.map(function(d){
                d.color = c;
                return d;
            });
            return prev.concat(row);
        }, []);
    },

    redraw :function(res){
        var fdata = this.flattenData(res);
        var x =this.x;
        var y0 =this.y0;
        var y1 =this.y1;
        var svg =this.svg;
        var selection = this.selection;

        //svg.on('click', this.click_callback);

        //update the axis and svgframe
        this.updateYAxis(fdata);
        this.updateXAxis(fdata);
        this.updateSVG();

        var widget = this;

        //bind data
        var bars = this.svg.selectAll('.bar').data(fdata);

        function clickFunc(d){
            if(!widget.selection.brush){
                widget.selection.brush = [];
            }

            var idx = widget.selection.brush.findIndex(function(b){
                return (b.cat == d.cat);
            });

            if (idx != -1){
                widget.selection.brush.splice(idx,1);
                }
            else{
                if(d3.event.shiftKey){
                    widget.selection.brush.push({id:d.id, cat:d.cat});
                }
                else{
                    widget.selection.brush = [{id:d.id, cat:d.cat}];
                }
            }

            if(widget.selection.brush.length < 1){
                delete widget.selection.brush;
            }

            widget.update(); //redraw itself
            widget.updateCallback(widget._encodeArgs());
        }

        //append new bars
        bars.enter()
            .append('rect')
            .attr('class', 'bar')
            .on('click', clickFunc)//toggle callback
            .append("svg:title"); //tooltip

        //set shape
        bars.attr('x', 0)
            .attr('y', function(d){return widget.y0(d.cat) + //category
                                   widget.y1(d.color);}) //selection group
            .style('fill', function(d){
                if (!widget.selection.brush || //no selection
                    widget.selection.brush.findIndex(function(b){
                        return (b.cat == d.cat); }) != -1){//in selection
                    return d.color;
                }
                else{
                    return 'gray';
                }
            })
            .attr('height',function(d){ return widget.y1.rangeBand()-1; })
            .transition().duration(500)
            .attr('width',function(d){
                return widget.x(d.val);
            });

        //add tool tip
        bars.select('title').text(function(d){
            return d3.format(',')(d.val);
        });

        //remove bars with no data
        bars.exit().remove();
    },

    updateSVG : function(){
        var svg = this.svg;
        var margin = this.margin;

        var svgframe = d3.select(svg.node().parentNode);
        var rect=svgframe.node().parentNode.getBoundingClientRect();

        //calculate width and height in side the margin
        var width = rect.width-margin.left-margin.right;
        var height = this.totalheight;

        //resize the frame
        svgframe.attr("width", width + margin.left + margin.right);
        svgframe.attr("height", height + margin.top + margin.bottom);

        svg.attr("transform", "translate("+margin.left+","+margin.top+")");

        this.width = width;
        this.height = height;
    },

    updateXAxis: function(data){
        var margin = this.margin;
        var x=this.x;
        var xAxis=this.xAxis;
        var svg=this.svg;

        var svgframe = d3.select(svg.node().parentNode);
        var rect=svgframe.node().parentNode.getBoundingClientRect();
        var width = rect.width - this.margin.left-this.margin.right;

        x.domain([d3.min(data, function(d) {return +d.val;})*0.5 ,
                  d3.max(data, function(d) {return +d.val;})]);

        x.range([0,width]);

        xAxis.scale(x);

        //move and draw the axis
        svg.select('.x.axis')
            .attr("transform", "translate(0,"+this.totalheight+")")
            .call(xAxis);
        this.width=width;
    },

    updateYAxis:function(data){
        var y0=this.y0;
        var y1=this.y1;
        var yAxis=this.yAxis;
        var svg = this.svg;

        y0.domain(data.map(function(d){return d.cat;}));
        y1.domain(data.map(function(d){return d.color;}));
        var totalheight = y0.domain().length* y1.domain().length * 18;

        y0.rangeRoundBands([0, totalheight]);
        y1.rangeRoundBands([0, y0.rangeBand()]);
        yAxis.scale(y0);
        svg.select('.y.axis').call(yAxis);

        //enable axis click
        var widget = this;
        svg.select('.y.axis').selectAll('.tick')
            .on('click',function(d){
                var obj = data.filter(function(e){return e.cat==d;})[0];
                //widget.click_callback(obj);
            });

        this.totalheight = totalheight;
        this.margin.left = svg.select('.y.axis').node().getBBox().width+10;
    }
};
<commit_msg>sort labels<commit_after>/*global d3 $ */

function GroupedBarChart(opts, getDataCallback, updateCallback){
    this.getDataCallback=getDataCallback;
    this.updateCallback=updateCallback;

    var name=opts.name;
    var id = "#"+name.replace(/\./g,'\\.');
    var margin = {top: 20, right: 20, bottom: 30, left: 40};

    //Add CSS to the div
    d3.select(id).style({
        "overflow-y":"auto",
        "overflow-x":"hidden"
    });

    //set param
    this.selection = {global:[]};
    if(opts.args){ // set selection from arguments
        this._decodeArgs(opts.args);
    }

    var widget = this;
    //Make draggable and resizable
    d3.select(id).attr("class","resize-drag");

    d3.select(id).on("divresize",function(){
        widget.update();
    });

    //Collapse on dbl click
    d3.select(id).on('dblclick',function(d){
        var currentheight = d3.select(id).style("height");
        if ( currentheight != "20px"){
            widget.restoreHeight =currentheight ;
            d3.select(id).style('height','20px');
        }
        else{
            d3.select(id).style("height",widget.restoreHeight);
        }
    });

    //SVG container
    var svg = d3.select(id).append("svg").append("g");

    //Title
    svg.append("text").attr('y',-5).text(name);

    //Axes
    svg.append("g").attr("class", "y axis")
        .attr("transform", "translate(-3,0)");
    svg.append("g").attr("class", "x axis");

    //Scales
    var y0 = d3.scale.ordinal();
    var y1 = d3.scale.ordinal();
    var x = d3.scale.linear();
    if (opts.logaxis){
        x = d3.scale.log();
    }

    //Axis
    var xAxis = d3.svg.axis();
    var yAxis = d3.svg.axis();

    xAxis.orient("bottom").ticks(3,",.1s");
    yAxis.orient("left");

    //Save vars to "this"
    this.margin = margin;
    this.svg=svg;
    this.y0=y0;
    this.y1=y1;
    this.x=x;
    this.xAxis = xAxis;
    this.yAxis = yAxis;

    this._datasrc = opts.datasrc;
    this._opts = opts;
    this._logaxis = opts.logaxis;
}

GroupedBarChart.prototype = {
    getSelection: function(){
        return this.selection;
    },

    _encodeArgs: function(){
        return JSON.stringify(this.getSelection());
    },

    _decodeArgs: function(s){
        this.selection = JSON.parse(s);
    },

    update: function(){
        var widget = this;
        var promises = {};

        //generate promise for each expr
        for (var d in widget._datasrc){
            if (widget._datasrc[d].disabled){
                continue;
            }
            var p = this.getDataCallback(d);
            for (var k in p){
                promises[k] = p[k];
            }
        }

        var promarray = Object.keys(promises).map(function(k){
            return promises[k];
        });

        var promkeys = Object.keys(promises);
        $.when.apply($,promarray).done(function(){
            var results = arguments;
            var res = {};
            promkeys.forEach(function(d,i){
                res[d] = results[i];
            });

            widget.redraw(res);
        });
    },

    flattenData: function(res){
        var widget = this;
        return Object.keys(res).reduce(function(prev,curr){
            var label = curr.split('-');
            var colormap = widget._datasrc[label[1]].colormap;
            var cidx = Math.floor(colormap.length/2);
            var c = colormap[cidx];

            //Add color
            var row = res[curr].data.map(function(d){
                d.color = c;
                return d;
            });
            return prev.concat(row);
        }, []);
    },

    redraw :function(res){
        var fdata = this.flattenData(res);
        var x =this.x;
        var y0 =this.y0;
        var y1 =this.y1;
        var svg =this.svg;
        var selection = this.selection;

        //svg.on('click', this.click_callback);

        //update the axis and svgframe
        this.updateYAxis(fdata);
        this.updateXAxis(fdata);
        this.updateSVG();

        var widget = this;

        //bind data
        var bars = this.svg.selectAll('.bar').data(fdata);

        function clickFunc(d){
            if(!widget.selection.brush){
                widget.selection.brush = [];
            }

            var idx = widget.selection.brush.findIndex(function(b){
                return (b.cat == d.cat);
            });

            if (idx != -1){
                widget.selection.brush.splice(idx,1);
                }
            else{
                if(d3.event.shiftKey){
                    widget.selection.brush.push({id:d.id, cat:d.cat});
                }
                else{
                    widget.selection.brush = [{id:d.id, cat:d.cat}];
                }
            }

            if(widget.selection.brush.length < 1){
                delete widget.selection.brush;
            }

            widget.update(); //redraw itself
            widget.updateCallback(widget._encodeArgs());
        }

        //append new bars
        bars.enter()
            .append('rect')
            .attr('class', 'bar')
            .on('click', clickFunc)//toggle callback
            .append("svg:title"); //tooltip

        //set shape
        bars.attr('x', 0)
            .attr('y', function(d){return widget.y0(d.cat) + //category
                                   widget.y1(d.color);}) //selection group
            .style('fill', function(d){
                if (!widget.selection.brush || //no selection
                    widget.selection.brush.findIndex(function(b){
                        return (b.cat == d.cat); }) != -1){//in selection
                    return d.color;
                }
                else{
                    return 'gray';
                }
            })
            .attr('height',function(d){ return widget.y1.rangeBand()-1; })
            .transition().duration(500)
            .attr('width',function(d){
                return widget.x(d.val);
            });

        //add tool tip
        bars.select('title').text(function(d){
            return d3.format(',')(d.val);
        });

        //remove bars with no data
        bars.exit().remove();
    },

    updateSVG : function(){
        var svg = this.svg;
        var margin = this.margin;

        var svgframe = d3.select(svg.node().parentNode);
        var rect=svgframe.node().parentNode.getBoundingClientRect();

        //calculate width and height in side the margin
        var width = rect.width-margin.left-margin.right;
        var height = this.totalheight;

        //resize the frame
        svgframe.attr("width", width + margin.left + margin.right);
        svgframe.attr("height", height + margin.top + margin.bottom);

        svg.attr("transform", "translate("+margin.left+","+margin.top+")");

        this.width = width;
        this.height = height;
    },

    updateXAxis: function(data){
        var margin = this.margin;
        var x=this.x;
        var xAxis=this.xAxis;
        var svg=this.svg;

        var svgframe = d3.select(svg.node().parentNode);
        var rect=svgframe.node().parentNode.getBoundingClientRect();
        var width = rect.width - this.margin.left-this.margin.right;

        x.domain([d3.min(data, function(d) {return +d.val;})*0.5 ,
                  d3.max(data, function(d) {return +d.val;})]);

        x.range([0,width]);

        xAxis.scale(x);

        //move and draw the axis
        svg.select('.x.axis')
            .attr("transform", "translate(0,"+this.totalheight+")")
            .call(xAxis);
        this.width=width;
    },

    updateYAxis:function(data){
        var y0=this.y0;
        var y1=this.y1;
        var yAxis=this.yAxis;
        var svg = this.svg;

        y0.domain(data.map(function(d){return d.cat;}).sort(
            function(a,b){
                return a-b;
            }));
        y1.domain(data.map(function(d){return d.color;}));
        var totalheight = y0.domain().length* y1.domain().length * 18;

        y0.rangeRoundBands([0, totalheight]);
        y1.rangeRoundBands([0, y0.rangeBand()]);
        yAxis.scale(y0);
        svg.select('.y.axis').call(yAxis);

        //enable axis click
        var widget = this;
        svg.select('.y.axis').selectAll('.tick')
            .on('click',function(d){
                var obj = data.filter(function(e){return e.cat==d;})[0];
                //widget.click_callback(obj);
            });

        this.totalheight = totalheight;
        this.margin.left = svg.select('.y.axis').node().getBBox().width+10;
    }
};
<|endoftext|>