<commit_before>(function($) {

    Sammy = Sammy || {};

    Sammy.CouchBibItemAdmin = function( app ) {

        var createNewItem = function( couchapp, data, context ) {

            if( !couchapp.ddoc.types[ data['doctype'] ] ) {

                context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Unbekannter Typ!" } ) );

            } else {

                var type = couchapp.ddoc.types[ data['doctype'] ];
                var doc = {};
                doc.fields = [ { id : "citekey", name : couchapp.ddoc.fieldnames[ "citekey" ] } ];

                for( var idx in type.fields ) {
                    if( type.fields[idx].indexOf( "note" ) == -1 ) {
                        doc.fields.push( { id : type.fields[idx], name : couchapp.ddoc.fieldnames[ type.fields[idx] ] } );
                    }
                }
                doc.fields.push( { id : "tags", name : couchapp.ddoc.fieldnames[ "tags" ] } );

                var allFields = ["citekey"];
                allFields = allFields.concat( type.fields );
                allFields.push( "tags" );

                $("#content").append( context.mustache( couchapp.ddoc.templates.itemdetails, doc ) );
                $("#itemDetails").tabs();

                var postForm = couchapp.docForm( "form#item_details", {
                    fields : allFields,
                    template : { type : data['doctype'] },
                    onLoad : function(doc) {
                        if( doc.tags ) {
                            doc.tags = doc.tags.join(" ");
                        }
                        if( doc.author ) {
                            doc.author = doc.author.join(";");
                        }
                    },
                    beforeSave : function(doc) {
                        if(!doc.created_at) {
                            doc.created_at = new Date();
                        }
                        if(!doc._id) {
                            doc._id = doc.citekey;
                        }
                        if(doc.tags) {
                            doc.tags = $.trim(doc.tags);
                            doc.tags = doc.tags.split(" ");
                            for(var idx in doc.tags) {
                                doc.tags[idx] = $.trim(doc.tags[idx]);
                            }
                        }
                        if(doc.author) {
                            doc.author = doc.author.split(";");
                            for(var idx in doc.author) {
                                doc.author[idx] = $.trim(doc.author[idx]);
                            }
                        }
                    },
                    success : function( resp, localDoc ) {
                        context.redirect( "#/doc/"+localDoc._id );
                    }
                });
                $("button, input:submit, input:file").button();
            }
        }

        var editItem = function( couchapp, data, context ) {

            var showEditor = function( citationformats, availableBibliographies ) {
                couchapp.db.openDoc( data['docid'], {
                    success : function( doc ) {

                        var type = couchapp.ddoc.types[ doc.type ];
                        doc.fields = [ { id : "citekey", name : couchapp.ddoc.fieldnames[ "citekey" ] } ];

                        var allFields = ["citekey"];
                        allFields = allFields.concat( type.fields );
                        allFields.push( "tags" );
                        allFields.push( "bibliography" );

                        for( var idx in type.fields ) {
                            if( type.fields[idx].indexOf( "note" ) == -1 ) {
                                doc.fields.push( { id : type.fields[idx], name : couchapp.ddoc.fieldnames[ type.fields[idx] ] } );
                            }
                        }
                        doc.fields.push( { id : "tags", name : couchapp.ddoc.fieldnames[ "tags" ] } );
                        doc.regular = true;

                        // add the quote
                        if( citationformats && citationformats.types[doc.type] ) {
                            doc.parsedquote = context.mustache( citationformats.types[doc.type], doc );
                            doc.parsedbibliography = context.mustache( citationformats.bibliography[doc.type], doc );
                        } else {
                            doc.parsedquote = context.mustache( "{{author}}, {{title}}, {{year}}", doc );
                            doc.parsedbibliography = context.mustache( "{{author}}, {{title}}, {{year}}", doc );
                        }

                        // add all the attachments
                        doc.attachments = "";
                        for( var name in doc._attachments ) {
                            var view = doc._attachments[name];
                            view.name = name;
                            view._id = doc._id;
                            view._rev = doc._rev;
                            doc.attachments += context.mustache( couchapp.ddoc.templates.attachment, view );
                            doc.has_attachments = true;
                        }

                        // update the ui
                        $("#content").append( context.mustache( couchapp.ddoc.templates.itemdetails, doc ) );
                        $("#itemDetails").tabs();
                        $("button, input:submit, input:file").button();
                        $("#newBibliography").button( {
                            icons : {
                                primary : "ui-icon-arrowthick-1-n"
                            },
                            text : false
                        });
                        $("#delBibliography").button( {
                            icons : {
                                primary : "ui-icon-trash"
                            },
                            text : false
                        });

                        // bind the form to the document
                        var postForm = couchapp.docForm( "form#item_details", {
                            id : data['docid'],
                            fields : allFields,
                            onLoad : function(doc) {
                                if( doc.tags ) {
                                    doc.tags = doc.tags.join(" ");
                                }
                                if( doc.author ) {
                                    doc.author = doc.author.join(";");
                                }
                            },
                            beforeSave : function(doc) {
                                if(doc.tags) {
                                    doc.tags = $.trim(doc.tags);
                                    doc.tags = doc.tags.split(" ");
                                    for(var idx in doc.tags) {
                                        doc.tags[idx] = $.trim(doc.tags[idx]);
                                    }
                                }
                                if(doc.author) {
                                    doc.author = doc.author.split(";");
                                    for(var idx in doc.author) {
                                        doc.author[idx] = $.trim(doc.author[idx]);
                                    }
                                }
                            },
                        });

                        var addBibIfNotExists = function( newBibliographyName ) {
                            var contains = false;
                            $("#bibliographySelector option").each( function() {
                                if( $(this).val() == newBibliographyName ) contains = true;
                            });
                            if(!contains) {
                                $("#bibliographySelector").append( "<option>"+newBibliographyName+"</option>" );
                            }
                        }

                        // add the newBibliography handling
                        $("#newBibliography").bind( 'click', function() {
                            addBibIfNotExists( $("#newBibliographyName").val() );
                        });

                        $("#delBibliography").bind( 'click', function() {
                            $("#bibliographySelector option:selected").each( function() {
                                $(this).remove();
                            });
                        });

                        // show all availableBibliographies
                        $.each( availableBibliographies, function(index, value) {
                            addBibIfNotExists( value );
                        });
                        var sorted_options = $("#bibliographySelector option");
                        sorted_options.sort( function(a,b) {
                            if(a.text > b.text) return 1;
                            else if(a.text < b.text) return -1;
                            else return 0;
                        });
                        $("#bibliographySelector").empty().append( sorted_options );

                        // activate the delete button
                        $("#deleteDoc").bind( 'click', function() {
                            context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Eintrag wirklich löschen?" } ), {
                                buttons : {
                                    Ok : function() {
                                        couchapp.db.removeDoc( { _id : doc._id, _rev : doc._rev } );
                                        $("#content").empty();
                                        context.redirect( "#/newest" );
                                        $( this ).dialog( "close" );
                                    },
                                    Abbrechen : function () {
                                        $( this ).dialog( "close" );
                                    }
                                }
                            });
                        });

                        // add the attachment uploading
                        $("form#upload_attachment").submit( function(e) {
                            e.preventDefault();

                            var data = {};
                            $.each($("form#upload_attachment :input").serializeArray(), function(i, field) {
                                data[field.name] = field.value;
                            });
                            $("form#upload_attachment :file").each(function() {
                                data[this.name] = this.value; // file inputs need special handling
                            });

                            if (!data._attachments || data._attachments.length == 0) {
                                context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog,
                                    { message : "Bitte eine Datei zum Speichen auswählen!" } ));
                                return;
                            }

                            var docUrl = [couchapp.db.uri, data._id].join('/');
                            $(this).ajaxSubmit({
                                url: docUrl,
                                success: function(resp) {
                                    context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Anhang hinzugefügt!" } ) );
                                    context.trigger( "show-item-details", { docid:data._id } );
                                }
                            });
                        });

                        // add the attachment deletion
                        $(".deleteattachments").click( function() {
                            var url = $(this).attr('name');
                            context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Eintrag wirklich löschen?" } ), {
                                buttons : {
                                    Ok : function() {
                                        $( this ).dialog( "close" );
                                        $.ajax( {
                                            type : "DELETE",
                                            url : url,
                                            success: function() {
                                                context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Wurde gelöscht" } ) );
                                                context.trigger( "show-item-details", { docid:data['docid'] } );
                                            }
                                        });
                                    },
                                    Abbrechen : function () {
                                        $( this ).dialog( "close" );
                                    }
                                }
                            });
                        });

                        // add the nice editor for notes
                        $("#nice_editor").markItUp(myMarkdownSettings);

                    }

                });
            }

            var prepareEditor = function( citationformats ) {

                // add all available bibliographies
                couchapp.design.view( "bibliography", {
                    group : true,
                    success : function(resp) {
                        var availableBibliographies = [];
                        for( var row in resp.rows ) {
                            availableBibliographies.push( resp.rows[ row ].key );
                        }

                        showEditor( citationformats, availableBibliographies );
                    }
                });

            }

            couchapp.db.openDoc( "citationformats", {
                success : function( citationformats ) {
                    prepareEditor( citationformats );
                },
                error : function() {
                }
            });

        }

        /*
         * show the input for a new entry
         */
        this.bind( 'new-item', function(e, data) {
            $("#content").empty();
            var self = this;
            this.withCouchApp( function(app) {
                createNewItem( app, data, self );
            });
        });

        /*
         * Show the item details
         */
        this.bind( 'show-item-details', function(e, data) {
            $("#content").empty();
            var self = this;
            this.withCouchApp( function( app ) {
                editItem( app, data, self );
            });

        });

    }

})(jQuery);
<commit_msg>404 error when there is no citationformats document<commit_after>(function($) {

    Sammy = Sammy || {};

    Sammy.CouchBibItemAdmin = function( app ) {

        var createNewItem = function( couchapp, data, context ) {

            if( !couchapp.ddoc.types[ data['doctype'] ] ) {

                context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Unbekannter Typ!" } ) );

            } else {

                var type = couchapp.ddoc.types[ data['doctype'] ];
                var doc = {};
                doc.fields = [ { id : "citekey", name : couchapp.ddoc.fieldnames[ "citekey" ] } ];

                for( var idx in type.fields ) {
                    if( type.fields[idx].indexOf( "note" ) == -1 ) {
                        doc.fields.push( { id : type.fields[idx], name : couchapp.ddoc.fieldnames[ type.fields[idx] ] } );
                    }
                }
                doc.fields.push( { id : "tags", name : couchapp.ddoc.fieldnames[ "tags" ] } );

                var allFields = ["citekey"];
                allFields = allFields.concat( type.fields );
                allFields.push( "tags" );

                $("#content").append( context.mustache( couchapp.ddoc.templates.itemdetails, doc ) );
                $("#itemDetails").tabs();

                var postForm = couchapp.docForm( "form#item_details", {
                    fields : allFields,
                    template : { type : data['doctype'] },
                    onLoad : function(doc) {
                        if( doc.tags ) {
                            doc.tags = doc.tags.join(" ");
                        }
                        if( doc.author ) {
                            doc.author = doc.author.join(";");
                        }
                    },
                    beforeSave : function(doc) {
                        if(!doc.created_at) {
                            doc.created_at = new Date();
                        }
                        if(!doc._id) {
                            doc._id = doc.citekey;
                        }
                        if(doc.tags) {
                            doc.tags = $.trim(doc.tags);
                            doc.tags = doc.tags.split(" ");
                            for(var idx in doc.tags) {
                                doc.tags[idx] = $.trim(doc.tags[idx]);
                            }
                        }
                        if(doc.author) {
                            doc.author = doc.author.split(";");
                            for(var idx in doc.author) {
                                doc.author[idx] = $.trim(doc.author[idx]);
                            }
                        }
                    },
                    success : function( resp, localDoc ) {
                        context.redirect( "#/doc/"+localDoc._id );
                    }
                });
                $("button, input:submit, input:file").button();
            }
        }

        var editItem = function( couchapp, data, context ) {

            var showEditor = function( citationformats, availableBibliographies ) {
                couchapp.db.openDoc( data['docid'], {
                    success : function( doc ) {

                        var type = couchapp.ddoc.types[ doc.type ];
                        doc.fields = [ { id : "citekey", name : couchapp.ddoc.fieldnames[ "citekey" ] } ];

                        var allFields = ["citekey"];
                        allFields = allFields.concat( type.fields );
                        allFields.push( "tags" );
                        allFields.push( "bibliography" );

                        for( var idx in type.fields ) {
                            if( type.fields[idx].indexOf( "note" ) == -1 ) {
                                doc.fields.push( { id : type.fields[idx], name : couchapp.ddoc.fieldnames[ type.fields[idx] ] } );
                            }
                        }
                        doc.fields.push( { id : "tags", name : couchapp.ddoc.fieldnames[ "tags" ] } );
                        doc.regular = true;

                        // add the quote
                        if( citationformats && citationformats.types[doc.type] ) {
                            doc.parsedquote = context.mustache( citationformats.types[doc.type], doc );
                            doc.parsedbibliography = context.mustache( citationformats.bibliography[doc.type], doc );
                        } else {
                            doc.parsedquote = context.mustache( "{{author}}, {{title}}, {{year}}", doc );
                            doc.parsedbibliography = context.mustache( "{{author}}, {{title}}, {{year}}", doc );
                        }

                        // add all the attachments
                        doc.attachments = "";
                        for( var name in doc._attachments ) {
                            var view = doc._attachments[name];
                            view.name = name;
                            view._id = doc._id;
                            view._rev = doc._rev;
                            doc.attachments += context.mustache( couchapp.ddoc.templates.attachment, view );
                            doc.has_attachments = true;
                        }

                        // update the ui
                        $("#content").append( context.mustache( couchapp.ddoc.templates.itemdetails, doc ) );
                        $("#itemDetails").tabs();
                        $("button, input:submit, input:file").button();
                        $("#newBibliography").button( {
                            icons : {
                                primary : "ui-icon-arrowthick-1-n"
                            },
                            text : false
                        });
                        $("#delBibliography").button( {
                            icons : {
                                primary : "ui-icon-trash"
                            },
                            text : false
                        });

                        // bind the form to the document
                        var postForm = couchapp.docForm( "form#item_details", {
                            id : data['docid'],
                            fields : allFields,
                            onLoad : function(doc) {
                                if( doc.tags ) {
                                    doc.tags = doc.tags.join(" ");
                                }
                                if( doc.author ) {
                                    doc.author = doc.author.join(";");
                                }
                            },
                            beforeSave : function(doc) {
                                if(doc.tags) {
                                    doc.tags = $.trim(doc.tags);
                                    doc.tags = doc.tags.split(" ");
                                    for(var idx in doc.tags) {
                                        doc.tags[idx] = $.trim(doc.tags[idx]);
                                    }
                                }
                                if(doc.author) {
                                    doc.author = doc.author.split(";");
                                    for(var idx in doc.author) {
                                        doc.author[idx] = $.trim(doc.author[idx]);
                                    }
                                }
                            },
                        });

                        var addBibIfNotExists = function( newBibliographyName ) {
                            var contains = false;
                            $("#bibliographySelector option").each( function() {
                                if( $(this).val() == newBibliographyName ) contains = true;
                            });
                            if(!contains) {
                                $("#bibliographySelector").append( "<option>"+newBibliographyName+"</option>" );
                            }
                        }

                        // add the newBibliography handling
                        $("#newBibliography").bind( 'click', function() {
                            addBibIfNotExists( $("#newBibliographyName").val() );
                        });

                        $("#delBibliography").bind( 'click', function() {
                            $("#bibliographySelector option:selected").each( function() {
                                $(this).remove();
                            });
                        });

                        // show all availableBibliographies
                        $.each( availableBibliographies, function(index, value) {
                            addBibIfNotExists( value );
                        });
                        var sorted_options = $("#bibliographySelector option");
                        sorted_options.sort( function(a,b) {
                            if(a.text > b.text) return 1;
                            else if(a.text < b.text) return -1;
                            else return 0;
                        });
                        $("#bibliographySelector").empty().append( sorted_options );

                        // activate the delete button
                        $("#deleteDoc").bind( 'click', function() {
                            context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Eintrag wirklich löschen?" } ), {
                                buttons : {
                                    Ok : function() {
                                        couchapp.db.removeDoc( { _id : doc._id, _rev : doc._rev } );
                                        $("#content").empty();
                                        context.redirect( "#/newest" );
                                        $( this ).dialog( "close" );
                                    },
                                    Abbrechen : function () {
                                        $( this ).dialog( "close" );
                                    }
                                }
                            });
                        });

                        // add the attachment uploading
                        $("form#upload_attachment").submit( function(e) {
                            e.preventDefault();

                            var data = {};
                            $.each($("form#upload_attachment :input").serializeArray(), function(i, field) {
                                data[field.name] = field.value;
                            });
                            $("form#upload_attachment :file").each(function() {
                                data[this.name] = this.value; // file inputs need special handling
                            });

                            if (!data._attachments || data._attachments.length == 0) {
                                context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog,
                                    { message : "Bitte eine Datei zum Speichen auswählen!" } ));
                                return;
                            }

                            var docUrl = [couchapp.db.uri, data._id].join('/');
                            $(this).ajaxSubmit({
                                url: docUrl,
                                success: function(resp) {
                                    context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Anhang hinzugefügt!" } ) );
                                    context.trigger( "show-item-details", { docid:data._id } );
                                }
                            });
                        });

                        // add the attachment deletion
                        $(".deleteattachments").click( function() {
                            var url = $(this).attr('name');
                            context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Eintrag wirklich löschen?" } ), {
                                buttons : {
                                    Ok : function() {
                                        $( this ).dialog( "close" );
                                        $.ajax( {
                                            type : "DELETE",
                                            url : url,
                                            success: function() {
                                                context.alertDialog( context.mustache( couchapp.ddoc.templates.messagedialog, { message : "Wurde gelöscht" } ) );
                                                context.trigger( "show-item-details", { docid:data['docid'] } );
                                            }
                                        });
                                    },
                                    Abbrechen : function () {
                                        $( this ).dialog( "close" );
                                    }
                                }
                            });
                        });

                        // add the nice editor for notes
                        $("#nice_editor").markItUp(myMarkdownSettings);

                    }

                });
            }

            var prepareEditor = function( citationformats ) {

                // add all available bibliographies
                couchapp.design.view( "bibliography", {
                    group : true,
                    success : function(resp) {
                        var availableBibliographies = [];
                        for( var row in resp.rows ) {
                            availableBibliographies.push( resp.rows[ row ].key );
                        }

                        showEditor( citationformats, availableBibliographies );
                    }
                });

            }

            couchapp.db.openDoc( "citationformats", {
                success : function( citationformats ) {
                    prepareEditor( citationformats );
                },
                error : function() {
                    prepareEditor();
                }
            });

        }

        /*
         * show the input for a new entry
         */
        this.bind( 'new-item', function(e, data) {
            $("#content").empty();
            var self = this;
            this.withCouchApp( function(app) {
                createNewItem( app, data, self );
            });
        });

        /*
         * Show the item details
         */
        this.bind( 'show-item-details', function(e, data) {
            $("#content").empty();
            var self = this;
            this.withCouchApp( function( app ) {
                editItem( app, data, self );
            });

        });

    }

})(jQuery);
<|endoftext|>


