<commit_before>define(['xaml!sprd/view/svg/PatternRenderer', "sprd/entity/Size", 'js/core/Bus', 'underscore'], function(PatternRenderer, Size, Bus, _) {

    return PatternRenderer.inherit("sprd.view.svg.BendingTextConfigurationRendererClass", {

        defaults: {
            tagName: "g",
            componentClass: "bendingText-configuration",
            productViewer: null,
            configurationViewer: null,
            configuration: null,

            textPath: null,
            path: null
        },

        $classAttributes: ['textPath', 'path', 'text', 'oldSize'],

        inject: {
            bus: Bus
        },

        ctor: function() {
            this.callBase();
            this.bind("dom:add", this.recalculateSize, this);

            this.bind("configuration", "recalculateSize", this.recalculateSize, this);

            this.bind("configuration", "change:font", this.loadFont, this);

            var resetMainConfigurationViewer = function() {
                var configuration = this.$.configuration;
                if (configuration) {
                    configuration.mainConfigurationRenderer = null;
                }
            };

            this.bind("productViewer.product", ["configurations", "reset"], resetMainConfigurationViewer, this);
            this.bind("configuration", "change:printArea", resetMainConfigurationViewer, this);

            var timer = null;
            this.bind("configuration", "change:angle", function() {
                var path = this.$.path;

                if (timer) {
                    clearTimeout(timer);
                }

                if (path) {
                    path.set("selected", true);

                    timer = setTimeout(function() {
                        path.set("selected", false);
                    }, 1000);
                }
            }, this);
        },

        // _initializationComplete: function() {
        //     this.callBase();
        //     // this.bind("configuration", "recalculateSize", this.balanceConfiguration, this);
        // },

        loadFont: function() {
            var svgRoot = this.getSvgRoot(),
                font = this.get("configuration.font"),
                extension = this.$stage.$browser.isIOS ? "svg#font" : "woff",
                self = this;

            if (!font || !svgRoot) {
                return;
            }

            svgRoot.fontManager.loadExternalFont(font.getUniqueFontName(), this.$.imageService.fontUrl(font, extension), function() {
                self.recalculateSize();
            });
        },

        recalculateSize: function() {
            var textPath = this.$.textPath;
            var path = this.$.path;
            if (textPath && textPath.$el && path && path.$el) {

                var configuration = this.$.configuration;
                if (configuration && configuration.mainConfigurationRenderer && configuration.mainConfigurationRenderer != this) {
                    return;
                }

                //path fix for IE
                path.set("d", configuration.$.textPath || "");
                var text = this.$.text;
                text.set("dy", configuration.$.dy);

                configuration.mainConfigurationRenderer = this;

                var textPathRect = textPath.$parent.$el.getBBox();
                var pathRect = path.$el.getBBox();

                configuration.set({
                    textPathOffsetX: 0,
                    textPathOffsetY: 0
                });

                var textBBox = this.$.text.$el.getBBox();

                var _size = configuration.$._size;
                this.balanceConfiguration(_size.$.width, textPathRect.width);
                _size.set({
                    width: textPathRect.width,
                    height: textPathRect.height
                });

                configuration.set({
                    textPathOffsetX: (textPathRect.width - pathRect.width) * 0.5,
                    textPathOffsetY: -textBBox.y
                });

                configuration._setError(configuration._validateTransform({
                    validateHardBoundary: true
                }));

                configuration.trigger("sizeChanged");
            }
        },

        balanceConfiguration: function(oldWidth, newWidth) {
            var configuration = this.$.configuration;
            if (configuration && oldWidth && newWidth) {
                var offset = configuration.$.offset;
                configuration.$.offset.set({
                    x: offset.$.x + ((oldWidth - newWidth) || 0) / 2
                });
            }
        },

        getTextPathSvg: function(options) {
            options = options || {};

            var size = this.$.configuration.$._size.$,
                svgNamespace = 'http://www.w3.org/2000/svg',
                svg = document.createElementNS(svgNamespace, "svg");
            assetContainer = this.$el.cloneNode(true);

            svg.setAttribute("viewBox", [0, 0, size.width, size.height].join(" "));

            //Remove redundant elements.
            this.removeElementsBlackListTags(assetContainer, ["path", "text"]);

            // Remove styling.
            var attrBlacklist = ["style", "class", "isSpecialFlex", "maskId", "largeSize", "filter"];
            this.removeAttributesOnDescendants(assetContainer, attrBlacklist);
            svg.appendChild(assetContainer);

            var w = size.width,
                h = size.height;

            if (options.width) {
                svg.setAttribute("width", options.width + "px");
                svg.setAttribute("height", (parseInt(options.width * h / w) + 1) + "px");
            }

            if (options.fill) {
                svg.setAttribute("fill", options.fill);
            }

            svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
            return svg;
        },

        removeElementsBlackListTags: function(node, tagList) {
            var children = node.childNodes,
                toBeRemovedChildren = [];
            for (var i = 0; i < children.length; i++) {
                var child = children.item(i);
                if (tagList.indexOf(child.localName) === -1) {
                    toBeRemovedChildren.push(child);
                }
            }

            _.each(toBeRemovedChildren, function(child) {
                child.parentNode.removeChild(child);
            })
        },

        removeAttributesOnDescendants: function(node, attributeNames) {
            if (node.nodeType === 1) {
                _.each(attributeNames, function(attributeName) {
                    node.removeAttribute(attributeName);
                });
            }

            var children = node.childNodes;
            for (var i = 0; i < children.length; i++) {
                this.removeAttributesOnDescendants(children.item(i), attributeNames);
            }
        },

        getPrintColor: function() {
            var configuration = this.$.configuration,
                printColors = configuration.$.printColors,
                printColor = null;

            if (printColors && printColors.size() && !this.isSpecialFlex() && !this.isFlock()) {
                printColor = printColors.at(0).toHexString();
            }

            return printColor;
        }.on(["configuration.printColors", "reset"]).onChange("configuration.printType"),

        bus_StageRendered: function() {
            this.loadFont();
        }.bus("Stage.Rendered")
    });
});<commit_msg>ViewBox sometimes too small cutting some letters away<commit_after>define(['xaml!sprd/view/svg/PatternRenderer', "sprd/entity/Size", 'js/core/Bus', 'underscore'], function(PatternRenderer, Size, Bus, _) {

    return PatternRenderer.inherit("sprd.view.svg.BendingTextConfigurationRendererClass", {

        defaults: {
            tagName: "g",
            componentClass: "bendingText-configuration",
            productViewer: null,
            configurationViewer: null,
            configuration: null,

            textPath: null,
            path: null
        },

        $classAttributes: ['textPath', 'path', 'text', 'oldSize'],

        inject: {
            bus: Bus
        },

        ctor: function() {
            this.callBase();
            this.bind("dom:add", this.recalculateSize, this);

            this.bind("configuration", "recalculateSize", this.recalculateSize, this);

            this.bind("configuration", "change:font", this.loadFont, this);

            var resetMainConfigurationViewer = function() {
                var configuration = this.$.configuration;
                if (configuration) {
                    configuration.mainConfigurationRenderer = null;
                }
            };

            this.bind("productViewer.product", ["configurations", "reset"], resetMainConfigurationViewer, this);
            this.bind("configuration", "change:printArea", resetMainConfigurationViewer, this);

            var timer = null;
            this.bind("configuration", "change:angle", function() {
                var path = this.$.path;

                if (timer) {
                    clearTimeout(timer);
                }

                if (path) {
                    path.set("selected", true);

                    timer = setTimeout(function() {
                        path.set("selected", false);
                    }, 1000);
                }
            }, this);
        },

        // _initializationComplete: function() {
        //     this.callBase();
        //     // this.bind("configuration", "recalculateSize", this.balanceConfiguration, this);
        // },

        loadFont: function() {
            var svgRoot = this.getSvgRoot(),
                font = this.get("configuration.font"),
                extension = this.$stage.$browser.isIOS ? "svg#font" : "woff",
                self = this;

            if (!font || !svgRoot) {
                return;
            }

            svgRoot.fontManager.loadExternalFont(font.getUniqueFontName(), this.$.imageService.fontUrl(font, extension), function() {
                self.recalculateSize();
            });
        },

        recalculateSize: function() {
            var textPath = this.$.textPath;
            var path = this.$.path;
            if (textPath && textPath.$el && path && path.$el) {

                var configuration = this.$.configuration;
                if (configuration && configuration.mainConfigurationRenderer && configuration.mainConfigurationRenderer != this) {
                    return;
                }

                //path fix for IE
                path.set("d", configuration.$.textPath || "");
                var text = this.$.text;
                text.set("dy", configuration.$.dy);

                configuration.mainConfigurationRenderer = this;

                var textPathRect = textPath.$parent.$el.getBBox();
                var pathRect = path.$el.getBBox();

                configuration.set({
                    textPathOffsetX: 0,
                    textPathOffsetY: 0
                });

                var textBBox = this.$.text.$el.getBBox();

                var _size = configuration.$._size;
                this.balanceConfiguration(_size.$.width, textPathRect.width);
                _size.set({
                    width: textPathRect.width,
                    height: textPathRect.height
                });

                configuration.set({
                    textPathOffsetX: (textPathRect.width - pathRect.width) * 0.5,
                    textPathOffsetY: -textBBox.y
                });

                configuration._setError(configuration._validateTransform({
                    validateHardBoundary: true
                }));

                configuration.trigger("sizeChanged");
            }
        },

        balanceConfiguration: function(oldWidth, newWidth) {
            var configuration = this.$.configuration;
            if (configuration && oldWidth && newWidth) {
                var offset = configuration.$.offset;
                configuration.$.offset.set({
                    x: offset.$.x + ((oldWidth - newWidth) || 0) / 2
                });
            }
        },

        getTextPathSvg: function(options) {
            options = options || {};

            var textBbox = this.$.text.$el.getBBox(),
                svgNamespace = 'http://www.w3.org/2000/svg',
                svg = document.createElementNS(svgNamespace, "svg");
            assetContainer = this.$el.cloneNode(true);

            svg.setAttribute("viewBox", [textBbox.x, textBbox.y, textBbox.width, textBbox.height].join(" "));
            //Remove redundant elements.
            this.removeElementsBlackListTags(assetContainer, ["path", "text"]);

            // Remove attributes.
            var attrBlacklist = ["style", "class", "isSpecialFlex", "maskId", "largeSize", "filter"];
            this.removeAttributesOnDescendants(assetContainer, attrBlacklist);
            svg.appendChild(assetContainer);

            var w = textBbox.width,
                h = textBbox.height;

            if (options.width) {
                svg.setAttribute("width", options.width + "px");
                svg.setAttribute("height", (parseInt(options.width * h / w) + 1) + "px");
            }

            if (options.fill) {
                svg.setAttribute("fill", options.fill);
            }

            svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
            return svg;
        },

        removeElementsBlackListTags: function(node, tagList) {
            var children = node.childNodes,
                toBeRemovedChildren = [];
            for (var i = 0; i < children.length; i++) {
                var child = children.item(i);
                if (tagList.indexOf(child.localName) === -1) {
                    toBeRemovedChildren.push(child);
                }
            }

            _.each(toBeRemovedChildren, function(child) {
                child.parentNode.removeChild(child);
            })
        },

        removeAttributesOnDescendants: function(node, attributeNames) {
            if (node.nodeType === 1) {
                _.each(attributeNames, function(attributeName) {
                    node.removeAttribute(attributeName);
                });
            }

            var children = node.childNodes;
            for (var i = 0; i < children.length; i++) {
                this.removeAttributesOnDescendants(children.item(i), attributeNames);
            }
        },

        getPrintColor: function() {
            var configuration = this.$.configuration,
                printColors = configuration.$.printColors,
                printColor = null;

            if (printColors && printColors.size() && !this.isSpecialFlex() && !this.isFlock()) {
                printColor = printColors.at(0).toHexString();
            }

            return printColor;
        }.on(["configuration.printColors", "reset"]).onChange("configuration.printType"),

        bus_StageRendered: function() {
            this.loadFont();
        }.bus("Stage.Rendered")
    });
});<|endoftext|>


