<commit_before>/* eslint max-len: 0 */
import React from 'react';
import { Link } from 'routes';
import classnames from 'classnames';
import { Autobind } from 'es-decorators';
import { Router } from 'routes';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import { getInsights } from 'redactions/insights';

// Layout
import Page from 'components/app/layout/Page';
import Head from 'components/app/layout/head';

// Components

let Map;
let Cesium;
if (typeof window !== 'undefined') {
  /* eslint-disable */
  Map = require('react-cesium').Map;
  /* eslint-enable */
}

const MARKERS = [
  {
    name: 'Tropical deforestation',
    lat: 0.076,
    lon: 101,
    type: 'billboard',
    image: '../../static/images/splash/marker.svg',
    imageSelected: '../../static/images/splash/markerSelected.svg',
    imageNotSelected: '../../static/images/splash/marker.svg'
  },
  {
    name: 'Coral bleaching',
    lat: -21,
    lon: 151,
    type: 'billboard',
    image: '../../static/images/splash/marker.svg',
    imageSelected: '../../static/images/splash/markerSelected.svg',
    imageNotSelected: '../../static/images/splash/marker.svg',
    thumbnail: '../../static/images/splash/bleached.jpg',
    routeId: 'coral'
  }
];

const CAMERA_INITIAL_POSITION = { lat: 35.46, lon: -3.55, height: 90000 };
const CAMERA_NEW_POSITION = { lat: 49.2002, lon: -0.1382, height: 20000000 };

class Splash extends Page {
  constructor(props) {
    super(props);

    this.state = {
      billboardHover: false,
      selectedMarker: null,
      viewer: null
    };
  }

  componentDidMount() {
    super.componentDidMount();

    // Init Cesium var
    Cesium = window.Cesium;
    Cesium.BingMapsApi.defaultKey = process.env.BING_MAPS_API_KEY;

    this.setState({ mounted: true }); // eslint-disable-line react/no-did-mount-set-state
  }

  runInitialAnimation() {
    const { viewer } = this.state;
    const { camera } = viewer;
    // const center = Cesium.Cartesian3.fromDegrees(CAMERA_INITIAL_POSITION.lon, CAMERA_INITIAL_POSITION.lat);
    // camera.lookAt(center, new Cesium.Cartesian3(0.0, 0.0, CAMERA_INITIAL_POSITION.height));
    camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(CAMERA_INITIAL_POSITION.lon, CAMERA_INITIAL_POSITION.lat, CAMERA_INITIAL_POSITION.height),
      orientation: {
        heading: 0.0,
        pitch: -0.3,
        roll: 0.0
      }
    });
    setTimeout(() => camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(CAMERA_NEW_POSITION.lon, CAMERA_NEW_POSITION.lat, CAMERA_INITIAL_POSITION.height),
      orientation: {
        heading: 0.0,
        pitch: -0.3,
        roll: 0.0
      },
      duration: 15,
      maximumHeight: CAMERA_INITIAL_POSITION.height
    }), 6000);
    setTimeout(() => camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(CAMERA_NEW_POSITION.lon, CAMERA_NEW_POSITION.lat, CAMERA_NEW_POSITION.height),
      orientation: {
        heading: 0.0,
        pitch: -Cesium.Math.PI_OVER_TWO,
        roll: 0.0
      },
      duration: 8,
      maximumHeight: CAMERA_INITIAL_POSITION.height + 9000000
    }), 16000);
  }

  handleMouseMove(e) {

  }

  @Autobind
  handleBillboardClick(e) {
    const name = e.id.name;
    this.setState({ selectedMarker: MARKERS.find(elem => elem.name === name) });
  }

  @Autobind
  handleBillboardHover() {
    this.setState({ billboardHover: true });
  }

  @Autobind
  handleBillboardOut() {
    this.setState({ billboardHover: false });
  }

  @Autobind
  handleVisitButton() {
    const { selectedMarker, viewer } = this.state;
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(selectedMarker.lat, selectedMarker.lon, 1000.0)
    });
    Router.pushRoute('splash_detail', { id: selectedMarker.routeId });
  }

  @Autobind
  handleMouseClick(e) {
  }

  @Autobind
  handleOnInit(viewer) {
    this.setState({ viewer }, this.runInitialAnimation);
  }

  render() {
    const { mounted, billboardHover, selectedMarker } = this.state;
    const cesiumClassname = classnames({
      'cesium-map': true,
      '-cursor-pointer': billboardHover
    });

    return (

          <Link route="home">

          </Link>
          <Link route="home">
            GO TO RESOURCE WATCH
          </Link>

        {mounted &&
          <Map
            className={cesiumClassname}
            shapes={MARKERS}
            homeButton={false}
            navigationHelpButton={false}
            selectionIndicator={false}
            showInfoWindow={false}
            onBillboardClick={this.handleBillboardClick}
            onBillboardHover={this.handleBillboardHover}
            onBillboardOut={this.handleBillboardOut}
            onClick={this.handleMouseClick}
            onInit={this.handleOnInit}
          />
        }
        {selectedMarker &&

                {selectedMarker.name}

                  VISIT THIS PLACE

        }

    );
  }
}

const mapStateToProps = state => ({ insights: state.insights.list });

const mapDispatchToProps = dispatch => ({
  getInsights: () => dispatch(getInsights())
});

export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(Splash);
<commit_msg>minor fix<commit_after>/* eslint max-len: 0 */
import React from 'react';
import { Link } from 'routes';
import classnames from 'classnames';
import { Autobind } from 'es-decorators';
import { Router } from 'routes';

// Redux
import withRedux from 'next-redux-wrapper';
import { initStore } from 'store';
import { getInsights } from 'redactions/insights';

// Layout
import Page from 'components/app/layout/Page';
import Head from 'components/app/layout/head';

// Components

let Map;
let Cesium;
if (typeof window !== 'undefined') {
  /* eslint-disable */
  Map = require('react-cesium').Map;
  /* eslint-enable */
}

const MARKERS = [
  {
    name: 'Tropical deforestation',
    lat: 0.076,
    lon: 101,
    type: 'billboard',
    image: '../../static/images/splash/marker.svg',
    imageSelected: '../../static/images/splash/markerSelected.svg',
    imageNotSelected: '../../static/images/splash/marker.svg'
  },
  {
    name: 'Coral bleaching',
    lat: -21,
    lon: 151,
    type: 'billboard',
    image: '../../static/images/splash/marker.svg',
    imageSelected: '../../static/images/splash/markerSelected.svg',
    imageNotSelected: '../../static/images/splash/marker.svg',
    thumbnail: '../../static/images/splash/bleached.jpg',
    routeId: 'coral'
  }
];

const CAMERA_INITIAL_POSITION = { lat: 35.46, lon: -3.55, height: 90000 };
const CAMERA_NEW_POSITION = { lat: 49.2002, lon: -0.1382, height: 20000000 };

class Splash extends Page {
  constructor(props) {
    super(props);

    this.state = {
      billboardHover: false,
      selectedMarker: null,
      viewer: null
    };
  }

  componentDidMount() {
    super.componentDidMount();

    // Init Cesium var
    Cesium = window.Cesium;
    Cesium.BingMapsApi.defaultKey = process.env.BING_MAPS_API_KEY;

    this.setState({ mounted: true }); // eslint-disable-line react/no-did-mount-set-state
  }