<commit_before>var populationSurroundings = require('./populationSurroundings');
var geographicalSurroundings = require('./geographicalSurroundings');
var parallel = require('async/parallel');
var jsonHelper = require('./jsonHelper');
var positionsHelper = require('./positionsHelper');
var logError = require('./errorLogger').logError;

function getSurroundings(req, res) {

    positionsHelper.choosePositions(req.body, res, function (positions) {

        //error occurred, but already handled
        if(!positions) {
            return;
        }

        calculateSurroundings(positions, req.body, res);
    });
}

function calculateSurroundings(positions, body, res) {

    parallel([
            function(callback) {
                geographicalSurroundings.getGeographicalSurroundings(positions, function (error, result) {
                    callback(error, result);
                });
            },
            function(callback) {
                populationSurroundings.getGeoAdminData(positions, function (error, result) {
                    callback(error, result);
                })
            }
        ],
        function(err, results) {

            if(err) {
                res.status(500).json({ error: 'Internal Server Error' });
                logError(500, 'Internal Server Error', err, 'parallel', 'surroundingsCommunication', body);
                return;
            }

            /*Parameters: geographicalSurroundings-result, geoAdmin-result */
            var response = jsonHelper.renderSurroundingsJson(results[0], results[1]);
            res.status(200).json(response);
        }
    );
}

