<commit_before>/**
 * @fileoverview Localization utils.
 *
 * @see https://google.github.io/styleguide/javascriptguide.xml
 * @see https://developers.google.com/closure/compiler/docs/js-for-compiler
 * @module glize/locale
 */

/**
 * Gets the current value of the default locale.
 * @return {string} Returns the current value of the default locale.
 * @method
 */
 export const getLocale = function() {
  const env = ('object' === typeof navigator && navigator) ||
              ('object' === typeof process && process.env);
  const lang = env['userLanguage'] || env['language'] ||
               env['LANG'] || env['LANGUAGE'] || 'en';
  return lang.substr(0, 2).toLowerCase();
};

/**
 * Gets locale week names.
 * @return {!Array<string>} Returns week names.
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
 * @method
 */
export const getWeekNames = () => {
  const locale = getLocale();
  let names = days_[locale];

  if (!names) {
    try {
      const formatter = new Intl.DateTimeFormat(locale, {weekday: "short"});
      const date = new Date(2021, 0, 3); // Sun Jan 03 2021
      names = new Array(7);
      for (let i = 0; i < 7; ++i) {
        date.setDate(3 + i);
        names[i] = formatter.format(date);
      }
    } catch (ex) {
      names = getData_('days');
    }

    days_[locale] = names;
  }

  return names;
};

/**
 * Gets locale month names.
 * @return {!Array.<string>} Returns month names.
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
 * @method
 */
export const getMonthNames = () => {
  const locale = getLocale();
  let names = months_[locale];

  if (!names) {
    try {
      const formatter = new Intl.DateTimeFormat(locale, {month: "long"});
      const year = new Date().getFullYear();
      names = new Array(12);
      for (let i = 0; i < 12; ++i) {
        names[i] = formatter.format(new Date(year, i));
      }
    } catch (ex) {
      names = getData_('months');
    }

    months_[locale] = names;
  }

  return names;
};

/**
 * Gets locale month name.
 * @param {?Date=} date Optional date object, defaults is current date.
 * @return {string} Returns month name.
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
 * @method
 */
export const getMonthName = (date = new Date()) => {
  try {
    return date.toLocaleString(getLocale(), {month: "long"});
  } catch(ex) {
    return getMonthNames()[date.getMonth()];
  }
};

/**
 * Gets month number by month name.
 * @param {string} name The month name.
 * @return {number} Returns month number.
 * @method
 */
 export const getMonthByName = (name) => {
  const monthes = getMonthNames();

  for (let i = 0; i < monthes.length; ++i) {
    if (name.substr(0, 3).toLowerCase() ===
        monthes[i].substr(0, 3).toLowerCase()) {
      return i;
    }
  }

  return -1;
};

/**
 * Gets locale data by key. Used for backward compatibility.
 * @param {string} key Data key.
 * @return {!Array<string>} Returns locale data.
 * @method
 * @private
 */
const getData_ = (key) => (data_[getLocale()] || data_['en'])[key];

/**
 * Storage for cached month names for locale.
 * @type {!Object<string, !Array<string>}
 * @private
 */
let months_ = {};

/**
 * Storage for cached weekday names for locale.
 * @type {!Object<string, !Array<string>}
 * @private
 */
 let days_ = {};

/**
 * @type {!Object<string, !Object>}
 * @private
 */
const data_ = {
  'en': {
    'days': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    'months': ['January', 'February', 'March', 'April', 'May', 'June',
               'July', 'August', 'September', 'October', 'November',
               'December']
  },
  'de': {
    'days': ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
    'months': ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
               'Juli', 'August', 'September', 'Oktober', 'November',
               'Dezember']
  },
  'ru': {
    'days': ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
    'months': ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
               'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь',
               'Декабрь']
  }
};
<commit_msg>Fixed jsdoc tags<commit_after>/**
 * @fileoverview Localization utils.
 *
 * @see https://google.github.io/styleguide/javascriptguide.xml
 * @see https://developers.google.com/closure/compiler/docs/js-for-compiler
 * @module glize/locale
 */

/**
 * Gets the current value of the default locale.
 * @return {string} Returns the current value of the default locale.
 * @method
 */
 export const getLocale = function() {
  const env = ('object' === typeof navigator && navigator) ||
              ('object' === typeof process && process.env);
  const lang = env['userLanguage'] || env['language'] ||
               env['LANG'] || env['LANGUAGE'] || 'en';
  return lang.substr(0, 2).toLowerCase();
};

/**
 * Gets locale week names.
 * @return {!Array<string>} Returns week names.
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
 * @method
 */
export const getWeekNames = () => {
  const locale = getLocale();
  let names = days_[locale];

  if (!names) {
    try {
      const formatter = new Intl.DateTimeFormat(locale, {weekday: "short"});
      const date = new Date(2021, 0, 3); // Sun Jan 03 2021
      names = new Array(7);
      for (let i = 0; i < 7; ++i) {
        date.setDate(3 + i);
        names[i] = formatter.format(date);
      }
    } catch (ex) {
      names = getData_('days');
    }

    days_[locale] = names;
  }

  return names;
};

/**
 * Gets locale month names.
 * @return {!Array.<string>} Returns month names.
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
 * @method
 */
export const getMonthNames = () => {
  const locale = getLocale();
  let names = months_[locale];

  if (!names) {
    try {
      const formatter = new Intl.DateTimeFormat(locale, {month: "long"});
      const year = new Date().getFullYear();
      names = new Array(12);
      for (let i = 0; i < 12; ++i) {
        names[i] = formatter.format(new Date(year, i));
      }
    } catch (ex) {
      names = getData_('months');
    }

    months_[locale] = names;
  }

  return names;
};

/**
 * Gets locale month name.
 * @param {?Date=} date Optional date object, defaults is current date.
 * @return {string} Returns month name.
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
 * @method
 */
export const getMonthName = (date = new Date()) => {
  try {
    return date.toLocaleString(getLocale(), {month: "long"});
  } catch(ex) {
    return getMonthNames()[date.getMonth()];
  }
};

/**
 * Gets month number by month name.
 * @param {string} name The month name.
 * @return {number} Returns month number.
 * @method
 */
 export const getMonthByName = (name) => {
  const monthes = getMonthNames();

  for (let i = 0; i < monthes.length; ++i) {
    if (name.substr(0, 3).toLowerCase() ===
        monthes[i].substr(0, 3).toLowerCase()) {
      return i;
    }
  }

  return -1;
};

/**
 * Gets locale data by key. Used for backward compatibility.
 * @param {string} key Data key.
 * @return {!Array<string>} Returns locale data.
 * @method
 * @private
 */
const getData_ = (key) => (data_[getLocale()] || data_['en'])[key];

/**
 * Storage for cached month names for locale.
 * @type {!Object<string, !Array<string>>}
 * @private
 */
let months_ = {};

/**
 * Storage for cached weekday names for locale.
 * @type {!Object<string, !Array<string>>}
 * @private
 */
 let days_ = {};

/**
 * @type {!Object<string, !Object>}
 * @private
 */
const data_ = {
  'en': {
    'days': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    'months': ['January', 'February', 'March', 'April', 'May', 'June',
               'July', 'August', 'September', 'October', 'November',
               'December']
  },
  'de': {
    'days': ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
    'months': ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni',
               'Juli', 'August', 'September', 'Oktober', 'November',
               'Dezember']
  },
  'ru': {
    'days': ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
    'months': ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
               'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь',
               'Декабрь']
  }
};
<|endoftext|>


