<commit_before>Module.register('MMM-cryptocurrency', {
    result: {},
    defaults: {
        currency: ['bitcoin'],
        conversion: 'USD',
        showUSD: false,
        displayLongNames: false,
        headers: [],
        displayTpe: 'detail',
        showGraphs: false,
        logoHeaderText: 'Crypto currency',
        significantDigits: 2,
        coloredLogos: false,
        fontSize: 'xx-large'
    },

    sparklineIds: {
        bitcoin: 1,
        ethereum: 1027,
        ripple: 52,
        litecoin: 2,
        'ethereum-classic': 1321,
        nem: 873,
        stratis: 1343,
        'bitcoin-cash': 1831,
        'bitcoin-gold': 2083,
        cardano: 2010,
        dash: 131,
        eos: 1765,
        monero: 328,
        neo: 1376,
        stellar: 512,
        iota: 1720,
        tron: 1958,
        qtum: 1684
    },

    start: function() {
        this.getTicker()
        this.scheduleUpdate()
    },

    getStyles: function() {
        return ['MMM-cryptocurrency.css']
    },

    getTicker: function() {
        var conversion = this.config.conversion
        var url = 'https://api.coinmarketcap.com/v1/ticker/?convert=' + conversion + '&limit=100'
        this.sendSocketNotification('get_ticker', url)
    },

    scheduleUpdate: function() {
        var self = this
            // Refresh time should not be less than 5 minutes
        var delay = 300000
        setInterval(function() {
            self.getTicker()
        }, delay)
    },

    getDom: function() {
        if (this.config.displayType == 'logo' || this.config.displayType == 'logoWithChanges') {
            this.folder = (this.config.coloredLogos ? 'colored/' : 'black-white/')
            return this.buildIconView(this.result, this.config.displayType)
        }
        var data = this.result

        var wrapper = document.createElement('table')
        wrapper.className = 'small mmm-cryptocurrency'

        var tableHeader = document.createElement('tr')
        tableHeader.className = 'header-row'

        var tableHeaderValues = [
            this.translate('CURRENCY'),
            this.translate('PRICE')
        ]
        if (this.config.headers.indexOf('change1h') > -1) {
            tableHeaderValues.push(this.translate('CHANGE') + ' (1h)')
        }
        if (this.config.headers.indexOf('change24h') > -1) {
            tableHeaderValues.push(this.translate('CHANGE') + ' (24h)')
        }
        if (this.config.headers.indexOf('change7d') > -1) {
            tableHeaderValues.push(this.translate('CHANGE') + ' (7d)')
        }
        for (var i = 0; i < tableHeaderValues.length; i++) {
            var tableHeadSetup = document.createElement('th')
            tableHeadSetup.innerHTML = tableHeaderValues[i]
            tableHeader.appendChild(tableHeadSetup)
        }
        wrapper.appendChild(tableHeader)

        for (i = 0; i < data.length; i++) {
            var currentCurrency = data[i]
            var trWrapper = document.createElement('tr')
            trWrapper.className = 'currency'
            var name
            if (this.config.displayLongNames) {
                name = currentCurrency.name
            } else {
                name = currentCurrency.symbol
            }

            var tdValues = [
                name,
                currentCurrency.price,
            ]
            if (this.config.headers.indexOf('change1h') > -1) {
                tdValues.push(currentCurrency.percent_change_1h + '%')
            }
            if (this.config.headers.indexOf('change24h') > -1) {
                tdValues.push(currentCurrency.percent_change_24h + '%')
            }
            if (this.config.headers.indexOf('change7d') > -1) {
                tdValues.push(currentCurrency.percent_change_7d + '%')
            }

            for (var j = 0; j < tdValues.length; j++) {
                var tdWrapper = document.createElement('td')
                let currValue = tdValues[j]
                // If I am showing value then set color
                if (currValue.includes('%')) {
                    tdWrapper.style.color = this.colorizeChange(currValue.slice(0,-1))
                }
                tdWrapper.innerHTML = currValue
                trWrapper.appendChild(tdWrapper)
            }
            wrapper.appendChild(trWrapper)
        }
        return wrapper
    },

    socketNotificationReceived: function(notification, payload) {
        if (notification === 'got_result') {
            this.result = this.getWantedCurrencies(this.config.currency, payload)
            this.updateDom()
        }
    },

    /**
     * Returns configured currencies
     *
     * @param chosenCurrencies
     * @param apiResult
     * @returns {Array}
     */
    getWantedCurrencies: function(chosenCurrencies, apiResult) {
        var filteredCurrencies = []
        for (var i = 0; i < chosenCurrencies.length; i++) {
            for (var j = 0; j < apiResult.length; j++) {
                var userCurrency = chosenCurrencies[i]
                var remoteCurrency = apiResult[j]
                if (userCurrency == remoteCurrency.id) {
                    remoteCurrency = this.formatPrice(remoteCurrency)
                    filteredCurrencies.push(remoteCurrency)
                }
            }
        }
        return filteredCurrencies
    },

    /**
     * Formats the price of the API result and adds it to the object with simply .price as key
     * instead of price_eur
     *
     * @param apiResult
     * @returns {*}
     */
    formatPrice: function(apiResult) {
        var rightCurrencyFormat = this.config.conversion.toLowerCase()

        // rounding the price in Conversion
        var unroundedPrice = apiResult['price_' + rightCurrencyFormat]
        var digitsBeforeDecimalPoint = Math.floor(unroundedPrice).toString().length
        var requiredDigitsAfterDecimalPoint = Math.max(this.config.significantDigits - digitsBeforeDecimalPoint, 2)
        var price = this.roundNumber(unroundedPrice, requiredDigitsAfterDecimalPoint)
        console.log("config.language: " + config.language);

        // add the currency string
        apiResult['price'] = price.toLocaleString(config.language, { style: 'currency', currency: this.config.conversion })
        if (rightCurrencyFormat != 'usd' && this.config.showUSD) {
            // rounding the priceUSD
            var unroundedPriceUSD = apiResult['price_usd']
            var digitsBeforeDecimalPointUSD = Math.floor(unroundedPriceUSD).toString().length
            var requiredDigitsAfterDecimalPointUSD = Math.max(this.config.significantDigits - digitsBeforeDecimalPointUSD, 2)
            var priceUSD = this.roundNumber(unroundedPriceUSD, requiredDigitsAfterDecimalPointUSD)
            apiResult['price'] += ' / ' + priceUSD.toLocaleString(config.language, { style: 'currency', currency: 'USD' })
        }

        return apiResult
    },

    /**
     * Rounds a number to a given number of digits after the decimal point
     *
     * @param number
     * @param precision
     * @returns {number}
     */
    roundNumber: function(number, precision) {
        var factor = Math.pow(10, precision)
        var tempNumber = number * factor
        var roundedTempNumber = Math.round(tempNumber)
        return roundedTempNumber / factor
    },

    /**
     * Creates the icon view type
     *
     * @param apiResult
     * @param displayType
     * @returns {Element}
     */
    buildIconView: function(apiResult, displayType) {
        var wrapper = document.createElement('div')
        var header = document.createElement('header')
        header.className = 'module-header'
        header.innerHTML = this.config.logoHeaderText
        if (this.config.logoHeaderText !== '') {
            wrapper.appendChild(header)
        }

        var table = document.createElement('table')
        table.className = 'medium mmm-cryptocurrency-icon'

        for (var j = 0; j < apiResult.length; j++) {

            var tr = document.createElement('tr')
            tr.className = 'icon-row'

            var logoWrapper = document.createElement('td')
            logoWrapper.className = 'icon-field'

            if (this.imageExists(apiResult[j].id)) {
                var logo = new Image()

                logo.src = '/MMM-cryptocurrency/' + this.folder + apiResult[j].id + '.png'
                logo.setAttribute('width', '50px')
                logo.setAttribute('height', '50px')
                logoWrapper.appendChild(logo)
            } else {
                this.sendNotification('SHOW_ALERT', {
                    timer: 5000,
                    title: 'MMM-cryptocurrency',
                    message: '' +
                        this.translate('IMAGE') + ' ' + apiResult[j].id + '.png ' + this.translate('NOTFOUND') + ' /MMM-cryptocurrency/public/' + this.folder
                })
            }

            var priceWrapper = document.createElement('td')
            var price = document.createElement('price')
            price.style.fontSize = this.config.fontSize
            price.innerHTML = apiResult[j].price.replace("EUR", "€")

            priceWrapper.appendChild(price)

            if (displayType == 'logoWithChanges') {
                let changesWrapper = document.createElement('div')
                var change_1h = document.createElement('change_1h')
                change_1h.style.color = this.colorizeChange(apiResult[j].percent_change_1h)
                change_1h.style.fontSize = 'medium'
                change_1h.innerHTML = 'h: ' + apiResult[j].percent_change_1h + '%'
                change_1h.style.marginRight = '12px'

                var change_24h = document.createElement('change_24h')
                change_24h.style.color = this.colorizeChange(apiResult[j].percent_change_24h)
                change_24h.style.fontSize = 'medium'
                change_24h.innerHTML = 'd: ' + apiResult[j].percent_change_24h + '%'
                change_24h.style.marginRight = '12px'

                var change_7d = document.createElement('change_7d')
                change_7d.style.color = this.colorizeChange(apiResult[j].percent_change_7d)
                change_7d.style.fontSize = 'medium'
                change_7d.innerHTML = 'w: ' + apiResult[j].percent_change_7d + '%'

                changesWrapper.appendChild(change_1h)
                changesWrapper.appendChild(change_24h)
                changesWrapper.appendChild(change_7d)
                priceWrapper.appendChild(changesWrapper)
            } else {
                priceWrapper.className = 'price'
            }

            tr.appendChild(logoWrapper)
            tr.appendChild(priceWrapper)

            if (this.config.showGraphs) {
                var graphWrapper = document.createElement('td')
                graphWrapper.className = 'graph'
                if (this.sparklineIds[apiResult[j].id]) {
                    var graph = document.createElement('img')
                    graph.src = 'https://files.coinmarketcap.com/generated/sparklines/' + this.sparklineIds[apiResult[j].id] + '.png?cachePrevention=' + Math.random()
                    console.log(graph.src)
                    graphWrapper.appendChild(graph)
                }
                tr.appendChild(graphWrapper)
            }

            table.appendChild(tr)
        }
        wrapper.appendChild(table)

        return wrapper

    },

    /**
     * Checks if an image with the passed name exists
     *
     * @param currencyName
     * @returns {boolean}
     */
    imageExists: function(currencyName) {
        var imgPath = '/MMM-cryptocurrency/' + this.folder + currencyName + '.png'
        var http = new XMLHttpRequest()
        http.open('HEAD', imgPath, false)
        http.send()
        return http.status != 404
    },

    colorizeChange: function(change) {

        if (change < 0) {
            return 'Red'
        } else if (change > 0) {
            return 'Green'
        } else {
            return 'White'
        }
    },

    /**
     * Load translations files
     * @returns {{en: string, de: string, it: string}}
     */
    getTranslations: function() {
        return {
            en: 'translations/en.json',
            de: 'translations/de.json',
            it: 'translations/it.json'
        }
    },

})<commit_msg>Fixed typo in displayType<commit_after>Module.register('MMM-cryptocurrency', {
    result: {},
    defaults: {
        currency: ['bitcoin'],
        conversion: 'USD',
        showUSD: false,
        displayLongNames: false,
        headers: [],
        displayType: 'detail',
        showGraphs: false,
        logoHeaderText: 'Crypto currency',
        significantDigits: 2,
        coloredLogos: false,
        fontSize: 'xx-large'
    },

    sparklineIds: {
        bitcoin: 1,
        ethereum: 1027,
        ripple: 52,
        litecoin: 2,
        'ethereum-classic': 1321,
        nem: 873,
        stratis: 1343,
        'bitcoin-cash': 1831,
        'bitcoin-gold': 2083,
        cardano: 2010,
        dash: 131,
        eos: 1765,
        monero: 328,
        neo: 1376,
        stellar: 512,
        iota: 1720,
        tron: 1958,
        qtum: 1684
    },

    start: function() {
        this.getTicker()
        this.scheduleUpdate()
    },

    getStyles: function() {
        return ['MMM-cryptocurrency.css']
    },

    getTicker: function() {
        var conversion = this.config.conversion
        var url = 'https://api.coinmarketcap.com/v1/ticker/?convert=' + conversion + '&limit=100'
        this.sendSocketNotification('get_ticker', url)
    },

    scheduleUpdate: function() {
        var self = this
            // Refresh time should not be less than 5 minutes
        var delay = 300000
        setInterval(function() {
            self.getTicker()
        }, delay)
    },

    getDom: function() {
        if (this.config.displayType == 'logo' || this.config.displayType == 'logoWithChanges') {
            this.folder = (this.config.coloredLogos ? 'colored/' : 'black-white/')
            return this.buildIconView(this.result, this.config.displayType)
        }
        var data = this.result

        var wrapper = document.createElement('table')
        wrapper.className = 'small mmm-cryptocurrency'

        var tableHeader = document.createElement('tr')
        tableHeader.className = 'header-row'

        var tableHeaderValues = [
            this.translate('CURRENCY'),
            this.translate('PRICE')
        ]
        if (this.config.headers.indexOf('change1h') > -1) {
            tableHeaderValues.push(this.translate('CHANGE') + ' (1h)')
        }
        if (this.config.headers.indexOf('change24h') > -1) {
            tableHeaderValues.push(this.translate('CHANGE') + ' (24h)')
        }
        if (this.config.headers.indexOf('change7d') > -1) {
            tableHeaderValues.push(this.translate('CHANGE') + ' (7d)')
        }
        for (var i = 0; i < tableHeaderValues.length; i++) {
            var tableHeadSetup = document.createElement('th')
            tableHeadSetup.innerHTML = tableHeaderValues[i]
            tableHeader.appendChild(tableHeadSetup)
        }
        wrapper.appendChild(tableHeader)

        for (i = 0; i < data.length; i++) {
            var currentCurrency = data[i]
            var trWrapper = document.createElement('tr')
            trWrapper.className = 'currency'
            var name
            if (this.config.displayLongNames) {
                name = currentCurrency.name
            } else {
                name = currentCurrency.symbol
            }

            var tdValues = [
                name,
                currentCurrency.price,
            ]
            if (this.config.headers.indexOf('change1h') > -1) {
                tdValues.push(currentCurrency.percent_change_1h + '%')
            }
            if (this.config.headers.indexOf('change24h') > -1) {
                tdValues.push(currentCurrency.percent_change_24h + '%')
            }
            if (this.config.headers.indexOf('change7d') > -1) {
                tdValues.push(currentCurrency.percent_change_7d + '%')
            }

            for (var j = 0; j < tdValues.length; j++) {
                var tdWrapper = document.createElement('td')
                let currValue = tdValues[j]
                // If I am showing value then set color
                if (currValue.includes('%')) {
                    tdWrapper.style.color = this.colorizeChange(currValue.slice(0,-1))
                }
                tdWrapper.innerHTML = currValue
                trWrapper.appendChild(tdWrapper)
            }
            wrapper.appendChild(trWrapper)
        }
        return wrapper
    },

    socketNotificationReceived: function(notification, payload) {
        if (notification === 'got_result') {
            this.result = this.getWantedCurrencies(this.config.currency, payload)
            this.updateDom()
        }
    },

    /**
     * Returns configured currencies
     *
     * @param chosenCurrencies
     * @param apiResult
     * @returns {Array}
     */
    getWantedCurrencies: function(chosenCurrencies, apiResult) {
        var filteredCurrencies = []
        for (var i = 0; i < chosenCurrencies.length; i++) {
            for (var j = 0; j < apiResult.length; j++) {
                var userCurrency = chosenCurrencies[i]
                var remoteCurrency = apiResult[j]
                if (userCurrency == remoteCurrency.id) {
                    remoteCurrency = this.formatPrice(remoteCurrency)
                    filteredCurrencies.push(remoteCurrency)
                }
            }
        }
        return filteredCurrencies
    },

    /**
     * Formats the price of the API result and adds it to the object with simply .price as key
     * instead of price_eur
     *
     * @param apiResult
     * @returns {*}
     */
    formatPrice: function(apiResult) {
        var rightCurrencyFormat = this.config.conversion.toLowerCase()

        // rounding the price in Conversion
        var unroundedPrice = apiResult['price_' + rightCurrencyFormat]
        var digitsBeforeDecimalPoint = Math.floor(unroundedPrice).toString().length
        var requiredDigitsAfterDecimalPoint = Math.max(this.config.significantDigits - digitsBeforeDecimalPoint, 2)
        var price = this.roundNumber(unroundedPrice, requiredDigitsAfterDecimalPoint)
        console.log("config.language: " + config.language);

        // add the currency string
        apiResult['price'] = price.toLocaleString(config.language, { style: 'currency', currency: this.config.conversion })
        if (rightCurrencyFormat != 'usd' && this.config.showUSD) {
            // rounding the priceUSD
            var unroundedPriceUSD = apiResult['price_usd']
            var digitsBeforeDecimalPointUSD = Math.floor(unroundedPriceUSD).toString().length
            var requiredDigitsAfterDecimalPointUSD = Math.max(this.config.significantDigits - digitsBeforeDecimalPointUSD, 2)
            var priceUSD = this.roundNumber(unroundedPriceUSD, requiredDigitsAfterDecimalPointUSD)
            apiResult['price'] += ' / ' + priceUSD.toLocaleString(config.language, { style: 'currency', currency: 'USD' })
        }

        return apiResult
    },

    /**
     * Rounds a number to a given number of digits after the decimal point
     *
     * @param number
     * @param precision
     * @returns {number}
     */
    roundNumber: function(number, precision) {
        var factor = Math.pow(10, precision)
        var tempNumber = number * factor
        var roundedTempNumber = Math.round(tempNumber)
        return roundedTempNumber / factor
    },

    /**
     * Creates the icon view type
     *
     * @param apiResult
     * @param displayType
     * @returns {Element}
     */
    buildIconView: function(apiResult, displayType) {
        var wrapper = document.createElement('div')
        var header = document.createElement('header')
        header.className = 'module-header'
        header.innerHTML = this.config.logoHeaderText
        if (this.config.logoHeaderText !== '') {
            wrapper.appendChild(header)
        }

        var table = document.createElement('table')
        table.className = 'medium mmm-cryptocurrency-icon'

        for (var j = 0; j < apiResult.length; j++) {

            var tr = document.createElement('tr')
            tr.className = 'icon-row'

            var logoWrapper = document.createElement('td')
            logoWrapper.className = 'icon-field'

            if (this.imageExists(apiResult[j].id)) {
                var logo = new Image()

                logo.src = '/MMM-cryptocurrency/' + this.folder + apiResult[j].id + '.png'
                logo.setAttribute('width', '50px')
                logo.setAttribute('height', '50px')
                logoWrapper.appendChild(logo)
            } else {
                this.sendNotification('SHOW_ALERT', {
                    timer: 5000,
                    title: 'MMM-cryptocurrency',
                    message: '' +
                        this.translate('IMAGE') + ' ' + apiResult[j].id + '.png ' + this.translate('NOTFOUND') + ' /MMM-cryptocurrency/public/' + this.folder
                })
            }

            var priceWrapper = document.createElement('td')
            var price = document.createElement('price')
            price.style.fontSize = this.config.fontSize
            price.innerHTML = apiResult[j].price.replace("EUR", "€")

            priceWrapper.appendChild(price)

            if (displayType == 'logoWithChanges') {
                let changesWrapper = document.createElement('div')
                var change_1h = document.createElement('change_1h')
                change_1h.style.color = this.colorizeChange(apiResult[j].percent_change_1h)
                change_1h.style.fontSize = 'medium'
                change_1h.innerHTML = 'h: ' + apiResult[j].percent_change_1h + '%'
                change_1h.style.marginRight = '12px'

                var change_24h = document.createElement('change_24h')
                change_24h.style.color = this.colorizeChange(apiResult[j].percent_change_24h)
                change_24h.style.fontSize = 'medium'
                change_24h.innerHTML = 'd: ' + apiResult[j].percent_change_24h + '%'
                change_24h.style.marginRight = '12px'

                var change_7d = document.createElement('change_7d')
                change_7d.style.color = this.colorizeChange(apiResult[j].percent_change_7d)
                change_7d.style.fontSize = 'medium'
                change_7d.innerHTML = 'w: ' + apiResult[j].percent_change_7d + '%'

                changesWrapper.appendChild(change_1h)
                changesWrapper.appendChild(change_24h)
                changesWrapper.appendChild(change_7d)
                priceWrapper.appendChild(changesWrapper)
            } else {
                priceWrapper.className = 'price'
            }

            tr.appendChild(logoWrapper)
            tr.appendChild(priceWrapper)

            if (this.config.showGraphs) {
                var graphWrapper = document.createElement('td')
                graphWrapper.className = 'graph'
                if (this.sparklineIds[apiResult[j].id]) {
                    var graph = document.createElement('img')
                    graph.src = 'https://files.coinmarketcap.com/generated/sparklines/' + this.sparklineIds[apiResult[j].id] + '.png?cachePrevention=' + Math.random()
                    console.log(graph.src)
                    graphWrapper.appendChild(graph)
                }
                tr.appendChild(graphWrapper)
            }

            table.appendChild(tr)
        }
        wrapper.appendChild(table)

        return wrapper

    },

    /**
     * Checks if an image with the passed name exists
     *
     * @param currencyName
     * @returns {boolean}
     */
    imageExists: function(currencyName) {
        var imgPath = '/MMM-cryptocurrency/' + this.folder + currencyName + '.png'
        var http = new XMLHttpRequest()
        http.open('HEAD', imgPath, false)
        http.send()
        return http.status != 404
    },

    colorizeChange: function(change) {

        if (change < 0) {
            return 'Red'
        } else if (change > 0) {
            return 'Green'
        } else {
            return 'White'
        }
    },

    /**
     * Load translations files
     * @returns {{en: string, de: string, it: string}}
     */
    getTranslations: function() {
        return {
            en: 'translations/en.json',
            de: 'translations/de.json',
            it: 'translations/it.json'
        }
    },

})
<|endoftext|>


