<commit_before>/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Arun Kumar T K @aruntk
  */
import fs from 'fs'
import url from 'url'
import path from 'path'
import vm from 'vm'
import parse5 from 'parse5'
import loaderUtils from 'loader-utils'
import polyclean from 'polyclean'
import * as _ from 'lodash'
import assign from 'object-assign'
import wcRenderer from './renderer'

function randomIdent() {
  return 'xxxWCLINKxxx' + Math.random() + Math.random() + 'xxx'
}

class DissectHtml {
  constructor(config, options) {
    this.dissected = {
      html: '/*__wc__loader*/',
      js: '',
      requires: '', // appended first
    }
    this.config = config
    this.links = {}
    this.otherDeps = []
    this.options = options
  }
  dissect(contents, sourcePath) {
    this.path = sourcePath
    const children = contents.childNodes || []
    this.processChildNodes(children)
    // this.dissected.js += `\n${this.dissected.js}\n`
  }
  processChildNodes(childNodes) {
    const self = this
    let pushNodes = []
    const processedNodes = _.compact(_.map(childNodes, child => {
      switch (child.nodeName) {
        case 'head':
        case 'body': {
          const _child = child
          _child.childNodes = self.processChildNodes(_child.childNodes)
          const _childContents = parse5.serialize(_child)
          this.dissected[_child.nodeName] = _childContents
          // boolean where determines the section of html the content goes in
          const where = _child.nodeName === 'head'
          self.dissected.html += `${wcRenderer.generateJS(_childContents, where, self.config)}`
        }
          break

        case 'template': {
          const template = child
          // template does not have a direct childNodes property.
          // instead it has a content peoperty which contains a document fragment node.
          // the document fragment node has childNodes prop
          const tmContent = template.content
          const isWalkable = tmContent && tmContent.nodeName === '#document-fragment' && tmContent.childNodes
          if (isWalkable) {
            tmContent.childNodes = self.processChildNodes(tmContent.childNodes)
          }
          template.content = tmContent
          return template
        }
        case 'link': {
          const processedLinkChild = self.processLinks(child)
          if (processedLinkChild) {
            return processedLinkChild
          }
        }
          break
        case 'script': {
          const result = self.processScripts(child)
          if (result) {
            return result
          }
        }
          break
        case 'style': {
          if (child.childNodes && child.childNodes.length) {
            const childNode = child.childNodes[0]
            const css = childNode.value
            const result = self.processStyle(css)
            if (result) {
              childNode.value = result
            }
          }
          return child
        }
        case 'dom-module': {
          const domModule = child
          if (domModule.childNodes) {
            domModule.childNodes = self.processChildNodes(domModule.childNodes)
          }
          return domModule
        }
        case 'div': {
          // this is required to avoid div added by vulcanization
          const divChild = child
          const attrs = _.filter(divChild.attrs, o => (o.name === 'hidden' || o.name === 'by-vulcanize'))
          if (attrs.length >= 2) {
            const _childNodes = self.processChildNodes(divChild.childNodes)
            pushNodes = pushNodes.concat(_childNodes)
          } else {
            if (divChild.childNodes) {
              divChild.childNodes = self.processChildNodes(divChild.childNodes)
            }
            return divChild
          }
        }
          break
          // remove comment and documentType nodes
        case '#comment':
        case '#documentType':
          break
          // every other node
        default: {
          const defChild = child
          const attrs = _.map(defChild.attrs, o => {
            // all src values without [[*]] and {{*}}
            if (o.name === 'src' || o.name === 'src$') {
              o.value = self._changeRelUrl(o.value)
            }
            return o
          })
          defChild.attrs = attrs
          if (defChild.childNodes) {
            defChild.childNodes = self.processChildNodes(defChild.childNodes)
          }
          return defChild
        }
      }
      return null
    }))
    return processedNodes.concat(pushNodes)
  }
  processStyle(css, cssBasePath = '') {
    return this._changeCssUrls(polyclean.stripCss(css), cssBasePath)
  }
  _changeCssUrls(text, cssBasePath) {
    const self = this
    // to get -> property: url(filepath)

    const processed = text.replace(/url\(["']?((?!.*:\/\/|"|'|\)).+?)["']?\)/ig, function (_u, url) {
      // to get -> filepath from url(filepath), url('filepath') and url('filepath')
      return `url(${self._changeRelUrl(url, path.dirname(cssBasePath))})`
    })
    return processed
  }

  processScripts(child) {
    const self = this
    const importSource = _.find(child.attrs, v => (v.name === 'src'))
    if (importSource && importSource.value) {
      // script tag contains a source file url
      const importableUrl = self.importableUrl(importSource.value)
      if (!importableUrl) {
        // link is absolute or remote. so do nothing
        return child
      }
      self.dissected.requires += `\nrequire('${importableUrl}');\n`
    } else {
      // script inside the tag is added to main js part
      self.dissected.js += `\n${parse5.serialize(child)}\n`
    }
    return null
  }
  _changeRelUrl(inpUrl, basePath) {
    // avoids var(--url-variable) and bound properties [[prop]] and {{prop}}
    if (inpUrl && !inpUrl.match(/var\(.*?\)|({{|\[\[)\s*[\w\.]+\s*(}}|\]\])/ig)) {

      const p = basePath ? path.join('', basePath, inpUrl) : inpUrl
      // avoids absolute & remote urls
      const link = this.importableUrl(p)
      if (link) {
        do {
          var ident = randomIdent()
        } while (this.links[ident])
        this.links[ident] = link
        return ident
      }
    }
    return inpUrl
  }
  // changes relative urls to request format and returns if link is absolute.
  importableUrl(link) {
    const root = this.config.root
    if (!loaderUtils.isUrlRequest(link, root)) {
      return
    }
    const uri = url.parse(link)
    if (uri.hash !== null && uri.hash !== undefined) {
      uri.hash = null
      link = uri.format()
    }

    return loaderUtils.urlToRequest(link, root)
  }
  processLinks(child) {
    const self = this
    // <link rel='import'...> and <link rel='stylesheet'...>
    const supportedRels = ['import', 'stylesheet']
    const ifImport = _.find(child.attrs, v => (v.name === 'rel' && supportedRels.indexOf(v.value) > -1))
    if (ifImport) {
      const hrefAttr = _.find(child.attrs, v => v.name === 'href')
      if (hrefAttr && hrefAttr.value) {
        const link = self.importableUrl(hrefAttr.value)
        if (!link) {
          return child
        }
        switch (ifImport.value) {
          case 'import': {
            // file is imported using require
            const typeAttr = _.find(child.attrs, v => (v.name === 'type'))
            if (typeAttr) {
              // process type="css" files
              switch (typeAttr.value) {
                case 'css':
                  return self.processCssImport(link, child)
                default:
                  break
              }
            }
            const importable = `require('${link}');`
            self.dissected.requires += `\n${importable}\n`
          }
            break
            // Processing <link rel='stylesheet' href='filename.css'>
          case 'stylesheet':
            // absolute file path
            return self.processCssImport(link, child)
          default:
            break
        }
      } else {
        return child
      }
    } else {
      return child
    }
    return null
  }
  processCssImport(link, child) {
    const absPath = path.resolve(path.dirname(this.path), link)
    this.otherDeps.push(absPath)
    // checks if file exists
    if (fs.existsSync(absPath)) {
      const contents = fs.readFileSync(absPath, 'utf8')
      // css is inlined
      const minified = this.processStyle(contents, link)
      if (minified) {
        // link tag is replaced with style tag
        return _.extend(child, {
          nodeName: 'style',
          tagName: 'style',
          attrs: [],
          childNodes: [
            {
              nodeName: '#text',
              value: minified
            }
          ]
        })
      }
    }
    return child
  }
}
function getLoaderConfig(context) {
  const query = loaderUtils.parseQuery(context.query)
  const configKey = query.config || 'wcLoader'
  const config = context.options && context.options.hasOwnProperty(configKey) ? context.options[configKey] : {}

  delete query.config

  return assign(query, config)
}
function convertPlaceholder(html, links, config) {
  const callback = this.async()
  const publicPath = typeof config.publicPath !== 'undefined' ? config.publicPath : this.options.output.publicPath
  const phs = Object.keys(links) // placeholders
  Promise.all(phs.map(function loadModule(ph) {
    const resourcePath = links[ph]
    const absPath = path.resolve(path.dirname(this.resourcePath), resourcePath)
    this.addDependency(absPath)
    return new Promise((resolve, reject) => {
      this.loadModule(resourcePath, (err, src) => err ? reject(err) : resolve(src))
    })
  }, this))
    .then(sources => sources.map(
      // runModule may throw an error, so it's important that our promise is rejected in this case
      (src, i) => runModule(src, links[phs[i]], publicPath)
    ))
    .then(results => {
      return html.replace(/xxxWCLINKxxx[0-9\.]+xxx/g, function (match) {
        const i = phs.indexOf(match)
        if (i === -1) {
          return match
        }
        return results[i]
      })
    })
    .then(content => callback(null, content))
    .catch(callback)
}

function runModule(src, filename, publicPath = '') {
  const script = new vm.Script(src, {
    filename,
    displayErrors: true
  })
  const sandbox = {
    module: {},
    __webpack_public_path__: publicPath // eslint-disable-line camelcase
  }

  script.runInNewContext(sandbox)
  return sandbox.module.exports.toString()
}
module.exports = function (source) {
  if (this.cacheable) {
    this.cacheable()
  }
  const config = getLoaderConfig(this)
  const srcFilepath = this.resourcePath
  const parsed = parse5.parse(source)
  const dissectFn = new DissectHtml(config, this.options)
  dissectFn.dissect(parsed, srcFilepath)
  const links = dissectFn.links
  const inject = dissectFn.dissected.html + dissectFn.dissected.requires + dissectFn.dissected.js
  // otherDeps -> css dependencies for hot code reload.
  dissectFn.otherDeps.forEach(dep => {
    this.addDependency(dep)
  }, this)
  convertPlaceholder.call(this, inject, links, config)
}
<commit_msg>Avoid importing data URLs in CSS<commit_after>/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Arun Kumar T K @aruntk
  */
import fs from 'fs'
import url from 'url'
import path from 'path'
import vm from 'vm'
import parse5 from 'parse5'
import loaderUtils from 'loader-utils'
import polyclean from 'polyclean'
import * as _ from 'lodash'
import assign from 'object-assign'
import wcRenderer from './renderer'

function randomIdent() {
  return 'xxxWCLINKxxx' + Math.random() + Math.random() + 'xxx'
}

