<commit_before>define(['app/models/key'],
    /**
     *  Keys Controller
     *
     *  @returns Class
     */
    function(Key) {
        return Ember.ArrayController.extend(Ember.Evented, {

            /**
             *  Properties
             */

            content: [],
            selectedKeys: [],

            loading: false,
            addingKey: false,
            keyRequest: false,
            renamingKey: false,
            associatingKey: false,
            gettingPublicKey: false,
            gettingPrivateKey: false,
            disassociatingKey: false,
            settingDefaultKey: false,

            /**
             *
             *  Initialization
             *
             */

            load: function() {
                var that = this;
                this.set('loading', true);
                Mist.ajax.GET('/keys', {
                }).success(function(keys) {
                    that._setContent(keys);
                }).error(function() {
                    that._reload();
                }).complete(function(success) {
                    that.set('loading', false);
                    that.trigger('onLoad');
                });
            }.on('init'),

            /**
             *
             *  Methods
             *
             */

            addKey: function(keyId, keyPrivate, callback) {
                var that = this;
                this.set('addingKey', true);
                Mist.ajax.PUT('/keys', {
                    'id': keyId,
                    'priv': keyPrivate
                }).success(function(key) {
                    that._addKey(key);
                }).error(function(message) {
                    Mist.notificationController.notify(message);
                }).complete(function(success, key) {
                    that.set('addingKey', false);
                    if (callback) callback(success, key);
                });
                keyPrivate = null;
            },

            renameKey: function(keyId, newKeyId, callback) {
                var that = this;
                this.set('renamingKey', true);
                Mist.ajax.PUT('/keys/' + keyId, {
                    'new_id': newKeyId
                }).success(function() {
                    that._renameKey(keyId, newKeyId);
                }).error(function() {
                    Mist.notificationController.notify('Failed to rename key');
                }).complete(function(success) {
                    that.set('renamingKey', false);
                    if (callback) callback(success);
                });
            },

            deleteKey: function(keyId, callback) {
                var that = this;
                this.set('deletingKey', true);
                Mist.ajax.DELETE('/keys/' + keyId, {
                }).success(function() {
                    that._deleteKey(keyId);
                }).error(function() {
                    Mist.notificationController.notify('Failed to delete key');
                }).complete(function(success) {
                    that.set('deletingKey', false);
                    if (callback) callback(success);
                });
            },

            setDefaultKey: function(keyId, callback) {
                var that = this;
                this.set('settingDefaultKey', true);
                Mist.ajax.POST('/keys/' + keyId, {
                }).success(function() {
                    that._setDefaultKey(keyId);
                }).error(function() {
                    Mist.notificationController.notify('Failed to set default key');
                }).complete(function(success) {
                    that.set('settingDefaultKey', false);
                    if (callback) callback(success);
                });
            },

            // BIG TODO: Callback argument should be at the end of the parameters
            // We need to check every call to this function and change it (not urgent)
            associateKey: function(keyId, machine, callback, user , port) {

                var that = this;
                this.set('associatingKey', true);
                Mist.ajax.PUT('/backends/' + machine.backend.id + '/machines/' + machine.id + '/keys/' + keyId, {
                    'host': machine.getHost(),
                    'user': user,
                    'port': port
                }).success(function() {
                    that._associateKey(keyId, machine);
                }).error(function() {
                    // Try another user/port
                    Mist.machineKeysController.openSSH_Details();
                }).complete(function(success) {
                    that.set('associatingKey', false);
                    if (callback) callback(success, machine, keyId);
                });
            },

            disassociateKey: function(keyId, machine, host, callback) {
                var backend_id = machine.backend.id ? machine.backend.id : machine.backend;
                var that = this;
                this.set('disassociatingKey', true);
                Mist.ajax.DELETE('/backends/' + backend_id + '/machines/' + machine.id + '/keys/' + keyId, {
                    'host': machine.getHost()
                }).success(function() {
                    that._disassociateKey(keyId, machine);
                }).error(function() {
                    Mist.notificationController.notify('Failed to disassociate key');
                }).complete(function(success) {
                    that.set('disassociatingKey', false);
                    if (callback) callback(success);
                });
            },

            generateKey: function(callback) {
                var that = this;
                this.set('generatingKey', true);
                Mist.ajax.POST('/keys', {
                }).error(function() {
                    Mist.notificationController.notify('Failed to generate key');
                }).complete(function(success, key) {
                    that.set('generatingKey', false);
                    if (callback) callback(success, key.priv);
                });
            },

            getPrivateKey: function(keyId, callback) {
                var that = this;
                this.set('gettingPrivateKey', true);
                Mist.ajax.GET('/keys/' + keyId + '/private', {
                }).error(function() {
                    Mist.notificationController.notify('Failed to get private key');
                }).complete(function(success, keyPriv) {
                    that.set('gettingPrivateKey', false);
                    if (callback) callback(success, keyPriv);
                });
            },

            getPublicKey: function(keyId, callback) {
                var that = this;
                this.set('gettingPublicKey', true);
                Mist.ajax.GET('/keys/' + keyId + '/public', {
                }).error(function() {
                    Mist.notificationController.notify('Failed to get public key');
                }).complete(function(success, keyPub) {
                    that.set('gettingPublicKey', false);
                    if (callback) callback(success, keyPub);
                });
            },

            getKey: function(keyId) {
                return this.content.findBy('id', keyId);
            },

            getRequestedKey: function() {
                if (this.keyRequest) {
                    return this.getKey(this.keyRequest);
                }
            },

            keyExists: function(keyId) {
                return !!this.getKey(keyId);
            },

            getMachineKeysCount: function(machine) {
                var count = 0;
                this.content.forEach(function(key) {
                    key.machines.some(function(key_machine) {
                        if (key_machine[1] == machine.id && key_machine[0] == machine.backend.id) {
                            return ++count;
                        }
                    });
                });
                return count;
            },

            /**
             *
             *  Pseudo-Private Methods
             *
             */

            _reload: function() {
                Ember.run.later(this, function() {
                    this.load();
                }, 2000);
            },

            _setContent: function(keys) {
                var that = this;
                Ember.run(function() {
                    that.set('content', []);
                    keys.forEach(function(key) {
                        that.content.pushObject(Key.create(key));
                    });
                    that.trigger('onKeyListChange');
                });
            },

            _addKey: function(key) {
                Ember.run(this, function() {
                    this.content.pushObject(Key.create(key));
                    this.trigger('onKeyListChange');
                    this.trigger('onKeyAdd');
                });
            },

            _deleteKey: function(keyId) {
                Ember.run(this, function() {
                    this.content.removeObject(this.getKey(keyId));
                    this.trigger('onKeyListChange');
                    this.trigger('onKeyDelete');
                });
            },

            _renameKey: function(keyId, newKeyId) {
                Ember.run(this, function() {
                    this.getKey(keyId).set('id', newKeyId);
                    this.trigger('onKeyRename');
                });
            },

            _setDefaultKey: function(keyId) {
                Ember.run(this, function() {
                    this.content.forEach(function(key) {
                        key.set('isDefault', key.id == keyId);
                    });
                    this.trigger('onDefaultKeySet');
                });
            },

            _associateKey: function(keyId, machine) {
                Ember.run(this, function() {
                    this.getKey(keyId).machines.pushObject([machine.backend.id, machine.id]);
                    machine.set('keysCount', this.getMachineKeysCount(machine));
                    machine.set('probed', true);
                    machine.probe(keyId);
                    this.trigger('onKeyAssociate');
                });
            },

            _disassociateKey: function(keyId, machine) {
                Ember.run(this, function() {
                    var key = this.getKey(keyId);
                    key.machines.some(function(key_machine) {
                        if (key_machine[1] == machine.id && (key_machine[0] == machine.backend.id ||
                                                             key_machine[0] == machine.backend)) { // For ghost machines
                            key.machines.removeObject(key_machine);
                            return true;
                        }
                    });
                    machine.set('keysCount', this.getMachineKeysCount(machine));
                    machine.set('probed', !!machine.keysCount);
                    this.trigger('onKeyDisassociate');
                });
            },

            _updateSelectedKeys: function() {
                Ember.run(this, function() {
                    var newSelectedKeys = [];
                    this.content.forEach(function(key) {
                        if (key.selected) newSelectedKeys.push(key);
                    });
                    this.set('selectedKeys', newSelectedKeys);
                    this.trigger('onSelectedKeysChange');
                });
            },

            /**
             *
             *  Observers
             *
             */

            selectedKeysObserver: function() {
                Ember.run.once(this, '_updateSelectedKeys');
            }.observes('content.@each.selected')
        });
    }
);
<commit_msg>Do not set machine as probed when associating a key because it breaks when machines get created too quickly<commit_after>define(['app/models/key'],
    /**
     *  Keys Controller
     *
     *  @returns Class
     */
    function(Key) {
        return Ember.ArrayController.extend(Ember.Evented, {

            /**
             *  Properties
             */

            content: [],
            selectedKeys: [],

            loading: false,
            addingKey: false,
            keyRequest: false,
            renamingKey: false,
            associatingKey: false,
            gettingPublicKey: false,
            gettingPrivateKey: false,
            disassociatingKey: false,
            settingDefaultKey: false,

            /**
             *
             *  Initialization
             *
             */

            load: function() {
                var that = this;
                this.set('loading', true);
                Mist.ajax.GET('/keys', {
                }).success(function(keys) {
                    that._setContent(keys);
                }).error(function() {
                    that._reload();
                }).complete(function(success) {
                    that.set('loading', false);
                    that.trigger('onLoad');
                });
            }.on('init'),

            /**
             *
             *  Methods
             *
             */

            addKey: function(keyId, keyPrivate, callback) {
                var that = this;
                this.set('addingKey', true);
                Mist.ajax.PUT('/keys', {
                    'id': keyId,
                    'priv': keyPrivate
                }).success(function(key) {
                    that._addKey(key);
                }).error(function(message) {
                    Mist.notificationController.notify(message);
                }).complete(function(success, key) {
                    that.set('addingKey', false);
                    if (callback) callback(success, key);
                });
                keyPrivate = null;
            },

            renameKey: function(keyId, newKeyId, callback) {
                var that = this;
                this.set('renamingKey', true);
                Mist.ajax.PUT('/keys/' + keyId, {
                    'new_id': newKeyId
                }).success(function() {
                    that._renameKey(keyId, newKeyId);
                }).error(function() {
                    Mist.notificationController.notify('Failed to rename key');
                }).complete(function(success) {
                    that.set('renamingKey', false);
                    if (callback) callback(success);
                });
            },

            deleteKey: function(keyId, callback) {
                var that = this;
                this.set('deletingKey', true);
                Mist.ajax.DELETE('/keys/' + keyId, {
                }).success(function() {
                    that._deleteKey(keyId);
                }).error(function() {
                    Mist.notificationController.notify('Failed to delete key');
                }).complete(function(success) {
                    that.set('deletingKey', false);
                    if (callback) callback(success);
                });
            },

            setDefaultKey: function(keyId, callback) {
                var that = this;
                this.set('settingDefaultKey', true);
                Mist.ajax.POST('/keys/' + keyId, {
                }).success(function() {
                    that._setDefaultKey(keyId);
                }).error(function() {
                    Mist.notificationController.notify('Failed to set default key');
                }).complete(function(success) {
                    that.set('settingDefaultKey', false);
                    if (callback) callback(success);
                });
            },

            // BIG TODO: Callback argument should be at the end of the parameters
            // We need to check every call to this function and change it (not urgent)
            associateKey: function(keyId, machine, callback, user , port) {

                var that = this;
                this.set('associatingKey', true);
                Mist.ajax.PUT('/backends/' + machine.backend.id + '/machines/' + machine.id + '/keys/' + keyId, {
                    'host': machine.getHost(),
                    'user': user,
                    'port': port
                }).success(function() {
                    that._associateKey(keyId, machine);
                }).error(function() {
                    // Try another user/port
                    Mist.machineKeysController.openSSH_Details();
                }).complete(function(success) {
                    that.set('associatingKey', false);
                    if (callback) callback(success, machine, keyId);
                });
            },

            disassociateKey: function(keyId, machine, host, callback) {
                var backend_id = machine.backend.id ? machine.backend.id : machine.backend;
                var that = this;
                this.set('disassociatingKey', true);
                Mist.ajax.DELETE('/backends/' + backend_id + '/machines/' + machine.id + '/keys/' + keyId, {
                    'host': machine.getHost()
                }).success(function() {
                    that._disassociateKey(keyId, machine);
                }).error(function() {
                    Mist.notificationController.notify('Failed to disassociate key');
                }).complete(function(success) {
                    that.set('disassociatingKey', false);
                    if (callback) callback(success);
                });
            },

            generateKey: function(callback) {
                var that = this;
                this.set('generatingKey', true);
                Mist.ajax.POST('/keys', {
                }).error(function() {
                    Mist.notificationController.notify('Failed to generate key');
                }).complete(function(success, key) {
                    that.set('generatingKey', false);
                    if (callback) callback(success, key.priv);
                });
            },

            getPrivateKey: function(keyId, callback) {
                var that = this;
                this.set('gettingPrivateKey', true);
                Mist.ajax.GET('/keys/' + keyId + '/private', {
                }).error(function() {
                    Mist.notificationController.notify('Failed to get private key');
                }).complete(function(success, keyPriv) {
                    that.set('gettingPrivateKey', false);
                    if (callback) callback(success, keyPriv);
                });
            },

            getPublicKey: function(keyId, callback) {
                var that = this;
                this.set('gettingPublicKey', true);
                Mist.ajax.GET('/keys/' + keyId + '/public', {
                }).error(function() {
                    Mist.notificationController.notify('Failed to get public key');
                }).complete(function(success, keyPub) {
                    that.set('gettingPublicKey', false);
                    if (callback) callback(success, keyPub);
                });
            },

            getKey: function(keyId) {
                return this.content.findBy('id', keyId);
            },

            getRequestedKey: function() {
                if (this.keyRequest) {
                    return this.getKey(this.keyRequest);
                }
            },

            keyExists: function(keyId) {
                return !!this.getKey(keyId);
            },

            getMachineKeysCount: function(machine) {
                var count = 0;
                this.content.forEach(function(key) {
                    key.machines.some(function(key_machine) {
                        if (key_machine[1] == machine.id && key_machine[0] == machine.backend.id) {
                            return ++count;
                        }
                    });
                });
                return count;
            },

            /**
             *
             *  Pseudo-Private Methods
             *
             */

            _reload: function() {
                Ember.run.later(this, function() {
                    this.load();
                }, 2000);
            },

            _setContent: function(keys) {
                var that = this;
                Ember.run(function() {
                    that.set('content', []);
                    keys.forEach(function(key) {
                        that.content.pushObject(Key.create(key));
                    });
                    that.trigger('onKeyListChange');
                });
            },

            _addKey: function(key) {
                Ember.run(this, function() {
                    this.content.pushObject(Key.create(key));
                    this.trigger('onKeyListChange');
                    this.trigger('onKeyAdd');
                });
            },

            _deleteKey: function(keyId) {
                Ember.run(this, function() {
                    this.content.removeObject(this.getKey(keyId));
                    this.trigger('onKeyListChange');
                    this.trigger('onKeyDelete');
                });
            },

            _renameKey: function(keyId, newKeyId) {
                Ember.run(this, function() {
                    this.getKey(keyId).set('id', newKeyId);
                    this.trigger('onKeyRename');
                });
            },

            _setDefaultKey: function(keyId) {
                Ember.run(this, function() {
                    this.content.forEach(function(key) {
                        key.set('isDefault', key.id == keyId);
                    });
                    this.trigger('onDefaultKeySet');
                });
            },

            _associateKey: function(keyId, machine) {
                Ember.run(this, function() {
                    this.getKey(keyId).machines.pushObject([machine.backend.id, machine.id]);
                    machine.set('keysCount', this.getMachineKeysCount(machine));
                    machine.probe(keyId);
                    this.trigger('onKeyAssociate');
                });
            },

            _disassociateKey: function(keyId, machine) {
                Ember.run(this, function() {
                    var key = this.getKey(keyId);
                    key.machines.some(function(key_machine) {
                        if (key_machine[1] == machine.id && (key_machine[0] == machine.backend.id ||
                                                             key_machine[0] == machine.backend)) { // For ghost machines
                            key.machines.removeObject(key_machine);
                            return true;
                        }
                    });
                    machine.set('keysCount', this.getMachineKeysCount(machine));
                    machine.set('probed', !!machine.keysCount);
                    this.trigger('onKeyDisassociate');
                });
            },

            _updateSelectedKeys: function() {
                Ember.run(this, function() {
                    var newSelectedKeys = [];
                    this.content.forEach(function(key) {
                        if (key.selected) newSelectedKeys.push(key);
                    });
                    this.set('selectedKeys', newSelectedKeys);
                    this.trigger('onSelectedKeysChange');
                });
            },

            /**
             *
             *  Observers
             *
             */

            selectedKeysObserver: function() {
                Ember.run.once(this, '_updateSelectedKeys');
            }.observes('content.@each.selected')
        });
    }
);
<|endoftext|>


