<commit_before>/* @flow */

import clone from 'lodash.clone'
import EventEmitter from 'events'
import { posix, sep } from 'path'
import * as stream from 'stream'

import Config from '../config'
import * as conversion from '../conversion'
import RemoteCozy from './cozy'
import logger from '../logger'
import Pouch from '../pouch'
import Prep from '../prep'
import Watcher from './watcher'

import type { RemoteDoc } from './document'
import type { FileStreamProvider } from '../file_stream_provider'
import type { Metadata } from '../metadata'
import type { Side } from '../side' // eslint-disable-line

const log = logger({
  component: 'RemoteWriter'
})

export default class Remote implements Side {
  other: FileStreamProvider
  pouch: Pouch
  events: EventEmitter
  watcher: Watcher
  remoteCozy: RemoteCozy

  constructor (config: Config, prep: Prep, pouch: Pouch, events: EventEmitter) {
    this.pouch = pouch
    this.events = events
    this.remoteCozy = new RemoteCozy(config)
    this.watcher = new Watcher(pouch, prep, this.remoteCozy, events)
  }

  start () {
    return this.watcher.start()
  }

  stop () {
    return this.watcher.stop()
  }

  sendMail (args: any) {
    return this.remoteCozy.createJob('sendmail', args)
  }

  unregister () {
    return this.remoteCozy.unregister()
  }

  // Create a readable stream for the given doc
  createReadStreamAsync (doc: Metadata): Promise<stream.Readable> {
    return this.remoteCozy.downloadBinary(doc.remote._id)
  }

  // Create a folder on the remote cozy instance
  async addFolderAsync (doc: Metadata): Promise<Metadata> {
    const {path} = doc
    log.info({path}, 'Creating folder...')

    const [parentPath, name] = conversion.extractDirAndName(doc.path)
    const parent: RemoteDoc = await this.remoteCozy.findOrCreateDirectoryByPath(parentPath)
    let dir: RemoteDoc

    try {
      dir = await this.remoteCozy.createDirectory({
        name,
        dirID: parent._id,
        lastModifiedDate: doc.updated_at
      })
    } catch (err) {
      if (err.status !== 409) { throw err }

      log.info({path}, 'Folder already exists')
      const remotePath = '/' + posix.join(...doc.path.split(sep))
      dir = await this.remoteCozy.findDirectoryByPath(remotePath)
    }

    doc.remote = {
      _id: dir._id,
      _rev: dir._rev
    }

    return conversion.createMetadata(dir)
  }

  async addFileAsync (doc: Metadata): Promise<Metadata> {
    const {path} = doc
    log.info({path}, 'Uploading new file...')
    const stream = await this.other.createReadStreamAsync(doc)
    const [dirPath, name] = conversion.extractDirAndName(path)
    const dir = await this.remoteCozy.findOrCreateDirectoryByPath(dirPath)

    // Emit events to track the upload progress
    let info = clone(doc)
    info.way = 'up'
    info.eventName = `transfer-up-${doc._id}`
    this.events.emit('transfer-started', info)
    stream.on('data', data => {
      this.events.emit(info.eventName, data)
    })
    stream.on('finish', () => {
      this.events.emit(info.eventName, {finished: true})
    })

    const created = await this.remoteCozy.createFile(stream, {
      name,
      dirID: dir._id,
      executable: doc.executable,
      contentType: doc.mime,
      lastModifiedDate: new Date(doc.updated_at)
    })

    doc.remote = {
      _id: created._id,
      _rev: created._rev
    }

    // TODO do we use the returned values somewhere?
    return conversion.createMetadata(created)
  }

  async overwriteFileAsync (doc: Metadata, old: ?Metadata): Promise<Metadata> {
    const {path} = doc
    log.info({path}, 'Uploading new file version...')
    const stream = await this.other.createReadStreamAsync(doc)
    const options = {
      contentType: doc.mime,
      checksum: doc.md5sum,
      lastModifiedDate: new Date(doc.updated_at),
      ifMatch: ''
    }
    if (old && old.remote) {
      options.ifMatch = old.remote._rev
    }
    const updated = await this.remoteCozy.updateFileById(doc.remote._id, stream, options)

    doc.remote._rev = updated._rev

    return conversion.createMetadata(updated)
  }

  async updateFileMetadataAsync (doc: Metadata, old: any): Promise<Metadata> {
    const {path} = doc
    log.info({path}, 'Updating file metadata...')

    const attrs = {
      executable: doc.executable,
      updated_at: doc.updated_at
    }
    const opts = {
      ifMatch: old.remote._rev
    }
    const updated = await this.remoteCozy.updateAttributesById(old.remote._id, attrs, opts)

    doc.remote = {
      _id: updated._id,
      _rev: updated._rev
    }

    return conversion.createMetadata(updated)
  }

  async moveFileAsync (newMetadata: Metadata, oldMetadata: Metadata): Promise<Metadata> {
    const {path} = newMetadata
    log.info({path}, `Moving from ${oldMetadata.path} ...`)

    const [newDirPath, newName]: [string, string] = conversion.extractDirAndName(path)
    const newDir: RemoteDoc = await this.remoteCozy.findDirectoryByPath(newDirPath)

    const attrs = {
      name: newName,
      dir_id: newDir._id,
      updated_at: newMetadata.updated_at
    }
    const opts = {
      ifMatch: oldMetadata.remote._rev
    }

    const newRemoteDoc: RemoteDoc = await this.remoteCozy.updateAttributesById(oldMetadata.remote._id, attrs, opts)

    newMetadata.remote = {
      _id: newRemoteDoc._id,
      _rev: newRemoteDoc._rev
    }

    return conversion.createMetadata(newRemoteDoc)
  }

  async updateFolderAsync (doc: Metadata, old: Metadata): Promise<Metadata> {
    const {path} = doc
    if (!old.remote) {
      return this.addFolderAsync(doc)
    }
    log.info({path}, 'Updating metadata...')

    const [newParentDirPath, newName] = conversion.extractDirAndName(path)
    const newParentDir = await this.remoteCozy.findDirectoryByPath(newParentDirPath)
    let newRemoteDoc: RemoteDoc

    const attrs = {
      name: newName,
      dir_id: newParentDir._id,
      updated_at: doc.updated_at
    }
    const opts = {
      ifMatch: old.remote._rev
    }

    try {
      newRemoteDoc = await this.remoteCozy.updateAttributesById(old.remote._id, attrs, opts)
    } catch (err) {
      if (err.status !== 404) { throw err }

      log.warn({path}, "Directory doesn't exist anymore. Recreating it...")
      newRemoteDoc = await this.remoteCozy.createDirectory({
        name: newName,
        dirID: newParentDir._id,
        lastModifiedDate: doc.updated_at
      })
    }

    doc.remote = {
      _id: newRemoteDoc._id,
      _rev: newRemoteDoc._rev
    }

    return conversion.createMetadata(newRemoteDoc)
  }

  async trashAsync (doc: Metadata): Promise<void> {
    const {path} = doc
    log.info({path}, 'Moving to the trash...')
    let newRemoteDoc: RemoteDoc
    try {
      newRemoteDoc = await this.remoteCozy.trashById(doc.remote._id, {
        ifMatch: doc.remote._rev
      })
    } catch (err) {
      // FIXME: Don't complain when file/dir is already trashed/deleted?
      throw err
    }
    doc.remote._rev = newRemoteDoc._rev
  }

  async deleteFolderAsync (doc: Metadata): Promise<void> {
    await this.trashAsync(doc)
    const {path} = doc

    // FIXME: We use cozy-client-js directly instead of RemoteCozy because we
    // want the dir contents.
    // FIXME: Couldn't we reuse RemoteDoc from trashAsync()
    const folder = await this.remoteCozy.client.files.statById(doc.remote._id)
    if (folder.relations('contents').length === 0) {
      log.info({path}, 'Deleting folder from the Cozy trash...')
      // FIXME: Would it make sense to have an ifMatch option in destroyById()?
      // FIXME: Don't complain when user cleared the trash? (race condition)
      const opts = doc.remote._rev ? { ifMatch: doc.remote._rev } : undefined
      await this.remoteCozy.destroyById(folder._id, opts)
    } else {
      log.warn({path}, 'Folder is not empty and cannot be deleted!')
    }
  }

  moveFolderAsync (doc: Metadata, from: Metadata): Promise<*> {
    // TODO: v3: Remote#moveFolderAsync()
    throw new Error('Remote#moveFolderAsync() is not implemented')
  }

  diskUsage (): Promise<*> {
    return this.remoteCozy.diskUsage()
  }

  // TODO add tests
  async renameConflictingDocAsync (doc: Metadata, newPath: string): Promise<void> {
    const {path} = doc
    log.info({path}, `Resolve a conflict: ${path} → ${newPath}`)
    const newName = conversion.extractDirAndName(newPath)[1]
    await this.remoteCozy.updateAttributesById(doc.remote._id, {
      name: newName
    })
  }
}
<commit_msg>Remove useless ifMatch comment since option is now implemented<commit_after>/* @flow */

import clone from 'lodash.clone'
import EventEmitter from 'events'
import { posix, sep } from 'path'
import * as stream from 'stream'

import Config from '../config'
import * as conversion from '../conversion'
import RemoteCozy from './cozy'
import logger from '../logger'
import Pouch from '../pouch'
import Prep from '../prep'
import Watcher from './watcher'

import type { RemoteDoc } from './document'
import type { FileStreamProvider } from '../file_stream_provider'
import type { Metadata } from '../metadata'
import type { Side } from '../side' // eslint-disable-line

const log = logger({
  component: 'RemoteWriter'
})

export default class Remote implements Side {
  other: FileStreamProvider
  pouch: Pouch
  events: EventEmitter
  watcher: Watcher
  remoteCozy: RemoteCozy

  constructor (config: Config, prep: Prep, pouch: Pouch, events: EventEmitter) {
    this.pouch = pouch
    this.events = events
    this.remoteCozy = new RemoteCozy(config)
    this.watcher = new Watcher(pouch, prep, this.remoteCozy, events)
  }

  start () {
    return this.watcher.start()
  }

  stop () {
    return this.watcher.stop()
  }

  sendMail (args: any) {
    return this.remoteCozy.createJob('sendmail', args)
  }

  unregister () {
    return this.remoteCozy.unregister()
  }

  // Create a readable stream for the given doc
  createReadStreamAsync (doc: Metadata): Promise<stream.Readable> {
    return this.remoteCozy.downloadBinary(doc.remote._id)
  }

  // Create a folder on the remote cozy instance
  async addFolderAsync (doc: Metadata): Promise<Metadata> {
    const {path} = doc
    log.info({path}, 'Creating folder...')

    const [parentPath, name] = conversion.extractDirAndName(doc.path)
    const parent: RemoteDoc = await this.remoteCozy.findOrCreateDirectoryByPath(parentPath)
    let dir: RemoteDoc

    try {
      dir = await this.remoteCozy.createDirectory({
        name,
        dirID: parent._id,
        lastModifiedDate: doc.updated_at
      })
    } catch (err) {
      if (err.status !== 409) { throw err }

      log.info({path}, 'Folder already exists')
      const remotePath = '/' + posix.join(...doc.path.split(sep))
      dir = await this.remoteCozy.findDirectoryByPath(remotePath)
    }

    doc.remote = {
      _id: dir._id,
      _rev: dir._rev
    }

    return conversion.createMetadata(dir)
  }

