<commit_before>
import React from 'react'
import {
  HashRouter as Router,
  Route,
  Link,
  matchPath,
  withRouter
} from 'react-router-dom'
import crate from './crate'
import Loading from './Loading'
import { Motion } from '../../src'
import colors from 'open-color'

const WOBBLY_SPRING = { stiffness: 350, damping: 15, precision: 0.1 }

const ApiDocs = crate.asyncCompile({
  loader: () => import('./docs/Api'),
  LoadingComponent: Loading,
  delay: 200
})

const TrippyDemo = crate.asyncCompile({
  loader: () => import('./demos/Trippy'),
  LoadingComponent: Loading,
  delay: 200
})

const ListDemo = crate.asyncCompile({
  loader: () => import('./demos/List'),
  LoadingComponent: Loading,
  delay: 200
})

const HomePage = ({ style }) => {
  return (

data-driven-motion

Easily animate your data in react

          npm install -S data-driven-motion

            <Link to='/demos'>Demos</Link>

<Link to='/docs'>Docs</Link>

              Github

  )
}

const DemosPage = ({ style }) => (

Demos

Trippy Perspective

      <TrippyDemo />

List with multiple layers

      <ListDemo />

)

const AnimationExample = () => (
  <Router>

          <Link to='/'>data-driven-motion</Link>

            <Link to='/demos'>Demos</Link>

<Link to='/docs'>Docs</Link>

              Github

      <AnimatedSwitch style={{ position: 'relative' }}>
        <AnimatedRoute exact path='/' component={HomePage} />
        <AnimatedRoute path='/demos' component={DemosPage} />
        <AnimatedRoute path='/docs' component={ApiDocs} />
      </AnimatedSwitch>

  </Router>
)

const AnimatedSwitch = withRouter(
  class AnimatedSwitch extends React.Component {
    render () {
      const { children, route, style } = this.props
      const location = this.props.location || this.context.route.location
      let match, child
      React.Children.forEach(children, element => {
        if (!React.isValidElement(element)) return

        const { path: pathProp, exact, strict, from } = element.props
        const path = pathProp || from

        if (match == null) {
          child = element
          match = path
            ? matchPath(location.pathname, { path, exact, strict })
            : route.match
        }
      })

      return (
        <Motion
          data={match ? [{ location, match, child }] : []}
          component={
}
          render={(key, data, style) => {
            return React.cloneElement(data.child, {
              key,
              location: data.location,
              computedMatch: data.match,
              style: {
                transform: `translate3d(0, ${style.y}%, 0)`,
                opacity: style.o
              }
            })
          }}
          getKey={({ child, location, match }) => {
            return child.props.getKey // param values used when generating keys
              ? child.props.getKey({ location, match })
              : child.props.path || child.props.from
          }}
          onComponentMount={data => ({ y: 50, o: 0.75 })}
          onRender={(data, i, spring) => ({
            y: spring(0, WOBBLY_SPRING),
            o: spring(1)
          })}
          onRemount={({ data: { child } }) => ({ y: 5, o: 0 })}
          onUnmount={({ data: { child } }, spring) => ({
            y: spring(20, WOBBLY_SPRING),
            o: spring(0)
          })}
        />
      )
    }
  }
)

const AnimatedRoute = ({ component: Component, style, getKey, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props => (
        <Component
          style={{
            position: 'absolute',
            left: 0,
            top: 0,
            height: 'calc(100% - 32px)',
            width: 'calc(100% - 32px)',
            padding: 16,
            ...props.style,
            ...style
          }}
        />
      )}
    />
  )
}

export default AnimationExample
<commit_msg>Load everything at once for now<commit_after>
import React from 'react'
import {
  HashRouter as Router,
  Route,
  Link,
  matchPath,
  withRouter
} from 'react-router-dom'
import crate from './crate'
import Loading from './Loading'
import { Motion } from '../../src'
import colors from 'open-color'
import TrippyDemo from './demos/Trippy'
import ListDemo from './demos/List'

const WOBBLY_SPRING = { stiffness: 350, damping: 15, precision: 0.1 }

const ApiDocs = crate.asyncCompile({
  loader: () => import('./docs/Api'),
  LoadingComponent: Loading,
  delay: 200
})

// const TrippyDemo = crate.asyncCompile({
//   loader: () => import('./demos/Trippy'),
//   LoadingComponent: Loading,
//   delay: 200
// })
//
// const ListDemo = crate.asyncCompile({
//   loader: () => import('./demos/List'),
//   LoadingComponent: Loading,
//   delay: 200
// })

const HomePage = ({ style }) => {
  return (

data-driven-motion

Easily animate your data in react

          npm install -S data-driven-motion

            <Link to='/demos'>Demos</Link>

<Link to='/docs'>Docs</Link>

              Github

  )
}

const DemosPage = ({ style }) => (

Demos

Trippy Perspective

      <TrippyDemo />

List with multiple layers

      <ListDemo />

)

const AnimationExample = () => (
  <Router>

          <Link to='/'>data-driven-motion</Link>

            <Link to='/demos'>Demos</Link>

<Link to='/docs'>Docs</Link>

              Github

      <AnimatedSwitch style={{ position: 'relative' }}>
        <AnimatedRoute exact path='/' component={HomePage} />
        <AnimatedRoute path='/demos' component={DemosPage} />
        <AnimatedRoute path='/docs' component={ApiDocs} />
      </AnimatedSwitch>

  </Router>
)

const AnimatedSwitch = withRouter(
  class AnimatedSwitch extends React.Component {
    render () {
      const { children, route, style } = this.props
      const location = this.props.location || this.context.route.location
      let match, child
      React.Children.forEach(children, element => {
        if (!React.isValidElement(element)) return

        const { path: pathProp, exact, strict, from } = element.props
        const path = pathProp || from

        if (match == null) {
          child = element
          match = path
            ? matchPath(location.pathname, { path, exact, strict })
            : route.match
        }
      })

      return (
        <Motion
          data={match ? [{ location, match, child }] : []}
          component={
}
          render={(key, data, style) => {
            return React.cloneElement(data.child, {
              key,
              location: data.location,
              computedMatch: data.match,
              style: {
                transform: `translate3d(0, ${style.y}%, 0)`,
                opacity: style.o
              }
            })
          }}
          getKey={({ child, location, match }) => {
            return child.props.getKey // param values used when generating keys
              ? child.props.getKey({ location, match })
              : child.props.path || child.props.from
          }}
          onComponentMount={data => ({ y: 50, o: 0.75 })}
          onRender={(data, i, spring) => ({
            y: spring(0, WOBBLY_SPRING),
            o: spring(1)
          })}
          onRemount={({ data: { child } }) => ({ y: 5, o: 0 })}
          onUnmount={({ data: { child } }, spring) => ({
            y: spring(20, WOBBLY_SPRING),
            o: spring(0)
          })}
        />
      )
    }
  }
)

const AnimatedRoute = ({ component: Component, style, getKey, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props => (
        <Component
          style={{
            position: 'absolute',
            left: 0,
            top: 0,
            height: 'calc(100% - 32px)',
            width: 'calc(100% - 32px)',
            padding: 16,
            ...props.style,
            ...style
          }}
        />
      )}
    />
  )
}

export default AnimationExample
<|endoftext|>


<commit_before>import React from 'react';
import {Navbar, Nav} from 'react-bootstrap';
import {Router} from './Router.js';
import Logo from './logo.svg';
import './App.css';

/**
 * @return {!JSX} Wrapper component that wraps the entire site with
 *     common components such as a header, navigation, and shopping cart.
 */
export function App() {
  return (

      <Navbar bg="light" className="px-lg-4" variant="light">
        <Navbar.Brand href="/">

          Prints of Poe
        </Navbar.Brand>

          Home
          About

            <svg className="shopping-cart" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
              <path
                fillRule="evenodd"
                // eslint-disable-next-line max-len
                d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm7 0a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"/>
            </svg>

      </Navbar>
      <Router/>

  );
}
<commit_msg>Add alt text to img tag<commit_after>import React from 'react';
import {Navbar, Nav} from 'react-bootstrap';
import {Router} from './Router.js';
import Logo from './logo.svg';
import './App.css';

/**
 * @return {!JSX} Wrapper component that wraps the entire site with
 *     common components such as a header, navigation, and shopping cart.
 */
export function App() {
  return (

      <Navbar bg="light" className="px-lg-4" variant="light">
        <Navbar.Brand href="/">

          Prints of Poe
        </Navbar.Brand>

          Home
          About

            <svg className="shopping-cart" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
              <path
                fillRule="evenodd"
                // eslint-disable-next-line max-len
                d="M0 1.5A.5.5 0 0 1 .5 1H2a.5.5 0 0 1 .485.379L2.89 3H14.5a.5.5 0 0 1 .491.592l-1.5 8A.5.5 0 0 1 13 12H4a.5.5 0 0 1-.491-.408L2.01 3.607 1.61 2H.5a.5.5 0 0 1-.5-.5zM3.102 4l1.313 7h8.17l1.313-7H3.102zM5 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm7 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4zm-7 1a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm7 0a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"/>
            </svg>

      </Navbar>
      <Router/>

  );
}
<|endoftext|>