module.exports = {
    "getSurroundings": getSurroundings
};<commit_msg>Codedokumentation surroundingsCommunication<commit_after>/**
 * This module chooses the best positions with help of the positionsHelper, passes them on to geographicalSurroundings and
 * populationSurroundings and prepares the answer of those delegations with help of the jsonHelper for the answer to the client.
 * @module business_logic/surroundingsCommunication
 */

var populationSurroundings = require('./populationSurroundings');
var geographicalSurroundings = require('./geographicalSurroundings');
var parallel = require('async/parallel');
var jsonHelper = require('./jsonHelper');
var positionsHelper = require('./positionsHelper');
var logError = require('./errorLogger').logError;

/**
 * Function which filters the best positions and returns the result of the surroundings calculation.
 *
 * @param {object} req - client request
 * @param {object} res - response which will be sent to the client
 */
function getSurroundings(req, res) {

    positionsHelper.choosePositions(req.body, res, function (positions) {

        //error occurred, but already handled
        if(!positions) {
            return;
        }

        calculateSurroundings(positions, req.body, res);
    });
}

/**
 * Function which starts the calculation of the geographical surroundings as well as the population density and the community type.
 *
 * @param {Array} positions - the array is expected to have the best three positions in it, positions should be the result of choosePositions from positionsHelper
 * @see {business_logic/positionsHelper}
 * @param {object} body - part of the request, will only be used in case of an error, so that the body which triggers the error can be logged
 * @param {object} res - response object, will be used to send an error if something went wrong otherwise the result of the
 * geographical surroundings calculation is returned.
 */
function calculateSurroundings(positions, body, res) {

    parallel([
            function(callback) {
                geographicalSurroundings.getGeographicalSurroundings(positions, function (error, result) {
                    callback(error, result);
                });
            },
            function(callback) {
                populationSurroundings.getGeoAdminData(positions, function (error, result) {
                    callback(error, result);
                })
            }
        ],
        function(err, results) {

            if(err) {
                res.status(500).json({ error: 'Internal Server Error' });
                logError(500, 'Internal Server Error', err, 'parallel', 'surroundingsCommunication', body);
                return;
            }

            /*Parameters: geographicalSurroundings-result, geoAdmin-result */
            var response = jsonHelper.renderSurroundingsJson(results[0], results[1]);
            res.status(200).json(response);
        }
    );
}

