<commit_before>/**
 * Controller for the subject overview.
 */
Ext.define('devilry_subjectadmin.controller.subject.Overview', {
    extend: 'Ext.app.Controller',
    mixins: {
        'setBreadcrumb': 'devilry_subjectadmin.utils.BasenodeBreadcrumbMixin',
        'onLoadFailure': 'devilry_subjectadmin.utils.DjangoRestframeworkLoadFailureMixin'
    },

    views: [
        'subject.Overview',
        'subject.ListOfPeriods',
        'RenameBasenodeWindow',
        'DeleteDjangoRestframeworkRecordDialog'
    ],

    requires: [
        'devilry_extjsextras.ConfirmDeleteDialog'
    ],

    stores: ['Periods'],
    models: ['Subject'],

    refs: [{
        ref: 'globalAlertmessagelist',
        selector: 'subjectoverview>alertmessagelist'
    }, {
        ref: 'deleteButton',
        selector: 'subjectoverview #deleteButton'
    }, {
        ref: 'renameButton',
        selector: 'subjectoverview #renameButton'
    }, {
        ref: 'header',
        selector: 'subjectoverview #header'
    }, {
        ref: 'subjectOverview',
        selector: 'subjectoverview'
    }, {
        ref: 'adminsbox',
        selector: 'subjectoverview adminsbox'
    }],

    init: function() {
        this.control({
            'viewport subjectoverview': {
                render: this._onSubjectViewRender
            },
            'viewport subjectoverview #deleteButton': {
                click: this._onDelete
            },
            'viewport subjectoverview #renameButton': {
                click: this._onRename
            }
        });
    },

    _onNotImplemented: function() {
        Ext.MessageBox.alert('Unavailable', 'Not implemented yet');
    },

    _onSubjectViewRender: function() {
        this.setLoadingBreadcrumb();
        this.subject_id = this.getSubjectOverview().subject_id;
        this._loadSubject(this.subject_id);
        this._loadPeriods();
    },

    _setDangerousActionsLabels: function() {
        var renameLabel = Ext.create('Ext.XTemplate', gettext('Rename {something}')).apply({
            something: this.subjectRecord.get('short_name')
        });
        var deleteLabel = Ext.create('Ext.XTemplate', gettext('Delete {something}')).apply({
            something: this.subjectRecord.get('short_name')
        });
        this.getRenameButton().setTitleText(renameLabel);
        this.getDeleteButton().setTitleText(deleteLabel);
    },

    _loadPeriods: function() {
        this.getPeriodsStore().loadPeriodsInSubject(this.subject_id, this._onLoadPeriods, this);
    },

    _onLoadPeriods: function(records, operation) {
        if(operation.success) {

        } else {
            this.onLoadFailure(operation);
        }
    },

    _loadSubject: function(subject_id) {
        this.getSubjectModel().load(subject_id, {
            scope: this,
            callback: function(record, operation) {
                if(operation.success) {
                    this._onLoadSubjectSuccess(record);
                } else {
                    this.onLoadFailure(operation);
                }
            }
        });
    },
    _onLoadSubjectSuccess: function(record) {
        this.subjectRecord = record;
        this.application.setTitle(this.subjectRecord.get('short_name'));
        this.getHeader().update({
            heading: record.get('long_name')
        });
        this.setBreadcrumb(this.subjectRecord);
        this.getAdminsbox().setBasenodeRecord(this.subjectRecord);
        this._setDangerousActionsLabels();
    },

    _onRename: function() {
        Ext.create('devilry_subjectadmin.view.RenameBasenodeWindow', {
            basenodeRecord: this.subjectRecord
        }).show();
    },
    _onDelete: function() {
        var short_description = this.subjectRecord.get('short_name');
        devilry_subjectadmin.view.DeleteDjangoRestframeworkRecordDialog.showIfCanDelete({
            basenodeRecord: this.subjectRecord,
            short_description: short_description,
            listeners: {
                scope: this,
                deleteSuccess: function() {
                    this.application.onAfterDelete(short_description);
                }
            }
        });
    }
});
<commit_msg>devilry_subjectadmin...subject: Use app alertmessagelist.<commit_after>/**
 * Controller for the subject overview.
 */
Ext.define('devilry_subjectadmin.controller.subject.Overview', {
    extend: 'Ext.app.Controller',
    mixins: {
        'setBreadcrumb': 'devilry_subjectadmin.utils.BasenodeBreadcrumbMixin',
        'onLoadFailure': 'devilry_subjectadmin.utils.DjangoRestframeworkLoadFailureMixin'
    },

    views: [
        'subject.Overview',
        'subject.ListOfPeriods',
        'RenameBasenodeWindow',
        'DeleteDjangoRestframeworkRecordDialog'
    ],

    requires: [
        'devilry_extjsextras.ConfirmDeleteDialog'
    ],

    stores: ['Periods'],
    models: ['Subject'],

    refs: [{
        ref: 'globalAlertmessagelist',
        selector: 'viewport floatingalertmessagelist#appAlertmessagelist'
    }, {
        ref: 'deleteButton',
        selector: 'subjectoverview #deleteButton'
    }, {
        ref: 'renameButton',
        selector: 'subjectoverview #renameButton'
    }, {
        ref: 'header',
        selector: 'subjectoverview #header'
    }, {
        ref: 'subjectOverview',
        selector: 'subjectoverview'
    }, {
        ref: 'adminsbox',
        selector: 'subjectoverview adminsbox'
    }],

    init: function() {
        this.control({
            'viewport subjectoverview': {
                render: this._onSubjectViewRender
            },
            'viewport subjectoverview #deleteButton': {
                click: this._onDelete
            },
            'viewport subjectoverview #renameButton': {
                click: this._onRename
            }
        });
    },

    _onNotImplemented: function() {
        Ext.MessageBox.alert('Unavailable', 'Not implemented yet');
    },

    _onSubjectViewRender: function() {
        this.setLoadingBreadcrumb();
        this.subject_id = this.getSubjectOverview().subject_id;
        this._loadSubject(this.subject_id);
        this._loadPeriods();
    },

    _setDangerousActionsLabels: function() {
        var renameLabel = Ext.create('Ext.XTemplate', gettext('Rename {something}')).apply({
            something: this.subjectRecord.get('short_name')
        });
        var deleteLabel = Ext.create('Ext.XTemplate', gettext('Delete {something}')).apply({
            something: this.subjectRecord.get('short_name')
        });
        this.getRenameButton().setTitleText(renameLabel);
        this.getDeleteButton().setTitleText(deleteLabel);
    },

    _loadPeriods: function() {
        this.getPeriodsStore().loadPeriodsInSubject(this.subject_id, this._onLoadPeriods, this);
    },

    _onLoadPeriods: function(records, operation) {
        if(operation.success) {

        } else {
            this.onLoadFailure(operation);
        }
    },

    _loadSubject: function(subject_id) {
        this.getSubjectModel().load(subject_id, {
            scope: this,
            callback: function(record, operation) {
                if(operation.success) {
                    this._onLoadSubjectSuccess(record);
                } else {
                    this.onLoadFailure(operation);
                }
            }
        });
    },
    _onLoadSubjectSuccess: function(record) {
        this.subjectRecord = record;
        this.application.setTitle(this.subjectRecord.get('short_name'));
        this.getHeader().update({
            heading: record.get('long_name')
        });
        this.setBreadcrumb(this.subjectRecord);
        this.getAdminsbox().setBasenodeRecord(this.subjectRecord);
        this._setDangerousActionsLabels();
    },

    _onRename: function() {
        Ext.create('devilry_subjectadmin.view.RenameBasenodeWindow', {
            basenodeRecord: this.subjectRecord
        }).show();
    },
    _onDelete: function() {
        var short_description = this.subjectRecord.get('short_name');
        devilry_subjectadmin.view.DeleteDjangoRestframeworkRecordDialog.showIfCanDelete({
            basenodeRecord: this.subjectRecord,
            short_description: short_description,
            listeners: {
                scope: this,
                deleteSuccess: function() {
                    this.application.onAfterDelete(short_description);
                }
            }
        });
    }
});
<|endoftext|>


<commit_before>import _ from 'lodash'

import { dbAdapter } from '../../../models'
import exceptions, { NotFoundException }  from '../../../support/exceptions'

export default class GroupsController {
  static async groupRequests(req, res) {
    if (!req.user)
      return res.status(401).jsonp({ err: 'Unauthorized', status: 'fail'})

    try {
      let managedGroups = await req.user.getManagedGroups()

      let groupsJson = []

      if (_.isArray(managedGroups) && managedGroups.length > 0){
        let promises = managedGroups.map(async (group)=>{
          let groupDescr = _.pick(group, ['id', 'username', 'screenName', 'isPrivate'])

          let unconfirmedFollowerIds = await group.getSubscriptionRequestIds()
          let unconfirmedFollowers = await dbAdapter.getUsersByIds(unconfirmedFollowerIds)
          groupDescr.requests = _.map(unconfirmedFollowers, (user)=>{ return _.pick(user, ['id', 'username', 'screenName']) })
          groupsJson.push(groupDescr)
        })
        await Promise.all(promises)
      }

      res.jsonp(groupsJson)
    } catch(e) {
      exceptions.reportError(res)(e)
    }
  }
}
<commit_msg>Fix unused import in api/v2/GroupsController<commit_after>import _ from 'lodash'

import { dbAdapter } from '../../../models'
import exceptions from '../../../support/exceptions'

