<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { handleRoute } from 'fluxible-router';
import PresentationSlide from './PresentationSlide';
import { connectToStores } from 'fluxible-addons-react';
import { Microservices } from '../../../configs/microservices';
import PresentationStore from '../../../stores/PresentationStore';

// if(process.env.BROWSER){
//    require('../../../assets/css/PresentationDefaults.css');
// }

class Presentation extends React.Component{
    constructor(props){
        super(props);
        this.playerCss = { height: '100%', position: 'absolute', top: '0' };
        this.clearStyle = { clear: 'both' };
        this.startingSlide = this.props.PresentationStore.selector.sid;
        this.revealDiv = null;
        this.secret = props.currentRoute.query.secret;
        this.id = props.currentRoute.query.id;
    }

    componentDidMount(){
        if(process.env.BROWSER){
            //$('[style*="absolute"]').children().attr('tabindex', 0);

            //remove existing tabindices
            $('[style*="absolute"]').each(function () {
                let el = $(this);
                if(el.attr('tabindex') !== 0)
                    el.attr('tabindex', 0);
            });
            //add tabindices to all children in absolute elements
            $('[style*="absolute"]').each(function () {
                $(this).children().attr('tabindex', 0);
                //if($(this).attr('tabindex') !== 0)
                //{
                //    $(this).attr('tabindex', 0);
                //}
            });
            //TODO: add hidden element at start of PPTX slide content + to focus on this.

             //loading reveal style

            // $('html.ios, html.ios body').css('height': '100% !important');
            // Get the theme information, and download the stylesheet

            this.revealDiv.style.display = 'inline';

            //SWIK-1321 - Non-canvas/pptx2html content is not scaled in presentation mode and bottom content is hidden
            let pptxwidth = '100%'; //use 100% of screen width
            let pptxheight = '100%'; //use 100% of screen height
            //if($('.pptx2html').html() !== ''){
            if($('.pptx2html').html()){
                pptxwidth = $('.pptx2html').width();
                pptxheight = $('.pptx2html').height();
            } else {
                pptxwidth = '100%';
                pptxheight = '100%';
            }

            window.location.hash = '#slide-' + this.startingSlide;

            let multiplexFileToLoad = (this.secret) ? '/custom_modules/reveal.js/plugin/multiplex/master.js' : '/custom_modules/reveal.js/plugin/multiplex/client.js' ;
            multiplexFileToLoad = (this.id) ? multiplexFileToLoad : '' ;
            let multiplexConfig = (this.secret) ? {secret: this.secret, id: this.id} : {secret: null, id: this.id};
            multiplexConfig.url = Microservices.webrtc.uri;
            multiplexConfig = (this.id) ? multiplexConfig : {};
            let dependencySocketIO = (this.id) ? Microservices.webrtc.uri.replace('http:','').replace('https:','') + '/socket.io/socket.io.js' : '' ;
            Reveal.initialize({
                width: pptxwidth,
                height: pptxheight,
                // margin: 0.2,
                transition: 'none',
                backgroundTransition: 'none',
                history: true,
                viewDistance: 2,
                dependencies: [
                    { src: dependencySocketIO, async: true },
                    { src: multiplexFileToLoad, async: true },
                    { src: '/custom_modules/reveal.js/plugin/notes/notes.js', async: true },
                    { src: '/custom_modules/reveal.js/plugin/zoom-js/zoom.js', async: true },
                    // { src: '/custom_modules/reveal.js/plugin/reveal.js-toolbar/toolbar.js', async: true},
                    { src: '/reveal.js-menu/menu.js', async: true},
                    { src: '/custom_modules/reveal.js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
                    // Plugin from https://github.com/marcysutton/reveal-a11y
                    //{ src: '/custom_modules/reveal.js/plugin/accessibility/helper.js', async: false,condition: function() {return !!document.body.classList;}}
                ],
                keyboard: {
                    72: null,
                    78: null
                },
                toolbar: {
                    captureMenu: false,  // set to false so it doesn't crash the plugin
                    deckUrl: ['/deck', this.props.PresentationStore.selector.id, this.props.PresentationStore.deckSlug].join('/')
                },
                menu: {
                    deckUrl: ['/deck', this.props.PresentationStore.selector.id, this.props.PresentationStore.deckSlug].join('/'),
                    speakerNotes: '/custom_modules/reveal.js/plugin/notes/notes.html',
                    overview: true,
                    side: 'left',
                    width: 'normal',
                    numbers: false,
                    titleSelector: 'h1, h2, h3, h4, h5, h6',
                    useTextContentForMissingTitles: true,
                    hideMissingTitles: false,
                    markers: true,

                    // Specify custom panels to be included in the menu, by
                    // providing an array of objects with 'title', 'icon'
                    // properties, and either a 'src' or 'content' property.
                    custom: false,

                    // Specifies the themes that will be available in the themes
                    // menu panel. Set to 'true' to show the themes menu panel
                    // with the default themes list. Alternatively, provide an
                    // array to specify the themes to make available in the
                    // themes menu panel, for example...
                    // [
                    //     { name: 'Black', theme: 'css/theme/black.css' },
                    //     { name: 'White', theme: 'css/theme/white.css' },
                    //     { name: 'League', theme: 'css/theme/league.css' }
                    // ]
                    themes: false,

                    themesPath: 'css/theme/',
                    transitions: false,
                    openButton: true,
                    openSlideNumber: false,
                    keyboard: true,
                    sticky: false,
                    autoOpen: true,
                    delayInit: false,
                    openOnInit: false,
                    loadIcons: true
                },
                multiplex: multiplexConfig
            });

            Reveal.addEventListener( 'ready', ( event ) => {
                //$('.accessibilityWrapper').attr('tabindex', '');
                //$('.present > .accessibilityWrapper > .pptx2html div:first-child').focus();
                //console.log($('.present > .accessibilityWrapper > .pptx2html div:first').html());
            	// event.currentSlide, event.indexh, event.indexv
                this.resize();
            } );

            Reveal.addEventListener( 'slidechanged', ( event ) => {
                //console.log('slidechanged: ' + $('.present > .accessibilityWrapper > .pptx2html div:first').html());
                //$('.present > .accessibilityWrapper > .pptx2html div:first-child').focus();
                //console.log('resize non-pptx2html slide content - presentwidth: ' + presentwidth + ' and height: ' + presentheight);
                this.resize();
            } );

            //$('.present > .pptx2html div:first').focus();

        //listen to resize event and resize.
        /*ReactDOM.findDOMNode(this.refs.container).addEventListener('resize', (evt) =>
            {
            //console.log('resize');
            this.resize();
        });*/
            window.addEventListener('resize', this.resize());
        }
        //$('.present >  .pptx2html div:first').focus();

        // update mathjax rendering
        // add to the mathjax rendering queue the command to type-set the slide content
        MathJax.Hub.Queue(['Typeset',MathJax.Hub,'slides']);

    }
    resize(){
        if(process.env.BROWSER){
            let pptxwidth;
            let pptxheight;
            if( $('.present > .pptx2html').html() ){
                pptxwidth = $('.present > .pptx2html').width();
                pptxheight = $('.present > .pptx2html').height();
            } else {

                pptxwidth = '100%';
                pptxheight = '100%';

                //resize non-pptx2html slide content based on current height of window
                //reimplemented based on old SlideWiki https://github.com/AKSW/SlideWiki/blob/307e9e87aee08543e46d270fe267aeaa5cdbfe3b/slidewiki/static/js/scale.js
                //let presentwidth = $('.present').width();
                let presentheight = $('.present').height();
                //console.log('resize non-pptx2html slide content - presentwidth: ' + presentwidth + ' and height: ' + presentheight);
                //let screenwidth = document.getElementsByClassName('reveal')[0].offsetWidth * 0.85;
                //let screenwidth = document.getElementsByClassName('reveal')[0].offsetWidth * 0.85;
                //let screenheight = (document.getElementsByClassName('reveal')[0].offsetHeight * 0.85);
                let screenheight = document.getElementsByClassName('reveal')[0].offsetHeight;
                //console.log('resize non-pptx2html slide content - screenwidth: ' + screenwidth + ' and height: ' + screenheight);
                let heightratio = screenheight / presentheight ;
                //let widthratio = screenwidth / presentwidth;
                let scaleratio = 1;
                //if (widthratio < heightratio){scaleratio = widthratio;} else {scaleratio = heightratio;}
                if (presentheight > screenheight){scaleratio = heightratio;}
                //console.log('resize non-pptx2html slide content - widthratio: ' + widthratio + ' and heightratioratio: ' + heightratio);
                //console.log('resize non-pptx2html slide content - scaleratio: ' + scaleratio);

                $('.present').css({'transform': '', 'transform-origin': ''});
                $('.present').css({'transform': 'scale('+scaleratio+','+scaleratio+')', 'transform-origin': 'center top'});

            }
            // event.previousSlide, event.currentSlide, event.indexh, event.indexv
            //let state = Reveal.getState();
            //console.log('state: ' + JSON.stringify(state));
            //console.log('slidechanged dimensions: ' + pptxheight + ' by ' + pptxwidth);
            Reveal.configure({
                width: pptxwidth,
                height: pptxheight,
                slideNumber: true
            });

        }
    }

    render(){

        // Load the theme stylesheet
        let styleName = 'default';
        if(this.props.PresentationStore.theme && typeof this.props.PresentationStore.theme !== 'undefined')
            styleName = this.props.PresentationStore.theme;
        if (styleName === '' || typeof styleName === 'undefined' || styleName === 'undefined')//if none of above yield a theme they will be legacy decks:
            styleName = 'white';
        let style = require('../../../custom_modules/reveal.js/css/theme/' + styleName + '.css');
        let slides = this.getSlides();
        return(
            //<ResizeAware ref='container' id='container'>

 this.revealDiv = refToDiv}  data-background-transition="none">

      			     	     {slides}

            //</ResizeAware>
        );
    }

