<commit_before>var React = require('react'),
    _ = require('underscore'),
    fin = require('../vendor/openfin.js');

var animationWindows = [],
    blotter,
    inLoop = false,
    cubeSize = 185,
    locations = [],
    numColumns = 6,
    numRows = 3,
    demoTiles = {},
    numTiles = numRows * numColumns + 1,
// Have the grid windows been created yet?
    _tilesCreated = false;

/* Static data for the floating 'trade' animation windows */

var rndData = [
    {ticker: "PCL", last: 21.251049070187836},
    {ticker: "SWI", last: 24.835458631124418},
    {ticker: "TCK", last: 6.235665990223004},
    {ticker: "DBD", last: 17.01733357355432},
    {ticker: "FHN", last: 6.624939800309766},
    {ticker: "EXR", last: 33.96528484183794},
    {ticker: "BP", last: 21.19160933461151},
    {ticker: "WCN", last: 23.501467942817747},
    {ticker: "PRE", last: 53.67873008625956},
    {ticker: "ITT", last: 22.803668802786465},
    {ticker: "BIN", last: 12.594969339431945},
    {ticker: "WTM", last: 348.8851038882928},
    {ticker: "FHN", last: 6.624939800309766},
    {ticker: "CYH", last: 19.131071861657016},
    {ticker: "SWK", last: 52.198226722926165},
    {ticker: "AMG", last: 127.23849660464248},
    {ticker: "BCE", last: 22.765628088640174},
    {ticker: "ACC", last: 14.787034222549517},
    {ticker: "AA", last: 13.787034222549517}];

var floor = Math.floor;
var random = Math.random;

fin.desktop.main(()=>{

    initAnimationWindows().then(function(val){
        fin.desktop.System.deleteCacheOnRestart(function () {
            console.log("successfully deleted cache");
        },function (err) {
            console.log("failure to delete cache: " + err);
        });

        fin.desktop.System.addEventListener('monitor-info-changed', function (evnt) {
            console.log("The monitor information has changed to: ", evnt);
            document.dispatchEvent(new CustomEvent('monitor-changed', {'detail': evnt}));
        }, function () {
            console.log("The registration of 'monitor-info-changed' was successful");
        },function (err) {
            console.log("failure: registration of 'monitor-info-changed' " + err);
        });
    });
});

/* Initialises all the floating 'trade' windows. */
var initAnimationWindows = function(){
    console.log("initAnimationWindows called _tilesCreated == ",_tilesCreated);
    return new Promise(function(resolve, reject){
        if(_tilesCreated){
            resolve()
        } else{
            var top = 5, left = 5, i = 1;
            for (; i < numTiles; i++){
                console.log("LOOP ",i, " numTiles ",numTiles);
                animationWindows.push(new fin.desktop.Window({
                    name: 'tile' + random(),
                    url: 'trade.html?t=' + rndData[i].ticker + '&l=' + rndData[i].last,
                    autoShow: false,
                    defaultHeight: cubeSize,
                    minHeight: cubeSize,
                    maxHeight:cubeSize,
                    defaultWidth: cubeSize,
                    minWidth:cubeSize,
                    maxWidth:cubeSize,
                    resizable:false,
                    frame: false,
                    maximizable: false,
                    saveWindowState: false,
                    defaultTop: top,
                    defaultLeft: left,
                    icon: "http://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/img/openfin.ico"
                }));

                locations.push({
                    top: top,
                    left: left,
                    duration: 1000
                });

                left += cubeSize + 5;

                if (i && !(i % numColumns)) {
                    left = 5;
                    top += cubeSize + 5;
                }
                if(i === numTiles-1){
                    console.log(" _tilesCreated === true");
                    _tilesCreated = true;
                    resolve();
                }
            }
        }
    });
};

/* If the blotter has not been created yet, create it and return a promise...*/
var initBlotter = function(){
    var _blotterPromise = new Promise((resolve, reject)=>{
        blotter = new fin.desktop.Window({
            name: 'blotter',
            url: 'hypergrid.html',
            autoShow: false,
            defaultWidth: 960,
            maxWidth: 960,
            minWidth: 960,
            maxHeight: 594,
            defaultHeight: 594,
            minHeight: 594,
            resizable:false,
            frame: false,
            maximizable: false,
            "icon": "http://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/img/openfin.ico"
        }, ()=>{
            resolve();
        })
    });
    return _blotterPromise
}

function showAsPromise (wnd) {
    return new Promise((resolve)=>{
        fin.desktop.main(()=>{
            wnd.show(()=>{
                resolve();
            },()=>{
                reject();
            });
        })
    })
}

function setTranspatentAsPromise(arr, opacity) {
    return new Promise((transparentFinished, transparentFailed)=>{
        Promise.all(arr.map((item)=>{
            return new Promise((resolve, reject)=>{
                item.updateOptions({opacity: opacity}, ()=>{
                    resolve();
                }, ()=>{
                    reject()
                });
            });
        }))
            .then(()=>{
                transparentFinished();
            }, ()=>{
                transparentFailed();
            });
    });
}

module.exports = React.createClass({
    closeApp: function(){
        fin.desktop.main(function(){
            fin.desktop.Application.getCurrent().close();
        });
    },
    minApp: function(){
        fin.desktop.main(function(){
            fin.desktop.Window.getCurrent().minimize();
        });
    },
    showWindows: function(){
        console.log("showWindows called");
        animationWindows.forEach((wnd)=>{
            try{
                wnd.show();
            }catch(err){
                //--
            }
        });
        this.animateWindows(animationWindows, false);
        this.setState({
            animationWindowsShowing: true,
            tilesMaximised: true
        });
    },
    toggleMinimised:function(){
        this.state.tilesMaximised ? this.minWindows() : this.restoreWindows();
    },
    minWindows: function() {
        animationWindows.forEach((wnd)=>{
            wnd.minimize();
        });
        this.setState({
            tilesMaximised: false
        })
    },
    restoreWindows: function () {
        this.openAnimationWindows();
        animationWindows.forEach((wnd)=>{
            wnd.restore();
        });

        this.setState({
            animationWindowsShowing: true,
            tilesMaximised: true
        })
    },
    toggleShowAnimationWindows:function(){
        console.log("toggleShowAnimationWindows called this. openAnimationWindows = ", this.openAnimationWindows);
        if(this.state.animationWindowsShowing){
            this.openAnimationWindows()
        }else{
            this.closeAnimationWindows();
        }
    },
    openAnimationWindows:function(){
        console.log(" openAnimationWindows called ");
        initAnimationWindows().then(()=>{
            console.log(" initAnimationWindows resolved ");
            this.showWindows();
        });
    },
    closeAnimationWindows: function(){
        this.toggleAnimateLoopStop();
        animationWindows.forEach((wnd)=>{
            wnd.close();
        });

        this.setState({
            animationWindowsShowing: false,
            tilesMaximised: false
        })
    },
    toggleAnimateLoop:function(){
        inLoop ? this.toggleAnimateLoopStop() : this.toggleAnimateLoopStart();
    },
    toggleAnimateLoopStart: function () {
        inLoop = true;
        this.setState({"inLoop":true});
        if (inLoop) {
            this.animateWindows(animationWindows);
        }
    },
    toggleAnimateLoopStop: function () {
        inLoop = false;
        this.setState({"inLoop":false});
    },
    // Abstracted out the function for randomising
    randomiseAnimationWindows: function(){
        return animationWindows
            .reduce(function(m, itm, idx, a) {
                m[0].push(m[1].splice(floor((random() * m[1].length)), 1)[0]);
                return m
            }, [
                [], animationWindows.slice()
            ])[0]
    },

    animateWindows: function(animationWindows, randomise){
        //Unless explicitly asked not to, randomise
        var _randomise = randomise !== false ? true : false;
        var _arr = _randomise ?  this.randomiseAnimationWindows() : animationWindows;
        setTranspatentAsPromise(animationWindows, 0.5).then(()=>{
            Promise.all(
                _arr
                    .map((item, index) => {
                        return new Promise((resolve, reject) => {
                            try{
                                item.animate({
                                    position: locations[index]
                                }, {}, () => {
                                    resolve()
                                })
                            }catch(err){
                                //-----
                            }
                        });
                    })
            ).then(() => {
                    setTranspatentAsPromise(animationWindows, 1).then(() => {
                        if (inLoop) {
                            setTimeout(() => {
                                this.animateWindows(animationWindows)
                            }, 700);
                        }
                    })
                });
        });
    },
    openBlotter: function(){
        if(!blotter){
            initBlotter().then(function(b){
                blotter.show();
            });
        }else{
            blotter.show();
        }
    },
    componentDidMount: function(){
        console.log('Component did mount...', this);
        var _repositionWindows = function(){
            if(!this.state.inLoop &&  this.state.animationWindowsShowing){
                this.animateWindows.call(this, animationWindows, false);
            }
        }.bind(this);

        document.addEventListener('monitor-changed', function(e){
            _repositionWindows();
        })
    },
    openExcel: function() {

        fin.desktop.main(function() {

          fin.desktop.System.launchExternalProcess({
            alias: 'hypergrid',
            arguments: '',
            listener: function(event){
               // react to close event
              if(event.topic === "exited" && event.exitCode === MY_KNOWN_BAD_STATE) {
                // your desired logic here
              }
            }
          });
        });

    },
    getInitialState: function(){
        return {
            animationWindowsShowing: false,
            tilesMaximised: false,
            inLoop : false
        }
    },
    getAnimatinWindowsClass:function(){
        return this.state.animationWindowsShowing ? "none" : "menuitem";
    },
    getAnimateClass:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.inLoop ?  "fa fa-pause" : "fa fa-play";
        } else{
            return "none";
        }
    },

    getAnimateParentClass:function(){
        if(this.state.animationWindowsShowing ){
            return "";
        } else{
            return "none";
        }
    },

    getAnimateText:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.inLoop ?   "Pause animation" :  "Play animation" ;
        }else{
            return "";
        }
    },
    getMinifyText:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.tilesMaximised ?  {text: " Minimise", css: "", icon:"fa fa-sort-amount-desc"} : {text: " Maximise", css: "", icon:"fa fa-sort-amount-asc"};
        } else{
            return {text: "Minimise", css: "none", icon:"fa fa-sort-amount-desc"};
        }
    },
    openGithub: function(){
        fin.desktop.System.openUrlWithBrowser("https://github.com/openfin/Hyperblotter/tree/develop", function () {
        },function (err) {
            console.log("Failed to open GitHub: " + err);
        });
    },
    render: function(){
        return

                <image className="" type="image/svg+xml" src="images/hyperblotter_sidetext.svg" />

    }
});