  runInitialAnimation() {
    const { viewer } = this.state;
    const { camera } = viewer;
    // const center = Cesium.Cartesian3.fromDegrees(CAMERA_INITIAL_POSITION.lon, CAMERA_INITIAL_POSITION.lat);
    // camera.lookAt(center, new Cesium.Cartesian3(0.0, 0.0, CAMERA_INITIAL_POSITION.height));
    camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(CAMERA_INITIAL_POSITION.lon, CAMERA_INITIAL_POSITION.lat, CAMERA_INITIAL_POSITION.height),
      orientation: {
        heading: 0.0,
        pitch: -0.3,
        roll: 0.0
      }
    });
    setTimeout(() => camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(CAMERA_NEW_POSITION.lat, CAMERA_NEW_POSITION.lon, CAMERA_INITIAL_POSITION.height),
      orientation: {
        heading: 0.0,
        pitch: -0.3,
        roll: 0.0
      },
      duration: 15,
      maximumHeight: CAMERA_INITIAL_POSITION.height
    }), 6000);
    setTimeout(() => camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(CAMERA_NEW_POSITION.lon, CAMERA_NEW_POSITION.lat, CAMERA_NEW_POSITION.height),
      orientation: {
        heading: 0.0,
        pitch: -Cesium.Math.PI_OVER_TWO,
        roll: 0.0
      },
      duration: 8,
      maximumHeight: CAMERA_INITIAL_POSITION.height + 9000000
    }), 16000);
  }

  handleMouseMove(e) {

  }

  @Autobind
  handleBillboardClick(e) {
    const name = e.id.name;
    this.setState({ selectedMarker: MARKERS.find(elem => elem.name === name) });
  }

  @Autobind
  handleBillboardHover() {
    this.setState({ billboardHover: true });
  }

  @Autobind
  handleBillboardOut() {
    this.setState({ billboardHover: false });
  }

  @Autobind
  handleVisitButton() {
    const { selectedMarker, viewer } = this.state;
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(selectedMarker.lat, selectedMarker.lon, 1000.0)
    });
    Router.pushRoute('splash_detail', { id: selectedMarker.routeId });
  }

  @Autobind
  handleMouseClick(e) {
  }

  @Autobind
  handleOnInit(viewer) {
    this.setState({ viewer }, this.runInitialAnimation);
  }

  render() {
    const { mounted, billboardHover, selectedMarker } = this.state;
    const cesiumClassname = classnames({
      'cesium-map': true,
      '-cursor-pointer': billboardHover
    });

    return (

          <Link route="home">

          </Link>
          <Link route="home">
            GO TO RESOURCE WATCH
          </Link>

        {mounted &&
          <Map
            className={cesiumClassname}
            shapes={MARKERS}
            homeButton={false}
            navigationHelpButton={false}
            selectionIndicator={false}
            showInfoWindow={false}
            onBillboardClick={this.handleBillboardClick}
            onBillboardHover={this.handleBillboardHover}
            onBillboardOut={this.handleBillboardOut}
            onClick={this.handleMouseClick}
            onInit={this.handleOnInit}
          />
        }
        {selectedMarker &&

                {selectedMarker.name}

                  VISIT THIS PLACE

        }

    );
  }
}

const mapStateToProps = state => ({ insights: state.insights.list });

const mapDispatchToProps = dispatch => ({
  getInsights: () => dispatch(getInsights())
});

export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(Splash);
<|endoftext|>


<commit_before>var gpio = require('rpi-gpio');
var SPI = require('spi');

var pin   = 7;
var onDelay = 60000;
var offDelay = 90000;
var count = 0;
var max   = 3;

gpio.setup(pin, gpio.DIR_OUT, on);

var spi = new SPI.Spi('/dev/spidev0.0', {
    'mode': SPI.MODE['MODE_0'],  // always set mode as the first option
    'chipSelect': SPI.CS['none'] // 'none', 'high' - defaults to low
  }, function(s){
    s.maxSpeed(1000000);
    s.open();
  });
setInterval(function(){
  getADC(0);
  getADC(1);
},500);
// function on() {
//     // if (count >= max) {
//     //     gpio.destroy(function() {
//     //         console.log('Closed pins, now exit');
//     //     });
//     //     return;
//     // }
//
//     setTimeout(function() {
//         gpio.write(pin, 1, off);
//         count += 1;
//     }, onDelay);
// }
//
// function off() {
//     setTimeout(function() {
//         gpio.write(pin, 0, on);
//     }, offDelay);
// }
var getADC = function(channel){
  var spiData =  new Buffer([1,0x80|(channel << 4),0]);
  var rxbuf = new Buffer([ 0x00, 0x00, 0x00]);
  spi.transfer(spiData, rxbuf, function(device, buf) {
    console.log("Channel " +channel +": " +buf.readUInt16BE(0));
  });
}
<commit_msg>add second ADC test<commit_after>var gpio = require('rpi-gpio');
var SPI = require('spi');

var pin   = 7;
var onDelay = 60000;
var offDelay = 90000;
var count = 0;
var max   = 3;

//gpio.setup(pin, gpio.DIR_OUT, on);

var spi = new SPI.Spi('/dev/spidev0.0', {
    'mode': SPI.MODE['MODE_0'],  // always set mode as the first option
    'chipSelect': SPI.CS['none'] // 'none', 'high' - defaults to low
  }, function(s){
    s.maxSpeed(1000000);
    s.open();
  });
setInterval(function(){
  getADC(0);
  getADC(1);
},500);
// function on() {
//     // if (count >= max) {
//     //     gpio.destroy(function() {
//     //         console.log('Closed pins, now exit');
//     //     });
//     //     return;
//     // }
//
//     setTimeout(function() {
//         gpio.write(pin, 1, off);
//         count += 1;
//     }, onDelay);
// }
//
// function off() {
//     setTimeout(function() {
//         gpio.write(pin, 0, on);
//     }, offDelay);
// }
var getADC = function(channel){
  var spiData =  new Buffer([1,0x80|(channel << 4),0]);
  var rxbuf = new Buffer([ 0x00, 0x00, 0x00]);
  spi.transfer(spiData, rxbuf, function(device, buf) {
    console.log("Channel " +channel +": " +buf.readUInt16BE(0));
  });
}
<|endoftext|>


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

var MessageHub = require('../../lib/messagehub');
var TestUtils = require('../test-utils');
var Expect = require('expect.js');
var Q = require('q');

