<commit_before>$(document)
  .ready(function() {

    $('.ui.dropdown')
      .dropdown({
        on: 'hover'
      })
    ;

    $('.masthead .information')
      .transition('scale in', 1000)
    ;

    var apiVersion = '0.1';

    // Function to create a table.
    function tableCreate(el, data)
    {
        var listBody = $('#table-list > tbody')[0];

        for (var i = 0; i < data.length; i++)
        {
            var tr = listBody.insertRow();
            var td = tr.insertCell();
            //var id = data[i].Id.substring(0, 11);
            //var id = data[i].Id;
            var idLink = data[i].Id;
            //var idLink = '' + id  + '';
            //var idLink = '' + id  + '';
            //td.appendChild(document.createTextNode(idLink));
            td.innerHTML = idLink;
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Name));

            // Add container for buttons.
            var btns = $('');

            // Add images button.
            var imagesBtn = buildButton('Images', 'cube icon');
            var link = document.createElement('a');
            var imagesUri = 'images.html?nodeid=' + idLink;
            console.log('URI: ' + imagesUri);
            link.setAttribute('href', imagesUri)
            $(link).append(imagesBtn);
            $(btns).append($(link));

            // Add containers button.
            var containersBtn = buildButton('Containers', 'cubes icon');
            var link = document.createElement('a');
            var containersUri = 'containers.html?nodeid=' + idLink;
            link.setAttribute('href', containersUri)
            $(link).append(containersBtn);
            $(btns).append($(link));
            $(td).append($(btns));

            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Scheme));
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Address));
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Port));
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Description));
            var td = tr.insertCell();
            //var dt = convertUnixTime(data[i].Created);
            var dt = data[i].Created;
            td.appendChild(document.createTextNode(dt));
            //var td = tr.insertCell();
            //var text = '';
            //if (data[i].Labels !== 'undefined' && data[i].Labels !== null)  {
            //    for (var j = 0; j < data[i].Labels.length; j++)
            //    {
            //        text += data[i].Labels[j] + '
';
            //    }
            //}
            //td.appendChild(document.createTextNode(text));
            //var td = tr.insertCell();
            //td.appendChild(document.createTextNode(data[i].RepoDigests));
        }
        $('#table-list > tbody > tr').each( function() {
            var td = $('td:eq(1)', this)[0];
            var val = td.childNodes[0].textContent;
            var btns = td.childNodes[1];
            var abbr = val.substring(0, 11);
            var link = document.createElement('a');
            var linkText = document.createTextNode(abbr);
            link.setAttribute('href', 'monitor.html?nodeid=' + $('td:eq(0)', this)[0].textContent);
            link.className = '';
            link.appendChild(linkText);
            td.innerHTML = '';  // Clear cell first.
            td.appendChild(link);
            td.appendChild(btns);

            /*
             * Add buttons.
             */

            /*
            var historyBtn = buildButton('History', 'history icon');
            $(td).append($(historyBtn));

            var deleteBtn = buildButton('Delete', 'delete icon');
            $(td).append($(deleteBtn));
            */

            /*
             * Bind button event handlers.
             */

            /*
            $(historyBtn).click( function() {
                $('#tab-history-message').text('');
                var t = document.getElementById('table-history');
                var tbl = new Table();
                tbl.create(t);
                tbl.clear();

                // Get inspect data.
                $.getJSON('/images/history/' + val, function() {
                        //console.log('requested');
                })
                .done(function(data) {
                    if (data.length === 0) {
                        $('#tab-history-message').text('No history.');
                        $('#tab-history').modal('show');
                        return;
                    }
                    var t = document.getElementById('table-history');
                    var tbl = new Table();
                    tbl.create(t);
                    tbl.setHeader(['Created', 'Created By', 'Id', 'Size', 'Tags']);
                    tbl.addBody(data);
                    $('#tab-history').modal('show');
                })
            });
            */
            /*
            $(link).click( function() {
                    //$('#menu-tabs #menu-tabs-inspect').click();
                    // Get inspect data.
                    $.getJSON('/images/inspect/' + val, function() {
                            //console.log('requested');
                        })
                        .done(function(data) {
                            //$('#tab-inspect #results').text(JSON.stringify(data));
                            var html = renderJson(data);
                            $('#tab-inspect #results').html(html);
                            $('#tab-inspect').modal('show');
                        })
                        .fail(
                            function( jqxhr, textStatus, error ) {
                                var err = textStatus + ", " + error;
                                console.log( "Request Failed: " + err );
                            }
                        )
                        .always(function() {
                            //console.log( "complete" );
                        })
                    ;
                }
            );
            */
            /*
            $(deleteBtn).click( function() {
                $('#tab-delete').modal('show');
                $.getJSON('/images/delete/' + val, function() {
                        //console.log('requested');
                })
                .done(function(data) {
                    var statusCode = data.StatusCode;
                    var html = renderJson(data);
                    $('#tab-delete #results').html(html);
                    $('#table-list-body').empty();
                    loadImageList();
                })
                .fail(
                    function( jqxhr, textStatus, error ) {
                        var err = textStatus + ", " + error;
                        console.log( "Request Failed: " + err );
                    }
                )
            });
            */
        });

    }

    $('#menu-tabs .item')
        .tab('change tab', 'tab-list')
    ;

    var clusterId = document.getElementById('hidden-clusterid').value;

    loadNodeList();

    function loadNodeList() {
        $.getJSON('/' + apiVersion  + '/clusters/' + clusterId  + '/nodes')
            .done(function(data) {
                if (data.length === 0) {
                    $('#tab-list-message').text('No nodes.');
                    return;
                }
                var t = document.getElementById('table-list');
                var tbl = new Table();
                tbl.create(t);
                tbl.setHeader([
                    'Id',
                    'Name',
                    'Scheme',
                    'Address',
                    'Port',
                    'Description',
                    'Created',
                    ]);
                tableCreate($("#tab-list #results")[0], data);
            })
        ;
    }

    /*
    $('#menu-tabs-search')
        .on('click', function() {
            $('#tab-search')
                .tab('change tab', 'tab-search')
            ;
        })
    ;

    $('#menu-tabs-add')
        .on('click', function() {
            $('#tab-add')
                .tab('change tab', 'tab-add')
            ;
        })
    ;
    */

    var addNodeValidationRules = {
        'tab-add-name-text': {
            identifier: 'tab-add-name-text',
            rules: [
            {
                type: 'empty',
                prompt: 'Give the node a name.'
            }
            ]
        },
        'tab-add-scheme-text': {
            identifier: 'tab-add-scheme-text',
            rules: [
            {
                type: 'empty',
                prompt: 'HTTP or HTTPS?'
            }
            ]
        },
        'tab-add-address-text': {
            identifier: 'tab-add-address-text',
            rules: [
            {
                type: 'empty',
                prompt: 'What\'s the IP address?'
            }
            ]
        },
        'tab-add-port-text': {
            identifier: 'tab-add-port-text',
            rules: [
            {
                type: 'empty',
                prompt: 'What\'s the port?'
            },
            {
                type: 'integer[1..65535]',
                prompt: 'Invalid port number.'
            }
            ]
        },
        'tab-add-description-text': {
            identifier: 'tab-add-description-text',
            rules: [
            {
                type: 'empty',
                prompt: 'Give the node a description.'
            }
            ]
        }

    };

    $('#tab-add .ui.form').form(addNodeValidationRules, { inline: true,  onSuccess: function() {
            $('.ui.dimmer').dimmer('show');

            var name = $('#tab-add-name-text').val();
            var scheme = $('#tab-add-scheme-text').val();
            var address = $('#tab-add-address-text').val();
            var port = parseInt( $('#tab-add-port-text').val(), 10);
            var desc = $('#tab-add-description-text').val();
            var node = {
                'Name': name,
                'Scheme': scheme,
                'Address': address,
                'Port': port,
                'Description': desc
            };
            var postBody = JSON.stringify(node);
            $.post('/' + apiVersion  + '/clusters/' + + '/nodes', postBody, function() { console.log('success') } )
                .done(function(data) {
                    $('.ui.dimmer').dimmer('hide');
                    var statusCode = data.StatusCode;
                    var html = renderJson(JSON.parse(data));
                    $('#tab-add-added #results').html(html);
                    $('#menu-tabs .item')
                        .tab('change tab', 'tab-list')
                    ;

                    var t = document.getElementById('table-list');
                    var tbl = new Table();
                    tbl.create(t);
                    tbl.clear();
                    loadNodeList();
                    $('#tab-add-added').modal('show');
                })
                .fail(function(jqxhr, textStatus, error) {
                    var err = textStatus + ", " + error;
                    console.log('Request Failed: ' + err);
                })
            ;

        }})
    ;

    function renderSearchResults(json) {
        $('#tab-search-results-message').text('');
        var t = document.getElementById('table-search-results');
        var tbl = new Table();
        tbl.create(t);
        tbl.clear();
        if (json.length === 0) {
            $('#tab-search-results-modal-message').modal('show');
            $('#tab-search-results-message').text('No results.');
            return;
        }
        tbl.setHeader(['Description', 'Is Official', 'Is Trusted', 'Name', 'Star Count']);
        tbl.addBody(json);
    }

  })