<commit_before>(function (window, document) { // eslint-disable-line no-unused-vars
  'use strict';
  var gapi = window.gapi;
  var lima = window.lima;
  var _ = lima._;  // underscore symbol is used for brevity, defined in tools.js

  var CLIENT_ID = "358237292980-kbme56c9ih4rpmob16sq8bjig5dms6pl.apps.googleusercontent.com";

  function onSignIn(googleUser) {
    if (!googleUser.isSignedIn()) {
      _.removeClass('body', 'signed-on');
      return;
    }

    // check if we should redirect to the /register page - if LiMA doesn't know the user who has just logged in
    // if the user has canceled registration by leaving the page, we will sign them out
    if (window.location.pathname != '/register') {
      var idToken = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().id_token;
      fetch('/api/user', {
        method: 'GET',
        headers: _.idTokenToFetchHeaders(idToken),
      })
      .then(function (res) {
        if (res.status == 401) {
          if (localStorage.limaUnfinishedRegistration) {
            // we've already been to the registration page and we left it, so sign out instead of redirecting
            gapi.auth2.getAuthInstance().signOut();
            delete localStorage.limaUnfinishedRegistration;
          } else {
            // user isn't known but someone is signed in. Save and then redirect to register.
            if (lima.userLocalStorage) _.manualSave();
            window.location.href = '/register';
            // don't call any more listeners
            onSignInListeners = [];
          }
        } else if (res.status >= 400) {
          // an unexpected error happened with /api/user, server not happy
          _.apiFail();
        } else {
          return _.fetchJson(res);
        }
      })
      .then(function(user) {
        if (!user) return;

        _.addClass('body', 'signed-on');
        _.fillEls('.userinfo .username', user.username || user.email);
        _.findEls('.userinfo .userphoto').forEach(function(el){
          if (!el.dataset.origsrc) el.dataset.origsrc = el.src;
          if (user.photos[0]) el.src = user.photos[0].value;
        });
      })
      .catch(function (err) {
        console.log(err);
      });
    }

    onSignInListeners.forEach(function (cb) { cb(); });
  }

  lima.getAuthenticatedUserEmail = function getAuthenticatedUserEmail() {
    try {
      if (window.gapi.auth2.getAuthInstance().isSignedIn.get()) {
        return window.gapi.auth2.getAuthInstance().currentUser.get().getBasicProfile().getEmail();
      }
    } catch (e) {console.info(e);} // any errors mean no current user
    return null;
  };

  var toggleButton = _.byId('toggle-editing');

  lima.toggleEditing = function (val) {
    if (val == null) {
      lima.editing = localStorage.limaEditing !== 'false';
    } else {
      localStorage.limaEditing = lima.editing = val;
    }

    document.body.classList.toggle('editing', !!lima.editing);
  };

  if (toggleButton) {
    lima.toggleEditing();
    toggleButton.addEventListener('click', function () {
      lima.toggleEditing(!lima.editing);
      if (lima.updateView) lima.updateView();
    });
  }

  function signOut() {
    // if there are unsaved changes when the user presses sign out,
    // that likely means they want to go and haven't thought of the save delay, so save right now
    _.manualSave()
    .catch(function () {
      var doSignOut = window.confirm('Save failed before signing out,\ndo you still wish to sign out AND lose your changes?');
      if (!doSignOut) return Promise.reject('sign out aborted by user');
    })
    .then(function() {
      gapi.auth2.getAuthInstance().signOut().then(
        function () {
          _.findEls('.userinfo .userphoto').forEach(function(el){
            if (el.dataset.origsrc) el.src = el.dataset.origsrc;
          });
          onSignInListeners.forEach(function (cb) { cb(); });
        },
        function (err) {
          console.log('error signing out');
          console.log(err);
        });
    });
  }

  /*
   * Retrieve (and possibly refresh) the ID token from Google Auth, as a Promise.
   * May resolve to `null` when no user is signed in.
   */

  var pendingToken = null;

  lima.getGapiIDToken = function getGapiIDToken() {
    if (pendingToken) return pendingToken;

    var token = pendingToken = new Promise(function (resolve, reject) {
      var currUser = gapi.auth2.getAuthInstance().currentUser.get();
      if (!currUser.isSignedIn()) {
        resolve(null);
        return;
      }
      var authResp = currUser.getAuthResponse();
      if (Date.now() < authResp.expires_at - 120000) {
        resolve(authResp.id_token);
      } else {
        // if the token is expired, or within two minutes of expiring, refresh it
        console.log('refreshing id token');
        currUser.reloadAuthResponse().then(
          function fulfilled() {
            authResp = currUser.getAuthResponse();
            resolve(authResp.id_token);
          },
          function rejected(reason) {
            console.error('error refreshing id token');
            console.error(reason);
            reject(reason);
          }
        );
      }
    });

    token.then(clearPendingToken, clearPendingToken);

    return token;
  };

  function clearPendingToken() {
    pendingToken = null;
  }

// todo distinguish initPage and gapiReady somehow because we can have a token already cached (localStroage)
// add param to getGapiIDToken to force immediate return of no token if none is available
// add whenGapiAuth2IsReady(fn)?
// because currently it takes a lot of time for the page to start touching the API and loading real stuff

  gapi.load('auth2', function() {
    gapi.auth2.init({client_id: CLIENT_ID });
    gapi.auth2.getAuthInstance().then(
      function (gauth) {
        gauth.currentUser.listen(onSignIn);
        _.findEls('a.signout').forEach(function (el){el.addEventListener('click', signOut);});
        if (gauth.isSignedIn.get()) onSignIn(gauth.currentUser.get());
        try {
          if (lima.initPage) lima.initPage();
        } catch (e) {
          console.error(e);
          _.apiFail();
        }
      },
      function (err) {
        console.log('failed getting gapi auth instance');
        console.log(err);
      });
  });

  var onSignInListeners = [];

  lima.onSignInChange = function (cb) {
    if (onSignInListeners.indexOf(cb) === -1) onSignInListeners.push(cb);
  };

})(window, document);
<commit_msg>:wrench: updated front end oauth id<commit_after>(function (window, document) { // eslint-disable-line no-unused-vars
  'use strict';
  var gapi = window.gapi;
  var lima = window.lima;
  var _ = lima._;  // underscore symbol is used for brevity, defined in tools.js

  var CLIENT_ID = "760012515336-d7mher4ga5qjql29n76ettedogdhbpqh.apps.googleusercontent.com";

  function onSignIn(googleUser) {
    if (!googleUser.isSignedIn()) {
      _.removeClass('body', 'signed-on');
      return;
    }

    // check if we should redirect to the /register page - if LiMA doesn't know the user who has just logged in
    // if the user has canceled registration by leaving the page, we will sign them out
    if (window.location.pathname != '/register') {
      var idToken = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse().id_token;
      fetch('/api/user', {
        method: 'GET',
        headers: _.idTokenToFetchHeaders(idToken),
      })
      .then(function (res) {
        if (res.status == 401) {
          if (localStorage.limaUnfinishedRegistration) {
            // we've already been to the registration page and we left it, so sign out instead of redirecting
            gapi.auth2.getAuthInstance().signOut();
            delete localStorage.limaUnfinishedRegistration;
          } else {
            // user isn't known but someone is signed in. Save and then redirect to register.
            if (lima.userLocalStorage) _.manualSave();
            window.location.href = '/register';
            // don't call any more listeners
            onSignInListeners = [];
          }
        } else if (res.status >= 400) {
          // an unexpected error happened with /api/user, server not happy
          _.apiFail();
        } else {
          return _.fetchJson(res);
        }
      })
      .then(function(user) {
        if (!user) return;

        _.addClass('body', 'signed-on');
        _.fillEls('.userinfo .username', user.username || user.email);
        _.findEls('.userinfo .userphoto').forEach(function(el){
          if (!el.dataset.origsrc) el.dataset.origsrc = el.src;
          if (user.photos[0]) el.src = user.photos[0].value;
        });
      })
      .catch(function (err) {
        console.log(err);
      });
    }

    onSignInListeners.forEach(function (cb) { cb(); });
  }

  lima.getAuthenticatedUserEmail = function getAuthenticatedUserEmail() {
    try {
      if (window.gapi.auth2.getAuthInstance().isSignedIn.get()) {
        return window.gapi.auth2.getAuthInstance().currentUser.get().getBasicProfile().getEmail();
      }
    } catch (e) {console.info(e);} // any errors mean no current user
    return null;
  };

  var toggleButton = _.byId('toggle-editing');

  lima.toggleEditing = function (val) {
    if (val == null) {
      lima.editing = localStorage.limaEditing !== 'false';
    } else {
      localStorage.limaEditing = lima.editing = val;
    }

    document.body.classList.toggle('editing', !!lima.editing);
  };

  if (toggleButton) {
    lima.toggleEditing();
    toggleButton.addEventListener('click', function () {
      lima.toggleEditing(!lima.editing);
      if (lima.updateView) lima.updateView();
    });
  }

  function signOut() {
    // if there are unsaved changes when the user presses sign out,
    // that likely means they want to go and haven't thought of the save delay, so save right now
    _.manualSave()
    .catch(function () {
      var doSignOut = window.confirm('Save failed before signing out,\ndo you still wish to sign out AND lose your changes?');
      if (!doSignOut) return Promise.reject('sign out aborted by user');
    })
    .then(function() {
      gapi.auth2.getAuthInstance().signOut().then(
        function () {
          _.findEls('.userinfo .userphoto').forEach(function(el){
            if (el.dataset.origsrc) el.src = el.dataset.origsrc;
          });
          onSignInListeners.forEach(function (cb) { cb(); });
        },
        function (err) {
          console.log('error signing out');
          console.log(err);
        });
    });
  }

  /*
   * Retrieve (and possibly refresh) the ID token from Google Auth, as a Promise.
   * May resolve to `null` when no user is signed in.
   */

  var pendingToken = null;

  lima.getGapiIDToken = function getGapiIDToken() {
    if (pendingToken) return pendingToken;

    var token = pendingToken = new Promise(function (resolve, reject) {
      var currUser = gapi.auth2.getAuthInstance().currentUser.get();
      if (!currUser.isSignedIn()) {
        resolve(null);
        return;
      }
      var authResp = currUser.getAuthResponse();
      if (Date.now() < authResp.expires_at - 120000) {
        resolve(authResp.id_token);
      } else {
        // if the token is expired, or within two minutes of expiring, refresh it
        console.log('refreshing id token');
        currUser.reloadAuthResponse().then(
          function fulfilled() {
            authResp = currUser.getAuthResponse();
            resolve(authResp.id_token);
          },
          function rejected(reason) {
            console.error('error refreshing id token');
            console.error(reason);
            reject(reason);
          }
        );
      }
    });

    token.then(clearPendingToken, clearPendingToken);

    return token;
  };

  function clearPendingToken() {
    pendingToken = null;
  }

// todo distinguish initPage and gapiReady somehow because we can have a token already cached (localStroage)
// add param to getGapiIDToken to force immediate return of no token if none is available
// add whenGapiAuth2IsReady(fn)?
// because currently it takes a lot of time for the page to start touching the API and loading real stuff

  gapi.load('auth2', function() {
    gapi.auth2.init({client_id: CLIENT_ID });
    gapi.auth2.getAuthInstance().then(
      function (gauth) {
        gauth.currentUser.listen(onSignIn);
        _.findEls('a.signout').forEach(function (el){el.addEventListener('click', signOut);});
        if (gauth.isSignedIn.get()) onSignIn(gauth.currentUser.get());
        try {
          if (lima.initPage) lima.initPage();
        } catch (e) {
          console.error(e);
          _.apiFail();
        }
      },
      function (err) {
        console.log('failed getting gapi auth instance');
        console.log(err);
      });
  });

  var onSignInListeners = [];

  lima.onSignInChange = function (cb) {
    if (onSignInListeners.indexOf(cb) === -1) onSignInListeners.push(cb);
  };

})(window, document);
<|endoftext|>


<commit_before>
var findById = function(id) {
    return document.getElementById(id);
};

var table = {};

var table_row = function (table_body, data) {
    var body = table_body;
    var t_row = data;
    var row = document.createElement("tr");
    for (var i=0; i<data.length; i++) {
        var td = document.createElement("td");
        var text_node = document.createTextNode(data[i]);
        td.appendChild(text_node);
        row.appendChild(td);
    }
    row.onclick = function () { alert(data[0]); };
    body.appendChild(row);
    return function() {
            var parent_body = table_body ;
            var data_row = data;
            var elem = row;
    };
};

var clear_child = function (node) {
    while (node.lastChild)
        node.removeChild(node.lastChild);
};

