<commit_before>'use strict';

var Home = React.createClass({
    displayName: 'Home',

    render: function render() {
        var socials = [{ link: 'https://github.com/sonnylazuardi', icon: 'github' }, { link: 'http://linkedin.com/in/sonnylazuardi', icon: 'linkedin' }, { link: 'https://speakerdeck.com/sonnylazuardi', icon: 'slideshare' }, { link: 'http://twitter.com/sonnylazuardi', icon: 'twitter' }, { link: 'http://facebook.com/sonny.lazuardi', icon: 'facebook' }];
        return React.createElement(
            'div',
            { className: 'about' },
            React.createElement('img', { src: 'img/header.png' }),
            React.createElement(
                'h1',
                { className: 'jumbo-title' },
                'I create web & mobile apps.'
            ),
            React.createElement(
                'p',
                { className: 'jumbo-desc' },
                'Sonny Lazuardi - a web & mobile developer, open source contributor, Javascript fanboy'
            ),
            React.createElement(
                'div',
                { className: 'social' },
                socials.map(function (item) {
                    return React.createElement(
                        'a',
                        { href: item.link },
                        React.createElement('i', { className: 'fa fa-' + item.icon })
                    );
                })
            )
        );
    }
});<commit_msg>Update home.js<commit_after>'use strict';

var Home = React.createClass({
    displayName: 'Home',

    render: function render() {
        var socials = [{ link: 'https://github.com/aligos', icon: 'github' }, { link: 'http://linkedin.com/in/aligos', icon: 'linkedin' }, { link: 'https://speakerdeck.com/aligos', icon: 'slideshare' }, { link: 'http://twitter.com/aligos', icon: 'twitter' }, { link: 'http://facebook.com/matt.aligos', icon: 'facebook' }];
        return React.createElement(
            'div',
            { className: 'about' },
            React.createElement('img', { src: 'img/header.png' }),
            React.createElement(
                'h1',
                { className: 'jumbo-title' },
                'I create web & mobile apps.'
            ),
            React.createElement(
                'p',
                { className: 'jumbo-desc' },
                'Aligos - JavaScript Fans'
            ),
            React.createElement(
                'div',
                { className: 'social' },
                socials.map(function (item) {
                    return React.createElement(
                        'a',
                        { href: item.link },
                        React.createElement('i', { className: 'fa fa-' + item.icon })
                    );
                })
            )
        );
    }
});
<|endoftext|>


<commit_before>import fs from 'fs-extra';
import less from 'less';
import { URL } from 'url';
import postcss from 'postcss';
import globImport from 'glob';
import {rollup} from 'rollup';
import {optimize} from 'svgo';
import uglify from 'uglify-js';
import {promisify} from 'util';
import minimist from 'minimist';
import CleanCSS from 'clean-css';
import html from 'rollup-plugin-html';
import buble from '@rollup/plugin-buble';
import alias from '@rollup/plugin-alias';
import replace from '@rollup/plugin-replace';
import {basename, dirname, resolve} from 'path';
import {exec as execImport} from 'child_process';

export const exec = promisify(execImport);
export const glob = promisify(globImport);
export const readJson = fs.readJson;
export const pathExists = fs.pathExists;
export const __dirname = new URL('.', import.meta.url).pathname;