;
<commit_msg>Show full node name on hover.<commit_after>$(document)
  .ready(function() {

    $('.ui.dropdown')
      .dropdown({
        on: 'hover'
      })
    ;

    $('.masthead .information')
      .transition('scale in', 1000)
    ;

    var apiVersion = '0.1';

    // Function to create a table.
    function tableCreate(el, data)
    {
        var listBody = $('#table-list > tbody')[0];

        for (var i = 0; i < data.length; i++)
        {
            var tr = listBody.insertRow();
            var td = tr.insertCell();
            //var id = data[i].Id.substring(0, 11);
            //var id = data[i].Id;
            var idLink = data[i].Id;
            //var idLink = '' + id  + '';
            //var idLink = '' + id  + '';
            //td.appendChild(document.createTextNode(idLink));
            td.innerHTML = idLink;
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Name));

            // Add container for buttons.
            var btns = $('');

            // Add images button.
            var imagesBtn = buildButton('Images', 'cube icon');
            var link = document.createElement('a');
            var imagesUri = 'images.html?nodeid=' + idLink;
            console.log('URI: ' + imagesUri);
            link.setAttribute('href', imagesUri)
            $(link).append(imagesBtn);
            $(btns).append($(link));

            // Add containers button.
            var containersBtn = buildButton('Containers', 'cubes icon');
            var link = document.createElement('a');
            var containersUri = 'containers.html?nodeid=' + idLink;
            link.setAttribute('href', containersUri)
            $(link).append(containersBtn);
            $(btns).append($(link));
            $(td).append($(btns));

            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Scheme));
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Address));
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Port));
            var td = tr.insertCell();
            td.appendChild(document.createTextNode(data[i].Description));
            var td = tr.insertCell();
            //var dt = convertUnixTime(data[i].Created);
            var dt = data[i].Created;
            td.appendChild(document.createTextNode(dt));
            //var td = tr.insertCell();
            //var text = '';
            //if (data[i].Labels !== 'undefined' && data[i].Labels !== null)  {
            //    for (var j = 0; j < data[i].Labels.length; j++)
            //    {
            //        text += data[i].Labels[j] + '
';
            //    }
            //}
            //td.appendChild(document.createTextNode(text));
            //var td = tr.insertCell();
            //td.appendChild(document.createTextNode(data[i].RepoDigests));
        }
        $('#table-list > tbody > tr').each( function() {
            var td = $('td:eq(1)', this)[0];
            var val = td.childNodes[0].textContent;
            var btns = td.childNodes[1];
            var abbr = val.substring(0, 11) + '...';
            var link = document.createElement('a');
            var linkText = document.createTextNode(abbr);
            link.setAttribute('href', 'monitor.html?nodeid=' + $('td:eq(0)', this)[0].textContent);
            link.setAttribute('title', val);
            link.className = '';
            link.appendChild(linkText);
            td.innerHTML = '';  // Clear cell first.
            td.appendChild(link);
            td.appendChild(btns);

            /*
             * Add buttons.
             */

            /*
            var historyBtn = buildButton('History', 'history icon');
            $(td).append($(historyBtn));

            var deleteBtn = buildButton('Delete', 'delete icon');
            $(td).append($(deleteBtn));
            */

            /*
             * Bind button event handlers.
             */

            /*
            $(historyBtn).click( function() {
                $('#tab-history-message').text('');
                var t = document.getElementById('table-history');
                var tbl = new Table();
                tbl.create(t);
                tbl.clear();

                // Get inspect data.
                $.getJSON('/images/history/' + val, function() {
                        //console.log('requested');
                })
                .done(function(data) {
                    if (data.length === 0) {
                        $('#tab-history-message').text('No history.');
                        $('#tab-history').modal('show');
                        return;
                    }
                    var t = document.getElementById('table-history');
                    var tbl = new Table();
                    tbl.create(t);
                    tbl.setHeader(['Created', 'Created By', 'Id', 'Size', 'Tags']);
                    tbl.addBody(data);
                    $('#tab-history').modal('show');
                })
            });
            */
            /*
            $(link).click( function() {
                    //$('#menu-tabs #menu-tabs-inspect').click();
                    // Get inspect data.
                    $.getJSON('/images/inspect/' + val, function() {
                            //console.log('requested');
                        })
                        .done(function(data) {
                            //$('#tab-inspect #results').text(JSON.stringify(data));
                            var html = renderJson(data);
                            $('#tab-inspect #results').html(html);
                            $('#tab-inspect').modal('show');
                        })
                        .fail(
                            function( jqxhr, textStatus, error ) {
                                var err = textStatus + ", " + error;
                                console.log( "Request Failed: " + err );
                            }
                        )
                        .always(function() {
                            //console.log( "complete" );
                        })
                    ;
                }
            );
            */
            /*
            $(deleteBtn).click( function() {
                $('#tab-delete').modal('show');
                $.getJSON('/images/delete/' + val, function() {
                        //console.log('requested');
                })
                .done(function(data) {
                    var statusCode = data.StatusCode;
                    var html = renderJson(data);
                    $('#tab-delete #results').html(html);
                    $('#table-list-body').empty();
                    loadImageList();
                })
                .fail(
                    function( jqxhr, textStatus, error ) {
                        var err = textStatus + ", " + error;
                        console.log( "Request Failed: " + err );
                    }
                )
            });
            */
        });

    }

    $('#menu-tabs .item')
        .tab('change tab', 'tab-list')
    ;

    var clusterId = document.getElementById('hidden-clusterid').value;

    loadNodeList();

    function loadNodeList() {
        $.getJSON('/' + apiVersion  + '/clusters/' + clusterId  + '/nodes')
            .done(function(data) {
                if (data.length === 0) {
                    $('#tab-list-message').text('No nodes.');
                    return;
                }
                var t = document.getElementById('table-list');
                var tbl = new Table();
                tbl.create(t);
                tbl.setHeader([
                    'Id',
                    'Name',
                    'Scheme',
                    'Address',
                    'Port',
                    'Description',
                    'Created',
                    ]);
                tableCreate($("#tab-list #results")[0], data);
            })
        ;
    }

    /*
    $('#menu-tabs-search')
        .on('click', function() {
            $('#tab-search')
                .tab('change tab', 'tab-search')
            ;
        })
    ;

    $('#menu-tabs-add')
        .on('click', function() {
            $('#tab-add')
                .tab('change tab', 'tab-add')
            ;
        })
    ;
    */

    var addNodeValidationRules = {
        'tab-add-name-text': {
            identifier: 'tab-add-name-text',
            rules: [
            {
                type: 'empty',
                prompt: 'Give the node a name.'
            }
            ]
        },
        'tab-add-scheme-text': {
            identifier: 'tab-add-scheme-text',
            rules: [
            {
                type: 'empty',
                prompt: 'HTTP or HTTPS?'
            }
            ]
        },
        'tab-add-address-text': {
            identifier: 'tab-add-address-text',
            rules: [
            {
                type: 'empty',
                prompt: 'What\'s the IP address?'
            }
            ]
        },
        'tab-add-port-text': {
            identifier: 'tab-add-port-text',
            rules: [
            {
                type: 'empty',
                prompt: 'What\'s the port?'
            },
            {
                type: 'integer[1..65535]',
                prompt: 'Invalid port number.'
            }
            ]
        },
        'tab-add-description-text': {
            identifier: 'tab-add-description-text',
            rules: [
            {
                type: 'empty',
                prompt: 'Give the node a description.'
            }
            ]
        }

    };

    $('#tab-add .ui.form').form(addNodeValidationRules, { inline: true,  onSuccess: function() {
            $('.ui.dimmer').dimmer('show');

            var name = $('#tab-add-name-text').val();
            var scheme = $('#tab-add-scheme-text').val();
            var address = $('#tab-add-address-text').val();
            var port = parseInt( $('#tab-add-port-text').val(), 10);
            var desc = $('#tab-add-description-text').val();
            var node = {
                'Name': name,
                'Scheme': scheme,
                'Address': address,
                'Port': port,
                'Description': desc
            };
            var postBody = JSON.stringify(node);
            $.post('/' + apiVersion  + '/clusters/' + + '/nodes', postBody, function() { console.log('success') } )
                .done(function(data) {
                    $('.ui.dimmer').dimmer('hide');
                    var statusCode = data.StatusCode;
                    var html = renderJson(JSON.parse(data));
                    $('#tab-add-added #results').html(html);
                    $('#menu-tabs .item')
                        .tab('change tab', 'tab-list')
                    ;

                    var t = document.getElementById('table-list');
                    var tbl = new Table();
                    tbl.create(t);
                    tbl.clear();
                    loadNodeList();
                    $('#tab-add-added').modal('show');
                })
                .fail(function(jqxhr, textStatus, error) {
                    var err = textStatus + ", " + error;
                    console.log('Request Failed: ' + err);
                })
            ;

        }})
    ;

    function renderSearchResults(json) {
        $('#tab-search-results-message').text('');
        var t = document.getElementById('table-search-results');
        var tbl = new Table();
        tbl.create(t);
        tbl.clear();
        if (json.length === 0) {
            $('#tab-search-results-modal-message').modal('show');
            $('#tab-search-results-message').text('No results.');
            return;
        }
        tbl.setHeader(['Description', 'Is Official', 'Is Trusted', 'Name', 'Star Count']);
        tbl.addBody(json);
    }

  })
;
<|endoftext|>


<commit_before>import React from 'react';
import {List, ListItem} from 'material-ui/List';
import IconButton from 'material-ui/IconButton';
import {grey400, darkBlack} from 'material-ui/styles/colors';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';

const iconButtonElement = (
  <IconButton
    touch={true}
    tooltip="more"
    tooltipPosition="bottom-left"
  >
    <MoreVertIcon color={grey400} />
  </IconButton>
);

const rightIconMenu = (
  <IconMenu iconButtonElement={iconButtonElement}>
    <MenuItem>Download</MenuItem>
    <MenuItem>Edit</MenuItem>
    <MenuItem>Delete</MenuItem>
  </IconMenu>
);

class MainPanel extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      sermons: [],
      loading: true
    }
  }

  componentWillMount() {

  }

  componentWillUnMount() {
    this.props.base.removeBinding(this.ref);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps && nextProps.selectedCongregation && nextProps.selectedCongregation.bucketID) {
        this.setState({
          loading:true
        });
      this.ref = this.props.base.fetch('sermons', {
        context: this,
        state: 'sermons',
        asArray: true,
        queries: {
          limitToLast: 20,
          orderByChild: 'bucketID',
          equalTo: nextProps.selectedCongregation.bucketID
        },
        then(data){
            this.setState({
              sermons: data,
              loading:false
            });
        }
      });
    }
  }

  render() {

    const contentStyle = {  transition: 'margin-left 450ms cubic-bezier(0.23, 1, 0.32, 1)' };
    if (this.props.sideMenuOpen) {
      contentStyle.marginLeft = '256px';
    }

    if (this.state.loading === true) {
      return
Loading...
;
    }
    else {
      return  (

        <List>
          {this.state.sermons.map((sermon) => (
            <ListItem
              key={sermon.key}
              rightIconButton={rightIconMenu}
              primaryText={

                  {sermon.minister} : {new Date(sermon.date).toLocaleDateString()} : {sermon.bibleText}

              }
              secondaryText={

                  {sermon.comments}

              }
              secondaryTextLines={1}
            />
          ))
        }
        </List>

      )
    }
  }
}