export default class GroupsController {
  static async groupRequests(req, res) {
    if (!req.user)
      return res.status(401).jsonp({ err: 'Unauthorized', status: 'fail'})

    try {
      let managedGroups = await req.user.getManagedGroups()

      let groupsJson = []

      if (_.isArray(managedGroups) && managedGroups.length > 0){
        let promises = managedGroups.map(async (group)=>{
          let groupDescr = _.pick(group, ['id', 'username', 'screenName', 'isPrivate'])

          let unconfirmedFollowerIds = await group.getSubscriptionRequestIds()
          let unconfirmedFollowers = await dbAdapter.getUsersByIds(unconfirmedFollowerIds)
          groupDescr.requests = _.map(unconfirmedFollowers, (user)=>{ return _.pick(user, ['id', 'username', 'screenName']) })
          groupsJson.push(groupDescr)
        })
        await Promise.all(promises)
      }

      res.jsonp(groupsJson)
    } catch(e) {
      exceptions.reportError(res)(e)
    }
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose');
var Show     = mongoose.model('Show');
var Media    = mongoose.model('Media');
var ObjectId = require('mongoose').Types.ObjectId;
var chalk    = require('chalk');
var async    = require('async');

/**
 * Create a Medium
 */
exports.create = function(req, res) {

    console.log(chalk.blue('Creating new media'));

    //create new media
    var media = new Media();

    //make sure name was included
    if( !req.body.name ){
        var error = 'You must include a name';
        console.log(chalk.red.bold(error));
        complete( error, null );
    } else {
        media.name = req.body.name;
    }

    //path is optional
    if( req.body.path ) media.path = req.body.path;
    //seq is optional TODO: Make this only accept numbers
    if( req.body.seq )  media.seq = req.body.seq;
    //show is optional on creation
    if( req.body.show ) addShow(media);
    else complete( null, media);

    function addShow( media ) {
        //find the media's new show
        Show.findOne({'name': req.body.show.name }).exec(function(err, show){
            if (!show) {
                var error = 'Show does not exist';
                return complete( new Error(error), null );
            }

            //add media to show
            show.addMediaID( media._id );

            //add show to media
            media.show = show;

            show.save( function (err, show) {
                if (err) return complete( err, media );
            });

            complete( err, media );
        });
    }

    function complete( err, media ){
        if (err){
            var error = err.message;
            console.log( chalk.red.bold( error ) );
            return res.json({ success: false, message: error });
        }
        media.save( function ( err, media ){
            if (err){
                var error;
                // duplicate entry
                if (err.code === 11000) {
                    error = 'Media with that name already exists.';
                } else {
                    error = err.message;
                }
                console.log( chalk.red.bold( error ) );
                return res.json({ success: false, message: error });
            }
            var msg = 'Creation Successfull!';
            console.log( chalk.green( msg ) );
            return res.json({ success: true, message: msg });
        });
    }

};

/**
 * Show the current Medium
 */
exports.read = function(req, res) {
    console.log(chalk.blue('Getting media with name: ' + req.params.media_name));
    Media.findOne({ 'name' : req.params.media_name }).populate('show').exec(function( err, media ){

        // if the show doesn't exist
        if (!media){
            var error = 'No media with that name exists.';
            res.json({success: false, message: error});
            console.log(chalk.bold.red('Error: ' + error));
            return;

        } if (err) res.send(err);

        // return a message
        res.json(media);
        console.log(chalk.green('Returning ' + req.params.media_name));

    });

};

/**
 * Update a Medium
 */
exports.update = function(req, res) {
    console.log(chalk.blue('Updating media: ' + req.params.media_name));
    async.waterfall([
        function( callback ){
            //find the media
            Media.findOne({ 'name': req.params.media_name }).populate('show').exec(function(err, media){
                if (!media) {
                    var error = 'No media with that name exists.';
                    return callback( new Error(error) );
                }

                if( req.body.name ) media.name = req.body.name;
                if( req.body.path ) media.path = req.body.path;
                if( req.body.seq ) media.seq = req.body.seq;
                if( !req.body.show ) return complete( err, media );

                callback(err, media);
            });
        },
        function( media, callback ){
            //find the media's current show
            Show.findOne({'name': media.show.name }).exec(function(err, show){
                if (!show) {
                    var error = 'Current show does not exists.';
                    console.log( chalk.red.bold( error ) );
                    return callback( null, media );
                }

                //remove the media from the show
                show.removeMediaID( media._id );
                show.save( function (err, show) {
                    if (err) return complete( err, media );
                });

                callback(err, media );
            });
        },
        function( media, callback ){
            //find the media's new show
            Show.findOne({'name': req.body.show.name }).exec(function(err, show){
                if (!show) {
                    var error = 'Newly entered show does not exist';
                    return complete( new Error(error), media );
                }

                //add media to show
                show.addMediaID( media._id );

                //add show to media
                media.show = show;

                show.save( function (err, show) {
                    if (err) return callback( err, media );
                });

                callback(err, media);
            });

        }
    ], complete);

    function complete( err, media ){
        if (err){
            var error = err.message;
            console.log( chalk.red.bold( error ) );
            return res.json({ success: false, message: error });
        }
        media.save( function ( err, media ){
            if (err){
                var error = err.message;
                console.log( chalk.red.bold( error ) );
                return res.json({ success: false, message: error });
            }
            var msg = 'Update Successfull!';
            console.log( chalk.green( msg ) );
            return res.json({ success: true, message: msg });
        });
    }

};

/**
 * Delete an Medium
 */
exports.delete = function(req, res) {
    console.log(chalk.blue('Deleting ' + req.params.media_name ));
    Media.findOne({ 'name': req.params.media_name}).populate('show').exec(function(err, media){

        if (!media) {
            var error = 'No media with that name exists.';
            console.log(chalk.bold.red(error));
            res.json({ success: false, message: error } );
            return;

        } else if(err) throw err;

        Show.findById(media.show._id).exec(function(err, show){

            if (!show) {
                var error = 'No show with that name exists.';
                console.log(chalk.bold.red(error));
                res.json({ success: false, message: error } );
                return;

            } else if(err) throw err;

            show.removeMediaID( media._id );

            Media.remove({ 'name': req.params.media_name}, function(err) {
                if (err) res.send(err);

                // Mongodb can delete things that don't exist, can only confirm an error didn't occur.
                var msg = 'Deletion of ' + req.params.media_name + ' occured without error.';
                console.log(chalk.green(msg));
                res.json({ success: true, message: msg });
            });
        });
    });
};

/**
 * List of Media
 */
exports.list = function(req, res) {
    console.log(chalk.blue('Listing all Media.'));
    Media.find().populate('show', 'name').exec(function(err, media) {
        if (err) res.send(err);

        // return the show
        res.json(media);
    });
};
<commit_msg>Minor bug fixes that prevent media controller from crashing<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose');
var Show     = mongoose.model('Show');
var Media    = mongoose.model('Media');
var ObjectId = require('mongoose').Types.ObjectId;
var chalk    = require('chalk');
var async    = require('async');

/**
 * Create a Medium
 */
exports.create = function(req, res) {

    console.log(chalk.blue('Creating new media'));

    //create new media
    var media = new Media();

    //make sure name was included
    if( !req.body.name ){
        var error = new Error('You must include a name');
        console.log(chalk.red.bold(error));
        return complete( error, null );
    } else {
        media.name = req.body.name;
    }

    //path is optional on creation
    if( req.body.path ) media.path = req.body.path;
    //seq is optional TODO: Make this only accept numbers
    if( req.body.seq ) media.seq = req.body.seq;
    //show is optional on creation TODO: Actually make it optional
    if( req.body.show ) addShow(media);
    else complete( null, media);

    function addShow( media ) {
        //find the media's new show
        Show.findOne({'name': req.body.show.name }).exec(function(err, show){
            if (!show) {
                var error = 'Show does not exist';
                return complete( new Error(error), null );
            }

            //add media to show
            show.addMediaID( media._id );

            //add show to media
            media.show = show;

            show.save( function (err, show) {
                if (err) return complete( err, media );
            });

            complete( err, media );
        });
    }

    function complete( err, media ){
        if (err){
            var error = err.message;
            console.log( chalk.red.bold( error ) );
            return res.json({ success: false, message: error });
        }
        media.save( function ( err, media ){
            if (err){
                var error;
                // duplicate entry
                if (err.code === 11000) {
                    error = 'Media with that name already exists.';
                } else {
                    error = err.message;
                }
                console.log( chalk.red.bold( error ) );
                return res.json({ success: false, message: error });
            }
            var msg = 'Creation Successfull!';
            console.log( chalk.green( msg ) );
            return res.json({ success: true, message: msg });
        });
    }

};

/**
 * Show the current Medium
 */
exports.read = function(req, res) {
    console.log(chalk.blue('Getting media with name: ' + req.params.media_name));
    Media.findOne({ 'name' : req.params.media_name }).populate('show').exec(function( err, media ){

        // if the show doesn't exist
        if (!media){
            var error = 'No media with that name exists.';
            res.json({success: false, message: error});
            console.log(chalk.bold.red('Error: ' + error));
            return;

        } if (err) res.send(err);

        // return a message
        res.json(media);
        console.log(chalk.green('Returning ' + req.params.media_name));

    });

};

/**
 * Update a Medium
 */
exports.update = function(req, res) {
    console.log(chalk.blue('Updating media: ' + req.params.media_name));
    async.waterfall([
        function( callback ){
            //find the media
            Media.findOne({ 'name': req.params.media_name }).populate('show').exec(function(err, media){
                if (!media) {
                    var error = 'No media with that name exists.';
                    return callback( new Error(error) );
                }

                if( req.body.name ) media.name = req.body.name;
                if( req.body.path ) media.path = req.body.path;
                if( req.body.seq ) media.seq = req.body.seq;
                if( !req.body.show ) return complete( err, media );

                callback(err, media);
            });
        },
        function( media, callback ){
            //if no show is assigned yet, just skip
            if( !media.show ) return callback(null, media);
            //find the media's current show
            Show.findOne({'name': media.show.name }).exec(function(err, show){
                if (!show) {
                    var error = 'Current show does not exists.';
                    console.log( chalk.red.bold( error ) );
                    return callback( null, media );
                }

                //remove the media from the show
                show.removeMediaID( media._id );
                show.save( function (err, show) {
                    if (err) return complete( err, media );
                });

                callback(err, media );
            });
        },
        function( media, callback ){
            //find the media's new show
            Show.findOne({'name': req.body.show.name }).exec(function(err, show){
                if (!show) {
                    var error = 'Newly entered show does not exist';
                    return complete( new Error(error), media );
                }

                //add media to show
                show.addMediaID( media._id );

                //add show to media
                media.show = show;

                show.save( function (err, show) {
                    if (err) return callback( err, media );
                });

                callback(err, media);
            });

        }
    ], complete);

    function complete( err, media ){
        if (err){
            var error = err.message;
            console.log( chalk.red.bold( error ) );
            return res.json({ success: false, message: error });
        }
        media.save( function ( err, media ){
            if (err){
                var error = err.message;
                console.log( chalk.red.bold( error ) );
                return res.json({ success: false, message: error });
            }
            var msg = 'Update Successfull!';
            console.log( chalk.green( msg ) );
            return res.json({ success: true, message: msg });
        });
    }

};

/**
 * Delete an Medium
 */
exports.delete = function(req, res) {
    console.log(chalk.blue('Deleting ' + req.params.media_name ));
    Media.findOne({ 'name': req.params.media_name}).populate('show').exec(function(err, media){

        if (!media) {
            var error = 'No media with that name exists.';
            console.log(chalk.bold.red(error));
            res.json({ success: false, message: error } );
            return;

        } else if(err) throw err;

        Show.findById(media.show._id).exec(function(err, show){

            if (!show) {
                var error = 'No show with that name exists.';
                console.log(chalk.bold.red(error));
                res.json({ success: false, message: error } );
                return;

            } else if(err) throw err;

            show.removeMediaID( media._id );

            Media.remove({ 'name': req.params.media_name}, function(err) {
                if (err) res.send(err);

                // Mongodb can delete things that don't exist, can only confirm an error didn't occur.
                var msg = 'Deletion of ' + req.params.media_name + ' occured without error.';
                console.log(chalk.green(msg));
                res.json({ success: true, message: msg });
            });
        });
    });
};

/**
 * List of Media
 */
exports.list = function(req, res) {
    console.log(chalk.blue('Listing all Media.'));
    Media.find().populate('show', 'name').exec(function(err, media) {
        if (err) res.send(err);

        // return the show
        res.json(media);
    });
};
<|endoftext|>


<commit_before>var states = require('./state')
var RNG = require('rng')
var deepEqual = require('deep-equal')
//state is {source, sink, nodeState, log, old_length}

var model = exports.model = function (pState, cState, random) {
  /*
    we want to handle appends (and thus validation) before handling any receives.
    we can handle get and send in parallel though.

  */

  var acts = {}
  //emit is shared
  if(pState.emit || cState.source.length || isMessage(cState.nodeState.effect)) //connection
    acts.ordered = true
  if(cState.nodeState.ready != null)
    acts.send = true
  if(isNote(cState.nodeState.effect))
    acts.get = true

  var keys = Object.keys(acts)

  var key = keys[~~(random*keys.length)]

  if(key === 'send') {
    var data = cState.nodeState.ready
    cState.sink.push(data)
    cState.nodeState = states.read(cState.nodeState)
  }
  else if(key === 'get') {
    var msg = pState.log[cState.nodeState.effect - 1] //shared
    cState.nodeState.effect = null
    cState.nodeState = states.gotMessage(cState.nodeState, msg)
  }
  else if(key == 'ordered'){
    //this bit should fire an event on all the connection states
    if(pState.emit) {
      throw new Error('emit should not be handed in cstate')
//      var msg = pState.emit
//      pState.emit = null
//      cState.nodeState = states.appendMessage(cState.nodeState, msg)
    }
    else if(isMessage(cState.nodeState.effect)) {
      pState.emit = cState.nodeState.effect
      //pState.log.push(pState.emit) //shared
      cState.nodeState.effect = null
    }
    else if(cState.source.length) {
      var data = cState.source.shift() //connection.
      if(data == null) throw new Error('should never read null/undefined from network')
      cState.nodeState = (isMessage(data) ? states.receiveMessage : states.receiveNote)(cState.nodeState, data)
    }
    else throw new Error('should not have ran out of options')
  }

  return [pState, cState]
}

function isMessage(data) { return data && 'object' === typeof data }
function isNote(n) { return Number.isInteger(n) }

exports.peer = function peer (network, id, log) {
  if(!log) log = []

  network[id] = {
    id: id, log: log, emit: false,
    connections: {}
  }

  return network
}

exports.connection = function connection (network, from, to) {
  network[from].connections[to] = {
    source: [], sink: [], nodeState: states.init(network[from].log.length),
    id: from, remote: to,
  }
  network[to].connections[from] = {
    source: [], sink: [], nodeState: states.init(network[to].log.length),
    id: to, remote: from,
  }
  return network
}

exports.countConnections = function countConnections (network) {
  //count unidirectional connections then divide by 2 to get duplex connections
  var uniplex = 0
  for(var k in network) {
    uniplex += Object.keys(network[k].connections).length
  }
  return uniplex / 2
}

exports.isConsistent = function isConsistent (network) {
  //this is the "handshaking lemma" if I recall
  var keys = Object.keys(network)
  for(var i = 0; i < keys.length; i++) {
    var k = keys[i]
    for(var j = i+1; j < keys.length; j++) {
      var l = keys[j]
      if(!deepEqual(network[k].log, network[l].log, 'peer:'+k +' is consistent with :'+j))
        return false
    }
  }
  return true
}

var hasWork = exports.hasWork = function hasWork (pState, cState) {
  return (
    pState.emit || cState.source.length ||
    cState.nodeState.ready != null ||
    cState.nodeState.effect != null
  )
}

exports.evolveNetwork = function evolveNetwork (network, msglog, seed) {
  var rng = new RNG.MT(seed)

  function random () {
    return rng.random()
  }

  function isWaiting() {
    for(var k in network)
      for(var j in network[k].connections)
        if(hasWork(network[k], network[k].connections[j])) {
          return true
        }
  }

  function randomValue(obj) {
    var k = Object.keys(obj)
    var rk = k[~~(random()*k.length)]
    return obj[rk]
  }

  while(isWaiting()) {
    var pState = randomValue(network)
    if(pState.emit) {
      var msg = pState.emit
      pState.emit = null
      if(msg.sequence > pState.log.length) {
        console.log("APPENDED TWICE")
        pState.log.push(msg)
  //      console.log('append', JSON.stringify(pState, null, 2), msg)
        for(var k in pState.connections)
          pState.connections[k].nodeState = states.appendMessage(pState.connections[k].nodeState, msg)
      }
    } else {
      var cState = randomValue(pState.connections)
      if(cState) {
        var r = model(pState, cState, random())
        pState = r[0]
        cState = r[1]

//        if(cState.nodeState.local.tx == false)
//          throw new Error('transmit should always be true in this test')
//
        if(cState.nodeState.error)
          throw new Error('error state')

        //copy from the sink to the source immediately, since it gets read randomly anyway.
        if(cState.sink.length)
          console.log('send', cState.id+'->'+cState.remote, cState.sink)

        if(isMessage(cState.effect)) {
          if(pState.emit) throw new Error('something already appening')
          pState.emit = cState.effect
          cState.effect = null
        }
        while(cState.sink.length) {
          if(cState.sink[0] == null) throw new Error('cannot send null')
          var data = cState.sink.shift()
          msglog.push({from: cState.id, to: cState.remote, data: data})
          network[cState.remote].connections[cState.id].source.push(data)
        }
      }
    }
  }
  return network
}

<commit_msg>correct logging<commit_after>var states = require('./state')
var RNG = require('rng')
var deepEqual = require('deep-equal')
//state is {source, sink, nodeState, log, old_length}

var model = exports.model = function (pState, cState, random) {
  /*
    we want to handle appends (and thus validation) before handling any receives.
    we can handle get and send in parallel though.

  */

  var acts = {}
  //emit is shared
  if(pState.emit || cState.source.length || isMessage(cState.nodeState.effect)) //connection
    acts.ordered = true
  if(cState.nodeState.ready != null)
    acts.send = true
  if(isNote(cState.nodeState.effect))
    acts.get = true

  var keys = Object.keys(acts)

  var key = keys[~~(random*keys.length)]

  if(key === 'send') {
    var data = cState.nodeState.ready
    cState.sink.push(data)
    cState.nodeState = states.read(cState.nodeState)
  }
  else if(key === 'get') {
    var msg = pState.log[cState.nodeState.effect - 1] //shared
    cState.nodeState.effect = null
    cState.nodeState = states.gotMessage(cState.nodeState, msg)
  }
  else if(key == 'ordered'){
    //this bit should fire an event on all the connection states
    if(pState.emit) {
      throw new Error('emit should not be handed in cstate')
//      var msg = pState.emit
//      pState.emit = null
//      cState.nodeState = states.appendMessage(cState.nodeState, msg)
    }
    else if(isMessage(cState.nodeState.effect)) {
      pState.emit = cState.nodeState.effect
      //pState.log.push(pState.emit) //shared
      cState.nodeState.effect = null
    }
    else if(cState.source.length) {
      var data = cState.source.shift() //connection.
      if(data == null) throw new Error('should never read null/undefined from network')
      cState.nodeState = (isMessage(data) ? states.receiveMessage : states.receiveNote)(cState.nodeState, data)
    }
    else throw new Error('should not have ran out of options')
  }

  return [pState, cState]
}

function isMessage(data) { return data && 'object' === typeof data }
function isNote(n) { return Number.isInteger(n) }

exports.peer = function peer (network, id, log) {
  if(!log) log = []

  network[id] = {
    id: id, log: log, emit: false,
    connections: {}
  }

  return network
}

exports.connection = function connection (network, from, to) {
  network[from].connections[to] = {
    source: [], sink: [], nodeState: states.init(network[from].log.length),
    id: from, remote: to,
  }
  network[to].connections[from] = {
    source: [], sink: [], nodeState: states.init(network[to].log.length),
    id: to, remote: from,
  }
  return network
}

exports.countConnections = function countConnections (network) {
  //count unidirectional connections then divide by 2 to get duplex connections
  var uniplex = 0
  for(var k in network) {
    uniplex += Object.keys(network[k].connections).length
  }
  return uniplex / 2
}

exports.isConsistent = function isConsistent (network) {
  //this is the "handshaking lemma" if I recall
  var keys = Object.keys(network)
  for(var i = 0; i < keys.length; i++) {
    var k = keys[i]
    for(var j = i+1; j < keys.length; j++) {
      var l = keys[j]
      if(!deepEqual(network[k].log, network[l].log, 'peer:'+k +' is consistent with :'+j))
        return false
    }
  }
  return true
}

var hasWork = exports.hasWork = function hasWork (pState, cState) {
  return (
    pState.emit || cState.source.length ||
    cState.nodeState.ready != null ||
    cState.nodeState.effect != null
  )
}

exports.evolveNetwork = function evolveNetwork (network, msglog, seed) {
  var rng = new RNG.MT(seed)

  function random () {
    return rng.random()
  }

  function isWaiting() {
    for(var k in network)
      for(var j in network[k].connections)
        if(hasWork(network[k], network[k].connections[j])) {
          return true
        }
  }

  function randomValue(obj) {
    var k = Object.keys(obj)
    var rk = k[~~(random()*k.length)]
    return obj[rk]
  }

  while(isWaiting()) {
    var pState = randomValue(network)
    if(pState.emit) {
      var msg = pState.emit
      pState.emit = null
      if(msg.sequence > pState.log.length) {
        pState.log.push(msg)
        for(var k in pState.connections)
          pState.connections[k].nodeState = states.appendMessage(pState.connections[k].nodeState, msg)
      }
      else
        console.log("APPENDED TWICE")

    } else {
      var cState = randomValue(pState.connections)
      if(cState) {
        var r = model(pState, cState, random())
        pState = r[0]
        cState = r[1]

//        if(cState.nodeState.local.tx == false)
//          throw new Error('transmit should always be true in this test')
//
        if(cState.nodeState.error)
          throw new Error('error state')

        //copy from the sink to the source immediately, since it gets read randomly anyway.
        if(cState.sink.length)
          console.log('send', cState.id+'->'+cState.remote, cState.sink)

        if(isMessage(cState.effect)) {
          if(pState.emit) throw new Error('something already appening')
          pState.emit = cState.effect
          cState.effect = null
        }
        while(cState.sink.length) {
          if(cState.sink[0] == null) throw new Error('cannot send null')
          var data = cState.sink.shift()
          msglog.push({from: cState.id, to: cState.remote, data: data})
          network[cState.remote].connections[cState.id].source.push(data)
        }
      }
    }
  }
  return network
}

<|endoftext|>


<commit_before>beforeAll(() => {
  require('../../app/assets/javascripts/autofocus.js');
});

afterAll(() => {
  require('./support/teardown.js');
});

describe('Autofocus', () => {

  let focusHandler;
  let search;

  beforeEach(() => {

    // set up DOM
    document.body.innerHTML =
      `

          Search by name

        <input autocomplete="off" class="form-control form-control-1-1" id="search" name="search" type="search" value="" data-module="autofocus">

`;

    focusHandler = jest.fn();
    search = document.getElementById('search');
    search.addEventListener('focus', focusHandler, false);

  });

  afterEach(() => {

    document.body.innerHTML = '';
    search.removeEventListener('focus', focusHandler);
    focusHandler = null;

  });

  test('is focused when modules start', () => {

    // start module
    window.GOVUK.modules.start();

    expect(focusHandler).toHaveBeenCalled();

  });

  test('is not focused if the window has scrolled', () => {

    // mock the window being scrolled 25px
    $.prototype.scrollTop = jest.fn(() => 25);

    // start module
    window.GOVUK.modules.start();

    expect(focusHandler).not.toHaveBeenCalled();

  });

  test('is focused if the window has scrolled but the force-focus flag is set', () => {

    // mock the window being scrolled 25px
    $.prototype.scrollTop = jest.fn(() => 25);

    // set the force-focus flag
    document.querySelector('#search').setAttribute('data-force-focus', true);

    // start module
    window.GOVUK.modules.start();

    expect(focusHandler).toHaveBeenCalled();

  });

});
<commit_msg>Add tests for changes to label<commit_after>const helpers = require('./support/helpers.js');

beforeAll(() => {
  require('../../app/assets/javascripts/autofocus.js');
});

afterAll(() => {
  require('./support/teardown.js');
});

describe('Autofocus', () => {

  const labelText = 'Search by name';
  let focusHandler;
  let search;

  beforeEach(() => {

    document.title = 'Find services by name - GOV.UK Notify';

    // set up DOM
    document.body.innerHTML =
      `

          ${labelText}

        <input autocomplete="off" class="form-control form-control-1-1" id="search" name="search" type="search" value="" data-module="autofocus">

`;

    focusHandler = jest.fn();
    search = document.getElementById('search');
    search.addEventListener('focus', focusHandler, false);

  });

  afterEach(() => {

    document.body.innerHTML = '';
    search.removeEventListener('focus', focusHandler);
    focusHandler = null;

  });

  test('is focused when modules start', () => {

    // start module
    window.GOVUK.modules.start();

    expect(focusHandler).toHaveBeenCalled();

  });

  test('has a label including the page title when the module starts', () => {

    // start module
    window.GOVUK.modules.start();

    expect(search.hasAttribute('aria-label')).toBe(true);
    expect(search.getAttribute('aria-label')).toEqual(document.title + ' - ' + labelText);

  });

  test('gets the original label back when focus moves away', () => {

    // start module
    window.GOVUK.modules.start();

    // shift focus away from textbox
    helpers.triggerEvent(search, 'blur');

    expect(search.hasAttribute('aria-label')).toBe(false);

  });

  test('is not focused if the window has scrolled', () => {

    // mock the window being scrolled 25px
    $.prototype.scrollTop = jest.fn(() => 25);

    // start module
    window.GOVUK.modules.start();

    expect(focusHandler).not.toHaveBeenCalled();

  });

  test('is focused if the window has scrolled but the force-focus flag is set', () => {

    // mock the window being scrolled 25px
    $.prototype.scrollTop = jest.fn(() => 25);

    // set the force-focus flag
    document.querySelector('#search').setAttribute('data-force-focus', true);

    // start module
    window.GOVUK.modules.start();

    expect(focusHandler).toHaveBeenCalled();

  });

});
<|endoftext|>


<commit_before>const baseUrl = "http://api.thisismyjam.com";
const version = "1";

var uxhr = require("uxhr");
var apiKey = null;

function Base() {}

Base.prototype.setApiKey = string => apiKey = string;

Base.prototype.constructUrl = function(string) {
  return [baseUrl, version, string].join("/");
};

Base.prototype.makeRequest = function(url) {
  return new Promise(function(resolve, reject) {
    uxhr(url, { key: apiKey }, {
      success: function(data) {
        try {
          data = JSON.parse(data);
          resolve(data);
        } catch(err) {
          reject(err);
        }
      },
      error: function(err) {
        reject(err);
      }
    });
  });
};

module.exports = Base;
<commit_msg>Add missing .json<commit_after>const baseUrl = "http://api.thisismyjam.com";
const version = "1";

var uxhr = require("uxhr");
var apiKey = null;

function Base() {}

Base.prototype.setApiKey = string => apiKey = string;

Base.prototype.constructUrl = function(string) {
  return [baseUrl, version, string].join("/") + ".json";
};

Base.prototype.makeRequest = function(url) {
  return new Promise(function(resolve, reject) {
    uxhr(url, { key: apiKey }, {
      success: function(data) {
        try {
          data = JSON.parse(data);
          resolve(data);
        } catch(err) {
          reject(err);
        }
      },
      error: function(err) {
        reject(err);
      }
    });
  });
};

module.exports = Base;
<|endoftext|>


<commit_before>//global directives go here

angular.module('omniwallet').directive('d3PieChart', function() {
    return {
      template: '<svg></svg>',
      controller: function($scope, $element, $attrs) {

        $scope.chart = {
          width: 300,
          height: 300
        };
        $scope.radius = Math.min($scope.chart.width, $scope.chart.height) / 2;

        $element.find('svg').attr('height', $scope.chart.height).attr('width', $scope.chart.width);

        var color = d3.scale.category20();

        var arc = d3.svg.arc()
        .outerRadius($scope.radius - 10)
        .innerRadius(0);

        var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) {
          return d.value;
        });

        var svg = d3.select("svg");

        $scope.totalsPromise.then(function(successData) {

          var data = [],
            keys = Object.keys($scope.totals);
          keys.forEach(function(e, i) {
            data.push({
              value: $scope.totals[e],
              name: keys[i],
              color: Math.floor(Math.random() * 10)
            });
          });

          var g = svg.selectAll(".arc")
          .data(pie(data))
          .enter().append("g")
          .attr("class", "arc");

          g.append("path")
            .attr("d", arc)
            .style("fill", function(d) {
              return color(d.data.color);
            })
            .attr('transform', 'translate(150,150)');

          g.append("text")
            .attr("transform", function(d) {
              var c = arc.centroid(d);
              return "translate(" + (150 + c[0]) + "," + (150 + c[1]) + ")";
            })
            .attr("dy", ".35em")
            .style("text-anchor", "middle")
            .text(function(d) {
            return d.data.name;
          });
        });
      }
    };
  }).directive('omTooltip', function() {
    return {
      template: '(?)',
      link: function(scope, iElement, iAttrs, controller) {
        if (iAttrs.text)
          iElement.tooltip({
            title: iAttrs.text,
            placement: 'down',
            container: 'body'
          });
      }
    };
  }).directive('match', [function() {
    return {
      require: 'ngModel',
      link: function(scope, elem, attrs, ctrl) {

        scope.$watch('[' + attrs.ngModel + ', ' + attrs.match + ']', function(value) {
          ctrl.$setValidity('match', value[0] === value[1]);
        }, true);

      }
    };
 }]).directive('autoFocus', function($timeout) {
  return {
    restrict: 'AC',
    scope: {
      'autoFocus': '=autoFocus'
    },
    link: function(scope, element) {
      scope.$watch('autoFocus', function() {
        if(scope.autoFocus) {
          $timeout(function(){
            $(element[0]).focus();
          }, 100);
        }
      });
    }
  };
}).directive('combobox', function(){
  return {
    restrict:'E',
    templateUrl:'/template/combobox/combobox.html',
    scope:{
      optionList: '=',
      modelValue:'=',
      label:'@',
      placeholder:'@',
      valueSelected:'&'
    },
    controller:function($scope){
      $scope.filteredList = $scope.optionList;
      $scope.selectedOption=false;

      $scope.filter=function(){
        var results = $scope.optionList.filter(function(option){
          var matcher = new RegExp("^"+$scope.modelValue);
          return matcher.test(option);
        }) ;

        $scope.filteredList = results.length > 0 ? results: ["No results"];

        $scope.valueSelected({category:$scope.modelValue});
      };

      $scope.$watch(function(){ return $scope.optionList; },function(options){
        $scope.filteredList = options.length > 0 ? options : ["No results"];
      });

    },
    link: function(scope, element, attr){
      scope.open = function(){
        $('ul',element).css({
          "max-height": 150,
          "overflow-y": "auto",
          "overflow-x": "hidden",
          "width":$('input',element).outerWidth(),
          "left":$('.input-group-addon',element).outerWidth()
        });
        $('.dropdown',element).addClass('open');
      };

      scope.close = function(){
        if(!scope.selectedOption)
          $('.dropdown',element).removeClass('open');
      };

      scope.optionSelected = function(option){
        scope.modelValue = option;
        $('.dropdown',element).removeClass('open');
        scope.valueSelected({category:option});
        scope.selectedOption=false;
      };

      element.on('mousedown','a',function(){
        scope.selectedOption = true;
      });
    }
  };
}).directive('ensureInteger', function() {
  return {
    restrict: 'A',
    scope:{
      ensureIf:'&',
      ensureOver:'='
    },
    link: function(scope, ele, attrs) {
      scope.$watch("ensureOver", function(value) {
        if(scope.ensureIf())
          if (!(typeof value==='number' && (value%1)===0)){
            if (typeof value == "object")
              scope.ensureOver = value.round();
            else
              scope.ensureOver = Math.ceil(value);
          }

      });
      scope.$watch("ensureIf", function(value) {
        if(scope.ensureIf())
          if (!(typeof value==='number' && (value%1)===0))
            if (typeof value == "object")
              scope.ensureOver = value.round();
            else
              scope.ensureOver = Math.ceil(value);
      });
    }
  };
}).directive('bigNumber', function() {
  return {
    restrict: 'A',
    require:'?ngModel',
    link: function(scope, ele, attr, ctrl) {

      // add a parser that will process each time the value is
      // parsed into the model when the user updates it.
      ctrl.$parsers.unshift(function(value) {
          // test and set the validity after update.
          var number=undefined;
          try{
            number= new Big(value);
            ctrl.$setValidity('invalidValue', true);
          } catch(e) {
            ctrl.$setValidity('invalidValue', false);
          };
          if(number != undefined){
            var min = number >= new Big(attr.min);
            ctrl.$setValidity('minValue', min);

            var max = number <= new Big(attr.max);
            ctrl.$setValidity('maxValue', max);

            if(!max || !min)
              number=undefined;
          }
          // if it's valid, return the value to the model,
          // otherwise return undefined.
          return number;
      });

      // add a formatter that will process each time the value
      // is updated on the DOM element.
      ctrl.$formatters.unshift(function(value) {
          // validate.
          var number=undefined;
          try{
            number= new Big(value);
            ctrl.$setValidity('invalidValue', true);
          } catch(e) {
            ctrl.$setValidity('invalidValue', false);
          };
          if(number != undefined){
            var min = number >= new Big(attr.min);
            ctrl.$setValidity('minValue', min);

            var max = number <= new Big(attr.max);
            ctrl.$setValidity('maxValue', max);

            if(!max || !min)
              number=undefined;
          }

          // return the value or nothing will be written to the DOM.
          return number || value;
      });
    }
  };
}).directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = loadEvent.target.result;
                    });
                };
                reader.readAsText(changeEvent.target.files[0]);
            });
        }
    };
}]);
<commit_msg>Fixed bigInt directive validation<commit_after>//global directives go here