<commit_before>/**********************************************************************
    Freeciv-web - the web version of Freeciv. http://play.freeciv.org/
    Copyright (C) 2009-2015  The Freeciv-web project

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

***********************************************************************/

/* The server will send information about its settings. It is stored here.
 * You can look up a setting by its name or by its id number. */
var server_settings = {};

/****************************************************************
 The "options" file handles actual "options", and also view options,
 message options, dialog/report settings, cma settings, server settings,
 and global worklists.
*****************************************************************/

/** Defaults for options normally on command line **/

var default_user_name = "";
var default_server_host = "localhost";
//var  default_server_port = DEFAULT_SOCK_PORT;
//var default_metaserver = META_URL;
var default_theme_name = "human";
var default_tileset_name = "";
var default_sound_set_name = "stdsounds";
var default_sound_plugin_name = "";

var sounds_enabled = true;

var save_options_on_exit = TRUE;
var fullscreen_mode = FALSE;

/** Local Options: **/

var solid_color_behind_units = FALSE;
var sound_bell_at_new_turn = FALSE;
var  smooth_move_unit_msec = 30;
var smooth_center_slide_msec = 200;
var do_combat_animation = TRUE;
var ai_manual_turn_done = TRUE;
var auto_center_on_unit = TRUE;
var auto_center_on_combat = FALSE;
var auto_center_each_turn = TRUE;
var wakeup_focus = TRUE;
var goto_into_unknown = TRUE;
var center_when_popup_city = TRUE;
var concise_city_production = FALSE;
var auto_turn_done = FALSE;
var meta_accelerators = TRUE;
var ask_city_name = TRUE;
var popup_new_cities = TRUE;
var popup_actor_arrival = true;
var keyboardless_goto = TRUE;
var enable_cursor_changes = TRUE;
var separate_unit_selection = FALSE;
var unit_selection_clears_orders = TRUE;
var highlight_our_names = "yellow";

