<commit_before>
import * as is from 'yox-common/util/is'
import * as env from 'yox-common/util/env'
import * as array from 'yox-common/util/array'
import * as object from 'yox-common/util/object'

/**
 * 节点基类
 */
export default class Node {

  constructor(type) {
    this.type = type
  }

  stringify() {
    return this.stringifyObject(this)
  }

  stringifyObject(obj) {
    let me = this, result = [ ]
    if (obj) {
      object.each(
        obj,
        function (value, key) {
          if (value == env.NULL) {
            return
          }
          if (value.stringify) {
            value = value.stringify()
          }
          else if (is.string(value)) {
            value = me.stringifyString(value)
          }
          else if (is.array(value)) {
            value = me.stringifyArray(value)
          }
          else if (is.object(value)) {
            value = me.stringifyObject(value)
          }
          array.push(result, `${key}:${value}`)
        }
      )
    }
    return `{${array.join(result, ',')}}`
  }

  stringifyArray(arr) {
    let me = this, result = [ ]
    if (arr) {
      array.each(
        arr,
        function (item) {
          if (item.stringify) {
            item = item.stringify()
          }
          else if (is.object(item)) {
            item = me.stringifyObject(item)
          }
          array.push(result, item)
        }
      )
    }
    return me.stringifyCall('a', result)
  }

  stringifyExpression(expr, safe) {
    if (expr) {
      return 'o(' + this.stringifyObject(expr) + ')'
    }
  }

  stringifyCall(name, params) {
    return `${name}(${array.join(params, ',')})`
  }

  stringifyString(str) {
    return `"${str.replace(/"/g, '\\"')}"`
  }

}
<commit_msg>update<commit_after>
import * as is from 'yox-common/util/is'
import * as env from 'yox-common/util/env'
import * as array from 'yox-common/util/array'
import * as object from 'yox-common/util/object'

/**
 * 节点基类
 */
export default class Node {

  constructor(type) {
    this.type = type
  }

  stringify() {
    return this.stringifyObject(this)
  }

  stringifyObject(obj) {
    let me = this, result = [ ]
    if (obj) {
      object.each(
        obj,
        function (value, key) {
          if (value == env.NULL) {
            return
          }
          if (value.stringify) {
            value = value.stringify()
          }
          else if (is.string(value)) {
            value = me.stringifyString(value)
          }
          else if (is.array(value)) {
            value = me.stringifyArray(value)
          }
          else if (is.object(value)) {
            value = me.stringifyObject(value)
          }
          array.push(result, `${key}:${value}`)
        }
      )
    }
    return `{${array.join(result, ',')}}`
  }

  stringifyArray(arr) {
    let me = this, result = [ ]
    if (arr) {
      array.each(
        arr,
        function (item) {
          if (item.stringify) {
            item = item.stringify()
          }
          else if (is.object(item)) {
            item = me.stringifyObject(item)
          }
          array.push(result, item)
        }
      )
    }
    return me.stringifyCall('a', result)
  }

  stringifyExpression(expr, safe) {
    if (expr) {
      return 'o(' + this.stringifyObject(expr) + ')'
    }
  }

  stringifyCall(name, params) {
    return `${name}(${array.join(params, ',')})`
  }

  stringifyString(str) {
    return `"${str.replace(/"/g, '\\"').replace(/\s*\n+\s*/g, ' ')}"`
  }

}
<|endoftext|>


