<commit_before>'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import url from 'url';
import { Button } from 'react-bootstrap';
import { content_views } from './../globals';
import { ajax, console, object, Filters, JWT, DateUtility, layout } from './../util';
import { ItemPageTitle, ItemDetailList } from './components';
import ReactTooltip from 'react-tooltip';
import * as vizUtil from './../viz/utilities';
import * as d3 from 'd3';
import _ from 'underscore';
import JSONTree from 'react-json-tree';

/**
 * Fallback content_view for pages which are not specifically 'Items.
 * Renders out JSON.
 *
 * @export
 * @class Item
 * @extends {React.Component}
 */
export class HealthView extends React.Component {

    static propTypes = {
        'href' : PropTypes.string
    }

    constructor(props){
        super(props);
        this.render = this.render.bind(this);
        this.componentDidMount = this.componentDidMount.bind(this);
        this.getCounts = _.throttle(this.getCounts.bind(this), 1000);
        this.state = {
            'db_es_total' : "loading...",
            'db_es_compare' : "loading...",
            'mounted' : false
        };
    }

    componentDidMount(){
        this.setState({ 'mounted' : true });
        this.getCounts();
    }

    getCounts(){

        ajax.load('/counts?format=json', (resp)=>{
            this.setState({
                'db_es_total' : resp.db_es_total,
                'db_es_compare': resp.db_es_compare,
            });
        }, 'GET', (resp)=>{
            this.setState({
                'error' : resp.error || resp.message,
                'db_es_total' : null,
                'db_es_compare': null
            });
        });
    }

    render() {
        var context = this.props.context;
        var title = typeof context.title == "string" ? context.title : url.parse(this.props.href).path;

        var width = null;
        if (this.state.mounted){
            width = layout.gridContainerWidth();
        }

        return (

Configuration

                {typeof context.description == "string" ?
{context.description}
 : null}
                <ItemDetailList excludedKeys={ItemDetailList.Detail.defaultProps.excludedKeys.concat(['content'])} hideButtons context={context} schemas={this.props.schemas} keyTitleDescriptionMap={{
                    'blob_bucket' : {
                        title : "Blob Bucket",
                        description : "Name of S3 bucket used for blob data."
                    },
                    'content' : {
                        title : "Extra Information"
                    },
                    'database' : {
                        title : "Database Location",
                        description : "URI used to connect to the back-end PgSQL DB."
                    },
                    'elasticsearch' : {
                        title : "ElasticSearch Location",
                        description : "URI used to connect to the back-end ES instance."
                    },
                    'db_es_total' : {
                        title : "DB and ES Counts",
                        description : "Total counts of items in database and elasticsearch."
                    },
                    'db_es_compare' : {
                        title : "DB and ES Counts by Type",
                        description : "Counts of items in database and elasticsearch for each doc_type index."
                    },
                    'file_upload_bucket' : {
                        title : "File Upload Bucket",
                        description : "Where uploaded files are stored."
                    },
                    'load_data' : {
                        title : "Data Loaded",
                        description : "Data which was loaded into database on initialization or boot."
                    },
                    'ontology_updated' : {
                        title : 'Last Ontology Update',
                        description : "Last time ontologies were updated."
                    },
                    'system_bucket' : {
                        title : 'System Bucket',
                        description : "Name of S3 Bucket used for system data."
                    },
                    'aggregations' : {
                        title : 'Aggregations',
                        description : "Aggregations of ES-indexed data."
                    }
                }} />

                <Button className="refresh-counts-button pull-right mt-2" onClick={this.getCounts}>  Refresh Counts</Button>

Database Counts

                <ItemDetailList excludedKeys={ItemDetailList.Detail.defaultProps.excludedKeys.concat(['content'])} hideButtons context={_.pick(this.state, 'db_es_total', 'db_es_compare')} schemas={this.props.schemas} keyTitleDescriptionMap={{
                    'db_es_total' : {
                        title : "DB and ES Counts",
                        description : "Total counts of items in database and elasticsearch."
                    },
                    'db_es_compare' : {
                        title : "DB and ES Counts by Type",
                        description : "Counts of items in database and elasticsearch for each doc_type index."
                    }
                }} />

                <HealthChart mounted={this.state.mounted} width={width} height={400} />

        );
    }
}

content_views.register(HealthView, 'Health');

class HealthChart extends React.Component {

    static defaultProps = {
        'mounted' : false,
    }

    constructor(props){
        super(props);
        this.state = {
            'loaded' : false,
            'data' : null
        };
    }

    componentDidMount(){
        this.load();
    }

    componentDidUpdate(){
        if (this.state.loaded) this.drawTreeMap();
    }

    load(){
        ajax.load('/bar_plot_aggregations/type=Item&field=@type/?field=@type', (r)=>{
            this.setState({
                data : r,
                loaded : true
            });
        });
    }

    drawTreeMap(){
        var { width, height, mounted } = this.props;

        var svg = this.refs && this.refs.svg && d3.select(this.refs.svg);

        var fader = function(color) { return d3.interpolateRgb(color, "#fff")(0.2); };
        var color = d3.scaleOrdinal(d3.schemeCategory20.map(fader));

        var d3Data = vizUtil.transformBarPlotAggregationsToD3CompatibleHierarchy(this.state.data);

        // Exclude ontology terms -
        d3Data.children = _.filter(d3Data.children, function(typeAggregation){ return typeAggregation.name !== 'OntologyTerm'; });

        var treemap = d3.treemap()
            .tile(d3.treemapResquarify)
            .size([width, height])
            .round(true)
            .paddingInner(1);

        var root = d3.hierarchy(d3Data)
            .eachBefore(function(d) {d.data.id = (d.parent ? d.parent.data.id + "." : "") + d.data.name; })
            .sum(function(d){ return d.size; })
            .sort(function(a, b) { return b.height - a.height || b.value - a.value; });

        treemap(root);

        var cell = svg.selectAll("g")
            .data(root.leaves())
            .enter().append("g")
            .attr("transform", function(d) { return "translate(" + d.x0 + "," + d.y0 + ")"; })
            .attr("data-tip", function(d){ return d.data.name + " - \n" + d.data.size + ' Items'; })
            .attr("data-effect", function(d){ return 'float'; });

        cell.append("rect")
            .attr("id", function(d) { return d.data.id; })
            .attr("width", function(d) { return d.x1 - d.x0; })
            .attr("height", function(d) { return d.y1 - d.y0; })
            .attr("fill", function(d) { return color(d.data.id); });

        cell.append("clipPath")
            .attr("id", function(d) { return "clip-" + d.data.id; })
            .append("use")
            .attr("xlink:href", function(d) { return "#" + d.data.id; });

        cell.append("text")
            .attr("clip-path", function(d) { return "url(#clip-" + d.data.id + ")"; })
            .selectAll("tspan")
            .data(function(d) { return d.data.name.split(/(?=[A-Z][^A-Z])/g); })
            .enter().append("tspan")
            .attr("x", 4)
            .attr("y", function(d, i) { return 13 + i * 10; })
            .text(function(d) { return d; });

        ReactTooltip.rebuild();
    }

    render(){
        var { width, height, mounted } = this.props;

        if (!mounted || !this.state.loaded || !this.state.data) return null;

        return (

Excluding OntologyTerm

ES Types by Count

                <svg width={width} height={height} ref="svg"/>

        );

    }

}
<commit_msg>Minor perf. improvement<commit_after>'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import url from 'url';
import { Button } from 'react-bootstrap';
import { content_views } from './../globals';
import { ajax, console, object, Filters, JWT, DateUtility, layout } from './../util';
import { ItemPageTitle, ItemDetailList } from './components';
import ReactTooltip from 'react-tooltip';
import * as vizUtil from './../viz/utilities';
import * as d3 from 'd3';
import _ from 'underscore';
import JSONTree from 'react-json-tree';

/**
 * Fallback content_view for pages which are not specifically 'Items.
 * Renders out JSON.
 *
 * @export
 * @class Item
 * @extends {React.Component}
 */
export class HealthView extends React.Component {

    static propTypes = {
        'href' : PropTypes.string
    }

    constructor(props){
        super(props);
        this.render = this.render.bind(this);
        this.componentDidMount = this.componentDidMount.bind(this);
        this.getCounts = _.throttle(this.getCounts.bind(this), 1000);
        this.state = {
            'db_es_total' : "loading...",
            'db_es_compare' : "loading...",
            'mounted' : false
        };
    }

    componentDidMount(){
        this.setState({ 'mounted' : true });
        this.getCounts();
    }

    getCounts(){

        ajax.load('/counts?format=json', (resp)=>{
            this.setState({
                'db_es_total' : resp.db_es_total,
                'db_es_compare': resp.db_es_compare,
            });
        }, 'GET', (resp)=>{
            this.setState({
                'error' : resp.error || resp.message,
                'db_es_total' : null,
                'db_es_compare': null
            });
        });
    }

    render() {
        var context = this.props.context;
        var title = typeof context.title == "string" ? context.title : url.parse(this.props.href).path;

        var width = null;
        if (this.state.mounted){
            width = layout.gridContainerWidth();
        }

        return (

Configuration

                {typeof context.description == "string" ?
{context.description}
 : null}
                <ItemDetailList excludedKeys={ItemDetailList.Detail.defaultProps.excludedKeys.concat(['content'])} hideButtons context={context} schemas={this.props.schemas} keyTitleDescriptionMap={{
                    'blob_bucket' : {
                        title : "Blob Bucket",
                        description : "Name of S3 bucket used for blob data."
                    },
                    'content' : {
                        title : "Extra Information"
                    },
                    'database' : {
                        title : "Database Location",
                        description : "URI used to connect to the back-end PgSQL DB."
                    },
                    'elasticsearch' : {
                        title : "ElasticSearch Location",
                        description : "URI used to connect to the back-end ES instance."
                    },
                    'db_es_total' : {
                        title : "DB and ES Counts",
                        description : "Total counts of items in database and elasticsearch."
                    },
                    'db_es_compare' : {
                        title : "DB and ES Counts by Type",
                        description : "Counts of items in database and elasticsearch for each doc_type index."
                    },
                    'file_upload_bucket' : {
                        title : "File Upload Bucket",
                        description : "Where uploaded files are stored."
                    },
                    'load_data' : {
                        title : "Data Loaded",
                        description : "Data which was loaded into database on initialization or boot."
                    },
                    'ontology_updated' : {
                        title : 'Last Ontology Update',
                        description : "Last time ontologies were updated."
                    },
                    'system_bucket' : {
                        title : 'System Bucket',
                        description : "Name of S3 Bucket used for system data."
                    },
                    'aggregations' : {
                        title : 'Aggregations',
                        description : "Aggregations of ES-indexed data."
                    }
                }} />

                <Button className="refresh-counts-button pull-right mt-2" onClick={this.getCounts}>  Refresh Counts</Button>

Database Counts

                <ItemDetailList excludedKeys={ItemDetailList.Detail.defaultProps.excludedKeys.concat(['content'])} hideButtons context={_.pick(this.state, 'db_es_total', 'db_es_compare')} schemas={this.props.schemas} keyTitleDescriptionMap={{
                    'db_es_total' : {
                        title : "DB and ES Counts",
                        description : "Total counts of items in database and elasticsearch."
                    },
                    'db_es_compare' : {
                        title : "DB and ES Counts by Type",
                        description : "Counts of items in database and elasticsearch for each doc_type index."
                    }
                }} />

                <HealthChart mounted={this.state.mounted} width={width} height={400} />

        );
    }
}

