<commit_before>/* extra stuff */

'use strict';

window.addEventListener('DOMContentLoaded', function () {
    angular.module('swiftBrowserE2E').run(function (swiftSim) {
        var text = [
            'Hey, this is some text. Have fun editing it!',
            '',
            '--Sincerely, the Swift Browser developers'
        ];
        var python = [
            'import math',
            '',
            'def primes(n):',
            '    """',
            '    Find all primes less than n.',
            '',
            '    >>> primes(3)',
            '    [2]',
            '    >>> primes(15)',
            '    [2, 3, 5, 7, 11, 13]',
            '    """',
            '    candidates = [True] * n',
            '    candidates[0] = candidates[1] = False',
            '    stop = int(math.sqrt(n))',
            '    for i in range(2, stop + 1):',
            '        if candidates[i]:',
            '            for j in range(2 * i, n, i):',
            '                candidates[j] = False',
            '    return [i for (i, c) in enumerate(candidates) if c]',
            '',
            'print "Primes below 20:", ", ".join(map(str, primes(20)))'
        ];
        var html = [
            '<!DOCTYPE html>',
            '',
            '  ',
            '    <meta charset="utf-8">',
            '    <title>Test Page</title>',
            '  ',
            '',
            '  ',
            '
Welcome!
',
            '
Pretty cool!
',
            '  ',
            ''
        ];

        swiftSim.addContainer('empty container');
        swiftSim.setObjects('foo', {
            'x.txt': {content: text.join('\n')},
            'primes.py': {content: python.join('\n')},
            'nested/z.html': {content: html.join('\n')}
        });

        /* Simple linear congruential random generator */
        var rand = (function () {
            var state = 1;
            var a = 31;
            var c = 11;
            var m = 50;
            return function () {
                state = (a * state + c) % m;
                return state;
            };
        })();

        var large = {};
        for (var i = 0; i < 1234; i++) {
            var r = rand();
            var xs = new Array(r + 1).join('x');
            var content = [
                'This is object ' + i + '.',
                '',
                'Here are: ' + r + " x's: " + xs + '.'
            ];
            large['o-' + i] = {content: content.join('\n')};
        }
        swiftSim.setObjects('large', large);

        swiftSim.setObjects('deep', {
            'this/is/a/deeply/nested/object.txt': {
                content: 'Maybe we could short-circuit the directories?\n'
            }
        });

        swiftSim.setObjects('funny names', {
            '   leading spaces': {content: ''},
            'trailing spaces   ': {content: ''},
            'Danish word: blåbærgrød': {
                content: 'This word means "blueberry porridge".\n'
            },
            'Japanese word: ブルーベリー': {
                content: 'Google Translate says this means "blueberry".\n'
            }
        });
    });
    angular.resumeBootstrap(['swiftBrowserE2E']);
});
<commit_msg>mock-env: partially revert d31c47a1f9ac<commit_after>/* extra stuff */

'use strict';

window.addEventListener('DOMContentLoaded', function () {
    angular.module('swiftBrowserE2E').run(function (swiftSim) {
        var text = [
            'Hey, this is some text. Have fun editing it!',
            '',
            '--Sincerely, the Swift Browser developers'
        ];
        var python = [
            'import math',
            '',
            'def primes(n):',
            '    """',
            '    Find all primes less than n.',
            '',
            '    >>> primes(3)',
            '    [2]',
            '    >>> primes(15)',
            '    [2, 3, 5, 7, 11, 13]',
            '    """',
            '    candidates = [True] * n',
            '    candidates[0] = candidates[1] = False',
            '    stop = int(math.sqrt(n))',
            '    for i in range(2, stop + 1):',
            '        if candidates[i]:',
            '            for j in range(2 * i, n, i):',
            '                candidates[j] = False',
            '    return [i for (i, c) in enumerate(candidates) if c]',
            '',
            'print "Primes below 20:", ", ".join(map(str, primes(20)))'
        ];
        var html = [
            '<!DOCTYPE html>',
            '',
            '  ',
            '    <meta charset="utf-8">',
            '    <title>Test Page</title>',
            '  ',
            '',
            '  ',
            '
Welcome!
',
            '
Pretty cool!
',
            '  ',
            ''
        ];

        swiftSim.addContainer('empty container');
        swiftSim.setObjects('foo', {
            'x.txt': {
                content: text.join('\n')
            },
            'primes.py': {
                content: python.join('\n'),
                headers: {'Content-Type': 'text/x-python'}
            },
            'nested/z.html': {
                content: html.join('\n'),
                headers: {'Content-Type': 'text/html'}
            }
        });

        /* Simple linear congruential random generator */
        var rand = (function () {
            var state = 1;
            var a = 31;
            var c = 11;
            var m = 50;
            return function () {
                state = (a * state + c) % m;
                return state;
            };
        })();

        var large = {};
        for (var i = 0; i < 1234; i++) {
            var r = rand();
            var xs = new Array(r + 1).join('x');
            var content = [
                'This is object ' + i + '.',
                '',
                'Here are: ' + r + " x's: " + xs + '.'
            ];
            large['o-' + i] = {content: content.join('\n')};
        }
        swiftSim.setObjects('large', large);

        swiftSim.setObjects('deep', {
            'this/is/a/deeply/nested/object.txt': {
                content: 'Maybe we could short-circuit the directories?\n'
            }
        });

        swiftSim.setObjects('funny names', {
            '   leading spaces': {content: ''},
            'trailing spaces   ': {content: ''},
            'Danish word: blåbærgrød': {
                content: 'This word means "blueberry porridge".\n'
            },
            'Japanese word: ブルーベリー': {
                content: 'Google Translate says this means "blueberry".\n'
            }
        });
    });
    angular.resumeBootstrap(['swiftBrowserE2E']);
});
<|endoftext|>