<commit_before>describe('Grid', function() {

    function createGrid(rows, cols) {
        var elements = [],
            cellWidth = 50,
            cellHeight = 50,
            leftMargin = 0,
            topMargin = 0,
            top,
            left;

        for (i = 0; i < rows; i += 1) {

            leftMargin = 0;

            for (j = 0; j < cols; j += 1) {
                top = i * cellHeight + i * topMargin,
                left = j * cellWidth + j * leftMargin,

                elements.push({
                    top: top,
                    left: left,
                    width: cellWidth,
                    height: cellHeight
                });

                leftMargin = 50;
            }

            topMargin = 10;
        }

        return elements;
    }

    function showGrid(elements) {
        var parent = document.createElement('div'),
            styles = {
                position: 'relative',
                left: '10px',
                top: '10px',
                background: '#444',
                width: '500px',
                height: '500px'
            };

        Object.keys(styles).forEach(function (propName) {
            parent.style[propName] = styles[propName];
        });

        elements.forEach(function (element) {
            var elem = document.createElement('div');

            Object.keys(element).forEach(function (prop) {
                elem.style[prop] = element[prop] + 'px';
            });

            elem.style.position = 'absolute';
            elem.style.background = '#660099';

            parent.appendChild(elem);
        });

        document.querySelector('body').appendChild(parent);
    }

    describe('augmentElements', function () {

        it('should set the bottom property according to the top and height', function () {
            var elements = [{ top: 0, height: 100 }];
            expect(augmentElements(elements)[0].bottom).toBe(100);
        })

        it('should set the right property according to the left and width', function () {
            var elements = [{ left: 0, width: 100 }];
            expect(augmentElements(elements)[0].right).toBe(100);
        })

    });

    describe('getTopElementIndex', function () {

        it('should find the highest element if the element is first', function () {
            var elements = [{ top: -10 }, { top: 5 }];

            expect(getTopElementIndex(elements)).toBe(0);
        });

        it('should find the highest element if the element is last', function () {
            var elements = [{ top: 100 }, { top: 5 }];

            expect(getTopElementIndex(elements)).toBe(1);
        });

        it('should find the first element in a list with equal elements', function () {
            var elements = [{ top: 100 }, { top: 10 }, { top: 10 }];

            expect(getTopElementIndex(elements)).toBe(1);
        });

    });

    describe('row detection', function () {

        it('should find elements that have the same top', function() {
            var elements = createGrid(1, 2),
                row = detectRow(augmentElements(elements));

            expect(row.length).toBe(2);
        });

        it('should find elements that have a top within the center range of elements', function () {
            var elements = createGrid(1, 2),
                row;

            elements[0].top -= elements[0].height / 2 - 1;

            row = detectRow(augmentElements(elements));

            expect(row.length).toBe(2);
        });

        it('should find elements that have are exactly above the center range', function () {
            var elements = createGrid(1, 2),
                row;

            elements[0].top -= elements[0].height / 2;

            row = detectRow(augmentElements(elements));

            expect(row.length).toBe(2);
        });

        it('should not find elements that are bellow the center range', function () {
            var elements = createGrid(1, 2),
                row;

            elements[0].top -= elements[0].height / 2 + 10;

            row = detectRow(augmentElements(elements));

            expect(row.length).toBe(1);
        });

        it('should find elements that have a hierarchical positioning', function () {
            var elements = createGrid(1, 4),
                row;

            elements[0].top -= elements[0].height / 2;
            elements[2].top += elements[2].height / 2;
            elements[3].top += elements[3].height;

            row = detectRow(augmentElements(elements));

            expect(row.length).toBe(4);
        });

        it('should find elements that have a hierarchical positioning having the last element as the highest', function () {
            var elements = createGrid(1, 4),
                row;

            elements[3].top -= elements[3].height;
            elements[2].top -= elements[2].height / 2;
            elements[0].top += elements[0].height / 2;

            row = detectRow(augmentElements(elements));

            expect(row.length).toBe(4);
        });

        it('should not find elements that do not have a hierarchical positioning', function () {
            var elements = createGrid(1, 4),
                row;

            elements[0].top -= elements[0].height / 2;
            elements[2].top += elements[2].height / 2;
            elements[3].top += elements[3].height + 1;

            row = detectRow(augmentElements(elements));

            expect(row.length).toBe(3);
        });

        it('should find elements that are stacked through hierarchical positioning', function () {
            var elements = createGrid(1, 4),
                row;

            elements[0].top -= elements[0].height / 2;
            elements[2].top += elements[2].height / 2;
            elements[3].top += elements[3].height;
            elements[3].left = elements[0].left;

            row = detectRow(augmentElements(elements));

            expect(row.length).toBe(4);
        });

    });

    describe('isValidBoundries', function () {

        it('should validate an element with top, left, width, height', function () {
            var element = {
                top: 100,
                left: 100,
                width: 200,
                height: 200
            };

            expect(isValidBoundries(element)).toBe(true);
        });

        it('should validate an element with bottom, right, width, height', function () {
            var element = {
                bottom: 200,
                right: 200,
                width: 200,
                height: 200
            };

            expect(isValidBoundries(element)).toBe(true);
        });

        it('should validate an element with top, right, bottom, left', function () {
            var element = {
                top: 100,
                left: 100,
                bottom: 200,
                right: 200
            };

            expect(isValidBoundries(element)).toBe(true);
        });

        it('should not validate an element with without a vertical conditional', function () {
            var element = {
                top: 100,
                left: 100,
                right: 200
            };

            expect(isValidBoundries(element)).toBe(false);
        });

        it('should not validate an element with without a horizontal conditional', function () {
            var element = {
                top: 100,
                height: 500,
                right: 200
            };

            expect(isValidBoundries(element)).toBe(false);
        });

    });

    describe('getBoundries', function () {

        it('should find the boundries based on top, left, right, bottom', function() {
            var elements = [{
                    top: 100,
                    left: 100,
                    right: 200,
                    bottom: 400
                }, {
                    top: 50,
                    left: 50,
                    right: 150,
                    bottom: 500

                }],
                boundries = getBoundries(augmentElements(elements));

            expect(boundries.left).toBe(50);
            expect(boundries.right).toBe(200);
            expect(boundries.top).toBe(50);
            expect(boundries.bottom).toBe(500);
            expect(boundries.width).toBe(150);
            expect(boundries.height).toBe(450);
        });

    });

    describe('getComposedElement', function () {

        var elements = [];

        beforeEach(function () {
            elements = [{
                id: 1,
                top: -10,
                left: -10,
                right: 100,
                bottom: 100
            }, {
                id: 2,
                top: 0,
                left: 0,
                right: 50,
                bottom: 50
            }, {
                id: 3,
                top: 50,
                left: 100,
                right: 250,
                bottom: 500
            }];
        });

        it('should get the boundries for the parent element correct', function () {
            var result = getComposedElement(augmentElements(elements));

            expect(result.width).toBe(260);
            expect(result.height).toBe(510);
            expect(result.left).toBe(-10);
            expect(result.right).toBe(250);
            expect(result.bottom).toBe(500);
            expect(result.top).toBe(-10);
        });

        it('should get the correct number of children', function () {
            var result = getComposedElement(augmentElements(elements));
            expect(result.children.length).toBe(3);
        });

        it('should set the correct positioning for the child elements', function () {
            var result = getComposedElement(augmentElements(elements));

            result.children.forEach(function (child) {
                var initial;

                switch (child.id) {
                    case 1:
                        expect(child.top).toBe(0);
                        expect(child.left).toBe(0);
                        expect(child.right).toBe(110);
                        expect(child.bottom).toBe(110);
                        break;
                    case 2:
                        expect(child.top).toBe(10);
                        expect(child.left).toBe(10);
                        expect(child.right).toBe(60);
                        expect(child.bottom).toBe(60);
                        break;

                    case 3:
                        expect(child.top).toBe(60);
                        expect(child.left).toBe(110);
                        expect(child.right).toBe(260);
                        expect(child.bottom).toBe(510);
                        break;
                }
            });

        });

    });

    describe('detectComposedElements', function () {

        it('should group the first 3 elements as a composed element', function () {
            var elements = createGrid(1, 4),
                result;

            elements[1].left -= elements[1].left / 2 + 1;
            elements[2].left -= elements[2].left / 2 + 2;

            result = detectComposedElements(augmentElements(elements));

            expect(result.length).toBe(2);
        });

        it('should group the last 3 elements as a composed element', function () {
            var elements = createGrid(1, 4),
                result;

            elements[1].left += elements[1].width * 2 + 2;
            elements[2].left += elements[2].width + 2;

            result = detectComposedElements(augmentElements(elements));

            expect(result.length).toBe(2);
        });

        it('should not find any composed elements', function () {
            var elements = createGrid(1, 4),
                result;

            elements[1].left -= elements[1].left / 2 - 1;
            elements[2].left -= elements[2].left / 2 - 2;

            result = detectComposedElements(augmentElements(elements));

            expect(result.length).toBe(4);
        });

        it('should group the elements of a composed element as children', function () {
            var elements = createGrid(1, 5),
                children,
                result;

            elements[2].left -= elements[2].left / 3;
            elements[3].left -= elements[3].left / 2;

            result = detectComposedElements(augmentElements(elements));

            result.every(function (element) {
                if (undefined !== element.children) {
                    children = element.children;
                    return false;
                } else {
                    return true;
                }
            });

            expect(children.length).toBe(3);
        });

    });

});
<commit_msg>Added boundary test for detectRow.<commit_after>describe('Grid', function() {

    function createGrid(rows, cols) {
        var elements = [],
            cellWidth = 50,
            cellHeight = 50,
            leftMargin = 0,
            topMargin = 0,
            top,
            left;

        for (i = 0; i < rows; i += 1) {

            leftMargin = 0;

            for (j = 0; j < cols; j += 1) {
                top = i * cellHeight + i * topMargin,
                left = j * cellWidth + j * leftMargin,

                elements.push({
                    top: top,
                    left: left,
                    width: cellWidth,
                    height: cellHeight
                });

                leftMargin = 50;
            }

            topMargin = 10;
        }

        return elements;
    }

    function showGrid(elements) {
        var parent = document.createElement('div'),
            styles = {
                position: 'relative',
                left: '10px',
                top: '10px',
                background: '#444',
                width: '500px',
                height: '500px'
            };

        Object.keys(styles).forEach(function (propName) {
            parent.style[propName] = styles[propName];
        });

        elements.forEach(function (element) {
            var elem = document.createElement('div');

            Object.keys(element).forEach(function (prop) {
                elem.style[prop] = element[prop] + 'px';
            });

            elem.style.position = 'absolute';
            elem.style.background = '#660099';

            parent.appendChild(elem);
        });

        document.querySelector('body').appendChild(parent);
    }

    describe('augmentElements', function () {

        it('should set the bottom property according to the top and height', function () {
            var elements = [{ top: 0, height: 100 }];
            expect(augmentElements(elements)[0].bottom).toBe(100);
        })

        it('should set the right property according to the left and width', function () {
            var elements = [{ left: 0, width: 100 }];
            expect(augmentElements(elements)[0].right).toBe(100);
        })

    });

    describe('getTopElementIndex', function () {

        it('should find the highest element if the element is first', function () {
            var elements = [{ top: -10 }, { top: 5 }];

            expect(getTopElementIndex(elements)).toBe(0);
        });

        it('should find the highest element if the element is last', function () {
            var elements = [{ top: 100 }, { top: 5 }];

            expect(getTopElementIndex(elements)).toBe(1);
        });

        it('should find the first element in a list with equal elements', function () {
            var elements = [{ top: 100 }, { top: 10 }, { top: 10 }];

            expect(getTopElementIndex(elements)).toBe(1);
        });

    });

    describe('detectRow', function () {

        it('should find elements that have the same top', function() {
            var elements = createGrid(1, 2),
                row = detectRow(augmentElements(elements));

            expect(row.children.length).toBe(2);
        });

        it('should find elements that have a top within the center range of elements', function () {
            var elements = createGrid(1, 2),
                row;

            elements[0].top -= elements[0].height / 2 - 1;

            row = detectRow(augmentElements(elements));

            expect(row.children.length).toBe(2);
        });

        it('should find elements that have are exactly above the center range', function () {
            var elements = createGrid(1, 2),
                row;

            elements[0].top -= elements[0].height / 2;

            row = detectRow(augmentElements(elements));

            expect(row.children.length).toBe(2);
        });

        it('should not find elements that are bellow the center range', function () {
            var elements = createGrid(1, 2),
                row;

            elements[0].top -= elements[0].height / 2 + 10;

            row = detectRow(augmentElements(elements));

            expect(row.children.length).toBe(1);
        });

        it('should find elements that have a hierarchical positioning', function () {
            var elements = createGrid(1, 4),
                row;

            elements[0].top -= elements[0].height / 2;
            elements[2].top += elements[2].height / 2;
            elements[3].top += elements[3].height;

            row = detectRow(augmentElements(elements));

            expect(row.children.length).toBe(4);
        });

        it('should find elements that have a hierarchical positioning having the last element as the highest', function () {
            var elements = createGrid(1, 4),
                row;

            elements[3].top -= elements[3].height;
            elements[2].top -= elements[2].height / 2;
            elements[0].top += elements[0].height / 2;

            row = detectRow(augmentElements(elements));

            expect(row.children.length).toBe(4);
        });

        it('should not find elements that do not have a hierarchical positioning', function () {
            var elements = createGrid(1, 4),
                row;

            elements[0].top -= elements[0].height / 2;
            elements[2].top += elements[2].height / 2;
            elements[3].top += elements[3].height + 1;

            row = detectRow(augmentElements(elements));

            expect(row.children.length).toBe(3);
        });

        it('should find elements that are stacked through hierarchical positioning', function () {
            var elements = createGrid(1, 4),
                row;

            elements[0].top -= elements[0].height / 2;
            elements[2].top += elements[2].height / 2;
            elements[3].top += elements[3].height;
            elements[3].left = elements[0].left;

            row = detectRow(augmentElements(elements));

            expect(row.children.length).toBe(4);
        });

        it('should have the row boundries set', function () {
            var elements = createGrid(1, 4),
                row,
                boundries;

            elements[0].top -= elements[0].height / 2;
            elements[2].top += elements[2].height / 2;
            elements[3].top += elements[3].height;
            elements[3].left = elements[0].left;

            elements = augmentElements(elements);
            boundries = getBoundries(elements);
            row = detectRow(elements);

            Object.keys(boundries).forEach(function (prop) {
                expect(row[prop]).toBe(boundries[prop]);
            });

        });

    });

    describe('isValidBoundries', function () {

        it('should validate an element with top, left, width, height', function () {
            var element = {
                top: 100,
                left: 100,
                width: 200,
                height: 200
            };

            expect(isValidBoundries(element)).toBe(true);
        });

        it('should validate an element with bottom, right, width, height', function () {
            var element = {
                bottom: 200,
                right: 200,
                width: 200,
                height: 200
            };

            expect(isValidBoundries(element)).toBe(true);
        });

        it('should validate an element with top, right, bottom, left', function () {
            var element = {
                top: 100,
                left: 100,
                bottom: 200,
                right: 200
            };

            expect(isValidBoundries(element)).toBe(true);
        });

        it('should not validate an element with without a vertical conditional', function () {
            var element = {
                top: 100,
                left: 100,
                right: 200
            };

            expect(isValidBoundries(element)).toBe(false);
        });

        it('should not validate an element with without a horizontal conditional', function () {
            var element = {
                top: 100,
                height: 500,
                right: 200
            };

            expect(isValidBoundries(element)).toBe(false);
        });

    });

    describe('getBoundries', function () {

        it('should find the boundries based on top, left, right, bottom', function() {
            var elements = [{
                    top: 100,
                    left: 100,
                    right: 200,
                    bottom: 400
                }, {
                    top: 50,
                    left: 50,
                    right: 150,
                    bottom: 500

                }],
                boundries = getBoundries(augmentElements(elements));

            expect(boundries.left).toBe(50);
            expect(boundries.right).toBe(200);
            expect(boundries.top).toBe(50);
            expect(boundries.bottom).toBe(500);
            expect(boundries.width).toBe(150);
            expect(boundries.height).toBe(450);
        });

    });

    describe('getComposedElement', function () {

        var elements = [];

        beforeEach(function () {
            elements = [{
                id: 1,
                top: -10,
                left: -10,
                right: 100,
                bottom: 100
            }, {
                id: 2,
                top: 0,
                left: 0,
                right: 50,
                bottom: 50
            }, {
                id: 3,
                top: 50,
                left: 100,
                right: 250,
                bottom: 500
            }];
        });

        it('should get the boundries for the parent element correct', function () {
            var result = getComposedElement(augmentElements(elements));

            expect(result.width).toBe(260);
            expect(result.height).toBe(510);
            expect(result.left).toBe(-10);
            expect(result.right).toBe(250);
            expect(result.bottom).toBe(500);
            expect(result.top).toBe(-10);
        });

        it('should get the correct number of children', function () {
            var result = getComposedElement(augmentElements(elements));
            expect(result.children.length).toBe(3);
        });

        it('should set the correct positioning for the child elements', function () {
            var result = getComposedElement(augmentElements(elements));

            result.children.forEach(function (child) {
                var initial;

                switch (child.id) {
                    case 1:
                        expect(child.top).toBe(0);
                        expect(child.left).toBe(0);
                        expect(child.right).toBe(110);
                        expect(child.bottom).toBe(110);
                        break;
                    case 2:
                        expect(child.top).toBe(10);
                        expect(child.left).toBe(10);
                        expect(child.right).toBe(60);
                        expect(child.bottom).toBe(60);
                        break;

                    case 3:
                        expect(child.top).toBe(60);
                        expect(child.left).toBe(110);
                        expect(child.right).toBe(260);
                        expect(child.bottom).toBe(510);
                        break;
                }
            });

        });

    });

    describe('detectComposedElements', function () {

        it('should group the first 3 elements as a composed element', function () {
            var elements = createGrid(1, 4),
                result;

            elements[1].left -= elements[1].left / 2 + 1;
            elements[2].left -= elements[2].left / 2 + 2;

            result = detectComposedElements(augmentElements(elements));

            expect(result.length).toBe(2);
        });

        it('should group the last 3 elements as a composed element', function () {
            var elements = createGrid(1, 4),
                result;

            elements[1].left += elements[1].width * 2 + 2;
            elements[2].left += elements[2].width + 2;

            result = detectComposedElements(augmentElements(elements));

            expect(result.length).toBe(2);
        });

        it('should not find any composed elements', function () {
            var elements = createGrid(1, 4),
                result;

            elements[1].left -= elements[1].left / 2 - 1;
            elements[2].left -= elements[2].left / 2 - 2;

            result = detectComposedElements(augmentElements(elements));

            expect(result.length).toBe(4);
        });

        it('should group the elements of a composed element as children', function () {
            var elements = createGrid(1, 5),
                children,
                result;

            elements[2].left -= elements[2].left / 3;
            elements[3].left -= elements[3].left / 2;

            result = detectComposedElements(augmentElements(elements));

            result.every(function (element) {
                if (undefined !== element.children) {
                    children = element.children;
                    return false;
                } else {
                    return true;
                }
            });

            expect(children.length).toBe(3);
        });

    });

});
<|endoftext|>