class DissectHtml {
  constructor(config, options) {
    this.dissected = {
      html: '/*__wc__loader*/',
      js: '',
      requires: '', // appended first
    }
    this.config = config
    this.links = {}
    this.otherDeps = []
    this.options = options
  }
  dissect(contents, sourcePath) {
    this.path = sourcePath
    const children = contents.childNodes || []
    this.processChildNodes(children)
    // this.dissected.js += `\n${this.dissected.js}\n`
  }
  processChildNodes(childNodes) {
    const self = this
    let pushNodes = []
    const processedNodes = _.compact(_.map(childNodes, child => {
      switch (child.nodeName) {
        case 'head':
        case 'body': {
          const _child = child
          _child.childNodes = self.processChildNodes(_child.childNodes)
          const _childContents = parse5.serialize(_child)
          this.dissected[_child.nodeName] = _childContents
          // boolean where determines the section of html the content goes in
          const where = _child.nodeName === 'head'
          self.dissected.html += `${wcRenderer.generateJS(_childContents, where, self.config)}`
        }
          break

        case 'template': {
          const template = child
          // template does not have a direct childNodes property.
          // instead it has a content peoperty which contains a document fragment node.
          // the document fragment node has childNodes prop
          const tmContent = template.content
          const isWalkable = tmContent && tmContent.nodeName === '#document-fragment' && tmContent.childNodes
          if (isWalkable) {
            tmContent.childNodes = self.processChildNodes(tmContent.childNodes)
          }
          template.content = tmContent
          return template
        }
        case 'link': {
          const processedLinkChild = self.processLinks(child)
          if (processedLinkChild) {
            return processedLinkChild
          }
        }
          break
        case 'script': {
          const result = self.processScripts(child)
          if (result) {
            return result
          }
        }
          break
        case 'style': {
          if (child.childNodes && child.childNodes.length) {
            const childNode = child.childNodes[0]
            const css = childNode.value
            const result = self.processStyle(css)
            if (result) {
              childNode.value = result
            }
          }
          return child
        }
        case 'dom-module': {
          const domModule = child
          if (domModule.childNodes) {
            domModule.childNodes = self.processChildNodes(domModule.childNodes)
          }
          return domModule
        }
        case 'div': {
          // this is required to avoid div added by vulcanization
          const divChild = child
          const attrs = _.filter(divChild.attrs, o => (o.name === 'hidden' || o.name === 'by-vulcanize'))
          if (attrs.length >= 2) {
            const _childNodes = self.processChildNodes(divChild.childNodes)
            pushNodes = pushNodes.concat(_childNodes)
          } else {
            if (divChild.childNodes) {
              divChild.childNodes = self.processChildNodes(divChild.childNodes)
            }
            return divChild
          }
        }
          break
          // remove comment and documentType nodes
        case '#comment':
        case '#documentType':
          break
          // every other node
        default: {
          const defChild = child
          const attrs = _.map(defChild.attrs, o => {
            // all src values without [[*]] and {{*}}
            if (o.name === 'src' || o.name === 'src$') {
              o.value = self._changeRelUrl(o.value)
            }
            return o
          })
          defChild.attrs = attrs
          if (defChild.childNodes) {
            defChild.childNodes = self.processChildNodes(defChild.childNodes)
          }
          return defChild
        }
      }
      return null
    }))
    return processedNodes.concat(pushNodes)
  }
  processStyle(css, cssBasePath = '') {
    return this._changeCssUrls(polyclean.stripCss(css), cssBasePath)
  }
  _changeCssUrls(text, cssBasePath) {
    const self = this
    // to get -> property: url(filepath)

    const processed = text.replace(/url\(["']?((?!.*:\/\/|"|'|\)).+?)["']?\)/ig, function (_u, url) {
      // to get -> filepath from url(filepath), url('filepath') and url('filepath')
      return `url(${self._changeRelUrl(url, path.dirname(cssBasePath))})`
    })
    return processed
  }

  processScripts(child) {
    const self = this
    const importSource = _.find(child.attrs, v => (v.name === 'src'))
    if (importSource && importSource.value) {
      // script tag contains a source file url
      const importableUrl = self.importableUrl(importSource.value)
      if (!importableUrl) {
        // link is absolute or remote. so do nothing
        return child
      }
      self.dissected.requires += `\nrequire('${importableUrl}');\n`
    } else {
      // script inside the tag is added to main js part
      self.dissected.js += `\n${parse5.serialize(child)}\n`
    }
    return null
  }
  _changeRelUrl(inpUrl, basePath) {
    // avoids var(--url-variable) and bound properties [[prop]] and {{prop}} and data urls
    if (inpUrl && !inpUrl.match(/var\(.*?\)|({{|\[\[)\s*[\w\.]+\s*(}}|\]\])/ig) && !inpUrl.startsWith('data:')) {

      const p = basePath ? path.join('', basePath, inpUrl) : inpUrl
      // avoids absolute & remote urls
      const link = this.importableUrl(p)
      if (link) {
        do {
          var ident = randomIdent()
        } while (this.links[ident])
        this.links[ident] = link
        return ident
      }
    }
    return inpUrl
  }
  // changes relative urls to request format and returns if link is absolute.
  importableUrl(link) {
    const root = this.config.root
    if (!loaderUtils.isUrlRequest(link, root)) {
      return
    }
    const uri = url.parse(link)
    if (uri.hash !== null && uri.hash !== undefined) {
      uri.hash = null
      link = uri.format()
    }

    return loaderUtils.urlToRequest(link, root)
  }
  processLinks(child) {
    const self = this
    // <link rel='import'...> and <link rel='stylesheet'...>
    const supportedRels = ['import', 'stylesheet']
    const ifImport = _.find(child.attrs, v => (v.name === 'rel' && supportedRels.indexOf(v.value) > -1))
    if (ifImport) {
      const hrefAttr = _.find(child.attrs, v => v.name === 'href')
      if (hrefAttr && hrefAttr.value) {
        const link = self.importableUrl(hrefAttr.value)
        if (!link) {
          return child
        }
        switch (ifImport.value) {
          case 'import': {
            // file is imported using require
            const typeAttr = _.find(child.attrs, v => (v.name === 'type'))
            if (typeAttr) {
              // process type="css" files
              switch (typeAttr.value) {
                case 'css':
                  return self.processCssImport(link, child)
                default:
                  break
              }
            }
            const importable = `require('${link}');`
            self.dissected.requires += `\n${importable}\n`
          }
            break
            // Processing <link rel='stylesheet' href='filename.css'>
          case 'stylesheet':
            // absolute file path
            return self.processCssImport(link, child)
          default:
            break
        }
      } else {
        return child
      }
    } else {
      return child
    }
    return null
  }
  processCssImport(link, child) {
    const absPath = path.resolve(path.dirname(this.path), link)
    this.otherDeps.push(absPath)
    // checks if file exists
    if (fs.existsSync(absPath)) {
      const contents = fs.readFileSync(absPath, 'utf8')
      // css is inlined
      const minified = this.processStyle(contents, link)
      if (minified) {
        // link tag is replaced with style tag
        return _.extend(child, {
          nodeName: 'style',
          tagName: 'style',
          attrs: [],
          childNodes: [
            {
              nodeName: '#text',
              value: minified
            }
          ]
        })
      }
    }
    return child
  }
}
function getLoaderConfig(context) {
  const query = loaderUtils.parseQuery(context.query)
  const configKey = query.config || 'wcLoader'
  const config = context.options && context.options.hasOwnProperty(configKey) ? context.options[configKey] : {}

  delete query.config

  return assign(query, config)
}
function convertPlaceholder(html, links, config) {
  const callback = this.async()
  const publicPath = typeof config.publicPath !== 'undefined' ? config.publicPath : this.options.output.publicPath
  const phs = Object.keys(links) // placeholders
  Promise.all(phs.map(function loadModule(ph) {
    const resourcePath = links[ph]
    const absPath = path.resolve(path.dirname(this.resourcePath), resourcePath)
    this.addDependency(absPath)
    return new Promise((resolve, reject) => {
      this.loadModule(resourcePath, (err, src) => err ? reject(err) : resolve(src))
    })
  }, this))
    .then(sources => sources.map(
      // runModule may throw an error, so it's important that our promise is rejected in this case
      (src, i) => runModule(src, links[phs[i]], publicPath)
    ))
    .then(results => {
      return html.replace(/xxxWCLINKxxx[0-9\.]+xxx/g, function (match) {
        const i = phs.indexOf(match)
        if (i === -1) {
          return match
        }
        return results[i]
      })
    })
    .then(content => callback(null, content))
    .catch(callback)
}

function runModule(src, filename, publicPath = '') {
  const script = new vm.Script(src, {
    filename,
    displayErrors: true
  })
  const sandbox = {
    module: {},
    __webpack_public_path__: publicPath // eslint-disable-line camelcase
  }

  script.runInNewContext(sandbox)
  return sandbox.module.exports.toString()
}
module.exports = function (source) {
  if (this.cacheable) {
    this.cacheable()
  }
  const config = getLoaderConfig(this)
  const srcFilepath = this.resourcePath
  const parsed = parse5.parse(source)
  const dissectFn = new DissectHtml(config, this.options)
  dissectFn.dissect(parsed, srcFilepath)
  const links = dissectFn.links
  const inject = dissectFn.dissected.html + dissectFn.dissected.requires + dissectFn.dissected.js
  // otherDeps -> css dependencies for hot code reload.
  dissectFn.otherDeps.forEach(dep => {
    this.addDependency(dep)
  }, this)
  convertPlaceholder.call(this, inject, links, config)
}
<|endoftext|>


<commit_before>import React from "react";
import ReactDOM from "react-dom";
import * as serviceWorker from "./serviceWorker";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

serviceWorker.unregister();
<commit_msg>✔ enable service worker<commit_after>import React from "react";
import ReactDOM from "react-dom";
import * as serviceWorker from "./serviceWorker";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

serviceWorker.register();
<|endoftext|>


<commit_before>import Tree from './data/Tree';
import Trie from './data/Trie';
import BinarySearchTree from './data/BinarySearchTree';
import Graph from './data/Graph';
import MinHeap from './data/MinHeap';
import LinkedList from './data/LinkedList';

export default { Tree, Trie, BinarySearchTree, Graph, MinHeap }<commit_msg>Remove default export to pure export<commit_after>import Tree from './data/Tree';
import Trie from './data/Trie';
import BinarySearchTree from './data/BinarySearchTree';
import Graph from './data/Graph';
import MinHeap from './data/MinHeap';
import LinkedList from './data/LinkedList';

export { Tree, Trie, BinarySearchTree, Graph, MinHeap, LinkedList }<|endoftext|>


<commit_before>'use strict';
import path from 'path';
import bbox from '@turf/bbox';
import centerOfMass from '@turf/center-of-mass';
import _ from 'lodash';

import config from '../../config';
import db from '../../db/';
import Operation from '../../utils/operation';
import { getJSONFileContents, putFileStream } from '../../s3/utils';
// import { getFileContents } from '../../s3/utils';
// import { importRoadNetwork } from '../rra-osm-p2p';
import AppLogger from '../../utils/app-logger';
import * as overpass from '../../utils/overpass';

const DEBUG = config.debug;
let appLogger = AppLogger({ output: DEBUG });
let logger;

process.on('message', function (e) {
  // Capture all the errors.
  try {
    logger = appLogger.group(`p${e.projId} s${e.scId} proj-setup`);
    logger.log('init');
    e.callback = (err) => {
      if (err) return process.exit(1);
      else process.exit(0);
    };
    concludeProjectSetup(e);
  } catch (err) {
    process.send({type: 'error', data: err.message, stack: err.stack});
    throw err;
  }
});

// The project setup script is setup so that it run on a different node process
// using fork. This allows us to offload the main server not causing blocking
// operations.

/**
 * Finishes the project setup by processing all the needed files:
 * Road network:
 *   - Convert the osm file to a changeset and import it to the osm-p2p-db
 * Admin Bound:
 *   - Extract all the village names, and store them on the database. This is
 *   needed to later select what admin areas are to be processed.
 *
 * @param  {object} e       Data.
 *         e.opId           Operation Id. It has to be already started.
 *         e.projId         Project Id.
 *         e.scId           Scenario Id.
 *         e.callback
 */
