<commit_before>/* exported sendImpToThirdParty, adReachability */
// MARK: - Test Checking The Impression Tracking
function sendImpToThirdParty(Imp, AdName, AssID) {
    if (typeof Imp === 'string') {
        var asRandom = 'IMG' + Math.round(Math.random() * 1000000000000);
        var timestamp = new Date().getTime();
        var ImpNew = Imp;
        if (ImpNew.indexOf('?') < 0) {
            ImpNew += '?';
        }
        ImpNew = ImpNew.replace('ord=[timestamp]', 'ord=' + timestamp) + '&' + asRandom + '&ftctime=' + timestamp;
        ImpNew = ImpNew.replace('http://ad.doubleclick.net', 'https://ad.doubleclick.net');
        if (typeof window.parent.gTrackThirdParyImpression !== 'object') {
            window.parent.gTrackThirdParyImpression = {};
        }
        window.parent.gTrackThirdParyImpression[asRandom] = new Image();
        window.parent.gTrackThirdParyImpression[asRandom].src = ImpNew;
        window.parent.gTrackThirdParyImpression[asRandom].title = AdName + ' (' + AssID + ')';
        window.parent.gTrackThirdParyImpression[asRandom].alt = Imp;

        window.parent.gTrackThirdParyImpression[asRandom].onload = function() {
            window.parent.ga('send', 'event', this.title, 'Success', this.alt, {
                'nonInteraction': 1
            });
            delete window.parent.gTrackThirdParyImpression[asRandom];
        };

        window.parent.gTrackThirdParyImpression[asRandom].onerror = function() {
            window.parent.ga('send', 'event', this.title, 'Fail', this.alt, {'nonInteraction': 1});
            window.parent.ga('send', 'event', 'Fail UA String', AssID, window.parent.adReachability(), {'nonInteraction': 1});
            if (typeof window.uaString === 'string') {
                //MAKR: Baidu Analytics
                try {
                  window.parent._hmt.push(['_trackEvent',this.title, 'Fail', window.uaString]);
                } catch (ignore) {

                }
                //window.parent.ga('send', 'event', 'Fail UA String', AssID, window.uaString, {'nonInteraction': 1});
            }
            var asRandom2 = 'IMG' + Math.round(Math.random() * 1000000000000);
            ImpNew = ImpNew.replace('https://', 'http://');
            window.parent.gTrackThirdParyImpression[asRandom2] = new Image();
            window.parent.gTrackThirdParyImpression[asRandom2].src = ImpNew;
            window.parent.gTrackThirdParyImpression[asRandom2].title = this.title;
            window.parent.gTrackThirdParyImpression[asRandom2].alt = this.alt;
            window.parent.gTrackThirdParyImpression[asRandom2].onload = function() {
                window.parent.ga('send', 'event', this.title, 'Success on Retry', this.alt, {
                    'nonInteraction': 1
                });
                delete window.parent.gTrackThirdParyImpression[asRandom2];
            };
            window.parent.gTrackThirdParyImpression[asRandom2].onerror = function() {
                window.parent.ga('send', 'event', this.title, 'Fail on Retry', this.alt, {
                    'nonInteraction': 1
                });
            };
            delete window.parent.gTrackThirdParyImpression[asRandom];
        };

        window.parent.ga('send', 'event', AdName + ' (' + AssID + ')', 'Request', Imp, {
            'nonInteraction': 1
        });
    }
}

function adReachability() {
  var thirdPartyVendors = {
    'dcR': '_dc',
    'mmR': '_mm',
    'szR': '_sz',
    'amR': '_am'
  };
  var adParameter = '';
  var adReachabilityStatus;
  for (var k in thirdPartyVendors) {
      if (thirdPartyVendors.hasOwnProperty(k)) {
         //user[k] = data[k];
         //console.log (k + ': ' + thirdPartyVendors[k]);
         try {
             if (typeof window.GetCookie === 'function') {
                adReachabilityStatus = GetCookie(k);
             } else {
                adReachabilityStatus = getCookie(k);
             }
         } catch(ignore) {
            adReachabilityStatus = null;
         }

         if (adReachabilityStatus === 'reachable') {
          adParameter += '&' + thirdPartyVendors[k] + '=1';
         } else if (window.gIsSpider === true && (k === 'dcR' || k === 'amR')) {
          // MARK: - If it's spam. Don't use DoubleClick and AdMaster to serve
          adParameter += '&' + thirdPartyVendors[k] + '=0';
         } else if (adReachabilityStatus === null) {
          adParameter += '&' + thirdPartyVendors[k] + '=2';
         }
      }
  }
  if (typeof window.gUserType !== 'string') {
    window.gUserType = 'visitor';
  }
  adParameter += '&' + '_ut=' + window.gUserType;
  //console.log (adParameter);
  return adParameter;
}
<commit_msg>Add 5 times retry<commit_after>/* exported sendImpToThirdParty, adReachability */
// MARK: - Test Checking The Impression Tracking
function sendImpToThirdParty(Imp, AdName, AssID) {
    if (typeof Imp === 'string') {

        if (typeof window.parent.gTrackThirdParyImpression !== 'object') {
            window.parent.gTrackThirdParyImpression = {};
        }
        var reRryTimes = 0;

        var sendOnetime = function() {
            var asRandom = 'IMG' + Math.round(Math.random() * 1000000000000);
            var timestamp = new Date().getTime();
            var ImpNew = Imp;
            if (ImpNew.indexOf('?') < 0) {
                ImpNew += '?';
            }
            ImpNew = ImpNew.replace('ord=[timestamp]', 'ord=' + timestamp) + '&' + asRandom + '&ftctime=' + timestamp;
            ImpNew = ImpNew.replace('http://ad.doubleclick.net', 'https://ad.doubleclick.net');

            window.parent.gTrackThirdParyImpression[asRandom] = new Image();
            window.parent.gTrackThirdParyImpression[asRandom].src = ImpNew;
            window.parent.gTrackThirdParyImpression[asRandom].title = AdName + ' (' + AssID + ')';
            window.parent.gTrackThirdParyImpression[asRandom].alt = Imp;

            window.parent.gTrackThirdParyImpression[asRandom].onload = function() {
                window.parent.ga('send', 'event', this.title, 'Success'+reRryTimes, this.alt, {
                    'nonInteraction': 1
                });
                delete window.parent.gTrackThirdParyImpression[asRandom];
            };

            window.parent.gTrackThirdParyImpression[asRandom].onerror = function() {
                window.parent.ga('send', 'event', this.title, 'Fail'+reRryTimes, this.alt, {'nonInteraction': 1});
                window.parent.ga('send', 'event', 'Fail UA String', AssID, window.parent.adReachability(), {'nonInteraction': 1});

                if (typeof window.uaString === 'string') {
                    //MAKR: Baidu Analytics
                    try {
                    window.parent._hmt.push(['_trackEvent',this.title, 'Fail', window.uaString]);
                    } catch (ignore) {

                    }
                    //window.parent.ga('send', 'event', 'Fail UA String', AssID, window.uaString, {'nonInteraction': 1});
                }
                reRryTimes++;
                if (reRryTimes < 5) {
                     sendOnetime();
                }

            }
        }
        sendOnetime();
        /*
            window.parent.gTrackThirdParyImpression[asRandom].onerror = function() {
                window.parent.ga('send', 'event', this.title, 'Fail', this.alt, {'nonInteraction': 1});
                window.parent.ga('send', 'event', 'Fail UA String', AssID, window.parent.adReachability(), {'nonInteraction': 1});
                if (typeof window.uaString === 'string') {
                    //MAKR: Baidu Analytics
                    try {
                    window.parent._hmt.push(['_trackEvent',this.title, 'Fail', window.uaString]);
                    } catch (ignore) {

                    }
                    //window.parent.ga('send', 'event', 'Fail UA String', AssID, window.uaString, {'nonInteraction': 1});
                }
                var asRandom2 = 'IMG' + Math.round(Math.random() * 1000000000000);
                ImpNew = ImpNew.replace('https://', 'http://');
                window.parent.gTrackThirdParyImpression[asRandom2] = new Image();
                window.parent.gTrackThirdParyImpression[asRandom2].src = ImpNew;
                window.parent.gTrackThirdParyImpression[asRandom2].title = this.title;
                window.parent.gTrackThirdParyImpression[asRandom2].alt = this.alt;
                window.parent.gTrackThirdParyImpression[asRandom2].onload = function() {
                    window.parent.ga('send', 'event', this.title, 'Success on Retry', this.alt, {
                        'nonInteraction': 1
                    });
                    delete window.parent.gTrackThirdParyImpression[asRandom2];
                };
                window.parent.gTrackThirdParyImpression[asRandom2].onerror = function() {
                    window.parent.ga('send', 'event', this.title, 'Fail on Retry', this.alt, {
                        'nonInteraction': 1
                    });
                };
                delete window.parent.gTrackThirdParyImpression[asRandom];
            };
        */
        window.parent.ga('send', 'event', AdName + ' (' + AssID + ')', 'Request', Imp, {
            'nonInteraction': 1
        });
    }
}

function adReachability() {
  var thirdPartyVendors = {
    'dcR': '_dc',
    'mmR': '_mm',
    'szR': '_sz',
    'amR': '_am'
  };
  var adParameter = '';
  var adReachabilityStatus;
  for (var k in thirdPartyVendors) {
      if (thirdPartyVendors.hasOwnProperty(k)) {
         //user[k] = data[k];
         //console.log (k + ': ' + thirdPartyVendors[k]);
         try {
             if (typeof window.GetCookie === 'function') {
                adReachabilityStatus = GetCookie(k);
             } else {
                adReachabilityStatus = getCookie(k);
             }
         } catch(ignore) {
            adReachabilityStatus = null;
         }

         if (adReachabilityStatus === 'reachable') {
          adParameter += '&' + thirdPartyVendors[k] + '=1';
         } else if (window.gIsSpider === true && (k === 'dcR' || k === 'amR')) {
          // MARK: - If it's spam. Don't use DoubleClick and AdMaster to serve
          adParameter += '&' + thirdPartyVendors[k] + '=0';
         } else if (adReachabilityStatus === null) {
          adParameter += '&' + thirdPartyVendors[k] + '=2';
         }
      }
  }
  if (typeof window.gUserType !== 'string') {
    window.gUserType = 'visitor';
  }
  adParameter += '&' + '_ut=' + window.gUserType;
  //console.log (adParameter);
  return adParameter;
}
<|endoftext|>