<commit_before>define(["backbone", "underscore", "jquery", "app", "hbs!contacts/templates/result-item"], function(Backbone, _, $, app, resultTemplate){
    var ResultItemView = Backbone.View.extend({
        manage: true,
        tagName: "li",
        attributes: {
            "class": "contact-record"
        },
        events: {
            "click .add-contact": "addContact"
        },
        addContact: function(ev) {
            if ('contacts' in navigator) {
                ev.preventDefault();
                this.handleContactNative();
                return false;
            }
            return true;
        },
        onContactSaveSuccess: function() {
            navigator.notification.alert(this.model.attributes.name + " has been added to your address book.", _.bind(this.render, this), "Contact Saved");
        },
        onContactSaveError: function(err) {
            var errorMessage = "An unknown error has occured";
            if (err.code === ContactError.UNKNOWN_ERROR) {
                // Log the error message but pass silently
                //
                // This is because we've seen the UNKNOWN_ERROR occur
                // even when everything seems to have succeeded.
                console.log(errorMessage);
                return;
            } else if (err.code === ContactError.INVALID_ARGUMENT_ERROR) {
                errorMessage = "An unknown error has occured";
            } else if (err.code === ContactError.TIMEOUT_ERROR) {
                errorMessage = "Enable to reach the address book";
            } else if (err.code === ContactError.PENDING_OPERATION_ERROR) {
                errorMessage = "Enable to reach the address book";
            } else if (err.code === ContactError.IO_ERROR) {
                errorMessage = "Enable to reach the address book";
            } else if (err.code === ContactError.NOT_SUPPORTED_ERROR) {
                errorMessage = "Function not supported";
            } else if (err.code === ContactError.PERMISSION_DENIED_ERROR) {
                errorMessage = "Permission denied";
            }
            navigator.notification.alert(errorMessage, _.bind(this.render, this), "Error");
        },
        handleContactNative: function() {
            var contact = navigator.contacts.create({
                displayName: this.model.attributes.name
            });

            var name = new ContactName();
            name.formatted = this.model.attributes.name;

            var names = this.extractName();
            if (names != null) {
                name.familyName = names[0];
                name.givenName = names[1];
            }

            contact.name = name;

            if (this.model.attributes.unit) {
                var organization = new ContactOrganization();
                organization.pref = true;
                organization.type = "Work";
                organization.name = this.model.attributes.unit;
                contact.organizations = [organization];
            }

            if (this.model.attributes.email) {
                var email = new ContactField();
                email.pref = true;
                email.type = "Work";
                email.value = this.model.attributes.email;
                contact.emails = [email];
            }

            if (this.model.attributes.external_tel) {
                // TODO try to update phone number with international prefix (or should it be on API-side?)
                var externalTel = new ContactField();
                externalTel.pref = true;
                externalTel.type = "External";
                externalTel.value = this.model.attributes.external_tel;
                contact.phoneNumbers = [externalTel];
            }
            contact.save(_.bind(this.onContactSaveSuccess, this), _.bind(this.onContactSaveError, this));
        },
        handleContactDataUri: function() {
            // will redirect the user - its browser should propose him to download the vcard
        },
        getVcard: function() {
            var vcard = "BEGIN:VCARD\n";

            var names = this.extractName();
            if (names != null) {
                vcard += "N:" + names[0] + ";" + names[1] + ";;;\n";
            }

            vcard += "FN:" + this.model.attributes.name + "\n";

            if (this.model.attributes.email) {
                vcard += "EMAIL;INTERNET:" + this.model.attributes.email + "\n";
            }

            if (this.model.attributes.external_tel) {
                vcard += "TEL;WORK:" + this.model.attributes.external_tel + "\n";
            }

            if (this.model.attributes.unit) {
                vcard += "ORG:" + this.model.attributes.unit + "\n";
            }

            vcard += "END:VCARD";

            return vcard;
        },
        extractName: function() {
            // attempt to get family name and given name out of a string
            // returns an array with last name, first name(s)
            // or null if there was an issue when trying to extract the parts
            var names = [];
            try {
                // TODO try to extract the prefix ("Mr", "Mrs" etc)
                var parts = this.model.attributes.name.split(',');
                names[0] = parts.shift();
                names[1] = parts.join().trim();
                return names;
            } catch(err) {
                console.log(err);
                return null;
            }
        },
        serialize: function() {
            var vcardData = "";
            if (!app.isCordova()) {
                // Only create a vCard if we're in a browser (not Cordova)
                var vcard = this.getVcard();
                vcardData = "data:text/vcard;base64," + btoa(vcard.replace(/\n/g, '\r\n'));
            }
            return {
                contact: this.model.toJSON(),
                vcardData: vcardData
            };
        },
        template: resultTemplate
    });
    return ResultItemView;
});
<commit_msg>jslinting<commit_after>define(["backbone", "underscore", "jquery", "app", "hbs!contacts/templates/result-item"], function(Backbone, _, $, app, resultTemplate){
    var ResultItemView = Backbone.View.extend({
        manage: true,
        tagName: "li",
        attributes: {
            "class": "contact-record"
        },
        events: {
            "click .add-contact": "addContact"
        },
        addContact: function(ev) {
            if ('contacts' in navigator) {
                ev.preventDefault();
                this.handleContactNative();
                return false;
            }
            return true;
        },
        onContactSaveSuccess: function() {
            navigator.notification.alert(this.model.attributes.name + " has been added to your address book.", _.bind(this.render, this), "Contact Saved");
        },
        onContactSaveError: function(err) {
            var errorMessage = "An unknown error has occured";
            if (err.code === ContactError.UNKNOWN_ERROR) {
                // Log the error message but pass silently
                //
                // This is because we've seen the UNKNOWN_ERROR occur
                // even when everything seems to have succeeded.
                console.log(errorMessage);
                return;
            } else if (err.code === ContactError.INVALID_ARGUMENT_ERROR) {
                errorMessage = "An unknown error has occured";
            } else if (err.code === ContactError.TIMEOUT_ERROR) {
                errorMessage = "Enable to reach the address book";
            } else if (err.code === ContactError.PENDING_OPERATION_ERROR) {
                errorMessage = "Enable to reach the address book";
            } else if (err.code === ContactError.IO_ERROR) {
                errorMessage = "Enable to reach the address book";
            } else if (err.code === ContactError.NOT_SUPPORTED_ERROR) {
                errorMessage = "Function not supported";
            } else if (err.code === ContactError.PERMISSION_DENIED_ERROR) {
                errorMessage = "Permission denied";
            }
            navigator.notification.alert(errorMessage, _.bind(this.render, this), "Error");
        },
        handleContactNative: function() {
            var contact = navigator.contacts.create({
                displayName: this.model.attributes.name
            });

            var name = new ContactName();
            name.formatted = this.model.attributes.name;

            var names = this.extractName();
            if (names !== null) {
                name.familyName = names[0];
                name.givenName = names[1];
            }

            contact.name = name;

            if (this.model.attributes.unit) {
                var organization = new ContactOrganization();
                organization.pref = true;
                organization.type = "Work";
                organization.name = this.model.attributes.unit;
                contact.organizations = [organization];
            }

            if (this.model.attributes.email) {
                var email = new ContactField();
                email.pref = true;
                email.type = "Work";
                email.value = this.model.attributes.email;
                contact.emails = [email];
            }

            if (this.model.attributes.external_tel) {
                // TODO try to update phone number with international prefix (or should it be on API-side?)
                var externalTel = new ContactField();
                externalTel.pref = true;
                externalTel.type = "External";
                externalTel.value = this.model.attributes.external_tel;
                contact.phoneNumbers = [externalTel];
            }
            contact.save(_.bind(this.onContactSaveSuccess, this), _.bind(this.onContactSaveError, this));
        },
        handleContactDataUri: function() {
            // will redirect the user - its browser should propose him to download the vcard
        },
        getVcard: function() {
            var vcard = "BEGIN:VCARD\n";

            var names = this.extractName();
            if (names !== null) {
                vcard += "N:" + names[0] + ";" + names[1] + ";;;\n";
            }

            vcard += "FN:" + this.model.attributes.name + "\n";

            if (this.model.attributes.email) {
                vcard += "EMAIL;INTERNET:" + this.model.attributes.email + "\n";
            }

            if (this.model.attributes.external_tel) {
                vcard += "TEL;WORK:" + this.model.attributes.external_tel + "\n";
            }

            if (this.model.attributes.unit) {
                vcard += "ORG:" + this.model.attributes.unit + "\n";
            }

            vcard += "END:VCARD";

            return vcard;
        },
        extractName: function() {
            // attempt to get family name and given name out of a string
            // returns an array with last name, first name(s)
            // or null if there was an issue when trying to extract the parts
            var names = [];
            try {
                // TODO try to extract the prefix ("Mr", "Mrs" etc)
                var parts = this.model.attributes.name.split(',');
                names[0] = parts.shift();
                names[1] = parts.join().trim();
                return names;
            } catch(err) {
                console.log(err);
                return null;
            }
        },
        serialize: function() {
            var vcardData = "";
            if (!app.isCordova()) {
                // Only create a vCard if we're in a browser (not Cordova)
                var vcard = this.getVcard();
                vcardData = "data:text/vcard;base64," + btoa(vcard.replace(/\n/g, '\r\n'));
            }
            return {
                contact: this.model.toJSON(),
                vcardData: vcardData
            };
        },
        template: resultTemplate
    });
    return ResultItemView;
});
<|endoftext|>