<commit_before>import Entry from '../base/Entry';
import Identifier from '../core/Identifier';

/** Generated from SHR definition for shr.base.Study */
class Study {
    constructor(json) {
        if (json) {
            this._entryInfo = new Entry(json);
            this._title = json.title ? json.title : '';
            if (json.identifier) this._identifier = new Identifier(json.identifier);
            this._enrollmentDate = json.enrollmentDate;
            this._endDate = json.endDate;
        } else {
            this._entryInfo = Entry.createEntry("http://standardhealthrecord.org/base/Study");
        }
    }
  /**
   * Getter for entry information (shr.base.Entry)
   */
  get entryInfo() {
    return this._entryInfo;
  }

  /**
   * Setter for entry information (shr.base.Entry)
   */
  set entryInfo(entryVal) {
    this._entryInfo = entryVal;
  }

  /**
   * Getter for shr.core.Title
   */
  get title() {
    return this._title;
  }

  /**
   * Setter for shr.core.Title
   */
  set title(titleVal) {
    this._title = titleVal;
  }

  /**
   * Getter for shr.core.Identifier
   */
  get identifier() {
    return this._identifier;
  }

  /**
   * Setter for shr.core.Identifier
   */
  set identifier(identifierVal) {
    this._identifier = identifierVal;
  }
}

export default Study;
<commit_msg>Removed date properties from Study, moved to FluxStudy.<commit_after>import Entry from '../base/Entry';
import Identifier from '../core/Identifier';

/** Generated from SHR definition for shr.base.Study */
class Study {
    constructor(json) {
        if (json) {
            this._entryInfo = new Entry(json);
            this._title = json.title ? json.title : '';
            if (json.identifier) this._identifier = new Identifier(json.identifier);
        } else {
            this._entryInfo = Entry.createEntry("http://standardhealthrecord.org/base/Study");
        }
    }
  /**
   * Getter for entry information (shr.base.Entry)
   */
  get entryInfo() {
    return this._entryInfo;
  }

  /**
   * Setter for entry information (shr.base.Entry)
   */
  set entryInfo(entryVal) {
    this._entryInfo = entryVal;
  }

  /**
   * Getter for shr.core.Title
   */
  get title() {
    return this._title;
  }

  /**
   * Setter for shr.core.Title
   */
  set title(titleVal) {
    this._title = titleVal;
  }

  /**
   * Getter for shr.core.Identifier
   */
  get identifier() {
    return this._identifier;
  }

  /**
   * Setter for shr.core.Identifier
   */
  set identifier(identifierVal) {
    this._identifier = identifierVal;
  }
}

export default Study;
<|endoftext|>


<commit_before>var repository = require('../src/repository');
var os = require('os');
/**
 * IN ORDER TO RUN BENCHMARK :
 * 1. Checkout the magento2 repository
 * 2. Make a symbolic link into test/workspace as magento2
 * 3. Run from cli :
 * node bin/test.js
 * 4. In order to test with fork processes :
 * node bin/test.js --fork
 */
workspace = new repository(
  __dirname + '/../test/workspaces/magento2', {
  forkWorker: process.argv.indexOf('--fork') > -1,
  exclude: ['bin'],
  scanVars: process.argv.indexOf('--disable-vars') === -1,
  scanExpr: process.argv.indexOf('--disable-expr') === -1,
  scanDocs: process.argv.indexOf('--disable-docs') === -1
});
console.log('Configuration', workspace.options);
var i = 0;
workspace.on('error', function(e) {
  console.error(e);
});
workspace.on('progress', function() {
  i++;
  if (i % 500 === 0) {
    var mem = process.memoryUsage();
    console.log(
      (new Date()).toString() + '\t' +
      Math.round(mem.heapUsed / 1024 / 1024) + 'Mb\t' +
      Math.round(workspace.counter.loaded / workspace.counter.total * 100) + '% - ' +
      workspace.counter.total
    );
  }
});
var start = process.hrtime();
var elapsed_time = function(note){
    var precision = 3; // 3 decimal places
    var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
    console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
    start = process.hrtime(); // reset the timer
};
workspace.scan().then(function() {
  elapsed_time('Scan finished');
  var items = workspace.getByType('trait', -1);
  elapsed_time('List of traits : ' + items.length);
  items = workspace.getByType('class', -1);
  elapsed_time('List of classes : ' + items.length);
  items = workspace.getByType('interface', -1);
  elapsed_time('List of interfaces : ' + items.length);
  items = workspace.getByType('constant', -1);
  elapsed_time('List of constants : ' + items.length);
  var ns = workspace.getNamespace('\\Magento\\Catalog\\Ui\\DataProvider\\Product\\Form\\Modifier');
  elapsed_time('Found Namespace : ' + (ns ? ns.name : 'KO'));
  console.log('Read ' + workspace.counter.loaded + ' files / ' + workspace.counter.total + ' total files');
  console.log('Parsed ' + Math.round(workspace.counter.size / 1024 / 1024) + 'Mb');
  console.log('Extracted ' + workspace.counter.symbols + ' symbols');
  var kindStats = {};
  for(var f in workspace.files) {
    var file = workspace.files[f];
    for(var i = 0; i < file.nodes.length; i++) {
      var node = file.nodes[i];
      if (!(node.type in kindStats)) {
        kindStats[node.type] = 1;
      } else {
        kindStats[node.type] ++;
      }
    }
  }
  console.log('Symbols stats : \n\n', kindStats);
  // tada (force workers to stop)
  // console.log(JSON.stringify(workspace.cache(), null, 1));
  process.exit(0);
});
<commit_msg>use new api<commit_after>var repository = require('../src/repository');
var os = require('os');
/**
 * IN ORDER TO RUN BENCHMARK :
 * 1. Checkout the magento2 repository
 * 2. Make a symbolic link into test/workspace as magento2
 * 3. Run from cli :
 * node bin/test.js
 * 4. In order to test with fork processes :
 * node bin/test.js --fork
 */
workspace = new repository(
  __dirname + '/../test/workspaces/magento2', {
  forkWorker: process.argv.indexOf('--fork') > -1,
  exclude: ['bin'],
  scanVars: process.argv.indexOf('--disable-vars') === -1,
  scanExpr: process.argv.indexOf('--disable-expr') === -1,
  scanDocs: process.argv.indexOf('--disable-docs') === -1
});
console.log('Configuration', workspace.options);
var i = 0;
workspace.on('error', function(e) {
  console.error(e);
});
workspace.on('progress', function() {
  i++;
  if (i % 500 === 0) {
    var mem = process.memoryUsage();
    console.log(
      (new Date()).toString() + '\t' +
      Math.round(mem.heapUsed / 1024 / 1024) + 'Mb\t' +
      Math.round(workspace.counter.loaded / workspace.counter.total * 100) + '% - ' +
      workspace.counter.total
    );
  }
});
var start = process.hrtime();
var elapsed_time = function(note){
    var precision = 3; // 3 decimal places
    var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
    console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
    start = process.hrtime(); // reset the timer
};
workspace.scan().then(function() {
  elapsed_time('Scan finished');
  var items = workspace.getByType('trait');
  elapsed_time('List of traits : ' + items.length);
  items = workspace.getByType('class');
  elapsed_time('List of classes : ' + items.length);
  items = workspace.getByType('interface');
  elapsed_time('List of interfaces : ' + items.length);
  items = workspace.getByType('constant');
  elapsed_time('List of constants : ' + items.length);
  var ns = workspace.getNamespace('\\Magento\\Catalog\\Ui\\DataProvider\\Product\\Form\\Modifier');
  elapsed_time('Found Namespace : ' + (ns ? ns.name : 'KO'));
  console.log('Read ' + workspace.counter.loaded + ' files / ' + workspace.counter.total + ' total files');
  console.log('Parsed ' + Math.round(workspace.counter.size / 1024 / 1024) + 'Mb');
  console.log('Extracted ' + workspace.counter.symbols + ' symbols');
  // tada (force workers to stop)
  // console.log(JSON.stringify(workspace.cache(), null, 1));
  process.exit(0);
});
<|endoftext|>


<commit_before>/**
 * @fileoverview This file provides a "search" directive. This directive is
 * used to insert a Search bar into a HTML page.
 * Example:
 *
 * <app-search app-search-map="::mainCtrl.map"></app-search>
 *
 * Note the use of the one-time binding operator (::) in the map expression.
 * One-time binding is used because we know the map is not going to change
 * during the lifetime of the application.
 *
 */