<commit_before>'use strict';

/* Controllers */

var controllers = angular.module('myApp.controllers', []);

controllers.controller('ChatController', ["$scope", 'socket', function($scope, socket) {
    $scope.chatInProgress = false;
    $scope.searching = true;
    $scope.transcript = [];
    $scope.inputText = "";
    socket.emit('new', null);

    socket.on('leave', function() {
        $scope.chatInProgress = false;
        socket.emit('leave', null);
    });

    socket.on('msg', function(data) {
        $scope.transcript.push({
            "participant": "Stranger",
            "txt": data
        });
    });

    socket.on('new', function() {
        $scope.chatInProgress = true;
        $scope.searching = false;
    });

    $scope.stopChat = function() {
        $scope.chatInProgress = false;
        $scope.transcript = [];
        socket.emit('leave', null);
    };

    $scope.sendMsg = function() {
        $scope.transcript.push({
            "participant": "You",
            "txt": $scope.inputText
        });
        socket.emit('msg', $scope.inputText);
        $scope.inputText = "";
    };

    $scope.keydown = function($event) {
        if ($event.keyCode == 13) {
            $scope.sendMsg();
        }
    };

    $scope.findNewPartner = function() {
        $scope.transcript = [];
        $scope.searching = true;
        socket.emit('new', null);
    };
}]);<commit_msg>Preventing default behavior for keypress<commit_after>'use strict';

/* Controllers */

var controllers = angular.module('myApp.controllers', []);

controllers.controller('ChatController', ["$scope", 'socket', function($scope, socket) {
    $scope.chatInProgress = false;
    $scope.searching = true;
    $scope.transcript = [];
    $scope.inputText = "";
    socket.emit('new', null);

    socket.on('leave', function() {
        $scope.chatInProgress = false;
        socket.emit('leave', null);
    });

    socket.on('msg', function(data) {
        $scope.transcript.push({
            "participant": "Stranger",
            "txt": data
        });
    });

    socket.on('new', function() {
        $scope.chatInProgress = true;
        $scope.searching = false;
    });

    $scope.stopChat = function() {
        $scope.chatInProgress = false;
        $scope.transcript = [];
        socket.emit('leave', null);
    };

    $scope.sendMsg = function() {
        $scope.transcript.push({
            "participant": "You",
            "txt": $scope.inputText
        });
        socket.emit('msg', $scope.inputText);
        $scope.inputText = "";
    };

    $scope.keydown = function($event) {
        if ($event.keyCode == 13) {
            $event.preventDefault();
            $scope.sendMsg();
        }
    };

    $scope.findNewPartner = function() {
        $scope.transcript = [];
        $scope.searching = true;
        socket.emit('new', null);
    };
}]);<|endoftext|>


<commit_before>import {throttle} from "lodash"
import {ImageCapture} from "../ImageCapture"
import React, { Component } from 'react'
import Slider from 'material-ui/Slider';

import Message from './message'
import Devices from './devices'
import Shutter from './shutter'
import CaptureButton from './captureButton'

const shutterSound = new Audio("./camera-shutter-click-01.wav")
const MAX_SCALE = 10
const MIN_SCALE = 1
const ZOOM_INCREMENT = .25

const cameraControlStyle = {
    width : 150,
    backgroundColor:"black"
}

export default class Camera extends Component {

    constructor(props) {

        super(props)

        this.canvas = document.createElement('canvas')

        this.canvas2dContext = this.canvas.getContext('2d')

        this.msgSpan = null;
        this.video = null;
        this.state = {
            scale: this.validateScale(this.props.scale),
            showDevices: this.props.showDevices,
            devices: [],
            selectedDeviceId: null,
            width: this.props.style.width - cameraControlStyle.width,
            height: this.props.style.height,
            emulation: this.props.emulation,
            emulationSrc : this.props.emulationSrc,
            isCapturing: false

        } // using react state to track ui state; should stay here even after introducing redux?

        this._onCapture = throttle(this._onCapture.bind(this), 1000)
        this._onError = this._onError.bind(this)

        this.changeDevice = this.changeDevice.bind(this)
        this.zoomIn = this.zoomIn.bind(this)
        this.zoomOut = this.zoomOut.bind(this)
        this.zoomChange = this.zoomChange.bind(this)

    }

    componentDidMount() {
        this.init();
    }
    componentWillReceiveProps(props) {
        if (this.video && this.video.videoHeight > 0) {
            let dimension = this.adjustAspectRatio(this.video.videoWidth, this.video.videoHeight, props.style.width)
            this.setState(dimension)
        }

    }
    componentWillMount() {
        this.getDeviceList()

    }
    render() {

        let cameraStyle = {
            width: this.state.width,
            height: this.state.height,
            overflow: "hidden",
            display: "flex",
            position: "relative",
            backgroundColor: "black"
        }

        let videoStyle = Object.assign({}, {
            position: "absolute",
            margin: 'auto',
            top: '50%',
            left: '50%'
        }, { WebkitTransform: "translate(-50%,-50%)scale(" + this.state.scale + ")", width: this.state.width, height: this.state.height })

        let sliderValue = (this.state.scale - MIN_SCALE) / (this.props.maxScale - MIN_SCALE)
        let sliderHeight = (this.state.height - 80)

        return (

                            <video style={videoStyle}
                                ref={vid => { this.video = vid }}

                            />

                            {
                                this.state.showDevices && <Devices devices={this.state.devices} style={{ margin: 20 }} onClick={this.changeDevice} />
                            }

                                {this.state.emulation && <Message msg="Emulation Mode" permanent={true} />}
                                <Message msg={Math.round(this.state.scale * 100) / 100 + "X"} />

                            <Shutter display={this.state.isCapturing} style={{ width: this.state.width, height: this.state.height }} />

                                <CaptureButton onClick={this._onCapture}/>

                                    <button onClick={this.zoomIn}>+</button>
                                    <Slider style={{ height: sliderHeight, marginTop: 10, marginBottom: 10, display: "flex", justifyContent: "center" }} sliderStyle={{ marginTop: 0, marginBottom: 0 }} axis="y" value={sliderValue} defaultValue={sliderValue} onChange={this.zoomChange} />
                                    <button onClick={this.zoomOut}>-</button>

        )
    }

    _onCapture(e) {

        let ctx = this;

        //calculate image dimension based on scale

        let dx = (this.video.videoWidth / this.state.scale)
        let dy = (this.video.videoHeight / this.state.scale)

        let x1 = (this.video.videoWidth - dx) / 2;
        let y1 = (this.video.videoHeight - dy) / 2;

        this.canvas2dContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.canvas2dContext.drawImage(this.video, x1, y1, dx, dy, 0, 0, this.canvas.width, this.canvas.height)

        let img = this.canvas.toDataURL('image/png');

        this.setState({ isCapturing: true }, () => {

            if (ctx.props.onCapture) {
                ctx.props.onCapture(e, img)
            }

            if ("vibrate" in navigator) {
                navigator.vibrate(100)
            }
            shutterSound.play().then(() => {
                this.setState({ isCapturing: false })
            })

        })
    }

    _onError(err){
        if(this.props.onError){
            this.props.onError(err)
        }
        else{
            console.error(err)
        }
    }

    zoomIn() {
        let currentScale = this.state.scale
        let newScale = currentScale + ZOOM_INCREMENT;
        if (newScale > this.props.maxScale) {
            newScale = this.props.maxScale;
        }
        this.setState({ scale: this.validateScale(newScale) })

    }
    zoomOut() {

        let currentScale = this.state.scale
        let newScale = currentScale - ZOOM_INCREMENT;
        if (newScale < MIN_SCALE) {
            newScale = MIN_SCALE;
        }
        this.setState({ scale: this.validateScale(newScale) })
    }

    zoomChange(e, newValue) {

        let newScale = MIN_SCALE + (newValue) * (this.props.maxScale - MIN_SCALE)

        this.setState({ scale: this.validateScale(newScale) })
    }

    validateScale(scale) {
        let newScale = MIN_SCALE;

        if (scale) {
            if (scale < MIN_SCALE) {
                newScale = MIN_SCALE;
            }
            else if (scale > this.props.maxScale) {
                newScale = this.props.maxScale
            }
            else {
                newScale = scale;
            }
        }

        return newScale;
    }

    adjustAspectRatio(videoWidth, videoHeight, width) {
        let dimension = { height: width * videoHeight / videoWidth, width }
        return dimension
    }

    setCanvasDimension(videoWidth, videoHeight, width) {
        this.canvas.width = videoWidth
        this.canvas.height = videoHeight
    }

    getDeviceList(){

        let ctx = this

        let deviceList = null;
        let filter = (item) => { return ( item.kind == "video" || item.kind =="videoinput");};
        let sort = (a,b) => {

            let labelA = (a.label || "").toLowerCase()
            let labelB = (b.label || "").toLowerCase()

            let isARearCamera = ( labelA.indexOf("rear") >= 0 )
            let isBRearCamera = ( labelB.indexOf("rear") >= 0 )

            let returnVal = 0

            if( isARearCamera == isBRearCamera ){
                returnVal = ( labelA < labelB ) ? -1 : ( (labelA > labelB) ? 1 : 0 )
            }
            else if ( isARearCamera && !isBRearCamera ) {
                returnVal = 1
            }
            else {
                returnVal = -1
            }
            return returnVal
        }
        let handleDeviceReceived = (sourceList) => {
            deviceList = sourceList || []
            deviceList = deviceList.filter( filter )
            deviceList = deviceList.sort( sort )
            ctx.deviceReceived(deviceList) //update device list
        }
        try{
            if (navigator.mediaDevices.enumerateDevices){
                navigator.mediaDevices.enumerateDevices().then( handleDeviceReceived ).catch(ctx._onError)
            }
            else if(MediaStreamTrack && MediaStreamTrack.getSources ) {
                MediaStreamTrack.getSources( handleDeviceReceived, ctx._onError );
            }
        }
        catch(err){
            this._onError(err)
        }

    }
    changeDevice(sourceId) {

        let ctx = this;
         //override device
        if(sourceId){

            if( sourceId == 1 ){
                //emulation
                this.setState({emulation:true},()=>{
                    ctx.getUserMedia()
                })
            }
            else{
                this.setState({emulation:false},()=>{
                    let constraints = {
                        audio: false,
                        video : {
                            optional: [{sourceId}]
                        }
                    }
                    ctx.getUserMedia(constraints)
                })
            }
        }
    }