content_views.register(HealthView, 'Health');

class HealthChart extends React.Component {

    static defaultProps = {
        'mounted' : false,
    }

    constructor(props){
        super(props);
        this.state = {
            'loaded' : false,
            'data' : null
        };
    }

    componentDidMount(){
        this.load();
    }

    componentDidUpdate(){
        if (this.state.loaded) this.drawTreeMap();
    }

    load(){
        ajax.load('/bar_plot_aggregations/type=Item&field=@type&type!=OntologyTerm/?field=@type', (r)=>{ // Exclude ontology terms
            this.setState({
                data : r,
                loaded : true
            });
        });
    }

    drawTreeMap(){
        var { width, height, mounted } = this.props;

        var svg = this.refs && this.refs.svg && d3.select(this.refs.svg);

        var fader = function(color) { return d3.interpolateRgb(color, "#fff")(0.2); };
        var color = d3.scaleOrdinal(d3.schemeCategory20.map(fader));

        var d3Data = vizUtil.transformBarPlotAggregationsToD3CompatibleHierarchy(this.state.data);

        var treemap = d3.treemap()
            .tile(d3.treemapResquarify)
            .size([width, height])
            .round(true)
            .paddingInner(1);

        var root = d3.hierarchy(d3Data)
            .eachBefore(function(d) {d.data.id = (d.parent ? d.parent.data.id + "." : "") + d.data.name; })
            .sum(function(d){ return d.size; })
            .sort(function(a, b) { return b.height - a.height || b.value - a.value; });

        treemap(root);

        var cell = svg.selectAll("g")
            .data(root.leaves())
            .enter().append("g")
            .attr("transform", function(d) { return "translate(" + d.x0 + "," + d.y0 + ")"; })
            .attr("data-tip", function(d){ return '' + d.data.name + "
" + d.data.size + ' Items'; })
            .attr("data-html", function(d){ return true; })
            .attr("data-effect", function(d){ return 'float'; });

        cell.append("rect")
            .attr("id", function(d) { return d.data.id; })
            .attr("width", function(d) { return d.x1 - d.x0; })
            .attr("height", function(d) { return d.y1 - d.y0; })
            .attr("fill", function(d) { return color(d.data.id); });

        cell.append("clipPath")
            .attr("id", function(d) { return "clip-" + d.data.id; })
            .append("use")
            .attr("xlink:href", function(d) { return "#" + d.data.id; });

        cell.append("text")
            .attr("clip-path", function(d) { return "url(#clip-" + d.data.id + ")"; })
            .selectAll("tspan")
            .data(function(d) { return d.data.name.split(/(?=[A-Z][^A-Z])/g); })
            .enter().append("tspan")
            .attr("x", 4)
            .attr("y", function(d, i) { return 15 + i * 15; })
            .text(function(d) { return d; });

        ReactTooltip.rebuild();
    }

    render(){
        var { width, height, mounted } = this.props;

        if (!mounted || !this.state.loaded || !this.state.data) return null;

        return (

Excluding OntologyTerm

Types by Count in ElasticSearch

                <svg width={width} height={height} ref="svg"/>

        );

    }

}
<|endoftext|>


<commit_before>var _curry = require('./internal/_curry');
var _arrSort = require('./internal/_arrSort');
var _arrEqual = require('./internal/_arrayEqual');
var _equal = require('./internal/_equal');
var _show = require('./internal/_show');
var _flip = require('./internal/_flip');
var _compose = require('./internal/_compose');
var __ = require('./internal/_blank');

var Functor = require('./Functor');
var Foldable = require('./Foldable');

var Obj = require('./internal/_primitives').Obj;

// implementation for Eq
Obj.eq = _curry(function(left, right) {
    if (left === right) {
        return true;
    }

    var lKeys = _arrSort(Object.keys(left));
    var rKeys = _arrSort(Object.keys(right));

    if (!_arrEqual(lKeys, rKeys)) {
        return false;
    }

    var keyInd = 0;
    while(keyInd < lKeys.length) {
        var key = lKeys[keyInd];
        if (!(key in right) || !_equal(left[key], right[key])) {
            return false;
        }
        keyInd += 1;
    }

    return true;
});

Obj.map = _curry(function(fn, obj) {
    return Foldable.foldl(function(accum, key){
        accum[key] = fn(obj[key]);
        return accum;
    }, {}, Obj.ownKeys(obj));
});

Obj.mapAssoc = _curry(function(fn, obj) {
    return Foldable.foldl(function(accum, key){
        accum[key] = fn(obj[key], key);
        return accum;
    }, {}, Obj.ownKeys(obj));
});

Obj.concat = _curry(function(left, right){
    var result = Obj.copy(left);
    for (var k in right){
        result[k] = right[k];
    }
    return result;
});

Obj.empty = function(){
    return {};
};

Obj.union = _flip(Obj.concat);

Obj.difference = _curry(function(left, right){
    var result = {};
    for (var k in left){
        if(!(k in right)){
            result[k] = left[k];
        }
    }

    return result;
});

Obj.intersection = _curry(function(left, right){
    var result = {};
    for (var k in left){
        if(k in right){
            result[k] = left[k];
        }
    }

    return result;
});

Obj.symettricDifference = _curry(function(left, right){
    var result = {};
    var k;
    for (k in left){
        if(!(k in right)){
            result[k] = left[k];
        }
    }

    for (k in right){
        if(!(k in left)){
            result[k] = right[k];
        }
    }

    return result;
});

Obj.foldl = _curry(function(fn, init, obj){
    var keys = _arrSort(Object.keys(obj));

    return Foldable.foldl(function(accum, key){
        return fn(accum, obj[key]);
    }, init, keys);
});

Obj.foldr = _curry(function(fn, init, obj){
    var keys = _arrSort(Object.keys(obj));

    return Foldable.foldr(function(accum, key){
        return fn(accum, obj[key]);
    }, init, keys);
});

Obj.foldlAssoc = _curry(function(fn, init, obj){
    var keys = _arrSort(Object.keys(obj));

    return Foldable.foldl(function(accum, key){
        return fn(accum, obj[key], key);
    }, init, keys);
});

Obj.foldrAssoc = _curry(function(fn, init, obj){
    var keys = _arrSort(Object.keys(obj));

    return Foldable.foldr(function(accum, key){
        return fn(accum, obj[key], key);
    }, init, keys);
});

Obj.copy = _curry(function(obj){
    var res = {};
    for (var k in obj) {
        res[k] = obj[k];
    }
    return res;
});

Obj.assoc = _curry(function(key, value, obj){
    var res = Obj.copy(obj);

    res[key] = value;
    return res;
});

Obj.dissoc = _curry(function(key, obj){
    var res = {};
    for (var k in obj) {
        if (k !== key) {
            res[k] = obj[k];
        }
    }

    return res;
});

Obj.has = _curry(function(key, obj){
    return key in obj;
});

Obj.hasOwn = _curry(function(key, obj){
    return Object.prototype.hasOwnProperty.call(obj, key);
});

Obj.prop = _curry(function(key, obj){
    return obj[key];
});

Obj.propOr = _curry(function(def, key, obj){
    return Obj.has(key, obj) ? obj[key] : def;
});

Obj.props = _curry(function(props, obj){
    return Functor.map(Obj.prop(__, obj), props);
});

Obj.keys = _curry(function(obj){
    return _arrSort(Object.keys(Obj.copy(obj)));
});

Obj.ownKeys = _curry(function(obj){
    return _arrSort(Object.keys(obj).filter(Obj.hasOwn(__, obj)));
});

Obj.values = _curry(function(obj){
    return Obj.props(Obj.keys(obj), obj);
});

Obj.ownValues = _curry(function(obj){
    return Obj.props(Obj.ownKeys(obj), obj);
});

Obj.pairs = _curry(function(obj){
    return Functor.map(function(key){
        return [key, obj[key]];
    }, Obj.keys(obj))
});

Obj.ownPairs = _curry(function(obj){
    return Functor.map(function(key){
        return [key, obj[key]];
    }, Obj.ownKeys(obj));
});

Obj.filter = _curry(function(fn, obj){
    return Obj.foldlAssoc(function(accum, value, key){
        if (fn(value)){
            accum[key] = value;
        }
        return accum;
    }, {}, obj);
});

Obj.filterAssoc = _curry(function(fn, obj){
    return Obj.foldlAssoc(function(accum, value, key){
        if (fn(value, key)){
            accum[key] = value;
        }
        return accum;
    }, {}, obj);
});

Obj.show = _curry(function(obj){
    var keys = _arrSort(Object.keys(obj));
    var items = keys.map(function(key){
        return '"' + key + '"' + ": " + _show(obj[key]);
    });

    return "{" + items.join(', ') + "}";
});

module.exports = Obj;<commit_msg>Added documentation stubs to Obj<commit_after>var _curry = require('./internal/_curry');
var _arrSort = require('./internal/_arrSort');
var _arrEqual = require('./internal/_arrayEqual');
var _equal = require('./internal/_equal');
var _show = require('./internal/_show');
var _flip = require('./internal/_flip');
var _compose = require('./internal/_compose');
var __ = require('./internal/_blank');

var Functor = require('./Functor');
var Foldable = require('./Foldable');

var Obj = require('./internal/_primitives').Obj;

// implementation for Eq

/**
 * Returns true if two objects are structurally equal based on their own keys.
 *
 * @sig {String: a} -> {String: a} -> Boolean
 * @since 0.5.0
 */
Obj.eq = _curry(function(left, right) {
    if (left === right) {
        return true;
    }

    var lKeys = _arrSort(Object.keys(left));
    var rKeys = _arrSort(Object.keys(right));

    if (!_arrEqual(lKeys, rKeys)) {
        return false;
    }

    var keyInd = 0;
    while(keyInd < lKeys.length) {
        var key = lKeys[keyInd];
        if (!(key in right) || !_equal(left[key], right[key])) {
            return false;
        }
        keyInd += 1;
    }

    return true;
});

/**
 * Maps the values of an objects own keys, returning a transformed object.
 *
 * @sig (a -> b) -> {String: a} -> {String: b}
 * @since 0.6.0
 */
Obj.map = _curry(function(fn, obj) {
    return Foldable.foldl(function(accum, key){
        accum[key] = fn(obj[key]);
        return accum;
    }, {}, Obj.ownKeys(obj));
});

/**
 * Like map, but includes the object keys as a second parameter to the mapping function.
 *
 * @sig (a -> String -> b) -> {String: a} -> {String: b}
 * @since 0.6.0
 */
Obj.mapAssoc = _curry(function(fn, obj) {
    return Foldable.foldl(function(accum, key){
        accum[key] = fn(obj[key], key);
        return accum;
    }, {}, Obj.ownKeys(obj));
});

/**
 * Right biased union of two objects based on their keys.
 *
 * @sig {String: a} -> {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.concat = _curry(function(left, right){
    var result = Obj.copy(left);
    for (var k in right){
        result[k] = right[k];
    }
    return result;
});

/**
 * Returns an empty object
 *
 * @sig () -> {String: *}
 * @since 0.6.0
 */
Obj.empty = function(){
    return {};
};

/**
 * Left biased union of two objects based on their keys.
 *
 * @sig {String: a} -> {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.union = _flip(Obj.concat);

/**
 * Returns an object with the key values in the left for which there is no key in right.
 *
 * @sig {String: a} -> {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.difference = _curry(function(left, right){
    var result = {};
    for (var k in left){
        if(!(k in right)){
            result[k] = left[k];
        }
    }

    return result;
});

/**
 * Returns an object whose keys are those that exist in both left and right and whose values are those in left.
 *
 * @sig {String: a} -> {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.intersection = _curry(function(left, right){
    var result = {};
    for (var k in left){
        if(k in right){
            result[k] = left[k];
        }
    }

    return result;
});

/**
 * Returns an object whose keys are all those present in left or right, but not both
 *
 * @sig {String: a} -> {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.symettricDifference = _curry(function(left, right){
    var result = {};
    var k;
    for (k in left){
        if(!(k in right)){
            result[k] = left[k];
        }
    }

    for (k in right){
        if(!(k in left)){
            result[k] = right[k];
        }
    }

    return result;
});

/**
 * Folds an object's values from left to right with keys in sorted order.
 *
 * @sig (b -> a -> b) -> b -> {String: a} -> b
 */
Obj.foldl = _curry(function(fn, init, obj){
    var keys = _arrSort(Object.keys(obj));

    return Foldable.foldl(function(accum, key){
        return fn(accum, obj[key]);
    }, init, keys);
});

/**
 * Folds an object's values from right to left with keys in sorted order.
 *
 * @sig (b -> a -> b) -> b -> {String: a} -> b
 */
Obj.foldr = _curry(function(fn, init, obj){
    var keys = _arrSort(Object.keys(obj));

    return Foldable.foldr(function(accum, key){
        return fn(accum, obj[key]);
    }, init, keys);
});

/**
 * Folds an object's values and keys from left to right with keys in sorted order.
 *
 * @sig (b -> a -> String -> b) -> b -> {String: a} -> b
 */
Obj.foldlAssoc = _curry(function(fn, init, obj){
    var keys = _arrSort(Object.keys(obj));

    return Foldable.foldl(function(accum, key){
        return fn(accum, obj[key], key);
    }, init, keys);
});

/**
 * Folds an object's values and keys from right to left with keys in sorted order.
 *
 * @sig (b -> a -> String -> b) -> b -> {String: a} -> b
 */
Obj.foldrAssoc = _curry(function(fn, init, obj){
    var keys = _arrSort(Object.keys(obj));

    return Foldable.foldr(function(accum, key){
        return fn(accum, obj[key], key);
    }, init, keys);
});

/**
 * Copies an objects enumerable properties to a new object
 *
 * @sig {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.copy = _curry(function(obj){
    var res = {};
    for (var k in obj) {
        res[k] = obj[k];
    }
    return res;
});

/**
 * Copies an objects own enumerable properties to a new object
 *
 * @sig {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.copyOwn = _curry(function(obj){
    var res = {};
    for (var k in obj) {
        if (obj.hasOwnProperty(k)){
            res[k] = obj[k];
        }
    }
    return res;
});

/**
 * Creates a new object from another with a key set to a new value.
 *
 * @sig String -> a -> {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.assoc = _curry(function(key, value, obj){
    var res = Obj.copy(obj);

    res[key] = value;
    return res;
});

/**
 * Creates a new object from another with a key removed.
 *
 * @sig String -> {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.dissoc = _curry(function(key, obj){
    var res = {};
    for (var k in obj) {
        if (k !== key) {
            res[k] = obj[k];
        }
    }

    return res;
});

/**
 * Returns true if an object has a property.
 *
 * @sig String -> {String: a} -> Boolean
 * @since 0.6.0
 */
Obj.has = _curry(function(key, obj){
    return key in obj;
});

/**
 * Returns true if an object has an own property.
 *
 * @sig String -> {String: a} -> Boolean
 * @since 0.6.0
 */
Obj.hasOwn = _curry(function(key, obj){
    return Object.prototype.hasOwnProperty.call(obj, key);
});

/**
 * Returns the property associated with a key in an object.
 *
 * @sig String -> {String: a} -> a|undefined
 * @since 0.6.0
 */
Obj.prop = _curry(function(key, obj){
    return obj[key];
});

/**
 * Returns the property associated with a key in an object if it exists or a default value if it does not exist.
 *
 * @sig a -> String -> {String: a} -> a
 * @since 0.6.0
 */
Obj.propOr = _curry(function(def, key, obj){
    return Obj.has(key, obj) ? obj[key] : def;
});

/**
 * Takes a structure of keys and returns a structure of properties.
 *
 * @sig Foldable f => f String -> {String: a} -> f a
 * @since 0.6.0
 */
Obj.props = _curry(function(props, obj){
    return Functor.map(Obj.prop(__, obj), props);
});

/**
 * Returns the enumerable keys of an object as an array.
 *
 * The keys are sorted.
 *
 * @sig {String: a} -> [String]
 * @since 0.6.0
 */
Obj.keys = _curry(function(obj){
    return _arrSort(Object.keys(Obj.copy(obj)));
});

/**
 * Returns the enumerable own keys of an object as an array.
 *
 * The keys are sorted.
 *
 * @sig {String: a} -> [String]
 * @since 0.6.0
 */
Obj.ownKeys = _curry(function(obj){
    return _arrSort(Object.keys(obj));
});

/**
 * Returns the enumerable values of an object as an array.
 *
 * @sig {String: a} -> [a]
 * @since 0.6.0
 */
Obj.values = _curry(function(obj){
    return Obj.props(Obj.keys(obj), obj);
});

/**
 * Returns the enumerable own values of an object as an array.
 *
 * @sig {String: a} -> [a]
 * @since 0.6.0
 */
Obj.ownValues = _curry(function(obj){
    return Obj.props(Obj.ownKeys(obj), obj);
});

/**
 * Returns an array of array of key value pairs where the first index of each pair is a key
 * in the object and the second index is the value associated with that key.
 *
 * @sig {String: a} -> [[String, a]]
 * @since 0.6.0
 */
Obj.pairs = _curry(function(obj){
    return Functor.map(function(key){
        return [key, obj[key]];
    }, Obj.keys(obj))
});

/**
 * Returns an array of array of key value pairs where the first index of each pair is an own key
 * in the object and the second index is the value associated with that key.
 *
 * @sig {String: a} -> [[String, a]]
 * @since 0.6.0
 */
Obj.ownPairs = _curry(function(obj){
    return Functor.map(function(key){
        return [key, obj[key]];
    }, Obj.ownKeys(obj));
});

/**
 * Takes a predicate function and an object and returns an object with the same keys
 * as the one given whose values pass the predicate function.
 *
 * @sig (a -> Boolean) -> {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.filter = _curry(function(fn, obj){
    return Obj.foldlAssoc(function(accum, value, key){
        if (fn(value)){
            accum[key] = value;
        }
        return accum;
    }, {}, obj);
});

/**
 * Works the same as filter, except passes the key as a second argument to the predicate.
 *
 * @sig (a -> String -> Boolean) -> {String: a} -> {String: a}
 * @since 0.6.0
 */
Obj.filterAssoc = _curry(function(fn, obj){
    return Obj.foldlAssoc(function(accum, value, key){
        if (fn(value, key)){
            accum[key] = value;
        }
        return accum;
    }, {}, obj);
});

/**
 * Returns a string representation of an object.
 *
 * @sig {String: a} -> String
 * @since 0.5.0
 */
Obj.show = _curry(function(obj){
    var keys = _arrSort(Object.keys(obj));
    var items = keys.map(function(key){
        return '"' + key + '"' + ": " + _show(obj[key]);
    });

    return "{" + items.join(', ') + "}";
});

module.exports = Obj;<|endoftext|>


<commit_before>/**
 * gulpfile.js
 * For build instructions, please see README.md.
 *
 * Copyright (C) 2014-2016 Karim Alibhai.
 **/

'use strict';

var gulp = require('gulp'),
    jslint = require('./');

// lint all code
gulp.task('default', function () {
    return gulp.src(['gulpfile.js', 'index.js', 'lib/**/*.js', 'test/test-gulp.jslint.js'])

        // pass your directives
        // as an object
        .pipe(jslint({
            // these directives can
            // be found in the official
            // JSLint documentation.
            node: true,
            es6: false,
            white: true,

            // you can also set global
            // declarations for all source
            // files like so:
            global: [],
            predef: []

            // both ways will achieve the
            // same result; predef will be
            // given priority because it is
            // promoted by JSLint
        }))

        // pass in your prefered reporter like so:
        .pipe(jslint.reporter('default', true));
});
<commit_msg>Remove tests from gulp<commit_after>/**
 * gulpfile.js
 * For build instructions, please see README.md.
 *
 * Copyright (C) 2014-2016 Karim Alibhai.
 **/

'use strict';

var gulp = require('gulp'),
    jslint = require('./');

// lint all code
gulp.task('default', function () {
    return gulp.src(['gulpfile.js', 'index.js', 'lib/**/*.js'])

        // pass your directives
        // as an object
        .pipe(jslint({
            // these directives can
            // be found in the official
            // JSLint documentation.
            node: true,
            es6: false,
            white: true,

            // you can also set global
            // declarations for all source
            // files like so:
            global: [],
            predef: []

            // both ways will achieve the
            // same result; predef will be
            // given priority because it is
            // promoted by JSLint
        }))

        // pass in your prefered reporter like so:
        .pipe(jslint.reporter('default', true));
});
<|endoftext|>


<commit_before>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Constant declarations for common key codes.
 *
 * @author eae@google.com (Emil A Eklund)
 */

goog.provide('goog.events.KeyNames');

/**
 * Key names for common characters.
 *
 * This list is not localized and therefore some of the key codes are not
 * correct for non-US keyboard layouts.
 *
 * @see goog.events.KeyCodes
 * @enum {string}
 */
goog.events.KeyNames = {
  8: 'backspace',
  9: 'tab',
  13: 'enter',
  16: 'shift',
  17: 'ctrl',
  18: 'alt',
  19: 'pause',
  20: 'caps-lock',
  27: 'esc',
  32: 'space',
  33: 'pg-up',
  34: 'pg-down',
  35: 'end',
  36: 'home',
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  45: 'insert',
  46: 'delete',
  48: '0',
  49: '1',
  50: '2',
  51: '3',
  52: '4',
  53: '5',
  54: '6',
  55: '7',
  56: '8',
  57: '9',
  59: 'semicolon',
  61: 'equals',
  65: 'a',
  66: 'b',
  67: 'c',
  68: 'd',
  69: 'e',
  70: 'f',
  71: 'g',
  72: 'h',
  73: 'i',
  74: 'j',
  75: 'k',
  76: 'l',
  77: 'm',
  78: 'n',
  79: 'o',
  80: 'p',
  81: 'q',
  82: 'r',
  83: 's',
  84: 't',
  85: 'u',
  86: 'v',
  87: 'w',
  88: 'x',
  89: 'y',
  90: 'z',
  93: 'context',
  96: 'num-0',
  97: 'num-1',
  98: 'num-2',
  99: 'num-3',
  100: 'num-4',
  101: 'num-5',
  102: 'num-6',
  103: 'num-7',
  104: 'num-8',
  105: 'num-9',
  106: 'num-multiply',
  107: 'num-plus',
  109: 'num-minus',
  110: 'num-period',
  111: 'num-division',
  112: 'f1',
  113: 'f2',
  114: 'f3',
  115: 'f4',
  116: 'f5',
  117: 'f6',
  118: 'f7',
  119: 'f8',
  120: 'f9',
  121: 'f10',
  122: 'f11',
  123: 'f12',
  186: 'semicolon',
  187: 'equals',
  188: ',',
  190: '.',
  191: '/',
  192: '~',
  219: 'open-square-bracket',
  220: '\\',
  224: 'win'
};
<commit_msg><commit_after>// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Constant declarations for common key codes.
 *
 * @author eae@google.com (Emil A Eklund)
 */

goog.provide('goog.events.KeyNames');

/**
 * Key names for common characters.
 *
 * This list is not localized and therefore some of the key codes are not
 * correct for non-US keyboard layouts.
 *
 * @see goog.events.KeyCodes
 * @enum {string}
 */
goog.events.KeyNames = {
  8: 'backspace',
  9: 'tab',
  13: 'enter',
  16: 'shift',
  17: 'ctrl',
  18: 'alt',
  19: 'pause',
  20: 'caps-lock',
  27: 'esc',
  32: 'space',
  33: 'pg-up',
  34: 'pg-down',
  35: 'end',
  36: 'home',
  37: 'left',
  38: 'up',
  39: 'right',
  40: 'down',
  45: 'insert',
  46: 'delete',
  48: '0',
  49: '1',
  50: '2',
  51: '3',
  52: '4',
  53: '5',
  54: '6',
  55: '7',
  56: '8',
  57: '9',
  59: 'semicolon',
  61: 'equals',
  65: 'a',
  66: 'b',
  67: 'c',
  68: 'd',
  69: 'e',
  70: 'f',
  71: 'g',
  72: 'h',
  73: 'i',
  74: 'j',
  75: 'k',
  76: 'l',
  77: 'm',
  78: 'n',
  79: 'o',
  80: 'p',
  81: 'q',
  82: 'r',
  83: 's',
  84: 't',
  85: 'u',
  86: 'v',
  87: 'w',
  88: 'x',
  89: 'y',
  90: 'z',
  93: 'context',
  96: 'num-0',
  97: 'num-1',
  98: 'num-2',
  99: 'num-3',
  100: 'num-4',
  101: 'num-5',
  102: 'num-6',
  103: 'num-7',
  104: 'num-8',
  105: 'num-9',
  106: 'num-multiply',
  107: 'num-plus',
  109: 'num-minus',
  110: 'num-period',
  111: 'num-division',
  112: 'f1',
  113: 'f2',
  114: 'f3',
  115: 'f4',
  116: 'f5',
  117: 'f6',
  118: 'f7',
  119: 'f8',
  120: 'f9',
  121: 'f10',
  122: 'f11',
  123: 'f12',
  186: 'semicolon',
  187: 'equals',
  188: ',',
  190: '.',
  191: '/',
  192: '~',
  219: 'open-square-bracket',
  220: '\\',
  221: 'close-square-bracket',
  224: 'win'
};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.auth.twofactor',
  name: 'GoogleTOTPAuthService',
  extends: 'foam.nanos.auth.twofactor.AbstractTOTPAuthService',

  javaImports: [
    'com.google.common.io.BaseEncoding',
    'foam.dao.DAO',
    'foam.nanos.app.AppConfig',
    'foam.nanos.auth.User',
    'foam.nanos.notification.email.SMTPEmailService',
    'foam.nanos.session.Session',
    'foam.util.SafetyUtil',
    'io.nayuki.qrcodegen.QrCode',
    'java.net.URI'
  ],

  constants: [
    {
      name: 'KEY_SIZE',
      value: 10,
      type: 'int'
    },
    {
      name: 'STEP_SIZE',
      value: 30 * 1000,
      type: 'long'
    },
    {
      name: 'WINDOW',
      value: 3,
      type: 'int'
    }
  ],

  properties: [
    ['algorithm', 'SHA1' ]
  ],

  methods: [
    {
      name: 'generateKey',
      javaCode: `
        User user = (User) (x.get("agent") != null ?
          x.get("agent") : x.get("user"));
        DAO userDAO = (DAO) x.get("localUserDAO");

        // fetch from user dao to get secret key
        user = (User) userDAO.find(user.getId());

        // generate secret key, encode as base32 and store
        String key = BaseEncoding.base32().encode(generateSecret(KEY_SIZE));
        key = key.replaceFirst("[=]*$", "");

        // update user with secret key
        user = (User) user.fclone();
        user.setTwoFactorSecret(key);
        userDAO.put_(x, user);

        if ( ! generateQrCode ) {
          return key;
        }

        try {
          AppConfig config = (AppConfig) x.get("appConfig");
          SMTPEmailService service = (SMTPEmailService) x.get("smtpEmailService");
          String name = service == null ? "FOAM" : service.getDisplayName();
          String path = String.format("/%s:%s", name, user.getEmail());
          String query = String.format("secret=%s&issuer=%s&algorithm=%s", key, name, getAlgorithm());
          URI uri = new URI("otpauth", "totp", path, query, null);
          return "data:image/svg+xml;charset=UTF-8," + QrCode.encodeText(uri.toASCIIString(), QrCode.Ecc.MEDIUM).toSvgString(0);
        } catch ( Throwable t ) {
          throw new RuntimeException(t);
        }
      `
    },
    {
      name: 'verifyToken',
      javaCode: `
        long code = Long.parseLong(token, 10);
        User user = (User) (x.get("agent") != null ?
          x.get("agent") : x.get("user"));
        DAO userDAO = (DAO) x.get("localUserDAO");
        DAO sessionDAO = (DAO) x.get("sessionDAO");

        String sessionUser = (String) ( x.get("agent") != null ? "agent" : "user" );

        // fetch from user dao to get secret key
        user = (User) userDAO.find(user.getId());

        if ( checkCode(BaseEncoding.base32().decode(user.getTwoFactorSecret()), code, STEP_SIZE, WINDOW) ) {
          if ( ! user.getTwoFactorEnabled() ) {
            user = (User) user.fclone();
            user.setTwoFactorEnabled(true);
            userDAO.put(user);
          }

          // update session with two factor success set to true
          Session session = x.get(Session.class);
          session.setContext(session.getContext().put(sessionUser, user).put("twoFactorSuccess", true));
          sessionDAO.put(session);
          return true;
        }

        return false;
      `
    },
    {
      name: 'disable',
      javaCode: `
        if ( verifyToken(x, token) ) {
          User user = (User) (x.get("agent") != null ?
            x.get("agent") : x.get("user"));
          DAO userDAO = (DAO) x.get("localUserDAO");

          // fetch user from DAO and set two factor secret to null
          user = (User) userDAO.find(user.getId()).fclone();
          user.setTwoFactorEnabled(false);
          user.setTwoFactorSecret(null);
          userDAO.put_(x, user);
          return true;
        }

        return false;
      `
    }
  ]
});
<commit_msg>Cleanup.<commit_after>/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.auth.twofactor',
  name: 'GoogleTOTPAuthService',
  extends: 'foam.nanos.auth.twofactor.AbstractTOTPAuthService',

  documentation: 'Google Authenticator Time-based One-time Password Service (TOTP)',

  javaImports: [
    'com.google.common.io.BaseEncoding',
    'foam.dao.DAO',
    'foam.nanos.app.AppConfig',
    'foam.nanos.auth.User',
    'foam.nanos.notification.email.SMTPEmailService',
    'foam.nanos.session.Session',
    'foam.util.SafetyUtil',
    'io.nayuki.qrcodegen.QrCode',
    'java.net.URI'
  ],

  constants: [
    {
      name: 'KEY_SIZE',
      value: 10,
      type: 'int'
    },
    {
      name: 'STEP_SIZE',
      value: 30 * 1000,
      type: 'long'
    },
    {
      name: 'WINDOW',
      value: 3,
      type: 'int'
    }
  ],

  properties: [
    [ 'algorithm', 'SHA1' ]
  ],

  methods: [
    {
      name: 'generateKey',
      javaCode: `
        User user = (User) (x.get("agent") != null ?
          x.get("agent") :
          x.get("user")) ;
        DAO userDAO = (DAO) x.get("localUserDAO");

        // fetch from user dao to get secret key
        user = (User) userDAO.find(user.getId());

        // generate secret key, encode as base32 and store
        String key = BaseEncoding.base32().encode(generateSecret(KEY_SIZE));
        key = key.replaceFirst("[=]*$", "");

        // update user with secret key
        user = (User) user.fclone();
        user.setTwoFactorSecret(key);
        userDAO.put_(x, user);

        if ( ! generateQrCode ) {
          return key;
        }

        try {
          AppConfig config = (AppConfig) x.get("appConfig");
          SMTPEmailService service = (SMTPEmailService) x.get("smtpEmailService");
          String name = service == null ? "FOAM" : service.getDisplayName();
          String path = String.format("/%s:%s", name, user.getEmail());
          String query = String.format("secret=%s&issuer=%s&algorithm=%s", key, name, getAlgorithm());
          URI uri = new URI("otpauth", "totp", path, query, null);
          return "data:image/svg+xml;charset=UTF-8," + QrCode.encodeText(uri.toASCIIString(), QrCode.Ecc.MEDIUM).toSvgString(0);
        } catch ( Throwable t ) {
          throw new RuntimeException(t);
        }
      `
    },
    {
      name: 'verifyToken',
      javaCode: `
        long code      = Long.parseLong(token, 10);
        User user      = (User) (x.get("agent") != null ?
          x.get("agent") :
          x.get("user")) ;
        DAO userDAO    = (DAO) x.get("localUserDAO");
        DAO sessionDAO = (DAO) x.get("sessionDAO");

        String sessionUser = (String) ( x.get("agent") != null ? "agent" : "user" );

        // fetch from user dao to get secret key
        user = (User) userDAO.find(user.getId());

        if ( checkCode(BaseEncoding.base32().decode(user.getTwoFactorSecret()), code, STEP_SIZE, WINDOW) ) {
          if ( ! user.getTwoFactorEnabled() ) {
            user = (User) user.fclone();
            user.setTwoFactorEnabled(true);
            userDAO.put(user);
          }

          // update session with two factor success set to true
          Session session = x.get(Session.class);
          session.setContext(session.getContext().put(sessionUser, user).put("twoFactorSuccess", true));
          sessionDAO.put(session);
          return true;
        }

        return false;
      `
    },
    {
      name: 'disable',
      javaCode: `
        if ( verifyToken(x, token) ) {
          User user   = (User) (x.get("agent") != null ?
            x.get("agent") :
            x.get("user")) ;
          DAO userDAO = (DAO) x.get("localUserDAO");

          // fetch user from DAO and set two factor secret to null
          user = (User) userDAO.find(user.getId()).fclone();
          user.setTwoFactorEnabled(false);
          user.setTwoFactorSecret(null);
          userDAO.put_(x, user);

          return true;
        }

        return false;
      `
    }
  ]
});
<|endoftext|>