goog.provide('app.searchDirective');

goog.require('app');
goog.require('app.GetLayerForCatalogNode');
goog.require('app.ShowLayerinfo');
goog.require('app.Themes');
goog.require('ngeo.CreateGeoJSONBloodhound');
goog.require('ngeo.searchDirective');

/**
 * @return {angular.Directive} The Directive Object Definition
 * @param {string} appSearchTemplateUrl
 * @ngInject
 */
app.searchDirective = function(appSearchTemplateUrl) {
  return {
    restrict: 'E',
    scope: {
      'map': '=appSearchMap'
    },
    controller: 'AppSearchController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appSearchTemplateUrl,
    link:
        /**
         * @param {angular.Scope} scope Scope
         * @param {angular.JQLite} element Element
         * @param {angular.Attributes} attrs Atttributes
         */
        function(scope, element, attrs) {
          // Empty the search field on focus and blur.
          element.find('input').on('focus blur', function() {
            $(this).val('');
          });
        }
  };
};

app.module.directive('appSearch', app.searchDirective);

/**
 * @ngInject
 * @constructor
 * @param {angular.Scope} $scope Angular root scope.
 * @param {app.Themes} appThemes Themes service.
 * @param {angular.$compile} $compile Angular compile service.
 * @param {ngeo.CreateGeoJSONBloodhound} ngeoCreateGeoJSONBloodhound The ngeo
 *     create GeoJSON Bloodhound service.o
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog
 * @param {app.GetLayerForCatalogNode} appGetLayerForCatalogNode
 * @param {app.ShowLayerinfo} appShowLayerinfo
 * @param {string} searchServiceUrl
 * @export
 */
app.SearchDirectiveController =
    function($scope, appThemes, $compile,
        ngeoCreateGeoJSONBloodhound, gettextCatalog,
        appGetLayerForCatalogNode, appShowLayerinfo, searchServiceUrl) {
  /**
   * @type {Array}
   */
  this.layers = [];

  /**
   * @type {ol.FeatureOverlay}
   * @private
   */
  this.featureOverlay_ = this.createFeatureOverlay_();

  /**
   * @type {app.GetLayerForCatalogNode}
   * @private
   */
  this.getLayerFunc_ = appGetLayerForCatalogNode;

  /**
   * @type {app.ShowLayerinfo}
   * @private
   */
  this.showLayerinfo_ = appShowLayerinfo;

  /** @type {Bloodhound} */
  var POIBloodhoundEngine = this.createAndInitPOIBloodhound_(
      ngeoCreateGeoJSONBloodhound, searchServiceUrl);
  /** @type {Bloodhound} */
  var LayerBloodhoundEngine = this.createAndInitLayerBloodhound_();

  $scope.$on('gettextLanguageChanged', goog.bind(function(event, args) {
    this.createLocalAllLayerData_(
        appThemes, LayerBloodhoundEngine, gettextCatalog);
  }, this));

  /** @type {TypeaheadOptions} */
  this['options'] = {
    highlight: true
  };

  /** @type {Array.<TypeaheadDataset>} */
  this['datasets'] = [{
    source: POIBloodhoundEngine.ttAdapter(),
    displayKey: function(suggestion) {
      var feature = /** @type {ol.Feature} */ (suggestion);
      return feature.get('label');
    },
    templates: {
      header: function() {
        return '
' +
          gettextCatalog.getString('Addresses') +
          '
';
      },
      suggestion: function(suggestion) {
        var feature = /** @type {ol.Feature} */ (suggestion);

        // A scope for the ng-click on the suggestion's « i » button.
        var scope = $scope.$new(true);
        scope['feature'] = feature;
        scope['click'] = function(event) {
          event.stopPropagation();
        };

        var html = '
' + feature.get('label') +
            ' (' + gettextCatalog.getString(
                /** @type {string} */ (feature.get('layer_name'))
            ) + ')
';
        return $compile(html)(scope);
      }
    }
  },{
    source: LayerBloodhoundEngine.ttAdapter(),
    displayKey: 'translated_name',
    templates: {
      header: function() {
        return '
' +
          gettextCatalog.getString('Layers') +
          '
';
      },
      suggestion: goog.bind(function(suggestion) {
        var scope = $scope.$new(true);
        scope['object'] = suggestion;
        scope['click'] = goog.bind(function(event) {
          this.showLayerinfo_(this.getLayerFunc_(suggestion));
          event.stopPropagation();
        }, this);

        var html = '
' + suggestion['translated_name'] +
            '<button ng-click="click($event)">i</button>
';
        return $compile(html)(scope);
      }, this)
    }
  }
  ];

  this['listeners'] = /** @type {ngeox.SearchDirectiveListeners} */ ({
    selected: goog.bind(app.SearchDirectiveController.selected_, this)
  });

};

/**
 * @return {ol.FeatureOverlay} The feature overlay.
 * @private
 */
app.SearchDirectiveController.prototype.createFeatureOverlay_ = function() {
  var featureOverlay = new ol.FeatureOverlay();
  featureOverlay.setMap(this['map']);
  return featureOverlay;
};

/**
 * @param {ngeo.CreateGeoJSONBloodhound} ngeoCreateGeoJSONBloodhound The ngeo
 *     create GeoJSON Bloodhound service.
 * @param {string} searchServiceUrl
 * @return {Bloodhound} The bloodhound engine.
 * @private
 */
app.SearchDirectiveController.prototype.createAndInitPOIBloodhound_ =
    function(ngeoCreateGeoJSONBloodhound, searchServiceUrl) {
  var url = 'fulltextsearch?query=%QUERY';
  var bloodhound = ngeoCreateGeoJSONBloodhound(url, ol.proj.get('EPSG:3857'));
  bloodhound.initialize();
  return bloodhound;
};

/**
 * @return {Bloodhound} The bloodhound engine.
 * @private
 */
app.SearchDirectiveController.prototype.createAndInitLayerBloodhound_ =
    function() {
  var bloodhound = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('translated_name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: []
  });
  bloodhound.initialize();
  return bloodhound;
};

/**
 * @param {app.Themes} appThemes Themes Service
 * @param {Bloodhound} bloodhound
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog
 * @private
 */
app.SearchDirectiveController.prototype.createLocalAllLayerData_ =
    function(appThemes, bloodhound, gettextCatalog) {
  appThemes.getThemesObject().then(
      goog.bind(function(themes) {
        for (var i = 0; i < themes.length; i++) {
          var theme = themes[i];
          goog.array.extend(this['layers'],
              app.SearchDirectiveController.getAllChildren_(
              theme.children, gettextCatalog
              )
          );
        }
        var dedup = [];
        goog.array.removeDuplicates(this['layers'], dedup, function(element) {
          return element['id'];
        });
        this['layers'] = dedup;
        bloodhound.clear();
        bloodhound.add(this['layers']);
      }, this)
  );
};

/**
 * @param {(Object|string)} input
 * @private
 */
app.SearchDirectiveController.prototype.addLayerToMap_ = function(input) {
  var layer = {};
  if (typeof input === 'string') {
    var node = goog.array.find(this['layers'], function(element) {
      return goog.object.containsKey(element, 'name') &&
          goog.object.containsValue(element, input);
    });
    if (!node) return; //stop error propagating if no node is found
    layer = this.getLayerFunc_(node);
  } else if (typeof input === 'object') {
    layer = this.getLayerFunc_(input);
  }
  var map = this['map'];
  if (map.getLayers().getArray().indexOf(layer) <= 0) {
    map.addLayer(layer);
  }
};

/**
 * @param {Array} element
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog
 * @return {Array} array
 * @private
 */
app.SearchDirectiveController.getAllChildren_ =
    function(element, gettextCatalog) {
  var array = [];
  for (var i = 0; i < element.length; i++) {
    if (element[i].hasOwnProperty('children')) {
      goog.array.extend(array, app.SearchDirectiveController.getAllChildren_(
          element[i].children, gettextCatalog)
      );
    } else {
      element[i].translated_name = gettextCatalog.getString(element[i].name);
      array.push(element[i]);
    }
  }
  return array;
};

/**
 * @param {jQuery.event} event Event.
 * @param {Object} suggestion Suggestion.
 * @param {TypeaheadDataset} dataset Dataset.
 * @this {app.SearchDirectiveController}
 * @private
 */
app.SearchDirectiveController.selected_ =
    function(event, suggestion, dataset) {
  if (suggestion instanceof ol.Feature) {
    var layerLookup = {
      'Adresse': ['addresses'],
      'Parcelle': ['parcels', 'parcels_labels'],
      'lieu_dit': ['toponymes'],
      'FLIK': ['asta_flik_parcels_2015'],
      'asta_esp': ['asta_esp_esp']
    };
    var showGeom = ['hydro', 'Adresse', 'FLIK', 'biotope',
      'hydro_km', 'asta_esp', 'Parcelle'];
    var map = /** @type {ol.Map} */ (this['map']);
    var feature = /** @type {ol.Feature} */ (suggestion);
    var featureGeometry = /** @type {ol.geom.SimpleGeometry} */
        (feature.getGeometry());
    var mapSize = /** @type {ol.Size} */ (map.getSize());
    var features = this.featureOverlay_.getFeatures();
    features.clear();
    if (goog.array.contains(showGeom, feature.get('layer_name'))) {
      features.push(feature);
    }
    map.getView().fitGeometry(featureGeometry, mapSize,
        /** @type {olx.view.FitGeometryOptions} */ ({maxZoom: 18}));
    var layers = layerLookup[suggestion.get('layer_name')];
    goog.array.forEach(layers, goog.bind(function(layer) {
      this.addLayerToMap_(layer);
    }, this));
  } else {
    this.addLayerToMap_(suggestion);
  }
};

app.module.controller('AppSearchController',
    app.SearchDirectiveController);
<commit_msg>fix linter<commit_after>/**
 * @fileoverview This file provides a "search" directive. This directive is
 * used to insert a Search bar into a HTML page.
 * Example:
 *
 * <app-search app-search-map="::mainCtrl.map"></app-search>
 *
 * Note the use of the one-time binding operator (::) in the map expression.
 * One-time binding is used because we know the map is not going to change
 * during the lifetime of the application.
 *
 */
goog.provide('app.searchDirective');

goog.require('app');
goog.require('app.GetLayerForCatalogNode');
goog.require('app.ShowLayerinfo');
goog.require('app.Themes');
goog.require('ngeo.CreateGeoJSONBloodhound');
goog.require('ngeo.searchDirective');