    getSlides(){
        let slides = this.props.PresentationStore.content;

        let html =
;
        if (slides) {
            html = slides.map((slide) => {
                let content = slide.content.replace(' src=', ' data-src=') + ((slide.speakernotes) ? '' + slide.speakernotes + '' : '');
                let bgColor = content.split('background-color: ');
                let bgImgTemp = content.split('background-image: ');
                let transition = slide.transition ? slide.transition : 'none';
                let resultingSlide =
;
                //need to check if bg is provided
                if (bgImgTemp.length > 1) {
                    let backgroundImageExtr = content.split('background-image: url("'); // url("
                    backgroundImageExtr = backgroundImageExtr.length > 1 ? backgroundImageExtr[1] :  undefined;
                    if (backgroundImageExtr) backgroundImageExtr = backgroundImageExtr.split('");').length > 1 ? backgroundImageExtr.split('");')[0] : undefined;
                    if (backgroundImageExtr) {
                        // Remove background of the inner slide
                        content = content.split('background-image: url("')[0] + content.split('");')[1];
                        if(bgColor.length > 1) content =  content.split('background-color: ')[0] + content.split('background-color: ')[1].split(';').slice(1).join('');
                        // Add resulting slide.
                        resultingSlide =
;
                    } else {
                        console.log('Problem extracting the background image: ', bgImgTemp[1]);
                    }
                } else if (bgColor.length > 1) {
                    let backgroundColour = bgColor[1].split(';').length > 1 ? bgColor[1].split(';')[0] : undefined;
                    if (backgroundColour) {
                        resultingSlide =
;
                    } else {
                        console.log('Problem extracting the background colour: ', bgColor[1]);
                    }
                }
                return resultingSlide;
            });
        }
        return html;
    }

}

Presentation = connectToStores(Presentation, [PresentationStore], (context, props) => {
    return {
        PresentationStore: context.getStore(PresentationStore).getState()
    };
});
Presentation = handleRoute(Presentation);//NOTE add currentRoute attribute to constructor props

export default Presentation;
<commit_msg>Fix duplicate key error presentation mode<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { handleRoute } from 'fluxible-router';
import PresentationSlide from './PresentationSlide';
import { connectToStores } from 'fluxible-addons-react';
import { Microservices } from '../../../configs/microservices';
import PresentationStore from '../../../stores/PresentationStore';

// if(process.env.BROWSER){
//    require('../../../assets/css/PresentationDefaults.css');
// }

class Presentation extends React.Component{
    constructor(props){
        super(props);
        this.playerCss = { height: '100%', position: 'absolute', top: '0' };
        this.clearStyle = { clear: 'both' };
        this.startingSlide = this.props.PresentationStore.selector.sid;
        this.revealDiv = null;
        this.secret = props.currentRoute.query.secret;
        this.id = props.currentRoute.query.id;
    }

    componentDidMount(){
        if(process.env.BROWSER){
            //$('[style*="absolute"]').children().attr('tabindex', 0);

            //remove existing tabindices
            $('[style*="absolute"]').each(function () {
                let el = $(this);
                if(el.attr('tabindex') !== 0)
                    el.attr('tabindex', 0);
            });
            //add tabindices to all children in absolute elements
            $('[style*="absolute"]').each(function () {
                $(this).children().attr('tabindex', 0);
                //if($(this).attr('tabindex') !== 0)
                //{
                //    $(this).attr('tabindex', 0);
                //}
            });
            //TODO: add hidden element at start of PPTX slide content + to focus on this.

             //loading reveal style

            // $('html.ios, html.ios body').css('height': '100% !important');
            // Get the theme information, and download the stylesheet

            this.revealDiv.style.display = 'inline';

            //SWIK-1321 - Non-canvas/pptx2html content is not scaled in presentation mode and bottom content is hidden
            let pptxwidth = '100%'; //use 100% of screen width
            let pptxheight = '100%'; //use 100% of screen height
            //if($('.pptx2html').html() !== ''){
            if($('.pptx2html').html()){
                pptxwidth = $('.pptx2html').width();
                pptxheight = $('.pptx2html').height();
            } else {
                pptxwidth = '100%';
                pptxheight = '100%';
            }

            window.location.hash = '#slide-' + this.startingSlide;

            let multiplexFileToLoad = (this.secret) ? '/custom_modules/reveal.js/plugin/multiplex/master.js' : '/custom_modules/reveal.js/plugin/multiplex/client.js' ;
            multiplexFileToLoad = (this.id) ? multiplexFileToLoad : '' ;
            let multiplexConfig = (this.secret) ? {secret: this.secret, id: this.id} : {secret: null, id: this.id};
            multiplexConfig.url = Microservices.webrtc.uri;
            multiplexConfig = (this.id) ? multiplexConfig : {};
            let dependencySocketIO = (this.id) ? Microservices.webrtc.uri.replace('http:','').replace('https:','') + '/socket.io/socket.io.js' : '' ;
            Reveal.initialize({
                width: pptxwidth,
                height: pptxheight,
                // margin: 0.2,
                transition: 'none',
                backgroundTransition: 'none',
                history: true,
                viewDistance: 2,
                dependencies: [
                    { src: dependencySocketIO, async: true },
                    { src: multiplexFileToLoad, async: true },
                    { src: '/custom_modules/reveal.js/plugin/notes/notes.js', async: true },
                    { src: '/custom_modules/reveal.js/plugin/zoom-js/zoom.js', async: true },
                    // { src: '/custom_modules/reveal.js/plugin/reveal.js-toolbar/toolbar.js', async: true},
                    { src: '/reveal.js-menu/menu.js', async: true},
                    { src: '/custom_modules/reveal.js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
                    // Plugin from https://github.com/marcysutton/reveal-a11y
                    //{ src: '/custom_modules/reveal.js/plugin/accessibility/helper.js', async: false,condition: function() {return !!document.body.classList;}}
                ],
                keyboard: {
                    72: null,
                    78: null
                },
                toolbar: {
                    captureMenu: false,  // set to false so it doesn't crash the plugin
                    deckUrl: ['/deck', this.props.PresentationStore.selector.id, this.props.PresentationStore.deckSlug].join('/')
                },
                menu: {
                    deckUrl: ['/deck', this.props.PresentationStore.selector.id, this.props.PresentationStore.deckSlug].join('/'),
                    speakerNotes: '/custom_modules/reveal.js/plugin/notes/notes.html',
                    overview: true,
                    side: 'left',
                    width: 'normal',
                    numbers: false,
                    titleSelector: 'h1, h2, h3, h4, h5, h6',
                    useTextContentForMissingTitles: true,
                    hideMissingTitles: false,
                    markers: true,

                    // Specify custom panels to be included in the menu, by
                    // providing an array of objects with 'title', 'icon'
                    // properties, and either a 'src' or 'content' property.
                    custom: false,

                    // Specifies the themes that will be available in the themes
                    // menu panel. Set to 'true' to show the themes menu panel
                    // with the default themes list. Alternatively, provide an
                    // array to specify the themes to make available in the
                    // themes menu panel, for example...
                    // [
                    //     { name: 'Black', theme: 'css/theme/black.css' },
                    //     { name: 'White', theme: 'css/theme/white.css' },
                    //     { name: 'League', theme: 'css/theme/league.css' }
                    // ]
                    themes: false,

                    themesPath: 'css/theme/',
                    transitions: false,
                    openButton: true,
                    openSlideNumber: false,
                    keyboard: true,
                    sticky: false,
                    autoOpen: true,
                    delayInit: false,
                    openOnInit: false,
                    loadIcons: true
                },
                multiplex: multiplexConfig
            });

            Reveal.addEventListener( 'ready', ( event ) => {
                //$('.accessibilityWrapper').attr('tabindex', '');
                //$('.present > .accessibilityWrapper > .pptx2html div:first-child').focus();
                //console.log($('.present > .accessibilityWrapper > .pptx2html div:first').html());
            	// event.currentSlide, event.indexh, event.indexv
                this.resize();
            } );

            Reveal.addEventListener( 'slidechanged', ( event ) => {
                //console.log('slidechanged: ' + $('.present > .accessibilityWrapper > .pptx2html div:first').html());
                //$('.present > .accessibilityWrapper > .pptx2html div:first-child').focus();
                //console.log('resize non-pptx2html slide content - presentwidth: ' + presentwidth + ' and height: ' + presentheight);
                this.resize();
            } );

            //$('.present > .pptx2html div:first').focus();

        //listen to resize event and resize.
        /*ReactDOM.findDOMNode(this.refs.container).addEventListener('resize', (evt) =>
            {
            //console.log('resize');
            this.resize();
        });*/
            window.addEventListener('resize', this.resize());
        }
        //$('.present >  .pptx2html div:first').focus();

        // update mathjax rendering
        // add to the mathjax rendering queue the command to type-set the slide content
        MathJax.Hub.Queue(['Typeset',MathJax.Hub,'slides']);

    }
    resize(){
        if(process.env.BROWSER){
            let pptxwidth;
            let pptxheight;
            if( $('.present > .pptx2html').html() ){
                pptxwidth = $('.present > .pptx2html').width();
                pptxheight = $('.present > .pptx2html').height();
            } else {

                pptxwidth = '100%';
                pptxheight = '100%';

                //resize non-pptx2html slide content based on current height of window
                //reimplemented based on old SlideWiki https://github.com/AKSW/SlideWiki/blob/307e9e87aee08543e46d270fe267aeaa5cdbfe3b/slidewiki/static/js/scale.js
                //let presentwidth = $('.present').width();
                let presentheight = $('.present').height();
                //console.log('resize non-pptx2html slide content - presentwidth: ' + presentwidth + ' and height: ' + presentheight);
                //let screenwidth = document.getElementsByClassName('reveal')[0].offsetWidth * 0.85;
                //let screenwidth = document.getElementsByClassName('reveal')[0].offsetWidth * 0.85;
                //let screenheight = (document.getElementsByClassName('reveal')[0].offsetHeight * 0.85);
                let screenheight = document.getElementsByClassName('reveal')[0].offsetHeight;
                //console.log('resize non-pptx2html slide content - screenwidth: ' + screenwidth + ' and height: ' + screenheight);
                let heightratio = screenheight / presentheight ;
                //let widthratio = screenwidth / presentwidth;
                let scaleratio = 1;
                //if (widthratio < heightratio){scaleratio = widthratio;} else {scaleratio = heightratio;}
                if (presentheight > screenheight){scaleratio = heightratio;}
                //console.log('resize non-pptx2html slide content - widthratio: ' + widthratio + ' and heightratioratio: ' + heightratio);
                //console.log('resize non-pptx2html slide content - scaleratio: ' + scaleratio);

                $('.present').css({'transform': '', 'transform-origin': ''});
                $('.present').css({'transform': 'scale('+scaleratio+','+scaleratio+')', 'transform-origin': 'center top'});

            }
            // event.previousSlide, event.currentSlide, event.indexh, event.indexv
            //let state = Reveal.getState();
            //console.log('state: ' + JSON.stringify(state));
            //console.log('slidechanged dimensions: ' + pptxheight + ' by ' + pptxwidth);
            Reveal.configure({
                width: pptxwidth,
                height: pptxheight,
                slideNumber: true
            });

        }
    }

    render(){

        // Load the theme stylesheet
        let styleName = 'default';
        if(this.props.PresentationStore.theme && typeof this.props.PresentationStore.theme !== 'undefined')
            styleName = this.props.PresentationStore.theme;
        if (styleName === '' || typeof styleName === 'undefined' || styleName === 'undefined')//if none of above yield a theme they will be legacy decks:
            styleName = 'white';
        let style = require('../../../custom_modules/reveal.js/css/theme/' + styleName + '.css');
        let slides = this.getSlides();
        return(
            //<ResizeAware ref='container' id='container'>

 this.revealDiv = refToDiv}  data-background-transition="none">

      			     	     {slides}

            //</ResizeAware>
        );
    }

