<commit_before>import Shader from '../../low_level/shaders/Shader';
import DecalShader from './DecalShader';
import Vector4 from '../../low_level/math/Vector4';

export class PBRPrincipledShaderSource {

  FSDefine_PBRPrincipledShaderSource(in_, f, lights) {

    var sampler2D = this._sampler2DShadow_func();
    var shaderText = '';
    shaderText += 'uniform vec4 Kd;\n';
    shaderText += 'uniform vec4 ambient;\n'; // Ka * amount of ambient lights

    let lightNumExceptAmbient = lights.filter((light)=>{return !light.isTypeAmbient();}).length;
    if (lightNumExceptAmbient > 0) {
      shaderText += `uniform highp ${sampler2D} uDepthTexture[${lightNumExceptAmbient}];\n`;
      shaderText += `uniform int isShadowCasting[${lightNumExceptAmbient}];\n`;
    }

    return shaderText;
  }

  VSMethodDefine_PBRPrincipledShaderSource(f, lights, material, extraData) {
    let shaderText = '';

    shaderText += `
      const float M_PI = 3.141592653589793;
    `;

    shaderText += `
    float angular_n_h(float NH) {
      return acos(NH);
    }
    `;

    shaderText += `
    float sqr(float x) {
      return x*x;
    }
    `;

    shaderText += `
    float d_phong(float NH, float c1) {
      return pow(
        cos(acos(NH))
        , c1
      );
    }
    `;

    shaderText += `
    // GGX NDF
    float d_ggx(float NH, float alphaRoughness) {
      float roughnessSqr = alphaRoughness * alphaRoughness;
      float f = (roughnessSqr - 1) * NH * NH + 1.0;
      return roughnessSq / (M_PI * f * f);
    }
    `;

    shaderText += `
    float d_torrance_reiz(float NH, float c3) {
      float CosSquared = NH*NH;
      float TanSquared = (1.0 - CosSquared)/CosSquared;
      //return (1.0/PI) * sqr(c3/(CosSquared * (c3*c3 + TanSquared)));  // gamma = 2, aka GGX
      return (1.0/sqrt(PI)) * (sqr(c3)/(CosSquared * (c3*c3 + TanSquared))); // gamma = 1, D_Berry
    }
    `;

    shaderText += `
    float d_beckmann(float NH, float m) {
      float co = 1.0 / (4.0 * m * m * NH * NH * NH * NH);
      float expx = exp((NH * NH - 1.0) / (m * m * NH * NH));
      return co * expx;
    }
    `;

    shaderText += `
    // the same as glTF WebGL sample
    // https://github.com/KhronosGroup/glTF-WebGL-PBR/blob/88eda8c5358efe03128b72b6c5f5f6e5b6d023e1/shaders/pbr-frag.glsl#L188
    // That is, Unreal Engine based approach, but modified to use alphaRoughness (squared artist's roughness parameter),
    // and based on 'Separable Masking and Shadowing' approximation (propesed by Christophe Schlick)
    // https://www.cs.virginia.edu/~jdl/bib/appearance/analytic%20models/schlick94b.pdf
    float g_shielding(float NH, float NV, float NL, float VH, float alphaRoughness) {
      float r = alphaRoughness;

      // Local Shadowing using Smith Masking Function
      float localShadowing = 2.0 * NL / (NL + sqrt(r * r + (1.0 - r * r) * (NL * NL)));

      // Local Masking using Smith Masking Function
      float localMasking = 2.0 * NV / (NV + sqrt(r * r + (1.0 - r * r) * (NV * NV)));

      return localShadowing * localMasking;
    }
    `;

    shaderText += `
    // The Schlick Approximation to Fresnel
    float fresnel(float f0, float LH) {
      return f0 + (1.0 - f0) * pow(1.0 - LH, 5);
    }
    `;

    shaderText += `
    float cook_torrance_specular_brdf(float n, float NH, float NV, float NL, float VH, float power) {
      float D = d_torrance_reiz(NH, power);
      float G = g_shielding(NH, NV, NL, VH);
      float F = fresnel(n, VH);
      return D*G*F/(4*NL*NV);
    }
    `;

    return shaderText;
  }

  FSShade_PBRPrincipledShaderSource(f, gl, lights) {
    var shaderText = '';

    shaderText += '  vec4 surfaceColor = rt0;\n';
    shaderText += '  rt0 = vec4(0.0, 0.0, 0.0, 0.0);\n';

    for (let i=0; i<lights.length; i++) {
      let light = lights[i];
      let isShadowEnabledAsTexture = (light.camera && light.camera.texture) ? true:false;
      shaderText += `  {\n`;
      shaderText +=      Shader._generateLightStr(i);
      shaderText +=      Shader._generateShadowingStr(gl, i, isShadowEnabledAsTexture);
      shaderText += `    float diffuse = max(dot(lightDirection, normal), 0.0);\n`;
      shaderText += `    rt0 += spotEffect * vec4(visibility, visibility, visibility, 1.0) * Kd * lightDiffuse[${i}] * vec4(diffuse, diffuse, diffuse, 1.0) * surfaceColor;\n`;
      shaderText += `  }\n`;
    }
    shaderText += '  rt0.xyz += ambient.xyz;\n';

    //shaderText += '  rt0.a = 1.0;\n';
    // shaderText += '  rt0 = surfaceColor;\n';
//    shaderText += '  rt0 = vec4(v_shadowCoord[0].xy, 0.0, 1.0);\n';

    return shaderText;
  }

  prepare_PBRPrincipledShaderSource(gl, shaderProgram, expression, vertexAttribs, existCamera_f, lights, material, extraData) {

    var vertexAttribsAsResult = [];

    material.setUniform(shaderProgram, 'uniform_Kd', this._glContext.getUniformLocation(shaderProgram, 'Kd'));
    material.setUniform(shaderProgram, 'uniform_ambient', this._glContext.getUniformLocation(shaderProgram, 'ambient'));

    return vertexAttribsAsResult;
  }
}

export default class PBRPrincipledShader extends DecalShader {
  constructor(glBoostContext, basicShader) {

    super(glBoostContext, basicShader);
    LambertShader.mixin(LambertShaderSource);
  }

  setUniforms(gl, glslProgram, scene, material, camera, mesh, lights) {
    super.setUniforms(gl, glslProgram, scene, material, camera, mesh, lights);

  }

}

GLBoost['PBRPrincipledShader'] = PBRPrincipledShader;
<commit_msg>Fix the comment for accuracy<commit_after>import Shader from '../../low_level/shaders/Shader';
import DecalShader from './DecalShader';
import Vector4 from '../../low_level/math/Vector4';

export class PBRPrincipledShaderSource {

  FSDefine_PBRPrincipledShaderSource(in_, f, lights) {

    var sampler2D = this._sampler2DShadow_func();
    var shaderText = '';
    shaderText += 'uniform vec4 Kd;\n';
    shaderText += 'uniform vec4 ambient;\n'; // Ka * amount of ambient lights

    let lightNumExceptAmbient = lights.filter((light)=>{return !light.isTypeAmbient();}).length;
    if (lightNumExceptAmbient > 0) {
      shaderText += `uniform highp ${sampler2D} uDepthTexture[${lightNumExceptAmbient}];\n`;
      shaderText += `uniform int isShadowCasting[${lightNumExceptAmbient}];\n`;
    }

    return shaderText;
  }

  VSMethodDefine_PBRPrincipledShaderSource(f, lights, material, extraData) {
    let shaderText = '';

    shaderText += `
      const float M_PI = 3.141592653589793;
    `;

    shaderText += `
    float angular_n_h(float NH) {
      return acos(NH);
    }
    `;

    shaderText += `
    float sqr(float x) {
      return x*x;
    }
    `;

    shaderText += `
    float d_phong(float NH, float c1) {
      return pow(
        cos(acos(NH))
        , c1
      );
    }
    `;

    shaderText += `
    // GGX NDF
    float d_ggx(float NH, float alphaRoughness) {
      float roughnessSqr = alphaRoughness * alphaRoughness;
      float f = (roughnessSqr - 1) * NH * NH + 1.0;
      return roughnessSq / (M_PI * f * f);
    }
    `;

    shaderText += `
    float d_torrance_reiz(float NH, float c3) {
      float CosSquared = NH*NH;
      float TanSquared = (1.0 - CosSquared)/CosSquared;
      //return (1.0/PI) * sqr(c3/(CosSquared * (c3*c3 + TanSquared)));  // gamma = 2, aka GGX
      return (1.0/sqrt(PI)) * (sqr(c3)/(CosSquared * (c3*c3 + TanSquared))); // gamma = 1, D_Berry
    }
    `;

    shaderText += `
    float d_beckmann(float NH, float m) {
      float co = 1.0 / (4.0 * m * m * NH * NH * NH * NH);
      float expx = exp((NH * NH - 1.0) / (m * m * NH * NH));
      return co * expx;
    }
    `;

    shaderText += `
    // the same as glTF WebGL sample
    // https://github.com/KhronosGroup/glTF-WebGL-PBR/blob/88eda8c5358efe03128b72b6c5f5f6e5b6d023e1/shaders/pbr-frag.glsl#L188
    // That is, Unreal Engine based approach, but modified to use alphaRoughness (squared artist's roughness parameter),
    // and based on 'Separable Masking and Shadowing' approximation (propesed by Christophe Schlick)
    // https://www.cs.virginia.edu/~jdl/bib/appearance/analytic%20models/schlick94b.pdf
    float g_shielding(float NH, float NV, float NL, float VH, float alphaRoughness) {
      float r = alphaRoughness;

      // Local Shadowing using Smith Masking Function (Schlick's approximation version)
      float localShadowing = 2.0 * NL / (NL + sqrt(r * r + (1.0 - r * r) * (NL * NL)));

      // Local Masking using Smith Masking Function (Schlick's approximation version)
      float localMasking = 2.0 * NV / (NV + sqrt(r * r + (1.0 - r * r) * (NV * NV)));

      return localShadowing * localMasking;
    }
    `;

    shaderText += `
    // The Schlick Approximation to Fresnel
    float fresnel(float f0, float LH) {
      return f0 + (1.0 - f0) * pow(1.0 - LH, 5);
    }
    `;

    shaderText += `
    float cook_torrance_specular_brdf(float n, float NH, float NV, float NL, float VH, float power) {
      float D = d_torrance_reiz(NH, power);
      float G = g_shielding(NH, NV, NL, VH);
      float F = fresnel(n, VH);
      return D*G*F/(4*NL*NV);
    }
    `;

    return shaderText;
  }