export function concludeProjectSetup (e) {
  const {opId, projId, scId, callback} = e;

  function processAdminAreas (adminBoundsFc) {
    logger && logger.log('process admin areas');

    let adminAreaTask = () => {
      return db.transaction(function (trx) {
        if (!adminBoundsFc.features) {
          throw new Error('Invalid administrative boundaries file');
        }
        let adminAreas = _(adminBoundsFc.features)
          .filter(o => !!o.properties.name && o.geometry.type !== 'Point')
          .sortBy(o => _.kebabCase(o.properties.name))
          .map(o => {
            return {
              name: o.properties.name,
              type: o.properties.type || 'Admin Area',
              geometry: JSON.stringify(o.geometry.coordinates),
              project_id: projId
            };
          })
          .value();

        let adminAreasBbox = bbox(adminBoundsFc);

        return Promise.all([
          trx('projects')
            .update({
              bbox: JSON.stringify(adminAreasBbox),
              updated_at: (new Date())
            })
            .where('id', projId),

          trx.batchInsert('projects_aa', adminAreas)
            .returning('id'),

          trx('scenarios_settings')
            .insert({
              scenario_id: scId,
              key: 'admin_areas',
              value: '[]',
              created_at: (new Date()),
              updated_at: (new Date())
            })
            .where('id', projId)
        ]);
      });
    };

    // Clean the tables so any remnants of previous attempts are removed.
    // This avoids primary keys collisions.
    let cleanAATable = () => {
      return Promise.all([
        db('projects_aa')
          .where('project_id', projId)
          .del(),
        db('scenarios_settings')
          .where('scenario_id', scId)
          .where('key', 'admin_areas')
          .del()
      ]);
    };

    return op.log('process:admin-bounds', {message: 'Processing admin areas'})
      .then(() => cleanAATable())
      .then(() => adminAreaTask());
  }

  function processOrigins (originsData) {
    logger && logger.log('process origins');

    let originsTask = () => {
      let indicators = originsData.data.indicators;
      let neededProps = indicators.map(o => o.key);
      neededProps.push('name');

      return getJSONFileContents(originsData.path)
        .then(originsFC => {
          logger && logger.log('origins before filter', originsFC.features.length);
          let features = originsFC.features.filter(feat => {
            let props = Object.keys(feat.properties);
            return neededProps.every(o => props.indexOf(o) !== -1);
          });

          logger && logger.log('origins after filter', features.length);

          let originsIndicators = [];
          let origins = features.map(feat => {
            let coordinates = feat.geometry.type === 'Point'
              ? feat.geometry.coordinates
              : centerOfMass(feat).geometry.coordinates;

            // Will be flattened later.
            // The array is constructed in this way so we can match the index of the
            // results array and attribute the correct id.
            let featureIndicators = indicators.map(ind => ({
              key: ind.key,
              label: ind.label,
              value: parseInt(feat.properties[ind.key])
            }));
            originsIndicators.push(featureIndicators);

            return {
              project_id: projId,
              name: feat.properties.name || 'N/A',
              coordinates: JSON.stringify(coordinates)
            };
          });

          return db.transaction(function (trx) {
            return trx.batchInsert('projects_origins', origins)
              .returning('id')
              .then(ids => {
                // Add ids to the originsIndicators and flatten the array in the process.
                let flat = [];
                originsIndicators.forEach((resInd, resIdx) => {
                  resInd.forEach(ind => {
                    ind.origin_id = ids[resIdx];
                    flat.push(ind);
                  });
                });
                return flat;
              })
              .then(data => trx.batchInsert('projects_origins_indicators', data));
          });
        });
    };

    // Clean the tables so any remnants of previous attempts are removed.
    // This avoids primary keys collisions.
    let cleanOriginsTable = () => {
      return db('projects_origins')
        .where('project_id', projId)
        .del();
    };

    return op.log('process:origins', {message: 'Processing origins'})
      .then(() => cleanOriginsTable())
      .then(() => originsTask());
  }

  function importOSMRoadNetwork (bbox) {
    logger && logger.log('Importing road network from overpass for bbox (S,W,N,E):', bbox);

    let importOSMRoadNetworkTask = () => overpass.importRoadNetwork(bbox)
      .catch(err => {
        // Just to log error
        logger && logger.log('Error importing from overpass', err.message);
        throw err;
      })
      .then(osmData => {
        logger && logger.log('Got road network. Saving to S3 and db');
        // Insert file into DB.
        let fileName = `road-network_${Date.now()}`;
        let filePath = `scenario-${scId}/${fileName}`;
        let data = {
          name: fileName,
          type: 'road-network',
          path: filePath,
          project_id: projId,
          scenario_id: scId,
          created_at: (new Date()),
          updated_at: (new Date())
        };

        return putFileStream(filePath, osmData)
          .then(() => db('scenarios_files').insert(data))
          .then(() => osmData);
      });

    // Clean the tables so any remnants of previous attempts are removed.
    // This avoids primary keys collisions and duplication.
    let cleanTable = () => {
      return db('scenarios_files')
        .where('project_id', projId)
        .where('scenario_id', scId)
        .where('type', 'road-network')
        .del();
    };

    return op.log('process:road-network', {message: 'Importing road network from OSM'})
      .then(() => cleanTable())
      .then(() => importOSMRoadNetworkTask());
  }

  function importOSMPOIs (bbox, poiTypes) {
    logger && logger.log('Importing pois from overpass for bbox (S,W,N,E):', bbox);
    logger && logger.log('POI types:', poiTypes);

    let importOSMPOIsTask = () => overpass.importPOI(bbox, poiTypes)
      .catch(err => {
        // Just to log error
        logger && logger.log('Error importing from overpass', err.message);
        throw err;
      })
      .then(osmGeoJSON => {
        logger && logger.log('Got POIS. Saving to S3 and db');
        let types = Object.keys(osmGeoJSON);

        let dbInsertions = [];
        let fileUploadPromises = [];
        let emptyPOI = [];

        types.forEach(poiType => {
          // Filter out pois without anything
          if (osmGeoJSON[poiType].features.length) {
            let fileName = `poi_${poiType}_${Date.now()}`;
            let filePath = `scenario-${scId}/${fileName}`;

            // Prepare for db insertion.
            dbInsertions.push({
              name: fileName,
              type: 'poi',
              subtype: poiType,
              path: filePath,
              project_id: projId,
              scenario_id: scId,
              created_at: (new Date()),
              updated_at: (new Date())
            });

            // Save each poi type to S3.
            fileUploadPromises.push(putFileStream(filePath, JSON.stringify(osmGeoJSON[poiType])));
          } else {
            emptyPOI.push(poiType);
          }
        });

        if (emptyPOI.length) {
          logger && logger.log(`No POI were returned for [${emptyPOI.join(', ')}]`);
          throw new Error(`No POI were returned for [${emptyPOI.join(', ')}]`);
        }

        // Save to database.
        let promises = fileUploadPromises.concat(db.batchInsert('scenarios_files', dbInsertions));

        return Promise.all(promises);
      });

    // Clean the tables so any remnants of previous attempts are removed.
    // This avoids primary keys collisions and duplication.
    let cleanTable = () => {
      return db('scenarios_files')
        .where('project_id', projId)
        .where('scenario_id', scId)
        .where('type', 'poi')
        .del();
    };

    return op.log('process:poi', {message: 'Importing poi from OSM'})
      .then(() => cleanTable())
      .then(() => importOSMPOIsTask());
  }

  let op = new Operation(db);
  op.loadById(opId)
  .then(() => Promise.all([
    // Get source for Road Network.
    db('scenarios_source_data')
      .select('*')
      .where('scenario_id', scId)
      .whereIn('name', ['poi', 'road-network'])
      .orderBy('name'),
    db('projects_files')
      .select('*')
      .where('project_id', projId)
      .whereIn('type', ['admin-bounds', 'origins'])
      .orderBy('type')
      .then(files => {
        // Get the data from the admin bounds file immediately but pass
        // the full data for the origins file because other values from the db
        // are needed.
        let [adminBoundsData, originsData] = files;
        return getJSONFileContents(adminBoundsData.path)
          .then(adminBoundsContent => ([adminBoundsContent, originsData]));
      })
  ]))
  .then(filesContent => {
    // let [roadNetwork, [adminBoundsFc, originsData]] = filesContent;
    let [[poiSource, rnSource], [adminBoundsFc, originsData]] = filesContent;

    let rnProcessPromise = rnSource.type === 'osm'
      ? () => importOSMRoadNetwork(overpass.fcBbox(adminBoundsFc))
      : () => Promise.resolve();
      // We'll need to get the RN contents to import to the osm-p2p-db.
      // : () => db('scenarios_files')
      //   .select('*')
      //   .where('project_id', projId)
      //   .where('type', 'road-network')
      //   .first()
      //   .then(file => getFileContents(file.path));

    let poiProcessPromise = poiSource.type === 'osm'
      ? () => importOSMPOIs(overpass.fcBbox(adminBoundsFc), poiSource.data.osmPoiTypes)
      : () => Promise.resolve();

    // Run the tasks in series rather than in parallel.
    // This is better for error handling. If they run in parallel and
    // `processAdminAreas` errors, the script hangs a bit while
    // `processRoadNetwork` (which is resource intensive) finished and only then
    // the error is captured by the promise.
    // Since processing the admin areas is a pretty fast operation, the
    // performance is not really affected.
    return Promise.all([
      processAdminAreas(adminBoundsFc),
      processOrigins(originsData)
    ])
    .then(() => poiProcessPromise())
    .then(() => rnProcessPromise()
      // .then(roadNetwork => {
      //   logger && logger.log('process road network');
      //   return importRoadNetwork(projId, scId, op, roadNetwork);
      // })
    );
  })
  .then(() => {
    return db.transaction(function (trx) {
      return Promise.all([
        trx('projects')
          .update({updated_at: (new Date()), status: 'active'})
          .where('id', projId),
        trx('scenarios')
          .update({updated_at: (new Date()), status: 'active'})
          .where('id', scId)
      ])
      .then(() => op.log('success', {message: 'Operation complete'}).then(op => op.finish()));
    });
  })
  .then(() => {
    logger && logger.log('process complete');
    DEBUG && appLogger && appLogger.toFile(path.resolve(__dirname, `../../../project-setup_p${projId}s${scId}.log`));
    callback();
  })
  .catch(err => {
    logger && logger.log('error', err);
    DEBUG && appLogger && appLogger.toFile(path.resolve(__dirname, `../../../project-setup_p${projId}s${scId}.log`));
    return op.log('error', {error: err.message})
      .then(op => op.finish())
      .then(() => callback(err.message), () => callback(err.message));
  });
}
<commit_msg>Exclude name as a needed prop<commit_after>'use strict';
import path from 'path';
import bbox from '@turf/bbox';
import centerOfMass from '@turf/center-of-mass';
import _ from 'lodash';

import config from '../../config';
import db from '../../db/';
import Operation from '../../utils/operation';
import { getJSONFileContents, putFileStream } from '../../s3/utils';
// import { getFileContents } from '../../s3/utils';
// import { importRoadNetwork } from '../rra-osm-p2p';
import AppLogger from '../../utils/app-logger';
import * as overpass from '../../utils/overpass';

const DEBUG = config.debug;
let appLogger = AppLogger({ output: DEBUG });
let logger;

process.on('message', function (e) {
  // Capture all the errors.
  try {
    logger = appLogger.group(`p${e.projId} s${e.scId} proj-setup`);
    logger.log('init');
    e.callback = (err) => {
      if (err) return process.exit(1);
      else process.exit(0);
    };
    concludeProjectSetup(e);
  } catch (err) {
    process.send({type: 'error', data: err.message, stack: err.stack});
    throw err;
  }
});

// The project setup script is setup so that it run on a different node process
// using fork. This allows us to offload the main server not causing blocking
// operations.

/**
 * Finishes the project setup by processing all the needed files:
 * Road network:
 *   - Convert the osm file to a changeset and import it to the osm-p2p-db
 * Admin Bound:
 *   - Extract all the village names, and store them on the database. This is
 *   needed to later select what admin areas are to be processed.
 *
 * @param  {object} e       Data.
 *         e.opId           Operation Id. It has to be already started.
 *         e.projId         Project Id.
 *         e.scId           Scenario Id.
 *         e.callback
 */