//function genPairs(arr) {
//    return arr.reduce(function(m, itm, idx, a) {
//        m[0].push(m[1].splice(floor((random() * m[1].length)), 1)[0]);
//        return m
//    }, [[], arr.slice()])[0].reduce(function(m, itm, idx, a) {
//
//            if (!(idx % 2)) {
//                m.push([itm, a[idx + 1]]);
//            }
//            return m
//        }, [])
//}

/*
 <image className="openfinLogo" type="image/svg+xml" src="images/openfin_logo.svg" />

 */<commit_msg>Reformatted the menu bar to have a more toolbar like design.<commit_after>var React = require('react'),
    _ = require('underscore'),
    fin = require('../vendor/openfin.js');

var animationWindows = [],
    blotter,
    inLoop = false,
    cubeSize = 185,
    locations = [],
    numColumns = 6,
    numRows = 3,
    demoTiles = {},
    numTiles = numRows * numColumns + 1,
// Have the grid windows been created yet?
    _tilesCreated = false;

/* Static data for the floating 'trade' animation windows */

var rndData = [
    {ticker: "PCL", last: 21.251049070187836},
    {ticker: "SWI", last: 24.835458631124418},
    {ticker: "TCK", last: 6.235665990223004},
    {ticker: "DBD", last: 17.01733357355432},
    {ticker: "FHN", last: 6.624939800309766},
    {ticker: "EXR", last: 33.96528484183794},
    {ticker: "BP", last: 21.19160933461151},
    {ticker: "WCN", last: 23.501467942817747},
    {ticker: "PRE", last: 53.67873008625956},
    {ticker: "ITT", last: 22.803668802786465},
    {ticker: "BIN", last: 12.594969339431945},
    {ticker: "WTM", last: 348.8851038882928},
    {ticker: "FHN", last: 6.624939800309766},
    {ticker: "CYH", last: 19.131071861657016},
    {ticker: "SWK", last: 52.198226722926165},
    {ticker: "AMG", last: 127.23849660464248},
    {ticker: "BCE", last: 22.765628088640174},
    {ticker: "ACC", last: 14.787034222549517},
    {ticker: "AA", last: 13.787034222549517}];

var floor = Math.floor;
var random = Math.random;

fin.desktop.main(()=>{

    initAnimationWindows().then(function(val){
        fin.desktop.System.deleteCacheOnRestart(function () {
            console.log("successfully deleted cache");
        },function (err) {
            console.log("failure to delete cache: " + err);
        });

        fin.desktop.System.addEventListener('monitor-info-changed', function (evnt) {
            console.log("The monitor information has changed to: ", evnt);
            document.dispatchEvent(new CustomEvent('monitor-changed', {'detail': evnt}));
        }, function () {
            console.log("The registration of 'monitor-info-changed' was successful");
        },function (err) {
            console.log("failure: registration of 'monitor-info-changed' " + err);
        });
    });
});

/* Initialises all the floating 'trade' windows. */
var initAnimationWindows = function(){
    console.log("initAnimationWindows called _tilesCreated == ",_tilesCreated);
    return new Promise(function(resolve, reject){
        if(_tilesCreated){
            resolve()
        } else{
            var top = 5, left = 5, i = 1;
            for (; i < numTiles; i++){
                console.log("LOOP ",i, " numTiles ",numTiles);
                animationWindows.push(new fin.desktop.Window({
                    name: 'tile' + random(),
                    url: 'trade.html?t=' + rndData[i].ticker + '&l=' + rndData[i].last,
                    autoShow: false,
                    defaultHeight: cubeSize,
                    minHeight: cubeSize,
                    maxHeight:cubeSize,
                    defaultWidth: cubeSize,
                    minWidth:cubeSize,
                    maxWidth:cubeSize,
                    resizable:false,
                    frame: false,
                    maximizable: false,
                    saveWindowState: false,
                    defaultTop: top,
                    defaultLeft: left,
                    icon: "http://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/img/openfin.ico"
                }));

                locations.push({
                    top: top,
                    left: left,
                    duration: 1000
                });

                left += cubeSize + 5;

                if (i && !(i % numColumns)) {
                    left = 5;
                    top += cubeSize + 5;
                }
                if(i === numTiles-1){
                    console.log(" _tilesCreated === true");
                    _tilesCreated = true;
                    resolve();
                }
            }
        }
    });
};

/* If the blotter has not been created yet, create it and return a promise...*/
var initBlotter = function(){
    var _blotterPromise = new Promise((resolve, reject)=>{
        blotter = new fin.desktop.Window({
            name: 'blotter',
            url: 'hypergrid.html',
            autoShow: false,
            defaultWidth: 960,
            maxWidth: 960,
            minWidth: 960,
            maxHeight: 594,
            defaultHeight: 594,
            minHeight: 594,
            resizable:false,
            frame: false,
            maximizable: false,
            "icon": "http://demoappdirectory.openf.in/desktop/config/apps/OpenFin/HelloOpenFin/img/openfin.ico"
        }, ()=>{
            resolve();
        })
    });
    return _blotterPromise
}

function showAsPromise (wnd) {
    return new Promise((resolve)=>{
        fin.desktop.main(()=>{
            wnd.show(()=>{
                resolve();
            },()=>{
                reject();
            });
        })
    })
}

function setTranspatentAsPromise(arr, opacity) {
    return new Promise((transparentFinished, transparentFailed)=>{
        Promise.all(arr.map((item)=>{
            return new Promise((resolve, reject)=>{
                item.updateOptions({opacity: opacity}, ()=>{
                    resolve();
                }, ()=>{
                    reject()
                });
            });
        }))
            .then(()=>{
                transparentFinished();
            }, ()=>{
                transparentFailed();
            });
    });
}

module.exports = React.createClass({
    closeApp: function(){
        fin.desktop.main(function(){
            fin.desktop.Application.getCurrent().close();
        });
    },
    minApp: function(){
        fin.desktop.main(function(){
            fin.desktop.Window.getCurrent().minimize();
        });
    },
    showWindows: function(){
        console.log("showWindows called");
        animationWindows.forEach((wnd)=>{
            try{
                wnd.show();
            }catch(err){
                //--
            }
        });
        this.animateWindows(animationWindows, false);
        this.setState({
            animationWindowsShowing: true,
            tilesMaximised: true
        });
    },
    toggleMinimised:function(){
        this.state.tilesMaximised ? this.minWindows() : this.restoreWindows();
    },
    minWindows: function() {
        animationWindows.forEach((wnd)=>{
            wnd.minimize();
        });
        this.setState({
            tilesMaximised: false
        })
    },
    restoreWindows: function () {
        this.openAnimationWindows();
        animationWindows.forEach((wnd)=>{
            wnd.restore();
        });

        this.setState({
            animationWindowsShowing: true,
            tilesMaximised: true
        })
    },
    toggleShowAnimationWindows:function(){
        console.log("toggleShowAnimationWindows called this. openAnimationWindows = ", this.openAnimationWindows);
        if(this.state.animationWindowsShowing){
            this.openAnimationWindows()
        }else{
            this.closeAnimationWindows();
        }
    },
    openAnimationWindows:function(){
        console.log(" openAnimationWindows called ");
        initAnimationWindows().then(()=>{
            console.log(" initAnimationWindows resolved ");
            this.showWindows();
        });
    },
    closeAnimationWindows: function(){
        this.toggleAnimateLoopStop();
        animationWindows.forEach((wnd)=>{
            wnd.close();
        });

        this.setState({
            animationWindowsShowing: false,
            tilesMaximised: false
        })
    },
    toggleAnimateLoop:function(){
        inLoop ? this.toggleAnimateLoopStop() : this.toggleAnimateLoopStart();
    },
    toggleAnimateLoopStart: function () {
        inLoop = true;
        this.setState({"inLoop":true});
        if (inLoop) {
            this.animateWindows(animationWindows);
        }
    },
    toggleAnimateLoopStop: function () {
        inLoop = false;
        this.setState({"inLoop":false});
    },
    // Abstracted out the function for randomising
    randomiseAnimationWindows: function(){
        return animationWindows
            .reduce(function(m, itm, idx, a) {
                m[0].push(m[1].splice(floor((random() * m[1].length)), 1)[0]);
                return m
            }, [
                [], animationWindows.slice()
            ])[0]
    },

    animateWindows: function(animationWindows, randomise){
        //Unless explicitly asked not to, randomise
        var _randomise = randomise !== false ? true : false;
        var _arr = _randomise ?  this.randomiseAnimationWindows() : animationWindows;
        setTranspatentAsPromise(animationWindows, 0.5).then(()=>{
            Promise.all(
                _arr
                    .map((item, index) => {
                        return new Promise((resolve, reject) => {
                            try{
                                item.animate({
                                    position: locations[index]
                                }, {}, () => {
                                    resolve()
                                })
                            }catch(err){
                                //-----
                            }
                        });
                    })
            ).then(() => {
                    setTranspatentAsPromise(animationWindows, 1).then(() => {
                        if (inLoop) {
                            setTimeout(() => {
                                this.animateWindows(animationWindows)
                            }, 700);
                        }
                    })
                });
        });
    },
    openBlotter: function(){
        if(!blotter){
            initBlotter().then(function(b){
                blotter.show();
            });
        }else{
            blotter.show();
        }
    },
    componentDidMount: function(){
        console.log('Component did mount...', this);
        var _repositionWindows = function(){
            if(!this.state.inLoop &&  this.state.animationWindowsShowing){
                this.animateWindows.call(this, animationWindows, false);
            }
        }.bind(this);

        document.addEventListener('monitor-changed', function(e){
            _repositionWindows();
        })
    },
    openExcel: function() {

        fin.desktop.main(function() {

          fin.desktop.System.launchExternalProcess({
            alias: 'hypergrid',
            arguments: '',
            listener: function(event){
               // react to close event
              if(event.topic === "exited" && event.exitCode === MY_KNOWN_BAD_STATE) {
                // your desired logic here
              }
            }
          });
        });

    },
    getInitialState: function(){
        return {
            animationWindowsShowing: false,
            tilesMaximised: false,
            inLoop : false
        }
    },
    getAnimationWindowsStyle:function(){
        return this.state.animationWindowsShowing ? "none" : "menuitem";
    },
    getAnimateClass:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.inLoop ?  "fa fa-pause" : "fa fa-play";
        } else{
            return "none";
        }
    },

    getAnimateParentClass:function(){
        if(this.state.animationWindowsShowing ){
            return {"display" : "none"};
        } else{
            return {"display":"block"};
        }
    },

    getAnimateText:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.inLoop ?   "Pause animation" :  "Play animation" ;
        }else{
            return "";
        }
    },
    getMinifyText:function(){
        if(this.state.animationWindowsShowing ){
            return this.state.tilesMaximised ?  {text: " Minimise", css: "", icon:"fa fa-sort-amount-desc"} : {text: " Maximise", css: "", icon:"fa fa-sort-amount-asc"};
        } else{
            return {text: "Minimise", css: "none", icon:"fa fa-sort-amount-desc"};
        }
    },
    openGithub: function(){
        fin.desktop.System.openUrlWithBrowser("https://github.com/openfin/Hyperblotter/tree/develop", function () {
        },function (err) {
            console.log("Failed to open GitHub: " + err);
        });
    },
    render: function(){
        return

                <image className="" type="image/svg+xml" src="images/hyperblotter_sidetext.svg" />

    }
});