/**
 * @return {angular.Directive} The Directive Object Definition
 * @param {string} appSearchTemplateUrl
 * @ngInject
 */
app.searchDirective = function(appSearchTemplateUrl) {
  return {
    restrict: 'E',
    scope: {
      'map': '=appSearchMap'
    },
    controller: 'AppSearchController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appSearchTemplateUrl,
    link:
        /**
         * @param {angular.Scope} scope Scope
         * @param {angular.JQLite} element Element
         * @param {angular.Attributes} attrs Atttributes
         */
        function(scope, element, attrs) {
          // Empty the search field on focus and blur.
          element.find('input').on('focus blur', function() {
            $(this).val('');
          });
        }
  };
};

app.module.directive('appSearch', app.searchDirective);

/**
 * @ngInject
 * @constructor
 * @param {angular.Scope} $scope Angular root scope.
 * @param {app.Themes} appThemes Themes service.
 * @param {angular.$compile} $compile Angular compile service.
 * @param {ngeo.CreateGeoJSONBloodhound} ngeoCreateGeoJSONBloodhound The ngeo
 *     create GeoJSON Bloodhound service.o
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog
 * @param {app.GetLayerForCatalogNode} appGetLayerForCatalogNode
 * @param {app.ShowLayerinfo} appShowLayerinfo
 * @param {string} searchServiceUrl
 * @export
 */
app.SearchDirectiveController =
    function($scope, appThemes, $compile,
        ngeoCreateGeoJSONBloodhound, gettextCatalog,
        appGetLayerForCatalogNode, appShowLayerinfo, searchServiceUrl) {
  /**
   * @type {Array}
   */
  this.layers = [];

  /**
   * @type {ol.FeatureOverlay}
   * @private
   */
  this.featureOverlay_ = this.createFeatureOverlay_();

  /**
   * @type {app.GetLayerForCatalogNode}
   * @private
   */
  this.getLayerFunc_ = appGetLayerForCatalogNode;

  /**
   * @type {app.ShowLayerinfo}
   * @private
   */
  this.showLayerinfo_ = appShowLayerinfo;

  /** @type {Bloodhound} */
  var POIBloodhoundEngine = this.createAndInitPOIBloodhound_(
      ngeoCreateGeoJSONBloodhound, searchServiceUrl);
  /** @type {Bloodhound} */
  var LayerBloodhoundEngine = this.createAndInitLayerBloodhound_();

  $scope.$on('gettextLanguageChanged', goog.bind(function(event, args) {
    this.createLocalAllLayerData_(
        appThemes, LayerBloodhoundEngine, gettextCatalog);
  }, this));

  /** @type {TypeaheadOptions} */
  this['options'] = {
    highlight: true
  };

  /** @type {Array.<TypeaheadDataset>} */
  this['datasets'] = [{
    source: POIBloodhoundEngine.ttAdapter(),
    displayKey: function(suggestion) {
      var feature = /** @type {ol.Feature} */ (suggestion);
      return feature.get('label');
    },
    templates: {
      header: function() {
        return '
' +
            gettextCatalog.getString('Addresses') +
            '
';
      },
      suggestion: function(suggestion) {
        var feature = /** @type {ol.Feature} */ (suggestion);

        // A scope for the ng-click on the suggestion's « i » button.
        var scope = $scope.$new(true);
        scope['feature'] = feature;
        scope['click'] = function(event) {
          event.stopPropagation();
        };

        var html = '
' + feature.get('label') +
            ' (' + gettextCatalog.getString(
                /** @type {string} */ (feature.get('layer_name'))
            ) + ')
';
        return $compile(html)(scope);
      }
    }
  },{
    source: LayerBloodhoundEngine.ttAdapter(),
    displayKey: 'translated_name',
    templates: {
      header: function() {
        return '
' +
            gettextCatalog.getString('Layers') +
            '
';
      },
      suggestion: goog.bind(function(suggestion) {
        var scope = $scope.$new(true);
        scope['object'] = suggestion;
        scope['click'] = goog.bind(function(event) {
          this.showLayerinfo_(this.getLayerFunc_(suggestion));
          event.stopPropagation();
        }, this);

        var html = '
' + suggestion['translated_name'] +
            '<button ng-click="click($event)">i</button>
';
        return $compile(html)(scope);
      }, this)
    }
  }
  ];

  this['listeners'] = /** @type {ngeox.SearchDirectiveListeners} */ ({
    selected: goog.bind(app.SearchDirectiveController.selected_, this)
  });

};

/**
 * @return {ol.FeatureOverlay} The feature overlay.
 * @private
 */
app.SearchDirectiveController.prototype.createFeatureOverlay_ = function() {
  var featureOverlay = new ol.FeatureOverlay();
  featureOverlay.setMap(this['map']);
  return featureOverlay;
};

/**
 * @param {ngeo.CreateGeoJSONBloodhound} ngeoCreateGeoJSONBloodhound The ngeo
 *     create GeoJSON Bloodhound service.
 * @param {string} searchServiceUrl
 * @return {Bloodhound} The bloodhound engine.
 * @private
 */
app.SearchDirectiveController.prototype.createAndInitPOIBloodhound_ =
    function(ngeoCreateGeoJSONBloodhound, searchServiceUrl) {
  var url = 'fulltextsearch?query=%QUERY';
  var bloodhound = ngeoCreateGeoJSONBloodhound(url, ol.proj.get('EPSG:3857'));
  bloodhound.initialize();
  return bloodhound;
};

/**
 * @return {Bloodhound} The bloodhound engine.
 * @private
 */
app.SearchDirectiveController.prototype.createAndInitLayerBloodhound_ =
    function() {
  var bloodhound = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('translated_name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: []
  });
  bloodhound.initialize();
  return bloodhound;
};

/**
 * @param {app.Themes} appThemes Themes Service
 * @param {Bloodhound} bloodhound
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog
 * @private
 */
app.SearchDirectiveController.prototype.createLocalAllLayerData_ =
    function(appThemes, bloodhound, gettextCatalog) {
  appThemes.getThemesObject().then(
      goog.bind(function(themes) {
        for (var i = 0; i < themes.length; i++) {
          var theme = themes[i];
          goog.array.extend(this['layers'],
              app.SearchDirectiveController.getAllChildren_(
              theme.children, gettextCatalog
              )
          );
        }
        var dedup = [];
        goog.array.removeDuplicates(this['layers'], dedup, function(element) {
          return element['id'];
        });
        this['layers'] = dedup;
        bloodhound.clear();
        bloodhound.add(this['layers']);
      }, this)
  );
};

/**
 * @param {(Object|string)} input
 * @private
 */
app.SearchDirectiveController.prototype.addLayerToMap_ = function(input) {
  var layer = {};
  if (typeof input === 'string') {
    var node = goog.array.find(this['layers'], function(element) {
      return goog.object.containsKey(element, 'name') &&
          goog.object.containsValue(element, input);
    });
    if (!node) return; //stop error propagating if no node is found
    layer = this.getLayerFunc_(node);
  } else if (typeof input === 'object') {
    layer = this.getLayerFunc_(input);
  }
  var map = this['map'];
  if (map.getLayers().getArray().indexOf(layer) <= 0) {
    map.addLayer(layer);
  }
};

/**
 * @param {Array} element
 * @param {angularGettext.Catalog} gettextCatalog Gettext catalog
 * @return {Array} array
 * @private
 */
app.SearchDirectiveController.getAllChildren_ =
    function(element, gettextCatalog) {
  var array = [];
  for (var i = 0; i < element.length; i++) {
    if (element[i].hasOwnProperty('children')) {
      goog.array.extend(array, app.SearchDirectiveController.getAllChildren_(
          element[i].children, gettextCatalog)
      );
    } else {
      element[i].translated_name = gettextCatalog.getString(element[i].name);
      array.push(element[i]);
    }
  }
  return array;
};

/**
 * @param {jQuery.event} event Event.
 * @param {Object} suggestion Suggestion.
 * @param {TypeaheadDataset} dataset Dataset.
 * @this {app.SearchDirectiveController}
 * @private
 */
app.SearchDirectiveController.selected_ =
    function(event, suggestion, dataset) {
  if (suggestion instanceof ol.Feature) {
    var layerLookup = {
      'Adresse': ['addresses'],
      'Parcelle': ['parcels', 'parcels_labels'],
      'lieu_dit': ['toponymes'],
      'FLIK': ['asta_flik_parcels_2015'],
      'asta_esp': ['asta_esp_esp']
    };
    var showGeom = ['hydro', 'Adresse', 'FLIK', 'biotope',
      'hydro_km', 'asta_esp', 'Parcelle'];
    var map = /** @type {ol.Map} */ (this['map']);
    var feature = /** @type {ol.Feature} */ (suggestion);
    var featureGeometry = /** @type {ol.geom.SimpleGeometry} */
        (feature.getGeometry());
    var mapSize = /** @type {ol.Size} */ (map.getSize());
    var features = this.featureOverlay_.getFeatures();
    features.clear();
    if (goog.array.contains(showGeom, feature.get('layer_name'))) {
      features.push(feature);
    }
    map.getView().fitGeometry(featureGeometry, mapSize,
        /** @type {olx.view.FitGeometryOptions} */ ({maxZoom: 18}));
    var layers = layerLookup[suggestion.get('layer_name')];
    goog.array.forEach(layers, goog.bind(function(layer) {
      this.addLayerToMap_(layer);
    }, this));
  } else {
    this.addLayerToMap_(suggestion);
  }
};

app.module.controller('AppSearchController',
    app.SearchDirectiveController);
<|endoftext|>


<commit_before>const fs = require('fs');
const del = require('del');
const path = require('path');
const childProcess = require('child_process');

function Builder() {
    var me = this;
    me.rootFolder = fs.realpathSync(__dirname + '/..');
    me.buildPath = me.rootFolder + '/build';
    me.blendPath = me.rootFolder + '/blend';
    me.blendSourcePath = me.blendPath + '/src';
    me.testPath = me.rootFolder + '/tests'
    me.copyrightHeader = [
        '/**',
        ' * Copyright 2016 TrueSoftware B.V. All Rights Reserved.',
        ' *',
        ' * Licensed under the Apache License, Version 2.0 (the "License");',
        ' * you may not use this file except in compliance with the License.',
        ' * You may obtain a copy of the License at',
        ' *',
        ' *      http://www.apache.org/licenses/LICENSE-2.0',
        ' *',
        ' * Unless required by applicable law or agreed to in writing, software',
        ' * distributed under the License is distributed on an "AS IS" BASIS,',
        ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.',
        ' * See the License for the specific language governing permissions and',
        ' * limitations under the License.',
        ' */'
    ]
}