module.exports.run = function(services, port, useMockService) {

  describe('[Client.prototype.topics] API', function() {
    var TOPIC_PREFIX = TestUtils.generateID();
    var instance;

    // Create a Message Hub client instance before each test. We're not
    // testing client instantiation here so a default one is fine for
    // each test.
    beforeEach('Create a new instance of Message Hub client', function() {
      instance = new MessageHub(services, { 'https': !useMockService });
    });

    it('Exposes topics object', function() {
      Expect(instance.hasOwnProperty('topics'));
    });

    it('prototype.topics.create', function() {
      Expect(instance.topics.hasOwnProperty('create'));
      Expect(instance.topics.create(TOPIC_PREFIX + 'mytopic').constructor.name).to.eql('Promise');
    });

    it('prototype.topics.delete', function() {
      Expect(instance.topics.hasOwnProperty('delete'));
      Expect(instance.topics.delete(TOPIC_PREFIX + 'mytopic').constructor.name).to.eql('Promise');
    });

    it('prototype.topics.get', function() {
      Expect(instance.topics.hasOwnProperty('get'));
      Expect(instance.topics.get().constructor.name).to.eql('Promise');
    });

  });

  describe('[Client.prototype.topics] Functionality', function() {
    var TOPIC_PREFIX = TestUtils.generateID();
    var instance;
    // Used for internal tracking of topic names.
    // (For comparison to Kafka backend).
    var topicList = [];

    // Create a Message Hub client instance before each test. We're not
    // testing client instantiation here so a default one is fine for
    // each test.
    beforeEach('Create a new instance of Message Hub client', function() {
      instance = new MessageHub(services, { 'https': !useMockService });
    });

    it('Creates a topic successfully', function(done) {
      var input = TOPIC_PREFIX + 'mytopic';

      topicList.push(input);

      instance.topics.create(input)
        .then(function(data) {
          done();
        })
        .catch(function(error) {
          done(new Error('Topic creation should have succeeded: ' + error.message));
        });
    });

    it('Rejects promise instantly when creating a topic with invalid inputs', function(done) {
      var input = [undefined, null, '', 7.3, {}, []];
      var expected = [ReferenceError, ReferenceError, Error, TypeError, TypeError, TypeError];
      var promisesResolved = 0;

      for(var index in input) {
        (function() {

          var i = index;

          instance.topics.create(input[i])
            .then(function(data) {
              done(new Error('Promise for value "' + input[i] + '"was not rejected.'));
            })
            .fail(function(error) {
              Expect(error).to.be.a(expected[i]);
              promisesResolved++;

              if(promisesResolved === input.length) {
                done();
              }
            });

        })();
      }
    });

    it('Deletes a topic successfully', function(done) {
      var input = TOPIC_PREFIX + 'delete_test_topic';
      var timeout = 2000;

      // First, create a topic to be deleted.
      instance.topics.create(input)
        .then(function(response) {
          // Wait <timeout> seconds for the topic to be inserted
          // into the server-side topic list.
          return Q.delay(instance.topics.get(), timeout);
        })
        .then(function(response) {
          var inList = false;
          var index = 0;
          // Search for the topic, if it is not in the list
          // the test fails.
          while(index < response.length && !inList) {
            if(response[index].name === input) {
              inList = true;
            }

            index++;
          }

          console.log("inlist" +inList);
          if(!inList) {
            done(new Error('Topic ' + input + ' not in list after ' + timeout + ' milliseconds.'));
          }

          // If the topic is in the list, delete it
          // and wait for a response.
          return instance.topics.delete(input);
        })
        .then(function(response) {
          done();
        })
        .fail(function(error) {
          done(new Error('Topic should have been deleted but received error: ' + error.message));
        });
    });

    it.skip('Gets a 404 when attempting to delete a topic which doesn\'t exist', function(done) {
      var input = 'abcdef';

      instance.topics.delete(input)
        .then(function(data) {
          done(new Error('Promise for value "' + input + '" should have been rejected.'));
        })
        .fail(function(error) {
          Expect(error).not.to.be(null);
          done();
        })
    });

    it('Rejects promise instantly when deleting a topic using invalid inputs', function(done) {
      var input = [undefined, null, '', 7.3, {}, []];
      var expected = [ReferenceError, ReferenceError, Error, TypeError, TypeError, TypeError];
      var promisesResolved = 0;

      for(var index in input) {
        (function() {

          var i = index;

          instance.topics.delete(input[i])
            .then(function(data) {
              done(new Error('Promise for value "' + input[i] + '"was not rejected.'));
            })
            .fail(function(error) {
              Expect(error).to.be.a(expected[i]);
              promisesResolved++;

              if(promisesResolved === input.length) {
                done();
              }
            });

        })();
      }
    });

    it('Successfully retrieves a list of topics', function(done) {
      instance.topics.create(TOPIC_PREFIX + 'topic_to_create')
        .then(function(response) {
          return Q.delay(response, 1000);
        })
        .then(function(data) {
          return instance.topics.get();
        })
        .then(function(response) {
          Expect(response).not.to.be(null);
          Expect(response).to.be.an(Array);
          Expect(response.length).to.be.greaterThan(0);
          done();
        });
    });

  });

};
<commit_msg>Removing console.log statement<commit_after>/**
 * Copyright 2015 IBM
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
*/
/**
 * Licensed Materials - Property of IBM
 * © Copyright IBM Corp. 2015
*/
'use strict';

var MessageHub = require('../../lib/messagehub');
var TestUtils = require('../test-utils');
var Expect = require('expect.js');
var Q = require('q');

module.exports.run = function(services, port, useMockService) {

  describe('[Client.prototype.topics] API', function() {
    var TOPIC_PREFIX = TestUtils.generateID();
    var instance;

    // Create a Message Hub client instance before each test. We're not
    // testing client instantiation here so a default one is fine for
    // each test.
    beforeEach('Create a new instance of Message Hub client', function() {
      instance = new MessageHub(services, { 'https': !useMockService });
    });

    it('Exposes topics object', function() {
      Expect(instance.hasOwnProperty('topics'));
    });

    it('prototype.topics.create', function() {
      Expect(instance.topics.hasOwnProperty('create'));
      Expect(instance.topics.create(TOPIC_PREFIX + 'mytopic').constructor.name).to.eql('Promise');
    });

    it('prototype.topics.delete', function() {
      Expect(instance.topics.hasOwnProperty('delete'));
      Expect(instance.topics.delete(TOPIC_PREFIX + 'mytopic').constructor.name).to.eql('Promise');
    });

    it('prototype.topics.get', function() {
      Expect(instance.topics.hasOwnProperty('get'));
      Expect(instance.topics.get().constructor.name).to.eql('Promise');
    });

  });

  describe('[Client.prototype.topics] Functionality', function() {
    var TOPIC_PREFIX = TestUtils.generateID();
    var instance;
    // Used for internal tracking of topic names.
    // (For comparison to Kafka backend).
    var topicList = [];

    // Create a Message Hub client instance before each test. We're not
    // testing client instantiation here so a default one is fine for
    // each test.
    beforeEach('Create a new instance of Message Hub client', function() {
      instance = new MessageHub(services, { 'https': !useMockService });
    });

    it('Creates a topic successfully', function(done) {
      var input = TOPIC_PREFIX + 'mytopic';

      topicList.push(input);

      instance.topics.create(input)
        .then(function(data) {
          done();
        })
        .catch(function(error) {
          done(new Error('Topic creation should have succeeded: ' + error.message));
        });
    });

    it('Rejects promise instantly when creating a topic with invalid inputs', function(done) {
      var input = [undefined, null, '', 7.3, {}, []];
      var expected = [ReferenceError, ReferenceError, Error, TypeError, TypeError, TypeError];
      var promisesResolved = 0;

      for(var index in input) {
        (function() {

          var i = index;

          instance.topics.create(input[i])
            .then(function(data) {
              done(new Error('Promise for value "' + input[i] + '"was not rejected.'));
            })
            .fail(function(error) {
              Expect(error).to.be.a(expected[i]);
              promisesResolved++;

              if(promisesResolved === input.length) {
                done();
              }
            });

        })();
      }
    });

    it('Deletes a topic successfully', function(done) {
      var input = TOPIC_PREFIX + 'delete_test_topic';
      var timeout = 2000;

      // First, create a topic to be deleted.
      instance.topics.create(input)
        .then(function(response) {
          // Wait <timeout> seconds for the topic to be inserted
          // into the server-side topic list.
          return Q.delay(instance.topics.get(), timeout);
        })
        .then(function(response) {
          var inList = false;
          var index = 0;
          // Search for the topic, if it is not in the list
          // the test fails.
          while(index < response.length && !inList) {
            if(response[index].name === input) {
              inList = true;
            }

            index++;
          }

          if(!inList) {
            done(new Error('Topic ' + input + ' not in list after ' + timeout + ' milliseconds.'));
          }

          // If the topic is in the list, delete it
          // and wait for a response.
          return instance.topics.delete(input);
        })
        .then(function(response) {
          done();
        })
        .fail(function(error) {
          done(new Error('Topic should have been deleted but received error: ' + error.message));
        });
    });

    it.skip('Gets a 404 when attempting to delete a topic which doesn\'t exist', function(done) {
      var input = 'abcdef';

      instance.topics.delete(input)
        .then(function(data) {
          done(new Error('Promise for value "' + input + '" should have been rejected.'));
        })
        .fail(function(error) {
          Expect(error).not.to.be(null);
          done();
        })
    });

    it('Rejects promise instantly when deleting a topic using invalid inputs', function(done) {
      var input = [undefined, null, '', 7.3, {}, []];
      var expected = [ReferenceError, ReferenceError, Error, TypeError, TypeError, TypeError];
      var promisesResolved = 0;

      for(var index in input) {
        (function() {

          var i = index;

          instance.topics.delete(input[i])
            .then(function(data) {
              done(new Error('Promise for value "' + input[i] + '"was not rejected.'));
            })
            .fail(function(error) {
              Expect(error).to.be.a(expected[i]);
              promisesResolved++;

              if(promisesResolved === input.length) {
                done();
              }
            });

        })();
      }
    });

    it('Successfully retrieves a list of topics', function(done) {
      instance.topics.create(TOPIC_PREFIX + 'topic_to_create')
        .then(function(response) {
          return Q.delay(response, 1000);
        })
        .then(function(data) {
          return instance.topics.get();
        })
        .then(function(response) {
          Expect(response).not.to.be(null);
          Expect(response).to.be.an(Array);
          Expect(response.length).to.be.greaterThan(0);
          done();
        });
    });

  });

};
<|endoftext|>