//function genPairs(arr) {
//    return arr.reduce(function(m, itm, idx, a) {
//        m[0].push(m[1].splice(floor((random() * m[1].length)), 1)[0]);
//        return m
//    }, [[], arr.slice()])[0].reduce(function(m, itm, idx, a) {
//
//            if (!(idx % 2)) {
//                m.push([itm, a[idx + 1]]);
//            }
//            return m
//        }, [])
//}

/*
 <image className="openfinLogo" type="image/svg+xml" src="images/openfin_logo.svg" />

 */<|endoftext|>


<commit_before>import log from '../lib/logger-service';
import * as strings from '../coaching-chatbot/strings.json';

module.exports = class InMemoryProvider {
  constructor() {
    this.db = {};
  }

  read(sessionId) {
    log.silly('DB contents: {0}', JSON.stringify(this.db));
    if (this.db[sessionId] === undefined) {
      this.db[sessionId] = {};
    }

    log.silly('Retrieved context for {0}: {1}',
        sessionId, JSON.stringify(this.db[sessionId]));
    return Promise.resolve(this.db[sessionId]);
  }

  readAll() {
    log.silly('DB contents: {0}', JSON.stringify(this.db));
    return this.db;
  }

  readAllWithReminders() {
    log.silly('Getting all sessions with reminders');
    let sessions = [];

    let d = new Date();
    let utc = d.getTime() + (d.getTimezoneOffset() * 60 * 1000);
    // UTC + 2 -> Suomen aika
    let currentDate = new Date(utc + (2 * 60 * 60 * 1000));
    let currentHour = ('0' + currentDate.getHours()).substr(-2, 2);
    console.log('WEEKDAY: ' + currentDate.getDay());
    console.log('HOURS: ' + currentDate.getHours());

    for (let sessionId in this.db) {
      if (!{}.hasOwnProperty.call(this.db, sessionId)) continue;
      log.silly('Evaluating session with id: ', sessionId);
      let context = this.db[sessionId];

      const day = context.weekDay;
      if(day === undefined) continue;
      let meetingDay = strings['@WEEKDAYS'].indexOf(day.toUpperCase());
      if (meetingDay == currentDate.getDay()) {
        if (('0' + context.time).substr(-5, 2) == currentHour) {
          log.silly('Found context with id: ', sessionId);
          sessions.push( { 'id': sessionId, 'context': context } );
        }
      }
    }

    return Promise.resolve(sessions);
  }

  readAllWithFeedbacks() {
    log.silly('Getting all sessions with feedbacks');
    let sessions = [];

    let d = new Date();
    let utc = d.getTime() + (d.getTimezoneOffset() * 60 * 1000);
    // UTC + 2 -> Suomen aika
    let currentDate = new Date(utc + (2 * 60 * 60 * 1000));
    let currentHour = ('0' + ((currentDate.getHours() - 1) % 24)).substr(-2, 2);

    for (let sessionId in this.db) {
      if (!{}.hasOwnProperty.call(this.db, sessionId)) continue;
      log.silly('Evaluating session with id: ', sessionId);
      let context = this.db[sessionId];

      const day = context.weekDay;
      if(day === undefined) continue;
      let meetingDay = strings['@WEEKDAYS'].indexOf(day.toUpperCase());
      if (meetingDay == ((currentDate.getDay() + 6) % 7)) {
        if (('0' + context.time).substr(-5, 2) == currentHour) {
          log.silly('Found context with id: ', sessionId);
          sessions.push( { 'id': sessionId, 'context': context } );
        }
      }
    }
    return Promise.resolve(sessions);
  }

  write(sessionId, context) {
    this.db[sessionId] = context;

    log.silly('Writing context for {0}: {1}',
        sessionId, JSON.stringify(this.db[sessionId]));
    return Promise.resolve(this.db[sessionId]);
  }

  getAvailablePairs(id) {
    return new Promise((resolve, reject) => {
      log.silly('Id: {0}', id);

      let pairs = [];

      for (let sessionId in this.db) {
        if (!{}.hasOwnProperty.call(this.db, sessionId)) continue;

        log.silly('Evaluating possible pair {0}', sessionId);
        if (sessionId == id) continue;
        let session = this.db[sessionId];
        let context = this.db[id];

        if (session.searching === true &&
            (!session.pairRequests || !session.pairRequests.includes(id)) &&
            (!session.rejectedPeers || !session.rejectedPeers.includes(id)) &&
            (session.communicationMethods && context.communicationMethods &&
              Object.keys(session.communicationMethods).some((method) =>
              Object.keys(context.communicationMethods).includes(method)))) {
          log.silly('Found a valid pair!');
          pairs.push({ id: sessionId });
        }
      }

      resolve(pairs);
    });
  }

  dump() {
    return this.db;
  }

  load(data) {
    this.db = data;
  }
};
<commit_msg>final changes<commit_after>import log from '../lib/logger-service';
import * as strings from '../coaching-chatbot/strings.json';

module.exports = class InMemoryProvider {
  constructor() {
    this.db = {};
  }

  read(sessionId) {
    log.silly('DB contents: {0}', JSON.stringify(this.db));
    if (this.db[sessionId] === undefined) {
      this.db[sessionId] = {};
    }

    log.silly('Retrieved context for {0}: {1}',
        sessionId, JSON.stringify(this.db[sessionId]));
    return Promise.resolve(this.db[sessionId]);
  }

  readAll() {
    log.silly('DB contents: {0}', JSON.stringify(this.db));
    return this.db;
  }

  readAllWithReminders() {
    log.silly('Getting all sessions with reminders');
    let sessions = [];

    let d = new Date();
    let utc = d.getTime() + (d.getTimezoneOffset() * 60 * 1000);
    // UTC + 2 -> Suomen aika
    let currentDate = new Date(utc + (2 * 60 * 60 * 1000));
    let currentHour = ('0' + currentDate.getHours()).substr(-2, 2);

    for (let sessionId in this.db) {
      if (!{}.hasOwnProperty.call(this.db, sessionId)) continue;
      log.silly('Evaluating session with id: ', sessionId);
      let context = this.db[sessionId];

      const day = context.weekDay;
      if(day === undefined) continue;
      let meetingDay = strings['@WEEKDAYS'].indexOf(day.toUpperCase());
      if (meetingDay == currentDate.getDay()) {
        if (('0' + context.time).substr(-5, 2) == currentHour) {
          log.silly('Found context with id: ', sessionId);
          sessions.push( { 'id': sessionId, 'context': context } );
        }
      }
    }

    return Promise.resolve(sessions);
  }

  readAllWithFeedbacks() {
    log.silly('Getting all sessions with feedbacks');
    let sessions = [];

    let d = new Date();
    let utc = d.getTime() + (d.getTimezoneOffset() * 60 * 1000);
    // UTC + 2 -> Suomen aika
    let currentDate = new Date(utc + (2 * 60 * 60 * 1000));
    let currentHour = ('0' + ((currentDate.getHours() - 1) % 24)).substr(-2, 2);

    for (let sessionId in this.db) {
      if (!{}.hasOwnProperty.call(this.db, sessionId)) continue;
      log.silly('Evaluating session with id: ', sessionId);
      let context = this.db[sessionId];

      const day = context.weekDay;
      if(day === undefined) continue;
      let meetingDay = strings['@WEEKDAYS'].indexOf(day.toUpperCase());
      if (meetingDay == ((currentDate.getDay() + 6) % 7)) {
        if (('0' + context.time).substr(-5, 2) == currentHour) {
          log.silly('Found context with id: ', sessionId);
          sessions.push( { 'id': sessionId, 'context': context } );
        }
      }
    }
    return Promise.resolve(sessions);
  }

  write(sessionId, context) {
    this.db[sessionId] = context;

    log.silly('Writing context for {0}: {1}',
        sessionId, JSON.stringify(this.db[sessionId]));
    return Promise.resolve(this.db[sessionId]);
  }

  getAvailablePairs(id) {
    return new Promise((resolve, reject) => {
      log.silly('Id: {0}', id);

      let pairs = [];

      for (let sessionId in this.db) {
        if (!{}.hasOwnProperty.call(this.db, sessionId)) continue;

        log.silly('Evaluating possible pair {0}', sessionId);
        if (sessionId == id) continue;
        let session = this.db[sessionId];
        let context = this.db[id];

        if (session.searching === true &&
            (!session.pairRequests || !session.pairRequests.includes(id)) &&
            (!session.rejectedPeers || !session.rejectedPeers.includes(id)) &&
            (session.communicationMethods && context.communicationMethods &&
              Object.keys(session.communicationMethods).some((method) =>
              Object.keys(context.communicationMethods).includes(method)))) {
          log.silly('Found a valid pair!');
          pairs.push({ id: sessionId });
        }
      }

      resolve(pairs);
    });
  }

  dump() {
    return this.db;
  }

  load(data) {
    this.db = data;
  }
};
<|endoftext|>