<commit_before>var ChatCommand = function(){

    var connection, userEmail;
    var $inputMessage = $("#inputMessage");
    var $messageBox = $('#messagesBox');

    return {

        init: function(serverAddress, restrictedMode){
            userEmail = restrictedMode || prompt("Now tell me you e-mail bro (we use it for Gravatar images)!", "dude'o");
            connection = io.connect('http://' + serverAddress + ':1337');

            $inputMessage.focus();

            connection.on('forceClientEmail', function(data) {
                userEmail = data.email;
                connection.emit("message", {userEmail: userEmail});
            });

            var hasNotAlreadyFetchedHistory = true;
            connection.on('chatHistoryLoad', function(chatMessages) {
                if(hasNotAlreadyFetchedHistory){
                    chatMessages.forEach(function(chatMessage){
                        addMessageToChatBox(chatMessage);
                    });
                    hasNotAlreadyFetchedHistory = false;
                }
            });

            connection.on('userJoined', function(user) {
                ChatCommand.scrollToBottom();
                var html = "
";
                html += "(" + user + ")";
                html += " entered the room.
";
                $("#messagesBox").append(html);
            });

            connection.on('userDisconnected', function(user) {
                ChatCommand.scrollToBottom();
                var html = "
";
                html += "(" + user + ")";
                html += " exited the room.
";
                $("#messagesBox").append(html);
            });

            connection.on('receiveMessage', addMessageToChatBox);

            $(document).tooltip({
                items: "[tooltip], [avatar]",
                position: {
                    my: "center bottom-25",
                    at: "center top",
                    collision: "flipfit flip",
                    using: function( position, feedback ) {
                        $(this).css( position );
                        $("
")
                            .addClass( "ui-tooltip-arrow" )
                            .addClass( feedback.vertical )
                            .addClass( feedback.horizontal )
                            .appendTo( this );
                    }
                },
                content: function() {
                    var element = $( this );
                    if (element.is("[tooltip]")) {
                        var url = $(this).attr("href")
                        return isImage(url) ? "" : false;
                    } else {
                        var url = $(this).attr("data-img")
                        return "";
                    }
                }
            });

            function isImage(url) {
                return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
            }

            function urlify(text) {
                var urlRegex = /(https?:\/\/[^\s]+)/g;
                return text.replace(urlRegex, '$1');
            }

            function addMessageToChatBox(data){
                ChatCommand.scrollToBottom();

                var msg = '
' + urlify(data.messageContent) + '
';

                var lastMessage = $(".messageBlock").last();
                if (lastMessage.find('.messageEmail').text() == data.userEmail) {
                    $(".messageBlock").last().find('.message').append(msg)
                } else {

                    var otherUserMessageClass = data.userEmail == userEmail ? "" : " otherUserMessage";

                    var html = '
';
                    html += '
'
                    html += '';
                    html += '
';
                    html += '
';
                    html += '
' + data.userEmail + '
';
                    html += msg;
                    html += '
';
                    html += '
';
                    $messageBox.append(html);
                }

                if(data.userEmail != userEmail){
                    $.titleAlert("New chat message!", {
                        stopOnFocus: true,
                        requireBlur: true
                    });
                }
            };

        },

        execute: function(chatMessage) {
            var message = removeHTMLTags(chatMessage);
            if (message.trim() > "" ) {
                connection.emit('newMessage', {
                    messageContent: message,
                    userEmail: userEmail
                });
                $inputMessage.val("").focus();
            }
        },

        scrollToBottom: function () {
            var scrollHeight = $messageBox.prop("scrollHeight");
            var outerHeight = $messageBox.scrollTop() + $messageBox.outerHeight();

            if (scrollHeight === outerHeight) {
                setTimeout(function() {$messageBox.scrollTop($messageBox.prop("scrollHeight"))}, 100);
            }
        },

        on: function (event, callback) {
            connection.on(event, callback);
        },

        emit: function (event, callback) {
            connection.emit(event, callback);
        }
    }

    function removeHTMLTags(text) {
        var regex = /(<([^>]+)>)/ig
        return text.replace(regex, "").replace(/(&nbsp)*/g,"");
    }

}();<commit_msg>Code refactoring<commit_after>var ChatCommand = function(){

    var connection, userEmail;
    var $inputMessage = $("#inputMessage");
    var $messageBox = $('#messagesBox');

    return {

        init: function(serverAddress, restrictedMode){
            userEmail = restrictedMode || prompt("Now tell me you e-mail bro (we use it for Gravatar images)!", "dude'o");
            connection = io.connect('http://' + serverAddress + ':1337');

            $inputMessage.focus();

            connection.on('forceClientEmail', function(data) {
                userEmail = data.email;
                connection.emit("message", {userEmail: userEmail});
            });

            var hasNotAlreadyFetchedHistory = true;
            connection.on('chatHistoryLoad', function(chatMessages) {
                if(hasNotAlreadyFetchedHistory){
                    chatMessages.forEach(function(chatMessage){
                        addMessageToChatBox(chatMessage);
                    });
                    hasNotAlreadyFetchedHistory = false;
                }
            });

            connection.on('userJoined', function(user) {
                ChatCommand.scrollToBottom();
                var html = "
";
                html += "(" + user + ")";
                html += " entered the room.
";
                $("#messagesBox").append(html);
            });

            connection.on('userDisconnected', function(user) {
                ChatCommand.scrollToBottom();
                var html = "
";
                html += "(" + user + ")";
                html += " exited the room.
";
                $("#messagesBox").append(html);
            });

            connection.on('receiveMessage', addMessageToChatBox);

            $(document).tooltip({
                items: "[tooltip], [avatar]",
                position: {
                    my: "center bottom-25",
                    at: "center top",
                    collision: "flipfit flip",
                    using: function( position, feedback ) {
                        $(this).css( position );
                        $("
")
                            .addClass( "ui-tooltip-arrow" )
                            .addClass( feedback.vertical )
                            .addClass( feedback.horizontal )
                            .appendTo( this );
                    }
                },
                content: function() {
                    var element = $( this );
                    if (element.is("[tooltip]")) {
                        var url = $(this).attr("href")
                        return isImage(url) ? "" : false;
                    } else {
                        var url = $(this).attr("data-img")
                        return "";
                    }
                }
            });

            function isImage(url) {
                return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
            }

            function urlify(text) {
                var urlRegex = /(https?:\/\/[^\s]+)/g;
                return text.replace(urlRegex, '$1');
            }

            function addMessageToChatBox(data){
                ChatCommand.scrollToBottom();

                var msg = '
' + urlify(data.messageContent) + '
';

                var lastMessage = $(".messageBlock").last();
                if (lastMessage.find('.messageEmail').text() == data.userEmail) {
                    $(".messageBlock").last().find('.message').append(msg)
                } else {

                    $('
'
                    + '
'
                    + ''
                    + '
'
                    + '
'
                    + '
' + data.userEmail + '
'
                    + msg
                    + '
'
                    + '
').appendTo($messageBox);

                    var isMessageFromAnotherUser = data.userEmail != userEmail;
                    if(isMessageFromAnotherUser){
                        var currentMessage =$(".messageBlock").last();
                        currentMessage
                            .addClass("otherUserMessage")
                            .find(".messagePhoto, .messageEmail")
                            .addClass("otherUserMessage");
                    }

                }

                if(data.userEmail != userEmail){
                    $.titleAlert("New chat message!", {
                        stopOnFocus: true,
                        requireBlur: true
                    });
                }
            };

        },

        execute: function(chatMessage) {
            var message = removeHTMLTags(chatMessage);
            if (message.trim() > "" ) {
                connection.emit('newMessage', {
                    messageContent: message,
                    userEmail: userEmail
                });
                $inputMessage.val("").focus();
            }
        },

        scrollToBottom: function () {
            var scrollHeight = $messageBox.prop("scrollHeight");
            var outerHeight = $messageBox.scrollTop() + $messageBox.outerHeight();

            if (scrollHeight === outerHeight) {
                setTimeout(function() {$messageBox.scrollTop($messageBox.prop("scrollHeight"))}, 100);
            }
        },

        on: function (event, callback) {
            connection.on(event, callback);
        },

        emit: function (event, callback) {
            connection.emit(event, callback);
        }
    }

    function removeHTMLTags(text) {
        var regex = /(<([^>]+)>)/ig
        return text.replace(regex, "").replace(/(&nbsp)*/g,"");
    }

}();<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';

import { RichText } from 'prismic-reactjs';

export default class LobbyMessage extends React.Component {
  static propTypes = {
    bookmark: PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);

    this.state = {
      document: null,
      bookmarks: null,
    };

    this.fetchDocument(props.bookmark);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.bookmark !== this.props.bookmark) {
      this.fetchDocument(nextProps.bookmark);
    }
  }

  async getIdByBookmark(bookmark) {
    if (this.state.bookmarks) {
      return this.state.bookmarks[bookmark];
    }

    const r = await fetch('https://ab-marketing.prismic.io/api/v2');
    const json = await r.json();

    this.setState({
      bookmarks: json.bookmarks,
    });

    return json.bookmarks[bookmark];
  }

  async fetchDocument(bookmark) {
    const documentId = await this.getIdByBookmark(bookmark);
    const r = await fetch(`https://ab-marketing.prismic.io/api/v2/documents/search?ref=Wc4-7ScAACgANK0y&q=%5B%5Bat(document.id%2C+%22${documentId}%22)%5D%5D&format=json`, {
      headers: {
        Accept: 'application/json',
      },
    });
    const { results } = await r.json();

    if (results && results.length === 1) {
      this.setState({
        document: results[0],
      });
    }
  }

  render() {
    const { document } = this.state;

    if (!document) {
      return null;
    }

    return (

        {RichText.render(document.data.title)}
        {RichText.render(document.data.message)}
        {document.data.embed && document.data.embed.html &&

        }

    );
  }

}
<commit_msg>Fix lobby message request<commit_after>import React from 'react';
import PropTypes from 'prop-types';

import { RichText } from 'prismic-reactjs';

export default class LobbyMessage extends React.Component {
  static propTypes = {
    bookmark: PropTypes.string.isRequired,
  };

  constructor(props) {
    super(props);

    this.state = {
      document: null,
      bookmarks: null,
    };

    this.fetchDocument(props.bookmark);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.bookmark !== this.props.bookmark) {
      this.fetchDocument(nextProps.bookmark);
    }
  }

  async fetchSettings() {
    const r = await fetch('https://ab-marketing.prismic.io/api/v2');
    const json = await r.json();

    this.setState({
      bookmarks: json.bookmarks,
      ref: json.refs[0].ref,
    });
  }

  async fetchDocument(bookmark) {
    if (!this.state.bookmarks) {
      await this.fetchSettings();
    }

    const { ref, bookmarks } = this.state;
    const documentId = await bookmarks[bookmark];

    const r = await fetch(`https://ab-marketing.prismic.io/api/v2/documents/search?ref=${ref}&q=%5B%5Bat(document.id%2C+%22${documentId}%22)%5D%5D&format=json`, {
      headers: {
        Accept: 'application/json',
      },
    });
    const { results } = await r.json();

    if (results && results.length === 1) {
      this.setState({
        document: results[0],
      });
    }
  }

  render() {
    const { document } = this.state;

    if (!document) {
      return null;
    }

    return (

        {RichText.render(document.data.title)}
        {RichText.render(document.data.message)}
        {document.data.embed && document.data.embed.html &&

        }

    );
  }

}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets: true, $, PathUtils, window, navigator */

/**
 * brackets is the root of the Brackets codebase. This file pulls in all other modules as
 * dependencies (or dependencies thereof), initializes the UI, and binds global menus & keyboard
 * shortcuts to their Commands.
 *
 * TODO: (issue #264) break out the definition of brackets into a separate module from the application controller logic
 *
 * Unlike other modules, this one can be accessed without an explicit require() because it exposes
 * a global object, window.brackets.
 */
