<commit_before>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw) {
      function getURL() {
        var url = API_URL + path;
        return url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime();
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json";}

      xhr.open(method, getURL());
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
          } else {
            cb({request: this, error: this.status});
          }
        }
      };
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        _request("GET", "/users/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef("heads/"+branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(path, cb) {
        _request("GET", repoPath + "/contents", { path: path }, cb);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, function(err, content) {
            cb(err, content, sha);
          });
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path; });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          if (err) return cb(err);
          that.postBlob(content, function(err, blob) {
            if (err) return cb(err);
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              if (err) return cb(err);
              that.commit(latestCommit, tree, message, function(err, commit) {
                if (err) return cb(err);
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<commit_msg>Add follow/unfollow user<commit_after>// Github.js 0.7.0
// (c) 2012 Michael Aufreiter, Development Seed
// Github.js is freely distributable under the MIT license.
// For all details and documentation:
// http://substance.io/michael/github

(function() {
  var Github;
  var API_URL = 'https://api.github.com';

  Github = window.Github = function(options) {

    // HTTP Request Abstraction
    // =======
    //
    // I'm not proud of this and neither should you be if you were responsible for the XMLHttpRequest spec.

    function _request(method, path, data, cb, raw) {
      function getURL() {
        var url = API_URL + path;
        return url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime();
      }

      var xhr = new XMLHttpRequest();
      if (!raw) {xhr.dataType = "json";}

      xhr.open(method, getURL());
      xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
          if (this.status >= 200 && this.status < 300 || this.status === 304) {
            cb(null, raw ? this.responseText : this.responseText ? JSON.parse(this.responseText) : true);
          } else {
            cb({request: this, error: this.status});
          }
        }
      };
      xhr.setRequestHeader('Accept','application/vnd.github.raw');
      xhr.setRequestHeader('Content-Type','application/json');
      if (
         (options.auth == 'oauth' && options.token) ||
         (options.auth == 'basic' && options.username && options.password)
         ) {
           xhr.setRequestHeader('Authorization',options.auth == 'oauth'
             ? 'token '+ options.token
             : 'Basic ' + Base64.encode(options.username + ':' + options.password)
           );
         }
      data ? xhr.send(JSON.stringify(data)) : xhr.send();
    }

    // User API
    // =======

    Github.User = function() {
      this.repos = function(cb) {
        _request("GET", "/user/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List user organizations
      // -------

      this.orgs = function(cb) {
        _request("GET", "/user/orgs", null, function(err, res) {
          cb(err, res);
        });
      };

      // List authenticated user's gists
      // -------

      this.gists = function(cb) {
        _request("GET", "/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // Show user information
      // -------

      this.show = function(username, cb) {
        _request("GET", "/users/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // List user repositories
      // -------

      this.userRepos = function(username, cb) {
        _request("GET", "/users/"+username+"/repos?type=all&per_page=1000&sort=updated", null, function(err, res) {
          cb(err, res);
        });
      };

      // List a user's gists
      // -------

      this.userGists = function(username, cb) {
        _request("GET", "/users/"+username+"/gists", null, function(err, res) {
          cb(err,res);
        });
      };

      // List organization repositories
      // -------

      this.orgRepos = function(orgname, cb) {
        _request("GET", "/orgs/"+orgname+"/repos?type=all&per_page=1000&sort=updated&direction=desc", null, function(err, res) {
          cb(err, res);
        });
      };

      // Follow user
      // -------

      this.follow = function(username, cb) {
        _request("PUT", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };

      // Unfollow user
      // -------

      this.unfollow = function(username, cb) {
        _request("DELETE", "/user/following/"+username, null, function(err, res) {
          cb(err, res);
        });
      };
    };

    // Repository API
    // =======

    Github.Repository = function(options) {
      var repo = options.name;
      var user = options.user;

      var that = this;
      var repoPath = "/repos/" + user + "/" + repo;

      var currentTree = {
        "branch": null,
        "sha": null
      };

      // Uses the cache if branch has not been changed
      // -------

      function updateTree(branch, cb) {
        if (branch === currentTree.branch && currentTree.sha) return cb(null, currentTree.sha);
        that.getRef("heads/"+branch, function(err, sha) {
          currentTree.branch = branch;
          currentTree.sha = sha;
          cb(err, sha);
        });
      }

      // Get a particular reference
      // -------

      this.getRef = function(ref, cb) {
        _request("GET", repoPath + "/git/refs/" + ref, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.object.sha);
        });
      };

      // Create a new reference
      // --------
      //
      // {
      //   "ref": "refs/heads/my-new-branch-name",
      //   "sha": "827efc6d56897b048c772eb4087f854f46256132"
      // }

      this.createRef = function(options, cb) {
        _request("POST", repoPath + "/git/refs", options, cb);
      };

      // Delete a reference
      // --------
      //
      // repo.deleteRef('heads/gh-pages')
      // repo.deleteRef('tags/v1.0')

      this.deleteRef = function(ref, cb) {
        _request("DELETE", repoPath + "/git/refs/"+ref, options, cb);
      };

      // List all branches of a repository
      // -------

      this.listBranches = function(cb) {
        _request("GET", repoPath + "/git/refs/heads", null, function(err, heads) {
          if (err) return cb(err);
          cb(null, _.map(heads, function(head) { return _.last(head.ref.split('/')); }));
        });
      };

      // Retrieve the contents of a blob
      // -------

      this.getBlob = function(sha, cb) {
        _request("GET", repoPath + "/git/blobs/" + sha, null, cb, 'raw');
      };

      // For a given file path, get the corresponding sha (blob for files, tree for dirs)
      // -------

      this.getSha = function(branch, path, cb) {
        // Just use head if path is empty
        if (path === "") return that.getRef("heads/"+branch, cb);
        that.getTree(branch+"?recursive=true", function(err, tree) {
          var file = _.select(tree, function(file) {
            return file.path === path;
          })[0];
          cb(null, file ? file.sha : null);
        });
      };

      // Retrieve the tree a commit points to
      // -------

      this.getTree = function(tree, cb) {
        _request("GET", repoPath + "/git/trees/"+tree, null, function(err, res) {
          if (err) return cb(err);
          cb(null, res.tree);
        });
      };

      // Post a new blob object, getting a blob SHA back
      // -------

      this.postBlob = function(content, cb) {
        if (typeof(content) === "string") {
          content = {
            "content": content,
            "encoding": "utf-8"
          };
        }

        _request("POST", repoPath + "/git/blobs", content, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update an existing tree adding a new blob object getting a tree SHA back
      // -------

      this.updateTree = function(baseTree, path, blob, cb) {
        var data = {
          "base_tree": baseTree,
          "tree": [
            {
              "path": path,
              "mode": "100644",
              "type": "blob",
              "sha": blob
            }
          ]
        };
        _request("POST", repoPath + "/git/trees", data, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Post a new tree object having a file path pointer replaced
      // with a new blob SHA getting a tree SHA back
      // -------

      this.postTree = function(tree, cb) {
        _request("POST", repoPath + "/git/trees", { "tree": tree }, function(err, res) {
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Create a new commit object with the current commit SHA as the parent
      // and the new tree SHA, getting a commit SHA back
      // -------

      this.commit = function(parent, tree, message, cb) {
        var data = {
          "message": message,
          "author": {
            "name": options.username
          },
          "parents": [
            parent
          ],
          "tree": tree
        };

        _request("POST", repoPath + "/git/commits", data, function(err, res) {
          currentTree.sha = res.sha; // update latest commit
          if (err) return cb(err);
          cb(null, res.sha);
        });
      };

      // Update the reference of your head to point to the new commit SHA
      // -------

      this.updateHead = function(head, commit, cb) {
        _request("PATCH", repoPath + "/git/refs/heads/" + head, { "sha": commit }, function(err, res) {
          cb(err);
        });
      };

      // Show repository information
      // -------

      this.show = function(cb) {
        _request("GET", repoPath, null, cb);
      };

      // Get contents
      // --------

      this.contents = function(path, cb) {
        _request("GET", repoPath + "/contents", { path: path }, cb);
      };

      // Fork repository
      // -------

      this.fork = function(cb) {
        _request("POST", repoPath + "/forks", null, cb);
      };

      // Create pull request
      // --------

      this.createPullRequest = function(options, cb) {
        _request("POST", repoPath + "/pulls", options, cb);
      };

      // Read file at given path
      // -------

      this.read = function(branch, path, cb) {
        that.getSha(branch, path, function(err, sha) {
          if (!sha) return cb("not found", null);
          that.getBlob(sha, function(err, content) {
            cb(err, content, sha);
          });
        });
      };

      // Remove a file from the tree
      // -------

      this.remove = function(branch, path, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            var newTree = _.reject(tree, function(ref) { return ref.path === path; });
            _.each(newTree, function(ref) {
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(newTree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Move a file to a new location
      // -------

      this.move = function(branch, path, newPath, cb) {
        updateTree(branch, function(err, latestCommit) {
          that.getTree(latestCommit+"?recursive=true", function(err, tree) {
            // Update Tree
            _.each(tree, function(ref) {
              if (ref.path === path) ref.path = newPath;
              if (ref.type === "tree") delete ref.sha;
            });

            that.postTree(tree, function(err, rootTree) {
              that.commit(latestCommit, rootTree, 'Deleted '+path , function(err, commit) {
                that.updateHead(branch, commit, function(err) {
                  cb(err);
                });
              });
            });
          });
        });
      };

      // Write file contents to a given branch and path
      // -------

      this.write = function(branch, path, content, message, cb) {
        updateTree(branch, function(err, latestCommit) {
          if (err) return cb(err);
          that.postBlob(content, function(err, blob) {
            if (err) return cb(err);
            that.updateTree(latestCommit, path, blob, function(err, tree) {
              if (err) return cb(err);
              that.commit(latestCommit, tree, message, function(err, commit) {
                if (err) return cb(err);
                that.updateHead(branch, commit, cb);
              });
            });
          });
        });
      };
    };

    // Gists API
    // =======

    Github.Gist = function(options) {
      var id = options.id;
      var gistPath = "/gists/"+id;

      // Read the gist
      // --------

      this.read = function(cb) {
        _request("GET", gistPath, null, function(err, gist) {
          cb(err, gist);
        });
      };

      // Delete the gist
      // --------

      this.delete = function(cb) {
        _request("DELETE", gistPath, null, function(err,res) {
          cb(err,res);
        });
      };

      // Fork a gist
      // --------

      this.fork = function(cb) {
        _request("POST", gistPath+"/fork", null, function(err,res) {
          cb(err,res);
        });
      };

      // Update a gist with the new stuff
      // --------

      this.update = function(options, cb) {
        _request("PATCH", gistPath, options, function(err,res) {
          cb(err,res);
        });
      };
    };

    // Top Level API
    // -------

    this.getRepo = function(user, repo) {
      return new Github.Repository({user: user, name: repo});
    };

    this.getUser = function() {
      return new Github.User();
    };

    this.getGist = function(id) {
      return new Github.Gist({id: id});
    };
  };
}).call(this);<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var Moment = require('moment');
var TimerMixin = require('react-native-timer-mixin');
var AudioPlayer = require('react-native-audioplayer');

var {
  AppRegistry,
  PickerIOS,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  PushNotificationIOS
} = React;

var PickerItemIOS = PickerIOS.Item;

var PRESSURES_AND_MINUTES = {
  '300': {
    bar: '300',
    minutes: '51',
  },
  '290': {
    bar: '290',
    minutes: '49',
  },
  '280': {
    bar: '280',
    minutes: '47',
  },
  '270': {
    bar: '270',
    minutes: '45',
  },
  '260': {
    bar: '260',
    minutes: '44',
  },
  '250': {
    bar: '250',
    minutes: '42',
  },
  '240': {
    bar: '240',
    minutes: '40',
  },
  '230': {
    bar: '230',
    minutes: '38',
  },
  '220': {
    bar: '220',
    minutes: '36',
  },
  '210': {
    bar: '210',
    minutes: '34',
  },
  '200': {
    bar: '200',
    minutes: '33',
  },
  '190': {
    bar: '190',
    minutes: '31',
  },
  '180': {
    bar: '180',
    minutes: '29',
  },
  '170': {
    bar: '170',
    minutes: '27',
  },
  '160': {
    bar: '160',
    minutes: '25',
  },
  '150': {
    bar: '150',
    minutes: '23',
  },
  '140': {
    bar: '140',
    minutes: '21',
  },
  '130': {
    bar: '130',
    minutes: '19',
  },
  '120': {
    bar: '120',
    minutes: '17',
  },
  '110': {
    bar: '110',
    minutes: '15',
  },
};

var SaveTheShoes = React.createClass({
  mixins: [TimerMixin],

  pressure: function() {
    var pressure = PRESSURES_AND_MINUTES[this.state.barPressure];

    return {
      pressureData: pressure,
      selectedBar: pressure.bar,
      minutesOfAir: pressure.minutes
    };
  },

  componentDidMount () {
    this.setInterval(this.decrementTimer, 1000);
  },

  startTimer: function () {
    if (false && this.state.timerRunning) {
      AlertIOS.alert(
          'Stop the timer?',
          'Are you sure you want to stop the timer?', [
          {text: 'Yes', onPress: () => this.setState({timerRunning: false})},
          {text: 'No', onPress: () => this.setState({timerRunning: true})},
          ]);

      return;
    }

    var timeInMilliseconds = this.pressure().minutesOfAir * 60 * 1000;

    this.setState({timerRunning: !this.state.timerRunning, inTime: Moment()});

    var timeInMinutes = PRESSURES_AND_MINUTES[this.state.barPressure].minutes;
    this.setState({timeRemaining: Moment.duration(parseInt(timeInMinutes, 10), 'minutes')});
  },

  decrementTimer: function() {
    if (!this.state.timerRunning) {
      return false;
    }

    // TODO - deltatime
    this.setState({timeRemaining: this.state.timeRemaining.subtract(1, 'second')});

    if (this.state.timeRemaining <= 0) {
      AudioPlayer.play('alarm.mp3');

      AlertIOS.alert(
        'Beep beep',
        "Time's up!"
      );

      this.setState({timerRunning: false});
    }
  },

  getInitialState: function() {
    return {
      barPressure: '110',
      minutes: 15,
      timerRunning: false,
      inTime: null,
      timeRemaining: Moment.duration(0)
    };
  },

  timesRunning: function(pressure) {
    if(this.state.inTime != null){
      var inTime = Moment(this.state.inTime);
      var outTime = Moment(this.state.inTime).add(pressure.minutes, 'minutes');

      var reliefAssemblyTime = Moment(outTime).subtract(15, 'minutes');
      var reliefInTime = Moment(outTime).subtract(10, 'minutes');
    }

    if(this.state.timerRunning) {
      return (

          <View>
          <TimeBox time={inTime} title="Crew Entered at"></TimeBox>
          <TimeBox time={reliefAssemblyTime} title="Relief Assembly"></TimeBox>
          <TimeBox time={reliefInTime} title="Relief In"></TimeBox>
          <TimeBox time={outTime} title="Time Due Out"></TimeBox>
          </View>
          );
    } else {
      return (<View></View>);
    }
  },

  render: function() {
    var pressure = this.pressure().pressureData;
    var selectedBar = this.pressure().selectedBar;
    var minutesOfAir =  this.pressure().minutesOfAir;

    return (
        <View style={[styles.background, styles.base,]}>
        <Text ></Text>
        <Text style={styles.header}>Select Cylinder Pressure </Text>
        <PickerIOS
        selectedValue={this.state.barPressure}
        onValueChange={(barPressure) => this.setState({barPressure})} style={styles.PickerIOS}>
        {Object.keys(PRESSURES_AND_MINUTES).map((barPressure) => (
              <PickerItemIOS
              key={barPressure}
              value={barPressure}
              label={PRESSURES_AND_MINUTES[barPressure].bar}
              />
              )
            )}
        </PickerIOS>

        <CountDownBox time={this.state.timeRemaining}></CountDownBox>
        {this.timesRunning(pressure)}

        <TouchableHighlight style={styles.buttonContainer} onPress={this.startTimer}>
          <Text style={styles.button}>
          {this.state.timerRunning ? 'Stop' : 'Go!'}
        </Text>
          </TouchableHighlight>
          </View>
          );
  },
});

var TimeBox = React.createClass({
  render: function() {
    return (
        <View style={{borderTopWidth: 1, borderTopColor: '#C2C2D6', padding: 10}}>
        <View><Text style={{textAlign: 'center'}}>{this.props.title}</Text></View>
        <View><Text style={{textAlign: 'center', fontSize: 24}}>{this.props.time.format('HH:mm')}</Text></View>
        </View>
        );
  }
});

var CountDownBox = React.createClass({
  render: function() {
    return (
        <View style={{borderTopWidth: 1, borderTopColor: '#C2C2D6', padding: 10}}>
        <View><Text style={{textAlign: 'center'}}>Time Remaining</Text></View>
        <View><Text style={{textAlign: 'center', fontSize: 34}}>{this.props.time.minutes()}′{this.props.time.seconds()}′′</Text></View>
        </View>
        );
  }
});

AppRegistry.registerComponent('SaveTheShoes', () => SaveTheShoes);
AppRegistry.registerComponent('TimeBox', () => TimeBox);
AppRegistry.registerComponent('CountDownBox', () => CountDownBox);

var styles = ({
  base: {
  },

  header: {
    paddingTop: 40,
    fontWeight: 'bold',
    textAlign: 'center',
    fontSize: 18
  },

  pickerIOS: {

  },

  background: {
    backgroundColor: '#EFEFEF',
  },

  button: {
    color: '#007aff'
  },

  buttonContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  }
});
<commit_msg>Countdown to RA time instead of 💀 💀 💀<commit_after>'use strict';

var React = require('react-native');
var Moment = require('moment');
var TimerMixin = require('react-native-timer-mixin');
var AudioPlayer = require('react-native-audioplayer');

var {
  AppRegistry,
  PickerIOS,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  PushNotificationIOS
} = React;

var PickerItemIOS = PickerIOS.Item;

var PRESSURES_AND_MINUTES = {
  '300': {
    bar: '300',
    minutes: '51',
  },
  '290': {
    bar: '290',
    minutes: '49',
  },
  '280': {
    bar: '280',
    minutes: '47',
  },
  '270': {
    bar: '270',
    minutes: '45',
  },
  '260': {
    bar: '260',
    minutes: '44',
  },
  '250': {
    bar: '250',
    minutes: '42',
  },
  '240': {
    bar: '240',
    minutes: '40',
  },
  '230': {
    bar: '230',
    minutes: '38',
  },
  '220': {
    bar: '220',
    minutes: '36',
  },
  '210': {
    bar: '210',
    minutes: '34',
  },
  '200': {
    bar: '200',
    minutes: '33',
  },
  '190': {
    bar: '190',
    minutes: '31',
  },
  '180': {
    bar: '180',
    minutes: '29',
  },
  '170': {
    bar: '170',
    minutes: '27',
  },
  '160': {
    bar: '160',
    minutes: '25',
  },
  '150': {
    bar: '150',
    minutes: '23',
  },
  '140': {
    bar: '140',
    minutes: '21',
  },
  '130': {
    bar: '130',
    minutes: '19',
  },
  '120': {
    bar: '120',
    minutes: '17',
  },
  '110': {
    bar: '110',
    minutes: '15',
  },
};

var SaveTheShoes = React.createClass({
  mixins: [TimerMixin],

  pressure: function() {
    var pressure = PRESSURES_AND_MINUTES[this.state.barPressure];

    return {
      pressureData: pressure,
      selectedBar: pressure.bar,
      minutesOfAir: pressure.minutes
    };
  },

  componentDidMount () {
    this.setInterval(this.decrementTimer, 1000);
  },

  startTimer: function () {
    if (false && this.state.timerRunning) {
      AlertIOS.alert(
          'Stop the timer?',
          'Are you sure you want to stop the timer?', [
          {text: 'Yes', onPress: () => this.setState({timerRunning: false})},
          {text: 'No', onPress: () => this.setState({timerRunning: true})},
          ]);

      return;
    }

    var timeInMilliseconds = this.pressure().minutesOfAir * 60 * 1000;

    this.setState({timerRunning: !this.state.timerRunning, inTime: Moment()});

    // TODO make a timer for each stage (- 15 for RA time currently)
    var timeInMinutes = PRESSURES_AND_MINUTES[this.state.barPressure].minutes - 15;
    this.setState({timeRemaining: Moment.duration(parseInt(timeInMinutes, 10), 'minutes')});
  },

  decrementTimer: function() {
    if (!this.state.timerRunning) {
      return false;
    }

    // TODO - deltatime
    this.setState({timeRemaining: this.state.timeRemaining.subtract(1, 'second')});

    if (this.state.timeRemaining <= 0) {
      AudioPlayer.play('alarm.mp3');

      AlertIOS.alert(
        'Beep beep',
        "Time for relief assembly!"
      );

      this.setState({timerRunning: false});
    }
  },

  getInitialState: function() {
    return {
      barPressure: '110',
      timerRunning: false,
      inTime: null,
      timeRemaining: Moment.duration(0)
    };
  },

  timesRunning: function(pressure) {
    if(this.state.inTime != null){
      var inTime = Moment(this.state.inTime);
      var outTime = Moment(this.state.inTime).add(pressure.minutes, 'minutes');

      var reliefAssemblyTime = Moment(outTime).subtract(15, 'minutes');
      var reliefInTime = Moment(outTime).subtract(10, 'minutes');
    }

    if(this.state.timerRunning) {
      return (

          <View>
          <TimeBox time={inTime} title="Crew Entered at"></TimeBox>
          <TimeBox time={reliefAssemblyTime} title="Relief Assembly"></TimeBox>
          <TimeBox time={reliefInTime} title="Relief In"></TimeBox>
          <TimeBox time={outTime} title="Time Due Out"></TimeBox>
          </View>
          );
    } else {
      return (<View></View>);
    }
  },

  render: function() {
    var pressure = this.pressure().pressureData;
    var selectedBar = this.pressure().selectedBar;
    var minutesOfAir =  this.pressure().minutesOfAir;

    return (
        <View style={[styles.background, styles.base,]}>
        <Text ></Text>
        <Text style={styles.header}>Select Cylinder Pressure </Text>
        <PickerIOS
        selectedValue={this.state.barPressure}
        onValueChange={(barPressure) => this.setState({barPressure})} style={styles.PickerIOS}>
        {Object.keys(PRESSURES_AND_MINUTES).map((barPressure) => (
              <PickerItemIOS
              key={barPressure}
              value={barPressure}
              label={PRESSURES_AND_MINUTES[barPressure].bar}
              />
              )
            )}
        </PickerIOS>

        <CountDownBox time={this.state.timeRemaining}></CountDownBox>
        {this.timesRunning(pressure)}

        <TouchableHighlight style={styles.buttonContainer} onPress={this.startTimer}>
          <Text style={styles.button}>
          {this.state.timerRunning ? 'Stop' : 'Go!'}
        </Text>
          </TouchableHighlight>
          </View>
          );
  },
});

var TimeBox = React.createClass({
  render: function() {
    return (
        <View style={{borderTopWidth: 1, borderTopColor: '#C2C2D6', padding: 10}}>
        <View><Text style={{textAlign: 'center'}}>{this.props.title}</Text></View>
        <View><Text style={{textAlign: 'center', fontSize: 24}}>{this.props.time.format('HH:mm')}</Text></View>
        </View>
        );
  }
});

var CountDownBox = React.createClass({
  render: function() {
    return (
        <View style={{borderTopWidth: 1, borderTopColor: '#C2C2D6', padding: 10}}>
        <View><Text style={{textAlign: 'center'}}>Time Remaining</Text></View>
        <View><Text style={{textAlign: 'center', fontSize: 34}}>{this.props.time.minutes()}′{this.props.time.seconds()}′′</Text></View>
        </View>
        );
  }
});

AppRegistry.registerComponent('SaveTheShoes', () => SaveTheShoes);
AppRegistry.registerComponent('TimeBox', () => TimeBox);
AppRegistry.registerComponent('CountDownBox', () => CountDownBox);

var styles = ({
  base: {
  },

  header: {
    paddingTop: 40,
    fontWeight: 'bold',
    textAlign: 'center',
    fontSize: 18
  },

  pickerIOS: {

  },

  background: {
    backgroundColor: '#EFEFEF',
  },

  button: {
    color: '#007aff'
  },

  buttonContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import dva from 'dva/mobile';
import { ipcRenderer as ipc } from 'electron';
import { parseArgs } from 'electron-window/lib/renderer';
import App from './routes/App';
import { message } from 'antd';

const ipcMiddleware = ({ dispatch, getState }) => next => action => {
  if (action.type === 'ipc') {
    ipc.send('ipc', 'action', action.payload);
  }
  return next(action);
};

const app = dva({
  onAction: [ipcMiddleware],
});
app.router(_ => <App />);
app.start('#root');

ipc.on('ipc', (event, type, payload) => {
  console.log('received', type, payload);
});

ipc.send('ipc', 'init', 1);

parseArgs();
message.error(window.__args__.sourcePath);
<commit_msg>feat: setup middleware and reducerEnhancer<commit_after>import React from 'react';
import dva from 'dva/mobile';
import { ipcRenderer as ipc } from 'electron';
import { parseArgs } from 'electron-window/lib/renderer';
import App from './routes/App';
import { message } from 'antd';

parseArgs();
const { sourcePath } = window.__args__;

function assert(check, msg) {
  if (!check) {
    message.error(msg);
  }
}

function ipcMiddleware({ dispatch, getState }) {
  return next => action => {
    if (action.type === 'ipc') {
      assert(action.method, 'ipcMiddleware: action should have method property');
      ipc.send('ipc', action.method, { ...action.payload, sourcePath });
    }
    return next(action);
  };
}

function repalceStateReducerEnhancer(reducer) {
  return (state, action) => {
    if (action.type === 'replaceState') {
      return action.payload;
    }
    return reducer(state, action);
  };
}

const app = dva({
  onAction: ipcMiddleware,
  onReducer: repalceStateReducerEnhancer,
});
app.router(_ => <App />);
app.start('#root');

ipc.on('ipc', (event, type, payload) => {
  console.log('received', type, payload);
});

ipc.send('ipc', 'init', 1);
<|endoftext|>


<commit_before>"use strict";

var $userInputTitle = $('.input-title');
var $userInputBody = $('.input-body');
var $searchValue = $('.search-input');
var qualities = ['swill', 'plausible', 'genius'];

function checkIdeas() {
  var currentIdeas = localStorage.getItem("ideas");
  if (currentIdeas === null || currentIdeas === undefined) {
    localStorage.setItem("ideas", JSON.stringify([]))
  }
}

function Idea (title, body) {
  this.title = title;
  this.body = body;
  this.quality = 'swill';
  this.id = Date.now();
}

Idea.prototype.storeIdea = function (idea) {
  var newIdeas = getAndParseIdeas();
  newIdeas.push(idea)
  localStorage.setItem("ideas", JSON.stringify(newIdeas))
}

var deleteIdeaFromStorage = function(ideaId) {
  var currentIdeas = getAndParseIdeas();
  currentIdeas.forEach(function(idea, index) {
    if (idea.id === ideaId) {
      currentIdeas.splice(index, 1)
      localStorage.setItem('ideas', JSON.stringify(currentIdeas))
    }
  })
}

function getAndParseIdeas() {
  return JSON.parse(localStorage.getItem('ideas'));
}

function deleteIdeasFromDom() {
  $('.delete').on('click', function(){
    var $idea = $(this).parent()
    deleteIdeaFromStorage($idea.data("id"))
    $idea.remove();
  });
}

function getIdeasFromStorageAndAppendThem() {
  var ideas = getAndParseIdeas();
  if (typeof ideas[0] !== "object") {
    console.log("NOTHINGGG");
  } else {
    for (var i = 0; i < ideas.length; i++) {
      createOutput(ideas[i]);
    }
    deleteIdeasFromDom();
  }
}

function createOutput(idea) {
  $('.all-ideas').prepend(
    `

${idea.title}

      <button class="idea-button delete" type="button"></button>

${idea.body}

      <button class="idea-button upvote" type="button"></button>
      <button class="idea-button downvote" type="button"></button>

quality: ${idea.quality}

`
  );
  upvoteIdea();
  downvoteIdea();
};

function upvoteIdea() {
  $('.upvote').on('click', function(event) {
    console.log('click upvote');
    var $ideaId = $(this).parent().parent().data('id');
    var ideas = getAndParseIdeas();
    for (var i = 0; i < ideas.length; i++) {
      if (ideas[i].id === $ideaId) {
        ideas[i].quality = incrementQuality(ideas[i]);
        localStorage.setItem('ideas', JSON.stringify(ideas));
        $('.all-ideas').children().remove();
        getIdeasFromStorageAndAppendThem();
      }
    };
  });
}

function incrementQuality(idea) {
  if (idea.quality !== 'genius') {
    for (var i = 0; i < qualities.length; i++) {
      if (idea.quality === qualities[i]) {
        return qualities[i + 1];
      }
    };
  } else {
    return 'genius';
  };
}

function downvoteIdea() {
  $('.downvote').on('click', function(event) {
    console.log('click downvote');
    var $ideaId = $(this).parent().parent().data('id');
    var ideas = getAndParseIdeas();
    for (var i = 0; i < ideas.length; i++) {
      if (ideas[i].id === $ideaId) {
        ideas[i].quality = decrementQuality(ideas[i]);
        localStorage.setItem('ideas', JSON.stringify(ideas));
        $('.all-ideas').children().remove();
        getIdeasFromStorageAndAppendThem();
      }
    };
  });
}

function decrementQuality(idea) {
  if (idea.quality !== 'swill') {
    for (var i = 0; i < qualities.length; i++) {
      if (idea.quality === qualities[i]) {
        return qualities[i - 1];
      }
    };
  } else {
    return 'swill';
  };
}

$('.save-button').on('click', function(event) {
  event.preventDefault();
  var title = $userInputTitle.val();
  var body = $userInputBody.val();
  var newIdea = new Idea(title, body);
  createOutput(newIdea);
  newIdea.storeIdea(newIdea);
  upvoteIdea();
  downvoteIdea();
  deleteIdeasFromDom();
  $userInputTitle.val('');
  $userInputBody.val('');
});

checkIdeas();
getIdeasFromStorageAndAppendThem();
<commit_msg>added search functionality<commit_after>"use strict";

var $userInputTitle = $('.input-title');
var $userInputBody = $('.input-body');
var $searchValue = $('.search-input');
var qualities = ['swill', 'plausible', 'genius'];

function checkIdeas() {
  var currentIdeas = localStorage.getItem("ideas");
  if (currentIdeas === null || currentIdeas === undefined) {
    localStorage.setItem("ideas", JSON.stringify([]))
  }
}

function Idea (title, body) {
  this.title = title;
  this.body = body;
  this.quality = 'swill';
  this.id = Date.now();
}

Idea.prototype.storeIdea = function (idea) {
  var newIdeas = getAndParseIdeas();
  newIdeas.push(idea)
  localStorage.setItem("ideas", JSON.stringify(newIdeas))
}

var deleteIdeaFromStorage = function(ideaId) {
  var currentIdeas = getAndParseIdeas();
  currentIdeas.forEach(function(idea, index) {
    if (idea.id === ideaId) {
      currentIdeas.splice(index, 1)
      localStorage.setItem('ideas', JSON.stringify(currentIdeas))
    }
  })
}

function getAndParseIdeas() {
  return JSON.parse(localStorage.getItem('ideas'));
}

function deleteIdeasFromDom() {
  $('.delete').on('click', function(){
    var $idea = $(this).parent()
    deleteIdeaFromStorage($idea.data("id"))
    $idea.remove();
  });
}

function getIdeasFromStorageAndAppendThem() {
  var ideas = getAndParseIdeas();
  if (typeof ideas[0] !== "object") {
    console.log("NOTHINGGG");
  } else {
    for (var i = 0; i < ideas.length; i++) {
      createOutput(ideas[i]);
    }
    deleteIdeasFromDom();
  }
}

function createOutput(idea) {
  $('.all-ideas').prepend(
    `

${idea.title}

      <button class="idea-button delete" type="button"></button>

${idea.body}

      <button class="idea-button upvote" type="button"></button>
      <button class="idea-button downvote" type="button"></button>

quality: ${idea.quality}

`
  );
  upvoteIdea();
  downvoteIdea();
};

function upvoteIdea() {
  $('.upvote').on('click', function(event) {
    console.log('click upvote');
    var $ideaId = $(this).parent().parent().data('id');
    var ideas = getAndParseIdeas();
    for (var i = 0; i < ideas.length; i++) {
      if (ideas[i].id === $ideaId) {
        ideas[i].quality = incrementQuality(ideas[i]);
        localStorage.setItem('ideas', JSON.stringify(ideas));
      }
    };
    $('.all-ideas').children().remove();
    getIdeasFromStorageAndAppendThem();
  });
}

function incrementQuality(idea) {
  if (idea.quality !== 'genius') {
    for (var i = 0; i < qualities.length; i++) {
      if (idea.quality === qualities[i]) {
        return qualities[i + 1];
      }
    };
  } else {
    return 'genius';
  };
}

function downvoteIdea() {
  $('.downvote').on('click', function(event) {
    console.log('click downvote');
    var $ideaId = $(this).parent().parent().data('id');
    var ideas = getAndParseIdeas();
    for (var i = 0; i < ideas.length; i++) {
      if (ideas[i].id === $ideaId) {
        ideas[i].quality = decrementQuality(ideas[i]);
        localStorage.setItem('ideas', JSON.stringify(ideas));
      }
    };
    $('.all-ideas').children().remove();
    getIdeasFromStorageAndAppendThem();
  });
}

function decrementQuality(idea) {
  if (idea.quality !== 'swill') {
    for (var i = 0; i < qualities.length; i++) {
      if (idea.quality === qualities[i]) {
        return qualities[i - 1];
      }
    };
  } else {
    return 'swill';
  };
}

$('.save-button').on('click', function(event) {
  event.preventDefault();
  var title = $userInputTitle.val();
  var body = $userInputBody.val();
  var newIdea = new Idea(title, body);
  createOutput(newIdea);
  newIdea.storeIdea(newIdea);
  upvoteIdea();
  downvoteIdea();
  deleteIdeasFromDom();
  $userInputTitle.val('');
  $userInputBody.val('');
});

$('.search-input').on('keyup', function(event){
 event.preventDefault();
 var $searchBox = $(this).val().toLowerCase();
 var ideas = $('.all-ideas').children();
 ideas.show();
 var hideIdeas = ideas.filter(function() {
 var allIdeas = $(this).children('.user-search-content').text();
 var search = (allIdeas).toLowerCase();
 return !(search.includes($searchBox));
})
hideIdeas.hide();
});

checkIdeas();
getIdeasFromStorageAndAppendThem();
<|endoftext|>


<commit_before>/**
 * Set up dataTables behavior on a rendered HTML table.
 * @function
 * @param {string} selector CSS selector for table
 * @param {object} [options] optional config for DataTable plugin
 * @param {boolean} [option.expand] expand double number of displayed rows for tall browser
 */
function setupTable(selector, options) {
  $(document).ready(function() {
    if (!options) options = {};

    var table = $(selector),
        pageLength = (options.expand && $(window).height() > 900) ? 20 : 10,
        numRows = table.find('tbody tr').length;

    var opts = _.extend({
      lengthMenu: [
        [ 10, 20, 50, -1 ],
        [ '10', '20', '50', 'all' ]
      ],
      pageLength: pageLength,
      paging: numRows > pageLength,
      searching: numRows > pageLength
    }, options);

    table.DataTable(opts);
  });
}
<commit_msg>hide dataTables info line along with other gadgets<commit_after>/**
 * Set up dataTables behavior on a rendered HTML table.
 * @function
 * @param {string} selector CSS selector for table
 * @param {object} [options] optional config for DataTable plugin
 * @param {boolean} [options.expand] double number of displayed rows for tall browser
 */
function setupTable(selector, options) {
  $(document).ready(function() {
    if (!options) options = {};

    var table = $(selector),
        pageLength = (options.expand && $(window).height() > 900) ? 20 : 10,
        numRows = table.find('tbody tr').length,
        gadgets = numRows > pageLength;

    var opts = _.extend({
      lengthMenu: [
        [ 10, 20, 50, -1 ],
        [ '10', '20', '50', 'all' ]
      ],
      pageLength: pageLength,

      searching: gadgets,
      info: gadgets,
      paging: gadgets,
    }, options);

    table.DataTable(opts);
  });
}
<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var Moment = require('moment');
var TimerMixin = require('react-native-timer-mixin');

var {
  AppRegistry,
  PickerIOS,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  PushNotificationIOS
} = React;

var PickerItemIOS = PickerIOS.Item;

var PRESSURES_AND_MINUTES = {
  '300': {
    bar: '300',
    minutes: '51',
  },
  '290': {
    bar: '290',
    minutes: '49',
  },
  '280': {
    bar: '280',
    minutes: '47',
  },
  '270': {
    bar: '270',
    minutes: '45',
  },
  '260': {
    bar: '260',
    minutes: '44',
  },
  '250': {
    bar: '250',
    minutes: '42',
  },
  '240': {
    bar: '240',
    minutes: '40',
  },
  '230': {
    bar: '230',
    minutes: '38',
  },
  '220': {
    bar: '220',
    minutes: '36',
  },
  '210': {
    bar: '210',
    minutes: '34',
  },
  '200': {
    bar: '200',
    minutes: '33',
  },
  '190': {
    bar: '190',
    minutes: '31',
  },
  '180': {
    bar: '180',
    minutes: '29',
  },
  '170': {
    bar: '170',
    minutes: '27',
  },
  '160': {
    bar: '160',
    minutes: '25',
  },
  '150': {
    bar: '150',
    minutes: '23',
  },
  '140': {
    bar: '140',
    minutes: '21',
  },
  '130': {
    bar: '130',
    minutes: '19',
  },
  '120': {
    bar: '120',
    minutes: '17',
  },
  '110': {
    bar: '110',
    minutes: '15',
  },
};

var SaveTheShoes = React.createClass({
  mixins: [TimerMixin],

  pressure: function() {
    var pressure = PRESSURES_AND_MINUTES[this.state.barPressure];

    return {
      pressureData: pressure,
      selectedBar: pressure.bar,
      minutesOfAir: pressure.minutes
    };
  },

  startTimer: function() {
    if (this.state.timerRunning) {
     AlertIOS.alert(
      'Stop the timer?',
      'Are you sure you want to stop the timer?', [
        {text: 'Yes', onPress: () => this.setState({timerRunning: false})},
        {text: 'No'}
      ])

       return;
    }

    var timeInSeconds = this.pressure().minutesOfAir * 60 * 1000;
    this.setTimeout(() => this.setState({timerRunning: false}), timeInSeconds);

    this.setState({timerRunning: true, inTime: Moment()});
  },

  getInitialState: function() {
    return {
      barPressure: '110',
      minutes: 15,
      timerRunning: false,
      inTime: null
    };
  },

  timesRunning: function(pressure) {
    if(this.state.inTime != null){
      var inTime = Moment(this.state.inTime);
      var outTime = Moment(this.state.inTime).add(pressure.minutes, 'minutes');

      var reliefAssemblyTime = Moment(outTime).subtract(15, 'minutes');
      var reliefInTime = Moment(outTime).subtract(10, 'minutes');
    }

    if(this.state.timerRunning) {
      return (
          <Text>
          <Text>Time In: {inTime.format('HH:mm')}</Text>
          <Text>Relief Assembly: {reliefAssemblyTime.format('HH:mm')}</Text>
          <Text>Relief In: {reliefInTime.format('HH:mm')}</Text>
          <Text>Time Out: {outTime.format('HH:mm')}</Text>
          </Text>
          );
    } else {
      return (<Text>Nothing to see here</Text>);
    }
  },

  render: function() {
    var pressure = this.pressure().pressureData;
    var selectedBar = this.pressure().selectedBar;
    var minutesOfAir =  this.pressure().minutesOfAir;

    return (
        <View style={[styles.background, styles.base,]}>
        <Text ></Text>
        <Text style={{fontWeight: 'bold',  textAlign: 'center', fontSize: 18}}>Enter Cylinder Pressure </Text>
        <PickerIOS
          selectedValue={this.state.barPressure}
          onValueChange={(barPressure) => this.setState({barPressure})}>
          {Object.keys(PRESSURES_AND_MINUTES).map((barPressure) => (
            <PickerItemIOS
              key={barPressure}
              value={barPressure}
              label={PRESSURES_AND_MINUTES[barPressure].bar}
              />
            )
          )}
        </PickerIOS>

        <Text>{selectedBar}bar</Text>
        <Text>{minutesOfAir}minutes air</Text>

        {this.timesRunning(pressure)}

        <TouchableHighlight style={styles.buttonContainer} onPress={this.startTimer}>
          <Text style={styles.button}>
            {this.state.timerRunning ? 'Stop' : 'Go!'}
          </Text>
        </TouchableHighlight>
      </View>
    );
  },
});

AppRegistry.registerComponent('SaveTheShoes', () => SaveTheShoes);

var styles = ({
  base: {
    padding: 20,
  },

  background: {
    backgroundColor: '#EFEFEF',
  },

  button: {
    color: '#007aff'
  },

  buttonContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  }

});
<commit_msg>Create a TimeBox component for the times.<commit_after>'use strict';

var React = require('react-native');
var Moment = require('moment');
var TimerMixin = require('react-native-timer-mixin');

var {
  AppRegistry,
  PickerIOS,
  Text,
  View,
  TouchableHighlight,
  AlertIOS,
  PushNotificationIOS
} = React;

var PickerItemIOS = PickerIOS.Item;

var PRESSURES_AND_MINUTES = {
  '300': {
    bar: '300',
    minutes: '51',
  },
  '290': {
    bar: '290',
    minutes: '49',
  },
  '280': {
    bar: '280',
    minutes: '47',
  },
  '270': {
    bar: '270',
    minutes: '45',
  },
  '260': {
    bar: '260',
    minutes: '44',
  },
  '250': {
    bar: '250',
    minutes: '42',
  },
  '240': {
    bar: '240',
    minutes: '40',
  },
  '230': {
    bar: '230',
    minutes: '38',
  },
  '220': {
    bar: '220',
    minutes: '36',
  },
  '210': {
    bar: '210',
    minutes: '34',
  },
  '200': {
    bar: '200',
    minutes: '33',
  },
  '190': {
    bar: '190',
    minutes: '31',
  },
  '180': {
    bar: '180',
    minutes: '29',
  },
  '170': {
    bar: '170',
    minutes: '27',
  },
  '160': {
    bar: '160',
    minutes: '25',
  },
  '150': {
    bar: '150',
    minutes: '23',
  },
  '140': {
    bar: '140',
    minutes: '21',
  },
  '130': {
    bar: '130',
    minutes: '19',
  },
  '120': {
    bar: '120',
    minutes: '17',
  },
  '110': {
    bar: '110',
    minutes: '15',
  },
};

var SaveTheShoes = React.createClass({
  mixins: [TimerMixin],

  pressure: function() {
    var pressure = PRESSURES_AND_MINUTES[this.state.barPressure];

    return {
      pressureData: pressure,
      selectedBar: pressure.bar,
      minutesOfAir: pressure.minutes
    };
  },

  startTimer: function () {
    if (false && this.state.timerRunning) {
      AlertIOS.alert(
          'Stop the timer?',
          'Are you sure you want to stop the timer?', [
          {text: 'Yes', onPress: () => this.setState({timerRunning: false})},
          {text: 'No', onPress: () => this.setState({timerRunning: true})},
          ]);

      return;
    }

    var timeInSeconds = this.pressure().minutesOfAir * 60 * 1000;
    this.setTimeout(() => this.setState({timerRunning: false}), timeInSeconds);

    this.setState({timerRunning: !this.state.timerRunning, inTime: Moment()});
  },

  getInitialState: function() {
    return {
      barPressure: '110',
      minutes: 15,
      timerRunning: false,
      inTime: null
    };
  },

  timesRunning: function(pressure) {
    if(this.state.inTime != null){
      var inTime = Moment(this.state.inTime);
      var outTime = Moment(this.state.inTime).add(pressure.minutes, 'minutes');

      var reliefAssemblyTime = Moment(outTime).subtract(15, 'minutes');
      var reliefInTime = Moment(outTime).subtract(10, 'minutes');
    }

    if(this.state.timerRunning) {
      return (
          <View>
          <TimeBox time={inTime} title="Time In"></TimeBox>
          <TimeBox time={reliefAssemblyTime} title="Relief Assembly"></TimeBox>
          <TimeBox time={reliefInTime} title="Relief In"></TimeBox>
          <TimeBox time={outTime} title="Time Out"></TimeBox>
          </View>
          );
    } else {
      return (<View></View>);
    }
  },

  render: function() {
    var pressure = this.pressure().pressureData;
    var selectedBar = this.pressure().selectedBar;
    var minutesOfAir =  this.pressure().minutesOfAir;

    return (
        <View style={[styles.background, styles.base,]}>
        <Text ></Text>
        <Text style={{fontWeight: 'bold',  textAlign: 'center', fontSize: 18}}>Enter Cylinder Pressure </Text>
        <PickerIOS
        selectedValue={this.state.barPressure}
        onValueChange={(barPressure) => this.setState({barPressure})}>
        {Object.keys(PRESSURES_AND_MINUTES).map((barPressure) => (
              <PickerItemIOS
              key={barPressure}
              value={barPressure}
              label={PRESSURES_AND_MINUTES[barPressure].bar}
              />
              )
            )}
        </PickerIOS>

        <Text>{selectedBar}bar</Text>
        <Text>{minutesOfAir}minutes air</Text>

        {this.timesRunning(pressure)}

        <TouchableHighlight style={styles.buttonContainer} onPress={this.startTimer}>
          <Text style={styles.button}>
          {this.state.timerRunning ? 'Stop' : 'Go!'}
        </Text>
          </TouchableHighlight>
          </View>
          );
  },
});

var TimeBox = React.createClass({
  render: function() {
    return (
        <View>
        <View><Text>{this.props.title}</Text></View>
        <View><Text>{this.props.time.format('HH:mm')}</Text></View>
        </View>
        );
  }
});

AppRegistry.registerComponent('SaveTheShoes', () => SaveTheShoes);
AppRegistry.registerComponent('TimeBox', () => TimeBox);

var styles = ({
  base: {
    padding: 20,
  },

  background: {
    backgroundColor: '#EFEFEF',
  },

  button: {
    color: '#007aff'
  },

  buttonContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  }
});
<|endoftext|>


<commit_before>import util from 'util';
import Ext from './twitch-ext';
import Client from './state-client';

export default class MuxyExtensionsSDK {
  constructor(extensionID) {
    console.log("🦊 Muxy Extensions SDK");

    this.extensionID = extensionID;

    if (util.inIframe()) {
      console.log('Running in an iframe');
    }
    else {
      console.log('Running as top level');
    }

    if (document.referrer.includes('twitch.tv')) { // https://www.twitch.tv/bux0
      console.log('Running on twitch.tv');
    }

    if (location.hostname.includes('.ext-twitch.tv')) { // ka3y28rrgh2f533mxt9ml37fv6zb8k.ext-twitch.tv
      console.log('Loaded from twitch CDN');
    }
    else {

    }

    Ext.onAuthorized(() => {
      if (!auth) {
        return;
      }

      if (this.client) {
        this.client.updateAuth(auth.token);
      }
      else {
        this.client = new Client(this.extensionID, auth.token.auth.channelId);
      }
    });
    // Ext.onContext(this.onContext);
  }

  /**
   * Listen for events from MuxyStore
   * @param type Event type to listen for. (Accumulate, Vote, Rank, Store)
   */
  listen(type) {

  }

  /**
   * Fetch accumulated data
   */
  getAccumulation(accumulationID, start) {
    return this.client.getAccumulation();
  }

  /**
   * Send data to be accumulated
   */
  accumulate() {
    return this.client.accumulate();
  }

  /**
   * Fetch the current vote data
   */
  getVoteData(voteID) {
    return this.client.getVotes(voteID);
  }

  /**
   * Submit a user's vote
   */
  vote(voteID, value) {
    return this.client.vote();
  }

  /**
   * Fetch the current ranking data
   */
  getRankingData(rankID) {
    return this.client.getRank();
  }

  /**
   * Submit data to be ranked
   */
  rank(rankID, value) {
    return this.client.rank();
  }
}<commit_msg>Hook up client to API surface<commit_after>import util from 'util';
import Ext from './twitch-ext';
import Client from './state-client';

export default class MuxyExtensionsSDK {
  constructor(extensionID) {
    console.log("🦊 Muxy Extensions SDK");

    this.extensionID = extensionID;

    if (util.inIframe()) {
      console.log('Running in an iframe');
    }
    else {
      console.log('Running as top level');
    }

    if (document.referrer.includes('twitch.tv')) { // https://www.twitch.tv/bux0
      console.log('Running on twitch.tv');
    }

    if (location.hostname.includes('.ext-twitch.tv')) { // ka3y28rrgh2f533mxt9ml37fv6zb8k.ext-twitch.tv
      console.log('Loaded from twitch CDN');
    }
    else {

    }

    Ext.onAuthorized(() => {
      if (!auth) {
        return;
      }

      if (this.client) {
        this.client.updateAuth(auth.token);
      }
      else {
        this.client = new Client(this.extensionID, auth.token.auth.channelId);
      }
    });
    // Ext.onContext(this.onContext);
  }

  /**
   * Listen for events from MuxyStore
   * @param type Event type to listen for. (Accumulate, Vote, Rank, Store)
   */
  listen(type) {

  }

  /**
   * Fetch accumulated data
   */
  getAccumulation(accumulationID, start) {
    return this.client.getAccumulation(accumulationID, start);
  }

  /**
   * Send data to be accumulated
   */
  accumulate(accumulationID, data) {
    return this.client.accumulate(accumulationID, data);
  }

  /**
   * Fetch the current vote data
   */
  getVoteData(voteID) {
    return this.client.getVotes(voteID);
  }

  /**
   * Submit a user's vote
   */
  vote(voteID, value) {
    return this.client.vote(voteID, {
      value: value
    });
  }

  /**
   * Fetch the current ranking data
   */
  getRankingData(rankID) {
    return this.client.getRank();
  }

  /**
   * Submit data to be ranked
   */
  rank(rankID, value) {
    return this.client.rank({
      key: value
    });
  }
}<|endoftext|>


<commit_before>function normalAlert(data) {
    $("#details").css("color", "#292b2c");
    $("#data_remainder").html(data.total - data.used);
    $("#data_remainder_label").html('remaining');
    $("#data_overage_charges_row").css("display", "none");
}

function overageAlert(data) {
    var overageCost = Math.ceil((data.used - data.total + 1) / 50) * 10;
    overageCost = overageCost >= 200 ? 200 : overageCost;
    $("#details").css("color", "#D71328");
    $("#data_remainder").html(data.used - data.total);
    $("#data_remainder_label").html('over limit');
    $("#data_overage_charges").html(overageCost);
    $("#data_overage_charges_row").css("display", "initial");
}

function daysRemaining() {
    var date = new Date();
    var firstofNextMonth = new Date(date.getFullYear(), date.getMonth() + 1, 1);
    var timeDiff = Math.abs(firstofNextMonth.getTime() - date.getTime());
    return Math.ceil(timeDiff / (1000 * 3600 * 24));
}

function updateStats(data) {
    var percent = 100 * data.used / data.total;
    var percentInt = Math.round(percent);
    var progressBarClasses = $(".progress-bar").attr("class").split(/\s+/);
    var progressBarBackground;
    if (percentInt >= 50 && percentInt < 70) {
        progressBarBackground = 'bg-success';
    } else if (percentInt >= 70 && percentInt < 90) {
        progressBarBackground = 'bg-warning';
    } else if (percentInt >= 90) {
        progressBarBackground = 'bg-danger';
    }
    $.each(progressBarClasses, function(index, item) {
        if (item.startsWith('bg-')) {
            $(".progress-bar").removeClass(item);
        }
    });
    if (percent >= 100) {
        percent = 100;
        overageAlert(data);
    } else {
        normalAlert(data);
    }
    $("#percent").html(percentInt + "%");
    $("#data_used").html(data.used);
    $("#data_total").html(data.total);
    $("#data_units").html(data.unit);
    $("#days_remaining").html(daysRemaining());
    $(".progress-bar").css("width", percent + "%");
    $(".progress-bar").addClass(progressBarBackground);
}

function presentDetails() {
    $("#loader").hide();
    $(".preload").show();
    $(".row").css("display", "flex");
}

function loadComcastQuery() {
    $.get("response", function(data) {
        updateStats(JSON.parse(data));
        presentDetails();
    });
}

function reloadComcastQuery() {
    $(".fa-refresh").addClass("fa-spin");
    $("#percent").addClass("half-transparent");
    $("#details").addClass("half-transparent");
    $(".progress-bar").addClass("half-transparent");
    $.get("response", function(data) {
        updateStats(JSON.parse(data));
        $(".fa-refresh").removeClass("fa-spin");
        $("#percent").removeClass("half-transparent");
        $("#details").removeClass("half-transparent");
        $(".progress-bar").removeClass("half-transparent");
    });
}

$("#reload").click(function() {
    reloadComcastQuery();
});

setInterval(function(){
    reloadComcastQuery();
}, 1800000);

loadComcastQuery();
<commit_msg>Cleaned up main.js<commit_after>function normalAlert(data) {
    $("#details").css("color", "#292b2c");
    $("#data_remainder").html(data.total - data.used);
    $("#data_remainder_label").html('remaining');
    $("#data_overage_charges_row").css("display", "none");
}

function overageAlert(data) {
    var overageCost = Math.ceil((data.used - data.total + 1) / 50) * 10;
    overageCost = overageCost >= 200 ? 200 : overageCost;
    $("#details").css("color", "#D71328");
    $("#data_remainder").html(data.used - data.total);
    $("#data_remainder_label").html('over limit');
    $("#data_overage_charges").html(overageCost);
    $("#data_overage_charges_row").css("display", "initial");
}

function daysRemaining() {
    var date = new Date();
    var firstofNextMonth = new Date(date.getFullYear(), date.getMonth() + 1, 1);
    var timeDiff = Math.abs(firstofNextMonth.getTime() - date.getTime());
    return Math.ceil(timeDiff / (1000 * 3600 * 24));
}

function updateStats(data) {
    var percent = 100 * data.used / data.total;
    var percentInt = Math.round(percent);
    var progressBarClasses = $(".progress-bar").attr("class").split(/\s+/);
    var progressBarBackground;
    if (percentInt >= 50 && percentInt < 70) {
        progressBarBackground = 'bg-success';
    } else if (percentInt >= 70 && percentInt < 90) {
        progressBarBackground = 'bg-warning';
    } else if (percentInt >= 90) {
        progressBarBackground = 'bg-danger';
    }
    $.each(progressBarClasses, function(index, item) {
        if (item.startsWith('bg-')) {
            $(".progress-bar").removeClass(item);
        }
    });
    if (percent >= 100) {
        percent = 100;
        overageAlert(data);
    } else {
        normalAlert(data);
    }
    $("#percent").html(percentInt + "%");
    $("#data_used").html(data.used);
    $("#data_total").html(data.total);
    $("#data_units").html(data.unit);
    $("#days_remaining").html(daysRemaining());
    $(".progress-bar").css("width", percent + "%");
    $(".progress-bar").addClass(progressBarBackground);
}

function presentDetails() {
    $("#loader").hide();
    $(".preload").show();
    $(".row").css("display", "flex");
}

function loadComcastQuery() {
    $.get("response", function(data) {
        updateStats(JSON.parse(data));
        presentDetails();
    });
}

function reloadComcastQuery() {
    $(".fa-refresh").addClass("fa-spin");
    $("header .row").addClass("half-transparent");
    $.get("response", function(data) {
        updateStats(JSON.parse(data));
        $(".fa-refresh").removeClass("fa-spin");
        $("header .row").removeClass("half-transparent");
    });
}

$("#reload").click(function() {
    reloadComcastQuery();
});

setInterval(function(){
    reloadComcastQuery();
}, 1800000);

loadComcastQuery();
<|endoftext|>


<commit_before>'use strict'
var EventEmitter2 = require('eventemitter2').EventEmitter2
var util = require('util')
var logger = require('../util/logger.js')
var parser = require('../parser/parser.js')

function LogEventEmitter () {
  this.DATA_RAW = 'data.raw'
  this.DATA_PARSED = 'data.parsed'

  EventEmitter2.call(this, {
    wildcard: true,
    delemiter: '.',
    newListener: true,
    maxListeners: 30
  })
  this.onAny(function (event) {
    logger.debug('Event received:' + JSON.stringify(arguments))
  })
}

LogEventEmitter.prototype.rawDataEvent = function (data, metadata) {
  this.emit(this.DATA_RAW, data, metadata)
}

LogEventEmitter.prototype.parsedEvent = function (data, metadata) {
  this.emit(this.DATA_PARSED, data, metadata)
}

util.inherits(LogEventEmitter, EventEmitter2)

var logEmitter = new LogEventEmitter()
logEmitter.on('input', console.log)
logEmitter.emit('test', 'hi')

module.exports = logEmitter
<commit_msg>cleanup logEventEmitter<commit_after>'use strict'
var EventEmitter2 = require('eventemitter2').EventEmitter2
var util = require('util')
var logger = require('../util/logger.js')
var parser = require('../parser/parser.js')

function LogEventEmitter () {
  this.DATA_RAW = 'data.raw'
  this.DATA_PARSED = 'data.parsed'

  EventEmitter2.call(this, {
    wildcard: true,
    delemiter: '.',
    newListener: true,
    maxListeners: 30
  })
  this.onAny(function (event) {
    logger.debug('Event received:' + JSON.stringify(arguments))
  })
}

LogEventEmitter.prototype.rawDataEvent = function (data, metadata) {
  this.emit(this.DATA_RAW, data, metadata)
}

LogEventEmitter.prototype.parsedEvent = function (data, metadata) {
  this.emit(this.DATA_PARSED, data, metadata)
}

util.inherits(LogEventEmitter, EventEmitter2)

var logEmitter = new LogEventEmitter()
// logEmitter.on('input', console.log)
// logEmitter.emit('test', 'hi')

module.exports = logEmitter
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import styles from './RunLog.css'

export default class RunLog extends Component {
  componentDidUpdate () {
    this.refs['ensureVisible'].scrollIntoView(true)
  }

  render () {
    const { style, commands } = this.props
    const commandItems = commands.map((command) => {
      const {id, isCurrent, description} = command
      const props = {
        key: id,
        className: classnames({[styles.current]: isCurrent})
      }
      // TODO: add ability to turn autoscroll on and off
      if (isCurrent) props.ref = 'ensureVisible'

      return (
[{id}] : {description}
)
    })
    return (

        {commandItems}

    )
  }
}

/*
Commenting out isRequired for some props for now, using local mock data for first pass
*/
RunLog.propTypes = {
  style: PropTypes.string,
  isConnected: PropTypes.bool.isRequired,
  // TODO(mc, 2017-08-23): use PropTypes.shape (or whatever that method is)
  // instead of object
  commands: PropTypes.arrayOf(PropTypes.object).isRequired
}
<commit_msg>syntax cleanup before merge<commit_after>import React, {Component} from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import styles from './RunLog.css'

export default class RunLog extends Component {
  componentDidUpdate () {
    this.refs.ensureVisible.scrollIntoView(true)
  }

  render () {
    const { style, commands } = this.props
    const commandItems = commands.map((command) => {
      const {id, isCurrent, description} = command
      const props = {
        key: id,
        className: classnames({[styles.current]: isCurrent})
      }
      // TODO: add ability to turn autoscroll on and off
      if (isCurrent) props.ref = 'ensureVisible'

      return (
[{id}] : {description}
)
    })
    return (

        {commandItems}

    )
  }
}

/*
Commenting out isRequired for some props for now, using local mock data for first pass
*/
RunLog.propTypes = {
  style: PropTypes.string,
  isConnected: PropTypes.bool.isRequired,
  // TODO(mc, 2017-08-23): use PropTypes.shape (or whatever that method is)
  // instead of object
  commands: PropTypes.arrayOf(PropTypes.object).isRequired
}
<|endoftext|>


<commit_before>// Dependencies
import React from 'react';
import { render } from 'react-dom';

import './index.html';
import style from '../style/master.scss';
import favicon from './favicon.ico';

import App from '../components/App.js';
import FrontPageController from '../components/FrontPageController';
import TodosController from '../components/TodosController';
import AdminController from '../components/AdminController';
import NotFoundController from '../components/NotFoundController';
import LiveChatController from '../components/LiveChatController';
import LoginController from '../components/LoginController';

// Router
import {
    Router,
    Route,
    IndexRedirect,
    browserHistory,
} from 'react-router';

render((
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRedirect to="/blog"></IndexRedirect>
            <Route path="/blog" component={FrontPageController}></Route>
            <Route path="/about" component={FrontPageController}></Route>
            <Route path="/todos" component={TodosController}></Route>
            <Route path="/admin" component={AdminController}></Route>
            <Route path="/livechat" component={LiveChatController}></Route>
            <Route path="/auth" component={LoginController}></Route>
            <Route path="/*" component={NotFoundController}></Route>
        </Route>
    </Router>
), document.getElementById('app'));

// Remove all noscript element from the page
Array.from(document.querySelectorAll('noscript')).forEach((element) => {
    element.parentElement.removeChild(element);
});
<commit_msg>Prevent browsers from saving scroll position<commit_after>// Dependencies
import React from 'react';
import { render } from 'react-dom';

import './index.html';
import style from '../style/master.scss';
import favicon from './favicon.ico';

import App from '../components/App.js';
import FrontPageController from '../components/FrontPageController';
import TodosController from '../components/TodosController';
import AdminController from '../components/AdminController';
import NotFoundController from '../components/NotFoundController';
import LiveChatController from '../components/LiveChatController';
import LoginController from '../components/LoginController';

// Router
import {
    Router,
    Route,
    IndexRedirect,
    browserHistory,
} from 'react-router';

render((
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <IndexRedirect to="/blog"></IndexRedirect>
            <Route path="/blog" component={FrontPageController}></Route>
            <Route path="/about" component={FrontPageController}></Route>
            <Route path="/todos" component={TodosController}></Route>
            <Route path="/admin" component={AdminController}></Route>
            <Route path="/livechat" component={LiveChatController}></Route>
            <Route path="/auth" component={LoginController}></Route>
            <Route path="/*" component={NotFoundController}></Route>
        </Route>
    </Router>
), document.getElementById('app'));

// Remove all noscript element from the page
Array.from(document.querySelectorAll('noscript')).forEach((element) => {
    element.parentElement.removeChild(element);
});

// Reset scroll position
window.addEventListener('load', (event) => {
    setTimeout(() => {
        window.scrollTo(0, 0);
    }, 10);
});
<|endoftext|>


<commit_before>define (["./_default-component-plugin"], function (DefaultPlugin) {
	var IgniteUIDialogPlugin = IgniteUIDialogPlugin || DefaultPlugin.extend({
		init: function (options) {
			this._super(options);
		},
		getName: function () {
			return "igDialog";
		},
		_getWidgetName: function () {
			return "igDialog";
		},
		getCodeEditorMarkupSnippet: function (descriptor) {
			var snippet = {
				codeString: descriptor.ide._tabStr(descriptor.extraIndent + 1) + "
\n" +
					descriptor.ide._tabStr(descriptor.extraIndent + 2) + "

\n" +
					descriptor.ide._tabStr(descriptor.extraIndent + 1) + "
\n",
				lineCount: 3,
				extraMarkers: [
					{ rowOffset: 1, colOffset: 0, rowCount: 1, colCount: 0 }
				]
			};
			return snippet;
		}
	});
	return IgniteUIDialogPlugin;
});
<commit_msg>#164533 Adding a designer attribute to recognize the DOM elements inside the dialog that need to be picked up as a DOM link.<commit_after>define (["./_default-component-plugin"], function (DefaultPlugin) {
	var IgniteUIDialogPlugin = IgniteUIDialogPlugin || DefaultPlugin.extend({
		init: function (options) {
			this._super(options);
		},
		getName: function () {
			return "igDialog";
		},
		_getWidgetName: function () {
			return "igDialog";
		},
		getCodeEditorMarkupSnippet: function (descriptor) {
			var snippet = {
				codeString: descriptor.ide._tabStr(descriptor.extraIndent + 1) + "
\n" +
					descriptor.ide._tabStr(descriptor.extraIndent + 2) + "

\n" +
					descriptor.ide._tabStr(descriptor.extraIndent + 1) + "
\n",
				lineCount: 3,
				extraMarkers: [
					{ rowOffset: 1, colOffset: 0, rowCount: 1, colCount: 0 }
				]
			};
			return snippet;
		},
		initComponent: function (descriptor) {
			var name = this._getWidgetName(descriptor.type);
			if (window.frames[0].$(descriptor.placeholder)[name]) {
				window.frames[0].$(descriptor.placeholder)[name](descriptor.options);
				window.frames[0].$(descriptor.placeholder).children('ui-igdialog-content').attr('data-design-visible-child', true);
			}
		}
	});
	return IgniteUIDialogPlugin;
});
<|endoftext|>


<commit_before>(function (module, exports, fn) {
    if (typeof module === 'undefined') {
        module = {
            exports: {}
        };

        window.gitIndexedDB = module;
    }

    if (typeof exports === 'undefined') {
        exports = module.exports;
    }

    fn(
        module,
        exports,
        window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB
    );
})(module, exports,
function (module, exports, indexedDB) {
    var version = 1;
    var hashStoreName = 'hashs';
    var hashIndexKey = 'hash';
    var pathStoreName = 'paths';
    var pathIndexKey = 'path';
    var isHash = /^[a-z0-9]{40}$/;

    var deflate, inflate;
    module.exports = function (platform) {
        deflate = platform.deflate || fake;
        inflate = platform.inflate || fake;
        return db;
    };

    var fake = function fake(input, callback) {
        callback(null, input);
    };

    var db = function db(prefix) {
        var context = {};
        'use strict';

        return {
            init: init.bind(context, prefix),
            get: get.bind(context),
            keys: keys.bind(context),
            set: set.bind(context),
            has: has.bind(context),
            del: del.bind(context),
            clear: clear.bind(context, prefix)
        };
    };

    var init = function init(prefix, callback) {
        if (!callback) return init.bind(this, prefix);
        var request = indexedDB.open(prefix, version);
        var context = this;

        request.addEventListener('upgradeneeded', function (e) {
            var db = e.target.result;

            var hashStore = db.createObjectStore(hashStoreName, { keyPath: hashIndexKey });

            var pathStore = db.createObjectStore(pathStoreName, { keyPath: pathIndexKey });
        });
        request.addEventListener('success', function (e) {
            context.db = e.target.result;
            callback();
        });
        request.addEventListener('error', function (e) {
            callback(e);
        });
    };

    var get = function get(key, callback) {
        if (!callback) return get.bind(this, key);
        var context = this;
        if (!callback) {
            return get.bind(this, key);
        }
        if (isHash.test(key)) {
            var transaction = context.db.transaction(hashStoreName);
            var store = transaction.objectStore(hashStoreName);

            var request = store.get(key);

            request.addEventListener('success', function (e) {
                //pretty sure if it goes in as Uint8Array it comes out as such
                callback(null, e.target.result.value);
            });
            request.addEventListener('error', function (e) {
                callback(e);
            });
        } else {
            var transaction = context.db.transaction(pathStoreName);
            var store = transaction.objectStore(pathStoreName);

            var request = store.get(key);

            request.addEventListener('success', function (e) {
                callback(null, e.target.result ? e.target.result.ref : undefined);
            });
            request.addEventListener('error', function (e) {
                callback(e);
            });
        }
    };

    var keys = function keys(prefix, callback) {
        if (!callback) return keys.bind(this, prefix);
        var context = this;

        var transaction = context.db.transaction(pathStoreName);
        var store = transaction.objectStore(pathStoreName);

        if (prefix) {
            var request = store.get(prefix);

            request.addEventListener('success', function (e) {
                if (e.target.result) {
                    callback(null, e.target.result.keys);
                } else {
                    callback(null, []);
                }
            });
            request.addEventListener('error', function (e) {
                callback(e);
            });
        } else {
            var request = store.openCursor();
            var keys = [];
            request.addEventListener('success', function (e) {
                var cursor = e.target.result;

                if (cursor) {
                    keys.push(cursor.value);
                    cursor['continue']();
                }
            });
            request.addEventListener('error', function (e) {
                callback(e);
            });
            transaction.addEventListener('success', function (e) {
                callback(null, keys.reduce(function (arr, key) {
                    return arr.concat(key.keys);
                }, []));
            });
        }
    };

    var set = function set(key, value, callback) {
        if (!callback) return set.bind(this, key, value);
        var context = this;
        if (!callback) {
            return set.bind(context, key, value);
        }

        if (isHash.test(key)) {
            return deflate(value, function (err, deflated) {
                var raw = "";
                for (var i = 0, l = deflated.length; i < l; ++i) {
                  raw += String.fromCharCode(deflated[i]);
                }

                var transaction = context.db.transaction(hashStoreName, 'readwrite');
                var store = transaction.objectStore(hashStoreName);

                var record = {
                    value: value,
                    raw: raw
                };

                record[hashIndexKey] = key;

                var request = store.put(record);

                transaction.addEventListener('complete', function (e) {
                    callback();
                });
                transaction.addEventListener('error', function (e) {
                    callback(e);
                });
            });
        } else {
            var transaction = context.db.transaction(pathStoreName, 'readwrite');
            var store = transaction.objectStore(pathStoreName);
            var record = {
                ref: value
            };
            record[pathIndexKey] = key;

            var request = store.put(record);

            transaction.addEventListener('complete', function (e) {
                callback();
            });
            transaction.addEventListener('error', function (e) {
                callback(e);
            });
        }
    };

    var has = function has(key, callback) {
        if (!callback) return has.bind(this, key);
        var store = pathStoreName;
        var context = this;

        if (isHash.test(key)) {
            store = hashStoreName;
        }

        var transaction = context.db.transaction(store);
        var store = transaction.objectStore(store);

        var request = store.get(key);

        request.addEventListener('success', function (e) {
            callback(null, !!e.target.result);
        });
        request.addEventListener('error', function (e) {
            callback(e);
        });
    };

    var del = function del(key, callback) {
        if (!callback) return del.bind(this, key);

        var store = pathStoreName;
        var context = this;

        if (isHash.test(key)) {
            store = hashStoreName;
        }

        var transaction = context.db.transaction(store, 'readwrite');
        var store = transaction.objectStore(store);

        var request = store.delete(key);

        request.addEventListener('success', function (e) {
            callback();
        });
        request.addEventListener('error', function (e) {
            callback(e);
        });
    };

    var clear = function clear(prefix, callback) {
        if (!callback) return clear.bind(this, prefix);
        var context = this;

        context.db.close();

        var request = indexedDB.deleteDatabase(prefix);
        request.addEventListener('success', function (e) {
            callback();
        });
        request.addEventListener('error', function (e) {
            callback(e);
        });
    };
});<commit_msg>cleaning up the object model a little bit<commit_after>(function (module, exports, fn) {
    'use strict';
    if (typeof module === 'undefined') {
        module = {
            exports: {}
        };

        window.gitIndexedDB = module;
    }

    if (typeof exports === 'undefined') {
        exports = module.exports;
    }

    fn(
        module,
        exports,
        window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB
    );
})(module, exports,
function (module, exports, indexedDB) {
    'use strict';
    var version = 1;
    var hashStoreName = 'hashs';
    var hashIndexKey = 'hash';
    var pathStoreName = 'paths';
    var pathIndexKey = 'path';
    var isHash = /^[a-z0-9]{40}$/;

    var deflate, inflate;
    module.exports = function (platform) {
        deflate = platform.deflate || fake;
        inflate = platform.inflate || fake;
        return db;
    };

    var fake = function fake(input, callback) {
        callback(null, input);
    };

    var db = function db(prefix) {
        var context = {};

        return {
            init: init.bind(context, prefix),
            get: get.bind(context),
            keys: keys.bind(context),
            set: set.bind(context),
            has: has.bind(context),
            del: del.bind(context),
            clear: clear.bind(context, prefix)
        };
    };

    var init = function init(prefix, callback) {
        if (!callback) return init.bind(this, prefix);
        var request = indexedDB.open(prefix, version);
        var context = this;

        request.addEventListener('upgradeneeded', function (e) {
            var db = e.target.result;

            var hashStore = db.createObjectStore(hashStoreName, { keyPath: hashIndexKey });

            var pathStore = db.createObjectStore(pathStoreName, { keyPath: pathIndexKey });
        });
        request.addEventListener('success', function (e) {
            context.db = e.target.result;
            callback();
        });
        request.addEventListener('error', function (e) {
            callback(e);
        });
    };

    var get = function get(key, callback) {
        if (!callback) return get.bind(this, key);
        var context = this;
        if (!callback) {
            return get.bind(this, key);
        }
        if (isHash.test(key)) {
            var transaction = context.db.transaction(hashStoreName);
            var store = transaction.objectStore(hashStoreName);

            var request = store.get(key);

            request.addEventListener('success', function (e) {
                callback(null, e.target.result.value);
            });
            request.addEventListener('error', function (e) {
                callback(e);
            });
        } else {
            var transaction = context.db.transaction(pathStoreName);
            var store = transaction.objectStore(pathStoreName);

            var request = store.get(key);

            request.addEventListener('success', function (e) {
                callback(null, e.target.result ? e.target.result.ref : undefined);
            });
            request.addEventListener('error', function (e) {
                callback(e);
            });
        }
    };

    var keys = function keys(prefix, callback) {
        if (!callback) return keys.bind(this, prefix);
        var context = this;

        var transaction = context.db.transaction(pathStoreName);
        var store = transaction.objectStore(pathStoreName);

        if (prefix) {
            var request = store.get(prefix);

            request.addEventListener('success', function (e) {
                if (e.target.result) {
                    callback(null, e.target.result.keys);
                } else {
                    callback(null, []);
                }
            });
            request.addEventListener('error', function (e) {
                callback(e);
            });
        } else {
            var request = store.openCursor();
            var refs = [];
            request.addEventListener('success', function (e) {
                var cursor = e.target.result;

                if (cursor) {
                    refs.push(cursor.value.ref);
                    cursor['continue']();
                }
            });
            request.addEventListener('error', function (e) {
                callback(e);
            });
            transaction.addEventListener('success', function (e) {
                callback(null, refs);
            });
        }
    };

    var set = function set(key, value, callback) {
        if (!callback) return set.bind(this, key, value);
        var context = this;
        if (!callback) {
            return set.bind(context, key, value);
        }

        if (isHash.test(key)) {
            var transaction = context.db.transaction(hashStoreName, 'readwrite');
            var store = transaction.objectStore(hashStoreName);
            var record = {
                value: value
            };
            record[hashIndexKey] = key;

            var request = store.put(record);

            transaction.addEventListener('complete', function (e) {
                callback();
            });
            transaction.addEventListener('error', function (e) {
                callback(e);
            });
        } else {
            var transaction = context.db.transaction(pathStoreName, 'readwrite');
            var store = transaction.objectStore(pathStoreName);
            var record = {
                ref: value
            };
            record[pathIndexKey] = key;

            var request = store.put(record);

            transaction.addEventListener('complete', function (e) {
                callback();
            });
            transaction.addEventListener('error', function (e) {
                callback(e);
            });
        }
    };

    var has = function has(key, callback) {
        if (!callback) return has.bind(this, key);
        var store = pathStoreName;
        var context = this;

        if (isHash.test(key)) {
            store = hashStoreName;
        }

        var transaction = context.db.transaction(store);
        var store = transaction.objectStore(store);

        var request = store.get(key);

        request.addEventListener('success', function (e) {
            callback(null, !!e.target.result);
        });
        request.addEventListener('error', function (e) {
            callback(e);
        });
    };

    var del = function del(key, callback) {
        if (!callback) return del.bind(this, key);

        var store = pathStoreName;
        var context = this;

        if (isHash.test(key)) {
            store = hashStoreName;
        }

        var transaction = context.db.transaction(store, 'readwrite');
        var store = transaction.objectStore(store);

        var request = store.delete(key);

        request.addEventListener('success', function (e) {
            callback();
        });
        request.addEventListener('error', function (e) {
            callback(e);
        });
    };

    var clear = function clear(prefix, callback) {
        if (!callback) return clear.bind(this, prefix);
        var context = this;

        context.db.close();

        var request = indexedDB.deleteDatabase(prefix);
        request.addEventListener('success', function (e) {
            callback();
        });
        request.addEventListener('error', function (e) {
            callback(e);
        });
    };
});<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const fs = require('fs');

const childProcess = require('child-process-promise');
const express = require('express');

const configPath = path.resolve(process.cwd(), process.argv.slice().pop());
const app = express();

let config = false;

async function build (args) {
    const commands = args.commands;
    const options = {
        cwd: args.path,
    };

    for (let i = 0; i < commands.length; i++) {
        const date = (new Date()).toLocaleDateString('sv-SE', {
            hour: 'numeric',
            minute: 'numeric',
            second: 'numeric',
        });

        console.log(`${ date } Running ${ commands[i] }...`);
        await childProcess.exec(commands[i], options);
        console.log('Done');
    }
}

app.post('/', (req, res) => {
    const target = req.query.target;

    if (config.repos[target]) {
        if(req.get('HTTP_X_GITHUB_EVENT') && req.get('HTTP_X_GITHUB_EVENT') === 'push'){
            build(config.repos[target]);
            res.status(200).send();
        } else {
            res.status(401).send();
        }
    } else {
        res.status(400).send();
    }
});

if(configPath.length < 1 || configPath === __filename ){
    console.error('Didnt\'t get a config file, are you sure you specified one?');
    process.exit(1);
}

fs.access(configPath, fs.R_OK, (err) => {
    if(err){
        console.error('Unable to read file "', configPath, '". Please make sure it exists and is readable.');
        process.exit(1);
    }

    try {
        config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    } catch (err){
        console.error('Unable to parse config file "' + configPath + '". Please make sure it\'s valid.');
        process.exit(1);
    }

    if(config){
        app.listen(config.port, config.host);
    }
});
<commit_msg>Fix previous accidental revert<commit_after>'use strict';

const path = require('path');
const fs = require('fs');

const childProcess = require('child-process-promise');
const express = require('express');

const configPath = path.resolve(process.cwd(), process.argv.slice().pop());
const app = express();

let config = false;

async function build (target, args) {
    const commands = args.commands;
    const options = {
        cwd: args.path,
    };

    console.log(`Deploying ${ target }...`);

    for (let i = 0; i < commands.length; i++) {
        const date = (new Date()).toLocaleDateString('sv-SE', {
            hour: 'numeric',
            minute: 'numeric',
            second: 'numeric',
        });

        console.log(`${ date } Running ${ commands[i] }...`);
        await childProcess.exec(commands[i], options);
        console.log('Done');
    }
}

app.post('/', (req, res) => {
    const target = req.query.target;

    if (config.repos[target]) {
        if (req.get('x-github-event') && req.get('x-github-event') === 'push') {
            build(target, config.repos[target]);
            res.status(200).send();
        } else {
            res.status(401).send();
        }
    } else {
        res.status(400).send();
    }
});

if(configPath.length < 1 || configPath === __filename ){
    console.error('Didnt\'t get a config file, are you sure you specified one?');
    process.exit(1);
}

fs.access(configPath, fs.R_OK, (err) => {
    if(err){
        console.error('Unable to read file "', configPath, '". Please make sure it exists and is readable.');
        process.exit(1);
    }

    try {
        config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    } catch (err){
        console.error('Unable to parse config file "' + configPath + '". Please make sure it\'s valid.');
        process.exit(1);
    }

    if(config){
        app.listen(config.port, config.host);
    }
});
<|endoftext|>