<commit_before>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../../../src/utils/Class');
var GetFastValue = require('../../../src/utils/object/GetFastValue');
var ImageFile = require('../../../src/loader/filetypes/ImageFile.js');
var IsPlainObject = require('../../../src/utils/object/IsPlainObject');
var JSONFile = require('../../../src/loader/filetypes/JSONFile.js');
var MultiFile = require('../../../src/loader/MultiFile.js');
var TextFile = require('../../../src/loader/filetypes/TextFile.js');

/**
 * @typedef {object} Phaser.Loader.FileTypes.SpineFileConfig
 *
 * @property {string} key - The key of the file. Must be unique within both the Loader and the Texture Manager.
 * @property {string|string[]} [jsonURL] - The absolute or relative URL to load the JSON file from. If undefined or `null` it will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
 * @property {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `<key>.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt".
 * @property {boolean} [preMultipliedAlpha=false] - Do the textures contain pre-multiplied alpha or not?
 * @property {XHRSettingsObject} [jsonXhrSettings] - An XHR Settings configuration object for the json file. Used in replacement of the Loaders default XHR Settings.
 * @property {XHRSettingsObject} [atlasXhrSettings] - An XHR Settings configuration object for the atlas data file. Used in replacement of the Loaders default XHR Settings.
 */

/**
 * @classdesc
 * A Spine File suitable for loading by the Loader.
 *
 * These are created when you use the Phaser.Loader.LoaderPlugin#spine method and are not typically created directly.
 *
 * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#spine.
 *
 * @class SpineFile
 * @extends Phaser.Loader.MultiFile
 * @memberof Phaser.Loader.FileTypes
 * @constructor
 *
 * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file.
 * @param {(string|Phaser.Loader.FileTypes.SpineFileConfig)} key - The key to use for this file, or a file configuration object.
 * @param {string|string[]} [jsonURL] - The absolute or relative URL to load the JSON file from. If undefined or `null` it will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
 * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `<key>.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt".
 * @param {boolean} [preMultipliedAlpha=false] - Do the textures contain pre-multiplied alpha or not?
 * @param {XHRSettingsObject} [jsonXhrSettings] - An XHR Settings configuration object for the json file. Used in replacement of the Loaders default XHR Settings.
 * @param {XHRSettingsObject} [atlasXhrSettings] - An XHR Settings configuration object for the atlas data file. Used in replacement of the Loaders default XHR Settings.
 */