define(function (require, exports, module) {
    'use strict';

    // Load dependent non-module scripts
    require("widgets/bootstrap-dropdown");
    require("widgets/bootstrap-modal");
    require("thirdparty/path-utils/path-utils.min");
    require("thirdparty/smart-auto-complete/jquery.smart_autocomplete");

    // Load LiveDeveopment
    require("LiveDevelopment/main");

    // Load dependent modules
    var ProjectManager          = require("project/ProjectManager"),
        DocumentManager         = require("document/DocumentManager"),
        EditorManager           = require("editor/EditorManager"),
        CSSInlineEditor         = require("editor/CSSInlineEditor"),
        WorkingSetView          = require("project/WorkingSetView"),
        DocumentCommandHandlers = require("document/DocumentCommandHandlers"),
        FileViewController      = require("project/FileViewController"),
        FileSyncManager         = require("project/FileSyncManager"),
        KeyBindingManager       = require("command/KeyBindingManager"),
        KeyMap                  = require("command/KeyMap"),
        Commands                = require("command/Commands"),
        CommandManager          = require("command/CommandManager"),
        BuildInfoUtils          = require("utils/BuildInfoUtils"),
        CodeHintManager         = require("editor/CodeHintManager"),
        JSLintUtils             = require("language/JSLintUtils"),
        PerfUtils               = require("utils/PerfUtils"),
        FileIndexManager        = require("project/FileIndexManager"),
        QuickOpen               = require("search/QuickOpen"),
        Menus                   = require("command/Menus"),
        FileUtils               = require("file/FileUtils"),
        Strings                 = require("strings"),
        Dialogs                 = require("widgets/Dialogs"),
        ExtensionLoader         = require("utils/ExtensionLoader"),
        SidebarView             = require("project/SidebarView"),
        Async                   = require("utils/Async");

    //Load modules that self-register and just need to get included in the main project
    require("editor/CodeHintManager");
    require("editor/EditorCommandHandlers");
    require("debug/DebugCommandHandlers");
    require("view/ViewCommandHandlers");
    require("search/FindInFiles");

    function _initGlobalBrackets() {
        // Define core brackets namespace if it isn't already defined
        //
        // We can't simply do 'brackets = {}' to define it in the global namespace because
        // we're in "use strict" mode. Most likely, 'window' will always point to the global
        // object when this code is running. However, in case it isn't (e.g. if we're running
        // inside Node for CI testing) we use this trick to get the global object.
        //
        // Taken from:
        //   http://stackoverflow.com/questions/3277182/how-to-get-the-global-object-in-javascript
        var Fn = Function, global = (new Fn('return this'))();
        if (!global.brackets) {
            global.brackets = {};
        }

        // Uncomment the following line to force all low level file i/o routines to complete
        // asynchronously. This should only be done for testing/debugging.
        // NOTE: Make sure this line is commented out again before committing!
        //brackets.forceAsyncCallbacks = true;

        // Load native shell when brackets is run in a native shell rather than the browser
        // TODO: (issue #266) load conditionally
        brackets.shellAPI = require("utils/ShellAPI");

        brackets.inBrowser = !brackets.hasOwnProperty("fs");

        brackets.platform = (global.navigator.platform === "MacIntel" || global.navigator.platform === "MacPPC") ? "mac" : "win";

        // Loading extensions requires creating new require.js contexts, which requires access to the global 'require' object
        // that always gets hidden by the 'require' in the AMD wrapper. We store this in the brackets object here so that
        // the ExtensionLoader doesn't have to have access to the global object.
        brackets.libRequire = global.require;

        // Also store our current require.js context (the one that loads brackets core modules) so that extensions can use it
        // Note: we change the name to "getModule" because this won't do exactly the same thing as 'require' in AMD-wrapped
        // modules. The extension will only be able to load modules that have already been loaded once.
        brackets.getModule = require;
    }

    function _initExtensions() {
        // FUTURE (JRB): As we get more fine-grained performance measurement, move this out of core application startup
        return Async.doInParallel(["default", "user"], function (item) {
            return ExtensionLoader.loadAllExtensionsInNativeDirectory(
                FileUtils.getNativeBracketsDirectoryPath() + "/extensions/" + item,
                "extensions/" + item
            );
        });
    }

    function _initTest() {
        // TODO: (issue #265) Make sure the "test" object is not included in final builds
        // All modules that need to be tested from the context of the application
        // must to be added to this object. The unit tests cannot just pull
        // in the modules since they would run in context of the unit test window,
        // and would not have access to the app html/css.
        brackets.test = {
            PreferencesManager      : require("preferences/PreferencesManager"),
            ProjectManager          : ProjectManager,
            DocumentCommandHandlers : DocumentCommandHandlers,
            FileViewController      : FileViewController,
            DocumentManager         : DocumentManager,
            EditorManager           : EditorManager,
            Commands                : Commands,
            WorkingSetView          : WorkingSetView,
            JSLintUtils             : JSLintUtils,
            PerfUtils               : PerfUtils,
            CommandManager          : require("command/CommandManager"),
            FileSyncManager         : FileSyncManager,
            FileIndexManager        : FileIndexManager,
            CSSUtils                : require("language/CSSUtils"),
            LiveDevelopment         : require("LiveDevelopment/LiveDevelopment"),
            Inspector               : require("LiveDevelopment/Inspector/Inspector"),
            NativeApp               : require("utils/NativeApp")
        };
    }

    function _initDragAndDropListeners() {
        // Prevent unhandled drag and drop of files into the browser from replacing
        // the entire Brackets app. This doesn't prevent children from choosing to
        // handle drops.
        $(window.document.body)
            .on("dragover", function (event) {
                if (event.originalEvent.dataTransfer.files) {
                    event.stopPropagation();
                    event.preventDefault();
                    event.originalEvent.dataTransfer.dropEffect = "none";
                }
            })
            .on("drop", function (event) {
                if (event.originalEvent.dataTransfer.files) {
                    event.stopPropagation();
                    event.preventDefault();
                }
            });
    }

    function _initCommandHandlers() {
        // Most command handlers are automatically registered when their module is loaded (see "modules
        // that self-register" above for some). A few commands need an extra kick here though:

        DocumentCommandHandlers.init($("#main-toolbar"));

        // About dialog
        CommandManager.register(Strings.CMD_ABOUT,  Commands.HELP_ABOUT, function () {
            // If we've successfully determined a "build number" via .git metadata, add it to dialog
            var bracketsSHA = BuildInfoUtils.getBracketsSHA(),
                bracketsAppSHA = BuildInfoUtils.getBracketsAppSHA(),
                versionLabel = "";
            if (bracketsSHA) {
                versionLabel += " (" + bracketsSHA.substr(0, 7) + ")";
            }
            if (bracketsAppSHA) {
                versionLabel += " (shell " + bracketsAppSHA.substr(0, 7) + ")";
            }
            $("#about-build-number").text(versionLabel);

            Dialogs.showModalDialog(Dialogs.DIALOG_ID_ABOUT);
        });
    }

    function initKeyHandler() {
        window.document.body.addEventListener(
            "keydown",
            function (event) {
                if (KeyBindingManager.handleKey(KeyMap.translateKeyboardEvent(event))) {
                    event.stopPropagation();
                }
            },
            true
        );
    }

    function _initWindowListeners() {
        // TODO: (issue 269) to support IE, need to listen to document instead (and even then it may not work when focus is in an input field?)
        $(window).focus(function () {
            FileSyncManager.syncOpenDocuments();
            FileIndexManager.markDirty();
        });

        $(window).contextmenu(function (e) {
            e.preventDefault();
        });
    }

    function _onReady() {
        // Add the platform (mac or win) to the body tag so we can have platform-specific CSS rules
        $("body").addClass("platform-" + brackets.platform);

        EditorManager.setEditorHolder($('#editor-holder'));

        // Let the user know Brackets doesn't run in a web browser yet
        if (brackets.inBrowser) {
            Dialogs.showModalDialog(
                Dialogs.DIALOG_ID_ERROR,
                Strings.ERROR_BRACKETS_IN_BROWSER_TITLE,
                Strings.ERROR_BRACKETS_IN_BROWSER
            );
        }

        _initDragAndDropListeners();
        _initCommandHandlers();
        initKeyHandler();
        Menus.init(); // key bindings should be initialized first
        _initWindowListeners();

        // Read "build number" SHAs off disk at the time the matching Brackets JS code is being loaded, instead
        // of later, when they may have been updated to a different version
        BuildInfoUtils.init();

        // Use quiet scrollbars if we aren't on Lion. If we're on Lion, only
        // use native scroll bars when the mouse is not plugged in or when
        // using the "Always" scroll bar setting.
        var osxMatch = /Mac OS X 10\D([\d+])\D/.exec(navigator.userAgent);
        if (osxMatch && osxMatch[1] && Number(osxMatch[1]) >= 7) {
            // test a scrolling div for scrollbars
            var $testDiv = $("

").appendTo(window.document.body);

            if ($testDiv.outerWidth() === $testDiv.get(0).clientWidth) {
                $(".sidebar").removeClass("quiet-scrollbars");
            }

            $testDiv.remove();
        }

        PerfUtils.addMeasurement("Application Startup");

        // load extensions before loading project
        _initExtensions().done(function () {
            ProjectManager.loadProject().done(function () {
                _initTest();
            });
        });
    }

    // Main Brackets initialization
    _initGlobalBrackets();
    $(window.document).ready(_onReady);

});
<commit_msg>JSLint fix<commit_after>/*
 * Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets: true, $, PathUtils, window, navigator */

/**
 * brackets is the root of the Brackets codebase. This file pulls in all other modules as
 * dependencies (or dependencies thereof), initializes the UI, and binds global menus & keyboard
 * shortcuts to their Commands.
 *
 * TODO: (issue #264) break out the definition of brackets into a separate module from the application controller logic
 *
 * Unlike other modules, this one can be accessed without an explicit require() because it exposes
 * a global object, window.brackets.
 */
define(function (require, exports, module) {
    'use strict';

    // Load dependent non-module scripts
    require("widgets/bootstrap-dropdown");
    require("widgets/bootstrap-modal");
    require("thirdparty/path-utils/path-utils.min");
    require("thirdparty/smart-auto-complete/jquery.smart_autocomplete");

    // Load LiveDeveopment
    require("LiveDevelopment/main");

    // Load dependent modules
    var ProjectManager          = require("project/ProjectManager"),
        DocumentManager         = require("document/DocumentManager"),
        EditorManager           = require("editor/EditorManager"),
        CSSInlineEditor         = require("editor/CSSInlineEditor"),
        WorkingSetView          = require("project/WorkingSetView"),
        DocumentCommandHandlers = require("document/DocumentCommandHandlers"),
        FileViewController      = require("project/FileViewController"),
        FileSyncManager         = require("project/FileSyncManager"),
        KeyBindingManager       = require("command/KeyBindingManager"),
        KeyMap                  = require("command/KeyMap"),
        Commands                = require("command/Commands"),
        CommandManager          = require("command/CommandManager"),
        BuildInfoUtils          = require("utils/BuildInfoUtils"),
        CodeHintManager         = require("editor/CodeHintManager"),
        JSLintUtils             = require("language/JSLintUtils"),
        PerfUtils               = require("utils/PerfUtils"),
        FileIndexManager        = require("project/FileIndexManager"),
        QuickOpen               = require("search/QuickOpen"),
        Menus                   = require("command/Menus"),
        FileUtils               = require("file/FileUtils"),
        Strings                 = require("strings"),
        Dialogs                 = require("widgets/Dialogs"),
        ExtensionLoader         = require("utils/ExtensionLoader"),
        SidebarView             = require("project/SidebarView"),
        Async                   = require("utils/Async");

    //Load modules that self-register and just need to get included in the main project
    require("editor/CodeHintManager");
    require("editor/EditorCommandHandlers");
    require("debug/DebugCommandHandlers");
    require("view/ViewCommandHandlers");
    require("search/FindInFiles");

    function _initGlobalBrackets() {
        // Define core brackets namespace if it isn't already defined
        //
        // We can't simply do 'brackets = {}' to define it in the global namespace because
        // we're in "use strict" mode. Most likely, 'window' will always point to the global
        // object when this code is running. However, in case it isn't (e.g. if we're running
        // inside Node for CI testing) we use this trick to get the global object.
        //
        // Taken from:
        //   http://stackoverflow.com/questions/3277182/how-to-get-the-global-object-in-javascript
        var Fn = Function, global = (new Fn('return this'))();
        if (!global.brackets) {
            global.brackets = {};
        }

        // Uncomment the following line to force all low level file i/o routines to complete
        // asynchronously. This should only be done for testing/debugging.
        // NOTE: Make sure this line is commented out again before committing!
        //brackets.forceAsyncCallbacks = true;

        // Load native shell when brackets is run in a native shell rather than the browser
        // TODO: (issue #266) load conditionally
        brackets.shellAPI = require("utils/ShellAPI");

        brackets.inBrowser = !brackets.hasOwnProperty("fs");

        brackets.platform = (global.navigator.platform === "MacIntel" || global.navigator.platform === "MacPPC") ? "mac" : "win";

        // Loading extensions requires creating new require.js contexts, which requires access to the global 'require' object
        // that always gets hidden by the 'require' in the AMD wrapper. We store this in the brackets object here so that
        // the ExtensionLoader doesn't have to have access to the global object.
        brackets.libRequire = global.require;

        // Also store our current require.js context (the one that loads brackets core modules) so that extensions can use it
        // Note: we change the name to "getModule" because this won't do exactly the same thing as 'require' in AMD-wrapped
        // modules. The extension will only be able to load modules that have already been loaded once.
        brackets.getModule = require;
    }

    function _initExtensions() {
        // FUTURE (JRB): As we get more fine-grained performance measurement, move this out of core application startup
        return Async.doInParallel(["default", "user"], function (item) {
            return ExtensionLoader.loadAllExtensionsInNativeDirectory(
                FileUtils.getNativeBracketsDirectoryPath() + "/extensions/" + item,
                "extensions/" + item
            );
        });
    }

    function _initTest() {
        // TODO: (issue #265) Make sure the "test" object is not included in final builds
        // All modules that need to be tested from the context of the application
        // must to be added to this object. The unit tests cannot just pull
        // in the modules since they would run in context of the unit test window,
        // and would not have access to the app html/css.
        brackets.test = {
            PreferencesManager      : require("preferences/PreferencesManager"),
            ProjectManager          : ProjectManager,
            DocumentCommandHandlers : DocumentCommandHandlers,
            FileViewController      : FileViewController,
            DocumentManager         : DocumentManager,
            EditorManager           : EditorManager,
            Commands                : Commands,
            WorkingSetView          : WorkingSetView,
            JSLintUtils             : JSLintUtils,
            PerfUtils               : PerfUtils,
            CommandManager          : require("command/CommandManager"),
            FileSyncManager         : FileSyncManager,
            FileIndexManager        : FileIndexManager,
            CSSUtils                : require("language/CSSUtils"),
            LiveDevelopment         : require("LiveDevelopment/LiveDevelopment"),
            Inspector               : require("LiveDevelopment/Inspector/Inspector"),
            NativeApp               : require("utils/NativeApp")
        };
    }

    function _initDragAndDropListeners() {
        // Prevent unhandled drag and drop of files into the browser from replacing
        // the entire Brackets app. This doesn't prevent children from choosing to
        // handle drops.
        $(window.document.body)
            .on("dragover", function (event) {
                if (event.originalEvent.dataTransfer.files) {
                    event.stopPropagation();
                    event.preventDefault();
                    event.originalEvent.dataTransfer.dropEffect = "none";
                }
            })
            .on("drop", function (event) {
                if (event.originalEvent.dataTransfer.files) {
                    event.stopPropagation();
                    event.preventDefault();
                }
            });
    }

    function _initCommandHandlers() {
        // Most command handlers are automatically registered when their module is loaded (see "modules
        // that self-register" above for some). A few commands need an extra kick here though:

        DocumentCommandHandlers.init($("#main-toolbar"));

        // About dialog
        CommandManager.register(Strings.CMD_ABOUT,  Commands.HELP_ABOUT, function () {
            // If we've successfully determined a "build number" via .git metadata, add it to dialog
            var bracketsSHA = BuildInfoUtils.getBracketsSHA(),
                bracketsAppSHA = BuildInfoUtils.getBracketsAppSHA(),
                versionLabel = "";
            if (bracketsSHA) {
                versionLabel += " (" + bracketsSHA.substr(0, 7) + ")";
            }
            if (bracketsAppSHA) {
                versionLabel += " (shell " + bracketsAppSHA.substr(0, 7) + ")";
            }
            $("#about-build-number").text(versionLabel);

            Dialogs.showModalDialog(Dialogs.DIALOG_ID_ABOUT);
        });
    }

    function initKeyHandler() {
        window.document.body.addEventListener(
            "keydown",
            function (event) {
                if (KeyBindingManager.handleKey(KeyMap.translateKeyboardEvent(event))) {
                    event.stopPropagation();
                }
            },
            true
        );
    }

    function _initWindowListeners() {
        // TODO: (issue 269) to support IE, need to listen to document instead (and even then it may not work when focus is in an input field?)
        $(window).focus(function () {
            FileSyncManager.syncOpenDocuments();
            FileIndexManager.markDirty();
        });

        $(window).contextmenu(function (e) {
            e.preventDefault();
        });
    }

    function _onReady() {
        // Add the platform (mac or win) to the body tag so we can have platform-specific CSS rules
        $("body").addClass("platform-" + brackets.platform);

        EditorManager.setEditorHolder($('#editor-holder'));

        // Let the user know Brackets doesn't run in a web browser yet
        if (brackets.inBrowser) {
            Dialogs.showModalDialog(
                Dialogs.DIALOG_ID_ERROR,
                Strings.ERROR_BRACKETS_IN_BROWSER_TITLE,
                Strings.ERROR_BRACKETS_IN_BROWSER
            );
        }

        _initDragAndDropListeners();
        _initCommandHandlers();
        initKeyHandler();
        Menus.init(); // key bindings should be initialized first
        _initWindowListeners();

        // Read "build number" SHAs off disk at the time the matching Brackets JS code is being loaded, instead
        // of later, when they may have been updated to a different version
        BuildInfoUtils.init();

        // Use quiet scrollbars if we aren't on Lion. If we're on Lion, only
        // use native scroll bars when the mouse is not plugged in or when
        // using the "Always" scroll bar setting.
        var osxMatch = /Mac OS X 10\D([\d+])\D/.exec(navigator.userAgent);
        if (osxMatch && osxMatch[1] && Number(osxMatch[1]) >= 7) {
            // test a scrolling div for scrollbars
            var $testDiv = $("

").appendTo(window.document.body);

            if ($testDiv.outerWidth() === $testDiv.get(0).clientWidth) {
                $(".sidebar").removeClass("quiet-scrollbars");
            }

            $testDiv.remove();
        }

        PerfUtils.addMeasurement("Application Startup");

        // load extensions before loading project
        _initExtensions().done(function () {
            ProjectManager.loadProject().done(function () {
                _initTest();
            });
        });
    }

    // Main Brackets initialization
    _initGlobalBrackets();
    $(window.document).ready(_onReady);

});
<|endoftext|>


<commit_before>function AJAX(url,fnSuccess, fnError) {
	var theAJAX = XMLHttpRequest();
	theAJAX.open('GET', url, true);//open(方法，文件名，异步传输)
	theAJAX.send();//发送请求
	//接收返回
	theAJAX.onreadystatechange = function(){
		if (theAJAX.readyState == 4) {
			if (theAJAX.status == 200) {
				fnSuccess(theAJAX.responseText);
			}else {
				if (fnError) fnError(theAJAX.status);
			}
		}
	};
}<commit_msg>Modified AJAX.js<commit_after>function AJAX(url,fnSuccess, fnError) {
	var theAJAX = XMLHttpRequest();
	theAJAX.open('GET', url, true);//open(方法，文件名，异步传输)
	//url + 't = ' + new Date().getTime()  时间戳阻止缓存，通过每一次改变url实现
	theAJAX.send();//发送请求
	//接收返回
	theAJAX.onreadystatechange = function(){
		if (theAJAX.readyState == 4) {
			if (theAJAX.status == 200) {
				fnSuccess(theAJAX.responseText);
			}else {
				if (fnError) fnError(theAJAX.status);
			}
		}
	};
}<|endoftext|>


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

/**
 * @fileoverview Externs for Jasmine.
 *
 * TODO: Remaining Spy properties and anything else missing.
 *
 * @see http://pivotal.github.com/jasmine/
 * @externs
 */

/** @const */
var jasmine = {};

/**
 * @param {string} name
 * @return {jasmine.Spy} spy
 */
jasmine.createSpy = function(name) {};

/** @constructor */
jasmine.Matcher = function() {};

/** @type {jasmine.Matcher} */
jasmine.Matcher.prototype.not;

/** @param {*} value */
jasmine.Matcher.prototype.toBe = function(value) {};

/** @return {void} */
jasmine.Matcher.prototype.toBeDefined = function() {};

/** @return {void} */
jasmine.Matcher.prototype.toBeFalsy = function() {};

/** @param {*} value */
jasmine.Matcher.prototype.toBeGreaterThan = function(value) {};

/** @param {*} value */
jasmine.Matcher.prototype.toBeLessThan = function(value) {};

/** @return {void} */
jasmine.Matcher.prototype.toBeNull = function() {};

/** @return {void} */
jasmine.Matcher.prototype.toBeTruthy = function() {};

/** @return {void} */
jasmine.Matcher.prototype.toBeUndefined = function() {};

/** @param {*} value */
jasmine.Matcher.prototype.toContain = function(value) {};

/** @param {*} value */
jasmine.Matcher.prototype.toEqual = function(value) {};

/** @return {void} */
jasmine.Matcher.prototype.toHaveBeenCalled = function() {};

/** @param {...*} var_args */
jasmine.Matcher.prototype.toHaveBeenCalledWith = function(var_args) {};

/** @param {(string|RegExp)} pattern */
jasmine.Matcher.prototype.toMatch = function(pattern) {};

/** @param {Error=} opt_expected */
jasmine.Matcher.prototype.toThrow = function(opt_expected) {};

/** @constructor */
jasmine.Spec = function() {};

/** @param {Error|string} e */
jasmine.Spec.prototype.fail = function(e) {};

/** @constructor */
jasmine.Spy = function() {};

/**
 * @param {Function} fn
 * @return {jasmine.Spy}
 */
jasmine.Spy.prototype.andCallFake = function(fn) {};

/** @return {jasmine.Spy} */
jasmine.Spy.prototype.andCallThrough = function() {};

/**
 * @param {*} value
 * @return {jasmine.Spy}
 */
jasmine.Spy.prototype.andReturn = function(value) {};

/**
 * @param {Error} exception
 * @return {jasmine.Spy}
 */
jasmine.Spy.prototype.andThrow = function(exception) {};

/** @type {Array.<Object>} */
jasmine.Spy.prototype.calls;

/** @constructor */
jasmine.Helper = function() {};

/** @param {*} value */
jasmine.Helper.prototype.addMatchers = function(value) {};

/** @type {*} */
jasmine.Helper.prototype.actual;

/** @type {boolean} */
jasmine.Helper.prototype.isNot;

/** @param {function()} handler */
function afterEach(handler) {}

/** @param {function(this:jasmine.Helper)} handler */
function beforeEach(handler) {}

/**
 * @param {string} description
 * @param {function()} handler
 */
function describe(description, handler) {}

/**
 * @param {*} expectedValue
 * @return {jasmine.Matcher} matcher
 */
function expect(expectedValue) {}

/**
 * Provided by angular-mocks.js.
 * @param {...(Function|Array.<(string,Function)>)} var_args
 */
function inject(var_args) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Spec)} handler
 */