<commit_before>var express = require('express');
var app = express();

require('./config/middleware.js')(app, express);
require('./config/routes.js')(app, express);

// Uncomment for testing server routes
// require('./config/worker.js').productRankByState('NY');
// require('./config/worker.js').birthsInRange('Bank of America', 2014);
require('./config/worker.js').stateByProduct(0, 'Mortgage', 2014);

var port = process.env.PORT || 3333;
var server = app.listen(port, function() {
  console.log('Server listening on port: ' + port);
  console.log(process.env.PORT, typeof ''+process.env.KEY);
});

module.exports = {
  app: app
};
<commit_msg>(refactor) Clear up server logs<commit_after>var express = require('express');
var app = express();

require('./config/middleware.js')(app, express);
require('./config/routes.js')(app, express);

// Uncomment for testing server routes
// require('./config/worker.js').productRankByState('NY');
// require('./config/worker.js').birthsInRange('Bank of America', 2014);
// require('./config/worker.js').stateByProduct(0, 'Mortgage', 2014);

var port = process.env.PORT || 3333;
var server = app.listen(port, function() {
  console.log('Server listening on port: ' + port);
  console.log('Census API Key:', process.env.KEY);
});

module.exports = {
  app: app
};
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import styled from 'styled-components';
import { push } from 'react-router-redux';

import BasicButton from 'component/basic-button';
import CountAction from 'action/count';

export class Index extends React.PureComponent {
  static propTypes = {
    className: PropTypes.string,
    count: PropTypes.number,
    add: PropTypes.func,
    navigate: PropTypes.func,
  };

  static defaultProps = {
    count: 0,
  };

  render() {
    const { className, count } = this.props;
    const { add, navigate } = this.props;
    return (

        <BasicButton
          className="statusButton"
          func={add}
          text={count.toString()}
        />
        <BasicButton
          className="navButton"
          func={() => navigate('/second')}
          text="To Second Page"
        />

    );
  }
}

const mapStateToProps = state => ({
  count: state.get('count'),
});

const mapDispatchToProps = dispatch => ({
  add: () => dispatch(CountAction.add),
  navigate: location => dispatch(push(location)),
});

const component = styled(Index)`
  width: 360px;
  margin: 240px auto;
  font-family: 'Helvetica';
  line-height: 30px;

  .statusButton {
    background: lightblue;
    color: white;
  }
`;

export default connect(mapStateToProps, mapDispatchToProps)(component);
<commit_msg>fix action bound<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import styled from 'styled-components';
import { push } from 'react-router-redux';

import BasicButton from 'component/basic-button';
import CountAction from 'action/count';

export class Index extends React.PureComponent {
  static propTypes = {
    className: PropTypes.string,
    count: PropTypes.number,
    add: PropTypes.func,
    navigate: PropTypes.func,
  };

  static defaultProps = {
    count: 0,
  };

  render() {
    const { className, count } = this.props;
    const { add, navigate } = this.props;
    return (

        <BasicButton
          className="statusButton"
          func={add}
          text={count.toString()}
        />
        <BasicButton
          className="navButton"
          func={() => navigate('/second')}
          text="To Second Page"
        />

    );
  }
}

const mapStateToProps = state => ({
  count: state.get('count'),
});

const mapDispatchToProps = dispatch => ({
  add: () => dispatch(CountAction.add()),
  navigate: location => dispatch(push(location)),
});

const component = styled(Index)`
  width: 360px;
  margin: 240px auto;
  font-family: 'Helvetica';
  line-height: 30px;

  .statusButton {
    background: lightblue;
    color: white;
  }
`;

export default connect(mapStateToProps, mapDispatchToProps)(component);
<|endoftext|>


<commit_before>/* eslint-env jest */
import { processWidthInput } from '../width_units'

jest.mock('../../streets/data_model', () => {
  return {
    getStreet: () => ({
      units: 1
    })
  }
})
jest.mock('../../users/localization', () => {
  return {
    SETTINGS_UNITS_IMPERIAL: 1,
    SETTINGS_UNITS_METRIC: 2
  }
})

describe('processWidthInput()', () => {
  it('trims leading and trailing whitespace', () => {
    const thing = processWidthInput(' 3.75 ')
    expect(thing).toEqual(3.75)
  })

  it('parses a value (3)', () => {
    const thing = processWidthInput('3')
    expect(thing).toEqual(3)
  })

  it('parses a value with trailing period (3.)', () => {
    const thing = processWidthInput('3.')
    expect(thing).toEqual(3)
  })

  it('parses a decimal with trailing zeroes (3.00)', () => {
    const thing = processWidthInput('3.00')
    expect(thing).toEqual(3)
  })

  it('parses a decimal without units (3.75)', () => {
    const thing = processWidthInput('3.75')
    expect(thing).toEqual(3.75)
  })

  it('parses a decimal with prime symbol (3.75\')', () => {
    const thing = processWidthInput("3.75'")
    expect(thing).toEqual(3.75)
  })

  it('parses a decimal with `ft` unit (3.75 ft)', () => {
    const thing = processWidthInput('3.75 ft')
    expect(thing).toEqual(3.75)
  })

  it('parses a decimal with `ft.` unit (3.75 ft.)', () => {
    const thing = processWidthInput('3.75 ft.')
    expect(thing).toEqual(3.75)
  })

  it('parses a decimal with `ft` unit and no space (3.75ft)', () => {
    const thing = processWidthInput('3.75ft')
    expect(thing).toEqual(3.75)
  })

  it('parses feet and inches with prime and double prime symbols (3\'9")', () => {
    const thing = processWidthInput("3'9\"")
    expect(thing).toEqual(3.75)
  })

  it('parses feet and inches with prime and double prime symbols and hyphen separator (3\'-9")', () => {
    const thing = processWidthInput("3'-9\"")
    expect(thing).toEqual(3.75)
  })

  it('parses feet and inches with prime and hyphen separator, lacking a final double prime symbol (3\'-9)', () => {
    const thing = processWidthInput("3'-9")
    expect(thing).toEqual(3.75)
  })

  it('parses feet and inches with prime and double prime symbols and space separator (3\' 9")', () => {
    const thing = processWidthInput("3' 9\"")
    expect(thing).toEqual(3.75)
  })

  it('parses feet and inches with prime and space separator, lacking a final double prime symbol (3\' 9)', () => {
    const thing = processWidthInput("3' 9")
    expect(thing).toEqual(3.75)
  })

  it('parses feet and inches with support for leading zero (0\'-3")', () => {
    const thing = processWidthInput("0'-3")
    expect(thing).toEqual(0.25)
  })

  it('parses a value with meters unit (3m)', () => {
    const thing = processWidthInput('3m')
    expect(thing).toEqual(10)
  })
})
<commit_msg>Update tests for greater parity with #614<commit_after>/* eslint-env jest */
import { processWidthInput } from '../width_units'

jest.mock('../../streets/data_model', () => {
  return {
    getStreet: () => ({
      units: 1
    })
  }
})
jest.mock('../../users/localization', () => {
  return {
    SETTINGS_UNITS_IMPERIAL: 1,
    SETTINGS_UNITS_METRIC: 2
  }
})

describe('processWidthInput()', () => {
  it('trims leading and trailing whitespace', () => {
    const input = processWidthInput(' 3.75 ')
    expect(input).toEqual(3.75)
  })

  it('parses a value (3)', () => {
    const input = processWidthInput('3')
    expect(input).toEqual(3)
  })

  it('parses a value with trailing period (3.)', () => {
    const input = processWidthInput('3.')
    expect(input).toEqual(3)
  })

  it('parses a value with a prime symbol (3\')', () => {
    const input = processWidthInput('3\'')
    expect(input).toEqual(3)
  })

  it('parses a value with a double-prime symbol (3")', () => {
    const input = processWidthInput('3"')
    expect(input).toEqual(0.25)
  })

  it('parses a decimal with trailing zeroes (3.00)', () => {
    const input = processWidthInput('3.00')
    expect(input).toEqual(3)
  })

  it('parses a decimal without units (3.75)', () => {
    const input = processWidthInput('3.75')
    expect(input).toEqual(3.75)
  })

  it('parses a decimal with prime symbol (3.75\')', () => {
    const input = processWidthInput("3.75'")
    expect(input).toEqual(3.75)
  })

  it('parses a decimal with `ft` unit (3.75 ft)', () => {
    const input = processWidthInput('3.75 ft')
    expect(input).toEqual(3.75)
  })

  it('parses a decimal with `ft.` unit (3.75 ft.)', () => {
    const input = processWidthInput('3.75 ft.')
    expect(input).toEqual(3.75)
  })

  it('parses a decimal with `ft` unit and no space (3.75ft)', () => {
    const input = processWidthInput('3.75ft')
    expect(input).toEqual(3.75)
  })

  it('parses feet and inches with prime and double-prime symbols (3\'9")', () => {
    const input = processWidthInput("3'9\"")
    expect(input).toEqual(3.75)
  })

  it('parses feet and inches with prime symbol, lacking a final double-prime symbol (3\'9)', () => {
    const input = processWidthInput("3'9")
    expect(input).toEqual(3.75)
  })

  it('parses feet and inches with prime and double-prime symbols and hyphen separator (3\'-9")', () => {
    const input = processWidthInput("3'-9\"")
    expect(input).toEqual(3.75)
  })

  it('parses feet and inches with prime and hyphen separator, lacking a final double-prime symbol (3\'-9)', () => {
    const input = processWidthInput("3'-9")
    expect(input).toEqual(3.75)
  })

  it('parses feet and inches with prime and double-prime symbols and space separator (3\' 9")', () => {
    const input = processWidthInput("3' 9\"")
    expect(input).toEqual(3.75)
  })

  it('parses feet and inches with prime and space separator, lacking a final double-prime symbol (3\' 9)', () => {
    const input = processWidthInput("3' 9")
    expect(input).toEqual(3.75)
  })

  it('parses feet and inches with support for leading zero (0\'6")', () => {
    const input = processWidthInput("0'6")
    expect(input).toEqual(0.5)
  })

  it('parses feet and inches with support for leading zero (0\'-3")', () => {
    const input = processWidthInput("0'-3")
    expect(input).toEqual(0.25)
  })

  it('parses a value with meters unit (3m)', () => {
    const input = processWidthInput('3m')
    expect(input).toEqual(10)
  })

  it('parses a decimal value with meters unit (3.0m)', () => {
    const input = processWidthInput('3.0m')
    expect(input).toEqual(10)
  })

  it.skip('todo: parses correctly under different unit preferences')
})
<|endoftext|>


