<commit_before>const path = require('path');
const os = require('os');

const forceUtils = require('../lib/forceUtils.js');
const forge = require('node-forge');
const certs = require('../lib/certs.js');
const fs = require('fs');

(function () {
  'use strict';

  module.exports = {
    topic: 'connectedapp',
    command: 'create',
    description: 'Create a connected app in your org',
    help: 'help text for waw:connectedapp:create',
    flags: [{
        name: 'targetusername',
        char: 'u',
        description: 'username or alias for the target org',
        hasValue: true
      },
      {
        name: 'name',
        char: 'n',
        description: 'connected app name',
        hasValue: true,
        required: true
      },
      {
        name: 'label',
        char: 'l',
        description: 'connected app label',
        hasValue: true,
        required: false
      },
      {
        name: 'certificate',
        char: 'r',
        description: 'create and register a certificate',
        required: false,
        hasValue: false,
        type: 'flag'
      },
      {
        name: 'callbackurl',
        char: 'c',
        description: 'callbackUrl (default is "sfdx://success")',
        hasValue: true,
        required: false
      },
      {
        name: 'description',
        char: 'd',
        description: 'connected app description',
        hasValue: true,
        required: false
      },
      {
        // Basic,Api,Web,Full,Chatter,CustomApplications,RefreshToken,OpenID,CustomPermissions,Wave,Eclair
        name: 'scopes',
        char: 's',
        description: 'scopes separated by commas (defaut: Basic, Api, Web, RefreshToken; valid: Basic, Api, Web, Full, Chatter, CustomApplications, RefreshToken, OpenID, CustomPermissions, Wave, Eclair)',
        hasValue: true,
        required: false
      },
      {
        name: 'contactemail',
        char: 'e',
        description: '',
        hasValue: true,
        required: false
      }
    ],
    run(context) {

      const targetUsername = context.flags.targetusername;
      const connectedAppName = context.flags.name;
      let connectedAppLabel = context.flags.label;
      let contactEmail = context.flags.contactemail;

      if (context.flags.label === null || context.flags.label === undefined) {
        connectedAppLabel = connectedAppName;
      }

      let callbackurl = context.flags.callbackurl;
      if (!callbackurl) {
        callbackurl = 'sfdx://success';
      }
      const createCerts = context.flags.certificate;
      let appDescription = context.flags.description;
      if (!appDescription) {
        appDescription = 'generated by waw:connectedapp:create';
      }
      const origScopes = context.flags.scopes;
      let appScopes = [];
      if (origScopes) {
        appScopes = origScopes.split(',');
      } else {
        appScopes = ['Basic', 'Api', 'Web', 'RefreshToken'];
      }

      const generatedConsumerSecret = forceUtils.getConsumerSecret();

      forceUtils.getOrg(targetUsername, (org) => {

        const pki = forge.pki;
        const keys = pki.rsa.generateKeyPair(2048);
        const privKey = forge.pki.privateKeyToPem(keys.privateKey);
        contactEmail = contactEmail || org.getName();

        certs.getSelfSignedCertificate(pki, keys, (cert) => {

          let pubKey;

          if (createCerts) {
            pubKey = pki.certificateToPem(cert);

            fs.writeFile('server.key', privKey, (err) => {
              if (err) {
                return console.log(err); // eslint-disable-line no-console
              }
            });

            fs.writeFile('server.crt', pubKey, (err) => {
              if (err) {
                return console.log(err); // eslint-disable-line no-console
              }
            });
          }

          org.force._getConnection(org, org.config).then((conn) => {

            let metadata;

            if (createCerts) {
              metadata = [{
                contactEmail,
                description: appDescription,
                fullName: connectedAppName,
                label: connectedAppLabel,
                oauthConfig: {
                  callbackUrl: callbackurl,
                  consumerSecret: generatedConsumerSecret,
                  certificate: pubKey,
                  scopes: appScopes
                }
              }];
            } else {
              metadata = [{
                contactEmail,
                description: appDescription,
                fullName: connectedAppName,
                label: connectedAppLabel,
                oauthConfig: {
                  callbackUrl: callbackurl,
                  consumerSecret: generatedConsumerSecret,
                  scopes: appScopes
                }
              }];
            }

            conn.metadata.create('ConnectedApp', metadata, (createErr, results) => {
              if (createErr) {
                console.log(createErr);
              } else if (results.success) {
                conn.metadata.read('ConnectedApp', connectedAppName, (readErr, metadataResult) => {
                  if (readErr) {
                    console.log(readErr);
                  } else {

                    metadataResult.oauthConfig.secret = generatedConsumerSecret;

                    console.log(JSON.stringify(metadataResult)); // eslint-disable-line no-console
                    // console.log('secret', generatedConsumerSecret);
                  }
                });
              } else {
                console.log(results); // eslint-disable-line no-console
              }
            });
          });
        });
      });
    }
  };
}());<commit_msg>Updating consumer secret name (again)<commit_after>const path = require('path');
const os = require('os');

const forceUtils = require('../lib/forceUtils.js');
const forge = require('node-forge');
const certs = require('../lib/certs.js');
const fs = require('fs');

(function () {
  'use strict';

  module.exports = {
    topic: 'connectedapp',
    command: 'create',
    description: 'Create a connected app in your org',
    help: 'help text for waw:connectedapp:create',
    flags: [{
        name: 'targetusername',
        char: 'u',
        description: 'username or alias for the target org',
        hasValue: true
      },
      {
        name: 'name',
        char: 'n',
        description: 'connected app name',
        hasValue: true,
        required: true
      },
      {
        name: 'label',
        char: 'l',
        description: 'connected app label',
        hasValue: true,
        required: false
      },
      {
        name: 'certificate',
        char: 'r',
        description: 'create and register a certificate',
        required: false,
        hasValue: false,
        type: 'flag'
      },
      {
        name: 'callbackurl',
        char: 'c',
        description: 'callbackUrl (default is "sfdx://success")',
        hasValue: true,
        required: false
      },
      {
        name: 'description',
        char: 'd',
        description: 'connected app description',
        hasValue: true,
        required: false
      },
      {
        // Basic,Api,Web,Full,Chatter,CustomApplications,RefreshToken,OpenID,CustomPermissions,Wave,Eclair
        name: 'scopes',
        char: 's',
        description: 'scopes separated by commas (defaut: Basic, Api, Web, RefreshToken; valid: Basic, Api, Web, Full, Chatter, CustomApplications, RefreshToken, OpenID, CustomPermissions, Wave, Eclair)',
        hasValue: true,
        required: false
      },
      {
        name: 'contactemail',
        char: 'e',
        description: '',
        hasValue: true,
        required: false
      }
    ],
    run(context) {

      const targetUsername = context.flags.targetusername;
      const connectedAppName = context.flags.name;
      let connectedAppLabel = context.flags.label;
      let contactEmail = context.flags.contactemail;

      if (context.flags.label === null || context.flags.label === undefined) {
        connectedAppLabel = connectedAppName;
      }

      let callbackurl = context.flags.callbackurl;
      if (!callbackurl) {
        callbackurl = 'sfdx://success';
      }
      const createCerts = context.flags.certificate;
      let appDescription = context.flags.description;
      if (!appDescription) {
        appDescription = 'generated by waw:connectedapp:create';
      }
      const origScopes = context.flags.scopes;
      let appScopes = [];
      if (origScopes) {
        appScopes = origScopes.split(',');
      } else {
        appScopes = ['Basic', 'Api', 'Web', 'RefreshToken'];
      }

      const generatedConsumerSecret = forceUtils.getConsumerSecret();

      forceUtils.getOrg(targetUsername, (org) => {

        const pki = forge.pki;
        const keys = pki.rsa.generateKeyPair(2048);
        const privKey = forge.pki.privateKeyToPem(keys.privateKey);
        contactEmail = contactEmail || org.getName();

        certs.getSelfSignedCertificate(pki, keys, (cert) => {

          let pubKey;

          if (createCerts) {
            pubKey = pki.certificateToPem(cert);

            fs.writeFile('server.key', privKey, (err) => {
              if (err) {
                return console.log(err); // eslint-disable-line no-console
              }
            });

            fs.writeFile('server.crt', pubKey, (err) => {
              if (err) {
                return console.log(err); // eslint-disable-line no-console
              }
            });
          }

          org.force._getConnection(org, org.config).then((conn) => {

            let metadata;

            if (createCerts) {
              metadata = [{
                contactEmail,
                description: appDescription,
                fullName: connectedAppName,
                label: connectedAppLabel,
                oauthConfig: {
                  callbackUrl: callbackurl,
                  consumerSecret: generatedConsumerSecret,
                  certificate: pubKey,
                  scopes: appScopes
                }
              }];
            } else {
              metadata = [{
                contactEmail,
                description: appDescription,
                fullName: connectedAppName,
                label: connectedAppLabel,
                oauthConfig: {
                  callbackUrl: callbackurl,
                  consumerSecret: generatedConsumerSecret,
                  scopes: appScopes
                }
              }];
            }

            conn.metadata.create('ConnectedApp', metadata, (createErr, results) => {
              if (createErr) {
                console.log(createErr);
              } else if (results.success) {
                conn.metadata.read('ConnectedApp', connectedAppName, (readErr, metadataResult) => {
                  if (readErr) {
                    console.log(readErr);
                  } else {

                    metadataResult.oauthConfig.consumerSecret = generatedConsumerSecret;

                    console.log(JSON.stringify(metadataResult)); // eslint-disable-line no-console
                    // console.log('secret', generatedConsumerSecret);
                  }
                });
              } else {
                console.log(results); // eslint-disable-line no-console
              }
            });
          });
        });
      });
    }
  };
}());<|endoftext|>


<commit_before>import React from 'react';
import Relay from 'react-relay';
import classNames from 'classnames';

class Metric extends React.Component {
  static propTypes = {
    pipelineMetric: React.PropTypes.shape({
      label: React.PropTypes.string.isRequired,
      value: React.PropTypes.string,
      url: React.PropTypes.string
    }).isRequired
  };

  render() {
    return (

        {this.props.pipelineMetric.label}
        {this.renderValue()}

    );
  }

  renderValue() {
    const match = String(this.props.pipelineMetric.value).match(/([\d\.]+)(.*)/);
    const valueClasses = "h3 light m0 line-height-1";

    if (match) {
      return (

          {match[1]}
          {match[2]}

      );
    } else if (this.props.pipelineMetric.value) {
      return (
        {this.props.pipelineMetric.value}
      );
    } else {
      return (
        ·
      );
    }
  }
}