  FSShade_PBRPrincipledShaderSource(f, gl, lights) {
    var shaderText = '';

    shaderText += '  vec4 surfaceColor = rt0;\n';
    shaderText += '  rt0 = vec4(0.0, 0.0, 0.0, 0.0);\n';

    for (let i=0; i<lights.length; i++) {
      let light = lights[i];
      let isShadowEnabledAsTexture = (light.camera && light.camera.texture) ? true:false;
      shaderText += `  {\n`;
      shaderText +=      Shader._generateLightStr(i);
      shaderText +=      Shader._generateShadowingStr(gl, i, isShadowEnabledAsTexture);
      shaderText += `    float diffuse = max(dot(lightDirection, normal), 0.0);\n`;
      shaderText += `    rt0 += spotEffect * vec4(visibility, visibility, visibility, 1.0) * Kd * lightDiffuse[${i}] * vec4(diffuse, diffuse, diffuse, 1.0) * surfaceColor;\n`;
      shaderText += `  }\n`;
    }
    shaderText += '  rt0.xyz += ambient.xyz;\n';

    //shaderText += '  rt0.a = 1.0;\n';
    // shaderText += '  rt0 = surfaceColor;\n';
//    shaderText += '  rt0 = vec4(v_shadowCoord[0].xy, 0.0, 1.0);\n';

    return shaderText;
  }

  prepare_PBRPrincipledShaderSource(gl, shaderProgram, expression, vertexAttribs, existCamera_f, lights, material, extraData) {

    var vertexAttribsAsResult = [];

    material.setUniform(shaderProgram, 'uniform_Kd', this._glContext.getUniformLocation(shaderProgram, 'Kd'));
    material.setUniform(shaderProgram, 'uniform_ambient', this._glContext.getUniformLocation(shaderProgram, 'ambient'));

    return vertexAttribsAsResult;
  }
}

export default class PBRPrincipledShader extends DecalShader {
  constructor(glBoostContext, basicShader) {

    super(glBoostContext, basicShader);
    LambertShader.mixin(LambertShaderSource);
  }

  setUniforms(gl, glslProgram, scene, material, camera, mesh, lights) {
    super.setUniforms(gl, glslProgram, scene, material, camera, mesh, lights);

  }

}

GLBoost['PBRPrincipledShader'] = PBRPrincipledShader;
<|endoftext|>


<commit_before>define('app/controllers/images', ['app/models/image'],
    //
    //  Images Controller
    //
    //  @returns Class
    //
    function (Image) {

        'use strict';

        var OS_MAP = [
            [
                ['rhel', 'redhat', 'red hat'], 'redhat'
            ],
            [
                ['ubuntu'], 'ubuntu'
            ],
            [
                ['ibm'], 'ibm'
            ],
            [
                ['canonical'], 'canonical'
            ],
            [
                ['sles', 'suse'], 'suse'
            ],
            [
                ['oracle'], 'oracle'
            ],
            [
                ['karmic'], 'karmic'
            ],
            [
                ['opensolaris'], 'opensolaris'
            ],
            [
                ['gentoo'], 'gentoo'
            ],
            [
                ['opensuse'], 'opensuse'
            ],
            [
                ['fedora'], 'fedora'
            ],
            [
                ['centos'], 'centos'
            ],
            [
                ['fedora'], 'fedora'
            ],
            [
                ['debian'], 'debian'
            ],
            [
                ['amazon'], 'amazon'
            ]
        ]

        return Ember.ArrayController.extend(Ember.Evented, {

            //
            //
            //  Properties
            //
            //

            content: null,
            loading: null,
            backend: null,

            //
            //
            //  Computed Properties
            //
            //

            hasStarred: function () {
                return !!this.content.findBy('star', true);
            }.property('content.@each.star'),

            //
            //
            //  Initialization
            //
            //

            init: function () {
                this._super();
                this.set('content', []);
                this.set('loading', true);
            },

            //
            //
            //  Methods
            //
            //

            load: function (images) {
                this._updateContent(images);
                this.set('loading', false);
            },

            searchImages: function (filter, callback) {
                var that = this;
                Mist.ajax.POST('/backends/' + this.backend.id + '/images', {
                    'search_term': filter
                }).success(function (images) {

                }).error(function () {
                    Mist.notificationController.notify(
                        'Failed to search images on ' + that.backend.title);
                }).complete(function (success, images) {
                    var imagesToReturn = [];
                    if (success) {
                        images.forEach(function (image) {
                            image.backend = that.backend;
                            imagesToReturn.push(Image.create(image));
                        });
                    }
                    if (callback) callback(success, imagesToReturn);
                });
            },

            toggleImageStar: function (image, callback) {
                var that = this;
                Mist.ajax.POST('/backends/' + this.backend.id + '/images/' + image.id, {
                }).success(function (star) {
                    if (!that.imageExists(image.id))
                        that._addImage(image);
                    that._toggleImageStar(image.id, star);
                }).error(function () {
                    Mist.notificationController.notify('Failed to (un)star image');
                }).complete(function (success, star) {
                    if (callback) callback(success, star);
                });
            },

            getImage: function (imageId) {
                return this.content.findBy('id', imageId);
            },

            getImageOS: function (imageId) {

                var os = 'generic';
                var image = this.getImage(imageId);
                var imageCred;

                if(!!image)
                    imageCred = image.name;
                else
                    imageCred = imageId;

                OS_MAP.some(function (pair) {
                    return pair[0].some(function (key) {
                        if (imageCred.toLowerCase().indexOf(key) > -1)
                            return os = pair[1];
                    });
                });

                return os;
            },

            imageExists: function (imageId) {
                return !!this.getImage(imageId);
            },

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

            _updateContent: function (images) {
                Ember.run(this, function () {

                    // Remove deleted images
                    this.content.forEach(function (image) {
                        if (!images.findBy('id', image.id))
                            this.content.removeObject(image);
                    }, this);

                    images.forEach(function (image) {

                        var oldImage = this.getImage(image.id);

                        if (oldImage)
                            // Update existing images
                            forIn(image, function (value, property) {
                                oldImage.set(property, value);
                            });
                        else
                            // Add new images
                            this._addImage(image);
                    }, this);

                    this.trigger('onImageListChange');
                });
            },

            _addImage: function (image) {
                Ember.run(this, function () {
                    image.backend = this.backend;
                    this.content.addObject(Image.create(image));
                    this.trigger('onImageAdd');
                });
            },

            _toggleImageStar: function (imageId, star) {
                Ember.run(this, function () {
                    this.getImage(imageId).set('star', star);
                    this.trigger('onImageStarToggle');
                });
            },
        });
    }
);
<commit_msg>Change imageCred to imageAttribute<commit_after>define('app/controllers/images', ['app/models/image'],
    //
    //  Images Controller
    //
    //  @returns Class
    //
    function (Image) {

        'use strict';

        var OS_MAP = [
            [
                ['rhel', 'redhat', 'red hat'], 'redhat'
            ],
            [
                ['ubuntu'], 'ubuntu'
            ],
            [
                ['ibm'], 'ibm'
            ],
            [
                ['canonical'], 'canonical'
            ],
            [
                ['sles', 'suse'], 'suse'
            ],
            [
                ['oracle'], 'oracle'
            ],
            [
                ['karmic'], 'karmic'
            ],
            [
                ['opensolaris'], 'opensolaris'
            ],
            [
                ['gentoo'], 'gentoo'
            ],
            [
                ['opensuse'], 'opensuse'
            ],
            [
                ['fedora'], 'fedora'
            ],
            [
                ['centos'], 'centos'
            ],
            [
                ['fedora'], 'fedora'
            ],
            [
                ['debian'], 'debian'
            ],
            [
                ['amazon'], 'amazon'
            ]
        ]

        return Ember.ArrayController.extend(Ember.Evented, {

            //
            //
            //  Properties
            //
            //

            content: null,
            loading: null,
            backend: null,

            //
            //
            //  Computed Properties
            //
            //

            hasStarred: function () {
                return !!this.content.findBy('star', true);
            }.property('content.@each.star'),

            //
            //
            //  Initialization
            //
            //

            init: function () {
                this._super();
                this.set('content', []);
                this.set('loading', true);
            },

            //
            //
            //  Methods
            //
            //

            load: function (images) {
                this._updateContent(images);
                this.set('loading', false);
            },

            searchImages: function (filter, callback) {
                var that = this;
                Mist.ajax.POST('/backends/' + this.backend.id + '/images', {
                    'search_term': filter
                }).success(function (images) {

                }).error(function () {
                    Mist.notificationController.notify(
                        'Failed to search images on ' + that.backend.title);
                }).complete(function (success, images) {
                    var imagesToReturn = [];
                    if (success) {
                        images.forEach(function (image) {
                            image.backend = that.backend;
                            imagesToReturn.push(Image.create(image));
                        });
                    }
                    if (callback) callback(success, imagesToReturn);
                });
            },

            toggleImageStar: function (image, callback) {
                var that = this;
                Mist.ajax.POST('/backends/' + this.backend.id + '/images/' + image.id, {
                }).success(function (star) {
                    if (!that.imageExists(image.id))
                        that._addImage(image);
                    that._toggleImageStar(image.id, star);
                }).error(function () {
                    Mist.notificationController.notify('Failed to (un)star image');
                }).complete(function (success, star) {
                    if (callback) callback(success, star);
                });
            },

            getImage: function (imageId) {
                return this.content.findBy('id', imageId);
            },

            getImageOS: function (imageId) {

                var os = 'generic';
                var image = this.getImage(imageId);
                var imageAttribute;

                if(!!image)
                    imageAttribute = image.name;
                else
                    imageAttribute = imageId;

                OS_MAP.some(function (pair) {
                    return pair[0].some(function (key) {
                        if (imageAttribute.toLowerCase().indexOf(key) > -1)
                            return os = pair[1];
                    });
                });

                return os;
            },

            imageExists: function (imageId) {
                return !!this.getImage(imageId);
            },

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

            _updateContent: function (images) {
                Ember.run(this, function () {

                    // Remove deleted images
                    this.content.forEach(function (image) {
                        if (!images.findBy('id', image.id))
                            this.content.removeObject(image);
                    }, this);

                    images.forEach(function (image) {

                        var oldImage = this.getImage(image.id);

                        if (oldImage)
                            // Update existing images
                            forIn(image, function (value, property) {
                                oldImage.set(property, value);
                            });
                        else
                            // Add new images
                            this._addImage(image);
                    }, this);

                    this.trigger('onImageListChange');
                });
            },

            _addImage: function (image) {
                Ember.run(this, function () {
                    image.backend = this.backend;
                    this.content.addObject(Image.create(image));
                    this.trigger('onImageAdd');
                });
            },

            _toggleImageStar: function (imageId, star) {
                Ember.run(this, function () {
                    this.getImage(imageId).set('star', star);
                    this.trigger('onImageStarToggle');
                });
            },
        });
    }
);
<|endoftext|>