function it(description, handler) {}

/**
 * Provided by angular-mocks.js.
 * @param {...(string|Function|Array.<(string,Function)>)} var_args
 */
function module(var_args) {}

/** @param {function()} handler */
function runs(handler) {}

/**
 * @param {Object} spiedOnObject
 * @param {string} methodName
 * @return {jasmine.Spy} spy
 */
function spyOn(spiedOnObject, methodName) {}

/** @param {number} timeout */
function waits(timeout) {}

/**
 * @param {function(): boolean} handler
 * @param {string=} opt_message
 * @param {number=} opt_timeout
 */
function waitsFor(handler, opt_message, opt_timeout) {}

/**
 * @nosideeffects
 * @param {string} description
 * @param {function()} handler
 */
function xdescribe(description, handler) {}

/**
 * @nosideeffects
 * @param {string} description
 * @param {function()} handler
 */
function xit(description, handler) {}
<commit_msg>Jasmine: Add an extern for this.message in a custom matcher.<commit_after>/*
 * Copyright 2013 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Externs for Jasmine.
 *
 * TODO: Remaining Spy properties and anything else missing.
 *
 * @see http://pivotal.github.com/jasmine/
 * @externs
 */

/** @const */
var jasmine = {};

/**
 * @param {string} name
 * @return {jasmine.Spy} spy
 */