var initTable = function () {
    table.id = "scoreboard_table";
    table.elem = findById(table.id);
    table.header = table.elem.childNodes[1];
    table.body = table.elem.childNodes[3];
	table.rows = [];
    table.clear = function () {
        //alert(this.id);
		this.rows.length = 0;
        clear_child(table.body);
        console.log(this.id);
    };
    table.addRow = function(data) {
       //alert(data[0]);
       var tRow = table_row(table.body, data);
       this.rows.push(tRow);
       console.log(data[0]);
    };
};

var initApplication = function () {
    var btn = document.getElementById("genButton");
    initTable();
    btn.onclick = function () {
        var rows = parseInt(findById("rowNum").value, 10);
        if (isNaN(rows)) return;
        if (rows <= 0) return;
        table.clear();
        for (var i = 0; i < rows; i++)
            table.addRow(["Name " + (i + 1), "p1", "p2", "p3"]);
    };
};

document.onreadystatechange = function() {
    if (document.readyState != "complete") return;
    initApplication();
};

<commit_msg>refactored anim.js<commit_after>
// UTILS
var clear_child = function (node) {
    while (node.lastChild)
        node.removeChild(node.lastChild);
};

var findById = function(id) {
    return document.getElementById(id);
};

// main objects
var table = {};

// creating new row object and linking to the table
// it also links the onclick event
var table_row = function (table_body, data) {
    var body = table_body;
    var t_row = data;
    var row = document.createElement("tr");
    for (var i=0; i<data.length; i++) {
        var td = document.createElement("td");
        var text_node = document.createTextNode(data[i]);
        td.appendChild(text_node);
        row.appendChild(td);
    }
    row.onclick = function () { alert(data[0]); };
    body.appendChild(row);
    return function() {
            var parent_body = table_body ;
            var data_row = data;
            var elem = row;
    };
};
// initialize table object and sets the references with the
// actual HTML table

var initTable = function () {
    table.id = "scoreboard_table";
    table.elem = findById(table.id);
    table.header = table.elem.childNodes[1];
    table.body = table.elem.childNodes[3];
	table.rows = [];
    table.clear = function () {
        //alert(this.id);
		this.rows.length = 0;
        clear_child(table.body);
        console.log(this.id);
    };
    table.addRow = function(data) {
       //alert(data[0]);
       var tRow = table_row(table.body, data);
       this.rows.push(tRow);
       console.log(data[0]);
    };
};

// EntryPoint
var initApplication = function () {
    var btn = document.getElementById("genButton");
    initTable();
    // mock to create random data when the button genButton is
    // pressed
    btn.onclick = function () {
        var rows = parseInt(findById("rowNum").value, 10);
        if (isNaN(rows)) return;
        if (rows <= 0) return;
        table.clear();
        for (var i = 0; i < rows; i++)
            table.addRow(["Name " + (i + 1), "p1", "p2", "p3"]);
    };
};

document.onreadystatechange = function() {
    if (document.readyState != "complete") return;
    initApplication();
};

<|endoftext|>


<commit_before>/* globals describe, it, expect, expectObservable, expectSubscriptions, cold, hot */
var Rx = require('../../dist/cjs/Rx');
var Observable = Rx.Observable;

describe('Observable.prototype.defaultIfEmpty()', function () {
  it('should return the argument if Observable is empty', function () {
    var e1 =  cold('|');
    var e1subs =   '(^!)';
    var expected = '(x|)';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return null if the Observable is empty and no arguments', function () {
    var e1 =  cold('|');
    var e1subs =   '(^!)';
    var expected = '(x|)';

    expectObservable(e1.defaultIfEmpty()).toBe(expected, { x: null });
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return the Observable if not empty with a default value', function () {
    var e1 =   hot('--a--b--|');
    var e1subs =   '^       !';
    var expected = '--a--b--|';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return the Observable if not empty with no default value', function () {
    var e1 =   hot('--a--b--|');
    var e1subs =   '^       !';
    var expected = '--a--b--|';

    expectObservable(e1.defaultIfEmpty()).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should error if the Observable errors', function () {
    var e1 =  cold('#');
    var e1subs =   '(^!)';
    var expected = '#';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });
});<commit_msg>test(defaultIfEmpty): add standard asDiagram test for defaultIfEmpty<commit_after>/* globals describe, it, expect, expectObservable, expectSubscriptions, cold, hot */
var Rx = require('../../dist/cjs/Rx');
var Observable = Rx.Observable;

describe('Observable.prototype.defaultIfEmpty()', function () {
  it.asDiagram('defaultIfEmpty(\'x\')')('should return the argument if the Observable eventually completes empty', function () {
    var e1 =   hot('--------|   ');
    var e1subs =   '^       !   ';
    var expected = '--------(x|)';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return the argument if Observable is empty', function () {
    var e1 =  cold('|');
    var e1subs =   '(^!)';
    var expected = '(x|)';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return null if the Observable is empty and no arguments', function () {
    var e1 =  cold('|');
    var e1subs =   '(^!)';
    var expected = '(x|)';

    expectObservable(e1.defaultIfEmpty()).toBe(expected, { x: null });
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return the Observable if not empty with a default value', function () {
    var e1 =   hot('--a--b--|');
    var e1subs =   '^       !';
    var expected = '--a--b--|';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should return the Observable if not empty with no default value', function () {
    var e1 =   hot('--a--b--|');
    var e1subs =   '^       !';
    var expected = '--a--b--|';

    expectObservable(e1.defaultIfEmpty()).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });

  it('should error if the Observable errors', function () {
    var e1 =  cold('#');
    var e1subs =   '(^!)';
    var expected = '#';

    expectObservable(e1.defaultIfEmpty('x')).toBe(expected);
    expectSubscriptions(e1.subscriptions).toBe(e1subs);
  });
});<|endoftext|>


<commit_before>/*!
 * VIZABI POP BY AGE Component
 */