<commit_before>"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var search_service_1 = require('./search.service');
var api = "art";
var DATA2 = "http://localhost:3000/" + api + "/";
var AppComponent = (function () {
    function AppComponent(appservice) {
        this.appservice = appservice;
        this.messageE = ['Criterios no cumplidos:'];
        this.tipes = [];
        this.keys2 = [];
        this.keys = [];
        this.optionals = [];
        this.validation = true;
    }
    //Lo principal es asignar los elementos de la estructura de datos a un objeto, actualmente usamos un post,
    //pero es posible que en el futuro usemos solo obj para permitir una mayor diversidad de EEDD,
    //Los metodos JSON son para que test coja el valor de test sin vincularse a post
    AppComponent.prototype.ngOnInit = function () {
        var _this = this;
        api = "art";
        this.appservice.getJSON(DATA2).subscribe(function (res) {
            return _this.datos = res;
        }, function (error) { return _this.errorMessage = error; }, function () {
            _this.sacar();
            _this.test = JSON.parse(JSON.stringify(_this.datos[0]));
        });
    };
    //Saca las claves y los tipos de los elementos, asi como los campos opcionales
    AppComponent.prototype.sacar = function () {
        var _this = this;
        this.datos.forEach(function (post) {
            var t3 = [];
            var t4 = [];
            var aux = Object.keys(post);
            if (_this.keys2.length == 0)
                _this.keys2 = Object.keys(post);
            Object.keys(_this.keys2).forEach(function (key) {
                if (_this.keys2[key] != aux[key] && _this.optionals[_this.keys2[key]] != _this.keys2[key]) {
                    _this.optionals[_this.keys2[key]] = _this.keys2[key];
                }
            });
            Object.keys(aux).forEach(function (key) {
                if (_this.keys2[key] != aux[key] && _this.tipes[aux[key]] != aux[key]) {
                    _this.keys2.push(aux[key]);
                    _this.optionals[aux[key]] = aux[key];
                }
            });
            _this.keys2.forEach(function (key) {
                if (_this.tipes[key] == null)
                    _this.tipes[key] = _this.isType(post[key]);
            });
            if (_this.keys.length === 0) {
                _this.keys2.forEach(function (key) {
                    //el orden de cuando t4 coge los keys
                    if (_this.isObject(post[key]))
                        t3 = t3.concat(Object.keys(post[key]));
                    Object.keys(t3).forEach(function (a) {
                        if (_this.keys[a] != t3[a]) {
                            _this.keys[a] = t3[a];
                        }
                    });
                });
            }
            else {
                _this.keys2.forEach(function (key) {
                    //if this.keys == null o [])?
                    t3 = t3.concat(Object.keys(post[key]));
                });
                Object.keys(t3).forEach(function (a) {
                    if (_this.keys[a] != t3[a] && _this.tipes[t3[a]] == null) {
                        _this.keys.push(t3[a]);
                        _this.optionals[t3[a]] = t3[a];
                    }
                });
                Object.keys(_this.keys).forEach(function (a) {
                    if (_this.keys[a] != t3[a] && _this.optionals[_this.keys[a]] != _this.keys[a])
                        _this.optionals[_this.keys[a]] = _this.keys[a];
                });
                _this.keys2.forEach(function (key) {
                    _this.keys.forEach(function (k) {
                        if (post[key][k] != null) {
                            if (_this.keys[k] == null)
                                _this.tipes[k] = _this.isType(post[key][k]);
                        }
                    });
                });
            }
        });
        this.lee = Object.keys(this.optionals) + "   ;   " + Object.keys(this.keys2) + "   ;   " + Object.keys(this.tipes) + "   ;   " + this.tipes["animal"] + "   ;   " + this.keys[3];
    };
    AppComponent.prototype.isObject = function (val) { return typeof val === 'object'; };
    AppComponent.prototype.isType = function (val) { return typeof val; };
    //Metodo para guardar el cambio del elemento booleano de la estructura de datos el cual es gestionado en un Radio Button
    AppComponent.prototype.onCheck = function (v, key2, key) {
        this.test[key2][key] = v;
    };
    AppComponent.prototype.onCheck2 = function (v, key2) {
        this.test[key2] = v;
    };
    //haber si podemos eliminar la dependencia en variables locales, El id lo presupondremos como clave primaria de los elementos.
    AppComponent.prototype.addb = function () {
        var _this = this;
        if (this.validar(this.test)) {
            var idp_1 = 1;
            var cont_1 = true;
            this.datos.forEach(function (post) {
                if (cont_1) {
                    if (post.id == idp_1)
                        idp_1 = idp_1 + 1;
                    else
                        cont_1 = false;
                }
            });
            this.test.id = idp_1;
            this.appservice.add(DATA2, this.test).subscribe(function (data) { return null; }, function (error) { return _this.errorMessage = error; }, function () { return _this.appservice.getJSON(DATA2).subscribe(function (res) {
                return _this.datos = res;
            }); });
            this.datos.sort;
        }
    };
    //tal vez mejor llevarlo a otro componente si es que acabo haciendo la tabla y el formulario en otro componente
    AppComponent.prototype.alform = function (post) {
        //this.title = post.datos.title;
        //this.category = post.datos.category;
        //this.id = post.id;
        //this.estado = post.varios.estado;
        this.test = JSON.parse(JSON.stringify(post));
    };
    //haber si podemos eliminar completamente la dependencia en variables locales.
    AppComponent.prototype.modificar = function (post) {
        var _this = this;
        if (this.validar(this.test)) {
            this.appservice.update(DATA2, this.test).subscribe(function (data) { return null; }, function (error) { return _this.errorMessage = error; }, function () { return _this.appservice.getJSON(DATA2).subscribe(function (res) {
                return _this.datos = res;
            }); });
        }
    };
    AppComponent.prototype.delet = function (post) {
        var _this = this;
        this.appservice.delete(DATA2, post.id).subscribe(function (data) { return null; }, function (error) { return _this.errorMessage = error; }, function () { return _this.appservice.getJSON(DATA2).subscribe(function (res) {
            return _this.datos = res;
        }); });
    };
    AppComponent.prototype.validar = function (post) {
        var _this = this;
        var val = true;
        var parser = new DOMParser();
        this.keys2.forEach(function (key2) {
            if (_this.tipes[key2] != 'object')
                post[key2] = parser.parseFromString(post[key2], 'text/html');
        });
        for (var _i = 0, _a = this.datos; _i < _a.length; _i++) {
            var p = _a[_i];
            if (p.id !== post.id)
                if (post.datos.title == p.datos.title) {
                    this.messageE.push('- No repita titulos');
                    val = false;
                }
            ;
        }
        ;
        this.keys2.forEach(function (key) {
            if (_this.tipes[key] == "number") {
                try {
                    post[key] = parseInt(post[key]);
                }
                catch (e) {
                    val = false;
                    _this.messageE.push("- Introduzca numeros donde corresponda.");
                }
            }
        });
        this.validation = val;
    };
    __decorate([
        core_1.Input(),
        __metadata('design:type', Array)
    ], AppComponent.prototype, "datos", void 0);
    __decorate([
        core_1.Input(),
        __metadata('design:type', Array)
    ], AppComponent.prototype, "tipes", void 0);
    __decorate([
        core_1.Input(),
        __metadata('design:type', Array)
    ], AppComponent.prototype, "keys2", void 0);
    __decorate([
        core_1.Input(),
        __metadata('design:type', Array)
    ], AppComponent.prototype, "keys", void 0);
    __decorate([
        core_1.Input(),
        __metadata('design:type', Array)
    ], AppComponent.prototype, "optionals", void 0);
    AppComponent = __decorate([
        core_1.Component({
            selector: 'my-app',
            templateUrl: 'app/app.component.html',
            providers: [search_service_1.AppServices],
        }),
        __metadata('design:paramtypes', [search_service_1.AppServices])
    ], AppComponent);
    return AppComponent;
}());
exports.AppComponent = AppComponent;
//# sourceMappingURL=app.component.js.map<commit_msg>Delete app.component.js<commit_after><|endoftext|>