<commit_before>
var File = require('../../../app/models/file');

var spies = require('../../mocks/helpers').spies,
    fileMocker = require('../../mocks/models/file'),
    filedata = require('../../fixtures/get-file-response.json');

describe('file model', function() {
  var server, callbacks, fileContents;

  before(function () { server = sinon.fakeServer.create(); });
  after(function () { server.restore(); });
  beforeEach(function() {
    // reset the DI state, so no File models are cached between tests.
    fileMocker.reset();
    callbacks = spies(['success', 'error', 'complete']);
  })

  /*
  Create a mock File model and set up the fake server to respond to a fetch().
  Returns the mock file.
  */
  var filecount = 0;
  function  mockFile(content, data) {
    var file = fileMocker();
    server.respondWith('GET', file.url(), JSON.stringify(data));
    file.set('content_url', 'https://api.gihub.com/repos/blah/blahblah/git/'+filecount++);
    server.respondWith('GET', file.get('content_url'), content);
    return file;
  }

  it('fetches data from github api and content directly content URL', function() {

    var content = 'content from server',
        file = mockFile(content, filedata);

    expect(file.get('content')).to.not.equal(content);
    expect(file.get('sha')).to.not.equal(filedata.sha);

    file.fetch(callbacks);

    server.respond();

    expect(callbacks.success).to.have.been.calledOnce;
    expect(callbacks.complete).to.have.been.calledOnce;
    expect(server.requests.length).to.equal(2);

    // use contain assertion (weaker than strict equality) to separate this from
    // tests that check for whitespace trimming
    expect(file.get('content')).to.contain(content);
    expect(file.get('sha')).to.equal(filedata.sha);
  })

  it('parses YAML frontmatter when present', function() {
    var content = 'my content',
        yaml = '---\nlayout: post\npublished: true\n---\n',
        file = mockFile(yaml + content, filedata);

    file.fetch(callbacks);
    server.respond();

    expect(callbacks.success).to.have.been.calledOnce;

    expect(file.get('metadata')).to.deep.equal({
      layout: 'post',
      published: true
    });
  })

  describe('trailing whitespace', function() {
    var content = 'my content',
        extraspace = '\n\t  \t\t\n   \n\t\t \n',
        yaml = '---\nlayout: post\npublished: true\n---\n';

    function whitespaceTests(withYaml) {
      var fileContent = withYaml ? (yaml + content) : content;

      it('appends a single newline if not already present', function() {
        var file = mockFile(fileContent, filedata);
        file.fetch(callbacks);
        server.respond();
        expect(callbacks.success).to.have.been.calledOnce;
        expect(file.get('content')).to.equal(content + '\n');
      });

      it('trims all EOF whitespace *except* single newline', function() {
        var file = mockFile(fileContent + extraspace, filedata)
        file.fetch(callbacks);
        server.respond();
        expect(callbacks.success).to.have.been.calledOnce;
        expect(file.get('content')).to.equal(content + '\n');
      })

      it('does not trim EOL whitespace', function() {
        var content = 'line with EOL space     \nanother line\n';
        var file = mockFile(content, filedata);
        file.fetch(callbacks);
        server.respond();
        expect(callbacks.success).to.have.been.calledOnce;
        expect(file.get('content')).to.equal(content);
      })
    }

    // run the tests both with and without yaml, since parsing code is different
    // for those two cases.
    describe('with frontmatter', whitespaceTests.bind(this, true));
    describe('without frontmatter', whitespaceTests.bind(this, false));

    describe('formatting urls', function () {
      it('properly formats urls', function () {
        var file = mockFile('', filedata);
        file.set('path', '///this-is-crazy///');
        file.collection.repo.url = function () { return 'www.test.com'; };
        expect(file.url()).to.equal('www.test.com/contents/this-is-crazy/?ref=master');
      })
    })
  })

});
<commit_msg>Test failure for #1065<commit_after>
var File = require('../../../app/models/file');

var spies = require('../../mocks/helpers').spies,
    fileMocker = require('../../mocks/models/file'),
    filedata = require('../../fixtures/get-file-response.json');

describe('file model', function() {
  var server, callbacks, fileContents;

  before(function () { server = sinon.fakeServer.create(); });
  after(function () { server.restore(); });
  beforeEach(function() {
    // reset the DI state, so no File models are cached between tests.
    fileMocker.reset();
    callbacks = spies(['success', 'error', 'complete']);
  })

  /*
  Create a mock File model and set up the fake server to respond to a fetch().
  Returns the mock file.
  */
  var filecount = 0;
  function  mockFile(content, data) {
    var file = fileMocker();
    server.respondWith('GET', file.url(), JSON.stringify(data));
    file.set('content_url', 'https://api.gihub.com/repos/blah/blahblah/git/'+filecount++);
    server.respondWith('GET', file.get('content_url'), content);
    return file;
  }

  it('fetches data from github api and content directly content URL', function() {

    var content = 'content from server',
        file = mockFile(content, filedata);

    expect(file.get('content')).to.not.equal(content);
    expect(file.get('sha')).to.not.equal(filedata.sha);

    file.fetch(callbacks);

    server.respond();

    expect(callbacks.success).to.have.been.calledOnce;
    expect(callbacks.complete).to.have.been.calledOnce;
    expect(server.requests.length).to.equal(2);

    // use contain assertion (weaker than strict equality) to separate this from
    // tests that check for whitespace trimming
    expect(file.get('content')).to.contain(content);
    expect(file.get('sha')).to.equal(filedata.sha);
  })

  it('parses YAML frontmatter when present', function() {
    var content = 'my content',
        yaml = '---\nlayout: post\npublished: true\n---\n',
        file = mockFile(yaml + content, filedata);

    file.fetch(callbacks);
    server.respond();

    expect(callbacks.success).to.have.been.calledOnce;

    expect(file.get('metadata')).to.deep.equal({
      layout: 'post',
      published: true
    });
  })

  describe('trailing whitespace', function() {
    var content = 'my content',
        extraspace = '\n\t  \t\t\n   \n\t\t \n',
        yaml = '---\nlayout: post\npublished: true\n---\n';

    function whitespaceTests(withYaml) {
      var fileContent = withYaml ? (yaml + content) : content;

      it('appends a single newline if not already present', function() {
        var file = mockFile(fileContent, filedata);
        file.fetch(callbacks);
        server.respond();
        expect(callbacks.success).to.have.been.calledOnce;
        expect(file.get('content')).to.equal(content + '\n');
      });

      it('trims all EOF whitespace *except* single newline', function() {
        var file = mockFile(fileContent + extraspace, filedata)
        file.fetch(callbacks);
        server.respond();
        expect(callbacks.success).to.have.been.calledOnce;
        expect(file.get('content')).to.equal(content + '\n');
      })

      it('does not trim EOL whitespace', function() {
        var content = 'line with EOL space     \nanother line\n';
        var file = mockFile(content, filedata);
        file.fetch(callbacks);
        server.respond();
        expect(callbacks.success).to.have.been.calledOnce;
        expect(file.get('content')).to.equal(content);
      })
    }

    // run the tests both with and without yaml, since parsing code is different
    // for those two cases.
    describe('with frontmatter', whitespaceTests.bind(this, true));
    describe('without frontmatter', whitespaceTests.bind(this, false));

    describe('formatting urls', function () {
      it('properly formats urls', function () {
        var file = mockFile('', filedata);
        file.set('path', '///this-is-crazy///');
        file.collection.repo.url = function () { return 'https://www.test.com'; };
        expect(file.url()).to.equal('https://www.test.com/contents/this-is-crazy/?ref=master');
      })
    })
  })

});
<|endoftext|>