angular.module('omniwallet').directive('d3PieChart', function() {
    return {
      template: '<svg></svg>',
      controller: function($scope, $element, $attrs) {

        $scope.chart = {
          width: 300,
          height: 300
        };
        $scope.radius = Math.min($scope.chart.width, $scope.chart.height) / 2;

        $element.find('svg').attr('height', $scope.chart.height).attr('width', $scope.chart.width);

        var color = d3.scale.category20();

        var arc = d3.svg.arc()
        .outerRadius($scope.radius - 10)
        .innerRadius(0);

        var pie = d3.layout.pie()
        .sort(null)
        .value(function(d) {
          return d.value;
        });

        var svg = d3.select("svg");

        $scope.totalsPromise.then(function(successData) {

          var data = [],
            keys = Object.keys($scope.totals);
          keys.forEach(function(e, i) {
            data.push({
              value: $scope.totals[e],
              name: keys[i],
              color: Math.floor(Math.random() * 10)
            });
          });

          var g = svg.selectAll(".arc")
          .data(pie(data))
          .enter().append("g")
          .attr("class", "arc");

          g.append("path")
            .attr("d", arc)
            .style("fill", function(d) {
              return color(d.data.color);
            })
            .attr('transform', 'translate(150,150)');

          g.append("text")
            .attr("transform", function(d) {
              var c = arc.centroid(d);
              return "translate(" + (150 + c[0]) + "," + (150 + c[1]) + ")";
            })
            .attr("dy", ".35em")
            .style("text-anchor", "middle")
            .text(function(d) {
            return d.data.name;
          });
        });
      }
    };
  }).directive('omTooltip', function() {
    return {
      template: '(?)',
      link: function(scope, iElement, iAttrs, controller) {
        if (iAttrs.text)
          iElement.tooltip({
            title: iAttrs.text,
            placement: 'down',
            container: 'body'
          });
      }
    };
  }).directive('match', [function() {
    return {
      require: 'ngModel',
      link: function(scope, elem, attrs, ctrl) {

        scope.$watch('[' + attrs.ngModel + ', ' + attrs.match + ']', function(value) {
          ctrl.$setValidity('match', value[0] === value[1]);
        }, true);

      }
    };
 }]).directive('autoFocus', function($timeout) {
  return {
    restrict: 'AC',
    scope: {
      'autoFocus': '=autoFocus'
    },
    link: function(scope, element) {
      scope.$watch('autoFocus', function() {
        if(scope.autoFocus) {
          $timeout(function(){
            $(element[0]).focus();
          }, 100);
        }
      });
    }
  };
}).directive('combobox', function(){
  return {
    restrict:'E',
    templateUrl:'/template/combobox/combobox.html',
    scope:{
      optionList: '=',
      modelValue:'=',
      label:'@',
      placeholder:'@',
      valueSelected:'&'
    },
    controller:function($scope){
      $scope.filteredList = $scope.optionList;
      $scope.selectedOption=false;

      $scope.filter=function(){
        var results = $scope.optionList.filter(function(option){
          var matcher = new RegExp("^"+$scope.modelValue);
          return matcher.test(option);
        }) ;

        $scope.filteredList = results.length > 0 ? results: ["No results"];

        $scope.valueSelected({category:$scope.modelValue});
      };

      $scope.$watch(function(){ return $scope.optionList; },function(options){
        $scope.filteredList = options.length > 0 ? options : ["No results"];
      });

    },
    link: function(scope, element, attr){
      scope.open = function(){
        $('ul',element).css({
          "max-height": 150,
          "overflow-y": "auto",
          "overflow-x": "hidden",
          "width":$('input',element).outerWidth(),
          "left":$('.input-group-addon',element).outerWidth()
        });
        $('.dropdown',element).addClass('open');
      };

      scope.close = function(){
        if(!scope.selectedOption)
          $('.dropdown',element).removeClass('open');
      };

      scope.optionSelected = function(option){
        scope.modelValue = option;
        $('.dropdown',element).removeClass('open');
        scope.valueSelected({category:option});
        scope.selectedOption=false;
      };

      element.on('mousedown','a',function(){
        scope.selectedOption = true;
      });
    }
  };
}).directive('ensureInteger', function() {
  return {
    restrict: 'A',
    scope:{
      ensureIf:'&',
      ensureOver:'='
    },
    link: function(scope, ele, attrs) {
      scope.$watch("ensureOver", function(value) {
        if(scope.ensureIf())
          if (!(typeof value==='number' && (value%1)===0)){
            if (typeof value == "object")
              scope.ensureOver = value.round();
            else
              scope.ensureOver = Math.ceil(value);
          }

      });
      scope.$watch("ensureIf", function(value) {
        if(scope.ensureIf())
          if (!(typeof value==='number' && (value%1)===0))
            if (typeof value == "object")
              scope.ensureOver = value.round();
            else
              scope.ensureOver = Math.ceil(value);
      });
    }
  };
}).directive('bigNumber', function() {
  return {
    restrict: 'A',
    require:'?ngModel',
    link: function(scope, ele, attr, ctrl) {

      // add a parser that will process each time the value is
      // parsed into the model when the user updates it.
      ctrl.$parsers.unshift(function(value) {
          // test and set the validity after update.
          var number=undefined;
          try{
            number= new Big(value);
            ctrl.$setValidity('validBigInt', true);
          } catch(e) {
            ctrl.$setValidity('validBigInt', false);
          };
          if(number != undefined){
            var min = number.gte(new Big(attr.min));
            ctrl.$setValidity('minValue', min);

            var max = number.lte(new Big(attr.max));
            ctrl.$setValidity('maxValue', max);

            if(!max || !min)
              number=undefined;
          }
          // if it's valid, return the value to the model,
          // otherwise return undefined.
          return number;
      });

      // add a formatter that will process each time the value
      // is updated on the DOM element.
      ctrl.$formatters.unshift(function(value) {
          // validate.
          var number=undefined;
          try{
            number= new Big(value);
            ctrl.$setValidity('validBigInt', true);
          } catch(e) {
            ctrl.$setValidity('validBigInt', false);
          };
          if(number != undefined){
            var min = number.gte(new Big(attr.min));
            ctrl.$setValidity('minValue', min);

            var max = number.lte(new Big(attr.max));
            ctrl.$setValidity('maxValue', max);

            if(!max || !min)
              number=undefined;
          }

          // return the value or nothing will be written to the DOM.
          return number || value;
      });
    }
  };
}).directive("fileread", [function () {
    return {
        scope: {
            fileread: "="
        },
        link: function (scope, element, attributes) {
            element.bind("change", function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        scope.fileread = loadEvent.target.result;
                    });
                };
                reader.readAsText(changeEvent.target.files[0]);
            });
        }
    };
}]);
<|endoftext|>