<commit_before>import DiseaseProgression from '../shr/condition/DiseaseProgression';
import Evidence from '../shr/finding/Evidence';
import lookup from '../../lib/progression_lookup.jsx';
import CreationTime from '../shr/core/CreationTime';
import ClinicallyRelevantTime from '../shr/finding/ClinicallyRelevantTime';
import Entry from '../shr/base/Entry';
import Reference from '../Reference';
import EntryType from '../shr/base/EntryType';
import moment from 'moment';
import LastUpdated from '../shr/base/LastUpdated';

// FluxDiseaseProgression class to hide codeableconcepts
class FluxDiseaseProgression {
    constructor(json) {
        this._diseaseProgression = DiseaseProgression.fromJSON(json);
        if (!this._diseaseProgression.entryInfo) {
            let entry = new Entry();
            entry.entryType = new EntryType();
            entry.entryType.uri = 'http://standardhealthrecord.org/spec/shr/condition/DiseaseProgression';
            let today = new moment().format("D MMM YYYY");
            entry.lastUpdated = new LastUpdated();
            entry.lastUpdated.instant = today;
            this._diseaseProgression.entryInfo = entry;
        }
    }

    get entryInfo() {
        return this._diseaseProgression.entryInfo;
    }

    /**
     *  Getter for status
     *  This will return the displayText string from CodeableConcept Value
     */
    get status() {
        if (!this._diseaseProgression.value) return null;
        return this._diseaseProgression.value.coding[0].displayText.value;
    }

    /**
     *  Setter for status
     *  The setter method is expecting a status sting
     *  The method will lookup the corresponding coding/codesystem and set the _codeableConcept property
     */
    set status(status) {
        this._diseaseProgression.value = lookup.getStatusCodeableConcept(status);
    }

    /**
     *  Getter for status' code
     *  This will return the code string from CodeableConcept, corresponding to the status' code
     */
    get statusAsCode() {
        return this._diseaseProgression.value.coding[0].code;
    }

    /**
     *  Getter for evidence
     *  This will return an array of displayText strings from Evidence array
     */
    get evidence() {
        if (!this._diseaseProgression.evidence) return [];
        return this._diseaseProgression.evidence.map((e) => {
            return e.value.coding[0].displayText.value;
        });
    }

    /**
     *  Setter for evidence
     *  The method is expecting an array of reason strings
     *  The method will lookup the corresponding coding/codesystem and set the evidence array
     */
    set evidence(evidence) {
        this._diseaseProgression.evidence = evidence.map((e) => {
            let ev = new Evidence();
            ev.value = lookup.getEvidenceCodeableConcept(e);
            return ev;
        });
    }

    get referenceDate() {
        if (!this._diseaseProgression.clinicallyRelevantTime) return null;
        return this._diseaseProgression.clinicallyRelevantTime.value;
    }

    set referenceDate(date) {
        if (!date) return;
        if (!this._diseaseProgression.clinicallyRelevantTime) {
            let clinicallyRelevantTime = new ClinicallyRelevantTime();
            clinicallyRelevantTime.value = date;
            this._diseaseProgression.clinicallyRelevantTime = clinicallyRelevantTime;
        } else {
            this._diseaseProgression.clinicallyRelevantTime.value = date;
        }
    }

    // Flux added
    get asOfDate() {
        if (!this._diseaseProgression.entryInfo || !this._diseaseProgression.entryInfo.creationTime) return null;
        return this._diseaseProgression.entryInfo.creationTime.value;
    }

    set asOfDate(val) {
        if (!this._diseaseProgression.entryInfo.creationTime) {
            let creationTime = new CreationTime();
            creationTime.value = val;
            this._diseaseProgression.entryInfo.creationTime = creationTime;
        } else {
            this._diseaseProgression.entryInfo.creationTime.value = val;
        }
    }

    get focalSubjectReference() {
        if (this._diseaseProgression.focalSubjectReference) {
            return this._diseaseProgression.focalSubjectReference;
        }
        return null;
    }

    set focalSubjectReference(val) {
        this._diseaseProgression.focalSubjectReference = val;
    }

    setFocalSubjectReference(obj) {
        let ref = new Reference(obj.entryInfo.shrId, obj.entryInfo.entryId, obj.entryInfo.entryType);
        this.focalSubjectReference = ref;
    }
}