<commit_before>const { merge } = require("../../source/merge.js");

describe("merge", function() {
    describe("merge", function() {
        it("clones objects", function() {
            const sourceA = {};
            const sourceB = {};
            const out1 = merge(sourceA);
            expect(out1).to.be.an("object");
            expect(out1).to.not.equal(sourceA);
            const out2 = merge(sourceA, sourceB);
            expect(out2).to.not.equal(sourceA);
            expect(out2).to.not.equal(sourceB);
        });

        it("merges shallow objects", function() {
            const merged = merge({ a: 12, b: 13 }, { b: 14, c: 15 });
            expect(merged).to.have.property("a", 12);
            expect(merged).to.have.property("b", 14);
            expect(merged).to.have.property("c", 15);
        });

        it("merges deep objects", function() {
            const merged = merge(
                {
                    a: {
                        b: {
                            c: {
                                d: 123
                            }
                        }
                    }
                },
                {
                    a: {
                        b: {
                            e: 456
                        }
                    }
                }
            );
            expect(merged).to.deep.equal({
                a: {
                    b: {
                        c: {
                            d: 123
                        },
                        e: 456
                    }
                }
            });
        });

        it("merges multiple objects", function() {
            const merged = merge({ a: true }, { b: true }, { c: true });
            expect(merged).to.deep.equal({
                a: true,
                b: true,
                c: true
            });
        });

        it("overwrites from right to left", function() {
            expect(merge({ a: 1 }, { a: 0 })).to.deep.equal({ a: 0 });
        });
    });
});
<commit_msg>Fix tests<commit_after>const mergeTools = require("../../source/merge.js");
const merge = mergeTools.merge;

describe("merge", function() {
    describe("merge", function() {
        it("clones objects", function() {
            const sourceA = {};
            const sourceB = {};
            const out1 = merge(sourceA);
            expect(out1).to.be.an("object");
            expect(out1).to.not.equal(sourceA);
            const out2 = merge(sourceA, sourceB);
            expect(out2).to.not.equal(sourceA);
            expect(out2).to.not.equal(sourceB);
        });

        it("merges shallow objects", function() {
            const merged = merge({ a: 12, b: 13 }, { b: 14, c: 15 });
            expect(merged).to.have.property("a", 12);
            expect(merged).to.have.property("b", 14);
            expect(merged).to.have.property("c", 15);
        });

        it("merges deep objects", function() {
            const merged = merge(
                {
                    a: {
                        b: {
                            c: {
                                d: 123
                            }
                        }
                    }
                },
                {
                    a: {
                        b: {
                            e: 456
                        }
                    }
                }
            );
            expect(merged).to.deep.equal({
                a: {
                    b: {
                        c: {
                            d: 123
                        },
                        e: 456
                    }
                }
            });
        });

        it("merges multiple objects", function() {
            const merged = merge({ a: true }, { b: true }, { c: true });
            expect(merged).to.deep.equal({
                a: true,
                b: true,
                c: true
            });
        });

        it("overwrites from right to left", function() {
            expect(merge({ a: 1 }, { a: 0 })).to.deep.equal({ a: 0 });
        });
    });
});
<|endoftext|>


<commit_before>'use strict';

var Vector = require('./vector');

function Graphics(ctx, width, height) {
    this.ctx = ctx;
    this.width = width;
    this.height = height;
}

Graphics.prototype = {

    ctx: undefined,
    width: 0,
    height: 0,

    _preDraw: function (props) {
        //this.ctx.save();
        Object.assign(this.ctx, props);
    },

    _postDraw: function () {
        //this.ctx.restore();
    },

    drawBackground: function () {
        this.drawRectangle(0, 0, this.width, this.height, {
            fillStyle: '#f4f4f4',
        });
    },

    drawLine(from, to, props) {
        this._preDraw(props);
        this.ctx.beginPath();
        this.ctx.moveTo(from.x, from.y);
        this.ctx.lineTo(to.x, to.y);
        this.ctx.stroke();
        this._postDraw();
    },

    drawCircle: function (origin, radius, props) {
        this._preDraw(props);
        this.ctx.beginPath();
        this.ctx.arc(origin.x, origin.y, radius, 0, 2 * Math.PI);
        this.ctx.fill();
        this._postDraw();
    },

    drawRectangle: function (x, y, width, height, props) {
        this._preDraw(props);
        this.ctx.beginPath();
        this.ctx.fillRect(x, y, width, height);
        this._postDraw();
    },

    drawOverlay: function (text) {
        this._preDraw(props);

        // transparent background for overlay
        this.drawRectangle(0, 0, this.width, 30, {
            fillStyle: 'rgba(100, 150, 255, .2)',
        });

        // print some info
        this.ctx.font = '16px sans-serif';
        this.ctx.fillStyle = 'black';

        this.ctx.fillText(text, 10, 20);

        this._postDraw();
    }
}

module.exports = Graphics;
<commit_msg>Fix graphics<commit_after>'use strict';

var Vector = require('./vector');

function Graphics(ctx, width, height) {
    this.ctx = ctx;
    this.width = width;
    this.height = height;
}

Graphics.prototype = {

    ctx: undefined,
    width: 0,
    height: 0,

    _preDraw: function (props) {
        this.ctx.save();
        Object.assign(this.ctx, props);
    },

    _postDraw: function () {
        this.ctx.restore();
    },

    drawBackground: function () {
        this.drawRectangle(0, 0, this.width, this.height, {
            fillStyle: '#f4f4f4',
        });
    },

    drawLine(from, to, props) {
        this._preDraw(props);
        this.ctx.beginPath();
        this.ctx.moveTo(from.x, from.y);
        this.ctx.lineTo(to.x, to.y);
        this.ctx.stroke();
        this._postDraw();
    },

    drawCircle: function (origin, radius, props) {
        this._preDraw(props);
        this.ctx.beginPath();
        this.ctx.arc(origin.x, origin.y, radius, 0, 2 * Math.PI);
        this.ctx.fill();
        this._postDraw();
    },

    drawRectangle: function (x, y, width, height, props) {
        this._preDraw(props);
        this.ctx.beginPath();
        this.ctx.fillRect(x, y, width, height);
        this._postDraw();
    },

    drawOverlay: function (text, props) {
        this._preDraw(props);

        // transparent background for overlay
        this.drawRectangle(0, 0, this.width, 30, {
            fillStyle: 'rgba(100, 150, 255, .2)',
        });

        // print some info
        this.ctx.font = '16px sans-serif';
        this.ctx.fillStyle = 'black';

        this.ctx.fillText(text, 10, 20);

        this._postDraw();
    }
}