jasmine.createSpy = function(name) {};

/** @constructor */
jasmine.Matcher = function() {};

/** @type {jasmine.Matcher} */
jasmine.Matcher.prototype.not;

/** @param {*} value */
jasmine.Matcher.prototype.toBe = function(value) {};

/** @return {void} */
jasmine.Matcher.prototype.toBeDefined = function() {};

/** @return {void} */
jasmine.Matcher.prototype.toBeFalsy = function() {};

/** @param {*} value */
jasmine.Matcher.prototype.toBeGreaterThan = function(value) {};

/** @param {*} value */
jasmine.Matcher.prototype.toBeLessThan = function(value) {};

/** @return {void} */
jasmine.Matcher.prototype.toBeNull = function() {};

/** @return {void} */
jasmine.Matcher.prototype.toBeTruthy = function() {};

/** @return {void} */
jasmine.Matcher.prototype.toBeUndefined = function() {};

/** @param {*} value */
jasmine.Matcher.prototype.toContain = function(value) {};

/** @param {*} value */
jasmine.Matcher.prototype.toEqual = function(value) {};

/** @return {void} */
jasmine.Matcher.prototype.toHaveBeenCalled = function() {};

/** @param {...*} var_args */
jasmine.Matcher.prototype.toHaveBeenCalledWith = function(var_args) {};

/** @param {(string|RegExp)} pattern */
jasmine.Matcher.prototype.toMatch = function(pattern) {};

/** @param {Error=} opt_expected */
jasmine.Matcher.prototype.toThrow = function(opt_expected) {};

/** @constructor */
jasmine.Spec = function() {};

/** @param {Error|string} e */
jasmine.Spec.prototype.fail = function(e) {};

/** @constructor */
jasmine.Spy = function() {};

/**
 * @param {Function} fn
 * @return {jasmine.Spy}
 */
jasmine.Spy.prototype.andCallFake = function(fn) {};

/** @return {jasmine.Spy} */
jasmine.Spy.prototype.andCallThrough = function() {};

/**
 * @param {*} value
 * @return {jasmine.Spy}
 */
jasmine.Spy.prototype.andReturn = function(value) {};

/**
 * @param {Error} exception
 * @return {jasmine.Spy}
 */
jasmine.Spy.prototype.andThrow = function(exception) {};

/** @type {Array.<Object>} */
jasmine.Spy.prototype.calls;

/** @constructor */
jasmine.Helper = function() {};

/** @param {*} value */
jasmine.Helper.prototype.addMatchers = function(value) {};

/** @type {*} */
jasmine.Helper.prototype.actual;

/** @type {boolean} */
jasmine.Helper.prototype.isNot;

/** @type {undefined|function(): string} */
jasmine.Helper.prototype.message;

/** @param {function()} handler */
function afterEach(handler) {}

/** @param {function(this:jasmine.Helper)} handler */
function beforeEach(handler) {}

/**
 * @param {string} description
 * @param {function()} handler
 */
function describe(description, handler) {}

/**
 * @param {*} expectedValue
 * @return {jasmine.Matcher} matcher
 */
function expect(expectedValue) {}

/**
 * Provided by angular-mocks.js.
 * @param {...(Function|Array.<(string,Function)>)} var_args
 */
function inject(var_args) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Spec)} handler
 */
function it(description, handler) {}

/**
 * Provided by angular-mocks.js.
 * @param {...(string|Function|Array.<(string,Function)>)} var_args
 */
function module(var_args) {}

/** @param {function()} handler */
function runs(handler) {}

/**
 * @param {Object} spiedOnObject
 * @param {string} methodName
 * @return {jasmine.Spy} spy
 */
function spyOn(spiedOnObject, methodName) {}

/** @param {number} timeout */
function waits(timeout) {}

/**
 * @param {function(): boolean} handler
 * @param {string=} opt_message
 * @param {number=} opt_timeout
 */
function waitsFor(handler, opt_message, opt_timeout) {}

/**
 * @nosideeffects
 * @param {string} description
 * @param {function()} handler
 */
function xdescribe(description, handler) {}

/**
 * @nosideeffects
 * @param {string} description
 * @param {function()} handler
 */
function xit(description, handler) {}
<|endoftext|>


<commit_before>angular.module('ssnocController', [])

	// inject the Todo service factory into our controller
	.controller('mainController', ['$scope','$http','SsnocFactory', function($scope, $http, SsnocFactory) {
		$scope.member = {};
		$scope.directory = {};
		$scope.loading = true;

		// GET =====================================================================
		// when landing on the page, get all todos and show them
		// use the service to get all the todos
		SsnocFactory.getDirectory()
			.success(function(data) {
				$scope.directory = data;
				$scope.loading = false;
			});

		$scope.login = function(){

			$scope.loading = true;
			if($scope.isExistingMember)
			{
				if($scope.validateLoginDetails)
				{
					goOnline();

				}
				else{

				}
			}
			else
			{

			}
		}

		$scope.logout = function(){
			$scope.loading = true;
			goOffline();
		}

		getDirectory = function()
		{
			$scope.loading = true;

			SsnocFactory.getDirectory()
			.success(function(data) {
				$scope.directory = data;
				$scope.loading = false;
			});

		}
		// CREATE ==================================================================
		// when submitting the add form, send the text to the node API
		createMember = function() {
				$scope.loading = true;

				// call the create function from our service (returns a promise object)
				SsnocFactory.create($scope.member)
					.success(function(data) {
						$scope.loading = false;
						$scope.member = member;
					});
			}
		};

		isExistingMember = function(){
			SsnocFactory.getMember($scope.member.username)
				.success(function(data){
					//@angela please use data to validate login details with $scope.member
					if(data != undefined)
					{
						$scope.member = data;
						return true;
					}else
					{
						return false;
					}
				});
		}

		$scope.validateLoginDetails = function(){

		}

		$scope.validateSignInDetails = function(){

		}

		goOnline = function(){
			//@angela validate here
			$scope.member.status =1;
			updateStatus();
		}

		goOffline = function(){
			//@angela please add validation
			$scope.member.status = 0;
			updateStatus();
		}

		updateStatus = function(){
			SsnocFactory.updateStatus($scope.member)
			 	.success(function(data){
			 		$scope.member = data;
			 		$scope.loading = false;
			 	});
		}

	}]);<commit_msg>Updates on controller<commit_after>angular.module('ssnocController', [])

	// inject the Todo service factory into our controller
	.controller('mainController', ['$scope','$http','SsnocFactory', function($scope, $http, SsnocFactory) {
		$scope.member = {};
		$scope.directory = {};
		$scope.loading = true;

		// GET =====================================================================
		// when landing on the page, get all todos and show them
		// use the service to get all the todos

		$scope.login = function(){

			$scope.loading = true;
			if($scope.isExistingMember)
			{
				if($scope.validateLoginDetails)
				{
					goOnline();

				}
				else{

				}
			}
			else
			{

			}
		}

		$scope.logout = function(){
			$scope.loading = true;
			goOffline();
		}

		getDirectory = function()
		{
			$scope.loading = true;

			SsnocFactory.getDirectory()
			.success(function(data) {
				$scope.directory = data;
				$scope.loading = false;
			});

		}
		// CREATE ==================================================================
		// when submitting the add form, send the text to the node API
		createMember = function() {
				$scope.loading = true;

				// call the create function from our service (returns a promise object)
				SsnocFactory.create($scope.member)
					.success(function(data) {
						$scope.loading = false;
						$scope.member = member;
					});
			}
		};

		isExistingMember = function(){
			SsnocFactory.getMember($scope.member.username)
				.success(function(data){
					//@angela please use data to validate login details with $scope.member
					if(data != undefined)
					{
						$scope.member = data;
						return true;
					}else
					{
						return false;
					}
				});
		}

		validateLoginDetails = function(){

		}

		validateSignInDetails = function(){

		}

		goOnline = function(){
			//@angela validate here
			$scope.member.status =1;
			updateStatus();
		}

		goOffline = function(){
			//@angela please add validation
			$scope.member.status = 0;
			updateStatus();
		}

		updateStatus = function(){
			SsnocFactory.updateStatus($scope.member)
			 	.success(function(data){
			 		$scope.member = data;
			 		$scope.loading = false;
			 	});
		}

	}]);<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Image,
  Text,
  View,
  TouchableHighlight,
} = React;