export default MainPanel
<commit_msg>Fixes #14, filters for published sermons.<commit_after>import React from 'react';
import {List, ListItem} from 'material-ui/List';
import IconButton from 'material-ui/IconButton';
import {grey400, darkBlack} from 'material-ui/styles/colors';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';

const iconButtonElement = (
  <IconButton
    touch={true}
    tooltip="more"
    tooltipPosition="bottom-left"
  >
    <MoreVertIcon color={grey400} />
  </IconButton>
);

const rightIconMenu = (
  <IconMenu iconButtonElement={iconButtonElement}>
    <MenuItem>Download</MenuItem>
    <MenuItem>Edit</MenuItem>
    <MenuItem>Delete</MenuItem>
  </IconMenu>
);

class MainPanel extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      sermons: [],
      loading: true
    }
  }

  componentWillMount() {

  }

  componentWillUnMount() {
    this.props.base.removeBinding(this.ref);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps && nextProps.selectedCongregation && nextProps.selectedCongregation.bucketID) {
        this.setState({
          loading:true
        });
      this.ref = this.props.base.fetch('sermons', {
        context: this,
        state: 'sermons',
        asArray: true,
        queries: {
          limitToLast: 20,
          orderByChild: 'bucketID',
          equalTo: nextProps.selectedCongregation.bucketID
        },
        then(data){
            this.setState({
              sermons: data,
              loading:false
            });
        }
      });
    }
  }

  render() {

    const contentStyle = {  transition: 'margin-left 450ms cubic-bezier(0.23, 1, 0.32, 1)' };
    if (this.props.sideMenuOpen) {
      contentStyle.marginLeft = '256px';
    }

    if (this.state.loading === true) {
      return
Loading...
;
    }
    else {
      return  (

        <List>
          {this.state.sermons.filter((sermon) => (
            sermon.published === true
          ))
            .map((sermon) => (
            <ListItem
              key={sermon.key}
              rightIconButton={rightIconMenu}
              primaryText={

                  {sermon.minister} : {new Date(sermon.date).toLocaleDateString()} : {sermon.bibleText}

              }
              secondaryText={

                  {sermon.comments}

              }
              secondaryTextLines={1}
            />
          ))
        }
        </List>

      )
    }
  }
}

export default MainPanel
<|endoftext|>


<commit_before><commit_msg>verify(): Check the type matches variable decl<commit_after><|endoftext|>


<commit_before>app.service('utils', function(validationService) {
    var self = this;

    /* This function takes care
    of boolean issues */
    self.processBool = function(x) {

        if (typeof(x) === 'boolean') {
            return x;
        }

        if (typeof(x) === 'string') {

            /* Change x to Uppercase
            for uniform comparison */
            x = x.toUpperCase();

            /* Set values for which
            to consider true */
            var trueArr = ['TRUE', 'YES', 'Y'];

            /* Find x in above array */
            if (trueArr.indexOf(x) > -1) {
                return true;
            }

        }

        /* If nothing matches */
        return false;
    };

    /* This function converts passed
    string to uppercase */
    self.upperCase = function(x) {

        if (typeof x === 'string') {
            return x.toUpperCase();
        }

        return x;
    };

    /* This function validates the
    data and returns object containing
    status and error in case */
    self.validate = function(value, attrs) {

        /* Define return object */
        var response = {
            status: 'success',
            error: ''
        };

        var x;

        for (var key in attrs) {

            if (response.status === 'fail') {
                break;
            }

            switch (key) {

                /* Required Validation Case */
                case 'required':
                    x = validationService.required(value);

                    if (!x) {
                        response.status = 'fail';
                        response.error = 'This field is mandatory';
                    }

                    break;

                /* Alphanumeric Validation Case */
                case 'alphanumeric':
                    x = validationService.alphanumeric(value);

                    if (!x) {
                        response.status = 'fail';
                        response.error = 'Only alphanumeric values allowed';
                    }

                    break;

                /* No Multispace Validation Case */
                case 'nomultispace':
                    x = validationService.multispace(value);

                    if (x) {
                        response.status = 'fail';
                        response.error = 'Multiple space not allowed';
                    }

                    break;

                /* Numeric Validation Case */
                case 'numeric':
                    x = validationService.numeric(value);

                    if (!x) {
                        response.status = 'fail';
                        response.error = 'Only numeric values allowed';
                    }

                    break;

                default: break;
            }

        }

        return response;

    };

    /**
     * Adjust viewport height
     */
    self.fixLayout = function() {

        // Window Height
        var t = $(window).height();

        // Set height
        $('.content-wrapper').height(t - 101);
        $('.content-wrapper').css('margin-left', '0px');
        $('.main-footer').css('margin-left', '0px');

    };

});
<commit_msg>:bug: Fixed a bug that was causing view port not to display properly<commit_after>app.service('utils', function(validationService) {
    var self = this;

    /* This function takes care
    of boolean issues */
    self.processBool = function(x) {

        if (typeof(x) === 'boolean') {
            return x;
        }

        if (typeof(x) === 'string') {

            /* Change x to Uppercase
            for uniform comparison */
            x = x.toUpperCase();

            /* Set values for which
            to consider true */
            var trueArr = ['TRUE', 'YES', 'Y'];

            /* Find x in above array */
            if (trueArr.indexOf(x) > -1) {
                return true;
            }

        }

        /* If nothing matches */
        return false;
    };

    /* This function converts passed
    string to uppercase */
    self.upperCase = function(x) {

        if (typeof x === 'string') {
            return x.toUpperCase();
        }

        return x;
    };

    /* This function validates the
    data and returns object containing
    status and error in case */
    self.validate = function(value, attrs) {

        /* Define return object */
        var response = {
            status: 'success',
            error: ''
        };

        var x;

        for (var key in attrs) {

            if (response.status === 'fail') {
                break;
            }

            switch (key) {

                /* Required Validation Case */
                case 'required':
                    x = validationService.required(value);

                    if (!x) {
                        response.status = 'fail';
                        response.error = 'This field is mandatory';
                    }

                    break;

                /* Alphanumeric Validation Case */
                case 'alphanumeric':
                    x = validationService.alphanumeric(value);

                    if (!x) {
                        response.status = 'fail';
                        response.error = 'Only alphanumeric values allowed';
                    }

                    break;

                /* No Multispace Validation Case */
                case 'nomultispace':
                    x = validationService.multispace(value);

                    if (x) {
                        response.status = 'fail';
                        response.error = 'Multiple space not allowed';
                    }

                    break;

                /* Numeric Validation Case */
                case 'numeric':
                    x = validationService.numeric(value);

                    if (!x) {
                        response.status = 'fail';
                        response.error = 'Only numeric values allowed';
                    }

                    break;

                default: break;
            }

        }

        return response;

    };

    /**
     * Adjust viewport height
     */
    self.fixLayout = function() {

        // Window Height
        var t = $(window).height();

        // Set height
        $('.content-wrapper').css('min-height', `${t - 101}px`);
        $('.content-wrapper').css('margin-left', '0px');
        $('.main-footer').css('margin-left', '0px');

    };

});
<|endoftext|>