  async addFileAsync (doc: Metadata): Promise<Metadata> {
    const {path} = doc
    log.info({path}, 'Uploading new file...')
    const stream = await this.other.createReadStreamAsync(doc)
    const [dirPath, name] = conversion.extractDirAndName(path)
    const dir = await this.remoteCozy.findOrCreateDirectoryByPath(dirPath)

    // Emit events to track the upload progress
    let info = clone(doc)
    info.way = 'up'
    info.eventName = `transfer-up-${doc._id}`
    this.events.emit('transfer-started', info)
    stream.on('data', data => {
      this.events.emit(info.eventName, data)
    })
    stream.on('finish', () => {
      this.events.emit(info.eventName, {finished: true})
    })

    const created = await this.remoteCozy.createFile(stream, {
      name,
      dirID: dir._id,
      executable: doc.executable,
      contentType: doc.mime,
      lastModifiedDate: new Date(doc.updated_at)
    })

    doc.remote = {
      _id: created._id,
      _rev: created._rev
    }

    // TODO do we use the returned values somewhere?
    return conversion.createMetadata(created)
  }

  async overwriteFileAsync (doc: Metadata, old: ?Metadata): Promise<Metadata> {
    const {path} = doc
    log.info({path}, 'Uploading new file version...')
    const stream = await this.other.createReadStreamAsync(doc)
    const options = {
      contentType: doc.mime,
      checksum: doc.md5sum,
      lastModifiedDate: new Date(doc.updated_at),
      ifMatch: ''
    }
    if (old && old.remote) {
      options.ifMatch = old.remote._rev
    }
    const updated = await this.remoteCozy.updateFileById(doc.remote._id, stream, options)

    doc.remote._rev = updated._rev

    return conversion.createMetadata(updated)
  }

  async updateFileMetadataAsync (doc: Metadata, old: any): Promise<Metadata> {
    const {path} = doc
    log.info({path}, 'Updating file metadata...')

    const attrs = {
      executable: doc.executable,
      updated_at: doc.updated_at
    }
    const opts = {
      ifMatch: old.remote._rev
    }
    const updated = await this.remoteCozy.updateAttributesById(old.remote._id, attrs, opts)

    doc.remote = {
      _id: updated._id,
      _rev: updated._rev
    }

    return conversion.createMetadata(updated)
  }

  async moveFileAsync (newMetadata: Metadata, oldMetadata: Metadata): Promise<Metadata> {
    const {path} = newMetadata
    log.info({path}, `Moving from ${oldMetadata.path} ...`)

    const [newDirPath, newName]: [string, string] = conversion.extractDirAndName(path)
    const newDir: RemoteDoc = await this.remoteCozy.findDirectoryByPath(newDirPath)

    const attrs = {
      name: newName,
      dir_id: newDir._id,
      updated_at: newMetadata.updated_at
    }
    const opts = {
      ifMatch: oldMetadata.remote._rev
    }

    const newRemoteDoc: RemoteDoc = await this.remoteCozy.updateAttributesById(oldMetadata.remote._id, attrs, opts)

    newMetadata.remote = {
      _id: newRemoteDoc._id,
      _rev: newRemoteDoc._rev
    }

    return conversion.createMetadata(newRemoteDoc)
  }

  async updateFolderAsync (doc: Metadata, old: Metadata): Promise<Metadata> {
    const {path} = doc
    if (!old.remote) {
      return this.addFolderAsync(doc)
    }
    log.info({path}, 'Updating metadata...')

    const [newParentDirPath, newName] = conversion.extractDirAndName(path)
    const newParentDir = await this.remoteCozy.findDirectoryByPath(newParentDirPath)
    let newRemoteDoc: RemoteDoc

    const attrs = {
      name: newName,
      dir_id: newParentDir._id,
      updated_at: doc.updated_at
    }
    const opts = {
      ifMatch: old.remote._rev
    }

    try {
      newRemoteDoc = await this.remoteCozy.updateAttributesById(old.remote._id, attrs, opts)
    } catch (err) {
      if (err.status !== 404) { throw err }

      log.warn({path}, "Directory doesn't exist anymore. Recreating it...")
      newRemoteDoc = await this.remoteCozy.createDirectory({
        name: newName,
        dirID: newParentDir._id,
        lastModifiedDate: doc.updated_at
      })
    }

    doc.remote = {
      _id: newRemoteDoc._id,
      _rev: newRemoteDoc._rev
    }

    return conversion.createMetadata(newRemoteDoc)
  }

  async trashAsync (doc: Metadata): Promise<void> {
    const {path} = doc
    log.info({path}, 'Moving to the trash...')
    let newRemoteDoc: RemoteDoc
    try {
      newRemoteDoc = await this.remoteCozy.trashById(doc.remote._id, {
        ifMatch: doc.remote._rev
      })
    } catch (err) {
      // FIXME: Don't complain when file/dir is already trashed/deleted?
      throw err
    }
    doc.remote._rev = newRemoteDoc._rev
  }

  async deleteFolderAsync (doc: Metadata): Promise<void> {
    await this.trashAsync(doc)
    const {path} = doc

    // FIXME: We use cozy-client-js directly instead of RemoteCozy because we
    // want the dir contents.
    // FIXME: Couldn't we reuse RemoteDoc from trashAsync()
    const folder = await this.remoteCozy.client.files.statById(doc.remote._id)
    if (folder.relations('contents').length === 0) {
      log.info({path}, 'Deleting folder from the Cozy trash...')
      // FIXME: Don't complain when user cleared the trash? (race condition)
      const opts = doc.remote._rev ? { ifMatch: doc.remote._rev } : undefined
      await this.remoteCozy.destroyById(folder._id, opts)
    } else {
      log.warn({path}, 'Folder is not empty and cannot be deleted!')
    }
  }

  moveFolderAsync (doc: Metadata, from: Metadata): Promise<*> {
    // TODO: v3: Remote#moveFolderAsync()
    throw new Error('Remote#moveFolderAsync() is not implemented')
  }

  diskUsage (): Promise<*> {
    return this.remoteCozy.diskUsage()
  }

  // TODO add tests
  async renameConflictingDocAsync (doc: Metadata, newPath: string): Promise<void> {
    const {path} = doc
    log.info({path}, `Resolve a conflict: ${path} → ${newPath}`)
    const newName = conversion.extractDirAndName(newPath)[1]
    await this.remoteCozy.updateAttributesById(doc.remote._id, {
      name: newName
    })
  }
}
<|endoftext|>


<commit_before>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "R:3jqO9zmsFuFpdn0BosPJbXpjf82PISOJXqMbwN";
var amigocloud_response = {"geocoding":{"version":"0.1","attribution":"https://search.mapzen.com/v1/attribution","query":{"text":"539 Alma St, Palo Alto, California","parsed_text":{"name":"539 Alma St","number":"539","street":"Alma St","state":"CA","regions":["Palo Alto"],"admin_parts":"Palo Alto, California"},"size":10,"private":false},"engine":{"name":"Pelias","author":"Mapzen","version":"1.0"},"timestamp":1458156768182},"type":"FeatureCollection","features":[{"type":"Feature","properties":{"id":"5e789adebdc84b9493235fe4efb2d5fa","gid":"oa:address:5e789adebdc84b9493235fe4efb2d5fa","layer":"address","source":"oa","name":"539 Alma Street","housenumber":"539","street":"Alma Street","country_a":"USA","country":"United States","region":"California","region_a":"CA","county":"Santa Clara County","locality":"Palo Alto","neighbourhood":"Downtown","confidence":0.488,"label":"539 Alma Street, Palo Alto, CA"},"geometry":{"type":"Point","coordinates":[-122.162803,37.442859]}}],"bbox":[-122.162803,37.442859,-122.162803,37.442859]};
console.log("amigo cloud response demo");
console.log(amigocloud_response);

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token, function(err, res) {

    if(err) {
        console.log("Error amigo cloud");
        console.log(err);
    }else{
        console.log("json amigo cloud response");
        console.log(res);
    }
  });

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    bingSuggestions_slice = bingSuggestions.slice(0,3);

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);
    console.log("slice ->", bingSuggestions_slice);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }

            console.log("resultado openstrep", nominatimSuggestions);
            nominatimSuggestions_slice = nominatimSuggestions.slice(0,2);
            console.log("parametro enviado",nominatimSuggestions_slice.concat(bingSuggestions_slice));
	    callback(
		null,
            nominatimSuggestions_slice.concat(bingSuggestions_slice);
	    );
	});
    }
  });

}
<commit_msg>show data response geocode search<commit_after>var config = require('config');
var log = require('./client/log')('geocode');
var get = require('./client/request').get;

var southWest = [-123.099060058594, 36.745486924699];
var northEast = [-121.192932128906, 38.182068998322];

/**********tismart **********************/
var dev_amigo_token = "R:3jqO9zmsFuFpdn0BosPJbXpjf82PISOJXqMbwN";
//var amigocloud_response = {"geocoding":{"version":"0.1","attribution":"https://search.mapzen.com/v1/attribution","query":{"text":"539 Alma St, Palo Alto, California","parsed_text":{"name":"539 Alma St","number":"539","street":"Alma St","state":"CA","regions":["Palo Alto"],"admin_parts":"Palo Alto, California"},"size":10,"private":false},"engine":{"name":"Pelias","author":"Mapzen","version":"1.0"},"timestamp":1458156768182},"type":"FeatureCollection","features":[{"type":"Feature","properties":{"id":"5e789adebdc84b9493235fe4efb2d5fa","gid":"oa:address:5e789adebdc84b9493235fe4efb2d5fa","layer":"address","source":"oa","name":"539 Alma Street","housenumber":"539","street":"Alma Street","country_a":"USA","country":"United States","region":"California","region_a":"CA","county":"Santa Clara County","locality":"Palo Alto","neighbourhood":"Downtown","confidence":0.488,"label":"539 Alma Street, Palo Alto, CA"},"geometry":{"type":"Point","coordinates":[-122.162803,37.442859]}}],"bbox":[-122.162803,37.442859,-122.162803,37.442859]};
console.log("amigo cloud response demo");
//console.log(amigocloud_response);

/**
 * Geocode
 */

module.exports = geocode;
module.exports.reverse = reverse;
module.exports.suggest = suggest;

/**
 * Geocode
 */