/* This option is currently set by the client - not by the user. */
var update_city_text_in_refresh_tile = TRUE;

var draw_city_outlines = TRUE;
var draw_city_output = FALSE;
var draw_map_grid = FALSE;
var draw_city_names = TRUE;
var draw_city_growth = TRUE;
var draw_city_productions = FALSE;
var draw_city_buycost = FALSE;
var draw_city_traderoutes = FALSE;
var draw_terrain = TRUE;
var draw_coastline = FALSE;
var draw_roads_rails = TRUE;
var draw_irrigation = TRUE;
var draw_mines = TRUE;
var draw_fortress_airbase = TRUE;
var draw_huts = TRUE;
var draw_resources = TRUE;
var draw_pollution = TRUE;
var draw_cities = TRUE;
var draw_units = TRUE;
var draw_focus_unit = FALSE;
var draw_fog_of_war = TRUE;
var draw_borders = TRUE;
var draw_full_citybar = TRUE;
var draw_unit_shields = TRUE;
var player_dlg_show_dead_players = TRUE;
var reqtree_show_icons = TRUE;
var reqtree_curved_lines = FALSE;

/* gui-gtk-2.0 client specific options. */
var gui_gtk2_map_scrollbars = FALSE;
var gui_gtk2_dialogs_on_top = TRUE;
var gui_gtk2_show_task_icons = TRUE;
var gui_gtk2_enable_tabs = TRUE;
var gui_gtk2_better_fog = TRUE;
var gui_gtk2_show_chat_message_time = FALSE;
var gui_gtk2_split_bottom_notebook = FALSE;
var gui_gtk2_new_messages_go_to_top = FALSE;
var gui_gtk2_show_message_window_buttons = TRUE;
var gui_gtk2_metaserver_tab_first = FALSE;
var gui_gtk2_allied_chat_only = FALSE;
var gui_gtk2_small_display_layout = FALSE;

function init_options_dialog()
{
  $("#save_button").button("option", "label", "Save Game");

  $("#timeout_setting").val(game_info['timeout']);
  $("#metamessage_setting").val(server_settings['metamessage']['val']);

  $('#metamessage_setting').change(function() {
    send_message("/metamessage " + $('#metamessage_setting').val());
  });

  $('#metamessage_setting').bind('keyup blur',function(){
    var cleaned_text = $(this).val().replace(/[^a-zA-Z\s\-]/g,'');
    if ($(this).val() != cleaned_text) {
      $(this).val( cleaned_text ); }
    }
  );

  $('#timeout_setting').change(function() {
    send_message("/set timeout " + $('#timeout_setting').val());
  });

  if (audio != null && !audio.source.src) {
    if (!supports_mp3()) {
      audio.load("/music/" + music_list[Math.floor(Math.random() * music_list.length)] + ".ogg");
    } else {
      audio.load("/music/" + music_list[Math.floor(Math.random() * music_list.length)] + ".mp3");
    }
  }

  $(".setting_button").tooltip();

  $('#play_sounds_setting').prop('checked', sounds_enabled);

  $('#play_sounds_setting').change(function() {
    sounds_enabled = !sounds_enabled;
  });

}
<commit_msg>Update Save game keyboard shortcut.<commit_after>/**********************************************************************
    Freeciv-web - the web version of Freeciv. http://play.freeciv.org/
    Copyright (C) 2009-2015  The Freeciv-web project

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

***********************************************************************/

/* The server will send information about its settings. It is stored here.
 * You can look up a setting by its name or by its id number. */
var server_settings = {};

/****************************************************************
 The "options" file handles actual "options", and also view options,
 message options, dialog/report settings, cma settings, server settings,
 and global worklists.
*****************************************************************/

/** Defaults for options normally on command line **/

var default_user_name = "";
var default_server_host = "localhost";
//var  default_server_port = DEFAULT_SOCK_PORT;
//var default_metaserver = META_URL;
var default_theme_name = "human";
var default_tileset_name = "";
var default_sound_set_name = "stdsounds";
var default_sound_plugin_name = "";

var sounds_enabled = true;

var save_options_on_exit = TRUE;
var fullscreen_mode = FALSE;

/** Local Options: **/

var solid_color_behind_units = FALSE;
var sound_bell_at_new_turn = FALSE;
var  smooth_move_unit_msec = 30;
var smooth_center_slide_msec = 200;
var do_combat_animation = TRUE;
var ai_manual_turn_done = TRUE;
var auto_center_on_unit = TRUE;
var auto_center_on_combat = FALSE;
var auto_center_each_turn = TRUE;
var wakeup_focus = TRUE;
var goto_into_unknown = TRUE;
var center_when_popup_city = TRUE;
var concise_city_production = FALSE;
var auto_turn_done = FALSE;
var meta_accelerators = TRUE;
var ask_city_name = TRUE;
var popup_new_cities = TRUE;
var popup_actor_arrival = true;
var keyboardless_goto = TRUE;
var enable_cursor_changes = TRUE;
var separate_unit_selection = FALSE;
var unit_selection_clears_orders = TRUE;
var highlight_our_names = "yellow";

/* This option is currently set by the client - not by the user. */
var update_city_text_in_refresh_tile = TRUE;

var draw_city_outlines = TRUE;
var draw_city_output = FALSE;
var draw_map_grid = FALSE;
var draw_city_names = TRUE;
var draw_city_growth = TRUE;
var draw_city_productions = FALSE;
var draw_city_buycost = FALSE;
var draw_city_traderoutes = FALSE;
var draw_terrain = TRUE;
var draw_coastline = FALSE;
var draw_roads_rails = TRUE;
var draw_irrigation = TRUE;
var draw_mines = TRUE;
var draw_fortress_airbase = TRUE;
var draw_huts = TRUE;
var draw_resources = TRUE;
var draw_pollution = TRUE;
var draw_cities = TRUE;
var draw_units = TRUE;
var draw_focus_unit = FALSE;
var draw_fog_of_war = TRUE;
var draw_borders = TRUE;
var draw_full_citybar = TRUE;
var draw_unit_shields = TRUE;
var player_dlg_show_dead_players = TRUE;
var reqtree_show_icons = TRUE;
var reqtree_curved_lines = FALSE;

/* gui-gtk-2.0 client specific options. */
var gui_gtk2_map_scrollbars = FALSE;
var gui_gtk2_dialogs_on_top = TRUE;
var gui_gtk2_show_task_icons = TRUE;
var gui_gtk2_enable_tabs = TRUE;
var gui_gtk2_better_fog = TRUE;
var gui_gtk2_show_chat_message_time = FALSE;
var gui_gtk2_split_bottom_notebook = FALSE;
var gui_gtk2_new_messages_go_to_top = FALSE;
var gui_gtk2_show_message_window_buttons = TRUE;
var gui_gtk2_metaserver_tab_first = FALSE;
var gui_gtk2_allied_chat_only = FALSE;
var gui_gtk2_small_display_layout = FALSE;