    getSlides(){
        let slides = this.props.PresentationStore.content;

        let html =
;
        if (slides) {
            html = slides.map((slide, index) => {
                let content = slide.content.replace(' src=', ' data-src=') + ((slide.speakernotes) ? '' + slide.speakernotes + '' : '');
                let bgColor = content.split('background-color: ');
                let bgImgTemp = content.split('background-image: ');
                let transition = slide.transition ? slide.transition : 'none';
                let resultingSlide =
;
                //need to check if bg is provided
                if (bgImgTemp.length > 1) {
                    let backgroundImageExtr = content.split('background-image: url("'); // url("
                    backgroundImageExtr = backgroundImageExtr.length > 1 ? backgroundImageExtr[1] :  undefined;
                    if (backgroundImageExtr) backgroundImageExtr = backgroundImageExtr.split('");').length > 1 ? backgroundImageExtr.split('");')[0] : undefined;
                    if (backgroundImageExtr) {
                        // Remove background of the inner slide
                        content = content.split('background-image: url("')[0] + content.split('");')[1];
                        if(bgColor.length > 1) content =  content.split('background-color: ')[0] + content.split('background-color: ')[1].split(';').slice(1).join('');
                        // Add resulting slide.
                        resultingSlide =
;
                    } else {
                        console.log('Problem extracting the background image: ', bgImgTemp[1]);
                    }
                } else if (bgColor.length > 1) {
                    let backgroundColour = bgColor[1].split(';').length > 1 ? bgColor[1].split(';')[0] : undefined;
                    if (backgroundColour) {
                        resultingSlide =
;
                    } else {
                        console.log('Problem extracting the background colour: ', bgColor[1]);
                    }
                }
                return resultingSlide;
            });
        }
        return html;
    }

}

Presentation = connectToStores(Presentation, [PresentationStore], (context, props) => {
    return {
        PresentationStore: context.getStore(PresentationStore).getState()
    };
});
Presentation = handleRoute(Presentation);//NOTE add currentRoute attribute to constructor props

export default Presentation;
<|endoftext|>


<commit_before>'use strict';

angular.module('setupApp', []).controller('wizardController', ['$scope', 'setupAPI', function($scope, setupAPI) {
  $scope.settings = {};
  $scope.settings.hostname = null;
  $scope.settings.port = null;
  $scope.settings.dbname = null;
  $scope.step = 0;
  $scope.test = {
    running: false,
    status: 'none',
    err: null
  };
  $scope.record={
    results: 'none',
    err: null,
    running: false
  };

  $scope.ajaxRunning = function() {
    return $scope.record.running || $scope.test.running ? true : false;
  };

  $scope.infocomplete = function() {
    return $scope.settings.hostname && $scope.settings.port && $scope.settings.dbname ? true : false;
  };

  $scope.testConnection = function() {
    if ( $scope.ajaxRunning() ) {
      return ;
    }
    $scope.test.running=true;
    setupAPI.testConnection($scope.settings.hostname, $scope.settings.port,$scope.settings.dbname)
      .success(function() {
        $scope.test.status='success';
      })
      .error(function(data) {
        $scope.test.status='error';
        $scope.test.err=data.error+': '+data.reason;
      })
      .finally(function() {
        $scope.test.running = false;
      });
  };

  $scope.recordSettings = function() {
    if ( $scope.ajaxRunning() ) {
      return ;
    }
    $scope.record.running = true;
    setupAPI.recordSettings($scope.settings)
      .success(function() {
        $scope.step++;
      })
      .error(function(data){
        $scope.record.results = 'error';
        $scope.record.err = data;
      })
      .finally(function() {
        $scope.record.running = false;
      });
  };

}]).service('setupAPI', ['$http', function($http) {

    function testConnection(hostname, port, dbname) {
      var url = '/api/setup/database/test/connection/'+
                encodeURIComponent(hostname)+'/'+
                encodeURIComponent(port)+'/'+
                encodeURIComponent(dbname);
      return $http.get(url);
    }

    function recordSettings(settings) {
      return $http.put('/api/setup/settings', settings);
    }

    return {
      testConnection: testConnection,
      recordSettings: recordSettings
    };
  }
]);<commit_msg>OR-17 Handle basic HTTP errors<commit_after>'use strict';

angular.module('setupApp', []).controller('wizardController', ['$scope', 'setupAPI', function($scope, setupAPI) {
  $scope.settings = {};
  $scope.settings.hostname = null;
  $scope.settings.port = null;
  $scope.settings.dbname = null;
  $scope.step = 0;
  $scope.test = {
    running: false,
    status: 'none',
    err: null
  };
  $scope.record={
    status: 'none',
    err: null,
    running: false
  };

  $scope.ajaxRunning = function() {
    return $scope.record.running || $scope.test.running ? true : false;
  };

  $scope.infocomplete = function() {
    return $scope.settings.hostname && $scope.settings.port && $scope.settings.dbname ? true : false;
  };

  $scope.testConnection = function() {
    if ( $scope.ajaxRunning() ) {
      return ;
    }
    $scope.test.running=true;
    setupAPI.testConnection($scope.settings.hostname, $scope.settings.port,$scope.settings.dbname)
      .success(function() {
        $scope.test.status='success';
      })
      .error(function(data) {
        $scope.test.status='error';
        if ( data.err && data.reason ) {
          $scope.test.err=data.error+': '+data.reason;
        } else {
          $scope.test.err=arguments[1]+': '+arguments[0];
        }
      })
      .finally(function() {
        $scope.test.running = false;
      });
  };

  $scope.recordSettings = function() {
    if ( $scope.ajaxRunning() ) {
      return ;
    }
    $scope.record.running = true;
    setupAPI.recordSettings($scope.settings)
      .success(function() {
        $scope.step++;
      })
      .error(function(data){
        $scope.record.status = 'error';
        if( data.error && data.reason ) {
          $scope.record.err = data;
        } else {
          $scope.record.err = {
            error: arguments[1],
            reason: arguments[0]
          };
        }
      })
      .finally(function() {
        $scope.record.running = false;
      });
  };

}]).service('setupAPI', ['$http', function($http) {

    function testConnection(hostname, port, dbname) {
      var url = '/api/setup/database/test/connection/'+
                encodeURIComponent(hostname)+'/'+
                encodeURIComponent(port)+'/'+
                encodeURIComponent(dbname);
      return $http.get(url);
    }

    function recordSettings(settings) {
      return $http.put('/api/setup/settings', settings);
    }

    return {
      testConnection: testConnection,
      recordSettings: recordSettings
    };
  }
]);<|endoftext|>


<commit_before>var _ = require('underscore-node');
var bus = require("hermes-bus");

// Retain a local cache of what was logged to the dashboard and console,
// so that, even if a web client connects later, it will still show all
// relevant past messages.
var logAreas = {
	dashboard: [],
	console: [],
};
var supportedLogAreaNames = Object.keys(logAreas);

bus.on("logMessage", function(loggerId, message){
	if(_.contains(supportedLogAreaNames, loggerId)) {
		logAreas[loggerId].push.apply(logAreas[loggerId], message.split(/\n/));
	}
});

bus.on("logReset", function(loggerId){
	if(_.contains(supportedLogAreaNames, loggerId)) {
		logAreas[loggerId] = [];
	}
});

var WebSocketServer = require('ws').Server;

var wss = new WebSocketServer({port: 3001});

wss.on('connection', function(ws) {
	var send = function(busMessageId, args) {
		ws.send(JSON.stringify({busMessageId: busMessageId, arguments: args}));
	};

	["logMessage", "logReset"].forEach(function(busMessageId) {
		bus.on(busMessageId, function() {
			send(busMessageId, _.toArray(arguments));
		});
	});

	supportedLogAreaNames.forEach(function(logAreaName) {
		logAreas[logAreaName].forEach(function(logEntry) {
			send("logMessage", [logAreaName, logEntry]);
		});
	});
});
<commit_msg>logging-websockets.js: Now adds a link to the web client task reporting<commit_after>var sprintf=require("sprintf-js").sprintf;
var _ = require('underscore-node');
var bus = require("hermes-bus");

// Retain a local cache of what was logged to the dashboard and console,
// so that, even if a web client connects later, it will still show all
// relevant past messages.
var logAreas = {
	dashboard: [],
	console: [],
};
var supportedLogAreaNames = Object.keys(logAreas);

bus.on("logMessage", function(loggerId, message){
	if(_.contains(supportedLogAreaNames, loggerId)) {
		logAreas[loggerId].push.apply(logAreas[loggerId], message.split(/\n/));
	}
});

bus.on("logReset", function(loggerId){
	if(_.contains(supportedLogAreaNames, loggerId)) {
		logAreas[loggerId] = [];
	}
});

// Adds a link to the web client reporting page
bus.on("logReset", function(loggerId){
	if(loggerId === "dashboard" && localConnectServerUri) {
		bus.triggerLogMessage("dashboard", "\033[H" + sprintf("%"+process.stdout.columns+"s", "Interactive log also available at: "+localConnectServerUri+"/report-task-status/"));
	}
});

// @TODO remove duplicate code
var localIpAddress = "127.0.0.1";

bus.on("applicationStarted", function() {
	var firstNonLocalNetworkConfig = _.values(os.networkInterfaces()).flatten().find((e) => e.address !== "127.0.0.1" && e.address !== "::1" );

	if(firstNonLocalNetworkConfig) {
		localIpAddress = firstNonLocalNetworkConfig.address;
	} else {
		console_log("Error: Unable to determine public ip address of this host!");
		console_log( "Exiting...");
		bus.triggerRequestStopApplication({value: 1});
	}
});