<commit_before>import {attr, children, createEvent, css, data, Dimensions, escape, getImage, includes, isUndefined, once, parent, queryAll, startsWith, toFloat, toPx, trigger} from 'uikit-util';

export default {

    props: {
        width: Number,
        height: Number,
        offsetTop: String,
        offsetLeft: String,
        target: String
    },

    data: {
        width: false,
        height: false,
        offsetTop: '50vh',
        offsetLeft: '50vw',
        target: false
    },

    computed: {

        cacheKey() {
            return `${this.$name}.${data(this.$el, 'data-src')}`;
        },

        width({width, dataWidth}) {
            return width || dataWidth;
        },

        height({height, dataHeight}) {
            return height || dataHeight;
        },

        target: {

            get({target}) {
                return [this.$el, ...queryAll(target, this.$el)];
            },

            watch() {
                this.observe();
            }

        },

        offsetTop({offsetTop}) {
            return toPx(offsetTop, 'height');
        },

        offsetLeft({offsetLeft}) {
            return toPx(offsetLeft, 'width');
        }

    },

    connected() {

        if (!window.IntersectionObserver) {
            setSrcAttrs(this.$el);
            return;
        }

        if (storage[this.cacheKey]) {
            setSrcAttrs(this.$el, storage[this.cacheKey]);
        } else if (isImg(this.$el) && this.width && this.height) {
            attr(this.$el, 'src', getPlaceholderImage(this.$el));
        }

        this.observer = new IntersectionObserver(this.load, {
            rootMargin: `${this.offsetTop}px ${this.offsetLeft}px`
        });

        requestAnimationFrame(this.observe);

    },

    disconnected() {
        this.observer && this.observer.disconnect();
    },

    update: {

        read({image}) {

            if (!this.observer) {
                return false;
            }

            if (!image && document.readyState === 'complete') {
                this.load(this.observer.takeRecords());
            }

            if (isImg(this.$el)) {
                return false;
            }

            image && image.then(img => img && img.currentSrc !== '' && setSrcAttrs(this.$el, currentSrc(img)));

        },

        write(store) {

            const srcset = data(this.$el, 'data-srcset');
            if (srcset && window.devicePixelRatio !== 1) {

                const bgSize = css(this.$el, 'backgroundSize');
                if (bgSize.match(/^(auto\s?)+$/) || toFloat(bgSize) === store.bgSize) {
                    store.bgSize = getSourceSize(srcset, data(this.$el, 'sizes'));
                    css(this.$el, 'backgroundSize', `${store.bgSize}px`);
                }

            }

        },

        events: ['resize']

    },

    methods: {

        load(entries) {

            // Old chromium based browsers (UC Browser) did not implement `isIntersecting`
            if (!entries.some(entry => isUndefined(entry.isIntersecting) || entry.isIntersecting)) {
                return;
            }

            this._data.image = getImageFromElement(this.$el).then(img => {

                setSrcAttrs(this.$el, currentSrc(img));
                storage[this.cacheKey] = currentSrc(img);
                return img;

            }, e => trigger(this.$el, new e.constructor(e.type, e)));

            this.observer.disconnect();
        },

        observe() {
            if (this._connected && !this._data.image) {
                this.target.forEach(el => this.observer.observe(el));
            }
        }

    }

};