module.exports = Graphics;
<|endoftext|>


<commit_before>
const fs        = require('fs');
const path      = require('path');
const Sequelize = require('sequelize');
const basename  = path.basename(module.filename);
const env       = process.env.NODE_ENV || 'development';
const config    = require(__dirname + '/../config/config.json')[env];
const db        = {};

let sequelize
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter((file) => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach((file) => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<commit_msg>configure dotenv for online db migrations<commit_after>const fs        = require('fs');
const path      = require('path');
const Sequelize = require('sequelize');
const dotenv = require('dotenv');

dotenv.config();

const basename  = path.basename(module.filename);
const env       = process.env.NODE_ENV || 'development';
const config    = require(__dirname + '/../config/config.json')[env];
const db        = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], { dialect: 'postgres' });
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter((file) => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach((file) => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;
<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        expect(fs.existsSync(__dirname + '/../LICENSE'), 'A LICENSE must exist');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should have a section ## License');
            console.log();
        }
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
'use strict';

const expect = require('chai').expect;
const fs     = require('fs');

describe('Test package.json and io-package.json', () => {
    it('Test package files', done => {
        console.log();

        const fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        const ioPackage = JSON.parse(fileContentIOPackage);

        const fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        const npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        expect(ioPackage.common.license, 'ERROR: License missing in io-package in common.license').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (!ioPackage.common.controller && !ioPackage.common.onlyWWW && !ioPackage.common.noConfig) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        const licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        const fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>import cozydb from 'cozydb';
import invariant from 'invariant';
import logger from 'debug';
import hasValue from '../hasValue';

const debug = logger('app:model:tasky');

const Task = cozydb.getModel('Tasky', {
    'done': {
        default: false,
        type: Boolean,
    },
    'creationDate': {
        default: Date.now,
        type: Date,
    },
    'completionDate': {
        default: null,
        type: Date,
    },
    'description': String,
    'order': Number,
    'tags': { type: JSON },
    'isArchived': {
        default: false,
        type: Boolean,
    },
});

export default Task;

Task.all = (callback) => {
    invariant(hasValue(callback), '`callback` is a mandatory parameter');
    invariant(typeof callback === 'function', '`callback` must be a function');

    debug('Retrieve all tasks.');
    Task.request('all', {}, (err, tasks) => {
        const error = err || tasks.error;
        callback(error, tasks);
    });
};

Task.allInInterval = (options, callback) => {
    invariant(hasValue(options), '`options` is a mandatory parameter');
    invariant(typeof options === 'object', '`callback` must be an object');
    invariant(hasValue(callback), '`callback` is a mandatory parameter');
    invariant(typeof callback === 'function', '`callback` must be a function');

    debug('Retrieve all tasks in given interval.');
    Task.request('byOrder', options, (err, tasks) => {
        const error = err || tasks.error;
        callback(error, tasks);
    });
};

Task.allNotArchived = (callback) => {
    invariant(hasValue(callback), '`callback` is a mandatory parameter');
    invariant(typeof callback === 'function', '`callback` must be a function');

    debug('Retrieve all unarchived tasks.');

    // null for backward compatibility
    const params = {
        keys: [false, null],
    };
    Task.request('byArchiveState', params, (err, tasks) => {
        const error = err || tasks.error;
        callback(error, tasks);
    });
};

Task.allArchived = (callback) => {
    invariant(hasValue(callback), '`callback` is a mandatory parameter');
    invariant(typeof callback === 'function', '`callback` must be a function');

    debug('Retrieve all archived tasks.');
    const params = {
        key: true,
    };
    Task.request('byArchiveState', params, (err, tasks) => {
        const error = err || tasks.error;
        callback(error, tasks);
    });
};
<commit_msg>Fix type of attribute 'tags' in model Tasky<commit_after>import cozydb from 'cozydb';
import invariant from 'invariant';
import logger from 'debug';
import hasValue from '../hasValue';

const debug = logger('app:model:tasky');

const Task = cozydb.getModel('Tasky', {
    'done': {
        default: false,
        type: Boolean,
    },
    'creationDate': {
        default: Date.now,
        type: Date,
    },
    'completionDate': {
        default: null,
        type: Date,
    },
    'description': {
        default: '',
        type: String,
    },
    'order': {
        type: Number,
    },
    'tags': {
        default: [],
        type: [String],
    },
    'isArchived': {
        default: false,
        type: Boolean,
    },
});

export default Task;

Task.all = (callback) => {
    invariant(hasValue(callback), '`callback` is a mandatory parameter');
    invariant(typeof callback === 'function', '`callback` must be a function');

    debug('Retrieve all tasks.');
    Task.request('all', {}, (err, tasks) => {
        const error = err || tasks.error;
        callback(error, tasks);
    });
};

Task.allInInterval = (options, callback) => {
    invariant(hasValue(options), '`options` is a mandatory parameter');
    invariant(typeof options === 'object', '`callback` must be an object');
    invariant(hasValue(callback), '`callback` is a mandatory parameter');
    invariant(typeof callback === 'function', '`callback` must be a function');

    debug('Retrieve all tasks in given interval.');
    Task.request('byOrder', options, (err, tasks) => {
        const error = err || tasks.error;
        callback(error, tasks);
    });
};

Task.allNotArchived = (callback) => {
    invariant(hasValue(callback), '`callback` is a mandatory parameter');
    invariant(typeof callback === 'function', '`callback` must be a function');

    debug('Retrieve all unarchived tasks.');

    // null for backward compatibility
    const params = {
        keys: [false, null],
    };
    Task.request('byArchiveState', params, (err, tasks) => {
        const error = err || tasks.error;
        callback(error, tasks);
    });
};

Task.allArchived = (callback) => {
    invariant(hasValue(callback), '`callback` is a mandatory parameter');
    invariant(typeof callback === 'function', '`callback` must be a function');

    debug('Retrieve all archived tasks.');
    const params = {
        key: true,
    };
    Task.request('byArchiveState', params, (err, tasks) => {
        const error = err || tasks.error;
        callback(error, tasks);
    });
};
<|endoftext|>


<commit_before>"use strict";

Meteor.publish ('courses', function(region){
	if(!region) return Courses.find();
				return Courses.find({region: region});
});

Meteor.publish ('courseDetails', function(id) {
	return Courses.find({ _id: id });
});

Meteor.publish ('coursesFind', coursesFind);

Meteor.publish ('roles', function(){
	return Roles.find();
});

Meteor.publish ('regions', function(){
	return Regions.find();
});

Meteor.publish ('locations', function(region) {
	var find = {}
	if (region != 'all') find.region = region
	return Locations.find(find);
});

Meteor.publish('discussion', function(courseId) {
	return CourseDiscussions.find({ course_ID: courseId });
});

Meteor.publish('events', function(region) {
	if(!region) return Events.find();
			   return Events.find({region: region});
});

Meteor.publish('event', function(eventId) {
	return Events.find({ _id: eventId });
});

Meteor.publish ('eventsFind', eventsFind);

Meteor.publish('eventsForCourse', function(courseId) {
	return Events.find({course_id: courseId});
});

Meteor.publish('futureEvents', function() {
	return Events.find({startdate: {$gt: new Date()}});
});

Meteor.publish('nextEvent', function(courseId) {
	return Events.find({ course_id: courseId });
});

Meteor.publish('user', function(userId) {
	var fields = {username: 1};

	// Admins may see other's privileges
	if (privileged(Meteor.users.findOne(this.userId), 'admin')) fields.privileges = 1;

	return Meteor.users.find(
		{ _id: userId },
		{ fields: fields }
	);
});

Meteor.publish('currentUser', function() {
  return Meteor.users.find(this.userId);
});

Meteor.publish ('groups', function(){
	return Groups.find();
});<commit_msg>housekeeping<commit_after>"use strict";

Meteor.publish ('courses', function(region){
	if(!region) {
		return Courses.find();
	} else {
		return Courses.find({region: region});
	}
});

Meteor.publish ('courseDetails', function(id) {
	return Courses.find({ _id: id });
});

Meteor.publish ('coursesFind', coursesFind);

Meteor.publish ('roles', function(){
	return Roles.find();
});

Meteor.publish ('regions', function(){
	return Regions.find();
});

Meteor.publish ('locations', function(region) {
	var find = {}
	if (region != 'all') find.region = region
	return Locations.find(find);
});

Meteor.publish('discussion', function(courseId) {
	return CourseDiscussions.find({ course_ID: courseId });
});

Meteor.publish('events', function(region) {
	if(!region) {
		return Events.find();
	} else {
		return Events.find({region: region});
	}
});

Meteor.publish('event', function(eventId) {
	return Events.find({ _id: eventId });
});

Meteor.publish ('eventsFind', eventsFind);

Meteor.publish('eventsForCourse', function(courseId) {
	return Events.find({course_id: courseId});
});

Meteor.publish('futureEvents', function() {
	return Events.find({startdate: {$gt: new Date()}});
});

Meteor.publish('nextEvent', function(courseId) {
	return Events.find({ course_id: courseId });
});

Meteor.publish('user', function(userId) {
	var fields = {username: 1};

	// Admins may see other's privileges
	if (privileged(Meteor.users.findOne(this.userId), 'admin')) fields.privileges = 1;

	return Meteor.users.find(
		{ _id: userId },
		{ fields: fields }
	);
});

Meteor.publish('currentUser', function() {
  return Meteor.users.find(this.userId);
});

Meteor.publish ('groups', function(){
	return Groups.find();
});<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

var request = require('request');
var baseUrls = {
    board: 'https://a.4cdn.org/g/catalog.json',
    img: 'https://i.4cdn.org/g/',
}

var requestOpts = {
    headers: {
        'Host': 'a.4cdn.org',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0)' /
                      'Gecko/20100101 Firefox/49.0',
        'Origin': 'http://boards.4chan.org/',
        'If-Modified-Since': '0'
    }
}

function errorHandler(err, res){
    console.log('\n\n')
    console.error("Couldn't get url. " + res.statusCode
                + " from " + errorHandler.caller.toString());
    console.log('\n\n');
}

router.get('/:board', function(req, res){
    console.log('Reached board');
    var board = req.params.board;
	console.log("Getting board /" +board+ "/");
    requestOpts.url = 'https://a.4cdn.org/' +board+ '/catalog.json';
	request(requestOpts, function(err, res2, json){
        if (err) return errorHandler(err, res2);
        res.send(json);
        res.end();
    });
});

router.get('/:board/thread/:threadID', function(req, res, next){
    console.log('Reached thread');
    var board = req.params.board;
    var id = req.params.threadID;
    requestOpts.url = 'http://a.4cdn.org/'+board+'/thread/'+id+'.json';
    console.log('Getting thread  url ' + requestOpts.url);
    request(requestOpts, function(err, res2, json){
        if (err) return errorHandler(err, res2);
        res.send(json);
        res.end();
    });
});

console.log('Reached bottom');

module.exports = router;
<commit_msg>Update server route 4chan<commit_after>var express = require('express');
var router = express.Router();

var request = require('request');
var baseUrls = {
    board: 'https://a.4cdn.org/g/catalog.json',
    img: 'https://i.4cdn.org/g/',
}

var requestOpts = {
    headers: {
        'Host': 'a.4cdn.org',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0)' /
                      'Gecko/20100101 Firefox/49.0',
        'Origin': 'http://boards.4chan.org/',
        'If-Modified-Since': '0'
    }
}

function errorHandler(err, res){
    console.log('\n\n')
    console.error("Couldn't get url. " + res.statusCode
                + " from " + errorHandler.caller.toString());
    console.log('\n\n');
}

router.get('/:boardID', function(req, res){
    var boardID = req.params.boardID;
    console.log('Reached board');

    requestOpts.url = 'https://a.4cdn.org/' +boardID+ '/catalog.json';
	request(requestOpts, function(err, res2, json){
        if (err) return errorHandler(err, res2);
        res.send(json);
        res.end();
    });
});

router.get('/:board/:threadID', function(req, res, next){
    var boardID = req.params.boardID;
    var threadID = req.params.threadID;
    console.log('Reached thread ' +boardID+ '/' +threadID);

    requestOpts.url = 'http://a.4cdn.org/'+boardID+'/thread/'+threadID+'.json';
    requestOpts.headers['Origin'] = 'http://boards.4chan.org/' +boardID,
    request(requestOpts, function(err, res2, json){
        if (err) return errorHandler(err, res2);
        res.send(json);
        res.end();
    });
});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var fs = require('file-system');
var path = require('path');
var router = express.Router();

var mongodb = require('mongodb');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//:lat1/:lon1/:lat3/:lon3
router.get('/getImages/:lat1/:lon1/:lat3/:lon3', function(req, res) {
	// Get a Mongo client to work with the Mongo server
  var MongoClient = mongodb.MongoClient;

  // Define where the MongoDB server is
  var url = 'mongodb://<dbuser>:<dbpassword>@ds117209.mlab.com:17209/image_database';

  // Connect to the server
  MongoClient.connect(url, function (err, db) {
    if (err) {
      console.log('Unable to connect to the Database Server', err);
    } else {
      // We are connected
      console.log('Connection established to', url);

      // Cast all parametters into integers
      var lat1 = parseFloat(req.params.lat1);
      var lon1 = parseFloat(req.params.lon1);
      var lat3 = parseFloat(req.params.lat3);
      var lon3 = parseFloat(req.params.lon3);
      var lat2 = lat1;
      var lon2 = lon3;
      var lat4 = lat3;
      var lon4 = lon1;

      // Get the documents collection
      var images = db.collection("images");

      // Find all images within the area
      images.find({
        loc: {
          $geoWithin: {
            $polygon: [ [ lat1, lon1 ],
                        [ lat2, lon2 ],
                        [ lat3, lon3 ],
                        [ lat4, lon4 ],
                        [ lat1, lon1 ] ]
          }
        }
      }).toArray(function (err, result) {
      if (err) {
          console.log(err);
          res.send([]);
        } else {
          console.log('Found:', result);
        var images = [];
        for (var i = 0; i < result.length; i++) {
          images[i] = {};
          images[i].comment = result[i].comment;
          images[i].loc = result[i].loc;
          images[i].image = fs.readFileSync(path.join(__dirname, result[i].path));
        }
        res.status(200).send(images);
        res.end();
        }
      });

      //Close the database connection
      db.close();
    }
  });

});

//:lat1/:lon1/:lat3/:lon3
router.get('/getImagesLocation/:lat1/:lon1/:lat3/:lon3', function(req, res) {
	// Get a Mongo client to work with the Mongo server
  var MongoClient = mongodb.MongoClient;

  // Define where the MongoDB server is
  var url = 'mongodb://<dbuser>:<dbpassword>@ds117209.mlab.com:17209/image_database';

  // Connect to the server
  MongoClient.connect(url, function (err, db) {
    if (err) {
      console.log('Unable to connect to the Database Server', err);
    } else {
      // We are connected
      console.log('Connection established to', url);

      // Cast all parametters into integers
      var lat1 = parseFloat(req.params.lat1);
      var lon1 = parseFloat(req.params.lon1);
      var lat3 = parseFloat(req.params.lat3);
      var lon3 = parseFloat(req.params.lon3);
      var lat2 = lat1;
      var lon2 = lon3;
      var lat4 = lat3;
      var lon4 = lon1;

      // Get the documents collection
      var images = db.collection("images");

      // Find all images within the area
      images.find({
        loc: {
          $geoWithin: {
            $polygon: [ [ lat1, lon1 ],
                        [ lat2, lon2 ],
                        [ lat3, lon3 ],
                        [ lat4, lon4 ],
                        [ lat1, lon1 ] ]
          }
        }
      }).toArray(function (err, result) {
      if (err) {
          console.log(err);
          res.send([]);
        } else {
          console.log('Found:', result);
        var images = [];
        for (var i = 0; i < result.length; i++) {
          images[i] = {};
          images[i].id = result[i].id;
          images[i].loc = result[i].loc;
        }
        res.status(200).send(images);
        res.end();
        }
      });

      //Close the database connection
      db.close();
    }
  });

});

router.post('/uploadImage', function(req, res) {
  // Get a Mongo client to work with the Mongo server
  var MongoClient = mongodb.MongoClient;

  // Define where the MongoDB server is
  var url = 'mongodb://<dbuser>:<dbpassword>@ds117209.mlab.com:17209/image_database';

  // Connect to the server
  MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the Database Server', err);
  } else {
      console.log('Connection established to', url);
      var images = db.collection("images");
      images.count({}, function( err, count){
        var number = count.toString();
        var location = path.join('uploads','image' + number + '.bmp');
        var imagepath = path.join(__dirname, location);
        var entry = {};
        entry.comment = req.headers.comment;
        entry.loc = [parseFloat(req.headers.latitude),parseFloat(req.headers.longitude)];
        entry.path = location;
        images.insert(entry);

        if (req.method == "POST") {
          var data = "";
          req.on("data", function(chunk) {
            data += chunk;
          });
          req.on("end", function() {
            console.log("Received posted data: " + data);
            fs.writeFile(imagepath, data, function (err) {
              if(err){
                console.log("Problem saving image");
              }else {
                console.log("Image Saved on server");
              }
            });

          });
        } else {
          console.dir(request);
        }

        db.close();
      });
    }
  });
});