var os = require('os');
var localConnectServerUri;
bus.on("connectServerStarted", function(connectServer) {
	localConnectServerUri = "http://"+localIpAddress+":"+connectServer.address().port;
});

var WebSocketServer = require('ws').Server;

var wss = new WebSocketServer({port: 3001});

wss.on('connection', function(ws) {
	var send = function(busMessageId, args) {
		ws.send(JSON.stringify({busMessageId: busMessageId, arguments: args}));
	};

	["logMessage", "logReset"].forEach(function(busMessageId) {
		bus.on(busMessageId, function() {
			send(busMessageId, _.toArray(arguments));
		});
	});

	supportedLogAreaNames.forEach(function(logAreaName) {
		logAreas[logAreaName].forEach(function(logEntry) {
			send("logMessage", [logAreaName, logEntry]);
		});
	});
});
<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var VersionChecker = require('ember-cli-version-checker');
var clone     = require('clone');
var path      = require('path');
var resolve   = require('resolve');

module.exports = {
  name: 'ember-cli-babel',

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    var checker = new VersionChecker(this);
    var dep = checker.for('ember-cli', 'npm');

    this._shouldSetupRegistryInIncluded = !dep.satisfies('>=0.2.0');
  },

  setupPreprocessorRegistry: function(type, registry) {
    var addon = this;

    registry.add('js', {
      name: 'ember-cli-babel',
      ext: 'js',
      toTree: function(tree) {
        return require('broccoli-babel-transpiler')(tree, getBabelOptions(addon));
      }
    });
  },

  shouldIncludePolyfill: function() {
    var addonOptions = getAddonOptions(this);
    return addonOptions.babel && addonOptions.babel.includePolyfill === true;
  },

  importPolyfill: function(app) {
    if (this.import) {  // support for ember-cli >= 2.7
      this.import('vendor/browser-polyfill.js', { prepend: true });
    } else if (app.import) { // support ember-cli < 2.7
      app.import('vendor/browser-polyfill.js', { prepend: true });
    } else {
      console.warn('Please run: ember install ember-cli-import-polyfill')
    }
  },

  treeFor: function(name) {
    if (name !== 'vendor') { return; }
    if (!this.shouldIncludePolyfill()) { return; }

    // Find babel-core's browser polyfill and use its directory as our vendor tree
    var transpilerRoot = path.dirname(resolve.sync('broccoli-babel-transpiler'));
    var polyfillDir = path.dirname(resolve.sync('babel-core/browser-polyfill', { basedir: transpilerRoot }));
    var Funnel = require('broccoli-funnel');
    return new Funnel(polyfillDir, {
      files: ['browser-polyfill.js']
    });
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;

    if (this._shouldSetupRegistryInIncluded) {
      this.setupPreprocessorRegistry('parent', app.registry);
    }

    if (this.shouldIncludePolyfill()) {
      this.importPolyfill(app);
    }
  }
};

function getAddonOptions(addonContext) {
  return (addonContext.parent && addonContext.parent.options) || (addonContext.app && addonContext.app.options) || {};
}

function getBabelOptions(addonContext) {
  var addonOptions = getAddonOptions(addonContext);
  var options = clone(addonOptions.babel || {});

  var compileModules = options.compileModules === true;

  var ui = addonContext.ui;

  // pass a console object that wraps the addon's `UI` object
  options.console = {
    log: function(message) {
      // fallback needed for support of ember-cli < 2.2.0
      if (ui.writeInfoLine) {
        ui.writeInfoLine(message);
      } else {
        ui.writeLine(message, 'INFO');
      }
    },

    warn: function(message) {
      // fallback needed for support of ember-cli < 2.2.0
      if (ui.writeWarnLine) {
        ui.writeWarnLine(message);
      } else {
        ui.writeLine(message, 'WARN');
      }
    },

    error: function(message) {
      // fallback needed for support of ember-cli < 2.2.0
      if (ui.writeError) {
        ui.writeError(message);
      } else {
        ui.writeLine(message, 'ERROR');
      }
    }
  };

  // Ensure modules aren't compiled unless explicitly set to compile
  options.blacklist = options.blacklist || ['es6.modules'];

  // do not enable non-standard transforms
  if (!('nonStandard' in options)) {
    options.nonStandard = false;
  }

  // Remove custom options from `options` hash that is passed to Babel
  delete options.includePolyfill;
  delete options.compileModules;

  if (compileModules) {
    if (options.blacklist.indexOf('es6.modules') >= 0) {
      options.blacklist.splice(options.blacklist.indexOf('es6.modules'), 1);
    }
  } else {
    if (options.blacklist.indexOf('es6.modules') < 0) {
      options.blacklist.push('es6.modules');
    }
  }

  // Ember-CLI inserts its own 'use strict' directive
  options.blacklist.push('useStrict');
  options.highlightCode = false;

  return options;
}
<commit_msg>Add "configKey" property<commit_after>/* jshint node: true */
'use strict';

var VersionChecker = require('ember-cli-version-checker');
var clone     = require('clone');
var path      = require('path');
var resolve   = require('resolve');

module.exports = {
  name: 'ember-cli-babel',
  configKey: 'ember-cli-babel',

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    var checker = new VersionChecker(this);
    var dep = checker.for('ember-cli', 'npm');

    this._shouldSetupRegistryInIncluded = !dep.satisfies('>=0.2.0');
  },

  setupPreprocessorRegistry: function(type, registry) {
    var addon = this;

    registry.add('js', {
      name: 'ember-cli-babel',
      ext: 'js',
      toTree: function(tree) {
        return require('broccoli-babel-transpiler')(tree, getBabelOptions(addon));
      }
    });
  },

  shouldIncludePolyfill: function() {
    var addonOptions = getAddonOptions(this);
    return addonOptions.babel && addonOptions.babel.includePolyfill === true;
  },

  importPolyfill: function(app) {
    if (this.import) {  // support for ember-cli >= 2.7
      this.import('vendor/browser-polyfill.js', { prepend: true });
    } else if (app.import) { // support ember-cli < 2.7
      app.import('vendor/browser-polyfill.js', { prepend: true });
    } else {
      console.warn('Please run: ember install ember-cli-import-polyfill')
    }
  },

  treeFor: function(name) {
    if (name !== 'vendor') { return; }
    if (!this.shouldIncludePolyfill()) { return; }

    // Find babel-core's browser polyfill and use its directory as our vendor tree
    var transpilerRoot = path.dirname(resolve.sync('broccoli-babel-transpiler'));
    var polyfillDir = path.dirname(resolve.sync('babel-core/browser-polyfill', { basedir: transpilerRoot }));
    var Funnel = require('broccoli-funnel');
    return new Funnel(polyfillDir, {
      files: ['browser-polyfill.js']
    });
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;

    if (this._shouldSetupRegistryInIncluded) {
      this.setupPreprocessorRegistry('parent', app.registry);
    }

    if (this.shouldIncludePolyfill()) {
      this.importPolyfill(app);
    }
  }
};

function getAddonOptions(addonContext) {
  return (addonContext.parent && addonContext.parent.options) || (addonContext.app && addonContext.app.options) || {};
}

function getBabelOptions(addonContext) {
  var addonOptions = getAddonOptions(addonContext);
  var options = clone(addonOptions.babel || {});

  var compileModules = options.compileModules === true;

  var ui = addonContext.ui;

  // pass a console object that wraps the addon's `UI` object
  options.console = {
    log: function(message) {
      // fallback needed for support of ember-cli < 2.2.0
      if (ui.writeInfoLine) {
        ui.writeInfoLine(message);
      } else {
        ui.writeLine(message, 'INFO');
      }
    },

    warn: function(message) {
      // fallback needed for support of ember-cli < 2.2.0
      if (ui.writeWarnLine) {
        ui.writeWarnLine(message);
      } else {
        ui.writeLine(message, 'WARN');
      }
    },

    error: function(message) {
      // fallback needed for support of ember-cli < 2.2.0
      if (ui.writeError) {
        ui.writeError(message);
      } else {
        ui.writeLine(message, 'ERROR');
      }
    }
  };

  // Ensure modules aren't compiled unless explicitly set to compile
  options.blacklist = options.blacklist || ['es6.modules'];

  // do not enable non-standard transforms
  if (!('nonStandard' in options)) {
    options.nonStandard = false;
  }

  // Remove custom options from `options` hash that is passed to Babel
  delete options.includePolyfill;
  delete options.compileModules;

  if (compileModules) {
    if (options.blacklist.indexOf('es6.modules') >= 0) {
      options.blacklist.splice(options.blacklist.indexOf('es6.modules'), 1);
    }
  } else {
    if (options.blacklist.indexOf('es6.modules') < 0) {
      options.blacklist.push('es6.modules');
    }
  }

  // Ember-CLI inserts its own 'use strict' directive
  options.blacklist.push('useStrict');
  options.highlightCode = false;

  return options;
}
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

slapp.command('/messagemany', '(.*)', (msg, text, question) => {
  // if "/inorout create Who is in?" is received:
  // text = create Who is in?
  // question = Who is in?

  msg.say('Which channel(s) would you like to post to?').route('handleWhichChannels',{ message: text })
})

slapp.route('handleWhichChannels', (msg, state) => {

    var arr = msg.channelsMentioned()
    for (var i = 0, len = arr.length; i < len; i++) {
        msg.say({
        text: state.message,
          channel: arr[i]
        })
    }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})<commit_msg>fixed for loop<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

slapp.command('/messagemany', '(.*)', (msg, text, question) => {
  // if "/inorout create Who is in?" is received:
  // text = create Who is in?
  // question = Who is in?

  msg.say('Which channel(s) would you like to post to?').route('handleWhichChannels',{ message: text })
})

slapp.route('handleWhichChannels', (msg, state) => {

    var arr = msg.channelsMentioned()
    for (var i = 0; i < arr.length; i++) {
        msg.say({
        text: state.message,
          channel: arr[i]
        })
    }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})<|endoftext|>


<commit_before>var FieldValue = function (field, value, attributeType) {

    this.field = '';
    this.value = '';
    this.attributeType = 'S';

    this.setField = function (field) {
        if (field === undefined) {
            var err = new Error();
            err.message = "'field' is required to Query";
            throw err;
        }
        this.field = field;
    };

    this.setValue = function (value) {
        if (value === undefined) {
            var err = new Error();
            err.message = "'value' is required to Query";
            throw err;
        }

        this.value = value;
    };

    this.setAttributeType = function (attributeType) {
        this.attributeType = attributeType || 'S';
    };

    this.setField(field);
    this.setValue(value);
    this.setAttributeType(attributeType);
};