const srcProps = ['data-src', 'data-srcset', 'sizes'];
function setSrcAttrs(el, src) {

    const parentNode = parent(el);
    if (isImg(el)) {
        (isPicture(parentNode) ? children(parentNode) : [el]).forEach(el =>
            srcProps.forEach(prop => {
                const value = data(el, prop);
                if (value) {
                    attr(el, prop.replace(/^(data-)+/, ''), value);
                }
            })
        );
    } else if (src) {

        const change = !includes(el.style.backgroundImage, src);
        if (change) {
            css(el, 'backgroundImage', `url(${escape(src)})`);
            trigger(el, createEvent('load', false));
        }

    }

}

function getPlaceholderImage(width, height, sizes) {

    if (sizes) {
        ({width, height} = Dimensions.ratio({width, height}, 'width', toPx(sizesToPixel(sizes))));
    }

    return `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"></svg>`;
}

const sizesRe = /\s*(.*?)\s*(\w+|calc\(.*?\))\s*(?:,|$)/g;
function sizesToPixel(sizes) {
    let matches;

    sizesRe.lastIndex = 0;

    while ((matches = sizesRe.exec(sizes))) {
        if (!matches[1] || window.matchMedia(matches[1]).matches) {
            matches = evaluateSize(matches[2]);
            break;
        }
    }

    return matches || '100vw';
}