var MovieList = React.createClass({
  propTypes: {
    movie: React.PropTypes.object.isRequired,
    onPress: React.PropTypes.func.isRequired,
  },

  render: function() {
    var movie = this.props.movie;
    return (
      <TouchableHighlight
        onPress={this.props.onPress}
        style={styles.container}
      >
        <View style={styles.container}>
          <Image
            style={styles.thumbnail}
            source={{uri: movie.posters.thumbnail}}
          />
          <View style={styles.rightContainer}>
            <Text style={styles.title}>{movie.title}</Text>
            <Text style={styles.year}>{movie.year}</Text>
          </View>
        </View>
      </TouchableHighlight>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  rightContainer: {
    flex: 1,
  },
  thumbnail: {
    width: 53,
    height: 81,
  },
  title: {
    fontSize: 20,
    marginBottom: 8,
    textAlign: 'center',
  },
  year: {
    textAlign: 'center',
  },
});

AppRegistry.registerComponent('MovieList', () => MovieList);

module.exports = MovieList;
<commit_msg>style the movie cell a bit<commit_after>'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Image,
  Text,
  View,
  TouchableHighlight,
  PixelRatio,
} = React;

var MovieList = React.createClass({
  propTypes: {
    movie: React.PropTypes.object.isRequired,
    onPress: React.PropTypes.func.isRequired,
  },

  render: function() {
    var movie = this.props.movie;
    return (
      <View>
        <TouchableHighlight
          onPress={this.props.onPress}
        >
          <View style={styles.container}>
            <Image
              style={styles.thumbnail}
              source={{uri: movie.posters.thumbnail}}
            />
            <View style={styles.rightContainer}>
              <Text style={styles.title} numberOfLines={2}>{movie.title}</Text>
              <Text style={styles.year} numberOfLines={1}>{movie.year}</Text>
            </View>
          </View>
        </TouchableHighlight>
        <View style={styles.cellBorder} />
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    backgroundColor: '#F5FCFF',

    alignItems: 'center',
    padding: 5,
  },
  rightContainer: {
    flex: 1,
    marginLeft: 5,
  },
  thumbnail: {
    width: 53,
    height: 81,
  },
  title: {
    flex: 1,
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 2,
  },
  year: {
    color: '#999999',
    fontSize: 12,
  },
  cellBorder: {
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
    // Trick to get the thinest line the device can display
    height: 1 / PixelRatio.get(),
    marginLeft: 4,
  },
});

AppRegistry.registerComponent('MovieList', () => MovieList);

module.exports = MovieList;
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const run = require('./run')
const interp = require('./interp')
const lib = require('./lib')
const C = require('./constants')

function exists(p) {
  // warning, this is synchronous
  try {
    fs.accessSync(p, fs.F_OK)
    return true
  } catch (err) {
    return false
  }
}

export function makeBuiltins() {
  let variables = {}

  variables['print'] = new lib.Variable(new lib.LFunction(function(args) {
    console.log(...args.map(arg => lib.toJString(arg)))
  }))

  variables['concat'] = new lib.Variable(new lib.LFunction(function(args) {
    return lib.toLString(args.map(lib.toJString).join(''))
  }))

  variables['if'] = new lib.Variable(new lib.LFunction(function(args) {
    if (lib.toJBoolean(args[0])) {
      lib.call(args[1], [])
    } else {
      // optional `else`
      if (args[2]) lib.call(args[2], [])
    }
  }))

  variables['ifel'] = new lib.Variable(new lib.LFunction(function(args) {
    if (lib.toJBoolean(args[0])) {
      lib.call(args[1], [])
    } else {
      lib.call(args[2], [])
    }
  }))

  variables['obj'] = new lib.Variable(new lib.LFunction(function(args) {
    return new lib.LObject()
  }))

  variables['array'] = new lib.Variable(new lib.LFunction(function(args) {
    return new lib.LArray()
  }))

  variables['+'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLNumber(lib.toJNumber(x) + lib.toJNumber(y))
  }))
  variables['add'] = variables['+']

  variables['-'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLNumber(lib.toJNumber(x) - lib.toJNumber(y))
  }))
  variables['minus'] = variables['-']

  variables['/'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLNumber(lib.toJNumber(x) / lib.toJNumber(y))
  }))
  variables['divide'] = variables['/']

  variables['*'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLNumber(lib.toJNumber(x) * lib.toJNumber(y))
  }))
  variables['multiply'] = variables['&']

  variables['not'] = new lib.Variable(new lib.LFunction(function([bool]) {
    return lib.toLBoolean(!lib.toJBoolean(bool))
  }))
  variables['!'] = variables['not']

  variables['and'] = new lib.Variable(new lib.LFunction(function([b1, b2]) {
    return lib.toLBoolean(lib.toJBoolean(b1) && lib.toJBoolean(b2))
  }))
  variables['&'] = variables['and']

  variables['or'] = new lib.Variable(new lib.LFunction(function([b1, b2]) {
    return lib.toLBoolean(lib.toJBoolean(b1) || lib.toJBoolean(b2))
  }))
  variables['|'] = variables['or']

  variables['lt'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLBoolean(lib.toJNumber(x) < lib.toJNumber(y))
  }))
  variables['<'] = variables['lt']

  variables['gt'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLBoolean(lib.toJNumber(x) > lib.toJNumber(y))
  }))
  variables['>'] = variables['gt']

  variables['eq'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLBoolean(lib.toJNumber(x) === lib.toJNumber(y))
  }))
  variables['='] = variables['eq']

  variables['is'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return Object.is(x, y)
  }))

  variables['loop'] = new lib.Variable(new lib.LFunction(function([fn]) {
    while (lib.toJBoolean(lib.call(fn, []))) { /* empty */ }
  }))

  variables['use'] = new lib.Variable(new lib.LFunction(function([pathStr]) {
    let p = lib.toJString(pathStr)
    let locationInBuiltins = `${__dirname}/builtin_lib/${p}`
    console.log('location in bulitins:', locationInBuiltins)
    let ext = path.parse(p).ext
    if (exists(locationInBuiltins)) {
      if (ext === '.js') {
        let used = require(locationInBuiltins)
        let usedObj = lib.toLObject(used)
        return usedObj
      } else if (ext === '.tul') {
        let program = fs.readFileSync(locationInBuiltins).toString()
        let result = run.run(program)
        if ('exports' in result.variables) {
          return result.variables.exports.value
        } else {
          return new lib.LObject()
        }
      } else {
        throw `Invalid use extension of ${p}`
      }
    } else {
      console.log('File not found')
    }
  }))

  let variableObject = new lib.LObject()

  lib.set(variableObject, 'make', new lib.LFunction(function([env, name, value]) {
    let v = new lib.Variable(value)
    env.vars[lib.toJString(name)] = v
    return v
  }))

  lib.set(variableObject, 'change', new lib.LFunction(function([variable, newValue]) {
    variable.value = newValue
  }))

  lib.set(variableObject, 'value', new lib.LFunction(function([variable]) {
    return variable.value
  }))

  lib.set(variableObject, 'from', new lib.LFunction(function([env, name]) {
    name = lib.toJString(name)
    let variable = env.vars[name]
    if (typeof variable === 'undefined') {
      throw new Error(`Can't access variable ${name} because it doesn't exist`)
    } else {
      return variable
    }
  }))

  lib.set(variableObject, 'exists', new lib.LFunction(function([env, name]) {
    return lib.toLBoolean(env.vars.hasOwnProperty(lib.toJString(name)))
  }))

  variables['Variable'] = new lib.Variable(variableObject)

  return variables
}
<commit_msg>add sleep(seconds)<commit_after>const fs = require('fs')
const path = require('path')
const run = require('./run')
const interp = require('./interp')
const lib = require('./lib')
const C = require('./constants')

function exists(p) {
  // warning, this is synchronous
  try {
    fs.accessSync(p, fs.F_OK)
    return true
  } catch (err) {
    return false
  }
}