(function () {

  "use strict";

  var Vizabi = this.Vizabi;
  var utils = Vizabi.utils;

  //warn client if d3 is not defined
  if (!Vizabi._require('d3')) return;

  //POP BY AGE CHART COMPONENT
  Vizabi.Component.extend('gapminder-popbyage', {

    /**
     * Initializes the component (Bar Chart).
     * Executed once before any template is rendered.
     * @param {Object} config The options passed to the component
     * @param {Object} context The component's parent
     */
    init: function (config, context) {
      this.name = 'popbyage';
      this.template = 'src/tools/popbyage/popbyage.html';

      //define expected models for this component
      this.model_expects = [{
        name: "time",
        type: "time"
      }, {
        name: "entities",
        type: "entities"
      }, {
        name: "age",
        type: "entities"
      },{
        name: "marker",
        type: "model"
      }, {
        name: "language",
        type: "language"
      }];

      var _this = this;
      this.model_binds = {
        "change:time:value": function (evt) {
          _this._updateEntities();
        },
        "change:entities:show": function (evt) {
          console.log('Trying to change show');
        },
        "change:age:select": function (evt) {
          _this._selectBars();
        }
      };

      //contructor is the same as any component
      this._super(config, context);

      this.xScale = null;
      this.yScale = null;
      this.cScale = d3.scale.category10();

      this.xAxis = d3.svg.axisSmart();
      this.yAxis = d3.svg.axisSmart();
    },

    /**
     * DOM is ready
     */
    readyOnce: function () {

      this.element = d3.select(this.element);

      this.graph = this.element.select('.vzb-bc-graph');
      this.yAxisEl = this.graph.select('.vzb-bc-axis-y');
      this.xAxisEl = this.graph.select('.vzb-bc-axis-x');
      this.yTitleEl = this.graph.select('.vzb-bc-axis-y-title');
      this.bars = this.graph.select('.vzb-bc-bars');
      this.labels = this.graph.select('.vzb-bc-labels');

      this.title = this.element.select('.vzb-bc-title');
      this.year = this.element.select('.vzb-bc-year');

      //only allow selecting one at a time
      this.model.age.selectMultiple(false);

      var _this = this;
      this.on("resize", function () {
        _this._updateEntities();
      });
    },

    /*
     * Both model and DOM are ready
     */
    ready: function () {

      this.AGEDIM = this.model.age.getDimension();
      this.TIMEDIM = this.model.time.getDimension();

      this.timeFormatter = d3.time.format(this.model.time.formatOutput);

      this.updateUIStrings();
      this._updateIndicators();
      this.resize();
      this._updateEntities();
      this._updateEntities();
    },

    updateUIStrings: function(){
      this.translator = this.model.language.getTFunction();

      var titleStringY = this.translator("indicator/" + this.model.marker.axis_y.which);

      var yTitle = this.yTitleEl.selectAll("text").data([0]);
      yTitle.enter().append("text");
      yTitle
        .attr("y", "-6px")
        .attr("x", "-9px")
        .attr("dx", "-0.72em")
        .text(titleStringY);
    },

    /**
     * Changes labels for indicators
     */
    _updateIndicators: function () {
      var _this = this;
      this.duration = this.model.time.speed;

      this.yScale = this.model.marker.axis_y.getScale(false);
      this.xScale = this.model.marker.axis_x.getScale(false);
      this.cScale = this.model.marker.color.getScale();

      this.yAxis.tickFormat(_this.model.marker.axis_y.tickFormatter);
      this.xAxis.tickFormat(_this.model.marker.axis_x.tickFormatter);
    },

    /**
     * Updates entities
     */
    _updateEntities: function () {

      var _this = this;
      var time = this.model.time;
      var timeFormatter = d3.time.format(this.model.time.formatInput);
      var ageDim = this.AGEDIM;
      var timeDim = this.TIMEDIM;
      var duration = (time.playing) ? time.speed : 0;
      var filter = {};
      filter[timeDim] = time.value;
      var items = this.model.marker.getKeys(filter);
      var values = this.model.marker.getValues(filter, [ageDim]);

      //TODO: this should be done at a data layer
      //Year Grouping

      var test = function(d) {
        return parseInt(d, 10) % group_by === 1;
      }

      var group_by = this.model.marker.group_by;
      if(group_by > 1) {
        items = items.filter(function(d) {
          return test(d[ageDim]);
        });

        var new_values = {};
        utils.forEach(values, function(hook, hook_name) {
          new_values[hook_name] = {};
          var hook_values = new_values[hook_name];
          var curr = false;
          utils.forEach(hook, function(val, key) {
            if(test(key) || curr === false) {
              curr = key;
              hook_values[curr] = val;
            }
            //if it's a number and axis x
            if(!utils.isNaN(val) && hook_name === "axis_x") {
              hook_values[curr] = parseFloat(hook_values[curr]) + parseFloat(val);
            }
          });

        });

        values = new_values;

      }

      //End Year Grouping

      this.model.age.setVisible(items);

      this.entityBars = this.bars.selectAll('.vzb-bc-bar')
        .data(items);

      this.entityLabels = this.labels.selectAll('.vzb-bc-label')
        .data(items);

      //exit selection
      this.entityBars.exit().remove();
      this.entityLabels.exit().remove();

      var highlight = this._highlightBar.bind(this);
      var unhighlight = this._unhighlightBars.bind(this)

      //enter selection -- init bars
      this.entityBars.enter().append("g")
          .attr("class", "vzb-bc-bar")
          .attr("id", function(d) {
            return  "vzb-bc-bar-"+d[ageDim];
          })
          .on("mousemove", highlight)
          .on("mouseout", unhighlight)
          .on("click", function (d, i) {
            _this.model.age.selectEntity(d);
          })
          .append('rect');

      this.entityLabels.enter().append("g")
          .attr("class", "vzb-bc-label")
          .attr("id", function(d) {
            return  "vzb-bc-label-"+d[ageDim];
          })
          .on("mousemove", highlight)
          .on("mouseout", unhighlight)
          .append('text')
          .attr("class", "vzb-bc-age");

      var barWidth = this.height / items.length;

      this.bars.selectAll('.vzb-bc-bar > rect')
        .attr("fill", function (d) {
          return _this.cScale(values.color[d[ageDim]]);
        })
        .style("stroke", function (d) {
          return _this.cScale(values.color[d[ageDim]]);
        })
        .attr("x", 0)
        .transition().duration(duration).ease("linear")
        .attr("y", function (d) {
          return _this.yScale(values.axis_y[d[ageDim]]) - barWidth;
        })
        .attr("height", barWidth)
        .attr("width", function (d) {
          return _this.xScale(values.axis_x[d[ageDim]]);
        });

      this.labels.selectAll('.vzb-bc-label > .vzb-bc-age')
               .text(function(d) {
                  var formatter = _this.model.marker.axis_x.tickFormatter;
                  var yearOldsIn = _this.translator("popbyage/yearOldsIn");

                  var age = parseInt(values.axis_y[d[ageDim]],10);

                  if(group_by > 1) {
                    age = age + "-to-" + (age + group_by - 1);
                  }

                  return age + yearOldsIn+" "+timeFormatter(time.value) + ": "+formatter(values.axis_x[d[ageDim]]);
               })
               .attr("x", 7)
               .attr("y", function (d) {
                  return _this.yScale(values.axis_y[d[ageDim]]) - barWidth - 10;
               })
               .style("fill", function (d) {
                  var color = _this.cScale(values.color[d[ageDim]]);
                  return d3.rgb(color).darker(2);
               });

      var label = utils.values(values.label_name).reverse()[0]; //get last name

      //TODO: remove hack
      label = label === "usa" ? "United States" : "Sweden";

      this.title.text(label);

      this.year.text(this.timeFormatter(this.model.time.value));

      //update x axis again
      //TODO: remove this when grouping is done at data level
      var x_domain = this.xScale.domain();
      var x_domain_max = d3.max(utils.values(values.axis_x));
      this.xScale = this.xScale.domain([x_domain[0], x_domain_max]);
      this.resize();

    },

    /**
     * Highlight and unhighlight labels
     */
    _unhighlightBars: function() {
      this.bars.classed('vzb-dimmed', false);
      this.bars.selectAll('.vzb-bc-bar.vzb-hovered').classed('vzb-hovered', false);
      this.labels.selectAll('.vzb-hovered').classed('vzb-hovered', false);
    },

    _highlightBar: function(d) {
      this.bars.classed('vzb-dimmed', true);
      var curr =  this.bars.select("#vzb-bc-bar-"+d[this.AGEDIM]);
      curr.classed('vzb-hovered', true);
      var label = this.labels.select("#vzb-bc-label-"+d[this.AGEDIM]);
      label.classed('vzb-hovered', true);
    },

    /**
     * Select Entities
     */
    _selectBars: function() {
      var _this = this;
      var AGEDIM = this.AGEDIM;
      var selected = this.model.age.select;

      this._unselectBars();

      if(selected.length) {
        this.bars.classed('vzb-dimmed-selected', true);
        utils.forEach(selected, function(s) {
          _this.bars.select("#vzb-bc-bar-"+s[AGEDIM]).classed('vzb-selected', true);
          _this.labels.select("#vzb-bc-label-"+s[AGEDIM]).classed('vzb-selected', true);
        });
      }
    },

    _unselectBars: function() {
      this.bars.classed('vzb-dimmed-selected', false);
      this.bars.selectAll('.vzb-bc-bar.vzb-selected').classed('vzb-selected', false);
      this.labels.selectAll('.vzb-selected').classed('vzb-selected', false);
    },

    /**
     * Executes everytime the container or vizabi is resized
     * Ideally,it contains only operations related to size
     */
    resize: function () {

      var _this = this;

      this.profiles = {
        "small": {
          margin: {
            top: 70,
            right: 20,
            left: 40,
            bottom: 40
          },
          minRadius: 2,
          maxRadius: 40
        },
        "medium": {
          margin: {
            top: 80,
            right: 60,
            left: 60,
            bottom: 40
          },
          minRadius: 3,
          maxRadius: 60
        },
        "large": {
          margin: {
            top: 100,
            right: 60,
            left: 60,
            bottom: 40
          },
          minRadius: 4,
          maxRadius: 80
        }
      };

      this.activeProfile = this.profiles[this.getLayoutProfile()];
      var margin = this.activeProfile.margin;

      //stage
      this.height = parseInt(this.element.style("height"), 10) - margin.top - margin.bottom;
      this.width = parseInt(this.element.style("width"), 10) - margin.left - margin.right;

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

      //update scales to the new range
      if (this.model.marker.axis_y.scaleType !== "ordinal") {
        this.yScale.range([this.height, 0]);
      } else {
        this.yScale.rangePoints([this.height, 0]).range();
      }
      if (this.model.marker.axis_x.scaleType !== "ordinal") {
        this.xScale.range([0, this.width]);
      } else {
        this.xScale.rangePoints([0, this.width]).range();
      }

      //apply scales to axes and redraw
      this.yAxis.scale(this.yScale)
        .orient("left")
        .tickSize(6, 0)
        .tickSizeMinor(3, 0)
        .labelerOptions({
          scaleType: this.model.marker.axis_y.scaleType,
          toolMargin: margin,
          limitMaxTickNumber: 6
        });

      this.xAxis.scale(this.xScale)
        .orient("bottom")
        .tickSize(6, 0)
        .tickSizeMinor(3, 0)
        .labelerOptions({
          scaleType: this.model.marker.axis_x.scaleType,
          toolMargin: margin,
          limitMaxTickNumber: 6
        });

      this.xAxisEl.attr("transform", "translate(0," + this.height + ")")
        .call(this.xAxis);

      this.yAxisEl.call(this.yAxis);
      this.xAxisEl.call(this.xAxis);

      this.title.attr('x', margin.right).attr('y', margin.top/2);

      this.year.attr('x', this.width + margin.left).attr('y', margin.top/2);

    }
  });

}).call(this);
<commit_msg>Fix values for x-scale<commit_after>/*!
 * VIZABI POP BY AGE Component
 */