export default FluxDiseaseProgression;<commit_msg>Filter evidence items to ignore case and duplicates for evidence items in FluxDiseaseProgression.<commit_after>import DiseaseProgression from '../shr/condition/DiseaseProgression';
import Evidence from '../shr/finding/Evidence';
import lookup from '../../lib/progression_lookup.jsx';
import CreationTime from '../shr/core/CreationTime';
import ClinicallyRelevantTime from '../shr/finding/ClinicallyRelevantTime';
import Entry from '../shr/base/Entry';
import Reference from '../Reference';
import EntryType from '../shr/base/EntryType';
import moment from 'moment';
import LastUpdated from '../shr/base/LastUpdated';

// FluxDiseaseProgression class to hide codeableconcepts
class FluxDiseaseProgression {
    constructor(json) {
        this._diseaseProgression = DiseaseProgression.fromJSON(json);
        if (!this._diseaseProgression.entryInfo) {
            let entry = new Entry();
            entry.entryType = new EntryType();
            entry.entryType.uri = 'http://standardhealthrecord.org/spec/shr/condition/DiseaseProgression';
            let today = new moment().format("D MMM YYYY");
            entry.lastUpdated = new LastUpdated();
            entry.lastUpdated.instant = today;
            this._diseaseProgression.entryInfo = entry;
        }
    }

    get entryInfo() {
        return this._diseaseProgression.entryInfo;
    }

    /**
     *  Getter for status
     *  This will return the displayText string from CodeableConcept Value
     */
    get status() {
        if (!this._diseaseProgression.value) return null;
        return this._diseaseProgression.value.coding[0].displayText.value;
    }

    /**
     *  Setter for status
     *  The setter method is expecting a status sting
     *  The method will lookup the corresponding coding/codesystem and set the _codeableConcept property
     */
    set status(status) {
        this._diseaseProgression.value = lookup.getStatusCodeableConcept(status);
    }

    /**
     *  Getter for status' code
     *  This will return the code string from CodeableConcept, corresponding to the status' code
     */
    get statusAsCode() {
        return this._diseaseProgression.value.coding[0].code;
    }

    /**
     *  Getter for evidence
     *  This will return an array of displayText strings from Evidence array
     */
    get evidence() {
        if (!this._diseaseProgression.evidence) return [];
        return this._diseaseProgression.evidence.map((e) => {
            return e.value.coding[0].displayText.value;
        });
    }

    /**
     *  Setter for evidence
     *  The method is expecting an array of reason strings
     *  The method will lookup the corresponding coding/codesystem and set the evidence array
     */
    set evidence(evidence) {
        // filter evidence to ignore case and to make sure there are no duplicates
        const filteredEvidence = evidence.map(e => e.toLowerCase()).filter((e, index, arr) => {
            return arr.indexOf(e) === index;
        });

        this._diseaseProgression.evidence = filteredEvidence.map((e) => {
            let ev = new Evidence();
            ev.value = lookup.getEvidenceCodeableConcept(e);
            return ev;
        });
    }

    get referenceDate() {
        if (!this._diseaseProgression.clinicallyRelevantTime) return null;
        return this._diseaseProgression.clinicallyRelevantTime.value;
    }

    set referenceDate(date) {
        if (!date) return;
        if (!this._diseaseProgression.clinicallyRelevantTime) {
            let clinicallyRelevantTime = new ClinicallyRelevantTime();
            clinicallyRelevantTime.value = date;
            this._diseaseProgression.clinicallyRelevantTime = clinicallyRelevantTime;
        } else {
            this._diseaseProgression.clinicallyRelevantTime.value = date;
        }
    }

    // Flux added
    get asOfDate() {
        if (!this._diseaseProgression.entryInfo || !this._diseaseProgression.entryInfo.creationTime) return null;
        return this._diseaseProgression.entryInfo.creationTime.value;
    }

    set asOfDate(val) {
        if (!this._diseaseProgression.entryInfo.creationTime) {
            let creationTime = new CreationTime();
            creationTime.value = val;
            this._diseaseProgression.entryInfo.creationTime = creationTime;
        } else {
            this._diseaseProgression.entryInfo.creationTime.value = val;
        }
    }

    get focalSubjectReference() {
        if (this._diseaseProgression.focalSubjectReference) {
            return this._diseaseProgression.focalSubjectReference;
        }
        return null;
    }

    set focalSubjectReference(val) {
        this._diseaseProgression.focalSubjectReference = val;
    }

    setFocalSubjectReference(obj) {
        let ref = new Reference(obj.entryInfo.shrId, obj.entryInfo.entryId, obj.entryInfo.entryType);
        this.focalSubjectReference = ref;
    }
}

export default FluxDiseaseProgression;<|endoftext|>


<commit_before>angular
	.module('ngSharepoint')
	.factory('$spLoader', ['$q', '$http', '$sp', function($q, $http, $sp) {
		var scripts = {};
		var SPLoader = {};
		SPLoader.loadScript = function(lib) {
			var query = $q(function(resolve, reject) {
				var element = document.createElement('script');
				element.type = 'text/javascript';
				if (lib.startsWith('//')) {
					element.src = lib;
				}else {
					element.src = $sp.getSiteUrl() + '_layouts/15/' + lib;
				}
				element.onload = resolve;
				element.onerror = reject;
				document.head.appendChild(element);
			});
			scripts[lib] = query;
			return query;
		};
		SPLoader.waitUntil = function(lib) {
			return $q(function(resolve, reject) {
				if (scripts.hasOwnProperty(lib)) {
					scripts[lib].then(resolve, reject);
				}else if ($sp.getAutoload()) {
					reject("Library was not requested");
				}else {
					resolve();
				}
			});
		};
		SPLoader.query = function(queryObject) {
			var query = {
				url: $sp.getSiteUrl() + queryObject.url,
				method: queryObject.method,
				headers: {
					'Accept': 'application/json; odata=verbose',
					'Content-Type': 'application/json; odata=verbose'
				}
			};
			if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken()) {
				return $q(function(resolve, reject) {
					SPLoader.waitUntil('SP.RequestExecutor.js').then(function() {
						if (queryObject.hasOwnProperty('data') && queryObject.data !== undefined && queryObject !== null) {
							query.body = queryObject.data;
						}
						query.success = resolve;
						query.error = reject;
						new SP.RequestExecutor($sp.getSiteUrl()).executeAsync(query);
					});
				});
			}else {
				return $q(function(resolve, reject) {
					if (queryObject.hasOwnProperty('data') && queryObject.data !== undefined && queryObject !== null) {
						query.data = queryObject.data;
					}
					query.headers.Authorization = 'Bearer ' + $sp.getAccessToken();
					$http(query).then(resolve, reject);
				});
			}
		};
		return (SPLoader);
	}]);<commit_msg>Load Logger<commit_after>angular
	.module('ngSharepoint')
	.factory('$spLoader', ['$q', '$http', '$sp', '$spLog', function($q, $http, $sp, $spLog) {
		var scripts = {};
		var SPLoader = {};
		SPLoader.loadScript = function(lib) {
			var query = $q(function(resolve, reject) {
				var element = document.createElement('script');
				element.type = 'text/javascript';
				if (lib.startsWith('//')) {
					element.src = lib;
				}else {
					element.src = $sp.getSiteUrl() + '_layouts/15/' + lib;
				}
				element.onload = resolve;
				element.onerror = reject;
				document.head.appendChild(element);
			});
			scripts[lib] = query;
			return query;
		};
		SPLoader.waitUntil = function(lib) {
			return $q(function(resolve, reject) {
				if (scripts.hasOwnProperty(lib)) {
					scripts[lib].then(resolve, reject);
				}else if ($sp.getAutoload()) {
					reject("Library was not requested");
				}else {
					resolve();
				}
			});
		};
		SPLoader.query = function(queryObject) {
			var query = {
				url: $sp.getSiteUrl() + queryObject.url,
				method: queryObject.method,
				headers: {
					'Accept': 'application/json; odata=verbose',
					'Content-Type': 'application/json; odata=verbose'
				}
			};
			if ($sp.getConnectionMode() === 'REST' && !$sp.getAccessToken()) {
				return $q(function(resolve, reject) {
					SPLoader.waitUntil('SP.RequestExecutor.js').then(function() {
						if (queryObject.hasOwnProperty('data') && queryObject.data !== undefined && queryObject !== null) {
							query.body = queryObject.data;
						}
						query.success = resolve;
						query.error = reject;
						new SP.RequestExecutor($sp.getSiteUrl()).executeAsync(query);
					});
				});
			}else {
				return $q(function(resolve, reject) {
					if (queryObject.hasOwnProperty('data') && queryObject.data !== undefined && queryObject !== null) {
						query.data = queryObject.data;
					}
					query.headers.Authorization = 'Bearer ' + $sp.getAccessToken();
					$http(query).then(resolve, reject);
				});
			}
		};
		return (SPLoader);
	}]);<|endoftext|>


<commit_before>goog.provide('ol.interaction.KeyboardZoom');

goog.require('goog.asserts');
goog.require('goog.events.KeyHandler.EventType');
goog.require('ol.events.ConditionType');
goog.require('ol.events.condition');
goog.require('ol.interaction.Interaction');

/**
 * @classdesc
 * Allows the user to zoom the map using keyboard + and -.
 * Note that, although this interaction is by default included in maps,
 * the keys can only be used when browser focus is on the element to which
 * the keyboard events are attached. By default, this is the map div,
 * though you can change this with the `keyboardEventTarget` in
 * {@link ol.Map}. `document` never loses focus but, for any other element,
 * focus will have to be on, and returned to, this element if the keys are to
 * function.
 * See also {@link ol.interaction.KeyboardPan}.
 *
 * @constructor
 * @param {olx.interaction.KeyboardZoomOptions=} opt_options Options.
 * @extends {ol.interaction.Interaction}
 * @api stable
 */
ol.interaction.KeyboardZoom = function(opt_options) {

  goog.base(this, {
    handleEvent: ol.interaction.KeyboardZoom.handleEvent
  });

  var options = opt_options ? opt_options : {};

  /**
   * @private
   * @type {ol.events.ConditionType}
   */
  this.condition_ = options.condition ? options.condition :
          ol.events.condition.targetNotEditable;

  /**
   * @private
   * @type {number}
   */
  this.delta_ = options.delta ? options.delta : 1;

  /**
   * @private
   * @type {number}
   */
  this.duration_ = options.duration ? options.duration : 100;

};
goog.inherits(ol.interaction.KeyboardZoom, ol.interaction.Interaction);

/**
 * Handles the {@link ol.MapBrowserEvent map browser event} if it was a
 * `KeyEvent`, and decides whether to zoom in or out (depending on whether the
 * key pressed was '+' or '-').
 * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
 * @return {boolean} `false` to stop event propagation.
 * @this {ol.interaction.KeyboardZoom}
 * @api
 */