Builder.prototype.checkSanity = function(callback) {
    var me = this;
    childProcess.exec('compass -v', { cwd: me.rootFolder }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, ['No Compass installation found!']);
        }
    });
}

Builder.prototype.cleanBuild = function(callback) {
    var me = this;
    try {
        console.log('-- Cleaning the build (' + me.buildPath + ')');
        if (fs.existsSync(me.buildPath)) {
            del.sync(me.buildPath, {
                force: true
            });
        }
        fs.mkdir(me.buildPath);
        callback.apply(me, [null]);
    } catch (e) {
        callback.apply(me, [e]);
    }
}

Builder.prototype.buildStyles = function(callback) {
    var me = this;
    console.log('-- Building Themes and Styles');
    childProcess.exec('compass compile', { cwd: me.blendPath }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, [stdout.toString()]);
        }
    });
}

Builder.prototype.buildBlend = function(callback) {
    var me = this;
    console.log('-- Building Blend');
    childProcess.exec('tsc', { cwd: me.blendPath }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, [stdout.toString()]);
        }
    });
}

Builder.prototype.buildFramework = function(callback) {
    var me = this;
    me.checkSanity(function(error) {
        if (!error) {
            me.cleanBuild(function(error) {
                if (!error) {
                    me.buildStyles(function(error) {
                        if (!error) {
                            me.buildBlend(function(error) {
                                if (!error) {
                                    callback.apply(me, [null])
                                } else {
                                    callback.apply(me, [error])
                                }
                            });
                        } else {
                            console.error(error);
                        }
                    });
                } else {
                    console.error(error);
                }
            });
        } else {
            console.error(error);
        }
    });
}

Builder.prototype.copyrightFiles = function() {
    console.log('-- Looking for files');
    var me = this,
        header = me.copyrightHeader.join("\n");
    files = me.readFiles(me.blendPath, function(fname) {
        var ext = path.extname(fname);
        return (ext === '.ts'
            || ext === '.scss')
            && fname.indexOf(path.sep + 'typings' + path.sep) === -1;
    });
    files.forEach(function(fname) {
        var contents = fs.readFileSync(fname).toString();
        if (contents.indexOf('Copyright 2016 TrueSoftware B.V') === -1) {
            contents = header + "\n\n" + contents;
            fs.writeFileSync(fname, contents);
            console.log('-- Updated ' + fname);
        }
    });
    console.log('-- Done\n');
}

Builder.prototype.readFiles = function(dir, filter) {
    var me = this,
        results = [];
    filter = filter || function(fname) {
        return true;
    }
    var list = fs.readdirSync(dir)
    list.forEach(function(file) {
        file = dir + '/' + file
        var stat = fs.statSync(file)
        if (stat && stat.isDirectory()) {
            results = results.concat(me.readFiles(file, filter))
        } else {
            if (filter(file) === true) {
                results.push(file)
            }
        }
    })
    return results;
}

Builder.prototype.run = function() {
    console.log("MaterialBlend Framework Builder v1.0\n");
    var me = this,
        argv = require('yargs')
            .command('build', 'Builds MaterialBlend and Tests')
            .command('copyright', 'Adds copyright headers to files')
            .demand(1)
            .help('h')
            .alias('h', 'help')
            .epilog('Copyright 2016 TrueSoftware B.V.')
            .argv;

    var command = argv._[0];
    if (command === 'build') {
        me.buildFramework(function() {
            console.log('-- Done.')
        })
    } else if (command === 'copyright') {
        me.copyrightFiles();
    }

}

var builder = new Builder();
builder.run();<commit_msg>Added copyright header<commit_after>
/**
 * Copyright 2016 TrueSoftware B.V. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const fs = require('fs');
const del = require('del');
const path = require('path');
const childProcess = require('child_process');

function Builder() {
    var me = this;
    me.rootFolder = fs.realpathSync(__dirname + '/..');
    me.buildPath = me.rootFolder + '/build';
    me.blendPath = me.rootFolder + '/blend';
    me.blendSourcePath = me.blendPath + '/src';
    me.testPath = me.rootFolder + '/tests'
    me.copyrightHeader = [
        '/**',
        ' * Copyright 2016 TrueSoftware B.V. All Rights Reserved.',
        ' *',
        ' * Licensed under the Apache License, Version 2.0 (the "License");',
        ' * you may not use this file except in compliance with the License.',
        ' * You may obtain a copy of the License at',
        ' *',
        ' *      http://www.apache.org/licenses/LICENSE-2.0',
        ' *',
        ' * Unless required by applicable law or agreed to in writing, software',
        ' * distributed under the License is distributed on an "AS IS" BASIS,',
        ' * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.',
        ' * See the License for the specific language governing permissions and',
        ' * limitations under the License.',
        ' */'
    ]
}

Builder.prototype.checkSanity = function(callback) {
    var me = this;
    childProcess.exec('compass -v', { cwd: me.rootFolder }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, ['No Compass installation found!']);
        }
    });
}

Builder.prototype.cleanBuild = function(callback) {
    var me = this;
    try {
        console.log('-- Cleaning the build (' + me.buildPath + ')');
        if (fs.existsSync(me.buildPath)) {
            del.sync(me.buildPath, {
                force: true
            });
        }
        fs.mkdir(me.buildPath);
        callback.apply(me, [null]);
    } catch (e) {
        callback.apply(me, [e]);
    }
}

Builder.prototype.buildStyles = function(callback) {
    var me = this;
    console.log('-- Building Themes and Styles');
    childProcess.exec('compass compile', { cwd: me.blendPath }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, [stdout.toString()]);
        }
    });
}

Builder.prototype.buildBlend = function(callback) {
    var me = this;
    console.log('-- Building Blend');
    childProcess.exec('tsc', { cwd: me.blendPath }, function(error, stdout, stderr) {
        if (!error) {
            callback.apply(me, [null]);
        } else {
            callback.apply(me, [stdout.toString()]);
        }
    });
}

Builder.prototype.buildFramework = function(callback) {
    var me = this;
    me.checkSanity(function(error) {
        if (!error) {
            me.cleanBuild(function(error) {
                if (!error) {
                    me.buildStyles(function(error) {
                        if (!error) {
                            me.buildBlend(function(error) {
                                if (!error) {
                                    callback.apply(me, [null])
                                } else {
                                    callback.apply(me, [error])
                                }
                            });
                        } else {
                            console.error(error);
                        }
                    });
                } else {
                    console.error(error);
                }
            });
        } else {
            console.error(error);
        }
    });
}

Builder.prototype.copyrightFiles = function() {
    console.log('-- Looking for files');
    var me = this,
        header = me.copyrightHeader.join("\n");
    files = me.readFiles(me.blendPath, function(fname) {
        var ext = path.extname(fname);
        return (ext === '.ts'
            || ext === '.scss')
            && fname.indexOf(path.sep + 'typings' + path.sep) === -1;
    });
    files.forEach(function(fname) {
        var contents = fs.readFileSync(fname).toString();
        if (contents.indexOf('Copyright 2016 TrueSoftware B.V') === -1) {
            contents = header + "\n\n" + contents;
            fs.writeFileSync(fname, contents);
            console.log('-- Updated ' + fname);
        }
    });
    console.log('-- Done\n');
}

Builder.prototype.readFiles = function(dir, filter) {
    var me = this,
        results = [];
    filter = filter || function(fname) {
        return true;
    }
    var list = fs.readdirSync(dir)
    list.forEach(function(file) {
        file = dir + '/' + file
        var stat = fs.statSync(file)
        if (stat && stat.isDirectory()) {
            results = results.concat(me.readFiles(file, filter))
        } else {
            if (filter(file) === true) {
                results.push(file)
            }
        }
    })
    return results;
}

Builder.prototype.run = function() {
    console.log("MaterialBlend Framework Builder v1.0\n");
    var me = this,
        argv = require('yargs')
            .command('build', 'Builds MaterialBlend and Tests')
            .command('copyright', 'Adds copyright headers to files')
            .demand(1)
            .help('h')
            .alias('h', 'help')
            .epilog('Copyright 2016 TrueSoftware B.V.')
            .argv;

    var command = argv._[0];
    if (command === 'build') {
        me.buildFramework(function() {
            console.log('-- Done.')
        })
    } else if (command === 'copyright') {
        me.copyrightFiles();
    }

}

var builder = new Builder();
builder.run();<|endoftext|>


<commit_before>import PDFDocument from 'pdfkit'
import * as svgson from 'svgson'
import archiver from 'archiver'
import svgtojs from '@nrk/svg-to-js'
import pkg from '../package.json'
import fs from 'fs'

function build () {
  const svgFiles = fs.readdirSync('lib').filter((file) => file.endsWith('.svg'))
  const docFiles = ['readme.md', 'lib/readme.md']
  const svgZipper = archiver('zip')
  const pdfZipper = archiver('zip')
  const icons = svgtojs({
    input: 'lib/',
    banner: `@nrk/core-icons v${pkg.version}`,
    scale: 16,
    cjs: 'core-icons.js',
    esm: 'core-icons.mjs',
    dts: 'core-icons.d.ts',
    cjsx: 'jsx/core-icons.js',
    esmx: 'jsx/core-icons.mjs',
    dtsx: 'jsx/core-icons.d.ts'
  })

  fs.writeFileSync('lib/core-icons.rss', rss())
  fs.writeFileSync('lib/core-icons.min.js', icons.iife)
  fs.writeFileSync('lib/core-icons.js', icons.iife)

  for (const file of svgFiles) {
    svgtopdf(`lib/${file}`)
  }
  for (const file of docFiles) {
    const readme = String(fs.readFileSync(file))
    fs.writeFileSync(file, readme.replace(/\/major\/\d+/, `/major/${pkg.version.match(/\d+/)}`))
  }

  svgZipper.pipe(fs.createWriteStream('lib/core-icons-svg.zip'))
  svgZipper.glob('lib/*.svg')
  svgZipper.finalize()
  pdfZipper.pipe(fs.createWriteStream('lib/core-icons-pdf.zip'))
  pdfZipper.glob('lib/*.pdf')
  pdfZipper.finalize()
}