module.exports = FieldValue;

// TODO: これ、Attribute という名前の方がよい。

<commit_msg>Update throw error<commit_after>var FieldValue = function (field, value, attributeType) {

    this.field = '';
    this.value = '';
    this.attributeType = 'S';

    this.setField = function (field) {
        if (field === undefined) {
            var err = new Error();
            err.message = "'field' is required to Query";
            throw err;
        }
        this.field = field;
    };

    this.setValue = function (value) {
        if (value === undefined) {
            throw new Error('"value" is required to Query');
        }

        this.value = value;
    };

    this.setAttributeType = function (attributeType) {
        this.attributeType = attributeType || 'S';
    };

    this.setField(field);
    this.setValue(value);
    this.setAttributeType(attributeType);
};

module.exports = FieldValue;

// TODO: これ、Attribute という名前の方がよい。

<|endoftext|>


<commit_before>
var http = require('http')
    , url  = require('url')
    , fs   = require('fs');
var neededstats = [];
//var p = __dirname + '/' + req.params.filepath; //there is some error here you haven't defined req yet
http.createServer(function (req,res) {
    if(req.url=='/index.html' || req.url=='/') {
        fs.readFile('./index.html',function(err,data){
            res.end(data);
        });
    } else {
        var url_parts = url.parse(req.url);
        //console.log(url_parts);
        console.log(url_parts.pathname);
        var p = '.' + url_parts.pathname;
        //fs.createReadStream(p).pipe(res);

        fs.stat(p, function (err, stats) {
            if (err) {
                //throw err;
            }
            //neededstats.push(stats.mtime);
            //neededstats.push(stats.size);
            //res.sendFile(p);
        });

        fs.readFile(p,function(err,data){
            if(err) {
                fs.createReadStream(p).pipe(res);
                res.end();
            }
            else
                res.end(data);
        });

    }

    }).listen(80,'0.0.0.0');
console.log('Server running.');

/*
var connect = require('connect');
var http = require('http');
var fs = require('fs');

var app = connect();

function handleRequest(request, response, next) {
    response.writeHead(200, {"Content-Type" : "text/html"});
    fs.createReadStream(request.url).pipe(response);

}

app.use(handleRequest);

http.createServer(app).listen(80);
console.log("Server is running");
    */<commit_msg>added process.env.PORT || 3000 to listen<commit_after>
var http = require('http')
    , url  = require('url')
    , fs   = require('fs');
var neededstats = [];
//var p = __dirname + '/' + req.params.filepath; //there is some error here you haven't defined req yet
http.createServer(function (req,res) {
    if(req.url=='/index.html' || req.url=='/') {
        fs.readFile('./index.html',function(err,data){
            res.end(data);
        });
    } else {
        var url_parts = url.parse(req.url);
        //console.log(url_parts);
        console.log(url_parts.pathname);
        var p = '.' + url_parts.pathname;
        //fs.createReadStream(p).pipe(res);

        fs.stat(p, function (err, stats) {
            if (err) {
                //throw err;
            }
            //neededstats.push(stats.mtime);
            //neededstats.push(stats.size);
            //res.sendFile(p);
        });

        fs.readFile(p,function(err,data){
            if(err) {
                fs.createReadStream(p).pipe(res);
                res.end();
            }
            else
                res.end(data);
        });

    }

    }).listen(process.env.PORT || 3000);
console.log('Server running.');

/*
var connect = require('connect');
var http = require('http');
var fs = require('fs');

var app = connect();

function handleRequest(request, response, next) {
    response.writeHead(200, {"Content-Type" : "text/html"});
    fs.createReadStream(request.url).pipe(response);

}

app.use(handleRequest);

http.createServer(app).listen(80);
console.log("Server is running");
    */<|endoftext|>


<commit_before>define([
  'intern!object',
  'intern/chai!expect',
  'require',
  // https://theintern.github.io/leadfoot/keys.html
  'intern/dojo/node!leadfoot/keys',
], function(registerSuite, expect, require, keys) {

  registerSuite(function() {
    var timeout = 120000;
    var advancesFocusOnTab = false;

    return {
      name: 'maintain/tab-focus',

      before: function() {
        return this.remote
          .get(require.toUrl('test/pages/intern.events.test.html'))
          .findById('first')
            .click()
            .end()
          .pressKeys(keys.TAB)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            advancesFocusOnTab = activeElementId === 'second';
          })

          .get(require.toUrl('test/pages/maintain.tab-focus.test.html'))
          .setPageLoadTimeout(timeout)
          .setFindTimeout(timeout)
          .setExecuteAsyncTimeout(timeout);
      },

      forward: function() {
        this.timeout = timeout;
        if (!advancesFocusOnTab) {
          this.skip('Cannot test Tab focus via WebDriver in this browser');
        }

        return this.remote
          .findById('first')
            .click()
            .end()
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('first', 'initial position');
          })

          .pressKeys(keys.TAB)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('second', 'after first Tab');
          })

          .pressKeys(keys.TAB)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('third', 'after second Tab');
          })

          .pressKeys(keys.TAB)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('first', 'after third Tab');
          });
      },
      backward: function() {
        this.timeout = timeout;
        if (!advancesFocusOnTab) {
          this.skip('Cannot test Tab focus via WebDriver in this browser');
        }

        return this.remote
          .findById('third')
            .click()
            .end()
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('third', 'initial position');
          })

          .pressKeys(keys.SHIFT)
          .pressKeys(keys.TAB)
          .pressKeys(keys.NULL)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('second', 'after first Tab');
          })

          .pressKeys(keys.SHIFT)
          .pressKeys(keys.TAB)
          .pressKeys(keys.NULL)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('first', 'after second Tab');
          })

          .pressKeys(keys.SHIFT)
          .pressKeys(keys.TAB)
          .pressKeys(keys.NULL)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('third', 'after third Tab');
          });
      },
    };
  });
});
<commit_msg>test(maintain/tab-focus): wait until we are really loaded, Chrome on WIN seems too fast<commit_after>define([
  'intern!object',
  'intern/chai!expect',
  'require',
  // https://theintern.github.io/leadfoot/keys.html
  'intern/dojo/node!leadfoot/keys',
  // https://theintern.github.io/leadfoot/pollUntil.html
  'intern/dojo/node!leadfoot/helpers/pollUntil',
], function(registerSuite, expect, require, keys, pollUntil) {

  registerSuite(function() {
    var timeout = 120000;
    var advancesFocusOnTab = false;

    return {
      name: 'maintain/tab-focus',

      before: function() {
        return this.remote
          .get(require.toUrl('test/pages/intern.events.test.html'))
          .findById('first')
            .click()
            .end()
          .pressKeys(keys.TAB)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            advancesFocusOnTab = activeElementId === 'second';
          })

          .get(require.toUrl('test/pages/maintain.tab-focus.test.html'))
          .setPageLoadTimeout(timeout)
          .setFindTimeout(timeout)
          .setExecuteAsyncTimeout(timeout)
          // wait until we're really initialized
          .then(pollUntil('return window.platform'), timeout);
      },

      forward: function() {
        this.timeout = timeout;
        if (!advancesFocusOnTab) {
          this.skip('Cannot test Tab focus via WebDriver in this browser');
        }

        return this.remote
          .findById('first')
            .click()
            .end()
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('first', 'initial position');
          })

          .pressKeys(keys.TAB)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('second', 'after first Tab');
          })

          .pressKeys(keys.TAB)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('third', 'after second Tab');
          })

          .pressKeys(keys.TAB)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('first', 'after third Tab');
          });
      },
      backward: function() {
        this.timeout = timeout;
        if (!advancesFocusOnTab) {
          this.skip('Cannot test Tab focus via WebDriver in this browser');
        }

        return this.remote
          .findById('third')
            .click()
            .end()
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('third', 'initial position');
          })

          .pressKeys(keys.SHIFT)
          .pressKeys(keys.TAB)
          .pressKeys(keys.NULL)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('second', 'after first Tab');
          })

          .pressKeys(keys.SHIFT)
          .pressKeys(keys.TAB)
          .pressKeys(keys.NULL)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('first', 'after second Tab');
          })

          .pressKeys(keys.SHIFT)
          .pressKeys(keys.TAB)
          .pressKeys(keys.NULL)
          .sleep(500)
          .execute('return document.activeElement.id || document.activeElement.nodeName')
          .then(function(activeElementId) {
            expect(activeElementId).to.equal('third', 'after third Tab');
          });
      },
    };
  });
});
<|endoftext|>


<commit_before>/* @flow */

import VNode, { createTextVNode } from 'core/vdom/vnode'
import { isFalse, isTrue, isDef, isUndef, isPrimitive } from 'shared/util'

// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:

// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
export function simpleNormalizeChildren (children: any) {
  for (let i = 0; i < children.length; i++) {
    if (Array.isArray(children[i])) {
      return Array.prototype.concat.apply([], children)
    }
  }
  return children
}

// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
export function normalizeChildren (children: any): ?Array<VNode> {
  return isPrimitive(children)
    ? [createTextVNode(children)]
    : Array.isArray(children)
      ? normalizeArrayChildren(children)
      : undefined
}