(function () {

  "use strict";

  var Vizabi = this.Vizabi;
  var utils = Vizabi.utils;

  //warn client if d3 is not defined
  if (!Vizabi._require('d3')) return;

  //POP BY AGE CHART COMPONENT
  Vizabi.Component.extend('gapminder-popbyage', {

    /**
     * Initializes the component (Bar Chart).
     * Executed once before any template is rendered.
     * @param {Object} config The options passed to the component
     * @param {Object} context The component's parent
     */
    init: function (config, context) {
      this.name = 'popbyage';
      this.template = 'src/tools/popbyage/popbyage.html';

      //define expected models for this component
      this.model_expects = [{
        name: "time",
        type: "time"
      }, {
        name: "entities",
        type: "entities"
      }, {
        name: "age",
        type: "entities"
      },{
        name: "marker",
        type: "model"
      }, {
        name: "language",
        type: "language"
      }];

      var _this = this;
      this.model_binds = {
        "change:time:value": function (evt) {
          _this._updateEntities();
        },
        "change:entities:show": function (evt) {
          console.log('Trying to change show');
        },
        "change:age:select": function (evt) {
          _this._selectBars();
        }
      };

      //contructor is the same as any component
      this._super(config, context);

      this.xScale = null;
      this.yScale = null;
      this.cScale = d3.scale.category10();

      this.xAxis = d3.svg.axisSmart();
      this.yAxis = d3.svg.axisSmart();
    },

    /**
     * DOM is ready
     */
    readyOnce: function () {

      this.element = d3.select(this.element);

      this.graph = this.element.select('.vzb-bc-graph');
      this.yAxisEl = this.graph.select('.vzb-bc-axis-y');
      this.xAxisEl = this.graph.select('.vzb-bc-axis-x');
      this.yTitleEl = this.graph.select('.vzb-bc-axis-y-title');
      this.bars = this.graph.select('.vzb-bc-bars');
      this.labels = this.graph.select('.vzb-bc-labels');

      this.title = this.element.select('.vzb-bc-title');
      this.year = this.element.select('.vzb-bc-year');

      //only allow selecting one at a time
      this.model.age.selectMultiple(false);

      var _this = this;
      this.on("resize", function () {
        _this._updateEntities();
      });
    },

    /*
     * Both model and DOM are ready
     */
    ready: function () {

      this.AGEDIM = this.model.age.getDimension();
      this.TIMEDIM = this.model.time.getDimension();

      this.timeFormatter = d3.time.format(this.model.time.formatOutput);

      this.updateUIStrings();
      this._updateIndicators();
      this.resize();
      this._updateEntities();
      this._updateEntities();
    },

    updateUIStrings: function(){
      this.translator = this.model.language.getTFunction();

      var titleStringY = this.translator("indicator/" + this.model.marker.axis_y.which);

      var yTitle = this.yTitleEl.selectAll("text").data([0]);
      yTitle.enter().append("text");
      yTitle
        .attr("y", "-6px")
        .attr("x", "-9px")
        .attr("dx", "-0.72em")
        .text(titleStringY);
    },

    /**
     * Changes labels for indicators
     */
    _updateIndicators: function () {
      var _this = this;
      this.duration = this.model.time.speed;

      this.yScale = this.model.marker.axis_y.getScale(false);
      this.xScale = this.model.marker.axis_x.getScale(false);
      this.cScale = this.model.marker.color.getScale();

      this.yAxis.tickFormat(_this.model.marker.axis_y.tickFormatter);
      this.xAxis.tickFormat(_this.model.marker.axis_x.tickFormatter);
    },

    /**
     * Updates entities
     */
    _updateEntities: function () {

      var _this = this;
      var time = this.model.time;
      var timeFormatter = d3.time.format(this.model.time.formatInput);
      var ageDim = this.AGEDIM;
      var timeDim = this.TIMEDIM;
      var duration = (time.playing) ? time.speed : 0;
      var filter = {};
      filter[timeDim] = time.value;
      var items = this.model.marker.getKeys(filter);
      var values = this.model.marker.getValues(filter, [ageDim]);

      //TODO: this should be done at a data layer
      //Year Grouping

      var test = function(d) {
        return parseInt(d, 10) % group_by === 1;
      }

      var group_by = this.model.marker.group_by;
      if(group_by > 1) {
        items = items.filter(function(d) {
          return test(d[ageDim]);
        });

        var new_values = {};
        utils.forEach(values, function(hook, hook_name) {
          new_values[hook_name] = {};
          var hook_values = new_values[hook_name];
          var curr = false;
          utils.forEach(hook, function(val, key) {
            if(test(key) || curr === false) {
              curr = key;
              hook_values[curr] = val;
            }
            //if it's a number and axis x
            if(!utils.isNaN(val) && hook_name === "axis_x") {
              hook_values[curr] = parseFloat(hook_values[curr]) + parseFloat(val);
            }
          });

        });

        values = new_values;

      }

      //End Year Grouping

      this.model.age.setVisible(items);

      this.entityBars = this.bars.selectAll('.vzb-bc-bar')
        .data(items);

      this.entityLabels = this.labels.selectAll('.vzb-bc-label')
        .data(items);

      //exit selection
      this.entityBars.exit().remove();
      this.entityLabels.exit().remove();

      var highlight = this._highlightBar.bind(this);
      var unhighlight = this._unhighlightBars.bind(this)

      //enter selection -- init bars
      this.entityBars.enter().append("g")
          .attr("class", "vzb-bc-bar")
          .attr("id", function(d) {
            return  "vzb-bc-bar-"+d[ageDim];
          })
          .on("mousemove", highlight)
          .on("mouseout", unhighlight)
          .on("click", function (d, i) {
            _this.model.age.selectEntity(d);
          })
          .append('rect');

      this.entityLabels.enter().append("g")
          .attr("class", "vzb-bc-label")
          .attr("id", function(d) {
            return  "vzb-bc-label-"+d[ageDim];
          })
          .on("mousemove", highlight)
          .on("mouseout", unhighlight)
          .append('text')
          .attr("class", "vzb-bc-age");

      var barWidth = this.height / items.length;

      this.bars.selectAll('.vzb-bc-bar > rect')
        .attr("fill", function (d) {
          return _this.cScale(values.color[d[ageDim]]);
        })
        .style("stroke", function (d) {
          return _this.cScale(values.color[d[ageDim]]);
        })
        .attr("x", 0)
        .transition().duration(duration).ease("linear")
        .attr("y", function (d) {
          return _this.yScale(values.axis_y[d[ageDim]]) - barWidth;
        })
        .attr("height", barWidth)
        .attr("width", function (d) {
          return _this.xScale(values.axis_x[d[ageDim]]);
        });

      this.labels.selectAll('.vzb-bc-label > .vzb-bc-age')
               .text(function(d) {
                  var formatter = _this.model.marker.axis_x.tickFormatter;
                  var yearOldsIn = _this.translator("popbyage/yearOldsIn");

                  var age = parseInt(values.axis_y[d[ageDim]],10);

                  if(group_by > 1) {
                    age = age + "-to-" + (age + group_by - 1);
                  }

                  return age + yearOldsIn+" "+timeFormatter(time.value) + ": "+formatter(values.axis_x[d[ageDim]]);
               })
               .attr("x", 7)
               .attr("y", function (d) {
                  return _this.yScale(values.axis_y[d[ageDim]]) - barWidth - 10;
               })
               .style("fill", function (d) {
                  var color = _this.cScale(values.color[d[ageDim]]);
                  return d3.rgb(color).darker(2);
               });

      var label = utils.values(values.label_name).reverse()[0]; //get last name

      //TODO: remove hack
      label = label === "usa" ? "United States" : "Sweden";

      this.title.text(label);

      this.year.text(this.timeFormatter(this.model.time.value));

      //update x axis again
      //TODO: remove this when grouping is done at data level
      var x_domain = this.xScale.domain();
      var x_domain_max = Math.max.apply(null, utils.values(values.axis_x));
      this.xScale = this.xScale.domain([x_domain[0], x_domain_max]);
      this.resize();

    },

    /**
     * Highlight and unhighlight labels
     */
    _unhighlightBars: function() {
      this.bars.classed('vzb-dimmed', false);
      this.bars.selectAll('.vzb-bc-bar.vzb-hovered').classed('vzb-hovered', false);
      this.labels.selectAll('.vzb-hovered').classed('vzb-hovered', false);
    },

    _highlightBar: function(d) {
      this.bars.classed('vzb-dimmed', true);
      var curr =  this.bars.select("#vzb-bc-bar-"+d[this.AGEDIM]);
      curr.classed('vzb-hovered', true);
      var label = this.labels.select("#vzb-bc-label-"+d[this.AGEDIM]);
      label.classed('vzb-hovered', true);
    },

    /**
     * Select Entities
     */
    _selectBars: function() {
      var _this = this;
      var AGEDIM = this.AGEDIM;
      var selected = this.model.age.select;

      this._unselectBars();

      if(selected.length) {
        this.bars.classed('vzb-dimmed-selected', true);
        utils.forEach(selected, function(s) {
          _this.bars.select("#vzb-bc-bar-"+s[AGEDIM]).classed('vzb-selected', true);
          _this.labels.select("#vzb-bc-label-"+s[AGEDIM]).classed('vzb-selected', true);
        });
      }
    },

    _unselectBars: function() {
      this.bars.classed('vzb-dimmed-selected', false);
      this.bars.selectAll('.vzb-bc-bar.vzb-selected').classed('vzb-selected', false);
      this.labels.selectAll('.vzb-selected').classed('vzb-selected', false);
    },

    /**
     * Executes everytime the container or vizabi is resized
     * Ideally,it contains only operations related to size
     */
    resize: function () {

      var _this = this;

      this.profiles = {
        "small": {
          margin: {
            top: 70,
            right: 20,
            left: 40,
            bottom: 40
          },
          minRadius: 2,
          maxRadius: 40
        },
        "medium": {
          margin: {
            top: 80,
            right: 60,
            left: 60,
            bottom: 40
          },
          minRadius: 3,
          maxRadius: 60
        },
        "large": {
          margin: {
            top: 100,
            right: 60,
            left: 60,
            bottom: 40
          },
          minRadius: 4,
          maxRadius: 80
        }
      };

      this.activeProfile = this.profiles[this.getLayoutProfile()];
      var margin = this.activeProfile.margin;

      //stage
      this.height = parseInt(this.element.style("height"), 10) - margin.top - margin.bottom;
      this.width = parseInt(this.element.style("width"), 10) - margin.left - margin.right;

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

      //update scales to the new range
      if (this.model.marker.axis_y.scaleType !== "ordinal") {
        this.yScale.range([this.height, 0]);
      } else {
        this.yScale.rangePoints([this.height, 0]).range();
      }
      if (this.model.marker.axis_x.scaleType !== "ordinal") {
        this.xScale.range([0, this.width]);
      } else {
        this.xScale.rangePoints([0, this.width]).range();
      }

      //apply scales to axes and redraw
      this.yAxis.scale(this.yScale)
        .orient("left")
        .tickSize(6, 0)
        .tickSizeMinor(3, 0)
        .labelerOptions({
          scaleType: this.model.marker.axis_y.scaleType,
          toolMargin: margin,
          limitMaxTickNumber: 6
        });

      this.xAxis.scale(this.xScale)
        .orient("bottom")
        .tickSize(6, 0)
        .tickSizeMinor(3, 0)
        .labelerOptions({
          scaleType: this.model.marker.axis_x.scaleType,
          toolMargin: margin,
          limitMaxTickNumber: 6
        });

      this.xAxisEl.attr("transform", "translate(0," + this.height + ")")
        .call(this.xAxis);

      this.yAxisEl.call(this.yAxis);
      this.xAxisEl.call(this.xAxis);

      this.title.attr('x', margin.right).attr('y', margin.top/2);

      this.year.attr('x', this.width + margin.left).attr('y', margin.top/2);

    }
  });

}).call(this);
<|endoftext|>


<commit_before>'use strict'
var trace = false

function formatResponse (apdu) {
  return apdu.slice(0, apdu.length - 2).toString('hex') + (apdu.length === 2 ? '' : ' ') + apdu.slice(-2).toString('hex')
}

function formatCommand (apdu) {
  if (apdu.length === 4) {
    return apdu.toString('hex')
  } else if (apdu.length >= 5) {
    return apdu.slice(0, 4).toString('hex') + ' ' + apdu.slice(4, 5).toString('hex') + ' ' + apdu.slice(5, 5 + apdu[4]).toString('hex')
  }
}

// given a function that returns promises for APDU-s as raw bytes
// wrap it with APDU semantics for GET RESPONSE handling
function apdufy (transmit) {
  return function (apdu) {
    // Allow to transmit hex strings
    if (typeof apdu === 'string') {
      apdu = Buffer.from(apdu, 'hex')
    }
    return new Promise(function (resolve, reject) {
      var start = new Date().getTime()
      if (trace) { console.log('A>> ' + formatCommand(apdu)) }
      transmit(apdu).then(function (response) {
        var sw = response.slice(-2)
        if (sw[0] === 0x61) {
          transmit(Buffer.from([0x00, 0xC0, 0x00, 0x00, sw[1]])).then(function (response) {
            if (trace) {
              var ms = new Date().getTime() - start
              console.log('A<< (%d ms) %s', ms, formatResponse(response))
            }
            return resolve(response)
          }).catch(function (reason) {
            return reject(reason)
          })
        } else {
          var ms = new Date().getTime() - start
          if (trace) { console.log('A<< (%d ms) %s', ms, formatResponse(response)) }
          return resolve(response)
        }
      }).catch(function (reason) {
        return reject(reason)
      })
    })
  }
}

// Given a APDU promise, reject it if sw is not 0x9000
function check (p, ok) {
  var oksw = []
  if (typeof ok === 'number') { oksw.push(ok) }
  if (oksw.indexOf(0x9000) === -1) { oksw.push(0x9000) }
  return new Promise(function (resolve, reject) {
    p.then(function (response) {
      const sw = getsw(response)
      if (oksw.indexOf(sw) === -1) {
        return reject(new Error('APDU SW check failed, SW 0x' + sw.toString(16) + ' not in ' + oksw.map((x) => '0x' + x.toString(16)).join(' ')))
      } else {
        return resolve(response)
      }
    }).catch(function (reason) {
      console.log('APDU failed, thus not SW check')
      reject(reason)
    })
  })
}

function getsw (response) {
  var sw = response.slice(-2)
  return (sw[0] << 8) | sw[1]
}

function getdata (response) {
  return response.slice(0, response.length - 2)
}

module.exports.apdufy = apdufy
module.exports.check = check
module.exports.sw = getsw
module.exports.data = getdata
<commit_msg>Browser compatibility<commit_after>'use strict'
var trace = false

function formatResponse (apdu) {
  return apdu.slice(0, apdu.length - 2).toString('hex') + (apdu.length === 2 ? '' : ' ') + apdu.slice(-2).toString('hex')
}

function formatCommand (apdu) {
  if (apdu.length === 4) {
    return apdu.toString('hex')
  } else if (apdu.length >= 5) {
    return apdu.slice(0, 4).toString('hex') + ' ' + apdu.slice(4, 5).toString('hex') + ' ' + apdu.slice(5, 5 + apdu[4]).toString('hex')
  }
}