function svgtopdf (el, options, pdf) {
  if (typeof el === 'string') {
    const svg = svgson.parseSync(fs.readFileSync(el, 'utf-8'))
    const [, , width, height] = svg.attributes.viewBox.split(' ').map(Number)
    const scale = 24 / Math.min(width, height)
    const pdfdoc = new PDFDocument({ size: [width * scale, height * scale] })
    pdfdoc.scale(scale)
    pdfdoc.pipe(fs.createWriteStream(el.replace('svg', 'pdf')))
    svgtopdf(svg, { fill: '#000' }, pdfdoc)
    pdfdoc.end()
  } else {
    for (const node of el.children) {
      const fillr = (node.attributes['fill-rule'] || 'nonzero').replace(/-*(zero|odd)$/, '-$1')
      const color = (val) => String(val).replace(/currentColor/i, options.color).replace(/none/i, '')
      const float = (key) => Number(node.attributes[key]) || 0
      const style = {}

      // Style
      pdf.fillColor(style.fill = color(node.attributes.fill || options.fill || options.color))
      pdf.strokeColor(style.stroke = color(node.attributes.stroke || options.stroke || 'none'))
      pdf.lineWidth(style.lineWidth = Number(node.attributes['stroke-width']) || options.lineWidth || 1)
      pdf.lineJoin(style.lineJoin = node.attributes['stroke-linejoin'] || options.lineJoin || 'miter')
      pdf.lineCap(style.lineCap = node.attributes['stroke-linecap'] || options.lineCap || 'butt')

      // Draw
      switch (node.name) {
        case 'g': svgtopdf(node, style, pdf); break
        case 'path': pdf.path(node.attributes.d); break
        case 'line': pdf.moveTo(float('x1'), float('y1')).lineTo(float('x2'), float('y2')); break
        case 'rect': pdf.roundedRect(float('x'), float('y'), float('width'), float('height'), float('rx') || float('ry')); break
        case 'ellipse': pdf.ellipse(float('cx'), float('cy'), float('rx'), float('ry') || float('rx')); break
        case 'circle': pdf.circle(float('cx'), float('cy'), float('r')); break
        case 'polygon': pdf.polygon(node.attributes.points); break
        default: console.log(`Unsupported shape: ${node.name}`)
      }

      // Paint
      if (style.stroke && style.fill) pdf.fillAndStroke(fillr, style.stroke)
      else if (style.stroke) pdf.stroke(style.stroke)
      else if (style.fill) pdf.fill(fillr)
    }
  }
}

function rss () {
  const fullName = 'Core Icons'
  const fileName = 'core-icons'
  const date = new Date(fs.statSync('lib/core-icons.sketch').mtime)
  return `
    <?xml version="1.0" encoding="UTF-8"?>
      <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle">
        <channel>
          <title>${fullName}</title>
          <description>${fullName}</description>
          <image>
            <url></url>
            <title>${fullName}</title>
          </image>
          <generator>Sketch</generator>
          <item>
            <title>${fullName}</title>
            <pubDate>${date.toUTCString()}</pubDate>
            <enclosure url="https://static.nrk.no/${fileName}/latest/${fileName}.sketch" type="application/octet-stream" sparkle:version="${date.getTime()}"/>
          </item>
        </channel>
      </rss>
  `
}

build()
console.log('Build successful')
<commit_msg>build!: Remove generation of rss-feed for sketch<commit_after>import PDFDocument from 'pdfkit'
import * as svgson from 'svgson'
import archiver from 'archiver'
import svgtojs from '@nrk/svg-to-js'
import pkg from '../package.json'
import fs from 'fs'

function build () {
  const svgFiles = fs.readdirSync('lib').filter((file) => file.endsWith('.svg'))
  const docFiles = ['readme.md', 'lib/readme.md']
  const svgZipper = archiver('zip')
  const pdfZipper = archiver('zip')
  const icons = svgtojs({
    input: 'lib/',
    banner: `@nrk/core-icons v${pkg.version}`,
    scale: 16,
    cjs: 'core-icons.js',
    esm: 'core-icons.mjs',
    dts: 'core-icons.d.ts',
    cjsx: 'jsx/core-icons.js',
    esmx: 'jsx/core-icons.mjs',
    dtsx: 'jsx/core-icons.d.ts'
  })

  fs.writeFileSync('lib/core-icons.min.js', icons.iife)
  fs.writeFileSync('lib/core-icons.js', icons.iife)

  for (const file of svgFiles) {
    svgtopdf(`lib/${file}`)
  }
  for (const file of docFiles) {
    const readme = String(fs.readFileSync(file))
    fs.writeFileSync(file, readme.replace(/\/major\/\d+/, `/major/${pkg.version.match(/\d+/)}`))
  }

  svgZipper.pipe(fs.createWriteStream('lib/core-icons-svg.zip'))
  svgZipper.glob('lib/*.svg')
  svgZipper.finalize()
  pdfZipper.pipe(fs.createWriteStream('lib/core-icons-pdf.zip'))
  pdfZipper.glob('lib/*.pdf')
  pdfZipper.finalize()
}

function svgtopdf (el, options, pdf) {
  if (typeof el === 'string') {
    const svg = svgson.parseSync(fs.readFileSync(el, 'utf-8'))
    const [, , width, height] = svg.attributes.viewBox.split(' ').map(Number)
    const scale = 24 / Math.min(width, height)
    const pdfdoc = new PDFDocument({ size: [width * scale, height * scale] })
    pdfdoc.scale(scale)
    pdfdoc.pipe(fs.createWriteStream(el.replace('svg', 'pdf')))
    svgtopdf(svg, { fill: '#000' }, pdfdoc)
    pdfdoc.end()
  } else {
    for (const node of el.children) {
      const fillr = (node.attributes['fill-rule'] || 'nonzero').replace(/-*(zero|odd)$/, '-$1')
      const color = (val) => String(val).replace(/currentColor/i, options.color).replace(/none/i, '')
      const float = (key) => Number(node.attributes[key]) || 0
      const style = {}

      // Style
      pdf.fillColor(style.fill = color(node.attributes.fill || options.fill || options.color))
      pdf.strokeColor(style.stroke = color(node.attributes.stroke || options.stroke || 'none'))
      pdf.lineWidth(style.lineWidth = Number(node.attributes['stroke-width']) || options.lineWidth || 1)
      pdf.lineJoin(style.lineJoin = node.attributes['stroke-linejoin'] || options.lineJoin || 'miter')
      pdf.lineCap(style.lineCap = node.attributes['stroke-linecap'] || options.lineCap || 'butt')

      // Draw
      switch (node.name) {
        case 'g': svgtopdf(node, style, pdf); break
        case 'path': pdf.path(node.attributes.d); break
        case 'line': pdf.moveTo(float('x1'), float('y1')).lineTo(float('x2'), float('y2')); break
        case 'rect': pdf.roundedRect(float('x'), float('y'), float('width'), float('height'), float('rx') || float('ry')); break
        case 'ellipse': pdf.ellipse(float('cx'), float('cy'), float('rx'), float('ry') || float('rx')); break
        case 'circle': pdf.circle(float('cx'), float('cy'), float('r')); break
        case 'polygon': pdf.polygon(node.attributes.points); break
        default: console.log(`Unsupported shape: ${node.name}`)
      }

      // Paint
      if (style.stroke && style.fill) pdf.fillAndStroke(fillr, style.stroke)
      else if (style.stroke) pdf.stroke(style.stroke)
      else if (style.fill) pdf.fill(fillr)
    }
  }
}

build()
console.log('Build successful')
<|endoftext|>


<commit_before>var recording = false;

$(function () {
    // Call one time record to get the user agreement for using the microphone
    Fr.voice.record(false);
    Fr.voice.pause();
    Fr.voice.recorder.clear();
});

$(document).ready(function () {

    $("#record").click(function () {
            var $recordingButton = $(".btn-circle");

            if (!recording) {
                $recordingButton.css('background-color', '#FF7F50').addClass("recording");
                recording = true;
                Fr.voice.resume();
            } else {
                $recordingButton.css('background-color', '#e6e6e6').removeClass("recording").hide();
                $("#mainDiv").addClass("loader");
                recording = false;
                Fr.voice.pause();
                Fr.voice.export(function (blob) {

                    var payload = {"payload": blob};
                    $.ajax({
                        //url: 'https://speech.googleapis.com/v1/speech:recognize?key=API_KEY',
                        url: 'https://openwhisk.ng.bluemix.net/api/v1/web/Hochschule_Test/default/Router.http',
                        //url: 'https://openwhisk.ng.bluemix.net/api/v1/web/Hochschule_Test/default/speechToText.http',
                        //url : 'https://openwhisk.ng.bluemix.net/api/v1/web/kuar1013_kuar1013-Sued/default/speech-to-text.http',
                        type: 'POST',
                        data: JSON.stringify(payload),
                        /* Example object for Google Cloud Speech Service
                         {
                         "config": {
                         "encoding": "LINEAR16",
                         "sampleRateHertz": 16000,
                         "languageCode": "en-US"
                         },
                         "audio": {
                         "content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-audio-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
                         }
                         }*/
                        contentType: "application/json",
                        processData: false,
                        success: function (data) {
                            console.log(data);
                            $("#mainDiv").removeClass("loader");
                            $recordingButton.show();
                            var obj = JSON.parse(data);
                            //obj = JSON.stringify(obj.payload);
                            console.log("Data: " + data);
                            $('.tts').attr('src', "data:audio/ogg;base64," + obj.payload.toString());
                            $('.stt').html(obj.text.toString());

                        },
                        error: function (err) {
                            console.log(err);
                            $("#mainDiv").removeClass("loader");
                            $recordingButton.show();
                            $('.stt').html(obj.text.toString());
                        }
                    });
                    console.log(blob);
                    /* var audio = document.createTextNode('audio');
                     audio.src = base64;
                     audio.controls = true;
                     audio.style.display = 'block';
                     document.appendChild(audio),
                     audio.play(); */

                }, "base64");
                Fr.voice.recorder.clear();
            }
        }
    )

});

<commit_msg>streaming working + new design<commit_after>var recording = false;

$(function () {
    // Call one time record to get the user agreement for using the microphone
    Fr.voice.record(false);
    Fr.voice.pause();
    Fr.voice.recorder.clear();
});