<commit_before>export default () => {
  if (window.location.search) {
    location.href = '#about-us'
  }
}
<commit_msg>fix(memory-comment): scroll to section after submit #167<commit_after>export default () => {
  if (window.location.search) {
    location.href = '#about-us'
  }
  if (window.location.hash) {
    setTimeout(() => {
      console.log('window.location.hash', window.location.hash)
      const hashTarget = document.querySelector(window.location.hash)
      if (hashTarget) hashTarget.scrollIntoView()
    })
  }
}
<|endoftext|>


<commit_before>import SymbolsHelper from '../helpers/SymbolsHelper';
import ContractsHelper from '../helpers/ContractsHelper';

import showBuyWindow from '../patches/showBuyWindow';
import TradingAnalysis from '../patches/TradingAnalysis';
import * as Actions from './Actions';
import text from '../helpers/text';

import { Map, List } from 'immutable';

const timers = {};

function authorize() {
  return (dispatch, getState) => {
    if (typeof window.CommonData !== 'object') {
      return Promise.resolve();
    }

    const apiToken = window.CommonData.getLoginToken();

    if (getState().has('user') || !apiToken || !localStorage.getItem('client.tokens')) {
      return Promise.resolve();
    }

    return dispatch(Actions.authorize({ apiToken }));
  };
}

function getTimeOffset() {
  return (dispatch) => dispatch(Actions.getTimeOffset());
}

function setExpiryCounter() {
  clearTimeout(timers.leftTime);
  return (dispatch, getState) => {
    const offset = getState().get('timeOffset');

    if (typeof offset !== 'undefined') {
      const expiry = getState().getIn(['values', 'period']).split('_')[1];
      const timeLeft = expiry - (parseInt((new Date()) / 1000, 10) + offset);

      return dispatch(Actions.setExpiryCounter({ timeLeft }))
        .then(() => {
          if (timeLeft > 0) {
            timers.leftTime = setTimeout(() => dispatch(setExpiryCounter()), 1000);
          }
        });
    }

    return Promise.resolve();
  };
}

function getTicks() {
  return (dispatch, getState) => {
    const symbol = getState().getIn(['values', 'symbol']);
    if (!symbol) {
      return Promise.resolve();
    }

    const prevTickChannel = getState().getIn(['streams', 'ticks', 'channel']);
    if (prevTickChannel) {
      prevTickChannel.close();
    }

    return dispatch(Actions.getTicks({ symbol }));
  };
}

export function getSymbols() {
  clearTimeout(timers.contractsTimer);
  return (dispatch) => dispatch(getTimeOffset())
    .then(() => dispatch(Actions.getSymbols()))
    .then(() => dispatch(setSymbols()))
    .then(() => dispatch(setSymbol()));
}

function setSymbols() {
  return (dispatch, getState) => {
    const symbols = getState().get('symbols', List());
    const symbolsList = SymbolsHelper.getSymbols(symbols, 'major_pairs')
      .toList()
      .map((symbol) => List.of(symbol.get('symbol'), symbol.get('display_name')));
    return dispatch(Actions.setSymbols({ symbols: symbolsList }));
  };
}

export function setSymbol(payload) {
  return (dispatch, getState) => {
    const symbols = getState().get('symbols');

    let symbol = payload && payload.symbol;
    const needToStore = Boolean(symbol);

    if (!symbol) {
      symbol = getState().getIn(['storage', 'symbol']);
    }

    if (!symbol) {
      const openedSymbols = SymbolsHelper.getSymbols(symbols, 'major_pairs', { state: true });
      symbol = openedSymbols.first() ? openedSymbols.first().get('symbol') : '';
    }

    if (!symbol) {
      return Promise.reject();
    }

    const displayName = SymbolsHelper.getDisplayName(symbols, symbol);

    return dispatch(deleteProposalsStreams())
      .then(() => dispatch(Actions.setSymbol({ needToStore, symbol })))
      .then(() => dispatch(Actions.setDisplayName({ needToStore: 1, symbol: symbol, display_name: displayName })))
      .then(() => dispatch(getContracts()))
      .then(() => dispatch(getTicks()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: err.message,
          level: 'error',
        })));
  };
}

function getContracts() {
  clearTimeout(timers.contractsTimer);
  return (dispatch, getState) => {
    const symbol = getState().getIn(['values', 'symbol']);
    return dispatch(Actions.getContracts({ symbol }))
      .then(() => {
        timers.contractsTimer = setTimeout(() => dispatch(updateContracts()), 15 * 1000);
      })
      .then(() => dispatch(setCategories()))
      .then(() => dispatch(setCategory()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: err.message,
          level: 'error',
        })));
  };
}

function updateContracts() {
  clearTimeout(timers.contractsTimer);
  return (dispatch, getState) => {
    const symbol = getState().getIn(['values', 'symbol']);
    return dispatch(Actions.getContracts({ symbol }))
      .then(() => {
        timers.contractsTimer = setTimeout(() => dispatch(updateContracts()), 15 * 1000);
      })
      .then(() => dispatch(setCategories()))
      .then(() => dispatch(setPeriods()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: err.message,
          level: 'error',
        })));
  };
}

function setCategories() {
  return (dispatch, getState) => {
    const contracts = getState().getIn(['contracts', 'available']);
    const categories = ContractsHelper.getCategories(contracts);

    return dispatch(Actions.setCategories({ categories }));
  };
}

function setPeriods() {
  return (dispatch, getState) => {
    const contracts = getState().getIn(['contracts', 'available']);
    const category = getState().getIn(['values', 'category']);
    const periods = ContractsHelper.getTradingPeriods(contracts, category);

    return dispatch(Actions.setPeriods({ periods }));
  };
}

function setBarriers() {
  return (dispatch, getState) => {
    const category = getState().getIn(['values', 'category']);
    const period = getState().getIn(['values', 'period']);
    const contracts = getState().getIn(['contracts', 'available']);
    const [startDate, endDate] = period.split('_');
    const barriers = ContractsHelper.getJapanBarriers(contracts, category, startDate, endDate);

    return dispatch(Actions.setBarriers({ barriers }));
  };
}

function setContractTypes() {
  return (dispatch, getState) => {
    const category = getState().getIn(['values', 'category']);
    const contracts = getState().getIn(['contracts', 'available']);
    const contractTypes = ContractsHelper.getContractTypes(contracts, category);

    return dispatch(Actions.setContractTypes({ contractTypes }));
  };
}

export function setCategory(payload) {
  return (dispatch, getState) => {
    let category = payload && payload.category;
    const needToStore = Boolean(category);

    if (!category) {
      category = getState().getIn(['storage', 'category']);
    }

    if (!category) {
      const categories = getState().getIn(['values', 'categories']);
      category = categories.first();
    }

    TradingAnalysis().request();

    return dispatch(deleteProposalsStreams())
      .then(() => dispatch(Actions.setCategory({ needToStore, category })))
      .then(() => dispatch(setContractTypes()))
      .then(() => dispatch(setPeriods()))
      .then(() => dispatch(setPeriod()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: err.message,
          level: 'error',
        })));
  };
}

export function setPeriod(payload) {
  clearTimeout(timers.leftTime);
  return (dispatch, getState) => {
    let period = payload && payload.period;
    const needToStore = Boolean(period);

    if (!period) {
      const periods = getState().getIn(['values', 'periods']);
      period = getState().getIn(['storage', 'period']);

      if (!periods.filter((v) => `${v.get('start')}_${v.get('end')}` === period).size) {
        period = `${periods.first().get('start')}_${periods.first().get('end')}`;
      }
    }

    return dispatch(deleteProposalsStreams())
      .then(() => dispatch(Actions.setPeriod({ period, needToStore })))
      .then(() => dispatch(setBarriers()))
      .then(() => dispatch(setExpiryCounter()))
      .then(() => {
        const offset = getState().get('timeOffset');
        if (typeof offset !== 'undefined') {
          const expiry = getState().getIn(['values', 'period']).split('_')[1];
          const timeLeft = expiry - (parseInt((new Date()) / 1000, 10) + offset);

          if (timeLeft < 120 && timeLeft > 0) {
            dispatch(Actions.showNotification({
              message: text('This contract can not be traded in the final 2 minutes before settlement'),
              level: 'info',
              uid: 'TIME_LEFT',
            }));
          }
        }
      })
      .then(() => dispatch(setPayout()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: err.message,
          level: 'error',
        })));
  };
}

let payoutPromise;
export function setPayout(payload) {
  return (dispatch, getState) => {
    let payout = payload && (+payload.payout);

    const needToStore = Boolean(payout);

    if (typeof payout === 'undefined') {
      payout = getState().getIn(['storage', 'payout']);
    }
    else if ((payout % 1 !== 0) || payout < 1 || payout > 100) {
        return false;
    }

    if (!payout) {
      payout = 1;
    }

    return dispatch(Actions.setPayout({ payout, needToStore }))
      .then(() => dispatch(deleteProposalsStreams()))
      .then(() => {
        if (!payoutPromise || payoutPromise.resolved) {
          let resolve;
          payoutPromise = new Promise((res) => { resolve = res });
          payoutPromise.resolve = resolve;
        }
        clearTimeout(timers.setPayout);
        timers.setPayout = setTimeout(() => {
          payoutPromise.resolve();
          payoutPromise.resolved = true;
          return dispatch(getPrices());
        }, needToStore ? 500 : 0);

        return payoutPromise;
      }).catch((err = {}) => dispatch(
        Actions.showNotification({
          message: err.message,
          level: 'error',
        })));
  }
}