function init_options_dialog()
{
  $("#save_button").button("option", "label", "Save Game (Ctrl+S)");

  $("#timeout_setting").val(game_info['timeout']);
  $("#metamessage_setting").val(server_settings['metamessage']['val']);

  $('#metamessage_setting').change(function() {
    send_message("/metamessage " + $('#metamessage_setting').val());
  });

  $('#metamessage_setting').bind('keyup blur',function(){
    var cleaned_text = $(this).val().replace(/[^a-zA-Z\s\-]/g,'');
    if ($(this).val() != cleaned_text) {
      $(this).val( cleaned_text ); }
    }
  );

  $('#timeout_setting').change(function() {
    send_message("/set timeout " + $('#timeout_setting').val());
  });

  if (audio != null && !audio.source.src) {
    if (!supports_mp3()) {
      audio.load("/music/" + music_list[Math.floor(Math.random() * music_list.length)] + ".ogg");
    } else {
      audio.load("/music/" + music_list[Math.floor(Math.random() * music_list.length)] + ".mp3");
    }
  }

  $(".setting_button").tooltip();

  $('#play_sounds_setting').prop('checked', sounds_enabled);

  $('#play_sounds_setting').change(function() {
    sounds_enabled = !sounds_enabled;
  });

}
<|endoftext|>


<commit_before>var should = require('should'),
    own = require('../');

describe('own', function(){

    it('should create an own properties object', function(){
        own({
            foo: 'bar'
        }).should.eql({
            foo: {
                value: 'bar',
                enumerable: true
            }
        });
    });

});<commit_msg>Fixed test.<commit_after>var should = require('should')
var own = require('../')

describe('own', function(){

    it('should create an own properties object', function(){
        own({
            foo: 'bar'
        }).should.eql({
            foo: {
                value: 'bar',
                enumerable: true,
                writable: true
            }
        })
    })

})
<|endoftext|>


<commit_before>import test from 'blue-tape';
import Deepstream from 'deepstream.io';
import getClient, { addEntry, polyfill } from '../src/index';

const server = new Deepstream();
server.start();
const c = getClient('localhost:6020');

test('polyfill', t => {
  const o = new class X {
    func() {
      this.x = 5;
      return this.x;
    }
  }();
  polyfill(o, 'func', 7); // should be blocked
  polyfill(o, 'x', 7); // should pass
  if (typeof o.func === 'function' && o.x === 7) t.pass();
  else if (o.func === 7) t.fail('polyfill overwrites!');
  else t.fail('polyfill failed');
  t.end();
});

test('loginP', () => c.loginP({}));

test('provide', t => {
  c.rpc.provide('rpc1', (err, res) => res.send(5));
  t.end();
});

test('getRecordP', () =>
  c.record.getRecordP('record1').then(r => {
    if (Object.keys(r.get()).length !== 0) throw new Error('Not empty object');
    r.set({ name: 'Record1', data: { a: 1 } });
    return true;
  }));

test('getListP', () =>
  c.record.getListP('list1').then(l => {
    if (l.getEntries().length !== 0) throw new Error('Not empty list');
    addEntry(l, 'record1');
    return true;
  }));

test('getExistingRecordP', () =>
  c.record.getExistingRecordP('record1').then(r => {
    if (r.get().name !== 'Record1') throw new Error('Bad record');
    return true;
  }));

test('getExistingListP', () =>
  c.record.getExistingListP('list1').then(l => {
    if (l.getEntries()[0] !== 'record1') throw new Error('Bad list');
    return true;
  }));

test('addToListP', () =>
  c.record.addToListP('list1', 'record2').then(l => {
    if (l.getEntries()[1] !== 'record2') throw new Error('Bad list');
    return true;
  }));

test('removeFromListP', () =>
  c.record.removeFromListP('list1', 'record2').then(l => {
    if (JSON.stringify(l.getEntries()) !== '["record1"]') throw new Error('Bad list');
    return true;
  }));

test('snapshotP', () =>
  c.record.snapshotP('record1').then(r => {
    if (JSON.stringify(r) !== '{"name":"Record1","data":{"a":1}}') throw new Error('Bad record');
    return true;
  }));

test('setExistingRecordP', () =>
  c.record.setExistingRecordP('record1', { data: { b: 2 } }, true).then(r => {
    if (JSON.stringify(r.get()) !== '{"name":"Record1","data":{"a":1,"b":2}}') {
      throw new Error('Bad record');
    }
    return true;
  }));

test('setExistingRecordP', () =>
  c.record.setExistingRecordP('record1', { data: 5 }).then(r => {
    if (JSON.stringify(r.get()) !== '{"name":"Record1","data":5}') {
      throw new Error('Bad record');
    }
    return true;
  }));

test('hasP', () =>
  c.record.hasP('record1').then(ok => {
    if (!ok) throw new Error('Bad record');
    return true;
  }));

test('makeP', () =>
  c.rpc.makeP('rpc1').then(res => {
    if (res !== 5) throw new Error('Bad answer');
    return true;
  }));

test('setListedRecordP', () =>
  c.record.setListedRecordP('records', 'record2', { name: 'Record2' }).then(([id, created]) => {
    if (!created) throw new Error('Was not created!?');
    if (id !== 'record2') throw new Error('Bad ID');
    return c.record.getExistingListP('records').then(l => {
      if (JSON.stringify(l.getEntries()) !== '["records/record2"]') throw new Error('Bad list');
      return c.record.getExistingRecordP('records/record2').then(r => {
        if (r.get().name !== 'Record2') throw new Error('Bad record content');
        return true;
      });
    });
  }));

test('p.getRecord', () =>
  c.record.p.getRecord('record1').then(r => {
    if (JSON.stringify(r.get()) !== '{"name":"Record1","data":5}') {
      throw new Error('Not empty object');
    }
    return true;
  }));
<commit_msg>test shutdown<commit_after>import test from 'blue-tape';
import Deepstream from 'deepstream.io';
import getClient, { addEntry, polyfill } from '../src/index';

const server = new Deepstream();
server.start();
const c = getClient('localhost:6020');

test('polyfill', t => {
  const o = new class X {
    func() {
      this.x = 5;
      return this.x;
    }
  }();
  polyfill(o, 'func', 7); // should be blocked
  polyfill(o, 'x', 7); // should pass
  if (typeof o.func === 'function' && o.x === 7) t.pass();
  else if (o.func === 7) t.fail('polyfill overwrites!');
  else t.fail('polyfill failed');
  t.end();
});

test('loginP', () => c.loginP({}));

test('provide', t => {
  c.rpc.provide('rpc1', (err, res) => res.send(5));
  t.end();
});

test('getRecordP', () =>
  c.record.getRecordP('record1').then(r => {
    if (Object.keys(r.get()).length !== 0) throw new Error('Not empty object');
    r.set({ name: 'Record1', data: { a: 1 } });
    return true;
  }));

test('getListP', () =>
  c.record.getListP('list1').then(l => {
    if (l.getEntries().length !== 0) throw new Error('Not empty list');
    addEntry(l, 'record1');
    return true;
  }));

test('getExistingRecordP', () =>
  c.record.getExistingRecordP('record1').then(r => {
    if (r.get().name !== 'Record1') throw new Error('Bad record');
    return true;
  }));

test('getExistingListP', () =>
  c.record.getExistingListP('list1').then(l => {
    if (l.getEntries()[0] !== 'record1') throw new Error('Bad list');
    return true;
  }));

test('addToListP', () =>
  c.record.addToListP('list1', 'record2').then(l => {
    if (l.getEntries()[1] !== 'record2') throw new Error('Bad list');
    return true;
  }));

test('removeFromListP', () =>
  c.record.removeFromListP('list1', 'record2').then(l => {
    if (JSON.stringify(l.getEntries()) !== '["record1"]') throw new Error('Bad list');
    return true;
  }));

test('snapshotP', () =>
  c.record.snapshotP('record1').then(r => {
    if (JSON.stringify(r) !== '{"name":"Record1","data":{"a":1}}') throw new Error('Bad record');
    return true;
  }));

test('setExistingRecordP', () =>
  c.record.setExistingRecordP('record1', { data: { b: 2 } }, true).then(r => {
    if (JSON.stringify(r.get()) !== '{"name":"Record1","data":{"a":1,"b":2}}') {
      throw new Error('Bad record');
    }
    return true;
  }));

test('setExistingRecordP', () =>
  c.record.setExistingRecordP('record1', { data: 5 }).then(r => {
    if (JSON.stringify(r.get()) !== '{"name":"Record1","data":5}') {
      throw new Error('Bad record');
    }
    return true;
  }));

test('hasP', () =>
  c.record.hasP('record1').then(ok => {
    if (!ok) throw new Error('Bad record');
    return true;
  }));

test('makeP', () =>
  c.rpc.makeP('rpc1').then(res => {
    if (res !== 5) throw new Error('Bad answer');
    return true;
  }));

test('setListedRecordP', () =>
  c.record.setListedRecordP('records', 'record2', { name: 'Record2' }).then(([id, created]) => {
    if (!created) throw new Error('Was not created!?');
    if (id !== 'record2') throw new Error('Bad ID');
    return c.record.getExistingListP('records').then(l => {
      if (JSON.stringify(l.getEntries()) !== '["records/record2"]') throw new Error('Bad list');
      return c.record.getExistingRecordP('records/record2').then(r => {
        if (r.get().name !== 'Record2') throw new Error('Bad record content');
        return true;
      });
    });
  }));

test('p.getRecord', () =>
  c.record.p.getRecord('record1').then(r => {
    if (JSON.stringify(r.get()) !== '{"name":"Record1","data":5}') {
      throw new Error('Not empty object');
    }
    return true;
  }));

test('shutdown', t => {
  c.close();
  server.stop();
  t.end();
});
<|endoftext|>


<commit_before>import test from 'ava'
import mobxstore from '../src'
import storage from '../src/localstorage'
import { autorun } from 'mobx'
import { map, find, filter, toUpper, sortBy, take, forEach } from 'lodash/fp'

global.localStorage = {
  store: { db: '{"a": [1, 2, 3]}' },
  setItem: (key, value) => localStorage.store[key] = value,
  getItem: (key) => localStorage.store[key]
}

test('Local storage works', function(t) {
  storage.read('x')
  t.deepEqual(JSON.parse(global.localStorage.store.x), {})
  storage.write('x', { hello: 'world' })
  t.deepEqual(JSON.parse(global.localStorage.store.x), { hello: 'world' })
})

test('Store reads from and writes to local storage', function(t) {
  const store = mobxstore('db', { storage })

  t.deepEqual(store('a').slice(), [1, 2, 3])
  store('a').replace([4, 5, 6])
  t.deepEqual(JSON.parse(global.localStorage.store.db).a, [4, 5, 6])
})