function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNode> {
  const res = []
  let i, c, last
  for (i = 0; i < children.length; i++) {
    c = children[i]
    if (isUndef(c) || typeof c === 'boolean') continue
    last = res[res.length - 1]
    //  nested
    if (Array.isArray(c)) {
      res.push.apply(res, normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`))
    } else if (isPrimitive(c)) {
      if (isDef(last) && isDef(last.text)) {
        last.text += String(c)
      } else if (c !== '') {
        // convert primitive to vnode
        res.push(createTextVNode(c))
      }
    } else {
      if (isFalse(c.isComment) && isDef(c.text) && isDef(last) && isFalse(last.isComment) && isDef(last.text)) {
        res[res.length - 1] = createTextVNode(last.text + c.text)
      } else {
        // default key for nested array children (likely generated by v-for)
        if (isTrue(children._isVList) &&
          isDef(c.tag) &&
          isUndef(c.key) &&
          isDef(nestedIndex)) {
          c.key = `__vlist${nestedIndex}_${i}__`
        }
        res.push(c)
      }
    }
  }
  return res
}
<commit_msg>tweak noramlizeArrayChildren<commit_after>/* @flow */

import VNode, { createTextVNode } from 'core/vdom/vnode'
import { isFalse, isTrue, isDef, isUndef, isPrimitive } from 'shared/util'

// The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:

// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
export function simpleNormalizeChildren (children: any) {
  for (let i = 0; i < children.length; i++) {
    if (Array.isArray(children[i])) {
      return Array.prototype.concat.apply([], children)
    }
  }
  return children
}

// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
export function normalizeChildren (children: any): ?Array<VNode> {
  return isPrimitive(children)
    ? [createTextVNode(children)]
    : Array.isArray(children)
      ? normalizeArrayChildren(children)
      : undefined
}

function isTextNode (node): boolean {
  return isDef(node) && isDef(node.text) && isFalse(node.isComment)
}

function normalizeArrayChildren (children: any, nestedIndex?: string): Array<VNode> {
  const res = []
  let i, c, last
  for (i = 0; i < children.length; i++) {
    c = children[i]
    if (isUndef(c) || typeof c === 'boolean') continue
    last = res[res.length - 1]
    //  nested
    if (Array.isArray(c)) {
      res.push.apply(res, normalizeArrayChildren(c, `${nestedIndex || ''}_${i}`))
    } else if (isPrimitive(c)) {
      if (isTextNode(last)) {
        (last: any).text += String(c)
      } else if (c !== '') {
        // convert primitive to vnode
        res.push(createTextVNode(c))
      }
    } else {
      if (isTextNode(c) && isTextNode(last)) {
        res[res.length - 1] = createTextVNode(last.text + c.text)
      } else {
        // default key for nested array children (likely generated by v-for)
        if (isTrue(children._isVList) &&
          isDef(c.tag) &&
          isUndef(c.key) &&
          isDef(nestedIndex)) {
          c.key = `__vlist${nestedIndex}_${i}__`
        }
        res.push(c)
      }
    }
  }
  return res
}
<|endoftext|>


<commit_before>/* eslint-env browser, jquery */
/* eslint quotes: [2, "single"], strict: 0 */
/* global Handlebars:false */

var cardTemplate;

function card (title, image, location, price, power, registration, mileage, consumption) {
    return {
        title: title,
        image: image,
        location: location,
        price: price,
        power: power,
        registration: registration,
        mileage: mileage,
        consumption: consumption
    };
}

var cards = [
    card('Audi A6 long long long long long long', 'lorempixel.com/400/300/transport/', 'August-Bebel-Str. 4, 14482 Potsdam', '34000', '140', '2006', '23000', '7'),
    card('VW Polo', 'i.ebayimg.com/00/s/NjAwWDgwMA==/z/IVgAAOSwPhdU-FPW/$_8.jpg', 'August-Bebel-Str. 12, 15345 Rehfelde', '5600', '90', '1997', '230000', '6'),
    card('Kaputte Karre', 'i.ebayimg.com/00/s/NDgwWDY0MA==/$T2eC16VHJGYFFlLe3qSvBReifcZW2!~~48_8.jpg', 'Großer Stern, 10355 Berlin', '300', '80', '2000', '104000', '14')
];

function templates () {
    cardTemplate = Handlebars.compile($('#card-template').html());
    Handlebars.registerHelper('trimString', function(passedString) {
        var theString = passedString.substring(0, 20);
        if (theString !== passedString) {
            theString += '…';
        }
        return new Handlebars.SafeString(theString);
    });
}

function UI () {
    var self = this;
    self.player = {
        name: ''
    };
    self.position = null;

    self.$allViews = $('.startView, .compareView, .cardView, .waitingView');

    $('#usernameForm').submit(function (e) {
        e.preventDefault();
        var data = {
            action: 'init',
            name: '',
            data: {
                lat: self.position.lat,
                long: self.position.lng
            }
        };

        if ($.trim($('#usernameForm #username').val()) === '') {
            alert('kein Username eingegeben');
        } else {
            data.name = $.trim($('#usernameForm #username').val());
            self.player.name = data.name;
            self.socket.send(JSON.stringify(data));
        }
    });

    $('.cardView').on('click', 'button', function () {
        self.disableCardButtons();
        var attributeToCompare = $(this).data('attribute');
        console.log('send selected attribute');
        self.socket.send(JSON.stringify({
            action: 'attributeSelected',
            name: self.player.name,
            data: {
                attributeToCompare: attributeToCompare
            }
        }));
    });

    navigator.geolocation.getCurrentPosition(
        function (position) {
            self.setPosition(position);
        },
        self.positionError
    );

    templates();

    // server: 87.106.33.22
    self.socket = new WebSocket('ws://localhost:8080', []);

    self.socket.onopen = function () {
        console.info('connected to server');
    };

    // Log errors
    self.socket.onerror = function (error) {
        console.log('WebSocket Error ' + error);
    };

    // Log messages from the server
    self.socket.onmessage = function (e) {
        // e is event object
        // server message is in e.data
        console.log('Server: ', e.data);

        var response = JSON.parse(e.data);
        switch (response.action) {
            case 'accepted':
                self.activateView('.waitingView');
                break;
            case 'start':
            case 'next':
                if (response.data.winner_card) {
                    self.createCompareView(
                        response.data.all_cards,
                        response.data.winner_card,
                        response.data.attribute_compared,
                        response.data.card,
                        response.data.turn);
                } else {
                    self.startNextRound(response.data.card, response.data.turn);
                }
                break;
            default:
                break;
        }
    };

    //self.createCardView(cards[0]);
    //self.createCompareView(cards);
}

UI.prototype.setPosition = function (position) {
    this.position = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
    };
    $('#locationMessage').hide();
    $('#usernameForm').show();
};

UI.prototype.positionError = function (err) {
    var message = '';
    if (err.code === 1) {
        message = 'Du musst deinen Standort mitteilen, um spielen zu k\u00f6nnen.';
    } else if (err.code === 2) {
        message = 'Dein Standort konnte nicht ermittelt werden.';
    }
    $('#locationMessage')
        .removeClass('panel-default')
        .addClass('panel-danger');
    $('#locationMessage .panel-body').html(message);
    console.log(err.code);
};

UI.prototype.createCompareView = function (cards, winnerCard, attributeCompared, nextCard, nextTurn) {
    var self = this;
    self.activateView('.compareView');
    $('.compareView').html('');

    cards.forEach(function (e) {
        $('.compareView').append(cardTemplate(e));
    });

    self.disableCardButtons();

    $('.card button[data-attribute="' + attributeCompared + '"]').addClass('btn-primary');

    if (nextCard !== undefined) {
        var endTime = Date.now() + 5000;
        $('.progress').show();
        var interval = setInterval(function () {
            var currentTime = Date.now();
            if (currentTime > endTime) {
                clearInterval(interval);
                $('.progress .progress-bar').width('100%');
                $('.progress').hide();
                self.startNextRound(nextCard, nextTurn);
            } else {
                $('.progress .progress-bar').width(((endTime - currentTime) / 50).toString() + '%');
            }
        }, 75);
    }
};

UI.prototype.createCardView = function (card) {
    this.activateView('.cardView');

    $('.cardView').html(cardTemplate(card));
};

UI.prototype.activateView = function (view) {
    this.$allViews.hide();
    $(view).show();
};

UI.prototype.setActivePlayer = function (playerName) {
    if (playerName !== this.player.name) {
        this.disableCardButtons();
    }
};

UI.prototype.disableCardButtons = function () {
    $('.card button').addClass('disabled');
};

UI.prototype.startNextRound = function (card, turn) {
    this.createCardView(card);
    this.setActivePlayer(turn);
};

var userInterface = new UI();
<commit_msg>extend sample stuff<commit_after>/* eslint-env browser, jquery */
/* eslint quotes: [2, "single"], strict: 0 */
/* global Handlebars:false */

var cardTemplate;

function card (title, image, location, price, power, registration, mileage, consumption, url) {
    return {
        title: title,
        image: image,
        location: location,
        price: price,
        power: power,
        registration: registration,
        mileage: mileage,
        consumption: consumption,
        url: url
    };
}

var cards = [
    card('Audi A6 long long long long long long', 'lorempixel.com/400/300/transport/', 'August-Bebel-Str. 4, 14482 Potsdam', '34000', '140', '2006', '23000', '7'),
    card('VW Polo', 'i.ebayimg.com/00/s/NjAwWDgwMA==/z/IVgAAOSwPhdU-FPW/$_8.jpg', 'August-Bebel-Str. 12, 15345 Rehfelde', '5600', '90', '1997', '230000', '6'),
    card('Kaputte Karre', 'i.ebayimg.com/00/s/NDgwWDY0MA==/$T2eC16VHJGYFFlLe3qSvBReifcZW2!~~48_8.jpg', 'Großer Stern, 10355 Berlin', '300', '80', '2000', '104000', '14')
];

function templates () {
    cardTemplate = Handlebars.compile($('#card-template').html());
    Handlebars.registerHelper('trimString', function(passedString) {
        var theString = passedString.substring(0, 20);
        if (theString !== passedString) {
            theString += '…';
        }
        return new Handlebars.SafeString(theString);
    });
}

function UI () {
    var self = this;
    self.player = {
        name: ''
    };
    self.position = null;

    self.$allViews = $('.startView, .compareView, .cardView, .waitingView');

    $('#usernameForm').submit(function (e) {
        e.preventDefault();
        var data = {
            action: 'init',
            name: '',
            data: {
                lat: self.position.lat,
                long: self.position.lng
            }
        };

        if ($.trim($('#usernameForm #username').val()) === '') {
            alert('kein Username eingegeben');
        } else {
            data.name = $.trim($('#usernameForm #username').val());
            self.player.name = data.name;
            self.socket.send(JSON.stringify(data));
        }
    });

    $('.cardView').on('click', 'button', function () {
        self.disableCardButtons();
        var attributeToCompare = $(this).data('attribute');
        console.log('send selected attribute');
        self.socket.send(JSON.stringify({
            action: 'attributeSelected',
            name: self.player.name,
            data: {
                attributeToCompare: attributeToCompare
            }
        }));
    });

    navigator.geolocation.getCurrentPosition(
        function (position) {
            self.setPosition(position);
        },
        self.positionError
    );

    templates();

    // server: 87.106.33.22
    self.socket = new WebSocket('ws://localhost:8080', []);

    self.socket.onopen = function () {
        console.info('connected to server');
    };

    // Log errors
    self.socket.onerror = function (error) {
        console.log('WebSocket Error ' + error);
    };

    // Log messages from the server
    self.socket.onmessage = function (e) {
        // e is event object
        // server message is in e.data
        console.log('Server: ', e.data);

        var response = JSON.parse(e.data);
        switch (response.action) {
            case 'accepted':
                self.activateView('.waitingView');
                break;
            case 'start':
            case 'next':
                if (response.data.winner_card) {
                    self.createCompareView(
                        response.data.all_cards,
                        response.data.winner_card,
                        response.data.attribute_compared,
                        response.data.card,
                        response.data.turn);
                } else {
                    self.startNextRound(response.data.card, response.data.turn);
                }
                break;
            default:
                break;
        }
    };

    //self.createCardView(cards[0]);
    //self.createCompareView(cards);
}

UI.prototype.setPosition = function (position) {
    this.position = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
    };
    $('#locationMessage').hide();
    $('#usernameForm').show();
};

UI.prototype.positionError = function (err) {
    var message = '';
    if (err.code === 1) {
        message = 'Du musst deinen Standort mitteilen, um spielen zu k\u00f6nnen.';
    } else if (err.code === 2) {
        message = 'Dein Standort konnte nicht ermittelt werden.';
    }
    $('#locationMessage')
        .removeClass('panel-default')
        .addClass('panel-danger');
    $('#locationMessage .panel-body').html(message);
    console.log(err.code);
};

UI.prototype.createCompareView = function (cards, winnerCard, attributeCompared, nextCard, nextTurn) {
    var self = this;
    self.activateView('.compareView');
    $('.compareView').html('');

    cards.forEach(function (e) {
        $('.compareView').append(cardTemplate(e));
    });

    self.disableCardButtons();

    $('.card button[data-attribute="' + attributeCompared + '"]').addClass('btn-primary');

    if (nextCard !== undefined) {
        var endTime = Date.now() + 5000;
        $('.progress').show();
        var interval = setInterval(function () {
            var currentTime = Date.now();
            if (currentTime > endTime) {
                clearInterval(interval);
                $('.progress .progress-bar').width('100%');
                $('.progress').hide();
                self.startNextRound(nextCard, nextTurn);
            } else {
                $('.progress .progress-bar').width(((endTime - currentTime) / 50).toString() + '%');
            }
        }, 75);
    }
};

UI.prototype.createCardView = function (card) {
    this.activateView('.cardView');

    $('.cardView').html(cardTemplate(card));
};

UI.prototype.activateView = function (view) {
    this.$allViews.hide();
    $(view).show();
};

UI.prototype.setActivePlayer = function (playerName) {
    if (playerName !== this.player.name) {
        this.disableCardButtons();
    }
};

UI.prototype.disableCardButtons = function () {
    $('.card button').addClass('disabled');
};

UI.prototype.startNextRound = function (card, turn) {
    this.createCardView(card);
    this.setActivePlayer(turn);
};

var userInterface = new UI();
<|endoftext|>


<commit_before>/*
 * Embeder builds a container for the link in regard of the extenion
 * embeder is a static object (less memory burnt)
 * therefore after inclusion : use it this way
 * > embeder.href="something.avi";
 * > container=emebeder.popup();
 *
 * Attributes are cleaned after popup so that I see errors
 *
 * principle :
 * get extension using embeder.ext()
 * watch in list of extension the type (html5 video or audio or embeded object)
 * generate a container in regard to the type.
 * therefore adding new mime type will be easy
 */
embeder = {
    ext: function() {
        this.extension=this.href.split('.').reverse()[0].toLowerCase();
    },
   mimetype: {
        mp3:    'audio/mpeg',
        wmv : 'video/x-ms-wmv'
   },
   //so we can use an hidden div to set it to .... vlc plugin for instance
   defVidType: 'video/x-msvideo',
    type2popup :  {
        vid : function() {
            embd=embeder;
            return('<video id=img width="' + embd.width + '" src="' + embd.href + '"/>' )
        },
        embed : function() {
            embd=embeder;
            return('<embed id=img width="' + embd.width + '"  src="' + embd.href + '" type="' + (
                (   embd.extension in embd.mimetype )      ?
                    embd.mimetype[embd.extension]       :
                    embd.defVidType ) +
                '" />' )
        },
        aud : function() {
            embd=embeder;
            return('<audio id=img width="' + embd.width + '" src="' + embd.href + '"/>' )
        }
   },
   ext2type : {
        wmv:    "embed",
        ogg :   "vid",
        wav:    "aud",
        mov:    'embed',
        mpeg:   'embed',
        mpg:    'embed',
        avi:    'embed',
        mkv:    'embed',
        mp4:    'embed',
        mp3:    'embed'
   },

   clean: function() {
    this.href=null;
    this.width=null;
    this.extension=null;
   },
   popup: function() {
        this.ext();
        //throw exception if this.href==null
        popup=(this.extension in this.ext2type)                         ?
                popup= this.type2popup[this.ext2type[this.extension]]() :
                '';
        this.clean();
        return popup;
    },
};

<commit_msg>still the gallery is made to download the contents :)<commit_after>/*
 * Embeder builds a container for the link in regard of the extenion
 * embeder is a static object (less memory burnt)
 * therefore after inclusion : use it this way
 * > embeder.href="something.avi";
 * > container=emebeder.popup();
 *
 * Attributes are cleaned after popup so that I see errors
 *
 * principle :
 * get extension using embeder.ext()
 * watch in list of extension the type (html5 video or audio or embeded object)
 * generate a container in regard to the type.
 * therefore adding new mime type will be easy
 */
embeder = {
    ext: function() {
        this.extension=this.href.split('.').reverse()[0].toLowerCase();
    },
   mimetype: {
        mp3:    'audio/mpeg',
        wmv : 'video/x-ms-wmv'
   },
   dlMe: function() {
    return ('
Download here
');
   },
   //so we can use an hidden div to set it to .... vlc plugin for instance
   defVidType: 'video/x-msvideo',
    type2popup :  {
        vid : function() {
            embd=embeder;
            return('<video id=img width="' + embd.width + '" src="' + embd.href + '"/>'  );
        },
        embed : function() {
            embd=embeder;
            return('<embed id=img width="' + embd.width + '"  src="' + embd.href + '" type="' + (
                (   embd.extension in embd.mimetype )      ?
                    embd.mimetype[embd.extension]       :
                    embd.defVidType ) +
                '" /> ' )
        },
        aud : function() {
            embd=embeder;
            return('<audio id=img width="' + embd.width + '" src="' + embd.href + '"/>' )
        }
   },
   ext2type : {
        wmv:    "embed",
        ogg :   "vid",
        wav:    "aud",
        mov:    'embed',
        mpeg:   'embed',
        mpg:    'embed',
        avi:    'embed',
        mkv:    'embed',
        mp4:    'embed',
        mp3:    'embed'
   },

   clean: function() {
    this.href=null;
    this.width=null;
    this.extension=null;
   },
   popup: function() {
        this.ext();
        //throw exception if this.href==null
        popup=(this.extension in this.ext2type)                         ?
                popup= this.type2popup[this.ext2type[this.extension]]() + this.dlMe() :
                '';
        this.clean();
        return popup;
    },
};

<|endoftext|>


<commit_before>import { createLogic } from 'redux-logic';

import { mapRefocus } from 'fm3/actions/mapActions';
import { startProgress, stopProgress } from 'fm3/actions/mainActions';
import { toastsAddError } from 'fm3/actions/toastsActions';
import { gallerySetImages } from 'fm3/actions/galleryActions';
import { infoPointSet } from 'fm3/actions/infoPointActions';

const galleryRequestImagesLogic = createLogic({
  cancelType: ['SET_TOOL', 'MAP_RESET'],
  type: 'GALLERY_REQUEST_IMAGES',
  process({ action: { payload: { lat, lon } }, getState, cancelled$ }, dispatch, done) {
    const pid = Math.random();
    dispatch(startProgress(pid));
    cancelled$.subscribe(() => {
      dispatch(stopProgress(pid));
    });

    fetch(`http://www.freemap.sk:3000/gallery/pictures?lat=${lat}&lon=${lon}&distance=${5000 / 2 ** getState().map.zoom}`)
      .then(res => res.json())
      .then((payload) => {
        dispatch(gallerySetImages(payload.map(item => toImage(item))));
      })
      .catch((e) => {
        dispatch(toastsAddError(`Nastala chyba pri načítavaní obrázkov: ${e.message}`));
      })
      .then(() => {
        dispatch(stopProgress(pid));
        done();
      });
  },
});

const galleryRequestImageLogic = createLogic({
  cancelType: ['SET_TOOL', 'MAP_RESET'],
  type: 'GALLERY_REQUEST_IMAGE',
  process({ action: { payload: id }, getState, cancelled$ }, dispatch, done) {
    const pid = Math.random();
    dispatch(startProgress(pid));
    cancelled$.subscribe(() => {
      dispatch(stopProgress(pid));
    });

    fetch(`http://www.freemap.sk:3000/gallery/picture/${id}`)
      .then(res => res.json())
      .then((payload) => {
        dispatch(gallerySetImages([toImage(payload)]));
      })
      .catch((e) => {
        dispatch(toastsAddError(`Nastala chyba pri načítavaní obrázku: ${e.message}`));
      })
      .then(() => {
        dispatch(stopProgress(pid));
        done();
      });
  },
});

const galleryShowOnTheMapLogic = createLogic({
  type: 'GALLERY_SHOW_ON_THE_MAP',
  process({ getState }, dispatch, done) {
    const { images, activeImageId } = getState().gallery;
    const activeImage = activeImageId ? images.find(({ id }) => id === activeImageId) : null;
    if (activeImage) {
      dispatch(infoPointSet(activeImage.lat, activeImage.lon, activeImage.title));
      dispatch(mapRefocus({ lat: activeImage.lat, lon: activeImage.lon }));
    }
    done();
  },
});

function toImage(payload) {
  return { ...payload, createdAt: new Date(payload.createdAt) }; // TODO validate payload
}

export default [galleryRequestImagesLogic, galleryRequestImageLogic, galleryShowOnTheMapLogic];
<commit_msg>added check if user is authenticated before showing gallery upload modal<commit_after>import { createLogic } from 'redux-logic';

import { mapRefocus } from 'fm3/actions/mapActions';
import { startProgress, stopProgress } from 'fm3/actions/mainActions';
import { toastsAddError } from 'fm3/actions/toastsActions';
import { gallerySetImages } from 'fm3/actions/galleryActions';
import { infoPointSet } from 'fm3/actions/infoPointActions';

const galleryRequestImagesLogic = createLogic({
  cancelType: ['SET_TOOL', 'MAP_RESET'],
  type: 'GALLERY_REQUEST_IMAGES',
  process({ action: { payload: { lat, lon } }, getState, cancelled$ }, dispatch, done) {
    const pid = Math.random();
    dispatch(startProgress(pid));
    cancelled$.subscribe(() => {
      dispatch(stopProgress(pid));
    });

    fetch(`http://www.freemap.sk:3000/gallery/pictures?lat=${lat}&lon=${lon}&distance=${5000 / 2 ** getState().map.zoom}`)
      .then(res => res.json())
      .then((payload) => {
        dispatch(gallerySetImages(payload.map(item => toImage(item))));
      })
      .catch((e) => {
        dispatch(toastsAddError(`Nastala chyba pri načítavaní obrázkov: ${e.message}`));
      })
      .then(() => {
        dispatch(stopProgress(pid));
        done();
      });
  },
});

const galleryRequestImageLogic = createLogic({
  cancelType: ['SET_TOOL', 'MAP_RESET'],
  type: 'GALLERY_REQUEST_IMAGE',
  process({ action: { payload: id }, getState, cancelled$ }, dispatch, done) {
    const pid = Math.random();
    dispatch(startProgress(pid));
    cancelled$.subscribe(() => {
      dispatch(stopProgress(pid));
    });

    fetch(`http://www.freemap.sk:3000/gallery/picture/${id}`)
      .then(res => res.json())
      .then((payload) => {
        dispatch(gallerySetImages([toImage(payload)]));
      })
      .catch((e) => {
        dispatch(toastsAddError(`Nastala chyba pri načítavaní obrázku: ${e.message}`));
      })
      .then(() => {
        dispatch(stopProgress(pid));
        done();
      });
  },
});

const galleryShowOnTheMapLogic = createLogic({
  type: 'GALLERY_SHOW_ON_THE_MAP',
  process({ getState }, dispatch, done) {
    const { images, activeImageId } = getState().gallery;
    const activeImage = activeImageId ? images.find(({ id }) => id === activeImageId) : null;
    if (activeImage) {
      dispatch(infoPointSet(activeImage.lat, activeImage.lon, activeImage.title));
      dispatch(mapRefocus({ lat: activeImage.lat, lon: activeImage.lon }));
    }
    done();
  },
});

const galleryUploadLogic = createLogic({
  type: 'SET_ACTIVE_MODAL',
  transform({ getState, action }, next) {
    if (action.payload === 'gallery-upload' && !getState().auth.user) {
      next(toastsAddError('Pre nahrávanie obrázkov do galérie musíte byť prihlásený.'));
    } else {
      next(action);
    }
  },
});

function toImage(payload) {
  return { ...payload, createdAt: new Date(payload.createdAt) }; // TODO validate payload
}

export default [galleryRequestImagesLogic, galleryRequestImageLogic, galleryShowOnTheMapLogic, galleryUploadLogic];
<|endoftext|>


<commit_before>
var Promise
var pseudoRandomBytes = require('crypto').pseudoRandomBytes
var escape = require('base64-url').escape

module.exports = uid

function uid(length, callback) {
  if (callback) {
    return generateUid(length, callback)
  }

  if (!Promise) {
    Promise = require('native-or-bluebird')
  }

  return new Promise(function (resolve, reject) {
    generateUid(length, function (err, str) {
      if (err) return reject(err)
      resolve(str)
    })
  })
}

uid.sync = function uid_sync(length) {
  return escapeBuffer(pseudoRandomBytes(length))
}

function escapeBuffer(buf) {
  return escape(buf.toString('base64'))
}

function generateUid(length, callback) {
  pseudoRandomBytes(length, function (err, buf) {
    if (err) return cb(err)
    callback(null, escapeBuffer(buf))
  })
}
<commit_msg>build: add source comments<commit_after>/*!
 * uid-safe
 * Copyright(c) 2014 Jonathan Ong
 * MIT Licensed
 */

/**
 * Module dependencies.
 * @private
 */

var Promise
var pseudoRandomBytes = require('crypto').pseudoRandomBytes
var escape = require('base64-url').escape

/**
 * Module exports.
 */

module.exports = uid
module.exports.sync = uidSync

/**
 * Create a unique ID.
 *
 * @param {number} length
 * @param {function} [callback]
 * @return {Promise}
 * @public
 */

function uid(length, callback) {
  if (callback) {
    return generateUid(length, callback)
  }

  if (!Promise) {
    Promise = require('native-or-bluebird')
  }

  return new Promise(function (resolve, reject) {
    generateUid(length, function (err, str) {
      if (err) return reject(err)
      resolve(str)
    })
  })
}

/**
 * Create a unique ID sync.
 *
 * @param {number} length
 * @return {string}
 * @public
 */

function uidSync(length) {
  return toString(pseudoRandomBytes(length))
}

/**
 * Generate a unique ID string.
 *
 * @param {number} length
 * @param {function} callback
 * @private
 */

function generateUid(length, callback) {
  pseudoRandomBytes(length, function (err, buf) {
    if (err) return cb(err)
    callback(null, toString(buf))
  })
}

/**
 * Change a Buffer into a string.
 *
 * @param {Buffer} buf
 * @return {string}
 * @private
 */

function toString(buf) {
  return escape(buf.toString('base64'))
}
<|endoftext|>


<commit_before>// This file is just added for convenience so this repository can be
// directly checked out into a project's deps folder
exports.timestamper = require('./lib/timestamper');

exports.slugger = require('./lib/slugger');

exports.authenticator = require('./lib/authenticator');
<commit_msg>Add validators to index<commit_after>// This file is just added for convenience so this repository can be
// directly checked out into a project's deps folder
exports.timestamper = require('./lib/timestamper');

exports.slugger = require('./lib/slugger');

exports.authenticator = require('./lib/authenticator');

exports.validators = require('./lib/validators');
<|endoftext|>


<commit_before>// OpenShift runner

var http = require('http'),
    txf = require('./index.js'),
    server = http.createServer();

var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var default_sender_secret = process.env.DEFAULT_SENDER_SECRET || '';
var default_receiver_secret = process.env.DEFAULT_RECEIVER_SECRET || '';

server.listen(port, ip, function()
{
    console.log('listening on', ip, port);
    txf(server, {
        default: { sender: default_sender_secret,
                   receiver: default_receiver_secret } });
});

<commit_msg>Log IP and port<commit_after>// OpenShift runner

var http = require('http'),
    txf = require('./index.js'),
    server = http.createServer();

var ip = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
var default_sender_secret = process.env.DEFAULT_SENDER_SECRET || '';
var default_receiver_secret = process.env.DEFAULT_RECEIVER_SECRET || '';

console.log('starting', ip, port);

server.listen(port, ip, function()
{
    console.log('listening on', ip, port);
    txf(server, {
        default: { sender: default_sender_secret,
                   receiver: default_receiver_secret } });
});

<|endoftext|>


<commit_before>/*
Rushed ugly code by <thomasalwyndavis@gmail.com>

Will clean up and make available

*/
var MailChimpAPI = require('mailchimp').MailChimpAPI;
//
var apiKey = process.env.MAILCHIMP_API_KEY;

try {
    var api = new MailChimpAPI(apiKey, { version : '2.0' });
} catch (error) {
    console.log(error.message);
}

var express = require('express');
var port = process.env.PORT || 8080;
var allowCrossDomain = function(req, res, next) {
  var allowedHost = [
    'http://2.stopwatching.us',
    'http://localhost:4000'
  ];
  if(allowedHost.indexOf(req.headers.origin) !== -1 ) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
    next();
  } else {
    res.send({auth: false});
  }
}