module.exports = router;
<commit_msg>Fixed POST request<commit_after>'use strict';

var express = require('express');
var fs = require('file-system');
var path = require('path');
var router = express.Router();

var mongodb = require('mongodb');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//:lat1/:lon1/:lat3/:lon3
router.get('/getImages/:lat1/:lon1/:lat3/:lon3', function(req, res) {
	// Get a Mongo client to work with the Mongo server
  var MongoClient = mongodb.MongoClient;

  // Define where the MongoDB server is
  var url = 'mongodb://<dbuser>:<dbpassword>@ds117209.mlab.com:17209/image_database';

  // Connect to the server
  MongoClient.connect(url, function (err, db) {
    if (err) {
      console.log('Unable to connect to the Database Server', err);
    } else {
      // We are connected
      console.log('Connection established to', url);

      // Cast all parametters into integers
      var lat1 = parseFloat(req.params.lat1);
      var lon1 = parseFloat(req.params.lon1);
      var lat3 = parseFloat(req.params.lat3);
      var lon3 = parseFloat(req.params.lon3);
      var lat2 = lat1;
      var lon2 = lon3;
      var lat4 = lat3;
      var lon4 = lon1;

      // Get the documents collection
      var images = db.collection("images");

      // Find all images within the area
      images.find({
        loc: {
          $geoWithin: {
            $polygon: [ [ lat1, lon1 ],
                        [ lat2, lon2 ],
                        [ lat3, lon3 ],
                        [ lat4, lon4 ],
                        [ lat1, lon1 ] ]
          }
        }
      }).toArray(function (err, result) {
      if (err) {
          console.log(err);
          res.send([]);
        } else {
          console.log('Found:', result);
        var images = [];
        for (var i = 0; i < result.length; i++) {
          images[i] = {};
          images[i].comment = result[i].comment;
          images[i].loc = result[i].loc;
          images[i].image = fs.readFileSync(path.join(__dirname, result[i].path));
        }
        res.status(200).send(images);
        res.end();
        }
      });

      //Close the database connection
      db.close();
    }
  });

});