export function makeBuiltins() {
  let variables = {}

  variables['print'] = new lib.Variable(new lib.LFunction(function(args) {
    console.log(...args.map(arg => lib.toJString(arg)))
  }))

  variables['concat'] = new lib.Variable(new lib.LFunction(function(args) {
    return lib.toLString(args.map(lib.toJString).join(''))
  }))

  variables['if'] = new lib.Variable(new lib.LFunction(function(args) {
    if (lib.toJBoolean(args[0])) {
      lib.call(args[1], [])
    } else {
      // optional `else`
      if (args[2]) lib.call(args[2], [])
    }
  }))

  variables['ifel'] = new lib.Variable(new lib.LFunction(function(args) {
    if (lib.toJBoolean(args[0])) {
      lib.call(args[1], [])
    } else {
      lib.call(args[2], [])
    }
  }))

  variables['sleep'] = new lib.Variable(new lib.LFunction(function([time]) {
    let e = new Date().getTime() + (lib.toJNumber(time) * 1000)
    while (new Date().getTime() <= e) { /* empty */ }
  }))

  variables['obj'] = new lib.Variable(new lib.LFunction(function(args) {
    return new lib.LObject()
  }))

  variables['array'] = new lib.Variable(new lib.LFunction(function(args) {
    return new lib.LArray()
  }))

  variables['+'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLNumber(lib.toJNumber(x) + lib.toJNumber(y))
  }))
  variables['add'] = variables['+']

  variables['-'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLNumber(lib.toJNumber(x) - lib.toJNumber(y))
  }))
  variables['minus'] = variables['-']

  variables['/'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLNumber(lib.toJNumber(x) / lib.toJNumber(y))
  }))
  variables['divide'] = variables['/']

  variables['*'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLNumber(lib.toJNumber(x) * lib.toJNumber(y))
  }))
  variables['multiply'] = variables['&']

  variables['not'] = new lib.Variable(new lib.LFunction(function([bool]) {
    return lib.toLBoolean(!lib.toJBoolean(bool))
  }))
  variables['!'] = variables['not']

  variables['and'] = new lib.Variable(new lib.LFunction(function([b1, b2]) {
    return lib.toLBoolean(lib.toJBoolean(b1) && lib.toJBoolean(b2))
  }))
  variables['&'] = variables['and']

  variables['or'] = new lib.Variable(new lib.LFunction(function([b1, b2]) {
    return lib.toLBoolean(lib.toJBoolean(b1) || lib.toJBoolean(b2))
  }))
  variables['|'] = variables['or']

  variables['lt'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLBoolean(lib.toJNumber(x) < lib.toJNumber(y))
  }))
  variables['<'] = variables['lt']

  variables['gt'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLBoolean(lib.toJNumber(x) > lib.toJNumber(y))
  }))
  variables['>'] = variables['gt']

  variables['eq'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return lib.toLBoolean(lib.toJNumber(x) === lib.toJNumber(y))
  }))
  variables['='] = variables['eq']

  variables['is'] = new lib.Variable(new lib.LFunction(function([x, y]) {
    return Object.is(x, y)
  }))

  variables['loop'] = new lib.Variable(new lib.LFunction(function([fn]) {
    while (lib.toJBoolean(lib.call(fn, []))) { /* empty */ }
  }))

  variables['use'] = new lib.Variable(new lib.LFunction(function([pathStr]) {
    let p = lib.toJString(pathStr)
    let locationInBuiltins = `${__dirname}/builtin_lib/${p}`
    console.log('location in bulitins:', locationInBuiltins)
    let ext = path.parse(p).ext
    if (exists(locationInBuiltins)) {
      if (ext === '.js') {
        let used = require(locationInBuiltins)
        let usedObj = lib.toLObject(used)
        return usedObj
      } else if (ext === '.tul') {
        let program = fs.readFileSync(locationInBuiltins).toString()
        let result = run.run(program)
        if ('exports' in result.variables) {
          return result.variables.exports.value
        } else {
          return new lib.LObject()
        }
      } else {
        throw `Invalid use extension of ${p}`
      }
    } else {
      console.log('File not found')
    }
  }))

  let variableObject = new lib.LObject()

  lib.set(variableObject, 'make', new lib.LFunction(function([env, name, value]) {
    let v = new lib.Variable(value)
    env.vars[lib.toJString(name)] = v
    return v
  }))

  lib.set(variableObject, 'change', new lib.LFunction(function([variable, newValue]) {
    variable.value = newValue
  }))

  lib.set(variableObject, 'value', new lib.LFunction(function([variable]) {
    return variable.value
  }))

  lib.set(variableObject, 'from', new lib.LFunction(function([env, name]) {
    name = lib.toJString(name)
    let variable = env.vars[name]
    if (typeof variable === 'undefined') {
      throw new Error(`Can't access variable ${name} because it doesn't exist`)
    } else {
      return variable
    }
  }))

  lib.set(variableObject, 'exists', new lib.LFunction(function([env, name]) {
    return lib.toLBoolean(env.vars.hasOwnProperty(lib.toJString(name)))
  }))

  variables['Variable'] = new lib.Variable(variableObject)

  return variables
}
<|endoftext|>


<commit_before>app.controller("UserSettingsController", function ($scope, AuthorizationService, UserService, CurrencyService, HTTPService) {
  $scope.userService = UserService;
  $scope.currencies = CurrencyService;
  $scope.file = undefined;
  $scope.operationSuccessful = false;
  var importPostHeaders = {"Content-Type": undefined};
  $scope.submitEditing = function () {
    AuthorizationService.username = $scope.user.username;
    if ($scope.user.password !== undefined)
      AuthorizationService.password = $scope.user.password;
    UserService.submit($scope.user).then($scope.importData);
  };
  $scope.cancelEditing = function () {
    UserService.update();
  };
  $scope.setFile = function (file) {
    $scope.$apply(function () {
      $scope.file = file.files[0];
    });
  };
  $scope.importData = function () {
    if ($scope.file === undefined)
      return;
    var formData = new FormData();
    formData.append("file", $scope.file);
    return HTTPService.post("service/import", formData, importPostHeaders, undefined, angular.identity).then(function () {
      HTTPService.updateAllData();
    });
  };
  $scope.exportData = function () {
    var form = $('<form>', {
      html: '<input type="hidden" name="access_token" value="' + AuthorizationService.access_token + '" />',
      action: "service/export",
      method: "post"
    });
    form.appendTo(document.body).submit().remove();
  };
  $scope.performCleanup = function () {
    $scope.operationSuccessful = false;
    $scope.userService.performCleanup().then(function () {
      $scope.operationSuccessful = true;
    });
  };
  $scope.performRecalculateBalance = function () {
    $scope.operationSuccessful = false;
    $scope.userService.performRecalculateBalance().then(function () {
      $scope.operationSuccessful = true;
    });
  };
  $scope.$watch(function () {
    return UserService.userData;
  }, function () {
    $scope.user = UserService.userData;
  });
});
<commit_msg>Tags are now updated after importing data.<commit_after>app.controller("UserSettingsController", function ($scope, AuthorizationService, UserService, CurrencyService, TagsService, HTTPService) {
  $scope.userService = UserService;
  $scope.currencies = CurrencyService;
  $scope.file = undefined;
  $scope.operationSuccessful = false;
  var importPostHeaders = {"Content-Type": undefined};
  $scope.submitEditing = function () {
    AuthorizationService.username = $scope.user.username;
    if ($scope.user.password !== undefined)
      AuthorizationService.password = $scope.user.password;
    UserService.submit($scope.user).then($scope.importData);
  };
  $scope.cancelEditing = function () {
    UserService.update();
  };
  $scope.setFile = function (file) {
    $scope.$apply(function () {
      $scope.file = file.files[0];
    });
  };
  $scope.importData = function () {
    if ($scope.file === undefined)
      return;
    var formData = new FormData();
    formData.append("file", $scope.file);
    return HTTPService.post("service/import", formData, importPostHeaders, undefined, angular.identity).then(function () {
      HTTPService.updateAllData();
      TagsService.update();
    });
  };
  $scope.exportData = function () {
    var form = $('<form>', {
      html: '<input type="hidden" name="access_token" value="' + AuthorizationService.access_token + '" />',
      action: "service/export",
      method: "post"
    });
    form.appendTo(document.body).submit().remove();
  };
  $scope.performCleanup = function () {
    $scope.operationSuccessful = false;
    $scope.userService.performCleanup().then(function () {
      $scope.operationSuccessful = true;
    });
  };
  $scope.performRecalculateBalance = function () {
    $scope.operationSuccessful = false;
    $scope.userService.performRecalculateBalance().then(function () {
      $scope.operationSuccessful = true;
    });
  };
  $scope.$watch(function () {
    return UserService.userData;
  }, function () {
    $scope.user = UserService.userData;
  });
});
<|endoftext|>


<commit_before>'use strict'
const reload = require('require-reload')(require);
const storage = require('./../util/node_persist_atomic.js');

const USER_DATA_KEY_PREFIX = 'User';
const SERVER_DATA_KEY_PREFIX = 'Server';
const GLOBAL_DATA_KEY = 'Global';

function getData(key) {
  return storage.getItem(key).then(data => {
    if (data) {
      return data;
    } else {
      return {};
    }
  });
}

function editData(key, editFunction) {
  return storage.editItem(key, data => {
    if (!data) {
      data = {};
    }
    return editFunction(data);
  });
}

function keyForUserId(userId) {
  return USER_DATA_KEY_PREFIX + userId;
}

function keyForServerId(serverId) {
  return SERVER_DATA_KEY_PREFIX + serverId;
}

class PersistenceImplementation {
  static getDataForUser(userId, persistenceState) {
    return getData(keyForUserId(userId));
  }

  static getDataForServer(serverId, persistenceState) {
    return getData(keyForServerId(serverId));
  }

  static getGlobalData(persistenceState) {
    return getData(GLOBAL_DATA_KEY);
  }

  static editDataForUser(userId, editDataFunction, persistenceState) {
    let key = keyForUserId(userId);
    return editData(key, editDataFunction);
  }

  static editDataForServer(serverId, editDataFunction, persistenceState) {
    let key = keyForServerId(serverId);
    return editData(key, editDataFunction);
  }

  static editGlobalData(editDataFunction, persistenceState) {
    return editData(GLOBAL_DATA_KEY, editDataFunction);
  }
}

module.exports = PersistenceImplementation;
<commit_msg>node persist atomic should be reloaded<commit_after>'use strict'
const reload = require('require-reload')(require);
const storage = reload('./../util/node_persist_atomic.js');

const USER_DATA_KEY_PREFIX = 'User';
const SERVER_DATA_KEY_PREFIX = 'Server';
const GLOBAL_DATA_KEY = 'Global';

function getData(key) {
  return storage.getItem(key).then(data => {
    if (data) {
      return data;
    } else {
      return {};
    }
  });
}

function editData(key, editFunction) {
  return storage.editItem(key, data => {
    if (!data) {
      data = {};
    }
    return editFunction(data);
  });
}

function keyForUserId(userId) {
  return USER_DATA_KEY_PREFIX + userId;
}

function keyForServerId(serverId) {
  return SERVER_DATA_KEY_PREFIX + serverId;
}

class PersistenceImplementation {
  static getDataForUser(userId, persistenceState) {
    return getData(keyForUserId(userId));
  }

  static getDataForServer(serverId, persistenceState) {
    return getData(keyForServerId(serverId));
  }

  static getGlobalData(persistenceState) {
    return getData(GLOBAL_DATA_KEY);
  }

  static editDataForUser(userId, editDataFunction, persistenceState) {
    let key = keyForUserId(userId);
    return editData(key, editDataFunction);
  }

  static editDataForServer(serverId, editDataFunction, persistenceState) {
    let key = keyForServerId(serverId);
    return editData(key, editDataFunction);
  }

  static editGlobalData(editDataFunction, persistenceState) {
    return editData(GLOBAL_DATA_KEY, editDataFunction);
  }
}

module.exports = PersistenceImplementation;
<|endoftext|>