<commit_before>const {until, WebElement} = require('selenium-webdriver');
const SeleniumWebdriver = require('./');
const Transport = require('../');
const {Logger, isString} = require('../../utils');

module.exports = class MethodMappings {
  get driver() {
    return this.transport.driver;
  }

  get settings() {
    return this.transport.settings;
  }

  getWebElement(webElementOrString) {
    if (webElementOrString instanceof WebElement) {
      return webElementOrString;
    }

    if (isString(webElementOrString)) {
      return new WebElement(this.driver, webElementOrString);
    }
  }

  constructor(transport) {
    this.transport = transport;
  }

  get methods() {
    return {
      ///////////////////////////////////////////////////////////
      // Session related
      ///////////////////////////////////////////////////////////
      sessionAction(action) {
        switch (action) {
          case 'DELETE':
            return this.driver.quit();

          default:
            return this.driver.getSession();
        }
      },

      getSessions: '/sessions',
      getStatus: '/status',

      session: {
        ///////////////////////////////////////////////////////////
        // Timeouts
        ///////////////////////////////////////////////////////////
        setTimeoutType(type, value) {
          return TransportActions.post({
            path: '/timeouts',
            data: {
              type: type,
              ms: value
            }
          });
        },

        setTimeoutsAsyncScript(value) {
          return TransportActions.post({
            path: '/timeouts/async_script',
            data: {
              ms: value
            }
          });
        },

        setTimeoutsImplicitWait(value) {
          return TransportActions.post({
            path: '/timeouts/implicit_wait',
            data: {
              ms: value
            }
          });
        },

        getTimeouts: '/timeouts',

        ///////////////////////////////////////////////////////////
        // Session log
        ///////////////////////////////////////////////////////////
        getSessionLogTypes: '/log/types',

        getLogContents(type) {
          return TransportActions.post({
            path: '/log',
            data: {
              type: type
            }
          });
        },

        ///////////////////////////////////////////////////////////
        // Navigation
        ///////////////////////////////////////////////////////////
        async navigateTo(url) {
          await this.driver.navigate().to(url);

          return {
            value: null
          };
        },

        getCurrentUrl: '/url',
        navigateBack() {
          return TransportActions.post({
            path: '/back'
          });
        },
        navigateForward() {
          return TransportActions.post({
            path: '/forward'
          });
        },
        pageRefresh() {
          return TransportActions.post({
            path: '/refresh'
          });
        },
        getPageTitle: '/title',

        ///////////////////////////////////////////////////////////
        // Windows
        ///////////////////////////////////////////////////////////
        async switchToWindow(handle) {
          await this.driver.switchTo().window(handle);

          return {
            value: null
          };
        },

        async closeWindow() {
          await this.driver.close();

          return {
            value: null
          };
        },

        async getWindowHandle() {
          const value = await this.driver.getWindowHandle();

          return {
            value
          };
        },

        async getAllWindowHandles() {
          const value = await this.driver.getAllWindowHandles();

          return {
            value
          };
        },

        async getWindowPosition() {
          const {x, y} = await this.driver.manage().window().getRect();

          return {
            value: {
              x,
              y
            }
          };
        },

        async maximizeWindow(windowHandle) {
          await this.driver.manage().window().maximize();

          return {
            value: null
          };
        },

        async minimizeWindow() {
          await this.driver.manage().window().minimize();

          return {
            value: null
          };
        },

        async fullscreenWindow() {
          await this.driver.manage().window().fullscreen();

          return {
            value: null
          };
        },

        async openNewWindow() {
          // return TransportActions.post('/window/new');
          await this.driver.switchTo().newWindow('window');

          return {
            value: null
          };
        },

        //Kept windowHandle as params for backward comptability.
        async setWindowPosition(windowHandle, x, y) {
          await this.driver.manage().window().setRect({
            x,
            y
          });

          return {
            value: null
          };
        },

        async getWindowSize() {
          const {width, height} = await this.driver.manage().window().getRect();

          return {
            value: {
              width,
              height
            }
          };
        },

        //Kept windowHandle as params for backward comptability.
        async setWindowSize(windowHandle, width, height) {
          await this.driver.manage().window().setRect({
            width,
            height
          });

          return {
            value: null
          };
        },

        async getWindowRect() {
          const value = await this.driver.manage().window().getRect();

          return {
            value
          };
        },

        async setWindowRect(data) {
          await this.driver.manage().window().setRect(data);

          return {
            value: null
          };
        },

        ///////////////////////////////////////////////////////////
        // Frames
        ///////////////////////////////////////////////////////////
        switchToFrame(frameId) {
          if (frameId === undefined) {
            frameId = null;
          }

          return TransportActions.post({
            path: '/frame',
            data: {
              id: frameId
            }
          });
        },

        switchToParentFrame() {
          return TransportActions.post('/frame/parent');
        },

        ///////////////////////////////////////////////////////////
        // Elements
        ///////////////////////////////////////////////////////////
        async locateSingleElement(element) {
          const locator = SeleniumWebdriver.createLocator(element);
          //const {waitForConditionTimeout, waitForConditionPollInterval}

          const webElement = await this.driver.wait(until.elementLocated(locator));
          const elementId = await webElement.getId();

          return {
            value: elementId,
            webElement
          };
        },

        async locateMultipleElements(element) {
          const locator = SeleniumWebdriver.createLocator(element);
          const resultValue = await this.driver.findElements(locator);
          const resultProcessed = await Promise.all(resultValue.map(async webElement => {
            const elementId = await webElement.getId();

            return {[Transport.WEB_ELEMENT_ID]: elementId};
          }));

          return {
            value: resultProcessed
          };
        },

        elementIdEquals(id, otherId) {
          return `/element/${id}/equals/${otherId}`;
        },

        locateSingleElementByElementId({id, using, value}) {
          return TransportActions.post({
            path: `/element/${id}/element`,
            data: {
              using,
              value
            }
          });
        },

        locateMultipleElementsByElementId({id, using, value}) {
          return TransportActions.post({
            path: `/element/${id}/elements`,
            data: {
              using,
              value
            }
          });
        },

        getActiveElement() {
          return TransportActions.post('/element/active');
        },

        getElementAttribute(id, attributeName) {
          return `/element/${id}/attribute/${attributeName}`;
        },

        getElementCSSValue(id, cssPropertyName) {
          return `/element/${id}/css/${cssPropertyName}`;
        },

        getElementProperty(id, propertyName) {
          return `/element/${id}/property/${propertyName}`;
        },

        getElementTagName(id) {
          return `/element/${id}/name`;
        },

        getElementSize(id) {
          return `/element/${id}/size`;
        },

        getElementText(id) {
          return `/element/${id}/text`;
        },

        getElementValue(id) {
          return `/element/${id}/attribute/value`;
        },

        getElementLocation(id) {
          return `/element/${id}/location`;
        },

        isElementLocationInView(id) {
          return `/element/${id}/location_in_view`;
        },

        async isElementDisplayed(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isDisplayed();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        isElementEnabled(id) {
          return `/element/${id}/enabled`;
        },

        isElementSelected(id) {
          return `/element/${id}/selected`;
        },

        clearElementValue(id) {
          return TransportActions.post(`/element/${id}/clear`);
        },

        setElementValue(id, value) {
          if (Array.isArray(value)) {
            value = value.join('');
          } else {
            value = String(value);
          }

          return TransportActions.post({
            path: `/element/${id}/value`,
            data: {
              value: value.split('')
            }
          });
        },

        clickElement(id) {
          return TransportActions.post(`/element/${id}/click`);
        },

        elementSubmit(id) {
          return TransportActions.post(`/element/${id}/submit`);
        },

        sendKeys(keys) {
          return TransportActions.post({
            path: '/keys',
            data: {
              value: keys
            }
          });
        },

        ///////////////////////////////////////////////////////////
        // Document Handling
        ///////////////////////////////////////////////////////////
        getPageSource: '/source',

        async executeScript(script, args) {
          const value = await this.driver.executeScript(script, args);

          return {
            value
          };
        },

        executeScriptAsync(fn, args) {
          return TransportActions.post({
            path: '/execute_async',
            data: {
              script: fn,
              args: args
            }
          });
        },

        ///////////////////////////////////////////////////////////
        // Cookies
        ///////////////////////////////////////////////////////////

        async setCookieString(cookie) {

          await this.driver.manage().addCookie(cookie);

          return {
            value: null
          };
        },

        async deleteCookie(cookieName) {
          await this.driver.manage().deleteCookie(cookieName);

          return {
            value: null
          };
        },

        async deleteAllCookies() {
          await this.driver.manage().deleteAllCookies();

          return {
            value: null
          };
        },

        async getCookieString() {

          const value = await this.driver.manage().getCookies();

          return {
            value
          };

        },

        ///////////////////////////////////////////////////////////
        // User Actions
        ///////////////////////////////////////////////////////////
        doubleClick() {
          return TransportActions.post('/doubleclick');
        },

        mouseButtonClick(buttonIndex) {
          return TransportActions.post({
            path: '/click',
            data: {
              button: buttonIndex
            }
          });
        },

        mouseButtonUp(buttonIndex) {
          return TransportActions.post({
            path: '/buttonup',
            data: {
              button: buttonIndex
            }
          });
        },

        mouseButtonDown(buttonIndex) {
          return TransportActions.post({
            path: '/buttondown',
            data: {
              button: buttonIndex
            }
          });
        },

        moveTo(id, xoffset, yoffset) {
          const data = {};

          if (typeof id == 'string') {
            data.element = id;
          }

          if (typeof xoffset == 'number') {
            data.xoffset = xoffset;
          }

          if (typeof yoffset == 'number') {
            data.yoffset = yoffset;
          }

          return TransportActions.post({
            path: '/moveto',
            data
          });
        },

        ///////////////////////////////////////////////////////////
        // User Prompts
        ///////////////////////////////////////////////////////////
        async acceptAlert() {
          await this.driver.switchTo().alert().accept();

          return {
            value: null
          };
        },

        async dismissAlert() {
          await this.driver.switchTo().alert().dismiss();

          return {
            value: null
          };
        },

        async getAlertText() {
          const value = await this.driver.switchTo().alert().getText();

          return {
            value
          };
        },

        async setAlertText(keys) {
          const alert = await this.driver.switchTo().alert();
          await alert.sendKeys(keys);
          const value = await alert.accept();

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Screen
        ///////////////////////////////////////////////////////////
        getScreenshot(logBase64Data) {
          return Promise.resolve('');

          return {
            path: '/screenshot',
            addtOpts: {
              suppressBase64Data: !logBase64Data
            }
          };
        },

        getScreenOrientation: '/orientation',

        setScreenOrientation(orientation) {
          return TransportActions.post({
            path: '/orientation',
            data: {
              orientation: orientation
            }
          });
        },

        getAvailableContexts: '/contexts',

        getCurrentContext: '/context',

        setCurrentContext(context) {
          return TransportActions.post({
            path: '/context',
            data: {
              name: context
            }
          });
        },

        ///////////////////////////////////////////////////////////////////////////
        // Selenium Webdriver
        ///////////////////////////////////////////////////////////////////////////
        async wait(conditionFn, timeMs) {
          await this.driver.wait(conditionFn(), timeMs);

          return {
            value: null
          };
        }
      }
    };
  }
};
<commit_msg>update: method-mapping for elments, and frames (#2739)<commit_after>const {until, WebElement} = require('selenium-webdriver');
const SeleniumWebdriver = require('./');
const Transport = require('../');
const {Logger, isString} = require('../../utils');

module.exports = class MethodMappings {
  get driver() {
    return this.transport.driver;
  }

  get settings() {
    return this.transport.settings;
  }

  getWebElement(webElementOrString) {
    if (webElementOrString instanceof WebElement) {
      return webElementOrString;
    }

    if (isString(webElementOrString)) {
      return new WebElement(this.driver, webElementOrString);
    }
  }

  constructor(transport) {
    this.transport = transport;
  }

  get methods() {
    return {
      ///////////////////////////////////////////////////////////
      // Session related
      ///////////////////////////////////////////////////////////
      sessionAction(action) {
        switch (action) {
          case 'DELETE':
            return this.driver.quit();

          default:
            return this.driver.getSession();
        }
      },

      getSessions: '/sessions',
      getStatus: '/status',

      session: {
        ///////////////////////////////////////////////////////////
        // Timeouts
        ///////////////////////////////////////////////////////////
        setTimeoutType(type, value) {
          return TransportActions.post({
            path: '/timeouts',
            data: {
              type: type,
              ms: value
            }
          });
        },

        setTimeoutsAsyncScript(value) {
          return TransportActions.post({
            path: '/timeouts/async_script',
            data: {
              ms: value
            }
          });
        },

        setTimeoutsImplicitWait(value) {
          return TransportActions.post({
            path: '/timeouts/implicit_wait',
            data: {
              ms: value
            }
          });
        },

        getTimeouts: '/timeouts',

        ///////////////////////////////////////////////////////////
        // Session log
        ///////////////////////////////////////////////////////////
        getSessionLogTypes: '/log/types',

        getLogContents(type) {
          return TransportActions.post({
            path: '/log',
            data: {
              type: type
            }
          });
        },

        ///////////////////////////////////////////////////////////
        // Navigation
        ///////////////////////////////////////////////////////////
        async navigateTo(url) {
          await this.driver.navigate().to(url);

          return {
            value: null
          };
        },

        getCurrentUrl: '/url',
        navigateBack() {
          return TransportActions.post({
            path: '/back'
          });
        },
        navigateForward() {
          return TransportActions.post({
            path: '/forward'
          });
        },
        pageRefresh() {
          return TransportActions.post({
            path: '/refresh'
          });
        },
        getPageTitle: '/title',

        ///////////////////////////////////////////////////////////
        // Windows
        ///////////////////////////////////////////////////////////
        async switchToWindow(handle) {
          await this.driver.switchTo().window(handle);

          return {
            value: null
          };
        },

        async closeWindow() {
          await this.driver.close();

          return {
            value: null
          };
        },

        async getWindowHandle() {
          const value = await this.driver.getWindowHandle();

          return {
            value
          };
        },

        async getAllWindowHandles() {
          const value = await this.driver.getAllWindowHandles();

          return {
            value
          };
        },

        async getWindowPosition() {
          const {x, y} = await this.driver.manage().window().getRect();

          return {
            value: {
              x,
              y
            }
          };
        },

        async maximizeWindow(windowHandle) {
          await this.driver.manage().window().maximize();

          return {
            value: null
          };
        },

        async minimizeWindow() {
          await this.driver.manage().window().minimize();

          return {
            value: null
          };
        },

        async fullscreenWindow() {
          await this.driver.manage().window().fullscreen();

          return {
            value: null
          };
        },

        async openNewWindow() {
          // return TransportActions.post('/window/new');
          await this.driver.switchTo().newWindow('window');

          return {
            value: null
          };
        },

        //Kept windowHandle as params for backward comptability.
        async setWindowPosition(windowHandle, x, y) {
          await this.driver.manage().window().setRect({
            x,
            y
          });

          return {
            value: null
          };
        },

        async getWindowSize() {
          const {width, height} = await this.driver.manage().window().getRect();

          return {
            value: {
              width,
              height
            }
          };
        },

        //Kept windowHandle as params for backward comptability.
        async setWindowSize(windowHandle, width, height) {
          await this.driver.manage().window().setRect({
            width,
            height
          });

          return {
            value: null
          };
        },

        async getWindowRect() {
          const value = await this.driver.manage().window().getRect();

          return {
            value
          };
        },

        async setWindowRect(data) {
          await this.driver.manage().window().setRect(data);

          return {
            value: null
          };
        },

        ///////////////////////////////////////////////////////////
        // Frames
        ///////////////////////////////////////////////////////////
        async switchToFrame(frameId) {
          if (frameId === undefined) {
            frameId = null;
          }

          await this.driver.manage().switchToFrame({
            id: frameId
          });

          return {
            value: null
          };
        },

        async switchToParentFrame() {
          await this.driver.manage().switchToParentFrame();

          return {
            value: null
          };
        },

        ///////////////////////////////////////////////////////////
        // Elements
        ///////////////////////////////////////////////////////////
        async locateSingleElement(element) {
          const locator = SeleniumWebdriver.createLocator(element);
          //const {waitForConditionTimeout, waitForConditionPollInterval}

          const webElement = await this.driver.wait(until.elementLocated(locator));
          const elementId = await webElement.getId();

          return {
            value: elementId,
            webElement
          };
        },

        async locateMultipleElements(element) {
          const locator = SeleniumWebdriver.createLocator(element);
          const resultValue = await this.driver.findElements(locator);
          const resultProcessed = await Promise.all(resultValue.map(async webElement => {
            const elementId = await webElement.getId();

            return {[Transport.WEB_ELEMENT_ID]: elementId};
          }));

          return {
            value: resultProcessed
          };
        },

        elementIdEquals(id, otherId) {
          return `/element/${id}/equals/${otherId}`;
        },

        async locateSingleElementByElementId({id, value}) {
          const locator = SeleniumWebdriver.createLocator(value);
          const element = await this.getWebElement(id);

          const webElement = await element.findElement(locator);

          const elementId = await webElement.getId();

          return {
            value: webElement,
            elementId
          };
        },

        async locateMultipleElementsByElementId({id, using, value}) {
          const locator = SeleniumWebdriver.createLocator(value);
          const element = await this.getWebElement(id);
          const resultValue = await element.findElements(locator);

          const resultProcessed = await Promise.all(resultValue.map(async webElement => {
            const elementId = await webElement.getId();

            return {[Transport.WEB_ELEMENT_ID]: elementId};
          }));

          return {
            value: resultProcessed
          };
        },

        getActiveElement() {
          return TransportActions.post('/element/active');
        },

        async getElementAttribute(webElement, attributeName) {
          const element = this.getWebElement(webElement);
          const elementValue = await element.getAttribute(attributeName);

          return {
            value: elementValue
          };
        },

        async getElementCSSValue(id, cssPropertyName) {
          const element = this.getWebElement(id);
          const elementCssValue = await element.getCssValue(cssPropertyName);

          return {
            value: elementCssValue
          };
        },

        async getElementProperty(webElement, propertyName) {
          const element = this.getWebElement(webElement);
          const elementValue = await element.getAttribute(propertyName);

          return {
            value: elementValue
          };
        },

        async getElementTagName(id) {
          const element = this.getWebElement(id);
          const elementTagName = await element.getTagName();

          return {
            value: elementTagName
          };
        },

        async getElementSize(id) {
          const element = this.getWebElement(id);
          const elementSize = await element.getRect();

          return {
            value: elementSize
          };
        },

        async getElementText(id) {
          const element = this.getWebElement(id);
          const elementText = await element.getText();

          return {
            value: elementText
          };
        },

        // the value param is compulsory
        async getElementValue(webElement, value) {
          const element = this.getWebElement(webElement);
          const elementValue = await element.getAttribute(value);

          return {
            value: elementValue
          };
        },

        async getElementLocation(id) {
          const element = this.getWebElement(id);
          const {x, y} = await element.getRect();

          return {
            value: {
              x,
              y
            }
          };
        },

        isElementLocationInView(id) {
          return `/element/${id}/location_in_view`;
        },

        async isElementDisplayed(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isDisplayed();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async isElementEnabled(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isEnabled();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async isElementSelected(webElement) {
          try {
            const element = this.getWebElement(webElement);
            const value = await element.isSelected();

            return {
              value
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async clearElementValue(webElement) {
          const element = this.getWebElement(webElement);
          await element.clear();

          return {
            value: null
          };
        },

        async setElementValue(webElement, value) {
          if (Array.isArray(value)) {
            value = value.join('');
          } else {
            value = String(value);
          }

          try {
            const element = this.getWebElement(webElement);
            await element.sendKeys(value);

            return {
              value: null
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async clickElement(webElement) {
          try {
            const element = this.getWebElement(webElement);
            await element.click();

            return {
              value: null
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        async elementSubmit(webElement) {
          try {
            const element = this.getWebElement(webElement);
            await element.submit();

            return {
              value: null
            };
          } catch (error) {
            Logger.error(error);

            return {
              error,
              status: -1
            };
          }
        },

        sendKeys(keys) {
          return TransportActions.post({
            path: '/keys',
            data: {
              value: keys
            }
          });
        },

        ///////////////////////////////////////////////////////////
        // Document Handling
        ///////////////////////////////////////////////////////////
        getPageSource: '/source',

        async executeScript(script, args) {
          const value = await this.driver.executeScript(script, args);

          return {
            value
          };
        },

        executeScriptAsync(fn, args) {
          return TransportActions.post({
            path: '/execute_async',
            data: {
              script: fn,
              args: args
            }
          });
        },

        ///////////////////////////////////////////////////////////
        // Cookies
        ///////////////////////////////////////////////////////////

        async setCookieString(cookie) {
          await this.driver.manage().addCookie(cookie);

          return {
            value: null
          };
        },

        async deleteCookie(cookieName) {
          await this.driver.manage().deleteCookie(cookieName);

          return {
            value: null
          };
        },

        async deleteAllCookies() {
          await this.driver.manage().deleteAllCookies();

          return {
            value: null
          };
        },

        async getCookieString() {
          const value = await this.driver.manage().getCookies();

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // User Actions
        ///////////////////////////////////////////////////////////
        doubleClick() {
          return TransportActions.post('/doubleclick');
        },

        mouseButtonClick(buttonIndex) {
          return TransportActions.post({
            path: '/click',
            data: {
              button: buttonIndex
            }
          });
        },

        mouseButtonUp(buttonIndex) {
          return TransportActions.post({
            path: '/buttonup',
            data: {
              button: buttonIndex
            }
          });
        },

        mouseButtonDown(buttonIndex) {
          return TransportActions.post({
            path: '/buttondown',
            data: {
              button: buttonIndex
            }
          });
        },

        moveTo(id, xoffset, yoffset) {
          const data = {};

          if (typeof id == 'string') {
            data.element = id;
          }

          if (typeof xoffset == 'number') {
            data.xoffset = xoffset;
          }

          if (typeof yoffset == 'number') {
            data.yoffset = yoffset;
          }

          return TransportActions.post({
            path: '/moveto',
            data
          });
        },

        ///////////////////////////////////////////////////////////
        // User Prompts
        ///////////////////////////////////////////////////////////
        async acceptAlert() {
          await this.driver.switchTo().alert().accept();

          return {
            value: null
          };
        },

        async dismissAlert() {
          await this.driver.switchTo().alert().dismiss();

          return {
            value: null
          };
        },

        async getAlertText() {
          const value = await this.driver.switchTo().alert().getText();

          return {
            value
          };
        },

        async setAlertText(keys) {
          const alert = await this.driver.switchTo().alert();
          await alert.sendKeys(keys);
          const value = await alert.accept();

          return {
            value
          };
        },

        ///////////////////////////////////////////////////////////
        // Screen
        ///////////////////////////////////////////////////////////
        getScreenshot(logBase64Data) {
          return Promise.resolve('');

          return {
            path: '/screenshot',
            addtOpts: {
              suppressBase64Data: !logBase64Data
            }
          };
        },

        getScreenOrientation: '/orientation',

        setScreenOrientation(orientation) {
          return TransportActions.post({
            path: '/orientation',
            data: {
              orientation: orientation
            }
          });
        },

        getAvailableContexts: '/contexts',

        getCurrentContext: '/context',

        setCurrentContext(context) {
          return TransportActions.post({
            path: '/context',
            data: {
              name: context
            }
          });
        },

        ///////////////////////////////////////////////////////////////////////////
        // Selenium Webdriver
        ///////////////////////////////////////////////////////////////////////////
        async wait(conditionFn, timeMs) {
          await this.driver.wait(conditionFn(), timeMs);

          return {
            value: null
          };
        }
      }
    };
  }
};
<|endoftext|>


<commit_before>'use strict';

+$(function () {
    var $window = $(window);
    var $body   = $(document.body);
    var $sideBar = $('.forum-toc-affix');
    var $header = $('#header');

    $body.scrollspy({ target: '.forum-toc-affix', offset: 300 + $header.outerHeight() })

    $sideBar.affix({
        offset: {
            top: function () {
                var sideBarMargin  = parseInt($sideBar.children(0).css('margin-top'), 10);
                return (this.top = $sideBar.offset().top - sideBarMargin - 30 - $header.outerHeight());
            }
        }
    });

    $('.forum-toc-affix .nav > li').popover({
        placement: 'left',
        title: 'Preview',
        trigger: 'hover'
    });

    var fooFunc = function (e) {
        var clName = 'post-being-read';
        $('.panel-header').removeClass(clName);
        $($(this).children(0).attr('href') + ' .panel-header').addClass(clName);
        // Hm, send read-info to server?
    };
    fooFunc.call($('.forum-toc-affix .nav > li.active'), 'e');

    $('.forum-toc-affix .nav > li').on('activate.bs.scrollspy', fooFunc);

    var clickFunc = _.debounce(function () {
        $('html, body').animate({scrollTop: $($(this).attr('href')).offset().top - 280}, 800);
    }, 500, true)

    $('.forum-toc-affix a[href^="#"]').click(function (e) {
          // don't follow the link (it's a fake)
          e.preventDefault()

          // instead scroll there!
          // subtracted something since we scroll-spy with offset and have to scroll a little bit higher
          clickFunc.call(this)
    });

    // Debounce + CSS transitions = 4wsum!
    var someFunc = function (e) {
        // Yes, always re-calc these values
        // The user may have resized windows, we may have added items, etc.
        var $window = $(window);
        var $body   = $(document.body);
        var $sideBar = $('.forum-toc-affix');
        var $sidebarAffix = $('.forum-toc-affix.affix');
        var $header = $('#header');

        var visibleHeight = $window.innerHeight();
        var sidebarHeight = $sideBar.outerHeight();

        var docHeight = $(document).innerHeight();
        var currentScrollPosition = $window.scrollTop();

        if (!!(($(document).innerWidth() > 768) && $sidebarAffix.length && (sidebarHeight > visibleHeight))) {
            var offsetTop = (currentScrollPosition / (docHeight)) * ((sidebarHeight + 150) - visibleHeight + $header.outerHeight());
            $sidebarAffix.css("top", ((-offsetTop) + 30 + $header.outerHeight()) + 'px');
        } else {
            $('.forum-toc-affix').css('top', 30 + $header.outerHeight());
            $('.forum-toc-affix.affix-top').css('top', 0);
        }
    };

    someFunc();
    $window.scroll(someFunc);
});
<commit_msg>Disabling popovers for non-main toc entries<commit_after>'use strict';

+$(function () {
    var $window = $(window);
    var $body   = $(document.body);
    var $sideBar = $('.forum-toc-affix');
    var $header = $('#header');

    $body.scrollspy({ target: '.forum-toc-affix', offset: 300 + $header.outerHeight() })

    $sideBar.affix({
        offset: {
            top: function () {
                var sideBarMargin  = parseInt($sideBar.children(0).css('margin-top'), 10);
                return (this.top = $sideBar.offset().top - sideBarMargin - 30 - $header.outerHeight());
            }
        }
    });

    $('.forum-toc-affix .nav > li[data-toggle="popover"]').popover({
        placement: 'left',
        title: 'Preview',
        trigger: 'hover'
    });

    var fooFunc = function (e) {
        var clName = 'post-being-read';
        $('.panel-header').removeClass(clName);
        $($(this).children(0).attr('href') + ' .panel-header').addClass(clName);
        // Hm, send read-info to server?
    };
    fooFunc.call($('.forum-toc-affix .nav > li.active'), 'e');

    $('.forum-toc-affix .nav > li').on('activate.bs.scrollspy', fooFunc);

    var clickFunc = _.debounce(function () {
        $('html, body').animate({scrollTop: $($(this).attr('href')).offset().top - 280}, 800);
    }, 500, true)

    $('.forum-toc-affix a[href^="#"]').click(function (e) {
          // don't follow the link (it's a fake)
          e.preventDefault()

          // instead scroll there!
          // subtracted something since we scroll-spy with offset and have to scroll a little bit higher
          clickFunc.call(this)
    });

    // Debounce + CSS transitions = 4wsum!
    var someFunc = function (e) {
        // Yes, always re-calc these values
        // The user may have resized windows, we may have added items, etc.
        var $window = $(window);
        var $body   = $(document.body);
        var $sideBar = $('.forum-toc-affix');
        var $sidebarAffix = $('.forum-toc-affix.affix');
        var $header = $('#header');

        var visibleHeight = $window.innerHeight();
        var sidebarHeight = $sideBar.outerHeight();

        var docHeight = $(document).innerHeight();
        var currentScrollPosition = $window.scrollTop();

        if (!!(($(document).innerWidth() > 768) && $sidebarAffix.length && (sidebarHeight > visibleHeight))) {
            var offsetTop = (currentScrollPosition / (docHeight)) * ((sidebarHeight + 150) - visibleHeight + $header.outerHeight());
            $sidebarAffix.css("top", ((-offsetTop) + 30 + $header.outerHeight()) + 'px');
        } else {
            $('.forum-toc-affix').css('top', 30 + $header.outerHeight());
            $('.forum-toc-affix.affix-top').css('top', 0);
        }
    };

    someFunc();
    $window.scroll(someFunc);
});
<|endoftext|>