module.exports = {
    "getSurroundings": getSurroundings
};<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {
  /////////////////////////////////////////////////////////////////////////////
  // OptionsPage class:

  /**
   * Base class for options page.
   * @constructor
   * @param {string} name Options page name, also defines id of the div element
   *     containing the options view and the name of options page navigation bar
   *     item as name+'PageNav'.
   * @param {string} title Options page title, used for navigation bar
   * @extends {EventTarget}
   */
  function OptionsPage(name, title, pageDivName) {
    this.name = name;
    this.title = title;
    this.pageDivName = pageDivName;
    this.pageDiv = $(this.pageDivName);
    this.tab = null;
    this.managed = false;
  }

  OptionsPage.registeredPages_ = {};

  /**
   * Pages which are nested under a main page.
   */
  OptionsPage.registeredSubPages_ = {};

  /**
   * Pages which are meant to behave like modal dialogs.
   */
  OptionsPage.registeredOverlayPages_ = {};

  /**
   * Shows a registered page. This handles both top-level pages and sub-pages.
   * @param {string} pageName Page name.
   */
  OptionsPage.showPageByName = function(pageName) {
    for (var name in OptionsPage.registeredPages_) {
      var page = OptionsPage.registeredPages_[name];
      page.visible = name == pageName;
    }
    for (var name in OptionsPage.registeredSubPages_) {
      var pageInfo = OptionsPage.registeredSubPages_[name];
      var match = name == pageName;
      if (match)
        pageInfo.parentPage.visible = true;
      pageInfo.page.visible = match;
    }
  };

  /**
   * Called on load. Dispatch the URL hash to the given page's handleHash
   * function.
   * @param {string} pageName The string name of the (registered) options page.
   * @param {string} hash The value of the hash component of the URL.
   */
  OptionsPage.handleHashForPage = function(pageName, hash) {
    var page = OptionsPage.registeredPages_[pageName];
    if (!page) {
      page = OptionsPage.registeredSubPages_[pageName].page;
    }
    page.handleHash(hash);
  };

  /**
   * Shows a registered Overlay page.
   * @param {string} overlayName Page name.
   */
  OptionsPage.showOverlay = function(overlayName) {
    if (OptionsPage.registeredOverlayPages_[overlayName]) {
      OptionsPage.registeredOverlayPages_[overlayName].visible = true;
    }
  };

  /**
   * Clears overlays (i.e. hide all overlays).
   */
  OptionsPage.clearOverlays = function() {
     for (var name in OptionsPage.registeredOverlayPages_) {
       var page = OptionsPage.registeredOverlayPages_[name];
       page.visible = false;
     }
  };

  /**
   * Clears overlays if the key event is ESC.
   * @param {Event} e Key event.
   * @private
   */
  OptionsPage.clearOverlaysOnEsc_ = function(e) {
    if (e.keyCode == 27) { // Esc
      OptionsPage.clearOverlays();
    }
  };

  /**
   * Closes any currently-open subpage.
   */
  OptionsPage.closeSubPage = function() {
    for (var name in OptionsPage.registeredSubPages_) {
      var pageInfo = OptionsPage.registeredSubPages_[name];
      if (pageInfo.page.visible) {
        pageInfo.page.visible = false;
        // Since the managed pref banner lives outside the overlay, and the
        // parent is not changing visibility, update the banner explicitly.
        var banner = $('managed-prefs-banner');
        banner.style.display = pageInfo.parentPage.managed ? 'block' : 'none';
      }
    }
  };

  /**
  * Shows the tab contents for the given navigation tab.
  * @param {!Element} tab The tab that the user clicked.
  */
  OptionsPage.showTab = function(tab) {
    // Search parents until we find a tab, or the nav bar itself. This allows
    // tabs to have child nodes, e.g. labels in separately-styled spans.
    while (tab && !tab.classList.contains('subpages-nav-tabs') &&
           !tab.classList.contains('inactive-tab')) {
      tab = tab.parentNode;
    }
    if (!tab || !tab.classList.contains('inactive-tab'))
      return;

    if (this.activeNavTab != null) {
      this.activeNavTab.classList.remove('active-tab');
      $(this.activeNavTab.getAttribute('tab-contents')).classList.
          remove('active-tab-contents');
    }

    tab.classList.add('active-tab');
    $(tab.getAttribute('tab-contents')).classList.add('active-tab-contents');
    this.activeNavTab = tab;
  }

  /**
   * Registers new options page.
   * @param {OptionsPage} page Page to register.
   */
  OptionsPage.register = function(page) {
    OptionsPage.registeredPages_[page.name] = page;
    // Create and add new page <li> element to navbar.
    var pageNav = document.createElement('li');
    pageNav.id = page.name + 'PageNav';
    pageNav.className = 'navbar-item';
    pageNav.setAttribute('pageName', page.name);
    pageNav.textContent = page.title;
    pageNav.tabIndex = 0;
    pageNav.onclick = function(event) {
      OptionsPage.showPageByName(this.getAttribute('pageName'));
    };
    pageNav.onkeypress = function(event) {
      // Enter or space
      if (event.keyCode == 13 || event.keyCode == 32) {
        OptionsPage.showPageByName(this.getAttribute('pageName'));
      }
    };
    var navbar = $('navbar');
    navbar.appendChild(pageNav);
    page.tab = pageNav;
    page.initializePage();
  };

  /**
   * Registers a new Sub tab page.
   * @param {OptionsPage} page Page to register.
   */
  OptionsPage.registerSubPage = function(subPage, parentPage) {
    OptionsPage.registeredSubPages_[subPage.name] = {
        page: subPage, parentPage: parentPage };
    subPage.tab = undefined;
    subPage.isSubPageSheet = true;
    subPage.initializePage();
  };

  /**
   * Registers a new Overlay page.
   * @param {OptionsPage} page Page to register, must be a class derived from
   * OptionsPage.
   */
  OptionsPage.registerOverlay = function(page) {
    OptionsPage.registeredOverlayPages_[page.name] = page;
    page.tab = undefined;
    page.isOverlay = true;
    page.initializePage();
  };

  /**
   * Callback for window.onpopstate.
   * @param {Object} data State data pushed into history.
   */
  OptionsPage.setState = function(data) {
    if (data && data.pageName) {
      OptionsPage.showPageByName(data.pageName);
    }
  };

  /**
   * Initializes the complete options page.  This will cause
   * all C++ handlers to be invoked to do final setup.
   */
  OptionsPage.initialize = function() {
    chrome.send('coreOptionsInitialize');

    // Set up the overlay sheet. Clicks on the visible part of the parent page
    // should close the overlay, not fall through to the parent page.
    $('subpage-sheet-container').onclick = function(event) {
      if (!$('subpage-sheet').contains(event.target))
        OptionsPage.closeSubPage();
      event.stopPropagation();
    }
  };

  OptionsPage.prototype = {
    __proto__: cr.EventTarget.prototype,

    /**
     * Initializes page content.
     */
    initializePage: function() {},

    /**
     * Sets managed banner visibility state.
     */
    setManagedBannerVisibility: function(visible) {
      this.managed = visible;
      if (this.visible) {
        $('managed-prefs-banner').style.display = visible ? 'block' : 'none';
      }
    },

    /**
     * Gets page visibility state.
     */
    get visible() {
      var page = $(this.pageDivName);
      return page && page.ownerDocument.defaultView.getComputedStyle(
          page).display == 'block';
    },

    /**
     * Sets page visibility.
     */
    set visible(visible) {
      if ((this.visible && visible) || (!this.visible && !visible))
        return;

      if (visible) {
        this.pageDiv.style.display = 'block';
        if (this.isOverlay) {
          var overlay = $('overlay');
          overlay.classList.remove('hidden');
          document.addEventListener('keydown',
                                    OptionsPage.clearOverlaysOnEsc_);
        } else {
          if (this.isSubPageSheet)
            $('subpage-sheet-container').classList.remove('hidden');

          var banner = $('managed-prefs-banner');
          banner.style.display = this.managed ? 'block' : 'none';

          // Recent webkit change no longer allows url change from "chrome://".
          window.history.pushState({pageName: this.name},
                                   this.title);
        }
        if (this.tab) {
          this.tab.classList.add('navbar-item-selected');
        }
      } else {
        if (this.isOverlay) {
          var overlay = $('overlay');
          overlay.classList.add('hidden');
          document.removeEventListener('keydown',
                                       OptionsPage.clearOverlaysOnEsc_);
        } else if (this.isSubPageSheet) {
          $('subpage-sheet-container').classList.add('hidden');
        }
        this.pageDiv.style.display = 'none';
        if (this.tab) {
          this.tab.classList.remove('navbar-item-selected');
        }
      }

      cr.dispatchPropertyChange(this, 'visible', visible, !visible);
    },

    /**
     * Handles a hash value in the URL (such as bar in
     * chrome://options/foo#bar). Called on page load. By default, this shows
     * an overlay that matches the hash name, but can be overriden by individual
     * OptionsPage subclasses to get other behavior.
     * @param {string} hash The hash value.
     */
    handleHash: function(hash) {
      OptionsPage.showOverlay(hash);
    },
  };

  // Export
  return {
    OptionsPage: OptionsPage
  };

});
<commit_msg>dom-ui settings: prefer to add/remove class 'hidden' rather than manipulate the style.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('options', function() {
  /////////////////////////////////////////////////////////////////////////////
  // OptionsPage class:

  /**
   * Base class for options page.
   * @constructor
   * @param {string} name Options page name, also defines id of the div element
   *     containing the options view and the name of options page navigation bar
   *     item as name+'PageNav'.
   * @param {string} title Options page title, used for navigation bar
   * @extends {EventTarget}
   */
  function OptionsPage(name, title, pageDivName) {
    this.name = name;
    this.title = title;
    this.pageDivName = pageDivName;
    this.pageDiv = $(this.pageDivName);
    this.tab = null;
    this.managed = false;
  }

  OptionsPage.registeredPages_ = {};

  /**
   * Pages which are nested under a main page.
   */
  OptionsPage.registeredSubPages_ = {};

  /**
   * Pages which are meant to behave like modal dialogs.
   */
  OptionsPage.registeredOverlayPages_ = {};

  /**
   * Shows a registered page. This handles both top-level pages and sub-pages.
   * @param {string} pageName Page name.
   */
  OptionsPage.showPageByName = function(pageName) {
    for (var name in OptionsPage.registeredPages_) {
      var page = OptionsPage.registeredPages_[name];
      page.visible = name == pageName;
    }
    for (var name in OptionsPage.registeredSubPages_) {
      var pageInfo = OptionsPage.registeredSubPages_[name];
      var match = name == pageName;
      if (match)
        pageInfo.parentPage.visible = true;
      pageInfo.page.visible = match;
    }
  };

  /**
   * Called on load. Dispatch the URL hash to the given page's handleHash
   * function.
   * @param {string} pageName The string name of the (registered) options page.
   * @param {string} hash The value of the hash component of the URL.
   */
  OptionsPage.handleHashForPage = function(pageName, hash) {
    var page = OptionsPage.registeredPages_[pageName];
    if (!page) {
      page = OptionsPage.registeredSubPages_[pageName].page;
    }
    page.handleHash(hash);
  };

  /**
   * Shows a registered Overlay page.
   * @param {string} overlayName Page name.
   */
  OptionsPage.showOverlay = function(overlayName) {
    if (OptionsPage.registeredOverlayPages_[overlayName]) {
      OptionsPage.registeredOverlayPages_[overlayName].visible = true;
    }
  };

  /**
   * Clears overlays (i.e. hide all overlays).
   */
  OptionsPage.clearOverlays = function() {
     for (var name in OptionsPage.registeredOverlayPages_) {
       var page = OptionsPage.registeredOverlayPages_[name];
       page.visible = false;
     }
  };

  /**
   * Clears overlays if the key event is ESC.
   * @param {Event} e Key event.
   * @private
   */
  OptionsPage.clearOverlaysOnEsc_ = function(e) {
    if (e.keyCode == 27) { // Esc
      OptionsPage.clearOverlays();
    }
  };

  /**
   * Closes any currently-open subpage.
   */
  OptionsPage.closeSubPage = function() {
    for (var name in OptionsPage.registeredSubPages_) {
      var pageInfo = OptionsPage.registeredSubPages_[name];
      if (pageInfo.page.visible) {
        pageInfo.page.visible = false;
        // Since the managed pref banner lives outside the overlay, and the
        // parent is not changing visibility, update the banner explicitly.
        pageInfo.parentPage.updateManagedBannerVisibility();
      }
    }
  };

  /**
  * Shows the tab contents for the given navigation tab.
  * @param {!Element} tab The tab that the user clicked.
  */
  OptionsPage.showTab = function(tab) {
    // Search parents until we find a tab, or the nav bar itself. This allows
    // tabs to have child nodes, e.g. labels in separately-styled spans.
    while (tab && !tab.classList.contains('subpages-nav-tabs') &&
           !tab.classList.contains('inactive-tab')) {
      tab = tab.parentNode;
    }
    if (!tab || !tab.classList.contains('inactive-tab'))
      return;

    if (this.activeNavTab != null) {
      this.activeNavTab.classList.remove('active-tab');
      $(this.activeNavTab.getAttribute('tab-contents')).classList.
          remove('active-tab-contents');
    }

    tab.classList.add('active-tab');
    $(tab.getAttribute('tab-contents')).classList.add('active-tab-contents');
    this.activeNavTab = tab;
  };

  /**
   * Registers new options page.
   * @param {OptionsPage} page Page to register.
   */
  OptionsPage.register = function(page) {
    OptionsPage.registeredPages_[page.name] = page;
    // Create and add new page <li> element to navbar.
    var pageNav = document.createElement('li');
    pageNav.id = page.name + 'PageNav';
    pageNav.className = 'navbar-item';
    pageNav.setAttribute('pageName', page.name);
    pageNav.textContent = page.title;
    pageNav.tabIndex = 0;
    pageNav.onclick = function(event) {
      OptionsPage.showPageByName(this.getAttribute('pageName'));
    };
    pageNav.onkeypress = function(event) {
      // Enter or space
      if (event.keyCode == 13 || event.keyCode == 32) {
        OptionsPage.showPageByName(this.getAttribute('pageName'));
      }
    };
    var navbar = $('navbar');
    navbar.appendChild(pageNav);
    page.tab = pageNav;
    page.initializePage();
  };

  /**
   * Registers a new Sub tab page.
   * @param {OptionsPage} page Page to register.
   */
  OptionsPage.registerSubPage = function(subPage, parentPage) {
    OptionsPage.registeredSubPages_[subPage.name] = {
        page: subPage, parentPage: parentPage };
    subPage.tab = undefined;
    subPage.isSubPageSheet = true;
    subPage.initializePage();
  };

  /**
   * Registers a new Overlay page.
   * @param {OptionsPage} page Page to register, must be a class derived from
   * OptionsPage.
   */
  OptionsPage.registerOverlay = function(page) {
    OptionsPage.registeredOverlayPages_[page.name] = page;
    page.tab = undefined;
    page.isOverlay = true;
    page.initializePage();
  };

  /**
   * Callback for window.onpopstate.
   * @param {Object} data State data pushed into history.
   */
  OptionsPage.setState = function(data) {
    if (data && data.pageName) {
      OptionsPage.showPageByName(data.pageName);
    }
  };

  /**
   * Initializes the complete options page.  This will cause
   * all C++ handlers to be invoked to do final setup.
   */
  OptionsPage.initialize = function() {
    chrome.send('coreOptionsInitialize');

    // Set up the overlay sheet. Clicks on the visible part of the parent page
    // should close the overlay, not fall through to the parent page.
    $('subpage-sheet-container').onclick = function(event) {
      if (!$('subpage-sheet').contains(event.target))
        OptionsPage.closeSubPage();
      event.stopPropagation();
    }
  };

  OptionsPage.prototype = {
    __proto__: cr.EventTarget.prototype,

    /**
     * Initializes page content.
     */
    initializePage: function() {},

    /**
     * Sets managed banner visibility state.
     */
    setManagedBannerVisibility: function(visible) {
      this.managed = visible;
      if (this.visible) {
        this.updateManagedBannerVisibility();
      }
    },

    /**
     * Updates managed banner visibility state.
     */
    updateManagedBannerVisibility: function() {
      if (this.managed) {
        $('managed-prefs-banner').classList.remove('hidden');
      } else {
        $('managed-prefs-banner').classList.add('hidden');
      }
    },

    /**
     * Gets page visibility state.
     */
    get visible() {
      var page = $(this.pageDivName);
      return page && page.ownerDocument.defaultView.getComputedStyle(
          page).display == 'block';
    },

    /**
     * Sets page visibility.
     */
    set visible(visible) {
      if ((this.visible && visible) || (!this.visible && !visible))
        return;

      if (visible) {
        this.pageDiv.classList.remove('hidden');
        if (this.isOverlay) {
          $('overlay').classList.remove('hidden');
          document.addEventListener('keydown',
                                    OptionsPage.clearOverlaysOnEsc_);
        } else {
          if (this.isSubPageSheet)
            $('subpage-sheet-container').classList.remove('hidden');

          this.updateManagedBannerVisibility();

          // Recent webkit change no longer allows url change from "chrome://".
          window.history.pushState({pageName: this.name}, this.title);
        }
        if (this.tab) {
          this.tab.classList.add('navbar-item-selected');
        }
      } else {
        this.pageDiv.classList.add('hidden');
        if (this.isOverlay) {
          $('overlay').classList.add('hidden');
          document.removeEventListener('keydown',
                                       OptionsPage.clearOverlaysOnEsc_);
        } else if (this.isSubPageSheet) {
          $('subpage-sheet-container').classList.add('hidden');
        }
        if (this.tab) {
          this.tab.classList.remove('navbar-item-selected');
        }
      }

      cr.dispatchPropertyChange(this, 'visible', visible, !visible);
    },

    /**
     * Handles a hash value in the URL (such as bar in
     * chrome://options/foo#bar). Called on page load. By default, this shows
     * an overlay that matches the hash name, but can be overriden by individual
     * OptionsPage subclasses to get other behavior.
     * @param {string} hash The hash value.
     */
    handleHash: function(hash) {
      OptionsPage.showOverlay(hash);
    },
  };

  // Export
  return {
    OptionsPage: OptionsPage
  };

});
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');