<commit_before>import MedicationRequested from '../shr/medication/MedicationRequested';
import RecurrencePattern from '../shr/core/RecurrencePattern';
import TimePeriod from '../shr/core/TimePeriod';
import moment from 'moment';

class FluxMedicationRequested {
    constructor(json) {
        this._medicationRequested = MedicationRequested.fromJSON(json);
    }

    /*
     *  Getter for requestedPerformanceTime
     *  Returns object containing timePeriodStart and timePeriodEnd value
     */
    get expectedPerformanceTime() {
        // doesn't support Timing option right now
        if(this._medicationRequested.actionContext.expectedPerformanceTime.value instanceof TimePeriod) {
            return {
                timePeriodStart: this._medicationRequested.actionContext.expectedPerformanceTime.value.timePeriodStart.value,
                timePeriodEnd: this._medicationRequested.actionContext.expectedPerformanceTime.value.timePeriodEnd.value
            };
        } else {
            return this._medicationRequested.actionContext.expectedPerformanceTime.value;
        }
    }

    isActiveAsOf(date) {
        const expectedPerformanceTime = this.expectedPerformanceTime;
        if (!expectedPerformanceTime || !(this._medicationRequested.actionContext.expectedPerformanceTime.value instanceof TimePeriod)) return null;
        const start = new moment(expectedPerformanceTime.timePeriodStart, "D MMM YYYY");
        const end = new moment(expectedPerformanceTime.timePeriodEnd, "D MMM YYYY");
        if (start && start > date) return false;
        if (end && end < date) return false;
        return true;
    }

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

    /*
     *  Getter for medication
     *  Returns displayText string for medication
     */
    get medication() {
        return this._medicationRequested.medicationOrCode.value.coding[0].displayText.value;
    }

    /*
     *  Getter for amountPerDose
     *  Returns object with value and units
     */
    get amountPerDose() {
        return {
            value: this._medicationRequested.dosage.doseAmount.value.decimal,
            units: this._medicationRequested.dosage.doseAmount.value.units.value.code
        };
    }

    /*
     *  Getter for timingOfDoses
     *  Returns object with value and units
     */
    get timingOfDoses() {
        let timingOfDoses = this._medicationRequested.dosage.timingOfDoses;
        if (timingOfDoses.timing.recurrencePattern instanceof RecurrencePattern) {
            let units;
            if (timingOfDoses.timing.recurrencePattern.recurrenceInterval.duration.units.value.code === 'd') {
                units = 'per day';
            }
            return {
                value: timingOfDoses.timing.recurrencePattern.recurrenceInterval.duration.decimal,
                units: units
            };
        }
        return {
            value: timingOfDoses.timing.recurrenceRange.value.positiveInt,
            units: 'cycles'
        }
    }

    /*
     *  Getter for status
     *  Returns status string
     */
    get status() {
        return this._medicationRequested.actionContext.status.value.coding[0].displayText.value.value;
    }

    /*
     * Getter for prescribed by, using Author as the prescribing doctor
     * Returns author string
     */
    get prescribedBy() {
        return this._medicationRequested.author.value;
    }

    /*
     * Getter for when prescribed, using the creation time of the entry as the time prescribed
     * Returns date as a string
     */
    get whenPrescribed() {
        return this._medicationRequested.entryInfo.creationTime.value;
    }

    /*
     *  Getter for reason for this medication
     *  Returns array of reasons
     */
    get reason() {
        return this._medicationRequested.actionContext.reason.value;
    }

    get code() {
        return this._medicationRequested.medicationOrCode.value.coding[0].code;
    }
}

export default FluxMedicationRequested;<commit_msg>fixed medication graphical visualization to get values for route into body and number of refills allowed<commit_after>import MedicationRequested from '../shr/medication/MedicationRequested';
import RecurrencePattern from '../shr/core/RecurrencePattern';
import TimePeriod from '../shr/core/TimePeriod';
import moment from 'moment';

class FluxMedicationRequested {
    constructor(json) {
        this._medicationRequested = MedicationRequested.fromJSON(json);
    }

    /*
     *  Getter for requestedPerformanceTime
     *  Returns object containing timePeriodStart and timePeriodEnd value
     */
    get expectedPerformanceTime() {
        // doesn't support Timing option right now
        if(this._medicationRequested.actionContext.expectedPerformanceTime.value instanceof TimePeriod) {
            return {
                timePeriodStart: this._medicationRequested.actionContext.expectedPerformanceTime.value.timePeriodStart.value,
                timePeriodEnd: this._medicationRequested.actionContext.expectedPerformanceTime.value.timePeriodEnd.value
            };
        } else {
            return this._medicationRequested.actionContext.expectedPerformanceTime.value;
        }
    }

    isActiveAsOf(date) {
        const expectedPerformanceTime = this.expectedPerformanceTime;
        if (!expectedPerformanceTime || !(this._medicationRequested.actionContext.expectedPerformanceTime.value instanceof TimePeriod)) return null;
        const start = new moment(expectedPerformanceTime.timePeriodStart, "D MMM YYYY");
        const end = new moment(expectedPerformanceTime.timePeriodEnd, "D MMM YYYY");
        if (start && start > date) return false;
        if (end && end < date) return false;
        return true;
    }

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

    /*
     *  Getter for medication
     *  Returns displayText string for medication
     */
    get medication() {
        return this._medicationRequested.medicationOrCode.value.coding[0].displayText.value;
    }

    /*
     *  Getter for amountPerDose
     *  Returns object with value and units
     */
    get amountPerDose() {
        return {
            value: this._medicationRequested.dosage.doseAmount.value.decimal,
            units: this._medicationRequested.dosage.doseAmount.value.units.value.code
        };
    }