    handleStreamReceived(constraints,stream) {
        let videoTracks = null;
        let video = this.video;
        let ctx = this;

        if(stream && stream.getVideoTracks){
            videoTracks = stream.getVideoTracks();

            if(videoTracks.length > 0 && videoTracks[0].getCapabilities ){
                console.log(videoTracks[0].label)
                let capabilities = videoTracks[0].getCapabilities();

                if(capabilities.zoom){
                    console.log("hardware zoom supportd")
                }
                if (capabilities.focusDistance){
                    console.log("focus supportd")
                }

                if (typeof ImageCapture !== 'undefined'){
                    try{
                        //experimental
                        console.log("ImageCapture supported")
                        let imageCapture = new ImageCapture(videoTracks[0])

                        let photoCapabilities = imageCapture.getPhotoCapabilities().then(c =>{
                            console.dir(c)
                        })
                        if(navigator.mediaDevices.getSupportedConstraints){
                            debugger
                            let c = navigator.mediaDevices.getSupportedConstraints();
                            console.dir(c)
                        }

                    }
                    catch(err){

                    }

                }

            }

        }

        if( this.state.emulation ){
            //emulation?

            //stop existing videotracks
            if(video.srcObject){
                video.srcObject.getVideoTracks().forEach(track=>track.stop())
                video.srcObject = null;
            }

            video.src = this.state.emulationSrc;
            video.muted = true
            if (typeof video.loop == 'boolean') {
                // loop supported
                video.loop = true;
            }
        }
        else if( stream instanceof MediaStream){
            video.src = null;
            video.srcObject = stream
        }
        else{

            //this should not reach, but just in case..
            this.setState({emulation:true})
            //emulation?
            video.srcObject = null;
            video.src = this.state.emulationSrc;
            video.muted = true
            if (typeof video.loop == 'boolean') {
                // loop supported
                video.loop = true;
            }
        }

        video.onloadedmetadata = (e) => {

            video.play().then(()=>{
                ctx.setCanvasDimension(video.videoWidth, video.videoHeight)
                let dimension = ctx.adjustAspectRatio(video.videoWidth, video.videoHeight,ctx.state.width)
                ctx.setState(dimension)
            }).catch(ctx._onError)
        }
        video.onabort = (e) => {
            console.log("video aborted", e)
        }
        video.onactivate = (e) => {
            console.log("video actived", e)
        }
        video.onclose = e => {
            console.log("video closed",e)
        }
        video.onerror = (e) => {
            this._onError(e)
        }

        if(stream){
            stream.oninactive = e => {
                console.log('Stream inactive',e);
            };
            stream.onactive = (e)=> {
                console.log("Stream active", e)
            }
            stream.oneded = e => {
                console.log("Stream ended",e)
            }
        }

    }

    deviceReceived(devices) {

        let deviceList = devices || []

        if(!deviceList.find(item=>{item.kind=="emulation"}) ) {
            deviceList.push(this.getEmulationDeviceInfo())
        }

        this.setState({ devices: deviceList })
    }

    loadDefaultDevice() {

        let constraints = {
            audio: false,
            video: { width: 1920, height: 1080, facingMode: "environment" },

        }

        if ( this.state.devices.length > 0 ){

            constraints.video = Object.assign( {} , constraints.video , {optional: [{sourceId: this.state.devices[0].deviceId}] }  )
        }

        this.getUserMedia(constraints)

    }

    getUserMedia(constraints){

        if (!constraints){
            constraints = {
                audio: false,
                video: { facingMode: "environment", width: 1920, height: 1080 }
            }
        }

        try {
            let getUserMedia = null;
            let ctx = null;

            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                getUserMedia = navigator.mediaDevices.getUserMedia;
                ctx = navigator.mediaDevices;
            }
            else if (navigator.getUserMedia) {
                getUserMedia = navigator.getUserMedia
                ctx = navigator;
            }
            else if (navigator.webkitGetUserMedia) {
                getUserMedia = navigator.webkitGetUserMedia
                ctx = navigator
            }
            else {
                getUserMedia = this.getUserMediaEmulation;
                ctx = this
            }
            //manually set the context to wherever the function belongs to, otherwise will get illegal invcation error
            return getUserMedia.call(ctx, constraints).then(this.handleStreamReceived.bind(this,constraints)).catch(this._onError);

        }
        catch (ex) {
            this._onError(ex)
        }
    }

    getEmulationDeviceInfo (){
        return {
            id : 1,
            deviceId: 1,
            label: "emulation",
            kind : "emulation",
            emulation : true,
            selected : false
        }
    }

    getUserMediaEmulation() {

        return new Promise( (resolve,reject)=>{
            this.setState({emulation:true},()=>{

                resolve(false);//no MediaStream
            })
        })
    }

    init() {
        this.loadDefaultDevice();
    }

}

//https://toddmotto.com/react-create-class-versus-component/
Camera.defaultProps = {

    scale: 1,

    emulation: false,
    emulationSrc : null,
    showDevices: true,

    maxScale: MAX_SCALE,

    style: {
        width: 480,
        height: 360
    },

    onCapture: null,
    onError : null
};<commit_msg>changed default device negotiation<commit_after>import { throttle } from "lodash"
import { ImageCapture } from "../ImageCapture"
import React, { Component } from 'react'
import Slider from 'material-ui/Slider';

import Message from './message'
import Devices from './devices'
import Shutter from './shutter'
import CaptureButton from './captureButton'

const shutterSound = new Audio("./camera-shutter-click-01.wav")
const MAX_SCALE = 10
const MIN_SCALE = 1
const ZOOM_INCREMENT = .25

const cameraControlStyle = {
    width: 150,
    backgroundColor: "black"
}

export default class Camera extends Component {

    constructor(props) {

        super(props)

        this.canvas = document.createElement('canvas')

        this.canvas2dContext = this.canvas.getContext('2d')

        this.msgSpan = null;
        this.video = null;
        this.state = {
            scale: this.validateScale(this.props.scale),
            showDevices: this.props.showDevices,
            devices: [],
            selectedDeviceId: null,
            width: this.props.style.width - cameraControlStyle.width,
            height: this.props.style.height,
            emulation: this.props.emulation,
            emulationSrc: this.props.emulationSrc,
            isCapturing: false

        } // using react state to track ui state; should stay here even after introducing redux?

        this._onCapture = throttle(this._onCapture.bind(this), 1000)
        this._onError = this._onError.bind(this)

        this.changeDevice = this.changeDevice.bind(this)
        this.zoomIn = this.zoomIn.bind(this)
        this.zoomOut = this.zoomOut.bind(this)
        this.zoomChange = this.zoomChange.bind(this)

    }

    componentDidMount() {
        this.init();
    }
    componentWillReceiveProps(props) {
        if (this.video && this.video.videoHeight > 0) {
            let dimension = this.adjustAspectRatio(this.video.videoWidth, this.video.videoHeight, props.style.width)
            this.setState(dimension)
        }

    }
    componentWillMount() {
        this.getDeviceList((deviceList=>{
            this.setState({ devices: deviceList || [] })
        }))

    }
    render() {

        let cameraStyle = {
            width: this.state.width,
            height: this.state.height,
            overflow: "hidden",
            display: "flex",
            position: "relative",
            backgroundColor: "black"
        }

        let videoStyle = Object.assign({}, {
            position: "absolute",
            margin: 'auto',
            top: '50%',
            left: '50%'
        }, { WebkitTransform: "translate(-50%,-50%)scale(" + this.state.scale + ")", width: this.state.width, height: this.state.height })

        let sliderValue = (this.state.scale - MIN_SCALE) / (this.props.maxScale - MIN_SCALE)
        let sliderHeight = (this.state.height - 80)

        return (

                            <video style={videoStyle}
                                ref={vid => { this.video = vid }}

                            />

                            {
                                this.state.showDevices && <Devices devices={this.state.devices} style={{ margin: 20 }} onClick={this.changeDevice} />
                            }

                                {this.state.emulation && <Message msg="Emulation Mode" permanent={true} />}
                                <Message msg={Math.round(this.state.scale * 100) / 100 + "X"} />

                            <Shutter display={this.state.isCapturing} style={{ width: this.state.width, height: this.state.height }} />

                            <CaptureButton onClick={this._onCapture} />

                                <button onClick={this.zoomIn}>+</button>
                                <Slider style={{ height: sliderHeight, marginTop: 10, marginBottom: 10, display: "flex", justifyContent: "center" }} sliderStyle={{ marginTop: 0, marginBottom: 0 }} axis="y" value={sliderValue} defaultValue={sliderValue} onChange={this.zoomChange} />
                                <button onClick={this.zoomOut}>-</button>

        )
    }

    _onCapture(e) {

        let ctx = this;

        //calculate image dimension based on scale

        let dx = (this.video.videoWidth / this.state.scale)
        let dy = (this.video.videoHeight / this.state.scale)

        let x1 = (this.video.videoWidth - dx) / 2;
        let y1 = (this.video.videoHeight - dy) / 2;

        this.canvas2dContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
        this.canvas2dContext.drawImage(this.video, x1, y1, dx, dy, 0, 0, this.canvas.width, this.canvas.height)

        let img = this.canvas.toDataURL('image/png');

        this.setState({ isCapturing: true }, () => {

            if (ctx.props.onCapture) {
                ctx.props.onCapture(e, img)
            }

            if ("vibrate" in navigator) {
                navigator.vibrate(100)
            }
            shutterSound.play().then(() => {
                this.setState({ isCapturing: false })
            })

        })
    }

    _onError(err) {
        if (this.props.onError) {
            this.props.onError(err)
        }
        else {
            console.error(err)
        }
    }