<commit_before>
define([
  'jquery',
  'underscore',
  'backbone',
  'collections/sidebar',
  'helpers/conf',
  'text!templates/sidebar.html'
], function ($, _, Backbone, SidebarCollection,
             ConfHelper, SidebarTemplate) {

  var SidebarView = Backbone.View.extend ({
    el: '#sidebar',
    leftFrameVisible: false,

    initialize: function () {
      this.sidebarCollection = new SidebarCollection ();

      // register channels event
      var that = this;

      $("#sidebar-wrapper").on ('scroll', function () {
        that.checkScroll (this);
      });

      // bind show left frame button for mobile layout
      $('#left-frame-toggle').click (function () { that.toggleLeftFrame (); });

      $(window).on ('resize', function () {
        that.hideLeftFrame ();
      });

      this.fillChannelsMenu();

      // TODO: add swipe events for sidebar
      // http://www.netcu.de/jquery-touchwipe-iphone-ipad-library
    },

    render: function () {

      var that = this;

      this.isLoading = true;

      this.sidebarCollection.fetch ({

        success: function (entries) {

          $(that.el).append (_.template (SidebarTemplate,
                                         {entries: entries.toJSON ()}));

          that.isLoading = false;

          // hide left frame when user clicks a item
          $('#sidebar a').click (function () {
            that.hideLeftFrame ();
          });

        }

      });
    },

    click: function (ev) {
      var channel = $(ev).attr ('href').match (/^#(hot)*(\/)*(.*?)$/, '')[3];

      if (channel == '')
        channel = 'basliklar/populer';
      else if (channel == 'bugun')
        channel = 'basliklar/bugun';
      else
        channel = 'basliklar/kanal/' + channel;

      this.sidebarCollection.channel = channel;
      this.sidebarCollection.page = 1;
      this.sidebarCollection.reset ();
      $(this.el).html ('');
      this.render ();

      this.showLeftFrame ();

      this.hideMenu(ev);
    },

    checkScroll: function () {
      if (!this.isLoading &&
          !this.sidebarCollection.lastPage () &&
          $('#sidebar-wrapper').scrollTop () +
              $('#sidebar-wrapper').height () + 200 >
              this.el.scrollHeight) {
        this.sidebarCollection.page++;
        this.render ();
      }

    },

    showLeftFrame: function () {
      if ($(window).width () > 767)
        return;
      $('#sidebar-wrapper').css ('margin-left', '0');
      this.leftFrameVisible = true;
    },

    hideLeftFrame: function () {
      $('#sidebar-wrapper').css ('margin-left', '-250px');
      this.leftFrameVisible = false;
    },

    toggleLeftFrame: function () {
      if (!this.leftFrameVisible)
        this.showLeftFrame ();
      else
        this.hideLeftFrame ();
    },

    fillChannelsMenu: function () {
      var that = this;

      $("#channels a").off();
      $('#channels li.divider').nextAll().remove();

      _.map(ConfHelper.options.channels, function(channel) {
        $('#channels').append(
            _.template('
<a href="#hot/<%= channel.substr(1, channel.length) %>"><%= channel %>
',
                       { channel: channel }))
      });

      $("#channels a").click (function () { that.click (this); });
    },

    // Hide menu for narrow screens
    hideMenu: function (currentTarget) {

      if ($(window).width () < 767 && $(currentTarget).attr ('href') != '#')
        $('div.navbar-eksi-okuyucu').removeClass('in');

    },

    bindHideMenu: function () {
      var that = this;

      $('div.navbar-eksi-okuyucu a').off();
      $('div.navbar-eksi-okuyucu a').click (function () {
        that.hideMenu(this);
      });
    }

  });

  return SidebarView;

});
<commit_msg>Remove removal of previous events<commit_after>
define([
  'jquery',
  'underscore',
  'backbone',
  'collections/sidebar',
  'helpers/conf',
  'text!templates/sidebar.html'
], function ($, _, Backbone, SidebarCollection,
             ConfHelper, SidebarTemplate) {

  var SidebarView = Backbone.View.extend ({
    el: '#sidebar',
    leftFrameVisible: false,

    initialize: function () {
      this.sidebarCollection = new SidebarCollection ();

      // register channels event
      var that = this;

      $("#sidebar-wrapper").on ('scroll', function () {
        that.checkScroll (this);
      });

      // bind show left frame button for mobile layout
      $('#left-frame-toggle').click (function () { that.toggleLeftFrame (); });

      $(window).on ('resize', function () {
        that.hideLeftFrame ();
      });

      this.fillChannelsMenu();

      // TODO: add swipe events for sidebar
      // http://www.netcu.de/jquery-touchwipe-iphone-ipad-library
    },

    render: function () {

      var that = this;

      this.isLoading = true;

      this.sidebarCollection.fetch ({

        success: function (entries) {

          $(that.el).append (_.template (SidebarTemplate,
                                         {entries: entries.toJSON ()}));

          that.isLoading = false;

          // hide left frame when user clicks a item
          $('#sidebar a').click (function () {
            that.hideLeftFrame ();
          });

        }

      });
    },

    click: function (ev) {
      console.log("ZZZZZZZZZZZ");
      var channel = $(ev).attr ('href').match (/^#(hot)*(\/)*(.*?)$/, '')[3];

      if (channel == '')
        channel = 'basliklar/populer';
      else if (channel == 'bugun')
        channel = 'basliklar/bugun';
      else
        channel = 'basliklar/kanal/' + channel;

      this.sidebarCollection.channel = channel;
      this.sidebarCollection.page = 1;
      this.sidebarCollection.reset ();
      $(this.el).html ('');
      this.render ();

      this.showLeftFrame ();

      this.hideMenu(ev);
    },

    checkScroll: function () {
      if (!this.isLoading &&
          !this.sidebarCollection.lastPage () &&
          $('#sidebar-wrapper').scrollTop () +
              $('#sidebar-wrapper').height () + 200 >
              this.el.scrollHeight) {
        this.sidebarCollection.page++;
        this.render ();
      }

    },

    showLeftFrame: function () {
      if ($(window).width () > 767)
        return;
      $('#sidebar-wrapper').css ('margin-left', '0');
      this.leftFrameVisible = true;
    },

    hideLeftFrame: function () {
      $('#sidebar-wrapper').css ('margin-left', '-250px');
      this.leftFrameVisible = false;
    },

    toggleLeftFrame: function () {
      if (!this.leftFrameVisible)
        this.showLeftFrame ();
      else
        this.hideLeftFrame ();
    },

    fillChannelsMenu: function () {
      var that = this;

      $("#channels a").off();
      $('#channels li.divider').nextAll().remove();

      _.map(ConfHelper.options.channels, function(channel) {
        $('#channels').append(
            _.template('
<a href="#hot/<%= channel.substr(1, channel.length) %>"><%= channel %>
',
                       { channel: channel }))
      });

      $("#channels a").click (function () { that.click (this); });
    },

    // Hide menu for narrow screens
    hideMenu: function (currentTarget) {

      if ($(window).width () < 767 && $(currentTarget).attr ('href') != '#')
        $('div.navbar-eksi-okuyucu').removeClass('in');

    },

    bindHideMenu: function () {
      var that = this;

      $('div.navbar-eksi-okuyucu a').click (function () {
        that.hideMenu(this);
      });
    }

  });

  return SidebarView;

});
<|endoftext|>


<commit_before>const SOCIAL_ICONS = {
  'bitbucket.com/': 'bitbucket',
  'facebook.com/': 'facebook-square',
  'github.com/': 'github',
  'pinterest.com/': 'pinterest',
  'plus.google.com/': 'google-plus',
  'reddit.com/': 'reddit',
  'tumblr.com/': 'tumblr',
  'twitter.com/': 'twitter',
  'weibo.com/': 'weibo',
  'wordpress.com/': 'wordpress',
  'youtube.com/': 'youtube'
};

export default SOCIAL_ICONS;
<commit_msg>Add Instagram and Medium<commit_after>const SOCIAL_ICONS = {
  'bitbucket.com/': 'bitbucket',
  'facebook.com/': 'facebook-square',
  'github.com/': 'github',
  'pinterest.com/': 'pinterest',
  'plus.google.com/': 'google-plus',
  'reddit.com/': 'reddit',
  'tumblr.com/': 'tumblr',
  'twitter.com/': 'twitter',
  'weibo.com/': 'weibo',
  'wordpress.com/': 'wordpress',
  'youtube.com/': 'youtube',
  'instagram.com/': 'instagram',
  'medium.com/': 'medium'
};

export default SOCIAL_ICONS;
<|endoftext|>


<commit_before>/*
===============================================================================================

    	Unify Project

		Homepage: unify-project.org
		License: MIT + Apache (V2)
		Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com

===============================================================================================
*/

/**
 * Detects the operating system name
 */
core.Module("unify.bom.detect.Html5Placeholder", {

	/** {Boolean} If html5 placeholders are supported */
	VALUE : (function(doc) {
		var i = doc.createElement("input");
        return ("placeholder" in i);
	})(document)
});
<commit_msg>Fix detection classes to support workers (no head, body document etc)<commit_after>/*
===============================================================================================

    	Unify Project

		Homepage: unify-project.org
		License: MIT + Apache (V2)
		Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com

===============================================================================================
*/

if (jasy.Env.isSet("runtime", "browser")) {
	/**
	 * Detects the operating system name
	 */
	core.Module("unify.bom.detect.Html5Placeholder", {

		/** {Boolean} If html5 placeholders are supported */
		VALUE : (function(doc) {
			var i = doc.createElement("input");
		    return ("placeholder" in i);
		})(document)
	});
} else {
	core.Module("unify.bom.detect.Html5Placeholder", {
		VALUE: true
	});
}
<|endoftext|>


<commit_before>Meteor.startup(i18nListsMoviesStartup);

function i18nListsMoviesStartup() {
    i18n.map('en', {
        listsMovies: {
            deleteMovieFailed: 'Unable to remove the movie from the list. {$1}',
            lists: 'Lists',
            addToList: 'Add movie to list',
            removeFromList: 'Remove from list',
            pickMovie: 'Pick me a movie',
            labels: {
                title: 'Title',
                runtime: 'Runtime',
                genres: 'Genres',
                userScore: 'My score',
                movieScore: 'Movie score'
            },
            filters: {
                title: 'Title...',
                genres: 'Genres...'
            },
            pickerDialog: {
                title: 'You should watch next...',
                next: 'Pick another movie',
                noMovieFound: 'No movie could be found.',
                error: 'Unable to pick a movie. {$1}'
            }
        }
    });
}<commit_msg>Text change<commit_after>Meteor.startup(i18nListsMoviesStartup);

function i18nListsMoviesStartup() {
    i18n.map('en', {
        listsMovies: {
            deleteMovieFailed: 'Unable to remove the movie from the list. {$1}',
            lists: 'Lists',
            addToList: 'Add movie to list',
            removeFromList: 'Remove from list',
            pickMovie: 'Pick me a movie!',
            labels: {
                title: 'Title',
                runtime: 'Runtime',
                genres: 'Genres',
                userScore: 'My score',
                movieScore: 'Movie score'
            },
            filters: {
                title: 'Title...',
                genres: 'Genres...'
            },
            pickerDialog: {
                title: 'You should watch next...',
                next: 'Pick another movie',
                noMovieFound: 'No movie could be found.',
                error: 'Unable to pick a movie. {$1}'
            }
        }
    });
}<|endoftext|>


<commit_before>const Command = require('../base/Command');
const moment = require('moment');

// To get the dates of any upcoming events if any (Adapted from shittybill#3024's Scorpio)
class CurrentEvents extends Command {
    constructor(client) {
        super(client, {
            name: 'currentevents',
            // enabled: false,
            category: "SWGoH",
            aliases: ['cevents', 'ce'],
            permissions: ['EMBED_LINKS'],    // Starts with ['SEND_MESSAGES', 'VIEW_CHANNEL'] so don't need to add them
            flags: {
                heists: {
                    aliases: ['$', 'heist']
                },
                heroic: {
                    aliases: ['hero']
                }
            }
        });
    }

    async run(client, message, [num], options) {
        const FLEET_CHALLENGES = ['shipevent_PRELUDE_ACKBAR', 'shipevent_PRELUDE_MACEWINDU', 'shipevent_PRELUDE_TARKIN', 'shipevent_SC01UPGRADE', 'shipevent_SC02TRAINING', 'shipevent_SC03TRAINING', 'shipevent_SC03ABILITY'];
        const MOD_CHALLENGES = ['restrictedmodbattle_set_1', 'restrictedmodbattle_set_2', 'restrictedmodbattle_set_3', 'restrictedmodbattle_set_4', 'restrictedmodbattle_set_5', 'restrictedmodbattle_set_6', 'restrictedmodbattle_set_7', 'restrictedmodbattle_set_8'];
        const DAILY_CHALLENGES = ['challenge_XP', 'challenge_CREDIT', 'challenge_ABILITYUPGRADEMATERIALS', 'challenge_EQUIPMENT_AGILITY', 'challenge_EQUIPMENT_INTELLIGENCE', 'challenge_EQUIPMENT_STRENGTH'];
        const HEISTS = ['EVENT_CREDIT_HEIST_GETAWAY_V2', 'EVENT_TRAINING_DROID_SMUGGLING'];
        const HEROIC = ['progressionevent_PIECES_AND_PLANS', 'progressionevent_GRANDMASTERS_TRAINING', 'EVENT_HERO_SCAVENGERREY'];

        const DEF_NUM = 10;
        const lang = message.guildSettings.swgohLanguage;

        let gohEvents = null;
        try {
            gohEvents = await client.swgohAPI.events(lang);
            gohEvents = gohEvents.events;
        } catch (e) {
            console.error(e);
        }

        // Let them specify the max # of events to show
        let eNum = parseInt(num);
        if (isNaN(eNum)) {
            eNum = DEF_NUM;
        }

        let filter = [];
        const evOut = [];
        if (options.flags.heists) {
            filter = filter.concat(HEISTS);
        }
        if (options.flags.heroic) {
            filter = filter.concat(HEROIC);
        }
        for (const event of gohEvents) {
            if (FLEET_CHALLENGES.includes(event.id) ||
                MOD_CHALLENGES.includes(event.id) ||
                DAILY_CHALLENGES.includes(event.id) ||
                event.id.includes('MOD_SALVAGE')) {
                delete gohEvents.event;
                continue;
            }

            if (filter.length) {
                if (filter.indexOf(event.id) < 0) {
                    delete gohEvents.event;
                    continue;
                }
            }

            // Filter out event dates from the past
            event.schedule = event.instances.filter(p => {
                if (!moment().isBefore(moment(p.endTime))) return false;
                return true;
            });

            // Put each event in the array
            event.schedule.forEach(s => {
                event.nameKey = event.nameKey
                    .replace(/\\n/g, ' ')
                    .replace(/(\[\/*c*-*\]|\[[\w\d]{6}\])/g,'')
                    .toProperCase();
                evOut.push({
                    name: (HEROIC.includes(event.id) || event.id === 'EVENT_CREDIT_HEIST_GETAWAY_V2') ? `**${event.nameKey}**` : event.nameKey,
                    date: s.startTime
                });
            });
        }

        const fields = [];
        let desc = '`------------------------------`';
        let count = 0;

        // Sort all the events
        const sortedEvents = evOut.sort((p, c) => p.date - c.date);
        for (const event of sortedEvents) {
            if (count >= eNum) break;
            count ++;
            // Expanded view
            // let enVal = '';
            // if (event.schedule.length) {
            //     if (fields.length >= eNum) break;
            //     event.schedule.forEach((d, ix) => {
            //         enVal += `${ix === 0 ? '' : '\n'}\`` + moment(d.start).format('DD/MM/YYYY') + '`';
            //     });
            //     fields.push({
            //         name: event.name,
            //         value: enVal + '\n`------------------------------`',
            //         inline: true
            //     });
            // }

            // Condensed view
            desc += `\n\`${moment(event.date).format('M-DD')} |\` ${event.name}`;
        }

        if (fields.length) {
            return message.channel.send({embed: {
                author: {
                    name: message.language.get('COMMAND_CURRENTEVENTS_HEADER')
                },
                color: 0x0f0f0f,
                description: message.language.get('COMMAND_CURRENTEVENTS_DESC', count),
                fields: fields
            }});
        } else if (count > 0) {
            return message.channel.send({embed: {
                author: {
                    name: message.language.get('COMMAND_CURRENTEVENTS_HEADER')
                },
                color: 0x0f0f0f,
                description: message.language.get('COMMAND_CURRENTEVENTS_DESC', count) + '\n' + desc + '\n`------------------------------`'
            }});
        } else {
            return message.channel.send('No events at this time');
        }
    }
}

module.exports = CurrentEvents;

<commit_msg>Added in a filter to keep the bounty hunter bonus drops out of the current events output<commit_after>const Command = require('../base/Command');
const moment = require('moment');

// To get the dates of any upcoming events if any (Adapted from shittybill#3024's Scorpio)
class CurrentEvents extends Command {
    constructor(client) {
        super(client, {
            name: 'currentevents',
            // enabled: false,
            category: "SWGoH",
            aliases: ['cevents', 'ce'],
            permissions: ['EMBED_LINKS'],    // Starts with ['SEND_MESSAGES', 'VIEW_CHANNEL'] so don't need to add them
            flags: {
                heists: {
                    aliases: ['$', 'heist']
                },
                heroic: {
                    aliases: ['hero']
                }
            }
        });
    }

    async run(client, message, [num], options) {
        const FLEET_CHALLENGES = ['shipevent_PRELUDE_ACKBAR', 'shipevent_PRELUDE_MACEWINDU', 'shipevent_PRELUDE_TARKIN', 'shipevent_SC01UPGRADE', 'shipevent_SC02TRAINING', 'shipevent_SC03TRAINING', 'shipevent_SC03ABILITY'];
        const MOD_CHALLENGES = ['restrictedmodbattle_set_1', 'restrictedmodbattle_set_2', 'restrictedmodbattle_set_3', 'restrictedmodbattle_set_4', 'restrictedmodbattle_set_5', 'restrictedmodbattle_set_6', 'restrictedmodbattle_set_7', 'restrictedmodbattle_set_8'];
        const DAILY_CHALLENGES = ['challenge_XP', 'challenge_CREDIT', 'challenge_ABILITYUPGRADEMATERIALS', 'challenge_EQUIPMENT_AGILITY', 'challenge_EQUIPMENT_INTELLIGENCE', 'challenge_EQUIPMENT_STRENGTH'];
        const HEISTS = ['EVENT_CREDIT_HEIST_GETAWAY_V2', 'EVENT_TRAINING_DROID_SMUGGLING'];
        const HEROIC = ['progressionevent_PIECES_AND_PLANS', 'progressionevent_GRANDMASTERS_TRAINING', 'EVENT_HERO_SCAVENGERREY'];
        const EXCLUDE_Strings = ['EVENT_ECONOMY_BH'];
        // console.log(gohEvents.map(e => e.id));

        const DEF_NUM = 10;
        const lang = message.guildSettings.swgohLanguage;

        let gohEvents = null;
        try {
            gohEvents = await client.swgohAPI.events(lang);
            gohEvents = gohEvents.events;
        } catch (e) {
            console.error(e);
        }

        // Let them specify the max # of events to show
        let eNum = parseInt(num);
        if (isNaN(eNum)) {
            eNum = DEF_NUM;
        }

        let filter = [];
        const excludeFilter = [];
        const evOut = [];
        if (options.flags.heists) {
            filter = filter.concat(HEISTS);
        }
        if (options.flags.heroic) {
            filter = filter.concat(HEROIC);
        }
        for (const event of gohEvents) {
            if (FLEET_CHALLENGES.includes(event.id) ||
                MOD_CHALLENGES.includes(event.id) ||
                DAILY_CHALLENGES.includes(event.id) ||
                event.id.includes('MOD_SALVAGE')) {
                delete gohEvents.event;
                continue;
            }

            EXCLUDE_Strings.forEach(e => {
                if (event.id.includes(e)) {
                    excludeFilter.push(event.id);
                }
            });

            if (filter.length) {
                if (filter.indexOf(event.id) < 0) {
                    delete gohEvents.event;
                    continue;
                }
            }

            if (excludeFilter.length) {
                if (excludeFilter.indexOf(event.id) > -1) {
                    delete gohEvents.event;
                    continue;
                }
            }

            // Filter out event dates from the past
            event.schedule = event.instances.filter(p => {
                if (!moment().isBefore(moment(p.endTime))) return false;
                return true;
            });

            // Put each event in the array
            event.schedule.forEach(s => {
                event.nameKey = event.nameKey
                    .replace(/\\n/g, ' ')
                    .replace(/(\[\/*c*-*\]|\[[\w\d]{6}\])/g,'')
                    .toProperCase();
                evOut.push({
                    name: (HEROIC.includes(event.id) || event.id === 'EVENT_CREDIT_HEIST_GETAWAY_V2') ? `**${event.nameKey}**` : event.nameKey,
                    date: s.startTime
                });
            });
        }

        const fields = [];
        let desc = '`------------------------------`';
        let count = 0;

        // Sort all the events
        const sortedEvents = evOut.sort((p, c) => p.date - c.date);
        for (const event of sortedEvents) {
            if (count >= eNum) break;
            count ++;
            // Expanded view
            // let enVal = '';
            // if (event.schedule.length) {
            //     if (fields.length >= eNum) break;
            //     event.schedule.forEach((d, ix) => {
            //         enVal += `${ix === 0 ? '' : '\n'}\`` + moment(d.start).format('DD/MM/YYYY') + '`';
            //     });
            //     fields.push({
            //         name: event.name,
            //         value: enVal + '\n`------------------------------`',
            //         inline: true
            //     });
            // }

            // Condensed view
            desc += `\n\`${moment(event.date).format('M-DD')} |\` ${event.name}`;
        }

        if (fields.length) {
            return message.channel.send({embed: {
                author: {
                    name: message.language.get('COMMAND_CURRENTEVENTS_HEADER')
                },
                color: 0x0f0f0f,
                description: message.language.get('COMMAND_CURRENTEVENTS_DESC', count),
                fields: fields
            }});
        } else if (count > 0) {
            return message.channel.send({embed: {
                author: {
                    name: message.language.get('COMMAND_CURRENTEVENTS_HEADER')
                },
                color: 0x0f0f0f,
                description: message.language.get('COMMAND_CURRENTEVENTS_DESC', count) + '\n' + desc + '\n`------------------------------`'
            }});
        } else {
            return message.channel.send('No events at this time');
        }
    }
}

module.exports = CurrentEvents;

<|endoftext|>


<commit_before>'use strict';

require('shelljs/global');
var _ = require('lodash');
var acquireRefs = require('../lib/acquireRefs');
var chalk = require('chalk');
var Command = require('../lib/command');
var getProjectId = require('../lib/getProjectId');
var logger = require('../lib/logger');
var requireAccess = require('../lib/requireAccess');
var requireConfig = require('../lib/requireConfig');
var RSVP = require('rsvp');
var utils = require('../lib/utils');

module.exports = new Command('functions:log [function_name]')
  .description('read logs from GCF Kubernetes cluster')
  .option('-P, --project <project_id>', 'override the project ID specified in firebase.json')
  .option('-f, --follow', 'tail logs from GCF Kubernetes cluster')
  .before(requireConfig)
  .before(requireAccess)
  .action(function(function_name, options) {
    if (!which('gcloud')) {
      logger.info('Sorry, this command requires gcloud');
      exit(1);
    }

    if (!which('kubectl')) {
      logger.info('Sorry, this command requires kubectl');
      exit(1);
    }

    var projectId = getProjectId(options);

    logger.info();
    logger.info(chalk.bold(chalk.gray('===') + ' Connecting to \'' + projectId +  '\' GCF Kubernetes cluster...'));
    logger.info();

    var cmd = 'gcloud config set project ' + projectId;
    utils.logBullet(cmd);
    exec(cmd, {silent:true});

    cmd = 'gcloud config set container/cluster gcf-cluster-us-central1-f';
    utils.logBullet(cmd);
    exec(cmd, {silent:true});

    cmd = 'gcloud container clusters get-credentials gcf-cluster-us-central1-f';
    utils.logBullet(cmd);
    var out = exec(cmd, {silent:true}).output;
    if (out.toLowerCase().indexOf('error: ') > -1) {
      echo(out);
      exit(1);
    }

    cmd = 'kubectl get pods -o json';
    utils.logBullet(cmd);
    var out = exec(cmd, {silent:true}).output;
    var pods = _.chain(JSON.parse(out).items)
      .pluck('metadata.name')
      .indexBy(function(name) {
          return name.substring(0, name.lastIndexOf('.'));
      })
      .value();

    cmd = 'kubectl logs';
    if (_.has(options, 'follow')) {
      cmd += ' -f';
    }
    if (_.isEmpty(pods)) {
      logger.info('Sorry, no running pod found.');
      exit(1);
    } else if (function_name) {
      if (pods[function_name]) {
        cmd += ' ' + pods[function_name] + ' worker';
      } else {
        logger.warn('Sorry, no running pod found for given function name ' + chalk.bold(function_name));
        exit(1);
      }
    } else {
      if (_.size(pods) == 1) {
        cmd += ' ' + _.values(pods)[0] + ' worker';
      } else {
        logger.info('Please select one of the available functions: ' + chalk.bold(_.keys(pods).join(', ')));
        exit(1);
      }
    }
    utils.logSuccess(cmd);
    logger.info();
    if (_.has(options, 'follow')) {
      exec(cmd, {silent:false});
    } else {
      var out = exec(cmd, {silent:true}).output;
      echo(out);
    }

    return RSVP.resolve('done');
  });
<commit_msg>Address bleigh's comments.<commit_after>'use strict';

var _ = require('lodash');
var acquireRefs = require('../lib/acquireRefs');
var chalk = require('chalk');
var Command = require('../lib/command');
var FirebaseError = require('../lib/error');
var getProjectId = require('../lib/getProjectId');
var logger = require('../lib/logger');
var requireAccess = require('../lib/requireAccess');
var requireConfig = require('../lib/requireConfig');
var RSVP = require('rsvp');
var sh = require('shelljs');
var utils = require('../lib/utils');

module.exports = new Command('functions:log [name]')
  .description('read logs from GCF Kubernetes cluster')
  .option('-P, --project <project_id>', 'override the project ID specified in firebase.json')
  .option('-f, --follow', 'tail logs from GCF Kubernetes cluster')
  .before(requireConfig)
  .before(requireAccess)
  .action(function(name, options) {
    if (!sh.which('gcloud')) {
      return RSVP.reject(new FirebaseError(
        'Must install gcloud (https://cloud.google.com/sdk/gcloud/) to use functions:log', {exit: 1}));
    }

    if (!sh.which('kubectl')) {
      return RSVP.reject(new FirebaseError(
        'Must have kubectl for functions:log. Please check that you have latest version of gcloud', {exit: 1}));
    }

    var projectId = getProjectId(options);

    logger.info();
    logger.info(chalk.bold(chalk.gray('===') + ' Connecting to \'' + projectId +  '\' GCF Kubernetes cluster...'));
    logger.info();

    var cmd = 'gcloud config set project ' + projectId;
    utils.logBullet(cmd);
    sh.exec(cmd, {silent:true});

    cmd = 'gcloud config set container/cluster gcf-cluster-us-central1-f';
    utils.logBullet(cmd);
    sh.exec(cmd, {silent:true});

    cmd = 'gcloud container clusters get-credentials gcf-cluster-us-central1-f';
    utils.logBullet(cmd);
    var out = sh.exec(cmd, {silent:true}).output;
    if (out.toLowerCase().indexOf('error: ') > -1) {
      echo(out);
      exit(1);
    }

    cmd = 'kubectl get pods -o json';
    utils.logBullet(cmd);
    var out = sh.exec(cmd, {silent:true}).output;
    var pods = _.chain(JSON.parse(out).items)
      .pluck('metadata.name')
      .indexBy(function(name) {
          return name.substring(0, name.lastIndexOf('.'));
      })
      .value();

    cmd = 'kubectl logs';
    if (options.follow) {
      cmd += ' -f';
    }
    if (_.isEmpty(pods)) {
      return RSVP.reject(new FirebaseError(
        'Sorry, no running pod found.', {exit: 1}));
    } else if (name) {
      if (pods[name]) {
        cmd += ' ' + pods[name] + ' worker';
      } else {
        return RSVP.reject(new FirebaseError(
          'Sorry, no running pod found for given function name ' + chalk.bold(name), {exit: 1}));
      }
    } else {
      if (_.size(pods) == 1) {
        cmd += ' ' + _.values(pods)[0] + ' worker';
      } else {
        return RSVP.reject(new FirebaseError(
          'Please select one of the available functions: ' + chalk.bold(_.keys(pods).join(', ')), {exit: 1}));
      }
    }
    utils.logSuccess(cmd);
    logger.info();
    if (options.follow) {
      sh.exec(cmd, {silent:false});
    } else {
      var out = sh.exec(cmd, {silent:true}).output;
      sh.echo(out);
    }

    return RSVP.resolve(true);
  });
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var api = require('../lib/api');
var chalk = require('chalk');
var Command = require('../lib/command');
var FirebaseError = require('../lib/error');
var gcp = require('../lib/gcp');
var getProjectId = require('../lib/getProjectId');
var logger = require('../lib/logger');
var requireAccess = require('../lib/requireAccess');
var requireConfig = require('../lib/requireConfig');
var RSVP = require('rsvp');
var sh = require('shelljs');
var utils = require('../lib/utils');

module.exports = new Command('functions:log [name]')
  .description('read logs from GCF Kubernetes cluster')
  .option('-P, --project <project_id>', 'override the project ID specified in firebase.json')
  .option('-n, --pageSize <page_size>', 'specify page size')
  .before(requireConfig)
  .before(requireAccess)
  .action(function(name, options) {
    var projectId = getProjectId(options);
    var authClient;
    return api.getAccessToken().then(function(result) {
      return gcp.createClient(result.access_token);
    }).then(function(client) {
      authClient = client;
      var filter = 'resource.type="cloud_function" labels."cloudfunctions.googleapis.com/region"="us-central1"'
      if (name) {
        filter += ' labels."cloudfunctions.googleapis.com/function_name"="'+ name +'"'
      }
      return gcp.cloudlogging.entries(authClient, projectId, filter, options.pageSize || 35);
    }).then(function(entries) {
      if ( _.isEmpty(entries)) {
        logger.info('No log entries found.')
      } else {
        _.forEach(entries, function(entry, id) {
          var __ = ' '
          logger.info(
            entry.severity.substring(0,1), __,
            entry.labels.execution_id || '              -', __,
            entry.timestamp, __,
            entry.resource.labels.function_name, __,
            entry.textPayload);
        });
      }
      return RSVP.resolve();
    }).catch(function(err) {
      return RSVP.reject(new FirebaseError(
        'Failed to list log entries ' + err.message , {exit: 1}));
    });
  });
<commit_msg>Address mbleigh's comments.<commit_after>'use strict';

var _ = require('lodash');
var api = require('../lib/api');
var chalk = require('chalk');
var Command = require('../lib/command');
var FirebaseError = require('../lib/error');
var gcp = require('../lib/gcp');
var getProjectId = require('../lib/getProjectId');
var logger = require('../lib/logger');
var requireAccess = require('../lib/requireAccess');
var requireConfig = require('../lib/requireConfig');
var RSVP = require('rsvp');
var sh = require('shelljs');
var utils = require('../lib/utils');

module.exports = new Command('functions:log')
  .description('read logs from GCF Kubernetes cluster')
  .option('-P, --project <project_id>', 'override the project ID specified in firebase.json')
  .option('-f, --function <function_name>', 'specify function name whose logs will be fetched')
  .option('-n, --lines <num_lines>', 'specify number of log lines to fetch')
  .before(requireConfig)
  .before(requireAccess)
  .action(function(options) {
    var projectId = getProjectId(options);
    var authClient;
    return api.getAccessToken().then(function(result) {
      return gcp.createClient(result.access_token);
    }).then(function(client) {
      authClient = client;
      var filter = 'resource.type="cloud_function" labels."cloudfunctions.googleapis.com/region"="us-central1"'
      if (options.function) {
        filter += ' labels."cloudfunctions.googleapis.com/function_name"="'+ options.function +'"'
      }
      return gcp.cloudlogging.entries(authClient, projectId, filter, options.lines || 35);
    }).then(function(entries) {
      if ( _.isEmpty(entries)) {
        logger.info('No log entries found.')
      } else {
        _.forEach(entries, function(entry, id) {
          var __ = ' '
          logger.info(
            entry.timestamp, __,
            entry.severity.substring(0,1), __,
            entry.resource.labels.function_name + ':', __,
            entry.textPayload);
        });
      }
      return RSVP.resolve(entries);
    }).catch(function(err) {
      return RSVP.reject(new FirebaseError(
        'Failed to list log entries ' + err.message , {exit: 1}));
    });
  });
<|endoftext|>


<commit_before>
var myApp = require('../app/fizz.js');
describe("Fizz Buzz tests ", function() {
it("should return `Fizz` for number divisible by 3", function() {
expect(myApp.fizzBuzz(3)).toBe('Fizz');
});
 it("should return `Buzz` for number divisible by 5", function() {
 expect(myApp.fizzBuzz(5)).toBe('Buzz');
 });
 it("should return `FizzBuzz` for 15", function() {
 expect(myApp.fizzBuzz(15)).toBe('FizzBuzz');
 });
 it("should return `FizzBuzz` for 45", function() {
 expect(myApp.fizzBuzz(45)).toBe('FizzBuzz');
 });  it("should return `FizzBuzz` for 90", function() {
 expect(myApp.fizzBuzz(90)).toBe('FizzBuzz');
 });  it("should return `Fizz` for 63", function() {
 expect(myApp.fizzBuzz(63)).toBe('Fizz');  });
 it("should return 7 since its indivisible by 3 and 5", function() {
 expect(myApp.fizzBuzz(7)).toBe(7);
 });
 it("should return 101 since its indivisible by 3 and 5", function() {
 expect(myApp.fizzBuzz(101)).toBe(101);
 });
 });<commit_msg> Add testcase 9 and 10 for fizztest<commit_after>
var myApp = require('../app/fizz.js');
describe("Fizz Buzz tests ", function() {
it("should return `Fizz` for number divisible by 3", function() {
expect(myApp.fizzBuzz(3)).toBe('Fizz');
});
 it("should return `Buzz` for number divisible by 5", function() {
 expect(myApp.fizzBuzz(5)).toBe('Buzz');
 });
 it("should return `FizzBuzz` for 15", function() {
 expect(myApp.fizzBuzz(15)).toBe('FizzBuzz');
 });
 it("should return `FizzBuzz` for 45", function() {
 expect(myApp.fizzBuzz(45)).toBe('FizzBuzz');
 });
 it("should return `FizzBuzz` for 90", function() {
 expect(myApp.fizzBuzz(90)).toBe('FizzBuzz');
 });
 it("should return `Fizz` for 63", function() {
 expect(myApp.fizzBuzz(63)).toBe('Fizz');  });
 it("should return 7 since its indivisible by 3 and 5", function() {
 expect(myApp.fizzBuzz(7)).toBe(7);
 });
 it("should return 101 since its indivisible by 3 and 5", function() {
 expect(myApp.fizzBuzz(101)).toBe(101);
 });
it("should return 104 since its indivisible by 3 and 5", function() {
	expect(myApp.fizzBuzz(104)).toBe(104);
})
it("should return 109 since its indivisible by 3 and 5", function() {
	expect(myApp.fizzBuzz(109)).toBe(109);
})
 });<|endoftext|>


<commit_before>import { app, BrowserWindow, Menu, ipcMain } from 'electron';

let mainWindow = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support'); // eslint-disable-line
  sourceMapSupport.install();
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')(); // eslint-disable-line global-require
  const path = require('path'); // eslint-disable-line
  const p = path.join(__dirname, '..', 'app', 'node_modules'); // eslint-disable-line
  require('module').globalPaths.push(p); // eslint-disable-line
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

const installExtensions = async () => {
  if (process.env.NODE_ENV === 'development') {
    const installer = require('electron-devtools-installer'); // eslint-disable-line global-require

    const extensions = [
      'REACT_DEVELOPER_TOOLS',
      'REDUX_DEVTOOLS'
    ];

    const forceDownload = !!process.env.UPGRADE_EXTENSIONS;

    // TODO: Use async interation statement.
    //       Waiting on https://github.com/tc39/proposal-async-iteration
    //       Promises will fail silently, which isn't what we want in development
    return Promise
      .all(extensions.map(name => installer.default(installer[name], forceDownload)))
      .catch(err => window.console.error(err));
  }
};

app.on('ready', async () => {
  await installExtensions();

  mainWindow = new BrowserWindow({
    show: false,
    width: 1200,
    height: 900,
    frame: false,
    resizable: true,
    minWidth: 1000,
    minHeight: 900,
    directWrite: false
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
    mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu.buildFromTemplate([{
        label: 'Inspect element',
        click() {
          mainWindow.inspectElement(x, y);
        }
      }]).popup(mainWindow);
    });
  }

  ipcMain.on('minsize', () => {
    mainWindow.minimize();
  });

  ipcMain.on('maxsize', () => {
    mainWindow.maximize();
  });
});
<commit_msg>hanxin<commit_after>import { app, BrowserWindow, Menu, ipcMain } from 'electron';

let mainWindow = null;

if (process.env.NODE_ENV === 'production') {
  const sourceMapSupport = require('source-map-support'); // eslint-disable-line
  sourceMapSupport.install();
}

if (process.env.NODE_ENV === 'development') {
  require('electron-debug')(); // eslint-disable-line global-require
  const path = require('path'); // eslint-disable-line
  const p = path.join(__dirname, '..', 'app', 'node_modules'); // eslint-disable-line
  require('module').globalPaths.push(p); // eslint-disable-line
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

const installExtensions = async () => {
  if (process.env.NODE_ENV === 'development') {
    const installer = require('electron-devtools-installer'); // eslint-disable-line global-require

    const extensions = [
      'REACT_DEVELOPER_TOOLS',
      'REDUX_DEVTOOLS'
    ];

    const forceDownload = !!process.env.UPGRADE_EXTENSIONS;

    // TODO: Use async interation statement.
    //       Waiting on https://github.com/tc39/proposal-async-iteration
    //       Promises will fail silently, which isn't what we want in development
    return Promise
      .all(extensions.map(name => installer.default(installer[name], forceDownload)))
      .catch(err => window.console.error(err));
  }
};

app.on('ready', async () => {
  await installExtensions();

  mainWindow = new BrowserWindow({
    show: false,
    width: 1200,
    height: 900,
    frame: false,
    resizable: true,
    minWidth: 1000,
    minHeight: 900,
    directWrite: true
  });

  mainWindow.loadURL(`file://${__dirname}/app.html`);

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.show();
    mainWindow.focus();
  });

  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  if (process.env.NODE_ENV === 'development') {
    mainWindow.openDevTools();
    mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu.buildFromTemplate([{
        label: 'Inspect element',
        click() {
          mainWindow.inspectElement(x, y);
        }
      }]).popup(mainWindow);
    });
  }

  ipcMain.on('minsize', () => {
    mainWindow.minimize();
  });

  ipcMain.on('maxsize', () => {
    mainWindow.maximize();
  });
});
<|endoftext|>


<commit_before>var should = require('should');

describe('IOB', function ( ) {
  var iob = require('../lib/iob')();

  it('should calculate IOB', function() {

    var time = new Date()
      , treatments = [ {
          created_at: time - 1,
          insulin: "1.00"
        }
      ]
      , profile = {
        dia: 3,
        sens: 0
      };

    var rightAfterBolus = iob.calcTotal(treatments, profile, time);

    rightAfterBolus.display.should.equal(1);

    var afterSomeTime = iob.calcTotal(treatments, profile, new Date(time.getTime() + (60 * 60 * 1000)));

    afterSomeTime.display.should.be.lessThan(1);
    afterSomeTime.display.should.be.greaterThan(0);

    var afterDIA = iob.calcTotal(treatments, profile, new Date(time.getTime() + (3 * 60 * 60 * 1000)));

    afterDIA.display.should.equal(0);

  });
});<commit_msg>fix iob test to expect new updated iob display value<commit_after>var should = require('should');

describe('IOB', function ( ) {
  var iob = require('../lib/iob')();

  it('should calculate IOB', function() {

    var time = new Date()
      , treatments = [ {
          created_at: time - 1,
          insulin: "1.00"
        }
      ]
      , profile = {
        dia: 3,
        sens: 0
      };

    var rightAfterBolus = iob.calcTotal(treatments, profile, time);

    rightAfterBolus.display.should.equal('1.00');

    var afterSomeTime = iob.calcTotal(treatments, profile, new Date(time.getTime() + (60 * 60 * 1000)));

    afterSomeTime.iob.should.be.lessThan(1);
    afterSomeTime.iob.should.be.greaterThan(0);

    var afterDIA = iob.calcTotal(treatments, profile, new Date(time.getTime() + (3 * 60 * 60 * 1000)));

    afterDIA.iob.should.equal(0);

  });
});<|endoftext|>


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

  // Set the main path on the server
  let URL="http://localhost/EntracesExitEmployees/index.php/"

  // it will get employee id
  var EMployeId="";

  // Redirect to Employee Details View
  $(".js_Employee").click(function () {

    // Get Employe Id
    var EmpId=$(this).data("empid");

    // Get Employe name in lower case
    var EmName=$(this).find("#js_EmpName").text().toLowerCase();

  });

  // Seacrh
  $("#js_SrchBtn").click(function () {

    // Get and convert the search string val to lowercase
    var Srchstring=$("#js_SrchString").val().toLowerCase();

    // add or remove deccision class
    $(this).toggleClass("Search");

    // Validate if the buttn has show class
    if ( $(this).hasClass("Search") ) {

      // Iterates over Employees list
      $(".js_Employee").each(function () {

        // Get the element
        var Item=$(this);

        // Get and convert the employees names to lower case
        var NamesFull=$(this).find(".js_EmpName").text().toLowerCase();

        // Separate the FstNme to the Name
        var SplitNames=NamesFull.split(" ");

        // Get only the name part
        var NamePart=SplitNames[0];

        // Validate Employees names
        if (NamePart != Srchstring) {

          // Hide the element.
          Item.hide();

        }

      });
      // End each

      // Change button text
      $(this).text("Show");

    }else {

      // Makes visible the employees
      $(".js_Employee").show();

      // Change button text
      $(this).text("Search");

    }

  });
  // End click

  // Get Employee Detail
  $(".js_Employee").click(function () {

    // Get Employe Id
    EMployeId= $(this).data("empid");

    // Start ajax
    $.ajax({
      type:"POST",
      url:URL+"EmployeeController/GetEmployeInfo",
      data:{EMPID:EMployeId},
      success:function (data) {

        // Display backend result in the dom
        $(".js_EmpInfo").html(data);

        // Get Employee info form Controller
        var RoleId=$("#js_EmpRole").text();
        var EmpNumber=$("#js_EmpNumberR").text();
        var FstName=$("#js_FstNmeR").text();
        var Name=$("#js_empnameR").text();

        // Place Employee info in the Employee details
        $("#js_empname").val(Name);
        $("#js_FstNme").val(FstName);
        $("#js_EmpNumber").val(EmpNumber);

        // Iterate over select tag
        $("#js_RolesId").each(function() {

          // select the option white the same roelid from employee
          $(this).find('option[value="'+RoleId+'"]').prop('selected', true);

        });

      },
      error:function (xhr) {

        alert("Error: " +xhr.responseText);

      }
    });
    // End ajax

    // Open modal
    $('#js_EmpDetail').modal('open');

  });

  // Update Employee Info
  $("#js_ModifyEmpInfo").click(function () {

    // Display Employee id
    alert(EMployeId);

    // Close modal
    $('#js_EmpDetail').modal('close');

  });
  // End click

  $.ajax({
    type:"GET",
    url:URL+"EmployeeController/ReturnJson",
    data:{},
    success:function (data) {

      // Display result in the dom
      $(".js_Json").html(data);

      // Parse data in to json
      var json = $.parseJSON(data);

      // Iterate over json array
      // $(json).each(function(i,val){
      //   $.each(val,function(k,v){
      //
      //     $(".js_Json").append("
"+k+" : "+v+"
")
      //   });
      // });

      $(json).each(function (i,val) {
        $(".js_Json").append("
"+val.Id+" :: "+ val.NameEmp +"
")

      });

    },
    error:function (xhr) {

      alert("Error: " +xhr.responseText);

    }
  });
  // End ajax

  // Allows use elements appended
  $(document).on('click','.js_t', function(){
  alert("HI");
  });

});
// End Scope
<commit_msg>Se agrego la linea para validar que efectivamente el evento click se esta ejecutndo en los elementos appendendeados<commit_after>$(document).ready(function () {

  // Set the main path on the server
  let URL="http://localhost/EntracesExitEmployees/index.php/"

  // it will get employee id
  var EMployeId="";

  // Redirect to Employee Details View
  $(".js_Employee").click(function () {

    // Get Employe Id
    var EmpId=$(this).data("empid");

    // Get Employe name in lower case
    var EmName=$(this).find("#js_EmpName").text().toLowerCase();

  });

  // Seacrh
  $("#js_SrchBtn").click(function () {

    // Get and convert the search string val to lowercase
    var Srchstring=$("#js_SrchString").val().toLowerCase();

    // add or remove deccision class
    $(this).toggleClass("Search");

    // Validate if the buttn has show class
    if ( $(this).hasClass("Search") ) {

      // Iterates over Employees list
      $(".js_Employee").each(function () {

        // Get the element
        var Item=$(this);

        // Get and convert the employees names to lower case
        var NamesFull=$(this).find(".js_EmpName").text().toLowerCase();

        // Separate the FstNme to the Name
        var SplitNames=NamesFull.split(" ");

        // Get only the name part
        var NamePart=SplitNames[0];

        // Validate Employees names
        if (NamePart != Srchstring) {

          // Hide the element.
          Item.hide();

        }

      });
      // End each

      // Change button text
      $(this).text("Show");

    }else {

      // Makes visible the employees
      $(".js_Employee").show();

      // Change button text
      $(this).text("Search");

    }

  });
  // End click

  // Get Employee Detail
  $(".js_Employee").click(function () {

    // Get Employe Id
    EMployeId= $(this).data("empid");

    // Start ajax
    $.ajax({
      type:"POST",
      url:URL+"EmployeeController/GetEmployeInfo",
      data:{EMPID:EMployeId},
      success:function (data) {

        // Display backend result in the dom
        $(".js_EmpInfo").html(data);

        // Get Employee info form Controller
        var RoleId=$("#js_EmpRole").text();
        var EmpNumber=$("#js_EmpNumberR").text();
        var FstName=$("#js_FstNmeR").text();
        var Name=$("#js_empnameR").text();

        // Place Employee info in the Employee details
        $("#js_empname").val(Name);
        $("#js_FstNme").val(FstName);
        $("#js_EmpNumber").val(EmpNumber);

        // Iterate over select tag
        $("#js_RolesId").each(function() {

          // select the option white the same roelid from employee
          $(this).find('option[value="'+RoleId+'"]').prop('selected', true);

        });

      },
      error:function (xhr) {

        alert("Error: " +xhr.responseText);

      }
    });
    // End ajax

    // Open modal
    $('#js_EmpDetail').modal('open');

  });

  // Update Employee Info
  $("#js_ModifyEmpInfo").click(function () {

    // Display Employee id
    alert(EMployeId);

    // Close modal
    $('#js_EmpDetail').modal('close');

  });
  // End click

  $.ajax({
    type:"GET",
    url:URL+"EmployeeController/ReturnJson",
    data:{},
    success:function (data) {

      // Display result in the dom
      $(".js_Json").html(data);

      // Parse data in to json
      var json = $.parseJSON(data);

      // Iterate over json array
      // $(json).each(function(i,val){
      //   $.each(val,function(k,v){
      //
      //     $(".js_Json").append("
"+k+" : "+v+"
")
      //   });
      // });

      $(json).each(function (i,val) {
        $(".js_Json").append("
"+val.Id+" :: "+ val.NameEmp +"
")

      });

    },
    error:function (xhr) {

      alert("Error: " +xhr.responseText);

    }
  });
  // End ajax

  // Allows use elements appended
  $(document).on('click','.js_t', function(){

    $(this).css("background-color", "yellow");

  });

});
// End Scope
<|endoftext|>


<commit_before>/*
 * service.js: RESTful JSON-based web service for the drone module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var haibu = require('../../haibu');

//
// ### function createRouter (dron, logger)
// #### @drone {Drone} Instance of the Drone resource to use in this router.
//
// Creates the Journey router which represents the `haibu` Drone webservice.
//
exports.createRouter = function (drone) {
  //
  // TODO (indexzero): Setup token-based auth for Drone API servers
  //
  haibu.router.strict = false;

  //
  // ### Default Root
  // `GET /` responds with default JSON message
  //
  haibu.router.get('/', function () {
    this.res.json(400, { message: 'No drones specified' });
  });

  //
  // ### Version Binding
  // `GET /version` returns the version string for this webservice
  //
  // TODO (indexzero): Consume `haibu.version` instead of journey.
  //
  haibu.router.get(/\/version/, function (response) {
    this.res.json(200, { version: 'haibu ' + haibu.version });
  });

  haibu.router.post(/\/deploy\/([\w\-\.]+)\/([\w\-\.]+)/, { stream: true }, function (userId, appId) {
    var res = this.res;

    drone.deploy(userId, appId, this.req, function (err, result) {
      if (err) {
        haibu.emit(['error', 'service'], 'error', err);
        return res.json(500, { error: err });
      }

      res.json(200, { drone: result });
    })
  });

  //
  // ### Drones Resource
  // Routes for RESTful access to the Drone resource.
  //
  haibu.router.path('/drones', function () {
    //
    // ### List Apps
    // `GET /drones` returns list of all drones managed by the
    // Drone associated with this router.
    //
    this.get(function () {
      var res = this.res,
          data = { drones: drone.list() };

      res.json(200, data);
    });

    //
    // ### List Drone Processes
    // `GET /drones/running` returns with a list of formatted
    // drone processes.
    //
    this.get(/\/running/, function () {
      this.res.json(200, drone.running());
    });

    //
    // ### Show App
    // `GET /drones/:id` shows details of a drone managed by the
    // Drone associated with this router.
    //
    this.get(/\/([\w\-\.]+)/, function (id) {
      var data = drone.show(id);
      if (typeof data === 'undefined') {
        this.res.json(404, { message: 'No drone(s) found for application ' + id });
      }
      else {
        this.res.json(200, data);
      }
    });

    //
    // ### Start Drone for App
    // `POST /drone/:id/start` starts a new drone for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/start/, function (id) {
      var res = this.res;

      drone.start(this.req.body.start, function (err, result) {
        if (err) {
          haibu.emit(['error', 'service'], 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { drone: result });
      });
    });

    //
    // ### Stop Drone for App
    // `POST /drone/:id/stop` stops all drones for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/stop/, function (id) {
      var res = this.res;

      drone.stop(this.req.body.stop.name, function (err, result) {
        if (err || !result) {
          err = err || new Error('Unknown error from drone.');
          haibu.emit('error:service', 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200);
      });
    });

    //
    // ### Restart Drone for App
    // `POST /drone/:id/restart` restarts all drones for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/restart/, function (id) {
      var res = this.res;

      drone.restart(this.req.body.restart.name, function (err, drones) {
        if (err) {
          haibu.emit(['error', 'service'], 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { drones: drones });
      });
    });

    //
    // ### Clean Drone for App
    // `POST /drones/:id/clean` removes all of the dependencies and source files for
    // the app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/clean/, function (id) {
      var res = this.res;

      drone.clean(this.req.body, function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { clean: true });
      });
    });

    //
    // ### Update Drone for App
    // `POST /drones/:id/update` cleans and starts
    // the app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/update/, function (id) {
      var res = this.res;

      drone.update(this.req.body, function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { update: true });
      });
    });

    //
    // ### Clean All Drones
    // `POST /drones/cleanall` removes all of the dependencies and source files for
    // all apps on this server.
    //
    this.post(/\/cleanall/, function (response) {
      var res = this.res;

      drone.cleanAll(function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { clean: true });
      });
    });
  });
};
<commit_msg>[minor] Remove unused response parameter<commit_after>/*
 * service.js: RESTful JSON-based web service for the drone module.
 *
 * (C) 2010, Nodejitsu Inc.
 *
 */

var haibu = require('../../haibu');

//
// ### function createRouter (dron, logger)
// #### @drone {Drone} Instance of the Drone resource to use in this router.
//
// Creates the Journey router which represents the `haibu` Drone webservice.
//
exports.createRouter = function (drone) {
  //
  // TODO (indexzero): Setup token-based auth for Drone API servers
  //
  haibu.router.strict = false;

  //
  // ### Default Root
  // `GET /` responds with default JSON message
  //
  haibu.router.get('/', function () {
    this.res.json(400, { message: 'No drones specified' });
  });

  //
  // ### Version Binding
  // `GET /version` returns the version string for this webservice
  //
  haibu.router.get(/\/version/, function () {
    this.res.json(200, { version: 'haibu ' + haibu.version });
  });

  haibu.router.post(/\/deploy\/([\w\-\.]+)\/([\w\-\.]+)/, { stream: true }, function (userId, appId) {
    var res = this.res;

    drone.deploy(userId, appId, this.req, function (err, result) {
      if (err) {
        haibu.emit(['error', 'service'], 'error', err);
        return res.json(500, { error: err });
      }

      res.json(200, { drone: result });
    })
  });

  //
  // ### Drones Resource
  // Routes for RESTful access to the Drone resource.
  //
  haibu.router.path('/drones', function () {
    //
    // ### List Apps
    // `GET /drones` returns list of all drones managed by the
    // Drone associated with this router.
    //
    this.get(function () {
      var res = this.res,
          data = { drones: drone.list() };

      res.json(200, data);
    });

    //
    // ### List Drone Processes
    // `GET /drones/running` returns with a list of formatted
    // drone processes.
    //
    this.get(/\/running/, function () {
      this.res.json(200, drone.running());
    });

    //
    // ### Show App
    // `GET /drones/:id` shows details of a drone managed by the
    // Drone associated with this router.
    //
    this.get(/\/([\w\-\.]+)/, function (id) {
      var data = drone.show(id);
      if (typeof data === 'undefined') {
        this.res.json(404, { message: 'No drone(s) found for application ' + id });
      }
      else {
        this.res.json(200, data);
      }
    });

    //
    // ### Start Drone for App
    // `POST /drone/:id/start` starts a new drone for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/start/, function (id) {
      var res = this.res;

      drone.start(this.req.body.start, function (err, result) {
        if (err) {
          haibu.emit(['error', 'service'], 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { drone: result });
      });
    });

    //
    // ### Stop Drone for App
    // `POST /drone/:id/stop` stops all drones for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/stop/, function (id) {
      var res = this.res;

      drone.stop(this.req.body.stop.name, function (err, result) {
        if (err || !result) {
          err = err || new Error('Unknown error from drone.');
          haibu.emit('error:service', 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200);
      });
    });

    //
    // ### Restart Drone for App
    // `POST /drone/:id/restart` restarts all drones for app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/restart/, function (id) {
      var res = this.res;

      drone.restart(this.req.body.restart.name, function (err, drones) {
        if (err) {
          haibu.emit(['error', 'service'], 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { drones: drones });
      });
    });

    //
    // ### Clean Drone for App
    // `POST /drones/:id/clean` removes all of the dependencies and source files for
    // the app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/clean/, function (id) {
      var res = this.res;

      drone.clean(this.req.body, function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { clean: true });
      });
    });

    //
    // ### Update Drone for App
    // `POST /drones/:id/update` cleans and starts
    // the app with :id on this server.
    //
    this.post(/\/([\w\-\.]+)\/update/, function (id) {
      var res = this.res;

      drone.update(this.req.body, function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { update: true });
      });
    });

    //
    // ### Clean All Drones
    // `POST /drones/cleanall` removes all of the dependencies and source files for
    // all apps on this server.
    //
    this.post(/\/cleanall/, function (response) {
      var res = this.res;

      drone.cleanAll(function (err, drones) {
        if (err) {
          haibu.emit('error:service', 'error', err);
          return res.json(500, { error: err });
        }

        res.json(200, { clean: true });
      });
    });
  });
};
<|endoftext|>


<commit_before>function logTestModule(module){
  console.log('\n==========\n' + module + '\n==========\n')
}
function logTestProto(proto){
  console.log('==> ' + proto)
}

var MAGNET = "magnet:?xt=urn:btih:6a9759bffd5c0af65319979fb7832189f4f3c35d&dn=sintel.mp4&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&tr=wss%3A%2F%2Ftracker.webtorrent.io&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel-1024-surround.mp4"
var OK = {
  'log': false,
  'client': false
}

/*
* TEST LOG
*/
function testLog(cb){
  logTestModule('Log')
  var Log = require('./log.js')

  logTestProto('print')
  Log.print('Print ok')

  logTestProto('echo')
  Log.echo('Echo ok')

  setTimeout(function(){
    delete Log
    cb(true)
  }, 1000)
}

testLog(function(value){
  OK.log = value
})

/*
* TEST CLIENT
*/
function testClient(cb){
  logTestModule('Client')
  var Client = require('./client.js')
  var c = new Client()

  logTestProto('on start')
  c.on('start', function(hash){
    console.log('Client start trigger')
    console.log('Hash: ' + hash)

    logTestProto('getTorrent')
    var torrent = c.getTorrent()
    console.log('Torrent: ')
    console.log(torrent)
  })

  logTestProto('on download')
  c.on('download', function(torrent){
    console.log('Client download trigger')
    console.log('Torrent: ')
    console.log(torrent)

    logTestProto('stop')
    c.stop()
  })

  logTestProto('on done')
  c.on('done', function(hash, name){
    console.log('Client done trigger')
    console.log('Hash: ' + hash + '\nName: ' + name)

    cb(true)
    delete Client
    delete c
  })

  c.download(MAGNET)
}

testClient(function(value){
  OK.client = value
})
<commit_msg>testing end of tests<commit_after>var MAGNET = "magnet:?xt=urn:btih:6a9759bffd5c0af65319979fb7832189f4f3c35d&dn=sintel.mp4&tr=wss%3A%2F%2Ftracker.btorrent.xyz&tr=wss%3A%2F%2Ftracker.fastcast.nz&tr=wss%3A%2F%2Ftracker.openwebtorrent.com&tr=wss%3A%2F%2Ftracker.webtorrent.io&ws=https%3A%2F%2Fwebtorrent.io%2Ftorrents%2Fsintel-1024-surround.mp4"
var OK = {
  'log': false,
  'client': false
}

function logTestModule(module){
  console.log('\n==========\n' + module + '\n==========\n')
}
function logTestProto(proto){
  console.log('==> ' + proto)
}
function finishTest(){
  var end = true
  for (var m in OK){
    end = end && OK[m]
  }
  if(end){
    process.exit(0)
  }
}

/*
* TEST LOG
*/
function testLog(cb){
  logTestModule('Log')
  var Log = require('./log.js')

  logTestProto('print')
  Log.print('Print ok')

  logTestProto('echo')
  Log.echo('Echo ok')

  setTimeout(function(){
    delete Log
    cb(true)
  }, 1000)
}

testLog(function(value){
  OK.log = value
  finishTest()
})

/*
* TEST CLIENT
*/
function testClient(cb){
  logTestModule('Client')
  var Client = require('./client.js')
  var c = new Client()

  logTestProto('on start')
  c.on('start', function(hash){
    console.log('Client start trigger')
    console.log('Hash: ' + hash)

    logTestProto('getTorrent')
    var torrent = c.getTorrent()
    console.log('Torrent: ')
    console.log(torrent)
  })

  logTestProto('on download')
  c.on('download', function(torrent){
    console.log('Client download trigger')
    console.log('Torrent: ')
    console.log(torrent)

    logTestProto('stop')
    c.stop()
  })

  logTestProto('on done')
  c.on('done', function(hash, name){
    console.log('Client done trigger')
    console.log('Hash: ' + hash + '\nName: ' + name)

    cb(true)
    delete Client
    delete c
  })

  c.download(MAGNET)
}

testClient(function(value){
  OK.client = value
  finishTest()
})
<|endoftext|>