<commit_before>describe("About Expects", function() {

  // We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(false).toBeTruthy(); // This should be true
  });

  // To understand reality, we must compare our expectations against reality.
  it("should expect equality", function() {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  // Some ways of asserting equality are better than others.
  it("should assert equality a better way", function() {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  // Sometimes you need to be precise about what you "type".
  it("should assert equality with ===", function() {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  // Sometimes we will ask you to fill in the values.
  it("should have filled in values", function() {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<commit_msg>Expect truthiness<commit_after>describe("About Expects", function() {

  // We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(true).toBeTruthy(); // This should be true
  });

  // To understand reality, we must compare our expectations against reality.
  it("should expect equality", function() {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  // Some ways of asserting equality are better than others.
  it("should assert equality a better way", function() {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  // Sometimes you need to be precise about what you "type".
  it("should assert equality with ===", function() {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  // Sometimes we will ask you to fill in the values.
  it("should have filled in values", function() {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(false).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<commit_msg>It now expects "true"<commit_after>describe("About Expects", function() {

  //We shall contemplate truth by testing reality, via spec expectations.
  it("should expect true", function() {
    expect(true).toBeTruthy(); //This should be true
  });

  //To understand reality, we must compare our expectations against reality.
  it("should expect equality", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

	  expect(actualValue === expectedValue).toBeTruthy();
  });

  //Some ways of asserting equality are better than others.
  it("should assert equality a better way", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = 1 + 1;

  // toEqual() compares using common sense equality.
	  expect(actualValue).toEqual(expectedValue);
  });

  //Sometimes you need to be really exact about what you "type".
  it("should assert equality with ===", function () {
	  var expectedValue = FILL_ME_IN;
	  var actualValue = (1 + 1).toString();

  // toBe() will always use === to compare.
	  expect(actualValue).toBe(expectedValue);
  });

  //Sometimes we will ask you to fill in the values.
  it("should have filled in values", function () {
	  expect(1 + 1).toEqual(FILL_ME_IN);
  });
});
<|endoftext|>


<commit_before>l10n.lftpd = { lang: 'en'
    ,modname: 'Data exchange'
    ,tooltip: "launch control of suprolftpd module"
    ,title: 'SUPROs use `lftp` for data exchange via Internet'
    ,refreshLog: 'Refresh log'
    ,noload: '== No log info loaded =='
    ,channels: 'data exchange channels'
    ,chaname: 'channel name'
    ,toolHelp: 'upload and download channels are independent but run and quit togather'
    ,go: 'Start: info exchange'
    ,stop: 'Finish: info exchange'
    ,run:  'Run lftp'
    ,quit: 'Quit lftp'
    ,test: 'Test'
    ,sts:{
        transport:'trasport',
        download:'lftp download',
        upload:'lftp upload',
        r:'Runs',
        q:'Quit',
        f:'Feeds files',
        g:'Go'
        s:'Configured, no autorun, stops',
        e:'Error',
        b:'Exists, is not configured'
    }
    // backend
    ,'~lftp_not_found': 'No lftp was found or wrong `id`'
    ,zzzz: 'warning: Remote peer (object) does not download data!'
    ,ENOENT: 'File not found'
}
<commit_msg>l10n: fix typo<commit_after>l10n.lftpd = { lang: 'en'
    ,modname: 'Data exchange'
    ,tooltip: "launch control of suprolftpd module"
    ,title: 'SUPROs use `lftp` for data exchange via Internet'
    ,refreshLog: 'Refresh log'
    ,noload: '== No log info loaded =='
    ,channels: 'data exchange channels'
    ,chaname: 'channel name'
    ,toolHelp: 'upload and download channels are independent but run and quit togather'
    ,go: 'Start: info exchange'
    ,stop: 'Finish: info exchange'
    ,run:  'Run lftp'
    ,quit: 'Quit lftp'
    ,test: 'Test'
    ,sts:{
        transport:'trasport',
        download:'lftp download',
        upload:'lftp upload',
        r:'Runs',
        q:'Quit',
        f:'Feeds files',
        g:'Go',
        s:'Configured, no autorun, stops',
        e:'Error',
        b:'Exists, is not configured'
    }
    // backend
    ,'~lftp_not_found': 'No lftp was found or wrong `id`'
    ,zzzz: 'warning: Remote peer (object) does not download data!'
    ,ENOENT: 'File not found'
}
<|endoftext|>


<commit_before>import Lists    from '../actions/lists'
import contrast from '../../lib/contrast'

export default {

  getInitialState() {
    return []
  },

  register() {
    return {
      [Lists.add]    : this.add,
      [Lists.remove] : this.remove
    }
  },

  add(state, params) {
    let record = Object.assign({
      color : '#aaaaaa',
    }, params)

    record.contrast = contrast(record.color)

    return state.concat(record)
  },

  remove(state, id) {
    return state.filter(i => i.id !== id)
  }

}
<commit_msg>Remove trailing comma in advanced example<commit_after>import Lists    from '../actions/lists'
import contrast from '../../lib/contrast'

export default {

  getInitialState() {
    return []
  },

  register() {
    return {
      [Lists.add]    : this.add,
      [Lists.remove] : this.remove
    }
  },

  add(state, params) {
    let record = Object.assign({
      color : '#aaaaaa'
    }, params)

    record.contrast = contrast(record.color)

    return state.concat(record)
  },

  remove(state, id) {
    return state.filter(i => i.id !== id)
  }

}
<|endoftext|>


<commit_before>#!/usr/bin/env node

require('pkginfo')(module, 'version');
var fs = require('fs');
var jsonfile = require('jsonfile');
var path = require('path');
var logger = require('./log');

var utils = require('./utils');
var ProjenodyPackage = require('./projenody-package');

function writeProjenodyPackage(pkg) {
    var isMain = pkg.isMain;
    try {
        delete pkg.isMain;
        jsonfile.writeFile(path.normalize(pkg.packageProjenodyFile), pkg, function (error) {
            if (error) {
                logger.error("Could not write projenody.json file.  Error: " + JSON.stringify(error));
                process.exit(1);
            }
            logger.info("Generated the projenody file at " + process.cwd());
        });
    }
    finally {
        pkg.isMain = isMain;
    }
}

function getProjenodyPackage(directory) {
    try {
        var p = require(path.normalize(directory + '/projenody.json'));
        var npmPackage = require(path.normalize(directory + '/package.json'));
        p.name = p.name || npmPackage.name;
        return new ProjenodyPackage(p);
    } catch (e) {
        return null;
    }
}

function initProjenodyPackage(pkg) {
    if (pkg) {
        return;
    }

    try {
        var obj = jsonfile.readFileSync(path.normalize(process.cwd() + '/package.json'));
        pkg = new ProjenodyPackage({name: obj.name});
        writeProjenodyPackage(pkg);
    } catch (e) {
        logger.error('Failed to create projenody.json file.');
    }
}

function linkProjenodyPackage(pkg) {
    if (!pkg) {
        logger.info('Cannot link from null package.');
        return;
    }
    logger.info("Checking existing symlinks and updating as needed...");

    logger.debug("Attempting to create the symlinks.");

    utils.checkDirectory(pkg.unityProjectAssetsPath);
    // utils.checkDirectory(ProjenodyPackage.unityProjectSettingsPath);

    // Create the directories
    utils.createLink(pkg.packageAssetPath, pkg.unityAssetsPath);
    utils.createLink(pkg.packageProjectSettingsPath, pkg.unityProjectSettingsPath);

    linkDirectories(pkg.packageBasePath);

    logger.debug('Done creating symlinks.');
}

var pkg = getProjenodyPackage(process.cwd());
pkg.isMain = true;
initProjenodyPackage(pkg);
linkProjenodyPackage(pkg);

function linkDirectories(directory) {
    logger.debug("Linking directory " + directory);
    directory = path.normalize(directory + '/node_modules/');

    if (fs.existsSync(directory)) {
        var directories = fs.readdirSync(directory);
        if (directories) {
            linkDirectories(directories);

            for (var dir of directories) {
                dir = path.normalize(pkg.packageModules + '/' + dir);
                logger.debug("Looking at directory: " + dir);

                var ppkg = getProjenodyPackage(dir);
                if (!ppkg) {
                    // TODO: Check for an Assets folder in the root.
                    logger.debug("Found non-projenody package.  Leaving it.");
                    continue;
                }

                logger.debug("Examining " + ppkg.name + " with asset path " + ppkg.packageAssetPath);
                var pluginOverride = pkg.pluginOverrides.indexOf(ppkg.name) > -1;
                utils.createLink(ppkg.packageAssetPath, pkg.unityProjectAssetsPath + '/' + (pluginOverride ? 'Plugins/' : '').toString() + ppkg.targetFolder);

                linkDirectories(dir);
            }
        }
    }
}<commit_msg>Fixing a bug in the package definition.<commit_after>#!/usr/bin/env node

require('pkginfo')(module, 'version');
var fs = require('fs');
var jsonfile = require('jsonfile');
var path = require('path');
var logger = require('./log');

var utils = require('./utils');
var ProjenodyPackage = require('./projenody-package');

function writeProjenodyPackage(pkg) {
    var isMain = pkg.isMain;
    try {
        delete pkg.isMain;
        jsonfile.writeFile(path.normalize(pkg.packageProjenodyFile), pkg, function (error) {
            if (error) {
                logger.error("Could not write projenody.json file.  Error: " + JSON.stringify(error));
                process.exit(1);
            }
            logger.info("Generated the projenody file at " + process.cwd());
        });
    }
    finally {
        pkg.isMain = isMain;
    }
}

function getProjenodyPackage(directory) {
    try {
        var p = require(path.normalize(directory + '/projenody.json'));
        var npmPackage = require(path.normalize(directory + '/package.json'));
        p.name = p.name || npmPackage.name;
        return new ProjenodyPackage(p);
    } catch (e) {
        return null;
    }
}

function initProjenodyPackage(pkg) {
    if (pkg) {
        return;
    }

    try {
        var obj = jsonfile.readFileSync(path.normalize(process.cwd() + '/package.json'));
        pkg = new ProjenodyPackage({name: obj.name});
        writeProjenodyPackage(pkg);
    } catch (e) {
        logger.error('Failed to create projenody.json file.');
    }
}

function linkProjenodyPackage(pkg) {
    if (!pkg) {
        logger.info('Cannot link from null package.');
        return;
    }
    logger.info("Checking existing symlinks and updating as needed...");

    logger.debug("Attempting to create the symlinks.");

    utils.checkDirectory(pkg.unityProjectAssetsPath);
    // utils.checkDirectory(ProjenodyPackage.unityProjectSettingsPath);

    // Create the directories
    utils.createLink(pkg.packageAssetPath, pkg.unityAssetsPath);
    utils.createLink(pkg.packageProjectSettingsPath, pkg.unityProjectSettingsPath);

    linkDirectories(pkg.packageBasePath);

    logger.debug('Done creating symlinks.');
}

var pkg = getProjenodyPackage(process.cwd());
initProjenodyPackage(pkg);
pkg.isMain = true;
linkProjenodyPackage(pkg);

function linkDirectories(directory) {
    logger.debug("Linking directory " + directory);
    directory = path.normalize(directory + '/node_modules/');

    if (fs.existsSync(directory)) {
        var directories = fs.readdirSync(directory);
        if (directories) {
            linkDirectories(directories);

            for (var dir of directories) {
                dir = path.normalize(pkg.packageModules + '/' + dir);
                logger.debug("Looking at directory: " + dir);

                var ppkg = getProjenodyPackage(dir);
                if (!ppkg) {
                    // TODO: Check for an Assets folder in the root.
                    logger.debug("Found non-projenody package.  Leaving it.");
                    continue;
                }

                logger.debug("Examining " + ppkg.name + " with asset path " + ppkg.packageAssetPath);
                var pluginOverride = pkg.pluginOverrides.indexOf(ppkg.name) > -1;
                utils.createLink(ppkg.packageAssetPath, pkg.unityProjectAssetsPath + '/' + (pluginOverride ? 'Plugins/' : '').toString() + ppkg.targetFolder);

                linkDirectories(dir);
            }
        }
    }
}<|endoftext|>


<commit_before>// config/database.js
const mongoose = require('mongoose');

const url = `mongodb+srv://${process.env.MLAB_USER}:${process.env.MLAB_PWD}@${process.env.MLAB_URL}`;

module.exports = { configureDatabase, url };

function configureDatabase() {
  // Permet de spécifier un autre moteur de promesses que mPromise
  // mongoose.Promise = global.Promise;

  // Connexion à la base de données
  mongoose
    .set('useNewUrlParser', true)
    .set('useUnifiedTopology', true)
    .connect(url)
    .then(() => console.log('Connected to database.'))
    .catch((error) => console.log("Couldn't connect to database.\n", error));

  return mongoose;
}
<commit_msg>git foo<commit_after>// config/database.js
const mongoose = require('mongoose');

const url = `mongodb+srv://${process.env.MLAB_USER}:${process.env.MLAB_PWD}@${process.env.MLAB_URL}`;

module.exports = { configureDatabase, url };

function configureDatabase() {
  // Permet de spécifier un autre moteur de promesses que mPromise
  mongoose.Promise = global.Promise;

  // Connexion à la base de données
  mongoose
    .set('useNewUrlParser', true)
    .set('useUnifiedTopology', true)
    .connect(url)
    .then(() => console.log('Connected to database.'))
    .catch((error) => console.log("Couldn't connect to database.\n", error));

  return mongoose;
}
<|endoftext|>


<commit_before>function getError(config) {
  return function error(err, req, res, next) {

    if(!err) {
      err = new HTTPError('Not Found', 404, '/')
    }

    let d = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

    if(!config.quiet)
      if(config.dev)
        console.error(d, err.stack);
      else
        console.error(d, err.code + ' - ' + err.message)

    return res.format({
      'text/plain': function() {
        return res.status(err.code).send(err.message).end()
      },
      'text/html': function() {
        req.flash('error', err.message)

        return res.redirect(err.redirect)
      },
      'application/json': function() {
        return res.status(err.code).json(err).end()
      },
      'default': function() {
        return res.status(406).send('Not acceptable')
      }
    })
  }
}

export {getError}
<commit_msg>fix(): No text/plain format, 500 if no errors 404 are handled by expresso (http://expressjs.com/starter/faq.html#how-do-you-handle-404s)<commit_after>function getError(config) {
  return function error(err, req, res, next) {

    if(!err) {
      err = new HTTPError('No errors - please report', 500, '/')
    }

    let d = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

    if(!config.quiet)
      if(config.dev)
        console.error(d, err.stack);
      else
        console.error(d, err.code + ' - ' + err.message)

    return res.format({
      'text/html': function() {
        req.flash('error', err.message)

        return res.redirect(err.redirect)
      },
      'application/json': function() {
        return res.status(err.code).json(err).end()
      },
      'default': function() {
        return res.status(406).send('Not acceptable')
      }
    })
  }
}

export {getError}
<|endoftext|>


<commit_before>define([
  './levels',
  'dojo/keys'
], function(levels, keys){

  'use strict';

  return function handleInput(im){
    //start game
    if(this.state.screen === 0 && (im.mouseAction.isPressed())){
      this.state.screen = 1;
      this.loadLevel(0);
    }

    //move paddles
    var position = im.mouseAction.position;
    if(position){
      var paddle = this.entities.paddle;
      if(this.state.screen === 1 && paddle){
        var xPos = position.x / this.box.scale;
        if(xPos < paddle.halfWidth){
          xPos = paddle.halfWidth;
        } else if(xPos > this.width / this.box.scale - paddle.halfWidth){
          xPos = this.width / this.box.scale - paddle.halfWidth;
        }
        if(this.state.launchMillis <= 0){
          this.box.setPosition(paddle.id, xPos, paddle.y);
        } else {
          paddle.x = xPos; //force update to render paddle movement during countdown
        }
      }
    }

    //advance the levels
    if(im.keyActions[keys.LEFT_ARROW].getAmount() && this.state.currentLevel > 0){
      this.state.currentLevel--;
      this.loadLevel(this.state.currentLevel);
    } else if(im.keyActions[keys.RIGHT_ARROW].getAmount() && this.state.currentLevel < (levels.length - 1)){
      this.state.currentLevel++;
      this.loadLevel(this.state.currentLevel);
    }
  };

});<commit_msg>use setAngularVelocity to stop shakey paddle<commit_after>define([
  './levels',
  'dojo/keys'
], function(levels, keys){

  'use strict';

  return function handleInput(im){
    //start game
    if(this.state.screen === 0 && (im.mouseAction.isPressed())){
      this.state.screen = 1;
      this.loadLevel(0);
    }

    //move paddles
    var position = im.mouseAction.position;
    if(position){
      var paddle = this.entities.paddle;
      if(this.state.screen === 1 && paddle){
        var xPos = position.x / this.box.scale;
        if(xPos < paddle.halfWidth){
          xPos = paddle.halfWidth;
        } else if(xPos > this.width / this.box.scale - paddle.halfWidth){
          xPos = this.width / this.box.scale - paddle.halfWidth;
        }
        if(this.state.launchMillis <= 0){
          this.box.setPosition(paddle.id, xPos, paddle.y);
          this.box.setAngularVelocity(paddle.id, 0);
        } else {
          paddle.x = xPos; //force update to render paddle movement during countdown
        }
      }
    }

    //advance the levels
    if(im.keyActions[keys.LEFT_ARROW].getAmount() && this.state.currentLevel > 0){
      this.state.currentLevel--;
      this.loadLevel(this.state.currentLevel);
    } else if(im.keyActions[keys.RIGHT_ARROW].getAmount() && this.state.currentLevel < (levels.length - 1)){
      this.state.currentLevel++;
      this.loadLevel(this.state.currentLevel);
    }
  };

});<|endoftext|>


<commit_before>
/**
 * @package Team Page
 * @version 5.0
 * @author Diego Andrés <diegoandres_cortes@outlook.com>
 * @copyright Copyright (c) 2020, SMF Tricks
 * @license https://www.mozilla.org/en-US/MPL/2.0/
 */

// Sortable for the groups management
$(document).ready(function() {
	// Left
	$('#tp_group_sort_left').sortable({
		connectWith: '.information',
		placeholder: 'tp_placeholder_sort',
		update: function( event, ui ) {
			savePositions($("#tp_group_sort_left").sortable('toArray', {attribute : 'group-id'}), 'left');
		}
	}).disableSelection();

	// Right
	$('#tp_group_sort_right').sortable({
		connectWith: '.information',
		placeholder: 'tp_placeholder_sort',
		update: function( event, ui ) {
			savePositions($("#tp_group_sort_right").sortable('toArray', {attribute : 'group-id'}), 'right');
		}
	}).disableSelection();

	// Bottom
	$('#tp_group_sort_bottom').sortable({
		connectWith: '.information',
		placeholder: 'tp_placeholder_sort',
		update: function( event, ui ) {
			savePositions($("#tp_group_sort_bottom").sortable('toArray', {attribute : 'group-id'}), 'bottom');
		}
	}).disableSelection();

	// All Groups
	$('#tp_group_sort_all').sortable({
		connectWith: '.information',
		placeholder: 'tp_placeholder_sort',
		receive: function( event, ui ) {
			savePositions($("#tp_group_sort_all").sortable('toArray', {attribute : 'group-id'}), 'all', true);
		}
	}).disableSelection();
});

// Update and save order
function savePositions(tp_groups, placement, group_delete = false) {
	var groups = [];
	var direction = (placement != undefined ? placement : 'left');

	if (tp_groups != undefined)
		groups = tp_groups;

	if (groups.length > 0) {
		$.ajax({
			url: smf_scripturl + "?action=admin;area=teampage;sa=sort",
			type: 'POST',
			dataType: 'json',
			data: {
				page: document.getElementById('tp_manage_groups').getAttribute('page-id'),
				delete: (group_delete == true ? 1 : 0),
				groups: groups,
				placement: direction,
			}, success: function(response) {
				console.log(response);
			}
		});
	}
}<commit_msg>typo<commit_after>
/**
 * @package Team Page
 * @version 5.0
 * @author Diego Andrés <diegoandres_cortes@outlook.com>
 * @copyright Copyright (c) 2020, SMF Tricks
 * @license https://www.mozilla.org/en-US/MPL/2.0/
 */

// Sortable for the groups management
$(document).ready(function() {
	// Left
	$('#tp_group_sort_left').sortable({
		connectWith: '.information',
		placeholder: 'tp_placeholder_sort',
		update: function( event, ui ) {
			savePositions($("#tp_group_sort_left").sortable('toArray', {attribute : 'group-id'}), 'left');
		}
	}).disableSelection();

	// Right
	$('#tp_group_sort_right').sortable({
		connectWith: '.information',
		placeholder: 'tp_placeholder_sort',
		update: function( event, ui ) {
			savePositions($("#tp_group_sort_right").sortable('toArray', {attribute : 'group-id'}), 'right');
		}
	}).disableSelection();

	// Bottom
	$('#tp_group_sort_bottom').sortable({
		connectWith: '.information',
		placeholder: 'tp_placeholder_sort',
		update: function( event, ui ) {
			savePositions($("#tp_group_sort_bottom").sortable('toArray', {attribute : 'group-id'}), 'bottom');
		}
	}).disableSelection();

	// All Groups
	$('#tp_group_sort_all').sortable({
		connectWith: '.information',
		placeholder: 'tp_placeholder_sort',
		receive: function( event, ui ) {
			savePositions($("#tp_group_sort_all").sortable('toArray', {attribute : 'group-id'}), 'all', true);
		}
	}).disableSelection();
});

// Update and save order
function savePositions(tp_groups, placement, group_delete = false) {
	var groups = [];
	var direction = (placement != undefined ? placement : 'left');

	if (tp_groups != undefined)
		groups = tp_groups;

	if (groups.length > 0) {
		$.ajax({
			url: smf_scripturl + "?action=admin;area=teampage;sa=sort",
			type: 'POST',
			dataType: 'json',
			data: {
				page: document.getElementById('tp_manage_Groups').getAttribute('page-id'),
				delete: (group_delete == true ? 1 : 0),
				groups: groups,
				placement: direction,
			}, success: function(response) {
				console.log(response);
			}
		});
	}
}<|endoftext|>


<commit_before>export { MultiplyTwoTensors };

import * as Pool from "../../util/Pool.js";
import * as TensorPlaceholder from "../TensorPlaceholder.js";
import * as BoundsArraySet from "../BoundsArraySet.js";
import { Root } from "./Operation_Base.js";

/**
 * Multiply two tensor3d. They should have the same channel count. Their ( height x width ) should be either the same or one is ( 1 x 1 ).
 * It could destroy one or two of the input tensors.
 *
 * @member {boolean} bKeepInputTensor0
 *   If false, the first input tensor will be disposed after multiplying. If true, the first input tensor will be kept after multiplying.
 *
 * @member {boolean} bKeepInputTensor1
 *   If false, the second input tensor will be disposed after multiplying. If true, the second input tensor will be kept after multiplying.
 *
 * @member {function} apply
 *   This is a method. It processes this.input0.realTensor and this.input1.realTensor as inputTensors. It puts to this.output0.realTensor
 * as outputTensor. Both inputTensors are tf.tensor3d and represents an images ( height x width x channel ) which will be multiplied. They
 * should have the same channel count. Their ( height x width ) should be either the same or one is ( 1 x 1 ). The outputTensor
 * (tf.tensor3d) represents the result of multiplying the two inputs. The inputTensors may or may not be disposed. In fact, this method
 * calls one of Multiply_and_keep0_keep1(), Multiply_and_keep0_destroy1(), Multiply_and_destroy0_keep1(), Multiply_and_destroy0_destroy1()
 * according to the parameters.
 *
 */
class MultiplyTwoTensors extends Root {

  /**
   * Used as default Operation.MultiplyTwoTensors provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Operation.MultiplyTwoTensors.Pool", MultiplyTwoTensors, MultiplyTwoTensors.setAsConstructor );

  /**
   */
  constructor(
    inputTensorPlaceholder0, inputTensorPlaceholder1,
    bKeepInputTensor0, bKeepInputTensor1
  ) {
    super( inputTensorPlaceholder0, inputTensorPlaceholder1, 1 );
    MultiplyTwoTensors.setAsConstructor_self.call(
      this, inputTensorPlaceholder0, inputTensorPlaceholder1, bKeepInputTensor0, bKeepInputTensor1 );
  }

  /** @override */
  static setAsConstructor(
    inputTensorPlaceholder0, inputTensorPlaceholder1,
    bKeepInputTensor0, bKeepInputTensor1
  ) {
    super.setAsConstructor( inputTensorPlaceholder0, inputTensorPlaceholder1, 1 );
    MultiplyTwoTensors.setAsConstructor_self.call(
      this, inputTensorPlaceholder0, inputTensorPlaceholder1, bKeepInputTensor0, bKeepInputTensor1 );
    return this;
  }

  /** @override */
  static setAsConstructor_self(
    inputTensorPlaceholder0, inputTensorPlaceholder1,
    bKeepInputTensor0, bKeepInputTensor1
  ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    MultiplyTwoTensors.adjust_pfn.call( this );
    MultiplyTwoTensors.setup_BoundsArraySet.call( this );
    MultiplyTwoTensors.setup_output0_TensorPlaceholder.call( this );
  }

  /** @override */
  disposeResources() {

    if ( this.boundsArraySet ) {
      this.boundsArraySet.disposeResources_and_recycleToPool();
      this.boundsArraySet = null;
    }

    this.apply = null;

    super.disposeResources();
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor0( bKeepInputTensor0 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    MultiplyTwoTensors.adjust_pfn.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor1( bKeepInputTensor1 ) {
    this.bKeepInputTensor1 = bKeepInputTensor1;
    MultiplyTwoTensors.adjust_pfn.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    MultiplyTwoTensors.adjust_pfn.call( this );
  }

  /** Set this.apply according to this.bKeepInputTensor0 and this.bKeepInputTensor1. */
  static adjust_pfn() {
    if ( this.bKeepInputTensor0 ) {
      if ( this.bKeepInputTensor1 ) {
        this.apply = MultiplyTwoTensors.Multiply_and_keep0_keep1;
      } else {
        this.apply = MultiplyTwoTensors.Multiply_and_keep0_destroy1;
      }
    } else {
      if ( this.bKeepInputTensor1 ) {
        this.apply = MultiplyTwoTensors.Multiply_and_destroy0_keep1;
      } else {
        this.apply = MultiplyTwoTensors.Multiply_and_destroy0_destroy1;
      }
    }
  }

  /** Create this.boundsArraySet. */
  static setup_BoundsArraySet() {
    let inputScaleBoundsArray0 = this.input0.scaleBoundsArray;
    let inputScaleBoundsArray1 = this.input1.scaleBoundsArray;

    if ( inputScaleBoundsArray0.channelCount != inputScaleBoundsArray1.channelCount )
      throw Error( `MultiplyTwoTensors.setup_BoundsArraySet(): `
        + `input0 channel count ( ${inputScaleBoundsArray0.channelCount} ) should be the same as `
        + `input1 channel count ( ${inputScaleBoundsArray1.channelCount} ).`
      );

    this.boundsArraySet = BoundsArraySet.InputsOutputs.Pool.get_or_create_by( inputScaleBoundsArray0, inputScaleBoundsArray1,
      inputScaleBoundsArray0.channelCount
    );

    this.boundsArraySet.output0
      .set_all_byScaleBoundsArray( inputScaleBoundsArray0 )
      .multiply_all_byScaleBoundsArray_all( inputScaleBoundsArray1 );
  }

  /** Setup this.output0.
   * This method should be called after setup_BoundsArraySet() because it uses BoundsArrarySet.
   */
  static setup_output0_TensorPlaceholder() {

    // 1. Only same channel count multiplying is supported.
    if ( this.input0.channelCount == this.input1.channelCount ) {

      this.output0.channelCount = this.input0.channelCount; // Result always has the same channel count.

      // 1.1 Multiplying two same dimension tensors. The result dimension is the same of any one.
      if ( ( this.input0.height == this.input1.height ) && ( this.input0.width == this.input1.width ) ) {
        this.output0.height = this.input0.height;
        this.output0.width = this.input0.width;

      // 1.2 Multiplying by broadcasting input0 to input1. The result dimension is the same as input1 (the larger one).
      } else if ( ( this.input0.height == 1 ) && ( this.input0.width == 1 ) ) {
        this.output0.height = this.input1.height;
        this.output0.width = this.input1.width;

      // 1.3 Multiplying by broadcasting input1 to input0. The result dimension is the same as input0 (the larger one).
      } else if ( ( this.input1.height == 1 ) && ( this.input1.width == 1 ) ) {
        this.output0.height = this.input0.height;
        this.output0.width = this.input0.width;

      // 1.4 Unsupported multiplying (height and width).
      } else {
        throw Error(
          `Operation.MultiplyTwoTensors.setup_output0_TensorPlaceholder(): `
            + `input0 ( height, width ) = ( ${this.input0.height}, ${this.input0.width} ) and `
            + `input1 ( height, width ) = ( ${this.input1.height}, ${this.input1.width} ) `
            + `should be either the same or one is ( 1, 1 ) for broadcating.`
        );
      }

      // Only if both inputs' lower half and higher half channel count are the same, they are passed through to output.
      // Otherwise, absent them in the output.
      {
        if ( this.input0.channelCount_lowerHalf == this.input1.channelCount_lowerHalf ) {
          this.output0.channelCount_lowerHalf = this.input0.channelCount_lowerHalf;
        } else {
          this.output0.channelCount_lowerHalf = undefined;
        }

        if ( this.input0.channelCount_higherHalf == this.input1.channelCount_higherHalf ) {
          this.output0.channelCount_higherHalf = this.input0.channelCount_higherHalf;
        } else {
          this.output0.channelCount_higherHalf = undefined;
        }
      }

      this.output0.ScaleBoundsArray_set_without_clone( this.boundsArraySet.output0 );

      // Release for reducing memory usage. (Since it has been transferred to inside the output tensor placeholder.)
      {
        this.boundsArraySet.output0 = null; // Because it has already been transferred to TensorPlaceholder this.output0
        this.boundsArraySet.disposeResources_and_recycleToPool();
        this.boundsArraySet = null;
      }

    // 2. Unsupported multiplying (different channel count).
    } else {
      throw Error(
        `Operation.MultiplyTwoTensors.setup_output0_TensorPlaceholder(): `
          + `input0 channel count ( ${this.input0.channelCount} ) and `
          + `input1 channel count ( ${this.input1.channelCount} ) `
          + `should be the same.`
      );
    }
  }

  /** Multiply. (Both the inputTensor0 and inputTensor1 will not be disposed. */
  static Multiply_and_keep0_keep1() {
    this.output0.realTensor = tf.mul( this.input0.realTensor, this.input1.realTensor );
  }

  /** Multiply. (The inputTensors0 will not be disposed. The inputTensor1 will be disposed. */
  static Multiply_and_keep0_destroy1() {
    this.output0.realTensor = tf.mul( this.input0.realTensor, this.input1.realTensor );
    this.input1.realTensor.dispose();
  }

  /** Multiply. (The inputTensor0 will be disposed. The inputTensor1 will not be disposed. */
  static Multiply_and_destroy0_keep1() {
    this.output0.realTensor = tf.mul( this.input0.realTensor, this.input1.realTensor );
    this.input0.realTensor.dispose();
  }

  /** Multiply. (Both the inputTensor0 and inputTensor1 will be disposed. */
  static Multiply_and_destroy0_destroy1() {
    this.output0.realTensor = tf.mul( this.input0.realTensor, this.input1.realTensor );
    this.input0.realTensor.dispose();
    this.input1.realTensor.dispose();
  }

}

<commit_msg>Update Operation_MultiplyTwoTensors.js<commit_after>export { MultiplyTwoTensors };

import * as Pool from "../../util/Pool.js";
import * as TensorPlaceholder from "../TensorPlaceholder.js";
import * as BoundsArraySet from "../BoundsArraySet.js";
import { Root } from "./Operation_Base.js";

/**
 * Multiply two tensor3d. They should have the same channel count. Their ( height x width ) should be either the same or one is ( 1 x 1 ).
 * It could destroy one or two of the input tensors.
 *
 * @member {boolean} bKeepInputTensor0
 *   If false, the first input tensor will be disposed after multiplying. If true, the first input tensor will be kept after multiplying.
 *
 * @member {boolean} bKeepInputTensor1
 *   If false, the second input tensor will be disposed after multiplying. If true, the second input tensor will be kept after multiplying.
 *
 * @member {function} apply
 *   This is a method. It processes this.input0.realTensor and this.input1.realTensor as inputTensors. It puts to this.output0.realTensor
 * as outputTensor. Both inputTensors are tf.tensor3d and represents an images ( height x width x channel ) which will be multiplied. They
 * should have the same channel count. Their ( height x width ) should be either the same or one is ( 1 x 1 ). The outputTensor
 * (tf.tensor3d) represents the result of multiplying the two inputs. The inputTensors may or may not be disposed. In fact, this method
 * calls one of Multiply_and_keep0_keep1(), Multiply_and_keep0_destroy1(), Multiply_and_destroy0_keep1(), Multiply_and_destroy0_destroy1()
 * according to the parameters.
 *
 */
class MultiplyTwoTensors extends Root {

  /**
   * Used as default Operation.MultiplyTwoTensors provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Operation.MultiplyTwoTensors.Pool", MultiplyTwoTensors, MultiplyTwoTensors.setAsConstructor );

  /**
   */
  constructor(
    inputTensorPlaceholder0, inputTensorPlaceholder1,
    bKeepInputTensor0, bKeepInputTensor1
  ) {
    super( inputTensorPlaceholder0, inputTensorPlaceholder1, 1 );
    MultiplyTwoTensors.setAsConstructor_self.call(
      this, inputTensorPlaceholder0, inputTensorPlaceholder1, bKeepInputTensor0, bKeepInputTensor1 );
  }

  /** @override */
  static setAsConstructor(
    inputTensorPlaceholder0, inputTensorPlaceholder1,
    bKeepInputTensor0, bKeepInputTensor1
  ) {
    super.setAsConstructor( inputTensorPlaceholder0, inputTensorPlaceholder1, 1 );
    MultiplyTwoTensors.setAsConstructor_self.call(
      this, inputTensorPlaceholder0, inputTensorPlaceholder1, bKeepInputTensor0, bKeepInputTensor1 );
    return this;
  }

  /** @override */
  static setAsConstructor_self(
    inputTensorPlaceholder0, inputTensorPlaceholder1,
    bKeepInputTensor0, bKeepInputTensor1
  ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    MultiplyTwoTensors.adjust_pfn.call( this );
    MultiplyTwoTensors.setup_BoundsArraySet.call( this );
    MultiplyTwoTensors.setup_output0_TensorPlaceholder.call( this );
  }

  /** @override */
  disposeResources() {
    if ( this.boundsArraySet ) {
      this.boundsArraySet.disposeResources_and_recycleToPool();
      this.boundsArraySet = null;
    }
    super.disposeResources();
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor0( bKeepInputTensor0 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    MultiplyTwoTensors.adjust_pfn.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor1( bKeepInputTensor1 ) {
    this.bKeepInputTensor1 = bKeepInputTensor1;
    MultiplyTwoTensors.adjust_pfn.call( this );
  }

  /**
   * Adjust this.apply so that this.apply() will or will not dispose its inputTensors.
   */
  setKeepInputTensor( bKeepInputTensor0, bKeepInputTensor1 ) {
    this.bKeepInputTensor0 = bKeepInputTensor0;
    this.bKeepInputTensor1 = bKeepInputTensor1;
    MultiplyTwoTensors.adjust_pfn.call( this );
  }

  /** Set this.apply according to this.bKeepInputTensor0 and this.bKeepInputTensor1. */
  static adjust_pfn() {
    if ( this.bKeepInputTensor0 ) {
      if ( this.bKeepInputTensor1 ) {
        this.apply = MultiplyTwoTensors.Multiply_and_keep0_keep1;
      } else {
        this.apply = MultiplyTwoTensors.Multiply_and_keep0_destroy1;
      }
    } else {
      if ( this.bKeepInputTensor1 ) {
        this.apply = MultiplyTwoTensors.Multiply_and_destroy0_keep1;
      } else {
        this.apply = MultiplyTwoTensors.Multiply_and_destroy0_destroy1;
      }
    }
  }

  /** Create this.boundsArraySet. */
  static setup_BoundsArraySet() {
    let inputScaleBoundsArray0 = this.input0.scaleBoundsArray;
    let inputScaleBoundsArray1 = this.input1.scaleBoundsArray;

    if ( inputScaleBoundsArray0.channelCount != inputScaleBoundsArray1.channelCount )
      throw Error( `MultiplyTwoTensors.setup_BoundsArraySet(): `
        + `input0 channel count ( ${inputScaleBoundsArray0.channelCount} ) should be the same as `
        + `input1 channel count ( ${inputScaleBoundsArray1.channelCount} ).`
      );

    this.boundsArraySet = BoundsArraySet.InputsOutputs.Pool.get_or_create_by( inputScaleBoundsArray0, inputScaleBoundsArray1,
      inputScaleBoundsArray0.channelCount
    );

    this.boundsArraySet.output0
      .set_all_byScaleBoundsArray( inputScaleBoundsArray0 )
      .multiply_all_byScaleBoundsArray_all( inputScaleBoundsArray1 );
  }

  /** Setup this.output0.
   * This method should be called after setup_BoundsArraySet() because it uses BoundsArrarySet.
   */
  static setup_output0_TensorPlaceholder() {

    // 1. Only same channel count multiplying is supported.
    if ( this.input0.channelCount == this.input1.channelCount ) {

      this.output0.channelCount = this.input0.channelCount; // Result always has the same channel count.

      // 1.1 Multiplying two same dimension tensors. The result dimension is the same of any one.
      if ( ( this.input0.height == this.input1.height ) && ( this.input0.width == this.input1.width ) ) {
        this.output0.height = this.input0.height;
        this.output0.width = this.input0.width;

      // 1.2 Multiplying by broadcasting input0 to input1. The result dimension is the same as input1 (the larger one).
      } else if ( ( this.input0.height == 1 ) && ( this.input0.width == 1 ) ) {
        this.output0.height = this.input1.height;
        this.output0.width = this.input1.width;

      // 1.3 Multiplying by broadcasting input1 to input0. The result dimension is the same as input0 (the larger one).
      } else if ( ( this.input1.height == 1 ) && ( this.input1.width == 1 ) ) {
        this.output0.height = this.input0.height;
        this.output0.width = this.input0.width;

      // 1.4 Unsupported multiplying (height and width).
      } else {
        throw Error(
          `Operation.MultiplyTwoTensors.setup_output0_TensorPlaceholder(): `
            + `input0 ( height, width ) = ( ${this.input0.height}, ${this.input0.width} ) and `
            + `input1 ( height, width ) = ( ${this.input1.height}, ${this.input1.width} ) `
            + `should be either the same or one is ( 1, 1 ) for broadcating.`
        );
      }

      // Only if both inputs' lower half and higher half channel count are the same, they are passed through to output.
      // Otherwise, absent them in the output.
      {
        if ( this.input0.channelCount_lowerHalf == this.input1.channelCount_lowerHalf ) {
          this.output0.channelCount_lowerHalf = this.input0.channelCount_lowerHalf;
        } else {
          this.output0.channelCount_lowerHalf = undefined;
        }

        if ( this.input0.channelCount_higherHalf == this.input1.channelCount_higherHalf ) {
          this.output0.channelCount_higherHalf = this.input0.channelCount_higherHalf;
        } else {
          this.output0.channelCount_higherHalf = undefined;
        }
      }

      this.output0.ScaleBoundsArray_set_without_clone( this.boundsArraySet.output0 );

      // Release for reducing memory usage. (Since it has been transferred to inside the output tensor placeholder.)
      {
        this.boundsArraySet.output0 = null; // Because it has already been transferred to TensorPlaceholder this.output0
        this.boundsArraySet.disposeResources_and_recycleToPool();
        this.boundsArraySet = null;
      }

    // 2. Unsupported multiplying (different channel count).
    } else {
      throw Error(
        `Operation.MultiplyTwoTensors.setup_output0_TensorPlaceholder(): `
          + `input0 channel count ( ${this.input0.channelCount} ) and `
          + `input1 channel count ( ${this.input1.channelCount} ) `
          + `should be the same.`
      );
    }
  }

  /** Multiply. (Both the inputTensor0 and inputTensor1 will not be disposed. */
  static Multiply_and_keep0_keep1() {
    this.output0.realTensor = tf.mul( this.input0.realTensor, this.input1.realTensor );
  }

  /** Multiply. (The inputTensors0 will not be disposed. The inputTensor1 will be disposed. */
  static Multiply_and_keep0_destroy1() {
    this.output0.realTensor = tf.mul( this.input0.realTensor, this.input1.realTensor );
    this.input1.realTensor.dispose();
  }

  /** Multiply. (The inputTensor0 will be disposed. The inputTensor1 will not be disposed. */
  static Multiply_and_destroy0_keep1() {
    this.output0.realTensor = tf.mul( this.input0.realTensor, this.input1.realTensor );
    this.input0.realTensor.dispose();
  }

  /** Multiply. (Both the inputTensor0 and inputTensor1 will be disposed. */
  static Multiply_and_destroy0_destroy1() {
    this.output0.realTensor = tf.mul( this.input0.realTensor, this.input1.realTensor );
    this.input0.realTensor.dispose();
    this.input1.realTensor.dispose();
  }

}

<|endoftext|>


<commit_before>import * as ScriptLoader from "../ScriptLoader.js";
import * as Base64ArrayBufferToUint8Array from "../Base64ArrayBufferToUint8Array.js";
import * as PartTime from "../PartTime.js";
import * as ValueMax from "../ValueMax.js";

const base64EncodedString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const base64DecodedString = atob(base64EncodedString);

const base64EncodedStrings_extra = [
  base64EncodedString,

  // Test extra has 0 to 3 bytes. (They should be ignored.)
  base64EncodedString + "ab",
  base64EncodedString + "ab",
  base64EncodedString + "abc",

  // Test extra non-base64 codes inside. (They should be ignored.)
  base64EncodedString.slice(0, 3) + "\n"   + base64EncodedString.slice(3, -1),
  base64EncodedString.slice(0, 3) + "\r"   + base64EncodedString.slice(3, -1),
  base64EncodedString.slice(0, 3) + "\r\n" + base64EncodedString.slice(3, -1),
  base64EncodedString.slice(0, 3) + "\n\r" + base64EncodedString.slice(3, -1),
];

let tEncoder = new TextEncoder();
let tDecoder = new TextDecoder();

//const base64EncodedUint8Array = tDecoder.decode(base64EncodedString);
const base64DecodedUint8Array = tEncoder.encode(base64DecodedString);

class TestCase {
  constructor(source, skipLineCount, result, note) {
    this.source = source;
    this.skipLineCount = skipLineCount;
    this.result = result;
    this.note = note;
  }
}

let testCases = [
  TestCase( tEncoder.encode(base64EncodedStrings_extra[0]), 0, base64DecodedUint8Array, "Extra 0 bytes" ),
  TestCase( tEncoder.encode(base64EncodedStrings_extra[1]), 0, base64DecodedUint8Array, "Extra 1 bytes" ),
  TestCase( tEncoder.encode(base64EncodedStrings_extra[2]), 0, base64DecodedUint8Array, "Extra 2 bytes" ),
  TestCase( tEncoder.encode(base64EncodedStrings_extra[3]), 0, base64DecodedUint8Array, "Extra 3 bytes" ),
  TestCase( tEncoder.encode(base64EncodedStrings_extra[4]), 0, base64DecodedUint8Array, "Extra LF inside" ),
  TestCase( tEncoder.encode(base64EncodedStrings_extra[5]), 0, base64DecodedUint8Array, "Extra CR inside" ),
  TestCase( tEncoder.encode(base64EncodedStrings_extra[6]), 0, base64DecodedUint8Array, "Extra CRLF inside" ),
  TestCase( tEncoder.encode(base64EncodedStrings_extra[7]), 0, base64DecodedUint8Array, "Extra LFCR inside" ),

  TestCase( tEncoder.encode("\n"   + base64EncodedString), 1, base64DecodedUint8Array, "Begin LF" ),
  TestCase( tEncoder.encode("\r"   + base64EncodedString), 1, base64DecodedUint8Array, "Begin CR" ),
  TestCase( tEncoder.encode("\r\n" + base64EncodedString), 1, base64DecodedUint8Array, "Begin CRLF" ),
  TestCase( tEncoder.encode("\n\r" + base64EncodedString), 2, base64DecodedUint8Array, "Begin LFCR" ),

  TestCase( tEncoder.encode("qwerty\n"   + base64EncodedString), 1, base64DecodedUint8Array, "Text LF" ),
  TestCase( tEncoder.encode("qwerty\r"   + base64EncodedString), 1, base64DecodedUint8Array, "Text CR" ),
  TestCase( tEncoder.encode("qwerty\r\n" + base64EncodedString), 1, base64DecodedUint8Array, "Text CRLF" ),
  TestCase( tEncoder.encode("qwerty\n\r" + base64EncodedString), 2, base64DecodedUint8Array, "Text LFCR" ),
];

/** Aggregate all progress about downloading, JSON parsing, characters scanning, and weights scanning.  */
class Progress extends ValueMax.Percentage.Aggregate {
  constructor() {
    let children = [
      new ValueMax.Percentage.Concrete(), // Increased when downloading from network.
      new ValueMax.Percentage.Concrete(), // Increased when parsing the downloaded data to Uint8Array.
    ];

    super(children);

    [this.download, this.uint8Array] = children;
  }
}

let progress = new Progress();
//let receiver = new ValueMax.Receiver.Base();

window.addEventListener("load", event => {
  ScriptLoader.createPromise("https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js").then(test); });

function test() {
  console.log("Base64 decode testing...");

  for (let i = 0; i < testCases.length; ++i) {
    let testCase = testCases[ i ];

    PartTime.forOf(
      Base64ArrayBufferToUint8Array.decode_Generator(
        testCase.source, testCase.skipLineCount, progress, progress.uint8Array, 5),
      progrgess => {}
    ).then(r => {
      tf.util.assert(
        r.toString() == testCase.result.toString(),
        `[${i}] (${testCase.skipLineCount}) (${testCase.note}) ${r} != ${testCase.result}`);
    });
  }

  console.log("Base64 decode testing... Done.");
}
<commit_msg>Update Base64ArrayBufferToUint8Array_tester.js<commit_after>import * as ScriptLoader from "../ScriptLoader.js";
import * as Base64ArrayBufferToUint8Array from "../Base64ArrayBufferToUint8Array.js";
import * as PartTime from "../PartTime.js";
import * as ValueMax from "../ValueMax.js";

const base64EncodedString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const base64DecodedString = atob(base64EncodedString);

const base64EncodedStrings_extra = [
  base64EncodedString,

  // Test extra has 0 to 3 bytes. (They should be ignored.)
  base64EncodedString + "ab",
  base64EncodedString + "ab",
  base64EncodedString + "abc",

  // Test extra non-base64 codes inside. (They should be ignored.)
  base64EncodedString.slice(0, 3) + "\n"   + base64EncodedString.slice(3, -1),
  base64EncodedString.slice(0, 3) + "\r"   + base64EncodedString.slice(3, -1),
  base64EncodedString.slice(0, 3) + "\r\n" + base64EncodedString.slice(3, -1),
  base64EncodedString.slice(0, 3) + "\n\r" + base64EncodedString.slice(3, -1),
];

let tEncoder = new TextEncoder();
let tDecoder = new TextDecoder();

//const base64EncodedUint8Array = tDecoder.decode(base64EncodedString);
const base64DecodedUint8Array = tEncoder.encode(base64DecodedString);

class TestCase {
  constructor(source, skipLineCount, result, note) {
    this.source = source;
    this.skipLineCount = skipLineCount;
    this.result = result;
    this.note = note;
  }
}

let testCases = [
  new TestCase( tEncoder.encode(base64EncodedStrings_extra[0]), 0, base64DecodedUint8Array, "Extra 0 bytes" ),
  new TestCase( tEncoder.encode(base64EncodedStrings_extra[1]), 0, base64DecodedUint8Array, "Extra 1 bytes" ),
  new TestCase( tEncoder.encode(base64EncodedStrings_extra[2]), 0, base64DecodedUint8Array, "Extra 2 bytes" ),
  new TestCase( tEncoder.encode(base64EncodedStrings_extra[3]), 0, base64DecodedUint8Array, "Extra 3 bytes" ),
  new TestCase( tEncoder.encode(base64EncodedStrings_extra[4]), 0, base64DecodedUint8Array, "Extra LF inside" ),
  new TestCase( tEncoder.encode(base64EncodedStrings_extra[5]), 0, base64DecodedUint8Array, "Extra CR inside" ),
  new TestCase( tEncoder.encode(base64EncodedStrings_extra[6]), 0, base64DecodedUint8Array, "Extra CRLF inside" ),
  new TestCase( tEncoder.encode(base64EncodedStrings_extra[7]), 0, base64DecodedUint8Array, "Extra LFCR inside" ),

  new TestCase( tEncoder.encode("\n"   + base64EncodedString), 1, base64DecodedUint8Array, "Begin LF" ),
  new TestCase( tEncoder.encode("\r"   + base64EncodedString), 1, base64DecodedUint8Array, "Begin CR" ),
  new TestCase( tEncoder.encode("\r\n" + base64EncodedString), 1, base64DecodedUint8Array, "Begin CRLF" ),
  new TestCase( tEncoder.encode("\n\r" + base64EncodedString), 2, base64DecodedUint8Array, "Begin LFCR" ),

  new TestCase( tEncoder.encode("qwerty\n"   + base64EncodedString), 1, base64DecodedUint8Array, "Text LF" ),
  new TestCase( tEncoder.encode("qwerty\r"   + base64EncodedString), 1, base64DecodedUint8Array, "Text CR" ),
  new TestCase( tEncoder.encode("qwerty\r\n" + base64EncodedString), 1, base64DecodedUint8Array, "Text CRLF" ),
  new TestCase( tEncoder.encode("qwerty\n\r" + base64EncodedString), 2, base64DecodedUint8Array, "Text LFCR" ),
];

/** Aggregate all progress about downloading, JSON parsing, characters scanning, and weights scanning.  */
class Progress extends ValueMax.Percentage.Aggregate {
  constructor() {
    let children = [
      new ValueMax.Percentage.Concrete(), // Increased when downloading from network.
      new ValueMax.Percentage.Concrete(), // Increased when parsing the downloaded data to Uint8Array.
    ];

    super(children);

    [this.download, this.uint8Array] = children;
  }
}

let progress = new Progress();
//let receiver = new ValueMax.Receiver.Base();

window.addEventListener("load", event => {
  ScriptLoader.createPromise("https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js").then(test); });

function test() {
  console.log("Base64 decode testing...");

  for (let i = 0; i < testCases.length; ++i) {
    let testCase = testCases[ i ];

    PartTime.forOf(
      Base64ArrayBufferToUint8Array.decode_Generator(
        testCase.source, testCase.skipLineCount, progress, progress.uint8Array, 5),
      progrgess => {}
    ).then(r => {
      tf.util.assert(
        r.toString() == testCase.result.toString(),
        `[${i}] (${testCase.skipLineCount}) (${testCase.note}) ${r} != ${testCase.result}`);
    });
  }

  console.log("Base64 decode testing... Done.");
}
<|endoftext|>