    zoomIn() {
        let currentScale = this.state.scale
        let newScale = currentScale + ZOOM_INCREMENT;
        if (newScale > this.props.maxScale) {
            newScale = this.props.maxScale;
        }
        this.setState({ scale: this.validateScale(newScale) })

    }
    zoomOut() {

        let currentScale = this.state.scale
        let newScale = currentScale - ZOOM_INCREMENT;
        if (newScale < MIN_SCALE) {
            newScale = MIN_SCALE;
        }
        this.setState({ scale: this.validateScale(newScale) })
    }

    zoomChange(e, newValue) {

        let newScale = MIN_SCALE + (newValue) * (this.props.maxScale - MIN_SCALE)

        this.setState({ scale: this.validateScale(newScale) })
    }

    validateScale(scale) {
        let newScale = MIN_SCALE;

        if (scale) {
            if (scale < MIN_SCALE) {
                newScale = MIN_SCALE;
            }
            else if (scale > this.props.maxScale) {
                newScale = this.props.maxScale
            }
            else {
                newScale = scale;
            }
        }

        return newScale;
    }

    adjustAspectRatio(videoWidth, videoHeight, width) {
        let dimension = { height: width * videoHeight / videoWidth, width }
        return dimension
    }

    setCanvasDimension(videoWidth, videoHeight, width) {
        this.canvas.width = videoWidth
        this.canvas.height = videoHeight
    }

    getDeviceList(callback) {

        let ctx = this

        let deviceList = null;
        let filter = (item) => { return (item.kind == "video" || item.kind == "videoinput"); };
        let sort = (a, b) => {

            let labelA = (a.label || "").toLowerCase()
            let labelB = (b.label || "").toLowerCase()

            let isARearCamera = (labelA.indexOf("rear") >= 0)
            let isBRearCamera = (labelB.indexOf("rear") >= 0)

            let returnVal = 0

            if (isARearCamera == isBRearCamera) {
                returnVal = (labelA < labelB) ? -1 : ((labelA > labelB) ? 1 : 0)
            }
            else if (isARearCamera && !isBRearCamera) {
                returnVal = 1
            }
            else {
                returnVal = -1
            }
            return returnVal
        }

        let handleDeviceReceived = (sourceList) => {
            deviceList = sourceList || []
            deviceList = deviceList.filter(filter)
            deviceList = deviceList.sort(sort)

            if (!deviceList.find(item => { item.kind == "emulation" })) {
                deviceList.push(this.getEmulationDeviceInfo())
            }

            if( callback ){
                callback(deviceList)
            }

        }
        try {
            if (navigator.mediaDevices.enumerateDevices) {
                navigator.mediaDevices.enumerateDevices().then(handleDeviceReceived).catch(ctx._onError)
            }
            else if (MediaStreamTrack && MediaStreamTrack.getSources) {
                MediaStreamTrack.getSources(handleDeviceReceived, ctx._onError);
            }
        }
        catch (err) {
            this._onError(err)
        }

    }

    changeDevice(sourceId) {

        let ctx = this;
        //override device
        if (sourceId) {

            if (sourceId == 1) {
                //emulation
                this.setState({ emulation: true }, () => {
                    ctx.getUserMedia()
                })
            }
            else {
                this.setState({ emulation: false }, () => {
                    let constraints = {
                        audio: false,
                        video: {
                            optional: [{ sourceId }]
                        }
                    }
                    ctx.getUserMedia(constraints)
                })
            }
        }
    }

    handleStreamReceived(constraints, stream) {
        let videoTracks = null;
        let video = this.video;
        let ctx = this;

        if (stream && stream.getVideoTracks) {
            videoTracks = stream.getVideoTracks();

            if (videoTracks.length > 0 && videoTracks[0].getCapabilities) {
                console.log(videoTracks[0].label)
                let capabilities = videoTracks[0].getCapabilities();

                if (capabilities.zoom) {
                    console.log("hardware zoom supportd")
                }
                if (capabilities.focusDistance) {
                    console.log("focus supportd")
                }

                if (typeof ImageCapture !== 'undefined') {
                    try {
                        //experimental
                        console.log("ImageCapture supported")
                        let imageCapture = new ImageCapture(videoTracks[0])

                        let photoCapabilities = imageCapture.getPhotoCapabilities().then(c => {
                            console.dir(c)
                        })
                        if (navigator.mediaDevices.getSupportedConstraints) {
                            debugger
                            let c = navigator.mediaDevices.getSupportedConstraints();
                            console.dir(c)
                        }

                    }
                    catch (err) {

                    }

                }

            }

        }

        if (this.state.emulation) {
            //emulation?

            //stop existing videotracks
            if (video.srcObject) {
                video.srcObject.getVideoTracks().forEach(track => track.stop())
                video.srcObject = null;
            }

            video.src = this.state.emulationSrc;
            video.muted = true
            if (typeof video.loop == 'boolean') {
                // loop supported
                video.loop = true;
            }
        }
        else if (stream instanceof MediaStream) {
            video.src = null;
            video.srcObject = stream
        }
        else {

            //this should not reach, but just in case..
            this.setState({ emulation: true })
            //emulation?
            video.srcObject = null;
            video.src = this.state.emulationSrc;
            video.muted = true
            if (typeof video.loop == 'boolean') {
                // loop supported
                video.loop = true;
            }
        }

        video.onloadedmetadata = (e) => {

            video.play().then(() => {
                ctx.setCanvasDimension(video.videoWidth, video.videoHeight)
                let dimension = ctx.adjustAspectRatio(video.videoWidth, video.videoHeight, ctx.state.width)
                ctx.setState(dimension)
            }).catch(ctx._onError)
        }
        video.onabort = (e) => {
            console.log("video aborted", e)
        }
        video.onactivate = (e) => {
            console.log("video actived", e)
        }
        video.onclose = e => {
            console.log("video closed", e)
        }
        video.onerror = (e) => {
            this._onError(e)
        }

        if (stream) {
            stream.oninactive = e => {
                console.log('Stream inactive', e);
            };
            stream.onactive = (e) => {
                console.log("Stream active", e)
            }
            stream.oneded = e => {
                console.log("Stream ended", e)
            }
        }

    }

    loadDefaultDevice() {

        let constraints = {
            audio: false,
            video: { width: 1920, height: 1080, facingMode: "environment" },

        }

        let ctx = this;

        this.getDeviceList(deviceList=>{
            debugger
            constraints.video = Object.assign({}, constraints.video, {   sourceId: deviceList[0].deviceId  })

            ctx.getUserMedia(constraints)
        })

    }

    getUserMedia(constraints) {

        if (!constraints) {
            constraints = {
                audio: false,
                video: { facingMode: "environment", width: 1920, height: 1080 }
            }
        }

        try {
            let getUserMedia = null;
            let ctx = null;

            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                getUserMedia = navigator.mediaDevices.getUserMedia;
                ctx = navigator.mediaDevices;
            }
            else if (navigator.getUserMedia) {
                getUserMedia = navigator.getUserMedia
                ctx = navigator;
            }
            else if (navigator.webkitGetUserMedia) {
                getUserMedia = navigator.webkitGetUserMedia
                ctx = navigator
            }
            else {
                getUserMedia = this.getUserMediaEmulation;
                ctx = this
            }
            //manually set the context to wherever the function belongs to, otherwise will get illegal invcation error
            return getUserMedia.call(ctx, constraints).then(this.handleStreamReceived.bind(this, constraints)).catch(this._onError);

        }
        catch (ex) {
            this._onError(ex)
        }
    }

    getEmulationDeviceInfo() {
        return {
            id: 1,
            deviceId: 1,
            label: "emulation",
            kind: "emulation",
            emulation: true,
            selected: false
        }
    }

    getUserMediaEmulation() {

        return new Promise((resolve, reject) => {
            this.setState({ emulation: true }, () => {

                resolve(false);//no MediaStream
            })
        })
    }

    init() {
        this.loadDefaultDevice();
    }

}

//https://toddmotto.com/react-create-class-versus-component/
Camera.defaultProps = {

    scale: 1,

    emulation: false,
    emulationSrc: null,
    showDevices: true,

    maxScale: MAX_SCALE,

    style: {
        width: 480,
        height: 360
    },

    onCapture: null,
    onError: null
};<|endoftext|>


<commit_before>'use strict';

const ASSERT = require('assert');
const MODULIZER = require('../');

describe('new Modulizer()', function() {

  it('should instantiate without errors, but with a logged warning.', function() {
    ASSERT.doesNotThrow(() => {
      let modulizer = new MODULIZER(__dirname + '/files');
    });
  });

});

describe('Modulizer.execute("test1")', function() {

  let modulizer = new MODULIZER(__dirname + '/files');

  it('should run without errors.', function() {
    ASSERT.doesNotThrow(() => {
      modulizer.execute('test1');
    });
  });

});

describe('Modulizer.executeAll()', function() {

  let modulizer = new MODULIZER(__dirname + '/files');

  it('should run without errors.', function() {
    ASSERT.doesNotThrow(() => {
      modulizer.executeAll();
    });
  });

});

describe('Modulizer.methodArray', function() {

  let modulizer = new MODULIZER(__dirname + '/files');

  it('should equal 1 since only one JavaScript file with a function export exists.', function() {
    ASSERT.equal(modulizer.methodArray.length, 1);;
  });

});

describe('Modulizer.methodObject', function() {

  let modulizer = new MODULIZER(__dirname + '/files');

  it('should exsist with "test1" as a property.', function() {
    ASSERT.ok(!!modulizer.methodObject['test1']);
  });

});
<commit_msg>remove trailing semi-colon.<commit_after>'use strict';

const ASSERT = require('assert');
const MODULIZER = require('../');

describe('new Modulizer()', function() {

  it('should instantiate without errors, but with a logged warning.', function() {
    ASSERT.doesNotThrow(() => {
      let modulizer = new MODULIZER(__dirname + '/files');
    });
  });

});

describe('Modulizer.execute("test1")', function() {

  let modulizer = new MODULIZER(__dirname + '/files');

  it('should run without errors.', function() {
    ASSERT.doesNotThrow(() => {
      modulizer.execute('test1');
    });
  });

});

describe('Modulizer.executeAll()', function() {

  let modulizer = new MODULIZER(__dirname + '/files');

  it('should run without errors.', function() {
    ASSERT.doesNotThrow(() => {
      modulizer.executeAll();
    });
  });

});