export function concludeProjectSetup (e) {
  const {opId, projId, scId, callback} = e;

  function processAdminAreas (adminBoundsFc) {
    logger && logger.log('process admin areas');

    let adminAreaTask = () => {
      return db.transaction(function (trx) {
        if (!adminBoundsFc.features) {
          throw new Error('Invalid administrative boundaries file');
        }
        let adminAreas = _(adminBoundsFc.features)
          .filter(o => !!o.properties.name && o.geometry.type !== 'Point')
          .sortBy(o => _.kebabCase(o.properties.name))
          .map(o => {
            return {
              name: o.properties.name,
              type: o.properties.type || 'Admin Area',
              geometry: JSON.stringify(o.geometry.coordinates),
              project_id: projId
            };
          })
          .value();

        let adminAreasBbox = bbox(adminBoundsFc);

        return Promise.all([
          trx('projects')
            .update({
              bbox: JSON.stringify(adminAreasBbox),
              updated_at: (new Date())
            })
            .where('id', projId),

          trx.batchInsert('projects_aa', adminAreas)
            .returning('id'),

          trx('scenarios_settings')
            .insert({
              scenario_id: scId,
              key: 'admin_areas',
              value: '[]',
              created_at: (new Date()),
              updated_at: (new Date())
            })
            .where('id', projId)
        ]);
      });
    };

    // Clean the tables so any remnants of previous attempts are removed.
    // This avoids primary keys collisions.
    let cleanAATable = () => {
      return Promise.all([
        db('projects_aa')
          .where('project_id', projId)
          .del(),
        db('scenarios_settings')
          .where('scenario_id', scId)
          .where('key', 'admin_areas')
          .del()
      ]);
    };

    return op.log('process:admin-bounds', {message: 'Processing admin areas'})
      .then(() => cleanAATable())
      .then(() => adminAreaTask());
  }

  function processOrigins (originsData) {
    logger && logger.log('process origins');

    let originsTask = () => {
      let indicators = originsData.data.indicators;
      let neededProps = indicators.map(o => o.key);

      return getJSONFileContents(originsData.path)
        .then(originsFC => {
          logger && logger.log('origins before filter', originsFC.features.length);
          let features = originsFC.features.filter(feat => {
            let props = Object.keys(feat.properties);
            return neededProps.every(o => props.indexOf(o) !== -1);
          });

          logger && logger.log('origins after filter', features.length);

          let originsIndicators = [];
          let origins = features.map(feat => {
            let coordinates = feat.geometry.type === 'Point'
              ? feat.geometry.coordinates
              : centerOfMass(feat).geometry.coordinates;

            // Will be flattened later.
            // The array is constructed in this way so we can match the index of the
            // results array and attribute the correct id.
            let featureIndicators = indicators.map(ind => ({
              key: ind.key,
              label: ind.label,
              value: parseInt(feat.properties[ind.key])
            }));
            originsIndicators.push(featureIndicators);

            return {
              project_id: projId,
              name: feat.properties.name || 'N/A',
              coordinates: JSON.stringify(coordinates)
            };
          });

          return db.transaction(function (trx) {
            return trx.batchInsert('projects_origins', origins)
              .returning('id')
              .then(ids => {
                // Add ids to the originsIndicators and flatten the array in the process.
                let flat = [];
                originsIndicators.forEach((resInd, resIdx) => {
                  resInd.forEach(ind => {
                    ind.origin_id = ids[resIdx];
                    flat.push(ind);
                  });
                });
                return flat;
              })
              .then(data => trx.batchInsert('projects_origins_indicators', data));
          });
        });
    };

    // Clean the tables so any remnants of previous attempts are removed.
    // This avoids primary keys collisions.
    let cleanOriginsTable = () => {
      return db('projects_origins')
        .where('project_id', projId)
        .del();
    };

    return op.log('process:origins', {message: 'Processing origins'})
      .then(() => cleanOriginsTable())
      .then(() => originsTask());
  }

  function importOSMRoadNetwork (bbox) {
    logger && logger.log('Importing road network from overpass for bbox (S,W,N,E):', bbox);

    let importOSMRoadNetworkTask = () => overpass.importRoadNetwork(bbox)
      .catch(err => {
        // Just to log error
        logger && logger.log('Error importing from overpass', err.message);
        throw err;
      })
      .then(osmData => {
        logger && logger.log('Got road network. Saving to S3 and db');
        // Insert file into DB.
        let fileName = `road-network_${Date.now()}`;
        let filePath = `scenario-${scId}/${fileName}`;
        let data = {
          name: fileName,
          type: 'road-network',
          path: filePath,
          project_id: projId,
          scenario_id: scId,
          created_at: (new Date()),
          updated_at: (new Date())
        };

        return putFileStream(filePath, osmData)
          .then(() => db('scenarios_files').insert(data))
          .then(() => osmData);
      });

    // Clean the tables so any remnants of previous attempts are removed.
    // This avoids primary keys collisions and duplication.
    let cleanTable = () => {
      return db('scenarios_files')
        .where('project_id', projId)
        .where('scenario_id', scId)
        .where('type', 'road-network')
        .del();
    };

    return op.log('process:road-network', {message: 'Importing road network from OSM'})
      .then(() => cleanTable())
      .then(() => importOSMRoadNetworkTask());
  }

  function importOSMPOIs (bbox, poiTypes) {
    logger && logger.log('Importing pois from overpass for bbox (S,W,N,E):', bbox);
    logger && logger.log('POI types:', poiTypes);

    let importOSMPOIsTask = () => overpass.importPOI(bbox, poiTypes)
      .catch(err => {
        // Just to log error
        logger && logger.log('Error importing from overpass', err.message);
        throw err;
      })
      .then(osmGeoJSON => {
        logger && logger.log('Got POIS. Saving to S3 and db');
        let types = Object.keys(osmGeoJSON);

        let dbInsertions = [];
        let fileUploadPromises = [];
        let emptyPOI = [];

        types.forEach(poiType => {
          // Filter out pois without anything
          if (osmGeoJSON[poiType].features.length) {
            let fileName = `poi_${poiType}_${Date.now()}`;
            let filePath = `scenario-${scId}/${fileName}`;

            // Prepare for db insertion.
            dbInsertions.push({
              name: fileName,
              type: 'poi',
              subtype: poiType,
              path: filePath,
              project_id: projId,
              scenario_id: scId,
              created_at: (new Date()),
              updated_at: (new Date())
            });

            // Save each poi type to S3.
            fileUploadPromises.push(putFileStream(filePath, JSON.stringify(osmGeoJSON[poiType])));
          } else {
            emptyPOI.push(poiType);
          }
        });

        if (emptyPOI.length) {
          logger && logger.log(`No POI were returned for [${emptyPOI.join(', ')}]`);
          throw new Error(`No POI were returned for [${emptyPOI.join(', ')}]`);
        }

        // Save to database.
        let promises = fileUploadPromises.concat(db.batchInsert('scenarios_files', dbInsertions));

        return Promise.all(promises);
      });

    // Clean the tables so any remnants of previous attempts are removed.
    // This avoids primary keys collisions and duplication.
    let cleanTable = () => {
      return db('scenarios_files')
        .where('project_id', projId)
        .where('scenario_id', scId)
        .where('type', 'poi')
        .del();
    };

    return op.log('process:poi', {message: 'Importing poi from OSM'})
      .then(() => cleanTable())
      .then(() => importOSMPOIsTask());
  }

  let op = new Operation(db);
  op.loadById(opId)
  .then(() => Promise.all([
    // Get source for Road Network.
    db('scenarios_source_data')
      .select('*')
      .where('scenario_id', scId)
      .whereIn('name', ['poi', 'road-network'])
      .orderBy('name'),
    db('projects_files')
      .select('*')
      .where('project_id', projId)
      .whereIn('type', ['admin-bounds', 'origins'])
      .orderBy('type')
      .then(files => {
        // Get the data from the admin bounds file immediately but pass
        // the full data for the origins file because other values from the db
        // are needed.
        let [adminBoundsData, originsData] = files;
        return getJSONFileContents(adminBoundsData.path)
          .then(adminBoundsContent => ([adminBoundsContent, originsData]));
      })
  ]))
  .then(filesContent => {
    // let [roadNetwork, [adminBoundsFc, originsData]] = filesContent;
    let [[poiSource, rnSource], [adminBoundsFc, originsData]] = filesContent;

    let rnProcessPromise = rnSource.type === 'osm'
      ? () => importOSMRoadNetwork(overpass.fcBbox(adminBoundsFc))
      : () => Promise.resolve();
      // We'll need to get the RN contents to import to the osm-p2p-db.
      // : () => db('scenarios_files')
      //   .select('*')
      //   .where('project_id', projId)
      //   .where('type', 'road-network')
      //   .first()
      //   .then(file => getFileContents(file.path));

    let poiProcessPromise = poiSource.type === 'osm'
      ? () => importOSMPOIs(overpass.fcBbox(adminBoundsFc), poiSource.data.osmPoiTypes)
      : () => Promise.resolve();

    // Run the tasks in series rather than in parallel.
    // This is better for error handling. If they run in parallel and
    // `processAdminAreas` errors, the script hangs a bit while
    // `processRoadNetwork` (which is resource intensive) finished and only then
    // the error is captured by the promise.
    // Since processing the admin areas is a pretty fast operation, the
    // performance is not really affected.
    return Promise.all([
      processAdminAreas(adminBoundsFc),
      processOrigins(originsData)
    ])
    .then(() => poiProcessPromise())
    .then(() => rnProcessPromise()
      // .then(roadNetwork => {
      //   logger && logger.log('process road network');
      //   return importRoadNetwork(projId, scId, op, roadNetwork);
      // })
    );
  })
  .then(() => {
    return db.transaction(function (trx) {
      return Promise.all([
        trx('projects')
          .update({updated_at: (new Date()), status: 'active'})
          .where('id', projId),
        trx('scenarios')
          .update({updated_at: (new Date()), status: 'active'})
          .where('id', scId)
      ])
      .then(() => op.log('success', {message: 'Operation complete'}).then(op => op.finish()));
    });
  })
  .then(() => {
    logger && logger.log('process complete');
    DEBUG && appLogger && appLogger.toFile(path.resolve(__dirname, `../../../project-setup_p${projId}s${scId}.log`));
    callback();
  })
  .catch(err => {
    logger && logger.log('error', err);
    DEBUG && appLogger && appLogger.toFile(path.resolve(__dirname, `../../../project-setup_p${projId}s${scId}.log`));
    return op.log('error', {error: err.message})
      .then(op => op.finish())
      .then(() => callback(err.message), () => callback(err.message));
  });
}
<|endoftext|>


<commit_before>
var jogada = function() {
  // define qual o jogador que está sendo manipulado agora. Se for o primeiro frame da jogada
  // grava as posições iniciais para resetar após a jogada ser finalizada

  var projectil;
  var player;
  if(!isPlayer1 && numeroJogada === 0){
    projectil = projectilPlayer1;
    projectilPosIniX = projectil.position.x;
    projectilPosIniY = projectil.position.y;
    numeroJogada++;
    num =2;
    player = player2;
  }else{if(!isPlayer1 && numeroJogada>0){
    projectil = projectilPlayer1;
    player = player2;
  }
}

if(isPlayer1 && numeroJogada === 0){
  projectil = projectilPlayer2;
  projectilPosIniX = projectil.position.x;
  projectilPosIniY = projectil.position.y;
  numeroJogada++;
  num = 1;
  player = player1;

}else{if(isPlayer1 && numeroJogada>0){
  projectil = projectilPlayer2;
  player = player1;
}

  }

// parte da física do game

// Do physics
// Drag force: Fd = -1/2 * Cd * A * rho * v * v
var Fx = -0.5 * projectil.Cd * projectil.A * projectil.rho * projectil.velocity.x * projectil.velocity.x * projectil.velocity.x / Math.abs(projectil.velocity.x);
var Fy = -0.5 * projectil.Cd * projectil.A * projectil.rho * projectil.velocity.y * projectil.velocity.y * projectil.velocity.y / Math.abs(projectil.velocity.y);

Fx = (isNaN(Fx) ? 0 : Fx);
Fy = (isNaN(Fy) ? 0 : Fy);

// Calculate acceleration ( F = ma )
var ax = Fx / projectil.mass;
var ay = projectil.ag + (Fy / projectil.mass);
// Integrate to get velocity
projectil.velocity.x += ax*frameRate;
projectil.velocity.y += ay*frameRate;

// Integrate to get position
projectil.position.x += projectil.velocity.x/5;
projectil.position.y += projectil.velocity.y/5;

contextoTemporario.beginPath();
contextoTemporario.clearRect(0,0,canvasTemporario.width,canvasTemporario.height);
contextoTemporario.closePath();

// Rotaciona projetil em "projectilAngleº", desenhando ele nas posições x,y e por ultimo, as coordenadas do eixo de rotação
rotacionaProjetil ( contextoTemporario, projectil.image, projectilAngle*(Math.PI/180), projectil.position.x, projectil.position.y, 15, 12 );
projectilAngle += 1.5;

analisaImpactoPlayer(projectil, player);
analisaImpactoPredio(projectil);

// identifica se o projetil saiu da tela para resetar tudo, possibilitando nova jogada
if(projectil.position.x > 1000 || projectil.position.y > 600 || projectil.position.x < 0 ){
  console.log("projetil pra fora");
  encerraJogada(projectil);
}

}