// given a function that returns promises for APDU-s as raw bytes
// wrap it with APDU semantics for GET RESPONSE handling
function apdufy (transmit) {
  return function (apdu) {
    // Allow to transmit hex strings
    if (typeof apdu === 'string') {
      apdu = Buffer.from(apdu, 'hex')
    }
    return new Promise(function (resolve, reject) {
      var start = new Date().getTime()
      if (trace) { console.log('A>> ' + formatCommand(apdu)) }
      transmit(apdu).then(function (response) {
        var sw = response.slice(-2)
        if (sw[0] === 0x61) {
          transmit(Buffer.from([0x00, 0xC0, 0x00, 0x00, sw[1]])).then(function (response) {
            if (trace) {
              var ms = new Date().getTime() - start
              console.log('A<< (%d ms) %s', ms, formatResponse(response))
            }
            return resolve(response)
          }).catch(function (reason) {
            return reject(reason)
          })
        } else {
          var ms = new Date().getTime() - start
          if (trace) { console.log('A<< (%d ms) %s', ms, formatResponse(response)) }
          return resolve(response)
        }
      }).catch(function (reason) {
        return reject(reason)
      })
    })
  }
}

// Given a APDU promise, reject it if sw is not 0x9000
function check (p, ok) {
  var oksw = []
  if (typeof ok === 'number') { oksw.push(ok) }
  if (oksw.indexOf(0x9000) === -1) { oksw.push(0x9000) }
  return new Promise(function (resolve, reject) {
    p.then(function (response) {
      const sw = getsw(response)
      if (oksw.indexOf(sw) === -1) {
        return reject(new Error('APDU SW check failed, SW 0x' + sw.toString(16) + ' not in ' + oksw.map(function (x) { return '0x' + x.toString(16)}).join(' ')))
      } else {
        return resolve(response)
      }
    }).catch(function (reason) {
      console.log('APDU failed, thus not SW check')
      reject(reason)
    })
  })
}

function getsw (response) {
  var sw = response.slice(-2)
  return (sw[0] << 8) | sw[1]
}

function getdata (response) {
  return response.slice(0, response.length - 2)
}

module.exports.apdufy = apdufy
module.exports.check = check
module.exports.sw = getsw
module.exports.data = getdata
<|endoftext|>


<commit_before>sap.ui.controller("sps.controller.treePage", {
    onInit: function() {
        responseCounter = 1;
        // create JSON model to manage data
        //var oModel = new sap.ui.model.json.JSONModel();
        oModel = new sap.ui.model.json.JSONModel();
        // load data from JSOM file, for use by the model
        oModel.loadData("sps/questions.json");
        sap.ui.getCore().setModel(oModel);

        // set the text property of the Question to "q1", when page is first loaded
        this.getView().byId("quest").bindText("/Questions/q1");

		//SetYes and No Buttons to Visible and Home button hidden
		this.getView().byId("yButton").setVisible(true);
		this.getView().byId("nButton").setVisible(true);
		this.getView().byId("homeButton").setVisible(false);
    },
	handleNavButtonPress: function () {
			this.getOwnerComponent().myNavBack();
	},
	myNavBack : function () {
			var oHistory = sap.ui.core.routing.History.getInstance();
			var oPrevHash = oHistory.getPreviousHash();
			if (oPrevHash !== undefined) {
				window.history.go(-1);
			} else {
				this._router.navTo("home", {}, true);
			}
	},

    // return to main page
    goHome: function() {
		questionCounter = 1;
		responseCounter = 1;
        app.back();

		//This returns the question back to question 1, and also
		//Sets the yes/no buttons to visible and Home button to hidden
		this.getView().byId("quest").bindText("/Questions/q1");
		this.getView().byId("yButton").setVisible(true);
		this.getView().byId("nButton").setVisible(true);
		this.getView().byId("homeButton").setVisible(false);
    },

    /* these two methods are temporary and need to be replaced with
     * the final code later on
     */
    respondYes : function() {
        // update question and response counters
        switch(questionCounter) {
            case 1:
                this.getView().byId("quest").bindText("/Questions/q2");
                questionCounter++;
                responseCounter++;
                break;
            case 2:
                this.getView().byId("quest").bindText("/Questions/q3");
                questionCounter++;
                responseCounter++;
                break;
            case 3:
                this.getView().byId("quest").bindText("/Questions/q4");
                questionCounter++;
                responseCounter++;
                break;
            default:
                // there are no more questions, so display a message
                this.getView().byId("quest").bindText("/Error/errQ");

				this.getView().byId("yButton").setVisible(false);
				this.getView().byId("nButton").setVisible(false);
				this.getView().byId("homeButton").setVisible(true);
                break;
        }
    },
	/*This can potentially replace the response Page. It isn't finished but
	  if we are only displaying an answering, it might be easier and cleaner.
	  */
    respondNo : function() {

    	//Previous code
    	/*questionCounter = 1;
        responseCounter++;
        app.to(responsePage);*/

		//Set Yes/No Buttons to Hidden and Home button Visible
		this.getView().byId("yButton").setVisible(false);
		this.getView().byId("nButton").setVisible(false);
		this.getView().byId("homeButton").setVisible(true);
		switch(responseCounter) {
            case 1:
                this.getView().byId("quest").bindText("/Responses/r1");
                break;
            case 2:
                this.getView().byId("quest").bindText("/Responses/r2");
                break;
            case 3:
                this.getView().byId("quest").bindText("/Responses/r3");
                break;
            case 4:
                this.getView().byId("quest").bindText("/Responses/r4");
                break;
            default:
                this.getView().byId("quest").bindText("/Error/errR");
                break;
        }
    }
});
<commit_msg>Removed mobile testing<commit_after>sap.ui.controller("sps.controller.treePage", {
    onInit: function() {
        responseCounter = 1;
        // create JSON model to manage data
        //var oModel = new sap.ui.model.json.JSONModel();
        oModel = new sap.ui.model.json.JSONModel();
        // load data from JSOM file, for use by the model
        oModel.loadData("sps/questions.json");
        sap.ui.getCore().setModel(oModel);

        // set the text property of the Question to "q1", when page is first loaded
        this.getView().byId("quest").bindText("/Questions/q1");

		//SetYes and No Buttons to Visible and Home button hidden
		this.getView().byId("yButton").setVisible(true);
		this.getView().byId("nButton").setVisible(true);
		this.getView().byId("homeButton").setVisible(false);
    },

    // return to main page
    goHome: function() {
		questionCounter = 1;
		responseCounter = 1;
        app.back();

		//This returns the question back to question 1, and also
		//Sets the yes/no buttons to visible and Home button to hidden
		this.getView().byId("quest").bindText("/Questions/q1");
		this.getView().byId("yButton").setVisible(true);
		this.getView().byId("nButton").setVisible(true);
		this.getView().byId("homeButton").setVisible(false);
    },

    /* these two methods are temporary and need to be replaced with
     * the final code later on
     */
    respondYes : function() {
        // update question and response counters
        switch(questionCounter) {
            case 1:
                this.getView().byId("quest").bindText("/Questions/q2");
                questionCounter++;
                responseCounter++;
                break;
            case 2:
                this.getView().byId("quest").bindText("/Questions/q3");
                questionCounter++;
                responseCounter++;
                break;
            case 3:
                this.getView().byId("quest").bindText("/Questions/q4");
                questionCounter++;
                responseCounter++;
                break;
            default:
                // there are no more questions, so display a message
                this.getView().byId("quest").bindText("/Error/errQ");

				this.getView().byId("yButton").setVisible(false);
				this.getView().byId("nButton").setVisible(false);
				this.getView().byId("homeButton").setVisible(true);
                break;
        }
    },
	/*This can potentially replace the response Page. It isn't finished but
	  if we are only displaying an answering, it might be easier and cleaner.
	  */
    respondNo : function() {

    	//Previous code
    	/*questionCounter = 1;
        responseCounter++;
        app.to(responsePage);*/

		//Set Yes/No Buttons to Hidden and Home button Visible
		this.getView().byId("yButton").setVisible(false);
		this.getView().byId("nButton").setVisible(false);
		this.getView().byId("homeButton").setVisible(true);
		switch(responseCounter) {
            case 1:
                this.getView().byId("quest").bindText("/Responses/r1");
                break;
            case 2:
                this.getView().byId("quest").bindText("/Responses/r2");
                break;
            case 3:
                this.getView().byId("quest").bindText("/Responses/r3");
                break;
            case 4:
                this.getView().byId("quest").bindText("/Responses/r4");
                break;
            default:
                this.getView().byId("quest").bindText("/Error/errR");
                break;
        }
    }
});
<|endoftext|>


<commit_before>import isDefined from '../../../utils/isDefined'

export default (state) => {

	const fetching = (
		Object.values(state.overview.value).some((value) => value.fetching) === true ||
		state.views.fetching === true ||
		state.pages.fetching === true ||
		state.referrers.fetching === true ||
		state.durations.fetching === true ||
		state.systems.fetching === true ||
		state.devices.fetching === true ||
		state.browsers.fetching === true ||
		state.sizes.fetching === true ||
		state.languages.fetching === true ||
		state.domains.fetching === true ||
		state.token.fetching === true
	)

	const errors = [
		...Object.values(state.overview.value).map((value) => value.error),
		state.views.error,
		state.pages.error,
		state.referrers.error,
		state.durations.error,
		state.systems.error,
		state.devices.error,
		state.browsers.error,
		state.sizes.error,
		state.languages.error,
		state.domains.error,
		state.token.error
	].filter(isDefined)

	return Object.assign({}, state, {
		fetching,
		errors
	})

}<commit_msg>Overview errors and fetching for all domains<commit_after>import { ALL_DOMAINS } from '../actions/overview'
import isDefined from '../../../utils/isDefined'
import * as selectOverviewValue from '../selectors/selectOverviewValue'

export default (state) => {

	const fetching = (
		selectOverviewValue.withoutType(state, ALL_DOMAINS).fetching === true ||
		Object.values(state.overview.value).some((value) => value.fetching) === true ||
		state.views.fetching === true ||
		state.pages.fetching === true ||
		state.referrers.fetching === true ||
		state.durations.fetching === true ||
		state.systems.fetching === true ||
		state.devices.fetching === true ||
		state.browsers.fetching === true ||
		state.sizes.fetching === true ||
		state.languages.fetching === true ||
		state.domains.fetching === true ||
		state.token.fetching === true
	)

	const errors = [
		selectOverviewValue.withoutType(state, ALL_DOMAINS).error,
		...Object.values(state.overview.value).map((value) => value.error),
		state.views.error,
		state.pages.error,
		state.referrers.error,
		state.durations.error,
		state.systems.error,
		state.devices.error,
		state.browsers.error,
		state.sizes.error,
		state.languages.error,
		state.domains.error,
		state.token.error
	].filter(isDefined)

	return Object.assign({}, state, {
		fetching,
		errors
	})

}<|endoftext|>