if (global.ethers) {
    console.log('Using global ethers; ' + __filename);
    var ethers = global.ethers;
} else {
    var ethers = require('..');
}

var provider = new ethers.providers.InfuraProvider('rinkeby');

var contract = (function() {
    var data = require('./test-contract.json');
    return new ethers.Contract(data.contractAddress, data.interface, provider);
})();

function equals(name, actual, expected) {
    if (Array.isArray(expected)) {
        assert.equal(actual.length, expected.length, 'array length mismatch - '  + name);
        expected.forEach(function(expected, index) {
            equals(name + ':' + index, actual[index], expected);
        });
        return;
    }

    if (typeof(actual) === 'object') {
        if (expected.indexed) {
            assert.ok(!!actual.indexed, 'index property has index - ' + name);
            if (expected.hash) {
                assert.equal(actual.hash, expected.hash, 'index property with known hash matches - ' + name);
            }
            return;
        }

        if (actual.eq) {
            assert.ok(actual.eq(expected), 'numeric value matches - ' + name);
        }
    }

    assert.equal(actual, expected, 'value matches - ' + name);
}

function TestContractEvents() {
    return ethers.providers.Provider.fetchJSON('https://api.ethers.io/api/v1/?action=triggerTest&address=' + contract.address).then(function(data) {
        console.log('  Triggered Transaction Hash: ' + data.hash);

        function waitForEvent(eventName, expected) {
            return new Promise(function(resolve, reject) {
                contract['on' + eventName.toLowerCase()] = function() {
                    //console.dir(this, { depth: null });
                    //console.log(this.event);
                    this.removeListener();
                    equals(this.event, Array.prototype.slice.call(arguments), expected);
                    resolve();
                };
            });
        }

        return new Promise(function(resolve, reject) {
            var p0 = '0x06B5955A67D827CDF91823E3bB8F069e6c89c1D6';
            var p0_1 = '0x06b5955A67d827CdF91823e3Bb8F069e6C89C1d7';
            var p1 = 0x42;
            var p1_1 = 0x43;

            return Promise.all([
                waitForEvent('Test', [ p0, p1 ]),
                waitForEvent('TestP0', [ p0, p1 ]),
                waitForEvent('TestP0P1', [ p0, p1 ]),
                waitForEvent('TestIndexedString', [ { indexed: true, hash: '0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331' }, p1 ]),
                waitForEvent('TestV2', [ { indexed: true }, [ p0, p1 ] ]),
                waitForEvent('TestV2Nested', [ { indexed: true }, [ p0_1, p1_1, [ p0, p1 ] ] ]),
            ]).then(function(result) {
                resolve();
            });
        });
    });
}