<commit_before>const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');

const auth = require('./service/auth');
const changelogsRoutes = require('./route/changelogs');

// Create app
const app = express();
app.set('etag', false);
app.set('x-powered-by', false);

// Configure middlewares
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Add routes after authentication
app.use(auth.validate);
app.use('/changelogs', changelogsRoutes);

// Map unknown requests to 404
app.use((req, res, next) => {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// Catch all errors
app.use((err, req, res, next) => {
    res.status(err.status || 500);
    res.json({ "message": err.message });
});

app.listen(process.env.PORT || 8080);
<commit_msg>Remove unnecessary quotes from object declaration<commit_after>const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');

const auth = require('./service/auth');
const changelogsRoutes = require('./route/changelogs');

// Create app
const app = express();
app.set('etag', false);
app.set('x-powered-by', false);

// Configure middlewares
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Add routes after authentication
app.use(auth.validate);
app.use('/changelogs', changelogsRoutes);

// Map unknown requests to 404
app.use((req, res, next) => {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// Catch all errors
app.use((err, req, res, next) => {
    res.status(err.status || 500);
    res.json({ message: err.message });
});

app.listen(process.env.PORT || 8080);
<|endoftext|>


<commit_before>/*!
 * ${copyright}
 */

/**
 * @fileOverview Application component to display information on entities from the
 *   V4_GW_SAMPLE_BASIC OData service.
 * @version @version@
 */
sap.ui.define([
	"sap/ui/core/mvc/View",
	"sap/ui/core/sample/common/Component",
	"sap/ui/model/json/JSONModel",
	"sap/ui/model/odata/v4/ODataModel",
	"sap/ui/test/TestUtils",
	"sap/ui/thirdparty/sinon"
], function (View, BaseComponent, JSONModel, ODataModel, TestUtils, sinon) {
	"use strict";

	return BaseComponent.extend("sap.ui.core.sample.odata.v4.SalesOrders.Component", {
		metadata : {
			manifest : "json"
		},

		createContent : function () {
			var bHasOwnProxy = this.proxy !== sap.ui.core.sample.common.Component.prototype.proxy,
				fnProxy = bHasOwnProxy
					? this.proxy
					: TestUtils.proxy,
				oModel = new ODataModel({
					serviceUrl: fnProxy("/sap/opu/local_V4/IWBEP/V4_GW_SAMPLE_BASIC/")
				}),
				bRealOData = TestUtils.isRealOData();

			if (!bHasOwnProxy) {
				TestUtils.setupODataV4Server(sinon.sandbox.create(), {
					"/sap/opu/local_V4/IWBEP/V4_GW_SAMPLE_BASIC/$metadata"
						: {source : "metadata.xml"},
					"/sap/opu/local_V4/IWBEP/V4_GW_SAMPLE_BASIC/BusinessPartnerList?$skip=0&$top=50"
						: {source : "BusinessPartnerList.json"},
					"/sap/opu/local_V4/IWBEP/V4_GW_SAMPLE_BASIC/SalesOrderList?$expand=SO_2_SOITEM(%24expand%3DSOITEM_2_PRODUCT(%24expand%3DPRODUCT_2_BP(%24expand%3DBP_2_CONTACT)))&$skip=0&$top=50"
						: {source : "SalesOrderList.json"},
				}, "sap/ui/core/demokit/sample/odata/v4/SalesOrders/data");
			}

			return sap.ui.view({
				type : sap.ui.core.mvc.ViewType.XML,
				id : "MainView",
				viewName : "sap.ui.core.sample.odata.v4.SalesOrders.Main",
				models : { undefined: oModel,
					ui : new JSONModel({
						bRealOData : bRealOData,
						icon : bRealOData ? "sap-icon://building" : "sap-icon://record",
						iconTooltip : bRealOData ? "real OData service" : "mock OData service"}
				)}
			});
			// TODO: enhance sample application after features are supported
			// - Error Handling; not yet implemented in model
		}
	});
});
<commit_msg>[INTERNAL] sap.ui.core.sample.odata.v4.SalesOrders.Main ESlint Error<commit_after>/*!
 * ${copyright}
 */

/**
 * @fileOverview Application component to display information on entities from the
 *   V4_GW_SAMPLE_BASIC OData service.
 * @version @version@
 */
sap.ui.define([
	"sap/ui/core/mvc/View",
	"sap/ui/core/sample/common/Component",
	"sap/ui/model/json/JSONModel",
	"sap/ui/model/odata/v4/ODataModel",
	"sap/ui/test/TestUtils",
	"sap/ui/thirdparty/sinon"
], function (View, BaseComponent, JSONModel, ODataModel, TestUtils, sinon) {
	"use strict";

	return BaseComponent.extend("sap.ui.core.sample.odata.v4.SalesOrders.Component", {
		metadata : {
			manifest : "json"
		},

		createContent : function () {
			var bHasOwnProxy = this.proxy !== sap.ui.core.sample.common.Component.prototype.proxy,
				fnProxy = bHasOwnProxy
					? this.proxy
					: TestUtils.proxy,
				oModel = new ODataModel({
					serviceUrl: fnProxy("/sap/opu/local_V4/IWBEP/V4_GW_SAMPLE_BASIC/")
				}),
				bRealOData = TestUtils.isRealOData();

			if (!bHasOwnProxy) {
				TestUtils.setupODataV4Server(sinon.sandbox.create(), {
					"/sap/opu/local_V4/IWBEP/V4_GW_SAMPLE_BASIC/$metadata"
						: {source : "metadata.xml"},
					"/sap/opu/local_V4/IWBEP/V4_GW_SAMPLE_BASIC/BusinessPartnerList?$skip=0&$top=50"
						: {source : "BusinessPartnerList.json"},
					"/sap/opu/local_V4/IWBEP/V4_GW_SAMPLE_BASIC/SalesOrderList?$expand=SO_2_SOITEM(%24expand%3DSOITEM_2_PRODUCT(%24expand%3DPRODUCT_2_BP(%24expand%3DBP_2_CONTACT)))&$skip=0&$top=50"
						: {source : "SalesOrderList.json"}
				}, "sap/ui/core/demokit/sample/odata/v4/SalesOrders/data");
			}

			return sap.ui.view({
				type : sap.ui.core.mvc.ViewType.XML,
				id : "MainView",
				viewName : "sap.ui.core.sample.odata.v4.SalesOrders.Main",
				models : { undefined: oModel,
					ui : new JSONModel({
						bRealOData : bRealOData,
						icon : bRealOData ? "sap-icon://building" : "sap-icon://record",
						iconTooltip : bRealOData ? "real OData service" : "mock OData service"}
				)}
			});
			// TODO: enhance sample application after features are supported
			// - Error Handling; not yet implemented in model
		}
	});
});
<|endoftext|>


<commit_before>// Variables
var gulp            = require('gulp')
var $               = require('gulp-load-plugins')();
var mainBowerFiles  = require('main-bower-files');
var browserSync     = require('browser-sync').create();
var runSequence     = require('run-sequence');
var rimraf          = require('rimraf');
var path            = require('path');
var through         = require('through2');

// Compile SCSS into css - Autoprefix it - Minify it - Push it into /build - Make a rev - Make a manifest
gulp.task('css', () => {
  return gulp.src('app/assets/css/*.scss')
    .pipe($.sass().on('error', $.sass.logError))
    .pipe($.plumber())
    .pipe($.autoprefixer('last 5 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe($.cleanCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('build/css/'))
    .pipe($.rev())
    .pipe(gulp.dest('build/css'))
    .pipe($.rev.manifest())
    .pipe( gulp.dest('build/css'))
    .pipe(browserSync.stream());
});

// Minify JS  - Push it into "build" - Make a rev - Make a manifest
gulp.task('js', () => {
  return gulp.src('app/assets/js/*.js')
  	.pipe($.uglify())
    .pipe(gulp.dest('build/js/'))
    .pipe($.rev())
    .pipe(gulp.dest('build/js'))
    .pipe($.rev.manifest())
    .pipe( gulp.dest('build/js'))
    .pipe(browserSync.stream());
});

// Replace links in .html files with the latest Rev of files
gulp.task('rev', function () {
    return gulp.src(['build/**/*.json', 'build/*.html'])
        .pipe($.revCollector({
            replaceReved: true,
            dirReplacements: {
                'css': 'css',
                'js': 'js'
            }
        }) )
        .pipe( gulp.dest('build') );
});

// Function that clean older versions of Rev
function cleaner() {
    return through.obj(function(file, enc, cb){
        rimraf( path.resolve( (file.cwd || process.cwd()), file.path), function (err) {
            if (err) {
                this.emit('error', new gutil.PluginError('Cleanup old files', err));
            }
            this.push(file);
            cb();
        }.bind(this));
    });
}

// Clean older verions of Rev
gulp.task('clean', function() {
    gulp.src( ['build/css/main*.css'], {read: false})
        .pipe($.revOutdated(2) ) // leave 1 latest asset file
        .pipe( cleaner() );
    gulp.src( ['build/js/app*.js'], {read: false})
        .pipe($.revOutdated(2) ) // leave 3 recent assets
        .pipe( cleaner() );
    return;
});

// Compile JADE into .html - Push it into build
gulp.task('jade', () => {
  return gulp.src(['app/assets/jade/**/*.jade', '!app/assets/jade/template.jade', '!app/assets/jade/blocks/*.jade'])
  // MULTILANGUAGE SUPPORT, '!app/assets/jade/en/template.jade', '!app/assets/jade/en/en-blocks/*.jade'])
    .pipe($.plumber())
    .pipe($.jade({pretty: true}))
    .pipe(gulp.dest('build'))
    .pipe(browserSync.stream());
})

// Compress images
gulp.task('img', () => {
  return gulp.src('build/img/**/*')
    .pipe($.imagemin({progressive: true}))
    .pipe(gulp.dest('build/img'))
});

// Take main files from bower-components - Push them into app/assets/vendor
gulp.task('bower', () => {
    return gulp.src(mainBowerFiles(), { base: 'bower_components' })
        .pipe(gulp.dest('app/assets/vendor'))
});

// Take .js files into app/assets/vendor - Minify them - Push them into build/js
gulp.task('vendor-js', () => {
  return gulp.src('app/assets/vendor/**/*.js')
      .pipe($.concat('vendor.js'))
      .pipe($.uglify())
      .pipe(gulp.dest('build/js'))
});

// Take .css files into app/assets/vendor - Minify them - Push them into build/css
gulp.task('vendor-css', () => {
  return gulp.src('app/assets/vendor/**/*.css')
      .pipe($.concat('vendor.css'))
      .pipe($.cleanCss({compatibility: 'ie8'}))
      .pipe(gulp.dest('build/css'))
});

// Take humans.txt, robots.txt, .htaccess - Push them into build
gulp.task('extras' , () => {
  return gulp.src('app/*.*')
      .pipe(gulp.dest('build'))
});

// Static Server + watching scss/html files
gulp.task('serve', ['watch'], () => {
    browserSync.init({
        server: "./build"
    });
});

// Watch for changes
gulp.task('watch', () => {
    gulp.watch('app/assets/jade/**/*.jade', ['jade']);
    gulp.watch('app/assets/js/*.js', ['js', 'clean']);
    gulp.watch('app/assets/css/*.scss', ['css','clean']);
});

gulp.task('default', (callback) => {
     runSequence(['watch', 'js', 'css', 'jade','img'], 'bower', ['vendor-js', 'vendor-css'], 'serve', callback);
});

gulp.task('build', ['extras', 'img', 'rev']);

gulp.task('inject', () => {
     runSequence('bower', ['vendor-js', 'vendor-css']);
});

<commit_msg>Some fixes<commit_after>// Variables
var gulp            = require('gulp')
var $               = require('gulp-load-plugins')();
var mainBowerFiles  = require('main-bower-files');
var browserSync     = require('browser-sync').create();
var runSequence     = require('run-sequence');
var rimraf          = require('rimraf');
var path            = require('path');
var through         = require('through2');

// Compile SCSS into css - Autoprefix it - Minify it - Push it into /build - Make a rev - Make a manifest
gulp.task('css', () => {
  return gulp.src('app/assets/css/*.scss')
    .pipe($.sass().on('error', $.sass.logError))
    .pipe($.plumber())
    .pipe($.autoprefixer('last 5 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
    .pipe($.cleanCss({compatibility: 'ie8'}))
    .pipe(gulp.dest('build/css/'))
    .pipe($.rev())
    .pipe(gulp.dest('build/css'))
    .pipe($.rev.manifest())
    .pipe( gulp.dest('build/css'))
    .pipe(browserSync.stream());
});

// Minify JS  - Push it into "build" - Make a rev - Make a manifest
gulp.task('js', () => {
  return gulp.src('app/assets/js/*.js')
    .pipe($.uglify())
    .pipe(gulp.dest('build/js/'))
    .pipe($.rev())
    .pipe(gulp.dest('build/js'))
    .pipe($.rev.manifest())
    .pipe( gulp.dest('build/js'))
    .pipe(browserSync.stream());
});

// Replace links in .html files with the latest Rev of files
gulp.task('rev', function () {
    return gulp.src(['build/**/*.json', 'build/*.html'])
        .pipe($.revCollector({
            replaceReved: true,
            dirReplacements: {
                'css': 'css',
                'js': 'js'
            }
        }) )
        .pipe( gulp.dest('build') );
});

// Function that clean older versions of Rev
function cleaner() {
    return through.obj(function(file, enc, cb){
        rimraf( path.resolve( (file.cwd || process.cwd()), file.path), function (err) {
            if (err) {
                this.emit('error', new gutil.PluginError('Cleanup old files', err));
            }
            this.push(file);
            cb();
        }.bind(this));
    });
}

// Clean older verions of Rev
gulp.task('clean', function() {
    gulp.src( ['build/css/main*.css'], {read: false})
        .pipe($.revOutdated(2) ) // leave 1 latest asset file
        .pipe( cleaner() );
    gulp.src( ['build/js/app*.js'], {read: false})
        .pipe($.revOutdated(2) ) // leave 3 recent assets
        .pipe( cleaner() );
    return;
});

// Compile JADE into .html - Push it into build
gulp.task('jade', () => {
  return gulp.src(['app/assets/jade/**/*.jade', '!app/assets/jade/template.jade', '!app/assets/jade/blocks/*.jade'])
  // MULTILANGUAGE SUPPORT, '!app/assets/jade/en/template.jade', '!app/assets/jade/en/en-blocks/*.jade'])
    .pipe($.plumber())
    .pipe($.jade({pretty: true}))
    .pipe(gulp.dest('build'))
    .pipe(browserSync.stream());
})

// Compress images
gulp.task('img', () => {
  return gulp.src('build/img/**/*')
    .pipe($.imagemin({progressive: true}))
    .pipe(gulp.dest('build/img'))
});

// Take main files from bower-components - Push them into app/assets/vendor
gulp.task('bower', () => {
    return gulp.src(mainBowerFiles(), { base: 'bower_components' })
        .pipe(gulp.dest('app/assets/vendor'))
});

// Take .js files into app/assets/vendor - Minify them - Push them into build/js
gulp.task('vendor-js', () => {
  return gulp.src('app/assets/vendor/**/*.js')
      .pipe($.concat('vendor.js'))
      .pipe($.uglify())
      .pipe(gulp.dest('build/js'))
});

// Take .css files into app/assets/vendor - Minify them - Push them into build/css
gulp.task('vendor-css', () => {
  return gulp.src('app/assets/vendor/**/*.css')
      .pipe($.concat('vendor.css'))
      .pipe($.cleanCss({compatibility: 'ie8'}))
      .pipe(gulp.dest('build/css'))
});

// Take humans.txt, robots.txt, .htaccess - Push them into build
gulp.task('extras' , () => {
  return gulp.src('app/*.*')
      .pipe(gulp.dest('build'))
});

// Static Server + watching scss/html files
gulp.task('serve', ['watch'], () => {
    browserSync.init({
        server: "./build"
    });
});

// Watch for changes
gulp.task('watch', () => {
    gulp.watch('app/assets/jade/**/*.jade', ['jade']);
    gulp.watch('app/assets/js/*.js', ['js', 'clean']);
    gulp.watch('app/assets/css/**/*.scss', ['css','clean']);
});

gulp.task('default', (callback) => {
     runSequence(['watch', 'js', 'css', 'jade','img'], 'bower', ['vendor-js', 'vendor-css'], 'serve', callback);
});

gulp.task('build', ['extras', 'img', 'rev']);

gulp.task('inject', () => {
     runSequence('bower', ['vendor-js', 'vendor-css']);
});

<|endoftext|>


<commit_before>/*Preprocess*/
var LANG = ['python', 'scala', 'r', 'julia', 'c++', 'perl'];
var TITLE_WITH_LANG = ['/get_started/', '/tutorials/', '/how_to/', '/architecture/'];
for(var i = 0; i < LANG.length; ++i) {
    TITLE_WITH_LANG.push('/api/' + LANG[i] + '/');
}

/*Check whether is API page*/
var API_PAGE = ['python'];
var isAPI = false;

function render_left_helper(toc, currentText) {
    var lefttoc = toc;
    var currentText = currentText, trailing = ' Documents';
    if (currentText.endsWith(trailing)) currentText = currentText.substring(0, currentText.length - trailing.length);
    if (currentText == 'System') currentText = 'Architecture';

    lefttoc.addClass('current');
    $('.leftsidebar > .sphinxsidebarwrapper').children().remove();
    $('.leftsidebar > .sphinxsidebarwrapper').append(lefttoc);

    $('.leftsidebar > .sphinxsidebarwrapper').prepend('
' + currentText + ' Contents
');
    addToggle('.leftsidebar');

    $('.leftsidebar li a').click(function () {
        $('.leftsidebar li a').css('color', 'black');
        $(this).css('color', '#337ab7');
    });
}

/*Render content tree of different pages*/
function render_lefttoc() {
    var url = window.location.href, indexTrailing = 'index.html';
    if (url.indexOf('/get_started/') != -1) {
        var leftToc = "

Installation

Why MXNet

";
        render_left_helper($($.parseHTML(leftToc)), 'Get Started');
        keepExpand();
        $('.sphinxsidebar').css("visibility", "visible");
        return;
    }
    if (url.indexOf(indexTrailing) == -1) {
        for(var i = 0; i < TITLE_WITH_LANG.length; ++i) {
            var path = TITLE_WITH_LANG[i];
            if (url.indexOf(path) != -1) {
                var urlPath = 'http://' + window.location.host + path;
                $.get(urlPath + indexTrailing, null, function(data) {
                    var currentText = $($.parseHTML(data)).find('.leftsidebar >  .sphinxsidebarwrapper > ul.current > li.current > a').html();
                    if (isAPI) {
                        render_left_helper($($.parseHTML(data)).find('#table-of-contents > div > ul'), currentText);
                    }
                    else {
                        render_left_helper($($.parseHTML(data)).find('.leftsidebar > .sphinxsidebarwrapper > ul.current > li.current > ul'), currentText);
                        var tocLink = $('.leftsidebar .sphinxsidebarwrapper .leaf a');
                        var staticLink = 'http';
                        tocLink.each(function () {
                            if (!$(this).attr('href').startsWith(staticLink)) {
                                $(this).attr('href', urlPath + $(this).attr('href'));
                            }
                        });
                    }
                    keepExpand();
                    $('.sphinxsidebar').css("visibility", "visible");
                })
            }
        }
    }
    else {
        var currentText = $('.leftsidebar >  .sphinxsidebarwrapper > ul.current > li.current > a').html();
        var toc = isAPI ? $('#table-of-contents > div > ul').clone() : $('.leftsidebar > .sphinxsidebarwrapper > ul.current > li.current > ul').clone();
        render_left_helper(toc, currentText);
        $('.sphinxsidebar').css("visibility", "visible");
    }
}

/*Render contents inside page*/
function render_righttoc() {
    var url = window.location.href, apiFlag = '/api/', indexTrailing = 'index.html';

    var rightTocTitle = "Page Contents";
    $("div.rightsidebar > div.sphinxsidebarwrapper > h3").children().remove();
    $("div.rightsidebar > div.sphinxsidebarwrapper > h3").html(rightTocTitle);

    addToggle('.rightsidebar');

    $('.rightsidebar li a').click(function () {
        $('.rightsidebar li a').css('color', 'black');
        $(this).css('color', '#337ab7');
    });

    if (url.indexOf(indexTrailing) != -1 || isAPI) {
        $('.rightsidebar').hide();
    }
}

/*Highlight entry when scrolling*/
function scroll_righttoc() {
    var navbarHeight = 60;
    var links = $('.rightsidebar a');
    for(var i = 1; i < links.length; ++i) {
        var divID = links.eq(i).attr('href');
        if ($(divID).offset().top - $(window).scrollTop() > navbarHeight) {
            $('.rightsidebar a').css('color', 'black');
            links.eq(i - 1).css('color', '#337ab7');
            if (!links.eq(i - 1).parent().hasClass('leaf')) {
                links.eq(i - 1).parent().removeClass('closed');
                links.eq(i - 1).parent().addClass('opened');
                links.eq(i - 1).parent().find('ul').first().show();
            }
            break;
        }
    }
}

/*Decorate toc*/
function addToggle(tocClass) {
    var allEntry = $(tocClass + " div.sphinxsidebarwrapper li");
    var subEntry = $(tocClass + " div.sphinxsidebarwrapper").children("ul").first().children("li");
    if (subEntry.length == 1) {
        subEntry.prepend("");
        subEntry.addClass('opened');
        allEntry = subEntry.find("li");
        //subEntry.children("a").hide();
        subEntry.children("ul").css("padding-left", "0");
        //subEntry.parent().css("margin-left", "-10px");
    }
    allEntry.each(function () {
        $(this).prepend("");
        var childUL = $(this).find("ul");
        if (childUL.length && childUL.first().children().length) {
            $(this).addClass("closed");
            $(this).find("ul").first().hide();
        }
        else $(this).addClass("leaf");
        var anchor = $(this).children("a").first();
        anchor.click(function () {
            autoExpand(anchor);
        });
    });
};

/*Sidebar toc toggle button behavior*/
function toggle(elem) {
    if ($(elem).parent().hasClass("closed")) {
        $(elem).parent().find("ul").first().show();
        $(elem).parent().removeClass("closed").addClass("opened");
    }
    else if ($(elem).parent().hasClass("opened")) {
        $(elem).parent().find("ul").first().hide();
        $(elem).parent().removeClass("opened").addClass("closed");
    }
}

/*Automatically expand child level while cilcking an entry*/
function autoExpand(elem) {
    if (elem.parent().hasClass("closed")) {
        elem.parent().removeClass("closed").addClass("opened");
        elem.parent().children("ul").first().show();
    }
    else {
        elem.parent().removeClass("opened").addClass("closed");
        elem.parent().children("ul").first().hide();
    }
}

/*Keep toc expansion while redirecting*/
function keepExpand() {
    var url = window.location.href, currentEntry;
    var entryList = isAPI ? $('.leftsidebar li') : $('.sphinxsidebar li');
    for(var i = entryList.length - 1; i >= 0; --i) {
        var entryURL = entryList.eq(i).find('a').first().attr('href');
        if (entryURL != '#' && url.indexOf(entryURL) != -1) {
            currentEntry = entryList.eq(i);
            break;
        }
    }

    if (isAPI) {
        var rootEntry = currentEntry;
        if (rootEntry.parent().parent().is('li')) rootEntry = rootEntry.parent().parent();
        rootEntry.children("ul").first().remove();
        rootEntry.append($('.rightsidebar .sphinxsidebarwrapper > ul > li > ul').clone());
        var allEntry = $(".leftsidebar div.sphinxsidebarwrapper li");
        allEntry.each(function () {
            var anchor = $(this).children("a").first();
            anchor.click(function () {
                autoExpand(anchor);
            });
        });
        $('.sphinxsidebar li').each(function () {
            if (url.endsWith($(this).find('a').first().attr('href'))) {
                currentEntry = $(this);
                return false;
            }
        });
        $('.leftsidebar li a').click(function () {
            $('.leftsidebar li a').css('color', 'black');
            $(this).css('color', '#337ab7');
        });
    }
    currentEntry.find('a').first().css('color', '#337ab7');
    currentEntry.children("ul").first().show();
    if (!currentEntry.hasClass('leaf')) currentEntry.removeClass("closed").addClass("opened");
    while(currentEntry.parent().is('ul') && currentEntry.parent().parent().is('li')) {
        currentEntry = currentEntry.parent().parent();
        currentEntry.removeClass("closed").addClass("opened");
        currentEntry.children("ul").first().show();
    }
}

$(document).ready(function () {
    var url = window.location.href, searchFlag = 'search.html';
    try {
        if (url.indexOf(searchFlag) == -1) {
            for(var i = 0; i < API_PAGE.length; ++i) {
                if (url.indexOf('/api/' + API_PAGE[i]) != -1) {
                    isAPI = true;
                    break;
                }
            }
            render_righttoc();
            if ($('.leftsidebar').length) render_lefttoc();
        }
        $(window).scroll(function () {
            scroll_righttoc();
        });
    }
    catch(err) {
        return;
    }
});<commit_msg>Improve style (#6445)<commit_after>/*Preprocess*/
var LANG = ['python', 'scala', 'r', 'julia', 'c++', 'perl'];
var TITLE_WITH_LANG = ['/get_started/', '/tutorials/', '/how_to/', '/architecture/'];
for(var i = 0; i < LANG.length; ++i) {
    TITLE_WITH_LANG.push('/api/' + LANG[i] + '/');
}

/*Check whether is API page*/
var API_PAGE = ['python'];
var isAPI = false;

function render_left_helper(toc, currentText) {
    var lefttoc = toc;
    var currentText = currentText, trailing = ' Documents';
    if (currentText.endsWith(trailing)) currentText = currentText.substring(0, currentText.length - trailing.length);
    if (currentText == 'System') currentText = 'Architecture';

    lefttoc.addClass('current');
    $('.leftsidebar > .sphinxsidebarwrapper').children().remove();
    $('.leftsidebar > .sphinxsidebarwrapper').append(lefttoc);

    $('.leftsidebar > .sphinxsidebarwrapper').prepend('
Contents
');
    addToggle('.leftsidebar');

    $('.leftsidebar li a').click(function () {
        $('.leftsidebar li a').css('color', 'black');
        $(this).css('color', '#337ab7');
    });
}

/*Render content tree of different pages*/
function render_lefttoc() {
    var url = window.location.href, indexTrailing = 'index.html';
    if (url.indexOf('/get_started/') != -1) {
        var leftToc = "

Installation

Why MXNet

";
        render_left_helper($($.parseHTML(leftToc)), 'Get Started');
        keepExpand();
        $('.sphinxsidebar').css("visibility", "visible");
        return;
    }
    if (url.indexOf(indexTrailing) == -1) {
        for(var i = 0; i < TITLE_WITH_LANG.length; ++i) {
            var path = TITLE_WITH_LANG[i];
            if (url.indexOf(path) != -1) {
                var urlPath = 'http://' + window.location.host + path;
                $.get(urlPath + indexTrailing, null, function(data) {
                    var currentText = $($.parseHTML(data)).find('.leftsidebar >  .sphinxsidebarwrapper > ul.current > li.current > a').html();
                    if (isAPI) {
                        render_left_helper($($.parseHTML(data)).find('#table-of-contents > div > ul'), currentText);
                    }
                    else {
                        render_left_helper($($.parseHTML(data)).find('.leftsidebar > .sphinxsidebarwrapper > ul.current > li.current > ul'), currentText);
                        var tocLink = $('.leftsidebar .sphinxsidebarwrapper .leaf a');
                        var staticLink = 'http';
                        tocLink.each(function () {
                            if (!$(this).attr('href').startsWith(staticLink)) {
                                $(this).attr('href', urlPath + $(this).attr('href'));
                            }
                        });
                    }
                    keepExpand();
                    $('.sphinxsidebar').css("visibility", "visible");
                })
            }
        }
    }
    else {
        var currentText = $('.leftsidebar >  .sphinxsidebarwrapper > ul.current > li.current > a').html();
        var toc = isAPI ? $('#table-of-contents > div > ul').clone() : $('.leftsidebar > .sphinxsidebarwrapper > ul.current > li.current > ul').clone();
        render_left_helper(toc, currentText);
        $('.sphinxsidebar').css("visibility", "visible");
    }
}

/*Render contents inside page*/
function render_righttoc() {
    var url = window.location.href, apiFlag = '/api/', indexTrailing = 'index.html';

    var rightTocTitle = "Page Contents";
    $("div.rightsidebar > div.sphinxsidebarwrapper > h3").children().remove();
    $("div.rightsidebar > div.sphinxsidebarwrapper > h3").html(rightTocTitle);

    addToggle('.rightsidebar');

    $('.rightsidebar li a').click(function () {
        $('.rightsidebar li a').css('color', 'black');
        $(this).css('color', '#337ab7');
    });

    if (url.indexOf(indexTrailing) != -1 || isAPI) {
        $('.rightsidebar').hide();
    }
}

/*Highlight entry when scrolling*/
function scroll_righttoc() {
    var navbarHeight = 60;
    var links = $('.rightsidebar a');
    for(var i = 1; i < links.length; ++i) {
        var divID = links.eq(i).attr('href');
        if ($(divID).offset().top - $(window).scrollTop() > navbarHeight) {
            $('.rightsidebar a').css('color', 'black');
            links.eq(i - 1).css('color', '#337ab7');
            if (!links.eq(i - 1).parent().hasClass('leaf')) {
                links.eq(i - 1).parent().removeClass('closed');
                links.eq(i - 1).parent().addClass('opened');
                links.eq(i - 1).parent().find('ul').first().show();
            }
            break;
        }
    }
}

/*Decorate toc*/
function addToggle(tocClass) {
    var allEntry = $(tocClass + " div.sphinxsidebarwrapper li");
    var subEntry = $(tocClass + " div.sphinxsidebarwrapper").children("ul").first().children("li");
    if (subEntry.length == 1) {
        subEntry.prepend("");
        subEntry.addClass('opened');
        allEntry = subEntry.find("li");
        //subEntry.children("a").hide();
        subEntry.children("ul").css("padding-left", "0");
        //subEntry.parent().css("margin-left", "-10px");
    }
    allEntry.each(function () {
        $(this).prepend("");
        var childUL = $(this).find("ul");
        if (childUL.length && childUL.first().children().length) {
            $(this).addClass("closed");
            $(this).find("ul").first().hide();
        }
        else $(this).addClass("leaf");
        var anchor = $(this).children("a").first();
        anchor.click(function () {
            autoExpand(anchor);
        });
    });
};

/*Sidebar toc toggle button behavior*/
function toggle(elem) {
    if ($(elem).parent().hasClass("closed")) {
        $(elem).parent().find("ul").first().show();
        $(elem).parent().removeClass("closed").addClass("opened");
    }
    else if ($(elem).parent().hasClass("opened")) {
        $(elem).parent().find("ul").first().hide();
        $(elem).parent().removeClass("opened").addClass("closed");
    }
}

/*Automatically expand child level while cilcking an entry*/
function autoExpand(elem) {
    if (elem.parent().hasClass("closed")) {
        elem.parent().removeClass("closed").addClass("opened");
        elem.parent().children("ul").first().show();
    }
    else {
        elem.parent().removeClass("opened").addClass("closed");
        elem.parent().children("ul").first().hide();
    }
}

/*Keep toc expansion while redirecting*/
function keepExpand() {
    var url = window.location.href, currentEntry;
    var entryList = isAPI ? $('.leftsidebar li') : $('.sphinxsidebar li');
    for(var i = entryList.length - 1; i >= 0; --i) {
        var entryURL = entryList.eq(i).find('a').first().attr('href');
        if (entryURL != '#' && url.indexOf(entryURL) != -1) {
            currentEntry = entryList.eq(i);
            break;
        }
    }

    if (isAPI) {
        var rootEntry = currentEntry;
        if (rootEntry.parent().parent().is('li')) rootEntry = rootEntry.parent().parent();
        rootEntry.children("ul").first().remove();
        rootEntry.append($('.rightsidebar .sphinxsidebarwrapper > ul > li > ul').clone());
        var allEntry = $(".leftsidebar div.sphinxsidebarwrapper li");
        allEntry.each(function () {
            var anchor = $(this).children("a").first();
            anchor.click(function () {
                autoExpand(anchor);
            });
        });
        $('.sphinxsidebar li').each(function () {
            if (url.endsWith($(this).find('a').first().attr('href'))) {
                currentEntry = $(this);
                return false;
            }
        });
        $('.leftsidebar li a').click(function () {
            $('.leftsidebar li a').css('color', 'black');
            $(this).css('color', '#337ab7');
        });
    }
    currentEntry.find('a').first().css('color', '#337ab7');
    currentEntry.children("ul").first().show();
    if (!currentEntry.hasClass('leaf')) currentEntry.removeClass("closed").addClass("opened");
    while(currentEntry.parent().is('ul') && currentEntry.parent().parent().is('li')) {
        currentEntry = currentEntry.parent().parent();
        currentEntry.removeClass("closed").addClass("opened");
        currentEntry.children("ul").first().show();
    }
}

$(document).ready(function () {
    var url = window.location.href, searchFlag = 'search.html';
    try {
        if(url.indexOf('/get_started/') != -1) return;
        if (url.indexOf(searchFlag) == -1) {
            for(var i = 0; i < API_PAGE.length; ++i) {
                if (url.indexOf('/api/' + API_PAGE[i]) != -1) {
                    isAPI = true;
                    break;
                }
            }
            render_righttoc();
            if ($('.leftsidebar').length) render_lefttoc();
        }
        $(window).scroll(function () {
            scroll_righttoc();
        });
    }
    catch(err) {
        return;
    }
});<|endoftext|>


<commit_before>IndexedDBStorage = function() {
    var self = this;

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
    if(!window.indexedDB) {
        throw new Error('Your browser does not support the IndexedDB API.');
    } else if(false) { // TODO
        throw(new Error('Your browser does not support the IndexedDB Blob storage feature.'));
    }

    self._urlPrefix = 'indexeddb:' + window.location.origin + '/persistent/';

    var request = window.indexedDB.open('audiopia', 1);
    request.onsuccess = function(event) {
        self.db = request.result;
        self.db.onerror = function(event) {
            console.warn('Database error', event.target.errorCode);
        }
    }
    request.onupgradeneeded = function(event) {
        var objectStore = request.result.createObjectStore('music');
    }
    request.onerror = function(event) {
        console.warn('IndexedDB error', request.errorCode);
    }
}

IndexedDBStorage.prototype.readFile = function(filePath, successCallback, errorCallback) {
    var self = this;
    var transaction = self.db.transaction(['music'], 'readwrite');
    transaction.onerror = function(event) {
        errorCallback(new Error('Transaction error.'));
    }
    transaction.objectStore('music').get(filePath).onsuccess = function(event) {
        var blob = event.target.result;
        if(!(blob instanceof Blob)) {
            errorCallback(new Error('Failed to decode data.'));
        } else {
            successCallback(blob);
        }
    }
}

IndexedDBStorage.prototype.readFileFromUrl = function(url, successCallback, errorCallback) {
    var self = this;
    if(url.indexOf(self._urlPrefix) == 0) {
        self.readFile(unescape(url.substr(self._urlPrefix.length)), successCallback, errorCallback);
    } else {
        errorCallback(new Error('Invalid URL schema.'));
    }
}

IndexedDBStorage.prototype.writeFile = function(filePath, blob, successCallback, errorCallback) {
    var self = this;
    try {
        var transaction = self.db.transaction(['music'], 'readwrite');
        transaction.onerror = function(event) {
            errorCallback(new Error('Transaction error.'));
        }
        transaction.objectStore('music').put(blob, filePath).onsuccess = function(event) {
            successCallback(self._urlPrefix + escape(filePath));
        }
    } catch(error) {
        errorCallback(error);
    }
}

IndexedDBStorage.prototype.clear = function(successCallback, errorCallback) {
    var self = this;
    var request = window.indexedDB.deleteDatabase('audiopia');
    request.onsuccess = function(event) {
        if(successCallback) {
            successCallback();
        }
    };
    request.onerror = function (event) {
        if(errorCallback) {
            errorCallback(new Error('Failed to delete database.'));
        }
    };
    request.onblocked = function () {
        if(errorCallback) {
            errorCallback(new Error('Couldn\'t delete database due to the operation being blocked.'));
        }
    };
}
<commit_msg>Don't remove database when clearing it (IndexedDB)<commit_after>IndexedDBStorage = function() {
    var self = this;

    window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
    window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
    window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
    if(!window.indexedDB) {
        throw new Error('Your browser does not support the IndexedDB API.');
    } else if(false) { // TODO
        throw(new Error('Your browser does not support the IndexedDB Blob storage feature.'));
    }

    self._urlPrefix = 'indexeddb:' + window.location.origin + '/persistent/';

    var request = window.indexedDB.open('audiopia', 1);
    request.onsuccess = function(event) {
        self.db = request.result;
        self.db.onerror = function(event) {
            console.warn('Database error', event.target.errorCode);
        }
    }
    request.onupgradeneeded = function(event) {
        request.result.createObjectStore('music');
    }
    request.onerror = function(event) {
        console.warn('IndexedDB error', request.errorCode);
    }
}

IndexedDBStorage.prototype.readFile = function(filePath, successCallback, errorCallback) {
    var self = this;
    var transaction = self.db.transaction(['music'], 'readwrite');
    transaction.onerror = function(event) {
        errorCallback(new Error('Transaction error.'));
    }
    transaction.objectStore('music').get(filePath).onsuccess = function(event) {
        var blob = event.target.result;
        if(!(blob instanceof Blob)) {
            errorCallback(new Error('Failed to decode data.'));
        } else {
            successCallback(blob);
        }
    }
}

IndexedDBStorage.prototype.readFileFromUrl = function(url, successCallback, errorCallback) {
    var self = this;
    if(url.indexOf(self._urlPrefix) == 0) {
        self.readFile(unescape(url.substr(self._urlPrefix.length)), successCallback, errorCallback);
    } else {
        errorCallback(new Error('Invalid URL schema.'));
    }
}

IndexedDBStorage.prototype.writeFile = function(filePath, blob, successCallback, errorCallback) {
    var self = this;
    try {
        var transaction = self.db.transaction(['music'], 'readwrite');
        transaction.onerror = function(event) {
            errorCallback(new Error('Transaction error.'));
        }
        transaction.objectStore('music').put(blob, filePath).onsuccess = function(event) {
            successCallback(self._urlPrefix + escape(filePath));
        }
    } catch(error) {
        errorCallback(error);
    }
}

IndexedDBStorage.prototype.clear = function(successCallback, errorCallback) {
    var self = this;
    var transaction = self.db.transaction(['music'], 'readwrite');
    transaction.onerror = function(event) {
        errorCallback(new Error('Transaction error.'));
    }
    transaction.objectStore('music').clear().onsuccess = function(event) {
        successCallback();
    }
}
<|endoftext|>


<commit_before>var Reaction = require("../reaction"),
    rules = require("../rules");

var VariableReaction = Reaction.extend({

  setFrom: function(key) {
    var newVal = this.get(key),
        oldVal,
        shouldTriggerChange = false,
        el = $(this.el);

    if(this.isInput) {
      oldVal = el.val();
      if(el.attr("type") === "checkbox") {
        if((el.prop('checked') && !newVal) || (!el.prop('checked') && newVal)) {
          shouldTriggerChange = true;
        }
        el.prop("checked", !!newVal);
      } else if(el.attr("type") === "radio") {
        if(oldVal == newVal) {
          if (!el.prop('checked')) {
            shouldTriggerChange = true;
          }
          el.prop("checked", true);
        } else {
          if (el.prop('checked')) {
            shouldTriggerChange = true;
          }
          el.prop("checked", false);
        }
      } else if(newVal !== oldVal) {
        shouldTriggerChange = true;
        //ugly nesting, but have to check for undefined because
        //this gets called by many things and newVal isn't always defined
        if (typeof newVal !== 'undefined') {
          el.val(newVal.toString());
        } else {
          el.val(newVal);
        }
      }
      if (shouldTriggerChange) {
        this.triggerDOMChange();
      }
    } else {
      oldVal = el.html();
      if(oldVal !== newVal) {
        el.html(newVal);
      }
    }
  },

  triggerDOMChange: function () {
      $(this.el).trigger('change');
  },

  init: function(next) {
    if (this.isInput) {
      var that = this;
      setTimeout(function () { that.setFrom(that.variableName)}, 0);
    } else {
      this.setFrom(this.variableName);
    }
    next();
  },

  observe: function() {
    var key = this.variableName,
        that = this,
        model = that.model,
        events = "input change";

    if((this.isInput || this.isContentEditable) && !this.isReadOnly) {
      this.clearUiEvent(events);
      this.uiEvent(events, function() {
        if(that.isContentEditable) {
          return model.set(key, that.el.html(), { validate: true });
        }
        if(that.el.attr("type") === "checkbox") {
          if (that.el.prop('checked')) {
            var value = that.el.val();
            if (value === 'on') {
              value = true;
            }
            return model.set(key, value, {validate: true});
          }
          return model.set(key, false, { validate: true });
        }
        if(that.el.attr("type") === "radio") {
          if(that.el.prop('checked')) {
            return model.set(key, that.el.val(), {validate: true});
          } else {
            return;
          }
        }
        model.set(key, that.el.val(), { validate: true });
      });
    }

    this.change(key, function() {
      this.setFrom(key);
    }, this);
  }
}, {
  selector: "[class]",

  reactIf: function(el) {
    return rules.variable(el);
  },

  parse: function(el) {
    return {
      isReadOnly: el.is("[data-readonly]"),
      isInput: el.is(":input:not(button)"),
      isContentEditable: el.is("[contenteditable]"),
      variableName: rules.variable(el)
    };
  }
});

module.exports = VariableReaction;
<commit_msg>set value after parsing children<commit_after>var Reaction = require("../reaction"),
    rules = require("../rules");

var VariableReaction = Reaction.extend({

  setFrom: function(key) {
    var newVal = this.get(key),
        oldVal,
        shouldTriggerChange = false,
        el = $(this.el);

    if(this.isInput) {
      oldVal = el.val();
      if(el.attr("type") === "checkbox") {
        if((el.prop('checked') && !newVal) || (!el.prop('checked') && newVal)) {
          shouldTriggerChange = true;
        }
        el.prop("checked", !!newVal);
      } else if(el.attr("type") === "radio") {
        if(oldVal == newVal) {
          if (!el.prop('checked')) {
            shouldTriggerChange = true;
          }
          el.prop("checked", true);
        } else {
          if (el.prop('checked')) {
            shouldTriggerChange = true;
          }
          el.prop("checked", false);
        }
      } else if(newVal !== oldVal) {
        shouldTriggerChange = true;
        //ugly nesting, but have to check for undefined because
        //this gets called by many things and newVal isn't always defined
        if (typeof newVal !== 'undefined') {
          el.val(newVal.toString());
        } else {
          el.val(newVal);
        }
      }
      if (shouldTriggerChange) {
        this.triggerDOMChange();
      }
    } else {
      oldVal = el.html();
      if(oldVal !== newVal) {
        el.html(newVal);
      }
    }
  },

  triggerDOMChange: function () {
      $(this.el).trigger('change');
  },

  init: function(next) {
    next();
    this.setFrom(this.variableName);
  },

  observe: function() {
    var key = this.variableName,
        that = this,
        model = that.model,
        events = "input change";

    if((this.isInput || this.isContentEditable) && !this.isReadOnly) {
      this.clearUiEvent(events);
      this.uiEvent(events, function() {
        if(that.isContentEditable) {
          return model.set(key, that.el.html(), { validate: true });
        }
        if(that.el.attr("type") === "checkbox") {
          if (that.el.prop('checked')) {
            var value = that.el.val();
            if (value === 'on') {
              value = true;
            }
            return model.set(key, value, {validate: true});
          }
          return model.set(key, false, { validate: true });
        }
        if(that.el.attr("type") === "radio") {
          if(that.el.prop('checked')) {
            return model.set(key, that.el.val(), {validate: true});
          } else {
            return;
          }
        }
        model.set(key, that.el.val(), { validate: true });
      });
    }

    this.change(key, function() {
      this.setFrom(key);
    }, this);
  }
}, {
  selector: "[class]",

  reactIf: function(el) {
    return rules.variable(el);
  },

  parse: function(el) {
    return {
      isReadOnly: el.is("[data-readonly]"),
      isInput: el.is(":input:not(button)"),
      isContentEditable: el.is("[contenteditable]"),
      variableName: rules.variable(el)
    };
  }
});

module.exports = VariableReaction;
<|endoftext|>


<commit_before>'use strict';

var homebridge;
var Characteristic, Service;

module.exports = function(pHomebridge) {
	if (pHomebridge && !homebridge) {
		homebridge = pHomebridge;
		Characteristic = homebridge.hap.Characteristic;
		Service = homebridge.hap.Service;
    }

    var hexToBase64 = function(val) {
        return new Buffer((''+val).replace(/[^0-9A-F]/ig, ''), 'hex').toString('base64');
    }, base64ToHex = function(val) {
        if(!val) return val;
        return new Buffer(val, 'base64').toString('hex');
    }, swap16 = function (val) {
        return ((val & 0xFF) << 8)
            | ((val >>> 8) & 0xFF);
    }, swap32 = function (val) {
        return ((val & 0xFF) << 24)
           | ((val & 0xFF00) << 8)
           | ((val >>> 8) & 0xFF00)
           | ((val >>> 24) & 0xFF);
    },	hexToHPA = function(val) {
        return parseInt(swap16(val), 10);
    }, hPAtoHex = function(val) {
        return swap16(Math.round(val)).toString(16);
    }, numToHex = function(val, len) {
        var s = Number(val>>>0).toString(16);
        if(s.length % 2 != 0) {
            s = '0' + s;
        }
        if(len) {
            return ('0000000000000' + s).slice(-1 * len);
        }
    return s;
}

    class S2R1Characteristic extends Characteristic {
        constructor() {
            super('S2R1', 'E863F116-079E-48FF-8F27-9C2605A29F52');
            this.setProps({
                format: Characteristic.Formats.DATA,
                perms: [
                    Characteristic.Perms.READ, Characteristic.Perms.NOTIFY, Characteristic.Perms.HIDDEN
                ]
            });
        }
    }

    S2R1Characteristic.UUID = 'E863F116-079E-48FF-8F27-9C2605A29F52';

    class S2R2Characteristic extends Characteristic {
        constructor() {
            super('S2R2', 'E863F117-079E-48FF-8F27-9C2605A29F52');
            this.setProps({
                format: Characteristic.Formats.DATA,
                perms: [
                    Characteristic.Perms.READ, Characteristic.Perms.NOTIFY, Characteristic.Perms.HIDDEN
                ]
            });
        }
    }

    S2R2Characteristic.UUID = 'E863F117-079E-48FF-8F27-9C2605A29F52';

    class S2W1Characteristic extends Characteristic {
        constructor() {
            super('S2W1', 'E863F11C-079E-48FF-8F27-9C2605A29F52');
            this.setProps({
                format: Characteristic.Formats.DATA,
                perms: [
                    Characteristic.Perms.WRITE, Characteristic.Perms.HIDDEN
                ]
            });
        }
    }

    S2W1Characteristic.UUID = 'E863F11C-079E-48FF-8F27-9C2605A29F52';

    class S2W2Characteristic extends Characteristic {
        constructor() {
            super('S2W2', 'E863F121-079E-48FF-8F27-9C2605A29F52');
            this.setProps({
                format: Characteristic.Formats.DATA,
                perms: [
                    Characteristic.Perms.WRITE, Characteristic.Perms.HIDDEN
                ]
            });
        }
    }

    S2W2Characteristic.UUID = 'E863F121-079E-48FF-8F27-9C2605A29F52';

    class FakeGatoHistoryService extends Service {
        constructor(accessoryType, accessory, size) {
            if (typeof size === 'undefined') { size = 4032; }

            super(accessory.displayName + " History", 'E863F007-079E-48FF-8F27-9C2605A29F52');

            var entry2address = function(val) {
                var temp = val % this.memorySize;
                return temp;
            }.bind(this);

            this.log = accessory.log;
            switch (accessoryType)
            {
                case "weather":
                    this.accessoryType116 = "03";
                    this.accessoryType117 = "07";
                    break;
                case "energy":
                    this.accessoryType116 = "07";
                    this.accessoryType117 = "1f";
                    break;
                case "room":
                    this.accessoryType116 = "04";
                    this.accessoryType117 = "0f";
                    break;
            }

            this.accessoryType=accessoryType;
            this.firstEntry = 0;
            this.lastEntry = 0;
            this.history = [];
            this.memorySize = size;
            this.usedMemory=0;
            this.currentEntry = 1;
            this.transfer=false;
            this.setTime=true;
            this.refTime=0;
            this.memoryAddress=0;
            this.dataStream='';

            this.addCharacteristic(S2R1Characteristic);

            this.addCharacteristic(S2R2Characteristic)
                .on('get', (callback) => {
                    if ((this.currentEntry<this.lastEntry) && (this.transfer==true))
                    {
                        this.memoryAddress = entry2address (this.currentEntry);

                        if ((this.history[this.memoryAddress].temp==0 &&
                            this.history[this.memoryAddress].pressure==0 &&
                            this.history[this.memoryAddress].humidity==0) || (this.history[this.memoryAddress].power==0xFFFF) || (this.setTime==true))
                        {
                            this.log.debug("Data "+ this.accessoryType + ": 15" + numToHex(swap16(this.currentEntry),4) + "0000 0000 0000 81" + numToHex(swap32(this.refTime),8) +"0000 0000 00 0000");
                            callback(null,hexToBase64('15' + numToHex(swap16(this.currentEntry),4) +' 0000 0000 0000 81' + numToHex(swap32(this.refTime),8) + '0000 0000 00 0000'));
                            this.setTime=false;
                            this.currentEntry++;
                        }
                        else
                        {
                            for (var i=0;i<11;i++)
                            {
                                switch (this.accessoryType)
                                {
                                    case "weather":
                                        this.log.debug(this.accessoryType + " Entry: " + this.currentEntry + ", Address: " + this.memoryAddress);
                                        this.dataStream = this.dataStream + " 10 " + numToHex(swap16(this.currentEntry),4) + " 0000 "
                                            + numToHex(swap32(this.history[this.memoryAddress].time-this.refTime-978307200),8)
                                            + this.accessoryType117
                                            + numToHex(swap16(this.history[this.memoryAddress].temp*100),4)
                                            + numToHex(swap16(this.history[this.memoryAddress].humidity*100),4)
                                            + numToHex(swap16(this.history[this.memoryAddress].pressure*10),4);
                                        break;
                                    case "energy":
                                        this.log.debug(this.accessoryType + " Entry: " + this.currentEntry + ", Address: " + this.memoryAddress);
                                        this.dataStream = this.dataStream + " 14 " + numToHex(swap16(this.currentEntry),4) + " 0000 "
                                                + numToHex(swap32(this.history[this.memoryAddress].time-this.refTime-978307200),8)
                                                + this.accessoryType117
                                                + "0000 0000"
                                                + numToHex(swap16(this.history[this.memoryAddress].power*10),4)
                                                + "0000 0000";
                                        break;
                                }
                                this.currentEntry++;
                                this.memoryAddress = entry2address (this.currentEntry);
                                if (this.currentEntry==this.lastEntry)
                                {
                                    break;
                                }
                            }
                            this.log.debug("Data " + this.accessoryType + ": " + this.dataStream);
                            callback(null,hexToBase64(this.dataStream));
                            this.dataStream='';
                        }
                    }
                    else
                    {
                        this.transfer=false;
                        callback(null,hexToBase64('00'));
                    }
            });

            this.addCharacteristic(S2W1Characteristic)
                .on('set', this.setCurrentS2W1.bind(this));

            this.addCharacteristic(S2W2Characteristic)
                .on('set', this.setCurrentS2W2.bind(this));

        }

        sendHistory(address){
            var hexAddress= address.toString('16');
            if (address!=0)
                this.currentEntry = address;
            else
                this.currentEntry = 1;
            this.transfer=true;
        }

        //in order to be consistent with Eve, entry address start from 1
        addEntry(entry){

            var entry2address = function(val) {
                return val % this.memorySize;
            }.bind(this);

            if (this.usedMemory<this.memorySize)
            {
                this.usedMemory++;
                this.firstEntry=0;
                this.lastEntry=this.usedMemory;
            }
            else
            {
                this.firstEntry++;
                this.lastEntry = this.firstEntry+this.usedMemory;
            }

            if (this.refTime==0)
                {
                    this.refTime=entry.time-978307200;
                    switch (this.accessoryType)
                        {
                            case "weather":
                                this.history[this.lastEntry]= {time: entry.time, temp:0, pressure:0, humidity:0};
                                break;
                            case "energy":
                                this.history[this.lastEntry]= {time: entry.time, power:0xFFFF};
                                break;
                        }
                    this.lastEntry++;
                    this.usedMemory++;
                }

            this.history[entry2address(this.lastEntry)] = (entry);

            this.getCharacteristic(S2R1Characteristic)
                .setValue(hexToBase64(numToHex(swap32(entry.time-this.refTime-978307200),8) + '00000000' + numToHex(swap32(this.refTime),8) + '0401020202' + this.accessoryType116 +'020f03' + numToHex(swap16(this.usedMemory),4) + numToHex(swap16(this.memorySize),4) + numToHex(swap32(this.firstEntry),8) + '000000000101'));
            this.log.debug("First entry " + this.accessoryType + ": " + this.firstEntry.toString(16));
            this.log.debug("Last entry " + this.accessoryType + ": " + this.lastEntry.toString(16));
            this.log.debug("Used memory " + this.accessoryType + ": " + this.usedMemory.toString(16));
            this.log.debug("116 " + this.accessoryType + ": " + numToHex(swap32(entry.time-this.refTime-978307200),8) + '00000000' + numToHex(swap32(this.refTime),8) + '0401020202' + this.accessoryType116 +'020f03 ' + numToHex(swap16(this.usedMemory),4) + numToHex(swap16(this.memorySize),4) + numToHex(swap32(this.firstEntry),8) + '000000000101');

        }

        setCurrentS2W1(val, callback) {
            callback(null,val);
            this.log.debug("Data request " + this.accessoryType + ": "+ base64ToHex(val));
            var valHex = base64ToHex(val);
            var substring = valHex.substring(4,12);
            var valInt = parseInt(substring,16);
            var address = swap32(valInt);
            var hexAddress= address.toString('16');

            this.log.debug("Address requested " + this.accessoryType + ": "+ hexAddress);
            //if (this.transfer==false)
            {
                //this.transfer=true;
                this.sendHistory(address);
            }
        }

        setCurrentS2W2(val, callback) {
            this.log.debug("Clock adjust: "+ base64ToHex(val));
            callback(null,val);
        }

    }

    FakeGatoHistoryService = 'E863F007-079E-48FF-8F27-9C2605A29F52';

    return FakeGatoHistoryService;
}
<commit_msg>replace accessoryType strings with constants<commit_after>'use strict';

const TYPE_ENERGY  = 'energy',
      TYPE_ROOM    = 'room',
      TYPE_WEATHER = 'weather';

var homebridge;
var Characteristic, Service;

module.exports = function(pHomebridge) {
	if (pHomebridge && !homebridge) {
		homebridge = pHomebridge;
		Characteristic = homebridge.hap.Characteristic;
		Service = homebridge.hap.Service;
    }

    var hexToBase64 = function(val) {
        return new Buffer((''+val).replace(/[^0-9A-F]/ig, ''), 'hex').toString('base64');
    }, base64ToHex = function(val) {
        if(!val) return val;
        return new Buffer(val, 'base64').toString('hex');
    }, swap16 = function (val) {
        return ((val & 0xFF) << 8)
            | ((val >>> 8) & 0xFF);
    }, swap32 = function (val) {
        return ((val & 0xFF) << 24)
           | ((val & 0xFF00) << 8)
           | ((val >>> 8) & 0xFF00)
           | ((val >>> 24) & 0xFF);
    },	hexToHPA = function(val) {
        return parseInt(swap16(val), 10);
    }, hPAtoHex = function(val) {
        return swap16(Math.round(val)).toString(16);
    }, numToHex = function(val, len) {
        var s = Number(val>>>0).toString(16);
        if(s.length % 2 != 0) {
            s = '0' + s;
        }
        if(len) {
            return ('0000000000000' + s).slice(-1 * len);
        }
    return s;
}

    class S2R1Characteristic extends Characteristic {
        constructor() {
            super('S2R1', 'E863F116-079E-48FF-8F27-9C2605A29F52');
            this.setProps({
                format: Characteristic.Formats.DATA,
                perms: [
                    Characteristic.Perms.READ, Characteristic.Perms.NOTIFY, Characteristic.Perms.HIDDEN
                ]
            });
        }
    }

    S2R1Characteristic.UUID = 'E863F116-079E-48FF-8F27-9C2605A29F52';

    class S2R2Characteristic extends Characteristic {
        constructor() {
            super('S2R2', 'E863F117-079E-48FF-8F27-9C2605A29F52');
            this.setProps({
                format: Characteristic.Formats.DATA,
                perms: [
                    Characteristic.Perms.READ, Characteristic.Perms.NOTIFY, Characteristic.Perms.HIDDEN
                ]
            });
        }
    }

    S2R2Characteristic.UUID = 'E863F117-079E-48FF-8F27-9C2605A29F52';

    class S2W1Characteristic extends Characteristic {
        constructor() {
            super('S2W1', 'E863F11C-079E-48FF-8F27-9C2605A29F52');
            this.setProps({
                format: Characteristic.Formats.DATA,
                perms: [
                    Characteristic.Perms.WRITE, Characteristic.Perms.HIDDEN
                ]
            });
        }
    }

    S2W1Characteristic.UUID = 'E863F11C-079E-48FF-8F27-9C2605A29F52';

    class S2W2Characteristic extends Characteristic {
        constructor() {
            super('S2W2', 'E863F121-079E-48FF-8F27-9C2605A29F52');
            this.setProps({
                format: Characteristic.Formats.DATA,
                perms: [
                    Characteristic.Perms.WRITE, Characteristic.Perms.HIDDEN
                ]
            });
        }
    }

    S2W2Characteristic.UUID = 'E863F121-079E-48FF-8F27-9C2605A29F52';

    class FakeGatoHistoryService extends Service {
        constructor(accessoryType, accessory, size) {
            if (typeof size === 'undefined') { size = 4032; }

            super(accessory.displayName + " History", 'E863F007-079E-48FF-8F27-9C2605A29F52');

            var entry2address = function(val) {
                var temp = val % this.memorySize;
                return temp;
            }.bind(this);

            this.log = accessory.log;
            switch (accessoryType)
            {
                case TYPE_WEATHER:
                    this.accessoryType116 = "03";
                    this.accessoryType117 = "07";
                    break;
                case TYPE_ENERGY:
                    this.accessoryType116 = "07";
                    this.accessoryType117 = "1f";
                    break;
                case TYPE_ROOM:
                    this.accessoryType116 = "04";
                    this.accessoryType117 = "0f";
                    break;
            }

            this.accessoryType=accessoryType;
            this.firstEntry = 0;
            this.lastEntry = 0;
            this.history = [];
            this.memorySize = size;
            this.usedMemory=0;
            this.currentEntry = 1;
            this.transfer=false;
            this.setTime=true;
            this.refTime=0;
            this.memoryAddress=0;
            this.dataStream='';

            this.addCharacteristic(S2R1Characteristic);

            this.addCharacteristic(S2R2Characteristic)
                .on('get', (callback) => {
                    if ((this.currentEntry<this.lastEntry) && (this.transfer==true))
                    {
                        this.memoryAddress = entry2address (this.currentEntry);

                        if ((this.history[this.memoryAddress].temp==0 &&
                            this.history[this.memoryAddress].pressure==0 &&
                            this.history[this.memoryAddress].humidity==0) || (this.history[this.memoryAddress].power==0xFFFF) || (this.setTime==true))
                        {
                            this.log.debug("Data "+ this.accessoryType + ": 15" + numToHex(swap16(this.currentEntry),4) + "0000 0000 0000 81" + numToHex(swap32(this.refTime),8) +"0000 0000 00 0000");
                            callback(null,hexToBase64('15' + numToHex(swap16(this.currentEntry),4) +' 0000 0000 0000 81' + numToHex(swap32(this.refTime),8) + '0000 0000 00 0000'));
                            this.setTime=false;
                            this.currentEntry++;
                        }
                        else
                        {
                            for (var i=0;i<11;i++)
                            {
                                switch (this.accessoryType)
                                {
                                    case TYPE_WEATHER:
                                        this.log.debug(this.accessoryType + " Entry: " + this.currentEntry + ", Address: " + this.memoryAddress);
                                        this.dataStream = this.dataStream + " 10 " + numToHex(swap16(this.currentEntry),4) + " 0000 "
                                            + numToHex(swap32(this.history[this.memoryAddress].time-this.refTime-978307200),8)
                                            + this.accessoryType117
                                            + numToHex(swap16(this.history[this.memoryAddress].temp*100),4)
                                            + numToHex(swap16(this.history[this.memoryAddress].humidity*100),4)
                                            + numToHex(swap16(this.history[this.memoryAddress].pressure*10),4);
                                        break;
                                    case TYPE_ENERGY:
                                        this.log.debug(this.accessoryType + " Entry: " + this.currentEntry + ", Address: " + this.memoryAddress);
                                        this.dataStream = this.dataStream + " 14 " + numToHex(swap16(this.currentEntry),4) + " 0000 "
                                                + numToHex(swap32(this.history[this.memoryAddress].time-this.refTime-978307200),8)
                                                + this.accessoryType117
                                                + "0000 0000"
                                                + numToHex(swap16(this.history[this.memoryAddress].power*10),4)
                                                + "0000 0000";
                                        break;
                                }
                                this.currentEntry++;
                                this.memoryAddress = entry2address (this.currentEntry);
                                if (this.currentEntry==this.lastEntry)
                                {
                                    break;
                                }
                            }
                            this.log.debug("Data " + this.accessoryType + ": " + this.dataStream);
                            callback(null,hexToBase64(this.dataStream));
                            this.dataStream='';
                        }
                    }
                    else
                    {
                        this.transfer=false;
                        callback(null,hexToBase64('00'));
                    }
            });

            this.addCharacteristic(S2W1Characteristic)
                .on('set', this.setCurrentS2W1.bind(this));

            this.addCharacteristic(S2W2Characteristic)
                .on('set', this.setCurrentS2W2.bind(this));

        }

        sendHistory(address){
            var hexAddress= address.toString('16');
            if (address!=0)
                this.currentEntry = address;
            else
                this.currentEntry = 1;
            this.transfer=true;
        }

        //in order to be consistent with Eve, entry address start from 1
        addEntry(entry){

            var entry2address = function(val) {
                return val % this.memorySize;
            }.bind(this);

            if (this.usedMemory<this.memorySize)
            {
                this.usedMemory++;
                this.firstEntry=0;
                this.lastEntry=this.usedMemory;
            }
            else
            {
                this.firstEntry++;
                this.lastEntry = this.firstEntry+this.usedMemory;
            }

            if (this.refTime==0)
                {
                    this.refTime=entry.time-978307200;
                    switch (this.accessoryType)
                        {
                            case TYPE_WEATHER:
                                this.history[this.lastEntry]= {time: entry.time, temp:0, pressure:0, humidity:0};
                                break;
                            case TYPE_ENERGY:
                                this.history[this.lastEntry]= {time: entry.time, power:0xFFFF};
                                break;
                        }
                    this.lastEntry++;
                    this.usedMemory++;
                }

            this.history[entry2address(this.lastEntry)] = (entry);

            this.getCharacteristic(S2R1Characteristic)
                .setValue(hexToBase64(numToHex(swap32(entry.time-this.refTime-978307200),8) + '00000000' + numToHex(swap32(this.refTime),8) + '0401020202' + this.accessoryType116 +'020f03' + numToHex(swap16(this.usedMemory),4) + numToHex(swap16(this.memorySize),4) + numToHex(swap32(this.firstEntry),8) + '000000000101'));
            this.log.debug("First entry " + this.accessoryType + ": " + this.firstEntry.toString(16));
            this.log.debug("Last entry " + this.accessoryType + ": " + this.lastEntry.toString(16));
            this.log.debug("Used memory " + this.accessoryType + ": " + this.usedMemory.toString(16));
            this.log.debug("116 " + this.accessoryType + ": " + numToHex(swap32(entry.time-this.refTime-978307200),8) + '00000000' + numToHex(swap32(this.refTime),8) + '0401020202' + this.accessoryType116 +'020f03 ' + numToHex(swap16(this.usedMemory),4) + numToHex(swap16(this.memorySize),4) + numToHex(swap32(this.firstEntry),8) + '000000000101');

        }

        setCurrentS2W1(val, callback) {
            callback(null,val);
            this.log.debug("Data request " + this.accessoryType + ": "+ base64ToHex(val));
            var valHex = base64ToHex(val);
            var substring = valHex.substring(4,12);
            var valInt = parseInt(substring,16);
            var address = swap32(valInt);
            var hexAddress= address.toString('16');

            this.log.debug("Address requested " + this.accessoryType + ": "+ hexAddress);
            //if (this.transfer==false)
            {
                //this.transfer=true;
                this.sendHistory(address);
            }
        }

        setCurrentS2W2(val, callback) {
            this.log.debug("Clock adjust: "+ base64ToHex(val));
            callback(null,val);
        }

    }

    FakeGatoHistoryService = 'E863F007-079E-48FF-8F27-9C2605A29F52';

    return FakeGatoHistoryService;
}
<|endoftext|>


<commit_before>function CommentsCtrl($scope) {
/*  $scope.comments = [
    {text:'Amaaaaaaaaaazing'},
    {text:'What is this crap?!'}];*/

  $scope.addComment = function() {
    $scope.comments.push({text:$scope.commentText});
    $scope.commentText = '';
  };
}<commit_msg>undoing that<commit_after>function CommentsCtrl($scope) {
  $scope.comments = [
    {text:'Amaaaaaaaaaazing'},
    {text:'What is this crap?!'}];

  $scope.addComment = function() {
    $scope.comments.push({text:$scope.commentText});
    $scope.commentText = '';
  };
}<|endoftext|>