<commit_before>
/****************************************************************************
 LICENSE: CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
 This is an original driver by Elijah Parker <mail@timelapseplus.com>
 It is free to use in other projects for non-commercial purposes.  For a
 commercial license and consulting, please contact mail@timelapseplus.com
*****************************************************************************/

var util = require('util');
var async = require('async');
var EventEmitter = require('events').EventEmitter;
var ptp = require('../common/ptp-functions.js');
var fs = require('fs');

var driver = new EventEmitter();

driver.name = "Fujifilm";

function _logD() {
    if(arguments.length > 0) {
        arguments[0] = "PTP-FUJI: " + arguments[0];
    }
    console.log.apply(console, arguments);
}

driver.supportedCameras = {
    '04cb:02cb': {
            name: "Fuji X-Pro2",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02cd': {
            name: "Fuji X-T2",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02d7': {
            name: "Fuji X-H1",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02dd': {
            name: "Fuji X-T3",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
}

var properties = {
    'shutter': {
        name: 'shutter',
        function: ptp.setPropU16,
        code: 0xD219,
        ev: true,
        values: [
            {name: '1s', ev: -6, code: 0},
        ]
    }
}

driver._error = function(camera, error) { // events received
    _logD("ERROR:", error);
};

driver._event = function(camera, data) { // events received
    _logD("EVENT:", data);
    ptp.parseEvent(data, function(type, event, param1, param2, param3) {
        if(event == ptp.PTP_EC_ObjectAdded) {
            _logD("object added:", param1);
            var objectId = param1;
            ptp.getObjectInfo(camera, objectId, function(err, oi) {
                console.log(oi);
                var image = null;
                if(camera.thumbnail) {
                    ptp.getThumb(camera, objectId, function(err, jpeg) {
                        fs.writeFileSync("thumb.jpg", jpeg);
                        ptp.deleteObject(camera, objectId);
                    })
                } else {
                    ptp.getObject(camera, objectId, function(err, image) {
                        fs.writeFileSync("embedded.jpg", ptp.extractJpeg(image));
                        fs.writeFileSync("image.raf", image);
                        ptp.deleteObject(camera, objectId);
                    })
                }
            });
        }
    });
};

driver.init = function(camera, callback) {
    ptp.init(camera._dev, function(err, di) {
        async.series([
            function(cb){ptp.setPropU16(camera._dev, 0xd38c, 1, cb);},
            function(cb){ptp.setPropU16(camera._dev, 0xd207, 2, cb);}
        ], function(err) {
            driver.capture(camera, "", {}, function(err){
                _logD("capture err result:", ptp.hex(err));
                driver.capture(camera, "", {}, function(err){
                    _logD("capture err result:", ptp.hex(err));
                });
            });
            callback && callback(err);
        });
    });
}

driver.set = function(camera, param, value, callback) {

}

driver.capture = function(camera, target, options, callback, tries) {
    var targetValue = (!target || target == "camera") ? 2 : 4;
    camera.thumbnail = true;
    async.series([
        function(cb){ptp.setPropU8(camera._dev, 0xd20c, targetValue, cb);}, // set target
        function(cb){ptp.setPropU16(camera._dev, 0xd208, 0x0200, cb);},
        function(cb){ptp.ptpCapture(camera._dev, [0x0, 0x0], cb);},
        function(cb){
            var check = function() {
                ptp.getPropU16(camera._dev, 0xd209, function(err, data) { // wait if busy
                    if(data == 0x0001) {
                        check();
                    } else {
                        cb(err);
                    }
                });
            }
            check();
        },
        function(cb){ptp.setPropU16(camera._dev, 0xd208, 0x0304, cb);},
        function(cb){ptp.ptpCapture(camera._dev, [0x0, 0x0], cb);},
    ], function(err) {
        if(err == 0x2019 && !tries || tries < 10) { // busy, try again
            _logD("capture busy, trying again...");
            if(!tries) tries = 0;
            tries++;
            setTimeout(function() {
                driver.capture(camera, target, options, callback, tries);
            }, 50);
        } else {
            callback && callback(err);
        }
    });
}

driver.captureHDR = function(camera, target, options, frames, stops, darkerOnly, callback) {

}

driver.liveviewMode = function(camera, enable, callback) {

}

driver.liveviewImage = function(camera, nable, callback) {

}

driver.moveFocus = function(camera, steps, resolution, callback) {

}

driver.get = function(camera, param, value, callback) {

}

module.exports = driver;
<commit_msg>usb testing<commit_after>
/****************************************************************************
 LICENSE: CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
 This is an original driver by Elijah Parker <mail@timelapseplus.com>
 It is free to use in other projects for non-commercial purposes.  For a
 commercial license and consulting, please contact mail@timelapseplus.com
*****************************************************************************/

var util = require('util');
var async = require('async');
var EventEmitter = require('events').EventEmitter;
var ptp = require('../common/ptp-functions.js');
var fs = require('fs');

var driver = new EventEmitter();

driver.name = "Fujifilm";

function _logD() {
    if(arguments.length > 0) {
        arguments[0] = "PTP-FUJI: " + arguments[0];
    }
    console.log.apply(console, arguments);
}

driver.supportedCameras = {
    '04cb:02cb': {
            name: "Fuji X-Pro2",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02cd': {
            name: "Fuji X-T2",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02d7': {
            name: "Fuji X-H1",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
    '04cb:02dd': {
            name: "Fuji X-T3",
            supports: {
                shutter: true,
                aperture: true,
                iso: true,
                liveview: true,
                target: true,
                focus: true,
            }
        },
}

var properties = {
    'shutter': {
        name: 'shutter',
        function: ptp.setPropU16,
        code: 0xD219,
        ev: true,
        values: [
            {name: '1s', ev: -6, code: 0},
        ]
    }
}

driver._error = function(camera, error) { // events received
    _logD("ERROR:", error);
};

driver._event = function(camera, data) { // events received
    _logD("EVENT:", data);
    ptp.parseEvent(data, function(type, event, param1, param2, param3) {
        if(event == ptp.PTP_EC_ObjectAdded) {
            _logD("object added:", param1);
            var objectId = param1;
            ptp.getObjectInfo(camera, objectId, function(err, oi) {
                console.log(oi);
                var image = null;
                if(camera.thumbnail) {
                    ptp.getThumb(camera, objectId, function(err, jpeg) {
                        //fs.writeFileSync("thumb.jpg", jpeg);
                        ptp.deleteObject(camera, objectId);
                        if(camera._captureCallback) {
                            camera._captureCallback(err, jpeg, oi.filename, null);
                            camera._captureCallback = null;
                        }
                    })
                } else {
                    ptp.getObject(camera, objectId, function(err, image) {
                        //fs.writeFileSync("embedded.jpg", ptp.extractJpeg(image));
                        //fs.writeFileSync("image.raf", image);
                        ptp.deleteObject(camera, objectId);
                        if(camera._captureCallback) {
                            camera._captureCallback(err, ptp.extractJpeg(image), oi.filename, image);
                            camera._captureCallback = null;
                        }
                    })
                }
            });
        }
    });
};

driver.init = function(camera, callback) {
    ptp.init(camera._dev, function(err, di) {
        async.series([
            function(cb){ptp.setPropU16(camera._dev, 0xd38c, 1, cb);},
            function(cb){ptp.setPropU16(camera._dev, 0xd207, 2, cb);}
        ], function(err) {
            driver.capture(camera, "", {}, function(err, thumb, filename, rawImage){
                _logD("capture err result:", ptp.hex(err), "filename", filename);
                driver.capture(camera, "", {}, function(err, thumb, filename, rawImage){
                    _logD("capture err result:", ptp.hex(err), "filename", filename);
                });
            });
            callback && callback(err);
        });
    });
}

driver.set = function(camera, param, value, callback) {

}

driver.capture = function(camera, target, options, callback, tries) {
    var targetValue = (!target || target == "camera") ? 2 : 4;
    camera.thumbnail = true;
    async.series([
        function(cb){ptp.setPropU8(camera._dev, 0xd20c, targetValue, cb);}, // set target
        function(cb){ptp.setPropU16(camera._dev, 0xd208, 0x0200, cb);},
        function(cb){ptp.ptpCapture(camera._dev, [0x0, 0x0], cb);},
        function(cb){
            var check = function() {
                ptp.getPropU16(camera._dev, 0xd209, function(err, data) { // wait if busy
                    if(data == 0x0001) {
                        check();
                    } else {
                        cb(err);
                    }
                });
            }
            check();
        },
        function(cb){ptp.setPropU16(camera._dev, 0xd208, 0x0304, cb);},
        function(cb){ptp.ptpCapture(camera._dev, [0x0, 0x0], cb);},
    ], function(err) {
        if(err) {
            callback && callback(err);
        } else {
            camera._captureCallback = function(err, thumb, filename, rawImage) {
                callback && callback(err, thumb, filename, rawImage);
            }
        }
    });
}

driver.captureHDR = function(camera, target, options, frames, stops, darkerOnly, callback) {

}

driver.liveviewMode = function(camera, enable, callback) {

}

driver.liveviewImage = function(camera, nable, callback) {

}

driver.moveFocus = function(camera, steps, resolution, callback) {

}

driver.get = function(camera, param, value, callback) {

}

module.exports = driver;
<|endoftext|>


<commit_before>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function ident(style, size, level) {
    return level <= 0
        ? ""
        : Array(level * (size + 1)).join(style === "tab" ? "\t" : " ");
}
var TsdBuilder = (function () {
    function TsdBuilder(encoding, identStyle, identSize) {
        this.encoding = encoding;
        this.identStyle = identStyle;
        this.identSize = identSize;
        this.chunks = [];
        this.currentIdentation = 0;
    }
    TsdBuilder.prototype.beginNamespace = function (name, declared) {
        if (declared === void 0) { declared = true; }
        var statement = (declared ? "declare " : "") + "namespace " + name + " {";
        this.putStatement(statement);
        this.beginIdentation();
        return this;
    };
    TsdBuilder.prototype.beginInterface = function (name, declared) {
        if (declared === void 0) { declared = true; }
        var statement = (declared ? "declare " : "") + "interface " + name + " {";
        this.putStatement(statement);
        this.beginIdentation();
        return this;
    };
    TsdBuilder.prototype.end = function () {
        this.endIdentation();
        this.putStatement("}");
        return this;
    };
    TsdBuilder.prototype.property = function (name, type) {
        this.putStatement("\"" + name + "\": " + type + ";");
        return this;
    };
    TsdBuilder.prototype.beginObjectProperty = function (name) {
        var statement = "\"" + name + "\": {";
        this.putStatement(statement);
        this.beginIdentation();
        return this;
    };
    TsdBuilder.prototype.endObjectProperty = function () {
        this.endIdentation();
        this.putStatement("};");
        return this;
    };
    TsdBuilder.prototype.declareConstant = function (name, type) {
        this.putStatement("declare const " + name + ": " + type + ";");
        return this;
    };
    TsdBuilder.prototype.putStatement = function (statement) {
        this.chunks.push(new Buffer("" + ident(this.identStyle, this.identSize, this.currentIdentation) + statement + "\n", this.encoding));
    };
    TsdBuilder.prototype.beginIdentation = function () {
        ++this.currentIdentation;
    };
    TsdBuilder.prototype.endIdentation = function () {
        --this.currentIdentation;
    };
    TsdBuilder.prototype.toBuffer = function () {
        return Buffer.concat(this.chunks);
    };
    return TsdBuilder;
}());
exports.TsdBuilder = TsdBuilder;
<commit_msg>Fix identiation (missed built version)<commit_after>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function ident(style, size, level) {
    return level <= 0
        ? ""
        : Array(level * size + 1).join(style === "tab" ? "\t" : " ");
}
var TsdBuilder = (function () {
    function TsdBuilder(encoding, identStyle, identSize) {
        this.encoding = encoding;
        this.identStyle = identStyle;
        this.identSize = identSize;
        this.chunks = [];
        this.currentIdentation = 0;
    }
    TsdBuilder.prototype.beginNamespace = function (name, declared) {
        if (declared === void 0) { declared = true; }
        var statement = (declared ? "declare " : "") + "namespace " + name + " {";
        this.putStatement(statement);
        this.beginIdentation();
        return this;
    };
    TsdBuilder.prototype.beginInterface = function (name, declared) {
        if (declared === void 0) { declared = true; }
        var statement = (declared ? "declare " : "") + "interface " + name + " {";
        this.putStatement(statement);
        this.beginIdentation();
        return this;
    };
    TsdBuilder.prototype.end = function () {
        this.endIdentation();
        this.putStatement("}");
        return this;
    };
    TsdBuilder.prototype.property = function (name, type) {
        this.putStatement("\"" + name + "\": " + type + ";");
        return this;
    };
    TsdBuilder.prototype.beginObjectProperty = function (name) {
        var statement = "\"" + name + "\": {";
        this.putStatement(statement);
        this.beginIdentation();
        return this;
    };
    TsdBuilder.prototype.endObjectProperty = function () {
        this.endIdentation();
        this.putStatement("};");
        return this;
    };
    TsdBuilder.prototype.declareConstant = function (name, type) {
        this.putStatement("declare const " + name + ": " + type + ";");
        return this;
    };
    TsdBuilder.prototype.putStatement = function (statement) {
        this.chunks.push(new Buffer("" + ident(this.identStyle, this.identSize, this.currentIdentation) + statement + "\n", this.encoding));
    };
    TsdBuilder.prototype.beginIdentation = function () {
        ++this.currentIdentation;
    };
    TsdBuilder.prototype.endIdentation = function () {
        --this.currentIdentation;
    };
    TsdBuilder.prototype.toBuffer = function () {
        return Buffer.concat(this.chunks);
    };
    return TsdBuilder;
}());
exports.TsdBuilder = TsdBuilder;
<|endoftext|>


<commit_before>import moment from 'moment';
import React from 'react';
import MetricsStore from '../stores/MetricsStore';

const MAX_POINTS_PER_GRAPH = 300;
const RUNNING_GRAPH_SHOWED_DURATION = 10; // minutes

class Graph extends React.Component {
    constructor(props) {
        super(props);

        this.streams = [];
        this.currentZoom = undefined;
        this.previouslyRunning = undefined;
        this.updatesCounter = 0;

        this.state = this._resolveState();
        this._onChange = this._onChange.bind(this);
    }

    componentDidMount() {
        MetricsStore.onChange(this._onChange);
        this.previouslyRunning = this.props.isRunning;

        this._createSubscriptions();
        this._renderGraph();
    }

    componentWillUnmount() {
        MetricsStore.off(this._onChange);

        this._destroySubscriptions();
    }

    shouldComponentUpdate(nextProps, nextState) {
        if(nextProps.isRunning != this.props.isRunning) {
            this._destroySubscriptions();
            this._createSubscriptions();
            this._resetState();
        }

        if(nextProps.targets[0] != this.props.targets[0]) {
            // The change of the first target will change the DOM Ids
            // of the MetricsGraphics.js targets. Its the only case
            // when rendering should be done.
            //
            // Happens in fullscreen mode.
            return true;
        } else {
            // Graph should probably be updated, but not the DOM.
            setTimeout(this._updateGraph.bind(this), 1);
            return false;
        }
    }

    componentDidUpdate() {
        this._onChange();
        setTimeout(this._renderGraph.bind(this), 1 + Math.round(3000*Math.random()));
    }

    render() {
        return (

);
    }

    _graphDOMId() {
        return this.props.domPrefix + this.props.targets[0].replace(/\./g, "-") + "-graph";
    }

    _formatClockNumber(number) {
        let result = number.toString();
        if(number < 10) {
            result = "0" + result;
        }
        return result;
    }

    _formatDate(rawDate) {
        const absDate = (rawDate < 0)?-1*rawDate:rawDate;
        const negDate = rawDate < 0;
        let date = moment.duration(absDate, 'seconds');

        let result = `${this._formatClockNumber(date.minutes())}:${this._formatClockNumber(date.seconds())}`;
        if(date.hours() > 0) {
            result = `${this._formatClockNumber(date.hours())}:` + result;
        }
        if(date.days() > 0) {
            result = `${date.days()}d ` + result;
        }
        if(date.months() > 0) {
            result = `${date.months()}m ` + result;
        }
        if(date.years() > 0) {
            result = `${date.years()}y ` + result;
        }

        if(negDate) {
            return '-' + result;
        } else {
            return result;
        }
    }

    _formatRolloverTextFullscreen(data, i) {
        let rolloverTextContainer = d3.select('#' + this._graphDOMId() + ' svg .mg-active-datapoint');
        rolloverTextContainer.selectAll('*').remove();

        if(data.key) {
            const dateString = this._formatDate(data.values[0].date);
            rolloverTextContainer.append('tspan').text(dateString).classed('mg-area1-color', true);

            let lineCount = 1;
            let lineHeight = 1.1;
            data.values.forEach((value) => {
                let label = rolloverTextContainer.append('tspan')
                            .attr({ x: 0, y: (lineCount * lineHeight) + 'em' })
                            .text(`${this.props.targets[value.line_id - 1]}: ${value.value}`)
                            .classed('mg-area' + value.line_id + '-color', true);

                ++lineCount;
            });
        } else {
            const dateString = this._formatDate(data.date);
            rolloverTextContainer.append('tspan').text(dateString).classed(`mg-area${data.line_id}-color`, true);

            let label = rolloverTextContainer.append('tspan')
                        .attr({ x: 0, y: 1.1 + 'em' })
                        .text(`${this.props.targets[data.line_id - 1]}: ${data.value}`)
                        .classed(`mg-area${data.line_id}-color`, true);
        }
    }

    _formatRolloverTextNormal(data, i) {
        let rolloverTextContainer = d3.select('#' + this._graphDOMId() + ' svg .mg-active-datapoint');
        rolloverTextContainer.selectAll('*').remove();

        if(data.key) {
            const dateString = this._formatDate(data.values[0].date);
            rolloverTextContainer.append('tspan').text(dateString).classed('mg-area1-color', true);

            let lineCount = 1;
            let lineHeight = 1.1;
            data.values.forEach((value) => {
                let label = rolloverTextContainer.append('tspan')
                            .attr({ x: 0, y: (lineCount * lineHeight) + 'em' })
                            .text(`${this.props.targets[value.line_id - 1]}: ${value.value}`)
                            .classed('mg-area' + value.line_id + '-color', true);

                ++lineCount;
            });
        } else {
            const dateString = this._formatDate(data.date);
            rolloverTextContainer.append('tspan').text(dateString).classed(`mg-area${data.line_id}-color`, true);

            let label = rolloverTextContainer.append('tspan')
                        .attr({ x: 0, y: 1.1 + 'em' })
                        .text(`${this.props.targets[data.line_id - 1]}: ${data.value}`)
                        .classed(`mg-area${data.line_id}-color`, true);
        }
    }

    _formatRolloverText(data, i) {
        if(this.props.renderFullscreen) {
            this._formatRolloverTextFullscreen(data, i);
        } else {
            this._formatRolloverTextNormal(data, i);
        }
    }

    _performZoom(step) {
        this.currentZoom = step;
        this._destroySubscriptions();
        this._createSubscriptions();
        this._resetState();
    }

    _renderGraph() {
        let graph_options = {
            title: this.props.title,
            y_label: this.props.units,
            missing_text: "Loading...",

            buffer: 0,
            left: 65,
            right: 0,
            height: 400,

            area: false,
            brushing: false,
            brushing_history: false,
            interpolate: 'monotone',
            x_extended_ticks: true,
            y_extended_ticks: true,
            full_width: true,
            aggregate_rollover: false,
            transition_on_update: false
        };

        if(this.props.renderFullscreen) {
            graph_options.width = window.innerWidth - 100;
            graph_options.height = window.innerHeight - 200;
            graph_options.full_width = false;

            graph_options.brushing = true;
            graph_options.brushing_history = true;
            graph_options.after_brushing = this._performZoom.bind(this);
            graph_options.brushing_manual_redraw = true;
            graph_options.aggregate_rollover = true;
        }

        if(this.state.isLoaded) {
            let isEmpty = this.state.data.reduce((prev, dataset) => {
                if (dataset.length > 0) return false;
                else return prev;
            }, true);
            graph_options.data = isEmpty ? [[{date: 0, value: 0, min: 0, max: 0}]] : this.state.data;
            graph_options.legend = this.props.targets;

            graph_options.target = document.getElementById(this._graphDOMId());

            graph_options.show_confidence_band = ['min', 'max'];

            graph_options.xax_format = this._formatDate.bind(this);
            graph_options.mouseover = this._formatRolloverText.bind(this);
            graph_options.x_sort = false;

            graph_options.min_x = (this.props.isRunning && !this.props.renderFullscreen)?this.state.maxDate - RUNNING_GRAPH_SHOWED_DURATION*60:0;
            graph_options.max_x = this.state.maxDate;

            MG.data_graphic(graph_options);
        } else {
            graph_options.chart_type = 'missing-data';
            graph_options.legend = this.props.targets;
            graph_options.target = document.getElementById(this._graphDOMId());

            MG.data_graphic(graph_options);
        }
    }

    _updateGraph() {
        if (!this.state.isLoaded) {
            return;
        }

        if (this.previouslyRunning != this.props.isRunning) {
            this._renderGraph();
            this.previouslyRunning = this.props.isRunning;
        } else {
            const newUpdatesCounter = this.state.dataBatchs.reduce((a, b) => { return a + b }, 0);
            let dataUpdated = newUpdatesCounter > this.updatesCounter;

            if(dataUpdated) {
                this._renderGraph();
                this.updatesCounter = newUpdatesCounter;
            }
        }
    }

    _computeSubsamplingInterval() {
        if(this.currentZoom) {
            const duration = this.currentZoom.max_x - this.currentZoom.min_x;
            return Math.floor(duration/MAX_POINTS_PER_GRAPH);
        }

        if(this.props.benchStartTime) {
            const lastActiveTime = this.props.isRunning ? moment() : this.props.benchFinishTime;
            const benchDuration = lastActiveTime.diff(this.props.benchStartTime, 'seconds');

            return Math.floor(benchDuration/MAX_POINTS_PER_GRAPH);
        } else {
            return 0;
        }
    }

    _createSubscriptions() {
        this.props.targets.forEach((metric, index) => {
            const streamId = this._subscribeToMetric(this.props.benchId, metric);
            this.streams[index] = streamId;
        });
    }

    _destroySubscriptions() {
        this.streams.forEach((streamId) => {
            MetricsStore.unsubscribeFromMetric(streamId);
        });
    }

    _subscribeToMetric(benchId, metric) {
        if(this.props.renderFullscreen) {
            if(this.currentZoom) {
                return MetricsStore.subscribeToMetricSubset(benchId, metric, this._computeSubsamplingInterval(),
                                                            this.currentZoom.min_x, this.currentZoom.max_x);
            } else {
                return MetricsStore.subscribeToEntireMetric(benchId, metric, this._computeSubsamplingInterval(), false);
            }
        } else {
            if(this.props.isRunning) {
                return MetricsStore.subscribeToMetricWithTimeWindow(benchId, metric, RUNNING_GRAPH_SHOWED_DURATION*60);
            } else {
                return MetricsStore.subscribeToEntireMetric(benchId, metric, this._computeSubsamplingInterval(), false);
            }
        }
    }

    _resetState() {
        this.updatesCounter = 0;

        this.setState({
            maxDate: 0,
            data: this.props.targets.map((metric) => { return []; }),
            dataBatchs: this.props.targets.map((metric) => { return 0; }),
            isLoaded: false
        });
    }

    _resolveState() {
        const maxDate = this.props.targets.reduce((maxDate, metric, index) => {
            const metricMaxDate = MetricsStore.getMetricMaxDate(this.streams[index]);

            if(metricMaxDate) {
                if(metricMaxDate > maxDate) {
                    return metricMaxDate;
                } else {
                    return maxDate;
                }
            } else {
                return maxDate;
            }
        }, 0);

        const metricData = this.props.targets.map((metric, index) => {
            const data = MetricsStore.getMetricData(this.streams[index]);
            if(data) {
                return data;
            } else {
                return [];
            }
        });

        const metricBatchs = this.props.targets.map((metric, index) => {
            const batchCounter = MetricsStore.getBatchCounter(this.streams[index]);
            if(batchCounter) {
                return batchCounter;
            } else {
                return 0;
            }
        });

        const isLoaded = metricBatchs.reduce((prev, v) => {
            if (v <= 0) return false;
            else return prev;
        }, true);

        return {
            maxDate: maxDate,
            data: metricData,
            dataBatchs: metricBatchs,
            isLoaded: isLoaded
        };
    }

    _onChange() {
        this.setState(this._resolveState());
    }
};

Graph.propTypes = {
    benchId: React.PropTypes.number.isRequired,
    benchStartTime: React.PropTypes.object,
    benchFinishTime: React.PropTypes.object,

    targets: React.PropTypes.array.isRequired,
    isRunning: React.PropTypes.bool,
    title: React.PropTypes.string,
    units: React.PropTypes.string,

    domPrefix: React.PropTypes.string,
    renderFullscreen: React.PropTypes.bool
};

Graph.defaultProps = {
    benchStartTime: undefined,
    benchFinishTime: undefined,

    isRunning: false,
    title: "",
    units: "",

    domPrefix: "",
    renderFullscreen: false
};

export default Graph;
<commit_msg>Workaround a bug in the current master of MG (bogus legend in fullscreen)<commit_after>import moment from 'moment';
import React from 'react';
import MetricsStore from '../stores/MetricsStore';

const MAX_POINTS_PER_GRAPH = 300;
const RUNNING_GRAPH_SHOWED_DURATION = 10; // minutes

class Graph extends React.Component {
    constructor(props) {
        super(props);

        this.streams = [];
        this.currentZoom = undefined;
        this.previouslyRunning = undefined;
        this.updatesCounter = 0;

        this.state = this._resolveState();
        this._onChange = this._onChange.bind(this);
    }

    componentDidMount() {
        MetricsStore.onChange(this._onChange);
        this.previouslyRunning = this.props.isRunning;

        this._createSubscriptions();
        this._renderGraph();
    }

    componentWillUnmount() {
        MetricsStore.off(this._onChange);

        this._destroySubscriptions();
    }

    shouldComponentUpdate(nextProps, nextState) {
        if(nextProps.isRunning != this.props.isRunning) {
            this._destroySubscriptions();
            this._createSubscriptions();
            this._resetState();
        }

        if(nextProps.targets[0] != this.props.targets[0]) {
            // The change of the first target will change the DOM Ids
            // of the MetricsGraphics.js targets. Its the only case
            // when rendering should be done.
            //
            // Happens in fullscreen mode.
            return true;
        } else {
            // Graph should probably be updated, but not the DOM.
            setTimeout(this._updateGraph.bind(this), 1);
            return false;
        }
    }

    componentDidUpdate() {
        this._onChange();
        setTimeout(this._renderGraph.bind(this), 1 + Math.round(3000*Math.random()));
    }

    render() {
        return (

);
    }

    _graphDOMId() {
        return this.props.domPrefix + this.props.targets[0].replace(/\./g, "-") + "-graph";
    }

    _formatClockNumber(number) {
        let result = number.toString();
        if(number < 10) {
            result = "0" + result;
        }
        return result;
    }

    _formatDate(rawDate) {
        const absDate = (rawDate < 0)?-1*rawDate:rawDate;
        const negDate = rawDate < 0;
        let date = moment.duration(absDate, 'seconds');

        let result = `${this._formatClockNumber(date.minutes())}:${this._formatClockNumber(date.seconds())}`;
        if(date.hours() > 0) {
            result = `${this._formatClockNumber(date.hours())}:` + result;
        }
        if(date.days() > 0) {
            result = `${date.days()}d ` + result;
        }
        if(date.months() > 0) {
            result = `${date.months()}m ` + result;
        }
        if(date.years() > 0) {
            result = `${date.years()}y ` + result;
        }

        if(negDate) {
            return '-' + result;
        } else {
            return result;
        }
    }

    _formatRolloverTextFullscreen(data, i) {
        let rolloverTextContainer = d3.select('#' + this._graphDOMId() + ' svg .mg-active-datapoint');
        rolloverTextContainer.selectAll('*').remove();

        if(data.key) {
            const dateString = this._formatDate(data.values[0].date);
            rolloverTextContainer.append('tspan').text(dateString).classed('mg-area1-color', true);

            let lineCount = 1;
            let lineHeight = 1.1;
            data.values.forEach((value) => {
                let label = rolloverTextContainer.append('tspan')
                            .attr({ x: 0, y: (lineCount * lineHeight) + 'em' })
                            .text(`${this.props.targets[value.line_id - 1]}: ${value.value}`)
                            .classed('mg-area' + value.line_id + '-color', true);

                ++lineCount;
            });
        } else {
            const dateString = this._formatDate(data.date);
            rolloverTextContainer.append('tspan').text(dateString).classed(`mg-area${data.line_id}-color`, true);

            let label = rolloverTextContainer.append('tspan')
                        .attr({ x: 0, y: 1.1 + 'em' })
                        .text(`${this.props.targets[data.line_id - 1]}: ${data.value}`)
                        .classed(`mg-area${data.line_id}-color`, true);
        }
    }

    _formatRolloverTextNormal(data, i) {
        let rolloverTextContainer = d3.select('#' + this._graphDOMId() + ' svg .mg-active-datapoint');
        rolloverTextContainer.selectAll('*').remove();

        if(data.key) {
            const dateString = this._formatDate(data.values[0].date);
            rolloverTextContainer.append('tspan').text(dateString).classed('mg-area1-color', true);

            let lineCount = 1;
            let lineHeight = 1.1;
            data.values.forEach((value) => {
                let label = rolloverTextContainer.append('tspan')
                            .attr({ x: 0, y: (lineCount * lineHeight) + 'em' })
                            .text(`${this.props.targets[value.line_id - 1]}: ${value.value}`)
                            .classed('mg-area' + value.line_id + '-color', true);

                ++lineCount;
            });
        } else {
            const dateString = this._formatDate(data.date);
            rolloverTextContainer.append('tspan').text(dateString).classed(`mg-area${data.line_id}-color`, true);

            let label = rolloverTextContainer.append('tspan')
                        .attr({ x: 0, y: 1.1 + 'em' })
                        .text(`${this.props.targets[data.line_id - 1]}: ${data.value}`)
                        .classed(`mg-area${data.line_id}-color`, true);
        }
    }

    _formatRolloverText(data, i) {
        if(this.props.renderFullscreen) {
            this._formatRolloverTextFullscreen(data, i);
        } else {
            this._formatRolloverTextNormal(data, i);
        }
    }

    _performZoom(step) {
        this.currentZoom = step;
        this._destroySubscriptions();
        this._createSubscriptions();
        this._resetState();
    }

    _renderGraph() {
        let graph_options = {
            title: this.props.title,
            y_label: this.props.units,
            missing_text: "Loading...",

            buffer: 0,
            left: 65,
            right: 0,
            height: 400,

            area: false,
            brushing: false,
            brushing_history: false,
            interpolate: 'monotone',
            x_extended_ticks: true,
            y_extended_ticks: true,
            full_width: true,
            aggregate_rollover: false,
            transition_on_update: false
        };

        if(this.props.renderFullscreen) {
            graph_options.width = window.innerWidth - 100;
            graph_options.height = window.innerHeight - 200;
            graph_options.full_width = false;

            graph_options.brushing = true;
            graph_options.brushing_history = true;
            graph_options.after_brushing = this._performZoom.bind(this);
            graph_options.brushing_manual_redraw = true;
            graph_options.aggregate_rollover = this.props.targets.length > 1;
        }

        if(this.state.isLoaded) {
            let isEmpty = this.state.data.reduce((prev, dataset) => {
                if (dataset.length > 0) return false;
                else return prev;
            }, true);
            graph_options.data = isEmpty ? [[{date: 0, value: 0, min: 0, max: 0}]] : this.state.data;
            graph_options.legend = this.props.targets;

            graph_options.target = document.getElementById(this._graphDOMId());

            graph_options.show_confidence_band = ['min', 'max'];

            graph_options.xax_format = this._formatDate.bind(this);
            graph_options.mouseover = this._formatRolloverText.bind(this);
            graph_options.x_sort = false;

            graph_options.min_x = (this.props.isRunning && !this.props.renderFullscreen)?this.state.maxDate - RUNNING_GRAPH_SHOWED_DURATION*60:0;
            graph_options.max_x = this.state.maxDate;

            MG.data_graphic(graph_options);
        } else {
            graph_options.chart_type = 'missing-data';
            graph_options.legend = this.props.targets;
            graph_options.target = document.getElementById(this._graphDOMId());

            MG.data_graphic(graph_options);
        }
    }

    _updateGraph() {
        if (!this.state.isLoaded) {
            return;
        }

        if (this.previouslyRunning != this.props.isRunning) {
            this._renderGraph();
            this.previouslyRunning = this.props.isRunning;
        } else {
            const newUpdatesCounter = this.state.dataBatchs.reduce((a, b) => { return a + b }, 0);
            let dataUpdated = newUpdatesCounter > this.updatesCounter;

            if(dataUpdated) {
                this._renderGraph();
                this.updatesCounter = newUpdatesCounter;
            }
        }
    }

    _computeSubsamplingInterval() {
        if(this.currentZoom) {
            const duration = this.currentZoom.max_x - this.currentZoom.min_x;
            return Math.floor(duration/MAX_POINTS_PER_GRAPH);
        }

        if(this.props.benchStartTime) {
            const lastActiveTime = this.props.isRunning ? moment() : this.props.benchFinishTime;
            const benchDuration = lastActiveTime.diff(this.props.benchStartTime, 'seconds');

            return Math.floor(benchDuration/MAX_POINTS_PER_GRAPH);
        } else {
            return 0;
        }
    }

    _createSubscriptions() {
        this.props.targets.forEach((metric, index) => {
            const streamId = this._subscribeToMetric(this.props.benchId, metric);
            this.streams[index] = streamId;
        });
    }

    _destroySubscriptions() {
        this.streams.forEach((streamId) => {
            MetricsStore.unsubscribeFromMetric(streamId);
        });
    }

    _subscribeToMetric(benchId, metric) {
        if(this.props.renderFullscreen) {
            if(this.currentZoom) {
                return MetricsStore.subscribeToMetricSubset(benchId, metric, this._computeSubsamplingInterval(),
                                                            this.currentZoom.min_x, this.currentZoom.max_x);
            } else {
                return MetricsStore.subscribeToEntireMetric(benchId, metric, this._computeSubsamplingInterval(), false);
            }
        } else {
            if(this.props.isRunning) {
                return MetricsStore.subscribeToMetricWithTimeWindow(benchId, metric, RUNNING_GRAPH_SHOWED_DURATION*60);
            } else {
                return MetricsStore.subscribeToEntireMetric(benchId, metric, this._computeSubsamplingInterval(), false);
            }
        }
    }

    _resetState() {
        this.updatesCounter = 0;

        this.setState({
            maxDate: 0,
            data: this.props.targets.map((metric) => { return []; }),
            dataBatchs: this.props.targets.map((metric) => { return 0; }),
            isLoaded: false
        });
    }

    _resolveState() {
        const maxDate = this.props.targets.reduce((maxDate, metric, index) => {
            const metricMaxDate = MetricsStore.getMetricMaxDate(this.streams[index]);

            if(metricMaxDate) {
                if(metricMaxDate > maxDate) {
                    return metricMaxDate;
                } else {
                    return maxDate;
                }
            } else {
                return maxDate;
            }
        }, 0);

        const metricData = this.props.targets.map((metric, index) => {
            const data = MetricsStore.getMetricData(this.streams[index]);
            if(data) {
                return data;
            } else {
                return [];
            }
        });

        const metricBatchs = this.props.targets.map((metric, index) => {
            const batchCounter = MetricsStore.getBatchCounter(this.streams[index]);
            if(batchCounter) {
                return batchCounter;
            } else {
                return 0;
            }
        });

        const isLoaded = metricBatchs.reduce((prev, v) => {
            if (v <= 0) return false;
            else return prev;
        }, true);

        return {
            maxDate: maxDate,
            data: metricData,
            dataBatchs: metricBatchs,
            isLoaded: isLoaded
        };
    }

    _onChange() {
        this.setState(this._resolveState());
    }
};

Graph.propTypes = {
    benchId: React.PropTypes.number.isRequired,
    benchStartTime: React.PropTypes.object,
    benchFinishTime: React.PropTypes.object,

    targets: React.PropTypes.array.isRequired,
    isRunning: React.PropTypes.bool,
    title: React.PropTypes.string,
    units: React.PropTypes.string,

    domPrefix: React.PropTypes.string,
    renderFullscreen: React.PropTypes.bool
};

Graph.defaultProps = {
    benchStartTime: undefined,
    benchFinishTime: undefined,

    isRunning: false,
    title: "",
    units: "",

    domPrefix: "",
    renderFullscreen: false
};

export default Graph;
<|endoftext|>


<commit_before>var async = require('../dist/js/async.js');

////////////////////
//DB

//DB common
function errorHandler(tx, error) {
    console.log("Error: " + error.message);
    if (debug)
    	alert("Error: " + error.message);
}
function successHandler(tx, result) {
    console.log("Success: " + result);
    if (debug)
    	alert("Success: " + result);
}

// DB init
function init_DB(callback)
{
	//init base
	if(isMobile)
    	db = window.sqlitePlugin.openDatabase("Database", "1.0", "Demo", -1);
    else
    	db = openDatabase("Database", "1.0", "Demo", -1);
	callback(null,'initDb');
}

function createTableQuestionnaires(callback)
{
	db.transaction(function(tx)
			{

				// id
				// sid : Survey ID
				// sdescription-survey_config : configuration (ex: #scheduling:D#duration:2400#startHour:10/18#maxOccurences:42#dayOff:0#test:1#)
				// gid : group ID?
				// qid : question ID
				// question
				// qtype -> template question
				// qhelp-question_config -> Configuration : template question complément, fréquence (ex: #tpl:sl7#frq:b#)
				// answers : jsontab? ex : radio buttons

				//tx.executeSql('DROP TABLE IF EXISTS "questionnaires"');
				tx.executeSql('CREATE TABLE IF NOT EXISTS "questionnaires" ' +
								' ("id" INTEGER PRIMARY KEY AUTOINCREMENT , ' +
								'  "sid" VARCHAR,' +
								'  "sdescription-survey_config" VARCHAR,' +
								'  "gid" VARCHAR,' +
								'  "qid" VARCHAR,' +
								'  "question" VARCHAR,' +
								'  "qtype" VARCHAR,' +
								'  "qhelp-question_config" VARCHAR,' +
								'  "answers" VARCHAR );');
								//'  "answers" VARCHAR );',[],callback(null,'createQuestionnairesSuccess'),callback(true,'createQuestionnairesError'));
								//'  "answers" VARCHAR );',[],createQuestionnairesSuccess,createQuestionnairesError);
			//});
			},function(tx){callback(true,'createQuestionnairesError')},function(tx){callback(null,'createQuestionnairesSuccess')});
}

function createTableHoraires(callback)
{
	db.transaction(function(tx)
	{
		//tx.executeSql('DROP TABLE IF EXISTS "horaires"');
		tx.executeSql('CREATE TABLE IF NOT EXISTS "horaires" ("id" INTEGER PRIMARY KEY AUTOINCREMENT , "uidquestionnaire" VARCHAR, "tsdebut" INTEGER, "dureevalidite" INTEGER, "notification" INTEGER, "fait" INTEGER);');
	},function(tx){callback(true,'createHorairesError')},function(tx){callback(null,'createHorairesSuccess')});
}

function createTableReponses(callback)
{
	db.transaction(function(tx)
	{
		//tx.executeSql('DROP TABLE IF EXISTS "reponses"');
		tx.executeSql('CREATE TABLE IF NOT EXISTS "reponses" ("id" INTEGER PRIMARY KEY AUTOINCREMENT , "idhoraire" INTEGER DEFAULT (0), "sid" VARCHAR, "gid" VARCHAR, "qid" VARCHAR, "reponse" VARCHAR, "tsreponse" INTEGER, "envoi" BOOLEAN not null default 0);');
	},function(tx){callback(true,'createReponsesError')},function(tx){callback(null,'createReponsesSuccess')});
}

//function createQuestionnairesSuccess(tx, result){
function createQuestionnairesSuccess(callback){
	if(isMobile)
	{
		store = cordova.file.applicationDirectory;
		if (debug)
			{
		alert('store');
		alert(store);
			}
		fileName = "www/db/questionnaires.txt";
		//window.resolveLocalFileSystemURL(store + fileName, readQuestionnairesSuccess, readQuestionnairesFail);
		window.resolveLocalFileSystemURL(store + fileName, function(fileEntry){readQuestionnairesSuccess(fileEntry,callback) }, readQuestionnairesFail);
		//callback(null,'ok');
	}
	else
	{
		    var req = new XMLHttpRequest();
		    req.open('GET', '../www/db/questionnaires.txt', true);
		    req.onreadystatechange = function (aEvt) {
		      if (req.readyState == 4) {
		         if(req.status == 200)
		        	 {console.log("200000!!!!");
		        	 if (debug)
		        	    	alert("200000!!!!");
		        	 res = req.responseText;
		        	 insertQuestionnaire(res,callback);
		        	 }
		         else
		        	 {
		        	 console.log("Erreur pendant le chargement de la page.\n");
		        	 if (debug)
		        	    	alert("Erreur pendant le chargement de la page.\n");
		        	 }

		      }
		    };
		    req.send(null);
	}

	console.log("dbquest");
	if (debug)
    	alert("dbquest");
	//callback();
};
function createQuestionnairesError(tx, error) {
    console.log("createQuestionnairesError: " + error.message);
    if (debug)
    	alert("createQuestionnairesError: " + error.message);
}
function readQuestionnairesSuccess(fileEntry,callback) {
	fileEntry.file(function(file) {
		var reader = new FileReader();
		reader.onloadend = function(e) {
			console.log(' reader');
			if (debug)
				alert(' reader');
			res = this.result;
			insertQuestionnaire(res,callback);
		}
		reader.readAsText(file);
	});
}
function readQuestionnairesFail(e) {
	console.log("FileSystem Error");
	if (debug)
		alert("FileSystem Error");
	console.dir(e);
	if (debug)
		alert(e);
}
function insertQuestionnaire(res,callback){
	db.transaction(function(tx) {
		var line = res.split("\n");
		for (var linekey in line)
		{
			var line2 = line[linekey].split("';'");
			(function (value) {
				tx.executeSql('SELECT COUNT("id") as cnt FROM "questionnaires" WHERE sid = "'+line2[0].substring(1,line2[0].length)+'";', [], function(tx, res) {
					if (res.rows.item(0).cnt < 1)
					{
						tx.executeSql('INSERT INTO "questionnaires" (sid, "sdescription-survey_config", gid,qid, question, qtype,"qhelp-question_config", answers) VALUES("'+
								value[0].substring(1,value[0].length)+'","'+
								value[1]+'","'+
								value[2]+'","'+
								value[3]+'","'+
								value[4]+'","'+
								value[5]+'","'+
								value[6]+'","'+
								encodeURI(value[7].substring(0,value[7].length-1))+'");',[], successHandler, errorHandler);
					}//fin if
				},errorHandler);//fin select
			})(line2);
		}
	},function(tx){callback(true,'err')},function(tx){callback(null,'ok')});
}

////////////////////
//Functions after_init
function after_init(){
	console.log('after_init');
	if (debug)
		alert('after_init');
	if (MC_UseOk)
	{
		console.log('MC_UseOk');
		do_MC_UseOk();
	}
}

////////////////////
//Functions MC_UseOk

function do_MC_UseOk(callback,$location,$route){
	/*$location.path('/scroll');
	 console.log('loc3 '+$location);
	 console.log('loc3 '+JSON.stringify($location) );*/

	//callback(null,"MC_UseOk_false");

	if (MC_UseOk)
	{
		console.log('MC_UseOk');
		db.transaction(function(tx)
		{
			(function ($location) {
				//tx.executeSql('INSERT INTO "reponses" (sid, reponse) VALUES ("useOK","'+resultForm+'");
				tx.executeSql('SELECT * FROM "reponses" where sid = "useOK" AND reponse = "ok";', [], function(tx, res) {
					console.log(res);
					var dataset = res.rows.length;
		            if(dataset<1)
					//if (res.rows.item(0).cnt < 1)
					{
						console.log('MC_UseOk:false');
						//Change path
						$location.path('/scroll');
						$route.reload();
						//callback(true,"MC_UseOk_false");
						//return false;
					}
					else
					{
						console.log('MC_UseOk:true');
						callback(null,"MC_UseOk_true");
						return true;
					}

				});//fin select
			})($location);
		}); //fin db.transaction
	}
	else
		//ok
		callback(null,"no_MC_UseOk");
}

testi = 0;
function test(callback,value){
//var test = function(tx,value){
	testi = testi + 1;
	console.log(testi);
	console.log(value);
	console.log("fin?");
	callback(null, 'test');
}

function displayQuestionTemplate($sanitize,$scope,$location,$route,res,current){
	console.log(current);
	if (debug)
		alert('displayQuestionTemplate');
	if (debug)
		alert(current);
	console.log(res);
	console.log(JSON.stringify(res));
	console.log(res.rows.item(current));
	console.log("qtype");
	console.log(res.rows.item(current).qtype);
	console.log("qtype ?");

	//test template
	if (res.rows.item(current).qtype == "N")
	{
		//console.log(res.rows.item(current)['qhelp-question_config']);
		qhelp = getQuestionConfig(res.rows.item(current)['qhelp-question_config'])
		if (qhelp.tpl=="radio")
		{
			$location.path('/radioButtonQuestion');
			$route.reload();
		}
	}

	$scope.question = res.rows.item(current).question;
	$scope.qid = res.rows.item(current).qid;
	$scope.reponses = JSON.parse(decodeURI(res.rows.item(current).answers));

	$scope.nextQuiz = function(clickEvent){
		//save
		console.log("save");
		console.log($("input[name="+res.rows.item(current).qid+"]:checked").attr("value"));
		rep = $("input[name="+res.rows.item(current).qid+"]:checked").attr("value");
		var timestamp = Math.round(new Date().getTime() / 1000);
		db.transaction(function(tx)
				{
						//tx.executeSql('INSERT INTO "reponses" (sid, reponse) VALUES ("useOK","'+resultForm+'");
						tx.executeSql('INSERT INTO "reponses" (sid, gid,qid, reponse,tsreponse) VALUES ("'+res.rows.item(current).sid+'","'+res.rows.item(current).gid+'","'+res.rows.item(current).qid+'","'+rep+'","'+timestamp+'");', [], function(tx, res) {});//insert
				});//Transaction

		if (current+1<res.rows.length)
			displayQuestionTemplate($sanitize,$scope,$location,$route,res,current+1);
		else
		{
			$location.path('/');
			$route.reload();
		}
	}
}

function getSurveyConfig()
{
	var config = {};
	var strSurveyConfig = surveys_languagesettings[0].surveyls_description;
	//alert(surveys_languagesettings[0].surveyls_description);
	var line = strSurveyConfig.split("#");
	for (var linekey in line)
	{
		line2 = line[linekey].split(":");
		if (line2[0]!= "")
		{
			line20=line2[0];
			line21=line2[1];
			config[line20] = line21;
		}
	}
	return config;
}

function getQuestionConfig(qhelp)
{
	var config = {};
	//var strSurveyConfig = question.help;
	//alert(surveys_languagesettings[0].surveyls_description);
	var line = qhelp.split("#");
	for (var linekey in line)
	{
		line2 = line[linekey].split(":");
		if (line2[0]!= "")
		{
			line20=line2[0];
			line21=line2[1];
			config[line20] = line21;
		}
	}
	return config;
}
<commit_msg>alert test<commit_after>var async = require('../dist/js/async.js');

////////////////////
//DB

//DB common
function errorHandler(tx, error) {
    console.log("Error: " + error.message);
    if (debug)
    	alert("Error: " + error.message);
}
function successHandler(tx, result) {
    console.log("Success: " + result);
    if (debug)
    	alert("Success: " + result);
}

// DB init
function init_DB(callback)
{
	//init base
	if(isMobile)
    	db = window.sqlitePlugin.openDatabase("Database", "1.0", "Demo", -1);
    else
    	db = openDatabase("Database", "1.0", "Demo", -1);
	callback(null,'initDb');
}

function createTableQuestionnaires(callback)
{
	db.transaction(function(tx)
			{

				// id
				// sid : Survey ID
				// sdescription-survey_config : configuration (ex: #scheduling:D#duration:2400#startHour:10/18#maxOccurences:42#dayOff:0#test:1#)
				// gid : group ID?
				// qid : question ID
				// question
				// qtype -> template question
				// qhelp-question_config -> Configuration : template question complément, fréquence (ex: #tpl:sl7#frq:b#)
				// answers : jsontab? ex : radio buttons

				//tx.executeSql('DROP TABLE IF EXISTS "questionnaires"');
				tx.executeSql('CREATE TABLE IF NOT EXISTS "questionnaires" ' +
								' ("id" INTEGER PRIMARY KEY AUTOINCREMENT , ' +
								'  "sid" VARCHAR,' +
								'  "sdescription-survey_config" VARCHAR,' +
								'  "gid" VARCHAR,' +
								'  "qid" VARCHAR,' +
								'  "question" VARCHAR,' +
								'  "qtype" VARCHAR,' +
								'  "qhelp-question_config" VARCHAR,' +
								'  "answers" VARCHAR );');
								//'  "answers" VARCHAR );',[],callback(null,'createQuestionnairesSuccess'),callback(true,'createQuestionnairesError'));
								//'  "answers" VARCHAR );',[],createQuestionnairesSuccess,createQuestionnairesError);
			//});
			},function(tx){callback(true,'createQuestionnairesError')},function(tx){callback(null,'createQuestionnairesSuccess')});
}

function createTableHoraires(callback)
{
	db.transaction(function(tx)
	{
		//tx.executeSql('DROP TABLE IF EXISTS "horaires"');
		tx.executeSql('CREATE TABLE IF NOT EXISTS "horaires" ("id" INTEGER PRIMARY KEY AUTOINCREMENT , "uidquestionnaire" VARCHAR, "tsdebut" INTEGER, "dureevalidite" INTEGER, "notification" INTEGER, "fait" INTEGER);');
	},function(tx){callback(true,'createHorairesError')},function(tx){callback(null,'createHorairesSuccess')});
}

function createTableReponses(callback)
{
	db.transaction(function(tx)
	{
		//tx.executeSql('DROP TABLE IF EXISTS "reponses"');
		tx.executeSql('CREATE TABLE IF NOT EXISTS "reponses" ("id" INTEGER PRIMARY KEY AUTOINCREMENT , "idhoraire" INTEGER DEFAULT (0), "sid" VARCHAR, "gid" VARCHAR, "qid" VARCHAR, "reponse" VARCHAR, "tsreponse" INTEGER, "envoi" BOOLEAN not null default 0);');
	},function(tx){callback(true,'createReponsesError')},function(tx){callback(null,'createReponsesSuccess')});
}

//function createQuestionnairesSuccess(tx, result){
function createQuestionnairesSuccess(callback){
	if(isMobile)
	{
		store = cordova.file.applicationDirectory;
		if (debug)
			{
		alert('store');
		alert(store);
			}
		fileName = "www/db/questionnaires.txt";
		//window.resolveLocalFileSystemURL(store + fileName, readQuestionnairesSuccess, readQuestionnairesFail);
		window.resolveLocalFileSystemURL(store + fileName, function(fileEntry){readQuestionnairesSuccess(fileEntry,callback) }, readQuestionnairesFail);
		//callback(null,'ok');
	}
	else
	{
		    var req = new XMLHttpRequest();
		    req.open('GET', '../www/db/questionnaires.txt', true);
		    req.onreadystatechange = function (aEvt) {
		      if (req.readyState == 4) {
		         if(req.status == 200)
		        	 {console.log("200000!!!!");
		        	 if (debug)
		        	    	alert("200000!!!!");
		        	 res = req.responseText;
		        	 insertQuestionnaire(res,callback);
		        	 }
		         else
		        	 {
		        	 console.log("Erreur pendant le chargement de la page.\n");
		        	 if (debug)
		        	    	alert("Erreur pendant le chargement de la page.\n");
		        	 }

		      }
		    };
		    req.send(null);
	}

	console.log("dbquest");
	if (debug)
    	alert("dbquest");
	//callback();
};
function createQuestionnairesError(tx, error) {
    console.log("createQuestionnairesError: " + error.message);
    if (debug)
    	alert("createQuestionnairesError: " + error.message);
}
function readQuestionnairesSuccess(fileEntry,callback) {
	fileEntry.file(function(file) {
		var reader = new FileReader();
		reader.onloadend = function(e) {
			console.log(' reader');
			if (debug)
				alert(' reader');
			res = this.result;
			insertQuestionnaire(res,callback);
		}
		reader.readAsText(file);
	});
}
function readQuestionnairesFail(e) {
	console.log("FileSystem Error");
	if (debug)
		alert("FileSystem Error");
	console.dir(e);
	if (debug)
		alert(JSON.stringify(e)));
}
function insertQuestionnaire(res,callback){
	db.transaction(function(tx) {
		var line = res.split("\n");
		for (var linekey in line)
		{
			var line2 = line[linekey].split("';'");
			(function (value) {
				tx.executeSql('SELECT COUNT("id") as cnt FROM "questionnaires" WHERE sid = "'+line2[0].substring(1,line2[0].length)+'";', [], function(tx, res) {
					if (res.rows.item(0).cnt < 1)
					{
						tx.executeSql('INSERT INTO "questionnaires" (sid, "sdescription-survey_config", gid,qid, question, qtype,"qhelp-question_config", answers) VALUES("'+
								value[0].substring(1,value[0].length)+'","'+
								value[1]+'","'+
								value[2]+'","'+
								value[3]+'","'+
								value[4]+'","'+
								value[5]+'","'+
								value[6]+'","'+
								encodeURI(value[7].substring(0,value[7].length-1))+'");',[], successHandler, errorHandler);
					}//fin if
				},errorHandler);//fin select
			})(line2);
		}
	},function(tx){callback(true,'err')},function(tx){callback(null,'ok')});
}

////////////////////
//Functions after_init
function after_init(){
	console.log('after_init');
	if (debug)
		alert('after_init');
	if (MC_UseOk)
	{
		console.log('MC_UseOk');
		do_MC_UseOk();
	}
}

////////////////////
//Functions MC_UseOk

function do_MC_UseOk(callback,$location,$route){
	/*$location.path('/scroll');
	 console.log('loc3 '+$location);
	 console.log('loc3 '+JSON.stringify($location) );*/

	//callback(null,"MC_UseOk_false");

	if (MC_UseOk)
	{
		console.log('MC_UseOk');
		db.transaction(function(tx)
		{
			(function ($location) {
				//tx.executeSql('INSERT INTO "reponses" (sid, reponse) VALUES ("useOK","'+resultForm+'");
				tx.executeSql('SELECT * FROM "reponses" where sid = "useOK" AND reponse = "ok";', [], function(tx, res) {
					console.log(res);
					var dataset = res.rows.length;
		            if(dataset<1)
					//if (res.rows.item(0).cnt < 1)
					{
						console.log('MC_UseOk:false');
						//Change path
						$location.path('/scroll');
						$route.reload();
						//callback(true,"MC_UseOk_false");
						//return false;
					}
					else
					{
						console.log('MC_UseOk:true');
						callback(null,"MC_UseOk_true");
						return true;
					}

				});//fin select
			})($location);
		}); //fin db.transaction
	}
	else
		//ok
		callback(null,"no_MC_UseOk");
}

testi = 0;
function test(callback,value){
//var test = function(tx,value){
	testi = testi + 1;
	console.log(testi);
	console.log(value);
	console.log("fin?");
	callback(null, 'test');
}

function displayQuestionTemplate($sanitize,$scope,$location,$route,res,current){
	console.log(current);
	if (debug)
		alert('displayQuestionTemplate');
	if (debug)
		alert(current);
	console.log(res);
	console.log(JSON.stringify(res));
	console.log(res.rows.item(current));
	console.log("qtype");
	console.log(res.rows.item(current).qtype);
	console.log("qtype ?");

	//test template
	if (res.rows.item(current).qtype == "N")
	{
		//console.log(res.rows.item(current)['qhelp-question_config']);
		qhelp = getQuestionConfig(res.rows.item(current)['qhelp-question_config'])
		if (qhelp.tpl=="radio")
		{
			$location.path('/radioButtonQuestion');
			$route.reload();
		}
	}

	$scope.question = res.rows.item(current).question;
	$scope.qid = res.rows.item(current).qid;
	$scope.reponses = JSON.parse(decodeURI(res.rows.item(current).answers));

	$scope.nextQuiz = function(clickEvent){
		//save
		console.log("save");
		console.log($("input[name="+res.rows.item(current).qid+"]:checked").attr("value"));
		rep = $("input[name="+res.rows.item(current).qid+"]:checked").attr("value");
		var timestamp = Math.round(new Date().getTime() / 1000);
		db.transaction(function(tx)
				{
						//tx.executeSql('INSERT INTO "reponses" (sid, reponse) VALUES ("useOK","'+resultForm+'");
						tx.executeSql('INSERT INTO "reponses" (sid, gid,qid, reponse,tsreponse) VALUES ("'+res.rows.item(current).sid+'","'+res.rows.item(current).gid+'","'+res.rows.item(current).qid+'","'+rep+'","'+timestamp+'");', [], function(tx, res) {});//insert
				});//Transaction

		if (current+1<res.rows.length)
			displayQuestionTemplate($sanitize,$scope,$location,$route,res,current+1);
		else
		{
			$location.path('/');
			$route.reload();
		}
	}
}

function getSurveyConfig()
{
	var config = {};
	var strSurveyConfig = surveys_languagesettings[0].surveyls_description;
	//alert(surveys_languagesettings[0].surveyls_description);
	var line = strSurveyConfig.split("#");
	for (var linekey in line)
	{
		line2 = line[linekey].split(":");
		if (line2[0]!= "")
		{
			line20=line2[0];
			line21=line2[1];
			config[line20] = line21;
		}
	}
	return config;
}

function getQuestionConfig(qhelp)
{
	var config = {};
	//var strSurveyConfig = question.help;
	//alert(surveys_languagesettings[0].surveyls_description);
	var line = qhelp.split("#");
	for (var linekey in line)
	{
		line2 = line[linekey].split(":");
		if (line2[0]!= "")
		{
			line20=line2[0];
			line21=line2[1];
			config[line20] = line21;
		}
	}
	return config;
}
<|endoftext|>


<commit_before>const db = require('../db.js');

// Get trips.
async function getTrips(req, res) {

	try {

		const trips = await db.query(`
			SELECT time, wheelchair, short_name, long_name FROM stops AS stop
				JOIN stop_times ON stop_id = id
				JOIN trips AS trip ON trip.id = trip_id
				JOIN routes AS route ON route.id = route_id
			WHERE
				stop.id = ?
				AND time BETWEEN CURTIME() AND ADDTIME(CURTIME(), '01:00:00')
				AND service_id IN (
					SELECT service_id FROM services
					WHERE
						CURDATE() BETWEEN start AND end
						AND SUBSTR(days, WEEKDAY(CURDATE()) + 1, 1) = '1'
						AND service_id NOT IN (
							SELECT service_id FROM service_Exceptions WHERE type = 0 AND date = CURDATE()
						)
					UNION
						SELECT service_id FROM service_exceptions WHERE type = 1 AND date = CURDATE()
				)
			ORDER BY time
		`, [ req.query['id'] ]);

	} catch (ex) {
		res.code(500).send(ex);
	}

}

module.exports = (fastify, opts, next) => {
	fastify.get('/trips', getTrips);
	next();
};
<commit_msg>Refactor trip route (api)<commit_after>const got = require('got');

const db = require('../db.js');

// Get trips.
async function getTrips(req, res) {

	const id = req.query['id'];

	try {

		const trips = await db.query(`
			SELECT TIME_TO_SEC(time) AS time, short_name, long_name, wheelchair, route.type, route.region, trip_id FROM stops AS stop
				JOIN stop_times ON stop_id = id
				JOIN trips AS trip ON trip.id = trip_id
				JOIN routes AS route ON route.id = route_id
			WHERE
				stop.id = ?
				AND time BETWEEN CURTIME() AND ADDTIME(CURTIME(), '01:00:00')
				AND service_id IN (
					SELECT service_id FROM services
					WHERE
						CURDATE() BETWEEN start AND end
						AND SUBSTR(days, WEEKDAY(CURDATE()) + 1, 1) = '1'
						AND service_id NOT IN (
							SELECT service_id FROM service_Exceptions WHERE type = 0 AND date = CURDATE()
						)
					UNION
						SELECT service_id FROM service_exceptions WHERE type = 1 AND date = CURDATE()
				)
			ORDER BY time
		`, [ id ]);

		res.send(trips);

	} catch (ex) {
		res.code(500).send(ex);
	}

}

module.exports = (fastify, opts, next) => {
	fastify.get('/trips', getTrips);
	next();
};
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const glob = require('glob');
const camelCase = require('camelcase');
const ngc = require('@angular/compiler-cli/src/main').main;
const rollup = require('rollup');
const uglify = require('rollup-plugin-uglify');
const sourcemaps = require('rollup-plugin-sourcemaps');
const commonjs = require('rollup-plugin-commonjs');
const nodeResolve = require('rollup-plugin-node-resolve');
const inlineResources = require('./inline-resources');
const libName = require('./package.json').name;
const rootFolder = path.join(__dirname);
const compilationFolder = path.join(rootFolder, 'out-tsc');
const srcFolder = path.join(rootFolder, 'src/lib');
const distFolder = path.join(rootFolder, 'dist');
const tempLibFolder = path.join(compilationFolder, 'lib');
const es5OutputFolder = path.join(compilationFolder, 'lib-es5');
const es2015OutputFolder = path.join(compilationFolder, 'lib-es2015');

return Promise.resolve()
  // Copy library to temporary folder and inline html/css.
  .then(() => _relativeCopy(`**/*`, srcFolder, tempLibFolder)
    .then(() => inlineResources(tempLibFolder))
    .then(() => console.log('Inlining succeeded.'))
  )
  // Compile to ES2015.
  .then(() => ngc({ project: `${tempLibFolder}/tsconfig.lib.json` })
    .then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
    .then(() => console.log('ES2015 compilation succeeded.'))
  )
  // Compile to ES5.
  .then(() => ngc({ project: `${tempLibFolder}/tsconfig.es5.json` })
    .then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
    .then(() => console.log('ES5 compilation succeeded.'))
  )
  // Copy typings and metadata to `dist/` folder.
  .then(() => Promise.resolve()
    .then(() => _relativeCopy('**/*.d.ts', es2015OutputFolder, distFolder))
    .then(() => _relativeCopy('**/*.metadata.json', es2015OutputFolder, distFolder))
    .then(() => console.log('Typings and metadata copy succeeded.'))
  )
  // Bundle lib.
  .then(() => {
    // Base configuration.
    const es5Entry = path.join(es5OutputFolder, `${libName}.js`);
    const es2015Entry = path.join(es2015OutputFolder, `${libName}.js`);
    const rollupBaseConfig = {
      moduleName: camelCase(libName),
      sourceMap: true,
      // ATTENTION:
      // Add any dependency or peer dependency your library to `globals` and `external`.
      // This is required for UMD bundle users.
      globals: {
        // The key here is library name, and the value is the the name of the global variable name
        // the window object.
        // See https://github.com/rollup/rollup/wiki/JavaScript-API#globals for more.
        '@angular/core': 'ng.core'
      },
      external: [
        // List of dependencies
        // See https://github.com/rollup/rollup/wiki/JavaScript-API#external for more.
        '@angular/core'
      ],
      plugins: [
        nodeResolve({
          main: true,
          jsnext: true,
          browser: true,
        }),
        commonjs({
          namedExports: {
            // left-hand side can be an absolute path, a path
            // relative to the current directory, or the name
            // of a module in node_modules
            'sidebarjs': [ 'SidebarElement', 'SidebarService' ]
          }
        }),
        sourcemaps()
      ]
    };

    // UMD bundle.
    const umdConfig = Object.assign({}, rollupBaseConfig, {
      entry: es5Entry,
      dest: path.join(distFolder, `bundles`, `${libName}.umd.js`),
      format: 'umd',
    });

    // Minified UMD bundle.
    const minifiedUmdConfig = Object.assign({}, rollupBaseConfig, {
      entry: es5Entry,
      dest: path.join(distFolder, `bundles`, `${libName}.umd.min.js`),
      format: 'umd',
      plugins: rollupBaseConfig.plugins.concat([uglify({})])
    });

    // ESM+ES5 flat module bundle.
    const fesm5config = Object.assign({}, rollupBaseConfig, {
      entry: es5Entry,
      dest: path.join(distFolder, `${libName}.es5.js`),
      format: 'es'
    });

    // ESM+ES2015 flat module bundle.
    const fesm2015config = Object.assign({}, rollupBaseConfig, {
      entry: es2015Entry,
      dest: path.join(distFolder, `${libName}.js`),
      format: 'es'
    });

    const allBundles = [
      umdConfig,
      minifiedUmdConfig,
      fesm5config,
      fesm2015config
    ].map(cfg => rollup.rollup(cfg).then(bundle => bundle.write(cfg)));

    return Promise.all(allBundles)
      .then(() => console.log('All bundles generated successfully.'))
  })
  // Copy package files
  .then(() => Promise.resolve()
    .then(() => _relativeCopy('LICENSE', rootFolder, distFolder))
    .then(() => _relativeCopy('package.json', rootFolder, distFolder))
    .then(() => _relativeCopy('README.md', rootFolder, distFolder))
    .then(() => console.log('Package files copy succeeded.'))
  )
  .catch(e => {
    console.error('\Build failed. See below for errors.\n');
    console.error(e);
    process.exit(1);
  });

// Copy files maintaining relative paths.
function _relativeCopy(fileGlob, from, to) {
  return new Promise((resolve, reject) => {
    glob(fileGlob, { cwd: from, nodir: true }, (err, files) => {
      if (err) reject(err);
      files.forEach(file => {
        const origin = path.join(from, file);
        const dest = path.join(to, file);
        const data = fs.readFileSync(origin, 'utf-8');
        _recursiveMkDir(path.dirname(dest));
        fs.writeFileSync(dest, data);
        resolve();
      })
    })
  });
}

// Recursively create a dir.
function _recursiveMkDir(dir) {
  if (!fs.existsSync(dir)) {
    _recursiveMkDir(path.dirname(dir));
    fs.mkdirSync(dir);
  }
}
<commit_msg>fix(build): new api of ngc|rollup<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const glob = require('glob');
const camelCase = require('camelcase');
const ngc = require('@angular/compiler-cli/src/main').main;
const rollup = require('rollup');
const uglify = require('rollup-plugin-uglify');
const sourcemaps = require('rollup-plugin-sourcemaps');
const commonjs = require('rollup-plugin-commonjs');
const nodeResolve = require('rollup-plugin-node-resolve');
const inlineResources = require('./inline-resources');
const libName = require('./package.json').name;
const rootFolder = path.join(__dirname);
const compilationFolder = path.join(rootFolder, 'out-tsc');
const srcFolder = path.join(rootFolder, 'src/lib');
const distFolder = path.join(rootFolder, 'dist');
const tempLibFolder = path.join(compilationFolder, 'lib');
const es5OutputFolder = path.join(compilationFolder, 'lib-es5');
const es2015OutputFolder = path.join(compilationFolder, 'lib-es2015');

return Promise.resolve()
  // Copy library to temporary folder and inline html/css.
  .then(() => _relativeCopy(`**/*`, srcFolder, tempLibFolder)
    .then(() => inlineResources(tempLibFolder))
    .then(() => console.log('Inlining succeeded.'))
  )
  // Compile to ES2015.
  .then(() => Promise.resolve(ngc(['-p', `${tempLibFolder}/tsconfig.lib.json`]))
    .then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
    .then(() => console.log('ES2015 compilation succeeded.'))
  )
  // Compile to ES5.
  .then(() => Promise.resolve(ngc(['-p', `${tempLibFolder}/tsconfig.es5.json`]))
    .then(exitCode => exitCode === 0 ? Promise.resolve() : Promise.reject())
    .then(() => console.log('ES5 compilation succeeded.'))
  )
  // Copy typings and metadata to `dist/` folder.
  .then(() => Promise.resolve()
    .then(() => _relativeCopy('**/*.d.ts', es2015OutputFolder, distFolder))
    .then(() => _relativeCopy('**/*.metadata.json', es2015OutputFolder, distFolder))
    .then(() => console.log('Typings and metadata copy succeeded.'))
  )
  // Bundle lib.
  .then(() => {
    // Base configuration.
    const extendConfig = (baseC, newC) => ({
      ...baseC, ...newC,
      output: {...baseC.output, ...newC.output,},
      plugins: [...baseC.plugins, ...(newC.plugins || [])],
    });
    const es5Entry = path.join(es5OutputFolder, `${libName}.js`);
    const es2015Entry = path.join(es2015OutputFolder, `${libName}.js`);
    const rollupBaseConfig = {
      output: {
        name: camelCase(libName),
        sourcemap: true,
        globals: {
          // The key here is library name, and the value is the the name of the global variable name
          // the window object.
          // See https://github.com/rollup/rollup/wiki/JavaScript-API#globals for more.
          '@angular/core': 'ng.core'
        },
      },
      // ATTENTION:
      // Add any dependency or peer dependency your library to `globals` and `external`.
      // This is required for UMD bundle users.
      external: [
        // List of dependencies
        // See https://github.com/rollup/rollup/wiki/JavaScript-API#external for more.
        '@angular/core'
      ],
      plugins: [
        nodeResolve({
          main: true,
          jsnext: true,
          browser: true,
        }),
        commonjs({
          namedExports: {
            // left-hand side can be an absolute path, a path
            // relative to the current directory, or the name
            // of a module in node_modules
            'sidebarjs': ['SidebarElement', 'SidebarService']
          }
        }),
        sourcemaps()
      ]
    };

    // UMD bundle.
    const umdConfig = extendConfig(rollupBaseConfig, {
      input: es5Entry,
      output: {
        file: path.join(distFolder, `bundles`, `${libName}.umd.js`),
        format: 'umd',
      },
    });

    // Minified UMD bundle.
    const minifiedUmdConfig = extendConfig(rollupBaseConfig, {
      input: es5Entry,
      output: {
        file: path.join(distFolder, `bundles`, `${libName}.umd.min.js`),
        format: 'umd',
      },
      plugins: [rollupBaseConfig.plugins.concat([uglify({})])]
    });

    // ESM+ES5 flat module bundle.
    const fesm5config = extendConfig(rollupBaseConfig, {
      input: es5Entry,
      output: {
        file: path.join(distFolder, `${libName}.es5.js`),
        format: 'es'
      },
    });

    // ESM+ES2015 flat module bundle.
    const fesm2015config = extendConfig(rollupBaseConfig, {
      input: es2015Entry,
      output: {
        file: path.join(distFolder, `${libName}.js`),
        format: 'es'
      },
    });

    const allBundles = [
      umdConfig,
      minifiedUmdConfig,
      fesm5config,
      fesm2015config
    ].map(cfg => rollup.rollup(cfg).then(bundle => bundle.write(cfg.output)));

    return Promise.all(allBundles)
      .then(() => console.log('All bundles generated successfully.'))
  })
  // Copy package files
  .then(() => Promise.resolve()
    .then(() => _relativeCopy('LICENSE', rootFolder, distFolder))
    .then(() => _relativeCopy('package.json', rootFolder, distFolder))
    .then(() => _relativeCopy('README.md', rootFolder, distFolder))
    .then(() => console.log('Package files copy succeeded.'))
  )
  .catch(e => {
    console.error('\Build failed. See below for errors.\n');
    console.error(e);
    process.exit(1);
  });

// Copy files maintaining relative paths.
function _relativeCopy(fileGlob, from, to) {
  return new Promise((resolve, reject) => {
    glob(fileGlob, {cwd: from, nodir: true}, (err, files) => {
      if (err) reject(err);
      files.forEach(file => {
        const origin = path.join(from, file);
        const dest = path.join(to, file);
        const data = fs.readFileSync(origin, 'utf-8');
        _recursiveMkDir(path.dirname(dest));
        fs.writeFileSync(dest, data);
        resolve();
      })
    })
  });
}

// Recursively create a dir.
function _recursiveMkDir(dir) {
  if (!fs.existsSync(dir)) {
    _recursiveMkDir(path.dirname(dir));
    fs.mkdirSync(dir);
  }
}
<|endoftext|>


<commit_before>CT.admin.monitor = {
	"snapshot": function() {
		var names = [], vals = [], lz = CT.admin.monitor._logs;
		lz.forEach(function(log, i) {
			names.push(log[0] + " (" + log[1].length + ")");
			vals.push(i);
		});
		var s1 = CT.dom.select(names, vals),
			s2 = CT.dom.select(names, vals);
		var mod = new CT.modal.Modal({
			transition: "slide",
			content: [
				"Start?", s1, "End?", s2,
				CT.dom.button("Go", function() {
					var vz = s1.value + s2.value;
					mod.hide();
					(new CT.modal.Modal({
						transition: "slide",
						slide: { origin: "bottom" },
						className: "basicpopup unlimited h4-5 w4-5",
						content: [
							CT.dom.div(names[s1.value].slice(13) + " - " + names[s2.value].slice(13),
								"biggest bold centered"),
							CT.dom.div(null, "ct-chart ct-perfect-fourth", "graph" + vz),
							CT.dom.div(null, "centered", "legend" + vz),
							CT.dom.div(null, "abs ctr", "web_totals" + vz),
							CT.dom.div(null, "abs ctl", "admin_totals" + vz)
						]
					})).show(null, function() {
						var graph = new CT.admin.monitor.Graph({
							graph: "graph" + vz,
							legend: "legend" + vz,
							web_totals: "web_totals" + vz,
							admin_totals: "admin_totals" + vz
						});
						lz.slice(parseInt(s1.value), parseInt(s2.value) + 1).forEach(function(ldata) {
							var lpath = ldata[0], lhours = ldata[1];
							lhours.forEach(function(hour) {
								CT.net.get("/" + lpath + "/" + hour).split("\n").forEach(function(log) {
									log && graph.update({ message: JSON.parse(log) });
								});
							});
						});
					});
				})
			]
		});
		mod.show();
	},
	"init": function() {
		CT.admin.core.init("monitor", function(data) {
			CT.admin.monitor._graph = new CT.admin.monitor.Graph();
			CT.pubsub.set_autohistory(true);
			CT.pubsub.set_cb("message", CT.admin.monitor._graph.update);
			CT.pubsub.subscribe("monitor");
			CT.pubsub.connect(data.host, data.port,
				"__admin__" + Math.floor(Math.random() * 1000) + btoa(CT.admin.core._pw));
			CT.admin.monitor._logs = data.logs;
			CT.admin.monitor._cache = {};
			if (data.logs) {
				var snap = CT.dom.id("snapshot");
				snap.onclick = CT.admin.monitor.snapshot;
				CT.dom.show(snap);
			}
		});
	}
};

CT.admin.monitor.Graph = CT.Class({
	CLASSNAME: "CT.admin.monitor.Graph",
	_graph: function() {
		new Chartist.Line("#" + this.opts.graph, {
			series: Object.values(this.data)
		}, { low: 0, high: 100 });
	},
	update: function(data) {
		var key, d, tcat, fresh = !Object.keys(this.data).length;
		for (key in data.message) {
			d = data.message[key];
			if (key == "totals") {
				for (tcat in d) {
					CT.dom.setContent(this.opts[tcat + "_totals"], Object.keys(d[tcat]).map(function(cname) {
						return d[tcat][cname] + " total " + tcat + " " + cname;
					}));
				}
				continue;
			}
			if (!(key in this.data))
				this.data[key] = [];
			if (["read", "write"].indexOf(key) != -1)
				d /= 10000;
			else if (["sent", "recv"].indexOf(key) != -1)
				d /= 100000000;
			this.data[key].push(d);
		}
		this._graph();
		if (fresh) {
			var lines = Object.keys(this.data).map(function(k) {
				if (["read", "write"].indexOf(k) != -1)
					k += " (X 10,000)";
				else if (["sent", "recv"].indexOf(k) != -1)
					k += " (X 100,000,000)";
				return CT.dom.div(k, "big m5 padded inline-block")
			}), graph = CT.dom.id(this.opts.graph);
			CT.dom.addContent(this.opts.legend, lines);
			setTimeout(function() {
				CT.dom.className("ct-line", graph).forEach(function(n, i) {
					lines[i].style.background
						= window.getComputedStyle(n).getPropertyValue("stroke");
				});
			}, 200);
		}
	},
	init: function(opts) {
		this.opts = opts = CT.merge(opts, {
			data: {},
			graph: "graph",
			legend: "legend",
			web_totals: "web_totals",
			admin_totals: "admin_totals"
		});
		this.data = opts.data;
	}
});<commit_msg>admin monitor snapshots: sort logs (by day)<commit_after>CT.admin.monitor = {
	"snapshot": function() {
		var names = [], vals = [], lz = CT.admin.monitor._logs;
		lz.forEach(function(log, i) {
			names.push(log[0] + " (" + log[1].length + ")");
			vals.push(i);
		});
		var s1 = CT.dom.select(names, vals),
			s2 = CT.dom.select(names, vals);
		var mod = new CT.modal.Modal({
			transition: "slide",
			content: [
				"Start?", s1, "End?", s2,
				CT.dom.button("Go", function() {
					var vz = s1.value + s2.value;
					mod.hide();
					(new CT.modal.Modal({
						transition: "slide",
						slide: { origin: "bottom" },
						className: "basicpopup unlimited h4-5 w4-5",
						content: [
							CT.dom.div(names[s1.value].slice(13) + " - " + names[s2.value].slice(13),
								"biggest bold centered"),
							CT.dom.div(null, "ct-chart ct-perfect-fourth", "graph" + vz),
							CT.dom.div(null, "centered", "legend" + vz),
							CT.dom.div(null, "abs ctr", "web_totals" + vz),
							CT.dom.div(null, "abs ctl", "admin_totals" + vz)
						]
					})).show(null, function() {
						var graph = new CT.admin.monitor.Graph({
							graph: "graph" + vz,
							legend: "legend" + vz,
							web_totals: "web_totals" + vz,
							admin_totals: "admin_totals" + vz
						});
						lz.slice(parseInt(s1.value), parseInt(s2.value) + 1).forEach(function(ldata) {
							var lpath = ldata[0], lhours = ldata[1];
							lhours.forEach(function(hour) {
								CT.net.get("/" + lpath + "/" + hour).split("\n").forEach(function(log) {
									log && graph.update({ message: JSON.parse(log) });
								});
							});
						});
					});
				})
			]
		});
		mod.show();
	},
	"init": function() {
		CT.admin.core.init("monitor", function(data) {
			CT.admin.monitor._graph = new CT.admin.monitor.Graph();
			CT.pubsub.set_autohistory(true);
			CT.pubsub.set_cb("message", CT.admin.monitor._graph.update);
			CT.pubsub.subscribe("monitor");
			CT.pubsub.connect(data.host, data.port,
				"__admin__" + Math.floor(Math.random() * 1000) + btoa(CT.admin.core._pw));
			data.logs.sort(function(a, b) { return a[0] < b[0] ? -1 : 1; });
			CT.admin.monitor._logs = data.logs;
			CT.admin.monitor._cache = {};
			if (data.logs) {
				var snap = CT.dom.id("snapshot");
				snap.onclick = CT.admin.monitor.snapshot;
				CT.dom.show(snap);
			}
		});
	}
};

CT.admin.monitor.Graph = CT.Class({
	CLASSNAME: "CT.admin.monitor.Graph",
	_graph: function() {
		new Chartist.Line("#" + this.opts.graph, {
			series: Object.values(this.data)
		}, { low: 0, high: 100 });
	},
	update: function(data) {
		var key, d, tcat, fresh = !Object.keys(this.data).length;
		for (key in data.message) {
			d = data.message[key];
			if (key == "totals") {
				for (tcat in d) {
					CT.dom.setContent(this.opts[tcat + "_totals"], Object.keys(d[tcat]).map(function(cname) {
						return d[tcat][cname] + " total " + tcat + " " + cname;
					}));
				}
				continue;
			}
			if (!(key in this.data))
				this.data[key] = [];
			if (["read", "write"].indexOf(key) != -1)
				d /= 10000;
			else if (["sent", "recv"].indexOf(key) != -1)
				d /= 100000000;
			this.data[key].push(d);
		}
		this._graph();
		if (fresh) {
			var lines = Object.keys(this.data).map(function(k) {
				if (["read", "write"].indexOf(k) != -1)
					k += " (X 10,000)";
				else if (["sent", "recv"].indexOf(k) != -1)
					k += " (X 100,000,000)";
				return CT.dom.div(k, "big m5 padded inline-block")
			}), graph = CT.dom.id(this.opts.graph);
			CT.dom.addContent(this.opts.legend, lines);
			setTimeout(function() {
				CT.dom.className("ct-line", graph).forEach(function(n, i) {
					lines[i].style.background
						= window.getComputedStyle(n).getPropertyValue("stroke");
				});
			}, 200);
		}
	},
	init: function(opts) {
		this.opts = opts = CT.merge(opts, {
			data: {},
			graph: "graph",
			legend: "legend",
			web_totals: "web_totals",
			admin_totals: "admin_totals"
		});
		this.data = opts.data;
	}
});<|endoftext|>


<commit_before>module.exports = (text) => {
  text = text.replace(/\w[sS]/g, 'sch');
  text = text.replace(/\bnein\b|\bNein\b/g, 'noi');
  text = text.replace(/\bDer\b|\bder\b/g, 'da');
  text = text.replace(/\bnicht\b|\bNicht\b/g, 'ned');
  text = text.replace(/\bwir\b|\bWir\b/g, 'mir');
  text = text.replace(/en\b/g, 'e');
  text = text.replace(/ei/g, 'oi');
  return text;
};
<commit_msg>:ant: fix(intents): fixed swabian<commit_after>module.exports = (text) => {
  text = text.replace(/[sS]/g, 'sch');
  text = text.replace(/\bnein\b|\bNein\b/g, 'noi');
  text = text.replace(/\bDer\b|\bder\b/g, 'da');
  text = text.replace(/\bnicht\b|\bNicht\b/g, 'ned');
  text = text.replace(/\bwir\b|\bWir\b/g, 'mir');
  text = text.replace(/en\b/g, 'e');
  text = text.replace(/ei/g, 'oi');
  return text;
};
<|endoftext|>