function geocode(address, callback) {
  log('--> geocoding %s', address);
  get('/geocode/' + address, function(err, res) {
    if (err) {
      log('<-- geocoding error %s', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Reverse geocode
 */

function reverse(ll, callback) {
  log('--> reverse geocoding %s', ll);
  get('/geocode/reverse/' + ll[0] + ',' + ll[1], function(err, res) {
    if (err) {
      log('<-- geocoding error %e', err);
      callback(err, res);
    } else {
      log('<-- geocoding complete %j', res.body);
      callback(null, res.body);
    }
  });
}

/**
 * Suggestions!
 */

function suggest(text, callback) {
  var bingSuggestions, nominatimSuggestions, totalSuggestions;
  log('--> getting suggestion for %s', text);

  get('https://www.amigocloud.com/api/v1/me/geocoder/autocomplete?text=' + text +'&token=' + dev_amigo_token, function(err, res) {

    if(err) {
        console.log("Error amigo cloud");
        console.log(err);
    }else{
        console.log("json amigo cloud response");
        console.log(res);
    }
  });

  get('/geocode/suggest/'+ text, function(err, res){

    if (err) {
      log('<-- suggestion error %s', err);
      callback(err, res);
    } else {
      log('<-- got %s suggestions', res.body.length);

	bingSuggestions = res.body;

    var bingSuggestions_slice = bingSuggestions.slice(0,3);

    console.log("------------API GEOCODE---------------");
    console.log("res ->", res.body);
    console.log("res.body ->", res);
    console.log("slice ->", bingSuggestions_slice);

//      callback(null, res.body);
	get('http://nominatim.openstreetmap.org/search' +
	    '?format=json&addressdetails=1&' +
	    'viewbox=' + southWest[0] + ',' +
	    northEast[1] + ',' + northEast[0] + ',' + southWest[1] +
	    '&bounded=1' +
	    'countrycodes=us&q=' + text, function (err, nRes) {
		var inside = false;
	    nominatimSuggestions = [];
            for (var i = 0; i < nRes.body.length; i++) {
//		inside = inside && (nRes.body[i].lng > southWest[0]);
//		inside = inside && (nRes.body[i].lng < northEast[0]);
//		inside = inside && (nRes.body[i].lat > southWest[1]);
//		inside = inside && (nRes.body[i].lat < northEast[1]);
//		if (inside) {
                    nominatimSuggestions.push(nRes.body[i]);
//		}
            }

            console.log("resultado openstrep", nominatimSuggestions);
            var nominatimSuggestions_slice = nominatimSuggestions.slice(0,2);
            console.log("parametro enviado",nominatimSuggestions_slice.concat(bingSuggestions_slice));
	    callback(
		null,
            nominatimSuggestions_slice.concat(bingSuggestions_slice);
	    );
	});
    }
  });

}
<|endoftext|>


<commit_before>/*globals qq */
qq.azure = qq.azure || {};
qq.azure.util = qq.azure.util || (function() {
    "use strict";

    return {
        AZURE_PARAM_PREFIX: "x-ms-meta-",

        /** Create Prefixed request headers which are appropriate for Azure.
         *
         * If the request header is appropriate for Azure (e.g. Cache-Control) then pass
         * it along without a metadata prefix. For all other request header parameter names,
         * apply qq.azure.util.AZURE_PARAM_PREFIX before the name.
         *
         * @param name Name of the Request Header parameter to construct a (possibly) prefixed name.
         * @returns {String} A valid Request Header parameter name.
         */
        _paramNameMatchesAzureParameter: function(name) {
            switch (name)
            {
                //
                // Valid request headers (not sent by fine-uploader) which should be returned as-is (case-sensitive)
                // see: https://msdn.microsoft.com/en-us/library/azure/dd179451.aspx
                //
                case "Cache-Control":
                case "Content-Disposition":
                case "Content-Encoding":
                case "Content-MD5":
                case "x-ms-blob-content-encoding":
                case "x-ms-blob-content-disposition":
                case "x-ms-blob-content-md5":
                case "x-ms-blob-cache-control":
                    return true;
                default:
                    return false;
            }
        },

        _getPrefixedParamName: function (name) {
            if (qq.azure.util._paramNameMatchesAzureParameter(name)) {
                return name;
            }
            else {
                return qq.azure.util.AZURE_PARAM_PREFIX + name;
            }
        },

        getParamsAsHeaders: function(params) {
            var headers = {};

            qq.each(params, function(name, val) {
                var headerName = qq.azure.util._getPrefixedParamName(name);

                if (qq.isFunction(val)) {
                    headers[headerName] = encodeURIComponent(String(val()));
                }
                else if (qq.isObject(val)) {
                    qq.extend(headers, qq.azure.util.getParamsAsHeaders(val));
                }
                else if (qq.azure.util._paramNameMatchesAzureParameter(name)) {
                    headers[headerName] = val;
                }
                else {
                    headers[headerName] = encodeURIComponent(String(val));
                }
            });

            return headers;
        },

        parseAzureError: function(responseText, log) {
            var domParser = new DOMParser(),
                responseDoc = domParser.parseFromString(responseText, "application/xml"),
                errorTag = responseDoc.getElementsByTagName("Error")[0],
                errorDetails = {},
                codeTag, messageTag;

            log("Received error response: " + responseText, "error");

            if (errorTag) {
                messageTag = errorTag.getElementsByTagName("Message")[0];
                if (messageTag) {
                    errorDetails.message = messageTag.textContent;
                }

                codeTag = errorTag.getElementsByTagName("Code")[0];
                if (codeTag) {
                    errorDetails.code = codeTag.textContent;
                }

                log("Parsed Azure error: " + JSON.stringify(errorDetails), "error");

                return errorDetails;
            }
        }
    };
}());
<commit_msg>Fixed another 2 jslint errors<commit_after>/*globals qq */
qq.azure = qq.azure || {};
qq.azure.util = qq.azure.util || (function() {
    "use strict";

    return {
        AZURE_PARAM_PREFIX: "x-ms-meta-",

        /** Create Prefixed request headers which are appropriate for Azure.
         *
         * If the request header is appropriate for Azure (e.g. Cache-Control) then pass
         * it along without a metadata prefix. For all other request header parameter names,
         * apply qq.azure.util.AZURE_PARAM_PREFIX before the name.
         *
         * @param name Name of the Request Header parameter to construct a (possibly) prefixed name.
         * @returns {String} A valid Request Header parameter name.
         */
        _paramNameMatchesAzureParameter: function(name) {
            switch (name)
            {
                //
                // Valid request headers (not sent by fine-uploader) which should be returned as-is (case-sensitive)
                // see: https://msdn.microsoft.com/en-us/library/azure/dd179451.aspx
                //
                case "Cache-Control":
                case "Content-Disposition":
                case "Content-Encoding":
                case "Content-MD5":
                case "x-ms-blob-content-encoding":
                case "x-ms-blob-content-disposition":
                case "x-ms-blob-content-md5":
                case "x-ms-blob-cache-control":
                    return true;
                default:
                    return false;
            }
        },

        _getPrefixedParamName: function(name) {
            if (qq.azure.util._paramNameMatchesAzureParameter(name)) {
                return name;
            }
            else {
                return qq.azure.util.AZURE_PARAM_PREFIX + name;
            }
        },

        getParamsAsHeaders: function(params) {
            var headers = {};

            qq.each(params, function(name, val) {
                var headerName = qq.azure.util._getPrefixedParamName(name);

                if (qq.isFunction(val)) {
                    headers[headerName] = encodeURIComponent(String(val()));
                }
                else if (qq.isObject(val)) {
                    qq.extend(headers, qq.azure.util.getParamsAsHeaders(val));
                }
                else if (qq.azure.util._paramNameMatchesAzureParameter(name)) {
                    headers[headerName] = val;
                }
                else {
                    headers[headerName] = encodeURIComponent(String(val));
                }
            });

            return headers;
        },

        parseAzureError: function(responseText, log) {
            var domParser = new DOMParser(),
                responseDoc = domParser.parseFromString(responseText, "application/xml"),
                errorTag = responseDoc.getElementsByTagName("Error")[0],
                errorDetails = {},
                codeTag, messageTag;

            log("Received error response: " + responseText, "error");

            if (errorTag) {
                messageTag = errorTag.getElementsByTagName("Message")[0];
                if (messageTag) {
                    errorDetails.message = messageTag.textContent;
                }

                codeTag = errorTag.getElementsByTagName("Code")[0];
                if (codeTag) {
                    errorDetails.code = codeTag.textContent;
                }

                log("Parsed Azure error: " + JSON.stringify(errorDetails), "error");

                return errorDetails;
            }
        }
    };
}());
<|endoftext|>


<commit_before>import { HashRouter as Router, Route, Switch, Redirect } from 'react-router-dom';
import React from 'react';
import Signin from '../js/components/authentication/Signin';
import NavBar from './components/common/NavBar';
import Signup from './components/authentication/Signup';
import UserPage from '../js/components/user/UserPage';

// user PageAccessHelper here on UserPage and remove from other components
export default (
  <Router >
    <Switch>

        <NavBar />
        <Route exact path="/signup" component={Signup} />
        <Route exact path="/signin" component={Signin} />
        <UserPage />
        <Redirect from="*" to="/signin" />

    </Switch>
  </Router>
);
<commit_msg>bug(eslint):fix eslint line exceed maximum character<commit_after>import { HashRouter as Router, Route, Switch, Redirect }
  from 'react-router-dom';
import React from 'react';
import Signin from '../js/components/authentication/Signin';
import NavBar from './components/common/NavBar';
import Signup from './components/authentication/Signup';
import UserPage from '../js/components/user/UserPage';

// user PageAccessHelper here on UserPage and remove from other components
export default (
  <Router >
    <Switch>

        <NavBar />
        <Route exact path="/signup" component={Signup} />
        <Route exact path="/signin" component={Signin} />
        <UserPage />
        <Redirect from="*" to="/signin" />

    </Switch>
  </Router>
);
<|endoftext|>


<commit_before><commit_msg>Fix warn message<commit_after><|endoftext|>


<commit_before><commit_msg>Added suggestions method<commit_after><|endoftext|>


<commit_before>/*
 The MIT License (MIT)

 Copyright ( c ) 2014-2015 Teem2 LLC

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/
'use strict';

/*
  TODO: Get the client to autoreload when the cache is cleared?
*/

var fs = require('fs');
var path = require('path');
var watch = require('watch');

var coffee = require('coffee-script');
var uglify = require("uglify-js");

var PROCESSORS_BY_EXTENSION = {
  coffee:["coffee"]
};

var cache;
var clearCache = function() {
  //console.log('CLEAR CACHE');
  cache = {};
}

var readFile = function(filePath, callback, context) {
  var rootPaths = context.rootPaths,
    srcSubDir = context.srcSubDir,
    i = 0, len = rootPaths.length;
  var readRecursivelyOverRoots = function(err, data) {
    if (err) {
      if (len > i) {
        var rootPath = rootPaths[i++],
          normalizedPath = path.normalize(rootPath + filePath);
        if (normalizedPath.indexOf(rootPath + srcSubDir) === 0) {
          fs.readFile(normalizedPath, {encoding: 'utf-8'}, readRecursivelyOverRoots);
        } else {
          callback(false, "SECURITY CHECK: Path resolved outside supported dir:" + normalizedPath);
        }
      } else {
        callback(false, "No file found for path:" + filePath);
      }
    } else {
      callback(true, data);
    }
  };
  readRecursivelyOverRoots(true);
};

var tokenize = function(text, tokens, context) {
  var c, token,
    i = 0, len = text.length,
    insideDecl = false,
    mightBeDeclEnd = false,
    wasTilde = false;
  for (; len > i; ++i) {
    c = text.charAt(i);
    switch (c) {
      case '~':
        if (insideDecl) {
          if (mightBeDeclEnd) {
            insideDecl = false;
            mightBeDeclEnd = false;
            token = null;
          } else {
            token.value.push(c);
          }
        } else {
          if (wasTilde) {
            if (!token) tokens.push(token = {type:'raw', value:[]});
            token.value.push(c);
            wasTilde = false;
          } else {
            wasTilde = true;
          }
        }
        break;

      case '[':
        if (!insideDecl && wasTilde) {
          insideDecl = true;
          tokens.push(token = {type:'decl', value:[]});
        }
        if (!token) tokens.push(token = {type:'raw', value:[]});
        token.value.push(c);
        wasTilde = false;
        break;

      case ']':
        if (wasTilde && !insideDecl) token.value.push('~');
        if (insideDecl) mightBeDeclEnd = true;
        if (!token) tokens.push(token = {type:'raw', value:[]});
        token.value.push(c);
        wasTilde = false;
        break;

      default:
        if (!token) tokens.push(token = {type:'raw', value:[]});
        if (wasTilde) token.value.push('~');
        token.value.push(c);
        wasTilde = false;
    }
  }
};

var processFile = function(filePath, tokenTreeNode, fileStack, context) {
  filePath = path.normalize(filePath);

  // Prevent cyclic includes
  var i = fileStack.length;
  while (i) {
    if (fileStack[--i] === filePath) {
      console.log('WARNING: Prevent cyclic include for: ' + filePath);
      return;
    }
  }
  fileStack.push(filePath);
  context.filesToProcessCount++;

  readFile(filePath, function(success, result) {
    try {
      if (success) {
        tokenize(result, tokenTreeNode.value, context);

        var tokens = tokenTreeNode.value,
          token, i = 0, len = tokens.length;

        // Assemble parse tree
        for (; len > i;) {
          token = tokens[i++];
          token.value = token.value.join('');
          if (token.type === 'decl') {
            try {
              token.value = JSON.parse(token.value);
              token.action = token.value.shift();

              // Process files recursively for includes
              if (token.action === 'include') {
                var relativePath = token.path = token.value.shift(),
                  idx = filePath.lastIndexOf('/');
                processFile(
                  (idx > 0 ? filePath.substring(0, idx + 1) : filePath) + relativePath, // Combine current path with relative path.
                  token,
                  fileStack.concat(), // Make a copy since file processing happens in parallel at each include level.
                  context
                );
              }
            } catch (e) {
              token.type = 'error';
              token.value = 'Declaration parse exception: ' + e;
            }
          }
        }

        // Insert processor tokens by extension
        var extIdx = filePath.lastIndexOf('.');
        if (extIdx >= 0) {
          var processors = PROCESSORS_BY_EXTENSION[filePath.substring(extIdx + 1)];
          if (processors) {
            tokens.unshift({type:'decl', action:'startprocess', value:processors});
            tokens.push({type:'decl', action:'endprocess', value:processors});
          }
        }
      } else {
        console.log('ERROR:', result);
      }
    } catch (e) {
      console.log('UNEXPECTED ERROR:', e);
    } finally {
      // We're done if there are no more files to process.
      if (--context.filesToProcessCount === 0) context.doneFunc();
    }
  }, context);
};

var processTokenTree = function(tokens, context) {
  var conditionalState = [{conditionIsTrue:true}], token;
  for (var i = 0, len = tokens.length; len > i; i++) {
    token = tokens[i];
    if (token.type === 'raw') {
      if (conditionalState[0].conditionIsTrue) context.outStack[0].push(token.value);
    } else if (token.type === 'decl') {
      switch (token.action) {
        case 'include':
          if (conditionalState[0].conditionIsTrue) processTokenTree(token.value, context);
          break;

        case 'if':
          if ((conditionalState.length <= 2) || conditionalState[1].conditionIsTrue) {
            conditionalState.unshift({});
            conditionalState[0].everTrue = conditionalState[0].conditionIsTrue = evaluateConditional(token.value, context);
          }
          break;
        case 'elseif':
          if ((conditionalState.length <= 2) || conditionalState[1].conditionIsTrue) {
            if (conditionalState[0].everTrue) {
              conditionalState[0].conditionIsTrue = false;
            } else {
              conditionalState[0].everTrue = conditionalState[0].conditionIsTrue = evaluateConditional(token.value, context);
            }
          }
          break;
        case 'else':
          if ((conditionalState.length <= 2) || conditionalState[1].conditionIsTrue) {
            conditionalState[0].conditionIsTrue = !conditionalState[0].everTrue;
          }
          break;
        case 'endif':
          conditionalState.shift();
          break;

        case 'startprocess':
          context.outStack.unshift([]);
          break;
        case 'endprocess':
          var processBody = context.outStack.shift().join(''),
            processors = token.value, j = 0, jLen = processors.length;
          for (; jLen > j;) processBody = doProcessDeclaration(processBody, processors[j++], context);
          context.outStack[0].push(processBody)
          break;

        default:
          console.log('Unknown Declaration: ', token.action, token.value);
      }
    } else if (token.type === 'error') {
      console.log(token.value);
    }
  }
};

var doProcessDeclaration = function(processBody, processName, context) {
  try {
    switch (processName) {
      case 'coffee':
        processBody = coffee.compile(processBody);
        break;
      case 'minify':
        processBody = uglify.minify(processBody, {fromString:true}).code;
        break;
      default:
        console.log('Unknown processor encountered: ' + processName);
    }
  } catch (e) {
    processBody = 'Process Error: ' + processName + " : " + e;
  }
  return processBody;
};

var evaluateConditional = function(value, context) {
  switch (value[0]) {
    case 'runtime':
      return context.req.query && context.req.query.runtime === value[1];
    case 'debug':
      return context.req.query && context.req.query.debug === value[1];
    default:
      return false;
  }
};

module.exports = function (projectsRoot, dreemRoot, srcSubDir) {
  var rootPaths = [];
  if (projectsRoot) rootPaths.push(projectsRoot); // Allow project to override dreem so push it on first.
  if (dreemRoot) rootPaths.push(dreemRoot);

  // Setup file watching. Will also call clearCache for us at least
  // once per root path.
  for (var i = 0, len = rootPaths.length; len > i; i++) {
    var path = rootPaths[i] + srcSubDir;
    console.log('The assembler started watching: ' + path + ' for changes.');
    watch.watchTree(path, function(f, curr, prev) {clearCache();});
  }

  return function(req, res, next) {
    // Clear cache if so indicated
    var query = query = req.query;
    if (query.cache === 'clear') clearCache();

    var filePath = req.path,
      cacheKey = req.originalUrl,
      cachedResponse = cache[cacheKey],
      context,
      tokenTree = {type:'root', value:[]},
      doneFunc = function() {
        processTokenTree(tokenTree.value, context);

        res.writeHead(200, {'Content-Type':'application/json'});
        if (cachedResponse) {
          //console.log('FROM CACHE');
          res.end(cachedResponse);
        } else {
          //console.log('BUILDING');
          res.end(cache[cacheKey] = context.outStack[0].join(''));
        }
      };

    if (cachedResponse) {
      doneFunc();
    } else {
      context = {
        rootPaths:rootPaths,
        srcSubDir:srcSubDir,
        req:req,
        outStack:[[]],
        filesToProcessCount:0,
        doneFunc: doneFunc
      };
      processFile(filePath, tokenTree, [], context);
    }
  }
}
<commit_msg>Added support for "actions". In particular a writefile action since doc generation needs to work off a file on disk.<commit_after>/*
 The MIT License (MIT)

 Copyright ( c ) 2014-2015 Teem2 LLC

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/
'use strict';

/*
  TODO: Get the client to autoreload when the cache is cleared?
*/

var fs = require('fs');
var path = require('path');
var watch = require('watch');

var coffee = require('coffee-script');
var uglify = require("uglify-js");

var PROCESSORS_BY_EXTENSION = {
  coffee:["coffee"]
};

var cache;
var clearCache = function() {
  //console.log('CLEAR CACHE');
  cache = {};
}

var readFile = function(filePath, callback, context) {
  var rootPaths = context.rootPaths,
    srcSubDir = context.srcSubDir,
    i = 0, len = rootPaths.length;
  var readRecursivelyOverRoots = function(err, data) {
    if (err) {
      if (len > i) {
        // SECURITY: Make sure we don't read outside a rootPath.
        var rootPath = rootPaths[i++],
          normalizedPath = path.normalize(rootPath + filePath);
        if (normalizedPath.indexOf(rootPath + srcSubDir) === 0) {
          fs.readFile(normalizedPath, {encoding: 'utf-8'}, readRecursivelyOverRoots);
        } else {
          callback(false, "Path resolved outside supported dir:" + normalizedPath);
        }
      } else {
        callback(false, "No file found for path:" + filePath);
      }
    } else {
      callback(true, data);
    }
  };
  readRecursivelyOverRoots(true);
};

var tokenize = function(text, tokens, context) {
  var c, token,
    i = 0, len = text.length,
    insideDecl = false,
    mightBeDeclEnd = false,
    wasTilde = false;
  for (; len > i; ++i) {
    c = text.charAt(i);
    switch (c) {
      case '~':
        if (insideDecl) {
          if (mightBeDeclEnd) {
            insideDecl = false;
            mightBeDeclEnd = false;
            token = null;
          } else {
            token.value.push(c);
          }
        } else {
          if (wasTilde) {
            if (!token) tokens.push(token = {type:'raw', value:[]});
            token.value.push(c);
            wasTilde = false;
          } else {
            wasTilde = true;
          }
        }
        break;

      case '[':
        if (!insideDecl && wasTilde) {
          insideDecl = true;
          tokens.push(token = {type:'decl', value:[]});
        }
        if (!token) tokens.push(token = {type:'raw', value:[]});
        token.value.push(c);
        wasTilde = false;
        break;

      case ']':
        if (wasTilde && !insideDecl) token.value.push('~');
        if (insideDecl) mightBeDeclEnd = true;
        if (!token) tokens.push(token = {type:'raw', value:[]});
        token.value.push(c);
        wasTilde = false;
        break;

      default:
        if (!token) tokens.push(token = {type:'raw', value:[]});
        if (wasTilde) token.value.push('~');
        token.value.push(c);
        wasTilde = false;
    }
  }
};

var processFile = function(filePath, tokenTreeNode, fileStack, context) {
  filePath = path.normalize(filePath);

  // Prevent cyclic includes
  var i = fileStack.length;
  while (i) {
    if (fileStack[--i] === filePath) {
      console.log('WARNING: Prevent cyclic include for: ' + filePath);
      return;
    }
  }
  fileStack.push(filePath);
  context.filesToProcessCount++;

  readFile(filePath, function(success, result) {
    try {
      if (success) {
        tokenize(result, tokenTreeNode.value, context);

        var tokens = tokenTreeNode.value,
          token, i = 0, len = tokens.length;

        // Assemble parse tree
        for (; len > i;) {
          token = tokens[i++];
          token.value = token.value.join('');
          if (token.type === 'decl') {
            try {
              token.value = JSON.parse(token.value);
              token.action = token.value.shift();
              token.file = filePath;

              // Process files recursively for includes
              if (token.action === 'include') {
                var relativePath = token.path = token.value.shift(),
                  idx = filePath.lastIndexOf('/');
                processFile(
                  (idx > 0 ? filePath.substring(0, idx + 1) : filePath) + relativePath, // Combine current path with relative path.
                  token,
                  fileStack.concat(), // Make a copy since file processing happens in parallel at each include level.
                  context
                );
              }
            } catch (e) {
              token.type = 'error';
              token.value = 'Declaration parse exception: ' + e;
            }
          }
        }

        // Insert processor tokens by extension
        var extIdx = filePath.lastIndexOf('.');
        if (extIdx >= 0) {
          var processors = PROCESSORS_BY_EXTENSION[filePath.substring(extIdx + 1)];
          if (processors) {
            tokens.unshift({type:'decl', action:'startprocess', value:processors});
            tokens.push({type:'decl', action:'endprocess', value:processors});
          }
        }
      } else {
        console.log('ERROR:', result);
      }
    } catch (e) {
      console.log('UNEXPECTED ERROR:', e);
    } finally {
      // We're done if there are no more files to process.
      if (--context.filesToProcessCount === 0) context.doneFunc();
    }
  }, context);
};

var processTokenTree = function(tokens, context) {
  var conditionalState = [{conditionIsTrue:true}], token;
  for (var i = 0, len = tokens.length; len > i; i++) {
    token = tokens[i];
    if (token.type === 'raw') {
      if (conditionalState[0].conditionIsTrue) context.outStack[0].push(token.value);
    } else if (token.type === 'decl') {
      switch (token.action) {
        case 'include':
          if (conditionalState[0].conditionIsTrue) processTokenTree(token.value, context);
          break;

        case 'if':
          if ((conditionalState.length <= 2) || conditionalState[1].conditionIsTrue) {
            conditionalState.unshift({});
            conditionalState[0].everTrue = conditionalState[0].conditionIsTrue = evaluateConditional(token.value, context);
          }
          break;
        case 'elseif':
          if ((conditionalState.length <= 2) || conditionalState[1].conditionIsTrue) {
            if (conditionalState[0].everTrue) {
              conditionalState[0].conditionIsTrue = false;
            } else {
              conditionalState[0].everTrue = conditionalState[0].conditionIsTrue = evaluateConditional(token.value, context);
            }
          }
          break;
        case 'else':
          if ((conditionalState.length <= 2) || conditionalState[1].conditionIsTrue) {
            conditionalState[0].conditionIsTrue = !conditionalState[0].everTrue;
          }
          break;
        case 'endif':
          conditionalState.shift();
          break;

        case 'startprocess':
          context.outStack.unshift([]);
          break;
        case 'endprocess':
          var processBody = context.outStack.shift().join(''),
            processors = token.value, j = 0, jLen = processors.length;
          for (; jLen > j;) processBody = doProcessDeclaration(processBody, processors[j++], context);
          context.outStack[0].push(processBody)
          break;

        case 'action':
          doActionDeclaration(token.value.shift(), token, context);
          break;

        default:
          console.log('Unknown Declaration: ', token.action, token.value);
      }
    } else if (token.type === 'error') {
      console.log(token.value);
    }
  }
};

var doActionDeclaration = function(actionName, token, context) {
  var params = token.value;

  switch (actionName) {
    case 'writefile':
      var data = context.outStack[0].join(''),
        rootPaths = context.rootPaths,
        filePath = token.file,
        idx = filePath.lastIndexOf('/'),
        filePath = path.normalize(rootPaths[0] + (idx > 0 ? filePath.substring(0, idx + 1) : filePath) + params[0]);

      idx = filePath.lastIndexOf('/');
      var dirPath = filePath.substring(0, idx);

      // SECURITY: Make sure we don't write outside a rootPath.
      var i = rootPaths.length, isOk = false;
      while (i) {
        if (filePath.indexOf(rootPaths[--i] + context.srcSubDir) === 0) {
          isOk = true;
        }
      }
      if (!isOk) {
        console.log("Can't write file to disk. Unsafe path: " + filePath);
        break;
      }

      var writeFileFunc = function() {
          fs.writeFile(filePath, data, function(err) {
            if (err) {
              console.log('Error writing file to disk:', filePath, err);
            } else {
              console.log('Wrote to disk: ' + data.length + ' characters into file ', filePath);
            }
          });
      };

      fs.exists(dirPath, function (exists) {
        if (exists) {
          writeFileFunc();
        } else {
          fs.mkdir(dirPath, function(err) {
            if (err) {
              console.log('Error writing file to disk. Could not mkdir:', dirPath, err);
            } else {
              writeFileFunc();
            }
          });
        }
      });

      break;
    default:
      console.log('Unknown Action: ', actionName);
  }
};

var doProcessDeclaration = function(processBody, processName, context) {
  try {
    switch (processName) {
      case 'coffee':
        processBody = coffee.compile(processBody);
        break;
      case 'minify':
        processBody = uglify.minify(processBody, {fromString:true}).code;
        break;
      default:
        console.log('Unknown processor encountered: ' + processName);
    }
  } catch (e) {
    processBody = 'Process Error: ' + processName + " : " + e;
  }
  return processBody;
};

var evaluateConditional = function(value, context) {
  switch (value[0]) {
    case 'runtime':
      return context.req.query && context.req.query.runtime === value[1];
    case 'debug':
      return context.req.query && context.req.query.debug === value[1];
    default:
      return false;
  }
};

module.exports = function (projectsRoot, dreemRoot, srcSubDir) {
  var rootPaths = [];
  if (projectsRoot) rootPaths.push(projectsRoot); // Allow project to override dreem so push it on first.
  if (dreemRoot) rootPaths.push(dreemRoot);

  // Setup file watching. Will also call clearCache for us at least
  // once per root path.
  for (var i = 0, len = rootPaths.length; len > i; i++) {
    var path = rootPaths[i] + srcSubDir;
    console.log('The assembler started watching: ' + path + ' for changes.');
    watch.watchTree(path, function(f, curr, prev) {clearCache();});
  }

  return function(req, res, next) {
    // Clear cache if so indicated
    var query = query = req.query;
    if (query.cache === 'clear') clearCache();

    var filePath = req.path,
      cacheKey = req.originalUrl,
      cachedResponse = cache[cacheKey],
      context,
      tokenTree = {type:'root', value:[]},
      doneFunc = function() {
        processTokenTree(tokenTree.value, context);

        res.writeHead(200, {'Content-Type':'application/json'});
        if (cachedResponse) {
          //console.log('FROM CACHE');
          res.end(cachedResponse);
        } else {
          //console.log('BUILDING');
          res.end(cache[cacheKey] = context.outStack[0].join(''));
        }
      };

    if (cachedResponse) {
      doneFunc();
    } else {
      context = {
        rootPaths:rootPaths,
        srcSubDir:srcSubDir,
        req:req,
        outStack:[[]],
        filesToProcessCount:0,
        doneFunc: doneFunc
      };
      processFile(filePath, tokenTree, [], context);
    }
  }
}
<|endoftext|>


<commit_before>import $ from 'jquery';
import Ember from 'ember';
import EmberError from '@ember/error';
import Service, {inject as service} from '@ember/service';
import {computed} from '@ember/object';
import {set} from '@ember/object';

export function feature(name, options = {}) {
    let {user, onChange} = options;
    let watchedProps = user ? [`accessibility.${name}`] : [`config.${name}`, `labs.${name}`];

    return computed.apply(Ember, watchedProps.concat({
        get() {
            let enabled = false;

            if (user) {
                enabled = this.get(`accessibility.${name}`);
            } else if (this.get(`config.${name}`)) {
                enabled = this.get(`config.${name}`);
            } else {
                enabled = this.get(`labs.${name}`) || false;
            }

            if (options.developer) {
                enabled = enabled && this.get('config.enableDeveloperExperiments');
            }

            return enabled;
        },
        set(key, value) {
            this.update(key, value, options);

            if (onChange) {
                // value must be passed here because the value isn't set until
                // the setter function returns
                this.get(onChange).bind(this)(value);
            }

            return value;
        }
    }));
}

export default Service.extend({
    store: service(),
    config: service(),
    session: service(),
    settings: service(),
    notifications: service(),
    lazyLoader: service(),

    emailAnalytics: feature('emailAnalytics'),
    nightShift: feature('nightShift', {user: true, onChange: '_setAdminTheme'}),
    multipleProducts: feature('multipleProducts'),
    oauthLogin: feature('oauthLogin', {developer: true}),
    customThemeSettings: feature('customThemeSettings'),
    membersActivity: feature('membersActivity', {developer: true}),
    cardSettingsPanel: feature('cardSettingsPanel', {developer: true}),
    membersAutoLogin: feature('membersAutoLogin', {developer: true}),
    urlCache: feature('urlCache', {developer: true}),
    mediaAPI: feature('mediaAPI', {developer: true}),
    filesAPI: feature('filesAPI', {developer: true}),
    calloutCard: feature('calloutCard', {developer: true}),
    nftCard: feature('nftCard'),
    accordionCard: feature('accordionCard', {developer: true}),
    fileCard: feature('fileCard', {developer: true}),
    audioCard: feature('audioCard', {developer: true}),
    videoCard: feature('videoCard', {developer: true}),
    productCard: feature('productCard', {developer: true}),
    quoteStyles: feature('quoteStyles', {developer: true}),

    _user: null,

    labs: computed('settings.labs', function () {
        let labs = this.get('settings.labs');

        try {
            return JSON.parse(labs) || {};
        } catch (e) {
            return {};
        }
    }),

    accessibility: computed('_user.accessibility', function () {
        let accessibility = this.get('_user.accessibility');

        try {
            return JSON.parse(accessibility) || {};
        } catch (e) {
            return {};
        }
    }),

    fetch() {
        return this.settings.fetch().then(() => {
            this.set('_user', this.session.user);
            return this._setAdminTheme().then(() => true);
        });
    },

    update(key, value, options = {}) {
        let serviceProperty = options.user ? 'accessibility' : 'labs';
        let model = this.get(options.user ? '_user' : 'settings');
        let featureObject = this.get(serviceProperty);

        // set the new key value for either the labs property or the accessibility property
        set(featureObject, key, value);

        if (options.requires && value === true) {
            options.requires.forEach((flag) => {
                set(featureObject, flag, true);
            });
        }

        // update the 'labs' or 'accessibility' key of the model
        model.set(serviceProperty, JSON.stringify(featureObject));

        return model.save().then(() => {
            // return the labs key value that we get from the server
            this.notifyPropertyChange(serviceProperty);
            return this.get(`${serviceProperty}.${key}`);
        }).catch((error) => {
            model.rollbackAttributes();
            this.notifyPropertyChange(serviceProperty);

            // we'll always have an errors object unless we hit a
            // validation error
            if (!error) {
                throw new EmberError(`Validation of the feature service ${options.user ? 'user' : 'settings'} model failed when updating ${serviceProperty}.`);
            }

            this.notifications.showAPIError(error);

            return this.get(`${serviceProperty}.${key}`);
        });
    },

    _setAdminTheme(enabled) {
        let nightShift = enabled;

        if (typeof nightShift === 'undefined') {
            nightShift = enabled || this.nightShift;
        }

        return this.lazyLoader.loadStyle('dark', 'assets/ghost-dark.css', true).then(() => {
            $('link[title=dark]').prop('disabled', !nightShift);
        }).catch(() => {
            //TODO: Also disable toggle from settings and Labs hover
            $('link[title=dark]').prop('disabled', true);
        });
    }
});
<commit_msg>Removed development option from feature helper (#2164)<commit_after>import $ from 'jquery';
import Ember from 'ember';
import EmberError from '@ember/error';
import Service, {inject as service} from '@ember/service';
import {computed} from '@ember/object';
import {set} from '@ember/object';

export function feature(name, options = {}) {
    let {user, onChange} = options;
    let watchedProps = user ? [`accessibility.${name}`] : [`config.${name}`, `labs.${name}`];

    return computed.apply(Ember, watchedProps.concat({
        get() {
            let enabled = false;

            if (user) {
                enabled = this.get(`accessibility.${name}`);
            } else if (this.get(`config.${name}`)) {
                enabled = this.get(`config.${name}`);
            } else {
                enabled = this.get(`labs.${name}`) || false;
            }

            return enabled;
        },
        set(key, value) {
            this.update(key, value, options);

            if (onChange) {
                // value must be passed here because the value isn't set until
                // the setter function returns
                this.get(onChange).bind(this)(value);
            }

            return value;
        }
    }));
}

export default Service.extend({
    store: service(),
    config: service(),
    session: service(),
    settings: service(),
    notifications: service(),
    lazyLoader: service(),

    emailAnalytics: feature('emailAnalytics'),
    nightShift: feature('nightShift', {user: true, onChange: '_setAdminTheme'}),
    multipleProducts: feature('multipleProducts'),
    oauthLogin: feature('oauthLogin'),
    customThemeSettings: feature('customThemeSettings'),
    membersActivity: feature('membersActivity'),
    cardSettingsPanel: feature('cardSettingsPanel'),
    membersAutoLogin: feature('membersAutoLogin'),
    urlCache: feature('urlCache'),
    mediaAPI: feature('mediaAPI'),
    filesAPI: feature('filesAPI'),
    calloutCard: feature('calloutCard'),
    nftCard: feature('nftCard'),
    accordionCard: feature('accordionCard'),
    fileCard: feature('fileCard'),
    audioCard: feature('audioCard'),
    videoCard: feature('videoCard'),
    productCard: feature('productCard'),
    quoteStyles: feature('quoteStyles'),

    _user: null,

    labs: computed('settings.labs', function () {
        let labs = this.get('settings.labs');

        try {
            return JSON.parse(labs) || {};
        } catch (e) {
            return {};
        }
    }),

    accessibility: computed('_user.accessibility', function () {
        let accessibility = this.get('_user.accessibility');

        try {
            return JSON.parse(accessibility) || {};
        } catch (e) {
            return {};
        }
    }),

    fetch() {
        return this.settings.fetch().then(() => {
            this.set('_user', this.session.user);
            return this._setAdminTheme().then(() => true);
        });
    },

    update(key, value, options = {}) {
        let serviceProperty = options.user ? 'accessibility' : 'labs';
        let model = this.get(options.user ? '_user' : 'settings');
        let featureObject = this.get(serviceProperty);

        // set the new key value for either the labs property or the accessibility property
        set(featureObject, key, value);

        if (options.requires && value === true) {
            options.requires.forEach((flag) => {
                set(featureObject, flag, true);
            });
        }

        // update the 'labs' or 'accessibility' key of the model
        model.set(serviceProperty, JSON.stringify(featureObject));

        return model.save().then(() => {
            // return the labs key value that we get from the server
            this.notifyPropertyChange(serviceProperty);
            return this.get(`${serviceProperty}.${key}`);
        }).catch((error) => {
            model.rollbackAttributes();
            this.notifyPropertyChange(serviceProperty);

            // we'll always have an errors object unless we hit a
            // validation error
            if (!error) {
                throw new EmberError(`Validation of the feature service ${options.user ? 'user' : 'settings'} model failed when updating ${serviceProperty}.`);
            }

            this.notifications.showAPIError(error);

            return this.get(`${serviceProperty}.${key}`);
        });
    },

    _setAdminTheme(enabled) {
        let nightShift = enabled;

        if (typeof nightShift === 'undefined') {
            nightShift = enabled || this.nightShift;
        }

        return this.lazyLoader.loadStyle('dark', 'assets/ghost-dark.css', true).then(() => {
            $('link[title=dark]').prop('disabled', !nightShift);
        }).catch(() => {
            //TODO: Also disable toggle from settings and Labs hover
            $('link[title=dark]').prop('disabled', true);
        });
    }
});
<|endoftext|>


<commit_before>/**
 * New node file
 */
var Product = require('../app/models/product');

//GET
//'/category/:categoryId/product/'
exports.getAllProduct = function(req, res){
	var categoryId = req.param('categoryId');

	Product.find({'categoryId': categoryId}, function(err, products){
		if(err) {
			res.status(500).json({status:'failure'});
			console.log("Get all products error! Category Id: " + categoryId);
		}
		else if(products === null) {
			res.send("could not find any product from category Id: " + categoryId);
			console.log("could not find any product from category Id: " + categoryId);
		}
		else {
			var productlist = [];

			products.forEach(function(product) {
				console.log(product);
				productlist.push(product);
			});

			res.status(200).json( {
				products : productlist
			});
		}
	});
};

//Post
//'/category/:categoryId/product/'
exports.addProduct = function(req, res){
	var newProduct = new Product();
	Product.count({ productId:{$exists: true} },
			function (err, count){
				newProduct.productId 		 = count + 1;
				newProduct.productName 		 = req.param('productName');
				newProduct.quantity 		 = req.param('quantity');
				newProduct.userId 			 = req.param('userId');
				newProduct.expectedOffer 	 = req.param('expectedOffer');
				newProduct.productDesc	 	 = req.param('productDesc');
				newProduct.productExpiryDate = req.param('productExpiryDate');
				newProduct.isValid 			 = req.param('isValid');
				newProduct.categoryId 		 = req.param('categoryId');
				newProduct.lastUpdated 		 = req.param('lastUpdated');

				newProduct.save(function(err){
					if(err){
						res.status(500).json({status:'failure'});
						console.log(err);
						console.log("failure to save new product");
					}
					else{
						res.status(200).json({
							productId 			: newProduct.productId,
							productName 		: newProduct.productName,
							quantity 			: newProduct.quantity,
							userId 				: newProduct.userId,
							expectedOffer 		: newProduct.expectedOffer,
							productDesc 		: newProduct.productDesc,
							productExpiryDate 	: newProduct.productExpiryDate,
							isValid 			: newProduct.isValid,
							categoryId 			: newProduct.categoryId,
							lastUpdated 		: newProduct.lastUpdated
						});
					}
			});

	});

};

//GET
//Yuan
//'/category/:categoryId/product/:productId'
exports.getProductDetail = function(req, res){
	var productId = req.param('productId');

	Product.findOne({"productId" : productId}, function(err, product) {
		if(err) {
			res.status(500).json({status:'failure'});
			console.log("Get product error! Product Id: " + productId);
		}
		else if(product === null) {
			res.send("could not find the product by Product Id: " + productId);
			console.log("could not find the product by Product Id: " + productId);
		}
		else {
			res.status(200).json(product);
		}
	});
};

//PUT
//Yuan
//'/category/:categoryId/product/:productId'
exports.updateProduct = function(req, res){
	var productId = req.param('productId');

	Product.findOne({"productId" : productId}, function(err, product) {
		if(err) {
			res.status(500).json({status:'failure'});
			console.log("Get product error! Product Id: " + productId);
		}
		else if(product === null) {
			res.send("could not find the product by Product Id: " + productId);
			console.log("could not find the product by Product Id: " + productId);
		}
		else {
			// update product info
			product.productName 	 = req.param('productName');
			product.quantity 		 = req.param('quantity');
			product.userId 			 = req.param('userId');
			product.expectedOffer 	 = req.param('expectedOffer');
			product.productDesc	 	 = req.param('productDesc');
			product.productExpiryDate = req.param('productExpiryDate');
			product.isValid 		 = req.param('isValid');
			product.categoryId 		 = req.param('categoryId');
			product.lastUpdated 	 = req.param('lastUpdated');

			product.save(function(err) {
				if(err){
					res.status(500).json({status:'failure'});
					console.log("failure to update found product");
				}
				else{
					res.status(200).json({
						productId 			: newProduct.productId,
						productName 		: newProduct.productName,
						quantity 			: newProduct.quantity,
						userId 				: newProduct.userId,
						expectedOffer 		: newProduct.expectedOffer,
						productDesc 		: newProduct.productDesc,
						productExpiryDate 	: newProduct.productExpiryDate,
						isValid 			: newProduct.isValid,
						categoryId 			: newProduct.categoryId,
						lastUpdated 		: newProduct.lastUpdated
					});
				}
			});
		}
	});
};

//DELETE
//Yuan
//'/category/:categoryId/product/:productId'

<commit_msg>update updateProduct routing<commit_after>/**
 * New node file
 */
var Product = require('../app/models/product');

//GET
//'/category/:categoryId/product/'
exports.getAllProduct = function(req, res){
	var categoryId = req.param('categoryId');

	Product.find({'categoryId': categoryId}, function(err, products){
		if(err) {
			res.status(500).json({status:'failure'});
			console.log("Get all products error! Category Id: " + categoryId);
		}
		else if(products === null) {
			res.send("could not find any product from category Id: " + categoryId);
			console.log("could not find any product from category Id: " + categoryId);
		}
		else {
			var productlist = [];

			products.forEach(function(product) {
				console.log(product);
				productlist.push(product);
			});

			res.status(200).json( {
				products : productlist
			});
		}
	});
};

//Post
//'/category/:categoryId/product/'
exports.addProduct = function(req, res){
	var newProduct = new Product();
	Product.count({ productId:{$exists: true} },
			function (err, count){
				newProduct.productId 		 = count + 1;
				newProduct.productName 		 = req.param('productName');
				newProduct.quantity 		 = req.param('quantity');
				newProduct.userId 			 = req.param('userId');
				newProduct.expectedOffer 	 = req.param('expectedOffer');
				newProduct.productDesc	 	 = req.param('productDesc');
				newProduct.productExpiryDate = req.param('productExpiryDate');
				newProduct.isValid 			 = req.param('isValid');
				newProduct.categoryId 		 = req.param('categoryId');
				newProduct.lastUpdated 		 = req.param('lastUpdated');

				newProduct.save(function(err){
					if(err){
						res.status(500).json({status:'failure'});
						console.log(err);
						console.log("failure to save new product");
					}
					else{
						res.status(200).json({
							productId 			: newProduct.productId,
							productName 		: newProduct.productName,
							quantity 			: newProduct.quantity,
							userId 				: newProduct.userId,
							expectedOffer 		: newProduct.expectedOffer,
							productDesc 		: newProduct.productDesc,
							productExpiryDate 	: newProduct.productExpiryDate,
							isValid 			: newProduct.isValid,
							categoryId 			: newProduct.categoryId,
							lastUpdated 		: newProduct.lastUpdated
						});
					}
			});

	});

};

//GET
//Yuan
//'/category/:categoryId/product/:productId'
exports.getProductDetail = function(req, res){
	var productId = req.param('productId');

	Product.findOne({"productId" : productId}, function(err, product) {
		if(err) {
			res.status(500).json({status:'failure'});
			console.log("Get product error! Product Id: " + productId);
		}
		else if(product === null) {
			res.send("could not find the product by Product Id: " + productId);
			console.log("could not find the product by Product Id: " + productId);
		}
		else {
			res.status(200).json(product);
		}
	});
};

//PUT
//Yuan
//'/category/:categoryId/product/:productId'
exports.updateProduct = function(req, res){
	var productId = req.param('productId');

	Product.findOne({"productId" : productId}, function(err, product) {
		if(err) {
			res.status(500).json({status:'failure'});
			console.log("Get product error! Product Id: " + productId);
		}
		else if(product === null) {
			res.send("could not find the product by Product Id: " + productId);
			console.log("could not find the product by Product Id: " + productId);
		}
		else {
			// update product info
			product.productName 	 = req.param('productName');
			product.quantity 		 = req.param('quantity');
			product.userId 			 = req.param('userId');
			product.expectedOffer 	 = req.param('expectedOffer');
			product.productDesc	 	 = req.param('productDesc');
			product.productExpiryDate = req.param('productExpiryDate');
			product.isValid 		 = req.param('isValid');
			product.categoryId 		 = req.param('categoryId');
			product.lastUpdated 	 = req.param('lastUpdated');

			product.save(function(err) {
				if(err){
					res.status(500).json({status:'failure'});
					console.log("failure to update found product");
				}
				else{
					res.status(200).json({
						productId 			: product.productId,
						productName 		: product.productName,
						quantity 			: product.quantity,
						userId 				: product.userId,
						expectedOffer 		: product.expectedOffer,
						productDesc 		: product.productDesc,
						productExpiryDate 	: product.productExpiryDate,
						isValid 			: product.isValid,
						categoryId 			: product.categoryId,
						lastUpdated 		: product.lastUpdated
					});
				}
			});
		}
	});
};

//DELETE
//Yuan
//'/category/:categoryId/product/:productId'

<|endoftext|>


<commit_before>import {readObject, writeObject} from './utils/cache'
import debugc from 'debug'
const debugCacheMiss = debugc('fil:cache:miss')
const debugChangeDetected = debugc('fil:cache:change')

export class ReactiveCache {
  constructor() {
    this._cache = {}
  }

  async calculate({id, valueFn, watchFn, notifyFn}) {
    if (this._cache[id]) {
      return this._cache[id].value
    }

    debugCacheMiss(id)
    const value = await valueFn()
    this._setAndWatchCache({id, notifyFn, value, watchFn})
    return value
  }

  remove({id}) {
    const cachedItem = this._cache[id]
    if (!cachedItem) { return null }

    const {unsubscribeFn, value} = cachedItem
    unsubscribeFn({oldValue: value})
    delete this._cache[id]
    return value
  }

  async persistCache({cachePath, key}) {
    const values = Object.keys(this._cache)
      .map((id) => {
        const value = this._cache[id].value
        return {id, value}
      })

    return writeObject({
      cachePath,
      key,
      object: values
    })
  }

  async loadCache({cachePath, key, functionLoaderFn}) {
    const values = await readObject({
      cachePath,
      key
    })

    if (values === null) {
      // Means we have no cache at all.
      return
    }

    values.forEach(({id, value}) => {
      const {watchFn, notifyFn} = functionLoaderFn({id, value})
      this._setAndWatchCache({id, notifyFn, value, watchFn})
    })
  }

  _setAndWatchCache({id, value, watchFn, notifyFn}) {
    const externalNotifyFn = this._onValueChanged.bind(this, {id})
    const retVal = watchFn({notifyFn: externalNotifyFn})
    const unsubscribeFn = retVal && retVal.unsubscribe ? retVal.unsubscribe : () => ({})

    this._cache[id] = {
      notifyFn,
      unsubscribeFn,
      value
    }
  }

  _onValueChanged({id}) {
    const cachedItem = this._cache[id]
    if (!cachedItem) {
      debugChangeDetected(`Watcher for ${id} is already unsubscribed. You shouldn't sent extra notifications!`)
      return
    }

    debugChangeDetected(id)
    const {unsubscribeFn, notifyFn, value} = cachedItem
    delete this._cache[id]
    unsubscribeFn({oldValue: value})
    notifyFn()
  }
}
<commit_msg>Fix a bug in notifyFn<commit_after>import {readObject, writeObject} from './utils/cache'
import debugc from 'debug'
const debugCacheMiss = debugc('fil:cache:miss')
const debugChangeDetected = debugc('fil:cache:change')

export class ReactiveCache {
  constructor() {
    this._cache = {}
  }

  async calculate({id, valueFn, watchFn, notifyFn}) {
    if (this._cache[id]) {
      return this._cache[id].value
    }

    debugCacheMiss(id)
    const value = await valueFn()
    this._setAndWatchCache({id, notifyFn, value, watchFn})
    return value
  }

  remove({id}) {
    const cachedItem = this._cache[id]
    if (!cachedItem) { return null }

    const {unsubscribeFn, value} = cachedItem
    unsubscribeFn({oldValue: value})
    delete this._cache[id]
    return value
  }

  async persistCache({cachePath, key}) {
    const values = Object.keys(this._cache)
      .map((id) => {
        const value = this._cache[id].value
        return {id, value}
      })

    return writeObject({
      cachePath,
      key,
      object: values
    })
  }

  async loadCache({cachePath, key, functionLoaderFn}) {
    const values = await readObject({
      cachePath,
      key
    })

    if (values === null) {
      // Means we have no cache at all.
      return
    }

    values.forEach(({id, value}) => {
      const {watchFn, notifyFn} = functionLoaderFn({id, value})
      this._setAndWatchCache({id, notifyFn, value, watchFn})
    })
  }

  _setAndWatchCache({id, value, watchFn, notifyFn}) {
    const externalNotifyFn = this._onValueChanged.bind(this, {id})
    const retVal = watchFn({notifyFn: externalNotifyFn})
    const unsubscribeFn = retVal && retVal.unsubscribe ? retVal.unsubscribe : () => ({})

    this._cache[id] = {
      notifyFn,
      unsubscribeFn,
      value
    }
  }

  _onValueChanged({id}) {
    const cachedItem = this._cache[id]
    if (!cachedItem) {
      debugChangeDetected(`Watcher for ${id} is already unsubscribed. You shouldn't sent extra notifications!`)
      return
    }

    debugChangeDetected(id)
    const {unsubscribeFn, notifyFn, value} = cachedItem
    delete this._cache[id]
    unsubscribeFn()
    notifyFn({oldValue: value})
  }
}
<|endoftext|>


<commit_before>module.exports = function(app, async, conn, cps) {

	app.get('/', function(req, res) {
		res.sendFile('public/index.html');
	});

    app.get('/db', function(req, res) {

         var id = 1;
        var twitterHandle = "lolbutts";
        var insert = new cps.InsertRequest('<document><id>'+id+'</id>'+cps.Term(twitterHandle, "twitter-handle")+'</document>');
        conn.sendRequest(insert, function(err, response) {
           if (err) {
                res.send(response);
                return console.error(err);
           }
           console.log('New user registered: ' + response);
                res.send(response);
        });
    });

};
<commit_msg>add activites by user and add activites skeleton<commit_after>module.exports = function(app, async, conn, cps) {

    app.get('/', function(req, res) {
        res.sendFile('public/index.html');
    });

    app.get('/db', function(req, res) {

         var id = 1;
        var twitterHandle = "lolbutts";
        var insert = new cps.InsertRequest('<document><id>'+id+'</id>'+cps.Term(twitterHandle, "twitter-handle")+'</document>');
        conn.sendRequest(insert, function(err, response) {
           if (err) {
                res.send(response);
                return console.error(err);
           }
           console.log('New user registered: ' + response);
                res.send(response);
        });
    });

    /////////////////////////////////////
    //      GET ACTIVITIES BY USER     //
    /////////////////////////////////////
    app.get('/activities', function(req, res) {
        var logged_user = req.get('Authorization');
        logged_user = logged_user.split(" ");
        logged_user = logged_user[1];
        console.log(logged_user);
        // Split comma separated users into list
        var user_list = (req.query.user).split(",");
        // Add <user> tag to each user
        for (var i = 0; i < user_list.length; i++) {
            user_list[i] = cps.Term(user_list[i], "user");
        }
        // Create OR query string
        var user_string = user_list.join(" ");
        var query_string = "{" + user_string + "}";
        // Create search object and output response JSON
        var search_req = new cps.SearchRequest(query_string);
        conn.sendRequest(search_req, function(err, response) {
            if(!err) {
                res.send(response.results.document);
                // TODO Async stuff
            }
            else {
                console.log(err);
            }
        });
    });
    /////////////////////////////////////
    //     GET ACTIVITIES BY RADIUS    //
    /////////////////////////////////////

    /////////////////////////////////////
    //     ADD ACTIVITIES BY USER      //
    /////////////////////////////////////
    app.post('/activities', function(req, res) {
        // Get User
        var logged_user = req.get('Authorization');
        logged_user = logged_user.split(" ");
        logged_user = logged_user[1];
        console.log(logged_user);
        // Get request parameters
        console.log(req);
        /*var post_object = JSON.parse(req.body);
        var vote = post_object.vote === "true";
        var photo_link = post_object.photo_link;
        var lat = post_object.lat;
        var lng = post_object.lng;
        // Check if this location has been added before by this user
        var query_string = [user, lat, lng].join(" ");
        // Create search object and check if the user already was added
        var search_req = new cps.SearchRequest(query_string);
        conn.sendRequest(search_req, function(err, response) {
            // Case: Successful request or error
            if(!err) {
                // Case: Empty response or existing values
                if(!response.results.document) {
                    var timestamp = new Date() | 0;
                    var activity_id = timestamp + logged_user;
                    var activity_document = '<document>'+
                                                cps.Term(activity_id, "id") +
                                                cps.Term(user, "user") +
                                                cps.Term(vote, "vote") +
                                                cps.Term(photo_link, "photo_link") +
                                                cps.Term(lat, "lat") +
                                                cps.Term(lng, "lng") +
                                            '</document>';
                    var insert = new cps.InsertRequest(activity_document);
                    conn.sendRequest(search_req, function(err, response) {
                        // Case: Activity successfully added or error.
                        if(!err) {
                            res.send({"success": "Activity successfully added."});
                        }
                        else {
                            console.log(err);
                        }
                    });
                }
                else {
                    res.send({"error": "User has already upvoted this area."});
                }
            }
            else {
                console.log(err);
            }
        });*/
    });
};
<|endoftext|>


<commit_before>import colorverter from 'helpers/colorverter';
import deepFreeze from 'helpers/deepFreeze';

const mocks = deepFreeze({
    validOne: {
        hex: ['00', '80', 'ff'],
        rgb: [0, 128, 255],
        hsl: [210, 100, 50],
        hwb: [210, 0, 0]
    },
    validTwo: {
        hex: ['00', '7f', 'ff'],
        rgb: [0, 127, 255],
        hsl: [210, 100, 50],
        hwb: [210, 0, 0]
    }
});

const hexConvertersMap = new Map([
    ['rgb', 'hexToRgb'],
    ['hsl', 'hexToHsl'],
    ['hwb', 'hexToHwb']
]);
const rgbConvertersMap = new Map([
    ['hex', 'rgbToHex'],
    ['hsl', 'rgbToHsl'],
    ['hwb', 'rgbToHwb']
]);
const hslConvertersMap = new Map([
    ['rgb', 'hslToRgb'],
    ['hex', 'hslToHex'],
    ['hwb', 'hslToHwb']
]);
const hwbConvertersMap = new Map([
    ['hex', 'hwbToHex'],
    ['rgb', 'hwbToRgb'],
    ['hsl', 'hwbToHsl']
]);
const convertersMap = new Map([
    ['hex', hexConvertersMap],
    ['rgb', rgbConvertersMap],
    ['hsl', hslConvertersMap],
    ['hwb', hwbConvertersMap]
]);

const validatorsMap = new Map([
    ['hex', 'isHex'],
    ['rgb', 'isRgb'],
    ['hsl', 'isHsl'],
    ['hwb', 'isHwb']
]);

const generatorsMap = new Map([
    ['hex', 'getRandomHex'],
    ['rgb', 'getRandomRgb'],
    ['hsl', 'getRandomHsl'],
    ['hwb', 'getRandomHwb']
]);

// -----------------------------------------------------------------------------
// testing returned values
// -----------------------------------------------------------------------------

describe('colorverter.*To*', () => {
    it('should return color array', () => {
        convertersMap.forEach((targetsMap, sourceName) => {
            targetsMap.forEach((convertName, targetName) => {
                const convert = colorverter[convertName].bind(colorverter);
                const newColor = convert(mocks.validOne[sourceName]);
                expect(newColor instanceof Array).toBeTruthy();
            });
        });
    });
});

describe('colorverter.*To*', () => {
    it('should generate valid values', () => {
        convertersMap.forEach((targetsMap, sourceName) => {
            targetsMap.forEach((convertName, targetName) => {
                const convert = colorverter[convertName].bind(colorverter);

                const generateName = generatorsMap.get(sourceName);
                const generate = colorverter[generateName].bind(colorverter);

                const validateName = validatorsMap.get(targetName);
                const validate = colorverter[validateName].bind(colorverter);

                for (let i = 0; i < 999; i++) {
                    const newRandom = convert(generate());
                    const isValid = validate(newRandom);
                    expect(isValid).toBeTruthy();
                }
            });
        });
    });
});

// -----------------------------------------------------------------------------
// testing conversion
// -----------------------------------------------------------------------------

describe('colorverter.*To*', () => {
    it('should convert colors to expected value', () => {
        convertersMap.forEach((targetsMap, sourceName) => {
            targetsMap.forEach((convertName, targetName) => {
                const convert = colorverter[convertName].bind(colorverter);

                let generated = convert(mocks.validOne[sourceName]);
                let expected = mocks.validOne[targetName];
                let isSame = colorverter.isSameColor(generated, expected);
                expect(isSame).toBeTruthy(`${generated} is not ${expected}`);

                generated = convert(mocks.validTwo[sourceName]);
                expected = mocks.validTwo[targetName];
                isSame = colorverter.isSameColor(generated, expected);
                expect(isSame).toBeTruthy(`${generated} is not ${expected}`);
            });
        });
    });
});
<commit_msg>better error message on failed test<commit_after>import colorverter from 'helpers/colorverter';
import deepFreeze from 'helpers/deepFreeze';

const mocks = deepFreeze({
    validOne: {
        hex: ['00', '80', 'ff'],
        rgb: [0, 128, 255],
        hsl: [210, 100, 50],
        hwb: [210, 0, 0]
    },
    validTwo: {
        hex: ['00', '7f', 'ff'],
        rgb: [0, 127, 255],
        hsl: [210, 100, 50],
        hwb: [210, 0, 0]
    }
});

const hexConvertersMap = new Map([
    ['rgb', 'hexToRgb'],
    ['hsl', 'hexToHsl'],
    ['hwb', 'hexToHwb']
]);
const rgbConvertersMap = new Map([
    ['hex', 'rgbToHex'],
    ['hsl', 'rgbToHsl'],
    ['hwb', 'rgbToHwb']
]);
const hslConvertersMap = new Map([
    ['rgb', 'hslToRgb'],
    ['hex', 'hslToHex'],
    ['hwb', 'hslToHwb']
]);
const hwbConvertersMap = new Map([
    ['hex', 'hwbToHex'],
    ['rgb', 'hwbToRgb'],
    ['hsl', 'hwbToHsl']
]);
const convertersMap = new Map([
    ['hex', hexConvertersMap],
    ['rgb', rgbConvertersMap],
    ['hsl', hslConvertersMap],
    ['hwb', hwbConvertersMap]
]);

const validatorsMap = new Map([
    ['hex', 'isHex'],
    ['rgb', 'isRgb'],
    ['hsl', 'isHsl'],
    ['hwb', 'isHwb']
]);

const generatorsMap = new Map([
    ['hex', 'getRandomHex'],
    ['rgb', 'getRandomRgb'],
    ['hsl', 'getRandomHsl'],
    ['hwb', 'getRandomHwb']
]);

// -----------------------------------------------------------------------------
// testing returned values
// -----------------------------------------------------------------------------

describe('colorverter.*To*', () => {
    it('should return color array', () => {
        convertersMap.forEach((targetsMap, sourceName) => {
            targetsMap.forEach((convertName, targetName) => {
                const convert = colorverter[convertName].bind(colorverter);
                const newColor = convert(mocks.validOne[sourceName]);
                expect(newColor instanceof Array).toBeTruthy();
            });
        });
    });
});

describe('colorverter.*To*', () => {
    it('should generate valid values', () => {
        convertersMap.forEach((targetsMap, sourceName) => {
            targetsMap.forEach((convertName, targetName) => {
                const convert = colorverter[convertName].bind(colorverter);

                const generateName = generatorsMap.get(sourceName);
                const generate = colorverter[generateName].bind(colorverter);

                const validateName = validatorsMap.get(targetName);
                const validate = colorverter[validateName].bind(colorverter);

                for (let i = 0; i < 999; i++) {
                    const newRandom = convert(generate());
                    const isValid = validate(newRandom);
                    expect(isValid).toBeTruthy();
                }
            });
        });
    });
});

// -----------------------------------------------------------------------------
// testing conversion
// -----------------------------------------------------------------------------

describe('colorverter.*To*', () => {
    it('should convert colors to expected value', () => {
        convertersMap.forEach((targetsMap, sourceName) => {
            targetsMap.forEach((convertName, targetName) => {
                const convert = colorverter[convertName].bind(colorverter);

                const errorPrefix = `From ${sourceName} to ${targetName}: `;

                let generated = convert(mocks.validOne[sourceName]);
                let expected = mocks.validOne[targetName];
                let isSame = colorverter.isSameColor(generated, expected);
                expect(isSame).toBeTruthy(
                    `${errorPrefix}expected ${expected}, but got ${generated}`
                );

                generated = convert(mocks.validTwo[sourceName]);
                expected = mocks.validTwo[targetName];
                isSame = colorverter.isSameColor(generated, expected);
                expect(isSame).toBeTruthy(
                    `${errorPrefix}expected ${expected}, but got ${generated}`
                );
            });
        });
    });
});
<|endoftext|>


<commit_before>import Express from 'express';
import http from 'http';
import renderFullPage from './utils/render';
const webpack = require('webpack');
const webpackConfig = require('../../webpack/common.config');
const compiler = webpack(webpackConfig);
const app = new Express();
const server = new http.Server(app);
const proxy = require('http-proxy').createProxyServer({});

// Port for web-dev-server and server app (bundle.js, bundle.css, dist, static)
const port = process.env.NODE_ENV === 'development'
  ? 3000
  : 80;

app.use(require('morgan')('short'));

if (process.env.NODE_ENV === 'development') {
  app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true, publicPath: webpackConfig.output.publicPath,
  }));

  app.use(require('webpack-hot-middleware')(compiler, {
    log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000,
  }));
}

proxy.on('error', (err, req) => {
  console.error(err, req.url);
});

// Activate proxy for session
app.use(/\/api\/(.*)/, (req, res) => {
  req.url = req.originalUrl;
  proxy.web(req, res, { target: 'http://localhost:3030' });
});

// Static directory for express
app.use('/static', Express.static(__dirname + '/../../static/'));
app.use('/dist', Express.static(__dirname + '/../../dist/'));

app.get(/.*/, (req, res) => {
  const domain = req.get('host').replace(/\:.*/, '');
  res.end(renderFullPage('', port, domain));
});

server.listen(port, () => {
  const host = server.address().address;

  console.log('Server is listening on http://%s:%s', host, port);
});
<commit_msg>Use env.PORT or 80 for production<commit_after>import Express from 'express';
import http from 'http';
import renderFullPage from './utils/render';
const webpack = require('webpack');
const webpackConfig = require('../../webpack/common.config');
const compiler = webpack(webpackConfig);
const app = new Express();
const server = new http.Server(app);
const proxy = require('http-proxy').createProxyServer({});

// Port for web-dev-server and server app (bundle.js, bundle.css, dist, static)
const port = process.env.NODE_ENV === 'development'
  ? 3000
  : (process.env.PORT || 80);

app.use(require('morgan')('short'));

if (process.env.NODE_ENV === 'development') {
  app.use(require('webpack-dev-middleware')(compiler, {
    noInfo: true, publicPath: webpackConfig.output.publicPath,
  }));

  app.use(require('webpack-hot-middleware')(compiler, {
    log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000,
  }));
}

proxy.on('error', (err, req) => {
  console.error(err, req.url);
});

// Activate proxy for session
app.use(/\/api\/(.*)/, (req, res) => {
  req.url = req.originalUrl;
  proxy.web(req, res, { target: 'http://localhost:3030' });
});

// Static directory for express
app.use('/static', Express.static(__dirname + '/../../static/'));
app.use('/dist', Express.static(__dirname + '/../../dist/'));

app.get(/.*/, (req, res) => {
  const domain = req.get('host').replace(/\:.*/, '');
  res.end(renderFullPage('', port, domain));
});

server.listen(port, () => {
  const host = server.address().address;

  console.log('Server is listening on http://%s:%s', host, port);
});
<|endoftext|>