<commit_before>// variable init
var map;
var info;
var regions_geojson;
var job_types_by_region;
var job_types_by_lep;
var display_columns_all = ['region_or_nation','job_family','occupation', 'demand_entry', 'demand_ticker', 'demand_entry_hs', 'demand_entry_fe', 'demand_entry_he'];
var display_columns_region = ['job_family','occupation', 'demand_entry', 'demand_ticker', 'demand_entry_hs', 'demand_entry_fe', 'demand_entry_he'];
var region_lep_mapping

// do stuff when the page loads
(function(){

    $("#detail-content").hide()

    map = L.map('map-select', {
        scrollWheelZoom: false,
        center: [55, -3.5],
        zoom: 4,
        attributionControl: false,
        zoomControl:false
    });

    initializeMapSelect(map);

    $.when($.getJSON('data/merged_regions.geojson'), $.get('data/job_types_by_region.csv')).then(function(geojson, csv){
        regions_geojson = L.geoJson(geojson[0], geojson_opts).addTo(map);
        job_types_by_region = _.where($.csv.toObjects(csv[0]), {medium_skilled: "1"});

        var table_guts = sliceColumns(job_types_by_region, display_columns_all);

        var agg_demand = _.chain(job_types_by_region)
            .groupBy("occupation")
            .map(function(value, key) {
                return {
                    occupation: key,
                    demand_entry: sum(_.pluck(value, "demand_entry")),
                    advertised_avg_salary_entry_degree: parseFloat(value[0]["advertised_avg_salary_entry_degree"])
                }
            })
            .value();

        if($.address.parameter("region")){
            if($.address.parameter("lep")){
                updateLep(decodeURIComponent($.address.parameter("region")), decodeURIComponent($.address.parameter("lep")), $.address.parameter("education"))
            }
            else{
                updateRegion(decodeURIComponent($.address.parameter("region")), $.address.parameter("education"))
            }
        }
        else{
            makeDemandScatterPlot('#agg-scatter', agg_demand);
        }

    });

    $.when($.get('data/job_types_by_lep_merge.csv')).then(function(csv){
        job_types_by_lep = _.where($.csv.toObjects(csv), {medium_skilled: "1"});

        region_lep_mapping = _.chain(job_types_by_lep).groupBy("region_or_nation").map(function(value, key) {
            return {
                region_or_nation: key,
                leps_within: _.uniq(_.pluck(value, "lep"))
            }
        }).value()

        // populating select menu w/ regions & leps
        $.each(region_lep_mapping, function(index, value){
            var r = value['region_or_nation']
            $('#list-select').append('
'+toTitleCase(r)+'
')
            $.each(value['leps_within'] , function(index, value){
                $('#list-select').append('
'+value+'
')
                $('.option-lep').last().click(function() {
                    updateLep(r, value, 'fe')
                    return false;
                });
            });

            $('.option-region').last().click(function() {
                updateRegion(r, 'fe')
                return false;
            });
        });

    });

})()

function updateLep(region_name, lep_name, education){

    $.address.parameter('region', region_name);
    $.address.parameter('lep', lep_name);
    $.address.parameter('education', education);

    if (education=='he'){
        var lep_data = _.where(job_types_by_lep, {lep: lep_name, include_he: "1"})
    }
    else{
        var lep_data = _.where(job_types_by_lep, {lep: lep_name, include_fe: "1"})
    }

    // TO DO: add lep point to selector map & clear any region highlighting
    // (will also need to clear all lep points in updateRegion)

    $("#default-content").hide()
    $("#detail-content").show()
    $("#content-heading").html('The United Kingdom » '+toTitleCase(region_name)+' » '+lep_name+'');
    $('.option-region').last().click(function() {
        updateRegion(region_name, 'fe')
        return false;
    });

    makeBubbleChart(lep_data);
}

function updateRegion(region_name, education){

    $.address.parameter('region', region_name);
    $.address.parameter('education', education);

    regions_geojson.eachLayer(function(layer){
        if(layer.feature.properties['JOB_REGION'] != region_name){
            layer.feature.properties['selected'] = false
            layer.setStyle({'fillOpacity': 0.2, 'color': '#fbab18'});
        }
        else{
            layer.feature.properties['selected'] = true
            layer.setStyle({'fillOpacity': 0.8, 'color': '#fbab18'});
        }
    })

    if (education=='he'){
        var place_data = _.where(job_types_by_region, {region_or_nation: region_name, include_he: "1"})
        $("#detail-scatter-title").html("Occupations — Higher Education")
        $("#detail-scatter-change-edu").text("View Further Education")
        $('#detail-scatter-change-edu').click(function() {
            updateRegion(region_name, 'fe')
            return false;
        });
    }
    else{
        var place_data = _.where(job_types_by_region, {region_or_nation: region_name, include_fe: "1"})
        $("#detail-scatter-title").html("Occupations — Further Education")
        $("#detail-scatter-change-edu").text("View Higher Education")
        $('#detail-scatter-change-edu').click(function() {
            updateRegion(region_name, 'he')
            return false;
        });
    }
    // var table_guts = sliceColumns(place_data, display_columns_region);

    $("#default-content").hide()
    $("#detail-content").show()
    $("#content-heading").html('The United Kingdom » ' + toTitleCase(region_name) + '');

    //makeBubbleChart(place_data);

    makeDemandBarChart('#region-bar-demand', place_data)
    makeDemandScatterPlot('#region-scatter-demand', place_data)
    makeCompScatterPlot('#region-scatter-comp', place_data)
    // initializeTable('#job-data-region', display_columns_region, table_guts);

}

<commit_msg>stacked bars for leps<commit_after>// variable init
var map;
var info;
var regions_geojson;
var job_types_by_region;
var job_types_by_lep;
var display_columns_all = ['region_or_nation','job_family','occupation', 'demand_entry', 'demand_ticker', 'demand_entry_hs', 'demand_entry_fe', 'demand_entry_he'];
var display_columns_region = ['job_family','occupation', 'demand_entry', 'demand_ticker', 'demand_entry_hs', 'demand_entry_fe', 'demand_entry_he'];
var region_lep_mapping

// do stuff when the page loads
(function(){

    $("#detail-content").hide()

    map = L.map('map-select', {
        scrollWheelZoom: false,
        center: [55, -3.5],
        zoom: 4,
        attributionControl: false,
        zoomControl:false
    });

    initializeMapSelect(map);

    $.when($.getJSON('data/merged_regions.geojson'), $.get('data/job_types_by_region.csv')).then(function(geojson, csv){
        regions_geojson = L.geoJson(geojson[0], geojson_opts).addTo(map);
        job_types_by_region = _.where($.csv.toObjects(csv[0]), {medium_skilled: "1"});

        var table_guts = sliceColumns(job_types_by_region, display_columns_all);

        var agg_demand = _.chain(job_types_by_region)
            .groupBy("occupation")
            .map(function(value, key) {
                return {
                    occupation: key,
                    demand_entry: sum(_.pluck(value, "demand_entry")),
                    advertised_avg_salary_entry_degree: parseFloat(value[0]["advertised_avg_salary_entry_degree"])
                }
            })
            .value();

        if($.address.parameter("region")){
            if($.address.parameter("lep")){
                updateLep(decodeURIComponent($.address.parameter("region")), decodeURIComponent($.address.parameter("lep")), $.address.parameter("education"))
            }
            else{
                updateRegion(decodeURIComponent($.address.parameter("region")), $.address.parameter("education"))
            }
        }
        else{
            makeDemandScatterPlot('#agg-scatter', agg_demand);
        }

    });

    $.when($.get('data/job_types_by_lep_merge.csv')).then(function(csv){
        job_types_by_lep = _.where($.csv.toObjects(csv), {medium_skilled: "1"});

        region_lep_mapping = _.chain(job_types_by_lep).groupBy("region_or_nation").map(function(value, key) {
            return {
                region_or_nation: key,
                leps_within: _.uniq(_.pluck(value, "lep"))
            }
        }).value()

        // populating select menu w/ regions & leps
        $.each(region_lep_mapping, function(index, value){
            var r = value['region_or_nation']
            $('#list-select').append('
'+toTitleCase(r)+'
')
            $.each(value['leps_within'] , function(index, value){
                $('#list-select').append('
'+value+'
')
                $('.option-lep').last().click(function() {
                    updateLep(r, value, 'fe')
                    return false;
                });
            });

            $('.option-region').last().click(function() {
                updateRegion(r, 'fe')
                return false;
            });
        });

    });

})()

function updateLep(region_name, lep_name, education){

    $.address.parameter('region', region_name);
    $.address.parameter('lep', lep_name);
    $.address.parameter('education', education);

    var lep_data = _.where(job_types_by_lep, {lep: lep_name})
    if (education=='he'){
        var lep_data_scatter = _.where(job_types_by_lep, {lep: lep_name, include_he: "1"})
    }
    else{
        var lep_data_scatter = _.where(job_types_by_lep, {lep: lep_name, include_fe: "1"})
    }

    // TO DO: add lep point to selector map & clear any region highlighting
    // (will also need to clear all lep points in updateRegion)

    $("#default-content").hide()
    $("#detail-content").show()
    $("#content-heading").html('The United Kingdom » '+toTitleCase(region_name)+' » '+lep_name+'');
    $('.option-region').last().click(function() {
        updateRegion(region_name, 'fe')
        return false;
    });

    makeDemandBarChart('#region-bar-demand', lep_data)
    makeDemandScatterPlot('#region-scatter-demand', lep_data_scatter)
    makeCompScatterPlot('#region-scatter-comp', lep_data_scatter)
}

function updateRegion(region_name, education){

    $.address.parameter('region', region_name);
    $.address.parameter('education', education);

    regions_geojson.eachLayer(function(layer){
        if(layer.feature.properties['JOB_REGION'] != region_name){
            layer.feature.properties['selected'] = false
            layer.setStyle({'fillOpacity': 0.2, 'color': '#fbab18'});
        }
        else{
            layer.feature.properties['selected'] = true
            layer.setStyle({'fillOpacity': 0.8, 'color': '#fbab18'});
        }
    })

    var place_data = _.where(job_types_by_region, {region_or_nation: region_name})
    if (education=='he'){
        var place_data_scatter = _.where(job_types_by_region, {region_or_nation: region_name, include_he: "1"})
        $("#detail-scatter-title").html("Occupations — Higher Education")
        $("#detail-scatter-change-edu").text("View Further Education")
        $('#detail-scatter-change-edu').click(function() {
            updateRegion(region_name, 'fe')
            return false;
        });
    }
    else{
        var place_data_scatter = _.where(job_types_by_region, {region_or_nation: region_name, include_fe: "1"})
        $("#detail-scatter-title").html("Occupations — Further Education")
        $("#detail-scatter-change-edu").text("View Higher Education")
        $('#detail-scatter-change-edu').click(function() {
            updateRegion(region_name, 'he')
            return false;
        });
    }
    // var table_guts = sliceColumns(place_data, display_columns_region);

    $("#default-content").hide()
    $("#detail-content").show()
    $("#content-heading").html('The United Kingdom » ' + toTitleCase(region_name) + '');

    //makeBubbleChart(place_data);

    makeDemandBarChart('#region-bar-demand', place_data)
    makeDemandScatterPlot('#region-scatter-demand', place_data_scatter)
    makeCompScatterPlot('#region-scatter-comp', place_data_scatter)
    // initializeTable('#job-data-region', display_columns_region, table_guts);

}

<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * 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.
 */

// Generic functions applicable to all track types

var igv = (function (igv) {

    /**
     * Set defaults for properties applicable to all tracks.
     * Insure required "config" properties are set.
     * @param track
     * @param config
     */
    igv.configTrack = function (track, config) {

        track.config = config;
        track.url = config.url;

        config.name = config.name || config.label;   // synonym for name, label is deprecated
        if (config.name) {
            track.name = config.name;
        }
        else {
            if (config.localFile) track.name = config.localFile.name;
            else track.name = config.url;

        }

        track.id = config.id || track.name;   // TODO -- remove this property, not used

        track.order = config.order;
        track.color = config.color || igv.browser.constants.defaultColor;

        track.removable = config.removable === undefined ? true : config.removable;      // Defaults to true

        track.height = config.height || ('wig' === config.type ? 50 : 100);

        if(config.autoHeight === undefined)  config.autoHeight = config.autoheight; // Some case confusion in the initial releasae

        track.autoHeight = config.autoHeight === undefined ?
            (config.height === undefined ? true : false) :
            config.autoHeight;
        track.minHeight = config.minHeight || Math.min(50, track.height);
        track.maxHeight = config.maxHeight || Math.max(500, track.height);

        if (config.visibilityWindow) {
            track.visibilityWindow = config.visibilityWindow;
        }

        if(track.type === undefined) track.type = config.type;
    };

    igv.setTrackLabel = function (track, label) {

        track.name = label;

        track.trackView.$viewport.find('.igv-track-label').html(track.name);

        if (track.trackView) {
            track.trackView.repaint();
        }
    };

    igv.setTrackColor = function (track, color) {

        track.color = color;

        if (track.trackView) {

            track.trackView.repaint();

        }

    };

    igv.paintAxis = function (ctx, pixelWidth, pixelHeight) {

        var x1,
            x2,
            y1,
            y2,
            a,
            b,
            reference,
            shim,
            font = {
                'font': 'normal 10px Arial',
                'textAlign': 'right',
                'strokeStyle': "black"
            };

        if (undefined === this.dataRange || undefined === this.dataRange.max || undefined === this.dataRange.min) {
            return;
        }

        igv.graphics.fillRect(ctx, 0, 0, pixelWidth, pixelHeight, {'fillStyle': "rgb(255, 255, 255)"});

        reference = 0.95 * pixelWidth;
        x1 = reference - 8;
        x2 = reference;

        //shim = 0.5 * 0.125;
        shim = .01;
        y1 = y2 = shim * pixelHeight;

        a = {x: x2, y: y1};

        // tick
        igv.graphics.strokeLine(ctx, x1, y1, x2, y2, font);
        igv.graphics.fillText(ctx, prettyPrint(this.dataRange.max), x1 + 4, y1 + 12, font);

        //shim = 0.25 * 0.125;
        y1 = y2 = (1.0 - shim) * pixelHeight;

        b = {x: x2, y: y1};

        // tick
        igv.graphics.strokeLine(ctx, x1, y1, x2, y2, font);
        igv.graphics.fillText(ctx, prettyPrint(this.dataRange.min), x1 + 4, y1 - 4, font);

        igv.graphics.strokeLine(ctx, a.x, a.y, b.x, b.y, font);

        function prettyPrint(number) {
            // if number >= 100, show whole number
            // if >= 1 show 1 significant digits
            // if <  1 show 2 significant digits

            if (number === 0) {
                return "0";
            } else if (Math.abs(number) >= 10) {
                return number.toFixed();
            } else if (Math.abs(number) >= 1) {
                return number.toFixed(1);
            } else {
                return number.toFixed(2);
            }
        }

    };

    return igv;
})(igv || {});<commit_msg>Bug fix. Track renaming now works.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * 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.
 */

// Generic functions applicable to all track types

var igv = (function (igv) {

    /**
     * Set defaults for properties applicable to all tracks.
     * Insure required "config" properties are set.
     * @param track
     * @param config
     */
    igv.configTrack = function (track, config) {

        track.config = config;
        track.url = config.url;

        config.name = config.name || config.label;   // synonym for name, label is deprecated
        if (config.name) {
            track.name = config.name;
        }
        else {
            if (config.localFile) track.name = config.localFile.name;
            else track.name = config.url;

        }

        track.id = config.id || track.name;   // TODO -- remove this property, not used

        track.order = config.order;
        track.color = config.color || igv.browser.constants.defaultColor;

        track.removable = config.removable === undefined ? true : config.removable;      // Defaults to true

        track.height = config.height || ('wig' === config.type ? 50 : 100);

        if(config.autoHeight === undefined)  config.autoHeight = config.autoheight; // Some case confusion in the initial releasae

        track.autoHeight = config.autoHeight === undefined ? (config.height === undefined) : config.autoHeight;
        track.minHeight = config.minHeight || Math.min(50, track.height);
        track.maxHeight = config.maxHeight || Math.max(500, track.height);

        if (config.visibilityWindow) {
            track.visibilityWindow = config.visibilityWindow;
        }

        if(track.type === undefined) track.type = config.type;
    };

    igv.setTrackLabel = function (track, label) {

        var vp = _.first(track.trackView.viewports);

        track.name = label;

        vp.$viewport.find('.igv-track-label').html(track.name);

        if (track.trackView) {
            track.trackView.repaint();
        }
    };

    igv.setTrackColor = function (track, color) {

        track.color = color;

        if (track.trackView) {

            track.trackView.repaint();

        }

    };

    igv.paintAxis = function (ctx, pixelWidth, pixelHeight) {

        var x1,
            x2,
            y1,
            y2,
            a,
            b,
            reference,
            shim,
            font = {
                'font': 'normal 10px Arial',
                'textAlign': 'right',
                'strokeStyle': "black"
            };

        if (undefined === this.dataRange || undefined === this.dataRange.max || undefined === this.dataRange.min) {
            return;
        }

        igv.graphics.fillRect(ctx, 0, 0, pixelWidth, pixelHeight, {'fillStyle': "rgb(255, 255, 255)"});

        reference = 0.95 * pixelWidth;
        x1 = reference - 8;
        x2 = reference;

        //shim = 0.5 * 0.125;
        shim = .01;
        y1 = y2 = shim * pixelHeight;

        a = {x: x2, y: y1};

        // tick
        igv.graphics.strokeLine(ctx, x1, y1, x2, y2, font);
        igv.graphics.fillText(ctx, prettyPrint(this.dataRange.max), x1 + 4, y1 + 12, font);

        //shim = 0.25 * 0.125;
        y1 = y2 = (1.0 - shim) * pixelHeight;

        b = {x: x2, y: y1};

        // tick
        igv.graphics.strokeLine(ctx, x1, y1, x2, y2, font);
        igv.graphics.fillText(ctx, prettyPrint(this.dataRange.min), x1 + 4, y1 - 4, font);

        igv.graphics.strokeLine(ctx, a.x, a.y, b.x, b.y, font);

        function prettyPrint(number) {
            // if number >= 100, show whole number
            // if >= 1 show 1 significant digits
            // if <  1 show 2 significant digits

            if (number === 0) {
                return "0";
            } else if (Math.abs(number) >= 10) {
                return number.toFixed();
            } else if (Math.abs(number) >= 1) {
                return number.toFixed(1);
            } else {
                return number.toFixed(2);
            }
        }

    };

    return igv;
})(igv || {});<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * The main 'kite' namespace object for the exported (non-Require.js) API. Used internally
 * since it prevents Require.js issues with circular dependencies.
 *
 * The returned kite object namespace may be incomplete if not all modules are listed as
 * dependencies. Please use the 'main' module for that purpose if all of Kite is desired.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

define( function( require ) {
  'use strict';

  // object allocation tracking
  window.phetAllocation = require( 'PHET_CORE/phetAllocation' );

  var kite = {
    svgNumber: function( n ) {
      return n.toFixed( 20 );
    }
  };

  // will be filled in by other modules
  return kite;
} );
<commit_msg>Adding arch undefined value workarounds<commit_after>// Copyright 2002-2014, University of Colorado Boulder

/**
 * The main 'kite' namespace object for the exported (non-Require.js) API. Used internally
 * since it prevents Require.js issues with circular dependencies.
 *
 * The returned kite object namespace may be incomplete if not all modules are listed as
 * dependencies. Please use the 'main' module for that purpose if all of Kite is desired.
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */

define( function( require ) {
  'use strict';

  // object allocation tracking
  window.phetAllocation = require( 'PHET_CORE/phetAllocation' );

  // workaround for Axon, since it needs window.arch to be defined
  window.arch = window.arch || null;

  var kite = {
    svgNumber: function( n ) {
      return n.toFixed( 20 );
    }
  };

  // will be filled in by other modules
  return kite;
} );
<|endoftext|>


<commit_before>var app = angular.module('translate', ['pascalprecht.translate']);

app.config(function ($translateProvider) {
  // Dictionaries
  $translateProvider.translations('en', {
    TITLE: 'Hello',
    FOO: 'This is a paragraph.',
    WORK_EXPE_TITLE: 'Work experience',
    FIRST_EXPE_TITLE: "Semantic Web design engineer",
    FIRST_EXPE_COMPANY: "2017 - today at LIRMM (Laboratory for informatics, robotics and microelectronics of Montpellier)",
    FIRST_EXPE_TXT: "BioPortal Project (https://github.com/sifrproject)

Administration and development of a local instance of BioPortal (NCBO ontologies repository ) for SIFR et IBC projects (http://bioportal.lirmm.fr et http://agroportal.lirmm.fr)

Feature development (ontologies metadata, text semantic annotation, multilingual annotation)

 Put into production new prototypes within the platform

Related publications:

Modèle de métadonnées dans un portail d'ontologies ( https://hal.archives-ouvertes.fr/lirmm-01397388 )

Skills: Ruby (on Rails), JSON, OWL Ontologies, SKOS thesaurus, Docker, Linux administration (CentOS)",
    TWO_EXPE_TITLE: "Design and development engineerof the computer science department at LIRMM",
    TWO_EXPE_COMPANY: "2016 - 2017 at LIRMM / CNRS (National Center for Scientific Research)",
    TWO_EXPE_TXT: "BioPortal Project (https://github.com/sifrproject)

Administration et development of a local instance of BioPortal (NCBO) for SIFR et IBC projects (http://bioportal.lirmm.fr et http://agroportal.lirmm.fr)

Feature development (model for ontologies metadata, handling multilingual ontologies)

Advanse team (https://gite.lirmm.fr/advanse)

Development of a web platform to expose Natural Language Processing program developed at the Advanse team (HTTP API and interface): http://advanse.lirmm.fr

Help packaging programs developed by the Advanse team

Advanse server administration (Slurm deployment)

Documentation production

Open Data team (https://gite.lirmm.fr/opendata)

Packaging, test et development of the Yam++ Large Scale tool (Maven Java project)

Development of a web interface and REST API to curate ontologies alignments

Related publications

Multilingual Mapping Reconciliation between English-French Biomedical Ontologies ( https://hal.archives-ouvertes.fr/lirmm-01395880 )

Modèle de métadonnées dans un portail d'ontologies ( https://hal.archives-ouvertes.fr/lirmm-01397388/ )

Skills: Java (Maven, Tomcat sevlet), Ruby (on Rails), ontologies, Docker, Linux administration"
  });

  $translateProvider.translations('fr', {
    TITLE: 'Salut',
    FOO: 'En français.',
    WORK_EXPE_TITLE: 'Expérience professionnelle',
    FIRST_EXPE_TITLE: "Ingénieur d'étude Web sémantique",
    FIRST_EXPE_COMPANY: "2017 - aujourd'hui au LIRMM, Laboratoire d'informatique, de robotique et de microélectronique de Montpellier",
    FIRST_EXPE_TXT: "Projet BioPortal (https://github.com/sifrproject)

Administration et modification d'une instance locale de BioPortal (répertoire d'ontologies du NCBO) pour le projet SIFR et IBC (http://bioportal.lirmm.fr et http://agroportal.lirmm.fr)

Développement de fonctionnalités (metadata des ontologies, annotation multilingue)

Mise en production de nouveau prototypes au sein de la plateforme

Publications:

Modèle de métadonnées dans un portail d'ontologies ( https://hal.archives-ouvertes.fr/lirmm-01397388 )

Compétences : Ruby (on Rails), JSON, OWL Ontologies, SKOS thesaurus, Docker, administration Linux (CentOS)",
    TWO_EXPE_TITLE: "Ingénieur d'étude au département informatique du LIRMM",
    TWO_EXPE_COMPANY: "2016 - 2017 au LIRMM / CNRS (Centre National de la Recherche Scientifique)",
    TWO_EXPE_TXT: "Projet BioPortal (https://github.com/sifrproject)

Administration et modification d'une instance locale de BioPortal (NCBO) pour le projet SIFR et IBC (http://bioportal.lirmm.fr et http://agroportal.lirmm.fr)

Développement de fonctionnalités (modèle de metadonnées pour ontologies, gestion d'ontologies multilangue)

Equipe Advanse (https://gite.lirmm.fr/advanse)

Développement d'une plateforme Web pour exposer les programmes de Natural Language Processing développés par l'équipe Advanse (RESTful API et interface) : http://advanse.lirmm.fr

Aide au packaging de programmes développés par l'équipe Advanse

Administration du serveur Advanse (mise en place de Slurm)

Production de documentation

Equipe Open Data (https://gite.lirmm.fr/opendata)

Packaging, test et amélioration de l'outil de matching d'ontologies Yam++ Large Scale

Développement d'une interface Web de matching et de validation d'alignements d'ontologies

Publications

Multilingual Mapping Reconciliation between English-French Biomedical Ontologies ( https://hal.archives-ouvertes.fr/lirmm-01395880 )

Modèle de métadonnées dans un portail d'ontologies ( https://hal.archives-ouvertes.fr/lirmm-01397388/ )

Compétences : Java (Maven, Tomcat), Ruby (on Rails), développement Web (HTML/CSS/AngularJS), ontologies, Docker, administration Linux"
  });

  $translateProvider.preferredLanguage('en');
});

app.controller('TranslateCtrl', function ($scope, $translate) {
  $scope.changeLanguage = function (key) {
    $translate.use(key);
    // Change opacity of flags when selected
    if (key === "fr") {
      $("#frFlag").css("opacity", "1");
      $("#enFlag").css("opacity", "0.5");
    } else {
      $("#frFlag").css("opacity", "0.5");
      $("#enFlag").css("opacity", "1");
    }
  };
});

// To highlight select nav btn. Take the URL (after /, not taking what after #)
app.controller('HeaderController', function ($scope, $location) {
  $scope.isActive = function (viewLocation) {
    console.log($location);
        return viewLocation === $location.path();
    };
});<commit_msg>fix typo<commit_after>var app = angular.module('translate', ['pascalprecht.translate']);

app.config(function ($translateProvider) {
  // Dictionaries
  $translateProvider.translations('en', {
    TITLE: 'Hello',
    FOO: 'This is a paragraph.',
    WORK_EXPE_TITLE: 'Work experience',
    FIRST_EXPE_TITLE: "Semantic Web design engineer",
    FIRST_EXPE_COMPANY: "2017 - today at LIRMM (Laboratory for informatics, robotics and microelectronics of Montpellier)",
    FIRST_EXPE_TXT: "BioPortal Project (https://github.com/sifrproject)

Administration and development of a local instance of BioPortal (NCBO ontologies repository ) for SIFR et IBC projects (http://bioportal.lirmm.fr et http://agroportal.lirmm.fr)

Feature development (ontologies metadata, text semantic annotation, multilingual annotation)

 Put into production new prototypes within the platform

Related publications:

Modèle de métadonnées dans un portail d'ontologies ( https://hal.archives-ouvertes.fr/lirmm-01397388 )

Skills: Ruby (on Rails), JSON, OWL Ontologies, SKOS thesaurus, Docker, Linux administration (CentOS)",
    TWO_EXPE_TITLE: "Design and development engineer of the computer science department at LIRMM",
    TWO_EXPE_COMPANY: "2016 - 2017 at LIRMM / CNRS (National Center for Scientific Research)",
    TWO_EXPE_TXT: "BioPortal Project (https://github.com/sifrproject)

Administration et development of a local instance of BioPortal (NCBO) for SIFR et IBC projects (http://bioportal.lirmm.fr et http://agroportal.lirmm.fr)

Feature development (model for ontologies metadata, handling multilingual ontologies)

Advanse team (https://gite.lirmm.fr/advanse)

Development of a web platform to expose Natural Language Processing program developed at the Advanse team (HTTP API and interface): http://advanse.lirmm.fr

Help packaging programs developed by the Advanse team

Advanse server administration (Slurm deployment)

Documentation production

Open Data team (https://gite.lirmm.fr/opendata)

Packaging, test et development of the Yam++ Large Scale tool (Maven Java project)

Development of a web interface and REST API to curate ontologies alignments

Related publications

Multilingual Mapping Reconciliation between English-French Biomedical Ontologies ( https://hal.archives-ouvertes.fr/lirmm-01395880 )

Modèle de métadonnées dans un portail d'ontologies ( https://hal.archives-ouvertes.fr/lirmm-01397388/ )

Skills: Java (Maven, Tomcat sevlet), Ruby (on Rails), ontologies, Docker, Linux administration"
  });

  $translateProvider.translations('fr', {
    TITLE: 'Salut',
    FOO: 'En français.',
    WORK_EXPE_TITLE: 'Expérience professionnelle',
    FIRST_EXPE_TITLE: "Ingénieur d'étude Web sémantique",
    FIRST_EXPE_COMPANY: "2017 - aujourd'hui au LIRMM, Laboratoire d'informatique, de robotique et de microélectronique de Montpellier",
    FIRST_EXPE_TXT: "Projet BioPortal (https://github.com/sifrproject)

Administration et modification d'une instance locale de BioPortal (répertoire d'ontologies du NCBO) pour le projet SIFR et IBC (http://bioportal.lirmm.fr et http://agroportal.lirmm.fr)

Développement de fonctionnalités (metadata des ontologies, annotation multilingue)

Mise en production de nouveau prototypes au sein de la plateforme

Publications:

Modèle de métadonnées dans un portail d'ontologies ( https://hal.archives-ouvertes.fr/lirmm-01397388 )

Compétences : Ruby (on Rails), JSON, OWL Ontologies, SKOS thesaurus, Docker, administration Linux (CentOS)",
    TWO_EXPE_TITLE: "Ingénieur d'étude au département informatique du LIRMM",
    TWO_EXPE_COMPANY: "2016 - 2017 au LIRMM / CNRS (Centre National de la Recherche Scientifique)",
    TWO_EXPE_TXT: "Projet BioPortal (https://github.com/sifrproject)

Administration et modification d'une instance locale de BioPortal (NCBO) pour le projet SIFR et IBC (http://bioportal.lirmm.fr et http://agroportal.lirmm.fr)

Développement de fonctionnalités (modèle de metadonnées pour ontologies, gestion d'ontologies multilangue)

Equipe Advanse (https://gite.lirmm.fr/advanse)

Développement d'une plateforme Web pour exposer les programmes de Natural Language Processing développés par l'équipe Advanse (RESTful API et interface) : http://advanse.lirmm.fr

Aide au packaging de programmes développés par l'équipe Advanse

Administration du serveur Advanse (mise en place de Slurm)

Production de documentation

Equipe Open Data (https://gite.lirmm.fr/opendata)

Packaging, test et amélioration de l'outil de matching d'ontologies Yam++ Large Scale

Développement d'une interface Web de matching et de validation d'alignements d'ontologies

Publications

Multilingual Mapping Reconciliation between English-French Biomedical Ontologies ( https://hal.archives-ouvertes.fr/lirmm-01395880 )

Modèle de métadonnées dans un portail d'ontologies ( https://hal.archives-ouvertes.fr/lirmm-01397388/ )

Compétences : Java (Maven, Tomcat), Ruby (on Rails), développement Web (HTML/CSS/AngularJS), ontologies, Docker, administration Linux"
  });

  $translateProvider.preferredLanguage('en');
});

app.controller('TranslateCtrl', function ($scope, $translate) {
  $scope.changeLanguage = function (key) {
    $translate.use(key);
    // Change opacity of flags when selected
    if (key === "fr") {
      $("#frFlag").css("opacity", "1");
      $("#enFlag").css("opacity", "0.5");
    } else {
      $("#frFlag").css("opacity", "0.5");
      $("#enFlag").css("opacity", "1");
    }
  };
});

// To highlight select nav btn. Take the URL (after /, not taking what after #)
app.controller('HeaderController', function ($scope, $location) {
  $scope.isActive = function (viewLocation) {
    console.log($location);
        return viewLocation === $location.path();
    };
});<|endoftext|>


<commit_before>"use strict";

// ---------------------------------------------------------------------------

const acx = require ('./acx.js')
const { ExchangeError, InsufficientFunds, OrderNotFound } = require ('./base/errors')

// ---------------------------------------------------------------------------

module.exports = class kuna extends acx {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'kuna',
            'name': 'Kuna',
            'countries': 'UA',
            'rateLimit': 1000,
            'version': 'v2',
            'hasCORS': false,
            'hasFetchTickers': false,
            'hasFetchOHLCV': false,
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/31697638-912824fa-b3c1-11e7-8c36-cf9606eb94ac.jpg',
                'api': 'https://kuna.io',
                'www': 'https://kuna.io',
                'doc': 'https://kuna.io/documents/api',
                'fees': 'https://kuna.io/documents/api',
            },
            'api': {
                'public': {
                    'get': [
                        'tickers/{market}',
                        'order_book',
                        'order_book/{market}',
                        'trades',
                        'trades/{market}',
                        'timestamp',
                    ],
                },
                'private': {
                    'get': [
                        'members/me',
                        'orders',
                        'trades/my',
                    ],
                    'post': [
                        'orders',
                        'order/delete',
                    ],
                },
            },
            'markets': {
                'BTC/UAH': { 'id': 'btcuah', 'symbol': 'BTC/UAH', 'base': 'BTC', 'quote': 'UAH', 'precision': { 'amount': 6, 'price': 0 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }}},
                'ETH/UAH': { 'id': 'ethuah', 'symbol': 'ETH/UAH', 'base': 'ETH', 'quote': 'UAH', 'precision': { 'amount': 6, 'price': 0 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }}},
                'GBG/UAH': { 'id': 'gbguah', 'symbol': 'GBG/UAH', 'base': 'GBG', 'quote': 'UAH', 'precision': { 'amount': 3, 'price': 2 }, 'lot': 0.001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.01, 'max': undefined }}}, // Golos Gold (GBG != GOLOS)
                'KUN/BTC': { 'id': 'kunbtc', 'symbol': 'KUN/BTC', 'base': 'KUN', 'quote': 'BTC', 'precision': { 'amount': 6, 'price': 6 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.000001, 'max': undefined }}},
                'BCH/BTC': { 'id': 'bchbtc', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC', 'precision': { 'amount': 6, 'price': 6 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.000001, 'max': undefined }}},
                'BCH/UAH': { 'id': 'bchuah', 'symbol': 'BCH/UAH', 'base': 'BCH', 'quote': 'UAH', 'precision': { 'amount': 6, 'price': 0 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }}},
                'WAVES/UAH': { 'id': 'wavesuah', 'symbol': 'WAVES/UAH', 'base': 'WAVES', 'quote': 'UAH', 'precision': { 'amount': 6, 'price': 0 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }}},
                'ARN/BTC': { 'id': 'arnbtc', 'symbol': 'ARN/BTC', 'base': 'ARN', 'quote': 'BTC'},
                'B2B/BTC': { 'id': 'b2bbtc', 'symbol': 'B2B/BTC', 'base': 'B2B', 'quote': 'BTC'},
                'EVR/BTC': { 'id': 'evrbtc', 'symbol': 'EVR/BTC', 'base': 'EVR', 'quote': 'BTC'},
                'GOL/GBG': { 'id': 'golgbg', 'symbol': 'GOL/GBG', 'base': 'GOL', 'quote': 'GBG'},
                'R/BTC': { 'id': 'rbtc', 'symbol': 'R/BTC', 'base': 'R', 'quote': 'BTC'},
                'RMC/BTC': { 'id': 'rmcbtc', 'symbol': 'RMC/BTC', 'base': 'RMC', 'quote': 'BTC'},
            },
            'fees': {
                'trading': {
                    'taker': 0.25 / 100,
                    'maker': 0.25 / 100,
                },
                'funding': {
                    'withdraw': {
                        'UAH': '1%',
                        'BTC': 0.001,
                        'BCH': 0.001,
                        'ETH': 0.01,
                        'WAVES': 0.01,
                        'GOL': 0.0,
                        'GBG': 0.0,
                        // 'RMC': 0.001 BTC
                        // 'ARN': 0.01 ETH
                        // 'R': 0.01 ETH
                        // 'EVR': 0.01 ETH
                    },
                    'deposit': {
                        // 'UAH': (amount) => amount * 0.001 + 5
                    },
                },
            },
        });
    }

    handleErrors (code, reason, url, method, headers, body) {
        if (code == 400) {
            let data = JSON.parse (body);
            let error = data['error'];
            let errorCode = error['code'];
            if (errorCode == 2002) {
                throw new InsufficientFunds ([ this.id, method, url, code, reason, body ].join (' '));
            } else if (errorCode == 2003) {
                throw new OrderNotFound ([ this.id, method, url, code, reason, body ].join (' '));
            }
        }
    }

    async fetchOrderBook (symbol, params = {}) {
        let market = this.market (symbol);
        let orderBook = await this.publicGetOrderBook (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseOrderBook (orderBook, undefined, 'bids', 'asks', 'price', 'remaining_volume');
    }

    async fetchL3OrderBook (symbol, params) {
        return this.fetchOrderBook (symbol, params);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (!symbol)
            throw new ExchangeError (this.id + ' fetchOpenOrders requires a symbol argument');
        let market = this.market (symbol);
        let orders = await this.privateGetOrders (this.extend ({
            'market': market['id'],
        }, params));
        // todo emulation of fetchClosedOrders, fetchOrders, fetchOrder
        // with order cache + fetchOpenOrders
        // as in BTC-e, Liqui, Yobit, DSX, Tidex, WEX
        return this.parseOrders (orders, market, since, limit);
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'id': trade['id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': undefined,
            'side': undefined,
            'price': parseFloat (trade['price']),
            'amount': parseFloat (trade['volume']),
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetTrades (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseMyTrade (trade, market) {
        let timestamp = this.parse8601 (trade['created_at']);
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'id': trade['id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'price': trade['price'],
            'amount': trade['volume'],
            'cost': trade['funds'],
            'symbol': symbol,
            'side': trade['side'],
            'order': trade['order_id'],
        };
    }

    parseMyTrades (trades, market = undefined) {
        let parsedTrades = [];
        for (let i = 0; i < trades.length; i++) {
            let trade = trades[i];
            let parsedTrade = this.parseMyTrade (trade, market);
            parsedTrades.push (parsedTrade);
        }
        return parsedTrades;
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (!symbol)
            throw new ExchangeError (this.id + ' fetchOpenOrders requires a symbol argument');
        let market = this.market (symbol);
        let response = await this.privateGetTradesMy ({ 'market': market['id'] });
        return this.parseMyTrades (response, market);
    }
}
<commit_msg>kuna: limits: cost = price * amount<commit_after>"use strict";

// ---------------------------------------------------------------------------

const acx = require ('./acx.js')
const { ExchangeError, InsufficientFunds, OrderNotFound } = require ('./base/errors')

// ---------------------------------------------------------------------------

module.exports = class kuna extends acx {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'kuna',
            'name': 'Kuna',
            'countries': 'UA',
            'rateLimit': 1000,
            'version': 'v2',
            'hasCORS': false,
            'hasFetchTickers': false,
            'hasFetchOHLCV': false,
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/31697638-912824fa-b3c1-11e7-8c36-cf9606eb94ac.jpg',
                'api': 'https://kuna.io',
                'www': 'https://kuna.io',
                'doc': 'https://kuna.io/documents/api',
                'fees': 'https://kuna.io/documents/api',
            },
            'api': {
                'public': {
                    'get': [
                        'tickers/{market}',
                        'order_book',
                        'order_book/{market}',
                        'trades',
                        'trades/{market}',
                        'timestamp',
                    ],
                },
                'private': {
                    'get': [
                        'members/me',
                        'orders',
                        'trades/my',
                    ],
                    'post': [
                        'orders',
                        'order/delete',
                    ],
                },
            },
            'markets': {
                'BTC/UAH': { 'id': 'btcuah', 'symbol': 'BTC/UAH', 'base': 'BTC', 'quote': 'UAH', 'precision': { 'amount': 6, 'price': 0 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
                'ETH/UAH': { 'id': 'ethuah', 'symbol': 'ETH/UAH', 'base': 'ETH', 'quote': 'UAH', 'precision': { 'amount': 6, 'price': 0 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
                'GBG/UAH': { 'id': 'gbguah', 'symbol': 'GBG/UAH', 'base': 'GBG', 'quote': 'UAH', 'precision': { 'amount': 3, 'price': 2 }, 'lot': 0.001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.01, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}}, // Golos Gold (GBG != GOLOS)
                'KUN/BTC': { 'id': 'kunbtc', 'symbol': 'KUN/BTC', 'base': 'KUN', 'quote': 'BTC', 'precision': { 'amount': 6, 'price': 6 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.000001, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
                'BCH/BTC': { 'id': 'bchbtc', 'symbol': 'BCH/BTC', 'base': 'BCH', 'quote': 'BTC', 'precision': { 'amount': 6, 'price': 6 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 0.000001, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
                'BCH/UAH': { 'id': 'bchuah', 'symbol': 'BCH/UAH', 'base': 'BCH', 'quote': 'UAH', 'precision': { 'amount': 6, 'price': 0 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
                'WAVES/UAH': { 'id': 'wavesuah', 'symbol': 'WAVES/UAH', 'base': 'WAVES', 'quote': 'UAH', 'precision': { 'amount': 6, 'price': 0 }, 'lot': 0.000001, 'limits': { 'amount': { 'min': 0.000001, 'max': undefined }, 'price': { 'min': 1, 'max': undefined }, 'cost': { 'min': 0.000001, 'max': undefined }}},
                'ARN/BTC': { 'id': 'arnbtc', 'symbol': 'ARN/BTC', 'base': 'ARN', 'quote': 'BTC'},
                'B2B/BTC': { 'id': 'b2bbtc', 'symbol': 'B2B/BTC', 'base': 'B2B', 'quote': 'BTC'},
                'EVR/BTC': { 'id': 'evrbtc', 'symbol': 'EVR/BTC', 'base': 'EVR', 'quote': 'BTC'},
                'GOL/GBG': { 'id': 'golgbg', 'symbol': 'GOL/GBG', 'base': 'GOL', 'quote': 'GBG'},
                'R/BTC': { 'id': 'rbtc', 'symbol': 'R/BTC', 'base': 'R', 'quote': 'BTC'},
                'RMC/BTC': { 'id': 'rmcbtc', 'symbol': 'RMC/BTC', 'base': 'RMC', 'quote': 'BTC'},
            },
            'fees': {
                'trading': {
                    'taker': 0.25 / 100,
                    'maker': 0.25 / 100,
                },
                'funding': {
                    'withdraw': {
                        'UAH': '1%',
                        'BTC': 0.001,
                        'BCH': 0.001,
                        'ETH': 0.01,
                        'WAVES': 0.01,
                        'GOL': 0.0,
                        'GBG': 0.0,
                        // 'RMC': 0.001 BTC
                        // 'ARN': 0.01 ETH
                        // 'R': 0.01 ETH
                        // 'EVR': 0.01 ETH
                    },
                    'deposit': {
                        // 'UAH': (amount) => amount * 0.001 + 5
                    },
                },
            },
        });
    }

    handleErrors (code, reason, url, method, headers, body) {
        if (code == 400) {
            let data = JSON.parse (body);
            let error = data['error'];
            let errorCode = error['code'];
            if (errorCode == 2002) {
                throw new InsufficientFunds ([ this.id, method, url, code, reason, body ].join (' '));
            } else if (errorCode == 2003) {
                throw new OrderNotFound ([ this.id, method, url, code, reason, body ].join (' '));
            }
        }
    }

    async fetchOrderBook (symbol, params = {}) {
        let market = this.market (symbol);
        let orderBook = await this.publicGetOrderBook (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseOrderBook (orderBook, undefined, 'bids', 'asks', 'price', 'remaining_volume');
    }

    async fetchL3OrderBook (symbol, params) {
        return this.fetchOrderBook (symbol, params);
    }

    async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (!symbol)
            throw new ExchangeError (this.id + ' fetchOpenOrders requires a symbol argument');
        let market = this.market (symbol);
        let orders = await this.privateGetOrders (this.extend ({
            'market': market['id'],
        }, params));
        // todo emulation of fetchClosedOrders, fetchOrders, fetchOrder
        // with order cache + fetchOpenOrders
        // as in BTC-e, Liqui, Yobit, DSX, Tidex, WEX
        return this.parseOrders (orders, market, since, limit);
    }

    parseTrade (trade, market = undefined) {
        let timestamp = this.parse8601 (trade['created_at']);
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'id': trade['id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': symbol,
            'type': undefined,
            'side': undefined,
            'price': parseFloat (trade['price']),
            'amount': parseFloat (trade['volume']),
            'info': trade,
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetTrades (this.extend ({
            'market': market['id'],
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    parseMyTrade (trade, market) {
        let timestamp = this.parse8601 (trade['created_at']);
        let symbol = undefined;
        if (market)
            symbol = market['symbol'];
        return {
            'id': trade['id'],
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'price': trade['price'],
            'amount': trade['volume'],
            'cost': trade['funds'],
            'symbol': symbol,
            'side': trade['side'],
            'order': trade['order_id'],
        };
    }

    parseMyTrades (trades, market = undefined) {
        let parsedTrades = [];
        for (let i = 0; i < trades.length; i++) {
            let trade = trades[i];
            let parsedTrade = this.parseMyTrade (trade, market);
            parsedTrades.push (parsedTrade);
        }
        return parsedTrades;
    }

    async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
        if (!symbol)
            throw new ExchangeError (this.id + ' fetchOpenOrders requires a symbol argument');
        let market = this.market (symbol);
        let response = await this.privateGetTradesMy ({ 'market': market['id'] });
        return this.parseMyTrades (response, market);
    }
}
<|endoftext|>


<commit_before>var player = {
//	"name":"",
	"Head":0,
	"LeftHand":0,
	"Chest":0,
	"RightHand":0,
	"LeftLeg":0,
	"RightLeg":0,
	"score":0,
};

var enemy = {
//	"name":"",
	"Head":0,
	"LeftHand":0,
	"Chest":0,
	"RightHand":0,
	"LeftLeg":0,
	"RightLeg":0,
	"score":0,
};

var allPlayers = [];
var playerString = {};
var stringToSave = {};
var allPlayers =[];

var assets = "../assets/monster/";

// Human = 3, Animal = 2, Robot = 1

var Head = [{"url":assets+"starter/head_0.png", "race":0}, {"url":assets+"robot/head_0.png", "race":1}, {"url":assets+"animal/head_0.png", "race":2}, {"url":assets+"human/head_0.png", "race":3}, {"url":assets+"human/head_1.png", "race":3}];
var Chest = [{"url":assets+"starter/body_0.png", "race":0}, {"url":assets+"robot/body_0.png", "race":1}, {"url":assets+"animal/body_0.png", "race":2}, {"url":assets+"human/body_0.png", "race":3}, {"url":assets+"human/body_1.png", "race":3}];
var LeftHand = [{"url":assets+"starter/hand_left_0.png", "race":0}, {"url":assets+"robot/hand_left_0.png", "race":1}, {"url":assets+"animal/hand_left_0.png", "race":2}, {"url":assets+"human/hand_left_0.png", "race":3}, {"url":assets+"human/hand_left_1.png", "race":3}];
var RightHand = [{"url":assets+"starter/hand_right_0.png", "race":0}, {"url":assets+"robot/hand_right_0.png", "race":1}, {"url":assets+"animal/hand_right_0.png", "race":2}, {"url":assets+"human/hand_right_0.png", "race":3}, {"url":assets+"human/hand_right_1.png", "race":3}];
var LeftLeg = [{"url":assets+"starter/leg_left_0.png", "race":0}, {"url":assets+"robot/leg_left_0.png", "race":1}, {"url":assets+"animal/leg_left_0.png", "race":2}, {"url":assets+"human/leg_left_0.png", "race":3}, {"url":assets+"human/leg_left_1.png", "race":3}];
var RightLeg = [{"url":assets+"starter/leg_right_0.png", "race":0}, {"url":assets+"robot/leg_right_0.png", "race":1}, {"url":assets+"animal/leg_right_0.png", "race":2}, {"url":assets+"human/leg_right_0.png", "race":3}, {"url":assets+"human/leg_right_1.png", "race":3}];

var parts = {};
parts["Head"] = Head;
parts["Chest"] = Chest;
parts["LeftHand"] = LeftHand;
parts["RightHand"] = RightHand;
parts["LeftLeg"] = LeftLeg;
parts["RightLeg"] = RightLeg;

var eTypes = ["eHead", "eLeftHand", "eChest", "eRightHand", "eLeftLeg", "eRightLeg"];
var pTypes = ["pHead", "pLeftHand", "pChest", "pRightHand", "pLeftLeg", "pRightLeg"];
var aIParts = ["aIHead", "aILeftHand", "aIChest", "aIRightHand", "aILeftLeg", "aIRightLeg"];

window.onload = function(){

	loadServerFn().then(function() {
		if (document.getElementById("opponentList")) {
			loadEnemyList();
		}
	})
	.catch(function(error) {
		console.log(error);
	});

	if (document.getElementById("reset")) {
		document.getElementById("reset").addEventListener("click", function() {
			reset();
		});
	}

	document.getElementById("pHead").addEventListener("click", function() {changePic("pHead", Head, false);} );

	document.getElementById("pChest").addEventListener("click", function() {changePic("pChest", Chest, false);} );

	document.getElementById("pLeftHand").addEventListener("click", function() {changePic("pLeftHand", LeftHand, false);} );

	document.getElementById("pRightHand").addEventListener("click", function() {changePic("pRightHand", RightHand, false);} );

	document.getElementById("pLeftLeg").addEventListener("click", function() {changePic("pLeftLeg", LeftLeg, false);} );

	document.getElementById("pRightLeg").addEventListener("click", function() {changePic("pRightLeg", RightLeg, false);} );

	var play = document.getElementById("play");
    if (play) {
    	play.addEventListener("click", function() {
	    	assignValues();
	    	if (checkMonster()) {
	    		resetScores();
	    		startPlay();
	    		assignValues();
	    		document.getElementById("guide").innerHTML = "The winning bodyparts have been highlighted";
	        	document.getElementById("opponentGuide").innerHTML = findVictor();
	    	} else {
	    		alert("Complete your monster.");
	    	}
	    });
    }

    if (document.getElementById("opponentList")) {
    	document.querySelector('body').addEventListener('click', function(event) {
			if (event.target.className == 'fightButton') {
				fight(event.target.id);
			}
		});
    }
};

function currentBodypartIndex(bodyparts, url) {
	var current = -1;
	for (var i=0;i<bodyparts.length;i++) {
		if (bodyparts[i]["url"] == url) {
			current = bodyparts.indexOf(bodyparts[i]);
		}
	}
	return current;
}

function raceFromUrl(partsList, url) {
	return parts[partsList][currentBodypartIndex(parts[partsList], url)]["race"];
}

function assignValues() {
	for (name in pTypes) {
		var part = pTypes[name];
		var partUrl = $("#"+part+" img").attr("src");
		if (!partUrl.includes("starter")) {
			player[part.slice(1)] = raceFromUrl(part.slice(1), partUrl);
		}
	}
	for (name in eTypes) {
		var part = eTypes[name];
		var partUrl = $("#"+part+" img").attr("src");
		if (!partUrl.includes("starter")) {
			enemy[part.slice(1)] = raceFromUrl(part.slice(1), partUrl);
		}
	}
}

function resetScores() {
	player["score"] = 0;
    enemy["score"] = 0;
	for (var i in player) {
		$("#e"+i).removeClass("greyed");
		$("#p"+i).removeClass("greyed");
	}
}

function reset() {
	for (var i in player) {
		if (i != "name" && i != "score") {
			player[i] = 0;
			enemy[i] = 0;
			$("#e"+i).removeClass("greyed");
			$("#p"+i).removeClass("greyed");
			changePic("p"+i, parts[i], true);
			changePic("e"+i, parts[i], true);
		}
		player["score"] = 0;
		enemy["score"] = 0;
	}
	document.getElementById("guide").innerHTML = "Loop through different bodyparts by clicking on the corresponding slot";
	document.getElementById("opponentGuide").innerHTML = "After you've created a monster,  either select an opponent from the list and click play or click random to receive a random enemy";
	$("#opponentGuide").css("color", "#afafaf");
}

function findVictor() {
	for (var i in player) {
		if (i != "name" && i != "score") {
			if (player[i] != enemy[i]) {
				var winningValue = calculate(player[i], enemy[i]);
				if (player[i] == winningValue) {
					$("#e"+i).addClass("greyed");
				} else {
					$("#p"+i).addClass("greyed");
				}
			} else {
				enemy["score"] += 1;
				player["score"] += 1;
			}
		}
	}
	if (player["score"] > enemy["score"]) {
		$("#opponentGuide").css("color", "#009600");
		return "You win!";
	} else {
		$("#opponentGuide").css("color", "#dc0000");
		return "You lose!";
	}
}

function calculate(player1, player2) {
	// Robot > Human
	// Human > Animal
	// Animal > Robot
	// robot - 1, animal - 2, human - 3
	if(player1 == 1) {
		if(player2 == 2) {
			// player2 won
			enemy["score"] += 1;
			return 2;
		} else {
			// player1 won
			player["score"] += 1;
			return 1;
		}
	}
	if(player1 == 2) {
		if(player2 == 3) {
			// player2 won
			enemy["score"] += 1;
			return 3;
		} else {
			// player1 won
			player["score"] += 1;
			return 2;
		}
	}
	if(player1 == 3) {
		if(player2 == 1) {
			// player2 won
			enemy["score"] += 1;
			return 1;
		} else {
			// player1 won
			player["score"] += 1;
			return 3;
		}
	}
}

function changePic(divId, bodyparts, reset) {
	var currentUrl = $("#"+divId+" img").attr("src");
	$("#"+divId).removeClass("greyed");
	var current = currentBodypartIndex(bodyparts, currentUrl);
	if (bodyparts[current+1]) {
		var next = current+1;
	} else {
		var next = 1;
	}
	if (reset) {
		var next = 0;
	}
	$("#"+divId+" img").remove();
	$("#"+divId).prepend("");
}

function saveServerFn() {
	$.ajax({
		url: "../server.php?save="+JSON.stringify(player)
	}).done(function(data) {
		console.log('Saved monster to server.');
		console.log(data);
	});
}

function saveMonster() {
	if(checkMonster()==1) {

    getName();

    if(player.name !== "") {
      console.log("Will save now");
  		saveServerFn();
    } else {
      console.log("Insert a name for the monster");
    }
	} else {
		console.log("Monster not ready to save!");
	}
}

function getName() {
  player.name = document.getElementById('newName').value;
}

function checkMonster() {
	var ready = 1;
	for(var i=0; i<pTypes.length; i++) {
		if(player[pTypes[i]]===0){
			ready = 0;
		}
	}
	return ready;
}

function startPlay() {
    console.log("Fight!");

// Loosin arvuti monsterile väärtused
    for (var i=0;i<eTypes.length;i++) {
        var partDiv = (eTypes[i]);
        var partName = eTypes[i].slice(1);
        giveAIValue(partDiv, parts[partName]);
    }
}

function randomizer(numberOfParts) {
    return Math.floor((Math.random() * (numberOfParts-1))+1);
}

function giveAIValue(divId, bodyparts) {
	var value = randomizer(bodyparts.length);
    $("#"+divId+" img").remove();
    $("#"+divId).prepend("");
}

function checkMonster() {
	var ready = true;
	for(var i=0; i<pTypes.length; i++) {
		if(player[pTypes[i].slice(1)]===0){
			ready = false;
		}
	}
	return ready;
}

function loadEnemyList() {

	if(allPlayers.length>0) {
		var heading = document.createElement("h3");
		var headingText = document.createTextNode("Choose an Enemy to fight with");
		heading.appendChild(headingText);
		document.getElementById("opponentList").appendChild(heading);
	} else {
		var emptyListHeading = document.createElement("h3");
		var emptyListHeadingText = document.createTextNode("No saved monsters yet, be first!");
		emptyListHeading.appendChild(emptyListHeadingText);
		document.getElementById("opponentList").appendChild(emptyListHeading);
	}

	for(var i=0; i<allPlayers.length; i++) {

		var oneEnemy = document.createElement("div");
		oneEnemy.className = 'oneEnemy';

		var enemyNameSpan = document.createElement("span");
		enemyNameSpan.className = 'enemyName';
		var enemyName = document.createTextNode(allPlayers[i].name);
		enemyNameSpan.appendChild(enemyName);
		oneEnemy.appendChild(enemyNameSpan);
		document.getElementById("opponentList").appendChild(oneEnemy);

		var fightButton = document.createElement("button");
		fightButton.className = 'fightButton';
		fightButton.id = i;
		var buttonName = document.createTextNode("Fight");
		fightButton.appendChild(buttonName);
		oneEnemy.appendChild(fightButton);
		document.getElementById("opponentList").appendChild(oneEnemy);

	}
}

function loadEnemy(chosenEnemy) {
	for(var e=0; e<allPlayers.length; e++){
		if(allPlayers[e].name==allPlayers[chosenEnemy].name){

			enemy.name = allPlayers[e].name;
			document.getElementById('enemyName').innerHTML = enemy.name;
			enemy.eHead = allPlayers[e].pHead;
			document.getElementById('eHead').style.backgroundColor = colors[enemy.eHead-1];
			enemy.eLeftHand = allPlayers[e].pLeftHand;
			document.getElementById('eLeftHand').style.backgroundColor = colors[enemy.eLeftHand-1];
			enemy.eChest = allPlayers[e].pChest;
			document.getElementById('eChest').style.backgroundColor = colors[enemy.eChest-1];
			enemy.eRightHand = allPlayers[e].pRightHand;
			document.getElementById('eRightHand').style.backgroundColor = colors[enemy.eRightHand-1];
			enemy.eLeftLeg = allPlayers[e].pLeftLeg;
			document.getElementById('eLeftLeg').style.backgroundColor = colors[enemy.eLeftLeg-1];
			enemy.eRightLeg = allPlayers[e].pRightLeg;
			document.getElementById('eRightLeg').style.backgroundColor = colors[enemy.eRightLeg-1];

			console.log(enemy.eHead);

		}
	}
}

function loadServerFn() {
	return $.ajax({
		url: "../database.txt"
	}).done(function(data) {
		allPlayers = JSON.parse(data).players;
		console.log('Loaded monsters from server.');
	});
}<commit_msg>Multiplayer works, no back button from the match or much design on the list yet.<commit_after>var player = {
//	"name":"",
	"Head":0,
	"LeftHand":0,
	"Chest":0,
	"RightHand":0,
	"LeftLeg":0,
	"RightLeg":0,
	"score":0,
};

var enemy = {
//	"name":"",
	"Head":0,
	"LeftHand":0,
	"Chest":0,
	"RightHand":0,
	"LeftLeg":0,
	"RightLeg":0,
	"score":0,
};

var allPlayers = [];
var playerString = {};
var stringToSave = {};
var allPlayers =[];

var assets = "../assets/monster/";

// Human = 3, Animal = 2, Robot = 1

var Head = [{"url":assets+"starter/head_0.png", "race":0}, {"url":assets+"robot/head_0.png", "race":1}, {"url":assets+"animal/head_0.png", "race":2}, {"url":assets+"human/head_0.png", "race":3}, {"url":assets+"human/head_1.png", "race":3}];
var Chest = [{"url":assets+"starter/body_0.png", "race":0}, {"url":assets+"robot/body_0.png", "race":1}, {"url":assets+"animal/body_0.png", "race":2}, {"url":assets+"human/body_0.png", "race":3}, {"url":assets+"human/body_1.png", "race":3}];
var LeftHand = [{"url":assets+"starter/hand_left_0.png", "race":0}, {"url":assets+"robot/hand_left_0.png", "race":1}, {"url":assets+"animal/hand_left_0.png", "race":2}, {"url":assets+"human/hand_left_0.png", "race":3}, {"url":assets+"human/hand_left_1.png", "race":3}];
var RightHand = [{"url":assets+"starter/hand_right_0.png", "race":0}, {"url":assets+"robot/hand_right_0.png", "race":1}, {"url":assets+"animal/hand_right_0.png", "race":2}, {"url":assets+"human/hand_right_0.png", "race":3}, {"url":assets+"human/hand_right_1.png", "race":3}];
var LeftLeg = [{"url":assets+"starter/leg_left_0.png", "race":0}, {"url":assets+"robot/leg_left_0.png", "race":1}, {"url":assets+"animal/leg_left_0.png", "race":2}, {"url":assets+"human/leg_left_0.png", "race":3}, {"url":assets+"human/leg_left_1.png", "race":3}];
var RightLeg = [{"url":assets+"starter/leg_right_0.png", "race":0}, {"url":assets+"robot/leg_right_0.png", "race":1}, {"url":assets+"animal/leg_right_0.png", "race":2}, {"url":assets+"human/leg_right_0.png", "race":3}, {"url":assets+"human/leg_right_1.png", "race":3}];

var parts = {};
parts["Head"] = Head;
parts["Chest"] = Chest;
parts["LeftHand"] = LeftHand;
parts["RightHand"] = RightHand;
parts["LeftLeg"] = LeftLeg;
parts["RightLeg"] = RightLeg;

var eTypes = ["eHead", "eLeftHand", "eChest", "eRightHand", "eLeftLeg", "eRightLeg"];
var pTypes = ["pHead", "pLeftHand", "pChest", "pRightHand", "pLeftLeg", "pRightLeg"];
var aIParts = ["aIHead", "aILeftHand", "aIChest", "aIRightHand", "aILeftLeg", "aIRightLeg"];

window.onload = function(){

	loadServerFn().then(function() {
		if (document.getElementById("opponentList")) {
			loadEnemyList();
		}
	})
	.catch(function(error) {
		console.log(error);
	});

	if (document.getElementById("reset")) {
		document.getElementById("reset").addEventListener("click", function() {
			reset();
		});
	}

	document.getElementById("pHead").addEventListener("click", function() {changePic("pHead", Head, false);} );

	document.getElementById("pChest").addEventListener("click", function() {changePic("pChest", Chest, false);} );

	document.getElementById("pLeftHand").addEventListener("click", function() {changePic("pLeftHand", LeftHand, false);} );

	document.getElementById("pRightHand").addEventListener("click", function() {changePic("pRightHand", RightHand, false);} );

	document.getElementById("pLeftLeg").addEventListener("click", function() {changePic("pLeftLeg", LeftLeg, false);} );

	document.getElementById("pRightLeg").addEventListener("click", function() {changePic("pRightLeg", RightLeg, false);} );

	var play = document.getElementById("play");
    if (play) {
    	play.addEventListener("click", function() {
	    	assignValues();
	    	if (checkMonster()) {
	    		resetScores();
	    		startPlay();
	    		assignValues();
	    		document.getElementById("guide").innerHTML = "The winning bodyparts have been highlighted";
	        	document.getElementById("opponentGuide").innerHTML = findVictor();
	    	} else {
	    		alert("Complete your monster.");
	    	}
	    });
    }

    if (document.getElementById("opponentList")) {
    	document.querySelector('body').addEventListener('click', function(event) {
			if (event.target.className == 'fightButton') {
				assignValues();
				if (checkMonster()) {
					fight(event.target.id);
					startPlay();
					document.getElementById("guide").innerHTML = "The winning bodyparts have been highlighted";
		        	document.getElementById("opponentGuide").innerHTML = findVictor();
		        }
			}
		});
    }
};

function currentBodypartIndex(bodyparts, url) {
	var current = -1;
	for (var i=0;i<bodyparts.length;i++) {
		if (bodyparts[i]["url"] == url) {
			current = bodyparts.indexOf(bodyparts[i]);
		}
	}
	return current;
}

function raceFromUrl(partsList, url) {
	return parts[partsList][currentBodypartIndex(parts[partsList], url)]["race"];
}

function assignValues() {
	for (name in pTypes) {
		var part = pTypes[name];
		var partUrl = $("#"+part+" img").attr("src");
		if (!partUrl.includes("starter")) {
			player[part.slice(1)] = raceFromUrl(part.slice(1), partUrl);
		}
	}
	for (name in eTypes) {
		var part = eTypes[name];
		var partUrl = $("#"+part+" img").attr("src");
		if (!partUrl.includes("starter")) {
			enemy[part.slice(1)] = raceFromUrl(part.slice(1), partUrl);
		}
	}
}

function resetScores() {
	player["score"] = 0;
    enemy["score"] = 0;
	for (var i in player) {
		$("#e"+i).removeClass("greyed");
		$("#p"+i).removeClass("greyed");
	}
}

function reset() {
	for (var i in player) {
		if (i != "name" && i != "score") {
			player[i] = 0;
			enemy[i] = 0;
			$("#e"+i).removeClass("greyed");
			$("#p"+i).removeClass("greyed");
			changePic("p"+i, parts[i], true);
			changePic("e"+i, parts[i], true);
		}
		player["score"] = 0;
		enemy["score"] = 0;
	}
	document.getElementById("guide").innerHTML = "Loop through different bodyparts by clicking on the corresponding slot";
	document.getElementById("opponentGuide").innerHTML = "After you've created a monster,  either select an opponent from the list and click play or click random to receive a random enemy";
	$("#opponentGuide").css("color", "#afafaf");
}

function findVictor() {
	for (var i in player) {
		if (i != "name" && i != "score") {
			if (player[i] != enemy[i]) {
				var winningValue = calculate(player[i], enemy[i]);
				if (player[i] == winningValue) {
					$("#e"+i).addClass("greyed");
				} else {
					$("#p"+i).addClass("greyed");
				}
			} else {
				enemy["score"] += 1;
				player["score"] += 1;
			}
		}
	}
	if (player["score"] > enemy["score"]) {
		$("#opponentGuide").css("color", "#009600");
		return "You win!";
	} else {
		$("#opponentGuide").css("color", "#dc0000");
		return "You lose!";
	}
}

function calculate(player1, player2) {
	// Robot > Human
	// Human > Animal
	// Animal > Robot
	// robot - 1, animal - 2, human - 3
	if(player1 == 1) {
		if(player2 == 2) {
			// player2 won
			enemy["score"] += 1;
			return 2;
		} else {
			// player1 won
			player["score"] += 1;
			return 1;
		}
	}
	if(player1 == 2) {
		if(player2 == 3) {
			// player2 won
			enemy["score"] += 1;
			return 3;
		} else {
			// player1 won
			player["score"] += 1;
			return 2;
		}
	}
	if(player1 == 3) {
		if(player2 == 1) {
			// player2 won
			enemy["score"] += 1;
			return 1;
		} else {
			// player1 won
			player["score"] += 1;
			return 3;
		}
	}
}

function changePic(divId, bodyparts, reset) {
	var currentUrl = $("#"+divId+" img").attr("src");
	$("#"+divId).removeClass("greyed");
	var current = currentBodypartIndex(bodyparts, currentUrl);
	if (bodyparts[current+1]) {
		var next = current+1;
	} else {
		var next = 1;
	}
	if (reset) {
		var next = 0;
	}
	$("#"+divId+" img").remove();
	$("#"+divId).prepend("");
}

function saveServerFn() {
	$.ajax({
		url: "../server.php?save="+JSON.stringify(player)
	}).done(function(data) {
		console.log('Saved monster to server.');
		console.log(data);
	});
}

function saveMonster() {
	if(checkMonster()) {

    getName();

    if(player.name !== "") {
      console.log("Will save now");
  		saveServerFn();
    } else {
      console.log("Insert a name for the monster");
    }
	} else {
		console.log("Monster not ready to save!");
	}
}

function getName() {
  player.name = document.getElementById('newName').value;
}

function checkMonster() {
	var ready = true;
	for (i in player) {
		if (i != "name" && i != "score") {
			if (player[i] == 0) {
				console.log("Complete your monster first");
				return false;
			}
		}
	}
	return ready;
}

function startPlay() {
    console.log("Fight!");

	if (document.getElementById("singlePlayer")) {
		console.log("singlePlayer");
		// Loosin arvuti monsterile väärtused
	    for (var i=0;i<eTypes.length;i++) {
	        var partDiv = (eTypes[i]);
	        var partName = eTypes[i].slice(1);
	        pictureEnemy(partDiv, parts[partName], true);
	    }
	} else if ($("#multiPlayer")) {
		console.log("multiPlayer");
		for (var i=0;i<eTypes.length;i++) {
	        var partDiv = (eTypes[i]);
	        var partName = eTypes[i].slice(1);
	        pictureEnemy(partDiv, parts[partName], false);
	    }
	}

}

function randomizer(numberOfParts) {
    return Math.floor((Math.random() * (numberOfParts-1))+1);
}

function pictureEnemy(divId, bodyparts, random) {
	if (random) {
		var value = randomizer(bodyparts.length);
	} else {
		var value = enemy[divId.slice(1)];
	}
    $("#"+divId+" img").remove();
    $("#"+divId).prepend("");
}

function loadEnemyList() {

	if(allPlayers.length>0) {
		var heading = document.createElement("h3");
		var headingText = document.createTextNode("Choose an Enemy to fight with");
		heading.appendChild(headingText);
		document.getElementById("opponentList").appendChild(heading);
	} else {
		var emptyListHeading = document.createElement("h3");
		var emptyListHeadingText = document.createTextNode("No saved monsters yet, be first!");
		emptyListHeading.appendChild(emptyListHeadingText);
		document.getElementById("opponentList").appendChild(emptyListHeading);
	}

	for(var i=0; i<allPlayers.length; i++) {

		var oneEnemy = document.createElement("div");
		oneEnemy.className = 'oneEnemy';

		var enemyNameSpan = document.createElement("span");
		enemyNameSpan.className = 'enemyName';
		var enemyName = document.createTextNode(allPlayers[i].name);
		enemyNameSpan.appendChild(enemyName);
		oneEnemy.appendChild(enemyNameSpan);
		document.getElementById("opponentList").appendChild(oneEnemy);

		var fightButton = document.createElement("button");
		fightButton.className = 'fightButton';
		fightButton.id = i;
		var buttonName = document.createTextNode("Fight");
		fightButton.appendChild(buttonName);
		oneEnemy.appendChild(fightButton);
		document.getElementById("opponentList").appendChild(oneEnemy);

	}
}

function loadEnemy(chosenEnemy) {
	for(var e=0; e<allPlayers.length; e++){
		if(allPlayers[e].name==allPlayers[chosenEnemy].name){
			enemy = allPlayers[e];
			assignValues();
		}
	}
}

function loadServerFn() {
	return $.ajax({
		url: "../database.txt"
	}).done(function(data) {
		allPlayers = JSON.parse(data).players;
		console.log('Loaded monsters from server.');
		for (enemies in allPlayers) {
			allPlayers[enemies]["score"] = 0;
		}
	});
}

function fight(enemy) {
	document.getElementById("opponentList").style.display = 'none';
	document.getElementById("enemyMonster").style.display = 'block';
	loadEnemy(parseInt(enemy));
}<|endoftext|>


<commit_before>/*!
 *  Lang.js for Laravel localization in JavaScript.
 *
 *  @version 1.0.0
 *  @license MIT
 *  @site    https://github.com/rmariuzzo/Laravel-JS-Localization
 *  @author  rmariuzzo
 */

'use strict';

(function(root, factory) {

    if (typeof define === 'function' && define.amd) {
        // AMD support.
        define([], factory);
    } else if (typeof exports === 'object') {
        // NodeJS support.
        module.exports = new(factory())();
    } else {
        // Browser global support.
        root.Lang = new(factory())();
    }

}(this, function() {

    // Default options //

    var defaults = {
        defaultLocale: 'en' /** The default locale if not set. */
    };

    // Constructor //

    var Lang = function(options) {
        options = options || {};
        this.defaultLocale = options.defaultLocale || defaults.defaultLocale;
    };

    // Methods //

    /**
     * Set messages source.
     *
     * @param messages {object} The messages source.
     *
     * @return void
     */
    Lang.prototype.setMessages = function(messages) {
        this.messages = messages;
    };

    /**
     * Returns a translation message.
     *
     * @param key {string} The key of the message.
     * @param replacements {object} The replacements to be done in the message.
     *
     * @return {string} The translation message, if not found the given key.
     */
    Lang.prototype.get = function(key, replacements) {
        if (!this.has(key)) {
            return key;
        }

        var message = this._getMessage(key, replacements);
        if (message === null) {
            return key;
        }

        if (replacements) {
            message = this._applyReplacements(message, replacements);
        }

        return message;
    };

    /**
     * Returns true if the key is defined on the messages source.
     *
     * @param key {string} The key of the message.
     *
     * @return {boolean} true if the given key is defined on the messages source, otherwise false.
     */
    Lang.prototype.has = function(key) {
        if (typeof key !== 'string' || !this.messages) {
            return false;
        }
        return this._getMessage(key) !== null;
    };

    /**
     * Set the current locale.
     *
     * @param locale {string} The locale to set.
     *
     * @return void
     */
    Lang.prototype.setLocale = function(locale) {
        this.locale = locale;
    };

    /**
     * Get the current locale.
     *
     * @return {string} The current locale.
     */
    Lang.prototype.getLocale = function() {
        return this.locale || this.defaultLocale;
    };

    /**
     * Parse a message key into components.
     *
     * @param key {string} The message key to parse.
     *
     * @return {object} A key object with source and entries properties.
     */
    Lang.prototype._parseKey = function(key) {
        if (typeof key !== 'string') {
            return null;
        }
        var segments = key.split('.');
        return {
            source: this.getLocale() + '.' + segments[0],
            entries: segments.slice(1)
        };
    };

    /**
     * Returns a translation message. Use `Lang.get()` method instead, this methods assumes the key exists.
     *
     * @param key {string} The key of the message.
     *
     * @return {string} The translation message for the given key.
     */
    Lang.prototype._getMessage = function(key) {

        key = this._parseKey(key);

        // Ensure message source exists.
        if (this.messages[key.source] === undefined) {
            return null;
        }

        // Get message text.
        var message = this.messages[key.source];
        while (key.entries.length && (message = message[key.entries.shift()]));

        if (typeof message !== 'string') {
            return null;
        }

        return message;
    };

    /**
     * Apply replacements to a string message containing placeholders.
     *
     * @param message {string} The text message.
     * @param replacements {object} The replacements to be done in the message.
     *
     * @return {string} The string message with replacements applied.
     */
    Lang.prototype._applyReplacements = function(message, replacements) {
        for (var replace in replacements) {
            message = message.split(':' + replace).join(replacements[replace]);
        }
        return message;
    };

    /**
     * Gets the plural or singular form of the message specified based on an integer value.
     *
     * @param key {string} The key of the message.
     * @param count {integer} The number of elements.
     * @param replacements {object} The replacements to be done in the message.
     * @param locale {string} Language to be used when getting the message.
     *
     * @return {string} The translation message according to an integer value.
     */
    Lang.prototype.choice = function(key,count,replacements,locale){
        // Set default values for parameters replace and locale
        replacements = typeof replacements !== 'undefined' ? replacements : [];
        locale = typeof locale !== 'undefined' ? locale : this.getLocale();

        // Message to get the plural or singular
        var message = this.get(key, replacements);

        // Check if message is not null or undefined
        if(message === null || message === undefined){
            return message;
        }

        // Separate the plural from the singular, if any
        var messageParts = message.split('|');

        // Get the explicit rules, If any
        var explicitRules = [];
        var regex = /{\d+}\s(.+)|\[\d+,\d+\]\s(.+)|\[\d+,Inf\]\s(.+)/;

        for (var i = 0; i < messageParts.length; i++) {
            messageParts[i] = messageParts[i].trim();

            if(regex.test(messageParts[i])){
                var messageSpaceSplit = messageParts[i].split(/\s/);
                explicitRules.push(messageSpaceSplit.shift());
                messageParts[i] = messageSpaceSplit.join(' ');
            }
        };

        // Check if there's only one message
        if(messageParts.length === 1){
            // Nothing to do here
            return message;
        }

        // Check the explicit rules
        for (var i = 0; i < explicitRules.length; i++) {
            if(this.testInterval(count, explicitRules[i])){
                return messageParts[i];
            }
        };

        // Standard rules
        if(count > 1){
            return messageParts[1];
        }else{
            return messageParts[0];
        }
    };

    /**
     * Checks if the given `count` is within the interval defined by the {string} `interval`
     *
     * @param  {int} count          The amount of items
     * @param  {string} interval    The interval to be compared with the count
     * @return {boolean}            Returns true if count is within interval; false otherwise
     */
    Lang.prototype.testInterval = function(count, interval) {
        /**
        * From the Synfony\Component\Translation\Interval Docs
        *
        * Tests if a given number belongs to a given math interval.
        * An interval can represent a finite set of numbers: {1,2,3,4}
        * An interval can represent numbers between two numbers: [1, +Inf] ]-1,2[
        * The left delimiter can be [ (inclusive) or ] (exclusive).
        * The right delimiter can be [ (exclusive) or ] (inclusive).
        * Beside numbers, you can use -Inf and +Inf for the infinite.
        */

        return false;
    };

    return Lang;

}));<commit_msg>addind _ to _testInterval method<commit_after>/*!
 *  Lang.js for Laravel localization in JavaScript.
 *
 *  @version 1.0.0
 *  @license MIT
 *  @site    https://github.com/rmariuzzo/Laravel-JS-Localization
 *  @author  rmariuzzo
 */

'use strict';

(function(root, factory) {

    if (typeof define === 'function' && define.amd) {
        // AMD support.
        define([], factory);
    } else if (typeof exports === 'object') {
        // NodeJS support.
        module.exports = new(factory())();
    } else {
        // Browser global support.
        root.Lang = new(factory())();
    }

}(this, function() {

    // Default options //

    var defaults = {
        defaultLocale: 'en' /** The default locale if not set. */
    };

    // Constructor //

    var Lang = function(options) {
        options = options || {};
        this.defaultLocale = options.defaultLocale || defaults.defaultLocale;
    };

    // Methods //

    /**
     * Set messages source.
     *
     * @param messages {object} The messages source.
     *
     * @return void
     */
    Lang.prototype.setMessages = function(messages) {
        this.messages = messages;
    };

    /**
     * Returns a translation message.
     *
     * @param key {string} The key of the message.
     * @param replacements {object} The replacements to be done in the message.
     *
     * @return {string} The translation message, if not found the given key.
     */
    Lang.prototype.get = function(key, replacements) {
        if (!this.has(key)) {
            return key;
        }

        var message = this._getMessage(key, replacements);
        if (message === null) {
            return key;
        }

        if (replacements) {
            message = this._applyReplacements(message, replacements);
        }

        return message;
    };

    /**
     * Returns true if the key is defined on the messages source.
     *
     * @param key {string} The key of the message.
     *
     * @return {boolean} true if the given key is defined on the messages source, otherwise false.
     */
    Lang.prototype.has = function(key) {
        if (typeof key !== 'string' || !this.messages) {
            return false;
        }
        return this._getMessage(key) !== null;
    };

    /**
     * Set the current locale.
     *
     * @param locale {string} The locale to set.
     *
     * @return void
     */
    Lang.prototype.setLocale = function(locale) {
        this.locale = locale;
    };

    /**
     * Get the current locale.
     *
     * @return {string} The current locale.
     */
    Lang.prototype.getLocale = function() {
        return this.locale || this.defaultLocale;
    };

    /**
     * Parse a message key into components.
     *
     * @param key {string} The message key to parse.
     *
     * @return {object} A key object with source and entries properties.
     */
    Lang.prototype._parseKey = function(key) {
        if (typeof key !== 'string') {
            return null;
        }
        var segments = key.split('.');
        return {
            source: this.getLocale() + '.' + segments[0],
            entries: segments.slice(1)
        };
    };

    /**
     * Returns a translation message. Use `Lang.get()` method instead, this methods assumes the key exists.
     *
     * @param key {string} The key of the message.
     *
     * @return {string} The translation message for the given key.
     */
    Lang.prototype._getMessage = function(key) {

        key = this._parseKey(key);

        // Ensure message source exists.
        if (this.messages[key.source] === undefined) {
            return null;
        }

        // Get message text.
        var message = this.messages[key.source];
        while (key.entries.length && (message = message[key.entries.shift()]));

        if (typeof message !== 'string') {
            return null;
        }

        return message;
    };

    /**
     * Apply replacements to a string message containing placeholders.
     *
     * @param message {string} The text message.
     * @param replacements {object} The replacements to be done in the message.
     *
     * @return {string} The string message with replacements applied.
     */
    Lang.prototype._applyReplacements = function(message, replacements) {
        for (var replace in replacements) {
            message = message.split(':' + replace).join(replacements[replace]);
        }
        return message;
    };

    /**
     * Gets the plural or singular form of the message specified based on an integer value.
     *
     * @param key {string} The key of the message.
     * @param count {integer} The number of elements.
     * @param replacements {object} The replacements to be done in the message.
     * @param locale {string} Language to be used when getting the message.
     *
     * @return {string} The translation message according to an integer value.
     */
    Lang.prototype.choice = function(key,count,replacements,locale){
        // Set default values for parameters replace and locale
        replacements = typeof replacements !== 'undefined' ? replacements : [];
        locale = typeof locale !== 'undefined' ? locale : this.getLocale();

        // Message to get the plural or singular
        var message = this.get(key, replacements);

        // Check if message is not null or undefined
        if(message === null || message === undefined){
            return message;
        }

        // Separate the plural from the singular, if any
        var messageParts = message.split('|');

        // Get the explicit rules, If any
        var explicitRules = [];
        var regex = /{\d+}\s(.+)|\[\d+,\d+\]\s(.+)|\[\d+,Inf\]\s(.+)/;

        for (var i = 0; i < messageParts.length; i++) {
            messageParts[i] = messageParts[i].trim();

            if(regex.test(messageParts[i])){
                var messageSpaceSplit = messageParts[i].split(/\s/);
                explicitRules.push(messageSpaceSplit.shift());
                messageParts[i] = messageSpaceSplit.join(' ');
            }
        };

        // Check if there's only one message
        if(messageParts.length === 1){
            // Nothing to do here
            return message;
        }

        // Check the explicit rules
        for (var i = 0; i < explicitRules.length; i++) {
            if(this._testInterval(count, explicitRules[i])){
                return messageParts[i];
            }
        };

        // Standard rules
        if(count > 1){
            return messageParts[1];
        }else{
            return messageParts[0];
        }
    };

    /**
     * Checks if the given `count` is within the interval defined by the {string} `interval`
     *
     * @param  count {int}  The amount of items.
     * @param  interval {string}    The interval to be compared with the count.
     * @return {boolean}    Returns true if count is within interval; false otherwise.
     */
    Lang.prototype._testInterval = function(count, interval) {
        /**
        * From the Synfony\Component\Translation\Interval Docs
        *
        * Tests if a given number belongs to a given math interval.
        * An interval can represent a finite set of numbers: {1,2,3,4}
        * An interval can represent numbers between two numbers: [1, +Inf] ]-1,2[
        * The left delimiter can be [ (inclusive) or ] (exclusive).
        * The right delimiter can be [ (exclusive) or ] (inclusive).
        * Beside numbers, you can use -Inf and +Inf for the infinite.
        */

        return false;
    };

    return Lang;

}));<|endoftext|>