function rotacionaProjetil ( context, image, angleInRad , positionX, positionY, axisX, axisY ) {
  context.translate( positionX, positionY );
  context.rotate( angleInRad );
  context.drawImage( image, -axisX, -axisY );
  context.rotate( -angleInRad );
  context.translate( -positionX, -positionY );

}

function limitaVelocidade (){
  var x = (mouseclick.x - mousePos.x) / 20;
  var y = (mouseclick.y - mousePos.y)/20;
  var limite = 15;

  if(x> limite){
    x = limite;
  }
  if(x<(limite-(2*limite))){
    x = limite-(2*limite);
  }
  if(y> limite){
    y = limite;
  }
  if(y<(limite-(2*limite))){
    y= limite-(2*limite);
  }
  return{
    x: x,
    y: y
  }
}

function analisaImpactoPlayer(projetil, player){
  if(projetil.position.x > player.posicao.x && projetil.position.x <(player.posicao.x +player.tamanho.width)){
    if(projetil.position.y > player.posicao.y && projetil.position.y <(player.posicao.y +player.tamanho.height)){
      console.log("Acertou o ardversário");
<<<<<<< HEAD

      if (isPlayer1) {
        console.log(player1Life);
        $(player1Life.diamonds[player1Life.index]).addClass('lifeLost');
        player1Life.index--;
      } else {
        console.log(player2Life);
        $(player2Life.diamonds[player2Life.index]).addClass('lifeLost');
        player2Life.index++;
      }

=======
      player.vida -=1;
      if(player.vida === 0){
        winner(player);
      }
>>>>>>> master
      encerraJogada(projetil);
    }
  }
}

function analisaImpactoPredio(projetil){
  for(var i = 0; i< predios.length; i++){
    if(projetil.position.x > predios[i].XInicial && projetil.position.x < predios[i].XFinal){ //testa se está na área de um predio
      if(projetil.position.y > predios[i].YInicial && projetil.position.y < predios[i].YFinal){
        for(var k = 0 ; k<damages.length;k++){ // varre o vetor de damages a fim de se certificar que o projetil está dentro de uma área já destruida
          if(projetil.position.x > damages[k].xin && projetil.position.x < damages[k].xfinal){
            if(projetil.position.y > damages[k].yin && projetil.position.y <  damages[k].yfinal){
              return 0; //se o projetil está em área já destruida, o projetil segue a trajetória.
            }
          }
        }
        console.log("Acertou o prédio");
        createDamage(projetil,context);
        encerraJogada(projetil);
      }
    }
  }
}

function encerraJogada(projetil){
  projetil.position.y = projectilPosIniY;
  projetil.position.x = projectilPosIniX;
  numeroJogada=0;
  contextoTemporario.clearRect(0,0,canvasTemporario.width,canvasTemporario.height); //impede que o projetil fique congelado onde o impacto acontece
  console.log("Player " + num);
  window.clearInterval(intervaloJogada);
  if (isPlayer1) {
	  $(playersUI[0]).addClass('player-active')
	  $(playersUI[1]).removeClass('player-active');
	} else {
	  $(playersUI[1]).addClass('player-active');
	  $(playersUI[0]).removeClass('player-active');
	}
}

function createDamage(projetil,context){

  context.clearRect(projetil.position.x-20,projetil.position.y-20,40,40);
  var damage = new Object();
  damage.xin= projetil.position.x-20;
  damage.yin= projetil.position.y-20;
  damage.xfinal = projetil.position.x+20;
  damage.yfinal = projetil.position.y+20;
  damages.push(damage);
}

function winner(player_loser){
  context.clearRect(0,0,1000,600);
  contextoTemporario.clearRect(0,0,1000,600);
  criaMenuEsboco(context);
  var textloser = player_loser.name +" was destroyed!";
  var winner;
  if(player_loser.name ==="Player 1") winner = "Player 2";
  else winner = "Player 1";
  var textWinner = winner +", you rock!";
  context.fillStyle = "#FFF";
  context.font = "40px 'Press Start 2P'";
  context.fillText(textWinner,110,150);
  context.font = "20px'Press Start 2P'";
  context.fillText(textloser,270,300);
  context.fillText("Try harder next time.",290,350);
  restart();
}
<commit_msg>Git bug fix<commit_after>
var jogada = function() {
  // define qual o jogador que está sendo manipulado agora. Se for o primeiro frame da jogada
  // grava as posições iniciais para resetar após a jogada ser finalizada

  var projectil;
  var player;
  if(!isPlayer1 && numeroJogada === 0){
    projectil = projectilPlayer1;
    projectilPosIniX = projectil.position.x;
    projectilPosIniY = projectil.position.y;
    numeroJogada++;
    num =2;
    player = player2;
  }else{if(!isPlayer1 && numeroJogada>0){
    projectil = projectilPlayer1;
    player = player2;
  }
}

if(isPlayer1 && numeroJogada === 0){
  projectil = projectilPlayer2;
  projectilPosIniX = projectil.position.x;
  projectilPosIniY = projectil.position.y;
  numeroJogada++;
  num = 1;
  player = player1;

}else{if(isPlayer1 && numeroJogada>0){
  projectil = projectilPlayer2;
  player = player1;
}

  }

// parte da física do game

// Do physics
// Drag force: Fd = -1/2 * Cd * A * rho * v * v
var Fx = -0.5 * projectil.Cd * projectil.A * projectil.rho * projectil.velocity.x * projectil.velocity.x * projectil.velocity.x / Math.abs(projectil.velocity.x);
var Fy = -0.5 * projectil.Cd * projectil.A * projectil.rho * projectil.velocity.y * projectil.velocity.y * projectil.velocity.y / Math.abs(projectil.velocity.y);

Fx = (isNaN(Fx) ? 0 : Fx);
Fy = (isNaN(Fy) ? 0 : Fy);

// Calculate acceleration ( F = ma )
var ax = Fx / projectil.mass;
var ay = projectil.ag + (Fy / projectil.mass);
// Integrate to get velocity
projectil.velocity.x += ax*frameRate;
projectil.velocity.y += ay*frameRate;

// Integrate to get position
projectil.position.x += projectil.velocity.x/5;
projectil.position.y += projectil.velocity.y/5;

contextoTemporario.beginPath();
contextoTemporario.clearRect(0,0,canvasTemporario.width,canvasTemporario.height);
contextoTemporario.closePath();

// Rotaciona projetil em "projectilAngleº", desenhando ele nas posições x,y e por ultimo, as coordenadas do eixo de rotação
rotacionaProjetil ( contextoTemporario, projectil.image, projectilAngle*(Math.PI/180), projectil.position.x, projectil.position.y, 15, 12 );
projectilAngle += 1.5;

analisaImpactoPlayer(projectil, player);
analisaImpactoPredio(projectil);

// identifica se o projetil saiu da tela para resetar tudo, possibilitando nova jogada
if(projectil.position.x > 1000 || projectil.position.y > 600 || projectil.position.x < 0 ){
  console.log("projetil pra fora");
  encerraJogada(projectil);
}

}

function rotacionaProjetil ( context, image, angleInRad , positionX, positionY, axisX, axisY ) {
  context.translate( positionX, positionY );
  context.rotate( angleInRad );
  context.drawImage( image, -axisX, -axisY );
  context.rotate( -angleInRad );
  context.translate( -positionX, -positionY );

}

function limitaVelocidade (){
  var x = (mouseclick.x - mousePos.x) / 20;
  var y = (mouseclick.y - mousePos.y)/20;
  var limite = 15;

  if(x> limite){
    x = limite;
  }
  if(x<(limite-(2*limite))){
    x = limite-(2*limite);
  }
  if(y> limite){
    y = limite;
  }
  if(y<(limite-(2*limite))){
    y= limite-(2*limite);
  }
  return{
    x: x,
    y: y
  }
}

function analisaImpactoPlayer(projetil, player){
  if(projetil.position.x > player.posicao.x && projetil.position.x <(player.posicao.x +player.tamanho.width)){
    if(projetil.position.y > player.posicao.y && projetil.position.y <(player.posicao.y +player.tamanho.height)){
      console.log("Acertou o ardversário");

      if (isPlayer1) {
        console.log(player1Life);
        $(player1Life.diamonds[player1Life.index]).addClass('lifeLost');
        player1Life.index--;
      } else {
        console.log(player2Life);
        $(player2Life.diamonds[player2Life.index]).addClass('lifeLost');
        player2Life.index++;
      }

      player.vida -=1;
      if(player.vida === 0){
        winner(player);
      }

      encerraJogada(projetil);
    }
  }
}

function analisaImpactoPredio(projetil){
  for(var i = 0; i< predios.length; i++){
    if(projetil.position.x > predios[i].XInicial && projetil.position.x < predios[i].XFinal){ //testa se está na área de um predio
      if(projetil.position.y > predios[i].YInicial && projetil.position.y < predios[i].YFinal){
        for(var k = 0 ; k<damages.length;k++){ // varre o vetor de damages a fim de se certificar que o projetil está dentro de uma área já destruida
          if(projetil.position.x > damages[k].xin && projetil.position.x < damages[k].xfinal){
            if(projetil.position.y > damages[k].yin && projetil.position.y <  damages[k].yfinal){
              return 0; //se o projetil está em área já destruida, o projetil segue a trajetória.
            }
          }
        }
        console.log("Acertou o prédio");
        createDamage(projetil,context);
        encerraJogada(projetil);
      }
    }
  }
}

function encerraJogada(projetil){
  projetil.position.y = projectilPosIniY;
  projetil.position.x = projectilPosIniX;
  numeroJogada=0;
  contextoTemporario.clearRect(0,0,canvasTemporario.width,canvasTemporario.height); //impede que o projetil fique congelado onde o impacto acontece
  console.log("Player " + num);
  window.clearInterval(intervaloJogada);
  if (isPlayer1) {
	  $(playersUI[0]).addClass('player-active')
	  $(playersUI[1]).removeClass('player-active');
	} else {
	  $(playersUI[1]).addClass('player-active');
	  $(playersUI[0]).removeClass('player-active');
	}
}

function createDamage(projetil,context){

  context.clearRect(projetil.position.x-20,projetil.position.y-20,40,40);
  var damage = new Object();
  damage.xin= projetil.position.x-20;
  damage.yin= projetil.position.y-20;
  damage.xfinal = projetil.position.x+20;
  damage.yfinal = projetil.position.y+20;
  damages.push(damage);
}