    /*
     *  Getter for timingOfDoses
     *  Returns object with value and units
     */
    get timingOfDoses() {
        let timingOfDoses = this._medicationRequested.dosage.timingOfDoses;
        if (timingOfDoses.timing.recurrencePattern instanceof RecurrencePattern) {
            let units;
            if (timingOfDoses.timing.recurrencePattern.recurrenceInterval.duration.units.value.code === 'd') {
                units = 'per day';
            }
            return {
                value: timingOfDoses.timing.recurrencePattern.recurrenceInterval.duration.decimal,
                units: units
            };
        }
        return {
            value: timingOfDoses.timing.recurrenceRange.value.positiveInt,
            units: 'cycles'
        }
    }

    /*
     *  Getter for status
     *  Returns status string
     */
    get status() {
        return this._medicationRequested.actionContext.status.value.coding[0].displayText.value.value;
    }

    /*
     * Getter for prescribed by, using Author as the prescribing doctor
     * Returns author string
     */
    get prescribedBy() {
        return this._medicationRequested.author.value;
    }

    /*
     * Getter for when prescribed, using the creation time of the entry as the time prescribed
     * Returns date as a string
     */
    get whenPrescribed() {
        return this._medicationRequested.entryInfo.creationTime.value;
    }

    /*
     *  Getter for reason for this medication
     *  Returns array of reasons
     */
    get reason() {
        return this._medicationRequested.actionContext.reason.value;
    }

    get code() {
        return this._medicationRequested.medicationOrCode.value.coding[0].code;
    }

    get routeIntoBody() {
        return this._medicationRequested.dosage.routeIntoBody.value.coding[0].displayText.value;
    }

    get numberOfRefillsAllowed() {
        return this._medicationRequested.numberOfRefillsAllowed.value;
    }
}

export default FluxMedicationRequested;<|endoftext|>


<commit_before>var assert = require('chai').assert;
var fs = require("fs");
var vm = require("vm");

let KeyboardProcessor = require('../../dist');

// Required initialization setup.
global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing.
global.keyman = {}; // So that keyboard-based checks against the global `keyman` succeed.
                    // 10.0+ dependent keyboards, like khmer_angkor, will otherwise fail to load.

// Initialize supplementary plane string extensions
String.kmwEnableSupplementaryPlane(false);

// Test basic KeyboardProcessor functionality.
describe('KeyboardProcessor', function() {
  describe('[[constructor]]', function () {
    it('should initialize without errors', function () {
      let kp = new KeyboardProcessor();
      assert.isNotNull(kp);
    });

    it('has expected default values after initialization', function () {
      let kp = new KeyboardProcessor();
      assert.equal('us', kp.baseLayout, 'KeyboardProcessor has unexpected base layout')
      assert.isNotNull(global.KeymanWeb, 'KeymanWeb global was not automatically installed');
      assert.equal('default', kp.layerId, 'Default layer is not set to "default"');
      assert.isUndefined(kp.activeKeyboard, 'Initialized with already-active keyboard');
    });
  });

  describe('activeKeyboard', function() {
    it('is automatically set (in headless) on keyboard load', function () {
      let kp = new KeyboardProcessor();

      // These two lines will load a keyboard from its file; headless-mode `registerKeyboard` will
      // automatically set the keyboard as active.
      var script = new vm.Script(fs.readFileSync('tests/resources/keyboards/khmer_angkor.js'));
      script.runInThisContext();

      assert.isDefined(kp.activeKeyboard, 'Keyboard failed to register on script load');
      assert.equal('Keyboard_khmer_angkor', kp.activeKeyboard.id, 'Unexpected keyboard id found after script load');
    });
  });

  describe('processKeystroke', function() {
    it('simple output, no context', function() {
      let kp = new KeyboardProcessor();

      // These two lines will load a keyboard from its file; headless-mode `registerKeyboard` will
      // automatically set the keyboard as active.
      var script = new vm.Script(fs.readFileSync('tests/resources/keyboards/khmer_angkor.js'));
      script.runInThisContext();

      // Fetch a key from the keyboard's layout.
      let defaultLayer = kp.activeKeyboard.layout('desktop').getLayer('default');
      assert.isNotNull(defaultLayer);
      let keyS = defaultLayer.getKey('K_S');
      assert.isNotNull(keyS);

      // Get the default synthetic key event for said key.
      // let keyEvent = keyS.constructKeyEvent(kp,
      //                                       new com.keyman.text.Mock(),
      //                                       new com.keyman.text.EngineDeviceSpec('chrome', 'desktop', 'windows', false)
      // );

      // assert.isNotNull(keyEvent);
    })
  });
});
<commit_msg>feat(web/engine): unit test - baby's first headless key event<commit_after>var assert = require('chai').assert;
var fs = require("fs");
var vm = require("vm");

let KeyboardProcessor = require('../../dist');

// Required initialization setup.
global.com = KeyboardProcessor.com; // exports all keyboard-processor namespacing.
global.keyman = {}; // So that keyboard-based checks against the global `keyman` succeed.
                    // 10.0+ dependent keyboards, like khmer_angkor, will otherwise fail to load.

// Initialize supplementary plane string extensions
String.kmwEnableSupplementaryPlane(false);

// Test the top-level LMLayer interface.
// Note: these tests can only be run after BOTH stages of compilation are completed.
describe('KeyboardProcessor', function() {
  describe('[[constructor]]', function () {
    it('should initialize without errors', function () {
      let kp = new KeyboardProcessor();
      assert.isNotNull(kp);
    });

    it('has expected default values after initialization', function () {
      let kp = new KeyboardProcessor();
      assert.equal('us', kp.baseLayout, 'KeyboardProcessor has unexpected base layout')
      assert.isNotNull(global.KeymanWeb, 'KeymanWeb global was not automatically installed');
      assert.equal('default', kp.layerId, 'Default layer is not set to "default"');
      assert.isUndefined(kp.activeKeyboard, 'Initialized with already-active keyboard');
    });
  });

  describe('activeKeyboard', function() {
    it('is automatically set (in headless) on keyboard load', function () {
      let kp = new KeyboardProcessor();

      // These two lines will load a keyboard from its file; headless-mode `registerKeyboard` will
      // automatically set the keyboard as active.
      var script = new vm.Script(fs.readFileSync('tests/resources/keyboards/khmer_angkor.js'));
      script.runInThisContext();

      assert.isDefined(kp.activeKeyboard, 'Keyboard failed to register on script load');
      assert.equal('Keyboard_khmer_angkor', kp.activeKeyboard.id, 'Unexpected keyboard id found after script load');
    });
  });

  describe('processKeystroke', function() {
    it('simple output, no context', function() {
      let kp = new KeyboardProcessor();

      // These two lines will load a keyboard from its file; headless-mode `registerKeyboard` will
      // automatically set the keyboard as active.
      var script = new vm.Script(fs.readFileSync('tests/resources/keyboards/khmer_angkor.js'));
      script.runInThisContext();

      // Fetch a key from the keyboard's layout.
      let defaultLayer = kp.activeKeyboard.layout('desktop').getLayer('default');
      assert.isNotNull(defaultLayer);
      let keyS = defaultLayer.getKey('K_S');
      assert.isNotNull(keyS);

      //Get the default synthetic key event for said key.
      let mock = new com.keyman.text.Mock();
      let keyEvent = keyS.constructKeyEvent(kp, mock,
                                            new com.keyman.text.EngineDeviceSpec('chrome', 'desktop', 'windows', false)
      );

      assert.isNotNull(keyEvent);

      let ruleBehavior = kp.processKeystroke(keyEvent, mock);
      assert.isNotNull(ruleBehavior);
      assert.isNotNull(ruleBehavior.transcription);
      assert.equal(mock.getText(), 'ស', 'Unexpected output from key event');

      let transform = ruleBehavior.transcription.transform;
      assert.isNotNull(transform);
    })
  });
});
<|endoftext|>


<commit_before>angular
	.module('ngSharepoint')
	.provider('$sp', function() {
		var siteUrl = "";
		var connMode = "JSOM"; //possible values: JSOM, REST
		return {
			setSiteUrl: function (newUrl) {
				siteUrl = newUrl;
			},
			setConnectionMode: function(connMode) {
				if (connMode == "JSOM" || connMode == "REST") {
					this.connMode = connMode;
				}
			},
			$get: function() {
				return ({
					getSiteUrl: function() {
						return siteUrl;
					},
					getContext: function() {
						return new SP.ClientContext(siteUrl);
					}
				});
			}
		};
	});<commit_msg>Added connectionmode getter<commit_after>angular
	.module('ngSharepoint')
	.provider('$sp', function() {
		var siteUrl = "";
		var connMode = "JSOM"; //possible values: JSOM, REST
		return {
			setSiteUrl: function (newUrl) {
				siteUrl = newUrl;
			},
			setConnectionMode: function(connMode) { //Only JSOM Supported for now
				if (connMode == "JSOM" || connMode == "REST") {
					this.connMode = connMode;
				}
			},
			$get: function() {
				return ({
					getSiteUrl: function() {
						return siteUrl;
					},
					getConnectionMode: function() {
						return connMode;
					},
					getContext: function() {
						return new SP.ClientContext(siteUrl);
					}
				});
			}
		};
	});