test('Store works when calling a single method', function(t) {
  let i = 0
  const store = mobxstore()

  store('test').replace([1, 2, 3])
  autorun(() => i += noop(store('test')[0]))
  store('test').replace([4, 5, 6])
  t.is(i, 2)
})

test('Store should not report a change when nothing changes', function(t) {
  let i = 0
  const store = mobxstore()

  store('test').replace([{ a: 1 }, { b: 2 }, { c: 3 }])
  autorun(() => i += noop(store('test')[0]))
  store('test', find({ a: 1 }))
  t.not(i, 2)
})

test('Store works when chaining', function(t) {
  let i = 0
  const store = mobxstore()

  store('test').replace([{ a: 1 }, { b: 2 }, { c: 3 }])
  autorun(() => i += noop(store('test')[0].a))
  store('test', find({ a: 1 })).a = 'wow'
  t.is(i, 2)
})

test('Store time travel works', function(t) {
  const store = mobxstore()

  store('time').replace([1, 2, 3])
  store('time').replace([4, 2, 3])
  store('travel').replace([1, 3, 3])
  store('travel').replace([1, 2, 3])
  t.deepEqual(store.states, [
    {},
    { time: [] },
    { time: [1, 2, 3] },
    { time: [4, 2, 3] },
    { time: [4, 2, 3], travel: [] },
    { time: [4, 2, 3], travel: [1, 3, 3] },
    { time: [4, 2, 3], travel: [1, 2, 3] }
  ])
})

test('Examples in store work', function(t) {
  const store = mobxstore()

  store('numbers')
  store('numbers').replace([1, 2, 3])
  t.deepEqual(store('numbers', filter((v) => v > 1)), [2, 3])

  const users = [{
    id: 1,
    name: 'a'
  }, {
    id: 2,
    name: 'b'
  }, {
    id: 3,
    name: 'c'
  }, {
    id: 4,
    name: 'd'
  }, {
    id: 5,
    name: 'e'
  }]

  store('users').replace(users)
  const top3 = store('users', [sortBy('id'), take(3)])
  t.deepEqual(store.chain(top3, map('name')), ['a', 'b', 'c'])
  t.deepEqual(store.chain(top3, map((v) => toUpper(v.name))), ['A', 'B', 'C'])
  t.deepEqual(store.chain(top3, map('name')), ['a', 'b', 'c'])
  store.chain(top3, forEach((v) => v.name = toUpper(v.name)))
  t.deepEqual(store.chain(top3, map('name')), ['A', 'B', 'C'])
})

function noop() {
  return 1
}
<commit_msg>:bug: fix states test<commit_after>import test from 'ava'
import mobxstore from '../src'
import storage from '../src/localstorage'
import { autorun } from 'mobx'
import { map, find, filter, toUpper, sortBy, take, forEach } from 'lodash/fp'

global.localStorage = {
  store: { db: '{"a": [1, 2, 3]}' },
  setItem: (key, value) => localStorage.store[key] = value,
  getItem: (key) => localStorage.store[key]
}

test('Local storage works', function(t) {
  storage.read('x')
  t.deepEqual(JSON.parse(global.localStorage.store.x), {})
  storage.write('x', { hello: 'world' })
  t.deepEqual(JSON.parse(global.localStorage.store.x), { hello: 'world' })
})

test('Store reads from and writes to local storage', function(t) {
  const store = mobxstore('db', { storage })

  t.deepEqual(store('a').slice(), [1, 2, 3])
  store('a').replace([4, 5, 6])
  t.deepEqual(JSON.parse(global.localStorage.store.db).a, [4, 5, 6])
})

test('Store works when calling a single method', function(t) {
  let i = 0
  const store = mobxstore()

  store('test').replace([1, 2, 3])
  autorun(() => i += noop(store('test')[0]))
  store('test').replace([4, 5, 6])
  t.is(i, 2)
})

test('Store should not report a change when nothing changes', function(t) {
  let i = 0
  const store = mobxstore()

  store('test').replace([{ a: 1 }, { b: 2 }, { c: 3 }])
  autorun(() => i += noop(store('test')[0]))
  store('test', find({ a: 1 }))
  t.not(i, 2)
})

test('Store works when chaining', function(t) {
  let i = 0
  const store = mobxstore()

  store('test').replace([{ a: 1 }, { b: 2 }, { c: 3 }])
  autorun(() => i += noop(store('test')[0].a))
  store('test', find({ a: 1 })).a = 'wow'
  t.is(i, 2)
})

test('Store time travel works', function(t) {
  const store = mobxstore()

  store('time').replace([1, 2, 3])
  store('time').replace([4, 2, 3])
  store('travel').replace([1, 3, 3])
  store('travel').replace([1, 2, 3])
  t.is(JSON.stringify(store.states.slice()), JSON.stringify([
    {},
    { time: [] },
    { time: [1, 2, 3] },
    { time: [4, 2, 3] },
    { time: [4, 2, 3], travel: [] },
    { time: [4, 2, 3], travel: [1, 3, 3] },
    { time: [4, 2, 3], travel: [1, 2, 3] }
  ]))
})

test('Examples in store work', function(t) {
  const store = mobxstore()

  store('numbers')
  store('numbers').replace([1, 2, 3])
  t.deepEqual(store('numbers', filter((v) => v > 1)), [2, 3])

  const users = [{
    id: 1,
    name: 'a'
  }, {
    id: 2,
    name: 'b'
  }, {
    id: 3,
    name: 'c'
  }, {
    id: 4,
    name: 'd'
  }, {
    id: 5,
    name: 'e'
  }]

  store('users').replace(users)
  const top3 = store('users', [sortBy('id'), take(3)])
  t.deepEqual(store.chain(top3, map('name')), ['a', 'b', 'c'])
  t.deepEqual(store.chain(top3, map((v) => toUpper(v.name))), ['A', 'B', 'C'])
  t.deepEqual(store.chain(top3, map('name')), ['a', 'b', 'c'])
  store.chain(top3, forEach((v) => v.name = toUpper(v.name)))
  t.deepEqual(store.chain(top3, map('name')), ['A', 'B', 'C'])
})

function noop() {
  return 1
}
<|endoftext|>


<commit_before>var createPool = require('../').createPool;
var assert = require('assert');
var fs = require('fs');
var path = require('path');

var db = 'dbname = postgres';
var sql = fs.readFileSync(path.join(__dirname, 'test.sql'));

var pool = createPool({db: db});

var execSQL = function (db, command, callback) {
  pool.acquire(function (err, client) {
    client.query(command).each(function(err, finished, columns, values, index) {
      callback(err, finished, columns, values, index);

      if (finished) {
        pool.release(client);
      }
    });
  });
};

describe('minipg', function () {
  it('should query the database', function (done) {
    var db = 'dbname = postgres';

    execSQL(db, sql, function (err, finished, columns, values, index) {
      if (finished) {
        assert.equal(columns.length, 1);
        assert.equal(values, null);
        assert.equal(index, 3999);
        done();
      }
    });
  });

  it('should return errors', function (done) {
    var db = 'dbname = postgres';

    execSQL(db, 'sele', function (err, finished, columns, values, index) {
      if (finished) {
        assert.equal(columns, null);
        assert.equal(values, null);
        assert.equal(index, -1);
        assert.equal(err.message, 'ERROR:  syntax error at or near "sele"\nLINE 1: sele\n        ^\n');
        assert.equal(err.primary, 'syntax error at or near "sele"');
        assert.equal(err.severity, 'ERROR');
        assert.equal(err.position, '1');
        done();
      }
    });
  });

  it('should work properly for empty result sets', function (done) {
    var db = 'dbname = postgres';

    execSQL(db, 'SELECT 1::int AS count WHERE 1 = 0', function (err, finished, columns, values, index) {
      if (finished) {
        assert.equal(columns.length, 1);
        assert.equal(values, null);
        assert.equal(index, -1);
        done();
      }
    });
  });

  it('should be able to process notices', function (done) {
    pool.acquire(function (err, client) {
      var warning = null;
      client.setNoticeProcessor(function (message) {
        warning = message;
      });

      client.query('COMMIT').each(function(err, finished, columns, values, index) {
        if (finished) {
          assert.equal(warning, 'WARNING:  there is no transaction in progress\n');
          pool.release(client);
          done();
        }
      });
    });
  });
});
<commit_msg>Add message<commit_after>var createPool = require('../').createPool;
var assert = require('assert');
var fs = require('fs');
var path = require('path');

var db = 'dbname = postgres';
var sql = fs.readFileSync(path.join(__dirname, 'test.sql'));

var pool = createPool({db: db});

var execSQL = function (db, command, callback) {
  pool.acquire(function (err, client) {
    client.query(command).each(function(err, finished, columns, values, index) {
      callback(err, finished, columns, values, index);

      if (finished) {
        pool.release(client);
      }
    });
  });
};

describe('minipg', function () {
  it('should query the database', function (done) {
    var db = 'dbname = postgres';

    execSQL(db, sql, function (err, finished, columns, values, index) {
      if (finished) {
        assert.equal(columns.length, 1);
        assert.equal(values, null);
        assert.equal(index, 3999);
        done();
      }
    });
  });

  it('should return errors', function (done) {
    var db = 'dbname = postgres';

    execSQL(db, 'sele', function (err, finished, columns, values, index) {
      if (finished) {
        assert.equal(columns, null);
        assert.equal(values, null);
        assert.equal(index, -1);
        assert.equal(err.message, 'ERROR:  syntax error at or near "sele"\nLINE 1: sele\n        ^\n');
        assert.equal(err.primary, 'syntax error at or near "sele"');
        assert.equal(err.severity, 'ERROR');
        assert.equal(err.position, '1');
        done();
      }
    });
  });

  it('should work properly for empty result sets', function (done) {
    var db = 'dbname = postgres';

    execSQL(db, 'SELECT 1::int AS count WHERE 1 = 0', function (err, finished, columns, values, index) {
      if (finished) {
        assert.equal(columns.length, 1);
        assert.equal(values, null);
        assert.equal(index, -1);
        done();
      }
    });
  });

  it('should be able to process notices', function (done) {
    pool.acquire(function (err, client) {
      var warning = null;
      client.setNoticeProcessor(function (message) {
        console.log('warn', message);
        warning = message;
      });

      client.query('COMMIT;').each(function(err, finished, columns, values, index) {
        if (finished) {
          assert.equal(warning, 'WARNING:  there is no transaction in progress\n');
          pool.release(client);
          done();
        }
      });
    });
  });
});
<|endoftext|>