export default Relay.createContainer(Metric, {
  fragments: {
    pipelineMetric: () => Relay.QL`
      fragment on PipelineMetric {
        label
        value
        url
      }
    `
  }
});
<commit_msg>Dash instead of dot<commit_after>import React from 'react';
import Relay from 'react-relay';
import classNames from 'classnames';

class Metric extends React.Component {
  static propTypes = {
    pipelineMetric: React.PropTypes.shape({
      label: React.PropTypes.string.isRequired,
      value: React.PropTypes.string,
      url: React.PropTypes.string
    }).isRequired
  };

  render() {
    return (

        {this.props.pipelineMetric.label}
        {this.renderValue()}

    );
  }

  renderValue() {
    const match = String(this.props.pipelineMetric.value).match(/([\d\.]+)(.*)/);
    const valueClasses = "h3 light m0 line-height-1";

    if (match) {
      return (

          {match[1]}
          {match[2]}

      );
    } else if (this.props.pipelineMetric.value) {
      return (
        {this.props.pipelineMetric.value}
      );
    } else {
      return (
        -
      );
    }
  }
}

export default Relay.createContainer(Metric, {
  fragments: {
    pipelineMetric: () => Relay.QL`
      fragment on PipelineMetric {
        label
        value
        url
      }
    `
  }
});
<|endoftext|>


<commit_before>var through = require('pull-through')
var createHash = require('crypto').createHash
var stringify = require('json-stable-stringify')

module.exports = function (size, ts) {
  var start, current, hash, count = 0
  if('function' !== typeof ts)
    throw new Error('ts(obj) must be provided')
  if(isNaN(size) || size < 0)
    throw new Error('size must be a positive integer')
  hash = createHash('sha256')
  return through(function (data) {
    var t = ts(data)
    if('number' !== typeof t)
      t = 'string' === typeof t ? +new Date(t) : +t

    if(!start)
      current = start = t - t % size

    if(t > current + size) {
      this.queue({start: current, length: size, hash: hash.digest('hex'), count: count})
      current += size
      hash = createHash('sha256')
      count = 0
    }

    count ++
    hash.update(stringify(data) + '\n', 'ascii')

  }, function () {
    if(current)
      this.queue({start: current, length: size, hash: hash.digest('hex')})
    this.queue(null)
  })
}
<commit_msg>represent range as {start, end}, not {start, length}<commit_after>var through = require('pull-through')
var createHash = require('crypto').createHash
var stringify = require('json-stable-stringify')
var assert = process.assert
module.exports = function (size, ts) {
  var start, current, hash, count = 0
  if('function' !== typeof ts)
    throw new Error('ts(obj) must be provided')
  if(isNaN(size) || size < 0)
    throw new Error('size must be a positive integer')
  hash = createHash('sha256')
  var prev = 0
  return through(function (data) {
    var t = ts(data)
    if('number' !== typeof t)
      t = 'string' === typeof t ? +new Date(t) : +t

    if(!start)
      current = start = t - t % size

    if(t > current + size) {
      this.queue({start: current, end: current + size, date: new Date(current), hash: hash.digest('hex'), count: count})
      while(t > current + size)
        current += size
      hash = createHash('sha256')
      count = 0
    }

    assert(t > prev, 'timestamp out of order')
    prev = t
    assert(t >= current, 'timestamp too low')
    assert(t <  current + size, 'timestamp too high')

    count ++
    hash.update(stringify(data) + '\n', 'ascii')

  }, function () {
    if(current)
      this.queue({start: current, end: current + size, hash: hash.digest('hex')})
    this.queue(null)
  })
}
<|endoftext|>


<commit_before>
/*

  data-store.js

*/

var fs    = require("fs"),
    low   = require("lowdb"),
    Utils = require("./utils"),
    _     = require("lodash/core"),
    pair  = require("lodash/fromPairs");

/*

  function extendDatabase

  Adds a "get" function so that lowdb can handle key/values.

*/

function extendDatabase(db) {

  // Gets a database key
  db.get = function(key) {
    var val = db.object[key];
    return (Array.isArray(val)) ? db(key) : _(val);
  }

  // Runs a database query
  db.query = function(query, context, next) {
    query.run(db.get(query.query.table).value(), context, next);
  }

  // Executes multiple queries and combines into a single object
  db.queries = function(queries, context, next) {

    var results = {},
        remaining;

    // Ensure that queries is an array
    queries = queries || [];
    if (!Array.isArray(queries)) queries = [queries];

    remaining = queries.length;
    if (!remaining) return next(null, {});

    _.each(queries, function(query) {
      db.query(query.query, context, function(err, result) {
        results = _.extend(results, (query.key) ? pair([[query.key, result]]) : result);
        if (--remaining === 0) next(err, results);
      });
    });

  }

  return db;

}

module.exports = function(options) {

  var db = extendDatabase(low()),
      val;

  // Set defaults
  options = _.extend({ path : "./data", route : "/" }, options);

  Utils.mapFiles(options.path).forEach(function(file) {

    var json = JSON.parse(fs.readFileSync(file.path, "utf8")),
        slug = Utils.makeRoutes(options.route, { folder : file.folder, name : "" })[0]

    // If array, use file name as key. Otherwise, parse keys
    if (Array.isArray(json)) {

      key = (slug + "/" + file.name).replace(/\/+/g, "/").replace(/^\/+/, "");
      db.object[key] = json;

    } else {

      // Create path-like keys using directories (and remove leading "/")
      for (key in json) {

        // Remove leading "/" and make db key-friendly
        val = json[key];
        key = (slug + "/" + key).replace(/\/+/g, "/").replace(/^\/+/, "");
        db.object[key] = val;

      }
    }

  });

  return db;

}
<commit_msg>data-store: allows idx to be specified<commit_after>
/*

  data-store.js

*/

var fs    = require("fs"),
    low   = require("lowdb"),
    Utils = require("./utils"),
    _     = require("lodash/core"),
    pair  = require("lodash/fromPairs");

/*

  function extendDatabase

  Adds a "get" function so that lowdb can handle key/values.

*/

function extendDatabase(db) {

  // Gets a database key
  db.get = function(key) {
    var val = db.object[key];
    return (Array.isArray(val)) ? db(key) : _(val);
  }

  // Runs a database query
  db.query = function(query, context, next) {
    query.run(db.get(query.query.table).value(), context, next);
  }

  // Executes multiple queries and combines into a single object
  db.queries = function(queries, context, next) {

    var results = {},
        remaining;

    // Ensure that queries is an array
    queries = queries || [];
    if (!Array.isArray(queries)) queries = [queries];

    remaining = queries.length;
    if (!remaining) return next(null, {});

    _.each(queries, function(query) {
      db.query(query.query, context, function(err, result) {
        if ("undefined" !== typeof query.idx) result = result[query.idx];
        results = _.extend(results, (query.key) ? pair([[query.key, result]]) : result);
        if (--remaining === 0) next(err, results);
      });
    });

  }

  return db;

}

module.exports = function(options) {

  var db = extendDatabase(low()),
      val;

  // Set defaults
  options = _.extend({ path : "./data", route : "/" }, options);

  Utils.mapFiles(options.path).forEach(function(file) {

    var json = JSON.parse(fs.readFileSync(file.path, "utf8")),
        slug = Utils.makeRoutes(options.route, { folder : file.folder, name : "" })[0]

    // If array, use file name as key. Otherwise, parse keys
    if (Array.isArray(json)) {

      key = (slug + "/" + file.name).replace(/\/+/g, "/").replace(/^\/+/, "");
      db.object[key] = json;

    } else {

      // Create path-like keys using directories (and remove leading "/")
      for (key in json) {

        // Remove leading "/" and make db key-friendly
        val = json[key];
        key = (slug + "/" + key).replace(/\/+/g, "/").replace(/^\/+/, "");
        db.object[key] = val;

      }
    }

  });

  return db;

}
<|endoftext|>


<commit_before>import Utils from '../core/Utils'
import Plugin from './Plugin'

export default class Google extends Plugin {
  constructor (core, opts) {
    super(core, opts)
    this.type = 'acquirer'
    this.files = []
    this.name = 'Google Drive'
    this.icon = `
      <svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fill="#ffffff" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="1.414">
        <path d="M2.955 14.93l2.667-4.62H16l-2.667 4.62H2.955zm2.378-4.62l-2.666 4.62L0 10.31l5.19-8.99 2.666 4.62-2.523 4.37zm10.523-.25h-5.333l-5.19-8.99h5.334l5.19 8.99z"/>
      </svg>
    `
    this.authUrl = 'http://localhost:3020/connect/google'
    // set default options
    const defaultOptions = {}

    // merge default options with the ones set by user
    this.opts = Object.assign({}, defaultOptions, opts)
    this.currentFolder = 'root'
    this.isAuthenticated = false
    this.checkAuthentication()
  }

  focus () {
    this.checkAuthentication()
    .then(res => {
      if (!this.isAuthenticated) {
        this.target.innerHTML = this.renderAuth()
      } else {
        this.renderFolder()
      }
    })
    .catch(err => {
      this.target.innerHTML = this.renderError(err)
    })
  }