export function getPrices() {
  return (dispatch, getState) => {
    const symbol = getState().getIn(['values', 'symbol']);
    const [, endDate] = getState().getIn(['values', 'period'], '').split('_');
    const payout = Number(getState().getIn(['values', 'payout']), 10) * 1000 || 1000;
    const barriers = getState().getIn(['values', 'barriers']);
    const contractTypes = getState().getIn(['values', 'contractTypes']);

    contractTypes.forEach((contractType) => barriers.forEach((barrier) => (
      dispatch(Actions.getPrice({ contractType, symbol, endDate, payout, barrier }))
      .catch((err = {}) => {
        if (err.code === 'RateLimit') {
          return dispatch(Actions.showNotification({
            message: err.message,
            level: 'error',
            autoDismiss: 0,
            dismissible: false,
            uid: 'PROPOSAL_LIMIT',
            action: {
              label: text('Refresh page'),
              callback() {
                location.reload();
              },
            },
          }));
        }

        return Promise.resolve();
      })
    )));

    return Promise.resolve();
  };
}

export function buy({ type, price, barriers }) {
  return (dispatch, getState) => {
    const payout = (getState().getIn(['values', 'payout']) || 1) * 1000;
    const symbol = getState().getIn(['values', 'symbol']);
    const expiry = getState().getIn(['values', 'period']).split('_')[1];

    dispatch(authorize())
      .then(() => dispatch(Actions.buy({ type, price, barriers, payout, symbol, expiry })))
      .then((payload) => {
        showBuyWindow(payload.contract_id);
      }).catch((err = {}) => (
        dispatch(Actions.showNotification({ message: err.message, level: 'error' }))
      ));
  };
}

export function close() {
  for (const id of Object.keys(timers)) {
    clearInterval(timers[id]);
    clearTimeout(timers[id]);
  }

  return Actions.close();
}

function deleteProposalsStreams() {
  return (dispatch, getState) => {
    const streams = getState().getIn(['streams', 'proposals'], Map())
      .concat(getState().getIn(['errors', 'proposals'], Map()));

    streams.forEach((stream) => {
      const channel = stream.get('channel');
      if (channel) {
        channel.close();
      }
    });

    if (!streams.isEmpty()) {
      return dispatch(Actions.deleteProposalsStreams());
    }

    return Promise.resolve();
  };
}
<commit_msg>wrap error message in localize<commit_after>import SymbolsHelper from '../helpers/SymbolsHelper';
import ContractsHelper from '../helpers/ContractsHelper';

import showBuyWindow from '../patches/showBuyWindow';
import TradingAnalysis from '../patches/TradingAnalysis';
import * as Actions from './Actions';
import text from '../helpers/text';

import { Map, List } from 'immutable';

const timers = {};

function authorize() {
  return (dispatch, getState) => {
    if (typeof window.CommonData !== 'object') {
      return Promise.resolve();
    }

    const apiToken = window.CommonData.getLoginToken();

    if (getState().has('user') || !apiToken || !localStorage.getItem('client.tokens')) {
      return Promise.resolve();
    }

    return dispatch(Actions.authorize({ apiToken }));
  };
}

function getTimeOffset() {
  return (dispatch) => dispatch(Actions.getTimeOffset());
}

function setExpiryCounter() {
  clearTimeout(timers.leftTime);
  return (dispatch, getState) => {
    const offset = getState().get('timeOffset');

    if (typeof offset !== 'undefined') {
      const expiry = getState().getIn(['values', 'period']).split('_')[1];
      const timeLeft = expiry - (parseInt((new Date()) / 1000, 10) + offset);

      return dispatch(Actions.setExpiryCounter({ timeLeft }))
        .then(() => {
          if (timeLeft > 0) {
            timers.leftTime = setTimeout(() => dispatch(setExpiryCounter()), 1000);
          }
        });
    }

    return Promise.resolve();
  };
}

function getTicks() {
  return (dispatch, getState) => {
    const symbol = getState().getIn(['values', 'symbol']);
    if (!symbol) {
      return Promise.resolve();
    }

    const prevTickChannel = getState().getIn(['streams', 'ticks', 'channel']);
    if (prevTickChannel) {
      prevTickChannel.close();
    }

    return dispatch(Actions.getTicks({ symbol }));
  };
}

export function getSymbols() {
  clearTimeout(timers.contractsTimer);
  return (dispatch) => dispatch(getTimeOffset())
    .then(() => dispatch(Actions.getSymbols()))
    .then(() => dispatch(setSymbols()))
    .then(() => dispatch(setSymbol()));
}

function setSymbols() {
  return (dispatch, getState) => {
    const symbols = getState().get('symbols', List());
    const symbolsList = SymbolsHelper.getSymbols(symbols, 'major_pairs')
      .toList()
      .map((symbol) => List.of(symbol.get('symbol'), symbol.get('display_name')));
    return dispatch(Actions.setSymbols({ symbols: symbolsList }));
  };
}

export function setSymbol(payload) {
  return (dispatch, getState) => {
    const symbols = getState().get('symbols');

    let symbol = payload && payload.symbol;
    const needToStore = Boolean(symbol);

    if (!symbol) {
      symbol = getState().getIn(['storage', 'symbol']);
    }

    if (!symbol) {
      const openedSymbols = SymbolsHelper.getSymbols(symbols, 'major_pairs', { state: true });
      symbol = openedSymbols.first() ? openedSymbols.first().get('symbol') : '';
    }

    if (!symbol) {
      return Promise.reject();
    }

    const displayName = SymbolsHelper.getDisplayName(symbols, symbol);

    return dispatch(deleteProposalsStreams())
      .then(() => dispatch(Actions.setSymbol({ needToStore, symbol })))
      .then(() => dispatch(Actions.setDisplayName({ needToStore: 1, symbol: symbol, display_name: displayName })))
      .then(() => dispatch(getContracts()))
      .then(() => dispatch(getTicks()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: text(err.message),
          level: 'error',
        })));
  };
}

function getContracts() {
  clearTimeout(timers.contractsTimer);
  return (dispatch, getState) => {
    const symbol = getState().getIn(['values', 'symbol']);
    return dispatch(Actions.getContracts({ symbol }))
      .then(() => {
        timers.contractsTimer = setTimeout(() => dispatch(updateContracts()), 15 * 1000);
      })
      .then(() => dispatch(setCategories()))
      .then(() => dispatch(setCategory()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: text(err.message),
          level: 'error',
        })));
  };
}

function updateContracts() {
  clearTimeout(timers.contractsTimer);
  return (dispatch, getState) => {
    const symbol = getState().getIn(['values', 'symbol']);
    return dispatch(Actions.getContracts({ symbol }))
      .then(() => {
        timers.contractsTimer = setTimeout(() => dispatch(updateContracts()), 15 * 1000);
      })
      .then(() => dispatch(setCategories()))
      .then(() => dispatch(setPeriods()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: text(err.message),
          level: 'error',
        })));
  };
}

function setCategories() {
  return (dispatch, getState) => {
    const contracts = getState().getIn(['contracts', 'available']);
    const categories = ContractsHelper.getCategories(contracts);

    return dispatch(Actions.setCategories({ categories }));
  };
}

function setPeriods() {
  return (dispatch, getState) => {
    const contracts = getState().getIn(['contracts', 'available']);
    const category = getState().getIn(['values', 'category']);
    const periods = ContractsHelper.getTradingPeriods(contracts, category);

    return dispatch(Actions.setPeriods({ periods }));
  };
}

function setBarriers() {
  return (dispatch, getState) => {
    const category = getState().getIn(['values', 'category']);
    const period = getState().getIn(['values', 'period']);
    const contracts = getState().getIn(['contracts', 'available']);
    const [startDate, endDate] = period.split('_');
    const barriers = ContractsHelper.getJapanBarriers(contracts, category, startDate, endDate);

    return dispatch(Actions.setBarriers({ barriers }));
  };
}

function setContractTypes() {
  return (dispatch, getState) => {
    const category = getState().getIn(['values', 'category']);
    const contracts = getState().getIn(['contracts', 'available']);
    const contractTypes = ContractsHelper.getContractTypes(contracts, category);

    return dispatch(Actions.setContractTypes({ contractTypes }));
  };
}

export function setCategory(payload) {
  return (dispatch, getState) => {
    let category = payload && payload.category;
    const needToStore = Boolean(category);

    if (!category) {
      category = getState().getIn(['storage', 'category']);
    }

    if (!category) {
      const categories = getState().getIn(['values', 'categories']);
      category = categories.first();
    }

    TradingAnalysis().request();

    return dispatch(deleteProposalsStreams())
      .then(() => dispatch(Actions.setCategory({ needToStore, category })))
      .then(() => dispatch(setContractTypes()))
      .then(() => dispatch(setPeriods()))
      .then(() => dispatch(setPeriod()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: text(err.message),
          level: 'error',
        })));
  };
}

export function setPeriod(payload) {
  clearTimeout(timers.leftTime);
  return (dispatch, getState) => {
    let period = payload && payload.period;
    const needToStore = Boolean(period);

    if (!period) {
      const periods = getState().getIn(['values', 'periods']);
      period = getState().getIn(['storage', 'period']);

      if (!periods.filter((v) => `${v.get('start')}_${v.get('end')}` === period).size) {
        period = `${periods.first().get('start')}_${periods.first().get('end')}`;
      }
    }

    return dispatch(deleteProposalsStreams())
      .then(() => dispatch(Actions.setPeriod({ period, needToStore })))
      .then(() => dispatch(setBarriers()))
      .then(() => dispatch(setExpiryCounter()))
      .then(() => {
        const offset = getState().get('timeOffset');
        if (typeof offset !== 'undefined') {
          const expiry = getState().getIn(['values', 'period']).split('_')[1];
          const timeLeft = expiry - (parseInt((new Date()) / 1000, 10) + offset);

          if (timeLeft < 120 && timeLeft > 0) {
            dispatch(Actions.showNotification({
              message: text('This contract can not be traded in the final 2 minutes before settlement'),
              level: 'info',
              uid: 'TIME_LEFT',
            }));
          }
        }
      })
      .then(() => dispatch(setPayout()))
      .catch((err = {}) => dispatch(
        Actions.showNotification({
          message: text(err.message),
          level: 'error',
        })));
  };
}