export const banner = `/*! UIkit ${await getVersion()} | https://www.getuikit.com | (c) 2014 - ${new Date().getFullYear()} YOOtheme | MIT License */\n`;
export const validClassName = /[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/;

const argv = minimist(process.argv.slice(2));

argv._.forEach(arg => {
    const tokens = arg.split('=');
    argv[tokens[0]] = tokens[1] || true;
});

export const args = argv;

export function read(file) {
    return fs.readFile(file, 'utf8');
}

export async function write(dest, data) {

    const err = await fs.writeFile(dest, data);

    if (err) {
        console.log(err);
        throw err;
    }

    await logFile(dest);

    return dest;

}

export async function logFile(file) {
    const data = await read(file);
    console.log(`${cyan(resolve(file))} ${getSize(data)}`);
}

export async function minify(file) {

    const {styles} = await new CleanCSS({
        advanced: false,
        keepSpecialComments: 0,
        rebase: false,
        returnPromise: true
    }).minify([file]);

    await write(`${resolve(dirname(file), basename(file, '.css'))}.min.css`, styles);

    return styles;

}

export async function renderLess(data, options) {
    return postcss()
        .use({
            postcssPlugin: 'calc',
            Once(root) {
                root.walk(node => {
                    const {type} = node;
                    if (type === 'decl') {
                        node.value = postcss.list.space(node.value).map(value =>
                            value.startsWith('calc(')
                                ? value.replace(/(.)calc/g, '$1')
                                : value
                        ).join(' ');
                    }
                });
            }
        })
        .process((await less.render(data, options)).css)
        .css;
}

export async function compile(file, dest, {external, globals, name, aliases, replaces, minify = true}) {

    name = (name || '').replace(/[^\w]/g, '_');

    const bundle = await rollup({
        external,
        input: resolve(file),
        plugins: [
            replace({
                preventAssignment: true,
                values: Object.assign({
                    VERSION: `'${await getVersion()}'`
                }, replaces)}
            ),
            alias({
                entries: Object.assign({
                    'uikit-util': './src/js/util/index.js'
                }, aliases)
            }),
            html({
                include: '**/*.svg',
                htmlMinifierOptions: {
                    collapseWhitespace: true
                }
            }),
            buble({namedFunctionExpressions: false})
        ]
    });

    let {output: [{code, map}]} = await bundle.generate({
        globals,
        banner,
        format: 'umd',
        amd: {id: `UIkit${name}`.toLowerCase()},
        name: `UIkit${ucfirst(name)}`,
        sourcemap: !minify ? 'inline' : false
    });

    code = code.replace(/(>)\\n\s+|\\n\s+(<)/g, '$1 $2');

    return Promise.all([
        write(`${dest}.js`, code + (!minify ? '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + Buffer.from(map.toString()).toString('base64') : '')),
        minify ? write(`${dest}.min.js`, uglify.minify(code, {output: {preamble: banner}}).code) : null
    ])[0];

}

export async function icons(src) {

    const options = {
        plugins: [
            {
                name: 'preset-default',
                params: {
                    overrides: {
                        removeViewBox: false,
                        cleanupNumericValues: {
                            floatPrecision: 3
                        },
                        convertPathData: false,
                        convertShapeToPath: false,
                        mergePaths: false,
                        removeDimensions: false,
                        removeStyleElement: false,
                        removeScriptElement: false,
                        removeUnknownsAndDefaults: false,
                        removeUselessStrokeAndFill: false
                    }
                }
            }
        ]
    };

    const files = await glob(src, {nosort: true});
    const icons = await Promise.all(files.map(async file =>
        (await optimize(await read(file), options)).data
    ));

    return JSON.stringify(files.reduce((result, file, i) => {
        result[basename(file, '.svg')] = icons[i];
        return result;
    }, {}), null, '    ');

}

export async function run(cmd) {
    const {stdout, stderr} = await exec(cmd);

    stdout && console.log(stdout.trim());
    stderr && console.log(stderr.trim());

    return stdout;
}

export function ucfirst(str) {
    return str.length ? str.charAt(0).toUpperCase() + str.slice(1) : '';
}

export async function getVersion() {
    return JSON.parse(await read(resolve(__dirname, '../package.json'))).version;
}

export async function replaceInFile(file, fn) {
    await write(file, await fn(await read(file)));
}

function cyan(str) {
    return `\x1b[1m\x1b[36m${str}\x1b[39m\x1b[22m`;
}

function getSize(data) {
    return `${(data.length / 1024).toFixed(2)}kb`;
}
<commit_msg>cleanup<commit_after>import fs from 'fs-extra';
import less from 'less';
import { URL } from 'url';
import postcss from 'postcss';
import globImport from 'glob';
import {rollup} from 'rollup';
import {optimize} from 'svgo';
import uglify from 'uglify-js';
import {promisify} from 'util';
import minimist from 'minimist';
import CleanCSS from 'clean-css';
import html from 'rollup-plugin-html';
import buble from '@rollup/plugin-buble';
import alias from '@rollup/plugin-alias';
import replace from '@rollup/plugin-replace';
import {basename, dirname, resolve} from 'path';
import {exec as execImport} from 'child_process';

export const exec = promisify(execImport);
export const glob = promisify(globImport);
export const readJson = fs.readJson;
export const pathExists = fs.pathExists;
export const __dirname = new URL('.', import.meta.url).pathname;

export const banner = `/*! UIkit ${await getVersion()} | https://www.getuikit.com | (c) 2014 - ${new Date().getFullYear()} YOOtheme | MIT License */\n`;
export const validClassName = /[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/;

const argv = minimist(process.argv.slice(2));

argv._.forEach(arg => {
    const tokens = arg.split('=');
    argv[tokens[0]] = tokens[1] || true;
});

export const args = argv;

export function read(file) {
    return fs.readFile(file, 'utf8');
}

export async function write(dest, data) {

    const err = await fs.writeFile(dest, data);

    if (err) {
        console.log(err);
        throw err;
    }

    await logFile(dest);

    return dest;

}

export async function logFile(file) {
    const data = await read(file);
    console.log(`${cyan(resolve(file))} ${getSize(data)}`);
}

export async function minify(file) {

    const {styles} = await new CleanCSS({
        advanced: false,
        keepSpecialComments: 0,
        rebase: false,
        returnPromise: true
    }).minify([file]);

    await write(`${resolve(dirname(file), basename(file, '.css'))}.min.css`, styles);

    return styles;

}

export async function renderLess(data, options) {
    return postcss()
        .use({
            postcssPlugin: 'calc',
            Once(root) {
                root.walk(node => {
                    const {type} = node;
                    if (type === 'decl') {
                        node.value = postcss.list.space(node.value).map(value =>
                            value.startsWith('calc(')
                                ? value.replace(/(.)calc/g, '$1')
                                : value
                        ).join(' ');
                    }
                });
            }
        })
        .process((await less.render(data, options)).css)
        .css;
}

export async function compile(file, dest, {external, globals, name, aliases, replaces, minify = true}) {

    name = (name || '').replace(/[^\w]/g, '_');

    const bundle = await rollup({
        external,
        input: resolve(file),
        plugins: [
            replace({
                preventAssignment: true,
                values: Object.assign({
                    VERSION: `'${await getVersion()}'`
                }, replaces)}
            ),
            alias({
                entries: Object.assign({
                    'uikit-util': './src/js/util/index.js'
                }, aliases)
            }),
            html({
                include: '**/*.svg',
                htmlMinifierOptions: {
                    collapseWhitespace: true
                }
            }),
            buble({namedFunctionExpressions: false})
        ]
    });

    let {output: [{code, map}]} = await bundle.generate({
        globals,
        banner,
        format: 'umd',
        amd: {id: `UIkit${name}`.toLowerCase()},
        name: `UIkit${ucfirst(name)}`,
        sourcemap: !minify ? 'inline' : false
    });

    code = code.replace(/(>)\\n\s+|\\n\s+(<)/g, '$1 $2');

    return Promise.all([
        write(`${dest}.js`, code + (!minify ? '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' + Buffer.from(map.toString()).toString('base64') : '')),
        minify ? write(`${dest}.min.js`, uglify.minify(code, {output: {preamble: banner}}).code) : null
    ])[0];

}

export async function icons(src) {

    const options = {
        plugins: [
            {
                name: 'preset-default',
                params: {
                    overrides: {
                        removeViewBox: false,
                        cleanupNumericValues: {
                            floatPrecision: 3
                        },
                        convertPathData: false,
                        convertShapeToPath: false,
                        mergePaths: false,
                        removeDimensions: false,
                        removeStyleElement: false,
                        removeScriptElement: false,
                        removeUnknownsAndDefaults: false,
                        removeUselessStrokeAndFill: false
                    }
                }
            }
        ]
    };

    const files = await glob(src, {nosort: true});
    const icons = await Promise.all(files.map(async file =>
        (await optimize(await read(file), options)).data
    ));

    return JSON.stringify(files.reduce((result, file, i) => {
        result[basename(file, '.svg')] = icons[i];
        return result;
    }, {}), null, '    ');

}

export async function run(cmd) {
    const {stdout, stderr} = await exec(cmd);

    stderr && console.error(stderr.trim());

    return stdout;
}

export function ucfirst(str) {
    return str.length ? str.charAt(0).toUpperCase() + str.slice(1) : '';
}

export async function getVersion() {
    return await readJson(resolve(__dirname, '../package.json')).version;
}

export async function replaceInFile(file, fn) {
    await write(file, await fn(await read(file)));
}

function cyan(str) {
    return `\x1b[1m\x1b[36m${str}\x1b[39m\x1b[22m`;
}

function getSize(data) {
    return `${(data.length / 1024).toFixed(2)}kb`;
}
<|endoftext|>


<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

// Comments the repeatition for user, to make it clear
function set_repeatition_comment() {
    var s = '';
    var repType = parseInt($('#repeatability').val(), 10);
    if(repType > 0) {
        var date = new Date(parseInt($('#sYear').val(), 10), parseInt($('#sMonth').val()-1, 10), parseInt($('#sDay').val(), 10));
        var weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        s = 'on ' + weekDays[date.getDay()];
        if(repType == 4) {
            var weekNr = Math.floor( date.getDate() / 7 ) + 1;
            var postfix = ['st', 'nd', 'rd', 'th', 'th'];
            var weekNrStr = 'the ' + weekNr + postfix[weekNr-1] + ' ';
            s = 'on ' + weekNrStr + weekDays[date.getDay()] + ' of a month';
        }
    }
    $('#repComment').html(s);
}

// Converting from time string to seconds
function __getTime(time) {
    var minutes = parseInt(time % 60);
    var hours = parseInt(time / 60 % 24);
    minutes = minutes + "";
    if (minutes.length == 1) {
        minutes = "0" + minutes;
    }
    return hours + ":" + minutes;
}

// Refresh time slider
function updateTimeSlider(event, ui) {
    if (event && event.type != "slidecreate" ) {
        $("#sTime").val(__getTime(ui.values[0]));
        $("#eTime").val(__getTime(ui.values[1]));
    }
    var sTime = parseInt($("#sTime").val().split(":")[0] * 60) + parseInt($("#sTime").val().split(":")[1]);
    var eTime = parseInt($("#eTime").val().split(":")[0] * 60) + parseInt($("#eTime").val().split(":")[1]);
    if (sTime && eTime || sTime == 0) {
        $('#timeRange').slider('values', 0, sTime).slider('values', 1, eTime);
    }
    $('#sTimeBubble').text($("#sTime").val()).offset({left:$('#timeRange .ui-slider-handle:first').offset().left});
    $('#eTimeBubble').text($("#eTime").val()).offset({left:$('#timeRange .ui-slider-handle:last').offset().left});
}

//Refresh datapicker's dates
function refreshDates(){
    if ($("#sDatePlace").datepicker('getDate') > $("#eDatePlace").datepicker('getDate')) {
        $("#eDatePlace").datepicker('setDate', $("#sDatePlace").datepicker('getDate'));
    }
    $("#sDay").val($("#sDatePlace").datepicker('getDate').getDate());
    $("#sMonth").val(parseInt($("#sDatePlace").datepicker('getDate').getMonth() + 1));
    $("#sYear").val($("#sDatePlace").datepicker('getDate').getFullYear());
    if ($('#finishDate').val() == 'true') {
        $("#eDay").val($("#eDatePlace").datepicker('getDate').getDate());
        $("#eMonth").val(parseInt($("#eDatePlace").datepicker('getDate').getMonth() + 1));
        $("#eYear").val($("#eDatePlace").datepicker('getDate').getFullYear()); }
    else {
        $("#eDay").val($("#sDatePlace").datepicker('getDate').getDate());
        $("#eMonth").val(parseInt($("#sDatePlace").datepicker('getDate').getMonth() + 1));
        $("#eYear").val($("#sDatePlace").datepicker('getDate').getFullYear());
    }
}

//Save calendar data
function saveCalendarData(finishDate) {
    $("#sDay").val($("#sDatePlace").datepicker('getDate').getDate());
    $("#sMonth").val(parseInt($("#sDatePlace").datepicker('getDate').getMonth() + 1));
    $("#sYear").val($("#sDatePlace").datepicker('getDate').getFullYear());
    if (finishDate == 'true') {
        $("#eDay").val($("#eDatePlace").datepicker('getDate').getDate());
        $("#eMonth").val(parseInt($("#eDatePlace").datepicker('getDate').getMonth() + 1));
        $("#eYear").val($("#eDatePlace").datepicker('getDate').getFullYear());
    } else {
        $("#eDay").val($("#sDatePlace").datepicker('getDate').getDate());
        $("#eMonth").val(parseInt($("#sDatePlace").datepicker('getDate').getMonth() + 1));
        $("#eYear").val($("#sDatePlace").datepicker('getDate').getFullYear());
    }
}

// Store all fields in local storage
function saveFormData() {
    var selectedRooms = $("#roomselector").roomselector("selection");
    var filterData = $("#roomselector").roomselector("userdata");
    saveCalendarData($('#finishDate').val());

    var rbDict = {"sDay": $("#sDay").val(),
                  "sMonth": $("#sMonth").val(),
                  "sYear": $("#sYear").val(),
                  "eDay": $("#eDay").val(),
                  "eMonth": $("#eMonth").val(),
                  "eYear": $("#eYear").val(),
                  "sTime": $('#sTime').val(),
                  "eTime": $('#eTime').val(),
                  "capacity": filterData.capacity,
                  "videoconference": filterData.videoconference,
                  "webcast": filterData.webcast,
                  'projector': filterData.projector,
                  "publicroom": filterData.publicroom,
                  "filter":  filterData.search,
                  "selectedRooms":  selectedRooms,
                  "finishDate": $('#finishDate').val(),
                  "flexibleDatesRange": $("#flexibleDates input[name=flexibleDatesRange]:checked").val(),
                  "repeatability": $('#repeatability input[name=repeatability]:checked').val()};

    $.jStorage.set(userId, rbDict);
    $.jStorage.setTTL(userId, 7200000); // 2 hours
}
<commit_msg>[MIN] indentation fix<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

// Comments the repeatition for user, to make it clear
function set_repeatition_comment() {
    var s = '';
    var repType = parseInt($('#repeatability').val(), 10);
    if(repType > 0) {
        var date = new Date(parseInt($('#sYear').val(), 10), parseInt($('#sMonth').val()-1, 10), parseInt($('#sDay').val(), 10));
        var weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        s = 'on ' + weekDays[date.getDay()];
        if(repType == 4) {
            var weekNr = Math.floor( date.getDate() / 7 ) + 1;
            var postfix = ['st', 'nd', 'rd', 'th', 'th'];
            var weekNrStr = 'the ' + weekNr + postfix[weekNr-1] + ' ';
            s = 'on ' + weekNrStr + weekDays[date.getDay()] + ' of a month';
        }
    }
    $('#repComment').html(s);
}

// Converting from time string to seconds
function __getTime(time) {
    var minutes = parseInt(time % 60);
    var hours = parseInt(time / 60 % 24);
    minutes = minutes + "";
    if (minutes.length == 1) {
        minutes = "0" + minutes;
    }
    return hours + ":" + minutes;
}

// Refresh time slider
function updateTimeSlider(event, ui) {
    if (event && event.type != "slidecreate" ) {
        $("#sTime").val(__getTime(ui.values[0]));
        $("#eTime").val(__getTime(ui.values[1]));
    }
    var sTime = parseInt($("#sTime").val().split(":")[0] * 60) + parseInt($("#sTime").val().split(":")[1]);
    var eTime = parseInt($("#eTime").val().split(":")[0] * 60) + parseInt($("#eTime").val().split(":")[1]);
    if (sTime && eTime || sTime == 0) {
        $('#timeRange').slider('values', 0, sTime).slider('values', 1, eTime);
    }
    $('#sTimeBubble').text($("#sTime").val()).offset({left:$('#timeRange .ui-slider-handle:first').offset().left});
    $('#eTimeBubble').text($("#eTime").val()).offset({left:$('#timeRange .ui-slider-handle:last').offset().left});
}

//Refresh datapicker's dates
function refreshDates(){
    if ($("#sDatePlace").datepicker('getDate') > $("#eDatePlace").datepicker('getDate')) {
        $("#eDatePlace").datepicker('setDate', $("#sDatePlace").datepicker('getDate'));
    }
    $("#sDay").val($("#sDatePlace").datepicker('getDate').getDate());
    $("#sMonth").val(parseInt($("#sDatePlace").datepicker('getDate').getMonth() + 1));
    $("#sYear").val($("#sDatePlace").datepicker('getDate').getFullYear());
    if ($('#finishDate').val() == 'true') {
        $("#eDay").val($("#eDatePlace").datepicker('getDate').getDate());
        $("#eMonth").val(parseInt($("#eDatePlace").datepicker('getDate').getMonth() + 1));
        $("#eYear").val($("#eDatePlace").datepicker('getDate').getFullYear()); }
    else {
        $("#eDay").val($("#sDatePlace").datepicker('getDate').getDate());
        $("#eMonth").val(parseInt($("#sDatePlace").datepicker('getDate').getMonth() + 1));
        $("#eYear").val($("#sDatePlace").datepicker('getDate').getFullYear());
    }
}

//Save calendar data
function saveCalendarData(finishDate) {
    $("#sDay").val($("#sDatePlace").datepicker('getDate').getDate());
    $("#sMonth").val(parseInt($("#sDatePlace").datepicker('getDate').getMonth() + 1));
    $("#sYear").val($("#sDatePlace").datepicker('getDate').getFullYear());
    if (finishDate == 'true') {
        $("#eDay").val($("#eDatePlace").datepicker('getDate').getDate());
        $("#eMonth").val(parseInt($("#eDatePlace").datepicker('getDate').getMonth() + 1));
        $("#eYear").val($("#eDatePlace").datepicker('getDate').getFullYear());
    } else {
        $("#eDay").val($("#sDatePlace").datepicker('getDate').getDate());
        $("#eMonth").val(parseInt($("#sDatePlace").datepicker('getDate').getMonth() + 1));
        $("#eYear").val($("#sDatePlace").datepicker('getDate').getFullYear());
    }
}

// Store all fields in local storage
function saveFormData() {
    var selectedRooms = $("#roomselector").roomselector("selection");
    var filterData = $("#roomselector").roomselector("userdata");
    saveCalendarData($('#finishDate').val());

    var rbDict = {
        "sDay": $("#sDay").val(),
        "sMonth": $("#sMonth").val(),
        "sYear": $("#sYear").val(),
        "eDay": $("#eDay").val(),
        "eMonth": $("#eMonth").val(),
        "eYear": $("#eYear").val(),
        "sTime": $('#sTime').val(),
        "eTime": $('#eTime').val(),
        "capacity": filterData.capacity,
        "videoconference": filterData.videoconference,
        "webcast": filterData.webcast,
        "publicroom": filterData.publicroom,
        "filter":  filterData.search,
        "selectedRooms":  selectedRooms,
        "finishDate": $('#finishDate').val(),
        "flexibleDatesRange": $("#flexibleDates input[name=flexibleDatesRange]:checked").val(),
        "repeatability": $('#repeatability input[name=repeatability]:checked').val()
    };

    $.jStorage.set(userId, rbDict);
    $.jStorage.setTTL(userId, 7200000); // 2 hours
}
<|endoftext|>


<commit_before>'use strict';

////////////////////////////////////////////////////////////////////////////////
/// @brief Foxx template engine
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2013 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Lucas Dohmen
/// @author Michael Hackstein
/// @author Alan Plum
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var _ = require('underscore');
var fs = require('fs');
var internal = require('internal');
var i = require('i')();
var templatePath = fs.join(
  internal.startupPath,
  'server',
  'modules',
  'org',
  'arangodb',
  'foxx',
  'templates'
);

function Engine(opts) {
  this._path = templatePath;
  this.folder = opts.path;
  this.name = opts.name;
  this.authenticated = opts.authenticated;
  this.author = opts.author;
  this.description = opts.description;
  this.license = opts.license;
  this.determineFromCollectionNames(opts.collectionNames);
}

_.extend(Engine.prototype, {
  write: function() {
    fs.makeDirectory(this.folder);
    fs.makeDirectory(fs.join(this.folder, 'controllers'));
    fs.makeDirectory(fs.join(this.folder, 'models'));
    fs.makeDirectory(fs.join(this.folder, 'repositories'));
    fs.makeDirectory(fs.join(this.folder, 'scripts'));
    fs.makeDirectory(fs.join(this.folder, 'test'));
    fs.write(fs.join(this.folder, 'manifest.json'), this.buildManifest());

    _.each(this.repositories, function (repository) {
      fs.write(fs.join(this.folder, repository.path), this.buildRepository());
    }, this);

    _.each(this.models, function (model) {
      fs.write(fs.join(this.folder, model.path), this.buildModel());
    }, this);

    _.each(this.controllers, function (controller) {
      fs.write(fs.join(this.folder, controller.path), this.buildController(controller));
    }, this);

    fs.write(fs.join(this.folder, 'scripts', 'setup.js'), this.buildSetup(this.collectionNames));
    fs.write(fs.join(this.folder, 'scripts', 'teardown.js'), this.buildTeardown(this.collectionNames));
    fs.write(fs.join(this.folder, 'test', 'example.js'), this.buildTest());
  },

  template: function(name) {
    return _.template(fs.read(fs.join(this._path, name)));
  },

  determineFromCollectionNames: function (collectionNames) {
    this.collectionNames = [];
    this.controllers = [];
    this.repositories = [];
    this.models = [];

    _.each(collectionNames, function (collectionName) {
      var modelBase = i.singularize(collectionName).substr(1),
        collectionStart,
        repositoryBase = collectionName.substr(1),
        repositoryName,
        repositoryPath,
        repositoryInstance,
        modelPath,
        modelName,
        modelInstance;
      collectionStart = collectionName.charAt(0);
      if (collectionStart.match(/[a-z]/i) === null) {
        throw new Error('Collection name has to start with a letter');
      }
      if (modelBase === repositoryBase) {
        repositoryBase += 'Repo';
      }
      modelName = collectionStart.toUpperCase() + modelBase;
      modelInstance = collectionStart.toLowerCase() + modelBase;
      repositoryName = collectionStart.toUpperCase() + repositoryBase;
      repositoryInstance = collectionStart.toLowerCase() + repositoryBase;
      repositoryPath = 'repositories/' + collectionName;
      modelPath = 'models/' + modelName.toLowerCase();

      this.collectionNames.push(collectionName);
      this.controllers.push({
        url: '/' + collectionName,
        path: 'controllers/' + collectionName + '.js',
        repositoryInstance: repositoryInstance,
        repository: repositoryName,
        repositoryPath: repositoryPath,
        modelInstance: modelInstance,
        model: modelName,
        modelPath: modelPath,
        basePath: collectionName,
        collectionName: collectionName
      });
      this.repositories.push({
        path: repositoryPath + '.js'
      });
      this.models.push({
        path: modelPath + '.js'
      });
    }, this);
  },

  buildManifest: function() {
    var manifest = {
      name: this.name,
      description: this.description,
      author: this.author,
      version: '0.0.1',
      license: this.license,
      controllers: {},
      scripts: {
        setup: 'scripts/setup.js',
        teardown: 'scripts/teardown.js'
      },
      tests: 'test/**/*.js'
    };

    _.each(this.controllers, function (controller) {
      manifest.controllers[controller.url] = controller.path;
    });

    return JSON.stringify(manifest, 0, 2);
  },

  buildSetup: function(collections) {
    var templ = this.template('setup.js.tmpl');

    return templ({
      collections: collections
    });
  },

  buildTeardown: function(collections) {
    var templ = this.template('teardown.js.tmpl');

    return templ({
      collections: collections
    });
  },

  buildController: function(controller) {
    var templ = this.template('controller.js.tmpl');

    return templ(controller);
  },

  buildRepository: function() {
    var templ = this.template('repository.js.tmpl');

    return templ();
  },

  buildModel: function() {
    var templ = this.template('model.js.tmpl');

    return templ();
  },

  buildTest: function () {
    var templ = this.template('test.js.tmpl');

    return templ();
  }
});

exports.Engine = Engine;
<commit_msg>org/arangodb -> @arangodb in Foxx generator<commit_after>'use strict';

////////////////////////////////////////////////////////////////////////////////
/// @brief Foxx template engine
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2013 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Lucas Dohmen
/// @author Michael Hackstein
/// @author Alan Plum
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var _ = require('underscore');
var fs = require('fs');
var internal = require('internal');
var i = require('i')();
var templatePath = fs.join(
  internal.startupPath,
  'server',
  'modules',
  '@arangodb',
  'foxx',
  'templates'
);

function Engine(opts) {
  this._path = templatePath;
  this.folder = opts.path;
  this.name = opts.name;
  this.authenticated = opts.authenticated;
  this.author = opts.author;
  this.description = opts.description;
  this.license = opts.license;
  this.determineFromCollectionNames(opts.collectionNames);
}

_.extend(Engine.prototype, {
  write: function() {
    fs.makeDirectory(this.folder);
    fs.makeDirectory(fs.join(this.folder, 'controllers'));
    fs.makeDirectory(fs.join(this.folder, 'models'));
    fs.makeDirectory(fs.join(this.folder, 'repositories'));
    fs.makeDirectory(fs.join(this.folder, 'scripts'));
    fs.makeDirectory(fs.join(this.folder, 'test'));
    fs.write(fs.join(this.folder, 'manifest.json'), this.buildManifest());

    _.each(this.repositories, function (repository) {
      fs.write(fs.join(this.folder, repository.path), this.buildRepository());
    }, this);

    _.each(this.models, function (model) {
      fs.write(fs.join(this.folder, model.path), this.buildModel());
    }, this);

    _.each(this.controllers, function (controller) {
      fs.write(fs.join(this.folder, controller.path), this.buildController(controller));
    }, this);

    fs.write(fs.join(this.folder, 'scripts', 'setup.js'), this.buildSetup(this.collectionNames));
    fs.write(fs.join(this.folder, 'scripts', 'teardown.js'), this.buildTeardown(this.collectionNames));
    fs.write(fs.join(this.folder, 'test', 'example.js'), this.buildTest());
  },

  template: function(name) {
    return _.template(fs.read(fs.join(this._path, name)));
  },

  determineFromCollectionNames: function (collectionNames) {
    this.collectionNames = [];
    this.controllers = [];
    this.repositories = [];
    this.models = [];

    _.each(collectionNames, function (collectionName) {
      var modelBase = i.singularize(collectionName).substr(1),
        collectionStart,
        repositoryBase = collectionName.substr(1),
        repositoryName,
        repositoryPath,
        repositoryInstance,
        modelPath,
        modelName,
        modelInstance;
      collectionStart = collectionName.charAt(0);
      if (collectionStart.match(/[a-z]/i) === null) {
        throw new Error('Collection name has to start with a letter');
      }
      if (modelBase === repositoryBase) {
        repositoryBase += 'Repo';
      }
      modelName = collectionStart.toUpperCase() + modelBase;
      modelInstance = collectionStart.toLowerCase() + modelBase;
      repositoryName = collectionStart.toUpperCase() + repositoryBase;
      repositoryInstance = collectionStart.toLowerCase() + repositoryBase;
      repositoryPath = 'repositories/' + collectionName;
      modelPath = 'models/' + modelName.toLowerCase();

      this.collectionNames.push(collectionName);
      this.controllers.push({
        url: '/' + collectionName,
        path: 'controllers/' + collectionName + '.js',
        repositoryInstance: repositoryInstance,
        repository: repositoryName,
        repositoryPath: repositoryPath,
        modelInstance: modelInstance,
        model: modelName,
        modelPath: modelPath,
        basePath: collectionName,
        collectionName: collectionName
      });
      this.repositories.push({
        path: repositoryPath + '.js'
      });
      this.models.push({
        path: modelPath + '.js'
      });
    }, this);
  },

  buildManifest: function() {
    var manifest = {
      name: this.name,
      description: this.description,
      author: this.author,
      version: '0.0.1',
      license: this.license,
      controllers: {},
      scripts: {
        setup: 'scripts/setup.js',
        teardown: 'scripts/teardown.js'
      },
      tests: 'test/**/*.js'
    };

    _.each(this.controllers, function (controller) {
      manifest.controllers[controller.url] = controller.path;
    });

    return JSON.stringify(manifest, 0, 2);
  },

  buildSetup: function(collections) {
    var templ = this.template('setup.js.tmpl');

    return templ({
      collections: collections
    });
  },

  buildTeardown: function(collections) {
    var templ = this.template('teardown.js.tmpl');

    return templ({
      collections: collections
    });
  },

  buildController: function(controller) {
    var templ = this.template('controller.js.tmpl');

    return templ(controller);
  },

  buildRepository: function() {
    var templ = this.template('repository.js.tmpl');

    return templ();
  },

  buildModel: function() {
    var templ = this.template('model.js.tmpl');

    return templ();
  },

  buildTest: function () {
    var templ = this.template('test.js.tmpl');

    return templ();
  }
});

exports.Engine = Engine;
<|endoftext|>


<commit_before>/**
 * Anecdote module.
 */

(function(){

    function anecdote_constructor(){

        this.layer_name = 'anecdote';

        this.dom_obj = this.create_block('layer_bg');
        document.body.appendChild(this.dom_obj);

        this.superclass = BaseLayer.prototype;

        this.page = 0;
        this.total_pages = 0;

        this.resp = [];

        this.bookmark_page = -1;

        this.quick_page_switch = {"on" : false, "hide_to" : 3000};

        this.init = function(){

            var container = create_block_element('', this.dom_obj);

            var anecdote_body_container = create_block_element('anecdote_body_container', container);

            var info_bar = create_block_element('', anecdote_body_container);

            this.anecdote_date = create_inline_element('date', info_bar);
            this.anecdote_rate = create_inline_element('rate', info_bar);

            this.anecdote_body = create_block_element('anecdote_body', anecdote_body_container);

            this.anecdote_page_bar = create_block_element('anecdote_page_bar', container);

            this.anecdote_left_arrow = create_block_element('anecdote_left_arrow', container);

            this.anecdote_right_arrow = create_block_element('anecdote_right_arrow', container);

            this.scrollbar = new scrollbar(anecdote_body_container, this.anecdote_body, {"height" : 330});
        };

        this.show = function(){
            _debug('anecdote.show');

            this.superclass.show.apply(this);

            this.load();
            this.get_bookmark();
        };

        this.hide = function(){
            _debug('anecdote.hide');

            this.superclass.hide.apply(this);

            if (this.quick_page_switch.on){
                this.cancel_quick_page_switch();
            }

            this.scrollbar && this.scrollbar.reset && this.scrollbar.reset();

            this.anecdote_body.scrollTop = 0;
        };

        this.load = function(){
            _debug('anecdote.load');

            this.set_loading();

            this.scrollbar && this.scrollbar.reset && this.scrollbar.reset();

            stb.load(
                {
                    "type"   : "anecdote",
                    "action" : "get_by_page",
                    "p"      : this.page
                },

                function(result){
                    this.fill(result);
                },

                this
            )
        };

        this.fill = function(resp){
            _debug('anecdote.fill', resp);

            this.resp = resp;

            this.total_pages = this.resp.total_items;

            this.fill_page_bar();

            if (parseInt(this.resp.data.voted) > 0){
                this.color_buttons[this.color_buttons.getIdxByVal('color', 'green')].text_obj.setClass('disable_color_btn_text');
            }else{
                this.color_buttons[this.color_buttons.getIdxByVal('color', 'green')].text_obj.delClass();
            }

            this.anecdote_date.innerHTML = this.resp.data['added'];

            /*var rating = parseInt(this.resp.data['rating']);

            if (rating > 0){
                rating = '+' + rating;
            }

            if (rating == 0){
                rating = '';
            }

            this.anecdote_rate.innerHTML = ' ' + rating;*/

            this.set_rating(this.resp.data['rating']);

            this.anecdote_body.innerHTML = this.resp.data['anec_body'];
        };

        this.set_rating = function(rating){
            _debug('anecdote.set_rating', rating);

            var rating = parseInt(rating);

            if (rating > 0){
                rating = '+' + rating;
            }

            if (rating == 0){
                rating = '';
            }

            this.anecdote_rate.innerHTML = ' ' + rating;
        }

        this.fill_page_bar = function(){
            _debug('anecdote.fill_page_bar');

            this.anecdote_page_bar.innerHTML = word['anecdote_pagebar_title'] + ' ' + (this.page+1) + ' ' + word['layer_from'] + ' ' + this.total_pages + '';
        };

        this.set_loading = function(){
            _debug('anecdote.set_loading');

            this.anecdote_page_bar.innerHTML = word['layer_loading'];
        }

        this.shift_page = function(dir){
            _debug('anecdote.shift_page', dir);

            if (dir>0){

                if (this.page < this.total_pages-1){
                    this.page++;
                }else{
                    this.page = 0;
                }

            }else{
                if (this.page > 0){
                    this.page--;
                }else{
                    this.page = this.total_pages-1;
                }
            }

            this.load();
        };

        this.bind = function(){

            this.shift_page.bind(key.LEFT, this, -1);
            this.shift_page.bind(key.RIGHT, this, 1);

            (function(){

                if (this.quick_page_switch.on){
                    this.hide_quick_page_switch();
                }

            }).bind(key.OK, this);

            (function(){
                this.hide();
                main_menu.show();
            }).bind(key.MENU, this);

            (function(){
                if (this.quick_page_switch.on){
                    this.cancel_quick_page_switch();
                }else{
                    this.hide();
                    main_menu.show();
                }
            }).bind(key.EXIT, this);

            this.show_quick_page_switch.bind(key.NUM1, this, 1);
            this.show_quick_page_switch.bind(key.NUM2, this, 2);
            this.show_quick_page_switch.bind(key.NUM3, this, 3);
            this.show_quick_page_switch.bind(key.NUM4, this, 4);
            this.show_quick_page_switch.bind(key.NUM5, this, 5);
            this.show_quick_page_switch.bind(key.NUM6, this, 6);
            this.show_quick_page_switch.bind(key.NUM7, this, 7);
            this.show_quick_page_switch.bind(key.NUM8, this, 8);
            this.show_quick_page_switch.bind(key.NUM9, this, 9);
            this.show_quick_page_switch.bind(key.NUM0, this, 0);

            (function(){
                if (this.quick_page_switch.on){
                    this.del_quick_go_page();
                }
            }).bind(key.BACK, this);

            this.vshift.bind(key.UP, this, -1);
            this.vshift.bind(key.DOWN, this, 1);

            this.vshift_page.bind(key.PAGE_PREV, this, -1);
            this.vshift_page.bind(key.PAGE_NEXT, this, 1);
        };

        this.like = function(){
            _debug('anecdote.like');

            if (parseInt(this.resp.data['voted']) > 0){
                return;
            }

            this.color_buttons[this.color_buttons.getIdxByVal('color', 'green')].text_obj.setClass('disable_color_btn_text');

            stb.load(
                {
                    "type"    : "anecdote",
                    "action"  : "set_vote",
                    "anec_id" : this.resp.data.id
                },

                function(result){
                    _debug('anecdote.like result', result);

                    this.resp.data['rating'] = parseInt(this.resp.data['rating'])+1;

                    this.set_rating(this.resp.data['rating']);

                },

                this
            );
        };

        this.get_bookmark = function(){
            _debug('anecdote.get_bookmark');

            stb.load(
                {
                    "type"    : "anecdote",
                    "action"  : "get_bookmark"
                },

                function(result){
                    _debug('anecdote.get_bookmark result', result);

                    this.bookmark_page = parseInt(result) - 1;

                    if (this.bookmark_page >= 0){
                        this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.delClass();
                        this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.innerHTML = word['anecdote_to_bookmark'] + ' ' + (this.bookmark_page + 1) + '';
                    }else{
                        this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.setClass('disable_color_btn_text');
                    }
                },

                this
            )
        };

        this.set_bookmark = function(){
            _debug('anecdote.set_bookmark');

            this.bookmark_page = this.page;

            stb.load(
                {
                    "type"    : "anecdote",
                    "action"  : "set_bookmark",
                    "anec_id" : this.resp.data.id
                },

                function(result){
                    _debug('anecdote.set_bookmark result', result);

                    this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.delClass();
                    this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.innerHTML = word['anecdote_to_bookmark'] + ' ' + (this.bookmark_page + 1) + '';
                },

                this
            )
        };

        this.to_bookmark = function(){
            _debug('anecdote.to_bookmark');

            if (this.bookmark_page < 0){
                return;
            }

            this.page = this.bookmark_page;

            this.load();
        };

        this.init_quick_page_switch = function(){
            _debug('anecdote.init_quick_page_switch');

            this.quick_page_switch.dom_obj = create_block_element('quick_page_switch');

            //this.quick_page_switch.dom_obj.moveY(300);

            this.quick_page_switch.input = create_block_element('quick_page_input', this.quick_page_switch.dom_obj);

            this.quick_page_switch.dom_obj.hide();
        };

        this.show_quick_page_switch = function(num){
            _debug('anecdote.show_quick_page_switch', num);

            num = num || 0;

            if (!this.quick_page_switch.on){
                this.quick_page_switch.dom_obj.show();
                this.quick_page_switch.on = true;
            }

            if (this.quick_page_switch.input.innerHTML.length <= 4){
                if (this.quick_page_switch.input.innerHTML.length == 0 && num == 0){

                }else{
                    this.quick_page_switch.input.innerHTML = this.quick_page_switch.input.innerHTML + '' + num;
                }
            }

            this.t_hide_quick_page_switch();
        };

        this.quick_go_to_page = function(){
            _debug('anecdote.quick_go_to_page');

            var page_num = parseInt(this.quick_page_switch.input.innerHTML);

            if (page_num < this.total_pages){
                this.page = page_num - 1;
                this.load();
            }
        };

        this.del_quick_go_page = function(){
            _debug('anecdote.del_quick_go_page');

            if (!this.quick_page_switch.on){
                return;
            }

            this.t_hide_quick_page_switch();

            this.quick_page_switch.input.innerHTML = this.quick_page_switch.input.innerHTML.substr(0, this.quick_page_switch.input.innerHTML.length - 1);
        };

        this.t_hide_quick_page_switch = function(){
            _debug('anecdote.t_hide_quick_page_switch');

            window.clearTimeout(this.quick_page_switch.hide_timer);

            var self = this;

            this.quick_page_switch.hide_timer = window.setTimeout(function(){

                self.hide_quick_page_switch();

            }, this.quick_page_switch.hide_to);
        };

        this.hide_quick_page_switch = function(){
            _debug('anecdote.hide_quick_page_switch');

            if (!this.quick_page_switch.on){
                return;
            }

            this.quick_go_to_page();

            this.cancel_quick_page_switch();
        };

        this.cancel_quick_page_switch = function(){
            _debug('anecdote.cancel_quick_page_switch');

            window.clearTimeout(this.quick_page_switch.hide_timer);

            this.quick_page_switch.dom_obj.hide();
            this.quick_page_switch.on = false;

            this.quick_page_switch.input.innerHTML = '';
        };

        this.vshift = function(dir){
            _debug('anecdote.shift', dir);

            var top = this.anecdote_body.scrollTop;

            _debug('top before: ', top);

            if (dir > 0){
                top = top + 40;
            }else{
                top = top - 40;
            }

            this.anecdote_body.scrollTop = top;

            _debug('top after: ', top);
            _debug('this.anecdote_body.scrollTop: ', this.anecdote_body.scrollTop);

            this.scrollbar.refresh();
        };

        this.vshift_page = function(dir){
            _debug('anecdote.vshift_page', dir);

            if (dir > 0){
                this.anecdote_body.scrollTop = this.anecdote_body.scrollTop + 200;
            }else{
                this.anecdote_body.scrollTop = this.anecdote_body.scrollTop - 200;
            }

            this.scrollbar.refresh();
        };

    }

    anecdote_constructor.prototype = new BaseLayer();

    var anecdote = new anecdote_constructor();

    anecdote.init();
    anecdote.init_quick_page_switch();

    anecdote.init_color_buttons([
        {"label" : word['anecdote_goto'], "cmd" : anecdote.show_quick_page_switch},
        {"label" : word['anecdote_like'], "cmd" : anecdote.like},
        {"label" : word['anecdote_bookmark'], "cmd" : anecdote.set_bookmark},
        {"label" : word['anecdote_to_bookmark'], "cmd" : anecdote.to_bookmark}
    ]);

    anecdote.bind();

    anecdote.init_header_path(word['anecdote_title']);

    anecdote.hide();

    module.anecdote = anecdote;

    if (!module.infoportal_sub){
        module.infoportal_sub = [];
    }

    module.infoportal_sub.push({
        "title" : word['anecdote_title'],
        "cmd"   : function(){
            main_menu.hide();
            module.anecdote.show();
        }
    })

})();

loader.next();<commit_msg>Modified color buttons control<commit_after>/**
 * Anecdote module.
 */

(function(){

    function anecdote_constructor(){

        this.layer_name = 'anecdote';

        this.dom_obj = this.create_block('layer_bg');
        document.body.appendChild(this.dom_obj);

        this.superclass = BaseLayer.prototype;

        this.page = 0;
        this.total_pages = 0;

        this.resp = [];

        this.bookmark_page = -1;

        this.quick_page_switch = {"on" : false, "hide_to" : 3000};

        this.init = function(){

            var container = create_block_element('', this.dom_obj);

            var anecdote_body_container = create_block_element('anecdote_body_container', container);

            var info_bar = create_block_element('', anecdote_body_container);

            this.anecdote_date = create_inline_element('date', info_bar);
            this.anecdote_rate = create_inline_element('rate', info_bar);

            this.anecdote_body = create_block_element('anecdote_body', anecdote_body_container);

            this.anecdote_page_bar = create_block_element('anecdote_page_bar', container);

            this.anecdote_left_arrow = create_block_element('anecdote_left_arrow', container);

            this.anecdote_right_arrow = create_block_element('anecdote_right_arrow', container);

            this.scrollbar = new scrollbar(anecdote_body_container, this.anecdote_body, {"height" : 330});
        };

        this.show = function(){
            _debug('anecdote.show');

            this.superclass.show.apply(this);

            this.load();
            this.get_bookmark();
        };

        this.hide = function(){
            _debug('anecdote.hide');

            this.superclass.hide.apply(this);

            if (this.quick_page_switch.on){
                this.cancel_quick_page_switch();
            }

            this.scrollbar && this.scrollbar.reset && this.scrollbar.reset();

            this.anecdote_body.scrollTop = 0;
        };

        this.load = function(){
            _debug('anecdote.load');

            this.set_loading();

            this.scrollbar && this.scrollbar.reset && this.scrollbar.reset();

            stb.load(
                {
                    "type"   : "anecdote",
                    "action" : "get_by_page",
                    "p"      : this.page
                },

                function(result){
                    this.fill(result);
                },

                this
            )
        };

        this.fill = function(resp){
            _debug('anecdote.fill', resp);

            this.resp = resp;

            this.total_pages = this.resp.total_items;

            this.fill_page_bar();

            if (parseInt(this.resp.data.voted) > 0){
                //this.color_buttons[this.color_buttons.getIdxByVal('color', 'green')].text_obj.setClass('disable_color_btn_text');
                this.color_buttons.get('green').disable();
            }else{
                //this.color_buttons[this.color_buttons.getIdxByVal('color', 'green')].text_obj.delClass();
                this.color_buttons.get('green').enable();
            }

            this.anecdote_date.innerHTML = this.resp.data['added'];

            /*var rating = parseInt(this.resp.data['rating']);

            if (rating > 0){
                rating = '+' + rating;
            }

            if (rating == 0){
                rating = '';
            }

            this.anecdote_rate.innerHTML = ' ' + rating;*/

            this.set_rating(this.resp.data['rating']);

            this.anecdote_body.innerHTML = this.resp.data['anec_body'];
        };

        this.set_rating = function(rating){
            _debug('anecdote.set_rating', rating);

            var rating = parseInt(rating);

            if (rating > 0){
                rating = '+' + rating;
            }

            if (rating == 0){
                rating = '';
            }

            this.anecdote_rate.innerHTML = ' ' + rating;
        }

        this.fill_page_bar = function(){
            _debug('anecdote.fill_page_bar');

            this.anecdote_page_bar.innerHTML = word['anecdote_pagebar_title'] + ' ' + (this.page+1) + ' ' + word['layer_from'] + ' ' + this.total_pages + '';
        };

        this.set_loading = function(){
            _debug('anecdote.set_loading');

            this.anecdote_page_bar.innerHTML = word['layer_loading'];
        }

        this.shift_page = function(dir){
            _debug('anecdote.shift_page', dir);

            if (dir>0){

                if (this.page < this.total_pages-1){
                    this.page++;
                }else{
                    this.page = 0;
                }

            }else{
                if (this.page > 0){
                    this.page--;
                }else{
                    this.page = this.total_pages-1;
                }
            }

            this.load();
        };

        this.bind = function(){

            this.shift_page.bind(key.LEFT, this, -1);
            this.shift_page.bind(key.RIGHT, this, 1);

            (function(){

                if (this.quick_page_switch.on){
                    this.hide_quick_page_switch();
                }

            }).bind(key.OK, this);

            (function(){
                this.hide();
                main_menu.show();
            }).bind(key.MENU, this);

            (function(){
                if (this.quick_page_switch.on){
                    this.cancel_quick_page_switch();
                }else{
                    this.hide();
                    main_menu.show();
                }
            }).bind(key.EXIT, this);

            this.show_quick_page_switch.bind(key.NUM1, this, 1);
            this.show_quick_page_switch.bind(key.NUM2, this, 2);
            this.show_quick_page_switch.bind(key.NUM3, this, 3);
            this.show_quick_page_switch.bind(key.NUM4, this, 4);
            this.show_quick_page_switch.bind(key.NUM5, this, 5);
            this.show_quick_page_switch.bind(key.NUM6, this, 6);
            this.show_quick_page_switch.bind(key.NUM7, this, 7);
            this.show_quick_page_switch.bind(key.NUM8, this, 8);
            this.show_quick_page_switch.bind(key.NUM9, this, 9);
            this.show_quick_page_switch.bind(key.NUM0, this, 0);

            (function(){
                if (this.quick_page_switch.on){
                    this.del_quick_go_page();
                }
            }).bind(key.BACK, this);

            this.vshift.bind(key.UP, this, -1);
            this.vshift.bind(key.DOWN, this, 1);

            this.vshift_page.bind(key.PAGE_PREV, this, -1);
            this.vshift_page.bind(key.PAGE_NEXT, this, 1);
        };

        this.like = function(){
            _debug('anecdote.like');

            if (parseInt(this.resp.data['voted']) > 0){
                return;
            }

            //this.color_buttons[this.color_buttons.getIdxByVal('color', 'green')].text_obj.setClass('disable_color_btn_text');
            this.color_buttons.get('green').disable();

            stb.load(
                {
                    "type"    : "anecdote",
                    "action"  : "set_vote",
                    "anec_id" : this.resp.data.id
                },

                function(result){
                    _debug('anecdote.like result', result);

                    this.resp.data['rating'] = parseInt(this.resp.data['rating'])+1;

                    this.set_rating(this.resp.data['rating']);

                },

                this
            );
        };

        this.get_bookmark = function(){
            _debug('anecdote.get_bookmark');

            stb.load(
                {
                    "type"    : "anecdote",
                    "action"  : "get_bookmark"
                },

                function(result){
                    _debug('anecdote.get_bookmark result', result);

                    this.bookmark_page = parseInt(result) - 1;

                    if (this.bookmark_page >= 0){
                        //this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.delClass();
                        //this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.innerHTML = word['anecdote_to_bookmark'] + ' ' + (this.bookmark_page + 1) + '';
                        this.color_buttons.get('blue').enable();
                        this.color_buttons.get('blue').setText( word['anecdote_to_bookmark'] + ' ' + (this.bookmark_page + 1) + '');
                    }else{
                        //this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.setClass('disable_color_btn_text');
                        this.color_buttons.get('blue').disable();
                    }
                },

                this
            )
        };

        this.set_bookmark = function(){
            _debug('anecdote.set_bookmark');

            this.bookmark_page = this.page;

            stb.load(
                {
                    "type"    : "anecdote",
                    "action"  : "set_bookmark",
                    "anec_id" : this.resp.data.id
                },

                function(result){
                    _debug('anecdote.set_bookmark result', result);

                    //this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.delClass();
                    //this.color_buttons[this.color_buttons.getIdxByVal('color', 'blue')].text_obj.innerHTML = word['anecdote_to_bookmark'] + ' ' + (this.bookmark_page + 1) + '';
                    this.color_buttons.get('blue').enable();
                    this.color_buttons.get('blue').setText(word['anecdote_to_bookmark'] + ' ' + (this.bookmark_page + 1) + '');
                },

                this
            )
        };

        this.to_bookmark = function(){
            _debug('anecdote.to_bookmark');

            if (this.bookmark_page < 0){
                return;
            }

            this.page = this.bookmark_page;

            this.load();
        };

        this.init_quick_page_switch = function(){
            _debug('anecdote.init_quick_page_switch');

            this.quick_page_switch.dom_obj = create_block_element('quick_page_switch');

            //this.quick_page_switch.dom_obj.moveY(300);

            this.quick_page_switch.input = create_block_element('quick_page_input', this.quick_page_switch.dom_obj);

            this.quick_page_switch.dom_obj.hide();
        };

        this.show_quick_page_switch = function(num){
            _debug('anecdote.show_quick_page_switch', num);

            num = num || 0;

            if (!this.quick_page_switch.on){
                this.quick_page_switch.dom_obj.show();
                this.quick_page_switch.on = true;
            }

            if (this.quick_page_switch.input.innerHTML.length <= 4){
                if (this.quick_page_switch.input.innerHTML.length == 0 && num == 0){

                }else{
                    this.quick_page_switch.input.innerHTML = this.quick_page_switch.input.innerHTML + '' + num;
                }
            }

            this.t_hide_quick_page_switch();
        };

        this.quick_go_to_page = function(){
            _debug('anecdote.quick_go_to_page');

            var page_num = parseInt(this.quick_page_switch.input.innerHTML);

            if (page_num < this.total_pages){
                this.page = page_num - 1;
                this.load();
            }
        };

        this.del_quick_go_page = function(){
            _debug('anecdote.del_quick_go_page');

            if (!this.quick_page_switch.on){
                return;
            }

            this.t_hide_quick_page_switch();

            this.quick_page_switch.input.innerHTML = this.quick_page_switch.input.innerHTML.substr(0, this.quick_page_switch.input.innerHTML.length - 1);
        };

        this.t_hide_quick_page_switch = function(){
            _debug('anecdote.t_hide_quick_page_switch');

            window.clearTimeout(this.quick_page_switch.hide_timer);

            var self = this;

            this.quick_page_switch.hide_timer = window.setTimeout(function(){

                self.hide_quick_page_switch();

            }, this.quick_page_switch.hide_to);
        };

        this.hide_quick_page_switch = function(){
            _debug('anecdote.hide_quick_page_switch');

            if (!this.quick_page_switch.on){
                return;
            }

            this.quick_go_to_page();

            this.cancel_quick_page_switch();
        };

        this.cancel_quick_page_switch = function(){
            _debug('anecdote.cancel_quick_page_switch');

            window.clearTimeout(this.quick_page_switch.hide_timer);

            this.quick_page_switch.dom_obj.hide();
            this.quick_page_switch.on = false;

            this.quick_page_switch.input.innerHTML = '';
        };

        this.vshift = function(dir){
            _debug('anecdote.shift', dir);

            var top = this.anecdote_body.scrollTop;

            _debug('top before: ', top);

            if (dir > 0){
                top = top + 40;
            }else{
                top = top - 40;
            }

            this.anecdote_body.scrollTop = top;

            _debug('top after: ', top);
            _debug('this.anecdote_body.scrollTop: ', this.anecdote_body.scrollTop);

            this.scrollbar.refresh();
        };

        this.vshift_page = function(dir){
            _debug('anecdote.vshift_page', dir);

            if (dir > 0){
                this.anecdote_body.scrollTop = this.anecdote_body.scrollTop + 200;
            }else{
                this.anecdote_body.scrollTop = this.anecdote_body.scrollTop - 200;
            }

            this.scrollbar.refresh();
        };

    }

    anecdote_constructor.prototype = new BaseLayer();

    var anecdote = new anecdote_constructor();

    anecdote.init();
    anecdote.init_quick_page_switch();

    anecdote.init_color_buttons([
        {"label" : word['anecdote_goto'], "cmd" : anecdote.show_quick_page_switch},
        {"label" : word['anecdote_like'], "cmd" : anecdote.like},
        {"label" : word['anecdote_bookmark'], "cmd" : anecdote.set_bookmark},
        {"label" : word['anecdote_to_bookmark'], "cmd" : anecdote.to_bookmark}
    ]);

    anecdote.bind();

    anecdote.init_header_path(word['anecdote_title']);

    anecdote.hide();

    module.anecdote = anecdote;

    if (!module.infoportal_sub){
        module.infoportal_sub = [];
    }

    module.infoportal_sub.push({
        "title" : word['anecdote_title'],
        "cmd"   : function(){
            main_menu.hide();
            module.anecdote.show();
        }
    })

})();

loader.next();<|endoftext|>


<commit_before>var CafeMapper = Class.create();
CafeMapper.activate = function(){
	if (!$('__barista__')){
		var e = new Element("div", {id: "__barista__"})
		e.style.display = "none";
		document.body.appendChild(e);
		CafeMapper.element = e;
	}
}
CafeMapper.Model = {}

CafeMapper.DataObject = Class.create({

	/**
	   *  new CafeMapper.DataObject(data)
	   *  - data (Object): An object/ Hash of information
	   *  to populate the object with.
	   *
	   *  Creates a new `CafeMapper.DataObject`.
	  **/
	initialize: function(data){
		Object.extend(this, data);

		// Set/Reset the expiration date as a string an as an Date object.
		if (this.expires_at == undefined){
			this._expires_at = (1).minutes().fromNow().toString();
			this.expires_at = Date.parse(this._expires_at);
  		}
		if (!this.id){this.model.uuid = uuid();}

		// If the the object has expired, refresh it.
		if (this.expires_at < new Date() && (typeof this.refresh == 'function')){
		    this.refresh(this);
		}
	},
	identify: function(){
	   	if (!this.id){return this.model.uuid} else {return this.id}
	},
	store: function(){
    	this._store();
		CafeMapper.element.fire("stored:"+this.model.klass.toLowerCase()+"."+this.id);
	},
	Store: function(){
		this._store();
	},
	_store: function(){
		if (this.id != undefined){
			return localStorage.setItem(this.model.klass+'.'+this.id, JSON.stringify(this));
		}else{
			return localStorage.setItem(this.model.klass+'.'+this.model.uuid, JSON.stringify(this));
		}
	}

});

CafeMapper.ServerCommunication = {
	receiveUpdate: function(data){
		Object.extend(this, data);
		this._expires_at = (1).minutes().fromNow().toString();
		this.expires_at = Date.parse(this._expires_at);
		this.store();
		$('app_element').fire("updated:"+this.model.klass.toLowerCase()+"."+this.id);
	},
	refresh: function(){
		CafeMapper.DataObject.refresh(this);
		CafeMapper.element.fire("refreshing:"+this.model.klass.toLowerCase()+"."+this.id);
	}
}

CafeMapper.ElementMethods = {
	wakeDataObject: function(element){
		element = $(element);
		return Reservation.get(element.retrieve('reservation_id'));
	},
	linkBooking: function(element, reservation_id){
		element = $(element);
		element.store('reservation_id', reservation_id);
		element.addClassName('_reservation');
		id = reservation_id;
		elementid = element.identify();
		$('app_element').observe(("updated:reservation."+id), function(){
			Reservation.update_element(id, elementid);
		});
	},
	update_element: function(element){
		var tag = element.tagName.toLowerCase();
		var f = this['render_'+tag].bind(this);
		if (typeof f == "function"){
			element.update(f());
		} else {
			console.warn("Unable to update Element#id:" + element.identify()+". " + this.model.klass + "#render_"+tag+ "() is not defined.");
		}
	},
};

CafeMapper.Model.initAs = function(klass, options){
	_options = {
		model: {
			klass: klass,
			serverPrefix: "",
		},
	}
	Object.extend(_options, options);
	_options.model.klass = klass;
	var c = Class.create(CafeMapper.DataObject, _options);
	c.klassName = klass;
	c.get = CafeMapper.DataObject.get
	c.createStub = CafeMapper.DataObject.createStub
	c.initObjectWithData = CafeMapper.DataObject.initObjectWithData
	c.include = c.addMethods
	return c
}

$MODEL = CafeMapper.Model.initAs

CafeMapper.DataObject.refresh = function(dobject){
	new Ajax.Request(dobject.model.serverPrefix+'/'+dobject.model.klass.toLowerCase()+"/"+dobject.id+".json", {
		method: "get",
		onSuccess: function(transport){
			var data = transport.responseText.evalJSON();
			dobject.receiveUpdate(data);
		},
		onFailure: function(){
			console.warn("Unable to refresh object.");
		}
	});
}

CafeMapper.DataObject.initObjectWithData = function(data){
	var o = new this(data);
	o.store();
	return o;
}

CafeMapper.DataObject.createStub = function(id){
	return this.initObjectWithData(this.stub);
}

CafeMapper.DataObject.get = function(id){
   var id = id;
   var data = JSON.parse(localStorage.getItem(this.klassName+'.'+id));
	if (data == null){
		return this.stub(id);
	} else {
		return this.initObjectWithData(data);
	}
}<commit_msg>Modified CafeMapper::DataObject.include to allow for triggering a callback.<commit_after>var CafeMapper = Class.create();
CafeMapper.activate = function(){
	if (!$('__barista__')){
		var e = new Element("div", {id: "__barista__"})
		e.style.display = "none";
		document.body.appendChild(e);
		CafeMapper.element = e;
	}
}
CafeMapper.Model = {}

CafeMapper.DataObject = Class.create({

	/**
	   *  new CafeMapper.DataObject(data)
	   *  - data (Object): An object/ Hash of information
	   *  to populate the object with.
	   *
	   *  Creates a new `CafeMapper.DataObject`.
	  **/
	initialize: function(data){
		Object.extend(this, data);

		// Set/Reset the expiration date as a string an as an Date object.
		if (this.expires_at == undefined){
			this._expires_at = (1).minutes().fromNow().toString();
			this.expires_at = Date.parse(this._expires_at);
  		}
		if (!this.id){this.model.uuid = uuid();}

		// If the the object has expired, refresh it.
		if (this.expires_at < new Date() && (typeof this.refresh == 'function')){
		    this.refresh(this);
		}
	},
	identify: function(){
	   	if (!this.id){return this.model.uuid} else {return this.id}
	},
	store: function(){
    	this._store();
		CafeMapper.element.fire("stored:"+this.model.klass.toLowerCase()+"."+this.id);
	},
	STORE: function(){
		this._store();
	},
	_save: function(){

	},
	save: function(){
		this._save();
	},
	SAVE: function(){

	},
	_store: function(){
		if (this.id != undefined){
			return localStorage.setItem(this.model.klass+'.'+this.id, JSON.stringify(this));
		}else{
			return localStorage.setItem(this.model.klass+'.'+this.model.uuid, JSON.stringify(this));
		}
	}

});

CafeMapper.ServerCommunication = {
	receiveUpdate: function(data){
		Object.extend(this, data);
		this._expires_at = (1).minutes().fromNow().toString();
		this.expires_at = Date.parse(this._expires_at);
		this.store();
		$('app_element').fire("updated:"+this.model.klass.toLowerCase()+"."+this.id);
	},
	refresh: function(){
		CafeMapper.DataObject.refresh(this);
		CafeMapper.element.fire("refreshing:"+this.model.klass.toLowerCase()+"."+this.id);
	}
}

CafeMapper.ElementMethods = {
	wakeDataObject: function(element){
		element = $(element);
		return Reservation.get(element.retrieve('reservation_id'));
	},
	linkBooking: function(element, reservation_id){
		element = $(element);
		element.store('reservation_id', reservation_id);
		element.addClassName('_reservation');
		id = reservation_id;
		elementid = element.identify();
		$('app_element').observe(("updated:reservation."+id), function(){
			Reservation.update_element(id, elementid);
		});
	},
	update_element: function(element){
		var tag = element.tagName.toLowerCase();
		var f = this['render_'+tag].bind(this);
		if (typeof f == "function"){
			element.update(f());
		} else {
			console.warn("Unable to update Element#id:" + element.identify()+". " + this.model.klass + "#render_"+tag+ "() is not defined.");
		}
	},
};

CafeMapper.Model.initAs = function(klass, options){
	_options = {
		model: {
			klass: klass,
			serverPrefix: "",
		},
	}
	Object.extend(_options, options);
	_options.model.klass = klass;
	var c = Class.create(CafeMapper.DataObject, _options);
	c.klassName = klass;
	c.get = CafeMapper.DataObject.get
	c.createStub = CafeMapper.DataObject.createStub
	c.initObjectWithData = CafeMapper.DataObject.initObjectWithData
	c.include = function(klass){
		if (typeof klass.includer == "function"){
			klass.includer();
		}
		c.addMethods(klass);
	}
	return c
}

$MODEL = CafeMapper.Model.initAs

CafeMapper.DataObject.refresh = function(dobject){
	new Ajax.Request(dobject.model.serverPrefix+'/'+dobject.model.klass.toLowerCase()+"/"+dobject.id+".json", {
		method: "get",
		onSuccess: function(transport){
			var data = transport.responseText.evalJSON();
			dobject.receiveUpdate(data);
		},
		onFailure: function(){
			console.warn("Unable to refresh object.");
		}
	});
}

CafeMapper.DataObject.initObjectWithData = function(data){
	var o = new this(data);
	o.store();
	return o;
}

CafeMapper.DataObject.createStub = function(id){
	return this.initObjectWithData(this.stub);
}

CafeMapper.DataObject.get = function(id){
   var id = id;
   var data = JSON.parse(localStorage.getItem(this.klassName+'.'+id));
	if (data == null){
		return this.stub(id);
	} else {
		return this.initObjectWithData(data);
	}
}<|endoftext|>


<commit_before>function pushCharacter(character) {
    var input = document.querySelector("#display");
    input.value = input.value + character;
};
function calculate() {
    var input = document.querySelector("#display");
    input.value = eval(input.value).toString();
};
function clear() {
    var input = document.querySelector("#display");
    input.value = "";
};

window.onload = function() {
    var buttons = document.querySelectorAll(".button");
    var button;
    for (var i = 0; i < buttons.length; i++) {
        button = buttons[i];
        button.onclick = function() { pushCharacter(button.innerHTML); }
    };

    var equalbutton = document.querySelector(".button-equals");
    equalbutton.onclick = calculate;

    var clearbutton = document.querySelector(".clearbutton");
    clearbutton.onclick = clear;
}
<commit_msg>js...<commit_after>function pushCharacter(character) {
    var input = document.querySelector("#display");
    input.value = input.value + character;
    console.log(character);
};
function calculate() {
    var input = document.querySelector("#display");
    input.value = eval(input.value).toString();
};
function clear() {
    var input = document.querySelector("#display");
    input.value = "";
};

window.onload = function() {
    var buttons = document.querySelectorAll(".button");
    for (var i = 0; i < buttons.length; i++) {
        var button = buttons[i];
        button.addEventListener("click", function() { pushCharacter(button.innerHTML); });
    };

    var equalbutton = document.querySelector(".button-equals");
    equalbutton.onclick = calculate;

    var clearbutton = document.querySelector(".clearbutton");
    clearbutton.onclick = clear;
}
<|endoftext|>


<commit_before>var cssId = 'CSSelement';
if (!document.getElementById(CSSelement))
{
    var head  = document.getElementsByTagName('head')[0];
    var link  = document.createElement('link');
    link.id   = cssId;
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = './stylesheet.css';
    link.media = 'all';
    head.appendChild(link);
}

//Hides and Shows
hideElement(){
  document.getElementById('id').classList.add('hideElement');
  document.getElementById('id').classList.remove('showElement');
}
showElement(){
  document.getElementById('id').classList.add('showElement');
  document.getElementById('id').classList.remove('hideElement');
}
<commit_msg>Fixed to classes<commit_after>var cssId = 'CSSelement';
if (!document.getElementById(CSSelement))
{
    var head  = document.getElementsByTagName('head')[0];
    var link  = document.createElement('link');
    link.id   = cssId;
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = './stylesheet.css';
    link.media = 'all';
    head.appendChild(link);
}

//Hides and Shows
hideElement(){
  document.getElementByClassName('hideElement').classList.add('hideElement');
  document.getElementByClassName('hideElement').classList.remove('showElement');
}
showElement(){
  document.getElementByClassName('showElement').classList.add('showElement');
  document.getElementByClassName('showElement').classList.remove('hideElement');
}
<|endoftext|>


<commit_before>/*
**  grunt-bower-install-simple -- Grunt Task for Installing Bower Dependencies
**  Copyright (c) 2013 Ralf S. Engelschall <rse@engelschall.com>
**
**  Permission is hereby granted, free of charge, to any person obtaining
**  a copy of this software and associated documentation files (the
**  "Software"), to deal in the Software without restriction, including
**  without limitation the rights to use, copy, modify, merge, publish,
**  distribute, sublicense, and/or sell copies of the Software, and to
**  permit persons to whom the Software is furnished to do so, subject to
**  the following conditions:
**
**  The above copyright notice and this permission notice shall be included
**  in all copies or substantial portions of the Software.
**
**  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
**  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
**  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
**  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
**  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
**  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
**  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/* global module:  false */
/* global require: false */
/* global process: false */

/*  foreign modules  */
var chalk         = require("chalk");
var bower         = require("bower");
var bowerRenderer = require("bower/lib/renderers/StandardRenderer");

module.exports = function (grunt) {
    grunt.registerTask("bower-install-simple", "Install Bower Dependencies", function () {
        /*  prepare options  */
        var options = this.options({
            /*  bower configuration options (renderer specific)  */
            color:        true,               /*  bower --config.color=true        */
            cwd:          process.cwd(),      /*  bower --config.cwd=`pwd`         */

            /*  bower install command options  */
            forceLatest:  false,              /*  bower install --force-latest     */
            production:   false,              /*  bower install --production       */

            /*  bower configuration options (general)  */
            interactive:  true,               /*  bower --config.interactive=true  */
            directory:    undefined           /*  bower --config.directory=<dir>   */
        });
        grunt.verbose.writeflags(options, "Options");

        /*  display header to explicitly inform user about our operation  */
        if (options.color)
            grunt.log.writeln(chalk.green("Install Bower Dependencies"));
        else
            grunt.log.writeln("Install Bower Dependencies");

        /*  run programatically the functionality behind
            the official "bower install" command  */
        var done = this.async();
        var renderer = new bowerRenderer("install", {
            color:          options.color,
            cwd:            options.cwd
        });
        bower.commands.install([], {
            "force-latest": options.forceLatest,
            production:     options.production
        }, {
            interactive:    options.interactive,
            directory:      options.directory,
        })
        .on("log", function (log) {
            renderer.log(log);
        })
        .on("prompt", function (prompt, callback) {
            renderer.prompt(prompt).then(function(answer) {
                callback(answer);
            });
        })
        .on("error", function (err) {
            renderer.error(err);
            done(false);
        })
        .on("end", function (data) {
            renderer.end(data);
            done();
        });
    });
};

<commit_msg>make ESLint happy, too<commit_after>/*
**  grunt-bower-install-simple -- Grunt Task for Installing Bower Dependencies
**  Copyright (c) 2013 Ralf S. Engelschall <rse@engelschall.com>
**
**  Permission is hereby granted, free of charge, to any person obtaining
**  a copy of this software and associated documentation files (the
**  "Software"), to deal in the Software without restriction, including
**  without limitation the rights to use, copy, modify, merge, publish,
**  distribute, sublicense, and/or sell copies of the Software, and to
**  permit persons to whom the Software is furnished to do so, subject to
**  the following conditions:
**
**  The above copyright notice and this permission notice shall be included
**  in all copies or substantial portions of the Software.
**
**  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
**  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
**  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
**  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
**  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
**  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
**  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

/* global module:  false */
/* global require: false */
/* global process: false */

/*  foreign modules  */
var chalk         = require("chalk");
var bower         = require("bower");
var bowerRenderer = require("bower/lib/renderers/StandardRenderer");

module.exports = function (grunt) {
    grunt.registerTask("bower-install-simple", "Install Bower Dependencies", function () {
        /*  prepare options  */
        var options = this.options({
            /*  bower configuration options (renderer specific)  */
            color:        true,               /*  bower --config.color=true        */
            cwd:          process.cwd(),      /*  bower --config.cwd=`pwd`         */

            /*  bower install command options  */
            forceLatest:  false,              /*  bower install --force-latest     */
            production:   false,              /*  bower install --production       */

            /*  bower configuration options (general)  */
            interactive:  true,               /*  bower --config.interactive=true  */
            directory:    undefined           /*  bower --config.directory=<dir>   */
        });
        grunt.verbose.writeflags(options, "Options");

        /*  display header to explicitly inform user about our operation  */
        if (options.color)
            grunt.log.writeln(chalk.green("Install Bower Dependencies"));
        else
            grunt.log.writeln("Install Bower Dependencies");

        /*  run programatically the functionality behind
            the official "bower install" command  */
        var done = this.async();
        var renderer = new bowerRenderer("install", {
            color:          options.color,
            cwd:            options.cwd
        });
        bower.commands.install([], {
            "force-latest": options.forceLatest,
            production:     options.production
        }, {
            interactive:    options.interactive,
            directory:      options.directory
        })
        .on("log", function (log) {
            renderer.log(log);
        })
        .on("prompt", function (prompt, callback) {
            renderer.prompt(prompt).then(function(answer) {
                callback(answer);
            });
        })
        .on("error", function (err) {
            renderer.error(err);
            done(false);
        })
        .on("end", function (data) {
            renderer.end(data);
            done();
        });
    });
};

<|endoftext|>


<commit_before>//Clean a dom node
let resetDOMNode = function (parent) {
    while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
    }
};
//Add a new dom node
let addDOMNode = function (parent, tag, attr, text) {
    let element = document.createElement(tag.toUpperCase());
    Object.keys(attr).forEach(function (key) {
        if (key === "className") {
            element.className = attr.className;
        }
        else {
            element.setAttribute(key, attr[key]);
        }
    });
    if (typeof text === "string") {
        element.textContent = text;
    }
    parent.appendChild(element);
    return element;
};
//Initialize the search box listener
let initSearchBox = function (searchInput, searchSubmit, searchPage) {
    //Submit the search
    let redirectToSearch = function () {
        let str = document.getElementById(searchInput).value;
        if (typeof str !== "string" || str.length > 0) {
            let redirectUrl = searchPage + "#query=" + window.encodeURIComponent(str);
            //console.log(redirectUrl);
            window.location.href = redirectUrl;
        }
    };
    //Enter key listener
    document.getElementById(searchInput).addEventListener("keydown", function (event) {
        if (event.keyCode === 13) {
            return redirectToSearch();
        }
    });
    //Submit button press
    document.getElementById(searchSubmit).addEventListener("click", function () {
        return redirectToSearch();
    });
};

//Initialize the main search component
let initSearchPage = function (searchInput, searchSubmit, searchResults, searchContent) {
    //Search on content
    let search = function (str) {
        console.log("Search string: " + str);
        //Split the search string by spaces
        //let searchItems = str.trim().toLowerCase().split(" ");
        let parent = document.getElementById(searchResults);
        resetDOMNode(parent);
        let countResults = 0;
        //Append the results count
        let countElement = addDOMNode(parent, "div", {"className": "sd-search-results-count", "id": "search-results-count"}, "");
        //Find items in the search content array
        searchContent.forEach(function (item) {
            let name = item.name.toLowerCase();
            let description = item.description.toLowerCase();
            let keywords = item.keywords.toLowerCase();
            if (name.indexOf(str) !== -1 || description.indexOf(str) !== -1 || keywords.indexOf(str) !== -1) {
                let container = addDOMNode(parent, "a", {"className": "sd-search-results-item", "href": item.url}, null);
                addDOMNode(container, "div", {"className": "sd-search-results-item-name"}, item.name);
                addDOMNode(container, "div", {"className": "sd-search-results-item-url"}, item.url);
                addDOMNode(container, "div", {"className": "sd-search-results-item-description"}, item.description);
                //Increment the results counter
                countResults = countResults + 1;
            }
        });
        //Save the number of results
        countElement.textContent = "" + countResults + " results found";
    };
    //Change the hash
    let updateHash = function () {
        let str = document.getElementById(searchInput).value;
        if (str.length > 0) {
            window.location.hash = "#query=" + window.encodeURIComponent(str);
        }
    };
    //Extract from hash
    let extractHash = function () {
        let str = window.location.hash.substr(1);
        let findStr = "query="
        if (str.indexOf(findStr) === 0 && str.length > findStr.length ) {
            let decodedStr = window.decodeURIComponent(str.replace(findStr, ""));
            return search(decodedStr.toLowerCase());
        }
    };
    //Register the hash change listener
    window.addEventListener("hashchange", function () {
        return extractHash();
    });
    //Enter key listener
    document.getElementById(searchInput).addEventListener("keydown", function (event) {
        if (event.keyCode === 13) {
            return updateHash();
        }
    });
    //Submit button press
    document.getElementById(searchSubmit).addEventListener("click", function () {
        return updateHash();
    });
    //Extract the hash the first time
    return extractHash();
};

<commit_msg>Removed unused<commit_after><|endoftext|>


<commit_before>"use strict";

var React = require("react");

var sizerStyle = { position: "absolute", visibility: "hidden", height: 0, width: 0, overflow: "scroll", whiteSpace: "nowrap" };

var AutosizeInput = React.createClass({

  displayName: "AutosizeInput",

  propTypes: {
    value: React.PropTypes.any, // field value
    defaultValue: React.PropTypes.any, // default field value
    onChange: React.PropTypes.func, // onChange handler: function(newValue) {}
    style: React.PropTypes.object, // css styles for the outer element
    className: React.PropTypes.string, // className for the outer element
    inputStyle: React.PropTypes.object, // css styles for the input element
    inputClassName: React.PropTypes.string // className for the input element
  },

  getDefaultProps: function () {
    return {
      minWidth: 1
    };
  },

  getInitialState: function () {
    return {
      inputWidth: this.props.minWidth
    };
  },

  componentDidMount: function () {
    this.copyInputStyles();
    this.updateInputWidth();
  },

  componentDidUpdate: function () {
    this.updateInputWidth();
  },

  copyInputStyles: function () {
    if (!this.isMounted() || !window.getComputedStyle) {
      return;
    }
    var inputStyle = window.getComputedStyle(this.refs.input.getDOMNode());
    var widthNode = this.refs.sizer.getDOMNode();
    widthNode.style.fontSize = inputStyle.fontSize;
    widthNode.style.fontFamily = inputStyle.fontFamily;
  },

  updateInputWidth: function () {
    if (!this.isMounted()) {
      return;
    }
    var newInputWidth = this.refs.sizer.getDOMNode().scrollWidth + 2;
    if (newInputWidth < this.props.minWidth) {
      newInputWidth = this.props.minWidth;
    }
    if (newInputWidth !== this.state.inputWidth) {
      this.setState({
        inputWidth: newInputWidth
      });
    }
  },

  getInput: function () {
    return this.refs.input;
  },

  focus: function () {
    this.refs.input.getDOMNode().focus();
  },

  select: function () {
    this.refs.input.getDOMNode().select();
  },

  render: function () {
    var nbspValue = (this.props.value || "").replace(/ /g, " ");

    var wrapperStyle = this.props.style || {};
    wrapperStyle.display = "inline-block";

    var inputStyle = this.props.inputStyle || {};
    inputStyle.width = this.state.inputWidth;

    return React.createElement(
      "div",
      { className: this.props.className, style: wrapperStyle },
      React.createElement("input", React.__spread({}, this.props, { ref: "input", className: this.props.inputClassName, style: inputStyle })),
      React.createElement("div", { ref: "sizer", style: sizerStyle, dangerouslySetInnerHTML: { __html: nbspValue } })
    );
  }

});

module.exports = AutosizeInput;<commit_msg>Add placeholder sizing<commit_after>"use strict";

var React = require("react");

var sizerStyle = { position: "absolute", visibility: "hidden", height: 0, width: 0, overflow: "scroll", whiteSpace: "nowrap" };

var AutosizeInput = React.createClass({

  displayName: "AutosizeInput",

  propTypes: {
    value: React.PropTypes.any, // field value
    defaultValue: React.PropTypes.any, // default field value
    onChange: React.PropTypes.func, // onChange handler: function(newValue) {}
    style: React.PropTypes.object, // css styles for the outer element
    className: React.PropTypes.string, // className for the outer element
    inputStyle: React.PropTypes.object, // css styles for the input element
    inputClassName: React.PropTypes.string // className for the input element
  },

  getDefaultProps: function () {
    return {
      minWidth: 1
    };
  },

  getInitialState: function () {
    return {
      inputWidth: this.props.minWidth
    };
  },

  componentDidMount: function () {
    this.copyInputStyles();
    this.updateInputWidth();
  },

  componentDidUpdate: function () {
    this.updateInputWidth();
  },

  copyInputStyles: function () {
    if (!this.isMounted() || !window.getComputedStyle) {
      return;
    }
    var inputStyle = window.getComputedStyle(this.refs.input.getDOMNode());
    var widthNode = this.refs.sizer.getDOMNode();
    widthNode.style.fontSize = inputStyle.fontSize;
    widthNode.style.fontFamily = inputStyle.fontFamily;

    if (this.props.placeholder) {
      widthNode = this.refs.placeholderSizer.getDOMNode();
      widthNode.style.fontSize = inputStyle.fontSize;
      widthNode.style.fontFamily = inputStyle.fontFamily;
    }
  },

  updateInputWidth: function () {
    if (!this.isMounted()) {
      return;
    }
    var newInputWidth;
    if (this.props.placeholder) {
      newInputWidth = Math.max(this.refs.sizer.getDOMNode().scrollWidth, this.refs.placeholderSizer.getDOMNode().scrollWidth) + 2;
    } else {
      newInputWidth = this.refs.sizer.getDOMNode().scrollWidth + 2;
    }

    if (newInputWidth < this.props.minWidth) {
      newInputWidth = this.props.minWidth;
    }
    if (newInputWidth !== this.state.inputWidth) {
      this.setState({
        inputWidth: newInputWidth
      });
    }
  },

  getInput: function () {
    return this.refs.input;
  },

  focus: function () {
    this.refs.input.getDOMNode().focus();
  },

  select: function () {
    this.refs.input.getDOMNode().select();
  },

  render: function () {
    var nbspValue = (this.props.value || "").replace(/ /g, " ");

    var wrapperStyle = this.props.style || {};
    wrapperStyle.display = "inline-block";

    var inputStyle = this.props.inputStyle || {};
    inputStyle.width = this.state.inputWidth;

    if (this.props.placeholder)
      var placeholder = React.createElement("div", { ref: "placeholderSizer", style: sizerStyle }, this.props.placeholder);

    return React.createElement(
      "div",
      { className: this.props.className, style: wrapperStyle },
      React.createElement("input", React.__spread({}, this.props, { ref: "input", className: this.props.inputClassName, style: inputStyle })),
      React.createElement("div", { ref: "sizer", style: sizerStyle, dangerouslySetInnerHTML: { __html: nbspValue } }),
      placeholder
    );
  }

});

module.exports = AutosizeInput;
<|endoftext|>


<commit_before>module.exports = function(req, res, next){
    "use strict";
    var Strings = require('../../../strings'),
        Response = require('../../helpers/response'),
        content = require('../../../entities/content'),
        strings = new Strings('en'),
        response = new Response()

    function onGetContent(err, doc){
        if(err){
            response.write(response.STATUS_CODES.NOT_FOUND, JSON.stringify(err), res);
        }
        else {
            if(doc.node && doc.node._id){
                req.parent = doc.node._id.toString();
            }

            next();
        }
    }

    content.getById(req.params.id, onGetContent);
};<commit_msg>Updated the content parent algorithm to handle the post scenario.<commit_after>module.exports = function(req, res, next){
    "use strict";
    var Strings = require('../../../strings'),
        Response = require('../../helpers/response'),
        content = require('../../../entities/content'),
        strings = new Strings('en'),
        response = new Response()

    function onGetContent(err, doc){
        if(err){
            if(req.body.node && req.body.node._id){
                req.parent = req.body.node._id;
            }
        }
        else {
            if(doc.node && doc.node._id){
                req.parent = doc.node._id.toString();
            }
        }

        next();
    }

    content.getById(req.params.id, onGetContent);
};<|endoftext|>