ol.interaction.KeyboardZoom.handleEvent = function(mapBrowserEvent) {
  var stopEvent = false;
  if (mapBrowserEvent.type == goog.events.KeyHandler.EventType.KEY) {
    var keyEvent = /** @type {goog.events.KeyEvent} */
        (mapBrowserEvent.browserEvent);
    var charCode = keyEvent.charCode;
    if (this.condition_(mapBrowserEvent) &&
        (charCode == '+'.charCodeAt(0) || charCode == '-'.charCodeAt(0))) {
      var map = mapBrowserEvent.map;
      var delta = (charCode == '+'.charCodeAt(0)) ? this.delta_ : -this.delta_;
      map.render();
      var view = map.getView();
      goog.asserts.assert(view, 'map must have view');
      ol.interaction.Interaction.zoomByDelta(
          map, view, delta, undefined, this.duration_);
      mapBrowserEvent.preventDefault();
      stopEvent = true;
    }
  }
  return !stopEvent;
};
<commit_msg>Fix KeyboardZoom interation duration option, allow `0` value.<commit_after>goog.provide('ol.interaction.KeyboardZoom');

goog.require('goog.asserts');
goog.require('goog.events.KeyHandler.EventType');
goog.require('ol.events.ConditionType');
goog.require('ol.events.condition');
goog.require('ol.interaction.Interaction');

/**
 * @classdesc
 * Allows the user to zoom the map using keyboard + and -.
 * Note that, although this interaction is by default included in maps,
 * the keys can only be used when browser focus is on the element to which
 * the keyboard events are attached. By default, this is the map div,
 * though you can change this with the `keyboardEventTarget` in
 * {@link ol.Map}. `document` never loses focus but, for any other element,
 * focus will have to be on, and returned to, this element if the keys are to
 * function.
 * See also {@link ol.interaction.KeyboardPan}.
 *
 * @constructor
 * @param {olx.interaction.KeyboardZoomOptions=} opt_options Options.
 * @extends {ol.interaction.Interaction}
 * @api stable
 */
ol.interaction.KeyboardZoom = function(opt_options) {

  goog.base(this, {
    handleEvent: ol.interaction.KeyboardZoom.handleEvent
  });

  var options = opt_options ? opt_options : {};

  /**
   * @private
   * @type {ol.events.ConditionType}
   */
  this.condition_ = options.condition ? options.condition :
          ol.events.condition.targetNotEditable;

  /**
   * @private
   * @type {number}
   */
  this.delta_ = options.delta ? options.delta : 1;

  /**
   * @private
   * @type {number}
   */
  this.duration_ = options.duration !== undefined ? options.duration : 100;

};
goog.inherits(ol.interaction.KeyboardZoom, ol.interaction.Interaction);

/**
 * Handles the {@link ol.MapBrowserEvent map browser event} if it was a
 * `KeyEvent`, and decides whether to zoom in or out (depending on whether the
 * key pressed was '+' or '-').
 * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event.
 * @return {boolean} `false` to stop event propagation.
 * @this {ol.interaction.KeyboardZoom}
 * @api
 */
ol.interaction.KeyboardZoom.handleEvent = function(mapBrowserEvent) {
  var stopEvent = false;
  if (mapBrowserEvent.type == goog.events.KeyHandler.EventType.KEY) {
    var keyEvent = /** @type {goog.events.KeyEvent} */
        (mapBrowserEvent.browserEvent);
    var charCode = keyEvent.charCode;
    if (this.condition_(mapBrowserEvent) &&
        (charCode == '+'.charCodeAt(0) || charCode == '-'.charCodeAt(0))) {
      var map = mapBrowserEvent.map;
      var delta = (charCode == '+'.charCodeAt(0)) ? this.delta_ : -this.delta_;
      map.render();
      var view = map.getView();
      goog.asserts.assert(view, 'map must have view');
      ol.interaction.Interaction.zoomByDelta(
          map, view, delta, undefined, this.duration_);
      mapBrowserEvent.preventDefault();
      stopEvent = true;
    }
  }
  return !stopEvent;
};
<|endoftext|>


<commit_before>// ERPNext: Copyright 2013 Web Notes Technologies Pvt Ltd
// GNU General Public License. See "license.txt"

wn.module_page["Accounts"] = [
	{
		title: wn._("Documents"),
		icon: "icon-copy",
		items: [
			{
				label: wn._("Journal Voucher"),
				description: wn._("Accounting journal entries."),
				doctype:"Journal Voucher"
			},
			{
				label: wn._("Sales Invoice"),
				description: wn._("Bills raised to Customers."),
				doctype:"Sales Invoice"
			},
			{
				label: wn._("Purchase Invoice"),
				description: wn._("Bills raised by Suppliers."),
				doctype:"Purchase Invoice"
			},
		]
	},
	{
		title: wn._("Masters"),
		icon: "icon-book",
		items: [
			{
				label: wn._("Chart of Accounts"),
				route: "Accounts Browser/Account",
				description: wn._("Structure of books of accounts."),
				doctype:"Account"
			},
			{
				label: wn._("Chart of Cost Centers"),
				route: "Accounts Browser/Cost Center",
				description: wn._("Structure cost centers for budgeting."),
				doctype:"Cost Center"
			},
			{
				label: wn._("Customer"),
				description: wn._("Customer database."),
				doctype:"Customer"
			},
			{
				label: wn._("Supplier"),
				description: wn._("Supplier database."),
				doctype:"Supplier"
			},
		]
	},
	{
		title: wn._("Tools"),
		icon: "icon-wrench",
		items: [
			{
				"route":"Form/Bank Reconciliation/Bank Reconciliation",
				"label": wn._("Bank Reconciliation"),
				"description": wn._("Update bank payment dates with journals."),
				doctype: "Bank Reconciliation"
			},
			{
				"route":"Form/Payment to Invoice Matching Tool/Payment to Invoice Matching Tool",
				"label": wn._("Payment Reconciliation"),
				"description": wn._("Match non-linked Invoices and Payments."),
				doctype: "Payment to Invoice Matching Tool"

			},
			{
				"label": wn._("Period Closing Voucher"),
				"doctype": "Period Closing Voucher",
				description: "Close Balance Sheet and book Profit or Loss."
			},
			{
				"page":"voucher-import-tool",
				"label": wn._("Voucher Import Tool"),
				"description": "Import accounting entries from CSV."
			},
		]
	},
	{
		title: wn._("Setup"),
		icon: "icon-cog",
		items: [
			{
				"label": wn._("Sales Taxes and Charges Master"),
				"doctype":"Sales Taxes and Charges Master",
				"description": wn._("Tax Template for Sales")
			},
			{
				"label": wn._("Purchase Taxes and Charges Master"),
				"doctype":"Purchase Taxes and Charges Master",
				"description": wn._("Tax Template for Purchase")
			},
			{
				"label": wn._("Point-of-Sale Setting"),
				"doctype":"POS Setting",
				"description": "User settings for Point-of-sale (POS)"
			},
			{
				"doctype":"Budget Distribution",
				"label": wn._("Budget Distribution"),
				"description": wn._("Seasonality for setting budgets.")
			},
			{
				"doctype":"Terms and Conditions",
				"label": wn._("Terms and Conditions Template"),
				description: wn._("Template of terms or contract.")
			},
			{
				"doctype":"Mode of Payment",
				"label": wn._("Mode of Payment"),
				description: wn._("e.g. Bank, Cash, Credit Card")
			},
			{
				"doctype":"C-Form",
				"label": wn._("C-Form"),
				description: "C-Form records",
				country: "India"
			}
		]
	},
	{
		title: wn._("Main Reports"),
		right: true,
		icon: "icon-table",
		items: [
			{
				"label":wn._("General Ledger"),
				page: "general-ledger"
			},
			{
				"label":wn._("Trial Balance"),
				page: "trial-balance"
			},
			{
				"page":"Financial Statements",
				"label": wn._("Financial Statements")
			},
			{
				"label":wn._("Accounts Receivable"),
				route: "query-report/Accounts Receivable",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Accounts Payable"),
				route: "query-report/Accounts Payable",
				doctype: "Purchase Invoice"
			},
			{
				"label":wn._("Sales Register"),
				route: "query-report/Sales Register",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Purchase Register"),
				route: "query-report/Purchase Register",
				doctype: "Purchase Invoice"
			},
		]
	},
	{
		title: wn._("Analytics"),
		right: true,
		icon: "icon-bar-chart",
		items: [
			{
				"label":wn._("Financial Analytics"),
				page: "financial-analytics"
			},
			{
				"label":wn._("Trend Analyzer"),
				route: "Report/Profile/Trend Analyzer",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Gross Profit"),
				route: "query-report/Gross Profit",
				doctype: "Sales Invoice"
			},
		]
	},
	{
		title: wn._("Reports"),
		right: true,
		icon: "icon-list",
		items: [
			{
				"label":wn._("Bank Reconciliation Statement"),
				route: "query-report/Bank Reconciliation Statement",
				doctype: "Journal Voucher"
			},
			{
				"label":wn._("Delivered Items To Be Billed"),
				route: "query-report/Delivered Items To Be Billed",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Ordered Items To Be Billed"),
				route: "query-report/Ordered Items To Be Billed",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Bank Clearance Summary"),
				route: "query-report/Bank Clearance Summary",
				doctype: "Journal Voucher"
			},
			{
				"label":wn._("Payment Collection With Ageing"),
				route: "query-report/Payment Collection With Ageing",
				doctype: "Journal Voucher"
			},
			{
				"label":wn._("Payment Made With Ageing"),
				route: "query-report/Payment Made With Ageing",
				doctype: "Journal Voucher"
			},
			{
				"label":wn._("Sales Partners Commission"),
				route: "query-report/Sales Partners Commission",
				doctype: "Sales Invoice"
			},
		]
	}
]

pscript['onload_accounts-home'] = function(wrapper) {
	wn.views.moduleview.make(wrapper, "Accounts");
}<commit_msg>[report] reports link added into accounts home page<commit_after>// ERPNext: Copyright 2013 Web Notes Technologies Pvt Ltd
// GNU General Public License. See "license.txt"