function getImageFromElement(el) {
    const parentNode = parent(el);
    if (!isPicture(parentNode)) {
        return getImage(...srcProps.map(prop => data(el, prop)));
    }

    return new Promise((resolve, reject) => {
        const picture = parentNode.cloneNode(true);
        once(picture, 'load error', e => e.type === 'error' ? reject(e) : resolve(e.target), true);
        setSrcAttrs(el);
    });
}

const sizeRe = /\d+(?:\w+|%)/g;
const additionRe = /[+-]?(\d+)/g;
function evaluateSize(size) {
    return startsWith(size, 'calc')
        ? size
            .slice(5, -1)
            .replace(sizeRe, size => toPx(size))
            .replace(/ /g, '')
            .match(additionRe)
            .reduce((a, b) => a + +b, 0)
        : size;
}

const srcSetRe = /\s+\d+w\s*(?:,|$)/g;
function getSourceSize(srcset, sizes) {
    const srcSize = toPx(sizesToPixel(sizes));
    const descriptors = (srcset.match(srcSetRe) || []).map(toFloat).sort((a, b) => a - b);

    return descriptors.filter(size => size >= srcSize)[0] || descriptors.pop() || '';
}

function isPicture(el) {
    return isA(el, 'PICTURE');
}

function isImg(el) {
    return isA(el, 'IMG');
}

function isA(el, tagName) {
    return el && el.tagName === tagName;
}

function currentSrc(el) {
    return el.currentSrc || el.src;
}

const key = '__test__';
let storage;

// workaround for Safari's private browsing mode and accessing sessionStorage in Blink
try {
    storage = window.sessionStorage || {};
    storage[key] = 1;
    delete storage[key];
} catch (e) {
    storage = {};
}
<commit_msg>fix: getPlaceholderImage<commit_after>import {attr, children, createEvent, css, data, Dimensions, escape, getImage, includes, isUndefined, once, parent, queryAll, startsWith, toFloat, toPx, trigger} from 'uikit-util';

export default {

    props: {
        width: Number,
        height: Number,
        offsetTop: String,
        offsetLeft: String,
        target: String
    },

    data: {
        width: false,
        height: false,
        offsetTop: '50vh',
        offsetLeft: '50vw',
        target: false
    },

    computed: {

        cacheKey() {
            return `${this.$name}.${data(this.$el, 'data-src')}`;
        },

        width({width, dataWidth}) {
            return width || dataWidth;
        },

        height({height, dataHeight}) {
            return height || dataHeight;
        },

        target: {

            get({target}) {
                return [this.$el, ...queryAll(target, this.$el)];
            },

            watch() {
                this.observe();
            }

        },

        offsetTop({offsetTop}) {
            return toPx(offsetTop, 'height');
        },

        offsetLeft({offsetLeft}) {
            return toPx(offsetLeft, 'width');
        }

    },

    connected() {

        if (!window.IntersectionObserver) {
            setSrcAttrs(this.$el);
            return;
        }

        if (storage[this.cacheKey]) {
            setSrcAttrs(this.$el, storage[this.cacheKey]);
        } else if (isImg(this.$el) && this.width && this.height) {
            attr(this.$el, 'src', getPlaceholderImage(this.$el));
        }

        this.observer = new IntersectionObserver(this.load, {
            rootMargin: `${this.offsetTop}px ${this.offsetLeft}px`
        });

        requestAnimationFrame(this.observe);

    },

    disconnected() {
        this.observer && this.observer.disconnect();
    },

    update: {

        read({image}) {

            if (!this.observer) {
                return false;
            }

            if (!image && document.readyState === 'complete') {
                this.load(this.observer.takeRecords());
            }

            if (isImg(this.$el)) {
                return false;
            }

            image && image.then(img => img && img.currentSrc !== '' && setSrcAttrs(this.$el, currentSrc(img)));

        },

        write(store) {

            const srcset = data(this.$el, 'data-srcset');
            if (srcset && window.devicePixelRatio !== 1) {

                const bgSize = css(this.$el, 'backgroundSize');
                if (bgSize.match(/^(auto\s?)+$/) || toFloat(bgSize) === store.bgSize) {
                    store.bgSize = getSourceSize(srcset, data(this.$el, 'sizes'));
                    css(this.$el, 'backgroundSize', `${store.bgSize}px`);
                }

            }

        },

        events: ['resize']

    },

    methods: {

        load(entries) {

            // Old chromium based browsers (UC Browser) did not implement `isIntersecting`
            if (!entries.some(entry => isUndefined(entry.isIntersecting) || entry.isIntersecting)) {
                return;
            }

            this._data.image = getImageFromElement(this.$el).then(img => {

                setSrcAttrs(this.$el, currentSrc(img));
                storage[this.cacheKey] = currentSrc(img);
                return img;

            }, e => trigger(this.$el, new e.constructor(e.type, e)));

            this.observer.disconnect();
        },

        observe() {
            if (this._connected && !this._data.image) {
                this.target.forEach(el => this.observer.observe(el));
            }
        }

    }

};

const srcProps = ['data-src', 'data-srcset', 'sizes'];
function setSrcAttrs(el, src) {

    const parentNode = parent(el);
    if (isImg(el)) {
        (isPicture(parentNode) ? children(parentNode) : [el]).forEach(el =>
            srcProps.forEach(prop => {
                const value = data(el, prop);
                if (value) {
                    attr(el, prop.replace(/^(data-)+/, ''), value);
                }
            })
        );
    } else if (src) {

        const change = !includes(el.style.backgroundImage, src);
        if (change) {
            css(el, 'backgroundImage', `url(${escape(src)})`);
            trigger(el, createEvent('load', false));
        }

    }

}

function getPlaceholderImage(el) {
    const sizes = data(el, 'sizes');
    let width = data(el, 'width');
    let height = data(el, 'height');

    if (sizes) {
        ({width, height} = Dimensions.ratio({width, height}, 'width', toPx(sizesToPixel(sizes))));
    }

    return `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"></svg>`;
}

const sizesRe = /\s*(.*?)\s*(\w+|calc\(.*?\))\s*(?:,|$)/g;
function sizesToPixel(sizes) {
    let matches;

    sizesRe.lastIndex = 0;

    while ((matches = sizesRe.exec(sizes))) {
        if (!matches[1] || window.matchMedia(matches[1]).matches) {
            matches = evaluateSize(matches[2]);
            break;
        }
    }

    return matches || '100vw';
}

function getImageFromElement(el) {
    const parentNode = parent(el);
    if (!isPicture(parentNode)) {
        return getImage(...srcProps.map(prop => data(el, prop)));
    }

    return new Promise((resolve, reject) => {
        const picture = parentNode.cloneNode(true);
        once(picture, 'load error', e => e.type === 'error' ? reject(e) : resolve(e.target), true);
        setSrcAttrs(el);
    });
}

const sizeRe = /\d+(?:\w+|%)/g;
const additionRe = /[+-]?(\d+)/g;
function evaluateSize(size) {
    return startsWith(size, 'calc')
        ? size
            .slice(5, -1)
            .replace(sizeRe, size => toPx(size))
            .replace(/ /g, '')
            .match(additionRe)
            .reduce((a, b) => a + +b, 0)
        : size;
}

const srcSetRe = /\s+\d+w\s*(?:,|$)/g;
function getSourceSize(srcset, sizes) {
    const srcSize = toPx(sizesToPixel(sizes));
    const descriptors = (srcset.match(srcSetRe) || []).map(toFloat).sort((a, b) => a - b);

    return descriptors.filter(size => size >= srcSize)[0] || descriptors.pop() || '';
}

function isPicture(el) {
    return isA(el, 'PICTURE');
}

function isImg(el) {
    return isA(el, 'IMG');
}

function isA(el, tagName) {
    return el && el.tagName === tagName;
}

function currentSrc(el) {
    return el.currentSrc || el.src;
}

const key = '__test__';
let storage;

// workaround for Safari's private browsing mode and accessing sessionStorage in Blink
try {
    storage = window.sessionStorage || {};
    storage[key] = 1;
    delete storage[key];
} catch (e) {
    storage = {};
}
<|endoftext|>


<commit_before>/* Noty
Hay que agregar esto al html

Se usa así
showNoty('success','Este va a ser el mensaje que se muestre');
*/

function showNoty(type,text)
{
	var bgClass;
	switch(type)
	{
		case 'danger':
			bgClass = 'bg-danger';
			break;
		case 'warning':
			bgClass = 'bg-warning';
			break;
		case 'success':
			bgClass = 'bg-success';
			break;
		default:
			bgClass = 'bg-info';
			break;
	}

	var n = noty({
		text: text,
		type: type,
		theme: 'defaultTheme', // or 'relax'
		template: '

',
		animation: {
			open: 'animated pulse', // Animate.css class names
			close: 'animated bounceOutLeft', // Animate.css class names
			easing: 'swing', // easing
			speed: 500 // opening & closing animation speed
		},
		timeout: 3000,
	});
}

function toasty(text,style)
{
	style = style.toLowerCase();
	var bgColor,fColor;
	switch(style)
	{
		case 'error':
			bgColor = '#f44336';
			color = 'black';
			break;
		case 'success':
			bgColor = 'green';
			color = 'white';
			break;
		default:
			 bgColor = 'black';
			 color = 'white';
			 break;
	}

	var $toastContent = $(`<span>${text}</span>`);
	Materialize.toast($toastContent, 1000);
	$('.toast').css('background-color',bgColor);
	$('.toast').css('color',color);
	$('#toast-container').css('top','auto');
	$('#toast-container').css('right','auto');
	$('#toast-container').css('bottom','50%');
}

var storage = window.localStorage;
var excludedLoc = ['index','registro','restaurarPass'];

function getLoc()
{
	return window.location.pathname.split('/')[(window.location.pathname.split('/')).length - 1].split('.')[0];
}