let payoutPromise;
export function setPayout(payload) {
  return (dispatch, getState) => {
    let payout = payload && (+payload.payout);

    const needToStore = Boolean(payout);

    if (typeof payout === 'undefined') {
      payout = getState().getIn(['storage', 'payout']);
    }
    else if ((payout % 1 !== 0) || payout < 1 || payout > 100) {
        return false;
    }

    if (!payout) {
      payout = 1;
    }

    return dispatch(Actions.setPayout({ payout, needToStore }))
      .then(() => dispatch(deleteProposalsStreams()))
      .then(() => {
        if (!payoutPromise || payoutPromise.resolved) {
          let resolve;
          payoutPromise = new Promise((res) => { resolve = res });
          payoutPromise.resolve = resolve;
        }
        clearTimeout(timers.setPayout);
        timers.setPayout = setTimeout(() => {
          payoutPromise.resolve();
          payoutPromise.resolved = true;
          return dispatch(getPrices());
        }, needToStore ? 500 : 0);

        return payoutPromise;
      }).catch((err = {}) => dispatch(
        Actions.showNotification({
          message: text(err.message),
          level: 'error',
        })));
  }
}

export function getPrices() {
  return (dispatch, getState) => {
    const symbol = getState().getIn(['values', 'symbol']);
    const [, endDate] = getState().getIn(['values', 'period'], '').split('_');
    const payout = Number(getState().getIn(['values', 'payout']), 10) * 1000 || 1000;
    const barriers = getState().getIn(['values', 'barriers']);
    const contractTypes = getState().getIn(['values', 'contractTypes']);

    contractTypes.forEach((contractType) => barriers.forEach((barrier) => (
      dispatch(Actions.getPrice({ contractType, symbol, endDate, payout, barrier }))
      .catch((err = {}) => {
        if (err.code === 'RateLimit') {
          return dispatch(Actions.showNotification({
            message: text(err.message),
            level: 'error',
            autoDismiss: 0,
            dismissible: false,
            uid: 'PROPOSAL_LIMIT',
            action: {
              label: text('Refresh page'),
              callback() {
                location.reload();
              },
            },
          }));
        }

        return Promise.resolve();
      })
    )));

    return Promise.resolve();
  };
}

export function buy({ type, price, barriers }) {
  return (dispatch, getState) => {
    const payout = (getState().getIn(['values', 'payout']) || 1) * 1000;
    const symbol = getState().getIn(['values', 'symbol']);
    const expiry = getState().getIn(['values', 'period']).split('_')[1];

    dispatch(authorize())
      .then(() => dispatch(Actions.buy({ type, price, barriers, payout, symbol, expiry })))
      .then((payload) => {
        showBuyWindow(payload.contract_id);
      }).catch((err = {}) => (
        dispatch(Actions.showNotification({ message: text(err.message), level: 'error' }))
      ));
  };
}

export function close() {
  for (const id of Object.keys(timers)) {
    clearInterval(timers[id]);
    clearTimeout(timers[id]);
  }

  return Actions.close();
}

function deleteProposalsStreams() {
  return (dispatch, getState) => {
    const streams = getState().getIn(['streams', 'proposals'], Map())
      .concat(getState().getIn(['errors', 'proposals'], Map()));

    streams.forEach((stream) => {
      const channel = stream.get('channel');
      if (channel) {
        channel.close();
      }
    });

    if (!streams.isEmpty()) {
      return dispatch(Actions.deleteProposalsStreams());
    }

    return Promise.resolve();
  };
}
<|endoftext|>


<commit_before>class ProofLine {
  constructor({equation, rule, newScope=false }) {
    this.equation = equation;
    this.rule = rule;
    this.newScope = newScope;
  }

  setChildren(children) {
    this.children = children;
    this.children.forEach(child => child.parent = this);
  }

  static createPremise(equation) {
    return new ProofLine({
      equation,
      rule: 'Premise'
    });
  }

  static createAssumption(equation) {
    return new ProofLine({
      equation,
      rule: 'Assumption',
      newScope: true
    });
  }
}

export default ProofLine;
<commit_msg>Remove proof line<commit_after><|endoftext|>


<commit_before>(function() {
  'use strict';

  angular.module('foundation.dynamicRouting.animations', ['foundation.dynamicRouting'])
    .directive('uiView', uiView)
  ;

  uiView.$inject = ['$rootScope', '$state'];

  function uiView($rootScope, $state) {
    var directive = {
      restrict : 'ECA',
      priority : -400,
      link     : link
    };

    return directive;

    function link(scope, element) {
      var animation = {};
      var initiator = false;
      var presetHeight;

      var cleanup = [
        $rootScope.$on('$stateChangeStart', onStateChangeStart),
        $rootScope.$on('$stateChangeError', onStateChangeError),
        scope.$on('$stateChangeSuccess', onStateChangeSuccess),
        scope.$on('$viewContentAnimationEnded', onViewContentAnimationEnded)
      ];

      var destroyed = scope.$on('$destroy', function onDestroy() {
        angular.forEach(cleanup, function (cb) {
          if (angular.isFunction(cb)) {
            cb();
          }
        });

        destroyed();
      });

      function onStateChangeStart() {
        if ($state.includes(getState()) && animation.leave) {
          element.addClass(animation.leave);
        }

        prepareParent();
      }

      function onStateChangeError() {
        if(animation.leave) {
          element.removeClass(animation.leave);
        }

        resetParent(); //reset parent if state change fails
      }

      function onStateChangeSuccess() {
        if ($state.includes(getState()) && animation.enter) {
          element.addClass(animation.enter);
        }
      }

      function onViewContentAnimationEnded(ev) {
        if (ev.targetScope === scope && animation.enter) {
          element.removeClass(animation.enter);
        }

        resetParent(); //reset parent if state change when animation is done

      }

      function getState() {
        var view  = element.data('$uiView');
        var state = view && view.state && view.state.self;

        if (state) {
          angular.extend(animation, state.animation);
        }

        return state;
      }

      function resetParent() {
        element.parent().removeClass('position-absolute');
        if(presetHeight !== true) {
          element.parent()[0].style.height = null;
        }
      }

      function prepareParent() {
        var parentHeight = parseInt(element.parent()[0].style.height);
        var elHeight = parseInt(window.getComputedStyle(element[0], null).getPropertyValue('height'));
        var tempHeight = parentHeight > 0 ? parentHeight : elHeight > 0 ? elHeight : '';

        if(parentHeight > 0) {
          presetHeight = true;
        }

        element.parent()[0].style.height = tempHeight + 'px';
        element.parent().addClass('position-absolute');
      }
    }
  }

})();
<commit_msg>Most animation cancellations working with a separate animation router function.<commit_after>(function() {
  'use strict';

  angular.module('foundation.dynamicRouting.animations', ['foundation.dynamicRouting'])
    .directive('uiView', uiView)
  ;

  uiView.$inject = ['$rootScope', '$state'];

  function uiView($rootScope, $state) {
    var directive = {
      restrict : 'ECA',
      priority : -400,
      link     : link
    };

    return directive;

    function link(scope, element) {
      var animation = {};
      var initiator = false;
      var presetHeight;

      var cleanup = [
        $rootScope.$on('$stateChangeStart', onStateChangeStart),
        $rootScope.$on('$stateChangeError', onStateChangeError),
        scope.$on('$stateChangeSuccess', onStateChangeSuccess),
        scope.$on('$viewContentAnimationEnded', onViewContentAnimationEnded),
      ];

      var destroyed = scope.$on('$destroy', function onDestroy() {
        angular.forEach(cleanup, function (cb) {
          if (angular.isFunction(cb)) {
            cb();
          }
        });

        destroyed();
      });

      function registerState(state) {
        if ($rootScope.registeredStates.indexOf(state) === -1) {
          $rootScope.registeredStates.push(state);
        }
      }

      function onStateChangeStart(event, toState, toParams, fromState, fromParams) {
        if ($state.includes(getState()) && animation.leave) {
          element.addClass(animation.leave);
        }

        animationRouter(event, toState, fromState);

        prepareParent();
      }

      function animationRouter(event, toState, fromState) {
        if (fromState.animation) {
          if (fromState.animation.leave && !toState.animation) {
            // if there is already a state existing on the page
            if (element.parent().children().length > 1) {
              resetParent();

              element.removeClass(fromState.animation.leave);
            }
          }
          else {

            element.remove();
            resetParent();
          }
        }
      }

      function onStateChangeError() {
        if(animation.leave) {
          element.removeClass(animation.leave);
        }

        resetParent(); //reset parent if state change fails
      }

      function onStateChangeSuccess() {
        if ($state.includes(getState()) && animation.enter) {
          element.addClass(animation.enter);
        }
      }

      function onViewContentAnimationEnded(event) {
        if (event.targetScope === scope && animation.enter) {
          element.removeClass(animation.enter);
        }
        resetParent(); //reset parent if state change when animation is done
      }

      function getState() {
        var view  = element.data('$uiView');
        var state = view && view.state && view.state.self;

        if (state) {
          angular.extend(animation, state.animation);
        }

        return state;
      }

      function resetElement() {
        element.removeClass()
      }

      function resetParent() {
        element.parent().removeClass('position-absolute');
        if(presetHeight !== true) {
          element.parent()[0].style.height = null;
        }
      }

      function prepareParent() {
        var parentHeight = parseInt(element.parent()[0].style.height);
        var elHeight = parseInt(window.getComputedStyle(element[0], null).getPropertyValue('height'));
        var tempHeight = parentHeight > 0 ? parentHeight : elHeight > 0 ? elHeight : '';

        if(parentHeight > 0) {
          presetHeight = true;
        }

        element.parent()[0].style.height = tempHeight + 'px';
        element.parent().addClass('position-absolute');
      }
    }
  }

})();
<|endoftext|>