//:lat1/:lon1/:lat3/:lon3
router.get('/getImagesLocation/:lat1/:lon1/:lat3/:lon3', function(req, res) {
	// Get a Mongo client to work with the Mongo server
  var MongoClient = mongodb.MongoClient;

  // Define where the MongoDB server is
  var url = 'mongodb://<dbuser>:<dbpassword>@ds117209.mlab.com:17209/image_database';

  // Connect to the server
  MongoClient.connect(url, function (err, db) {
    if (err) {
      console.log('Unable to connect to the Database Server', err);
    } else {
      // We are connected
      console.log('Connection established to', url);

      // Cast all parametters into integers
      var lat1 = parseFloat(req.params.lat1);
      var lon1 = parseFloat(req.params.lon1);
      var lat3 = parseFloat(req.params.lat3);
      var lon3 = parseFloat(req.params.lon3);
      var lat2 = lat1;
      var lon2 = lon3;
      var lat4 = lat3;
      var lon4 = lon1;

      // Get the documents collection
      var images = db.collection("images");

      // Find all images within the area
      images.find({
        loc: {
          $geoWithin: {
            $polygon: [ [ lat1, lon1 ],
                        [ lat2, lon2 ],
                        [ lat3, lon3 ],
                        [ lat4, lon4 ],
                        [ lat1, lon1 ] ]
          }
        }
      }).toArray(function (err, result) {
      if (err) {
          console.log(err);
          res.send([]);
        } else {
          console.log('Found:', result);
        var images = [];
        for (var i = 0; i < result.length; i++) {
          images[i] = {};
          images[i].id = result[i].id;
          images[i].loc = result[i].loc;
        }
        res.status(200).send(images);
        res.end();
        }
      });

      //Close the database connection
      db.close();
    }
  });

});

router.post('/uploadImage', function(req, res) {
  // Get a Mongo client to work with the Mongo server
  var MongoClient = mongodb.MongoClient;

  // Define where the MongoDB server is
  var url = 'mongodb://<dbuser>:<dbpassword>@ds117209.mlab.com:17209/image_database';

  // Connect to the server
  MongoClient.connect(url, function (err, db) {
  if (err) {
    console.log('Unable to connect to the Database Server', err);
  } else {
      console.log('Connection established to', url);
      var images = db.collection("images");
      images.count({}, function( err, count){
        var number = count.toString();
        var location = path.join('uploads','image' + number + '.jpeg');
        var imagepath = path.join(__dirname, location);
        var entry = {};
        entry.comment = req.headers.comment;
        entry.loc = [parseFloat(req.headers.latitude),parseFloat(req.headers.longitude)];
        entry.path = location;
        images.insert(entry);

        if (req.method == "POST") {
          var data = [];
          req.on("data", function(chunk) {
            data.push(chunk);
          });
          req.on("end", function() {
            var towrite = Buffer.concat(data);
            console.log("Received posted data: " + data);
            fs.writeFile(imagepath, towrite, function (err) {
              if(err){
                console.log("Problem saving image");
              }else {
                console.log("Image Saved on server");
              }
            });

          });
        } else {
          console.dir(request);
        }

        db.close();
      });
    }
  });
});

module.exports = router;
<|endoftext|>