function checkId()
{
	if(excludedLoc.indexOf(getLoc()) == -1)
	{
		if(getItem('id') == undefined)
		{
			logout();
		}
	}
}
checkId();

function checkAdministrador()
{
	if(getItem('administrador') == 't')
	{
		return true;
	}
	else
	{
		return false;
	}
}

//Trae la cantidad de graduados a la espera de ser habilitados
function setCantidad()
{
	var cant = getItem('cantidad');
	if(parseInt(cant) > 0)
	{
		$('.cantGraduados').html(cant);
	}
	else
	{
		$('.cantGraduados').hide();
	}
}

function initializeCantidad(cant)
{
	setItem('cantidad',cant);
	setCantidad();
}

function getItem(item)
{
	return storage.getItem(item);
}

function removeItem(item)
{
	storage.removeItem(item);
}

function setItem(item,val)
{
	storage.setItem(item,val);
}

function logout()
{
	removeItem('id');
	removeItem('administrador');
	removeItem('cantidad');
	setItem('logout','t');
	window.location.href = 'index.html';
}

function checkMenu()
{
	if(excludedLoc.indexOf(getLoc()) != -1) return;
	var cH,pH,eH,dH;
	if(checkAdministrador())
	{
		cH = 'cursosAdmin.html';
		pH = 'posgradosAdmin.html';
		eH = 'empleoAdmin.html';
		dH = 'descuentosAdmin.html';
		$('.hideNotAdmin').show();
		successGetCantGraduados();
	}
	else
	{
		cH = 'cursos.html';
		pH = 'posgrados.html';
		eH = 'empleo.html';
		dH = 'descuentos.html';
		$('.hideNotAdmin').hide();
	}

	$('.cursosHref').prop('href',cH);
	$('.posgradosHref').prop('href',pH);
	$('.empleoHref').prop('href',eH);
	$('.descuentosHref').prop('href',dH);
}

function successGetCantGraduados()
{
	var cant = getItem('cantidad');
	if(cant == null) return;

	if(parseInt(cant) > 0)
	{
		$('.cantGraduados').show();
		$('.cantGraduados').html(cant);
	}
	else
	{
		$('.cantGraduados').hide();
	}
}

function controlVacio(nombreSelector)
{
	if($.trim($(nombreSelector).val()) == '')
	{
		$(nombreSelector).css('box-shadow','0px 0px 1px 1px #f24d4d');
		$(nombreSelector).focus();
		return false;
	}
	return true;
}

function sacarColor(me)
{
	$(me).css('box-shadow','0px 0px 0px 0px #ccc');
}

function loadNav()
{
	$("#nav").load("menu.html");
}

function getCard(cT,cC)
{
	return `

			${cT}

${cC}

`;
}

function controlBack()
{
	if(getItem('back') == 't')
	{
		removeItem('back');
		history.back()
	};

	window.onload = function () {
		var loc = getLoc();
		if (typeof history.pushState === "function") {
			history.pushState("jibberish", null, null);
			window.onpopstate = function () {
				if(loc == 'inicio' || loc == 'index')
				{
					try
					{
					(navigator.app && navigator.app.exitApp()) || (device && device.exitApp());
					}
					catch(err)
					{
						setItem('back','t');
						var next = (history.length - 2) * -1;
						history.go(next);
					}
				}
				else
				{
					if(loc != "registrar" || loc != "restaurarPass")
					{
						window.location.href = "inicio.html";
					}
				}
			};
		}
		else {
			var ignoreHashChange = true;
			window.onhashchange = function () {
				if(loc == 'inicio' || loc == 'index')
				{
					try
					{
					(navigator.app && navigator.app.exitApp()) || (device && device.exitApp());
					}
					catch(err)
					{
						setItem('back','t');
						var next = (history.length - 1) * -1;
						history.go(next);
					}
				}
				else
				{
					if(loc != "registrar" || loc != "restaurarPass")
					{
						window.location.href = "inicio.html";
					}
				}
			};
		}
	}
}

function parse(json)
{
	return JSON.parse(json);
}

function checkSelectedOption()
{
	var options = {
		'cursos':'liCurso',
		'cursosAdmin':'liCurso',
		'descuentos':'liDescuento',
		'descuentosAdmin':'liDescuento',
		'empleo':'liEmpleo',
		'empleoAdmin':'liEmpleo',
		'graduadosAdmin':'liGraduado',
		'perfil':'liPerfil',
		'posgrados':'liPosgrado',
		'posgradosAdmin':'liPosgrado'
	};
	var l = getLoc();
	var name = `.${options[l]}`;
	$(name).addClass('selectedOption');
}
/*
document.addEventListener('DOMContentLoaded', function() {
    var exitApp = true, intval = setInterval(function (){exitApp = false;}, 1000);
    document.addEventListener("backbutton", function (e){
        e.preventDefault();
        if (exitApp) {
            clearInterval(intval)
            (navigator.app && navigator.app.exitApp()) || (device && device.exitApp())
        }
        else {
            exitApp = true
            history.back(1);
        }
    }, false);
}, false);
*/
document.addEventListener('deviceready', function() {
	alert('DeviceReady');
    var exitApp = true;
    document.addEventListener("backbutton", function (e){
        e.preventDefault();
		if(getLoc() == 'index' || getLoc() == 'inicio')
		{
			(navigator.app && navigator.app.exitApp()) || (device && device.exitApp())
		}
		else
		{
			window.location.href = "inicio.html";
		}
    }, false);
}, false);
//document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("DOMContentLoaded", controlBack, false);
document.addEventListener("DOMContentLoaded", checkMenu, false);
document.addEventListener("DOMContentLoaded", checkSelectedOption, false);<commit_msg>Back control<commit_after>/* Noty
Hay que agregar esto al html

Se usa así
showNoty('success','Este va a ser el mensaje que se muestre');
*/

function showNoty(type,text)
{
	var bgClass;
	switch(type)
	{
		case 'danger':
			bgClass = 'bg-danger';
			break;
		case 'warning':
			bgClass = 'bg-warning';
			break;
		case 'success':
			bgClass = 'bg-success';
			break;
		default:
			bgClass = 'bg-info';
			break;
	}

	var n = noty({
		text: text,
		type: type,
		theme: 'defaultTheme', // or 'relax'
		template: '

',
		animation: {
			open: 'animated pulse', // Animate.css class names
			close: 'animated bounceOutLeft', // Animate.css class names
			easing: 'swing', // easing
			speed: 500 // opening & closing animation speed
		},
		timeout: 3000,
	});
}

function toasty(text,style)
{
	style = style.toLowerCase();
	var bgColor,fColor;
	switch(style)
	{
		case 'error':
			bgColor = '#f44336';
			color = 'black';
			break;
		case 'success':
			bgColor = 'green';
			color = 'white';
			break;
		default:
			 bgColor = 'black';
			 color = 'white';
			 break;
	}

	var $toastContent = $(`<span>${text}</span>`);
	Materialize.toast($toastContent, 1000);
	$('.toast').css('background-color',bgColor);
	$('.toast').css('color',color);
	$('#toast-container').css('top','auto');
	$('#toast-container').css('right','auto');
	$('#toast-container').css('bottom','50%');
}

var storage = window.localStorage;
var excludedLoc = ['index','registro','restaurarPass'];

function getLoc()
{
	return window.location.pathname.split('/')[(window.location.pathname.split('/')).length - 1].split('.')[0];
}

function checkId()
{
	if(excludedLoc.indexOf(getLoc()) == -1)
	{
		if(getItem('id') == undefined)
		{
			logout();
		}
	}
}
checkId();

function checkAdministrador()
{
	if(getItem('administrador') == 't')
	{
		return true;
	}
	else
	{
		return false;
	}
}

//Trae la cantidad de graduados a la espera de ser habilitados
function setCantidad()
{
	var cant = getItem('cantidad');
	if(parseInt(cant) > 0)
	{
		$('.cantGraduados').html(cant);
	}
	else
	{
		$('.cantGraduados').hide();
	}
}

function initializeCantidad(cant)
{
	setItem('cantidad',cant);
	setCantidad();
}

function getItem(item)
{
	return storage.getItem(item);
}

function removeItem(item)
{
	storage.removeItem(item);
}

function setItem(item,val)
{
	storage.setItem(item,val);
}

function logout()
{
	removeItem('id');
	removeItem('administrador');
	removeItem('cantidad');
	setItem('logout','t');
	window.location.href = 'index.html';
}

function checkMenu()
{
	if(excludedLoc.indexOf(getLoc()) != -1) return;
	var cH,pH,eH,dH;
	if(checkAdministrador())
	{
		cH = 'cursosAdmin.html';
		pH = 'posgradosAdmin.html';
		eH = 'empleoAdmin.html';
		dH = 'descuentosAdmin.html';
		$('.hideNotAdmin').show();
		successGetCantGraduados();
	}
	else
	{
		cH = 'cursos.html';
		pH = 'posgrados.html';
		eH = 'empleo.html';
		dH = 'descuentos.html';
		$('.hideNotAdmin').hide();
	}

	$('.cursosHref').prop('href',cH);
	$('.posgradosHref').prop('href',pH);
	$('.empleoHref').prop('href',eH);
	$('.descuentosHref').prop('href',dH);
}

function successGetCantGraduados()
{
	var cant = getItem('cantidad');
	if(cant == null) return;

	if(parseInt(cant) > 0)
	{
		$('.cantGraduados').show();
		$('.cantGraduados').html(cant);
	}
	else
	{
		$('.cantGraduados').hide();
	}
}

function controlVacio(nombreSelector)
{
	if($.trim($(nombreSelector).val()) == '')
	{
		$(nombreSelector).css('box-shadow','0px 0px 1px 1px #f24d4d');
		$(nombreSelector).focus();
		return false;
	}
	return true;
}

function sacarColor(me)
{
	$(me).css('box-shadow','0px 0px 0px 0px #ccc');
}

function loadNav()
{
	$("#nav").load("menu.html");
}

function getCard(cT,cC)
{
	return `

			${cT}

${cC}

`;
}
/*
function controlBack()
{
	if(getItem('back') == 't')
	{
		removeItem('back');
		history.back()
	};

	window.onload = function () {
		var loc = getLoc();
		if (typeof history.pushState === "function") {
			history.pushState("jibberish", null, null);
			window.onpopstate = function () {
				if(loc == 'inicio' || loc == 'index')
				{
					try
					{
					(navigator.app && navigator.app.exitApp()) || (device && device.exitApp());
					}
					catch(err)
					{
						setItem('back','t');
						var next = (history.length - 2) * -1;
						history.go(next);
					}
				}
				else
				{
					if(loc != "registrar" || loc != "restaurarPass")
					{
						window.location.href = "inicio.html";
					}
				}
			};
		}
		else {
			var ignoreHashChange = true;
			window.onhashchange = function () {
				if(loc == 'inicio' || loc == 'index')
				{
					try
					{
					(navigator.app && navigator.app.exitApp()) || (device && device.exitApp());
					}
					catch(err)
					{
						setItem('back','t');
						var next = (history.length - 1) * -1;
						history.go(next);
					}
				}
				else
				{
					if(loc != "registrar" || loc != "restaurarPass")
					{
						window.location.href = "inicio.html";
					}
				}
			};
		}
	}
}
*/
function parse(json)
{
	return JSON.parse(json);
}