describe('Test Contract Objects', function() {

    it('parses events', function() {
        this.timeout(120000);
        return TestContractEvents();
    });

    it('ABIv2 parameters and return types work', function() {
        var p0 = '0x06B5955A67D827CDF91823E3bB8F069e6c89c1D6';
        var p0_0f = '0x06B5955a67d827cDF91823e3bB8F069E6c89c1e5';
        var p0_f0 = '0x06b5955a67D827CDF91823e3Bb8F069E6C89c2C6';
        var p1 = 0x42;
        var p1_0f = 0x42 + 0x0f;
        var p1_f0 = 0x42 + 0xf0;

        var posStruct = [p0, p1, [ p0, p1 ] ];
        var expectedPosStruct = [ p0_f0, p1_f0, [ p0_0f, p1_0f ] ];
        return contract.testV2(posStruct).then(function(result) {
            equals('position input', result, expectedPosStruct);
        });
    });

    it('collapses single argument solidity methods', function() {
        return contract.testSingleResult(4).then(function(result) {
            assert.equal(result, 5, 'single value returned');
        });
    });

    it('does not collapses multi argument solidity methods', function() {
        return contract.testMultiResult(6).then(function(result) {
            assert.equal(result[0], 7, 'multi value [0] returned');
            assert.equal(result[1], 8, 'multi value [1] returned');
            assert.equal(result.r0, 7, 'multi value [r0] returned');
            assert.equal(result.r1, 8, 'multi value [r1] returned');
        });
    });
});
<commit_msg>Added positional and keyword argument test cases for ABIv2.<commit_after>'use strict';

var assert = require('assert');

if (global.ethers) {
    console.log('Using global ethers; ' + __filename);
    var ethers = global.ethers;
} else {
    var ethers = require('..');
}

var provider = new ethers.providers.InfuraProvider('rinkeby');

var contract = (function() {
    var data = require('./test-contract.json');
    return new ethers.Contract(data.contractAddress, data.interface, provider);
})();

function equals(name, actual, expected) {
    if (Array.isArray(expected)) {
        assert.equal(actual.length, expected.length, 'array length mismatch - '  + name);
        expected.forEach(function(expected, index) {
            equals(name + ':' + index, actual[index], expected);
        });
        return;
    }

    if (typeof(actual) === 'object') {
        if (expected.indexed) {
            assert.ok(!!actual.indexed, 'index property has index - ' + name);
            if (expected.hash) {
                assert.equal(actual.hash, expected.hash, 'index property with known hash matches - ' + name);
            }
            return;
        }

        if (actual.eq) {
            assert.ok(actual.eq(expected), 'numeric value matches - ' + name);
        }
    }

    assert.equal(actual, expected, 'value matches - ' + name);
}

function TestContractEvents() {
    return ethers.providers.Provider.fetchJSON('https://api.ethers.io/api/v1/?action=triggerTest&address=' + contract.address).then(function(data) {
        console.log('  Triggered Transaction Hash: ' + data.hash);

        function waitForEvent(eventName, expected) {
            return new Promise(function(resolve, reject) {
                contract['on' + eventName.toLowerCase()] = function() {
                    //console.dir(this, { depth: null });
                    //console.log(this.event);
                    this.removeListener();
                    equals(this.event, Array.prototype.slice.call(arguments), expected);
                    resolve();
                };
            });
        }

        return new Promise(function(resolve, reject) {
            var p0 = '0x06B5955A67D827CDF91823E3bB8F069e6c89c1D6';
            var p0_1 = '0x06b5955A67d827CdF91823e3Bb8F069e6C89C1d7';
            var p1 = 0x42;
            var p1_1 = 0x43;

            return Promise.all([
                waitForEvent('Test', [ p0, p1 ]),
                waitForEvent('TestP0', [ p0, p1 ]),
                waitForEvent('TestP0P1', [ p0, p1 ]),
                waitForEvent('TestIndexedString', [ { indexed: true, hash: '0x7c5ea36004851c764c44143b1dcb59679b11c9a68e5f41497f6cf3d480715331' }, p1 ]),
                waitForEvent('TestV2', [ { indexed: true }, [ p0, p1 ] ]),
                waitForEvent('TestV2Nested', [ { indexed: true }, [ p0_1, p1_1, [ p0, p1 ] ] ]),
            ]).then(function(result) {
                resolve();
            });
        });
    });
}

describe('Test Contract Objects', function() {

    it('parses events', function() {
        this.timeout(120000);
        return TestContractEvents();
    });

    it('ABIv2 parameters and return types work', function() {
        var p0 = '0x06B5955A67D827CDF91823E3bB8F069e6c89c1D6';
        var p0_0f = '0x06B5955a67d827cDF91823e3bB8F069E6c89c1e5';
        var p0_f0 = '0x06b5955a67D827CDF91823e3Bb8F069E6C89c2C6';
        var p1 = 0x42;
        var p1_0f = 0x42 + 0x0f;
        var p1_f0 = 0x42 + 0xf0;

        var expectedPosStruct = [ p0_f0, p1_f0, [ p0_0f, p1_0f ] ];

        var seq = Promise.resolve();
        [
            [p0, p1, [ p0, p1 ] ],
            { p0: p0, p1: p1, child: [ p0, p1 ] },
            [ p0, p1, { p0: p0, p1: p1 } ],
            { p0: p0, p1: p1, child: { p0: p0, p1: p1 } }
        ].forEach(function(struct) {
            seq = seq.then(function() {
                return contract.testV2(struct).then(function(result) {
                    equals('position input', result, expectedPosStruct);
                    equals('keyword input p0', result.p0, expectedPosStruct[0]);
                    equals('keyword input p1', result.p1, expectedPosStruct[1]);
                    equals('keyword input child.p0', result.child.p0, expectedPosStruct[2][0]);
                    equals('keyword input child.p1', result.child.p1, expectedPosStruct[2][1]);
                });
            });
        });

        return seq;
    });

    it('collapses single argument solidity methods', function() {
        return contract.testSingleResult(4).then(function(result) {
            assert.equal(result, 5, 'single value returned');
        });
    });

    it('does not collapses multi argument solidity methods', function() {
        return contract.testMultiResult(6).then(function(result) {
            assert.equal(result[0], 7, 'multi value [0] returned');
            assert.equal(result[1], 8, 'multi value [1] returned');
            assert.equal(result.r0, 7, 'multi value [r0] returned');
            assert.equal(result.r1, 8, 'multi value [r1] returned');
        });
    });
});
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');
var pg = require('../src');

describe('nor-pgrunner', function() {
	it('Initialize, start and stop', function(done) {
		pg().then(function(db){
			return db.stop();
		}).then(function(){
			done();
		}).fail(function(err){
			throw err;
		}).done();
	});

	it("Generate config string", function(done) {

		var opts = {
			host: "127.0.0.1",
			port: "54323",
			user: "dummyuser",
			database: "dummydb"
		}

		pg(opts).then(function(db){
			assert.equal("pg://dummyuser@127.0.0.1:54323/dummydb", db.pgconfig, "Should generate proper config string!");
			return db.stop();
		}).then(function(){
			done();
		}).done();
	});

});
<commit_msg>minor semicolon fix<commit_after>"use strict";

var assert = require('assert');
var pg = require('../src');

describe('nor-pgrunner', function() {
	it('Initialize, start and stop', function(done) {
		pg().then(function(db){
			return db.stop();
		}).then(function(){
			done();
		}).fail(function(err){
			throw err;
		}).done();
	});

	it("Generate config string", function(done) {

		var opts = {
			host: "127.0.0.1",
			port: "54323",
			user: "dummyuser",
			database: "dummydb"
		};

		pg(opts).then(function(db){
			assert.equal("pg://dummyuser@127.0.0.1:54323/dummydb", db.pgconfig, "Should generate proper config string!");
			return db.stop();
		}).then(function(){
			done();
		}).done();
	});

});
<|endoftext|>