function winner(player_loser){
  context.clearRect(0,0,1000,600);
  contextoTemporario.clearRect(0,0,1000,600);
  criaMenuEsboco(context);
  var textloser = player_loser.name +" was destroyed!";
  var winner;
  if(player_loser.name ==="Player 1") winner = "Player 2";
  else winner = "Player 1";
  var textWinner = winner +", you rock!";
  context.fillStyle = "#FFF";
  context.font = "40px 'Press Start 2P'";
  context.fillText(textWinner,110,150);
  context.font = "20px'Press Start 2P'";
  context.fillText(textloser,270,300);
  context.fillText("Try harder next time.",290,350);
  restart();
}
<|endoftext|>


<commit_before>import xs from 'xstream'
import { run } from '@cycle/run'
import { makeDOMDriver } from '@cycle/dom'

import { board as boardController } from 'board'
import { moveHistory as moveHistoryController } from 'move-history'

import { combinedDOM } from 'view'

const main = (sources) => {
  const board1 = boardController.main1(sources)
  const moveHistory1 = moveHistoryController.main1(board1)

  const board$ = board1.reducer$.fold((board, reducer) => reducer(board), board1.initialState)
  const moveHistory$ = moveHistory1.reducer$.fold((moveHistory, reducer) => reducer(moveHistory), moveHistory1.initialState)

  const board2 = boardController.main2({ board$ })
  const moveHistory2 = moveHistoryController.main2({ moveHistory$ })

  const combinedDOM$ = xs.combine(board2.DOM, moveHistory2.DOM)
    .map(combinedDOM).remember()

  return {
    DOM: combinedDOM$
  }
}

const drivers = {
  DOM: makeDOMDriver('#free-the-clones'),
}

window.xs = xs

run(main, drivers)
<commit_msg>unify the state stream<commit_after>import xs from 'xstream'
import { run } from '@cycle/run'
import { makeDOMDriver } from '@cycle/dom'

import { board as boardController } from 'board'
import { moveHistory as moveHistoryController } from 'move-history'

import { combinedDOM } from 'view'

const localizeReducer = namespace => reducer => state => Object.assign(state, { [namespace]: reducer(state[namespace]) })

const main = (sources) => {
  const board1 = boardController.main1(sources)
  const moveHistory1 = moveHistoryController.main1(board1)

  const reducer$ = xs.merge(
    board1.reducer$.map(localizeReducer('board')),
    moveHistory1.reducer$.map(localizeReducer('moveHistory'))
  )
  const state$ = reducer$.fold((board, reducer) => reducer(board), {
    board: board1.initialState,
    moveHistory: moveHistory1.initialState
  })

  const board$ = state$.map(({ board }) => board)
  const moveHistory$ = state$.map(({ moveHistory }) => moveHistory)

  const board2 = boardController.main2({ board$ })
  const moveHistory2 = moveHistoryController.main2({ moveHistory$ })

  const combinedDOM$ = xs.combine(board2.DOM, moveHistory2.DOM)
    .map(combinedDOM).remember()

  return {
    DOM: combinedDOM$
  }
}

const drivers = {
  DOM: makeDOMDriver('#free-the-clones'),
}

window.xs = xs

run(main, drivers)
<|endoftext|>


<commit_before>'use strict'

const connect = require('pull-ws/client')
const mafmt = require('mafmt')
const contains = require('lodash.contains')
const Connection = require('interface-connection').Connection
const debug = require('debug')
const log = debug('libp2p:websockets:dialer')

const createListener = require('./listener')

module.exports = class WebSockets {
  dial (ma, options, callback) {
    if (typeof options === 'function') {
      callback = options
      options = {}
    }

    if (!callback) {
      callback = () => {}
    }

    const maOpts = ma.toOptions()

    const url = `ws://${maOpts.host}:${maOpts.port}`
    log('dialing %s', url)
    const socket = connect(url, {
      binary: true,
      onConnect: () => callback
    })

    const conn = new Connection(socket)
    conn.getObservedAddrs = (cb) => cb(null, [ma])
    conn.close = (cb) => socket.close(cb)

    return conn
  }

  createListener (options, handler) {
    if (typeof options === 'function') {
      handler = options
      options = {}
    }

    return createListener(options, handler)
  }

  filter (multiaddrs) {
    if (!Array.isArray(multiaddrs)) {
      multiaddrs = [multiaddrs]
    }

    return multiaddrs.filter((ma) => {
      if (contains(ma.protoNames(), 'ipfs')) {
        ma = ma.decapsulate('ipfs')
      }
      return mafmt.WebSockets.matches(ma)
    })
  }
}
<commit_msg>fix: the fix<commit_after>'use strict'

const connect = require('pull-ws/client')
const mafmt = require('mafmt')
const contains = require('lodash.contains')
const Connection = require('interface-connection').Connection
const debug = require('debug')
const log = debug('libp2p:websockets:dialer')

const createListener = require('./listener')

module.exports = class WebSockets {
  dial (ma, options, callback) {
    if (typeof options === 'function') {
      callback = options
      options = {}
    }

    if (!callback) {
      callback = () => {}
    }

    const maOpts = ma.toOptions()

    const url = `ws://${maOpts.host}:${maOpts.port}`
    log('dialing %s', url)
    const socket = connect(url, {
      binary: true,
      onConnect: () => callback()
    })

    const conn = new Connection(socket)
    conn.getObservedAddrs = (cb) => cb(null, [ma])
    conn.close = (cb) => socket.close(cb)

    return conn
  }

  createListener (options, handler) {
    if (typeof options === 'function') {
      handler = options
      options = {}
    }

    return createListener(options, handler)
  }

  filter (multiaddrs) {
    if (!Array.isArray(multiaddrs)) {
      multiaddrs = [multiaddrs]
    }

    return multiaddrs.filter((ma) => {
      if (contains(ma.protoNames(), 'ipfs')) {
        ma = ma.decapsulate('ipfs')
      }
      return mafmt.WebSockets.matches(ma)
    })
  }
}
<|endoftext|>


<commit_before>;(function(window, document, undefined){
  'use strict'

  var options = {
    searchInput: null,
    resultsContainer: null,
    json: [],
    searchResultTemplate: '
{title}
',
    templateMiddleware: function(){},
    noResultsText: 'No results found',
    limit: 10,
    fuzzy: false,
    exclude: []
  }

  var requiredOptions = ['searchInput','resultsContainer','json']

  var templater = require('./Templater')
  var repository = require('./Repository')
  var jsonLoader = require('./JSONLoader')
  var optionsValidator = require('./OptionsValidator')({
    required: requiredOptions
  })
  var utils = require('./utils')

  /*
    Public API
  */
  window.SimpleJekyllSearch = function SimpleJekyllSearch(_options){
    var errors = optionsValidator.validate(_options)
    if( errors.length > 0 ){
      throwError('You must specify the following required options: ' + requiredOptions)
    }

    options = utils.merge(options, _options)

    templater.setOptions({
      template: options.searchResultTemplate,
      middleware: options.templateMiddleware,
    })

    repository.setOptions({
      fuzzy: options.fuzzy,
      limit: options.limit,
    })

    if( utils.isJSON(options.json) ){
      initWithJSON(options.json)
    }else{
      initWithURL(options.json)
    }
  }

  // for backwards compatibility
  window.SimpleJekyllSearch.init = window.SimpleJekyllSearch

  function initWithJSON(json){
    repository.put(json)
    registerInput()
  }

  function initWithURL(url){
    jsonLoader.load(url, function(err,json){
      if( err ){
        throwError('failed to get JSON (' + url + ')')
      }
      initWithJSON(json)
    })
  }

  function emptyResultsContainer(){
    options.resultsContainer.innerHTML = ''
  }

  function appendToResultsContainer(text){
    options.resultsContainer.innerHTML += text
  }

  function registerInput(){

    // https://remysharp.com/2010/07/21/throttling-function-calls
    function debounce(fn, delay) {
      var timer = null;
      return function () {
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
          fn.apply(context, args);
        }, delay);
      };
    }

    options.searchInput.addEventListener('keyup', debounce(function(e){

      // whitelist the following keycodes
      var whitelist = [37,38,39,40];

      var keyCodes = whitelist.map(function(code){
        return 'e.which != ' + code;
      }).join(' && ');

      // if the key pressed isn't one of the following whitelisted codes precede
      if( eval(keyCodes) ){
        emptyResultsContainer()
        if( e.target.value.length > 0 ){
          render( repository.search(e.target.value) )
        }
      }

    }, 100)) // timeout
  }

  function render(results){
    if( results.length === 0 ){
      return appendToResultsContainer(options.noResultsText)
    }
    for (var i = 0; i < results.length; i++) {
      appendToResultsContainer( templater.compile(results[i]) )
    }
  }

  function throwError(message){ throw new Error('SimpleJekyllSearch --- '+ message) }
})(window, document);<commit_msg>added 'enter' key to whitelist<commit_after>;(function(window, document, undefined){
  'use strict'

  var options = {
    searchInput: null,
    resultsContainer: null,
    json: [],
    searchResultTemplate: '
{title}
',
    templateMiddleware: function(){},
    noResultsText: 'No results found',
    limit: 10,
    fuzzy: false,
    exclude: []
  }

  var requiredOptions = ['searchInput','resultsContainer','json']

  var templater = require('./Templater')
  var repository = require('./Repository')
  var jsonLoader = require('./JSONLoader')
  var optionsValidator = require('./OptionsValidator')({
    required: requiredOptions
  })
  var utils = require('./utils')

  /*
    Public API
  */
  window.SimpleJekyllSearch = function SimpleJekyllSearch(_options){
    var errors = optionsValidator.validate(_options)
    if( errors.length > 0 ){
      throwError('You must specify the following required options: ' + requiredOptions)
    }

    options = utils.merge(options, _options)

    templater.setOptions({
      template: options.searchResultTemplate,
      middleware: options.templateMiddleware,
    })

    repository.setOptions({
      fuzzy: options.fuzzy,
      limit: options.limit,
    })

    if( utils.isJSON(options.json) ){
      initWithJSON(options.json)
    }else{
      initWithURL(options.json)
    }
  }

  // for backwards compatibility
  window.SimpleJekyllSearch.init = window.SimpleJekyllSearch

  function initWithJSON(json){
    repository.put(json)
    registerInput()
  }

  function initWithURL(url){
    jsonLoader.load(url, function(err,json){
      if( err ){
        throwError('failed to get JSON (' + url + ')')
      }
      initWithJSON(json)
    })
  }

  function emptyResultsContainer(){
    options.resultsContainer.innerHTML = ''
  }

  function appendToResultsContainer(text){
    options.resultsContainer.innerHTML += text
  }

  function registerInput(){

    // https://remysharp.com/2010/07/21/throttling-function-calls
    function debounce(fn, delay) {
      var timer = null;
      return function () {
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
          fn.apply(context, args);
        }, delay);
      };
    }

    options.searchInput.addEventListener('keyup', debounce(function(e){

      // whitelist the following keycodes
      var whitelist = [13,37,38,39,40];

      var keyCodes = whitelist.map(function(code){
        return 'e.which != ' + code;
      }).join(' && ');

      // if the key pressed isn't one of the following whitelisted codes precede
      if( eval(keyCodes) ){
        emptyResultsContainer()
        if( e.target.value.length > 0 ){
          render( repository.search(e.target.value) )
        }
      }

    }, 100)) // timeout
  }

  function render(results){
    if( results.length === 0 ){
      return appendToResultsContainer(options.noResultsText)
    }
    for (var i = 0; i < results.length; i++) {
      appendToResultsContainer( templater.compile(results[i]) )
    }
  }

  function throwError(message){ throw new Error('SimpleJekyllSearch --- '+ message) }
})(window, document);<|endoftext|>


<commit_before>import next from 'next';
import path from 'path';
import express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import userRoutes from './routes/userRoutes';
// import authRouter from './routes/AuthenticationRoute';
require('dotenv').config();

const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({
  dev,
  dir: path.resolve(__dirname)
});
const handle = nextApp.getRequestHandler();

const PORT = process.env.PORT || 8001;