<commit_before>import React from 'react'
import { inject, observer } from 'mobx-react'
import { DropTarget } from 'react-dnd'
import Paper from 'material-ui/Paper'
import FlipMove from 'react-flip-move'
import Title from './Title'
import Preview from 'components/Preview'
import DraggableTab from 'components/Tab/DraggableTab'
import { ItemTypes } from 'libs'

@inject('dragStore')
@DropTarget(
  ItemTypes.TAB,
  {
    drop (props, monitor) {
      if (monitor.didDrop()) {
        return
      }
      const { win: { tabs }, dragStore: { drop } } = props
      const tab = tabs[tabs.length - 1]
      drop(tab, false)
    }
  },
  (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver({ shallow: true })
  })
)
@observer
export default class Window extends React.Component {
  render () {
    const {
      connectDropTarget, isOver, win: { tabs, lastFocused },
      getScrollbars, dragPreview, left, right
    } = this.props
    const content = tabs.map(tab => (
      <DraggableTab key={tab.id}
        tab={tab}
        {...{ getScrollbars, dragPreview }}
      />
    ))
    const style = {
      minWidth: '18rem',
      padding: '0 2px',
      boxSizing: 'border-box',
      marginLeft: left && 'auto',
      marginRight: right && 'auto'
    }
    const dropIndicator = isOver && (
      <Preview />
    )
    const elevation = lastFocused ? 4 : 0
    return connectDropTarget(

        <Paper elevation={elevation}>
          <Title {...this.props} />
          <FlipMove duration={256}
            easing='ease-in-out'
            appearAnimation='accordionHorizontal'
            enterAnimation='accordionHorizontal'
            leaveAnimation='accordionHorizontal'
          >
            {content}
          </FlipMove>
          {dropIndicator}
        </Paper>

    )
  }
}
<commit_msg>minWidth of Window 18 -> 20rem<commit_after>import React from 'react'
import { inject, observer } from 'mobx-react'
import { DropTarget } from 'react-dnd'
import Paper from 'material-ui/Paper'
import FlipMove from 'react-flip-move'
import Title from './Title'
import Preview from 'components/Preview'
import DraggableTab from 'components/Tab/DraggableTab'
import { ItemTypes } from 'libs'

@inject('dragStore')
@DropTarget(
  ItemTypes.TAB,
  {
    drop (props, monitor) {
      if (monitor.didDrop()) {
        return
      }
      const {
        win: { tabs },
        dragStore: { drop }
      } = props
      const tab = tabs[tabs.length - 1]
      drop(tab, false)
    }
  },
  (connect, monitor) => ({
    connectDropTarget: connect.dropTarget(),
    isOver: monitor.isOver({ shallow: true })
  })
)
@observer
export default class Window extends React.Component {
  render () {
    const {
      connectDropTarget,
      isOver,
      win: { tabs, lastFocused },
      getScrollbars,
      dragPreview,
      left,
      right
    } = this.props
    const content = tabs.map(tab => (
      <DraggableTab
        key={tab.id}
        tab={tab}
        {...{ getScrollbars, dragPreview }}
      />
    ))
    const style = {
      minWidth: '20rem',
      padding: '0 1px',
      boxSizing: 'border-box',
      marginLeft: left && 'auto',
      marginRight: right && 'auto'
    }
    const dropIndicator = isOver && <Preview />
    const elevation = lastFocused ? 4 : 0
    return connectDropTarget(

        <Paper elevation={elevation}>
          <Title {...this.props} />
          <FlipMove
            duration={256}
            easing='ease-in-out'
            appearAnimation='accordionHorizontal'
            enterAnimation='accordionHorizontal'
            leaveAnimation='accordionHorizontal'
          >
            {content}
          </FlipMove>
          {dropIndicator}
        </Paper>

    )
  }
}
<|endoftext|>


<commit_before>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import OK from './status/OK';
import CriticalStatus from './status/CriticalStatus';
import ErrorStatus from './status/ErrorStatus';
import Warning from './status/Warning';
import Disabled from './status/Disabled';
import Unknown from './status/Unknown';
import Label from './status/Label';

const CLASS_ROOT = "status-icon";

export default class Status extends Component {
  constructor (props, context) {
    super(props, context);
    this.state = this._stateFromProps(props);
  }

  componentWillReceiveProps (newProps) {
    this.setState(this._stateFromProps(newProps));
  }

  _stateFromProps ({size, small, large}) {
    return {size: size || (small ? 'small' : (large ? 'large' : null))};
  }

  render () {
    let classes = [CLASS_ROOT];
    let { a11yTitle } = this.props;
    let { size } = this.state;

    if (this.props.className) {
      classes.push(this.props.className);
    }
    if (size) {
      classes.push(CLASS_ROOT + "--" + size);
    }
    let className = classes.join(' ');
    let icon = ({'?'});
    switch (this.props.value.toLowerCase()) {
      case 'ok':
      case 'normal':
        icon = (<OK className={className} a11yTitle={a11yTitle} />);
        break;
      case 'warning':
        icon = (<Warning className={className} a11yTitle={a11yTitle} />);
        break;
      // 'error' is deprecated, use 'critical'
      case 'error':
        icon = (<ErrorStatus className={className} a11yTitle={a11yTitle} />);
        break;
      case 'critical':
        icon = (<CriticalStatus className={className} a11yTitle={a11yTitle} />);
        break;
      case 'disabled':
        icon = (<Disabled className={className} a11yTitle={a11yTitle} />);
        break;
      case 'unknown':
        icon = (<Unknown className={className} a11yTitle={a11yTitle} />);
        break;
      case 'label':
        icon = ();
        break;
    }
    return icon;
  }
}

Status.defaultProps = {value: 'unknown'};

Status.propTypes = {
  a11yTitle: PropTypes.string,
  large: PropTypes.bool,
  small: PropTypes.bool,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  value: PropTypes.oneOf(['critical', 'warning', 'ok', 'unknown', 'disabled',
    'Critical', 'Warning', 'OK', 'Unknown', 'Disabled'])
};
<commit_msg>Add Label to Status PropTypes value<commit_after>// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP

import React, { Component, PropTypes } from 'react';
import OK from './status/OK';
import CriticalStatus from './status/CriticalStatus';
import ErrorStatus from './status/ErrorStatus';
import Warning from './status/Warning';
import Disabled from './status/Disabled';
import Unknown from './status/Unknown';
import Label from './status/Label';

const CLASS_ROOT = "status-icon";

export default class Status extends Component {
  constructor (props, context) {
    super(props, context);
    this.state = this._stateFromProps(props);
  }

  componentWillReceiveProps (newProps) {
    this.setState(this._stateFromProps(newProps));
  }

  _stateFromProps ({size, small, large}) {
    return {size: size || (small ? 'small' : (large ? 'large' : null))};
  }

  render () {
    let classes = [CLASS_ROOT];
    let { a11yTitle } = this.props;
    let { size } = this.state;

    if (this.props.className) {
      classes.push(this.props.className);
    }
    if (size) {
      classes.push(CLASS_ROOT + "--" + size);
    }
    let className = classes.join(' ');
    let icon = ({'?'});
    switch (this.props.value.toLowerCase()) {
      case 'ok':
      case 'normal':
        icon = (<OK className={className} a11yTitle={a11yTitle} />);
        break;
      case 'warning':
        icon = (<Warning className={className} a11yTitle={a11yTitle} />);
        break;
      // 'error' is deprecated, use 'critical'
      case 'error':
        icon = (<ErrorStatus className={className} a11yTitle={a11yTitle} />);
        break;
      case 'critical':
        icon = (<CriticalStatus className={className} a11yTitle={a11yTitle} />);
        break;
      case 'disabled':
        icon = (<Disabled className={className} a11yTitle={a11yTitle} />);
        break;
      case 'unknown':
        icon = (<Unknown className={className} a11yTitle={a11yTitle} />);
        break;
      case 'label':
        icon = ();
        break;
    }
    return icon;
  }
}

Status.defaultProps = {value: 'unknown'};

Status.propTypes = {
  a11yTitle: PropTypes.string,
  large: PropTypes.bool,
  small: PropTypes.bool,
  size: PropTypes.oneOf(['small', 'medium', 'large']),
  value: PropTypes.oneOf(['critical', 'warning', 'ok', 'unknown', 'disabled', 'label',
    'Critical', 'Warning', 'OK', 'Unknown', 'Disabled', 'Label'])
};
<|endoftext|>


<commit_before>/**
 * Created by xubt on 4/29/16.
 */