<commit_before>//User inputs their name

var userName = prompt('Welcome to the Guessing Game! What is your name?');
console.log('The user\'s name is ' + userName);

alert('Welcome, ' + userName + ' ! Please guess \'yes or no\' for the following questions!');
var understandCheck = confirm('Are you ready?');

if (understandCheck === true) {
  alert('Great! Let\'s get started');
  console.log(userName + ' is ready to play the guessing game!');
} else {
  alert('What don\'t you understand about answering yes or no?');
  console.log(userName + ' might not be the sharpest tool in the shed.');
}

var questions = ['Did you know that I am from Chicago?',
'Yes or No: I have 3 or more pets?',
'Do I enjoy outdoor activities?',
'Do you think I am engaged?',
'Do you think you can guess what type of dog I have?',,
'How many siblings do I have? You have four trys to get it right. Make sure you enter a number!'];
var correct = ['That\'s right, ' + userName + '! I am from Chicago!',
'That\'s right ' + userName + '! I have 5 total pets!',
'That\'s right, ' + userName + '! The only outdoor activity I will partake in is sitting in a beer garden!',
'Yep, ' + userName + '! I am planning a wedding for next spring!',
'How did you know I had a Chihuahua? Technically, I have one and a half chihuahuas! \(Yeah, figure that one out!\)',
'That\'s correct, ' + userName + '! I have three siblings.'];
var incorrect = ['Well, ' + userName + ', now you do!',
'That is incorrect, ' + userName + '. I actually have 5 total pets!',
'No, ' + userName + ' ! The only outdoor activity I enjoy is sitting in a beer garden!',
'Shockingly, ' + userName + ', someone actually agreed to marry me!',
'That\'s ok, ' + userName + '! I will just tell you that I have a chihuahua.',
'Try again, ' + userName + '! You have ' + guessesLeft + ' guesses left!',
'Sorry, ' + userName + ', you ran out of guesses! I have 3 siblings'];

//Begin guessing game
function question1() {
  var answerOne = prompt(questions[0]);
  if (answerOne.toUpperCase() === 'YES' || answerOne.toUpperCase() === 'Y') {
    alert(correct[0]);
    console.log(userName + ' knew that I am from Chicago');
  } else {
    alert(incorrect[0]);
    console.log(userName + ' did not know that I am from Chicago');
  }
}
function question2() {
  var answerTwo = prompt(questions[1]);
  if (answerTwo.toUpperCase() === 'YES' || answerTwo.toUpperCase() === 'Y') {
    alert(correct[1]);
    console.log(userName + ' knew that I had more than 3 pets!');
  } else {
    alert(incorrect[1]);
    console.log(userName + ' did not know that I have more than 3 pets.');
  }
}

function question3() {
  var answerThree = prompt(questions[2]);
  if (answerThree.toUpperCase() === 'YES' || answerThree.toUpperCase() === 'Y') {
    alert(incorrect[2]);
    console.log(userName + ' did not know about my disdain for the outdoors!');
  } else {
    alert(correct[2]);
    console.log(userName + ' knew that they would never find me participating in outdoor activities.');
  }
}

function question4() {
  var answerFour = prompt(questions[3]);
  if (answerFour.toUpperCase() === 'YES' || answerFour.toUpperCase() === 'Y') {
    alert(correct[3]);
    console.log(userName + ' knew I was engaged.');
  } else {
    alert(incorrect[3]);
    console.log(userName + ' did not think anyne would want to marry me!');
  }
}

function question5() {
  var answerFive = prompt(questions[4]);
  if (answerFive.toUpperCase() === 'YES' || answerFive.toUpperCase() === 'Y') {
    var bonusQuestion = prompt('Ok, hotshot! What type of dog do I have?');
    if (bonusQuestion.toUpperCase() === 'CHIHUAHUA') {
      alert(correct[4]);
      console.log(userName + ' knew that I had a chihuahua!');
    } else {
      alert(incorrect[4]);
      console.log(userName + ' thought they knew what kind of dog I had, but they were WRONG!');
    }
  } else {
    alert('That\'s ok, ' + userName + '! I will just tell you that I have a chihuahua.');
    console.log(userName + ' did not want to guess what type of dog I have.');
  }
}

//adding count down question six
function question6 () {
  var guessesLeft = 3;
  var siblingsLeft = prompt(questions[5]);
  var userGuess;
  var wrongAnswer = 'Incorrect, ' + userName + '. Try again! You have ' + guessesLeft + ' guesses left!';

  while (guessesLeft <= 4 && guessesLeft > 0) {
    if (parseInt(siblingsLeft) === 3) {
      alert(correct[5]);
      console.log(userName + ' guessed that I had three siblings.');
      break;
    } else if (parseInt(siblingsLeft) < 3) {
      var siblingsLeft = prompt(incorrect[5]);
      guessesLeft--;
    } else if (parseInt(siblingsLeft) > 3) {
      var siblingsLeft = prompt(incorrect[5]);
      guessesLeft--;
    } else {
      var siblingsLeft = prompt('Input error. Please enter a number!');
    }
    if (siblingsLeft !== 3 && guessesLeft === 0) {
      alert(incorrect[6]);
      console.log(userName + ' did not correctly guess how many siblings I have.');
    }
  }
}
//end of guessing game

// alert('Thank you, ' + userName + ', for playing my guessing game!');
<commit_msg>added for loop<commit_after>//User inputs their name
var guessesLeft = 5;
var userName = prompt('Welcome to the Guessing Game! What is your name?');
console.log('The user\'s name is ' + userName);

alert('Welcome, ' + userName + ' ! Please guess \'yes or no\' for the following questions!');
var understandCheck = confirm('Are you ready?');

if (understandCheck === true) {
  alert('Great! Let\'s get started');
  console.log(userName + ' is ready to play the guessing game!');
} else {
  alert('What don\'t you understand about answering yes or no?');
  console.log(userName + ' might not be the sharpest tool in the shed.');
}

var questions = ['Did you know that I am from Chicago?', 'Yes or No: I have 3 or more pets?', 'Do I enjoy outdoor activities?', 'Do you think I am engaged?', 'Do you think you can guess what type of dog I have?', 'How many siblings do I have? You have four trys to get it right. Make sure you enter a number!'];
var correct = ['That\'s right, ' + userName + '! I am from Chicago!', 'That\'s right ' + userName + '! I have 5 total pets!', 'That\'s right, ' + userName + '! The only outdoor activity I will partake in is sitting in a beer garden!', 'Yep, ' + userName + '! I am planning a wedding for next spring!', 'How did you know I had a Chihuahua? Technically, I have one and a half chihuahuas! \(Yeah, figure that one out!\)', 'That\'s correct, ' + userName + '! I have three siblings.'];
var incorrect = ['Well, ' + userName + ', now you do!', 'That is incorrect, ' + userName + '. I actually have 5 total pets!', 'No, ' + userName + ' ! The only outdoor activity I enjoy is sitting in a beer garden!', 'Shockingly, ' + userName + ', someone actually agreed to marry me!', 'That\'s ok, ' + userName + '! I will just tell you that I have a chihuahua.', 'Try again, ' + userName + '! You have ' + guessesLeft + ' guesses left!', 'Sorry, you ran out of gueesses! I have 3 siblings!'];
var yesNo = ['YES', 'YES', 'NO', 'YES', 'NO'];

function ask() {
for (var i = 0; i < 5; i++){
  var answer = prompt(questions[i]);
  if (answer.toUpperCase() === yesNo[i]) {
    alert(correct[i]);
  } else {
    alert(incorrect[i]);
  }
}
}
//Begin guessing game
// function question1() {
//   var answerOne = prompt(questions[0]);
//   if (answerOne.toUpperCase() === 'YES' || answerOne.toUpperCase() === 'Y') {
//     alert(correct[0]);
//     console.log(userName + ' knew that I am from Chicago');
//   } else {
//     alert(incorrect[0]);
//     console.log(userName + ' did not know that I am from Chicago');
//   }
// }
// function question2() {
//   var answerTwo = prompt(questions[1]);
//   if (answerTwo.toUpperCase() === 'YES' || answerTwo.toUpperCase() === 'Y') {
//     alert(correct[1]);
//     console.log(userName + ' knew that I had more than 3 pets!');
//   } else {
//     alert(incorrect[1]);
//     console.log(userName + ' did not know that I have more than 3 pets.');
//   }
// }
//
// function question3() {
//   var answerThree = prompt(questions[2]);
//   if (answerThree.toUpperCase() === 'YES' || answerThree.toUpperCase() === 'Y') {
//     alert(incorrect[2]);
//     console.log(userName + ' did not know about my disdain for the outdoors!');
//   } else {
//     alert(correct[2]);
//     console.log(userName + ' knew that they would never find me participating in outdoor activities.');
//   }
// }
//
// function question4() {
//   var answerFour = prompt(questions[3]);
//   if (answerFour.toUpperCase() === 'YES' || answerFour.toUpperCase() === 'Y') {
//     alert(correct[3]);
//     console.log(userName + ' knew I was engaged.');
//   } else {
//     alert(incorrect[3]);
//     console.log(userName + ' did not think anyne would want to marry me!');
//   }
// }
//
// function question5() {
//   var answerFive = prompt(questions[4]);
//   if (answerFive.toUpperCase() === 'YES' || answerFive.toUpperCase() === 'Y') {
//     var bonusQuestion = prompt('Ok, hotshot! What type of dog do I have?');
//     if (bonusQuestion.toUpperCase() === 'CHIHUAHUA') {
//       alert(correct[4]);
//       console.log(userName + ' knew that I had a chihuahua!');
//     } else {
//       alert(incorrect[4]);
//       console.log(userName + ' thought they knew what kind of dog I had, but they were WRONG!');
//     }
//   } else {
//     alert('That\'s ok, ' + userName + '! I will just tell you that I have a chihuahua.');
//     console.log(userName + ' did not want to guess what type of dog I have.');
//   }
// }
//
// //adding count down question six
// function question6 () {
//   var guessesLeft = 3;
//   var siblingsLeft = prompt(questions[5]);
//   var userGuess;
//   var wrongAnswer = 'Incorrect, ' + userName + '. Try again! You have ' + guessesLeft + ' guesses left!';
//
//   while (guessesLeft <= 4 && guessesLeft > 0) {
//     if (parseInt(siblingsLeft) === 3) {
//       alert(correct[5]);
//       console.log(userName + ' guessed that I had three siblings.');
//       break;
//     } else if (parseInt(siblingsLeft) < 3) {
//       var siblingsLeft = prompt(incorrect[5]);
//       guessesLeft--;
//     } else if (parseInt(siblingsLeft) > 3) {
//       var siblingsLeft = prompt(incorrect[5]);
//       guessesLeft--;
//     } else {
//       var siblingsLeft = prompt('Input error. Please enter a number!');
//     }
//     if (siblingsLeft !== 3 && guessesLeft === 0) {
//       alert(incorrect[6]);
//       console.log(userName + ' did not correctly guess how many siblings I have.');
//     }
//   }
// }
//end of guessing game