nextApp.prepare().then(() => {
  const app = express();

  app.use(bodyParser.json());

  // Define all you backend handlers here...
  mongoose.Promise = global.Promise;
  mongoose.connect('heroku_nv8wv6z2:v5eb88j1j0aukbsbbu3mb2dtes@ds129023.mlab.com:29023/heroku_nv8wv6z2', {
    useMongoClient: true,
  });

  const db = mongoose.connection;

  db.on('error', console.error.bind(console, 'connection error'));
  db.once('open', function () {
    console.log('we are connected!');
  });

  app.use(userRoutes);
  // app.use(authRouter);
  // Handle everything that is not covered in above routes with next.js
  app.get('*', (request, response) => {
    return handle(request, response);
  });

  app.listen(PORT, () => {
    // eslint-disable-next-line
    console.log('Server listening on port ' + PORT);
  });
});
<commit_msg>trying to fix db<commit_after>import next from 'next';
import path from 'path';
import express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import userRoutes from './routes/userRoutes';
// import authRouter from './routes/AuthenticationRoute';
require('dotenv').config();

const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({
  dev,
  dir: path.resolve(__dirname)
});
const handle = nextApp.getRequestHandler();

const PORT = process.env.PORT || 8001;

nextApp.prepare().then(() => {
  const app = express();

  app.use(bodyParser.json());

  // Define all you backend handlers here...
  mongoose.Promise = global.Promise;
  mongoose.connect('heroku_nv8wv6z2:v5eb88j1j0aukbsbbu3mb2dtes@ds129023.mlab.com:29023/heroku_nv8wv6z2/29017/drpat', {
    useMongoClient: true,
  });

  const db = mongoose.connection;

  db.on('error', console.error.bind(console, 'connection error'));
  db.once('open', function () {
    console.log('we are connected!');
  });

  app.use(userRoutes);
  // app.use(authRouter);
  // Handle everything that is not covered in above routes with next.js
  app.get('*', (request, response) => {
    return handle(request, response);
  });

  app.listen(PORT, () => {
    // eslint-disable-next-line
    console.log('Server listening on port ' + PORT);
  });
});
<|endoftext|>


<commit_before>import Table from './Table';
import Column from './Column';
import ColumnGroup from './ColumnGroup';

Table.Column = Column;
Table.ColumnGroup = ColumnGroup;

export default Table;
<commit_msg>export Column and ColumnGroup<commit_after>import Table from './Table';
import Column from './Column';
import ColumnGroup from './ColumnGroup';

Table.Column = Column;
Table.ColumnGroup = ColumnGroup;

export default Table;
export { Column, ColumnGroup };
<|endoftext|>