wn.module_page["Accounts"] = [
	{
		title: wn._("Documents"),
		icon: "icon-copy",
		items: [
			{
				label: wn._("Journal Voucher"),
				description: wn._("Accounting journal entries."),
				doctype:"Journal Voucher"
			},
			{
				label: wn._("Sales Invoice"),
				description: wn._("Bills raised to Customers."),
				doctype:"Sales Invoice"
			},
			{
				label: wn._("Purchase Invoice"),
				description: wn._("Bills raised by Suppliers."),
				doctype:"Purchase Invoice"
			},
		]
	},
	{
		title: wn._("Masters"),
		icon: "icon-book",
		items: [
			{
				label: wn._("Chart of Accounts"),
				route: "Accounts Browser/Account",
				description: wn._("Structure of books of accounts."),
				doctype:"Account"
			},
			{
				label: wn._("Chart of Cost Centers"),
				route: "Accounts Browser/Cost Center",
				description: wn._("Structure cost centers for budgeting."),
				doctype:"Cost Center"
			},
			{
				label: wn._("Customer"),
				description: wn._("Customer database."),
				doctype:"Customer"
			},
			{
				label: wn._("Supplier"),
				description: wn._("Supplier database."),
				doctype:"Supplier"
			},
		]
	},
	{
		title: wn._("Tools"),
		icon: "icon-wrench",
		items: [
			{
				"route":"Form/Bank Reconciliation/Bank Reconciliation",
				"label": wn._("Bank Reconciliation"),
				"description": wn._("Update bank payment dates with journals."),
				doctype: "Bank Reconciliation"
			},
			{
				"route":"Form/Payment to Invoice Matching Tool/Payment to Invoice Matching Tool",
				"label": wn._("Payment Reconciliation"),
				"description": wn._("Match non-linked Invoices and Payments."),
				doctype: "Payment to Invoice Matching Tool"

			},
			{
				"label": wn._("Period Closing Voucher"),
				"doctype": "Period Closing Voucher",
				description: "Close Balance Sheet and book Profit or Loss."
			},
			{
				"page":"voucher-import-tool",
				"label": wn._("Voucher Import Tool"),
				"description": "Import accounting entries from CSV."
			},
		]
	},
	{
		title: wn._("Setup"),
		icon: "icon-cog",
		items: [
			{
				"label": wn._("Sales Taxes and Charges Master"),
				"doctype":"Sales Taxes and Charges Master",
				"description": wn._("Tax Template for Sales")
			},
			{
				"label": wn._("Purchase Taxes and Charges Master"),
				"doctype":"Purchase Taxes and Charges Master",
				"description": wn._("Tax Template for Purchase")
			},
			{
				"label": wn._("Point-of-Sale Setting"),
				"doctype":"POS Setting",
				"description": "User settings for Point-of-sale (POS)"
			},
			{
				"doctype":"Budget Distribution",
				"label": wn._("Budget Distribution"),
				"description": wn._("Seasonality for setting budgets.")
			},
			{
				"doctype":"Terms and Conditions",
				"label": wn._("Terms and Conditions Template"),
				description: wn._("Template of terms or contract.")
			},
			{
				"doctype":"Mode of Payment",
				"label": wn._("Mode of Payment"),
				description: wn._("e.g. Bank, Cash, Credit Card")
			},
			{
				"doctype":"C-Form",
				"label": wn._("C-Form"),
				description: "C-Form records",
				country: "India"
			}
		]
	},
	{
		title: wn._("Main Reports"),
		right: true,
		icon: "icon-table",
		items: [
			{
				"label":wn._("General Ledger"),
				page: "general-ledger"
			},
			{
				"label":wn._("Trial Balance"),
				page: "trial-balance"
			},
			{
				"page":"Financial Statements",
				"label": wn._("Financial Statements")
			},
			{
				"label":wn._("Accounts Receivable"),
				route: "query-report/Accounts Receivable",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Accounts Payable"),
				route: "query-report/Accounts Payable",
				doctype: "Purchase Invoice"
			},
			{
				"label":wn._("Sales Register"),
				route: "query-report/Sales Register",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Purchase Register"),
				route: "query-report/Purchase Register",
				doctype: "Purchase Invoice"
			},
		]
	},
	{
		title: wn._("Analytics"),
		right: true,
		icon: "icon-bar-chart",
		items: [
			{
				"label":wn._("Financial Analytics"),
				page: "financial-analytics"
			},
			{
				"label":wn._("Trend Analyzer"),
				route: "Report/Profile/Trend Analyzer",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Gross Profit"),
				route: "query-report/Gross Profit",
				doctype: "Sales Invoice"
			},
		]
	},
	{
		title: wn._("Reports"),
		right: true,
		icon: "icon-list",
		items: [
			{
				"label":wn._("Bank Reconciliation Statement"),
				route: "query-report/Bank Reconciliation Statement",
				doctype: "Journal Voucher"
			},
			{
				"label":wn._("Delivered Items To Be Billed"),
				route: "query-report/Delivered Items To Be Billed",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Received Items To Be Billed"),
				route: "query-report/Received Items To Be Billed",
				doctype: "Purchase Invoice"
			},
			{
				"label":wn._("Ordered Items To Be Billed"),
				route: "query-report/Ordered Items To Be Billed",
				doctype: "Sales Invoice"
			},
			{
				"label":wn._("Purchase Order Items To Be Billed"),
				route: "query-report/Purchase Order Items To Be Billed",
				doctype: "Purchase Invoice"
			},
			{
				"label":wn._("Bank Clearance Summary"),
				route: "query-report/Bank Clearance Summary",
				doctype: "Journal Voucher"
			},
			{
				"label":wn._("Payment Collection With Ageing"),
				route: "query-report/Payment Collection With Ageing",
				doctype: "Journal Voucher"
			},
			{
				"label":wn._("Payment Made With Ageing"),
				route: "query-report/Payment Made With Ageing",
				doctype: "Journal Voucher"
			},
			{
				"label":wn._("Sales Partners Commission"),
				route: "query-report/Sales Partners Commission",
				doctype: "Sales Invoice"
			},
		]
	}
]

pscript['onload_accounts-home'] = function(wrapper) {
	wn.views.moduleview.make(wrapper, "Accounts");
}<|endoftext|>


<commit_before>/* global Scroller */
import Ember from 'ember';
import { translate } from 'ember-collection/utils/translate';