// alert('Thank you, ' + userName + ', for playing my guessing game!');
<|endoftext|>


<commit_before>/**
 *
 *    Copyright (c) 2020 Silicon Labs
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

/**
 * This module contains the API for templating. For more detailed instructions, read {@tutorial template-tutorial}
 *
 * @module Templating API: Overridable functions.
 */

// Local utility function
function cleanseUints(uint) {
  if (uint == 'uint24_t') return 'uint32_t'
  if (uint == 'uint48_t') return 'uint8_t *'
  return uint
}

/**
 * Returns the name of a fall-through non-atomic type.
 * This method will be used unless the override is
 * providing a different implementation.
 *
 * @param {*} arg
 */
function nonAtomicType(arg = { name: 'unknown' }) {
  return `EmberAf${arg.name}`
}

/**
 * Returns the default atomic C type for a given atomic from
 * the database. These values are used unless there is an
 * override in template package json file. (Not yet fully
 * implemented, but the plan is for template pkg to be able
 * to override these.)
 *
 * @param {*} arg Object containing name and size
 */
function atomicType(arg = { name: 'unknown', size: 0 }) {
  let name = arg.name
  let size = arg.size
  if (name.startsWith('int')) {
    let signed
    if (name.endsWith('s')) signed = true
    else signed = false

    let ret = `${signed ? '' : 'u'}int${size * 8}_t`

    // few exceptions
    ret = cleanseUints(ret)
    return ret
  } else if (name.startsWith('enum') || name.startsWith('data')) {
    return cleanseUints(`uint${name.slice(4)}_t`)
  } else if (name.startsWith('bitmap')) {
    return cleanseUints(`uint${name.slice(6)}_t`)
  } else {
    switch (name) {
      case 'utc_time':
      case 'date':
        return 'uint32_t'
      case 'attribute_id':
      case 'cluster_id':
        return 'uint16_t'
      case 'no_data':
      case 'octet_string':
      case 'char_string':
      case 'ieee_address':
        return 'uint8_t *'
      case 'boolean':
        return 'uint8_t'
      case 'array':
        return `/* TYPE WARNING: ${name} array defaults to */ uint8_t * `
      default:
        return `/* TYPE WARNING: ${name} defaults to */ uint8_t * `
    }
  }
}

// WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!
//
// Note: these exports are public API. Templates that might have been created in the past and are
// available in the wild might depend on these names.
// If you rename the functions, you need to still maintain old exports list.
exports.atomicType = atomicType
exports.nonAtomicType = nonAtomicType
<commit_msg>Overriding some atomic zcl attribute types<commit_after>/**
 *
 *    Copyright (c) 2020 Silicon Labs
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

/**
 * This module contains the API for templating. For more detailed instructions, read {@tutorial template-tutorial}
 *
 * @module Templating API: Overridable functions.
 */

// Local utility function
function cleanseUints(uint) {
  if (uint == 'uint24_t') return 'uint32_t'
  if (uint == 'uint48_t') return 'uint8_t *'
  return uint
}

/**
 * Returns the name of a fall-through non-atomic type.
 * This method will be used unless the override is
 * providing a different implementation.
 *
 * @param {*} arg
 */
function nonAtomicType(arg = { name: 'unknown' }) {
  return `EmberAf${arg.name}`
}

/**
 * Returns the default atomic C type for a given atomic from
 * the database. These values are used unless there is an
 * override in template package json file. (Not yet fully
 * implemented, but the plan is for template pkg to be able
 * to override these.)
 *
 * @param {*} arg Object containing name and size
 */
function atomicType(arg = { name: 'unknown', size: 0 }) {
  let name = arg.name
  let size = arg.size
  if (name.startsWith('int')) {
    let signed
    if (name.endsWith('s')) signed = true
    else signed = false

    let ret = `${signed ? '' : 'u'}int${size * 8}_t`

    // few exceptions
    ret = cleanseUints(ret)
    return ret
  } else if (name.startsWith('enum') || name.startsWith('data')) {
    return cleanseUints(`uint${name.slice(4)}_t`)
  } else if (name.startsWith('bitmap')) {
    return cleanseUints(`uint${name.slice(6)}_t`)
  } else {
    switch (name) {
      case 'utc_time':
      case 'date':
      case 'time_of_day':
      case 'bacnet_oid':
        return 'uint32_t'
      case 'attribute_id':
      case 'cluster_id':
        return 'uint16_t'
      case 'no_data':
      case 'octet_string':
      case 'char_string':
      case 'ieee_address':
        return 'uint8_t *'
      case 'boolean':
        return 'uint8_t'
      case 'array':
        return `/* TYPE WARNING: ${name} array defaults to */ uint8_t * `
      default:
        return `/* TYPE WARNING: ${name} defaults to */ uint8_t * `
    }
  }
}

// WARNING! WARNING! WARNING! WARNING! WARNING! WARNING!
//
// Note: these exports are public API. Templates that might have been created in the past and are
// available in the wild might depend on these names.
// If you rename the functions, you need to still maintain old exports list.
exports.atomicType = atomicType
exports.nonAtomicType = nonAtomicType
<|endoftext|>


<commit_before>define([
  'module-tt-article/app',
  'module-tt-article/model/article',
  'lib/requirejs/hbs!module-tt-article/view/tmpl/article',
  'lib/requirejs/text!module-tt-article/data/mock-articles.json'
],
  function (App, ArticleObj, ArticleTmpl, mockArticlesJson) {
    /**
     * Article's test suite.
     */
    describe('ModuleTtArticle: Article', function () {

      var that = this;
      setFixtures(ArticleTmpl);
      that.$container = $('.tt-articles-items');
      that.App = App;
      that.mainConf = App.getModuleConfig('module-tt-article');
      /*that.testArticles = [{
        id: 2,
        isActive: true,
        image: "http://placehold.it/72x80",
        title: "reprehenderit ad eiusmod",
        description: "Exercitation aliqua minim proident adipisicing incididunt cupidatat laboris nisi. Mollit consectetur magna amet cupidatat adipisicing dolor fugiat. Deserunt aliqua anim eiusmod elit fugiat culpa ea. Est irure exercitation enim occaecat Lorem pariatur. Nulla reprehenderit magna ad nulla sint velit laborum aliquip aliquip minim ut. Et irure laborum magna excepteur tempor. ",
        tags: ["ea","aute","ea","aliqua","do"]
      }];*/
      that.testArticles = $.parseJSON(mockArticlesJson).articles;

      beforeEach(function () {
        that.Article = new ArticleObj(that.testArticles[2]);
        that.Article.setMaxDefaultTags(that.mainConf.maxDefaultTags);
      });

      afterEach(function () {
        that.Article = null;
      });

      it("tests the Article constructor", function () {
       expect(that.Article).toEqual(jasmine.any(Object));
      });

      it("checks the initialised properties", function () {
        expect(that.Article.id).toBe(that.testArticles[2].id);
        expect(that.Article.isActive).toBe(that.testArticles[2].isActive);
        expect(that.Article.image).toBe(that.testArticles[2].image);
        expect(that.Article.title).toBe(that.testArticles[2].title);
        expect(that.Article.description).toBe(that.testArticles[2].description);
        expect(that.Article.tags).toEqual(that.testArticles[2].tags);
      });

      it("is active", function () {
        expect(that.Article.isItemActive()).toBe(true);
      });

      it("is to show no more than specified number of tags by default", function () {
        expect(that.Article.maxDefaultTags).toEqual(that.mainConf.maxDefaultTags);
      });

      it("prepares default tags", function () {
        spyOn(that.Article, 'isMoreTags');
        that.Article.setTagsMaxToShow();
        expect(that.Article.isMoreTags).toHaveBeenCalled();
        expect(that.Article.lessTags).toContain('ea');
        expect(that.Article.lessTags).toContain('aute');
        expect(that.Article.moreTags).not.toContain('aliqua');
        expect(that.Article.moreTags).not.toContain('do');
      });

      it("generates HTML", function () {
        spyOn(that.Article, 'setTagsMaxToShow');
        spyOn(that.Article, 'isMoreTags');
        expect($(that.Article.generateHtml())).
          toHaveId("tt-articles-article-" + that.testArticles[2].id);
        expect(that.Article.setTagsMaxToShow).toHaveBeenCalled();
        expect(that.Article.isMoreTags).toHaveBeenCalled();
      });
    });
  });<commit_msg>Cleaning test suite.<commit_after>define([
  'module-tt-article/app',
  'module-tt-article/model/article',
  'lib/requirejs/hbs!module-tt-article/view/tmpl/article',
  'lib/requirejs/text!module-tt-article/data/mock-articles.json'
],
  function (App, ArticleObj, ArticleTmpl, mockArticlesJson) {
    /**
     * Article's test suite.
     */
    describe('ModuleTtArticle: Article', function () {

      var that = this;
      setFixtures(ArticleTmpl);
      that.$container = $('.tt-articles-items');
      that.App = App;
      that.mainConf = App.getModuleConfig('module-tt-article');
      that.testArticles = $.parseJSON(mockArticlesJson).articles;

      beforeEach(function () {
        that.Article = new ArticleObj(that.testArticles[2]);
        that.Article.setMaxDefaultTags(that.mainConf.maxDefaultTags);
      });

      afterEach(function () {
        that.Article = null;
      });

      it("tests the Article constructor", function () {
       expect(that.Article).toEqual(jasmine.any(Object));
      });

      it("checks the initialised properties", function () {
        expect(that.Article.id).toBe(that.testArticles[2].id);
        expect(that.Article.isActive).toBe(that.testArticles[2].isActive);
        expect(that.Article.image).toBe(that.testArticles[2].image);
        expect(that.Article.title).toBe(that.testArticles[2].title);
        expect(that.Article.description).toBe(that.testArticles[2].description);
        expect(that.Article.tags).toEqual(that.testArticles[2].tags);
      });

      it("is active", function () {
        expect(that.Article.isItemActive()).toBe(true);
      });

      it("is to show no more than specified number of tags by default", function () {
        expect(that.Article.maxDefaultTags).toEqual(that.mainConf.maxDefaultTags);
      });

      it("prepares default tags", function () {
        spyOn(that.Article, 'isMoreTags');
        that.Article.setTagsMaxToShow();
        expect(that.Article.isMoreTags).toHaveBeenCalled();
        expect(that.Article.lessTags).toContain('ea');
        expect(that.Article.lessTags).toContain('aute');
        expect(that.Article.moreTags).not.toContain('aliqua');
        expect(that.Article.moreTags).not.toContain('do');
      });

      it("generates HTML", function () {
        spyOn(that.Article, 'setTagsMaxToShow');
        spyOn(that.Article, 'isMoreTags');
        expect($(that.Article.generateHtml())).
          toHaveId("tt-articles-article-" + that.testArticles[2].id);
        expect(that.Article.setTagsMaxToShow).toHaveBeenCalled();
        expect(that.Article.isMoreTags).toHaveBeenCalled();
      });
    });
  });<|endoftext|>