<commit_before>const TAN_22_5 = Math.tan(Math.PI / 8);
const UTILITIES = {
	isBetween: (x, a, b) => x >= Math.min(a, b) && x < Math.max(a, b),
	runForTime: (object, callback, onComplete) => {
		const time = Date.now();
		for (const key in object) {
			callback(key);
			if (Date.now() - time > 20) {
				setTimeout(() => UTILITIES.runForTime(object, callback, onComplete));
				return;
			}
		}
		if (onComplete != null) {
			setTimeout(onComplete);
		}
	},
	connectLine: (x1, y1, direction1, offsetIndex1, routeCount1, x2, y2, direction2, offsetIndex2, routeCount2, lineWidth, segments) => {
		const offset1 = (offsetIndex1 - (routeCount1 - 1) / 2) * lineWidth;
		const offset2 = (offsetIndex2 - (routeCount2 - 1) / 2) * lineWidth;
		const offset1Rotated = UTILITIES.rotatePoint(offset1, 0, direction1);
		const offset2Rotated = UTILITIES.rotatePoint(offset2, 0, direction2);
		x1 += offset1Rotated["x"];
		y1 += offset1Rotated["y"];
		x2 += offset2Rotated["x"];
		y2 += offset2Rotated["y"];

		const {x, y} = UTILITIES.rotatePoint(x2 - x1, y2 - y1, -direction1);
		const signX = Math.sign(x);
		const signY = Math.sign(y);
		const absX = Math.abs(x);
		const absY = Math.abs(y);
		const rotatedDirection = (direction2 - direction1 + 180) % 180;
		const isTopRight = (x > 0) === (y > 0);
		const points = [];

		points.push(UTILITIES.rotatePoint(0, 0, direction1));
		const getEndOffset = (maxHeight, isTop) => clamp(signX * offset1 * TAN_22_5 + routeCount1 * lineWidth / (isTop ? 2 : -2), maxHeight);

		if (rotatedDirection === 0) {
			if (absX > absY) {
				const difference = absY / 2;
				const lineOffset = clamp(offset1, absY / routeCount1);
				const endOffset1 = getEndOffset((difference - Math.abs(lineOffset)) / 2, false);
				const endOffset2 = getEndOffset((difference - Math.abs(lineOffset)) / 2, true);
				points.push(UTILITIES.rotatePoint(0, -signY * endOffset1, direction1));
				points.push(UTILITIES.rotatePoint(signX * difference + signX * endOffset1 - lineOffset, signY * difference + (isTopRight ? -1 : 1) * lineOffset, direction1));
				points.push(UTILITIES.rotatePoint(x - signX * difference + signX * endOffset2 - lineOffset, signY * difference + (isTopRight ? -1 : 1) * lineOffset, direction1));
				points.push(UTILITIES.rotatePoint(x, y - signY * endOffset2, direction1));
			} else {
				const difference = (absY - absX) / 2;
				const lineOffset = clamp((isTopRight ? -1 : 1) * offset1 * TAN_22_5, difference);
				points.push(UTILITIES.rotatePoint(0, signY * difference + lineOffset, direction1));
				points.push(UTILITIES.rotatePoint(x, y - signY * difference + lineOffset, direction1));
			}
		} else {
			const var2 = direction1 === 45 && direction2 === 0 || direction1 === 90 && direction2 === 45 || direction1 === 135 && direction2 === 0 || direction1 === 135 && direction2 === 90;
			const getFinalPoint = () => UTILITIES.rotatePoint(0, ((rotatedDirection === 45) !== var2 ? -1 : 1) * getEndOffset(Math.sqrt(absX * absX / 4 + absY * absY / 4), (rotatedDirection === 45) !== var2), rotatedDirection);
			if (absX > absY) {
				const endOffset1 = getEndOffset(absY / 2, false);
				points.push(UTILITIES.rotatePoint(0, -signY * endOffset1, direction1));
				if (rotatedDirection === 90) {
					points.push(UTILITIES.rotatePoint(signX * absY + signX * endOffset1, y, direction1));
				} else {
					const finalPoint = getFinalPoint();
					points.push(UTILITIES.rotatePoint(signX * absY + signX * endOffset1 + (rotatedDirection === 45 === isTopRight ? 1 : -1) * signX * finalPoint["x"], y - signX * finalPoint["y"], direction1));
					points.push(UTILITIES.rotatePoint(x - signX * finalPoint["x"], y - signX * finalPoint["y"], direction1));
				}
			} else {
				if (rotatedDirection === 90) {
					const var1 = direction1 - direction2 !== 90;
					const endOffset2 = getEndOffset(absX / 2, isTopRight === var1);
					points.push(UTILITIES.rotatePoint(0, y - signY * absX + (var1 ? 1 : -1) * signX * endOffset2, direction1));
					points.push(UTILITIES.rotatePoint(x - (var1 ? 1 : -1) * signY * endOffset2, y, direction1));
				} else {
					if (rotatedDirection === 45 && isTopRight || rotatedDirection === 135 && !isTopRight) {
						const endOffset1 = getEndOffset(absY / 2, false);
						points.push(UTILITIES.rotatePoint(0, -signY * endOffset1, direction1));
						const finalPoint = getFinalPoint();
						points.push(UTILITIES.rotatePoint(x + signX * finalPoint["x"], signY * absX - signY * endOffset1 - signX * finalPoint["y"], direction1));
						points.push(UTILITIES.rotatePoint(x + signX * finalPoint["x"], y + signX * finalPoint["y"], direction1));
					} else {
						points.push(UTILITIES.rotatePoint(0, y - signY * absX + signX, direction1));
					}
				}
			}
		}

		points.push(UTILITIES.rotatePoint(x, y, direction1));
		points.forEach(point => segments.push({"x": point["x"] + x1, "y": point["y"] + y1}));
	},
	getDrawStationElement: (stationElement, color1, color2) => {
		const element = document.createElement("div");
		element.className = "route_station_name";
		if (color1 != null) {
			element.innerHTML = `<span class="route_segment bottom" style="background-color: ${UTILITIES.convertColor(color1)}">&nbsp</span>`;
		}
		if (color2 != null) {
			element.innerHTML += `<span class="route_segment top" style="background-color: ${UTILITIES.convertColor(color2)}">&nbsp</span>`;
		}
		element.innerHTML += `<span class="station_circle"></span>`;
		element.appendChild(stationElement);
		return element;
	},
	getDrawLineElement: (icon, innerElement, color) => {
		const element = document.createElement("div");
		element.className = "route_duration";
		element.innerHTML =
			`<span class="route_segment ${color == null ? "walk" : ""}" style="background-color: ${color == null ? 0 : UTILITIES.convertColor(color)}">&nbsp</span>` +
			`<span class="material-icons small">${icon}</span>`;
		element.appendChild(innerElement);
		return element;
	},
	convertGtfsRouteType: routeType => {
		switch (routeType) {
			case 0:
			case 5:
			case 12:
				return "train_light_rail";
			case 2:
				return "train_high_speed";
			case 3:
			case 11:
				return "bus_normal";
			case 4:
				return "boat_light_rail";
			case 6:
				return "cable_car_normal";
			default:
				return "train_normal";
		}
	},
	directionToAngle: direction => {
		const directionIndex = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"].indexOf(direction);
		return UTILITIES.angles[(directionIndex >= 0 ? directionIndex : 0) % UTILITIES.angles.length];
	},
	formatTime: time => {
		const hour = Math.floor(time / 3600);
		const minute = Math.floor(time / 60) % 60;
		const second = Math.floor(time) % 60;
		return (hour > 0 ? hour.toString() + ":" : "") + (hour > 0 ? minute.toString().padStart(2, "0") : minute.toString()) + ":" + second.toString().padStart(2, "0");
	},
	getColorStyle: style => parseInt(getComputedStyle(document.body).getPropertyValue(style).replace(/#/g, ""), 16),
	convertColor: colorInt => "#" + Number(colorInt).toString(16).padStart(6, "0"),
	isCJK: text => text.match(/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u3400-\u4dbf]/),
	removeFromArray: (array, element) => {
		const index = array.indexOf(element);
		if (index > -1) {
			array.splice(index, 1);
		}
	},
	rotatePoint: (x, y, direction) => {
		const getSin = direction => {
			switch ((direction + 360) % 360) {
				case 90:
					return 1;
				case 270:
					return -1;
				case 45:
				case 135:
					return Math.SQRT1_2;
				case 225:
				case 315:
					return -Math.SQRT1_2;
				default:
					return 0;
			}
		};
		const getCos = direction => {
			switch ((direction + 360) % 360) {
				case 0:
					return 1;
				case 180:
					return -1;
				case 45:
				case 315:
					return Math.SQRT1_2;
				case 135:
				case 225:
					return -Math.SQRT1_2;
				default:
					return 0;
			}
		};
		return {
			"x": x * getCos(direction) - y * getSin(direction),
			"y": x * getSin(direction) + y * getCos(direction),
		};
	},
	routeTypes: {
		"train_normal": "directions_train",
		"train_light_rail": "tram",
		"train_high_speed": "train",
		"boat_normal": "sailing",
		"boat_light_rail": "directions_boat",
		"boat_high_speed": "snowmobile",
		"cable_car_normal": "airline_seat_recline_extra",
		"bus_normal": "directions_bus",
		"bus_light_rail": "local_taxi",
		"bus_high_speed": "airport_shuttle",
	},
	angles: [0, 45, 90, 135],
	fonts: ["Noto Sans", "Noto Serif TC", "Noto Serif SC", "Noto Serif JP", "Noto Serif KR", "Material Icons"],
	obaMode: false,
	testMode: false,
};

const clamp = (x, bound) => Math.max(Math.min(x, bound), -bound);

export default UTILITIES;
<commit_msg>System map temp fix<commit_after>const TAN_22_5 = Math.tan(Math.PI / 8);
const UTILITIES = {
	isBetween: (x, a, b) => x >= Math.min(a, b) && x < Math.max(a, b),
	runForTime: (object, callback, onComplete) => {
		const time = Date.now();
		for (const key in object) {
			callback(key);
			if (Date.now() - time > 20) {
				setTimeout(() => UTILITIES.runForTime(object, callback, onComplete));
				return;
			}
		}
		if (onComplete != null) {
			setTimeout(onComplete);
		}
	},
	connectLine: (x1, y1, direction1, offsetIndex1, routeCount1, x2, y2, direction2, offsetIndex2, routeCount2, lineWidth, segments) => {
		if (x2 > x1) {
			UTILITIES.connectLine1(x1, y1, direction1, offsetIndex1, routeCount1, x2, y2, direction2, offsetIndex2, routeCount2, lineWidth, segments);
		} else {
			UTILITIES.connectLine1(x2, y2, direction2, offsetIndex2, routeCount2, x1, y1, direction1, offsetIndex1, routeCount1, lineWidth, segments);
		}
	},
	connectLine1: (x1, y1, direction1, offsetIndex1, routeCount1, x2, y2, direction2, offsetIndex2, routeCount2, lineWidth, segments) => {
		const offset1 = (offsetIndex1 - (routeCount1 - 1) / 2) * lineWidth;
		const offset2 = (offsetIndex2 - (routeCount2 - 1) / 2) * lineWidth;
		const offset1Rotated = UTILITIES.rotatePoint(offset1, 0, direction1);
		const offset2Rotated = UTILITIES.rotatePoint(offset2, 0, direction2);
		x1 += offset1Rotated["x"];
		y1 += offset1Rotated["y"];
		x2 += offset2Rotated["x"];
		y2 += offset2Rotated["y"];

		const {x, y} = UTILITIES.rotatePoint(x2 - x1, y2 - y1, -direction1);
		const signX = Math.sign(x);
		const signY = Math.sign(y);
		const absX = Math.abs(x);
		const absY = Math.abs(y);
		const rotatedDirection = (direction2 - direction1 + 180) % 180;
		const isTopRight = (x > 0) === (y > 0);
		const points = [];

		points.push(UTILITIES.rotatePoint(0, 0, direction1));
		const halfRouteCount1 = routeCount1 * lineWidth / 2;
		const halfRouteCount2 = routeCount2 * lineWidth / 2;

		if (rotatedDirection === 0) {
			if (absX > absY) {
				const difference = absY / 2;
				const lineOffset = -clamp(offset1, absY / routeCount1) * signX * signY;
				const endOffset1 = clamp(-signX * offset1 * TAN_22_5 + halfRouteCount1, (difference - Math.abs(lineOffset)) / 2);
				const endOffset2 = clamp(signX * offset2 * TAN_22_5 + halfRouteCount2, (difference - Math.abs(lineOffset)) / 2);
				points.push(UTILITIES.rotatePoint(0, signY * endOffset1, direction1));
				points.push(UTILITIES.rotatePoint(signX * difference - signX * endOffset1 + signX * signY * lineOffset, signY * difference + lineOffset, direction1));
				points.push(UTILITIES.rotatePoint(x - signX * difference + signX * endOffset2 + signX * signY * lineOffset, signY * difference + lineOffset, direction1));
				points.push(UTILITIES.rotatePoint(x, y - signY * endOffset2, direction1));
			} else {
				const offsetDifference = offset2 - offset1;
				const difference = (absY - absX + offsetDifference) / 2;
				const lineOffset = clamp((isTopRight ? -(direction1 === 0 ? offset1 : offset2) : offset1) * TAN_22_5, difference);
				points.push(UTILITIES.rotatePoint(0, signY * difference + lineOffset, direction1));
				points.push(UTILITIES.rotatePoint(x, y - signY * difference + lineOffset + (direction1 === 0 ? signX * signY : -1) * offsetDifference, direction1));
			}
		} else {
			const getFinalPoint = () => UTILITIES.rotatePoint(0, clamp((direction1 === 0 || direction1 === 45 ? 1 : -1) * offset2 * TAN_22_5 + halfRouteCount2, absX / 2), rotatedDirection);
			if (absX > absY) {
				const endOffset1 = clamp(-signX * offset1 * TAN_22_5 + halfRouteCount1, absY / 2);
				points.push(UTILITIES.rotatePoint(0, signY * endOffset1, direction1));
				if (rotatedDirection === 90) {
					points.push(UTILITIES.rotatePoint(signX * absY - signX * endOffset1, y, direction1));
				} else {
					const offsetDifference = offset2 - offset1;
					const finalPoint = getFinalPoint();
					points.push(UTILITIES.rotatePoint(signX * absY - signX * endOffset1 + (direction2 === 45 ? -1 : 1) * signY * finalPoint["x"], y + finalPoint["y"], direction1));
					points.push(UTILITIES.rotatePoint(x + finalPoint["x"], y + finalPoint["y"], direction1));
				}
			} else {
				if (rotatedDirection === 90) {
					const endOffset2 = clamp((direction1 === 0 || direction1 === 45 ? 1 : -1) * signY * offset2 * TAN_22_5 + halfRouteCount2, absX / 2);
					points.push(UTILITIES.rotatePoint(0, y - signY * absX + (isTopRight ? 1 : -1) * signX * endOffset2, direction1));
					points.push(UTILITIES.rotatePoint(x - signX * endOffset2, y, direction1));
				} else {
					// if (rotatedDirection === 45 && isTopRight || rotatedDirection === 135 && !isTopRight) {
					// 	const endOffset1 = getEndOffset(absY / 2, false);
					// 	points.push(UTILITIES.rotatePoint(0, -signY * endOffset1, direction1));
					// 	const finalPoint = getFinalPoint();
					// 	points.push(UTILITIES.rotatePoint(x + signX * finalPoint["x"], signY * absX - signY * endOffset1 - signX * finalPoint["y"], direction1));
					// 	points.push(UTILITIES.rotatePoint(x + signX * finalPoint["x"], y + signX * finalPoint["y"], direction1));
					// } else {
					// 	points.push(UTILITIES.rotatePoint(0, y - signY * absX + signX, direction1));
					// }
				}
			}
		}

		points.push(UTILITIES.rotatePoint(x, y, direction1));
		points.forEach(point => segments.push({"x": point["x"] + x1, "y": point["y"] + y1}));
	},
	getDrawStationElement: (stationElement, color1, color2) => {
		const element = document.createElement("div");
		element.className = "route_station_name";
		if (color1 != null) {
			element.innerHTML = `<span class="route_segment bottom" style="background-color: ${UTILITIES.convertColor(color1)}">&nbsp</span>`;
		}
		if (color2 != null) {
			element.innerHTML += `<span class="route_segment top" style="background-color: ${UTILITIES.convertColor(color2)}">&nbsp</span>`;
		}
		element.innerHTML += `<span class="station_circle"></span>`;
		element.appendChild(stationElement);
		return element;
	},
	getDrawLineElement: (icon, innerElement, color) => {
		const element = document.createElement("div");
		element.className = "route_duration";
		element.innerHTML =
			`<span class="route_segment ${color == null ? "walk" : ""}" style="background-color: ${color == null ? 0 : UTILITIES.convertColor(color)}">&nbsp</span>` +
			`<span class="material-icons small">${icon}</span>`;
		element.appendChild(innerElement);
		return element;
	},
	convertGtfsRouteType: routeType => {
		switch (routeType) {
			case 0:
			case 5:
			case 12:
				return "train_light_rail";
			case 2:
				return "train_high_speed";
			case 3:
			case 11:
				return "bus_normal";
			case 4:
				return "boat_light_rail";
			case 6:
				return "cable_car_normal";
			default:
				return "train_normal";
		}
	},
	directionToAngle: direction => {
		const directionIndex = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"].indexOf(direction);
		return UTILITIES.angles[(directionIndex >= 0 ? directionIndex : 0) % UTILITIES.angles.length];
	},
	formatTime: time => {
		const hour = Math.floor(time / 3600);
		const minute = Math.floor(time / 60) % 60;
		const second = Math.floor(time) % 60;
		return (hour > 0 ? hour.toString() + ":" : "") + (hour > 0 ? minute.toString().padStart(2, "0") : minute.toString()) + ":" + second.toString().padStart(2, "0");
	},
	getColorStyle: style => parseInt(getComputedStyle(document.body).getPropertyValue(style).replace(/#/g, ""), 16),
	convertColor: colorInt => "#" + Number(colorInt).toString(16).padStart(6, "0"),
	isCJK: text => text.match(/[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\uff00-\uff9f\u4e00-\u9faf\u3400-\u4dbf]/),
	removeFromArray: (array, element) => {
		const index = array.indexOf(element);
		if (index > -1) {
			array.splice(index, 1);
		}
	},
	rotatePoint: (x, y, direction) => {
		const getSin = direction => {
			switch ((direction + 360) % 360) {
				case 90:
					return 1;
				case 270:
					return -1;
				case 45:
				case 135:
					return Math.SQRT1_2;
				case 225:
				case 315:
					return -Math.SQRT1_2;
				default:
					return 0;
			}
		};
		const getCos = direction => {
			switch ((direction + 360) % 360) {
				case 0:
					return 1;
				case 180:
					return -1;
				case 45:
				case 315:
					return Math.SQRT1_2;
				case 135:
				case 225:
					return -Math.SQRT1_2;
				default:
					return 0;
			}
		};
		return {
			"x": x * getCos(direction) - y * getSin(direction),
			"y": x * getSin(direction) + y * getCos(direction),
		};
	},
	routeTypes: {
		"train_normal": "directions_train",
		"train_light_rail": "tram",
		"train_high_speed": "train",
		"boat_normal": "sailing",
		"boat_light_rail": "directions_boat",
		"boat_high_speed": "snowmobile",
		"cable_car_normal": "airline_seat_recline_extra",
		"bus_normal": "directions_bus",
		"bus_light_rail": "local_taxi",
		"bus_high_speed": "airport_shuttle",
	},
	angles: [0, 45, 90, 135],
	fonts: ["Noto Sans", "Noto Serif TC", "Noto Serif SC", "Noto Serif JP", "Noto Serif KR", "Material Icons"],
	obaMode: false,
	testMode: false,
};

const clamp = (x, bound) => Math.max(Math.min(x, bound), -bound);

export default UTILITIES;
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';

import SearchBar from './components/search-bar';

import { YOU_TUBE_KEY } from '../keys'

// function to fetch videos from YouTube:
YTSearch({key: YOU_TUBE_KEY, term: 'surfboards'}, function(data) {
  console.log(data);
});

const App = () => {
  return (

      <SearchBar />

  );
}

ReactDOM.render(<App />, document.querySelector('.container'));
<commit_msg>app component changed from functional to class based<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';

import SearchBar from './components/search-bar';

import { YOU_TUBE_KEY } from '../keys'

// function to fetch videos from YouTube:
YTSearch({key: YOU_TUBE_KEY, term: 'surfboards'}, function(data) {
  console.log(data);
});

/* functional component, which got refactored to a class component below
const App = () => {
  return (

      <SearchBar />

  );
}
*/

class App extends Component {
  render() {
    return (

        <SearchBar />

    )
  }
}

ReactDOM.render(<App />, document.querySelector('.container'));
<|endoftext|>