<commit_before>/* eslint-env mocha */

var chai = require('chai')
chai.use(require('chai-as-promised'))
chai.should()

var schema = {
  type: 'object',
  additionalProperties: false,
  patternProperties: {
    '[0-9]*': {
      type: 'object',
      additionalProperties: false,
      properties: {
        browserName: {type: 'string'},
        version: {type: 'string'},
        platform: {type: 'string'},
        base: {type: 'string', enum: ['SauceLabs']}
      },
      required: ['browserName', 'version', 'platform', 'base']
    }
  }
}

var ZSchema = require('z-schema')
var validator = new ZSchema()
var browsers = require('../')

describe('exports', function () {
  this.timeout(10000)

  it('is a promise that fulfills according to the schema', function (done) {
    return browsers.then(function (browsers) {
      var valid = validator.validate(browsers, schema)
      if (!valid) {
        var errors = validator.getLastErrors()
        console.log(errors)
      }
      return valid
    }).should.eventually.be.true
  })
})
<commit_msg>Fix test: redundant done argument<commit_after>/* eslint-env mocha */

var chai = require('chai')
chai.use(require('chai-as-promised'))
chai.should()

var schema = {
  type: 'object',
  additionalProperties: false,
  patternProperties: {
    '[0-9]*': {
      type: 'object',
      additionalProperties: false,
      properties: {
        browserName: {type: 'string'},
        version: {type: 'string'},
        platform: {type: 'string'},
        base: {type: 'string', enum: ['SauceLabs']}
      },
      required: ['browserName', 'version', 'platform', 'base']
    }
  }
}

var ZSchema = require('z-schema')
var validator = new ZSchema()
var browsers = require('../')

describe('exports', function () {
  this.timeout(10000)

  it('is a promise that fulfills according to the schema', function () {
    return browsers.then(function (browsers) {
      var valid = validator.validate(browsers, schema)
      if (!valid) {
        var errors = validator.getLastErrors()
        console.log(errors)
      }
      return valid
    }).should.eventually.be.true
  })
})
<|endoftext|>


<commit_before>var test = require('tape');

var OpenGeocoder = require('../');

<commit_msg>add a test unit<commit_after>var test = require('tape');

var OpenGeocoder = require('../');

var geo = new OpenGeocoder();

test('geocode', function (t) {
  t.plan(1);

  geo.geocode('135 pilkington avenue, birmingham', function (err, res) {
    if (err) return t.notOk(false, err);

    t.ok(res !== null, JSON.stringify(res));
  });

});
<|endoftext|>


<commit_before>/**
 * Created by dob on 20.11.13.
 */
var should = require('should'),
  util = require('util'),
  EventEmitter = require('events').EventEmitter,
  mlcl_database = require('mlcl_database'),
  mlcl_elastic = require('../');

describe('mlcl_elastic', function() {
  var mlcl;
  var molecuel;
  var mongo;
  var testobjEn;
  var testobjDe;

  before(function(done) {
    // init fake molecuel
    mlcl = function() {
      return this;
    };
    util.inherits(mlcl, EventEmitter);
    molecuel = new mlcl();

    molecuel.config = { };
    molecuel.config.search = {
      host: 'localhost',
      port: '9200',
      prefix: 'mlcl-elastic-unit'
    };
    molecuel.config.database = {
      type: 'mongodb',
      uri: 'mongodb://localhost/mlcl-elastic-unit'
    };
    mongo = mlcl_database(molecuel);
    mlcl_elastic(molecuel);

    testobjEn = {
      '_id': '98098098',
      'title': 'test title',
      'lang': 'en',
      'url': '/test_title'
    };

    testobjDe = {
      '_id': '123456',
      'title': 'test title',
      'lang': 'de',
      'url': '/test_title'
    };
    done();
  });

  describe('elastic', function() {
    var searchcon;
    var dbcon;
    var model;
    var mongoobj;

    it('should initialize db connection', function(done) {
      molecuel.once('mlcl::database::connection:success', function(database) {
        dbcon = database;
        database.should.be.a.object;
        done();
      });
      molecuel.emit('mlcl::core::init:post', molecuel);
    });

    it('should initialize search connection', function(done) {
      molecuel.once('mlcl::search::connection:success', function(search) {
        searchcon = search;
        search.should.be.a.object;
        done();
      });
      molecuel.emit('mlcl::core::init:post', molecuel);
    });

    it('should initialize schema plugin', function(done) {
      var Schema = dbcon.database.Schema;
      var testSchema = new Schema({
        name: {type: String},
        url: {type: String},
        lang: {type: String}
      });
      molecuel.on('mlcl::elastic::registerPlugin:post',function(el, modelname, schema) {
        schema.methods.search.should.be.a.function;
        schema.statics.searchById.should.be.a.function;
        schema.statics.searchByUrl.should.be.a.function;
        done();
      });
      model = dbcon.registerModel('test', testSchema, {indexable:true});
    });

    it('should add german object to the index', function(done) {
      searchcon.index('test', testobjDe, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        done();
      });
    });

    it('should add english object to the index', function(done) {
      searchcon.index('test', testobjEn, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        // timeout before reading the data
        setTimeout(function() {
          done();
        }, 1000);
      });
    });

    it('should get german object by URL', function(done) {
      searchcon.searchByUrl(testobjDe.url, testobjDe.lang, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        should.exists(result.hits.hits[0]);
        result.hits.hits[0].should.be.a.object;
        done();
      });
    });

    it('should get english object by URL', function(done) {
      searchcon.searchByUrl(testobjEn.url, testobjEn.lang, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        should.exists(result.hits.hits[0]);
        result.hits.hits[0].should.be.a.object;
        done();
      });
    });

    it('should get a object by id', function(done) {
      searchcon.searchById('123456', function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        should.exists(result.hits.hits[0]);
        result.hits.hits[0].should.be.a.object;
        done();
      });
    });

    it('should save to mongodb', function(done) {
      mongoobj = new model({
        name: 'testname',
        url: '/mytesturl',
        lang: 'de'
      });

      mongoobj.save(function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        // timeout before reading the data
        setTimeout(function() {
          done();
        }, 1000);
      });
    });

    it('should search by db connection static function', function(done) {
      searchcon.searchByUrl(mongoobj.url, mongoobj.lang, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        should.exists(result.hits.hits[0]);
        result.hits.hits[0].should.be.a.object;
        done();
      });
    });

    after(function(done) {
      dbcon.database.connection.db.dropDatabase(function(error) {
        should.not.exists(error);
        searchcon.deleteIndex('*', function(error) {
          should.not.exists(error);
          done();
        });
      });
    });
  });
});
<commit_msg>add timeout after registering the model<commit_after>/**
 * Created by dob on 20.11.13.
 */
var should = require('should'),
  util = require('util'),
  EventEmitter = require('events').EventEmitter,
  mlcl_database = require('mlcl_database'),
  mlcl_elastic = require('../');

describe('mlcl_elastic', function() {
  var mlcl;
  var molecuel;
  var mongo;
  var testobjEn;
  var testobjDe;

  before(function(done) {
    // init fake molecuel
    mlcl = function() {
      return this;
    };
    util.inherits(mlcl, EventEmitter);
    molecuel = new mlcl();

    molecuel.config = { };
    molecuel.config.search = {
      host: 'localhost',
      port: '9200',
      prefix: 'mlcl-elastic-unit'
    };
    molecuel.config.database = {
      type: 'mongodb',
      uri: 'mongodb://localhost/mlcl-elastic-unit'
    };
    mongo = mlcl_database(molecuel);
    mlcl_elastic(molecuel);

    testobjEn = {
      '_id': '98098098',
      'title': 'test title',
      'lang': 'en',
      'url': '/test_title'
    };

    testobjDe = {
      '_id': '123456',
      'title': 'test title',
      'lang': 'de',
      'url': '/test_title'
    };
    done();
  });

  describe('elastic', function() {
    var searchcon;
    var dbcon;
    var model;
    var mongoobj;

    it('should initialize db connection', function(done) {
      molecuel.once('mlcl::database::connection:success', function(database) {
        dbcon = database;
        database.should.be.a.object;
        done();
      });
      molecuel.emit('mlcl::core::init:post', molecuel);
    });

    it('should initialize search connection', function(done) {
      molecuel.once('mlcl::search::connection:success', function(search) {
        searchcon = search;
        search.should.be.a.object;
        done();
      });
      molecuel.emit('mlcl::core::init:post', molecuel);
    });

    it('should initialize schema plugin', function(done) {
      var Schema = dbcon.database.Schema;
      var testSchema = new Schema({
        name: {type: String},
        url: {type: String},
        lang: {type: String}
      });
      molecuel.on('mlcl::elastic::registerPlugin:post',function(el, modelname, schema) {
        schema.methods.search.should.be.a.function;
        schema.statics.searchById.should.be.a.function;
        schema.statics.searchByUrl.should.be.a.function;
        setTimeout(function() {
          done();
        }, 1000);
      });
      model = dbcon.registerModel('test', testSchema, {indexable:true});
    });

    it('should add german object to the index', function(done) {
      searchcon.index('test', testobjDe, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        done();
      });
    });

    it('should add english object to the index', function(done) {
      searchcon.index('test', testobjEn, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        // timeout before reading the data
        setTimeout(function() {
          done();
        }, 1000);
      });
    });

    it('should get german object by URL', function(done) {
      searchcon.searchByUrl(testobjDe.url, testobjDe.lang, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        should.exists(result.hits.hits[0]);
        result.hits.hits[0].should.be.a.object;
        done();
      });
    });

    it('should get english object by URL', function(done) {
      searchcon.searchByUrl(testobjEn.url, testobjEn.lang, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        should.exists(result.hits.hits[0]);
        result.hits.hits[0].should.be.a.object;
        done();
      });
    });

    it('should get a object by id', function(done) {
      searchcon.searchById('123456', function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        should.exists(result.hits.hits[0]);
        result.hits.hits[0].should.be.a.object;
        done();
      });
    });

    it('should save to mongodb', function(done) {
      mongoobj = new model({
        name: 'testname',
        url: '/mytesturl',
        lang: 'de'
      });

      mongoobj.save(function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        // timeout before reading the data
        setTimeout(function() {
          done();
        }, 1000);
      });
    });

    it('should search by db connection static function', function(done) {
      searchcon.searchByUrl(mongoobj.url, mongoobj.lang, function(error, result) {
        should.not.exists(error);
        result.should.be.a.object;
        should.exists(result.hits.hits[0]);
        result.hits.hits[0].should.be.a.object;
        done();
      });
    });

    after(function(done) {
      dbcon.database.connection.db.dropDatabase(function(error) {
        should.not.exists(error);
        searchcon.deleteIndex('*', function(error) {
          should.not.exists(error);
          done();
        });
      });
    });
  });
});
<|endoftext|>