var SpineFile = new Class({

    Extends: MultiFile,

    initialize:

    function SpineFile (loader, key, jsonURL, atlasURL, preMultipliedAlpha, jsonXhrSettings, atlasXhrSettings)
    {
        var i;
        var json;
        var atlas;
        var files = [];
        var cache = loader.cacheManager.custom.spine;

        //  atlas can be an array of atlas files, not just a single one

        if (IsPlainObject(key))
        {
            var config = key;

            key = GetFastValue(config, 'key');

            json = new JSONFile(loader, {
                key: key,
                url: GetFastValue(config, 'jsonURL'),
                extension: GetFastValue(config, 'jsonExtension', 'json'),
                xhrSettings: GetFastValue(config, 'jsonXhrSettings')
            });

            atlasURL = GetFastValue(config, 'atlasURL');
            preMultipliedAlpha = GetFastValue(config, 'preMultipliedAlpha');

            if (!Array.isArray(atlasURL))
            {
                atlasURL = [ atlasURL ];
            }

            for (i = 0; i < atlasURL.length; i++)
            {
                atlas = new TextFile(loader, {
                    key: key + '_' + i,
                    url: atlasURL[i],
                    extension: GetFastValue(config, 'atlasExtension', 'atlas'),
                    xhrSettings: GetFastValue(config, 'atlasXhrSettings')
                });

                atlas.cache = cache;

                files.push(atlas);
            }
        }
        else
        {
            json = new JSONFile(loader, key, jsonURL, jsonXhrSettings);

            if (!Array.isArray(atlasURL))
            {
                atlasURL = [ atlasURL ];
            }

            for (i = 0; i < atlasURL.length; i++)
            {
                atlas = new TextFile(loader, key + '_' + i, atlasURL[i], atlasXhrSettings);
                atlas.cache = cache;

                files.push(atlas);
            }
        }

        files.unshift(json);

        MultiFile.call(this, loader, 'spine', key, files);

        this.config.preMultipliedAlpha = preMultipliedAlpha;
    },

    /**
     * Called by each File when it finishes loading.
     *
     * @method Phaser.Loader.FileTypes.SpineFile#onFileComplete
     * @since 3.19.0
     *
     * @param {Phaser.Loader.File} file - The File that has completed processing.
     */
    onFileComplete: function (file)
    {
        var index = this.files.indexOf(file);

        if (index !== -1)
        {
            this.pending--;

            if (file.type === 'text')
            {
                //  Inspect the data for the files to now load
                var content = file.data.split('\n');

                //  Extract the textures
                var textures = [];

                for (var t = 0; t < content.length; t++)
                {
                    var line = content[t];

                    if (line.trim() === '' && t < content.length - 1)
                    {
                        line = content[t + 1];

                        textures.push(line);
                    }
                }

                var config = this.config;
                var loader = this.loader;

                var currentBaseURL = loader.baseURL;
                var currentPath = loader.path;
                var currentPrefix = loader.prefix;

                var baseURL = GetFastValue(config, 'baseURL', this.baseURL);
                var path = GetFastValue(config, 'path', file.src.match(/^.*\//))[0];
                var prefix = GetFastValue(config, 'prefix', this.prefix);
                var textureXhrSettings = GetFastValue(config, 'textureXhrSettings');

                loader.setBaseURL(baseURL);
                loader.setPath(path);
                loader.setPrefix(prefix);

                for (var i = 0; i < textures.length; i++)
                {
                    var textureURL = textures[i];

                    var key = this.prefix + textureURL;

                    var image = new ImageFile(loader, key, textureURL, textureXhrSettings);

                    this.addToMultiFile(image);

                    loader.addFile(image);
                }

                //  Reset the loader settings
                loader.setBaseURL(currentBaseURL);
                loader.setPath(currentPath);
                loader.setPrefix(currentPrefix);
            }
        }
    },

    /**
     * Adds this file to its target cache upon successful loading and processing.
     *
     * @method Phaser.Loader.FileTypes.SpineFile#addToCache
     * @since 3.19.0
     */
    addToCache: function ()
    {
        if (this.isReadyToProcess())
        {
            var fileJSON = this.files[0];

            fileJSON.addToCache();

            var atlasCache;
            var atlasKey = '';
            var combinedAtlasData = '';
            var preMultipliedAlpha = (this.config.preMultipliedAlpha) ? true : false;

            for (var i = 1; i < this.files.length; i++)
            {
                var file = this.files[i];

                if (file.type === 'text')
                {
                    atlasKey = file.key.replace(/_[\d]$/, '');

                    atlasCache = file.cache;

                    combinedAtlasData = combinedAtlasData.concat(file.data);
                }
                else
                {
                    var src = file.key.trim();
                    var pos = src.indexOf('_');
                    var key = src.substr(pos + 1);

                    this.loader.textureManager.addImage(key, file.data);
                }

                file.pendingDestroy();
            }

            atlasCache.add(atlasKey, { preMultipliedAlpha: preMultipliedAlpha, data: combinedAtlasData, prefix: this.prefix });

            this.complete = true;
        }
    }

});

module.exports = SpineFile;
<commit_msg>The `SpineFile` will no longer throw a warning if adding a texture into the Texture Manager that already exists. This allows you to have multiple Spine JSON use the same texture file, however, it also means you now get no warning if you accidentally load a texture that exists, so be careful with your keys! Fix #4947<commit_after>/**
 * @author       Richard Davey <rich@photonstorm.com>
 * @copyright    2018 Photon Storm Ltd.
 * @license      {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
 */

var Class = require('../../../src/utils/Class');
var GetFastValue = require('../../../src/utils/object/GetFastValue');
var ImageFile = require('../../../src/loader/filetypes/ImageFile.js');
var IsPlainObject = require('../../../src/utils/object/IsPlainObject');
var JSONFile = require('../../../src/loader/filetypes/JSONFile.js');
var MultiFile = require('../../../src/loader/MultiFile.js');
var TextFile = require('../../../src/loader/filetypes/TextFile.js');

/**
 * @typedef {object} Phaser.Loader.FileTypes.SpineFileConfig
 *
 * @property {string} key - The key of the file. Must be unique within both the Loader and the Texture Manager.
 * @property {string|string[]} [jsonURL] - The absolute or relative URL to load the JSON file from. If undefined or `null` it will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
 * @property {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `<key>.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt".
 * @property {boolean} [preMultipliedAlpha=false] - Do the textures contain pre-multiplied alpha or not?
 * @property {XHRSettingsObject} [jsonXhrSettings] - An XHR Settings configuration object for the json file. Used in replacement of the Loaders default XHR Settings.
 * @property {XHRSettingsObject} [atlasXhrSettings] - An XHR Settings configuration object for the atlas data file. Used in replacement of the Loaders default XHR Settings.
 */

/**
 * @classdesc
 * A Spine File suitable for loading by the Loader.
 *
 * These are created when you use the Phaser.Loader.LoaderPlugin#spine method and are not typically created directly.
 *
 * For documentation about what all the arguments and configuration options mean please see Phaser.Loader.LoaderPlugin#spine.
 *
 * @class SpineFile
 * @extends Phaser.Loader.MultiFile
 * @memberof Phaser.Loader.FileTypes
 * @constructor
 *
 * @param {Phaser.Loader.LoaderPlugin} loader - A reference to the Loader that is responsible for this file.
 * @param {(string|Phaser.Loader.FileTypes.SpineFileConfig)} key - The key to use for this file, or a file configuration object.
 * @param {string|string[]} [jsonURL] - The absolute or relative URL to load the JSON file from. If undefined or `null` it will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
 * @param {string} [atlasURL] - The absolute or relative URL to load the texture atlas data file from. If undefined or `null` it will be set to `<key>.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt".
 * @param {boolean} [preMultipliedAlpha=false] - Do the textures contain pre-multiplied alpha or not?
 * @param {XHRSettingsObject} [jsonXhrSettings] - An XHR Settings configuration object for the json file. Used in replacement of the Loaders default XHR Settings.
 * @param {XHRSettingsObject} [atlasXhrSettings] - An XHR Settings configuration object for the atlas data file. Used in replacement of the Loaders default XHR Settings.
 */
var SpineFile = new Class({

    Extends: MultiFile,

    initialize:

    function SpineFile (loader, key, jsonURL, atlasURL, preMultipliedAlpha, jsonXhrSettings, atlasXhrSettings)
    {
        var i;
        var json;
        var atlas;
        var files = [];
        var cache = loader.cacheManager.custom.spine;

        //  atlas can be an array of atlas files, not just a single one

        if (IsPlainObject(key))
        {
            var config = key;

            key = GetFastValue(config, 'key');

            json = new JSONFile(loader, {
                key: key,
                url: GetFastValue(config, 'jsonURL'),
                extension: GetFastValue(config, 'jsonExtension', 'json'),
                xhrSettings: GetFastValue(config, 'jsonXhrSettings')
            });

            atlasURL = GetFastValue(config, 'atlasURL');
            preMultipliedAlpha = GetFastValue(config, 'preMultipliedAlpha');

            if (!Array.isArray(atlasURL))
            {
                atlasURL = [ atlasURL ];
            }

            for (i = 0; i < atlasURL.length; i++)
            {
                atlas = new TextFile(loader, {
                    key: key + '_' + i,
                    url: atlasURL[i],
                    extension: GetFastValue(config, 'atlasExtension', 'atlas'),
                    xhrSettings: GetFastValue(config, 'atlasXhrSettings')
                });

                atlas.cache = cache;

                files.push(atlas);
            }
        }
        else
        {
            json = new JSONFile(loader, key, jsonURL, jsonXhrSettings);

            if (!Array.isArray(atlasURL))
            {
                atlasURL = [ atlasURL ];
            }

            for (i = 0; i < atlasURL.length; i++)
            {
                atlas = new TextFile(loader, key + '_' + i, atlasURL[i], atlasXhrSettings);
                atlas.cache = cache;

                files.push(atlas);
            }
        }

        files.unshift(json);

        MultiFile.call(this, loader, 'spine', key, files);

        this.config.preMultipliedAlpha = preMultipliedAlpha;
    },

    /**
     * Called by each File when it finishes loading.
     *
     * @method Phaser.Loader.FileTypes.SpineFile#onFileComplete
     * @since 3.19.0
     *
     * @param {Phaser.Loader.File} file - The File that has completed processing.
     */
    onFileComplete: function (file)
    {
        var index = this.files.indexOf(file);

        if (index !== -1)
        {
            this.pending--;

            if (file.type === 'text')
            {
                //  Inspect the data for the files to now load
                var content = file.data.split('\n');

                //  Extract the textures
                var textures = [];

                for (var t = 0; t < content.length; t++)
                {
                    var line = content[t];

                    if (line.trim() === '' && t < content.length - 1)
                    {
                        line = content[t + 1];

                        textures.push(line);
                    }
                }

                var config = this.config;
                var loader = this.loader;

                var currentBaseURL = loader.baseURL;
                var currentPath = loader.path;
                var currentPrefix = loader.prefix;

                var baseURL = GetFastValue(config, 'baseURL', this.baseURL);
                var path = GetFastValue(config, 'path', file.src.match(/^.*\//))[0];
                var prefix = GetFastValue(config, 'prefix', this.prefix);
                var textureXhrSettings = GetFastValue(config, 'textureXhrSettings');

                loader.setBaseURL(baseURL);
                loader.setPath(path);
                loader.setPrefix(prefix);

                for (var i = 0; i < textures.length; i++)
                {
                    var textureURL = textures[i];

                    var key = this.prefix + textureURL;

                    var image = new ImageFile(loader, key, textureURL, textureXhrSettings);

                    this.addToMultiFile(image);

                    loader.addFile(image);
                }

                //  Reset the loader settings
                loader.setBaseURL(currentBaseURL);
                loader.setPath(currentPath);
                loader.setPrefix(currentPrefix);
            }
        }
    },

    /**
     * Adds this file to its target cache upon successful loading and processing.
     *
     * @method Phaser.Loader.FileTypes.SpineFile#addToCache
     * @since 3.19.0
     */
    addToCache: function ()
    {
        if (this.isReadyToProcess())
        {
            var fileJSON = this.files[0];

            fileJSON.addToCache();

            var atlasCache;
            var atlasKey = '';
            var combinedAtlasData = '';
            var preMultipliedAlpha = (this.config.preMultipliedAlpha) ? true : false;
            var textureManager = this.loader.textureManager;

            for (var i = 1; i < this.files.length; i++)
            {
                var file = this.files[i];

                if (file.type === 'text')
                {
                    atlasKey = file.key.replace(/_[\d]$/, '');

                    atlasCache = file.cache;

                    combinedAtlasData = combinedAtlasData.concat(file.data);
                }
                else
                {
                    var src = file.key.trim();
                    var pos = src.indexOf('_');
                    var key = src.substr(pos + 1);

                    if (!textureManager.exists(key))
                    {
                        textureManager.addImage(key, file.data);
                    }
                }

                file.pendingDestroy();
            }

            atlasCache.add(atlasKey, { preMultipliedAlpha: preMultipliedAlpha, data: combinedAtlasData, prefix: this.prefix });

            this.complete = true;
        }
    }

});

module.exports = SpineFile;
<|endoftext|>


<commit_before>const Database = require('../../src/dataBase.js');
const FunctionSerializer = require('../../src/functionSerializer');
const { MenuItem } = require('electron');

var fs = require('fs');
var DataFileNames = fs.readdirSync('./assets/data');
DataFileNames.forEach(fileName => {
    console.log(fileName);
    if (fileName.includes('.db')) {
        fs.unlinkSync(`./assets/data/${fileName}`);
    }
})

const db = new Database('time.manager', ['menu', 'tasks']);

var menuTemplate = [
    {
        label: 'File',
        submenu: [
            {
                label: 'Reload',
                accelerator: 'CmdOrCtrl+R',
                click(item, win) {
                    console.log(win.baseURl);
                    win.webContents.loadURL(win.baseURL);
                }
            },
            {
                role: 'close'
            },
            {
                role: 'quit'
            }
        ]
    },
    {
        label: 'Edit',
        submenu: [
            {
                role: 'undo'
            },
            {
                role: 'redo'
            }
        ]
    },
    {
        label: 'View',
        submenu: [
        ]
    }
]

function Mocks() {
    var _mocks = [];
    var _objectives =  [
        'QA New feature',
        'Build initial Spec',
        'Develop working model',
        'Implement new feature'
    ];
    var _notes = [
        'This is a note',
        'Notes are a great way to add more information to a task',
        'Some things to keep in mind...',
        `Do not for get about this!`,
        'More information is important'
    ]
    for (var i = 0;i<25;i++) {
        var task = {};
        var workNumber = rnd(0, 5);
        task.work = [];
        task.notes = [];
        for (var j = 0;j<workNumber;j++) {
            var work = {};
            var daysInPast = rnd(0, 5)
            var dt = new Date()
            dt.setDate(new Date().getDate() - daysInPast);
            work.start = dt;
            work.duration = rnd(0, 60);
            task.work.push(work);
        }
        var notes = [];
        for (var h = 0; h < rnd(0, 10); h++) {
            var noteIndex = rnd(0, _notes.length);
            var note = _notes[noteIndex];
            notes.push(`${note}`);
        }
        task.notes = notes;
        task.created = new Date();
        _mocks.push(task);
    }
    return _mocks;
}

function rnd(min, max) {
    return Math.floor(Math.random() * (max - min) + min)
}

var mocks = Mocks();

function insertDocs(docs) {
    if (docs.length < 1) return;
    var doc = docs.splice(0,1);
    db.tasks.insert(doc, (err, doc) => {
        if (err) throw err;
        insertDocs(docs);
    })
}

insertDocs(mocks)

fs.writeFileSync('testa.json', JSON.stringify(mocks));

db.menu.insert(menuTemplate, (err, doc) => {
    if (err) return console.log('Menu Seed Error: ', err);
    if (doc) //console.log('inserted menuitems', doc)
    db.tasks.insert(mocks, (err, docs) => {
        if (err) return console.log('Tasks Seed Error: ', err);
        if (docs) //console.log('inserted tasks: ', docs)
        testInsert();
    })
})

function testInsert() {
    db.menu.find({}, (err, docs) => {
        if (err) throw err;
        console.log('menu: ', docs);
        db.tasks.find({}, (err, docs) => {
            fs.writeFileSync('testb.json', JSON.stringify(docs));
            if (err) throw err;
            docs.forEach(doc => {
                for (var k in doc) {
                    //console.log(doc[k]);
                }
            })
        })
    })
}<commit_msg>remove logging<commit_after>const Database = require('../../src/dataBase.js');
const FunctionSerializer = require('../../src/functionSerializer');
const { MenuItem } = require('electron');

var fs = require('fs');
var DataFileNames = fs.readdirSync('./assets/data');
DataFileNames.forEach(fileName => {
    console.log(fileName);
    if (fileName.includes('.db')) {
        fs.unlinkSync(`./assets/data/${fileName}`);
    }
})

const db = new Database('time.manager', ['menu', 'tasks']);

var menuTemplate = [
    {
        label: 'File',
        submenu: [
            {
                label: 'Reload',
                accelerator: 'CmdOrCtrl+R',
                click(item, win) {
                    win.webContents.loadURL(win.baseURL);
                }
            },
            {
                role: 'close'
            },
            {
                role: 'quit'
            }
        ]
    },
    {
        label: 'Edit',
        submenu: [
            {
                role: 'undo'
            },
            {
                role: 'redo'
            }
        ]
    },
    {
        label: 'View',
        submenu: [
        ]
    }
]

function Mocks() {
    var _mocks = [];
    var _objectives =  [
        'QA New feature',
        'Build initial Spec',
        'Develop working model',
        'Implement new feature'
    ];
    var _notes = [
        'This is a note',
        'Notes are a great way to add more information to a task',
        'Some things to keep in mind...',
        `Do not for get about this!`,
        'More information is important'
    ]
    for (var i = 0;i<25;i++) {
        var task = {};
        var workNumber = rnd(0, 5);
        task.work = [];
        task.notes = [];
        for (var j = 0;j<workNumber;j++) {
            var work = {};
            var daysInPast = rnd(0, 5)
            var dt = new Date()
            dt.setDate(new Date().getDate() - daysInPast);
            work.start = dt;
            work.duration = rnd(0, 60);
            task.work.push(work);
        }
        var notes = [];
        for (var h = 0; h < rnd(0, 10); h++) {
            var noteIndex = rnd(0, _notes.length);
            var note = _notes[noteIndex];
            notes.push(`${note}`);
        }
        task.notes = notes;
        task.created = new Date();
        _mocks.push(task);
    }
    return _mocks;
}

function rnd(min, max) {
    return Math.floor(Math.random() * (max - min) + min)
}

var mocks = Mocks();

function insertDocs(docs) {
    if (docs.length < 1) return;
    var doc = docs.splice(0,1);
    db.tasks.insert(doc, (err, doc) => {
        if (err) throw err;
        insertDocs(docs);
    })
}

insertDocs(mocks)

fs.writeFileSync('testa.json', JSON.stringify(mocks));

db.menu.insert(menuTemplate, (err, doc) => {
    if (err) return console.log('Menu Seed Error: ', err);
    if (doc) //console.log('inserted menuitems', doc)
    db.tasks.insert(mocks, (err, docs) => {
        if (err) return console.log('Tasks Seed Error: ', err);
        if (docs) //console.log('inserted tasks: ', docs)
        testInsert();
    })
})

function testInsert() {
    db.menu.find({}, (err, docs) => {
        if (err) throw err;
        console.log('menu: ', docs);
        db.tasks.find({}, (err, docs) => {
            fs.writeFileSync('testb.json', JSON.stringify(docs));
            if (err) throw err;
            docs.forEach(doc => {
                for (var k in doc) {
                    //console.log(doc[k]);
                }
            })
        })
    })
}<|endoftext|>


<commit_before>/***** BEGIN LICENSE BLOCK ***** {{{
Version: MPL 1.1/GPL 2.0/LGPL 2.1

The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

(c) 2006-2008: Martin Stubenschrott <stubenschrott@gmx.net>

Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/

const modes = (function () //{{{
{
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////// PRIVATE SECTION /////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    var main = 1;     // NORMAL
    var extended = 0; // NONE

    var passNextKey = false;
    var passAllKeys = false;
    var isRecording = false;
    var isReplaying = false; // playing a macro

    var modeStack = [];

    function getModeMessage()
    {
        if (passNextKey && !passAllKeys)
            return "-- PASS THROUGH (next) --";
        else if (passAllKeys && !passNextKey)
            return "-- PASS THROUGH --";

        // when recording a macro
        var macromode = "";
        if (modes.isRecording)
            macromode = "recording";
        else if (modes.isReplaying)
            macromode = "replaying";

        var ext = "";
        if (extended & modes.MENU) // TODO: desirable?
            ext += " (menu)";
        ext += " --" + macromode;

        if (main in modeMap && typeof modeMap[main].display == "function")
            return "-- " + modeMap[main].display() + ext;
        return macromode;
    }

    // NOTE: Pay attention that you don't run into endless loops
    // Usually you should only indicate to leave a special mode like HINTS
    // by calling modes.reset() and adding the stuff which is needed
    // for its cleanup here
    function handleModeChange(oldMode, newMode)
    {
        // TODO: fix v.log() to work with verbosity level
        //liberator.log("switching from mode " + oldMode + " to mode " + newMode, 7);
        //liberator.dump("switching from mode " + oldMode + " to mode " + newMode + "\n");

        switch (oldMode)
        {
            case modes.TEXTAREA:
            case modes.INSERT:
                editor.unselectText();
                break;

            case modes.VISUAL:
                if (newMode == modes.CARET)
                {
                    // clear any selection made
                    var selection = window.content.getSelection();
                    try
                    { // a simple if (selection) does not work
                        selection.collapseToStart();
                    }
                    catch (e) {}
                }
                else
                    editor.unselectText();
                break;

            case modes.CUSTOM:
                plugins.stop();
                break;

            case modes.COMMAND_LINE:
                // clean up for HINT mode
                if (modes.extended & modes.HINTS)
                        hints.hide();
                commandline.close();
                break;
        }

        if (newMode == modes.NORMAL)
        {
            // disable caret mode when we want to switch to normal mode
            var value = options.getPref("accessibility.browsewithcaret", false);
            if (value)
                options.setPref("accessibility.browsewithcaret", false);

            statusline.updateUrl();
            // Kludge to prevent the input field losing focus on MS/Mac
            setTimeout(function () {
                let focus = document.commandDispatcher.focusedElement;
                if (focus != document.getElementById("urlbar").inputField)
                    liberator.focusContent(false);
            }, 100);
        }
    }

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// PUBLIC SECTION //////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    var self = {
        NONE:             0,

        __iterator__: function () util.Array.iterator(this.all),

        get all() mainModes.slice(),

        addMode: function (name, extended, display) {
            let disp = name.replace("_", " ", "g");
            this[name] = 1 << lastMode++;
            modeMap[name] = modeMap[this[name]] = {
                extended: extended,
                mask: this[name],
                name: name,
                display: display || function () disp
            };
            if (!extended)
                mainModes.push(this[name]);
        },

        // show the current mode string in the command line
        show: function ()
        {
            if (!options["showmode"])
                return;

            // never show mode messages if we are in command line mode
            if (main == modes.COMMAND_LINE)
                return;

            commandline.echo(getModeMessage(), commandline.HL_MODEMSG,
                                        commandline.DISALLOW_MULTILINE);
        },

        // add/remove always work on the extended mode only
        add: function (mode)
        {
            extended |= mode;
            this.show();
        },

        // helper function to set both modes in one go
        // if silent == true, you also need to take care of the mode handling changes yourself
        set: function (mainMode, extendedMode, silent)
        {
            // if a main mode is set, the extended is always cleared
            if (typeof mainMode === "number")
            {
                if (!silent && mainMode != main)
                    handleModeChange(main, mainMode);

                main = mainMode;
                if (!extendedMode)
                    extended = modes.NONE;
            }
            if (typeof extendedMode === "number")
                extended = extendedMode;

            if (!silent)
                this.show();
        },

        push: function (mainMode, extendedMode, silent)
        {
            modeStack.push([main, extended]);
            this.set(mainMode, extendedMode, silent);
        },

        pop: function (silent)
        {
            var a = modeStack.pop();
            if (a)
                this.set(a[0], a[1], silent);
            else
                this.reset(silent);
        },

        setCustomMode: function (modestr, oneventfunc, stopfunc)
        {
            // TODO this.plugin[id]... ('id' maybe submode or what..)
            plugins.mode = modestr;
            plugins.onEvent = oneventfunc;
            plugins.stop = stopfunc;
        },

        // keeps recording state
        reset: function (silent)
        {
            modeStack = [];
            if (config.isComposeWindow)
                this.set(modes.COMPOSE, modes.NONE, silent);
            else
                this.set(modes.NORMAL, modes.NONE, silent);
        },

        remove: function (mode)
        {
            extended &= ~mode;
            this.show();
        },

        get passNextKey() passNextKey,
        set passNextKey(value) { passNextKey = value; this.show(); },

        get passAllKeys() passAllKeys,
        set passAllKeys(value) { passAllKeys = value; this.show(); },

        get isRecording()  isRecording,
        set isRecording(value) { isRecording = value; this.show(); },

        get isReplaying() isReplaying,
        set isReplaying(value) { isReplaying = value; this.show(); },

        get main() main,
        set main(value) {
            if (value != main)
                handleModeChange(main, value);

            main = value;
            // setting the main mode always resets any extended mode
            extended = modes.NONE;
            this.show();
        },

        get extended() extended,
        set extended(value) { extended = value; this.show(); }

    };

    var mainModes = [self.NONE];
    var lastMode = 0;
    var modeMap = {};

    // main modes, only one should ever be active
    self.addMode("NORMAL", false, -1);
    self.addMode("INSERT");
    self.addMode("VISUAL", false, function () "VISUAL" + (extended & modes.LINE ? " LINE" : ""));
    self.addMode("COMMAND_LINE");
    self.addMode("CARET"); // text cursor is visible
    self.addMode("TEXTAREA"); // text cursor is in a HTMLTextAreaElement
    self.addMode("MESSAGE"); // for now only used in Muttator when the message has focus
    self.addMode("COMPOSE");
    self.addMode("CUSTOM", false, function () plugins.mode);
    // extended modes, can include multiple modes, and even main modes
    self.addMode("EX", true);
    self.addMode("HINTS", true);
    self.addMode("INPUT_MULTILINE", true);
    self.addMode("OUTPUT_MULTILINE", true);
    self.addMode("SEARCH_FORWARD", true);
    self.addMode("SEARCH_BACKWARD", true);
    self.addMode("MENU", true); // a popupmenu is active
    self.addMode("LINE", true); // linewise visual mode
    self.addMode("RECORDING", true);
    self.addMode("PROMPT", true);

    return self;
    //}}}
})(); //}}}

// vim: set fdm=marker sw=4 ts=4 et:
<commit_msg>fixed esc for muttator<commit_after>/***** BEGIN LICENSE BLOCK ***** {{{
Version: MPL 1.1/GPL 2.0/LGPL 2.1

The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.

(c) 2006-2008: Martin Stubenschrott <stubenschrott@gmx.net>

Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
}}} ***** END LICENSE BLOCK *****/

const modes = (function () //{{{
{
    ////////////////////////////////////////////////////////////////////////////////
    ////////////////////// PRIVATE SECTION /////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    var main = 1;     // NORMAL
    var extended = 0; // NONE

    var passNextKey = false;
    var passAllKeys = false;
    var isRecording = false;
    var isReplaying = false; // playing a macro

    var modeStack = [];

    function getModeMessage()
    {
        if (passNextKey && !passAllKeys)
            return "-- PASS THROUGH (next) --";
        else if (passAllKeys && !passNextKey)
            return "-- PASS THROUGH --";

        // when recording a macro
        var macromode = "";
        if (modes.isRecording)
            macromode = "recording";
        else if (modes.isReplaying)
            macromode = "replaying";

        var ext = "";
        if (extended & modes.MENU) // TODO: desirable?
            ext += " (menu)";
        ext += " --" + macromode;

        if (main in modeMap && typeof modeMap[main].display == "function")
            return "-- " + modeMap[main].display() + ext;
        return macromode;
    }

    // NOTE: Pay attention that you don't run into endless loops
    // Usually you should only indicate to leave a special mode like HINTS
    // by calling modes.reset() and adding the stuff which is needed
    // for its cleanup here
    function handleModeChange(oldMode, newMode)
    {
        // TODO: fix v.log() to work with verbosity level
        //liberator.log("switching from mode " + oldMode + " to mode " + newMode, 7);
        //liberator.dump("switching from mode " + oldMode + " to mode " + newMode + "\n");

        switch (oldMode)
        {
            case modes.TEXTAREA:
            case modes.INSERT:
                editor.unselectText();
                break;

            case modes.VISUAL:
                if (newMode == modes.CARET)
                {
                    // clear any selection made
                    var selection = window.content.getSelection();
                    try
                    { // a simple if (selection) does not work
                        selection.collapseToStart();
                    }
                    catch (e) {}
                }
                else
                    editor.unselectText();
                break;

            case modes.CUSTOM:
                plugins.stop();
                break;

            case modes.COMMAND_LINE:
                // clean up for HINT mode
                if (modes.extended & modes.HINTS)
                        hints.hide();
                commandline.close();
                break;
        }

        if (newMode == modes.NORMAL)
        {
            // disable caret mode when we want to switch to normal mode
            var value = options.getPref("accessibility.browsewithcaret", false);
            if (value)
                options.setPref("accessibility.browsewithcaret", false);

            statusline.updateUrl();
            // Kludge to prevent the input field losing focus on MS/Mac
            setTimeout(function () {
                let focus = document.commandDispatcher.focusedElement;
                let urlbar = document.getElementById("urlbar");
                if (!urlbar || focus != urlbar.inputField)
                    liberator.focusContent(false);
            }, 100);
        }
    }

    /////////////////////////////////////////////////////////////////////////////}}}
    ////////////////////// PUBLIC SECTION //////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////{{{

    var self = {
        NONE:             0,

        __iterator__: function () util.Array.iterator(this.all),

        get all() mainModes.slice(),

        addMode: function (name, extended, display) {
            let disp = name.replace("_", " ", "g");
            this[name] = 1 << lastMode++;
            modeMap[name] = modeMap[this[name]] = {
                extended: extended,
                mask: this[name],
                name: name,
                display: display || function () disp
            };
            if (!extended)
                mainModes.push(this[name]);
        },

        // show the current mode string in the command line
        show: function ()
        {
            if (!options["showmode"])
                return;

            // never show mode messages if we are in command line mode
            if (main == modes.COMMAND_LINE)
                return;

            commandline.echo(getModeMessage(), commandline.HL_MODEMSG,
                                        commandline.DISALLOW_MULTILINE);
        },

        // add/remove always work on the extended mode only
        add: function (mode)
        {
            extended |= mode;
            this.show();
        },

        // helper function to set both modes in one go
        // if silent == true, you also need to take care of the mode handling changes yourself
        set: function (mainMode, extendedMode, silent)
        {
            // if a main mode is set, the extended is always cleared
            if (typeof mainMode === "number")
            {
                if (!silent && mainMode != main)
                    handleModeChange(main, mainMode);

                main = mainMode;
                if (!extendedMode)
                    extended = modes.NONE;
            }
            if (typeof extendedMode === "number")
                extended = extendedMode;

            if (!silent)
                this.show();
        },

        push: function (mainMode, extendedMode, silent)
        {
            modeStack.push([main, extended]);
            this.set(mainMode, extendedMode, silent);
        },

        pop: function (silent)
        {
            var a = modeStack.pop();
            if (a)
                this.set(a[0], a[1], silent);
            else
                this.reset(silent);
        },

        setCustomMode: function (modestr, oneventfunc, stopfunc)
        {
            // TODO this.plugin[id]... ('id' maybe submode or what..)
            plugins.mode = modestr;
            plugins.onEvent = oneventfunc;
            plugins.stop = stopfunc;
        },

        // keeps recording state
        reset: function (silent)
        {
            modeStack = [];
            if (config.isComposeWindow)
                this.set(modes.COMPOSE, modes.NONE, silent);
            else
                this.set(modes.NORMAL, modes.NONE, silent);
        },

        remove: function (mode)
        {
            extended &= ~mode;
            this.show();
        },

        get passNextKey() passNextKey,
        set passNextKey(value) { passNextKey = value; this.show(); },

        get passAllKeys() passAllKeys,
        set passAllKeys(value) { passAllKeys = value; this.show(); },

        get isRecording()  isRecording,
        set isRecording(value) { isRecording = value; this.show(); },

        get isReplaying() isReplaying,
        set isReplaying(value) { isReplaying = value; this.show(); },

        get main() main,
        set main(value) {
            if (value != main)
                handleModeChange(main, value);

            main = value;
            // setting the main mode always resets any extended mode
            extended = modes.NONE;
            this.show();
        },

        get extended() extended,
        set extended(value) { extended = value; this.show(); }

    };

    var mainModes = [self.NONE];
    var lastMode = 0;
    var modeMap = {};

    // main modes, only one should ever be active
    self.addMode("NORMAL", false, -1);
    self.addMode("INSERT");
    self.addMode("VISUAL", false, function () "VISUAL" + (extended & modes.LINE ? " LINE" : ""));
    self.addMode("COMMAND_LINE");
    self.addMode("CARET"); // text cursor is visible
    self.addMode("TEXTAREA"); // text cursor is in a HTMLTextAreaElement
    self.addMode("MESSAGE"); // for now only used in Muttator when the message has focus
    self.addMode("COMPOSE");
    self.addMode("CUSTOM", false, function () plugins.mode);
    // extended modes, can include multiple modes, and even main modes
    self.addMode("EX", true);
    self.addMode("HINTS", true);
    self.addMode("INPUT_MULTILINE", true);
    self.addMode("OUTPUT_MULTILINE", true);
    self.addMode("SEARCH_FORWARD", true);
    self.addMode("SEARCH_BACKWARD", true);
    self.addMode("MENU", true); // a popupmenu is active
    self.addMode("LINE", true); // linewise visual mode
    self.addMode("RECORDING", true);
    self.addMode("PROMPT", true);

    return self;
    //}}}
})(); //}}}

// vim: set fdm=marker sw=4 ts=4 et:
<|endoftext|>


<commit_before>var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
var Buffer = require('buffer').Buffer;
var _ = require('lodash');
var async = require('../..').async;
var await = require('../..').await;

/**
  * Finds the largest file in the given directory, optionally performing a recursive search.
  * @param {string} dir - the directory to search.
  * @param {object?} options - optional settings: { recurse?: boolean; preview?: boolean }.
  * @returns {object?} null if no files found, otherwise an object of the form
  *                    { path: string; size: number; preview?: string, searched: number; }.
  */
var largest = async.cps (function self(dir, options, internal) {

    // Parse arguments.
    options = options || largest.options;

    // Enumerate all files and subfolders in 'dir' to get their stats.
    var files = await.in (fs.readdirAsync(dir));
    var paths = _.map(files, function (file) { return path.join(dir, file); });
    var stats = await.in (_.map(paths, function (path) { return fs.statAsync(path); }));

    // Build up a list of possible candidates, recursing into subfolders if requested.
    var candidates = await (_.map(stats, function (stat, i) {
        if (stat.isFile()) return { path: paths[i], size: stat.size, searched: 1 };
        return options.recurse ? self(paths[i], options, true) : null;
    }));

    // Choose the best candidate.
    var result = _(candidates)
        .compact()
        .reduce(function (best, cand) {
            if (cand.size > best.size) var temp = cand, cand = best, best = temp;
            best.searched += cand.searched;
            return best;
        });

    // Add a preview if requested (but skip if this is an internal step in a recursive search).
    if (result && options.preview && !internal) {
        var fd = await (fs.openAsync(result.path, 'r'));
        var buffer = new Buffer(40);
        var bytesRead = await (fs.readAsync(fd, buffer, 0, 40, 0));
        result.preview = buffer.toString('utf-8', 0, bytesRead);
        await (fs.closeSync(fd));
    }
    return result;
});
largest.options = {};

module.exports = largest;
<commit_msg>Update largest-asyncawait.js<commit_after>var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var path = require('path');
var Buffer = require('buffer').Buffer;
var _ = require('lodash');
var async = require('../..').async;
var await = require('../..').await;

/**
  * Finds the largest file in the given directory, optionally performing a recursive search.
  * @param {string} dir - the directory to search.
  * @param {object?} options - optional settings: { recurse?: boolean; preview?: boolean }.
  * @returns {object?} null if no files found, otherwise an object of the form
  *                    { path: string; size: number; preview?: string, searched: number; }.
  */
var largest = async.cps (function self(dir, options, internal) {

    // Parse arguments.
    options = options || largest.options;

    // Enumerate all files and subfolders in 'dir' to get their stats.
    var files = await (fs.readdirAsync(dir));
    var paths = _.map(files, function (file) { return path.join(dir, file); });
    var stats = await (_.map(paths, function (path) { return fs.statAsync(path); }));

    // Build up a list of possible candidates, recursing into subfolders if requested.
    var candidates = await (_.map(stats, function (stat, i) {
        if (stat.isFile()) return { path: paths[i], size: stat.size, searched: 1 };
        return options.recurse ? self(paths[i], options, true) : null;
    }));

    // Choose the best candidate.
    var result = _(candidates)
        .compact()
        .reduce(function (best, cand) {
            if (cand.size > best.size) var temp = cand, cand = best, best = temp;
            best.searched += cand.searched;
            return best;
        });

    // Add a preview if requested (but skip if this is an internal step in a recursive search).
    if (result && options.preview && !internal) {
        var fd = await (fs.openAsync(result.path, 'r'));
        var buffer = new Buffer(40);
        var bytesRead = await (fs.readAsync(fd, buffer, 0, 40, 0));
        result.preview = buffer.toString('utf-8', 0, bytesRead);
        await (fs.closeSync(fd));
    }
    return result;
});
largest.options = {};

module.exports = largest;
<|endoftext|>


<commit_before>
function raportti_alustus(e) {
	raportointi=0;
	if (e=="nappulasta") { raportointi=1;  }
	if (e.keyCode == '13' ) { raportointi=1;  }

	if (raportointi==1) {

	var muuttuja=0;
	var sijainti=0;
	var kuntakoodi=document.getElementById("kuntakysely").value;
	if (kuntakoodi.length==3) {	sijainti=metatiedot.variables[muuttuja].values.indexOf(kuntakoodi); }
	if (kuntakoodi.length>3) {	sijainti=kuntanimikkeet.indexOf(kuntakoodi);		kuntakoodi=metatiedot.variables[muuttuja].values[sijainti];		 }
	kuntanimi=metatiedot.variables[muuttuja].valueTexts[sijainti];
	document.getElementById("otsikko").innerHTML=kuntanimi;
	document.getElementById("taulukoitavakuntakoodi").innerHTML=kuntakoodi;

	haetaulukko();

	}

}

function raportti() {

	vakiluku=haeluku('SS;SSS;');
	tyollisiaTyoikaisia=haeluku('11;18-64;');
	tyottomiaTyoikaisia=haeluku('12;18-64;');
	tyollisia=haeluku('11;SSS;');
	tyottomia=haeluku('12;SSS;');
	tyoikaisia=haeluku('SS;18-64;');
	alaikaisia=haeluku('SS;0-17;');
	elakeikaisia=haeluku('SS;65+;');

	var ekavuosi = parseInt(document.getElementById("vuosi_min").value);
	var vikavuosi = parseInt(document.getElementById("vuosi_max").value);

	vuodet = new Array();
	tal_huoltosuhde = new Array();
	vae_huoltosuhde = new Array();

	var vuosi = ekavuosi;
	var erotus = vikavuosi-ekavuosi;
	for (i=0;i<=erotus;i++) { 	vuodet[i]=vuosi;	vuosi=vuosi+1;

	tal_huoltosuhde[i]=(vakiluku[i]-tyollisia[i])/tyollisia[i]*100;

	vae_huoltosuhde[i]=(vakiluku[i]-tyoikaisia[i])/tyoikaisia[i]*100;

	}

	document.getElementById("kpl_1").innerHTML="Vuonna "+vikavuosi+" kunnassa oli "+vakiluku[vuodet.length-1]+" henkilöä, joista "+alaikaisia[vuodet.length-1]+" oli alaikäisiä";

	var vaestokuvaData = new Array();
	vaestokuvaData[0] = vuodet;
	vaestokuvaData[1] = tyoikaisia;
	vaestokuvaData[2] = elakeikaisia;
	vaestokuvaData[3] = alaikaisia;

	var tyollisyyskuvaData = new Array();
	tyollisyyskuvaData[0] = vuodet;
	tyollisyyskuvaData[1] = tyollisiaTyoikaisia;
	tyollisyyskuvaData[2] = tyottomiaTyoikaisia;

	var huoltosuhdeData = new Array();
	huoltosuhdeData[0] = vuodet;
	huoltosuhdeData[1] = vae_huoltosuhde;
	huoltosuhdeData[2] = tal_huoltosuhde;

	if (document.getElementById("vaestotietokuva_tyyppi_P").checked ) { tyyppi="P"; }
	if (document.getElementById("vaestotietokuva_tyyppi_N").checked ) { tyyppi="N"; }
	if (document.getElementById("vaestotietokuva_tyyppi_NP").checked ) { tyyppi="NP"; }
	if (document.getElementById("vaestotietokuva_tyyppi_0").checked ) { tyyppi="0"; }

	piirra(vaestokuvaData,['Vuosi','Työikäisiä','Eläkeikäisiä','Alaikäisiä'],"Väestönkehitys",'vaestotietokuva',tyyppi);

	if (document.getElementById("tyollisyyskuva_tyyppi_P").checked ) { tyyppi="P"; }
	if (document.getElementById("tyollisyyskuva_tyyppi_N").checked ) { tyyppi="N"; }
	//if (document.getElementById("tyollisyyskuva_tyyppi_NP").checked ) { tyyppi="NP"; }
	if (document.getElementById("tyollisyyskuva_tyyppi_0").checked ) { tyyppi="0"; }

	piirra(tyollisyyskuvaData,['Vuosi','Työllisiä (18-64)',"Työttömiä (18-64)"],"Työllisyyden kehitys",'tyollisyyskuva',tyyppi);

	if (document.getElementById("huoltosuhdekuva_tyyppi_N").checked ) { tyyppi="N"; }
	if (document.getElementById("huoltosuhdekuva_tyyppi_0").checked ) { tyyppi="0"; }

   piirra(huoltosuhdeData,['Vuosi','Väestöllinen huoltosuhde','Taloudellinen huoltosuhde'],"Huoltosuhteiden kehitys",'huoltosuhdekuva',tyyppi);

	/*
	// Onko koko maan tt-aste suurempi vai pienempi
	tt_vertailu="yhtä suuri";
	if (Math.round(luvut_3[8]/(parseInt(luvut_3[4])+parseInt(luvut_3[8]))*100)>Math.round(luvut_1[8]/(parseInt(luvut_1[4])+parseInt(luvut_1[8]))*100)) { tt_vertailu="suurempi"	}
	if (Math.round(luvut_3[8]/(parseInt(luvut_3[4])+parseInt(luvut_3[8]))*100)<Math.round(luvut_1[8]/(parseInt(luvut_1[4])+parseInt(luvut_1[8]))*100)) { tt_vertailu="pienempi"	}

	// Onko väestö kasvanut vai vähentynyt ko. ajanjaksolla

	aikavertailu_vakiluku="kasvanut";
	if ((luvut_2[1]-luvut_2[0])<0) { aikavertailu_vakiluku="vähentynyt"; }
	*/

	/*" henkilöä, joista "+luvut_1[1]+" ("+Math.round(luvut_1[1]/luvut_1[0]*100)+" %) oli alaikäisiä. Työikäisiä eli 18-64 -vuotiaita oli "+Math.round(luvut_1[2]/luvut_1[0]*100)+" prosenttia väestöstä ja eläikään	ehtineitä "
		+ Math.round(luvut_1[3]/luvut_1[0]*100) +" prosenttia.";
	document.getElementById("kpl_2").innerHTML="Kunnan työllisyysaste oli "+Math.round(luvut_1[6]/luvut_1[2]*100)+" % ja työttömyysaste "	+Math.round(luvut_1[8]/(parseInt(luvut_1[4])+parseInt(luvut_1[8]))*100)+"%. Koko maan työttömyysaste oli "+tt_vertailu+":"+Math.round(luvut_3[8]/(parseInt(luvut_3[4])+parseInt(luvut_3[8]))*100)+"%";
	document.getElementById("kpl_3").innerHTML="Vuonna "+ekavuosi+" kunnassa oli "+luvut_2[0]+" henkilöä. Ajanjaksolla "+ekavuosi+"-"+vikavuosi+" kunnan väestö on siis "+aikavertailu_vakiluku+" "+(luvut_2[1]-luvut_2[0])+" ("+(Math.round(luvut_2[1]/luvut_2[0]*100)-100)+"%) henkilöllä";
	*/

}
<commit_msg>Update raportti.js<commit_after>
function raportti_alustus(e) {
	raportointi=0;
	if (e=="nappulasta") { raportointi=1;  }
	if (e.keyCode == '13' ) { raportointi=1;  }

	if (raportointi==1) {

	var muuttuja=0;
	var sijainti=0;
	var kuntakoodi=document.getElementById("kuntakysely").value;
	if (kuntakoodi.length==3) {	sijainti=metatiedot.variables[muuttuja].values.indexOf(kuntakoodi); }
	if (kuntakoodi.length>3) {	sijainti=kuntanimikkeet.indexOf(kuntakoodi);		kuntakoodi=metatiedot.variables[muuttuja].values[sijainti];		 }
	kuntanimi=metatiedot.variables[muuttuja].valueTexts[sijainti];
	document.getElementById("otsikko").innerHTML=kuntanimi;
	document.getElementById("taulukoitavakuntakoodi").innerHTML=kuntakoodi;

	haetaulukko(0);

	}

}

function raportti() {

	vakiluku=haeluku('SS;SSS;');
	tyollisiaTyoikaisia=haeluku('11;18-64;');
	tyottomiaTyoikaisia=haeluku('12;18-64;');
	tyollisia=haeluku('11;SSS;');
	tyottomia=haeluku('12;SSS;');
	tyoikaisia=haeluku('SS;18-64;');
	alaikaisia=haeluku('SS;0-17;');
	elakeikaisia=haeluku('SS;65+;');

	var ekavuosi = parseInt(document.getElementById("vuosi_min").value);
	var vikavuosi = parseInt(document.getElementById("vuosi_max").value);

	vuodet = new Array();
	tal_huoltosuhde = new Array();
	vae_huoltosuhde = new Array();

	var vuosi = ekavuosi;
	var erotus = vikavuosi-ekavuosi;
	for (i=0;i<=erotus;i++) { 	vuodet[i]=vuosi;	vuosi=vuosi+1;

	tal_huoltosuhde[i]=(vakiluku[i]-tyollisia[i])/tyollisia[i]*100;

	vae_huoltosuhde[i]=(vakiluku[i]-tyoikaisia[i])/tyoikaisia[i]*100;

	}

	document.getElementById("kpl_1").innerHTML="Vuonna "+vikavuosi+" kunnassa oli "+vakiluku[vuodet.length-1]+" henkilöä, joista "+alaikaisia[vuodet.length-1]+" oli alaikäisiä";

	var vaestokuvaData = new Array();
	vaestokuvaData[0] = vuodet;
	vaestokuvaData[1] = tyoikaisia;
	vaestokuvaData[2] = elakeikaisia;
	vaestokuvaData[3] = alaikaisia;

	var tyollisyyskuvaData = new Array();
	tyollisyyskuvaData[0] = vuodet;
	tyollisyyskuvaData[1] = tyollisiaTyoikaisia;
	tyollisyyskuvaData[2] = tyottomiaTyoikaisia;

	var huoltosuhdeData = new Array();
	huoltosuhdeData[0] = vuodet;
	huoltosuhdeData[1] = vae_huoltosuhde;
	huoltosuhdeData[2] = tal_huoltosuhde;

	if (document.getElementById("vaestotietokuva_tyyppi_P").checked ) { tyyppi="P"; }
	if (document.getElementById("vaestotietokuva_tyyppi_N").checked ) { tyyppi="N"; }
	if (document.getElementById("vaestotietokuva_tyyppi_NP").checked ) { tyyppi="NP"; }
	if (document.getElementById("vaestotietokuva_tyyppi_0").checked ) { tyyppi="0"; }

	piirra(vaestokuvaData,['Vuosi','Työikäisiä','Eläkeikäisiä','Alaikäisiä'],"Väestönkehitys",'vaestotietokuva',tyyppi);

	if (document.getElementById("tyollisyyskuva_tyyppi_P").checked ) { tyyppi="P"; }
	if (document.getElementById("tyollisyyskuva_tyyppi_N").checked ) { tyyppi="N"; }
	//if (document.getElementById("tyollisyyskuva_tyyppi_NP").checked ) { tyyppi="NP"; }
	if (document.getElementById("tyollisyyskuva_tyyppi_0").checked ) { tyyppi="0"; }

	piirra(tyollisyyskuvaData,['Vuosi','Työllisiä (18-64)',"Työttömiä (18-64)"],"Työllisyyden kehitys",'tyollisyyskuva',tyyppi);

	if (document.getElementById("huoltosuhdekuva_tyyppi_N").checked ) { tyyppi="N"; }
	if (document.getElementById("huoltosuhdekuva_tyyppi_0").checked ) { tyyppi="0"; }

   piirra(huoltosuhdeData,['Vuosi','Väestöllinen huoltosuhde','Taloudellinen huoltosuhde'],"Huoltosuhteiden kehitys",'huoltosuhdekuva',tyyppi);

	/*
	// Onko koko maan tt-aste suurempi vai pienempi
	tt_vertailu="yhtä suuri";
	if (Math.round(luvut_3[8]/(parseInt(luvut_3[4])+parseInt(luvut_3[8]))*100)>Math.round(luvut_1[8]/(parseInt(luvut_1[4])+parseInt(luvut_1[8]))*100)) { tt_vertailu="suurempi"	}
	if (Math.round(luvut_3[8]/(parseInt(luvut_3[4])+parseInt(luvut_3[8]))*100)<Math.round(luvut_1[8]/(parseInt(luvut_1[4])+parseInt(luvut_1[8]))*100)) { tt_vertailu="pienempi"	}

	// Onko väestö kasvanut vai vähentynyt ko. ajanjaksolla

	aikavertailu_vakiluku="kasvanut";
	if ((luvut_2[1]-luvut_2[0])<0) { aikavertailu_vakiluku="vähentynyt"; }
	*/

	/*" henkilöä, joista "+luvut_1[1]+" ("+Math.round(luvut_1[1]/luvut_1[0]*100)+" %) oli alaikäisiä. Työikäisiä eli 18-64 -vuotiaita oli "+Math.round(luvut_1[2]/luvut_1[0]*100)+" prosenttia väestöstä ja eläikään	ehtineitä "
		+ Math.round(luvut_1[3]/luvut_1[0]*100) +" prosenttia.";
	document.getElementById("kpl_2").innerHTML="Kunnan työllisyysaste oli "+Math.round(luvut_1[6]/luvut_1[2]*100)+" % ja työttömyysaste "	+Math.round(luvut_1[8]/(parseInt(luvut_1[4])+parseInt(luvut_1[8]))*100)+"%. Koko maan työttömyysaste oli "+tt_vertailu+":"+Math.round(luvut_3[8]/(parseInt(luvut_3[4])+parseInt(luvut_3[8]))*100)+"%";
	document.getElementById("kpl_3").innerHTML="Vuonna "+ekavuosi+" kunnassa oli "+luvut_2[0]+" henkilöä. Ajanjaksolla "+ekavuosi+"-"+vikavuosi+" kunnan väestö on siis "+aikavertailu_vakiluku+" "+(luvut_2[1]-luvut_2[0])+" ("+(Math.round(luvut_2[1]/luvut_2[0]*100)-100)+"%) henkilöllä";
	*/

}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Text } from 'react-native';

import styles from '../../styles/styles.ios';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';

const IMAGES = [
  require('../../images/animals/myvalSeverni/01.jpg'),
  require('../../images/animals/myvalSeverni/02.jpg'),
  require('../../images/animals/myvalSeverni/03.jpg'),
];

const THUMBNAILS = [
  require('../../images/animals/myvalSeverni/01-thumb.jpg'),
  require('../../images/animals/myvalSeverni/02-thumb.jpg'),
  require('../../images/animals/myvalSeverni/03-thumb.jpg'),
];

var AnimalDetail = React.createClass({
  render() {
    return (
      <AnimalTemplate firstIndex={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
          <AnimalText>
            <Text style={styles.strong}> Milí člověčí kamarádi, těší nás, že jste zavítali k našemu výběhu! Jsme mývali severní a rádi bychom vám povykládali krátký mývalí příběh. </Text>
          </AnimalText>
          <AnimalText>
            Za devatero horami, devatero řekami a jedním Atlantským oceánem, na světadílu zvaném Amerika, bydlela taková malá roztomilá šelma. Srst měla šedou a její huňatý ocas zdobily tmavé kroužky. Vzrůstem tato šelma jen trochu převyšovala domácí kočky, zato čenich se jí protáhl tak, že dokázala vyčmuchat kdejakého špindíru. Snad proto žila u vody a pečlivě umývala nejen sebe, ale i všechno, co chtěla sežrat. Nikdo jí neřekl jinak než princezna Mývalka.
          </AnimalText>
          <AnimalText>
            Princeznu neohrožoval žádný drak ani čert. A k tomu neuměla kouzlit. Až jednou, když si tak umývala žábu k obědu, připlaval k ní z protějšího břehu princ Mýval. Byl stejně čistotný jako ona, a tak se skamarádili. Měli spolu spoustu dětí a nadále vedli svůj nezajímavý život, pustý draků, čertů a kouzel. Inu, i takhle nudné mohou princezny být.
          </AnimalText>
          <AnimalText>
          Mezitím se rod mývalů rozrůstal a rozšířil se do mnoha koutů světa. Dnes je naleznete dokonce i v Česku, avšak musíte si uvědomit, že ne všichni jsou svatoušci…
          </AnimalText>
          <InPageImage indexes={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
          <AnimalText>
          Když na les padne tma, vydávají se na lov mývalí loupežníci. Oči skrývají pod černými škraboškami – to aby nebylo vidět, jak moc se jim oči hladem blyští. Mývali sice neumějí moc rychle běhat, ale hbitě šplhají po stromech a přepadávají ptačí hnízda. Milují vajíčka. Ptáčkům vždy pohrozí svými nezatažitelnými drápy, šikovnými prstíky zašmátrají v hnízdě a kořist je jejich. Když si vajíčko ochutí oříšky nebo si k němu přikousnou kousek hmyzu, jsou na vrcholu blaha.
          </AnimalText>
          <AnimalText>
          Ale znáte to, někdy se ani člověku nechce nic dělat, natož aby se vyčerpával lovem. Mývalí loupežnická banda si to moc dobře uvědomuje. Její členové jsou vysoce inteligentní, a tak si našli snadnější kořist – popelnice. Dají se z nich vyhrabat všelijaké delikatesy, zbytky ovoce počínaje, kousky šťavnatého masa konče. Bohužel ale mývali nemají takový smysl pro čistotu, jaký kdysi mívali. Kolem popelnic dělají nepořádek, navíc z kožichu vytřepávají všemožné kousavé breberky.
          </AnimalText>
          <AnimalText>
          To se lidem vůbec nelíbí. Rozhodli se, že pošlou na loupežnické mývaly myslivce, aby jim ukázali, zač je toho loket.
          </AnimalText>
          <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
          <AnimalText>
          Některých hodných mývalů se ale lidem zželelo a začali je chovat v zajetí. Tihle mývali už nemusejí krást. Dostávají žrádlo skoro do postele. Už si zase můžou připadat jako princezny a princové.
          </AnimalText>
          <AnimalText>
          <Text style={styles.strong}> Ani my, mývali v brněnské zoo, si nestěžujeme. Máme útulný výběh s místy, kde si můžeme hrát na schovávanou, a pan chovatel nám připravuje spousty dobrot. </Text>
          </AnimalText>
      </AnimalTemplate>
    );
  }
});

module.exports = AnimalDetail;
<commit_msg>Update myvalSeverni.child.js<commit_after>import React, { Component } from 'react';
import { Text } from 'react-native';

import styles from '../../styles/styles.ios';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';

const IMAGES = [
  require('../../images/animals/myvalSeverni/01.jpg'),
  require('../../images/animals/myvalSeverni/02.jpg'),
  require('../../images/animals/myvalSeverni/03.jpg'),
];

const THUMBNAILS = [
  require('../../images/animals/myvalSeverni/01-thumb.jpg'),
  require('../../images/animals/myvalSeverni/02-thumb.jpg'),
  require('../../images/animals/myvalSeverni/03-thumb.jpg'),
];

var AnimalDetail = React.createClass({
  render() {
    return (
      <AnimalTemplate firstIndex={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
          <AnimalText>
            <Text style={styles.strong}> Milí člověčí kamarádi, těší nás, že jste zavítali k našemu výběhu! Jsme mývali severní a rádi bychom vám povykládali krátký mývalí příběh. </Text>
          </AnimalText>
          <AnimalText>
            Za devatero horami, devatero řekami a jedním Atlantským oceánem, na světadílu zvaném Amerika, bydlela taková malá roztomilá šelma. Srst měla šedou a její huňatý ocas zdobily tmavé kroužky. Vzrůstem tato šelma jen trochu převyšovala domácí kočky, zato čenich se jí protáhl tak, že dokázala vyčmuchat kdejakého špindíru. Snad proto žila u vody a pečlivě umývala nejen sebe, ale i všechno, co chtěla sežrat. Nikdo jí neřekl jinak než princezna Mývalka.
          </AnimalText>
          <AnimalText>
            Princeznu neohrožoval žádný drak ani čert. A k tomu neuměla kouzlit. Až jednou, když si tak umývala žábu k obědu, připlaval k ní z protějšího břehu princ Mýval. Byl stejně čistotný jako ona, a tak se skamarádili. Měli spolu spoustu dětí a nadále vedli svůj nezajímavý život, pustý draků, čertů a kouzel. Inu, i takhle nudné mohou princezny být.
          </AnimalText>
          <AnimalText>
            Mezitím se rod mývalů rozrůstal a rozšířil se do mnoha koutů světa. Dnes je naleznete dokonce i v Česku, avšak musíte si uvědomit, že ne všichni jsou svatoušci…
          </AnimalText>
        <InPageImage indexes={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
          <AnimalText>
            Když na les padne tma, vydávají se na lov mývalí loupežníci. Oči skrývají pod černými škraboškami – to aby nebylo vidět, jak moc se jim oči hladem blyští. Mývali sice neumějí moc rychle běhat, ale hbitě šplhají po stromech a přepadávají ptačí hnízda. Milují vajíčka. Ptáčkům vždy pohrozí svými nezatažitelnými drápy, šikovnými prstíky zašmátrají v hnízdě a kořist je jejich. Když si vajíčko ochutí oříšky nebo si k němu přikousnou kousek hmyzu, jsou na vrcholu blaha.
          </AnimalText>
          <AnimalText>
            Ale znáte to, někdy se ani člověku nechce nic dělat, natož aby se vyčerpával lovem. Mývalí loupežnická banda si to moc dobře uvědomuje. Její členové jsou vysoce inteligentní, a tak si našli snadnější kořist – popelnice. Dají se z nich vyhrabat všelijaké delikatesy, zbytky ovoce počínaje, kousky šťavnatého masa konče. Bohužel ale mývali nemají takový smysl pro čistotu, jaký kdysi mívali. Kolem popelnic dělají nepořádek, navíc z kožichu vytřepávají všemožné kousavé breberky.
          </AnimalText>
          <AnimalText>
          To se lidem vůbec nelíbí. Rozhodli se, že pošlou na loupežnické mývaly myslivce, aby jim ukázali, zač je toho loket.
          </AnimalText>
        <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
          <AnimalText>
            Některých hodných mývalů se ale lidem zželelo a začali je chovat v zajetí. Tihle mývali už nemusejí krást. Dostávají žrádlo skoro do postele. Už si zase můžou připadat jako princezny a princové.
          </AnimalText>
          <AnimalText>
          <Text style={styles.strong}> Ani my, mývali v brněnské zoo, si nestěžujeme. Máme útulný výběh s místy, kde si můžeme hrát na schovávanou, a pan chovatel nám připravuje spousty dobrot. </Text>
          </AnimalText>
      </AnimalTemplate>
    );
  }
});

module.exports = AnimalDetail;
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box, { omitBoxProps, pickBoxProps } from '../box';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import Icon from '../icon';
import NavigationBar from './NavigationBar';
import WeekDay from './WeekDay';
import { convertModifiersToClassnames } from './utils';
import { IconCalendarSmallOutline, IconWarningBadgedSmallFilled } from '@teamleader/ui-icons';
import { TextSmall } from '../typography';
import cx from 'classnames';
import omit from 'lodash.omit';
import theme from './theme.css';

class DatePickerInput extends PureComponent {
  state = {
    inputHasFocus: false,
    selectedDate: null,
  };

  static getDerivedStateFromProps(props, state) {
    if (props.selectedDate !== undefined && props.selectedDate !== state.selectedDate) {
      return {
        selectedDate: props.selectedDate,
      };
    }

    return null;
  }

  handleBlur = () => {
    this.setState({ inputHasFocus: false }, () => this.props.onBlur && this.props.onBlur());
  };

  handleFocus = () => {
    this.setState({ inputHasFocus: true }, () => this.props.onFocus && this.props.onFocus());
  };

  handleInputDateChange = date => {
    this.setState(
      {
        selectedDate: date,
      },
      () => this.props.onChange(date),
    );
  };

  renderDayPickerInput = () => {
    const { className, dayPickerProps, disabled, modifiers, readOnly, size, ...others } = this.props;
    const { selectedDate } = this.state;

    const dayPickerClassNames = cx(theme['date-picker'], theme[`is-${size}`], className);

    const propsWithoutBoxProps = omitBoxProps(others);
    const restProps = omit(propsWithoutBoxProps, ['helpText', 'onBlur', 'onChange', 'onFocus']);

    return (
      <DayPickerInput
        classNames={theme}
        dayPickerProps={{
          className: dayPickerClassNames,
          classNames: theme,
          modifiers: convertModifiersToClassnames(modifiers, theme),
          onDayClick: this.handleInputDateChange,
          selectedDays: selectedDate,
          navbarElement: <NavigationBar size={size} />,
          weekdayElement: <WeekDay size={size} />,
          ...dayPickerProps,
        }}
        onDayChange={this.handleInputDateChange}
        hideOnDayClick={false}
        inputProps={{
          disabled: disabled || readOnly,
          onBlur: this.handleBlur,
          onFocus: this.handleFocus,
        }}
        {...restProps}
      />
    );
  };

  renderIcon = () => {
    const { inverse } = this.props;

    return (
      <Icon
        className={theme['input-icon']}
        color={inverse ? 'teal' : 'neutral'}
        tint={inverse ? 'light' : 'darkest'}
        marginHorizontal={2}
      >
        <IconCalendarSmallOutline />
      </Icon>
    );
  };

  renderHelpText = () => {
    const { helpText, inverse } = this.props;

    if (helpText) {
      return (
        <TextSmall color={inverse ? 'white' : 'neutral'} marginTop={1} soft>
          {helpText}
        </TextSmall>
      );
    }
  };

  renderValidationMessage = () => {
    return (
      <Box marginTop={2}>
        <IconWarningBadgedSmallFilled className={theme['validation-icon']} />
        <TextSmall className={theme['validation-text']} element="span" marginLeft={1}>
          {this.props.error}
        </TextSmall>
      </Box>
    );
  };

  render() {
    const { bold, disabled, error, inverse, readOnly, size, ...others } = this.props;
    const { inputHasFocus } = this.state;

    const boxProps = pickBoxProps(others);

    const classNames = cx(theme['date-picker-input'], theme[`is-${size}`], {
      [theme['is-bold']]: bold,
      [theme['is-disabled']]: disabled,
      [theme['is-inverse']]: inverse,
      [theme['is-read-only']]: readOnly,
      [theme['has-error']]: error,
      [theme['has-focus']]: inputHasFocus,
    });

    return (
      <Box className={classNames} {...boxProps}>

          {this.renderIcon()}
          {this.renderDayPickerInput()}

        {error ? this.renderValidationMessage() : this.renderHelpText()}
      </Box>
    );
  }
}

DatePickerInput.propTypes = {
  bold: PropTypes.bool,
  className: PropTypes.string,
  dayPickerProps: PropTypes.object,
  disabled: PropTypes.bool,
  /** The text string/element to use as error message below the input. */
  error: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
  helpText: PropTypes.string,
  inverse: PropTypes.bool,
  modifiers: PropTypes.object,
  onBlur: PropTypes.func,
  onChange: PropTypes.func,
  onFocus: PropTypes.func,
  readOnly: PropTypes.bool,
  selectedDate: PropTypes.instanceOf(Date),
  size: PropTypes.oneOf(['small', 'medium', 'large']),
};

DatePickerInput.defaultProps = {
  bold: false,
  disabled: false,
  inverse: false,
  readOnly: false,
  size: 'medium',
};

export default DatePickerInput;
<commit_msg>DatePickerInput: reduce handler code to one line to be consistent with the other handlers<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import Box, { omitBoxProps, pickBoxProps } from '../box';
import DayPickerInput from 'react-day-picker/DayPickerInput';
import Icon from '../icon';
import NavigationBar from './NavigationBar';
import WeekDay from './WeekDay';
import { convertModifiersToClassnames } from './utils';
import { IconCalendarSmallOutline, IconWarningBadgedSmallFilled } from '@teamleader/ui-icons';
import { TextSmall } from '../typography';
import cx from 'classnames';
import omit from 'lodash.omit';
import theme from './theme.css';

class DatePickerInput extends PureComponent {
  state = {
    inputHasFocus: false,
    selectedDate: null,
  };

  static getDerivedStateFromProps(props, state) {
    if (props.selectedDate !== undefined && props.selectedDate !== state.selectedDate) {
      return {
        selectedDate: props.selectedDate,
      };
    }

    return null;
  }

  handleBlur = () => {
    this.setState({ inputHasFocus: false }, () => this.props.onBlur && this.props.onBlur());
  };

  handleFocus = () => {
    this.setState({ inputHasFocus: true }, () => this.props.onFocus && this.props.onFocus());
  };

  handleInputDateChange = date => {
    this.setState({ selectedDate: date }, () => this.props.onChange(date));
  };

  renderDayPickerInput = () => {
    const { className, dayPickerProps, disabled, modifiers, readOnly, size, ...others } = this.props;
    const { selectedDate } = this.state;

    const dayPickerClassNames = cx(theme['date-picker'], theme[`is-${size}`], className);

    const propsWithoutBoxProps = omitBoxProps(others);
    const restProps = omit(propsWithoutBoxProps, ['helpText', 'onBlur', 'onChange', 'onFocus']);

    return (
      <DayPickerInput
        classNames={theme}
        dayPickerProps={{
          className: dayPickerClassNames,
          classNames: theme,
          modifiers: convertModifiersToClassnames(modifiers, theme),
          onDayClick: this.handleInputDateChange,
          selectedDays: selectedDate,
          navbarElement: <NavigationBar size={size} />,
          weekdayElement: <WeekDay size={size} />,
          ...dayPickerProps,
        }}
        onDayChange={this.handleInputDateChange}
        hideOnDayClick={false}
        inputProps={{
          disabled: disabled || readOnly,
          onBlur: this.handleBlur,
          onFocus: this.handleFocus,
        }}
        {...restProps}
      />
    );
  };

  renderIcon = () => {
    const { inverse } = this.props;

    return (
      <Icon
        className={theme['input-icon']}
        color={inverse ? 'teal' : 'neutral'}
        tint={inverse ? 'light' : 'darkest'}
        marginHorizontal={2}
      >
        <IconCalendarSmallOutline />
      </Icon>
    );
  };

  renderHelpText = () => {
    const { helpText, inverse } = this.props;

    if (helpText) {
      return (
        <TextSmall color={inverse ? 'white' : 'neutral'} marginTop={1} soft>
          {helpText}
        </TextSmall>
      );
    }
  };

  renderValidationMessage = () => {
    return (
      <Box marginTop={2}>
        <IconWarningBadgedSmallFilled className={theme['validation-icon']} />
        <TextSmall className={theme['validation-text']} element="span" marginLeft={1}>
          {this.props.error}
        </TextSmall>
      </Box>
    );
  };

  render() {
    const { bold, disabled, error, inverse, readOnly, size, ...others } = this.props;
    const { inputHasFocus } = this.state;

    const boxProps = pickBoxProps(others);

    const classNames = cx(theme['date-picker-input'], theme[`is-${size}`], {
      [theme['is-bold']]: bold,
      [theme['is-disabled']]: disabled,
      [theme['is-inverse']]: inverse,
      [theme['is-read-only']]: readOnly,
      [theme['has-error']]: error,
      [theme['has-focus']]: inputHasFocus,
    });

    return (
      <Box className={classNames} {...boxProps}>

          {this.renderIcon()}
          {this.renderDayPickerInput()}

        {error ? this.renderValidationMessage() : this.renderHelpText()}
      </Box>
    );
  }
}

DatePickerInput.propTypes = {
  bold: PropTypes.bool,
  className: PropTypes.string,
  dayPickerProps: PropTypes.object,
  disabled: PropTypes.bool,
  /** The text string/element to use as error message below the input. */
  error: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
  helpText: PropTypes.string,
  inverse: PropTypes.bool,
  modifiers: PropTypes.object,
  onBlur: PropTypes.func,
  onChange: PropTypes.func,
  onFocus: PropTypes.func,
  readOnly: PropTypes.bool,
  selectedDate: PropTypes.instanceOf(Date),
  size: PropTypes.oneOf(['small', 'medium', 'large']),
};

DatePickerInput.defaultProps = {
  bold: false,
  disabled: false,
  inverse: false,
  readOnly: false,
  size: 'medium',
};

export default DatePickerInput;
<|endoftext|>


<commit_before>/*
Canvas class

Florian Wokurka (2013)
https://github.com/notiontaxi
*/

"use strict"

define([], function() {

  var Canvas, module;
  module = function() {}
  Canvas = (function(){
// --------------------------------------

    function Canvas(id){

      this.id = id;
      this.cv = document.getElementById(this.id);
      this.ctx = this.cv.getContext('2d');

      this.highlight(false);

      this.ctx.font = "bold 12px sans-serif"
      this.ctx.textAlign = 'center'
      this.ctx.textBaseline = 'middle'

    }

    Canvas.prototype.drawImage = function(img, _this){

      if(!_this)
        var _this = this

      var height = img.height * (_this.cv.width/img.width)
      var xOffset = 0
      var yOffset = 0

      if(height < _this.cv.height){
        yOffset = (_this.cv.height - height) / 2
      }

      _this.clear()
      _this.getContext().drawImage(img, xOffset, yOffset, _this.cv.width, height)
    }

    Canvas.prototype.getElement = function(){
      return $('#'+this.id)
    }

    Canvas.prototype.getContext = function(){
      return this.ctx;
    }

    Canvas.prototype.updateSize = function(func) {

      this.ctx.canvas.width  = $('#container').width()*.833;
      $("#canvas-overlay").css({
        'left': this.ctx.canvas.left+'px',
        'top': this.ctx.canvas.top+'px'
      })
      if(!!func)
        func();
    }

    Canvas.prototype.highlight = function(onOrOff){
      if (onOrOff)
        this.ctx.fillStyle="#4A8FF0";
      else
        this.ctx.fillStyle="#FFFFFF";

      this.ctx.fillRect(0,0, this.ctx.canvas.width, this.ctx.canvas.height);
    }

     Canvas.prototype.clear = function(){
      this.ctx.fillStyle="white"
      this.ctx.fillRect(0,0, this.ctx.canvas.width, this.ctx.canvas.height)
    }

    // DRAWING

    Canvas.prototype.drawLine = function(startPoint, endPoint){
      this.ctx.moveTo(startPoint.x,startPoint.y);
      this.ctx.lineTo(endPoint.x,endPoint.y);
      this.ctx.stroke();
    }

    Canvas.prototype.drawText = function(text, pos, color,rot){
      this.ctx.font = "bold 12px sans-serif"
      this.ctx.textAlign = 'center'
      this.ctx.textBaseline = 'middle'
      // cut if its a number
      if(!isNaN(text*2))
        text = text.toFixed(1)

      this.ctx.fillStyle = color;

      // rotate text by -90 degrees
      if(rot){
        this.ctx.save()
        this.ctx.translate(pos.x, pos.y)
        this.ctx.rotate(Math.PI/2)
        this.ctx.fillText(text, 0, 0)
        this.ctx.restore()
      }
      else
        this.ctx.fillText(text, pos.x, pos.y);
    }

// --------------------------------------
    return Canvas
  })()
  return module.exports = Canvas
})

<commit_msg>render protraits correct in canvas<commit_after>/*
Canvas class

Florian Wokurka (2013)
https://github.com/notiontaxi
*/

"use strict"

define([], function() {

  var Canvas, module;
  module = function() {}
  Canvas = (function(){
// --------------------------------------

    function Canvas(id){

      this.id = id;
      this.cv = document.getElementById(this.id);
      this.ctx = this.cv.getContext('2d');

      this.highlight(false);

      this.ctx.font = "bold 12px sans-serif"
      this.ctx.textAlign = 'center'
      this.ctx.textBaseline = 'middle'

    }

    Canvas.prototype.drawImage = function(img, _this){

      if(!_this)
        var _this = this

      _this.imageHeight = 0
      _this.imageWidth = 0
      _this.imageXOffset = 0
      _this.imageYOffset = 0

      if(img.width >= img.height)
      {
        _this.imageHeight = img.height * (_this.cv.width/img.width)
        _this.imageWidth = _this.cv.width

        if(_this.imageHeight < _this.cv.height){
          _this.imageYOffset = (_this.cv.height - _this.imageHeight) / 2
        }
      }else{
        _this.imageHeight = _this.cv.height
        _this.imageWidth = img.width * (_this.cv.height/img.height)

        if(_this.imageWidth < _this.cv.width){
          _this.imageXOffset = (_this.cv.width - _this.imageWidth) / 2
        }

      }

      _this.clear()
      _this.getContext().drawImage(img, _this.imageXOffset, _this.imageYOffset, _this.imageWidth, _this.imageHeight)
    }

    Canvas.prototype.getElement = function(){
      return $('#'+this.id)
    }

    Canvas.prototype.getContext = function(){
      return this.ctx;
    }

    Canvas.prototype.updateSize = function(func) {

      this.ctx.canvas.width  = $('#container').width()*.833;
      $("#canvas-overlay").css({
        'left': this.ctx.canvas.left+'px',
        'top': this.ctx.canvas.top+'px'
      })
      if(!!func)
        func();
    }

    Canvas.prototype.highlight = function(onOrOff){
      // todo: fill canvas with old content when highlight off

      if (onOrOff)
        this.ctx.fillStyle="#4A8FF0";
      else
        this.ctx.fillStyle="#FFFFFF";

      this.ctx.fillRect(0,0, this.ctx.canvas.width, this.ctx.canvas.height);
    }

     Canvas.prototype.clear = function(){
      this.ctx.fillStyle="white"
      this.ctx.fillRect(0,0, this.ctx.canvas.width, this.ctx.canvas.height)
    }

    // DRAWING

    Canvas.prototype.drawLine = function(startPoint, endPoint){
      this.ctx.moveTo(startPoint.x,startPoint.y);
      this.ctx.lineTo(endPoint.x,endPoint.y);
      this.ctx.stroke();
    }

    Canvas.prototype.drawText = function(text, pos, color,rot){
      this.ctx.font = "bold 12px sans-serif"
      this.ctx.textAlign = 'center'
      this.ctx.textBaseline = 'middle'
      // cut if its a number
      if(!isNaN(text*2))
        text = text.toFixed(1)

      this.ctx.fillStyle = color;

      // rotate text by -90 degrees
      if(rot){
        this.ctx.save()
        this.ctx.translate(pos.x, pos.y)
        this.ctx.rotate(Math.PI/2)
        this.ctx.fillText(text, 0, 0)
        this.ctx.restore()
      }
      else
        this.ctx.fillText(text, pos.x, pos.y);
    }

// --------------------------------------
    return Canvas
  })()
  return module.exports = Canvas
})

<|endoftext|>