var fieldRegex = /input|textarea|select/i,
  hasTouch = ('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch,
  handleStart, handleMove, handleEnd, handleCancel,
  startEvent, moveEvent, endEvent, cancelEvent;
if (hasTouch) {
  startEvent = 'touchstart';
  handleStart = function (e) {
    var touch = e.touches[0],
      target = touch && touch.target;
    // avoid e.preventDefault() on fields
    if (target && fieldRegex.test(target.tagName)) {
      return;
    }
    bindWindow(this.scrollerEventHandlers);
    this.doTouchStart(e.touches, e.timeStamp);
  };
  moveEvent = 'touchmove';
  handleMove = function (e) {
    this.doTouchMove(e.touches, e.timeStamp);
  };
  endEvent = 'touchend';
  handleEnd = function (e) {
    unbindWindow(this.scrollerEventHandlers);
    this.doTouchEnd(e.timeStamp);
  };
  cancelEvent = 'touchcancel';
  handleCancel = function (e) {
    unbindWindow(this.scrollerEventHandlers);
    this.doTouchEnd(e.timeStamp);
  };
} else {
  startEvent = 'mousedown';
  handleStart = function (e) {
    if (e.which !== 1) {
      return;
    }
    var target = e.target;
    // avoid e.preventDefault() on fields
    if (target && fieldRegex.test(target.tagName)) {
      return;
    }
    bindWindow(this.scrollerEventHandlers);
    this.doTouchStart([e], e.timeStamp);
    e.preventDefault();
  };
  moveEvent = 'mousemove';
  handleMove = function (e) {
    this.doTouchMove([e], e.timeStamp);
  };
  endEvent = 'mouseup';
  handleEnd = function (e) {
    unbindWindow(this.scrollerEventHandlers);
    this.doTouchEnd(e.timeStamp);
  };
  cancelEvent = 'mouseout';
  handleCancel = function (e) {
    if (e.relatedTarget) {
      return;
    }
    unbindWindow(this.scrollerEventHandlers);
    this.doTouchEnd(e.timeStamp);
  };
}

function handleWheel(e) {
  this.mouseWheel(e);
  e.preventDefault();
}

function bindElement(el, handlers) {
  el.addEventListener(startEvent, handlers.start, false);
  el.addEventListener('mousewheel', handlers.wheel, false);
}

function unbindElement(el, handlers) {
  el.removeEventListener(startEvent, handlers.start, false);
  el.removeEventListener('mousewheel', handlers.wheel, false);
}

function bindWindow(handlers) {
  window.addEventListener(moveEvent, handlers.move, true);
  window.addEventListener(endEvent, handlers.end, true);
  window.addEventListener(cancelEvent, handlers.cancel, true);
}

function unbindWindow(handlers) {
  window.removeEventListener(moveEvent, handlers.move, true);
  window.removeEventListener(endEvent, handlers.end, true);
  window.removeEventListener(cancelEvent, handlers.cancel, true);
}

export default Ember.Component.extend({
  init() {
    this._clientWidth = undefined;
    this._clientHeight = undefined;
    this._contentSize = undefined;
    this._appliedContentSize = {};
    this._needsContentSizeUpdate = false;
    this._scrollLeft = 0;
    this._scrollTop = 0;
    this._appliedScrollLeft = undefined;
    this._appliedScrollTop = undefined;
    this._animationFrame = undefined;
    this._isTouching = false;
    this.scroller = undefined;
    this.scrollerEventHandlers = {
      start: handleStart.bind(this),
      move: handleMove.bind(this),
      end: handleEnd.bind(this),
      cancel: handleCancel.bind(this),
      wheel: handleWheel.bind(this)
    };
    this._super();
  },
  didReceiveAttrs() {
    this._contentSize = this.getAttr('content-size');
    this._scrollLeft = this.getAttr('scroll-left');
    this._scrollTop = this.getAttr('scroll-top');
  },
  didInsertElement() {
    this.contentElement = this.element.firstElementChild;
    this.setupScroller();
    this.applyStyle();
    this.applyContentSize();
    this.syncScrollFromAttr();
    this.startSizeCheck();
    this.bindScrollerEvents();
  },
  willRender() {
    this.willRenderContentSize();
  },
  didUpdate() {
    this.applyContentSize();
  },
  setupScroller: function(){
    this.scroller = new Scroller((left, top/*, zoom*/) => {
      Ember.run.join(this, this.onScrollChange, left|0, top|0);
    }, {
      scrollingX: false
    });
  },
  onScrollChange(scrollLeft, scrollTop) {
    if (this._appliedScrollTop !== scrollTop || this._appliedScrollLeft !== scrollLeft) {
      this._appliedScrollLeft = scrollLeft;
      this._appliedScrollTop = scrollTop;
      translate(this.contentElement, scrollLeft, -1 * scrollTop);
      if (this._scrollLeft !== scrollLeft || this._scrollTop !== scrollTop) {
        this.sendAction('scrollChange', { scrollLeft, scrollTop });
      }
    }
  },
  syncScrollFromAttr() {
    if (this._appliedScrollLeft !== this._scrollLeft || this._appliedScrollTop !== this._scrollTop) {
      this.scroller.scrollTo(this._scrollLeft, this._scrollTop);
    }
  },
  updateScrollerDimensions() {
    if (this._clientWidth && this._clientHeight) {
      this.scroller.setDimensions(this._clientWidth, this._clientHeight, this._contentSize.width, this._contentSize.height);
    }
  },
  didRender(){
    this.syncScrollFromAttr();
  },
  willDestroyElement() {
    this.contentElement = undefined;
    this.unbindScrollerEvents();
    this.cancelSizeCheck();
  },
  applyStyle() {
    // hack to force render buffer so outside doesn't repaint on scroll
    translate(this.element, 0, 0);

    this.element.style.overflow = 'hidden';
    this.element.style.position = 'absolute';
    this.element.style.left = 0;
    this.element.style.top = 0;
    this.element.style.bottom = 0;
    this.element.style.right = 0;
    this.element.style.boxSizing = 'border-box';

    this.contentElement.style.position = 'relative';
  },
  willRenderContentSize(){
    if (this._appliedContentSize &&
        (this._appliedContentSize.width !== this._contentSize.width ||
        this._appliedContentSize.height !== this._contentSize.height)
      ) {
      this._appliedContentSize = this._contentSize;
      this._needsContentSizeUpdate = true;
      this.updateScrollerDimensions();
    }
  },
  applyContentSize() {
    if (this._needsContentSizeUpdate) {
      this.contentElement.style.width = this._contentSize.width + 'px';
      this.contentElement.style.height = this._contentSize.height + 'px';
      this._needsContentSizeUpdate = false;
    }
  },
  startSizeCheck() {
    const component = this;
    function step() {
      component.sizeCheck();
      nextStep();
    }
    function nextStep() {
      component._animationFrame = requestAnimationFrame(step);
    }
    nextStep();
  },
  cancelSizeCheck() {
    if (this._animationFrame) {
      cancelAnimationFrame(this._animationFrame);
      this._animationFrame = undefined;
    }
  },
  sizeCheck() {
    let element = this.element;
    let clientWidth = element.offsetWidth;
    let clientHeight = element.offsetHeight;
    if (clientWidth !== this._clientWidth || clientHeight !== this._clientHeight) {
      this._clientWidth = clientWidth;
      this._clientHeight = clientHeight;
      Ember.run.join(() => {
        this.updateScrollerDimensions();
        this.sendClientSizeChange(clientWidth, clientHeight);
      });
    }
  },
  sendClientSizeChange(width, height) {
    this.sendAction('clientSizeChange', { width, height });
  },
  bindScrollerEvents: function() {
    bindElement(this.element, this.scrollerEventHandlers);
  },
  unbindScrollerEvents: function() {
    unbindElement(this.element, this.scrollerEventHandlers);
    unbindWindow(this.scrollerEventHandlers);
  },

  doTouchStart: function(touches, timeStamp) {
    this._isTouching = true;
    this.scroller.doTouchStart(touches, timeStamp);
    this.sendAction('touchingChange', this._isTouching);
  },
  doTouchMove: function(touches, timeStamp) {
    this.scroller.doTouchMove(touches, timeStamp);
  },
  doTouchEnd: function(timeStamp) {
    this._isTouching = false;
    this.scroller.doTouchEnd(timeStamp);
    this.sendAction('touchingChange', this._isTouching);
  },

  mouseWheel: function(e){
    var inverted, delta, candidatePosition;

    inverted = e.webkitDirectionInvertedFromDevice;
    delta = e.wheelDeltaY * (inverted ? 0.8 : -0.8);
    candidatePosition = this.scroller.__scrollTop + delta;

    if ((candidatePosition >= 0) && (candidatePosition <= this.scroller.__maxScrollTop)) {
      this.scroller.scrollBy(0, delta, true);
      e.stopPropagation();
    }

    return false;
  }
});
<commit_msg>hacky fix for an android problem with touchCancel<commit_after>/* global Scroller */
import Ember from 'ember';
import { translate } from 'ember-collection/utils/translate';

// Certain android devices are firing a touchCancel immediately after
// touchStart, which prevents scrolling entirely.
let needsTouchCancelHack = false;
const userAgent = window.navigator.userAgent;
if (userAgent && userAgent.indexOf && userAgent.indexOf('Android 4.4') !== -1) {
  needsTouchCancelHack = true;
}

var fieldRegex = /input|textarea|select/i,
  hasTouch = ('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch,
  handleStart, handleMove, handleEnd, handleCancel,
  startEvent, moveEvent, endEvent, cancelEvent;
if (hasTouch) {
  startEvent = 'touchstart';
  handleStart = function (e) {
    var touch = e.touches[0],
      target = touch && touch.target;
    // avoid e.preventDefault() on fields
    if (target && fieldRegex.test(target.tagName)) {
      return;
    }
    bindWindow(this.scrollerEventHandlers);
    this.doTouchStart(e.touches, e.timeStamp);
  };
  moveEvent = 'touchmove';
  handleMove = function (e) {
    if (needsTouchCancelHack) {
      e.preventDefault();
    }
    this.doTouchMove(e.touches, e.timeStamp);
  };
  endEvent = 'touchend';
  handleEnd = function (e) {
    unbindWindow(this.scrollerEventHandlers);
    this.doTouchEnd(e.timeStamp);
  };
  cancelEvent = 'touchcancel';
  handleCancel = function (e) {
    unbindWindow(this.scrollerEventHandlers);
    this.doTouchEnd(e.timeStamp);
  };
} else {
  startEvent = 'mousedown';
  handleStart = function (e) {
    if (e.which !== 1) {
      return;
    }
    var target = e.target;
    // avoid e.preventDefault() on fields
    if (target && fieldRegex.test(target.tagName)) {
      return;
    }
    bindWindow(this.scrollerEventHandlers);
    this.doTouchStart([e], e.timeStamp);
    e.preventDefault();
  };
  moveEvent = 'mousemove';
  handleMove = function (e) {
    this.doTouchMove([e], e.timeStamp);
  };
  endEvent = 'mouseup';
  handleEnd = function (e) {
    unbindWindow(this.scrollerEventHandlers);
    this.doTouchEnd(e.timeStamp);
  };
  cancelEvent = 'mouseout';
  handleCancel = function (e) {
    if (e.relatedTarget) {
      return;
    }
    unbindWindow(this.scrollerEventHandlers);
    this.doTouchEnd(e.timeStamp);
  };
}

function handleWheel(e) {
  this.mouseWheel(e);
  e.preventDefault();
}

function bindElement(el, handlers) {
  el.addEventListener(startEvent, handlers.start, false);
  el.addEventListener('mousewheel', handlers.wheel, false);
}

function unbindElement(el, handlers) {
  el.removeEventListener(startEvent, handlers.start, false);
  el.removeEventListener('mousewheel', handlers.wheel, false);
}

function bindWindow(handlers) {
  window.addEventListener(moveEvent, handlers.move, true);
  window.addEventListener(endEvent, handlers.end, true);
  window.addEventListener(cancelEvent, handlers.cancel, true);
}

function unbindWindow(handlers) {
  window.removeEventListener(moveEvent, handlers.move, true);
  window.removeEventListener(endEvent, handlers.end, true);
  window.removeEventListener(cancelEvent, handlers.cancel, true);
}

export default Ember.Component.extend({
  init() {
    this._clientWidth = undefined;
    this._clientHeight = undefined;
    this._contentSize = undefined;
    this._appliedContentSize = {};
    this._needsContentSizeUpdate = false;
    this._scrollLeft = 0;
    this._scrollTop = 0;
    this._appliedScrollLeft = undefined;
    this._appliedScrollTop = undefined;
    this._animationFrame = undefined;
    this._isTouching = false;
    this.scroller = undefined;
    this.scrollerEventHandlers = {
      start: handleStart.bind(this),
      move: handleMove.bind(this),
      end: handleEnd.bind(this),
      cancel: handleCancel.bind(this),
      wheel: handleWheel.bind(this)
    };
    this._super();
  },
  didReceiveAttrs() {
    this._contentSize = this.getAttr('content-size');
    this._scrollLeft = this.getAttr('scroll-left');
    this._scrollTop = this.getAttr('scroll-top');
  },
  didInsertElement() {
    this.contentElement = this.element.firstElementChild;
    this.setupScroller();
    this.applyStyle();
    this.applyContentSize();
    this.syncScrollFromAttr();
    this.startSizeCheck();
    this.bindScrollerEvents();
  },
  willRender() {
    this.willRenderContentSize();
  },
  didUpdate() {
    this.applyContentSize();
  },
  setupScroller: function(){
    this.scroller = new Scroller((left, top/*, zoom*/) => {
      Ember.run.join(this, this.onScrollChange, left|0, top|0);
    }, {
      scrollingX: false
    });
  },
  onScrollChange(scrollLeft, scrollTop) {
    if (this._appliedScrollTop !== scrollTop || this._appliedScrollLeft !== scrollLeft) {
      this._appliedScrollLeft = scrollLeft;
      this._appliedScrollTop = scrollTop;
      translate(this.contentElement, scrollLeft, -1 * scrollTop);
      if (this._scrollLeft !== scrollLeft || this._scrollTop !== scrollTop) {
        this.sendAction('scrollChange', { scrollLeft, scrollTop });
      }
    }
  },
  syncScrollFromAttr() {
    if (this._appliedScrollLeft !== this._scrollLeft || this._appliedScrollTop !== this._scrollTop) {
      this.scroller.scrollTo(this._scrollLeft, this._scrollTop);
    }
  },
  updateScrollerDimensions() {
    if (this._clientWidth && this._clientHeight) {
      this.scroller.setDimensions(this._clientWidth, this._clientHeight, this._contentSize.width, this._contentSize.height);
    }
  },
  didRender(){
    this.syncScrollFromAttr();
  },
  willDestroyElement() {
    this.contentElement = undefined;
    this.unbindScrollerEvents();
    this.cancelSizeCheck();
  },
  applyStyle() {
    // hack to force render buffer so outside doesn't repaint on scroll
    translate(this.element, 0, 0);

    this.element.style.overflow = 'hidden';
    this.element.style.position = 'absolute';
    this.element.style.left = 0;
    this.element.style.top = 0;
    this.element.style.bottom = 0;
    this.element.style.right = 0;
    this.element.style.boxSizing = 'border-box';

    this.contentElement.style.position = 'relative';
  },
  willRenderContentSize(){
    if (this._appliedContentSize &&
        (this._appliedContentSize.width !== this._contentSize.width ||
        this._appliedContentSize.height !== this._contentSize.height)
      ) {
      this._appliedContentSize = this._contentSize;
      this._needsContentSizeUpdate = true;
      this.updateScrollerDimensions();
    }
  },
  applyContentSize() {
    if (this._needsContentSizeUpdate) {
      this.contentElement.style.width = this._contentSize.width + 'px';
      this.contentElement.style.height = this._contentSize.height + 'px';
      this._needsContentSizeUpdate = false;
    }
  },
  startSizeCheck() {
    const component = this;
    function step() {
      component.sizeCheck();
      nextStep();
    }
    function nextStep() {
      component._animationFrame = requestAnimationFrame(step);
    }
    nextStep();
  },
  cancelSizeCheck() {
    if (this._animationFrame) {
      cancelAnimationFrame(this._animationFrame);
      this._animationFrame = undefined;
    }
  },
  sizeCheck() {
    let element = this.element;
    let clientWidth = element.offsetWidth;
    let clientHeight = element.offsetHeight;
    if (clientWidth !== this._clientWidth || clientHeight !== this._clientHeight) {
      this._clientWidth = clientWidth;
      this._clientHeight = clientHeight;
      Ember.run.join(() => {
        this.updateScrollerDimensions();
        this.sendClientSizeChange(clientWidth, clientHeight);
      });
    }
  },
  sendClientSizeChange(width, height) {
    this.sendAction('clientSizeChange', { width, height });
  },
  bindScrollerEvents: function() {
    bindElement(this.element, this.scrollerEventHandlers);
  },
  unbindScrollerEvents: function() {
    unbindElement(this.element, this.scrollerEventHandlers);
    unbindWindow(this.scrollerEventHandlers);
  },

  doTouchStart: function(touches, timeStamp) {
    this._isTouching = true;
    this.scroller.doTouchStart(touches, timeStamp);
    this.sendAction('touchingChange', this._isTouching);
  },
  doTouchMove: function(touches, timeStamp) {
    this.scroller.doTouchMove(touches, timeStamp);
  },
  doTouchEnd: function(timeStamp) {
    this._isTouching = false;
    this.scroller.doTouchEnd(timeStamp);
    this.sendAction('touchingChange', this._isTouching);
  },

  mouseWheel: function(e){
    var inverted, delta, candidatePosition;

    inverted = e.webkitDirectionInvertedFromDevice;
    delta = e.wheelDeltaY * (inverted ? 0.8 : -0.8);
    candidatePosition = this.scroller.__scrollTop + delta;

    if ((candidatePosition >= 0) && (candidatePosition <= this.scroller.__maxScrollTop)) {
      this.scroller.scrollBy(0, delta, true);
      e.stopPropagation();
    }

    return false;
  }
});
<|endoftext|>


<commit_before>use steamworks;

db.pike.aggregate([
    {
        $project:
            {
                "teamNumber": 1,
                "autoScore.total": 1,
                "teleScore.vaultPoints": 1,
                "teleScore.levitation": 1,
                "teleScore.cubes": 1,
                "teleScore.total": 1,
                "teleScore.foul": 1,
                "teleScore.parking": 1,
                "teleScore.playStyle": 1,
                "teleScore.climbSuccess": 1,
                "teleScore.climbAttempt": 1,
                "autoScore.placement": 1,
                "autoScore.placememt": 1

            }
    },

    {
        $group:
            {
                "_id": "$teamNumber",
                "teleFoul": {"$sum": "$teleScore.foul"},
                "teleVault": {"$sum": "$teleScore.vaultPoints"},
                "teleParking": {"$sum": "$teleScore.parking"},
                "autoPlace": {"$sum": "$autoScore.placement"},
                "teleLevi": {"$avg": "$teleScore.levitation"},
                "telePlay": {"$sum": "$teleScore.playStyle"},
                "teleTotal": {"$sum": "$teleScore.total"},
                "teleCubes": {"$sum": "$teleScore.cubes"},
                "teleAvgCubes": {"$avg": "teleScore.cubes"},
                "autoTotal": {"$sum": "$autoScore.total"},
                "attemptedClimbs": {"$sum": {"$cond": ["$teleScore.climbAttempt", 1, 0]}},
                "successfulClimbs": {"$sum": {"$cond": ["$teleScore.climbSuccess", 1, 0]}},
                "matches": {"$sum": 1}
            }
    },
    {
        $out: "temp"
    }
]);<commit_msg>changing out to pike<commit_after>use steamworks;

db.pike.aggregate([
    {
        $project:
            {
                "teamNumber": 1,
                "autoScore.total": 1,
                "teleScore.vaultPoints": 1,
                "teleScore.levitation": 1,
                "teleScore.cubes": 1,
                "teleScore.total": 1,
                "teleScore.foul": 1,
                "teleScore.parking": 1,
                "teleScore.playStyle": 1,
                "teleScore.climbSuccess": 1,
                "teleScore.climbAttempt": 1,
                "autoScore.placement": 1,
                "autoScore.placememt": 1

            }
    },

    {
        $group:
            {
                "_id": "$teamNumber",
                "teleFoul": {"$sum": "$teleScore.foul"},
                "teleVault": {"$sum": "$teleScore.vaultPoints"},
                "teleParking": {"$sum": "$teleScore.parking"},
                "autoPlace": {"$sum": "$autoScore.placement"},
                "teleLevi": {"$avg": "$teleScore.levitation"},
                "telePlay": {"$sum": "$teleScore.playStyle"},
                "teleTotal": {"$sum": "$teleScore.total"},
                "teleCubes": {"$sum": "$teleScore.cubes"},
                "teleAvgCubes": {"$avg": "teleScore.cubes"},
                "autoTotal": {"$sum": "$autoScore.total"},
                "attemptedClimbs": {"$sum": {"$cond": ["$teleScore.climbAttempt", 1, 0]}},
                "successfulClimbs": {"$sum": {"$cond": ["$teleScore.climbSuccess", 1, 0]}},
                "matches": {"$sum": 1}
            }
    },
    {
        $out: "pike"
    }
]);<|endoftext|>


<commit_before>/**
 * ResetButton component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { Fragment, useState, useEffect, useCallback, createInterpolateElement } from '@wordpress/element';
import { ESCAPE } from '@wordpress/keycodes';
import { useDebounce } from '../hooks/useDebounce';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { clearWebStorage } from '../util';
import Dialog from './Dialog';
import Modal from './Modal';
import Link from './Link';
import { CORE_SITE } from '../googlesitekit/datastore/site/constants';
import { CORE_LOCATION } from '../googlesitekit/datastore/location/constants';
const { useSelect, useDispatch } = Data;

function ResetButton( { children } ) {
	const postResetURL = useSelect( ( select ) => select( CORE_SITE ).getAdminURL( 'googlesitekit-splash', { notification: 'reset_success' } ) );
	const isDoingReset = useSelect( ( select ) => select( CORE_SITE ).isDoingReset() );
	const isNavigatingToPostResetURL = useSelect( ( select ) => select( CORE_LOCATION ).isNavigatingTo( postResetURL || '' ) );
	const [ isInProgress, setIsInProgress ] = useState( false );
	const [ dialogActive, setDialogActive ] = useState( false );

	const debouncedInProgress = useDebounce( setIsInProgress, 3000 );

	const mediatedSetInProgress = ( bool ) => bool ? setIsInProgress( true ) : debouncedInProgress( false );

	useEffect( () => {
		mediatedSetInProgress( isDoingReset || isNavigatingToPostResetURL );
	}, [ isDoingReset, isNavigatingToPostResetURL ] );

	useEffect( () => {
		const handleCloseModal = ( event ) => {
			if ( ESCAPE === event.keyCode ) {
				// Only close the modal if the "Escape" key is pressed.
				setDialogActive( false );
			}
		};

		if ( dialogActive ) {
			// When the dialogActive changes and it is set to true(has opened), add the event listener.
			global.addEventListener( 'keyup', handleCloseModal, false );
		}
		// Remove the event listener when the dialog is removed; there's no need
		// to have it attached when it won't be used.
		return () => {
			if ( dialogActive ) {
				// When the dialogActive is true(is open) and its value changes, remove the event listener.
				global.removeEventListener( 'keyup', handleCloseModal );
			}
		};
	}, [ dialogActive ] );

	const { reset } = useDispatch( CORE_SITE );
	const { navigateTo } = useDispatch( CORE_LOCATION );

	const handleUnlinkConfirm = useCallback( async () => {
		await reset();
		clearWebStorage();
		navigateTo( postResetURL );
	}, [ reset, postResetURL ] );

	const toggleDialogActive = useCallback( () => {
		setDialogActive( ! dialogActive );
	}, [ dialogActive ] );

	const openDialog = useCallback( () => {
		setDialogActive( true );
	}, [] );

	return (
		<Fragment>
			<Link
				className="googlesitekit-reset-button"
				onClick={ openDialog }
				inherit
			>
				{ children || __( 'Reset Site Kit', 'google-site-kit' ) }
			</Link>
			<Modal>
				<Dialog
					dialogActive={ dialogActive }
					handleConfirm={ handleUnlinkConfirm }
					handleDialog={ toggleDialogActive }
					title={ __( 'Reset Site Kit', 'google-site-kit' ) }
					subtitle={ createInterpolateElement(
						__( `Resetting will disconnect all users and remove all Site Kit settings and data within WordPress. <br />You and any other users who wish to use Site Kit will need to reconnect to restore access.`, 'google-site-kit' ),
						{
							br:
,
						} ) }
					confirmButton={ __( 'Reset', 'google-site-kit' ) }
					danger
					inProgress={ isInProgress }
				/>
			</Modal>
		</Fragment>
	);
}

export default ResetButton;
<commit_msg>Improve naming of inProgress-related variables.<commit_after>/**
 * ResetButton component.
 *
 * Site Kit by Google, Copyright 2021 Google LLC
 *
 * 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
 *
 *     https://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.
 */

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { Fragment, useState, useEffect, useCallback, createInterpolateElement } from '@wordpress/element';
import { ESCAPE } from '@wordpress/keycodes';
import { useDebounce } from '../hooks/useDebounce';

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { clearWebStorage } from '../util';
import Dialog from './Dialog';
import Modal from './Modal';
import Link from './Link';
import { CORE_SITE } from '../googlesitekit/datastore/site/constants';
import { CORE_LOCATION } from '../googlesitekit/datastore/location/constants';
const { useSelect, useDispatch } = Data;

function ResetButton( { children } ) {
	const postResetURL = useSelect( ( select ) => select( CORE_SITE ).getAdminURL( 'googlesitekit-splash', { notification: 'reset_success' } ) );
	const isDoingReset = useSelect( ( select ) => select( CORE_SITE ).isDoingReset() );
	const isNavigatingToPostResetURL = useSelect( ( select ) => select( CORE_LOCATION ).isNavigatingTo( postResetURL || '' ) );
	const [ inProgress, setInProgress ] = useState( false );
	const [ dialogActive, setDialogActive ] = useState( false );

	/*
	 * Using debounce here because the spinner has to render across two separate calls.
	 * Rather than risk it flickering on and off in between the reset call completing and
	 * the navigate call starting, we will just set a debounce to keep the spinner for 3 seconds.
	 */
	const debouncedSetInProgress = useDebounce( setInProgress, 3000 );
	const mediatedSetInProgress = ( bool ) => bool ? setInProgress( true ) : debouncedSetInProgress( false );

	useEffect( () => {
		mediatedSetInProgress( isDoingReset || isNavigatingToPostResetURL );
	}, [ isDoingReset, isNavigatingToPostResetURL ] );

	useEffect( () => {
		const handleCloseModal = ( event ) => {
			if ( ESCAPE === event.keyCode ) {
				// Only close the modal if the "Escape" key is pressed.
				setDialogActive( false );
			}
		};

		if ( dialogActive ) {
			// When the dialogActive changes and it is set to true(has opened), add the event listener.
			global.addEventListener( 'keyup', handleCloseModal, false );
		}
		// Remove the event listener when the dialog is removed; there's no need
		// to have it attached when it won't be used.
		return () => {
			if ( dialogActive ) {
				// When the dialogActive is true(is open) and its value changes, remove the event listener.
				global.removeEventListener( 'keyup', handleCloseModal );
			}
		};
	}, [ dialogActive ] );

	const { reset } = useDispatch( CORE_SITE );
	const { navigateTo } = useDispatch( CORE_LOCATION );

	const handleUnlinkConfirm = useCallback( async () => {
		await reset();
		clearWebStorage();
		navigateTo( postResetURL );
	}, [ reset, postResetURL ] );

	const toggleDialogActive = useCallback( () => {
		setDialogActive( ! dialogActive );
	}, [ dialogActive ] );

	const openDialog = useCallback( () => {
		setDialogActive( true );
	}, [] );

	return (
		<Fragment>
			<Link
				className="googlesitekit-reset-button"
				onClick={ openDialog }
				inherit
			>
				{ children || __( 'Reset Site Kit', 'google-site-kit' ) }
			</Link>
			<Modal>
				<Dialog
					dialogActive={ dialogActive }
					handleConfirm={ handleUnlinkConfirm }
					handleDialog={ toggleDialogActive }
					title={ __( 'Reset Site Kit', 'google-site-kit' ) }
					subtitle={ createInterpolateElement(
						__( `Resetting will disconnect all users and remove all Site Kit settings and data within WordPress. <br />You and any other users who wish to use Site Kit will need to reconnect to restore access.`, 'google-site-kit' ),
						{
							br:
,
						} ) }
					confirmButton={ __( 'Reset', 'google-site-kit' ) }
					danger
					inProgress={ inProgress }
				/>
			</Modal>
		</Fragment>
	);
}

export default ResetButton;
<|endoftext|>


<commit_before>var React = require('react-native');
var posts = require('../Utils/posts');
var Swiper = require('react-native-swiper')

var {
  StyleSheet,
  ListView,
  Text,
  TextInput,
  View,
  TouchableHighlight,
  Component,
  Image,
  DeviceEventEmitter
} = React;

var renderPagination = function (index, total, context) {
  return (
    <View style={{
      position: 'absolute',
      bottom: -25,
      right: 10,
    }}>
      <Text><Text style={{
        color: '#007aff',
        fontSize: 20,
      }}>{index + 1}</Text>/{total}</Text>
    </View>
  )
}

class GroupMembers extends Component {
  constructor(props) {
    super(props);
    var ds = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    this.state = {
      username: '',
      image_url: '',
      btnLocation: 0,
      dataSource: ds.cloneWithRows(this.props.members)
    };
  }

  componentWillMount () {
    DeviceEventEmitter.addListener('keyboardWillShow', this.keyboardWillShow.bind(this))
    DeviceEventEmitter.addListener('keyboardWillHide', this.keyboardWillHide.bind(this))
  }

  keyboardWillShow (e) {
    this.setState({btnLocation: e.endCoordinates.height})
  }

  keyboardWillHide (e) {
    this.setState({btnLocation: 0})
  }

  handleChange(e) {
    this.setState({
      memberToAdd: e.nativeEvent.text
    });
  }

  handleSubmit(){
    var memberToAdd = this.state.memberToAdd;
    if (memberToAdd !== '') {
      this.setState({
          memberToAdd: ''
        });
        posts.addMemberToGroup(memberToAdd, this.props.group.id)
          .then((responseJSON) => {
            this.props.members.push(responseJSON);
            this.setState({
              dataSource: this.state.dataSource.cloneWithRows(this.props.members)
            });
          })
          .catch((error) => {
            console.log('Request failed', error);
            this.setState({error});
          });
        }
  }

  addNewMemberForm() {
    return (
      <View style={styles.addNewMemberForm}>
        <TextInput
          style={styles.inputComment}
          value={this.state.memberToAdd}
          autoCapitalize='none' autoCorrect={false}
          onChange={this.handleChange.bind(this)}
          placeholder="Enter username" />
        <TouchableHighlight
          style={styles.button}
          onPress={this.handleSubmit.bind(this)}
          underlayColor="#88d4f5">
            <Text style={styles.buttonText}>Add to Group</Text>
        </TouchableHighlight>
      </View>
    )
  }

  renderRow(member) {
    var profilePic = member.image_url ? <Image style={styles.image} source={{uri:member.image_url}} /> : <Text style={styles.imageSquare}> No Picture yet </Text>;
    return (
      <View >
        <View style={styles.rowContainer}>
          {profilePic}
          <Text style={styles.name}> {member.username} </Text>
        </View>
      </View>
    );
  }

 render(){
    return (
      <View style={styles.container}>
        <Swiper style={styles.wrapper} height={480} renderPagination={renderPagination} paginationStyle={{bottom: -23, left: null, right: 10}} loop={false}>
            <ListView
              dataSource={this.state.dataSource}
              renderRow={this.renderRow.bind(this)} />
          </Swiper>
        <View style={{bottom: this.state.btnLocation}}>{this.addNewMemberForm()}</View>
      </View>
      )
  }

};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 60,
    backgroundColor: '#4800a8',
  },
  rowContainer: {
    flexDirection: 'row',
    padding: 10
  },
  image: {
    width: 150,
    height: 150,
    borderRadius: 75,
  },
  imageSquare: {
    width: 150,
    height: 150
  },
  name: {
    flex: 3,
    paddingLeft: 10,
    alignSelf: 'center',
    color: 'white',
    fontSize: 35
  },
  inputComment: {
    color: "black",
    justifyContent: 'center',
    textAlign: 'center',
    height: 48,
    padding: 10,
    fontSize: 25,
    backgroundColor: '#fff',
  },
  button: {
    height: 48,
    backgroundColor: '#48BBEC',
    alignItems: 'center',
    justifyContent: 'center'
  },
  buttonText: {
    color: 'white',
    fontSize: 22
  },
    wrapper: {
  },
  slide: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
  text: {
    color: '#fff',
    fontSize: 30,
    fontWeight: 'bold',
  },
  image: {
    flex: 1,
  }

});