<commit_before>import _assign from 'lodash/assign'
import _find from 'lodash/find'
import localForage from 'localforage'

export default class DictionariesManager {
  constructor() {
    this.dictionaries = null
    return this.getDictionaries().then((dictionaries) => {
      this.dictionaries = dictionaries || []
      return this
    })
  }

  async saveDictionary(newDictionary, forceFlag) {
    let storageDictionary = this.getDictionary({id: newDictionary.id, domain: newDictionary.domain})
    if(storageDictionary) {
      if(!forceFlag && storageDictionary.raw && newDictionary.raw) {
        let newRubies = this.getNewRubiesOnly(newDictionary, storageDictionary)
        newDictionary.raw = newRubies.length
          ? storageDictionary.raw + `\n${this.getDictionaryText(newRubies)}`
          : storageDictionary.raw
      }
    } else {
      newDictionary.raw = newDictionary.raw || ''
      this.dictionaries.push(newDictionary)
    }
    _assign(storageDictionary, newDictionary)
    await localForage.setItem('dictionaries', this.dictionaries)
    return storageDictionary
  }

  getDictionary(findOption) {
    // standard findOption: {id: 'xxx', domain: 'xxx'}
    return _find(this.dictionaries, findOption)
  }

  async getDictionaries() {
    return await localForage.getItem('dictionaries')
  }

  getNewRubiesOnly(newDictionary, oldDictionary) {
    return this.getRubies(newDictionary.raw).filter((ruby) => {
      return _find(this.getRubies(oldDictionary.raw), ruby) == undefined
    })
  }

  getDictionaryText(rubies) {
    let dictionaryText = ''
    rubies.forEach((ruby) => {
      dictionaryText += `${ruby.rb}::${ruby.rt}\n`
    })
    return dictionaryText.trim()
  }

  getRubies(dictionaryText) {
    let lines = dictionaryText.split('\n').filter((ruby) => {
      return !/^\/\//.test(ruby) && ruby != ''
    })
    let rubies = []
    lines.forEach((line) => {
      let splited = line.split('::')
      rubies.push({rb: splited[0], rt: splited[1]})
    })
    return rubies
  }
}
<commit_msg>fix for saveDictionary function<commit_after>import _assign from 'lodash/assign'
import _merge from 'lodash/merge'
import _find from 'lodash/find'
import localForage from 'localforage'

export default class DictionariesManager {
  constructor() {
    this.dictionaries = null
    return this.getDictionaries().then((dictionaries) => {
      this.dictionaries = dictionaries || []
      return this
    })
  }

  async saveDictionary(newDictionary, forceFlag) {
    let storageDictionary = this.getDictionary({id: newDictionary.id, domain: newDictionary.domain})
    if(storageDictionary) {
      if(!forceFlag) {
        if(newDictionary.raw) {
          let newline = storageDictionary.raw ? '\n' : ''
          let newRubies = this.getNewRubiesOnly(newDictionary, storageDictionary)
          newDictionary.raw = newRubies.length ?
            storageDictionary.raw + newline + this.getDictionaryText(newRubies) :
            storageDictionary.raw
        } else {
          newDictionary.raw = storageDictionary.raw
        }
      }
    } else {
      newDictionary.raw = newDictionary.raw || ''
      this.dictionaries.push(newDictionary)
    }
    _assign(storageDictionary, newDictionary)
    await localForage.setItem('dictionaries', this.dictionaries)
    return storageDictionary
  }

  getDictionary(findOption) {
    // standard findOption: {id: 'xxx', domain: 'xxx'}
    return _find(this.dictionaries, findOption)
  }

  async getDictionaries() {
    return await localForage.getItem('dictionaries')
  }

  getNewRubiesOnly(newDictionary, oldDictionary) {
    return this.getRubies(newDictionary.raw).filter((ruby) => {
      return _find(this.getRubies(oldDictionary.raw), ruby) == undefined
    })
  }

  getDictionaryText(rubies) {
    let dictionaryText = ''
    rubies.forEach((ruby) => {
      dictionaryText += `${ruby.rb}::${ruby.rt}\n`
    })
    return dictionaryText.trim()
  }

  getRubies(dictionaryText) {
    let lines = dictionaryText.split('\n').filter((ruby) => {
      return !/^\/\//.test(ruby) && ruby != ''
    })
    let rubies = []
    lines.forEach((line) => {
      let splited = line.split('::')
      rubies.push({rb: splited[0], rt: splited[1]})
    })
    return rubies
  }
}
<|endoftext|>


<commit_before>var getFixtures = require("babel-helper-fixtures").multiple;
var parse       = require("../lib").parse;
var test        = require("ava");
var _           = require("lodash");

var fixtures = getFixtures(__dirname + "/fixtures");

_.each(fixtures, function (suites, name) {
  _.each(suites, function (testSuite) {
    _.each(testSuite.tests, function (task) {
      test(name + "/" + testSuite.title + "/" + task.title, !task.disabled && function () {
        try {
          return runTest(task);
        } catch (err) {
          err.message = task.actual.loc + ": " + err.message;
          throw err;
        }
      });
    });
  });
});

function save(test, ast) {
  delete ast.tokens;
  if (!ast.comments.length) delete ast.comments;
  require("fs").writeFileSync(test.expect.loc, JSON.stringify(ast, null, "  "));
}

function runTest(test) {
  var opts = test.options;
  opts.locations = true;
  opts.ranges = true;

  try {
    var ast = parse(test.actual.code, opts);
  } catch (err) {
    if (opts.throws) {
      if (err.message === opts.throws) {
        return;
      } else {
        err.message = "Expected error message: " + opts.throws + ". Got error message: " + err.message;
        throw err;
      }
    }

    throw err;
  }

  if (!test.expect.code) {
    test.expect.loc += "on";
    return save(test, ast);
  }

  if (opts.throws) {
    throw new Error("Expected error message: " + opts.throws + ". But parsing succeeded.");
  } else {
    var mis = misMatch(JSON.parse(test.expect.code), ast);
    if (mis) {
      //save(test, ast);
      throw new Error(mis);
    }
  }
}

function ppJSON(v) {
  return v instanceof RegExp ? v.toString() : JSON.stringify(v, null, 2);
}

function addPath(str, pt) {
  if (str.charAt(str.length - 1) == ")") {
    return str.slice(0, str.length - 1) + "/" + pt + ")";
  } else {
    return str + " (" + pt + ")";
  }
}

function misMatch(exp, act) {
  if (!exp || !act || (typeof exp != "object") || (typeof act != "object")) {
    if (exp !== act && typeof exp != "function")
      return ppJSON(exp) + " !== " + ppJSON(act);
  } else if (exp instanceof RegExp || act instanceof RegExp) {
    var left = ppJSON(exp), right = ppJSON(act);
    if (left !== right) return left + " !== " + right;
  } else if (exp.splice) {
    if (!act.slice) return ppJSON(exp) + " != " + ppJSON(act);
    if (act.length != exp.length) return "array length mismatch " + exp.length + " != " + act.length;
    for (var i = 0; i < act.length; ++i) {
      var mis = misMatch(exp[i], act[i]);
      if (mis) return addPath(mis, i);
    }
  } else {
    for (var prop in exp) {
      var mis = misMatch(exp[prop], act[prop]);
      if (mis) return addPath(mis, prop);
    }
  }
}
<commit_msg>Fix tests to not save expected output if we expect the test to fail<commit_after>var getFixtures = require("babel-helper-fixtures").multiple;
var parse       = require("../lib").parse;
var test        = require("ava");
var _           = require("lodash");

var fixtures = getFixtures(__dirname + "/fixtures");

_.each(fixtures, function (suites, name) {
  _.each(suites, function (testSuite) {
    _.each(testSuite.tests, function (task) {
      test(name + "/" + testSuite.title + "/" + task.title, !task.disabled && function () {
        try {
          return runTest(task);
        } catch (err) {
          err.message = task.actual.loc + ": " + err.message;
          throw err;
        }
      });
    });
  });
});

function save(test, ast) {
  delete ast.tokens;
  if (!ast.comments.length) delete ast.comments;
  require("fs").writeFileSync(test.expect.loc, JSON.stringify(ast, null, "  "));
}

function runTest(test) {
  var opts = test.options;
  opts.locations = true;
  opts.ranges = true;

  try {
    var ast = parse(test.actual.code, opts);
  } catch (err) {
    if (opts.throws) {
      if (err.message === opts.throws) {
        return;
      } else {
        err.message = "Expected error message: " + opts.throws + ". Got error message: " + err.message;
        throw err;
      }
    }

    throw err;
  }

  if (!test.expect.code && !opts.throws) {
    test.expect.loc += "on";
    return save(test, ast);
  }

  if (opts.throws) {
    throw new Error("Expected error message: " + opts.throws + ". But parsing succeeded.");
  } else {
    var mis = misMatch(JSON.parse(test.expect.code), ast);
    if (mis) {
      //save(test, ast);
      throw new Error(mis);
    }
  }
}

function ppJSON(v) {
  return v instanceof RegExp ? v.toString() : JSON.stringify(v, null, 2);
}

function addPath(str, pt) {
  if (str.charAt(str.length - 1) == ")") {
    return str.slice(0, str.length - 1) + "/" + pt + ")";
  } else {
    return str + " (" + pt + ")";
  }
}

function misMatch(exp, act) {
  if (!exp || !act || (typeof exp != "object") || (typeof act != "object")) {
    if (exp !== act && typeof exp != "function")
      return ppJSON(exp) + " !== " + ppJSON(act);
  } else if (exp instanceof RegExp || act instanceof RegExp) {
    var left = ppJSON(exp), right = ppJSON(act);
    if (left !== right) return left + " !== " + right;
  } else if (exp.splice) {
    if (!act.slice) return ppJSON(exp) + " != " + ppJSON(act);
    if (act.length != exp.length) return "array length mismatch " + exp.length + " != " + act.length;
    for (var i = 0; i < act.length; ++i) {
      var mis = misMatch(exp[i], act[i]);
      if (mis) return addPath(mis, i);
    }
  } else {
    for (var prop in exp) {
      var mis = misMatch(exp[prop], act[prop]);
      if (mis) return addPath(mis, prop);
    }
  }
}
<|endoftext|>