function checkSelectedOption()
{
	var options = {
		'cursos':'liCurso',
		'cursosAdmin':'liCurso',
		'descuentos':'liDescuento',
		'descuentosAdmin':'liDescuento',
		'empleo':'liEmpleo',
		'empleoAdmin':'liEmpleo',
		'graduadosAdmin':'liGraduado',
		'perfil':'liPerfil',
		'posgrados':'liPosgrado',
		'posgradosAdmin':'liPosgrado'
	};
	var l = getLoc();
	var name = `.${options[l]}`;
	$(name).addClass('selectedOption');
}
/*
document.addEventListener('DOMContentLoaded', function() {
    var exitApp = true, intval = setInterval(function (){exitApp = false;}, 1000);
    document.addEventListener("backbutton", function (e){
        e.preventDefault();
        if (exitApp) {
            clearInterval(intval)
            (navigator.app && navigator.app.exitApp()) || (device && device.exitApp())
        }
        else {
            exitApp = true
            history.back(1);
        }
    }, false);
}, false);
*/
document.addEventListener('deviceready', function() {
	alert('DeviceReady');
    var exitApp = true;
    document.addEventListener("backbutton", function (e){
        e.preventDefault();
		if(getLoc() == 'index' || getLoc() == 'inicio')
		{
			(navigator.app && navigator.app.exitApp()) || (device && device.exitApp())
		}
		else
		{
			window.location.href = "inicio.html";
		}
    }, false);
}, false);

$(function()
{
    var rx = /INPUT|SELECT|TEXTAREA/i;

    $(document).bind("keydown keypress", function(e){
        if( e.which == 8 ){ // 8 == backspace
            if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
                alert('Ba');
            }
        }
    });
});
//document.addEventListener("deviceready", onDeviceReady, false);
//document.addEventListener("DOMContentLoaded", controlBack, false);
document.addEventListener("DOMContentLoaded", checkMenu, false);
document.addEventListener("DOMContentLoaded", checkSelectedOption, false);<|endoftext|>


<commit_before>import Promise from 'promise-polyfill';
import { loadFontGroup } from './utils/load-font';

const canela = [
	{ family: 'Canela Web', weight: 300 },
	{ family: 'Canela Web', weight: 700 },
];

const publico = [
	{ family: 'Publico Text Web', weight: 400 },
	{ family: 'Publico Text Web', weight: 700 },
];

const atlas = [
	{ family: 'Atlas Grotesk Web', weight: 400 },
	{ family: 'Atlas Grotesk Web', weight: 500 },
	{ family: 'Atlas Grotesk Web', weight: 600 },
];

// polyfill promise
if (!window.Promise) window.Promise = Promise;

// load fonts
loadFontGroup(canela);
loadFontGroup(publico);
loadFontGroup(atlas);
<commit_msg>include polyfills by default<commit_after>import Promise from 'promise-polyfill';
import './polyfills/endswith';
import './polyfills/find-index';
import './polyfills/find';
import './polyfills/includes';
import { loadFontGroup } from './utils/load-font';

const canela = [
	{ family: 'Canela Web', weight: 300 },
	{ family: 'Canela Web', weight: 700 },
];

const publico = [
	{ family: 'Publico Text Web', weight: 400 },
	{ family: 'Publico Text Web', weight: 700 },
];

const atlas = [
	{ family: 'Atlas Grotesk Web', weight: 400 },
	{ family: 'Atlas Grotesk Web', weight: 500 },
	{ family: 'Atlas Grotesk Web', weight: 600 },
];

// polyfill promise
if (!window.Promise) window.Promise = Promise;

// load fonts
loadFontGroup(canela);
loadFontGroup(publico);
loadFontGroup(atlas);
<|endoftext|>


<commit_before>var module = angular.module('royal-hub.processor', []);

module.provider('processor', function () {
  var listeners = [];
  this.addListener = function (listener) {
    listeners.push(listener);
  };

  this.$get = function (rating) {
    return {
      addEvent: function (githubEvent) {
        listeners.forEach(function (listener) {
          listener(githubEvent, rating);
        });
      }
    };
  };
});

module.service('rating', function () {
  this.rating = {};
  this.badges = {};

  this.addEvent = function (githubUser, event) {
    var userRating = this.rating[githubUser.id];
    if (userRating == null) {
      userRating = {
        user: githubUser,
        events: [],
        points: 0
      };
      this.rating[githubUser.id] = userRating;
    }
    userRating.events.push(event);
    userRating.points += event.points;
  };

  this.addBadge = function (githubUser, badge) {
    this.addEvent(githubUser, {
      type: 'Badge',
      badge: badge.key,
      points: 5,
      message: badge.message,
      timestamp: badge.timestamp
    });
    var userBadges = this.badges[githubUser.id];
    if (userBadges == null) {
      userBadges = {};
      this.badges[githubUser.id] = userBadges;
    }
    userBadges[badge.key] = true;
  };

  this.hasBadge = function(githubUser, badgeKey) {
    var userBadges = this.badges[githubUser.id];
    return !!(userBadges && userBadges[badgeKey]);
  };
});

/**
 * Score commits
 */
module.config(function (processorProvider) {
  processorProvider.addListener(function (githubEvent, rating) {
    if (githubEvent.type === 'PushEvent') {
      rating.addEvent(githubEvent.actor, {
        type: 'Push',
        points: githubEvent.payload.size,
        message: 'Pushed ' + githubEvent.payload.size + ' commit(s)',
        timestamp: githubEvent.created_at
      });
    }
  });
});

/**
 * Leo Tolstoy badge
 */
module.config(function (processorProvider) {
  var LONG_COMMIT_MESSAGE_LENGTH = 400;
  var BADGE_KEY = 'tolstoy';

  processorProvider.addListener(function (githubEvent, rating) {
    if (githubEvent.type === 'PushEvent' && !rating.hasBadge(githubEvent.actor, BADGE_KEY)) {
      githubEvent.payload.commits.forEach(function (commit) {
        if (commit.message && commit.message.length > LONG_COMMIT_MESSAGE_LENGTH) {
          rating.addBadge(githubEvent.actor, {
            key: BADGE_KEY,
            message: 'Got badge Leo Tolstoy for the commit comment: ' + commit.message,
            timestamp: githubEvent.created_at
          });
        }
      });
    }
  });
});
<commit_msg>Ouroboros in progress<commit_after>var module = angular.module('royal-hub.processor', []);

module.provider('processor', function () {
  var listeners = [];
  this.addListener = function (listener) {
    listeners.push(listener);
  };

  this.$get = function (rating) {
    return {
      addEvent: function (githubEvent) {
        listeners.forEach(function (listener) {
          listener(githubEvent, rating);
        });
      }
    };
  };
});

module.service('rating', function () {
  this.rating = {};
  this.badges = {};

  this.addEvent = function (githubUser, event) {
    var userRating = this.rating[githubUser.id];
    if (userRating == null) {
      userRating = {
        user: githubUser,
        events: [],
        points: 0
      };
      this.rating[githubUser.id] = userRating;
    }
    userRating.events.push(event);
    userRating.points += event.points;
  };

  this.addBadge = function (githubUser, badge) {
    this.addEvent(githubUser, {
      type: 'Badge',
      badge: badge.key,
      points: 5,
      message: badge.message,
      timestamp: badge.timestamp
    });
    var userBadges = this.badges[githubUser.id];
    if (userBadges == null) {
      userBadges = {};
      this.badges[githubUser.id] = userBadges;
    }
    userBadges[badge.key] = true;
  };

  this.hasBadge = function(githubUser, badgeKey) {
    var userBadges = this.badges[githubUser.id];
    return !!(userBadges && userBadges[badgeKey]);
  };
});

/**
 * Score commits
 */
module.config(function (processorProvider) {
  processorProvider.addListener(function (githubEvent, rating) {
    if (githubEvent.type === 'PushEvent') {
      rating.addEvent(githubEvent.actor, {
        type: 'Push',
        points: githubEvent.payload.size,
        message: 'Pushed ' + githubEvent.payload.size + ' commit(s)',
        timestamp: githubEvent.created_at
      });
    }
  });
});

/**
 * Leo Tolstoy badge
 */
module.config(function (processorProvider) {
  var LONG_COMMIT_MESSAGE_LENGTH = 400;
  var BADGE_KEY = 'tolstoy';

  processorProvider.addListener(function (githubEvent, rating) {
    if (githubEvent.type === 'PushEvent' && !rating.hasBadge(githubEvent.actor, BADGE_KEY)) {
      githubEvent.payload.commits.forEach(function (commit) {
        if (commit.message && commit.message.length > LONG_COMMIT_MESSAGE_LENGTH) {
          rating.addBadge(githubEvent.actor, {
            key: BADGE_KEY,
            message: 'Got badge Leo Tolstoy for the commit comment: ' + commit.message,
            timestamp: githubEvent.created_at
          });
        }
      });
    }
  });
});

/**
 * Ouroboros badge
 */
module.config(function (processorProvider) {
  var LONG_COMMIT_MESSAGE_LENGTH = 400;
  var BADGE_KEY = 'ouroboros';

  processorProvider.addListener(function (githubEvent, rating) {
    if (githubEvent.type === 'IssuesEvent' && !rating.hasBadge(githubEvent.actor, BADGE_KEY)) {
      var issue = githubEvent.payload.issue;
      //
      //if (issue.message && commit.message.length > LONG_COMMIT_MESSAGE_LENGTH) {
      //  rating.addBadge(githubEvent.actor, {
      //    key: BADGE_KEY,
      //    message: 'Got badge Leo Tolstoy for the commit comment: ' + commit.message,
      //    timestamp: githubEvent.created_at
      //  });
      //}

    }
  });
});
<|endoftext|>


<commit_before>/*! Kernel CI Dashboard | Licensed under the GNU GPL v3 (or later) */
define(function() {
    'use strict';
    var appConstants;

    appConstants = {
        MAX_DATE_RANGE: 14,
        MAX_QUERY_LIMIT: 1024
    };

    return appConstants;
});
<commit_msg>Define new const<commit_after>/*! Kernel CI Dashboard | Licensed under the GNU GPL v3 (or later) */
define(function() {
    'use strict';
    var appConstants;

    appConstants = {
        MAX_DATE_RANGE: 14,
        MAX_NUMBER_RANGE: 20,
        MAX_QUERY_LIMIT: 1024
    };

    return appConstants;
});
<|endoftext|>