$(document).ready(function () {

    $("#record").click(function () {
            var $recordingButton = $(".btn-circle");

           if (!recording) {
                $recordingButton.css('background-color', '#FF7F50').addClass("recording");
                recording = true;
                Fr.voice.resume();
            } else {
                $recordingButton.css('background-color', '#e6e6e6').removeClass("recording").hide();
                $("#mainDiv").addClass("loader");
                recording = false;
                Fr.voice.pause();
                Fr.voice.export(function (blob) {

                    var payload = {"payload": blob};
                    $.ajax({
                        //url: 'https://speech.googleapis.com/v1/speech:recognize?key=API_KEY',
                        url: 'https://openwhisk.ng.bluemix.net/api/v1/web/Hochschule_Test/default/Router.http',
                        //url: 'https://openwhisk.ng.bluemix.net/api/v1/web/Hochschule_Test/default/speechToText.http',
                        //url : 'https://openwhisk.ng.bluemix.net/api/v1/web/kuar1013_kuar1013-Sued/default/speech-to-text.http',
                        type: 'POST',
                        data: JSON.stringify(payload),
                        /* Example object for Google Cloud Speech Service
                         {
                         "config": {
                         "encoding": "LINEAR16",
                         "sampleRateHertz": 16000,
                         "languageCode": "en-US"
                         },
                         "audio": {
                         "content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-audio-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
                         }
                         }*/
                        contentType: "application/json",
                        processData: false,
                        success: function (data) {
                            console.log(data);
                            $("#mainDiv").removeClass("loader");
                            $recordingButton.show();
                            var obj = JSON.parse(data);
                            //obj = JSON.stringify(obj.payload);
                            console.log("Data: " + data);
                            $('.tts').attr('src', "data:audio/ogg;base64," + obj.payload.toString());
                            $('.stt').html(obj.text.toString());

                        },
                        error: function (err) {
                            console.log(err);
                            $("#mainDiv").removeClass("loader");
                            $recordingButton.show();
                            $('.stt').html(obj.text.toString());
                        }
                    });
                    console.log(blob);
                    /* var audio = document.createTextNode('audio');
                     audio.src = base64;
                     audio.controls = true;
                     audio.style.display = 'block';
                     document.appendChild(audio),
                     audio.play(); */

                }, "base64");
                Fr.voice.recorder.clear();
            }
        }
    )

});

<|endoftext|>


<commit_before>(function () {
    'use strict';

    const PATH = 'modules/ui/directives/transactionInfo/types';
    const ds = require('data-service');
    const { Money } = require('@waves/data-entities');

    /**
     * @param Base
     * @param $filter
     * @param explorerLinks
     * @param {BaseAssetService} baseAssetService
     * @param dexService
     * @param waves
     * @return {BaseTxInfo}
     */
    const factory = function (Base, $filter, explorerLinks, baseAssetService, dexService, waves) {

        class BaseTxInfo extends Base {

            transaction = null;
            $scope = null;
            txId = null;
            templatePostfix = '';
            needShowMirror = true;

            constructor($scope) {
                super();

                this.$scope = $scope;
            }

            $postLink() {
                if (!this.signable) {
                    throw new Error('Has no signable!');
                }

                const $scope = this.$scope;

                const transaction = waves.node.transactions.createTransaction(this.signable.getTxData());
                this.transaction = transaction;

                this.signable.getId().then(id => {
                    this.txId = id;
                });

                this.templateUrl = `${PATH}/${transaction.templateType}${this.templatePostfix}.html`;
                this.datetime = $filter('date')(transaction.timestamp, 'dd.MM.yyyy, HH:mm');
                this.shownAddress = transaction.shownAddress;
                this.typeName = transaction.typeName;
                this.numberOfRecipients = transaction.numberOfRecipients;
                this.isScam = !!WavesApp.scam[this.transaction.assetId];
                this.explorerLink = explorerLinks.getTxLink(transaction.id);
                if (transaction.amount || (transaction.lease && transaction.lease.amount)) {
                    const amount = transaction.amount || transaction.lease.amount;
                    this.needShowMirror = amount.asset.id !== baseAssetService.getBaseAssetId();
                    baseAssetService.convertToBaseAsset(amount)
                        .then((baseMoney) => {
                            this.mirrorBalance = baseMoney;
                            $scope.$digest();
                        });
                }

                const TYPES = waves.node.transactions.TYPES;

                if (this.typeName === TYPES.BURN || this.typeName === TYPES.ISSUE || this.typeName === TYPES.REISSUE) {
                    this._tokens();
                }

                if (this.typeName === TYPES.EXCHANGE_BUY || this.typeName === TYPES.EXCHANGE_SELL) {
                    this.totalPrice = dexService.getTotalPrice(this.transaction.amount, this.transaction.price);
                    if (this.typeName === TYPES.EXCHANGE_BUY) {
                        this.calculatedFee = this.transaction.buyMatcherFee;
                    } else {
                        this.calculatedFee = this.transaction.sellMatcherFee;
                    }
                } else if (this.typeName === TYPES.SPONSORSHIP_FEE) {
                    this.calculatedFee = null;
                    ds.api.assets.get('WAVES').then((asset) => {
                        this.calculatedFee = new Money(100000, asset); // TODO hardcode fee
                        $scope.$digest();
                    });
                } else if (this.typeName === TYPES.SPONSORSHIP_START) {
                    this.isSponsoredFee = true;
                    this.calculatedFee = this.transaction.fee;
                } else {
                    this.calculatedFee = this.transaction.fee;
                }
            }

            _tokens() {
                this.name = tsUtils.get(this.transaction, 'amount.asset.name') ||
                    tsUtils.get(this.transaction, 'quantity.asset.name') ||
                    this.transaction.name;
                this.amount = (tsUtils.get(this.transaction, 'amount') ||
                    tsUtils.get(this.transaction, 'quantity')).toFormat();
                this.quantity = this.transaction.quantity &&
                    this.transaction.quantity.div(Math.pow(10, this.transaction.precision)) ||
                    this.transaction.amount;
                this.precision = this.transaction.precision ||
                    (this.quantity.asset ? this.quantity.asset.precision : 0);
            }

        }

        return BaseTxInfo;
    };

    factory.$input = ['Base', '$filter', 'explorerLinks', 'baseAssetService', 'dexService', 'waves'];

    angular.module('app.ui').factory('BaseTxInfo', factory);
})();
<commit_msg>CLIENT-1301: fix tx id<commit_after>(function () {
    'use strict';

    const PATH = 'modules/ui/directives/transactionInfo/types';
    const ds = require('data-service');
    const { Money } = require('@waves/data-entities');

    /**
     * @param Base
     * @param $filter
     * @param explorerLinks
     * @param {BaseAssetService} baseAssetService
     * @param dexService
     * @param waves
     * @return {BaseTxInfo}
     */
    const factory = function (Base, $filter, explorerLinks, baseAssetService, dexService, waves) {

        class BaseTxInfo extends Base {

            transaction = null;
            /**
             * @type {$rootScope.Scope}
             */
            $scope = null;
            txId = null;
            templatePostfix = '';
            needShowMirror = true;

            constructor($scope) {
                super();

                this.$scope = $scope;
            }

            $postLink() {
                if (!this.signable) {
                    throw new Error('Has no signable!');
                }

                const $scope = this.$scope;

                const transaction = waves.node.transactions.createTransaction(this.signable.getTxData());
                this.transaction = transaction;

                this.signable.getId().then(id => {
                    this.txId = id;
                    this.$scope.$apply();
                });

                this.templateUrl = `${PATH}/${transaction.templateType}${this.templatePostfix}.html`;
                this.datetime = $filter('date')(transaction.timestamp, 'dd.MM.yyyy, HH:mm');
                this.shownAddress = transaction.shownAddress;
                this.typeName = transaction.typeName;
                this.numberOfRecipients = transaction.numberOfRecipients;
                this.isScam = !!WavesApp.scam[this.transaction.assetId];
                this.explorerLink = explorerLinks.getTxLink(transaction.id);
                if (transaction.amount || (transaction.lease && transaction.lease.amount)) {
                    const amount = transaction.amount || transaction.lease.amount;
                    this.needShowMirror = amount.asset.id !== baseAssetService.getBaseAssetId();
                    baseAssetService.convertToBaseAsset(amount)
                        .then((baseMoney) => {
                            this.mirrorBalance = baseMoney;
                            $scope.$digest();
                        });
                }

                const TYPES = waves.node.transactions.TYPES;

                if (this.typeName === TYPES.BURN || this.typeName === TYPES.ISSUE || this.typeName === TYPES.REISSUE) {
                    this._tokens();
                }

                if (this.typeName === TYPES.EXCHANGE_BUY || this.typeName === TYPES.EXCHANGE_SELL) {
                    this.totalPrice = dexService.getTotalPrice(this.transaction.amount, this.transaction.price);
                    if (this.typeName === TYPES.EXCHANGE_BUY) {
                        this.calculatedFee = this.transaction.buyMatcherFee;
                    } else {
                        this.calculatedFee = this.transaction.sellMatcherFee;
                    }
                } else if (this.typeName === TYPES.SPONSORSHIP_FEE) {
                    this.calculatedFee = null;
                    ds.api.assets.get('WAVES').then((asset) => {
                        this.calculatedFee = new Money(100000, asset); // TODO hardcode fee
                        $scope.$digest();
                    });
                } else if (this.typeName === TYPES.SPONSORSHIP_START) {
                    this.isSponsoredFee = true;
                    this.calculatedFee = this.transaction.fee;
                } else {
                    this.calculatedFee = this.transaction.fee;
                }
            }

            _tokens() {
                this.name = tsUtils.get(this.transaction, 'amount.asset.name') ||
                    tsUtils.get(this.transaction, 'quantity.asset.name') ||
                    this.transaction.name;
                this.amount = (tsUtils.get(this.transaction, 'amount') ||
                    tsUtils.get(this.transaction, 'quantity')).toFormat();
                this.quantity = this.transaction.quantity &&
                    this.transaction.quantity.div(Math.pow(10, this.transaction.precision)) ||
                    this.transaction.amount;
                this.precision = this.transaction.precision ||
                    (this.quantity.asset ? this.quantity.asset.precision : 0);
            }

        }

        return BaseTxInfo;
    };

    factory.$input = ['Base', '$filter', 'explorerLinks', 'baseAssetService', 'dexService', 'waves'];

    angular.module('app.ui').factory('BaseTxInfo', factory);
})();
<|endoftext|>