<commit_before>'use strict';
describe('$jet', function () {

  var $jet, $timeout, $rootScope;

  beforeEach(function() {
    module('jet');

    inject(function (_$jet_, _$timeout_, _$rootScope_) {
      $jet = _$jet_;
      $timeout = _$timeout_;
      $rootScope = _$rootScope_;
    });
  });

  describe('$Peer', function() {

    it('<ctor> is function', function() {
      expect(typeof $jet.$Peer).toBe('function');
    });

    describe('instance', function() {
      var peer;

      beforeEach(function() {
        peer = new $jet.$Peer();
      });

      afterEach(function() {
        peer.$close();
      });

      it('is an object', function() {
        expect(typeof peer).toBe('object');
      });

      it('.$closed is initially false', function() {
        var $closed = peer.$closed;
        expect(angular.isObject($closed)).toBe(true);
        expect(typeof $closed.then).toBe('function');
      });

      it('.$closed is true after scope destroy', function() {
        var scope = $rootScope.$new();
        var peer = new $jet.$Peer({
          scope: scope
        });
        expect(peer.$$closed).toBe(false);
        scope.$destroy();
        expect(peer.$$closed).toBe(true);
      });

      it('.$close is function', function() {
        expect(typeof peer.$close).toBe('function');
      });

      it('.$close resolves $closed promise', function(done) {
        peer.$close();
        peer.$closed.then(function() {
          done();
        });
      });

      it('.$fetch is function', function() {
        expect(typeof peer.$fetch).toBe('function');
      });

      it('.$wait is function', function() {
        expect(typeof peer.$wait).toBe('function');
      });

      it('.$set is function', function() {
        expect(typeof peer.$wait).toBe('function');
      });

      it('.$connected is promise', function() {
        var $connected = peer.$connected;
        expect(angular.isObject($connected)).toBe(true);
        expect(typeof $connected.then).toBe('function');
      });

      it('.$connected promise gets resolved', function(done) {
        peer.$connected.then(function() {
            done();
        });
      });

      it('.$connected promise gets rejected (using a non-valid url)', function(done) {
        var peer2 = new $jet.$Peer({
          url: 'ws://this.is.dead'
        });
        peer2.$connected.then(function() {
        }, function(err) {

          done();
        });
        $timeout.flush();
      });

      it('.$set returns promise', function() {
        var set = peer.$set('doesnotexist');
        expect(angular.isObject(set)).toBe(true);
        expect(typeof set.then).toBe('function');
      });

      it('.$set gets resolved', function(done) {
        peer.$set('acceptOnlyNumbers', 421).then(function(result) {
          expect(result).toBe(true);
          done();
        });
      });

      it('.$set gets rejected', function(done) {
        peer.$set('acceptOnlyNumbers', {x:1}).then(function() {
          expect(false).toBe('this should not happen');
        }, function(err) {
          expect(err.message).toBe('Internal error');
          done();
        });
      });

      it('.$call returns promise', function() {
        var call = peer.$call('doesnotexist');
        expect(angular.isObject(call)).toBe(true);
        expect(typeof call.then).toBe('function');
      });

      it('.$call checks arg type', function() {
        [false, 123, 'foo'].forEach(function(unsupported) {
          expect( function() {peer.$call('asd', unsupported);} ).toThrow(new Error('second arg to $call must be undefined, Array or Object'));
        });
        [{},[]].forEach(function(supported) {
          expect( function() {peer.$call('asd', supported);} ).not.toThrow();
        });
      });

      it('.$call gets resolved', function(done) {
        peer.$call('syncHello',['Joe']).then(function(greet) {
          expect(greet).toBe('Hello Joe');
          done();
        });
      });

      it('.$call gets rejected', function(done) {
        peer.$call('letsFailSync').then(function(greet) {
          expect(false).toBe('this should not happen');
        }, function(err) {
          expect(err.message).toBe('Internal error');
          done();
        });
      });

      it('.$wait(...) returns a promise and gets resolved', function(done) {
        var wait = peer.$wait('syncHello', 'asyncHello');
        expect(angular.isObject(wait)).toBe(true);
        expect(typeof wait.then).toBe('function');
        wait.then(function() {
          done();
        });
      }); // wait

      describe('.$fetch', function() {

        describe('basics', function() {
        var fetcher;

        beforeEach(function() {
          fetcher = peer.$fetch();
        });

        it('returns an object', function() {
          expect(typeof fetcher).toBe('object');
        });

        it('.$ready is a promise', function() {
          expect(angular.isObject(fetcher.$ready)).toBe(true);
          expect(typeof fetcher.$ready.then).toBe('function');
        });

        it('.$active should be initially false', function() {
          expect(fetcher.$active).toBe(false);
        });

        it('.$unfetch is a function', function() {
          expect(typeof fetcher.$unfetch).toBe('function');
        });

        it('.$unfetch can be called immediatly and gets resolved', function(done) {
          fetcher.$unfetch().then(function() {
            done();
          });
        });

        it('.$ready promise gets resolved and .$active is true', function(done) {
          fetcher.$ready.then(function() {
            expect(fetcher.$active).toBe(true);
            done();
          });
        });

        xit('.$ready promise gets rejected and $active is still false', function(done) {
          var fetcher = peer.$fetch({path: {
            invalidRule: 'asd'
          }});
          fetcher.$ready.then(function() {
            expect('this should not happen').toBe(false);
          }, function(err) {
            expect(fetcher.$active).toBe(false);
            done();
          });
        });

      }); // basics

      it('fetch states as map (default) from "node-jet/bin/some-service.js"', function(done) {
        var fetcher = peer.$fetch({path: {
          equalsOneOf: ['acceptOnlyNumbers', 'persons/1']
        }});
        setTimeout(function() {
          expect(typeof fetcher['acceptOnlyNumbers'].$value).toBe('number');
          expect(typeof fetcher['persons/1'].$value).toBe('object');
          expect(typeof fetcher['persons/1'].$save).toBe('function');
          expect(fetcher['persons/1'].$path).toBe('persons/1');
          done();
        },70);
      });

      it('fetch states as array from "node-jet/bin/some-service.js"', function(done) {
        var topPlayers = peer.$fetch({
          path: {
            startsWith: 'persons/'
          },
          sort: {
            byValueField: {
              score: 'number'
            },
            descending: true,
            from: 1,
            to: 3
          }
        });

        expect(topPlayers.length).toBe(0);
        expect(typeof topPlayers.filter).toBe('function');

        $rootScope.topPlayers = topPlayers;
        // test watch gets called
        $rootScope.$watch('topPlayers', function(topPlayers, old) {
            expect(typeof topPlayers.$unfetch).toBe('function');
            if (topPlayers.length !== 0) {
              expect(topPlayers.$active).toBe(true);
              expect(topPlayers.length).toBe(3)
              expect(typeof topPlayers[0].$value).toBe('object');
              expect(typeof topPlayers[1].$value).toBe('object');
              expect(typeof topPlayers[2].$value).toBe('object');

              expect(topPlayers[0].$value.score > topPlayers[1].$value.score).toBe(true);
              expect(topPlayers[1].$value.score > topPlayers[2].$value.score).toBe(true);

              expect(typeof topPlayers[0].$save).toBe('function');
              expect(typeof topPlayers[0].$path).toBe('string');
              expect(topPlayers[0].$index).toBe(1);
              done();
            }
        },true);
        setTimeout(function() {
          $timeout.flush();
        },70);
      });

      it('unfetches on scope $destroy', function(done) {
        var scope = $rootScope.$new();
        var fetcher = peer.$fetch({}, scope);
        fetcher.$ready.then(function() {
          expect(fetcher.$active).toBe(true);
          scope.$destroy();
          expect(fetcher.$active).toBe(false);
          done();
        });
      });

    }); //$fetch

    });

  });

});
<commit_msg>fix tests<commit_after>'use strict';
describe('$jet', function () {

  var $jet, $timeout, $rootScope;

  beforeEach(function() {
    module('jet');

    inject(function (_$jet_, _$timeout_, _$rootScope_) {
      $jet = _$jet_;
      $timeout = _$timeout_;
      $rootScope = _$rootScope_;
    });
  });

  describe('$Peer', function() {

    it('<ctor> is function', function() {
      expect(typeof $jet.$Peer).toBe('function');
    });

    describe('instance', function() {
      var peer;

      beforeEach(function() {
        peer = new $jet.$Peer();
      });

      afterEach(function() {
        peer.$close();
      });

      it('is an object', function() {
        expect(typeof peer).toBe('object');
      });

      it('.$closed is initially false', function() {
        var $closed = peer.$closed;
        expect(angular.isObject($closed)).toBe(true);
        expect(typeof $closed.then).toBe('function');
      });

      it('.$closed is true after scope destroy', function() {
        var scope = $rootScope.$new();
        var peer = new $jet.$Peer({
          scope: scope
        });
        expect(peer.$$closed).toBe(false);
        scope.$destroy();
        expect(peer.$$closed).toBe(true);
      });

      it('.$close is function', function() {
        expect(typeof peer.$close).toBe('function');
      });

      it('.$close resolves $closed promise', function(done) {
        peer.$close();
        peer.$closed.then(function() {
          done();
        });
      });

      it('.$fetch is function', function() {
        expect(typeof peer.$fetch).toBe('function');
      });

      it('.$wait is function', function() {
        expect(typeof peer.$wait).toBe('function');
      });

      it('.$set is function', function() {
        expect(typeof peer.$wait).toBe('function');
      });

      it('.$connected is promise', function() {
        var $connected = peer.$connected;
        expect(angular.isObject($connected)).toBe(true);
        expect(typeof $connected.then).toBe('function');
      });

      it('.$connected promise gets resolved', function(done) {
        peer.$connected.then(function() {
            done();
        });
      });

      it('.$connected promise gets rejected (using a non-valid url)', function(done) {
        var peer2 = new $jet.$Peer({
          url: 'ws://this.is.dead'
        });
        peer2.$connected.then(function() {
        }, function(err) {

          done();
        });
        $timeout.flush();
      });

      it('.$set returns promise', function() {
        var set = peer.$set('doesnotexist');
        expect(angular.isObject(set)).toBe(true);
        expect(typeof set.then).toBe('function');
      });

      it('.$set gets resolved', function(done) {
        peer.$set('acceptOnlyNumbers', 421).then(function(result) {
          expect(result).toBe(true);
          done();
        });
      });

      it('.$set gets rejected', function(done) {
        peer.$set('acceptOnlyNumbers', {x:1}).then(function() {
          expect(false).toBe('this should not happen');
        }, function(err) {
          expect(err.message).toBe('Internal error');
          done();
        });
      });

      it('.$call returns promise', function() {
        var call = peer.$call('doesnotexist');
        expect(angular.isObject(call)).toBe(true);
        expect(typeof call.then).toBe('function');
      });

      it('.$call checks arg type', function() {
        [false, 123, 'foo'].forEach(function(unsupported) {
          expect( function() {peer.$call('asd', unsupported);} ).toThrow(new Error('second arg to $call must be undefined, Array or Object'));
        });
        [{},[]].forEach(function(supported) {
          expect( function() {peer.$call('asd', supported);} ).not.toThrow();
        });
      });

      it('.$call gets resolved', function(done) {
        peer.$call('syncHello',['Joe']).then(function(greet) {
          expect(greet).toBe('Hello Joe');
          done();
        });
      });

      it('.$call gets rejected', function(done) {
        peer.$call('letsFailSync').then(function(greet) {
          expect(false).toBe('this should not happen');
        }, function(err) {
          expect(err.message).toBe('Internal error');
          done();
        });
      });

      it('.$wait(...) returns a promise and gets resolved', function(done) {
        var wait = peer.$wait('syncHello', 'asyncHello');
        expect(angular.isObject(wait)).toBe(true);
        expect(typeof wait.then).toBe('function');
        wait.then(function() {
          done();
        });
      }); // wait

      describe('.$fetch', function() {

        describe('basics', function() {
        var fetcher;

        beforeEach(function() {
          fetcher = peer.$fetch();
        });

        it('returns an object', function() {
          expect(typeof fetcher).toBe('object');
        });

        it('.$ready is a promise', function() {
          expect(angular.isObject(fetcher.$ready)).toBe(true);
          expect(typeof fetcher.$ready.then).toBe('function');
        });

        it('.$active should be initially false', function() {
          expect(fetcher.$active).toBe(false);
        });

        it('.$unfetch is a function', function() {
          expect(typeof fetcher.$unfetch).toBe('function');
        });

        it('.$unfetch can be called immediatly and gets resolved', function(done) {
          fetcher.$unfetch().then(function() {
            done();
          });
        });

        it('.$ready promise gets resolved and .$active is true', function(done) {
          fetcher.$ready.then(function() {
            expect(fetcher.$active).toBe(true);
            done();
          });
        });

        xit('.$ready promise gets rejected and $active is still false', function(done) {
          var fetcher = peer.$fetch({path: {
            invalidRule: 'asd'
          }});
          fetcher.$ready.then(function() {
            expect('this should not happen').toBe(false);
          }, function(err) {
            expect(fetcher.$active).toBe(false);
            done();
          });
        });

      }); // basics

      it('fetch unsorted states from "node-jet/bin/some-service.js"', function(done) {
        var fetcher = peer.$fetch({path: {
          equalsOneOf: ['acceptOnlyNumbers', 'persons/1']
        }});
        setTimeout(function() {
          var pathSortedFetcher = fetcher.sort(function(a,b) {
            return a.$path - b.$path;
          });
          expect(pathSortedFetcher[0].$path).toBe('acceptOnlyNumbers');
          expect(typeof pathSortedFetcher[0].$value).toBe('number');
          expect(typeof pathSortedFetcher[0].$save).toBe('function');
          expect(typeof pathSortedFetcher[0].$index).toBe('undefined');
          expect(pathSortedFetcher[1].$path).toBe('persons/1');
          done();
        },70);
      });

      it('fetch states as array from "node-jet/bin/some-service.js"', function(done) {
        var topPlayers = peer.$fetch({
          path: {
            startsWith: 'persons/'
          },
          sort: {
            byValueField: {
              score: 'number'
            },
            descending: true,
            from: 1,
            to: 3
          }
        });

        expect(topPlayers.length).toBe(0);
        expect(typeof topPlayers.filter).toBe('function');

        $rootScope.topPlayers = topPlayers;
        // test watch gets called
        $rootScope.$watch('topPlayers', function(topPlayers, old) {
            expect(typeof topPlayers.$unfetch).toBe('function');
            if (topPlayers.length !== 0) {
              expect(topPlayers.$active).toBe(true);
              expect(topPlayers.length).toBe(3)
              expect(typeof topPlayers[0].$value).toBe('object');
              expect(typeof topPlayers[1].$value).toBe('object');
              expect(typeof topPlayers[2].$value).toBe('object');

              expect(topPlayers[0].$value.score > topPlayers[1].$value.score).toBe(true);
              expect(topPlayers[1].$value.score > topPlayers[2].$value.score).toBe(true);

              expect(typeof topPlayers[0].$save).toBe('function');
              expect(typeof topPlayers[0].$path).toBe('string');
              expect(topPlayers[0].$index).toBe(1);
              done();
            }
        },true);
        setTimeout(function() {
          $timeout.flush();
        },70);
      });

      it('unfetches on scope $destroy', function(done) {
        var scope = $rootScope.$new();
        var fetcher = peer.$fetch({}, scope);
        fetcher.$ready.then(function() {
          expect(fetcher.$active).toBe(true);
          scope.$destroy();
          expect(fetcher.$active).toBe(false);
          done();
        });
      });

    }); //$fetch

    });

  });

});
<|endoftext|>