<|endoftext|>


<commit_before>const chatReducer = (state = {}, action) => {
  switch (action.type) {
  case 'INTERESTED':
    return {
      interested: action.interested,
    };
  default:
    return state;
  }
};

export default chatReducer;
<commit_msg>Changed 'INTERESTED' to constant in src/chat/chatReducer.js<commit_after>import { INTERESTED } from './chatActions';

const chatReducer = (state = {}, action) => {
  switch (action.type) {
  case INTERESTED:
    return {
      interested: action.interested,
    };
  default:
    return state;
  }
};

export default chatReducer;
<|endoftext|>


<commit_before>/**
 * Analyzes DOM complexity
 */
/* global document: true, Node: true, window: true */
'use strict';

exports.version = '0.2';

exports.module = function(phantomas) {

	// HTML size
	phantomas.on('report', function() {
		phantomas.setMetricEvaluate('bodyHTMLSize', function() { // @desc the size of body tag content (document.body.innerHTML.length)
			return document.body && document.body.innerHTML.length || 0;
		});

		phantomas.evaluate(function() {
			(function(phantomas) {
				var runner = new phantomas.nodeRunner(),
					whitespacesRegExp = /^\s+$/,
					size = 0;

				// include all nodes
				runner.isSkipped = function(node) {
					return false;
				};

				runner.walk(document.body, function(node, depth) {
					switch (node.nodeType) {
						case Node.COMMENT_NODE:
							size = node.textContent.length + 7; // '<!--' + '-->'.length
							phantomas.incr('commentsSize', size);

							// log HTML comments bigger than 64 characters
							if (size > 64) {
								phantomas.addOffender('commentsSize', phantomas.getDOMPath(node) + ' (' + size + ' characters)');
							}
							break;

						case Node.ELEMENT_NODE:
							phantomas.incr('DOMelementsCount');
							phantomas.set('DOMelementMaxDepth', Math.max(phantomas.get('DOMelementMaxDepth') || 0, depth));

							// ignore inline <script> tags
							if (node.nodeName === 'SCRIPT') {
								return false;
							}

							// @see https://developer.mozilla.org/en/DOM%3awindow.getComputedStyle
							var styles = window.getComputedStyle(node);

							if (styles && styles.getPropertyValue('display') === 'none') {
								if (typeof node.innerHTML === 'string') {
									size = node.innerHTML.length;
									phantomas.incr('hiddenContentSize', size);

									// log hidden containers bigger than 1 kB
									if (size > 1024) {
										phantomas.addOffender('hiddenContentSize', phantomas.getDOMPath(node) + ' (' + size + ' characters)');
									}
								}

								// don't run for child nodes as they're hidden as well
								return false;
							}

							// count nodes with inline CSS
							if (node.hasAttribute('style')) {
								phantomas.incr('nodesWithInlineCSS');
								phantomas.addOffender('nodesWithInlineCSS', phantomas.getDOMPath(node) + ' (' + node.getAttribute('style')  + ')');
							}

							break;

						case Node.TEXT_NODE:
							if (whitespacesRegExp.test(node.textContent)) {
								phantomas.incr('whiteSpacesSize', node.textContent.length);
							}
							break;
					}
				});

				phantomas.spyEnabled(false, 'counting iframes and images');

				// count <iframe> tags
				phantomas.setMetric('iframesCount', document.querySelectorAll('iframe').length); // @desc number of iframe nodes

				// <img> nodes without dimensions (one of width / height missing)
				phantomas.setMetric('imagesWithoutDimensions', (function() { // @desc number of <img> nodes without both width and height attribute @offenders
					var imgNodes = document.body && document.body.querySelectorAll('img') || [],
						node,
						imagesWithoutDimensions = 0;

					for (var i=0, len=imgNodes.length; i<len; i++) {
						node = imgNodes[i];
						if (!node.hasAttribute('width') || !node.hasAttribute('height')) {
							phantomas.addOffender('imagesWithoutDimensions', phantomas.getDOMPath(node));
							imagesWithoutDimensions++;
						}
					}

					return imagesWithoutDimensions;
				})());

				phantomas.spyEnabled(true);
			}(window.__phantomas));
		});

		// total length of HTML comments (including <!-- --> brackets)
		phantomas.setMetricFromScope('commentsSize'); // @desc the size of HTML comments on the page @offenders

		// total length of HTML of hidden elements (i.e. display: none)
		phantomas.setMetricFromScope('hiddenContentSize'); // @desc the size of content of hidden elements on the page (with CSS display: none) @offenders

		// total length of text nodes with whitespaces only (i.e. pretty formatting of HTML)
		phantomas.setMetricFromScope('whiteSpacesSize'); // @desc the size of text nodes with whitespaces only

		// count all tags
		phantomas.setMetricFromScope('DOMelementsCount'); // @desc total number of HTML element nodes
		phantomas.setMetricFromScope('DOMelementMaxDepth'); // @desc maximum level on nesting of HTML element node

		// nodes with inlines CSS (style attribute)
		phantomas.setMetricFromScope('nodesWithInlineCSS'); // @desc number of nodes with inline CSS styling (with style attribute) @offenders
	});
};
<commit_msg>domComplexity/: phantomas.incr() -> phantomas.incrMetric()<commit_after>/**
 * Analyzes DOM complexity
 */
/* global document: true, Node: true, window: true */
'use strict';

exports.version = '0.3';

exports.module = function(phantomas) {

	// total length of HTML comments (including <!-- --> brackets)
	phantomas.setMetric('commentsSize'); // @desc the size of HTML comments on the page @offenders

	// total length of HTML of hidden elements (i.e. display: none)
	phantomas.setMetric('hiddenContentSize'); // @desc the size of content of hidden elements on the page (with CSS display: none) @offenders

	// total length of text nodes with whitespaces only (i.e. pretty formatting of HTML)
	phantomas.setMetric('whiteSpacesSize'); // @desc the size of text nodes with whitespaces only

	// count all tags
	phantomas.setMetric('DOMelementsCount'); // @desc total number of HTML element nodes
	phantomas.setMetric('DOMelementMaxDepth'); // @desc maximum level on nesting of HTML element node

	// nodes with inlines CSS (style attribute)
	phantomas.setMetric('nodesWithInlineCSS'); // @desc number of nodes with inline CSS styling (with style attribute) @offenders

	// HTML size
	phantomas.on('report', function() {
		phantomas.setMetricEvaluate('bodyHTMLSize', function() { // @desc the size of body tag content (document.body.innerHTML.length)
			return document.body && document.body.innerHTML.length || 0;
		});

		phantomas.evaluate(function() {
			(function(phantomas) {
				var runner = new phantomas.nodeRunner(),
					whitespacesRegExp = /^\s+$/,
					DOMelementMaxDepth = 0,
					size = 0;

				// include all nodes
				runner.isSkipped = function(node) {
					return false;
				};

				runner.walk(document.body, function(node, depth) {
					switch (node.nodeType) {
						case Node.COMMENT_NODE:
							size = node.textContent.length + 7; // '<!--' + '-->'.length
							phantomas.incrMetric('commentsSize', size);

							// log HTML comments bigger than 64 characters
							if (size > 64) {
								phantomas.addOffender('commentsSize', phantomas.getDOMPath(node) + ' (' + size + ' characters)');
							}
							break;

						case Node.ELEMENT_NODE:
							phantomas.incrMetric('DOMelementsCount');
							DOMelementMaxDepth = Math.max(DOMelementMaxDepth, depth);

							// ignore inline <script> tags
							if (node.nodeName === 'SCRIPT') {
								return false;
							}

							// @see https://developer.mozilla.org/en/DOM%3awindow.getComputedStyle
							var styles = window.getComputedStyle(node);

							if (styles && styles.getPropertyValue('display') === 'none') {
								if (typeof node.innerHTML === 'string') {
									size = node.innerHTML.length;
									phantomas.incrMetric('hiddenContentSize', size);

									// log hidden containers bigger than 1 kB
									if (size > 1024) {
										phantomas.addOffender('hiddenContentSize', phantomas.getDOMPath(node) + ' (' + size + ' characters)');
									}
								}

								// don't run for child nodes as they're hidden as well
								return false;
							}

							// count nodes with inline CSS
							if (node.hasAttribute('style')) {
								phantomas.incrMetric('nodesWithInlineCSS');
								phantomas.addOffender('nodesWithInlineCSS', phantomas.getDOMPath(node) + ' (' + node.getAttribute('style')  + ')');
							}

							break;

						case Node.TEXT_NODE:
							if (whitespacesRegExp.test(node.textContent)) {
								phantomas.incrMetric('whiteSpacesSize', node.textContent.length);
							}
							break;
					}
				});

				phantomas.setMetric('DOMelementMaxDepth', DOMelementMaxDepth);

				phantomas.spyEnabled(false, 'counting iframes and images');

				// count <iframe> tags
				phantomas.setMetric('iframesCount', document.querySelectorAll('iframe').length); // @desc number of iframe nodes

				// <img> nodes without dimensions (one of width / height missing)
				phantomas.setMetric('imagesWithoutDimensions', (function() { // @desc number of <img> nodes without both width and height attribute @offenders
					var imgNodes = document.body && document.body.querySelectorAll('img') || [],
						node,
						imagesWithoutDimensions = 0;

					for (var i=0, len=imgNodes.length; i<len; i++) {
						node = imgNodes[i];
						if (!node.hasAttribute('width') || !node.hasAttribute('height')) {
							phantomas.addOffender('imagesWithoutDimensions', phantomas.getDOMPath(node));
							imagesWithoutDimensions++;
						}
					}

					return imagesWithoutDimensions;
				})());

				phantomas.spyEnabled(true);
			}(window.__phantomas));
		});
	});
};
<|endoftext|>