module.exports = GroupMembers;

<commit_msg>revert members page to scrollview<commit_after>var React = require('react-native');
var posts = require('../Utils/posts');
var Swiper = require('react-native-swiper')

var {
  StyleSheet,
  ScrollView,
  Text,
  TextInput,
  View,
  TouchableHighlight,
  Component,
  Image,
  DeviceEventEmitter
} = React;

var renderPagination = function (index, total, context) {
  return (
    <View style={{
      position: 'absolute',
      bottom: -25,
      right: 10,
    }}>
      <Text><Text style={{
        color: '#007aff',
        fontSize: 20,
      }}>{index + 1}</Text>/{total}</Text>
    </View>
  )
}

class GroupMembers extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      image_url: ''
    };
  }

  componentWillMount () {
    DeviceEventEmitter.addListener('keyboardWillShow', this.keyboardWillShow.bind(this))
    DeviceEventEmitter.addListener('keyboardWillHide', this.keyboardWillHide.bind(this))
  }

  keyboardWillShow (e) {
    this.setState({btnLocation: e.endCoordinates.height})
  }

  keyboardWillHide (e) {
    this.setState({btnLocation: 0})
  }

  handleChange(e) {
    this.setState({
      memberToAdd: e.nativeEvent.text
    });
  }

  handleSubmit(){
    var memberToAdd = this.state.memberToAdd;
    this.setState({
      memberToAdd: ''
    });
    posts.addMemberToGroup(memberToAdd, this.props.group.id)
      .then((data) => {
        this.props.members.push(data);
        this.setState({});
      })
      .catch((error) => {
        console.log('Request failed', error);
        this.setState({error});
      });
  }

  footer() {
    return (
      <View style={styles.footer}>
        <TextInput
          style={styles.inputComment}
          value={this.state.memberToAdd}
          autoCapitalize='none' autoCorrect={false}
          onChange={this.handleChange.bind(this)}
          placeholder="Enter username" />
        <TouchableHighlight
          style={styles.button}
          onPress={this.handleSubmit.bind(this)}
          underlayColor="#88d4f5">
            <Text style={styles.buttonText}>Add to Group</Text>
        </TouchableHighlight>
      </View>
    )
  }

  render(){
    var members = this.props.members;
    var list = members.map((member, index) => {
    var profilePic = members[index].image_url ? <Image style={styles.image} source={{uri:members[index].image_url}} /> : <Text style={styles.imageSquare}> No Picture yet </Text>;

      return (
        <View key={index} style={styles.slide} title={<Text style={styles.text}>{members[index].username} </Text>}>
            {profilePic}
        </View>
      )
    });
    return (
      <View style={styles.container}>
        <Swiper style={styles.wrapper} height={480} renderPagination={renderPagination} paginationStyle={{
            bottom: -23, left: null, right: 10}} loop={false}>
        {list}</Swiper>
        <View style={{bottom: this.state.btnLocation}}>{this.footer()}</View>
      </View>
    )
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 60,
    backgroundColor: '#4800a8',
  },
  rowContainer: {
    flexDirection: 'row',
    padding: 10
  },
  image: {
    width: 150,
    height: 150,
    borderRadius: 75,
  },
  imageSquare: {
    width: 150,
    height: 150
  },
  name: {
    flex: 3,
    paddingLeft: 10,
    alignSelf: 'center',
    color: 'white',
    fontSize: 35
  },
  inputComment: {
    color: "black",
    justifyContent: 'center',
    textAlign: 'center',
    height: 48,
    padding: 10,
    fontSize: 25,
    backgroundColor: '#fff',
    marginTop: 2
  },
  button: {
    height: 48,
    backgroundColor: '#4800a8',
    alignItems: 'center',
    justifyContent: 'center'
  },
  buttonText: {
    color: 'white',
    fontSize: 30
  },
    wrapper: {
  },
  slide: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
  text: {
    color: '#fff',
    fontSize: 30,
    fontWeight: 'bold',
  },
  image: {
    flex: 1,
  }

});

module.exports = GroupMembers;
<|endoftext|>