<commit_before>module.exports = function() {
  var server;
  var has_err = false;

  beforeAll(function(done) {
    // process.env.BLOT_HOST = 'localhost';

    server = require("child_process").fork(__dirname + "/../../app", {
      silent: true
    });

    // App should not emit anything on standard error
    server.stderr.on("data", function(data) {
      has_err = true;
      console.log("CONFIGURATION error:", data.toString("utf8"));
      server.kill();
      done(new Error("Server failed to start: " + data.toString("utf8")));
    });

    // Listen for listening message
    server.stdout.on("data", function(data) {
      // This is a bit of a flimsy check to see if the server is running
      if (data.toString("utf8").indexOf("started") > -1) {
        done();
      }
    });
  });

  afterAll(function(done) {
    server.on("close", function(code) {
      // 128 + 15
      // https://github.com/sindresorhus/exit-hook/commit/b6c274f6dc7617b8c800d612ac343ecc0cdef867
      expect(code).toEqual(143);
      expect(has_err).toEqual(false);
      done();
    });

    server.kill();
  });
};
<commit_msg>Added timeout<commit_after>module.exports = function() {
  var server;
  var has_err = false;

  beforeAll(function(done) {
    // process.env.BLOT_HOST = 'localhost';

    server = require("child_process").fork(__dirname + "/../../app", {
      silent: true
    });

    // App should not emit anything on standard error
    server.stderr.on("data", function(data) {
      has_err = true;
      console.log("CONFIGURATION error:", data.toString("utf8"));
      server.kill();
      done(new Error("Server failed to start: " + data.toString("utf8")));
    });

    // Listen for listening message
    server.stdout.on("data", function(data) {
      // This is a bit of a flimsy check to see if the server is running
      if (data.toString("utf8").indexOf("started") > -1) {
        done();
      }
    });
  });

  afterAll(function(done) {

    server.on("close", function(code) {
      // 128 + 15
      // https://github.com/sindresorhus/exit-hook/commit/b6c274f6dc7617b8c800d612ac343ecc0cdef867
      expect(code).toEqual(143);
      expect(has_err).toEqual(false);
    });

    server.kill();

    done();
  });
};
<|endoftext|>