  checkAuthentication () {
    return fetch('http://localhost:3020/google/authorize', {
      method: 'get',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then(res => {
      if (res.status >= 200 && res.status <= 300) {
        return res.json().then(data => {
          this.isAuthenticated = data.isAuthenticated
        })
      } else {
        let error = new Error(res.statusText)
        error.response = res
        throw error
      }
    })
    .catch(err => {
      this.target.innerHTML = this.renderError(err)
    })
  }

  getFolder (folderId = this.currentFolder) {
    /**
     * Leave this here
     */
    // fetch('http://localhost:3020/google/logout', {
    //   method: 'get',
    //   credentials: 'include',
    //   headers: {
    //     'Accept': 'application/json',
    //     'Content-Type': 'application/json'
    //   }
    // }).then(res => console.log(res))
    return fetch('http://localhost:3020/google/list', {
      method: 'get',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: {
        dir: folderId || undefined
      }
    })
    .then(res => {
      if (res.status >= 200 && res.status <= 300) {
        return res.json().then(data => {
          let folders = []
          let files = []
          data.items.forEach(item => {
            if (item.mimeType === 'application/vnd.google-apps.folder') {
              folders.push(item)
            } else {
              files.push(item)
            }
          })

          return {
            folders,
            files
          }
        })
      }
    })
  }

  getFile (fileId) {
    if (fileId !== 'string') {
      return console.log('Error: File Id not a string.')
    }
    return fetch('http://localhost:3020/google/get', {
      method: 'get',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: {
        fileId
      }
    })
  }

  install () {
    const caller = this
    this.target = document.querySelector(this.getTarget(this.opts.target, caller))
    return
  }

  renderAuth () {
    return `<div><h1>Authenticate With Google Drive</h1><a href=${ this.authUrl || '#' }>Authenticate</a></div>`
  }

  renderBrowser (data) {
    const folders = data.folders.map(folder => `<li>Folder<button class="GoogleDriveFolder" data-id="${folder.id}" data-title="${folder.title}">${folder.title}</button></li>`)
    const files = data.files.map(file => `<li><button class="GoogleDriveFile" data-id="${file.id}" data-title="${file.title}">${file.title}</button></li>`)
    return `<ul>${folders}</ul><ul>${files}</ul>`
  }

  renderError (err) {
    return `Something went wrong.  Probably our fault. ${err}`
  }

  renderFolder (folder = this.currentFolder) {
    this.getFolder(folder)
    .then(data => {
      this.target.innerHTML = this.renderBrowser(data)
      const folders = Utils.qsa('.GoogleDriveFolder')
      const files = Utils.qsa('.GoogleDriveFile')

      folders.forEach(folder => folder.addEventListener('click', e => this.renderFolder(folder.dataset.id)))
      files.forEach(file => file.addEventListener('click', e => this.getFile(file.dataset.id)))
    })
  }
}
<commit_msg>Fix GoogleDrive icon<commit_after>import Utils from '../core/Utils'
import Plugin from './Plugin'

export default class Google extends Plugin {
  constructor (core, opts) {
    super(core, opts)
    this.type = 'acquirer'
    this.files = []
    this.name = 'Google Drive'
    this.icon = `
      <svg class="UppyModalTab-icon" width="28" height="28" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
        <path d="M2.955 14.93l2.667-4.62H16l-2.667 4.62H2.955zm2.378-4.62l-2.666 4.62L0 10.31l5.19-8.99 2.666 4.62-2.523 4.37zm10.523-.25h-5.333l-5.19-8.99h5.334l5.19 8.99z"/>
      </svg>
    `
    this.authUrl = 'http://localhost:3020/connect/google'
    // set default options
    const defaultOptions = {}

    // merge default options with the ones set by user
    this.opts = Object.assign({}, defaultOptions, opts)
    this.currentFolder = 'root'
    this.isAuthenticated = false
    this.checkAuthentication()
  }

  focus () {
    this.checkAuthentication()
    .then(res => {
      if (!this.isAuthenticated) {
        this.target.innerHTML = this.renderAuth()
      } else {
        this.renderFolder()
      }
    })
    .catch(err => {
      this.target.innerHTML = this.renderError(err)
    })
  }

  checkAuthentication () {
    return fetch('http://localhost:3020/google/authorize', {
      method: 'get',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then(res => {
      if (res.status >= 200 && res.status <= 300) {
        return res.json().then(data => {
          this.isAuthenticated = data.isAuthenticated
        })
      } else {
        let error = new Error(res.statusText)
        error.response = res
        throw error
      }
    })
    .catch(err => {
      this.target.innerHTML = this.renderError(err)
    })
  }

  getFolder (folderId = this.currentFolder) {
    /**
     * Leave this here
     */
    // fetch('http://localhost:3020/google/logout', {
    //   method: 'get',
    //   credentials: 'include',
    //   headers: {
    //     'Accept': 'application/json',
    //     'Content-Type': 'application/json'
    //   }
    // }).then(res => console.log(res))
    return fetch('http://localhost:3020/google/list', {
      method: 'get',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: {
        dir: folderId || undefined
      }
    })
    .then(res => {
      if (res.status >= 200 && res.status <= 300) {
        return res.json().then(data => {
          let folders = []
          let files = []
          data.items.forEach(item => {
            if (item.mimeType === 'application/vnd.google-apps.folder') {
              folders.push(item)
            } else {
              files.push(item)
            }
          })

          return {
            folders,
            files
          }
        })
      }
    })
  }

  getFile (fileId) {
    if (fileId !== 'string') {
      return console.log('Error: File Id not a string.')
    }
    return fetch('http://localhost:3020/google/get', {
      method: 'get',
      credentials: 'include',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: {
        fileId
      }
    })
  }

  install () {
    const caller = this
    this.target = document.querySelector(this.getTarget(this.opts.target, caller))
    return
  }

  renderAuth () {
    return `<div><h1>Authenticate With Google Drive</h1><a href=${ this.authUrl || '#' }>Authenticate</a></div>`
  }

  renderBrowser (data) {
    const folders = data.folders.map(folder => `<li>Folder<button class="GoogleDriveFolder" data-id="${folder.id}" data-title="${folder.title}">${folder.title}</button></li>`)
    const files = data.files.map(file => `<li><button class="GoogleDriveFile" data-id="${file.id}" data-title="${file.title}">${file.title}</button></li>`)
    return `<ul>${folders}</ul><ul>${files}</ul>`
  }

  renderError (err) {
    return `Something went wrong.  Probably our fault. ${err}`
  }

  renderFolder (folder = this.currentFolder) {
    this.getFolder(folder)
    .then(data => {
      this.target.innerHTML = this.renderBrowser(data)
      const folders = Utils.qsa('.GoogleDriveFolder')
      const files = Utils.qsa('.GoogleDriveFile')

      folders.forEach(folder => folder.addEventListener('click', e => this.renderFolder(folder.dataset.id)))
      files.forEach(file => file.addEventListener('click', e => this.getFile(file.dataset.id)))
    })
  }
}
<|endoftext|>


<commit_before>(function (window, $, ch) {
    'use strict';

    if (ch === undefined) {
        throw new window.Error('Expected ch namespace defined.');
    }

    /**
     * Popover improves the native popovers. Popover uses the 'alt' and 'title' attributes to grab its content.
     * @name Popover
     * @class Popover
     * @augments ch.Floats
     * @memberOf ch
     * @param {Object} [conf] Object with configuration properties.
     * @param {Boolean} [conf.fx] Enable or disable UI effects. By default, the effects are enable.
     * @param {String} [conf.points] Sets the points where component will be positioned, specified by configuration or centered by default: "cm cm".
     * @param {String} [conf.offset] Sets the offset in pixels that component will be displaced from original position determined by points. It's specified by configuration or zero by default: "0 0".
     * @returns itself
     * @factorized
     * @see ch.Modal
     * @see ch.Popover
     * @see ch.Zoom
     * @see ch.Flaots
     * @exampleDescription Create a popover.
     * @example
     * var widget = $(".some-element").popover();
     * @exampleDescription Create a new popover with configuration.
     * @example
     * var widget = $("a.example").popover({
     *     "fx": false,
     *     "offset": "10 -10",
     *     "points": "lt rt"
     * });
     * @exampleDescription
     * Now widget is a reference to the popover instance controller.
     * You can set a new content by using widget like this:
     * @example
     * widget.width(300);
     */
    function Popover($el, options) {

        this.init($el, options);

        /**
         * Reference to a internal component instance, saves all the information and configuration properties.
         * @private
         * @type {Object}
         */
        var that = this;

        /**
         * Triggers when the component is ready to use (Since 0.8.0).
         * @name ch.Popover#ready
         * @event
         * @public
         * @since 0.8.0
         * @exampleDescription Following the first example, using widget as popover's instance controller:
         * @example
         * widget.on("ready",function () {
         * this.show();
         * });
         */
        window.setTimeout(function () { that.emit('ready'); }, 50);
    }

    /**
     * Private members
     */
    var $document = $(window.document),

        $body = $('body'),

        parent = ch.util.inherits(Popover, ch.Widget),

        shownbyEvent = {
            'click': ch.onpointertap,
            'mouseenter': ch.onpointerenter
        };

    /**
     * Public members
     */
    Popover.prototype.name = 'popover';

    Popover.prototype.constructor = Popover;

    Popover.prototype._defaults = {
        '_ariaRole': 'dialog',
        '_className': '',
        '_hideDelay': 400,
        'addClass': '',
        'fx': 'fadeIn',
        'width': 'auto',
        'height': 'auto',
        'shownby': 'click',
        'hiddenby': 'button-only',
        'waiting': '

',
        'positioned': 'absolute'
    };

    Popover.prototype.init = function ($el, options) {

        var that = this;

        parent.init.call(this, $el, options);

        this.require('Collapsible', 'Content');

        /**
         * Inner function that resolves the component's layout and returns a static reference.
         * @protected
         * @name ch.Floats#$container
         * @type jQuery
         */
        this.$container = $([
            '
'
        ].join('')).on(ch.onpointertap + '.' + this.name, function (event) {
            event.stopPropagation();
        });

        /**
         * Inner reference to content container. Here is where the content will be added.
         * @protected
         * @name ch.Floats#$content
         * @type jQuery
         * @see ch.Content
         */
        this._$content = $('
').appendTo(this.$container);

        /**
         * Trigger: Add functionality to the trigger if it exists
         */
        if (this._el !== undefined) {
            this._configureTrigger();
        }

        /**
         * Configure abilities
         */
        this._closable();

        this._positioner = new ch.Positioner({
            'target': this.$container,
            'reference': this._options.reference,
            'side': this._options.side,
            'align': this._options.align,
            'offsetX': this._options.offsetX,
            'offsetY': this._options.offsetY,
            'positioned': this._options.positioned
        });

        /**
         * Bind behaviors
         */

        /**
         * TODO: Define this function on prototye and use bind.
         * $document.on(ch.onchangelayout, this.refreshPosition.bind(this));
         */
        this._refreshPositionListener = function () {
            that._positioner.refresh(options);
            return that;
        };

        // Refersh position on:

        // If the popover hasn't got content, .once('show', this._refreshPositionListener)

        // onchangelayout
        $document.on(ch.onchangelayout, this._refreshPositionListener);

        // resize
        ch.viewport.on(ch.onresize, this._refreshPositionListener);

        // _contentchange
        this.on('_contentchange', this._refreshPositionListener)

            .on('hide', function () {
                that.$container.remove(null, true);
            });

        return this;
    };

    /**
     *
     *
     */
    Popover.prototype._configureTrigger = function () {

        var that = this,
            showHandler = (function () {
                var fn = that._toggle;

                if (that._options.hiddenby === 'none' || that._options.hiddenby === 'button-only') {
                    fn = function () {
                        if (!that._shown) {
                            that.show();
                        }
                    };
                }

                return fn;
            }());

        // cloneNode(true) > parameters is required. Opera & IE throws and internal error. Opera mobile breaks.
        this._snippet = this._el.cloneNode(true);

        // Use the trigger as the positioning reference
        this._options.reference = this._options.reference || this._$el;

        // Open event when configured as openable
        if (this._options.shownby !== 'none') {
            this._$el
                .addClass('ch-shownby-' + this._options.shownby)
                .on(shownbyEvent[this._options.shownby] + '.' + this.name, function (event) {
                    ch.util.prevent(event);
                    showHandler();
                });
        }

        // Get a content if it's not defined
        if (this._options.content === undefined) {
            // Content from anchor href
            if (this._el.href) {
                this._options.content = this._el.href;

            // Content from title or alt
            } else if (this._el.title || this._el.alt) {
                // Set the configuration parameter
                this._options.content = this._el.title || this._el.alt;
                // Keep the attributes content into the element for possible usage
                this._el.setAttribute('data-title', this._options.content);
                // Avoid to trigger the native tooltip
                this._el.title = this._el.alt = '';
            }
        }

        /**
         *
         * @protected
         * @name ch.Floats#
         * @type jQuery
         */
        this.$trigger = this._$el.attr({
            'aria-owns': 'ch-' + this.name + '-' + this.uid,
            'aria-haspopup': 'true'
        });
    };

    /**
     * Inner show method. Attach the component layout to the DOM tree.
     * @protected
     * @name ch.Popover#innerShow
     * @function
     * @returns itself
     */
    Popover.prototype.show = function (content) {

        if (!this._enabled) {
            return this;
        }

        // // Do it before content.set, because content.set triggers the position.refresh)
        this.$container.css('z-index', (ch.util.zIndex += 1)).appendTo($body);

        // Open the collapsible
        this._show();

        // // Request the content
        if (content !== undefined) {
            this.content(content);
        }

        return this;
    };

    /**
     * Inner hide method. Hides the component and detach it from DOM tree.
     * @protected
     * @name ch.Popover#innerHide
     * @function
     * @returns itself
     */
    Popover.prototype.hide = function () {
        this._hide();

        return this;
    };

    /**
     * Returns a Boolean if the component's core behavior is shown. That means it will return 'true' if the component is on and it will return false otherwise.
     * @public
     * @function
     * @name ch.Floats#isShown
     * @returns boolean
     */
    Popover.prototype.isShown = function () {
        return this._shown;
    };

    /**
     * Sets or gets the width property of the component's layout. Use it without arguments to get the value. To set a new value pass an argument, could be a Number or CSS value like '300' or '300px'.
     * @public
     * @function
     * @name ch.Floats#width
     * @param {Number|String} [width]
     * @returns itself
     * @see ch.Zarasa#size
     * @see ch.Floats#size
     * @exampleDescription to set the width
     * @example
     * widget.width(700);
     * @exampleDescription to get the width
     * @example
     * widget.width() // 700
     */
    Popover.prototype.width = function (data) {

        if (data === undefined) {
            return this._options.width;
        }

        this.$container.css('width', data);

        this._options.width = data;

        this.refreshPosition();

        return this;
    };

    /**
     * Sets or gets the height of the Float element.
     * @public
     * @function
     * @name ch.Floats#height
     * @returns itself
     * @see ch.Floats#size
     * @exampleDescription to set the height
     * @example
     * widget.height(300);
     * @exampleDescription to get the height
     * @example
     * widget.height // 300
     */
    Popover.prototype.height = function (data) {

        if (data === undefined) {
            return this._options.height;
        }

        this.$container.css('height', data);

        this._options.height = data;

        this.refreshPosition();

        return this;
    };

    /**
     * Refresh the position of the popover if it's shown.
     * @public
     * @function
     * @name ch.Popover#$refreshPosition
     * @example
     * widget.refreshPosition();
     */
    Popover.prototype.refreshPosition = function (options) {
        if (this._shown) {
            this._positioner.refresh(options);
        }

        return this;
    };

    /**
     * Allows to manage the widgets content.
     * @param {String} content - Description.
     * @param {Object} [options] - Description.
     * @private
     */
    Popover.prototype._closable = function () {

        var that = this,
            setTimeout = window.setTimeout,
            clearTimeout = window.clearTimeout,
            hiddenby = this._options.hiddenby,
            pointerTap = ch.onpointertap + '.' + this.name,
            pointerEnter = ch.onpointerenter + '.' + this.name,
            pointerLeave = ch.onpointerleave + '.' + this.name,
            escEvent = ch.onkeyesc || 'touchend',
            timeOut,
            events;

        function hide(event) {
            if (event.target !== that._el && event.target !== that.$container[0]) {
                that.hide();
            }
        }

        function hideTimer() {
            timeOut = setTimeout(function () {
                that.hide();
            }, that._options._hideDelay);
        }

        // Closable none
        if (hiddenby === 'none') { return; }

        // Closable by leaving the widget
        if (hiddenby === 'mouseleave' && that.$trigger !== undefined) {

            events = {};

            events[pointerEnter] = function () {
                clearTimeout(timeOut);
            };

            events[pointerLeave] = hideTimer;

            that.$trigger.on(events);
            that.$container.on(events);
        }

        // Closable button-only
        if (hiddenby === 'button-only' || hiddenby === 'all') {
            // Append a close button
            $('').on(pointerTap, function () {
                that.hide();
            }).prependTo(that.$container);
        }

        if (hiddenby === 'pointers-only' || hiddenby === 'all') {
            ch.shortcuts.add(escEvent, that.uid, function () { that.hide(); });
            that
                .on('show', function () {
                    ch.shortcuts.on(that.uid);
                    $document.on(pointerTap, hide);
                })
                .on('hide', function () {
                    ch.shortcuts.off(that.uid);
                    $document.off(pointerTap, hide);
                });
        }

        return this;
    };

    Popover.prototype._normalizeOptions = function (options) {
        if (typeof options === 'string' || ch.util.is$(options)) {
            options = {
                'content': options
            };
        }
        return options;
    };

    /**
     * Destroys an Popover instance.
     * @public
     * @function
     * @name ch.Popover#destroy
     */
    Popover.prototype.destroy = function () {

        if (this.$trigger !== undefined) {
            this.$trigger
                .off('.' + this.name)
                .removeClass('ch-' + this.name + '-trigger')
                .removeAttr('data-title')
                .removeAttr('aria-owns')
                .removeAttr('aria-haspopup')
                .removeAttr('data-side')
                .removeAttr('data-align')
                .removeAttr('role')
                .attr('alt', this._snippet.alt)
                .attr('title', this._snippet.title);
        }

        $document.off(ch.onchangelayout, this._refreshPositionListener);
        ch.viewport.off(ch.onresize, this._refreshPositionListener);

        parent.destroy.call(this);
    };

    /**
     * Factory
     */
    ch.factory(Popover, Popover.prototype._normalizeOptions);

}(this, this.ch.$, this.ch));<commit_msg>GH-989 Popover: The show() method must receive options to configurate content() method.<commit_after>(function (window, $, ch) {
    'use strict';

    if (ch === undefined) {
        throw new window.Error('Expected ch namespace defined.');
    }

    /**
     * Popover improves the native popovers. Popover uses the 'alt' and 'title' attributes to grab its content.
     * @name Popover
     * @class Popover
     * @augments ch.Floats
     * @memberOf ch
     * @param {Object} [conf] Object with configuration properties.
     * @param {Boolean} [conf.fx] Enable or disable UI effects. By default, the effects are enable.
     * @param {String} [conf.points] Sets the points where component will be positioned, specified by configuration or centered by default: "cm cm".
     * @param {String} [conf.offset] Sets the offset in pixels that component will be displaced from original position determined by points. It's specified by configuration or zero by default: "0 0".
     * @returns itself
     * @factorized
     * @see ch.Modal
     * @see ch.Popover
     * @see ch.Zoom
     * @see ch.Flaots
     * @exampleDescription Create a popover.
     * @example
     * var widget = $(".some-element").popover();
     * @exampleDescription Create a new popover with configuration.
     * @example
     * var widget = $("a.example").popover({
     *     "fx": false,
     *     "offset": "10 -10",
     *     "points": "lt rt"
     * });
     * @exampleDescription
     * Now widget is a reference to the popover instance controller.
     * You can set a new content by using widget like this:
     * @example
     * widget.width(300);
     */
    function Popover($el, options) {

        this.init($el, options);

        /**
         * Reference to a internal component instance, saves all the information and configuration properties.
         * @private
         * @type {Object}
         */
        var that = this;

        /**
         * Triggers when the component is ready to use (Since 0.8.0).
         * @name ch.Popover#ready
         * @event
         * @public
         * @since 0.8.0
         * @exampleDescription Following the first example, using widget as popover's instance controller:
         * @example
         * widget.on("ready",function () {
         * this.show();
         * });
         */
        window.setTimeout(function () { that.emit('ready'); }, 50);
    }

    /**
     * Private members
     */
    var $document = $(window.document),

        $body = $('body'),

        parent = ch.util.inherits(Popover, ch.Widget),

        shownbyEvent = {
            'click': ch.onpointertap,
            'mouseenter': ch.onpointerenter
        };

    /**
     * Public members
     */
    Popover.prototype.name = 'popover';

    Popover.prototype.constructor = Popover;

    Popover.prototype._defaults = {
        '_ariaRole': 'dialog',
        '_className': '',
        '_hideDelay': 400,
        'addClass': '',
        'fx': 'fadeIn',
        'width': 'auto',
        'height': 'auto',
        'shownby': 'click',
        'hiddenby': 'button-only',
        'waiting': '

',
        'positioned': 'absolute'
    };

    Popover.prototype.init = function ($el, options) {

        var that = this;

        parent.init.call(this, $el, options);

        this.require('Collapsible', 'Content');

        /**
         * Inner function that resolves the component's layout and returns a static reference.
         * @protected
         * @name ch.Floats#$container
         * @type jQuery
         */
        this.$container = $([
            '
'
        ].join('')).on(ch.onpointertap + '.' + this.name, function (event) {
            event.stopPropagation();
        });

        /**
         * Inner reference to content container. Here is where the content will be added.
         * @protected
         * @name ch.Floats#$content
         * @type jQuery
         * @see ch.Content
         */
        this._$content = $('
').appendTo(this.$container);

        /**
         * Trigger: Add functionality to the trigger if it exists
         */
        if (this._el !== undefined) {
            this._configureTrigger();
        }

        /**
         * Configure abilities
         */
        this._closable();

        this._positioner = new ch.Positioner({
            'target': this.$container,
            'reference': this._options.reference,
            'side': this._options.side,
            'align': this._options.align,
            'offsetX': this._options.offsetX,
            'offsetY': this._options.offsetY,
            'positioned': this._options.positioned
        });

        /**
         * Bind behaviors
         */

        /**
         * TODO: Define this function on prototye and use bind.
         * $document.on(ch.onchangelayout, this.refreshPosition.bind(this));
         */
        this._refreshPositionListener = function () {
            that._positioner.refresh(options);
            return that;
        };

        // Refersh position on:

        // If the popover hasn't got content, .once('show', this._refreshPositionListener)

        // onchangelayout
        $document.on(ch.onchangelayout, this._refreshPositionListener);

        // resize
        ch.viewport.on(ch.onresize, this._refreshPositionListener);

        // _contentchange
        this.on('_contentchange', this._refreshPositionListener)

            .on('hide', function () {
                that.$container.remove(null, true);
            });

        return this;
    };

    /**
     *
     *
     */
    Popover.prototype._configureTrigger = function () {

        var that = this,
            showHandler = (function () {
                var fn = that._toggle;

                if (that._options.hiddenby === 'none' || that._options.hiddenby === 'button-only') {
                    fn = function () {
                        if (!that._shown) {
                            that.show();
                        }
                    };
                }

                return fn;
            }());

        // cloneNode(true) > parameters is required. Opera & IE throws and internal error. Opera mobile breaks.
        this._snippet = this._el.cloneNode(true);

        // Use the trigger as the positioning reference
        this._options.reference = this._options.reference || this._$el;

        // Open event when configured as openable
        if (this._options.shownby !== 'none') {
            this._$el
                .addClass('ch-shownby-' + this._options.shownby)
                .on(shownbyEvent[this._options.shownby] + '.' + this.name, function (event) {
                    ch.util.prevent(event);
                    showHandler();
                });
        }

        // Get a content if it's not defined
        if (this._options.content === undefined) {
            // Content from anchor href
            if (this._el.href) {
                this._options.content = this._el.href;

            // Content from title or alt
            } else if (this._el.title || this._el.alt) {
                // Set the configuration parameter
                this._options.content = this._el.title || this._el.alt;
                // Keep the attributes content into the element for possible usage
                this._el.setAttribute('data-title', this._options.content);
                // Avoid to trigger the native tooltip
                this._el.title = this._el.alt = '';
            }
        }

        /**
         *
         * @protected
         * @name ch.Floats#
         * @type jQuery
         */
        this.$trigger = this._$el.attr({
            'aria-owns': 'ch-' + this.name + '-' + this.uid,
            'aria-haspopup': 'true'
        });
    };

    /**
     * Inner show method. Attach the component layout to the DOM tree.
     * @protected
     * @name ch.Popover#innerShow
     * @function
     * @returns itself
     */
    Popover.prototype.show = function (content, options) {

        if (!this._enabled) {
            return this;
        }

        // // Do it before content.set, because content.set triggers the position.refresh)
        this.$container.css('z-index', (ch.util.zIndex += 1)).appendTo($body);

        // Open the collapsible
        this._show();

        // // Request the content
        if (content !== undefined) {
            this.content(content, options);
        }

        return this;
    };

    /**
     * Inner hide method. Hides the component and detach it from DOM tree.
     * @protected
     * @name ch.Popover#innerHide
     * @function
     * @returns itself
     */
    Popover.prototype.hide = function () {
        this._hide();

        return this;
    };

    /**
     * Returns a Boolean if the component's core behavior is shown. That means it will return 'true' if the component is on and it will return false otherwise.
     * @public
     * @function
     * @name ch.Floats#isShown
     * @returns boolean
     */
    Popover.prototype.isShown = function () {
        return this._shown;
    };

    /**
     * Sets or gets the width property of the component's layout. Use it without arguments to get the value. To set a new value pass an argument, could be a Number or CSS value like '300' or '300px'.
     * @public
     * @function
     * @name ch.Floats#width
     * @param {Number|String} [width]
     * @returns itself
     * @see ch.Zarasa#size
     * @see ch.Floats#size
     * @exampleDescription to set the width
     * @example
     * widget.width(700);
     * @exampleDescription to get the width
     * @example
     * widget.width() // 700
     */
    Popover.prototype.width = function (data) {

        if (data === undefined) {
            return this._options.width;
        }

        this.$container.css('width', data);

        this._options.width = data;

        this.refreshPosition();

        return this;
    };

    /**
     * Sets or gets the height of the Float element.
     * @public
     * @function
     * @name ch.Floats#height
     * @returns itself
     * @see ch.Floats#size
     * @exampleDescription to set the height
     * @example
     * widget.height(300);
     * @exampleDescription to get the height
     * @example
     * widget.height // 300
     */
    Popover.prototype.height = function (data) {

        if (data === undefined) {
            return this._options.height;
        }

        this.$container.css('height', data);

        this._options.height = data;

        this.refreshPosition();

        return this;
    };

    /**
     * Refresh the position of the popover if it's shown.
     * @public
     * @function
     * @name ch.Popover#$refreshPosition
     * @example
     * widget.refreshPosition();
     */
    Popover.prototype.refreshPosition = function (options) {
        if (this._shown) {
            this._positioner.refresh(options);
        }

        return this;
    };

    /**
     * Allows to manage the widgets content.
     * @param {String} content - Description.
     * @param {Object} [options] - Description.
     * @private
     */
    Popover.prototype._closable = function () {

        var that = this,
            setTimeout = window.setTimeout,
            clearTimeout = window.clearTimeout,
            hiddenby = this._options.hiddenby,
            pointerTap = ch.onpointertap + '.' + this.name,
            pointerEnter = ch.onpointerenter + '.' + this.name,
            pointerLeave = ch.onpointerleave + '.' + this.name,
            escEvent = ch.onkeyesc || 'touchend',
            timeOut,
            events;

        function hide(event) {
            if (event.target !== that._el && event.target !== that.$container[0]) {
                that.hide();
            }
        }

        function hideTimer() {
            timeOut = setTimeout(function () {
                that.hide();
            }, that._options._hideDelay);
        }

        // Closable none
        if (hiddenby === 'none') { return; }

        // Closable by leaving the widget
        if (hiddenby === 'mouseleave' && that.$trigger !== undefined) {

            events = {};

            events[pointerEnter] = function () {
                clearTimeout(timeOut);
            };

            events[pointerLeave] = hideTimer;

            that.$trigger.on(events);
            that.$container.on(events);
        }

        // Closable button-only
        if (hiddenby === 'button-only' || hiddenby === 'all') {
            // Append a close button
            $('').on(pointerTap, function () {
                that.hide();
            }).prependTo(that.$container);
        }

        if (hiddenby === 'pointers-only' || hiddenby === 'all') {
            ch.shortcuts.add(escEvent, that.uid, function () { that.hide(); });
            that
                .on('show', function () {
                    ch.shortcuts.on(that.uid);
                    $document.on(pointerTap, hide);
                })
                .on('hide', function () {
                    ch.shortcuts.off(that.uid);
                    $document.off(pointerTap, hide);
                });
        }

        return this;
    };

    Popover.prototype._normalizeOptions = function (options) {
        if (typeof options === 'string' || ch.util.is$(options)) {
            options = {
                'content': options
            };
        }
        return options;
    };

    /**
     * Destroys an Popover instance.
     * @public
     * @function
     * @name ch.Popover#destroy
     */
    Popover.prototype.destroy = function () {

        if (this.$trigger !== undefined) {
            this.$trigger
                .off('.' + this.name)
                .removeClass('ch-' + this.name + '-trigger')
                .removeAttr('data-title')
                .removeAttr('aria-owns')
                .removeAttr('aria-haspopup')
                .removeAttr('data-side')
                .removeAttr('data-align')
                .removeAttr('role')
                .attr('alt', this._snippet.alt)
                .attr('title', this._snippet.title);
        }

        $document.off(ch.onchangelayout, this._refreshPositionListener);
        ch.viewport.off(ch.onresize, this._refreshPositionListener);

        parent.destroy.call(this);
    };

    /**
     * Factory
     */
    ch.factory(Popover, Popover.prototype._normalizeOptions);

}(this, this.ch.$, this.ch));<|endoftext|>


<commit_before>/**
 * Created by akhil on 01-12-2015.
 */

'use strict';

var mongoose = require('mongoose'),
    FreelancerEmailsSchema = mongoose.model('freelancer_emails'),
    UserSchema = mongoose.model('User'),
    ProductSchema = mongoose.model('freelancer_products'),
    Freelancer_DetailsSchema = mongoose.model('freelancer_landing'),
    OrderSchema = mongoose.model('freelancer_order'),
    mean = require('meanio'),
    nodemailer = require('nodemailer'),
    templates = require('../template'),
    config = require('meanio').loadConfig(),
    _ = require('lodash');

exports.render = function(req, res) {
    res.render('index');
};

exports.getUserSentEmails = function(req,resMain){

    FreelancerEmailsSchema.find({user_id : req.user._id}, function(err,res){
        if(err){
            console.log(err);
            resMain.json({success: false});
        } else{
            resMain.json({success: true, emails : res});
        }
    }).sort({ created: -1 });
};

exports.createFreelancerProduct = function(req,resMain){
    req.body.user_id = req.user._id;
    req.body.username = req.user.name;

    var product_db = new ProductSchema(req.body);
    product_db.save(function(err,res) {
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else
        {
            resMain.json({success: true, product_object : res});
        }
    })
};

exports.createEmail = function(req,resMain){

    var composeObject ={
        user_id : req.user._id,
        recipient_id : 0,
        to_user :req.body.to_user,
        subject:req.body.subject,
        content:req.body.content,
        from:'freelancer'
    };
    var freelancer_db = new FreelancerEmailsSchema(composeObject);
    freelancer_db.save(function(err,res) {
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else
        {
            resMain.json({success: true});
            var mailOptions = {
                to: req.body.to_user,
                from: config.emailFrom
            };
            mailOptions = templates.notify_contrator(mailOptions,req.body);
            sendMail(mailOptions);

            console.log(res);
        }
    })
};

exports.getUserWorkerEmail = function(req,resMain){
    UserSchema.findOne({email : req.query.email}, function(err,res){
        if(err){
            console.log('err',err);
            resMain.json({success: false});
        } else{
            console.log(res);
            if(res != null){
                if((res.roles.indexOf('freelancer')!= -1) && (res.email != req.user.email)){
                    resMain.json({success: true, freelancer_object : res});
                }else{
                    resMain.json({success: false});
                }
            }else{
                resMain.json({success: false});
            }
        }
    })
};

exports.getFreelancerEmail =function(req,resMain){
    UserSchema.find({roles : 'freelancer'}, function(err,res){
        if(err){
            console.log(err);
            resMain.json({success: false});
        } else{
            resMain.json({success: true, freelancer_object :res});
        }
    })
};

exports.putWorker = function(req, resMain){
    Freelancer_DetailsSchema.findOneAndUpdate(
        {$and :[{user_id: req.user._id},{coworkers:{$nin:[req.body.freelancer_id]}}]},
        {$push: {coworkers: req.body.freelancer_id}},
        {safe: true},function(err, res) {
            if(err){
                console.log(err);
                resMain.json({success: false});
            }
            else{
                console.log(res);
                if(res != null){

                    var mailOptions = {
                        to: req.body.freelancer_email,
                        from: config.emailFrom
                    };
                    mailOptions = templates.co_worker_Mail(mailOptions,req.body);
                    sendMail(mailOptions);

                    resMain.json({success: true, status : 0});
                }else{
                    resMain.json({success: true, status : 1});
                }
            }
        });
};

exports.getSearchEmail =function(req,resMain){
    UserSchema.find({roles : 'contractor'}, function(err,res){
        if(err){
            console.log(err);
            resMain.json({success: false});
        } else{
            resMain.json({success: true, contrator_list :res});
        }
    })

};

exports.createOrder = function(req,resMain){

    if(req.user != undefined){
        if(req.user.roles.indexOf('freelancer') != -1){
            req.body.freelancer_id = req.user._id;
            req.body.customer_id = req.user._id;
        }else{
            req.body.customer_id = req.user._id;
        }
    }

    var order_db = new OrderSchema(req.body);
    order_db.save(function(err,res) {
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else
        {
            resMain.json({success: true, order_object : res});
        }
    })
};

exports.updateOrderId = function(req,resMain) {
    OrderSchema.findOneAndUpdate({_id: req.body.order_id}, {paymentStatus: req.body.state}, function(err,res){
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else
        {
            console.log(res);
            if(req.body.state == 'Success'){
                UserSchema.findById(res.freelancer_id, function(err,user){
                    if(err){
                        console.log(err);
                    }else{
                        var mailOptions = {
                            to: req.user.email,
                            bcc: user.email,
                            from: config.emailFrom
                        };
                        mailOptions = templates.paypalSuccess_Mail(mailOptions,req.body);
                        sendMail(mailOptions);
                    }
                });
            }
            else{
                var mailOptions = {
                    to: req.user.email,
                    from: config.emailFrom
                };
                mailOptions = templates.paypalFail_Mail(mailOptions,req.body);
                sendMail(mailOptions);
            }

            resMain.json({success: true, order_object : res});
        }
    })
};

exports.putRequirement = function(req,resMain){
    UserSchema.findById({_id: req.body.freelancer_id}, function(err,res){
        if(err){
            console.log(err);
            resMain.json({success: false});
        }
        else{
            var email_schema ={
                user_id : req.user._id,
                recipient_id : req.body.freelancer_id,
                to_user :res.email,
                subject:'Hi '+res.name+'! You have received the requirements from order #'+req.body.order_id,
                content:req.body.client_Des.description,
                from:'contractor'
            };

            var freelancer_db = new FreelancerEmailsSchema(email_schema);
            freelancer_db.save(function(err,resemail){
                if(err){
                    console.log(err);
                    resMain.json({success:false});
                }
                else{
                    resMain.json({success:true ,email_object:resemail});
                    console.log(resemail);
                }
            })
            var mailOptions = {
                to: res.email,
                from: config.emailFrom
            };

            var clientreq = {
                freelancer : res,
                contractor:req.user.name,
                orderId:req.body.order_id,
                clientreqire:req.body.client_Des
            };
            mailOptions = templates.client_Mail(mailOptions,clientreq);
            sendMail(mailOptions);
            resMain.json({success: true});
        }
    })
};

exports.putProductOrder = function(req,resMain){
    OrderSchema.find({freelancer_id : req.user._id, paymentStatus:'Success'}, function(err,res){
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else{
            var product_id_array = [];
            var customer_id_array = [];
            for (var i =0; i<res.length; i=i+1){
                product_id_array.push(res[i].product_id);
                customer_id_array.push(res[i].customer_id);
            }
            ProductSchema.find({'_id': { $in: product_id_array}}, function(err, products){
                if(err){
                    resMain.json({success: false});
                } else{
                    UserSchema.find({
                        '_id': { $in: customer_id_array}
                    }, function(err, customers){
                        if(err){
                            resMain.json({success: false});
                        } else{

                            resMain.json({success: true,purchased_products : products, my_orders: res, my_customers: customers});
                        }
                    })
                }
            });
        }

    })
};

exports.submitWork = function(req,resMain) {
    var d = new Date();
    var date_string = d.getDate()+'-'+d.getMonth()+'-'+d.getFullYear();
    var deliverable = {date : date_string, url : req.body.work_url};
    OrderSchema.findOneAndUpdate({_id: req.body.order_id},
        {$push: {deliverables: deliverable}},
        {safe: true},function(err, res){
            if(err){
                console.log(err);
                resMain.json({success: false});
            }else{
                resMain.json({success: true,deliverable : deliverable});
                UserSchema.findById(res.customer_id, function(err,customer){
                    if(err){
                        console.log(err);
                    }else{

                        var mailOptions = {
                            to: customer.email,
                            bcc: req.user.email,
                            from: config.emailFrom
                        };
                        var email_content ={
                            order: res,
                            deliverable : deliverable,
                            freelancer : req.user,
                            customer : customer
                        }

                        mailOptions = templates.deliverable_notify(mailOptions,email_content);
                        sendMail(mailOptions);
                    }
                });
            }
        });
};

exports.getClientWork = function(req, resMain){
    OrderSchema.find({customer_id : req.user._id , paymentStatus:'Success'}, function(err, orders){
        if(err){
            console.log(err);
            resMain.json({success: false});
        }else{
            var product_id_array = [];
            var freelancer_id_array = [];
            for (var i =0; i<orders.length; i=i+1){
                product_id_array.push(orders[i].product_id);
                freelancer_id_array.push(orders[i].freelancer_id);
            }

            ProductSchema.find({'_id': { $in: product_id_array}}, function(err, products) {
                if (err) {
                    resMain.json({success: false});
                } else {
                    UserSchema.find({
                        '_id': { $in: freelancer_id_array}
                    }, function(err, freelancer){
                        if(err){
                            resMain.json({success: false});
                        }
                        else{
                            resMain.json({success: true,purchased_products : products, my_orders: orders, my_freelancer: freelancer});
                        }
                    });
                }
            });

        }
    });
};

function sendMail(mailOptions) {
    var transport = nodemailer.createTransport(config.mailer);
    transport.sendMail(mailOptions, function(error, success) {
        if (error) console.log(error);
        else console.log(success);
    });
}<commit_msg>update work approval status<commit_after>/**
 * Created by akhil on 01-12-2015.
 */

'use strict';

var mongoose = require('mongoose'),
    FreelancerEmailsSchema = mongoose.model('freelancer_emails'),
    UserSchema = mongoose.model('User'),
    ProductSchema = mongoose.model('freelancer_products'),
    Freelancer_DetailsSchema = mongoose.model('freelancer_landing'),
    OrderSchema = mongoose.model('freelancer_order'),
    mean = require('meanio'),
    nodemailer = require('nodemailer'),
    templates = require('../template'),
    config = require('meanio').loadConfig(),
    _ = require('lodash');

exports.render = function(req, res) {
    res.render('index');
};

exports.getUserSentEmails = function(req,resMain){

    FreelancerEmailsSchema.find({user_id : req.user._id}, function(err,res){
        if(err){
            console.log(err);
            resMain.json({success: false});
        } else{
            resMain.json({success: true, emails : res});
        }
    }).sort({ created: -1 });
};

exports.createFreelancerProduct = function(req,resMain){
    req.body.user_id = req.user._id;
    req.body.username = req.user.name;

    var product_db = new ProductSchema(req.body);
    product_db.save(function(err,res) {
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else
        {
            resMain.json({success: true, product_object : res});
        }
    })
};

exports.createEmail = function(req,resMain){

    var composeObject ={
        user_id : req.user._id,
        recipient_id : 0,
        to_user :req.body.to_user,
        subject:req.body.subject,
        content:req.body.content,
        from:'freelancer'
    };
    var freelancer_db = new FreelancerEmailsSchema(composeObject);
    freelancer_db.save(function(err,res) {
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else
        {
            resMain.json({success: true});
            var mailOptions = {
                to: req.body.to_user,
                from: config.emailFrom
            };
            mailOptions = templates.notify_contrator(mailOptions,req.body);
            sendMail(mailOptions);

            console.log(res);
        }
    })
};

exports.getUserWorkerEmail = function(req,resMain){
    UserSchema.findOne({email : req.query.email}, function(err,res){
        if(err){
            console.log('err',err);
            resMain.json({success: false});
        } else{
            console.log(res);
            if(res != null){
                if((res.roles.indexOf('freelancer')!= -1) && (res.email != req.user.email)){
                    resMain.json({success: true, freelancer_object : res});
                }else{
                    resMain.json({success: false});
                }
            }else{
                resMain.json({success: false});
            }
        }
    })
};

exports.getFreelancerEmail =function(req,resMain){
    UserSchema.find({roles : 'freelancer'}, function(err,res){
        if(err){
            console.log(err);
            resMain.json({success: false});
        } else{
            resMain.json({success: true, freelancer_object :res});
        }
    })
};

exports.putWorker = function(req, resMain){
    Freelancer_DetailsSchema.findOneAndUpdate(
        {$and :[{user_id: req.user._id},{coworkers:{$nin:[req.body.freelancer_id]}}]},
        {$push: {coworkers: req.body.freelancer_id}},
        {safe: true},function(err, res) {
            if(err){
                console.log(err);
                resMain.json({success: false});
            }
            else{
                console.log(res);
                if(res != null){

                    var mailOptions = {
                        to: req.body.freelancer_email,
                        from: config.emailFrom
                    };
                    mailOptions = templates.co_worker_Mail(mailOptions,req.body);
                    sendMail(mailOptions);

                    resMain.json({success: true, status : 0});
                }else{
                    resMain.json({success: true, status : 1});
                }
            }
        });
};

exports.getSearchEmail =function(req,resMain){
    UserSchema.find({roles : 'contractor'}, function(err,res){
        if(err){
            console.log(err);
            resMain.json({success: false});
        } else{
            resMain.json({success: true, contrator_list :res});
        }
    })

};

exports.createOrder = function(req,resMain){

    if(req.user != undefined){
        if(req.user.roles.indexOf('freelancer') != -1){
            req.body.freelancer_id = req.user._id;
            req.body.customer_id = req.user._id;
        }else{
            req.body.customer_id = req.user._id;
        }
    }

    var order_db = new OrderSchema(req.body);
    order_db.save(function(err,res) {
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else
        {
            resMain.json({success: true, order_object : res});
        }
    })
};

exports.updateOrderId = function(req,resMain) {
    OrderSchema.findOneAndUpdate({_id: req.body.order_id}, {paymentStatus: req.body.state}, function(err,res){
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else
        {
            console.log(res);
            if(req.body.state == 'Success'){
                UserSchema.findById(res.freelancer_id, function(err,user){
                    if(err){
                        console.log(err);
                    }else{
                        var mailOptions = {
                            to: req.user.email,
                            bcc: user.email,
                            from: config.emailFrom
                        };
                        mailOptions = templates.paypalSuccess_Mail(mailOptions,req.body);
                        sendMail(mailOptions);
                    }
                });
            }
            else{
                var mailOptions = {
                    to: req.user.email,
                    from: config.emailFrom
                };
                mailOptions = templates.paypalFail_Mail(mailOptions,req.body);
                sendMail(mailOptions);
            }

            resMain.json({success: true, order_object : res});
        }
    })
};

exports.putRequirement = function(req,resMain){
    UserSchema.findById({_id: req.body.freelancer_id}, function(err,res){
        if(err){
            console.log(err);
            resMain.json({success: false});
        }
        else{
            var email_schema ={
                user_id : req.user._id,
                recipient_id : req.body.freelancer_id,
                to_user :res.email,
                subject:'Hi '+res.name+'! You have received the requirements from order #'+req.body.order_id,
                content:req.body.client_Des.description,
                from:'contractor'
            };

            var freelancer_db = new FreelancerEmailsSchema(email_schema);
            freelancer_db.save(function(err,resemail){
                if(err){
                    console.log(err);
                    resMain.json({success:false});
                }
                else{
                    resMain.json({success:true ,email_object:resemail});
                    console.log(resemail);
                }
            })
            var mailOptions = {
                to: res.email,
                from: config.emailFrom
            };

            var clientreq = {
                freelancer : res,
                contractor:req.user.name,
                orderId:req.body.order_id,
                clientreqire:req.body.client_Des
            };
            mailOptions = templates.client_Mail(mailOptions,clientreq);
            sendMail(mailOptions);
            resMain.json({success: true});
        }
    })
};

exports.putProductOrder = function(req,resMain){
    OrderSchema.find({freelancer_id : req.user._id, paymentStatus:'Success'}, function(err,res){
        if (err) {
            console.log(err);
            resMain.json({success: false});
        }
        else{
            var product_id_array = [];
            var customer_id_array = [];
            for (var i =0; i<res.length; i=i+1){
                product_id_array.push(res[i].product_id);
                customer_id_array.push(res[i].customer_id);
            }
            ProductSchema.find({'_id': { $in: product_id_array}}, function(err, products){
                if(err){
                    resMain.json({success: false});
                } else{
                    UserSchema.find({
                        '_id': { $in: customer_id_array}
                    }, function(err, customers){
                        if(err){
                            resMain.json({success: false});
                        } else{

                            resMain.json({success: true,purchased_products : products, my_orders: res, my_customers: customers});
                        }
                    })
                }
            });
        }

    })
};

exports.submitWork = function(req,resMain) {
    var d = new Date();
    var date_string = d.getDate()+'-'+d.getMonth()+'-'+d.getFullYear();
    var deliverable = {date : date_string, url : req.body.work_url};
    OrderSchema.findOneAndUpdate({_id: req.body.order_id},
        {$push: {deliverables: deliverable}},
        {safe: true},function(err, res){
            if(err){
                console.log(err);
                resMain.json({success: false});
            }else{
                resMain.json({success: true,deliverable : deliverable});
                UserSchema.findById(res.customer_id, function(err,customer){
                    if(err){
                        console.log(err);
                    }else{

                        var mailOptions = {
                            to: customer.email,
                            bcc: req.user.email,
                            from: config.emailFrom
                        };
                        var email_content ={
                            order: res,
                            deliverable : deliverable,
                            freelancer : req.user,
                            customer : customer
                        }

                        mailOptions = templates.deliverable_notify(mailOptions,email_content);
                        sendMail(mailOptions);
                    }
                });
            }
        });
};
exports.updateWorkApprovalStatus = function(req, resMain){
    OrderSchema.findByIdAndUpdate(req.body.order_id, {approval_status: true}, function(err, res){
        if(err){
            console.log(err);
            resMain.json({success: false});
        }else{
            resMain.json({success: true});
            UserSchema.findById(res.freelancer_id, function(err, freelancer){

                if(err){

                }else{
                    var mailOptions = {
                        to: freelancer.email,
                        from: config.emailFrom
                    };
                    var email_content ={
                        order: res,
                        freelancer : freelancer,
                        customer : req.user
                    }

                    mailOptions = templates.deliverable_notify(mailOptions,email_content);
                    sendMail(mailOptions);
                }

            });
        }
    });
};
exports.getClientWork = function(req, resMain){
    OrderSchema.find({customer_id : req.user._id , paymentStatus:'Success'}, function(err, orders){
        if(err){
            console.log(err);
            resMain.json({success: false});
        }else{
            var product_id_array = [];
            var freelancer_id_array = [];
            for (var i =0; i<orders.length; i=i+1){
                product_id_array.push(orders[i].product_id);
                freelancer_id_array.push(orders[i].freelancer_id);
            }

            ProductSchema.find({'_id': { $in: product_id_array}}, function(err, products) {
                if (err) {
                    resMain.json({success: false});
                } else {
                    UserSchema.find({
                        '_id': { $in: freelancer_id_array}
                    }, function(err, freelancer){
                        if(err){
                            resMain.json({success: false});
                        }
                        else{
                            resMain.json({success: true,purchased_products : products, my_orders: orders, my_freelancer: freelancer});
                        }
                    });
                }
            });

        }
    });
};

function sendMail(mailOptions) {
    var transport = nodemailer.createTransport(config.mailer);
    transport.sendMail(mailOptions, function(error, success) {
        if (error) console.log(error);
        else console.log(success);
    });
}<|endoftext|>


<commit_before>
var cobs = require('../..'),
    fs = require('fs');

var runtime = {
    display: function(msg) {
        console.log(msg);
    }
}

function runFile(filename) {
    var text = fs.readFileSync(filename).toString();
    var parser = new cobs.Parser(text);
    var program = parser.parseProgram();
    cobs.run(program.command.compile(program), runtime, program);
};

process.argv.forEach(function(val) {
    if (val.slice(-5) == ".cobs" || val.slice(-4) == ".cob")
        runFile(val);
});

<commit_msg>Refactor hellopgm sample to use compileProgramFile<commit_after>
var cobs = require('../..'),
    fs = require('fs');

var runtime = {
    display: function(msg) {
        console.log(msg);
    }
}

function runFile(filename) {
    cobs.compileProgramFile(filename).run(runtime);
};

process.argv.forEach(function(val) {
    if (val.slice(-5) == ".cobs" || val.slice(-4) == ".cob")
        runFile(val);
});

<|endoftext|>


<commit_before>'use strict';

/*

The following section defines the Constants.h file

*/

// PIN Constants
const HackH = 48;
const HackA = 26;
const HackC = 24;
const HackK = 46;
const MiddleA = 36;
const ColaC = 38;
const ColaO = 28;
const ColaL = 40;
const ColaA = 30;
const RedZero = 44;
const RedOne = 34;
const RedTwo = 50;
const RedThree = 42;
const RedFour = 22;
const RedFive = 32;

// Lights
const Lights = [
    HackH,
    HackA,
    HackC,
    HackK,
    MiddleA,
    ColaC,
    ColaO,
    ColaL,
    ColaA,
    RedZero,
    RedOne,
    RedTwo,
    RedThree,
    RedFour,
    RedFive
];

// Letters
const letters = [
    HackH,
    HackA,
    HackC,
    HackK,
    MiddleA,
    ColaC,
    ColaO,
    ColaL,
    ColaA,
];

// Background
const background = [
    RedZero,
    RedOne,
    RedTwo,
    RedThree,
    RedFour,
    RedFive
];

// Timeouts
const none = 0;
const blinky = 1000;
const minimal = 500;
const normal = 800;
const ish = 2000;
const extended = 4000;

// Constants
const PATTERN_OFF = 0; // HIGH
const PATTERN_ON = 1; // LOW

/*

The following section defines global methods needed

*/

const signDrawer = require('./signDrawer.js');

const lightsState = [ ];

Lights.forEach(function (value, idx) {
    lightsState[idx] = PATTERN_OFF;
});

const delay = function(time) {
    const entryTime = Date.now();
    while (true) {
        if (Date.now() - entryTime >= time) {
            break;
        }
    }
}

const digitalWrite = function(pin, highOrLow) {
    if (typeof(pin) === 'undefined') {
        throw new Error(`You have an undefined pin being set to: ${highOrLow}`)
    }
     console.log(`digitalWrite light:${Lights.indexOf(pin)} pin:${pin} highOrLow:${highOrLow}`);
     lightsState[Lights.indexOf(pin)] = highOrLow ? PATTERN_ON : PATTERN_OFF;
     signDrawer.drawSign(lightsState);

}

const sizeof = function(value) {
    return value.length;
}

const random = function(min, max) {
    // Min inclusive, max exclusive
    return Math.floor(Math.random() * ((max - 0) - min) + min);
}

const log = function(message, integer) {
    console.log(`${message} ${typeof(integer) !== 'undefined' ? integer : ''}`);
}

/*

The following section attempts, transpile, and run the arduino code

*/

const fs = require('fs');

let pathToArduinoCode = './CocaCola/CocaCola.ino';
let test = false;
let verbose = false;

process.argv.forEach(function (value, index, array) {

    if ((value == "--file" || value == "-f") && array[index+1]) {
        pathToArduinoCode = array[index+1];
    } else if (value == "--test" || value == "-t") {
        test = true;
    } else if (value == "--verbose" || value == "-v") {
        verbose = true;
    }

});

const arduinoCode = fs.readFileSync(pathToArduinoCode).toString();

const arduinoCodeParts = arduinoCode.split("// )'(");

const runableCode = arduinoCodeParts[1]
    .replace(/int(\s*_*[A-Za-z]+_*\d*\s*)=/g, 'var$1=') // Replace any instance of "int variable = n"
    .replace(/int /g, '') // Remove "int" from any instance of "int variable"
    .replace(/void loop\(\) {/, 'while (true) {') // Turn our main method into a while loop
    .replace(/void (\s*_*[A-Za-z]+_*\d*\s*)/g, ' var $1 = function'); // Replace any "void function" with a javascript function definition

if (runableCode.indexOf(")\n") != -1) {
        throw new Error(`${pathToArduinoCode}: )\\n found without a semicolon`);
}

if (verbose) {

    console.log(`
    ######################################

    Loading: ${pathToArduinoCode}

    ######################################

    ${arduinoCode}

    ######################################

    Runable Code:

    ######################################

    ${runableCode}

    ######################################

    Running code:

    ######################################
    `);

}

if (test) {
    // Will pass the test flag to verify quickly
    console.log(`OK: ${pathToArduinoCode}`);
    process.exit(0);
}

eval(runableCode);
<commit_msg>teach emulator.js how to handle C arrays<commit_after>'use strict';

/*

The following section defines the Constants.h file

*/

// PIN Constants
const HackH = 48;
const HackA = 26;
const HackC = 24;
const HackK = 46;
const MiddleA = 36;
const ColaC = 38;
const ColaO = 28;
const ColaL = 40;
const ColaA = 30;
const RedZero = 44;
const RedOne = 34;
const RedTwo = 50;
const RedThree = 42;
const RedFour = 22;
const RedFive = 32;

// Lights
const Lights = [
    HackH,
    HackA,
    HackC,
    HackK,
    MiddleA,
    ColaC,
    ColaO,
    ColaL,
    ColaA,
    RedZero,
    RedOne,
    RedTwo,
    RedThree,
    RedFour,
    RedFive
];

// Letters
const letters = [
    HackH,
    HackA,
    HackC,
    HackK,
    MiddleA,
    ColaC,
    ColaO,
    ColaL,
    ColaA,
];

// Background
const background = [
    RedZero,
    RedOne,
    RedTwo,
    RedThree,
    RedFour,
    RedFive
];

// Timeouts
const none = 0;
const blinky = 1000;
const minimal = 500;
const normal = 800;
const ish = 2000;
const extended = 4000;

// Constants
const PATTERN_OFF = 0; // HIGH
const PATTERN_ON = 1; // LOW

/*

The following section defines global methods needed

*/

const signDrawer = require('./signDrawer.js');

const lightsState = [ ];

Lights.forEach(function (value, idx) {
    lightsState[idx] = PATTERN_OFF;
});

const delay = function(time) {
    const entryTime = Date.now();
    while (true) {
        if (Date.now() - entryTime >= time) {
            break;
        }
    }
}

const digitalWrite = function(pin, highOrLow) {
    if (typeof(pin) === 'undefined') {
        throw new Error(`You have an undefined pin being set to: ${highOrLow}`)
    }
     console.log(`digitalWrite light:${Lights.indexOf(pin)} pin:${pin} highOrLow:${highOrLow}`);
     lightsState[Lights.indexOf(pin)] = highOrLow ? PATTERN_ON : PATTERN_OFF;
     signDrawer.drawSign(lightsState);

}

const sizeof = function(value) {
    return value.length;
}

const random = function(min, max) {
    // Min inclusive, max exclusive
    return Math.floor(Math.random() * ((max - 0) - min) + min);
}

const log = function(message, integer) {
    console.log(`${message} ${typeof(integer) !== 'undefined' ? integer : ''}`);
}

/*

The following section attempts, transpile, and run the arduino code

*/

const fs = require('fs');

let pathToArduinoCode = './CocaCola/CocaCola.ino';
let test = false;
let verbose = false;

process.argv.forEach(function (value, index, array) {

    if ((value == "--file" || value == "-f") && array[index+1]) {
        pathToArduinoCode = array[index+1];
    } else if (value == "--test" || value == "-t") {
        test = true;
    } else if (value == "--verbose" || value == "-v") {
        verbose = true;
    }

});

const arduinoCode = fs.readFileSync(pathToArduinoCode).toString();

const arduinoCodeParts = arduinoCode.split("// )'(");

const runableCode = arduinoCodeParts[1]
    .replace(/\[\]\s?=\s?/g, ' = ') // turn any C array[]'s into [regular, arrays]
    .replace(/int(\s*_*[A-Za-z]+_*\d*\s*)=/g, 'var$1=') // Replace any instance of "int variable = n"
    .replace(/int /g, '') // Remove "int" from any instance of "int variable"
    .replace(/void loop\(\) {/, 'while (true) {') // Turn our main method into a while loop
    .replace(/void (\s*_*[A-Za-z]+_*\d*\s*)/g, ' var $1 = function'); // Replace any "void function" with a javascript function definition

if (runableCode.indexOf(")\n") != -1) {
        throw new Error(`${pathToArduinoCode}: )\\n found without a semicolon`);
}

if (verbose) {

    console.log(`
    ######################################

    Loading: ${pathToArduinoCode}

    ######################################

    ${arduinoCode}

    ######################################

    Runable Code:

    ######################################

    ${runableCode}

    ######################################

    Running code:

    ######################################
    `);

}

if (test) {
    // Will pass the test flag to verify quickly
    console.log(`OK: ${pathToArduinoCode}`);
    process.exit(0);
}

eval(runableCode);
<|endoftext|>


<commit_before>export default function makeServiceActions (service) {
  const { vuexOptions } = service
  const idField = vuexOptions.module.idField || vuexOptions.global.idField
  const serviceActions = {
    find ({ commit, dispatch }, params) {
      commit('setFindPending')
      const handleResponse = response => {
        commit('unsetFindPending')
        let data = response.data || response
        data.map(item => dispatch('addOrUpdate', item))
        return response
      }
      const request = service.find(params)
          commit('unsetFindPending')
      return request.subscribe ? request.subscribe(handleResponse) : request.then(handleResponse)
    },

    get ({ commit, dispatch }, params) {
      let id
      if (typeof params === 'string' || typeof params === 'number') {
        id = params[idField]
        delete params[idField]
      } else {
        id = params
        params = undefined
      }
      commit('setGetPending')
      return service.get(id, params)
        .then(item => {
          commit('unsetGetPending')
          dispatch('addOrUpdate', item)
          commit('setCurrent', item)
          return item
        })
          commit('unsetGetPending')
    },

    create ({ commit, dispatch }, data) {
      commit('setCreatePending')
      return service.create(data)
        .then(item => {
          commit('unsetCreatePending')
          dispatch('addOrUpdate', item)
          commit('setCurrent', item)
          return item
        })
          commit('unsetCreatePending')
    },

    update ({ commit, dispatch }, id, data) {
      console.log(id)
      console.log(data)
      commit('setUpdatePending')
          commit('unsetUpdatePending')
          commit('unsetUpdatePending')
    },

    patch ({ commit, dispatch }) {
      commit('setPatchPending')
          commit('unsetPatchPending')
          commit('unsetPatchPending')
    },
    remove ({ commit, dispatch }) {
      commit('setRemovePending')
          commit('unsetRemovePending')
          commit('unsetRemovePending')
    }
  }

  const actions = {
    addOrUpdate ({ state, commit }, item) {
      let id = item[idField]
      if (id === undefined) {
        throw new Error('No id found for item. Did you set the idField?', item)
      }
      let existing = state.keyedById[id]
      existing ? commit('updateItem', item) : commit('addItem', item)
    }
  }
  Object.keys(serviceActions).map(method => {
    if (typeof service[method] === 'function') {
      actions[method] = serviceActions[method]
    }
  })
  return actions
}
<commit_msg>Catch errors for service.find and service.get<commit_after>export default function makeServiceActions (service) {
  const { vuexOptions } = service
  const idField = vuexOptions.module.idField || vuexOptions.global.idField
  const serviceActions = {
    find ({ commit, dispatch }, params) {
      commit('setFindPending')
      const handleResponse = response => {
        commit('unsetFindPending')
        let data = response.data || response
        data.map(item => dispatch('addOrUpdate', item))
        return response
      }
      const request = service.find(params)
        .catch(error => {
          commit('unsetFindPending')
          commit('setFindError', error)
          return error
        })
      return request.subscribe ? request.subscribe(handleResponse) : request.then(handleResponse)
    },

    get ({ commit, dispatch }, params) {
      let id
      if (typeof params === 'string' || typeof params === 'number') {
        id = params[idField]
        delete params[idField]
      } else {
        id = params
        params = undefined
      }
      commit('setGetPending')
      return service.get(id, params)
        .then(item => {
          commit('unsetGetPending')
          dispatch('addOrUpdate', item)
          commit('setCurrent', item)
          return item
        })
        .catch(error => {
          commit('unsetGetPending')
          commit('setGetError', error)
          return error
        })
    },

    create ({ commit, dispatch }, data) {
      commit('setCreatePending')
      return service.create(data)
        .then(item => {
          commit('unsetCreatePending')
          dispatch('addOrUpdate', item)
          commit('setCurrent', item)
          return item
        })
        .catch(error => {
          commit('unsetCreatePending')
          commit('setCreateError', error)
          return error
        })
    },

    update ({ commit, dispatch }, id, data) {
      console.log(id)
      console.log(data)
      commit('setUpdatePending')
          commit('unsetUpdatePending')
          commit('unsetUpdatePending')
    },

    patch ({ commit, dispatch }) {
      commit('setPatchPending')
          commit('unsetPatchPending')
          commit('unsetPatchPending')
    },
    remove ({ commit, dispatch }) {
      commit('setRemovePending')
          commit('unsetRemovePending')
          commit('unsetRemovePending')
    }
  }

  const actions = {
    addOrUpdate ({ state, commit }, item) {
      let id = item[idField]
      if (id === undefined) {
        throw new Error('No id found for item. Did you set the idField?', item)
      }
      let existing = state.keyedById[id]
      existing ? commit('updateItem', item) : commit('addItem', item)
    }
  }
  Object.keys(serviceActions).map(method => {
    if (typeof service[method] === 'function') {
      actions[method] = serviceActions[method]
    }
  })
  return actions
}
<|endoftext|>