kanbanApp.directive('procedure', function ($uibModal) {
    return {
        restrict: 'E',
        templateUrl: 'component/procedure/partials/procedure.html',
        replace: true,
        transclude: true,
        scope: {
            procedure: '='
        },
        controller: ['$scope', 'boardsService', 'proceduresServices', function ($scope, boardsService, proceduresServices, $document) {
            $scope.displayProcedureMenu = false;
            $scope.onProcedureMenuMouseOver = function ($event) {
                $scope.displayProcedureMenu = true;
            };
            $scope.onProcedureMenuMouseLeave = function ($event) {
                $scope.displayProcedureMenu = false;
            };

            var currentScope = $scope;
            $scope.openModal = function (_message, _link) {
                $uibModal.open({
                    animation: false,
                    templateUrl: 'foundation/modal/partials/confirm-dialog.html',
                    controller: function ($scope, $uibModalInstance) {
                        $scope.title = '警告';
                        $scope.message = "确定要删除" + _message + "吗?";
                        $scope.ok = function () {
                            var _procedureDeletePromise = proceduresServices.deleteByLink(_link);
                            _procedureDeletePromise.then(function () {
                                currentScope.$parent.loadProcedures();
                            });
                            $uibModalInstance.close();
                        };
                        $scope.cancel = function () {
                            $uibModalInstance.dismiss('cancel');
                        };
                    },
                    size: 'sm'
                });
            };
            $scope.updateProcedure = function (_title, _procedure) {
                var procedure = _procedure;
                if (_title === "") {
                    return "标题不能为空";
                }
                procedure.title = _title;
                var procedurePromise = proceduresServices.update(procedure);
                procedurePromise.then(function () {
                });
            };

            $scope.open = function () {
                $scope.displayProcedureMenu = false;
            };
            var proceduresScope = $scope;
            $scope.openProcedureConfiguration = function () {
                $uibModal.open({
                    animation: true,
                    templateUrl: 'component/procedure/partials/procedure-configuration.html',
                    controller: ['$scope', 'teamsService', 'timerMessageService', '$uibModalInstance',
                        function ($scope, teamsService, timerMessageService, $uibModalInstance) {
                            $scope.procedure = proceduresScope.procedure;
                            $scope.procedureSaveButton = "保存";
                            $scope.saveProcedure = function () {
                                $scope.procedureSaveButton = "保存中..";
                                $scope.isDisableProcedureSaveButton = true;
                                var procedurePromise = proceduresServices.update($scope.procedure);
                                procedurePromise.then(function (_procedure) {
                                    timerMessageService.message("配置已经更新");
                                    proceduresScope.procedure = _procedure;
                                    $scope.procedure = _procedure;
                                    $uibModalInstance.dismiss('cancel');
                                }).finally(function () {
                                    $scope.procedureSaveButton = "保存";
                                    $scope.isDisableProcedureSaveButton = false;
                                });
                            };
                        }],
                    size: 'mid',
                    backdrop: "static"
                });
            };
            $scope.scrollToCardCreation = function () {
                $scope.procedure.isShowCardCreation = true;
                var cardsElement = angular.element(document.getElementById("cards-" + $scope.procedure.id));
                var cardCreationElement = angular.element(document.getElementById("card-creation-" + $scope.procedure.id));
                cardsElement.scrollToElement(cardCreationElement, 20, 500).then(function () {
                });
            };
            $scope.toFullScreen = function () {
                $uibModal.open({
                    animation: true,
                    templateUrl: 'component/procedure/partials/procedure-full-screen.html',
                    controller: ['$scope', 'teamsService', 'timerMessageService', '$uibModalInstance',
                        function ($scope, teamsService, timerMessageService, $uibModalInstance) {
                            $scope.procedure = proceduresScope.procedure;
                            $scope.finishCardsOperation = function () {
                                $uibModalInstance.dismiss('cancel');
                            }
                        }],
                    size: 'fullscreen'
                });
            };
        }
        ]
    };
});
<commit_msg>Fix jshit problem.<commit_after>/**
 * Created by xubt on 4/29/16.
 */

kanbanApp.directive('procedure', function ($uibModal) {
    return {
        restrict: 'E',
        templateUrl: 'component/procedure/partials/procedure.html',
        replace: true,
        transclude: true,
        scope: {
            procedure: '='
        },
        controller: ['$scope', 'boardsService', 'proceduresServices', function ($scope, boardsService, proceduresServices, $document) {
            $scope.displayProcedureMenu = false;
            $scope.onProcedureMenuMouseOver = function ($event) {
                $scope.displayProcedureMenu = true;
            };
            $scope.onProcedureMenuMouseLeave = function ($event) {
                $scope.displayProcedureMenu = false;
            };

            var currentScope = $scope;
            $scope.openModal = function (_message, _link) {
                $uibModal.open({
                    animation: false,
                    templateUrl: 'foundation/modal/partials/confirm-dialog.html',
                    controller: function ($scope, $uibModalInstance) {
                        $scope.title = '警告';
                        $scope.message = "确定要删除" + _message + "吗?";
                        $scope.ok = function () {
                            var _procedureDeletePromise = proceduresServices.deleteByLink(_link);
                            _procedureDeletePromise.then(function () {
                                currentScope.$parent.loadProcedures();
                            });
                            $uibModalInstance.close();
                        };
                        $scope.cancel = function () {
                            $uibModalInstance.dismiss('cancel');
                        };
                    },
                    size: 'sm'
                });
            };
            $scope.updateProcedure = function (_title, _procedure) {
                var procedure = _procedure;
                if (_title === "") {
                    return "标题不能为空";
                }
                procedure.title = _title;
                var procedurePromise = proceduresServices.update(procedure);
                procedurePromise.then(function () {
                });
            };

            $scope.open = function () {
                $scope.displayProcedureMenu = false;
            };
            var proceduresScope = $scope;
            $scope.openProcedureConfiguration = function () {
                $uibModal.open({
                    animation: true,
                    templateUrl: 'component/procedure/partials/procedure-configuration.html',
                    controller: ['$scope', 'teamsService', 'timerMessageService', '$uibModalInstance',
                        function ($scope, teamsService, timerMessageService, $uibModalInstance) {
                            $scope.procedure = proceduresScope.procedure;
                            $scope.procedureSaveButton = "保存";
                            $scope.saveProcedure = function () {
                                $scope.procedureSaveButton = "保存中..";
                                $scope.isDisableProcedureSaveButton = true;
                                var procedurePromise = proceduresServices.update($scope.procedure);
                                procedurePromise.then(function (_procedure) {
                                    timerMessageService.message("配置已经更新");
                                    proceduresScope.procedure = _procedure;
                                    $scope.procedure = _procedure;
                                    $uibModalInstance.dismiss('cancel');
                                }).finally(function () {
                                    $scope.procedureSaveButton = "保存";
                                    $scope.isDisableProcedureSaveButton = false;
                                });
                            };
                        }],
                    size: 'mid',
                    backdrop: "static"
                });
            };
            $scope.scrollToCardCreation = function () {
                $scope.procedure.isShowCardCreation = true;
                var cardsElement = angular.element(document.getElementById("cards-" + $scope.procedure.id));
                var cardCreationElement = angular.element(document.getElementById("card-creation-" + $scope.procedure.id));
                cardsElement.scrollToElement(cardCreationElement, 20, 500).then(function () {
                });
            };
            $scope.toFullScreen = function () {
                $uibModal.open({
                    animation: true,
                    templateUrl: 'component/procedure/partials/procedure-full-screen.html',
                    controller: ['$scope', 'teamsService', 'timerMessageService', '$uibModalInstance',
                        function ($scope, teamsService, timerMessageService, $uibModalInstance) {
                            $scope.procedure = proceduresScope.procedure;
                            $scope.finishCardsOperation = function () {
                                $uibModalInstance.dismiss('cancel');
                            };
                        }],
                    size: 'fullscreen'
                });
            };
        }
        ]
    };
});
<|endoftext|>


<commit_before>/*Copyright ©2013-2014 Memba® Sarl. All rights reserved.*/
/*jslint browser:true*/
/*jshint browser:true*/

(function () {

    "use strict";

    var fn = Function,
        global = fn('return this')(),
        kendo = global.kendo,
        app = global.app,
        hrefs = app.hrefs,
        routes = app.routes;

    //application i18n resources
    app.resources =  $.extend(app.resources || {}, {
        LOCALE: 'en',

        //Application layout

        // Header - Navigation Bar
        //HEADER_VIEW_NAVBAR_BRAND: '',
        HEADER_VIEW_NAVBAR_TOGGLE: 'Toggle navigation',
        HEADER_VIEW_NAVBAR_SEARCH_INPUT: 'Search',
        HEADER_VIEW_NAVBAR_SEARCH_BUTTON: 'Go',
        HEADER_VIEW_NAVBAR_MENU: [
            { text: 'Explore', items: [
                { text: 'All Posts', href: hrefs.INDEX + routes.HASH + routes.HOME },
                { text: 'FAQs', href: hrefs.INDEX + routes.HASH + routes.FAQS }
            ] }
        ],

        //Footer
        FOOTER_VIEW_COPYRIGHT: 'Copyright ©Memba 2013-2014. All rights reserved.',

        //Side sections
        ALL_POSTS_SECTION_TITLE: ' All Posts',
        CATEGORIES_SECTION_TITLE: ' Categories',
        ARCHIVE_SECTION_TITLE: ' Archive',
        RSS_SECTION_TITLE: ' RSS Feed',

        //List View
        ARTICLE_READMORE: 'Read full article ',

        //Detail View

        //Search View

        //FAQs View

        //Error View
        ERROR_VIEW_TITLE: 'Error 404',
        ERROR_VIEW_MESSAGE: 'We are sorry, the page that you requested cannot be found. The URL may have been misspelled or the page that you\'re looking may no longer be available.',

        //Dummy
        DUMMY: 'dummy'
    });

}());<commit_msg>Minor change<commit_after>/*Copyright ©2013-2014 Memba® Sarl. All rights reserved.*/
/*jslint browser:true*/
/*jshint browser:true*/

(function () {

    "use strict";

    var fn = Function,
        global = fn('return this')(),
        kendo = global.kendo,
        app = global.app,
        hrefs = app.hrefs,
        routes = app.routes;

    //application i18n resources
    app.resources =  $.extend(app.resources || {}, {
        LOCALE: 'en',

        //Application layout

        // Header - Navigation Bar
        //HEADER_VIEW_NAVBAR_BRAND: '',
        HEADER_VIEW_NAVBAR_TOGGLE: 'Toggle navigation',
        HEADER_VIEW_NAVBAR_SEARCH_INPUT: 'Search',
        HEADER_VIEW_NAVBAR_SEARCH_BUTTON: 'Go',
        HEADER_VIEW_NAVBAR_MENU: [
            { text: 'Explore', items: [
                { text: 'All Posts', href: hrefs.INDEX + routes.HASH + routes.HOME },
                { text: 'FAQs', href: hrefs.INDEX + routes.HASH + routes.FAQS }
            ] }
        ],

        //Footer
        FOOTER_VIEW_COPYRIGHT: 'Copyright ©Memba 2013-2014. All rights reserved.',

        //Side sections
        ALL_POSTS_SECTION_TITLE: ' All Posts',
        CATEGORIES_SECTION_TITLE: ' Categories',
        ARCHIVE_SECTION_TITLE: ' Archive',
        RSS_SECTION_TITLE: ' RSS Feed',

        //List View
        ARTICLE_READMORE: 'Read full article ',

        //Detail View

        //Search View

        //FAQs View

        //Error View
        ERROR_VIEW_TITLE: 'Error 404',
        ERROR_VIEW_MESSAGE: 'We are sorry, the page that you requested cannot be found. The URL may have been misspelled or the page that you\'re looking for may no longer be available.',

        //Dummy
        DUMMY: 'dummy'
    });

}());<|endoftext|>