<commit_before>function GcodeViewModel(loginStateViewModel, settingsViewModel) {
    var self = this;

    self.loginState = loginStateViewModel;
    self.settings = settingsViewModel;

    self.ui_progress_percentage = ko.observable();
    self.ui_progress_type = ko.observable();
    self.ui_progress_text = ko.computed(function() {
        var text = "";
        switch (self.ui_progress_type()) {
            case "loading": {
                text = gettext("Loading...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
                break;
            }
            case "analyzing": {
                text = gettext("Analyzing...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
                break;
            }
            case "done": {
                text = gettext("Analyzed");
                break;
            }
        }

        return text;
    });
    self.ui_modelInfo = ko.observable("");
    self.ui_layerInfo = ko.observable("");

    self.enableReload = ko.observable(false);

    self.waitForApproval = ko.observable(false);
    self.selectedFile = {
        name: ko.observable(undefined),
        date: ko.observable(undefined),
        size: ko.observable(undefined)
    };

    self.renderer_centerModel = ko.observable(false);
    self.renderer_centerViewport = ko.observable(false);
    self.renderer_zoomOnModel = ko.observable(false);
    self.renderer_showMoves = ko.observable(true);
    self.renderer_showRetracts = ko.observable(true);
    self.renderer_extrusionWidthEnabled = ko.observable(false);
    self.renderer_extrusionWidth = ko.observable(2);
    self.renderer_showNext = ko.observable(false);
    self.renderer_showPrevious = ko.observable(false);
    self.renderer_syncProgress = ko.observable(true);

    self.reader_sortLayers = ko.observable(true);
    self.reader_hideEmptyLayers = ko.observable(true);

    self.synchronizeOptions = function(additionalRendererOptions, additionalReaderOptions) {
        var renderer = {
            moveModel: self.renderer_centerModel(),
            centerViewport: self.renderer_centerViewport(),
            showMoves: self.renderer_showMoves(),
            showRetracts: self.renderer_showRetracts(),
            extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1,
            showNextLayer: self.renderer_showNext(),
            showPreviousLayer: self.renderer_showPrevious(),
            zoomInOnModel: self.renderer_zoomOnModel(),
            onInternalOptionChange: self._onInternalRendererOptionChange
        };
        if (additionalRendererOptions) {
            _.extend(renderer, additionalRendererOptions);
        }

        var reader = {
            sortLayers: self.reader_sortLayers(),
            purgeEmptyLayers: self.reader_hideEmptyLayers()
        };
        if (additionalReaderOptions) {
            _.extend(reader, additionalReaderOptions);
        }

        GCODE.ui.updateOptions({
            renderer: renderer,
            reader: reader
        });
    };

    // subscribe to update Gcode view on updates...
    self.renderer_centerModel.subscribe(self.synchronizeOptions);
    self.renderer_centerViewport.subscribe(self.synchronizeOptions);
    self.renderer_zoomOnModel.subscribe(self.synchronizeOptions);
    self.renderer_showMoves.subscribe(self.synchronizeOptions);
    self.renderer_showRetracts.subscribe(self.synchronizeOptions);
    self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions);
    self.renderer_extrusionWidth.subscribe(self.synchronizeOptions);
    self.renderer_showNext.subscribe(self.synchronizeOptions);
    self.renderer_showPrevious.subscribe(self.synchronizeOptions);
    self.reader_sortLayers.subscribe(self.synchronizeOptions);
    self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions);

    // subscribe to relevant printer settings...
    self.settings.printer_extruderOffsets.subscribe(function() {
        if (!self.enabled) return;
        if (!self.settings.printer_extruderOffsets()) return;

        GCODE.ui.updateOptions({
            reader: {
                toolOffsets: self.settings.printer_extruderOffsets()
            }
        });
    });
    self.settings.printer_bedDimensions.subscribe(function() {
        if (!self.enabled) return;

        var bedDimensions = self.settings.printer_bedDimensions();
        if (!bedDimensions || (!bedDimensions.hasOwnProperty("x") && !bedDimensions.hasOwnProperty("y") && !bedDimensions.hasOwnProperty("r"))) return;

        GCODE.ui.updateOptions({
            renderer: {
                bed: bedDimensions
            }
        });
    });
    self.settings.printer_invertAxes.subscribe(function() {
        if (!self.enabled) return;
        if (!self.settings.printer_invertAxes()) return;

        GCODE.ui.updateOptions({
            renderer: {
                invertAxes: {
                    x: self.settings.printer_invertX(),
                    y: self.settings.printer_invertY()
                }
            }
        });
    });

    self.loadedFilename = undefined;
    self.loadedFileDate = undefined;
    self.status = 'idle';
    self.enabled = false;

    self.currentlyPrinting = false;

    self.errorCount = 0;

    self.layerSlider = undefined;
    self.layerCommandSlider = undefined;

    self.currentLayer = undefined;
    self.currentCommand = undefined;

    self.initialize = function() {
        self._configureLayerSlider();
        self._configureLayerCommandSlider();

        self.settings.requestData(function() {
            GCODE.ui.init({
                container: "#gcode_canvas",
                onProgress: self._onProgress,
                onModelLoaded: self._onModelLoaded,
                onLayerSelected: self._onLayerSelected,
                bed: self.settings.printer_bedDimensions(),
                toolOffsets: self.settings.printer_extruderOffsets()
            });
            self.synchronizeOptions();
            self.enabled = true;
        });
    };

    self.reset = function() {
        self.enableReload(false);
        self.loadedFilename = undefined;
        self.loadedFileDate = undefined;
        self.clear();
    };

    self.clear = function() {
        GCODE.ui.clear();
    };

    self._configureLayerSlider = function() {
        self.layerSlider = $("#gcode_slider_layers").slider({
            id: "gcode_layer_slider",
            reversed: true,
            selection: "after",
            orientation: "vertical",
            min: 0,
            max: 1,
            step: 1,
            value: 0,
            enabled: false,
            formatter: function(value) { return "Layer #" + (value + 1); }
        }).on("slide", self.changeLayer);
    };

    self._configureLayerCommandSlider = function() {
        self.layerCommandSlider = $("#gcode_slider_commands").slider({
            id: "gcode_command_slider",
            orientation: "horizontal",
            min: 0,
            max: 1,
            step: 1,
            value: [0, 1],
            enabled: false,
            tooltip: "hide"
        }).on("slide", self.changeCommandRange);
    };

    self.loadFile = function(filename, date){
        self.enableReload(false);
        if (self.status == "idle" && self.errorCount < 3) {
            self.status = "request";
            $.ajax({
                url: BASEURL + "downloads/files/local/" + filename,
                data: { "ctime": date },
                type: "GET",
                success: function(response, rstatus) {
                    if(rstatus === 'success'){
                        self.showGCodeViewer(response, rstatus);
                        self.loadedFilename = filename;
                        self.loadedFileDate = date;
                        self.status = "idle";
                        self.enableReload(true);
                    }
                },
                error: function() {
                    self.status = "idle";
                    self.errorCount++;
                }
            });
        }
    };

    self.showGCodeViewer = function(response, rstatus) {
        var par = {
            target: {
                result: response
            }
        };
        GCODE.gCodeReader.loadFile(par);

        self.layerSlider.slider("disable");
        self.layerCommandSlider.slider("disable");
    };

    self.reload = function() {
        if (!self.enableReload()) return;
        self.loadFile(self.loadedFilename, self.loadedFileDate);
    };

    self.fromHistoryData = function(data) {
        self._processData(data);
    };

    self.fromCurrentData = function(data) {
        self._processData(data);
    };

    self._processData = function(data) {
        if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) {
            self.waitForApproval(false);

            self.loadedFilename = undefined;
            self.loadedFileDate = undefined;
            self.selectedFile.name(undefined);
            self.selectedFile.date(undefined);
            self.selectedFile.size(undefined);

            self.clear();
            return;
        }
        if (!self.enabled) return;
        self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused);

        if(self.loadedFilename
                && self.loadedFilename == data.job.file.name
                && self.loadedFileDate == data.job.file.date) {
            if (self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
                var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.completion);
                if(cmdIndex){
                    GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
                    GCODE.ui.updateLayerInfo(cmdIndex.layer);

                    self.layerSlider.slider("setValue", cmdIndex.layer);
                    self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
                }
            }
            self.errorCount = 0
        } else {
            self.clear();
            if (data.job.file.name && data.job.file.origin != "sdcard"
                    && (!self.waitForApproval() || (self.selectedFile.name() != data.job.file.name || self.selectedFile.date() != data.job.file.date))) {
                self.selectedFile.name(data.job.file.name);
                self.selectedFile.date(data.job.file.date);
                self.selectedFile.size(data.job.file.size);

                if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || ($.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) {
                    self.waitForApproval(true);
                    self.loadedFilename = undefined;
                    self.loadedFileDate = undefined;
                } else {
                    self.waitForApproval(false);
                    self.loadFile(data.job.file.name, data.job.file.date);
                }
            }
        }
    };

    self.approveLargeFile = function() {
        self.waitForApproval(false);
        self.loadFile(self.selectedFile.name(), self.selectedFile.date());
    };

    self._onProgress = function(type, percentage) {
        self.ui_progress_type(type);
        self.ui_progress_percentage(percentage);
    };

    self._onModelLoaded = function(model) {
        if (!model) {
            self.ui_modelInfo("");
            self.layerSlider.slider("disable");
            self.layerSlider.slider("setMax", 1);
            self.layerSlider.slider("setValue", 0);
            self.currentLayer = 0;
        } else {
            var output = [];
            output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm");
            if (model.filament.length == 0) {
                output.push(gettext("Total filament used") + ": " + model.filament.toFixed(2) + gettext("mm"));
            } else {
                for (var i = 0; i < model.filament.length; i++) {
                    output.push(gettext("Total filament used") + " (" + gettext("Tool") + " " + i + "): " + model.filament[i].toFixed(2) + gettext("mm"));
                }
            }
            output.push(gettext("Estimated print time") + ": " + formatDuration(model.printTime));
            output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
            output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));

            self.ui_modelInfo(output.join("
"));

            self.layerSlider.slider("enable");
            self.layerSlider.slider("setMax", model.layersPrinted - 1);
            self.layerSlider.slider("setValue", 0);
        }
    };

    self._onLayerSelected = function(layer) {
        if (!layer) {
            self.ui_layerInfo("");
            self.layerCommandSlider.slider("disable");
            self.layerCommandSlider.slider("setMax", 1);
            self.layerCommandSlider.slider("setValue", [0, 1]);
            self.currentCommand = [0, 1];
        } else {
            var output = [];
            output.push(gettext("Layer number") + ": " + (layer.number + 1));
            output.push(gettext("Layer height") + " (mm): " + layer.height);
            output.push(gettext("GCODE commands in layer") + ": " + layer.commands);
            if (layer.filament.length == 1) {
                output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm");
            } else {
                for (var i = 0; i < layer.filament.length; i++) {
                    output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
                }
            }
            output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime));

            self.ui_layerInfo(output.join("
"));

            self.layerCommandSlider.slider("enable");
            self.layerCommandSlider.slider("setMax", layer.commands - 1);
            self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]);
        }
    };

    self._onInternalRendererOptionChange = function(options) {
        if (!options) return;

        for (var opt in options) {
            if (opt == "zoomInOnModel" && options[opt] != self.renderer_zoomOnModel()) {
                self.renderer_zoomOnModel(false);
            } else if (opt == "centerViewport" && options[opt] != self.renderer_centerViewport()) {
                self.renderer_centerViewport(false);
            } else if (opt == "moveModel" && options[opt] != self.renderer_centerModel()) {
                self.renderer_centerModel(false);
            }
        }
    };

    self.changeLayer = function(event) {
        if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);

        var value = event.value;
        if (self.currentLayer !== undefined && self.currentLayer == value) return;
        self.currentLayer = value;

        GCODE.ui.changeSelectedLayer(value);
    };

    self.changeCommandRange = function(event) {
        if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);

        var tuple = event.value;
        if (self.currentCommand !== undefined && self.currentCommand[0] == tuple[0] && self.currentCommand[1] == tuple[1]) return;
        self.currentCommand = tuple;

        GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]);
    };

    self.onDataUpdaterReconnect = function() {
        self.reset();
    }

}
<commit_msg>Disabled extrustion check for gcode files without extrustion values (Thanks foosel)<commit_after>function GcodeViewModel(loginStateViewModel, settingsViewModel) {
    var self = this;

    self.loginState = loginStateViewModel;
    self.settings = settingsViewModel;

    self.ui_progress_percentage = ko.observable();
    self.ui_progress_type = ko.observable();
    self.ui_progress_text = ko.computed(function() {
        var text = "";
        switch (self.ui_progress_type()) {
            case "loading": {
                text = gettext("Loading...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
                break;
            }
            case "analyzing": {
                text = gettext("Analyzing...") + " (" + self.ui_progress_percentage().toFixed(0) + "%)";
                break;
            }
            case "done": {
                text = gettext("Analyzed");
                break;
            }
        }

        return text;
    });
    self.ui_modelInfo = ko.observable("");
    self.ui_layerInfo = ko.observable("");

    self.enableReload = ko.observable(false);

    self.waitForApproval = ko.observable(false);
    self.selectedFile = {
        name: ko.observable(undefined),
        date: ko.observable(undefined),
        size: ko.observable(undefined)
    };

    self.renderer_centerModel = ko.observable(false);
    self.renderer_centerViewport = ko.observable(false);
    self.renderer_zoomOnModel = ko.observable(false);
    self.renderer_showMoves = ko.observable(true);
    self.renderer_showRetracts = ko.observable(true);
    self.renderer_extrusionWidthEnabled = ko.observable(false);
    self.renderer_extrusionWidth = ko.observable(2);
    self.renderer_showNext = ko.observable(false);
    self.renderer_showPrevious = ko.observable(false);
    self.renderer_syncProgress = ko.observable(true);

    self.reader_sortLayers = ko.observable(true);
    self.reader_hideEmptyLayers = ko.observable(false);

    self.synchronizeOptions = function(additionalRendererOptions, additionalReaderOptions) {
        var renderer = {
            moveModel: self.renderer_centerModel(),
            centerViewport: self.renderer_centerViewport(),
            showMoves: self.renderer_showMoves(),
            showRetracts: self.renderer_showRetracts(),
            extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1,
            showNextLayer: self.renderer_showNext(),
            showPreviousLayer: self.renderer_showPrevious(),
            zoomInOnModel: self.renderer_zoomOnModel(),
            onInternalOptionChange: self._onInternalRendererOptionChange
        };
        if (additionalRendererOptions) {
            _.extend(renderer, additionalRendererOptions);
        }

        var reader = {
            sortLayers: self.reader_sortLayers(),
            purgeEmptyLayers: self.reader_hideEmptyLayers()
        };
        if (additionalReaderOptions) {
            _.extend(reader, additionalReaderOptions);
        }

        GCODE.ui.updateOptions({
            renderer: renderer,
            reader: reader
        });
    };

    // subscribe to update Gcode view on updates...
    self.renderer_centerModel.subscribe(self.synchronizeOptions);
    self.renderer_centerViewport.subscribe(self.synchronizeOptions);
    self.renderer_zoomOnModel.subscribe(self.synchronizeOptions);
    self.renderer_showMoves.subscribe(self.synchronizeOptions);
    self.renderer_showRetracts.subscribe(self.synchronizeOptions);
    self.renderer_extrusionWidthEnabled.subscribe(self.synchronizeOptions);
    self.renderer_extrusionWidth.subscribe(self.synchronizeOptions);
    self.renderer_showNext.subscribe(self.synchronizeOptions);
    self.renderer_showPrevious.subscribe(self.synchronizeOptions);
    self.reader_sortLayers.subscribe(self.synchronizeOptions);
    self.reader_hideEmptyLayers.subscribe(self.synchronizeOptions);

    // subscribe to relevant printer settings...
    self.settings.printer_extruderOffsets.subscribe(function() {
        if (!self.enabled) return;
        if (!self.settings.printer_extruderOffsets()) return;

        GCODE.ui.updateOptions({
            reader: {
                toolOffsets: self.settings.printer_extruderOffsets()
            }
        });
    });
    self.settings.printer_bedDimensions.subscribe(function() {
        if (!self.enabled) return;

        var bedDimensions = self.settings.printer_bedDimensions();
        if (!bedDimensions || (!bedDimensions.hasOwnProperty("x") && !bedDimensions.hasOwnProperty("y") && !bedDimensions.hasOwnProperty("r"))) return;

        GCODE.ui.updateOptions({
            renderer: {
                bed: bedDimensions
            }
        });
    });
    self.settings.printer_invertAxes.subscribe(function() {
        if (!self.enabled) return;
        if (!self.settings.printer_invertAxes()) return;

        GCODE.ui.updateOptions({
            renderer: {
                invertAxes: {
                    x: self.settings.printer_invertX(),
                    y: self.settings.printer_invertY()
                }
            }
        });
    });

    self.loadedFilename = undefined;
    self.loadedFileDate = undefined;
    self.status = 'idle';
    self.enabled = false;

    self.currentlyPrinting = false;

    self.errorCount = 0;

    self.layerSlider = undefined;
    self.layerCommandSlider = undefined;

    self.currentLayer = undefined;
    self.currentCommand = undefined;

    self.initialize = function() {
        self._configureLayerSlider();
        self._configureLayerCommandSlider();

        self.settings.requestData(function() {
            GCODE.ui.init({
                container: "#gcode_canvas",
                onProgress: self._onProgress,
                onModelLoaded: self._onModelLoaded,
                onLayerSelected: self._onLayerSelected,
                bed: self.settings.printer_bedDimensions(),
                toolOffsets: self.settings.printer_extruderOffsets()
            });
            self.synchronizeOptions();
            self.enabled = true;
        });
    };

    self.reset = function() {
        self.enableReload(false);
        self.loadedFilename = undefined;
        self.loadedFileDate = undefined;
        self.clear();
    };

    self.clear = function() {
        GCODE.ui.clear();
    };

    self._configureLayerSlider = function() {
        self.layerSlider = $("#gcode_slider_layers").slider({
            id: "gcode_layer_slider",
            reversed: true,
            selection: "after",
            orientation: "vertical",
            min: 0,
            max: 1,
            step: 1,
            value: 0,
            enabled: false,
            formatter: function(value) { return "Layer #" + (value + 1); }
        }).on("slide", self.changeLayer);
    };

    self._configureLayerCommandSlider = function() {
        self.layerCommandSlider = $("#gcode_slider_commands").slider({
            id: "gcode_command_slider",
            orientation: "horizontal",
            min: 0,
            max: 1,
            step: 1,
            value: [0, 1],
            enabled: false,
            tooltip: "hide"
        }).on("slide", self.changeCommandRange);
    };

    self.loadFile = function(filename, date){
        self.enableReload(false);
        if (self.status == "idle" && self.errorCount < 3) {
            self.status = "request";
            $.ajax({
                url: BASEURL + "downloads/files/local/" + filename,
                data: { "ctime": date },
                type: "GET",
                success: function(response, rstatus) {
                    if(rstatus === 'success'){
                        self.showGCodeViewer(response, rstatus);
                        self.loadedFilename = filename;
                        self.loadedFileDate = date;
                        self.status = "idle";
                        self.enableReload(true);
                    }
                },
                error: function() {
                    self.status = "idle";
                    self.errorCount++;
                }
            });
        }
    };

    self.showGCodeViewer = function(response, rstatus) {
        var par = {
            target: {
                result: response
            }
        };
        GCODE.gCodeReader.loadFile(par);

        self.layerSlider.slider("disable");
        self.layerCommandSlider.slider("disable");
    };

    self.reload = function() {
        if (!self.enableReload()) return;
        self.loadFile(self.loadedFilename, self.loadedFileDate);
    };

    self.fromHistoryData = function(data) {
        self._processData(data);
    };

    self.fromCurrentData = function(data) {
        self._processData(data);
    };

    self._processData = function(data) {
        if (!data.job.file || !data.job.file.name && (self.loadedFilename || self.loadedFileDate)) {
            self.waitForApproval(false);

            self.loadedFilename = undefined;
            self.loadedFileDate = undefined;
            self.selectedFile.name(undefined);
            self.selectedFile.date(undefined);
            self.selectedFile.size(undefined);

            self.clear();
            return;
        }
        if (!self.enabled) return;
        self.currentlyPrinting = data.state.flags && (data.state.flags.printing || data.state.flags.paused);

        if(self.loadedFilename
                && self.loadedFilename == data.job.file.name
                && self.loadedFileDate == data.job.file.date) {
            if (self.currentlyPrinting && self.renderer_syncProgress() && !self.waitForApproval()) {
                var cmdIndex = GCODE.gCodeReader.getCmdIndexForPercentage(data.progress.completion);
                if(cmdIndex){
                    GCODE.renderer.render(cmdIndex.layer, 0, cmdIndex.cmd);
                    GCODE.ui.updateLayerInfo(cmdIndex.layer);

                    self.layerSlider.slider("setValue", cmdIndex.layer);
                    self.layerCommandSlider.slider("setValue", [0, cmdIndex.cmd]);
                }
            }
            self.errorCount = 0
        } else {
            self.clear();
            if (data.job.file.name && data.job.file.origin != "sdcard"
                    && (!self.waitForApproval() || (self.selectedFile.name() != data.job.file.name || self.selectedFile.date() != data.job.file.date))) {
                self.selectedFile.name(data.job.file.name);
                self.selectedFile.date(data.job.file.date);
                self.selectedFile.size(data.job.file.size);

                if (data.job.file.size > CONFIG_GCODE_SIZE_THRESHOLD || ($.browser.mobile && data.job.file.size > CONFIG_GCODE_MOBILE_SIZE_THRESHOLD)) {
                    self.waitForApproval(true);
                    self.loadedFilename = undefined;
                    self.loadedFileDate = undefined;
                } else {
                    self.waitForApproval(false);
                    self.loadFile(data.job.file.name, data.job.file.date);
                }
            }
        }
    };

    self.approveLargeFile = function() {
        self.waitForApproval(false);
        self.loadFile(self.selectedFile.name(), self.selectedFile.date());
    };

    self._onProgress = function(type, percentage) {
        self.ui_progress_type(type);
        self.ui_progress_percentage(percentage);
    };

    self._onModelLoaded = function(model) {
        if (!model) {
            self.ui_modelInfo("");
            self.layerSlider.slider("disable");
            self.layerSlider.slider("setMax", 1);
            self.layerSlider.slider("setValue", 0);
            self.currentLayer = 0;
        } else {
            var output = [];
            output.push(gettext("Model size") + ": " + model.width.toFixed(2) + "mm × " + model.depth.toFixed(2) + "mm × " + model.height.toFixed(2) + "mm");
            if (model.filament.length == 0) {
                output.push(gettext("Total filament used") + ": " + model.filament.toFixed(2) + gettext("mm"));
            } else {
                for (var i = 0; i < model.filament.length; i++) {
                    output.push(gettext("Total filament used") + " (" + gettext("Tool") + " " + i + "): " + model.filament[i].toFixed(2) + gettext("mm"));
                }
            }
            output.push(gettext("Estimated print time") + ": " + formatDuration(model.printTime));
            output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm"));
            output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited"));

            self.ui_modelInfo(output.join("
"));

            self.layerSlider.slider("enable");
            self.layerSlider.slider("setMax", model.layersPrinted - 1);
            self.layerSlider.slider("setValue", 0);
        }
    };

    self._onLayerSelected = function(layer) {
        if (!layer) {
            self.ui_layerInfo("");
            self.layerCommandSlider.slider("disable");
            self.layerCommandSlider.slider("setMax", 1);
            self.layerCommandSlider.slider("setValue", [0, 1]);
            self.currentCommand = [0, 1];
        } else {
            var output = [];
            output.push(gettext("Layer number") + ": " + (layer.number + 1));
            output.push(gettext("Layer height") + " (mm): " + layer.height);
            output.push(gettext("GCODE commands in layer") + ": " + layer.commands);
            if (layer.filament.length == 1) {
                output.push(gettext("Filament used by layer") + ": " + layer.filament[0].toFixed(2) + "mm");
            } else {
                for (var i = 0; i < layer.filament.length; i++) {
                    output.push(gettext("Filament used by layer") + " (" + gettext("Tool") + " " + i + "): " + layer.filament[i].toFixed(2) + "mm");
                }
            }
            output.push(gettext("Print time for layer") + ": " + formatDuration(layer.printTime));

            self.ui_layerInfo(output.join("
"));

            self.layerCommandSlider.slider("enable");
            self.layerCommandSlider.slider("setMax", layer.commands - 1);
            self.layerCommandSlider.slider("setValue", [0, layer.commands - 1]);
        }
    };

    self._onInternalRendererOptionChange = function(options) {
        if (!options) return;

        for (var opt in options) {
            if (opt == "zoomInOnModel" && options[opt] != self.renderer_zoomOnModel()) {
                self.renderer_zoomOnModel(false);
            } else if (opt == "centerViewport" && options[opt] != self.renderer_centerViewport()) {
                self.renderer_centerViewport(false);
            } else if (opt == "moveModel" && options[opt] != self.renderer_centerModel()) {
                self.renderer_centerModel(false);
            }
        }
    };

    self.changeLayer = function(event) {
        if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);

        var value = event.value;
        if (self.currentLayer !== undefined && self.currentLayer == value) return;
        self.currentLayer = value;

        GCODE.ui.changeSelectedLayer(value);
    };

    self.changeCommandRange = function(event) {
        if (self.currentlyPrinting && self.renderer_syncProgress()) self.renderer_syncProgress(false);

        var tuple = event.value;
        if (self.currentCommand !== undefined && self.currentCommand[0] == tuple[0] && self.currentCommand[1] == tuple[1]) return;
        self.currentCommand = tuple;

        GCODE.ui.changeSelectedCommands(self.layerSlider.slider("getValue"), tuple[0], tuple[1]);
    };

    self.onDataUpdaterReconnect = function() {
        self.reset();
    }

}
<|endoftext|>