var server = express();
server.use(express.bodyParser());
server.use(allowCrossDomain);

server.options("*", function(req,res,next){res.send({});});

server.post('/subscribe', function(req,res,next){

    var email = req.body.email;
    var name = req.body.name || '';
    var phone = req.body.phone || '';
    var zipcode = req.body.zipcode || '';

    api.call('lists', 'subscribe', {
        id: 'c05d6bd75f',
        email: {email: email},
        merge_vars: {
          EMAIL: email,
          PHONE: phone,
          ZIPCODE: zipcode,
          NAME: name
        },
        send_welcome: true,
        double_optin: false

    }, function (error, data) {
    if (error)
        res.send({error: error.message});
    else
        res.send(JSON.stringify(data)); // Do something with your data!
});
});

  server.listen(port, function() {
    console.log('%s listening at %s', server.name, server.url);
  });

<commit_msg>stop watching us<commit_after>/*
Rushed ugly code by <thomasalwyndavis@gmail.com>

Will clean up and make available

*/
var MailChimpAPI = require('mailchimp').MailChimpAPI;
//
var apiKey = process.env.MAILCHIMP_API_KEY;

try {
    var api = new MailChimpAPI(apiKey, { version : '2.0' });
} catch (error) {
    console.log(error.message);
}

var express = require('express');
var port = process.env.PORT || 8080;
var allowCrossDomain = function(req, res, next) {
  var allowedHost = [
    'http://dev.stopwatching.us',
    'http://rally.stopwatching.us',
    'http://2.stopwatching.us',
    'http://localhost:4000'
  ];
  if(allowedHost.indexOf(req.headers.origin) !== -1 ) {
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Origin', req.headers.origin)
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
    next();
  } else {
    res.send({auth: false});
  }
}

var server = express();
server.use(express.bodyParser());
server.use(allowCrossDomain);

server.options("*", function(req,res,next){res.send({});});

server.post('/subscribe', function(req,res,next){

    var email = req.body.email;
    var name = req.body.name || '';
    var phone = req.body.phone || '';
    var zipcode = req.body.zipcode || '';

    api.call('lists', 'subscribe', {
        id: 'c05d6bd75f',
        email: {email: email},
        merge_vars: {
          EMAIL: email,
          PHONE: phone,
          ZIPCODE: zipcode,
          NAME: name
        },
        send_welcome: true,
        double_optin: false

    }, function (error, data) {
    if (error)
        res.send({error: error.message});
    else
        res.send(JSON.stringify(data)); // Do something with your data!
});
});

  server.listen(port, function() {
    console.log('%s listening at %s', server.name, server.url);
  });

<|endoftext|>