<commit_before>var tape = require('tape')
var crypto = require('crypto')
var b = require('../')

tape('simple', function (t) {

  var byte = b.byte
  var double = b.Double

  t.equal(byte.decode(byte.encode(9)), 9)
  t.equal(byte.decode.bytesRead, 1)
  t.equal(byte.encode.bytesWritten, 1)
  var r = Math.random()
  t.equal(double.decode(double.encode(r)), r)
  t.equal(double.decode.bytesRead, 8)
  t.equal(double.encode.bytesWritten, 8)
  t.end()
})

tape('vector', function (t) {
  var double = b.Double

  var vector = b({
    x: double,
    y: double,
    z: double
  })

  var v = {x: 1, y: 2, z: 3}
  var buffer = vector.encode(v)
  t.equal(vector.encode.bytesWritten, 24)
  console.log(buffer)
  t.equal(buffer.length, vector.length)
  t.deepEqual(vector.decode(buffer), v)
  t.equal(vector.decode.bytesRead, 24)
  t.end()
})

tape('buffer', function (t) {

  var sha256 = b.array(32) //a fixed length buffer

  var message = b({
    num : b.byte,
    hash: sha256
  })

  t.equal(message.length, 33)

  var expected = {
    num: 25,
    hash: crypto.createHash('sha256').digest()
  }
  var buffer = message.encode(expected)
  t.equal(message.encode.bytesWritten, 33)
  t.equal(sha256.encode.bytesWritten, 32)
  t.equal(buffer.length, 33)

  t.deepEqual(message.decode(buffer), expected)
  t.equal(sha256.decode.bytesRead, 32)
  t.equal(message.decode.bytesRead, 33)
  t.end()

})

tape('varbuf', function (t) {
  var slice = b.varbuf(b.byte)
  var expected = new Buffer([1, 2, 3, 4, 5])
  var buffer = slice.encode(expected)
  t.deepEqual(buffer, new Buffer([5, 1, 2, 3, 4, 5]))
  t.deepEqual(slice.decode(buffer), expected)
  t.end()
})

tape('varbuf + static', function (t) {

  var sha256 = b.array(32)

  var message = b({
    prev: sha256,
    author: sha256,
    sequence: b.UInt32,
    type: sha256,
    message: b.varbuf(b.byte)
  })
  var empty = crypto.createHash('sha256').digest()

  var zeros = new Buffer(32); zeros.fill()

  var expected = {
    prev     : empty, author : empty,
    sequence : 0,     type   : zeros,
    message  : new Buffer('hello there this is the first message', 'utf8')
  }

  var buffer = message.encode(expected)
  var expectedLength = 32 + 32 + 4 + 32 + expected.message.length + 1

  t.equal(message.encode.bytesWritten, expectedLength)

  t.deepEqual(message.decode(buffer), expected)
  t.equal(message.decode.bytesRead, expectedLength)

  t.end()

})

tape('varint buffer', function (t) {

  var buf = b.varbuf(b.varint)

  var buffer = buf.encode(new Buffer('hello'))
  console.log('out', buffer)
  t.deepEqual(new Buffer([0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f]), buffer)

  var expected = new Buffer(
    'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  )

  var buffer = buf.encode(expected)

  console.log(buffer)
  t.equal(buffer.length, expected.length + 2)
  t.equal(buf.encode.bytesWritten, expected.length + 2)
  t.deepEqual(buf.decode(buffer), expected)
  t.equal(buf.decode.bytesRead, expected.length + 2)
  t.end()
})

tape('vararray', function (t) {

  var array = b.vararray(b.byte, b.DoubleBE)
  var expected = [
    Math.random(), Math.random(), Math.random(), Math.random(),
    Math.random(), Math.random(), Math.random(), Math.random(),
    Math.random(), Math.random(), Math.random(), Math.random(),
    Math.random(), Math.random(), Math.random(), Math.random(),
  ]

  var expectedLength = 1 + 8*4*4
  t.equal(array.dynamicLength(expected), expectedLength)
  var buffer = array.encode(expected)
  t.equal(array.encode.bytesWritten, expectedLength)
  console.log(buffer)
  t.deepEqual(array.decode(buffer), expected)
  t.equal(array.decode.bytesRead, expectedLength)
  t.end()
})

tape('varstruct inside array', function (t) {
  var struct = b({
    i: b.varint,
    d: b.Double
  })
  var array = b.vararray(b.varint, struct)

  var expected = [          //length of varint
    {i:10, d:0.1},          //1
    {i:142, d:0.1231},      //2
    {i:123456,d:1e23},      //3
    {i:8383838,d:1e23},     //4
    {i:4000000000, d:2e-17} //5
  ]

  var buffer = array.encode(expected)
  var length = 1+2+3+4+5+(5*8)+1
  t.equal(array.encode.bytesWritten, length, 'bytesWritten')
  t.equal(array.dynamicLength(expected), length, 'dynamicLength()')
  t.deepEqual(array.decode(buffer), expected)
  t.equal(array.decode.bytesRead, array.encode.bytesWritten)
  t.end()
})
<commit_msg>bind a number to a range<commit_after>var tape = require('tape')
var crypto = require('crypto')
var b = require('../')

tape('simple', function (t) {

  var byte = b.byte
  var double = b.Double

  t.equal(byte.decode(byte.encode(9)), 9)
  t.equal(byte.decode.bytesRead, 1)
  t.equal(byte.encode.bytesWritten, 1)
  var r = Math.random()
  t.equal(double.decode(double.encode(r)), r)
  t.equal(double.decode.bytesRead, 8)
  t.equal(double.encode.bytesWritten, 8)
  t.end()
})

tape('vector', function (t) {
  var double = b.Double

  var vector = b({
    x: double,
    y: double,
    z: double
  })

  var v = {x: 1, y: 2, z: 3}
  var buffer = vector.encode(v)
  t.equal(vector.encode.bytesWritten, 24)
  console.log(buffer)
  t.equal(buffer.length, vector.length)
  t.deepEqual(vector.decode(buffer), v)
  t.equal(vector.decode.bytesRead, 24)
  t.end()
})

tape('buffer', function (t) {

  var sha256 = b.array(32) //a fixed length buffer

  var message = b({
    num : b.byte,
    hash: sha256
  })

  t.equal(message.length, 33)

  var expected = {
    num: 25,
    hash: crypto.createHash('sha256').digest()
  }
  var buffer = message.encode(expected)
  t.equal(message.encode.bytesWritten, 33)
  t.equal(sha256.encode.bytesWritten, 32)
  t.equal(buffer.length, 33)

  t.deepEqual(message.decode(buffer), expected)
  t.equal(sha256.decode.bytesRead, 32)
  t.equal(message.decode.bytesRead, 33)
  t.end()

})

tape('varbuf', function (t) {
  var slice = b.varbuf(b.byte)
  var expected = new Buffer([1, 2, 3, 4, 5])
  var buffer = slice.encode(expected)
  t.deepEqual(buffer, new Buffer([5, 1, 2, 3, 4, 5]))
  t.deepEqual(slice.decode(buffer), expected)
  t.end()
})

tape('varbuf + static', function (t) {

  var sha256 = b.array(32)

  var message = b({
    prev: sha256,
    author: sha256,
    sequence: b.UInt32,
    type: sha256,
    message: b.varbuf(b.byte)
  })
  var empty = crypto.createHash('sha256').digest()

  var zeros = new Buffer(32); zeros.fill()

  var expected = {
    prev     : empty, author : empty,
    sequence : 0,     type   : zeros,
    message  : new Buffer('hello there this is the first message', 'utf8')
  }

  var buffer = message.encode(expected)
  var expectedLength = 32 + 32 + 4 + 32 + expected.message.length + 1

  t.equal(message.encode.bytesWritten, expectedLength)

  t.deepEqual(message.decode(buffer), expected)
  t.equal(message.decode.bytesRead, expectedLength)

  t.end()

})

tape('varint buffer', function (t) {

  var buf = b.varbuf(b.varint)

  var buffer = buf.encode(new Buffer('hello'))
  console.log('out', buffer)
  t.deepEqual(new Buffer([0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f]), buffer)

  var expected = new Buffer(
    'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  + 'hellohellohellohellohellohellohellohellohellohellohellohello\n'
  )

  var buffer = buf.encode(expected)

  console.log(buffer)
  t.equal(buffer.length, expected.length + 2)
  t.equal(buf.encode.bytesWritten, expected.length + 2)
  t.deepEqual(buf.decode(buffer), expected)
  t.equal(buf.decode.bytesRead, expected.length + 2)
  t.end()
})

tape('vararray', function (t) {

  var array = b.vararray(b.byte, b.DoubleBE)
  var expected = [
    Math.random(), Math.random(), Math.random(), Math.random(),
    Math.random(), Math.random(), Math.random(), Math.random(),
    Math.random(), Math.random(), Math.random(), Math.random(),
    Math.random(), Math.random(), Math.random(), Math.random(),
  ]

  var expectedLength = 1 + 8*4*4
  t.equal(array.dynamicLength(expected), expectedLength)
  var buffer = array.encode(expected)
  t.equal(array.encode.bytesWritten, expectedLength)
  console.log(buffer)
  t.deepEqual(array.decode(buffer), expected)
  t.equal(array.decode.bytesRead, expectedLength)
  t.end()
})

tape('varstruct inside array', function (t) {
  var struct = b({
    i: b.varint,
    d: b.Double
  })
  var array = b.vararray(b.varint, struct)

  var expected = [          //length of varint
    {i:10, d:0.1},          //1
    {i:142, d:0.1231},      //2
    {i:123456,d:1e23},      //3
    {i:8383838,d:1e23},     //4
    {i:4000000000, d:2e-17} //5
  ]

  var buffer = array.encode(expected)
  var length = 1+2+3+4+5+(5*8)+1
  t.equal(array.encode.bytesWritten, length, 'bytesWritten')
  t.equal(array.dynamicLength(expected), length, 'dynamicLength()')
  t.deepEqual(array.decode(buffer), expected)
  t.equal(array.decode.bytesRead, array.encode.bytesWritten)
  t.end()
})

tape('bounded numbers', function (t) {

  var max32 = b.bound(b.byte, 0, 32)
  var buffer = max32.encode(31)
  console.log(buffer)
  t.deepEqual(buffer, new Buffer([31]))
  t.equal(max32.decode(buffer), 31)
  t.throws(function () {
    max32.encode(33)
  })
  t.end()
})
<|endoftext|>