describe('Modulizer.methodArray', function() {

  let modulizer = new MODULIZER(__dirname + '/files');

  it('should equal 1 since only one JavaScript file with a function export exists.', function() {
    ASSERT.equal(modulizer.methodArray.length, 1);
  });

});

describe('Modulizer.methodObject', function() {

  let modulizer = new MODULIZER(__dirname + '/files');

  it('should exsist with "test1" as a property.', function() {
    ASSERT.ok(!!modulizer.methodObject['test1']);
  });

});
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

// Load Up our Native Module..
var {
    RNReverseGeo
} = require('NativeModules');

var RNReverseGeoDemo = React.createClass({

  componentDidMount: function() {
    RNReverseGeo.geoCodeAddress("370 Tompkins Ave, Brooklyn, NY 11216",
      function(_results){
        console.log(_results);
        this.setState({
          reverseGeoResults : JSON.stringify(_results)
        })
      });
  },

  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          {this.state.reverseGeoResults}
        </Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('RNReverseGeoDemo', () => RNReverseGeoDemo);
<commit_msg>Update index.ios.js<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

// Load Up our Native Module..
var {
    RNReverseGeo
} = require('NativeModules');

var RNReverseGeoDemo = React.createClass({

  getInitialState: function() {
    return {
      reverseGeoResults: "Loading..."
    };
  },

  componentDidMount: function() {
    var that = this;
    RNReverseGeo.geoCodeAddress("370 Tompkins Ave, Brooklyn, NY 11216",
      function(_results){
        console.log(_results);
        that.setState({
          reverseGeoResults : JSON.stringify(_results,null,2)
        })
      });
  },

  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          "REVERSE GEO - 370 Tompkins Ave, Brooklyn, NY 11216"
        </Text>
        <Text style={styles.instructions}>
          {this.state.reverseGeoResults}
        </Text>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('RNReverseGeoDemo', () => RNReverseGeoDemo);
<|endoftext|>


<commit_before>'use strict';

chrome.runtime.sendMessage({request: 'lock-tab', url: location.href}, function (response) {
	if (!response.pinned) {
		//console.log('no pinned.');
		return;
	}
	// 閉じる時にアラートを表示させる
	window.addEventListener('beforeunload', function() {
		return 'CLOSING OK?';
	});
});
<commit_msg>Update content_script.js<commit_after>'use strict';

chrome.runtime.sendMessage({request: 'lock-tab', url: location.href}, function (response) {
	if (!response.pinned) {
		return;
	}
	// 閉じる時にアラートを表示させる
	window.addEventListener('beforeunload', function() {
		return 'CLOSING OK?';
	});
});
<|endoftext|>


<commit_before>/* app/js/controllers.js -- application controllers
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */

'use strict';

function loadDeviceState($scope, deviceId) {
  if ($scope.stateStream) $scope.stateStream.close();
  $scope.stateStream = new EventSource('/devices/' + deviceId
      + '/states?stream=1&interval=10');
  $scope.state = { outputs: {} };
  $scope.stateStream.addEventListener('message', function (e) {
    $scope.$apply(function () {
      $scope.state = angular.fromJson(e.data);
    });
  }, false);
  var off = $scope.$on('$locationChangeStart', function (e, next, current) {
    if ($scope.stateStream) $scope.stateStream.close();
    off();
  });
}

function setDeviceUpdater($scope) {
  $scope.updateDevice = function () {
    $scope.device = {};
    $scope.system.device = null;
    var devices = Device.query({ name: $scope.n.deviceName }, function () {
      if (devices.length !== 2) {
        return;
      }
      $scope.device = devices[0];
      $scope.system.device = devices[0]._id;
      loadDeviceState($scope, $scope.system.device);
    });
  }
}

angular.module('pcs.controllers', [])
  .controller('NavCtrl', ['$scope', '$location', function($scope, $location) {
    $scope.isActive = function (viewLocation) {
      return viewLocation === '#' + $location.path();
    }
  }])
  .controller('PageCtrl', ['$scope', '$location', function($scope, $location) {
    $scope.pager = {
      first: 0,
      last: 0,
      count: 0,
      page: 1,
      show: false
    }
    $scope.moment = moment;
    $scope.operator = {}
    $scope.setNewURL = function (url) {
      $scope.newURL = url;
    }
    $scope.page = function (page, perPage, count) {
      $scope.pager.count = count;
      if (count) {
        $scope.pager.show = true;
      } else {
        $scope.pager.show = false;
      }
      $scope.pager.page = page;
      $scope.pager.first = (page - 1) * perPage + 1;
      $scope.pager.last = page * perPage;
      if (page > 1) {
        $scope.pager.prev = '#' + $location.path() + '?page=' + (page - 1);
      } else {
        $scope.pager.prev = '';
      }
      if ($scope.pager.last >= $scope.pager.count) {
        $scope.pager.last = $scope.pager.count;
        $scope.pager.next = '';
      } else {
        $scope.pager.next = '#' + $location.path() + '?page=' + (page + 1);
      }
    }
  }])
  .controller('NewDeviceCtrl', ['$scope', '$location', 'Device',
      function($scope, $location, Device) {
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.device = new Device();
        $scope.save = function () {
          console.log('Saving ' + $scope.device.name);
          $scope.device.$save({}, function () {
            $scope.deviceForm.$setPristine();
            console.log($scope.device);
            $location.path('/devices/' + $scope.device._id).replace();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('DeviceCtrl', ['$scope', '$routeParams', 'Device', 'State',
      'Setpoints',
      function($scope, $routeParams, Device, State, Setpoints) {
        $scope.page(1, 1, 0);
        $scope.setNewURL('#/devices/new');
        $scope.device = Device.get({ deviceId: $routeParams.deviceId }, function () {
        });
        $scope.setpoints = Setpoints.get({ deviceId: $routeParams.deviceId }, function () {
        });
        loadDeviceState($scope, $routeParams.deviceId);
        $scope.save = function () {
          console.log('Saving ' + $scope.device._id);
          $scope.device.$save({}, function () {
            $scope.deviceForm.$setPristine();
            console.log($scope.device);
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('DevicesCtrl', ['$scope', '$location', 'Device',
      function($scope, $location, Device) {
        var page = Number($location.search().page) || 1;
        $scope.setNewURL('#/devices/new');
        $scope.devices = Device.query({page: page}, function () {
          var len = $scope.devices.length - 1;
          var count = $scope.devices.splice(len)[0].count;
          $scope.page(page, 25, count);
        });
  }])
  .controller('NewSiteCtrl', ['$scope', '$location', 'Site',
      function($scope, $location, Site) {
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.site = new Site();
        $scope.save = function () {
          console.log('Saving ' + $scope.site.name);
          $scope.site.$save({}, function () {
            $scope.siteForm.$setPristine();
            console.log($scope.site);
            $location.path('/sites/' + $scope.site._id).replace();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('SiteCtrl', ['$scope', '$routeParams', 'Site', 'System',
      function($scope, $routeParams, Site, System) {
        var page = Number($routeParams.page) || 1;
        $scope.setNewURL('#/sites/' + $routeParams.siteId + '/systems/new');
        $scope.site = Site.get({ siteId: $routeParams.siteId }, function () {
        });
        $scope.systems = System.query({siteId: $routeParams.siteId,
          page: page}, function () {
            var len = $scope.systems.length - 1;
            var count = $scope.systems.splice(len)[0].count;
            $scope.page(page, 25, count);
        });
        $scope.save = function () {
          $scope.site.$save({}, function () {
            $scope.siteForm.$setPristine();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('SitesCtrl', ['$scope', '$location', 'Site',
      function($scope, $location, Site) {
        var page = Number($location.search().page) || 1;
        $scope.setNewURL('#/sites/new');
        $scope.sites = Site.query({page: page}, function () {
          var len = $scope.sites.length - 1;
          var count = $scope.sites.splice(len)[0].count;
          $scope.page(page, 25, count);
        });
  }])
  .controller('NewSystemCtrl', ['$scope', '$routeParams', '$location',
		  'Site', 'System',
      function($scope, $routeParams, $location, Site, System) {
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.system = new System();
        $scope.system.site = $routeParams.siteId;
        $scope.site = Site.get({ siteId: $routeParams.siteId });
        $scope.save = function () {
          console.log('Saving ' + $scope.system.name);
          $scope.system.$save({}, function () {
            $scope.systemForm.$setPristine();
            console.log($scope.system);
            $location.path('/sites/' + $scope.site._id + '/systems/'
		    + $scope.system._id).replace();
          }, function (res) {
            console.log(res);
          });
        }
        setDeviceUpdater($scope);
  }])
  .controller('SystemCtrl', ['$scope', '$routeParams', 'Site', 'System',
      'Device', 'State',
      function($scope, $routeParams, Site, System, Device, State
        ) {
        $scope.device = {};
        $scope.state = { outputs: {} };
        $scope.n = {};
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.system = System.get({ siteId: $routeParams.siteId,
          systemId: $routeParams.systemId }, function () {
            $scope.device = Device.get({ deviceId: $scope.system.device }, function () {
              $scope.n.deviceName = $scope.device.name;
            });
            if (!$scope.system.outputs)
              $scope.system.outputs = [];
            if (!$scope.system.setpoints)
              $scope.system.setpoints = {};
            loadDeviceState($scope, $scope.system.device);
          });
        $scope.site = Site.get({ siteId: $routeParams.siteId });
        $scope.addOutput = function () {
          $scope.system.outputs.push($scope.n.out);
          $scope.n.out = null;
        }
        $scope.dropOutput = function (i) {
          $scope.system.outputs.splice(i);
          $scope.systemForm.$setDirty();
        }
        $scope.addSetpoint = function () {
          $scope.system.setpoints[$scope.n.set] = $scope.n.setValue;
          $scope.n.set = null;
        }
        $scope.dropSetpoint = function (key) {
          delete $scope.system.setpoints[key];
          $scope.systemForm.$setDirty();
        }
        $scope.save = function () {
          $scope.system.$save({}, function (e) {
            $scope.systemForm.$setPristine();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('NewUserCtrl', ['$scope', '$location', 'User',
      function($scope, $location, User) {
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.user = new User();
        $scope.save = function () {
          console.log('Saving ' + $scope.user.name);
          $scope.user.$save({}, function () {
            $scope.userForm.$setPristine();
            console.log($scope.user);
            $location.path('/users/' + $scope.user._id).replace();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('UserCtrl', ['$scope', '$routeParams', 'User',
      function($scope, $routeParams, User) {
        $scope.page(1, 1, 0);
        $scope.setNewURL('#/users/new');
        $scope.user = User.get({ userId: $routeParams.userId }, function () {
          console.log($scope.user);
        });
        $scope.save = function () {
          console.log('Saving ' + $scope.user._id);
          $scope.user.$save({}, function () {
            $scope.userForm.$setPristine();
            console.log($scope.user);
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('UsersCtrl', ['$scope', '$location', 'User',
      function($scope, $location, User) {
        var page = Number($location.search().page) || 1;
        $scope.setNewURL('#/users/new');
        $scope.users = User.query({page: page}, function () {
          var len = $scope.users.length - 1;
          var count = $scope.users.splice(len)[0].count;
          $scope.page(page, 25, count);
        });
  }]);

// vim:ts=2 sts=2 sw=2 et:
<commit_msg>sites page: handle loading error<commit_after>/* app/js/controllers.js -- application controllers
 * Copyright 2014 Sergei Ianovich
 *
 * Licensed under AGPL-3.0 or later, see LICENSE
 * Process Control Service Web Interface
 */

'use strict';

function loadDeviceState($scope, deviceId) {
  if ($scope.stateStream) $scope.stateStream.close();
  $scope.stateStream = new EventSource('/devices/' + deviceId
      + '/states?stream=1&interval=10');
  $scope.state = { outputs: {} };
  $scope.stateStream.addEventListener('message', function (e) {
    $scope.$apply(function () {
      $scope.state = angular.fromJson(e.data);
    });
  }, false);
  var off = $scope.$on('$locationChangeStart', function (e, next, current) {
    if ($scope.stateStream) $scope.stateStream.close();
    off();
  });
}

function setDeviceUpdater($scope) {
  $scope.updateDevice = function () {
    $scope.device = {};
    $scope.system.device = null;
    var devices = Device.query({ name: $scope.n.deviceName }, function () {
      if (devices.length !== 2) {
        return;
      }
      $scope.device = devices[0];
      $scope.system.device = devices[0]._id;
      loadDeviceState($scope, $scope.system.device);
    });
  }
}

angular.module('pcs.controllers', [])
  .controller('NavCtrl', ['$scope', '$location', function($scope, $location) {
    $scope.isActive = function (viewLocation) {
      return viewLocation === '#' + $location.path();
    }
  }])
  .controller('PageCtrl', ['$scope', '$location', function($scope, $location) {
    $scope.pager = {
      first: 0,
      last: 0,
      count: 0,
      page: 1,
      show: false
    }
    $scope.moment = moment;
    $scope.operator = {}
    $scope.setNewURL = function (url) {
      $scope.newURL = url;
    }
    $scope.page = function (page, perPage, count) {
      $scope.pager.count = count;
      if (count) {
        $scope.pager.show = true;
      } else {
        $scope.pager.show = false;
      }
      $scope.pager.page = page;
      $scope.pager.first = (page - 1) * perPage + 1;
      $scope.pager.last = page * perPage;
      if (page > 1) {
        $scope.pager.prev = '#' + $location.path() + '?page=' + (page - 1);
      } else {
        $scope.pager.prev = '';
      }
      if ($scope.pager.last >= $scope.pager.count) {
        $scope.pager.last = $scope.pager.count;
        $scope.pager.next = '';
      } else {
        $scope.pager.next = '#' + $location.path() + '?page=' + (page + 1);
      }
    }
  }])
  .controller('NewDeviceCtrl', ['$scope', '$location', 'Device',
      function($scope, $location, Device) {
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.device = new Device();
        $scope.save = function () {
          console.log('Saving ' + $scope.device.name);
          $scope.device.$save({}, function () {
            $scope.deviceForm.$setPristine();
            console.log($scope.device);
            $location.path('/devices/' + $scope.device._id).replace();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('DeviceCtrl', ['$scope', '$routeParams', 'Device', 'State',
      'Setpoints',
      function($scope, $routeParams, Device, State, Setpoints) {
        $scope.page(1, 1, 0);
        $scope.setNewURL('#/devices/new');
        $scope.device = Device.get({ deviceId: $routeParams.deviceId }, function () {
        });
        $scope.setpoints = Setpoints.get({ deviceId: $routeParams.deviceId }, function () {
        });
        loadDeviceState($scope, $routeParams.deviceId);
        $scope.save = function () {
          console.log('Saving ' + $scope.device._id);
          $scope.device.$save({}, function () {
            $scope.deviceForm.$setPristine();
            console.log($scope.device);
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('DevicesCtrl', ['$scope', '$location', 'Device',
      function($scope, $location, Device) {
        var page = Number($location.search().page) || 1;
        $scope.setNewURL('#/devices/new');
        $scope.devices = Device.query({page: page}, function () {
          var len = $scope.devices.length - 1;
          var count = $scope.devices.splice(len)[0].count;
          $scope.page(page, 25, count);
        });
  }])
  .controller('NewSiteCtrl', ['$scope', '$location', 'Site',
      function($scope, $location, Site) {
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.site = new Site();
        $scope.save = function () {
          console.log('Saving ' + $scope.site.name);
          $scope.site.$save({}, function () {
            $scope.siteForm.$setPristine();
            console.log($scope.site);
            $location.path('/sites/' + $scope.site._id).replace();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('SiteCtrl', ['$scope', '$routeParams', 'Site', 'System',
      function($scope, $routeParams, Site, System) {
        var page = Number($routeParams.page) || 1;
        $scope.setNewURL('#/sites/' + $routeParams.siteId + '/systems/new');
        $scope.site = Site.get({ siteId: $routeParams.siteId }, function () {
        });
        $scope.systems = System.query({siteId: $routeParams.siteId,
          page: page}, function () {
            var len = $scope.systems.length - 1;
            var count = $scope.systems.splice(len)[0].count;
            $scope.page(page, 25, count);
        });
        $scope.save = function () {
          $scope.site.$save({}, function () {
            $scope.siteForm.$setPristine();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('SitesCtrl', ['$scope', '$location', 'Site',
      function($scope, $location, Site) {
        var page = Number($location.search().page) || 1;
        $scope.setNewURL('#/sites/new');
        $scope.sites = Site.query({page: page}, function () {
          var len = $scope.sites.length - 1;
          var count = $scope.sites.splice(len)[0].count;
          $scope.page(page, 25, count);
        }, function (res) {
          console.log(res);
        });
  }])
  .controller('NewSystemCtrl', ['$scope', '$routeParams', '$location',
		  'Site', 'System',
      function($scope, $routeParams, $location, Site, System) {
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.system = new System();
        $scope.system.site = $routeParams.siteId;
        $scope.site = Site.get({ siteId: $routeParams.siteId });
        $scope.save = function () {
          console.log('Saving ' + $scope.system.name);
          $scope.system.$save({}, function () {
            $scope.systemForm.$setPristine();
            console.log($scope.system);
            $location.path('/sites/' + $scope.site._id + '/systems/'
		    + $scope.system._id).replace();
          }, function (res) {
            console.log(res);
          });
        }
        setDeviceUpdater($scope);
  }])
  .controller('SystemCtrl', ['$scope', '$routeParams', 'Site', 'System',
      'Device', 'State',
      function($scope, $routeParams, Site, System, Device, State
        ) {
        $scope.device = {};
        $scope.state = { outputs: {} };
        $scope.n = {};
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.system = System.get({ siteId: $routeParams.siteId,
          systemId: $routeParams.systemId }, function () {
            $scope.device = Device.get({ deviceId: $scope.system.device }, function () {
              $scope.n.deviceName = $scope.device.name;
            });
            if (!$scope.system.outputs)
              $scope.system.outputs = [];
            if (!$scope.system.setpoints)
              $scope.system.setpoints = {};
            loadDeviceState($scope, $scope.system.device);
          });
        $scope.site = Site.get({ siteId: $routeParams.siteId });
        $scope.addOutput = function () {
          $scope.system.outputs.push($scope.n.out);
          $scope.n.out = null;
        }
        $scope.dropOutput = function (i) {
          $scope.system.outputs.splice(i);
          $scope.systemForm.$setDirty();
        }
        $scope.addSetpoint = function () {
          $scope.system.setpoints[$scope.n.set] = $scope.n.setValue;
          $scope.n.set = null;
        }
        $scope.dropSetpoint = function (key) {
          delete $scope.system.setpoints[key];
          $scope.systemForm.$setDirty();
        }
        $scope.save = function () {
          $scope.system.$save({}, function (e) {
            $scope.systemForm.$setPristine();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('NewUserCtrl', ['$scope', '$location', 'User',
      function($scope, $location, User) {
        $scope.page(1, 1, 0);
        $scope.setNewURL(null);
        $scope.user = new User();
        $scope.save = function () {
          console.log('Saving ' + $scope.user.name);
          $scope.user.$save({}, function () {
            $scope.userForm.$setPristine();
            console.log($scope.user);
            $location.path('/users/' + $scope.user._id).replace();
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('UserCtrl', ['$scope', '$routeParams', 'User',
      function($scope, $routeParams, User) {
        $scope.page(1, 1, 0);
        $scope.setNewURL('#/users/new');
        $scope.user = User.get({ userId: $routeParams.userId }, function () {
          console.log($scope.user);
        });
        $scope.save = function () {
          console.log('Saving ' + $scope.user._id);
          $scope.user.$save({}, function () {
            $scope.userForm.$setPristine();
            console.log($scope.user);
          }, function (res) {
            console.log(res);
          });
        }
  }])
  .controller('UsersCtrl', ['$scope', '$location', 'User',
      function($scope, $location, User) {
        var page = Number($location.search().page) || 1;
        $scope.setNewURL('#/users/new');
        $scope.users = User.query({page: page}, function () {
          var len = $scope.users.length - 1;
          var count = $scope.users.splice(len)[0].count;
          $scope.page(page, 25, count);
        });
  }]);

// vim:ts=2 sts=2 sw=2 et:
<|endoftext|>


<commit_before>/* jshint node:true */
/* global require, it, before, beforeEach, describe */

'use strict';
var should = require('should'),
    inquirer = require('inquirer'),
    gulp = require('gulp'),
    mockGulpDest = require('mock-gulp-dest')(gulp);

require('../slushfile');

/**
 * Mock inquirer prompt
 */

function mockPrompt(answers) {
    inquirer.prompt = function (prompts, done) {

        [].concat(prompts).forEach(function (prompt) {
            if (!(prompt.name in answers)) {
                answers[prompt.name] = prompt.default;
            }
        });

        done(answers);
    };
}

describe('slush-ng-app', function() {
    before(function () {
        process.chdir(__dirname);
    });

    describe('default generator', function () {
        beforeEach(function () {
            mockPrompt({
                moveon: true
            });
        });

        it('should put all project files in current working directory', function (done) {
            gulp.start('default').once('stop', function () {
                mockGulpDest.cwd().should.equal(__dirname);
                mockGulpDest.basePath().should.equal(__dirname);
                done();
            });
        });

        it('should create expected files', function (done) {
            gulp.start('default').once('stop', function () {
                mockGulpDest.assertDestContains([
                    '.bowerrc',
                    '.gitignore',
                    '.jshintrc',
                    '.travis.yml',
                    'bower.json',
                    'package.json',
                    'LICENSE',
                    'README.md',
                    'app/index.html',
                    'app/index-async.html',
                    'app/img/.gitkeep',
                    'app/css/app.css',
                    'app/js/app.js',
                    'app/js/controllers.js',
                    'app/js/directives.js',
                    'app/js/filters.js',
                    'app/js/services.js',
                    'app/partials/partial1.html',
                    'app/partials/partial2.html',
                    'test/karma.conf.js',
                    'test/protractor-conf.js',
                    'test/e2e/scenarios.js',
                    'test/unit/controllersSpec.js',
                    'test/unit/directivesSpec.js',
                    'test/unit/filtersSpec.js',
                    'test/unit/servicesSpec.js'
                ]);

                done();
            });
        });
    });
});
<commit_msg>Update tests.<commit_after>/* jshint node:true */
/* global require, it, before, beforeEach, describe */

'use strict';
var should = require('should'),
    inquirer = require('inquirer'),
    gulp = require('gulp'),
    mockGulpDest = require('mock-gulp-dest')(gulp);

require('../slushfile');

/**
 * Mock inquirer prompt
 */

function mockPrompt(answers) {
    inquirer.prompt = function (prompts, done) {

        [].concat(prompts).forEach(function (prompt) {
            if (!(prompt.name in answers)) {
                answers[prompt.name] = prompt.default;
            }
        });

        done(answers);
    };
}

describe('slush-ng-app', function() {
    before(function () {
        process.chdir(__dirname);
    });

    describe('default generator', function () {
        beforeEach(function () {
            mockPrompt({
                moveon: true
            });
        });

        it('should put all project files in current working directory', function (done) {
            gulp.start('default').once('stop', function () {
                mockGulpDest.cwd().should.equal(__dirname);
                mockGulpDest.basePath().should.equal(__dirname);
                done();
            });
        });

        it('should create expected files', function (done) {
            gulp.start('default').once('stop', function () {
                mockGulpDest.assertDestContains([
                    '.bowerrc',
                    '.gitignore',
                    '.jshintrc',
                    '.travis.yml',
                    'bower.json',
                    'gulpfile.js',
                    'package.json',
                    'LICENSE',
                    'README.md',
                    'app/index.html',
                    'app/index-async.html',
                    'app/img/.gitkeep',
                    'app/css/main.css',
                    'app/css/app.css',
                    'app/js/app.js',
                    'app/js/controllers.js',
                    'app/js/directives.js',
                    'app/js/filters.js',
                    'app/js/services.js',
                    'app/partials/partial1.html',
                    'app/partials/partial2.html',
                    'test/karma.conf.js',
                    'test/protractor-conf.js',
                    'test/e2e/scenarios.js',
                    'test/unit/controllersSpec.js',
                    'test/unit/directivesSpec.js',
                    'test/unit/filtersSpec.js',
                    'test/unit/servicesSpec.js'
                ]);

                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>"use strict";

angular.module("lookAroundApp.controllers",[])

	.controller( "ZipCodeFrmCtrl", function( $scope, $location, $routeParams ){
		var placeurl = $routeParams.place || '';
		$scope.sendZip = function( zipcode ) {
			$location.path("/search/" + zipcode + "/" + placeurl);
		}
	})

	.controller( "SearchCtrl", function( $scope, $routeParams, $location, googleMap, $http ){
		$scope.zipCode = $routeParams.zipcode;
		$scope.place = $routeParams.place;
		if(!$scope.zipCode){
			$location.path("/");
		}
		$http.get("data/places.json").success( function( results ){
			$scope.places = results.data;
		});
		$scope.getUrl = function( placeurl ) {
			return "#/search/" + $scope.zipCode + placeurl ;
		};
		$scope.activeClass = function( place ) {
			return place.url.slice(1).toLowerCase() === $scope.place ? 'active':'';
		}
		if(!$scope.place){
			$location.path( $scope.getUrl("/atm").slice(1) );
		}
		else {
			googleMap.getGeoCoder().geocode( { address: $scope.zipCode }, function( results, status ) {
				var lat = results[0].geometry.location.lat(),
		        	lng = results[0].geometry.location.lng();

		       	googleMap.placeService.textSearch( {
		       		query: $scope.place,
		       		type: $scope.place,
		       		location: new googleMap._maps.LatLng( lat, lng ),
		       		radius: 50
		       	}, function( data ) {
		       		$scope.$apply(function(){
		       			$scope.data = data;
		       		});
		       	});
			});
		}

	})
	.controller( "ResultsTabCtrl", function( $scope, $routeParams, $location, googleMap ){
		$scope.tabs = {
			"map" : false,
			"list": true
		};
		$scope.selectedMarker = 0;
		$scope.listView = function(){
			$scope.tabs = {
				"map" : false,
				"list": true
			};
		};
		$scope.mapView = function(){
			$scope.tabs = {
				"map" : true,
				"list": false
			};
		};
		$scope.$watch(function(){
			return googleMap.selectedMarkerIdx;
		}, function(newVal){
			var fn = function(){
				$scope.selectedMarker = newVal;
				if( newVal !== null ) {
					$scope.listView();
				}
			}
			fn();
		});
	})
	.controller( "MainCtrl", function( $scope, $routeParams, $location, $window ){
		$scope.applied = function(){
			return !!$routeParams.zipcode;
		}
		$scope.$on('$viewContentLoaded', function(event) {
			$window.ga('send', 'pageview', {'page': $location.path()});
		});
	})
	.controller( "AboutDialogCtrl", function($scope,$window){
		$scope.opened = false;
		$scope.open = function () {
			$scope.opened = true;
			$window.ga('send', 'modal displayed', 'button', 'click', 'about');
		};

		$scope.close = function () {
			$scope.opened = false;
		};

		$scope.opts = {
			backdropFade: true,
			dialogFade:true
		};
	});
<commit_msg>Fixing GA script<commit_after>"use strict";

angular.module("lookAroundApp.controllers",[])

	.controller( "ZipCodeFrmCtrl", function( $scope, $location, $routeParams ){
		var placeurl = $routeParams.place || '';
		$scope.sendZip = function( zipcode ) {
			$location.path("/search/" + zipcode + "/" + placeurl);
		}
	})

	.controller( "SearchCtrl", function( $scope, $routeParams, $location, googleMap, $http ){
		$scope.zipCode = $routeParams.zipcode;
		$scope.place = $routeParams.place;
		if(!$scope.zipCode){
			$location.path("/");
		}
		$http.get("data/places.json").success( function( results ){
			$scope.places = results.data;
		});
		$scope.getUrl = function( placeurl ) {
			return "#/search/" + $scope.zipCode + placeurl ;
		};
		$scope.activeClass = function( place ) {
			return place.url.slice(1).toLowerCase() === $scope.place ? 'active':'';
		}
		if(!$scope.place){
			$location.path( $scope.getUrl("/atm").slice(1) );
		}
		else {
			googleMap.getGeoCoder().geocode( { address: $scope.zipCode }, function( results, status ) {
				var lat = results[0].geometry.location.lat(),
		        	lng = results[0].geometry.location.lng();

		       	googleMap.placeService.textSearch( {
		       		query: $scope.place,
		       		type: $scope.place,
		       		location: new googleMap._maps.LatLng( lat, lng ),
		       		radius: 50
		       	}, function( data ) {
		       		$scope.$apply(function(){
		       			$scope.data = data;
		       		});
		       	});
			});
		}

	})
	.controller( "ResultsTabCtrl", function( $scope, $routeParams, $location, googleMap ){
		$scope.tabs = {
			"map" : false,
			"list": true
		};
		$scope.selectedMarker = 0;
		$scope.listView = function(){
			$scope.tabs = {
				"map" : false,
				"list": true
			};
		};
		$scope.mapView = function(){
			$scope.tabs = {
				"map" : true,
				"list": false
			};
		};
		$scope.$watch(function(){
			return googleMap.selectedMarkerIdx;
		}, function(newVal){
			var fn = function(){
				$scope.selectedMarker = newVal;
				if( newVal !== null ) {
					$scope.listView();
				}
			}
			fn();
		});
	})
	.controller( "MainCtrl", function( $scope, $routeParams, $location, $window ){
		$scope.applied = function(){
			return !!$routeParams.zipcode;
		}
		$scope.$on('$viewContentLoaded', function(event) {
			$window.ga('send', 'pageview', {'page': $location.path()});
		});
	})
	.controller( "AboutDialogCtrl", function($scope,$window){
		$scope.opened = false;
		$scope.open = function () {
			$scope.opened = true;
			$window.ga('send', 'pageview', {'page': 'about.html'});
		};

		$scope.close = function () {
			$scope.opened = false;
		};

		$scope.opts = {
			backdropFade: true,
			dialogFade:true
		};
	});
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-generator').test;

describe('node:gulp', function () {
  describe('including coveralls', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          coveralls: true,
          projectRoot: 'lib'
        })
        .on('end', done);
    });

    it('creates files and configuration', function () {
      assert.file([
        'gulpfile.js',
        'package.json'
      ]);

      assert.fileContent('gulpfile.js', 'gulp.task(\'coveralls\'');
      assert.fileContent('gulpfile.js', 'gulp.task(\'test\'');
      assert.fileContent('gulpfile.js', 'gulp.task(\'static\'');

      assert.fileContent('package.json', 'gulp');
      assert.fileContent('package.json', 'gulp-coveralls');
      assert.fileContent('package.json', '"test": "gulp"');
      assert.fileContent('package.json', '"prepublish": "gulp prepublish"');
    });

    it('does not include babel configurations', function () {
      assert.noFileContent('gulpfile.js', 'gulp.task(\'babel\'');
      assert.noFileContent('package.json', 'gulp-babel');
    });
  });

  describe('excluding coveralls', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          coveralls: false,
          projectRoot: 'lib'
        })
        .on('end', done);
    });

    it('does not include coveralls configurations', function () {
      assert.noFileContent('gulpfile.js', 'gulp.task(\'coveralls\'');
      assert.noFileContent('package.json', 'gulp-coveralls');
    });
  });

  describe('--no-coveralls', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          coveralls: false,
          projectRoot: 'lib'
        })
        .on('end', done);
    });

    it('does not include coveralls configurations', function () {
      assert.noFileContent('gulpfile.js', 'gulp.task(\'coveralls\'');
      assert.noFileContent('package.json', 'gulp-coveralls');
    });
  });

  describe('--babel', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          babel: true,
          projectRoot: 'lib'
        })
        .on('end', done);
    });

    it('includes babel configuration', function () {
      assert.fileContent('gulpfile.js', 'gulp.task(\'babel\'');
      assert.fileContent('gulpfile.js', 'gulp.task(\'prepublish\', [\'nsp\', \'babel\']);');
      assert.fileContent('package.json', 'gulp-babel');
      assert.fileContent('.gitignore', 'dist');
    });
  });

  describe('--projectRoot', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          projectRoot: 'generators'
        })
        .on('end', done);
    });

    it('define a custom root', function () {
      assert.fileContent('gulpfile.js', 'gulp.src(\'generators/**/*.js\')');
      assert.noFileContent('gulpfile.js', 'gulp.src(\'lib/**/*.js\')');
    });
  });
});
<commit_msg>Update gulp babel related tests<commit_after>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-generator').test;

describe('node:gulp', function () {
  describe('including coveralls', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          coveralls: true,
          projectRoot: 'lib'
        })
        .on('end', done);
    });

    it('creates files and configuration', function () {
      assert.file([
        'gulpfile.js',
        'package.json'
      ]);

      assert.fileContent('gulpfile.js', 'gulp.task(\'coveralls\'');
      assert.fileContent('gulpfile.js', 'gulp.task(\'test\'');
      assert.fileContent('gulpfile.js', 'gulp.task(\'static\'');

      assert.fileContent('package.json', 'gulp');
      assert.fileContent('package.json', 'gulp-coveralls');
      assert.fileContent('package.json', '"test": "gulp"');
      assert.fileContent('package.json', '"prepublish": "gulp prepublish"');
    });

    it('does not include babel configurations', function () {
      assert.noFileContent('gulpfile.js', 'gulp.task(\'babel\'');
      assert.noFileContent('package.json', 'gulp-babel');
    });
  });

  describe('excluding coveralls', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          coveralls: false,
          projectRoot: 'lib'
        })
        .on('end', done);
    });

    it('does not include coveralls configurations', function () {
      assert.noFileContent('gulpfile.js', 'gulp.task(\'coveralls\'');
      assert.noFileContent('package.json', 'gulp-coveralls');
    });
  });

  describe('--no-coveralls', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          coveralls: false,
          projectRoot: 'lib'
        })
        .on('end', done);
    });

    it('does not include coveralls configurations', function () {
      assert.noFileContent('gulpfile.js', 'gulp.task(\'coveralls\'');
      assert.noFileContent('package.json', 'gulp-coveralls');
    });
  });

  describe('--babel', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          babel: true,
          projectRoot: 'lib'
        })
        .on('end', done);
    });

    it('includes babel configuration', function () {
      assert.fileContent('gulpfile.js', 'gulp.task(\'babel\'');
      assert.fileContent('gulpfile.js', 'gulp.task(\'prepublish\', [\'nsp\', \'clean\', \'babel\']);');
      assert.fileContent('package.json', 'gulp-babel');
      assert.fileContent('.gitignore', 'dist');
    });
  });

  describe('--projectRoot', function () {
    before(function (done) {
      helpers.run(path.join(__dirname, '../generators/gulp'))
        .withOptions({
          projectRoot: 'generators'
        })
        .on('end', done);
    });

    it('define a custom root', function () {
      assert.fileContent('gulpfile.js', 'gulp.src(\'generators/**/*.js\')');
      assert.noFileContent('gulpfile.js', 'gulp.src(\'lib/**/*.js\')');
    });
  });
});
<|endoftext|>


<commit_before>/*
Passport-Live is a modern web app for schools that helps them manage passes.
    Copyright (C) 2017  Joseph Hassell

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

email: hi@josephhassell.com
*/
/**
* @module mediaRESTAPI
*/
var express = require('express');
var router = express.Router();
var r = require('rethinkdb')
var db = require('../../modules/db/index.js');
var GeoPattern = require('geopattern');
var jdenticon = require("jdenticon");
var crypto = require('crypto');
var cors = require('cors');

router.use(cors());
router.options('*', cors())

jdenticon.config = {
    lightness: {
        color: [0.0, 1.0],
        grayscale: [0.3, 0.5]
    },
    saturation: 0.5
};

/**
* Generates a unique backdrop for each user
* @function generateBackdrop
* @async
* @param {request} req
* @param {response} res
* @api GET /api/media/background/:id.svg
* @apiparam {string} id ID of the user.
* @apiresponse {image/svg+xml} Returnes the unique svg image
* @todo move rethink db to passport-api module
*/
router.get('/background/:id.svg',function generateBackdrop(req, res, next) {

    res.setHeader('Content-Type', 'image/svg+xml');
    r.table('accounts').get(req.params.id).run(db.conn(), function(err, data) {
        if (err) {
            return next(err);
        }
        if(data) {
            var pattern = GeoPattern.generate(data.name.first + " " + data.name.last);
            var svg = pattern.toSvg();
            var color = pattern.color;
            res.status(200).send(svg);
            //res.sendFile(svg)
        } else {
            var err = new Error("Not Found");
            err.status = 404;
            return next(err)
        }

    })

});

/**
* Gets an avatar for the user
* @function getIdenticon
* @async
* @param {request} req
* @param {response} res
* @api GET /api/media/avatar/:id/:size.svg
* @apiparam {string} id ID of the user.
* @apiparam {string} size How big the svg should be
* @apiresponse {image/svg+xml} Returnes the avatar png
* @todo move rethink db to passport-api module
*/
router.get('/avatar/:id/:size.svg', function getAvatar(req, res, next) {
    res.setHeader('Content-Type', 'image/svg+xml');
    var size = parseInt(req.params.size)
    if(isNaN(size)) {
         var err = new Error("Size must be a number");
                err.status = 400;
                return next(err)
    } else {
        r.table('accounts').get(req.params.id).run(db.conn(), function(err, data) {
            if (err) {
                return next(err);
            }
            if(data) {
                var hash = crypto.createHash('md5').update(data.name.first + " " + data.name.last).digest("hex")
                var svg = jdenticon.toSvg(hash, size);
                res.status(200).send(svg);
            } else {
                var err = new Error("Not Found");
                err.status = 404;
                return next(err)
            }

        })
    }
});

module.exports = router;<commit_msg>fixed docs<commit_after>/*
Passport-Live is a modern web app for schools that helps them manage passes.
    Copyright (C) 2017  Joseph Hassell

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

email: hi@josephhassell.com
*/
/**
* @module mediaRESTAPI
*/
var express = require('express');
var router = express.Router();
var r = require('rethinkdb')
var db = require('../../modules/db/index.js');
var GeoPattern = require('geopattern');
var jdenticon = require("jdenticon");
var crypto = require('crypto');
var cors = require('cors');

router.use(cors());
router.options('*', cors())

jdenticon.config = {
    lightness: {
        color: [0.0, 1.0],
        grayscale: [0.3, 0.5]
    },
    saturation: 0.5
};

/**
* Generates a unique backdrop for each user
* @function generateBackdrop
* @async
* @param {request} req
* @param {response} res
* @api GET /api/media/background/:id.svg
* @apiparam {string} id ID of the user.
* @apiresponse {image/svg\u002Bxml} Returnes the unique svg image
* @todo move rethink db to passport-api module
*/
router.get('/background/:id.svg',function generateBackdrop(req, res, next) {

    res.setHeader('Content-Type', 'image/svg+xml');
    r.table('accounts').get(req.params.id).run(db.conn(), function(err, data) {
        if (err) {
            return next(err);
        }
        if(data) {
            var pattern = GeoPattern.generate(data.name.first + " " + data.name.last);
            var svg = pattern.toSvg();
            var color = pattern.color;
            res.status(200).send(svg);
            //res.sendFile(svg)
        } else {
            var err = new Error("Not Found");
            err.status = 404;
            return next(err)
        }

    })

});

/**
* Gets an avatar for the user
* @function getIdenticon
* @async
* @param {request} req
* @param {response} res
* @api GET /api/media/avatar/:id/:size.svg
* @apiparam {string} id ID of the user.
* @apiparam {string} size How big the svg should be
* @apiresponse {image/svg\u002Bxml} Returnes the avatar png
* @todo move rethink db to passport-api module
*/
router.get('/avatar/:id/:size.svg', function getAvatar(req, res, next) {
    res.setHeader('Content-Type', 'image/svg+xml');
    var size = parseInt(req.params.size)
    if(isNaN(size)) {
         var err = new Error("Size must be a number");
                err.status = 400;
                return next(err)
    } else {
        r.table('accounts').get(req.params.id).run(db.conn(), function(err, data) {
            if (err) {
                return next(err);
            }
            if(data) {
                var hash = crypto.createHash('md5').update(data.name.first + " " + data.name.last).digest("hex")
                var svg = jdenticon.toSvg(hash, size);
                res.status(200).send(svg);
            } else {
                var err = new Error("Not Found");
                err.status = 404;
                return next(err)
            }

        })
    }
});

module.exports = router;<|endoftext|>