<commit_before>//  Created by Boris Schneiderman.
//  Copyright (c) 2012-2013 The Readium Foundation.
//
//  The Readium SDK is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 *
 * Top level View object. Interface for view manipulation public APIs
 *
 * @class ReadiumSDK.Views.ReaderView
 *
 * */
ReadiumSDK.Views.ReaderView = Backbone.View.extend({

    el: 'body',
    currentView: undefined,
    package: undefined,
    spine: undefined,
    viewerSettings:undefined,

    initialize: function() {

        this.viewerSettings = new ReadiumSDK.Models.ViewerSettings(true, 20, 20);

    },

    renderCurrentView: function(isReflowable) {

        if(this.currentView){

            //current view is already rendered
            if( this.currentView.isReflowable() === isReflowable) {
                return;
            }

            this.resetCurrentView();
        }

        if(isReflowable) {

            this.currentView = new ReadiumSDK.Views.ReflowableView({spine:this.spine});
        }
        else {

            this.currentView = new ReadiumSDK.Views.FixedView({spine:this.spine});
        }

        this.currentView.setViewSettings(this.viewerSettings);

        this.$el.append(this.currentView.render().$el);

        var self = this;
        this.currentView.on("ViewPaginationChanged", function(){

            var paginationReportData = self.currentView.getPaginationInfo();
            self.trigger("PaginationChanged", paginationReportData);

        });

    },

    resetCurrentView: function() {

        if(!this.currentView) {
            return;
        }

        this.currentView.off("ViewPaginationChanged");
        this.currentView.remove();
        this.currentView = undefined;
    },

    /**
     * Triggers the process of opening the book and requesting resources specified in the packageData
     *
     * @method openBook
     * @param {ReadiumSDK.Models.PackageData} packageData DTO Object hierarchy of Package, Spine, SpineItems passed by
     * host application to the reader
     * @param {ReadiumSDK.Models.PageOpenRequest|undefined} openPageRequestData Optional parameter specifying
     * on what page book should be open when it is loaded. If nothing is specified book will be opened on the first page
     */
    openBook: function(packageData, openPageRequestData) {

        this.package = new ReadiumSDK.Models.Package({packageData: packageData});
        this.spine = this.package.spine;

        this.resetCurrentView();

        if(openPageRequestData) {

            if(openPageRequestData.idref) {

                if(openPageRequestData.spineItemPageIndex) {
                    this.openSpineItemPage(openPageRequestData.idref, openPageRequestData.spineItemPageIndex);
                }
                else if(openPageRequestData.elementCfi) {
                    this.openSpineItemElementCfi(openPageRequestData.idref, openPageRequestData.elementCfi);
                }
                else {
                    this.openSpineItemPage(openPageRequestData.idref, 0);
                }
            }
            else if(openPageRequestData.contentRefUrl && openPageRequestData.sourceFileHref) {
                this.openContentUrl(openPageRequestData.contentRefUrl, openPageRequestData.sourceFileHref);
            }
            else {
                console.log("Invalid page request data: idref required!");
            }
        }
        else {// if we where not asked to open specific page we will open the first one

            var spineItem = this.spine.first();
            if(spineItem) {
                var pageOpenRequest = new ReadiumSDK.Models.PageOpenRequest(spineItem);
                pageOpenRequest.setFirstPage();
                this.openPage(pageOpenRequest);
            }

        }

    },

    /**
     * Flips the page from left to right. Takes to account the page progression direction to decide to flip to prev or next page.
     * @method openPageLeft
     */
    openPageLeft: function() {

        if(this.package.spine.isLeftToRight()) {
            this.openPagePrev();
        }
        else {
            this.openPageNext();
        }
    },

    /**
     * Flips the page from right to left. Takes to account the page progression direction to decide to flip to prev or next page.
     * @method openPageRight
     */
    openPageRight: function() {

        if(this.package.spine.isLeftToRight()) {
            this.openPageNext();
        }
        else {
            this.openPagePrev();
        }

    },

    /**
     * Updates reader view based on the settings specified in settingsData object
     * @param settingsData
     */
    updateSettings: function(settingsData) {

        console.log("UpdateSettings: " + JSON.stringify(settingsData));

        this.viewerSettings.update(settingsData);

        if(this.currentView) {

            var bookMark = this.currentView.bookmarkCurrentPage();

            this.currentView.setViewSettings(this.viewerSettings);

            if(bookMark) {
                this.openSpineItemElementCfi(bookMark.idref, bookMark.elementCfi);
            }
        }
    },

    /**
     * Opens the next page.
     */
    openPageNext: function() {

        var paginationInfo = this.currentView.getPaginationInfo();

        if(paginationInfo.openPages.length == 0) {
            return;
        }

        var lastOpenPage = paginationInfo.openPages[paginationInfo.openPages.length - 1];

        if(lastOpenPage.spineItemPageIndex < lastOpenPage.spineItemPageCount - 1) {
            this.currentView.openPageNext();
            return;
        }

        var currentSpineItem = this.spine.getItemById(lastOpenPage.idref);

        var nextSpineItem = this.spine.nextItem(currentSpineItem);

        if(!nextSpineItem) {
            return;
        }

        var openPageRequest = new ReadiumSDK.Models.PageOpenRequest(nextSpineItem);
        openPageRequest.setFirstPage();

        this.openPage(openPageRequest);
    },

    /**
     * Opens the previews page.
     */
    openPagePrev: function() {

        var paginationInfo = this.currentView.getPaginationInfo();

        if(paginationInfo.openPages.length == 0) {
            return;
        }

        var firstOpenPage = paginationInfo.openPages[0];

        if(firstOpenPage.spineItemPageIndex > 0) {
            this.currentView.openPagePrev();
            return;
        }

        var currentSpineItem = this.spine.getItemById(firstOpenPage.idref);

        var prevSpineItem = this.spine.prevItem(currentSpineItem);

        if(!prevSpineItem) {
            return;
        }

        var openPageRequest = new ReadiumSDK.Models.PageOpenRequest(prevSpineItem);
        openPageRequest.setLastPage();

        this.openPage(openPageRequest);
    },

    getSpineItem: function(idref) {

        if(!idref) {

            console.log("idref parameter value missing!");
            return undefined;
        }

        var spineItem = this.spine.getItemById(idref);
        if(!spineItem) {
            console.log("Spine item with id " + idref + " not found!");
            return undefined;
        }

        return spineItem;

    },

    /**
     * Opens the page of the spine item with element with provided cfi
     *
     * @method openSpineItemElementCfi
     *
     * @param {string} idref Id of the spine item
     * @param {string} elementCfi CFI of the element to be shown
     */
    openSpineItemElementCfi: function(idref, elementCfi) {

        var spineItem = this.getSpineItem(idref);

        if(!spineItem) {
            return;
        }

        var pageData = new ReadiumSDK.Models.PageOpenRequest(spineItem);
        if(elementCfi) {
            pageData.setElementCfi(elementCfi);
        }

        this.openPage(pageData);
    },

    /**
     *
     * Opens specified page index of the current spine item
     *
     * @method openPageIndex
     *
     * @param {number} pageIndex Zero based index of the page in the current spine item
     */
    openPageIndex: function(pageIndex) {

        if(!this.currentView) {
            return;
        }

        var pageRequest;
        if(this.package.isFixedLayout()) {
            var spineItem = this.package.spine.items[pageIndex];
            if(!spineItem) {
                return;
            }

            pageRequest = new ReadiumSDK.Models.PageOpenRequest(spineItem);
            pageRequest.setPageIndex(0);
        }
        else {

            pageRequest = new ReadiumSDK.Models.PageOpenRequest(undefined);
            pageRequest.setPageIndex(pageIndex);

        }

        this.openPage(pageRequest);
    },

    openPage: function(pageRequest) {

        this.renderCurrentView(pageRequest.spineItem.isReflowable());
        this.currentView.openPage(pageRequest);
    },

    /**
     *
     * Opens page index of the spine item with idref provided
     *
     * @param {string} idref Id of the spine item
     * @param {number} pageIndex Zero based index of the page in the spine item
     */
    openSpineItemPage: function(idref, pageIndex) {

        var spineItem = this.getSpineItem(idref);

        if(!spineItem) {
            return;
        }

        var pageData = new ReadiumSDK.Models.PageOpenRequest(spineItem);
        if(pageIndex) {
            pageData.setPageIndex(pageIndex);
        }

        this.openPage(pageData);
    },

    /**
     * Opens the content document specified by the url
     *
     * @method openContentUrl
     *
     * @param {string} contentRefUrl Url of the content document
     * @param {string | undefined} sourceFileHref Url to the file that contentRefUrl is relative to. If contentRefUrl is
     * relative ot the source file that contains it instead of the package file (ex. TOC file) We have to know the
     * sourceFileHref to resolve contentUrl relative to the package file.
     *
     */
    openContentUrl: function(contentRefUrl, sourceFileHref) {

        var combinedPath = ReadiumSDK.Helpers.ResolveContentRef(contentRefUrl, sourceFileHref);

        var hashIndex = combinedPath.indexOf("#");
        var hrefPart;
        var elementId;
        if(hashIndex >= 0) {
            hrefPart = combinedPath.substr(0, hashIndex);
            elementId = combinedPath.substr(hashIndex + 1);
        }
        else {
            hrefPart = combinedPath;
            elementId = undefined;
        }

        var spineItem = this.spine.getItemByHref(hrefPart);

        if(!spineItem) {
            return;
        }

        var pageData = new ReadiumSDK.Models.PageOpenRequest(spineItem)
        if(elementId){
            pageData.setElementId(elementId);
        }

        this.openPage(pageData);
    },

    /**
     *
     * Returns the bookmark associated with currently opened page.
     *
     * @method bookmarkCurrentPage
     *
     * @returns {string} Stringified ReadiumSDK.Models.BookmarkData object.
     */
    bookmarkCurrentPage: function() {
        return JSON.stringify(this.currentView.bookmarkCurrentPage());
    }

});<commit_msg>added SettingsApplied event<commit_after>//  Created by Boris Schneiderman.
//  Copyright (c) 2012-2013 The Readium Foundation.
//
//  The Readium SDK is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 *
 * Top level View object. Interface for view manipulation public APIs
 *
 * @class ReadiumSDK.Views.ReaderView
 *
 * */
ReadiumSDK.Views.ReaderView = Backbone.View.extend({

    el: 'body',
    currentView: undefined,
    package: undefined,
    spine: undefined,
    viewerSettings:undefined,

    initialize: function() {

        this.viewerSettings = new ReadiumSDK.Models.ViewerSettings(true, 20, 20);

    },

    renderCurrentView: function(isReflowable) {

        if(this.currentView){

            //current view is already rendered
            if( this.currentView.isReflowable() === isReflowable) {
                return;
            }

            this.resetCurrentView();
        }

        if(isReflowable) {

            this.currentView = new ReadiumSDK.Views.ReflowableView({spine:this.spine});
        }
        else {

            this.currentView = new ReadiumSDK.Views.FixedView({spine:this.spine});
        }

        this.currentView.setViewSettings(this.viewerSettings);

        this.$el.append(this.currentView.render().$el);

        var self = this;
        this.currentView.on("ViewPaginationChanged", function(){

            var paginationReportData = self.currentView.getPaginationInfo();
            self.trigger("PaginationChanged", paginationReportData);

        });

    },

    resetCurrentView: function() {

        if(!this.currentView) {
            return;
        }

        this.currentView.off("ViewPaginationChanged");
        this.currentView.remove();
        this.currentView = undefined;
    },

    /**
     * Triggers the process of opening the book and requesting resources specified in the packageData
     *
     * @method openBook
     * @param {ReadiumSDK.Models.PackageData} packageData DTO Object hierarchy of Package, Spine, SpineItems passed by
     * host application to the reader
     * @param {ReadiumSDK.Models.PageOpenRequest|undefined} openPageRequestData Optional parameter specifying
     * on what page book should be open when it is loaded. If nothing is specified book will be opened on the first page
     */
    openBook: function(packageData, openPageRequestData) {

        this.package = new ReadiumSDK.Models.Package({packageData: packageData});
        this.spine = this.package.spine;

        this.resetCurrentView();

        if(openPageRequestData) {

            if(openPageRequestData.idref) {

                if(openPageRequestData.spineItemPageIndex) {
                    this.openSpineItemPage(openPageRequestData.idref, openPageRequestData.spineItemPageIndex);
                }
                else if(openPageRequestData.elementCfi) {
                    this.openSpineItemElementCfi(openPageRequestData.idref, openPageRequestData.elementCfi);
                }
                else {
                    this.openSpineItemPage(openPageRequestData.idref, 0);
                }
            }
            else if(openPageRequestData.contentRefUrl && openPageRequestData.sourceFileHref) {
                this.openContentUrl(openPageRequestData.contentRefUrl, openPageRequestData.sourceFileHref);
            }
            else {
                console.log("Invalid page request data: idref required!");
            }
        }
        else {// if we where not asked to open specific page we will open the first one

            var spineItem = this.spine.first();
            if(spineItem) {
                var pageOpenRequest = new ReadiumSDK.Models.PageOpenRequest(spineItem);
                pageOpenRequest.setFirstPage();
                this.openPage(pageOpenRequest);
            }

        }

    },

    /**
     * Flips the page from left to right. Takes to account the page progression direction to decide to flip to prev or next page.
     * @method openPageLeft
     */
    openPageLeft: function() {

        if(this.package.spine.isLeftToRight()) {
            this.openPagePrev();
        }
        else {
            this.openPageNext();
        }
    },

    /**
     * Flips the page from right to left. Takes to account the page progression direction to decide to flip to prev or next page.
     * @method openPageRight
     */
    openPageRight: function() {

        if(this.package.spine.isLeftToRight()) {
            this.openPageNext();
        }
        else {
            this.openPagePrev();
        }

    },

    /**
     * Updates reader view based on the settings specified in settingsData object
     * @param settingsData
     */
    updateSettings: function(settingsData) {

        console.log("UpdateSettings: " + JSON.stringify(settingsData));

        this.viewerSettings.update(settingsData);

        if(this.currentView) {

            var bookMark = this.currentView.bookmarkCurrentPage();

            this.currentView.setViewSettings(this.viewerSettings);

            if(bookMark) {
                this.openSpineItemElementCfi(bookMark.idref, bookMark.elementCfi);
            }
        }

        this.trigger("SettingsApplied");
    },

    /**
     * Opens the next page.
     */
    openPageNext: function() {

        var paginationInfo = this.currentView.getPaginationInfo();

        if(paginationInfo.openPages.length == 0) {
            return;
        }

        var lastOpenPage = paginationInfo.openPages[paginationInfo.openPages.length - 1];

        if(lastOpenPage.spineItemPageIndex < lastOpenPage.spineItemPageCount - 1) {
            this.currentView.openPageNext();
            return;
        }

        var currentSpineItem = this.spine.getItemById(lastOpenPage.idref);

        var nextSpineItem = this.spine.nextItem(currentSpineItem);

        if(!nextSpineItem) {
            return;
        }

        var openPageRequest = new ReadiumSDK.Models.PageOpenRequest(nextSpineItem);
        openPageRequest.setFirstPage();

        this.openPage(openPageRequest);
    },

    /**
     * Opens the previews page.
     */
    openPagePrev: function() {

        var paginationInfo = this.currentView.getPaginationInfo();

        if(paginationInfo.openPages.length == 0) {
            return;
        }

        var firstOpenPage = paginationInfo.openPages[0];

        if(firstOpenPage.spineItemPageIndex > 0) {
            this.currentView.openPagePrev();
            return;
        }

        var currentSpineItem = this.spine.getItemById(firstOpenPage.idref);

        var prevSpineItem = this.spine.prevItem(currentSpineItem);

        if(!prevSpineItem) {
            return;
        }

        var openPageRequest = new ReadiumSDK.Models.PageOpenRequest(prevSpineItem);
        openPageRequest.setLastPage();

        this.openPage(openPageRequest);
    },

    getSpineItem: function(idref) {

        if(!idref) {

            console.log("idref parameter value missing!");
            return undefined;
        }

        var spineItem = this.spine.getItemById(idref);
        if(!spineItem) {
            console.log("Spine item with id " + idref + " not found!");
            return undefined;
        }

        return spineItem;

    },

    /**
     * Opens the page of the spine item with element with provided cfi
     *
     * @method openSpineItemElementCfi
     *
     * @param {string} idref Id of the spine item
     * @param {string} elementCfi CFI of the element to be shown
     */
    openSpineItemElementCfi: function(idref, elementCfi) {

        var spineItem = this.getSpineItem(idref);

        if(!spineItem) {
            return;
        }

        var pageData = new ReadiumSDK.Models.PageOpenRequest(spineItem);
        if(elementCfi) {
            pageData.setElementCfi(elementCfi);
        }

        this.openPage(pageData);
    },

    /**
     *
     * Opens specified page index of the current spine item
     *
     * @method openPageIndex
     *
     * @param {number} pageIndex Zero based index of the page in the current spine item
     */
    openPageIndex: function(pageIndex) {

        if(!this.currentView) {
            return;
        }

        var pageRequest;
        if(this.package.isFixedLayout()) {
            var spineItem = this.package.spine.items[pageIndex];
            if(!spineItem) {
                return;
            }

            pageRequest = new ReadiumSDK.Models.PageOpenRequest(spineItem);
            pageRequest.setPageIndex(0);
        }
        else {

            pageRequest = new ReadiumSDK.Models.PageOpenRequest(undefined);
            pageRequest.setPageIndex(pageIndex);

        }

        this.openPage(pageRequest);
    },

    openPage: function(pageRequest) {

        this.renderCurrentView(pageRequest.spineItem.isReflowable());
        this.currentView.openPage(pageRequest);
    },

    /**
     *
     * Opens page index of the spine item with idref provided
     *
     * @param {string} idref Id of the spine item
     * @param {number} pageIndex Zero based index of the page in the spine item
     */
    openSpineItemPage: function(idref, pageIndex) {

        var spineItem = this.getSpineItem(idref);

        if(!spineItem) {
            return;
        }

        var pageData = new ReadiumSDK.Models.PageOpenRequest(spineItem);
        if(pageIndex) {
            pageData.setPageIndex(pageIndex);
        }

        this.openPage(pageData);
    },

    /**
     * Opens the content document specified by the url
     *
     * @method openContentUrl
     *
     * @param {string} contentRefUrl Url of the content document
     * @param {string | undefined} sourceFileHref Url to the file that contentRefUrl is relative to. If contentRefUrl is
     * relative ot the source file that contains it instead of the package file (ex. TOC file) We have to know the
     * sourceFileHref to resolve contentUrl relative to the package file.
     *
     */
    openContentUrl: function(contentRefUrl, sourceFileHref) {

        var combinedPath = ReadiumSDK.Helpers.ResolveContentRef(contentRefUrl, sourceFileHref);

        var hashIndex = combinedPath.indexOf("#");
        var hrefPart;
        var elementId;
        if(hashIndex >= 0) {
            hrefPart = combinedPath.substr(0, hashIndex);
            elementId = combinedPath.substr(hashIndex + 1);
        }
        else {
            hrefPart = combinedPath;
            elementId = undefined;
        }

        var spineItem = this.spine.getItemByHref(hrefPart);

        if(!spineItem) {
            return;
        }

        var pageData = new ReadiumSDK.Models.PageOpenRequest(spineItem)
        if(elementId){
            pageData.setElementId(elementId);
        }

        this.openPage(pageData);
    },

    /**
     *
     * Returns the bookmark associated with currently opened page.
     *
     * @method bookmarkCurrentPage
     *
     * @returns {string} Stringified ReadiumSDK.Models.BookmarkData object.
     */
    bookmarkCurrentPage: function() {
        return JSON.stringify(this.currentView.bookmarkCurrentPage());
    }

});<|endoftext|>


<commit_before>'use babel'

export default [
  {
    scopes: ['source.js', 'source.js.jsx', 'source.coffee', 'source.coffee.jsx', 'source.ts', 'source.tsx', 'text.html.vue'],
    prefixes: [
      'import\\s+.*?from\\s+[\'"]', // import foo from './foo'
      'import\s+[\'"]', // import './foo'
      'require\\([\'"]', // require('./foo')
      'define\\(\\[?[\'"]' // define(['./foo']) or define('./foo')
    ],
    extensions: ['js', 'jsx', 'vue', 'ts', 'tsx', 'coffee'],
    relative: true,
    replaceOnInsert: [
      ['.jsx?$', ''],
      ['.vue$', ''],
      ['.ts$', ''],
      ['.coffee$', '']
    ]
  },
  {
    scopes: ['source.coffee', 'source.coffee.jsx'],
    prefixes: [
      'require\\s+[\'"]', // require './foo'
      'define\\s+\\[?[\'"]' // define(['./foo']) or define('./foo')
    ],
    extensions: ['js', 'jsx', 'ts', 'tsx', 'coffee'],
    relative: true,
    replaceOnInsert: [
      ['.jsx?$', ''],
      ['.ts$', ''],
      ['.coffee$', '']
    ]
  },
  {
    scopes: ['source.php'],
    prefixes: [
      'require_once\\([\'"]', // require_once('foo.php')
      'include\\([\'"]' // include('./foo.php')
    ],
    extensions: ['php'],
    relative: true
  },
  {
    scopes: ['source.sass', 'source.css.scss', 'source.less', 'source.stylus'],
    prefixes: [
      '@import[\\(|\\s+]?[\'"]' // @import 'foo' or @import('foo')
    ],
    extensions: ['sass', 'scss', 'css'],
    relative: true,
    replaceOnInsert: [
      ['(/)?_([^/]*?)$', '$1$2'] // dir1/_dir2/_file.sass => dir1/_dir2/file.sass
    ]
  },
  {
    scopes: ['source.css'],
    prefixes: [
      '@import\s+[\'"]?', // @import 'foo.css'
      '@import\s+url\\([\'"]?' // @import url('foo.css')
    ],
    extensions: ['css'],
    relative: true
  },
  {
    scopes: ['source.css', 'source.sass', 'source.less', 'source.css.scss', 'source.stylus'],
    prefixes: [
      'url\\([\'"]?'
    ],
    extensions: ['png', 'gif', 'jpeg', 'jpg', 'woff', 'ttf', 'svg', 'otf'],
    relative: true
  },
  {
    scopes: ['source.c', 'source.cpp'],
    prefixes: [
      '^\\s*#include\\s+[\'"]'
    ],
    extensions: ['h', 'hpp'],
    relative: true,
    includeCurrentDirectory: false
  },
  {
    scopes: ['source.lua'],
    prefixes: [
      'require[\s+|\\(][\'"]'
    ],
    extensions: ['lua'],
    relative: true,
    includeCurrentDirectory: false,
    replaceOnInsert: [
      ['\\/', '.'],
      ['\\\\', '.'],
      ['\\.lua$', '']
    ]
  },
  {
    scopes: ['source.ruby'],
    prefixes: [
      '^\\s*require[\\s+|\\(][\'"]'
    ],
    extensions: ['rb'],
    relative: true,
    includeCurrentDirectory: false,
    replaceOnInsert: [
      ['\\.rb$', '']
    ]
  },
  {
    scopes: ['source.python'],
    prefixes: [
      '^\\s*from\\s+',
      '^\\s*import\\s+'
    ],
    extensions: ['py'],
    relative: true,
    includeCurrentDirectory: false,
    replaceOnInsert: [
      ['\\/', '.'],
      ['\\\\', '.'],
      ['\\.py$', '']
    ]
  }
]
<commit_msg>:sparkles: Better .vue support<commit_after>'use babel'

export default [
  {
    scopes: ['source.js', 'source.js.jsx', 'source.coffee', 'source.coffee.jsx', 'source.ts', 'source.tsx'],
    prefixes: [
      'import\\s+.*?from\\s+[\'"]', // import foo from './foo'
      'import\\s+[\'"]', // import './foo'
      'require\\([\'"]', // require('./foo')
      'define\\(\\[?[\'"]' // define(['./foo']) or define('./foo')
    ],
    extensions: ['js', 'jsx', 'ts', 'tsx', 'coffee'],
    relative: true,
    replaceOnInsert: [
      ['.jsx?$', ''],
      ['.ts$', ''],
      ['.coffee$', '']
    ]
  },
  {
    scopes: ['text.html.vue'],
    prefixes: [
      'import\\s+.*?from\\s+[\'"]', // import foo from './foo'
      'import\\s+[\'"]', // import './foo'
      'require\\([\'"]', // require('./foo')
      'define\\(\\[?[\'"]' // define(['./foo']) or define('./foo')
    ],
    extensions: ['js', 'jsx', 'vue', 'ts', 'tsx', 'coffee'],
    relative: true,
    replaceOnInsert: [
      ['.jsx?$', ''],
      ['.ts$', ''],
      ['.coffee$', '']
    ]
  },
  {
    scopes: ['text.html.vue'],
    prefixes: [
      '@import[\\(|\\s+]?[\'"]' // @import 'foo' or @import('foo')
    ],
    extensions: ['css', 'sass', 'scss', 'less', 'styl'],
    relative: true,
    replaceOnInsert: [
      ['(/)?_([^/]*?)$', '$1$2'] // dir1/_dir2/_file.sass => dir1/_dir2/file.sass
    ]
  },
  {
    scopes: ['source.coffee', 'source.coffee.jsx'],
    prefixes: [
      'require\\s+[\'"]', // require './foo'
      'define\\s+\\[?[\'"]' // define(['./foo']) or define('./foo')
    ],
    extensions: ['js', 'jsx', 'ts', 'tsx', 'coffee'],
    relative: true,
    replaceOnInsert: [
      ['.jsx?$', ''],
      ['.ts$', ''],
      ['.coffee$', '']
    ]
  },
  {
    scopes: ['source.php'],
    prefixes: [
      'require_once\\([\'"]', // require_once('foo.php')
      'include\\([\'"]' // include('./foo.php')
    ],
    extensions: ['php'],
    relative: true
  },
  {
    scopes: ['source.sass', 'source.css.scss', 'source.less', 'source.stylus'],
    prefixes: [
      '@import[\\(|\\s+]?[\'"]' // @import 'foo' or @import('foo')
    ],
    extensions: ['sass', 'scss', 'css'],
    relative: true,
    replaceOnInsert: [
      ['(/)?_([^/]*?)$', '$1$2'] // dir1/_dir2/_file.sass => dir1/_dir2/file.sass
    ]
  },
  {
    scopes: ['source.css'],
    prefixes: [
      '@import\\s+[\'"]?', // @import 'foo.css'
      '@import\\s+url\\([\'"]?' // @import url('foo.css')
    ],
    extensions: ['css'],
    relative: true
  },
  {
    scopes: ['source.css', 'source.sass', 'source.less', 'source.css.scss', 'source.stylus'],
    prefixes: [
      'url\\([\'"]?'
    ],
    extensions: ['png', 'gif', 'jpeg', 'jpg', 'woff', 'ttf', 'svg', 'otf'],
    relative: true
  },
  {
    scopes: ['source.c', 'source.cpp'],
    prefixes: [
      '^\\s*#include\\s+[\'"]'
    ],
    extensions: ['h', 'hpp'],
    relative: true,
    includeCurrentDirectory: false
  },
  {
    scopes: ['source.lua'],
    prefixes: [
      'require[\\s+|\\(][\'"]'
    ],
    extensions: ['lua'],
    relative: true,
    includeCurrentDirectory: false,
    replaceOnInsert: [
      ['\\/', '.'],
      ['\\\\', '.'],
      ['\\.lua$', '']
    ]
  },
  {
    scopes: ['source.ruby'],
    prefixes: [
      '^\\s*require[\\s+|\\(][\'"]'
    ],
    extensions: ['rb'],
    relative: true,
    includeCurrentDirectory: false,
    replaceOnInsert: [
      ['\\.rb$', '']
    ]
  },
  {
    scopes: ['source.python'],
    prefixes: [
      '^\\s*from\\s+',
      '^\\s*import\\s+'
    ],
    extensions: ['py'],
    relative: true,
    includeCurrentDirectory: false,
    replaceOnInsert: [
      ['\\/', '.'],
      ['\\\\', '.'],
      ['\\.py$', '']
    ]
  }
]
<|endoftext|>


<commit_before>/* SQB
 ------------------------
 (c) 2017-present Panates
 SQB may be freely distributed under the MIT license.
 For details and documentation:
 https://panates.github.io/sqb/
 */

/**
 * Module dependencies.
 * @private
 */
const debug = require('debug')('sqb:Connection');
const merge = require('putil-merge');
const {AdapterError} = require('../errors');
const Cursor = require('./Cursor');
const normalizeRows = require('../helper/normalizeRows');
const waterfall = require('putil-waterfall');

/**
 *
 * @class
 */
class PreparedQuery {

  /**
   * @param {Connection} connection
   * @param {String|Query} query
   * @param {Object} options
   * @constructor
   * @public
   */
  constructor(connection, query, options) {
    this.connection = connection;
    this.onExecute = [];
    this.onFetch = [];
    this.query = {sql: null};

    options = options || {};
    const defaults = this.pool.config.defaults;

    this.options = {
      autoCommit: options.autoCommit != null ? options.autoCommit :
          connection.autoCommit,
      cursor: options.cursor != null ? options.cursor : defaults.cursor,
      objectRows: options.objectRows != null ? options.objectRows :
          (defaults.objectRows != null ? defaults.objectRows : true),
      ignoreNulls: options.ignoreNulls != null ?
          options.ignoreNulls : defaults.ignoreNulls,
      fetchRows: options.fetchRows != null ?
          options.fetchRows : defaults.fetchRows,
      naming: options.naming || defaults.naming,
      fetchAsString: Array.isArray(options.fetchAsString) ? options.fetchAsString :
          (options.fetchAsString ? [options.fetchAsString] : undefined),
      showSql: options.showSql != null ? options.showSql : defaults.showSql,
      action: options.action
    };
    this.options.ignoreNulls =
        this.options.objectRows && this.options.ignoreNulls;

    if (typeof query === 'object' &&
        typeof query.generate === 'function') {
      let o = merge.clone(this.pool.config);
      o.values = query.values;
      o.prettyPrint = options.prettyPrint != null ? options.prettyPrint :
          (defaults.prettyPrint != null ? defaults.prettyPrint : true);
      o = query.generate(o, false);
      this.query.sql = o.sql;
      if (o.values)
        this.query.values = o.values;
      if (o.returningParams)
        this.query.returningParams = o.returningParams;
      if (this.options.fetchRows == null)
        this.options.fetchRows = query._limit;
      if (this.options.action === null)
        this.options.action = query._action;
      if (query.listenerCount('execute'))
        this.onExecute.push(...query.listeners('execute'));
      if (query.listenerCount('fetch')) {
        this.onFetch.push(...query.listeners('fetch'));
      }
    } else {
      this.query.sql = String(query);
      if (options.values)
        this.query.values = options.values;
      if (options.returningParams)
        this.query.returningParams = options.returningParams;
    }

    if (this.options.fetchRows == null)
      this.options.fetchRows = 100;

    for (const key of Object.getOwnPropertyNames(this.options)) {
      if (this.options[key] == null)
        delete this.options[key];
    }

  }

  get pool() {
    return this.connection.pool;
  }

  execute() {
    const startTime = Date.now();
    const conn = this.connection;
    /* istanbul ignore next */
    if (process.env.DEBUG)
      debug('[%s] execute | %o', conn.sessionId, this.options);
    conn.emitSafe('execute', conn, this.options);

    /* Keep connection alive */
    conn.acquire();
    /* Call execute hooks */
    return this.callExecuteHooks(conn).then(() => {
      /* Execute query */

      return conn._client.execute(this.query, this.options).then(response => {

        if (!response)
          throw new AdapterError('Database adapter returned empty response');

        const result = {
          executeTime: Date.now() - startTime
        };

        const fields = {};
        /* istanbul ignore else */
        if (response.fields) {
          let i = 0;
          for (const f of response.fields) {
            const name = f.name &&
                (this.options.naming === 'lowercase' ? f.name.toLowerCase() :
                    (this.options.naming === 'uppercase' ?
                        f.name.toUpperCase() : f.name));
            fields[name] = merge({index: i++}, f);
            delete fields[name].name;
          }
          response.fields = fields;
        }

        if (response.cursor) {
          result.cursor = new Cursor(this, response);

        } else if (response.rows) {
          /* Normalize rows */
          normalizeRows(response.rows, this.options);
          this.callFetchHooks(response.rows);
          result.fields = response.fields;
          result.rows = response.rows;
        } else if (response.returns)
          result.returns = response.returns;

        if (this.options.showSql) {
          result.query = this.query;
          result.options = this.options;
        }

        return result;

      }).catch(err => {
        err = new AdapterError(err);
        err.query = this.query;
        err.options = this.options;
        throw err;
      });
    }).finally(() => conn.release());
  }

  callExecuteHooks(conn) {
    return waterfall.every(this.onExecute, (next, fn) => {
      return Promise.try(() => fn(conn, this.query, this.options));
    });
  }

  callFetchHooks(rows) {
    for (const row of rows) {
      for (const fn of this.onFetch)
        fn(row, this.options);
    }
  }

}

/**
 * Expose `PreparedQuery`.
 */
module.exports = PreparedQuery;
<commit_msg>[-] Fixed. Can not pass values to query.execute<commit_after>/* SQB
 ------------------------
 (c) 2017-present Panates
 SQB may be freely distributed under the MIT license.
 For details and documentation:
 https://panates.github.io/sqb/
 */

/**
 * Module dependencies.
 * @private
 */
const debug = require('debug')('sqb:Connection');
const merge = require('putil-merge');
const {AdapterError} = require('../errors');
const Cursor = require('./Cursor');
const normalizeRows = require('../helper/normalizeRows');
const waterfall = require('putil-waterfall');

/**
 *
 * @class
 */
class PreparedQuery {

  /**
   * @param {Connection} connection
   * @param {String|Query} query
   * @param {Object} options
   * @constructor
   * @public
   */
  constructor(connection, query, options) {
    this.connection = connection;
    this.onExecute = [];
    this.onFetch = [];
    this.query = {sql: null};

    options = options || {};
    const defaults = this.pool.config.defaults;

    this.options = {
      autoCommit: options.autoCommit != null ? options.autoCommit :
          connection.autoCommit,
      cursor: options.cursor != null ? options.cursor : defaults.cursor,
      objectRows: options.objectRows != null ? options.objectRows :
          (defaults.objectRows != null ? defaults.objectRows : true),
      ignoreNulls: options.ignoreNulls != null ?
          options.ignoreNulls : defaults.ignoreNulls,
      fetchRows: options.fetchRows != null ?
          options.fetchRows : defaults.fetchRows,
      naming: options.naming || defaults.naming,
      fetchAsString: Array.isArray(options.fetchAsString) ? options.fetchAsString :
          (options.fetchAsString ? [options.fetchAsString] : undefined),
      showSql: options.showSql != null ? options.showSql : defaults.showSql,
      action: options.action
    };
    this.options.ignoreNulls =
        this.options.objectRows && this.options.ignoreNulls;

    if (typeof query === 'object' &&
        typeof query.generate === 'function') {
      let o = merge.clone(this.pool.config);
      o.values = options.values;
      o.prettyPrint = options.prettyPrint != null ? options.prettyPrint :
          (defaults.prettyPrint != null ? defaults.prettyPrint : true);
      o = query.generate(o, false);
      this.query.sql = o.sql;
      if (o.values)
        this.query.values = o.values;
      if (o.returningParams)
        this.query.returningParams = o.returningParams;
      if (this.options.fetchRows == null)
        this.options.fetchRows = query._limit;
      if (this.options.action === null)
        this.options.action = query._action;
      if (query.listenerCount('execute'))
        this.onExecute.push(...query.listeners('execute'));
      if (query.listenerCount('fetch')) {
        this.onFetch.push(...query.listeners('fetch'));
      }
    } else {
      this.query.sql = String(query);
      if (options.values)
        this.query.values = options.values;
      if (options.returningParams)
        this.query.returningParams = options.returningParams;
    }

    if (this.options.fetchRows == null)
      this.options.fetchRows = 100;

    for (const key of Object.getOwnPropertyNames(this.options)) {
      if (this.options[key] == null)
        delete this.options[key];
    }

  }

  get pool() {
    return this.connection.pool;
  }

  execute() {
    const startTime = Date.now();
    const conn = this.connection;
    /* istanbul ignore next */
    if (process.env.DEBUG)
      debug('[%s] execute | %o', conn.sessionId, this.options);
    conn.emitSafe('execute', conn, this.options);

    /* Keep connection alive */
    conn.acquire();
    /* Call execute hooks */
    return this.callExecuteHooks(conn).then(() => {
      /* Execute query */

      return conn._client.execute(this.query, this.options).then(response => {

        if (!response)
          throw new AdapterError('Database adapter returned empty response');

        const result = {
          executeTime: Date.now() - startTime
        };

        const fields = {};
        /* istanbul ignore else */
        if (response.fields) {
          let i = 0;
          for (const f of response.fields) {
            const name = f.name &&
                (this.options.naming === 'lowercase' ? f.name.toLowerCase() :
                    (this.options.naming === 'uppercase' ?
                        f.name.toUpperCase() : f.name));
            fields[name] = merge({index: i++}, f);
            delete fields[name].name;
          }
          response.fields = fields;
        }

        if (response.cursor) {
          result.cursor = new Cursor(this, response);

        } else if (response.rows) {
          /* Normalize rows */
          normalizeRows(response.rows, this.options);
          this.callFetchHooks(response.rows);
          result.fields = response.fields;
          result.rows = response.rows;
        } else if (response.returns)
          result.returns = response.returns;

        if (this.options.showSql) {
          result.query = this.query;
          result.options = this.options;
        }

        return result;

      }).catch(err => {
        err = new AdapterError(err);
        err.query = this.query;
        err.options = this.options;
        throw err;
      });
    }).finally(() => conn.release());
  }

  callExecuteHooks(conn) {
    return waterfall.every(this.onExecute, (next, fn) => {
      return Promise.try(() => fn(conn, this.query, this.options));
    });
  }

  callFetchHooks(rows) {
    for (const row of rows) {
      for (const fn of this.onFetch)
        fn(row, this.options);
    }
  }

}

/**
 * Expose `PreparedQuery`.
 */
module.exports = PreparedQuery;
<|endoftext|>


<commit_before>var RippleRestClient = require('ripple-rest-client');
var uuid = require('node-uuid');
var async = require('async');
var gateway = require(__dirname+'/../../');
var hotWallet = gateway.config.get('HOT_WALLET');

function OutgoingPayment(outgoingPaymentRecord) {
  this.record = outgoingPaymentRecord;
  this.rippleRestClient = new RippleRestClient({
    account: hotWallet.address,
    secret: hotWallet.secret
  });
}

OutgoingPayment.prototype = {

  processOutgoingPayment: function(callback) {
    var self = this;
    async.waterfall([
      function(next) {
        self._getRippleAddressRecord(next);
      },
      function(address, next) {
        self._buildPayment(address, next);
      },
      function(payment, next) {
        self._sendPayment(payment, next);
      },
      function(response, next) {
        self._markRecordAsSent(response, next);
      },
      function(response, next) {
        self._confirmSuccessfulPayment(response, next);
      }
    ], function(error) {
      if (error) {
        self._handleRippleRestFailure(error, function() {
          logger.error('payments:outgoing:failed', error, self.record.toJSON());
          callback(error, self.record);
        });
      } else {
        logger.info('payment:outgoing:succeeded', self.record.toJSON());
        callback(error, self.record);
      }
    });
  },

  _recordAcceptanceOrRejectionStatus: function(payment, callback) {
    var self = this;
    self.record.transaction_state = payment.result;
    self.record.transaction_hash = payment.hash;
    switch(self.record.transaction_state) {
    case 'tesSUCCESS':
      self.record.state = 'succeeded';
      break;
    default:
      self.record.state = 'failed';
    }
    self.record.save().complete(function(error, record){
      //depositCallbackJob.perform([self.record.id], console.log);
      callback(null, record);
    });
  },

  _confirmSuccessfulPayment: function(response, callback) {
    var statusUrl = response.status_url;
    var self = this;
    self.rippleRestClient.pollPaymentStatus(statusUrl, function(error, paymentStatus) {
      if (error) {
        return callback(error, null);
      }
      self._recordAcceptanceOrRejectionStatus(paymentStatus, function(error, record) {
        callback(null, record);
      });
    });
  },

  _markRecordAsSent: function(response, callback) {
    var self = this;
    self.record.state = 'sent';
    self.record.uid = response.client_resource_id;
    self.record.save().complete(function(){
      callback(null, response);
    });
  },

  _handleRippleRestFailure: function(error, callback) {
    var self = this;
    if (typeof error === 'string' && error.match('No paths found')){
      error = 'noPathFound';
    }
    switch(error) {
      case 'retry':
        self.record.state = 'outgoing';
        break;
      case 'noPathFound':
        self.record.transaction_state = 'tecPATH_DRY';
        self.record.state = 'failed';
        break;
      default:
        self.record.state = 'failed';
    }
    self.record.save().complete(function(){
      //depositCallbackJob.perform([self.record.id], console.log);
      callback();
    });
  },

  _getRippleAddressRecord: function(callback) {
    var self = this;
    gateway.data.rippleAddresses.read(self.record.to_address_id, callback);
  },

  _buildPayment: function(address, callback) {
    var self = this;
    self.rippleRestClient.buildPayment({
      amount: self.record.to_amount,
      currency: self.record.to_currency,
      issuer: gateway.config.get('COLD_WALLET'),
      account: hotWallet.address,
      recipient: address.address
    }, function(error, response) {
      if (error) {
        return callback(error.message, null);
      }
      if (response.success) {
        callback(null, response.payments[0]);
      } else {
        callback(response.message, null);
      }
    });
  },

  _sendPayment: function(payment, callback) {
    var self = this;
    payment.source_tag = self.record.from_address_id.toString();
    self.rippleRestClient.sendPayment({
      payment: payment,
      client_resource_id: uuid.v4(),
      secret: hotWallet.secret
    }, function(error, response){
      if (error) {
        callback(error, null);
      } else if (response.success){
        callback(null, response);
      } else {
        callback(response.message, null);
      }
    });
  }

};

module.exports = OutgoingPayment;

<commit_msg>[TASK] Add more failure expresses to ripple rest handler.<commit_after>var RippleRestClient = require('ripple-rest-client');
var uuid = require('node-uuid');
var async = require('async');
var gateway = require(__dirname+'/../../');
var hotWallet = gateway.config.get('HOT_WALLET');

function OutgoingPayment(outgoingPaymentRecord) {
  this.record = outgoingPaymentRecord;
  this.rippleRestClient = new RippleRestClient({
    account: hotWallet.address,
    secret: hotWallet.secret
  });
}

OutgoingPayment.prototype = {

  processOutgoingPayment: function(callback) {
    var self = this;
    async.waterfall([
      function(next) {
        self._getRippleAddressRecord(next);
      },
      function(address, next) {
        self._buildPayment(address, next);
      },
      function(payment, next) {
        self._sendPayment(payment, next);
      },
      function(response, next) {
        self._markRecordAsSent(response, next);
      },
      function(response, next) {
        self._confirmSuccessfulPayment(response, next);
      }
    ], function(error) {
      if (error) {
        self._handleRippleRestFailure(error, function() {
          logger.error('payments:outgoing:failed', error, self.record.toJSON());
          callback(error, self.record);
        });
      } else {
        logger.info('payment:outgoing:succeeded', self.record.toJSON());
        callback(error, self.record);
      }
    });
  },

  _recordAcceptanceOrRejectionStatus: function(payment, callback) {
    var self = this;
    self.record.transaction_state = payment.result;
    self.record.transaction_hash = payment.hash;
    switch(self.record.transaction_state) {
    case 'tesSUCCESS':
      self.record.state = 'succeeded';
      break;
    default:
      self.record.state = 'failed';
    }
    self.record.save().complete(function(error, record){
      //depositCallbackJob.perform([self.record.id], console.log);
      callback(null, record);
    });
  },

  _confirmSuccessfulPayment: function(response, callback) {
    var statusUrl = response.status_url;
    var self = this;
    self.rippleRestClient.pollPaymentStatus(statusUrl, function(error, paymentStatus) {
      if (error) {
        return callback(error, null);
      }
      self._recordAcceptanceOrRejectionStatus(paymentStatus, function(error, record) {
        callback(null, record);
      });
    });
  },

  _markRecordAsSent: function(response, callback) {
    var self = this;
    self.record.state = 'sent';
    self.record.uid = response.client_resource_id;
    self.record.save().complete(function(){
      callback(null, response);
    });
  },

  _handleRippleRestFailure: function(error, callback) {
    var self = this;
    if (typeof error === 'string' && error.match('No paths found')){
      error = 'noPathFound';
    }
    if (error.match('No connection to rippled') ||
        error.match('try again') ||
        error.match('Cannot connect to rippled'))
    {
      error = 'retry';
    }

    switch(error) {
      case 'retry':
        self.record.state = 'outgoing';
        break;
      case 'noPathFound':
        self.record.transaction_state = 'tecPATH_DRY';
        self.record.state = 'failed';
        break;
      default:
        self.record.state = 'failed';
    }
    self.record.save().complete(function(){
      //depositCallbackJob.perform([self.record.id], console.log);
      callback();
    });
  },

  _getRippleAddressRecord: function(callback) {
    var self = this;
    gateway.data.rippleAddresses.read(self.record.to_address_id, callback);
  },

  _buildPayment: function(address, callback) {
    var self = this;
    self.rippleRestClient.buildPayment({
      amount: self.record.to_amount,
      currency: self.record.to_currency,
      issuer: gateway.config.get('COLD_WALLET'),
      account: hotWallet.address,
      recipient: address.address
    }, function(error, response) {
      if (error) {
        return callback(error.message, null);
      }
      if (response.success) {
        callback(null, response.payments[0]);
      } else {
        callback(response.message, null);
      }
    });
  },

  _sendPayment: function(payment, callback) {
    var self = this;
    payment.source_tag = self.record.from_address_id.toString();
    self.rippleRestClient.sendPayment({
      payment: payment,
      client_resource_id: uuid.v4(),
      secret: hotWallet.secret
    }, function(error, response){
      if (error) {
        callback(error, null);
      } else if (response.success){
        callback(null, response);
      } else {
        callback(response.message, null);
      }
    });
  }

};

module.exports = OutgoingPayment;

<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var rawbg = require('../plugins/rawbg')();

module.exports = function fitTreatmentsToBGCurve (ddata, settings) {

  function updateTreatmentBG(treatment) {

    function mgdlByTime() {

      var withBGs = _.filter(ddata.sgvs, function(d) {
        return d.mgdl > 39 || env.settings.isEnabled('rawbg');
      });

      var beforeTreatment = _.findLast(withBGs, function (d) {
        return d.mills <= treatment.mills;
      });
      var afterTreatment = _.find(withBGs, function (d) {
        return d.mills >= treatment.mills;
      });

      var mgdlBefore = mgdlValue(beforeTreatment) || calcRaw(beforeTreatment);
      var mgdlAfter = mgdlValue(afterTreatment) || calcRaw(afterTreatment);

      var calcedBG = 0;
      if (mgdlBefore && mgdlAfter) {
        calcedBG = (mgdlBefore + mgdlAfter) / 2;
      } else if (mgdlBefore) {
        calcedBG = mgdlBefore;
      } else if (mgdlAfter) {
        calcedBG = mgdlAfter;
      }

      return calcedBG || 180;
    }

    function mgdlValue (entry) {
      return entry && entry.mgdl >= 39 && Number(entry.mgdl);
    }

    function calcRaw (entry) {
      var raw;
      if (entry && settings.isEnabled('rawbg')) {
        var cal = _.last(ddata.cals);
        if (cal) {
          raw = rawbg.calc(entry, cal);
        }
      }
      return raw;
    }

    //to avoid checking if eventType is null everywhere, just default it here
    treatment.eventType = treatment.eventType || '';

    if (treatment.glucose && isNaN(treatment.glucose)) {
      console.warn('found an invalid glucose value', treatment);
    } else if (treatment.glucose && treatment.units) {
      if (treatment.units === 'mmol') {
        treatment.mmol = Number(treatment.glucose);
      } else {
        treatment.mgdl = Number(treatment.glucose);
      }
    } else if (treatment.glucose) {
      //no units, assume everything is the same
      console.warn('found a glucose value without any units, maybe from an old version?', _.pick(treatment, '_id', 'created_at', 'enteredBy'));
      var units = settings.units === 'mmol' ? 'mmol' : 'mgdl';
      treatment[units] = Number(treatment.glucose);
    } else {
      treatment.mgdl = mgdlByTime();
    }
  }

  _.each(ddata.treatments, updateTreatmentBG);

};

<commit_msg>using settings directly<commit_after>'use strict';

var _ = require('lodash');
var rawbg = require('../plugins/rawbg')();

module.exports = function fitTreatmentsToBGCurve (ddata, settings) {

  function updateTreatmentBG(treatment) {

    function mgdlByTime() {

      var withBGs = _.filter(ddata.sgvs, function(d) {
        return d.mgdl > 39 || settings.isEnabled('rawbg');
      });

      var beforeTreatment = _.findLast(withBGs, function (d) {
        return d.mills <= treatment.mills;
      });
      var afterTreatment = _.find(withBGs, function (d) {
        return d.mills >= treatment.mills;
      });

      var mgdlBefore = mgdlValue(beforeTreatment) || calcRaw(beforeTreatment);
      var mgdlAfter = mgdlValue(afterTreatment) || calcRaw(afterTreatment);

      var calcedBG = 0;
      if (mgdlBefore && mgdlAfter) {
        calcedBG = (mgdlBefore + mgdlAfter) / 2;
      } else if (mgdlBefore) {
        calcedBG = mgdlBefore;
      } else if (mgdlAfter) {
        calcedBG = mgdlAfter;
      }

      return calcedBG || 180;
    }

    function mgdlValue (entry) {
      return entry && entry.mgdl >= 39 && Number(entry.mgdl);
    }

    function calcRaw (entry) {
      var raw;
      if (entry && settings.isEnabled('rawbg')) {
        var cal = _.last(ddata.cals);
        if (cal) {
          raw = rawbg.calc(entry, cal);
        }
      }
      return raw;
    }

    //to avoid checking if eventType is null everywhere, just default it here
    treatment.eventType = treatment.eventType || '';

    if (treatment.glucose && isNaN(treatment.glucose)) {
      console.warn('found an invalid glucose value', treatment);
    } else if (treatment.glucose && treatment.units) {
      if (treatment.units === 'mmol') {
        treatment.mmol = Number(treatment.glucose);
      } else {
        treatment.mgdl = Number(treatment.glucose);
      }
    } else if (treatment.glucose) {
      //no units, assume everything is the same
      console.warn('found a glucose value without any units, maybe from an old version?', _.pick(treatment, '_id', 'created_at', 'enteredBy'));
      var units = settings.units === 'mmol' ? 'mmol' : 'mgdl';
      treatment[units] = Number(treatment.glucose);
    } else {
      treatment.mgdl = mgdlByTime();
    }
  }

  _.each(ddata.treatments, updateTreatmentBG);

};

<|endoftext|>


<commit_before>import Immutable, { Map } from 'immutable'
import { logError } from '../helpers'
import { actionReducer, removeMissingItems } from './utils'

const initialState = Immutable.fromJS({
  vms: {},
  pools: {},
  loadInProgress: true,
  page: 1,
  /**
   * true ~ we need to fetch further vms and pools
   * false ~ all visible entities already fetched
   */
  notAllPagesLoaded: true,
})

const vms = actionReducer(initialState, {
  UPDATE_VMS (state, { payload: { vms, copySubResources, page } }) {
    const emptyMap = Map()
    const updates = {}
    vms.forEach(vm => {
      if (!state.getIn(['vms', vm.id])) {
        state = state.set('notAllPagesLoaded', true)
      }
      updates[vm.id] = vm

      if (copySubResources) {
        updates[vm.id].disks = state.getIn(['vms', vm.id, 'disks'], emptyMap).toJS()
        updates[vm.id].consoles = state.getIn(['vms', vm.id, 'consoles'], emptyMap).toJS()
        updates[vm.id].cdrom = state.getIn(['vms', vm.id, 'cdrom'], Immutable.fromJS({ file: { id: '' } })).toJS()
      }
    })
    const imUpdates = Immutable.fromJS(updates)
    let st = state.mergeIn(['vms'], imUpdates)
    if (page) {
      st = st.set('page', page)
    }
    return st
  },
  REMOVE_VMS (state, { payload: { vmIds } }) {
    const mutable = state.asMutable()
    vmIds.forEach(vmId => mutable.deleteIn([ 'vms', vmId ]))
    return mutable.asImmutable()
  },
  REMOVE_MISSING_VMS (state, { payload: { vmIdsToPreserve } }) {
    return removeMissingItems({ state, subStateName: 'vms', idsToPreserve: vmIdsToPreserve })
  },
  SET_VM_DISKS (state, { payload: { vmId, disks } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'disks'], Immutable.fromJS(disks)) // deep immutable
    } else { // fail, if VM not found
      logError(`vms.setVmDisks() reducer: vmId ${vmId} not found`)
    }
    return state
  },
  SET_VM_CDROM (state, { payload: { vmId, cdrom } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'cdrom'], Immutable.fromJS(cdrom)) // deep immutable
    } else { // fail, if VM not found
      logError(`vms.setVmCdrom() reducer: vmId ${vmId} not found`)
    }
    return state
  },
  VM_ACTION_IN_PROGRESS (state, { payload: { vmId, name, started } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'actionInProgress', name], started)
    }
    return state
  },
  POOL_ACTION_IN_PROGRESS (state, { payload: { poolId, name, started } }) {
    return state.setIn(['pools', poolId, 'vm', 'actionInProgress', name], started)
  },
  SET_VM_CONSOLES (state, { payload: { vmId, consoles } }) {
    return state.setIn(['vms', vmId, 'consoles'], Immutable.fromJS(consoles))
  },
  SET_VM_SESSIONS (state, { payload: { vmId, sessions } }) {
    let consoleInUse = false
    for (var i in sessions) {
      if (sessions[i].consoleUser) {
        consoleInUse = true
        break
      }
    }
    state = state.setIn(['vms', vmId, 'sessions'], Immutable.fromJS(sessions))
    return state.setIn(['vms', vmId, 'consoleInUse'], consoleInUse)
  },
  UPDATE_POOLS (state, { payload: { pools } }) {
    const updates = {}
    pools.forEach(pool => {
      if (!state.getIn(['pools', pool.id])) {
        state = state.set('notAllPagesLoaded', true)
      }
      updates[pool.id] = pool
    })
    const imUpdates = Immutable.fromJS(updates)

    return state.mergeIn(['pools'], imUpdates)
  },
  REMOVE_POOLS (state, { payload: { poolIds } }) {
    const mutable = state.asMutable()
    poolIds.forEach(poolId => mutable.deleteIn([ 'pools', poolId ]))
    return mutable.asImmutable()
  },
  REMOVE_MISSING_POOLS (state, { payload: { poolIdsToPreserve } }) {
    const newPools = poolIdsToPreserve
      .reduce((pools, poolId) => {
        const pool = state.getIn(['pools', poolId])
        if (pool) {
          pools.set(poolId, pool)
        }
        return pools
      }, Map().asMutable())
      .asImmutable()
    return state.set('pools', newPools)
  },
  UPDATE_VMPOOLS_COUNT (state) {
    state.get('pools').toList().map(pool => {
      state = state.setIn(['pools', pool.id, 'vmsCount'], 0)
    })

    state.get('vms').toList().map(vm => {
      // Check if vm is in actual pool and its down, checking for down vms is for not count that vms in admin mode
      if (vm.getIn(['pool', 'id']) && vm.get('status') !== 'down') {
        state = state.updateIn(['pools', vm.getIn(['pool', 'id']), 'vmsCount'], count => count + 1)
      }
    })
    return state
  },
  LOGOUT (state) { // see the config() reducer
    return state.set('vms', Immutable.fromJS({}))
  },
  SET_LOAD_IN_PROGRESS (state, { payload: { value } }) {
    return state.set('loadInProgress', value)
  },
  SET_PAGE (state, { payload: { page } }) {
    return state.set('page', page)
  },
  FAILED_EXTERNAL_ACTION (state, { payload }) { // see the userMessages() reducer
    /* Example:
     payload = {
     "message": "[Cannot run VM. There is no host that satisfies current scheduling constraints. See below for details:, The host vdsm did not satisfy internal filter CPU because it does not have enough cores to run the VM.]",
     "type": 409,
     "action": {"type": "START_VM", "payload": {"vmId": "083bd87a-bdd6-47ee-b997-2c9eb381cf79"}}
     }
     */
    if (payload.message && payload.action && payload.action.payload) {
      if (payload.action.payload.vmId) {
        const vmId = payload.action.payload.vmId
        if (state.getIn(['vms', vmId])) {
          return state.setIn(['vms', vmId, 'lastMessage'], payload.shortMessage ? payload.shortMessage : payload.message)
        } else { // fail, if VM not found
          logError(`vms.updateVmIcon() reducer: vmId ${vmId} not found`)
        }
      }
    }
    return state
  },
  SET_CHANGED (state, { payload: { value } }) {
    return state.set('notAllPagesLoaded', value)
  },
})

export default vms
<commit_msg>VMs reducer: error message updated<commit_after>import Immutable, { Map } from 'immutable'
import { logError } from '../helpers'
import { actionReducer, removeMissingItems } from './utils'

const initialState = Immutable.fromJS({
  vms: {},
  pools: {},
  loadInProgress: true,
  page: 1,
  /**
   * true ~ we need to fetch further vms and pools
   * false ~ all visible entities already fetched
   */
  notAllPagesLoaded: true,
})

const vms = actionReducer(initialState, {
  UPDATE_VMS (state, { payload: { vms, copySubResources, page } }) {
    const emptyMap = Map()
    const updates = {}
    vms.forEach(vm => {
      if (!state.getIn(['vms', vm.id])) {
        state = state.set('notAllPagesLoaded', true)
      }
      updates[vm.id] = vm

      if (copySubResources) {
        updates[vm.id].disks = state.getIn(['vms', vm.id, 'disks'], emptyMap).toJS()
        updates[vm.id].consoles = state.getIn(['vms', vm.id, 'consoles'], emptyMap).toJS()
        updates[vm.id].cdrom = state.getIn(['vms', vm.id, 'cdrom'], Immutable.fromJS({ file: { id: '' } })).toJS()
      }
    })
    const imUpdates = Immutable.fromJS(updates)
    let st = state.mergeIn(['vms'], imUpdates)
    if (page) {
      st = st.set('page', page)
    }
    return st
  },
  REMOVE_VMS (state, { payload: { vmIds } }) {
    const mutable = state.asMutable()
    vmIds.forEach(vmId => mutable.deleteIn([ 'vms', vmId ]))
    return mutable.asImmutable()
  },
  REMOVE_MISSING_VMS (state, { payload: { vmIdsToPreserve } }) {
    return removeMissingItems({ state, subStateName: 'vms', idsToPreserve: vmIdsToPreserve })
  },
  SET_VM_DISKS (state, { payload: { vmId, disks } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'disks'], Immutable.fromJS(disks)) // deep immutable
    } else { // fail, if VM not found
      logError(`vms.setVmDisks() reducer: vmId ${vmId} not found`)
    }
    return state
  },
  SET_VM_CDROM (state, { payload: { vmId, cdrom } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'cdrom'], Immutable.fromJS(cdrom)) // deep immutable
    } else { // fail, if VM not found
      logError(`vms.setVmCdrom() reducer: vmId ${vmId} not found`)
    }
    return state
  },
  VM_ACTION_IN_PROGRESS (state, { payload: { vmId, name, started } }) {
    if (state.getIn(['vms', vmId])) {
      return state.setIn(['vms', vmId, 'actionInProgress', name], started)
    }
    return state
  },
  POOL_ACTION_IN_PROGRESS (state, { payload: { poolId, name, started } }) {
    return state.setIn(['pools', poolId, 'vm', 'actionInProgress', name], started)
  },
  SET_VM_CONSOLES (state, { payload: { vmId, consoles } }) {
    return state.setIn(['vms', vmId, 'consoles'], Immutable.fromJS(consoles))
  },
  SET_VM_SESSIONS (state, { payload: { vmId, sessions } }) {
    let consoleInUse = false
    for (var i in sessions) {
      if (sessions[i].consoleUser) {
        consoleInUse = true
        break
      }
    }
    state = state.setIn(['vms', vmId, 'sessions'], Immutable.fromJS(sessions))
    return state.setIn(['vms', vmId, 'consoleInUse'], consoleInUse)
  },
  UPDATE_POOLS (state, { payload: { pools } }) {
    const updates = {}
    pools.forEach(pool => {
      if (!state.getIn(['pools', pool.id])) {
        state = state.set('notAllPagesLoaded', true)
      }
      updates[pool.id] = pool
    })
    const imUpdates = Immutable.fromJS(updates)

    return state.mergeIn(['pools'], imUpdates)
  },
  REMOVE_POOLS (state, { payload: { poolIds } }) {
    const mutable = state.asMutable()
    poolIds.forEach(poolId => mutable.deleteIn([ 'pools', poolId ]))
    return mutable.asImmutable()
  },
  REMOVE_MISSING_POOLS (state, { payload: { poolIdsToPreserve } }) {
    const newPools = poolIdsToPreserve
      .reduce((pools, poolId) => {
        const pool = state.getIn(['pools', poolId])
        if (pool) {
          pools.set(poolId, pool)
        }
        return pools
      }, Map().asMutable())
      .asImmutable()
    return state.set('pools', newPools)
  },
  UPDATE_VMPOOLS_COUNT (state) {
    state.get('pools').toList().map(pool => {
      state = state.setIn(['pools', pool.id, 'vmsCount'], 0)
    })

    state.get('vms').toList().map(vm => {
      // Check if vm is in actual pool and its down, checking for down vms is for not count that vms in admin mode
      if (vm.getIn(['pool', 'id']) && vm.get('status') !== 'down') {
        state = state.updateIn(['pools', vm.getIn(['pool', 'id']), 'vmsCount'], count => count + 1)
      }
    })
    return state
  },
  LOGOUT (state) { // see the config() reducer
    return state.set('vms', Immutable.fromJS({}))
  },
  SET_LOAD_IN_PROGRESS (state, { payload: { value } }) {
    return state.set('loadInProgress', value)
  },
  SET_PAGE (state, { payload: { page } }) {
    return state.set('page', page)
  },
  FAILED_EXTERNAL_ACTION (state, { payload }) { // see the userMessages() reducer
    /* Example:
     payload = {
     "message": "[Cannot run VM. There is no host that satisfies current scheduling constraints. See below for details:, The host vdsm did not satisfy internal filter CPU because it does not have enough cores to run the VM.]",
     "type": 409,
     "action": {"type": "START_VM", "payload": {"vmId": "083bd87a-bdd6-47ee-b997-2c9eb381cf79"}}
     }
     */
    if (payload.message && payload.action && payload.action.payload) {
      if (payload.action.payload.vmId) {
        const vmId = payload.action.payload.vmId
        if (state.getIn(['vms', vmId])) {
          return state.setIn(['vms', vmId, 'lastMessage'], payload.shortMessage ? payload.shortMessage : payload.message)
        } else { // fail, if VM not found
          logError('API reports an error associated to nonexistent VM. error=', payload, 'vmId=', vmId)
        }
      }
    }
    return state
  },
  SET_CHANGED (state, { payload: { value } }) {
    return state.set('notAllPagesLoaded', value)
  },
})

export default vms
<|endoftext|>


<commit_before>/* @flow */

import * as stream from 'stream'

import Config from '../config'
import * as conversion from '../conversion'
import RemoteCozy from './cozy'
import logger from '../logger'
import Pouch from '../pouch'
import Prep from '../prep'
import Watcher from './watcher'

import type { RemoteDoc } from './document'
import type { FileStreamProvider } from '../file_stream_provider'
import type { Metadata } from '../metadata'
import type { Side } from '../side' // eslint-disable-line
import type { Callback } from '../utils/func'

const log = logger({
  component: 'RemoteWriter'
})

export default class Remote implements Side {
  other: FileStreamProvider
  pouch: Pouch
  watcher: Watcher
  remoteCozy: RemoteCozy

  constructor (config: Config, prep: Prep, pouch: Pouch) {
    this.pouch = pouch
    this.remoteCozy = new RemoteCozy(config)
    this.watcher = new Watcher(pouch, prep, this.remoteCozy)
  }

  start () {
    return this.watcher.start()
  }

  stop () {
    return this.watcher.stop()
  }

  unregister () {
    return this.remoteCozy.unregister()
  }

  // Create a readable stream for the given doc
  createReadStreamAsync (doc: Metadata): Promise<stream.Readable> {
    return this.remoteCozy.downloadBinary(doc.remote._id)
  }

  createReadStream (doc: Metadata, callback: Callback) {
    // $FlowFixMe
    this.createReadStreamAsync(doc).asCallback(callback)
  }

  // Create a folder on the remote cozy instance
  async addFolderAsync (doc: Metadata): Promise<Metadata> {
    log.info(`${doc.path}: Creating folder...`)

    const [parentPath, name] = conversion.extractDirAndName(doc.path)
    const parent: RemoteDoc = await this.remoteCozy.findDirectoryByPath(parentPath)
    let dir: RemoteDoc

    try {
      dir = await this.remoteCozy.createDirectory({
        name,
        dirID: parent._id,
        lastModifiedDate: doc.lastModification
      })
    } catch (err) {
      if (err.status !== 409) { throw err }

      log.info(`${doc.path}: Folder already exists`)
      dir = await this.remoteCozy.findDirectoryByPath(`/${doc.path}`)
    }

    doc.remote = {
      _id: dir._id,
      _rev: dir._rev
    }

    return conversion.createMetadata(dir)
  }

  async addFolder (doc: Metadata, callback: Callback) {
    // $FlowFixMe
    this.addFolderAsync(doc).asCallback(callback)
  }

  async addFileAsync (doc: Metadata): Promise<Metadata> {
    log.info(`${doc.path}: Uploading new file...`)
    const stream = await this.other.createReadStreamAsync(doc)
    const [dirPath, name] = conversion.extractDirAndName(doc.path)
    const dir = await this.remoteCozy.findDirectoryByPath(dirPath)
    const created = await this.remoteCozy.createFile(stream, {
      name,
      dirID: dir._id,
      executable: doc.executable,
      contentType: doc.mime,
      lastModifiedDate: new Date(doc.lastModification)
    })

    doc.remote = {
      _id: created._id,
      _rev: created._rev
    }

    return conversion.createMetadata(created)
  }

  // FIXME: Drop this wrapper as soon as Sync uses promises
  addFile (doc: Metadata, callback: Callback) {
    try {
      this.addFileAsync(doc)
        .then(created => callback(null, created))
        .catch(callback)
    } catch (err) {
      callback(err)
    }
  }

  async overwriteFileAsync (doc: Metadata, old: ?Metadata): Promise<Metadata> {
    log.info(`${doc.path}: Uploading new file version...`)
    const stream = await this.other.createReadStreamAsync(doc)
    const updated = await this.remoteCozy.updateFileById(doc.remote._id, stream, {
      contentType: doc.mime,
      checksum: doc.md5sum,
      lastModifiedDate: new Date(doc.lastModification)
    })

    doc.remote._rev = updated._rev

    return conversion.createMetadata(updated)
  }

  async overwriteFile (doc: Metadata, old: ?Metadata, callback: Callback) {
    try {
      const updated = await this.overwriteFileAsync(doc, old)
      callback(null, updated)
    } catch (err) {
      callback(err)
    }
  }

  async updateFileMetadataAsync (doc: Metadata, old: any): Promise<Metadata> {
    log.info(`${doc.path}: Updating file metadata...`)
    // TODO: v3: addFile() when no old.remote

    // TODO: v3: Update more metadata, not just the last modification date.
    const attrs = {}

    // TODO: v3: ifMatch old rev
    const updated = await this.remoteCozy.updateAttributesById(old.remote._id, attrs, {})

    // TODO: v3: Handle trivial remote changes and conflicts.
    // See Couch#putRemoteDoc() and #sameRemoteDoc()

    doc.remote = {
      _id: updated._id,
      _rev: updated._rev
    }

    return conversion.createMetadata(updated)
  }

  updateFileMetadata (doc: Metadata, old: any, callback: Callback) {
    try {
      this.updateFileMetadataAsync(doc, old)
        .then(() => { callback() })
        .catch(callback)
    } catch (err) {
      callback(err)
    }
  }

  async moveFileAsync (newMetadata: Metadata, oldMetadata: Metadata): Promise<Metadata> {
    log.info(`${oldMetadata.path}: Moving to ${newMetadata.path}`)
    // TODO: v3: Call addFile() when !from.remote?
    // TODO: v3: Call addFile() when file not found on cozy
    // TODO: v3: Call addFolder() on DirectoryNotFound?
    const [newDirPath, newName]: [string, string] = conversion.extractDirAndName(newMetadata.path)
    const newDir: RemoteDoc = await this.remoteCozy.findDirectoryByPath(newDirPath)
    const newRemoteDoc: RemoteDoc = await this.remoteCozy.updateAttributesById(oldMetadata.remote._id, {
      name: newName,
      dir_id: newDir._id
    })

    newMetadata.remote = {
      _id: newRemoteDoc._id,
      _rev: newRemoteDoc._rev
    }

    return conversion.createMetadata(newRemoteDoc)
  }

  moveFile (doc: Metadata, from: Metadata, callback: Callback): void {
    // $FlowFixMe
    this.moveFileAsync(doc, from).asCallback(callback)
  }

  async updateFolderAsync (doc: Metadata, old: ?Metadata): Promise<Metadata> {
    log.info(`${doc.path}: Updating metadata...`)
    const [newParentDirPath, newName] = conversion.extractDirAndName(doc.path)
    const newParentDir = await this.remoteCozy.findDirectoryByPath(newParentDirPath)
    // XXX: Should we recreate missing parent, or would it duplicate work in Merge#ensureParentExist()?
    let newRemoteDoc: RemoteDoc

    if (!old || !old.remote) {
      return this.addFolderAsync(doc)
    }

    try {
      newRemoteDoc = await this.remoteCozy.updateAttributesById(old.remote._id, {
        name: newName,
        dir_id: newParentDir._id
      })
    } catch (err) {
      if (err.status !== 404) { throw err }

      log.warn(`${doc.path}: Directory doesn't exist anymore. Recreating it...`)
      newRemoteDoc = await this.remoteCozy.createDirectory({
        name: newName,
        dirID: newParentDir._id,
        lastModifiedDate: doc.lastModification
      })
    }

    doc.remote = {
      _id: newRemoteDoc._id,
      _rev: newRemoteDoc._rev
    }

    return conversion.createMetadata(newRemoteDoc)
  }

  updateFolder (doc: Metadata, old: Metadata, callback: Callback) {
    // $FlowFixMe
    this.updateFolderAsync(doc, old).asCallback(callback)
  }

  async destroyAsync (doc: Metadata): Promise<void> {
    log.info(`${doc.path}: Destroying...`)
    await this.remoteCozy.destroyById(doc.remote._id)
  }

  destroy (doc: Metadata, callback: Callback) {
    // $FlowFixMe
    this.destroyAsync(doc).asCallback(callback)
  }

  async trashAsync (doc: Metadata): Promise<void> {
    log.info(`${doc.path}: Moving to the trash...`)
    await this.remoteCozy.trashById(doc.remote._id)
  }

  trash (doc: Metadata, callback: Callback) {
    // $FlowFixMe
    this.trashAsync(doc).asCallback(callback)
  }

  moveFolderAsync (doc: Metadata, from: Metadata): Promise<*> {
    // TODO: v3: Remote#moveFolderAsync()
    throw new Error('Remote#moveFolderAsync() is not implemented')
  }

  moveFolder (doc: Metadata, from: Metadata, callback: Callback) {
    // $FlowFixMe
    this.moveFolderAsync(doc, from).asCallback(callback)
  }

  diskUsage (): Promise<*> {
    return this.remoteCozy.diskUsage()
  }
}
<commit_msg>Remove some dead code<commit_after>/* @flow */

import * as stream from 'stream'

import Config from '../config'
import * as conversion from '../conversion'
import RemoteCozy from './cozy'
import logger from '../logger'
import Pouch from '../pouch'
import Prep from '../prep'
import Watcher from './watcher'

import type { RemoteDoc } from './document'
import type { FileStreamProvider } from '../file_stream_provider'
import type { Metadata } from '../metadata'
import type { Side } from '../side' // eslint-disable-line
import type { Callback } from '../utils/func'

const log = logger({
  component: 'RemoteWriter'
})

export default class Remote implements Side {
  other: FileStreamProvider
  pouch: Pouch
  watcher: Watcher
  remoteCozy: RemoteCozy

  constructor (config: Config, prep: Prep, pouch: Pouch) {
    this.pouch = pouch
    this.remoteCozy = new RemoteCozy(config)
    this.watcher = new Watcher(pouch, prep, this.remoteCozy)
  }

  start () {
    return this.watcher.start()
  }

  stop () {
    return this.watcher.stop()
  }

  unregister () {
    return this.remoteCozy.unregister()
  }

  // Create a readable stream for the given doc
  createReadStreamAsync (doc: Metadata): Promise<stream.Readable> {
    return this.remoteCozy.downloadBinary(doc.remote._id)
  }

  createReadStream (doc: Metadata, callback: Callback) {
    // $FlowFixMe
    this.createReadStreamAsync(doc).asCallback(callback)
  }

  // Create a folder on the remote cozy instance
  async addFolderAsync (doc: Metadata): Promise<Metadata> {
    log.info(`${doc.path}: Creating folder...`)

    const [parentPath, name] = conversion.extractDirAndName(doc.path)
    const parent: RemoteDoc = await this.remoteCozy.findDirectoryByPath(parentPath)
    let dir: RemoteDoc

    try {
      dir = await this.remoteCozy.createDirectory({
        name,
        dirID: parent._id,
        lastModifiedDate: doc.lastModification
      })
    } catch (err) {
      if (err.status !== 409) { throw err }

      log.info(`${doc.path}: Folder already exists`)
      dir = await this.remoteCozy.findDirectoryByPath(`/${doc.path}`)
    }

    doc.remote = {
      _id: dir._id,
      _rev: dir._rev
    }

    return conversion.createMetadata(dir)
  }

  async addFileAsync (doc: Metadata): Promise<Metadata> {
    log.info(`${doc.path}: Uploading new file...`)
    const stream = await this.other.createReadStreamAsync(doc)
    const [dirPath, name] = conversion.extractDirAndName(doc.path)
    const dir = await this.remoteCozy.findDirectoryByPath(dirPath)
    const created = await this.remoteCozy.createFile(stream, {
      name,
      dirID: dir._id,
      executable: doc.executable,
      contentType: doc.mime,
      lastModifiedDate: new Date(doc.lastModification)
    })

    doc.remote = {
      _id: created._id,
      _rev: created._rev
    }

    // TODO do we use the returned values somewhere?
    return conversion.createMetadata(created)
  }

  async overwriteFileAsync (doc: Metadata, old: ?Metadata): Promise<Metadata> {
    log.info(`${doc.path}: Uploading new file version...`)
    const stream = await this.other.createReadStreamAsync(doc)
    const updated = await this.remoteCozy.updateFileById(doc.remote._id, stream, {
      contentType: doc.mime,
      checksum: doc.md5sum,
      lastModifiedDate: new Date(doc.lastModification)
    })

    doc.remote._rev = updated._rev

    return conversion.createMetadata(updated)
  }

  async updateFileMetadataAsync (doc: Metadata, old: any): Promise<Metadata> {
    log.info(`${doc.path}: Updating file metadata...`)
    // TODO: v3: addFile() when no old.remote

    // TODO: v3: Update more metadata, not just the last modification date.
    const attrs = {}

    // TODO: v3: ifMatch old rev
    const updated = await this.remoteCozy.updateAttributesById(old.remote._id, attrs, {})

    // TODO: v3: Handle trivial remote changes and conflicts.
    // See Couch#putRemoteDoc() and #sameRemoteDoc()

    doc.remote = {
      _id: updated._id,
      _rev: updated._rev
    }

    return conversion.createMetadata(updated)
  }

  async moveFileAsync (newMetadata: Metadata, oldMetadata: Metadata): Promise<Metadata> {
    log.info(`${oldMetadata.path}: Moving to ${newMetadata.path}`)
    // TODO: v3: Call addFile() when !from.remote?
    // TODO: v3: Call addFile() when file not found on cozy
    // TODO: v3: Call addFolder() on DirectoryNotFound?
    const [newDirPath, newName]: [string, string] = conversion.extractDirAndName(newMetadata.path)
    const newDir: RemoteDoc = await this.remoteCozy.findDirectoryByPath(newDirPath)
    const newRemoteDoc: RemoteDoc = await this.remoteCozy.updateAttributesById(oldMetadata.remote._id, {
      name: newName,
      dir_id: newDir._id
    })

    newMetadata.remote = {
      _id: newRemoteDoc._id,
      _rev: newRemoteDoc._rev
    }

    return conversion.createMetadata(newRemoteDoc)
  }

  async updateFolderAsync (doc: Metadata, old: ?Metadata): Promise<Metadata> {
    log.info(`${doc.path}: Updating metadata...`)
    const [newParentDirPath, newName] = conversion.extractDirAndName(doc.path)
    const newParentDir = await this.remoteCozy.findDirectoryByPath(newParentDirPath)
    // XXX: Should we recreate missing parent, or would it duplicate work in Merge#ensureParentExist()?
    let newRemoteDoc: RemoteDoc

    if (!old || !old.remote) {
      return this.addFolderAsync(doc)
    }

    try {
      newRemoteDoc = await this.remoteCozy.updateAttributesById(old.remote._id, {
        name: newName,
        dir_id: newParentDir._id
      })
    } catch (err) {
      if (err.status !== 404) { throw err }

      log.warn(`${doc.path}: Directory doesn't exist anymore. Recreating it...`)
      newRemoteDoc = await this.remoteCozy.createDirectory({
        name: newName,
        dirID: newParentDir._id,
        lastModifiedDate: doc.lastModification
      })
    }

    doc.remote = {
      _id: newRemoteDoc._id,
      _rev: newRemoteDoc._rev
    }

    return conversion.createMetadata(newRemoteDoc)
  }

  async destroyAsync (doc: Metadata): Promise<void> {
    log.info(`${doc.path}: Destroying...`)
    await this.remoteCozy.destroyById(doc.remote._id)
  }

  async trashAsync (doc: Metadata): Promise<void> {
    log.info(`${doc.path}: Moving to the trash...`)
    await this.remoteCozy.trashById(doc.remote._id)
  }

  moveFolderAsync (doc: Metadata, from: Metadata): Promise<*> {
    // TODO: v3: Remote#moveFolderAsync()
    throw new Error('Remote#moveFolderAsync() is not implemented')
  }

  diskUsage (): Promise<*> {
    return this.remoteCozy.diskUsage()
  }
}
<|endoftext|>


<commit_before>//import {isArray, each} from "../util.js";

//Style props
export const styleProps = {
    //Fill props
    "fill": "fill",
    //Stroke props
    "stroke": "stroke",
    "strokewidth": "stroke-width",
    "strokedash": "stroke-dasharray",
    "strokedashoffset": "stroke-dashoffset",
    "strokelinecap": "stroke-linecap",  //Values: butt|square|round
    "strokelinejoin": "stroke-linejoin",  //Values: arcs|bevel|miter|miter-clip|round
    //Text
    "color": "color",
    "fontsize": "font-size",
    "fontfamily": "font-family",  //Values: arial|Times|serif
    "fontstyle": "font-style",  //Values: normal|italic|oblique
    "fontweight": "font-weight",  //Values: normal|bold
    //Border
    "border": "border",
    "bordercolor": "border-color",
    "borderstyle": "border-style",
    "borderwidth": "border-width",
    //General
    "opacity": "opacity",
    "cursor": "cursor",
    "transform": "transform"
};

//Apply style
//export function applyStyle (context, datum, props, target) {
//    //Draw all available styles
//    return each(props, function (key, value) {
//        //Check if this key is a style prop
//        if (typeof styleProps[key] !== "undefined" && value !== null) {
//            let parsedValue = context.value(props[key], ((isArray(datum) === true) ? datum[0] : datum)); //Get value from context
//            //Add this css style
//            target.style(styleProps[key], parsedValue);
//        }
//    });
//}

//Set style property to element
export function setStyle (element, name, value) {
    return element.style(styleProps[parseStyleName(name)], value);
}

//Parse style name
export function parseStypeProp (name) {
    return name.replace(/-/g, "").toLowerCase();
}

//Check if the provided name is a valid style property
export function isStyleName (name) {
    return typeof name === "string" && typeof styleProps[parseStyleName(name)] !== "undefined";
}

//Clear all styles of an element
export function cleanStyle (target) {
    return target.each(function () {
        this.style.cssText = "";
    });
}

<commit_msg>Removed unused methods in style scene manager. Fixed style names<commit_after>//Style props
export const styleProps = {
    //Fill props
    "fill": "fill",
    //Stroke props
    "stroke": "stroke",
    "strokeWidth": "stroke-width",
    "strokeDash": "stroke-dasharray",
    "strokeDashOffset": "stroke-dashoffset",
    "strokeLineCap": "stroke-linecap",  //Values: butt|square|round
    "strokeLineJoin": "stroke-linejoin",  //Values: arcs|bevel|miter|miter-clip|round
    //Text
    "color": "color",
    "fontSize": "font-size",
    "fontFamily": "font-family",  //Values: arial|Times|serif
    "fontStyle": "font-style",  //Values: normal|italic|oblique
    "fontWeight": "font-weight",  //Values: normal|bold
    //Border
    "border": "border",
    "borderColor": "border-color",
    "borderStyle": "border-style",
    "borderWidth": "border-width",
    //General
    "opacity": "opacity",
    "cursor": "cursor",
    "transform": "transform"
};

//Set style property to element
export function setStyle (element, name, value) {
    return element.style(styleProps[name], value);
}

//Check if the provided name is a valid style property
export function isStyleName (name) {
    return typeof name === "string" && typeof styleProps[name] !== "undefined";
}

<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe('local');
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe("first");

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(undefined);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe("John rules!");

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!");

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>Change FILL_ME_INs to 3 & function to string in "should use function body as a string" in AboutFunctions.js<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe('local');
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe("first");

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(undefined);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe("John rules!");

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!");

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(3);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe("function (a, b) {
      //An internal comment
      return a * b;
    }");
  });
});
<|endoftext|>


<commit_before>'use strict'
var execattach = require('./attach')
var triggerBind = require('./bind')

exports.define = {
  isExecutable (property, key, base, stamp) {
    return !base._properties[key]
  },
  execInternal (bind, event, data) {
    var emitter = this
    var stamp = event.stamp
    if (!bind._context && emitter.base) {
      // *** CLEAN UP MAYBE GET SPEED BY JUST DOING THIS IN FUNCTION MAKE NICER ANYWAYS ***
      let type = emitter.key
      let on = (!bind.__on && bind._on) || bind.hasOwnProperty('__on') && bind.__on
      let _type = '_' + type //this is fucked slow
      if (on && !on[_type] || on.hasOwnProperty(_type)) {
        emitter.base.each(function (property) {
          property.clearContext()
          triggerBind(property._on[type], property, event, data)
        }, function (property, key, base, stamp) {
          // maybe we dont need to do this like this -- reuse own emitter if not -- may need to fire for contexts/instance etc
          return !base._properties[key] && base.hasOwnProperty(key) && property._on && property._on[type]
        }, stamp)
      }
    }

    // *** CANDITATE FOR MURDER! ***
    var original = bind
    bind = bind.getBind()

    if (bind) {
      if (emitter.fn) {
        emitter.fn.each(function (property, key) {
          property.call(bind, data, event, original)
        }, emitter.isExecutable, stamp)
      }
      if (emitter.attach) {
        emitter.attach.each(function (property) {
          execattach(property, bind, event, emitter, data)
        }, emitter.isExecutable, stamp)
      }
    }
  },
  trigger (binds, event) {
    if (binds) {
      for (let uid in binds) {
        if (uid !== 'val') {
          let bind = binds[uid]
          let data
          triggerBind(this, bind, event, data)
        }
      }
    }
  }
}
<commit_msg>disable unessecary line<commit_after>'use strict'
var execattach = require('./attach')
var triggerBind = require('./bind')

exports.define = {
  isExecutable (property, key, base, stamp) {
    return !base._properties[key]
  },
  execInternal (bind, event, data) {
    var emitter = this
    var stamp = event.stamp
    if (!bind._context && emitter.base) {
      // *** CLEAN UP MAYBE GET SPEED BY JUST DOING THIS IN FUNCTION MAKE NICER ANYWAYS ***
      let type = emitter.key
      let on = (!bind.__on && bind._on) || bind.hasOwnProperty('__on') && bind.__on
      let _type = '_' + type // this is fucked slow
      if (on && !on[_type] || on.hasOwnProperty(_type)) {
        emitter.base.each(function (property) {
          // property.clearContext() //nessecary?
          triggerBind(property._on[type], property, event, data)
        }, function (property, key, base, stamp) {
          // maybe we dont need to do this like this -- reuse own emitter if not -- may need to fire for contexts/instance etc
          return !base._properties[key] && base.hasOwnProperty(key) && property._on && property._on[type]
        }, stamp)
      }
    }

    // *** CANDITATE FOR MURDER! ***
    var original = bind
    bind = bind.getBind()

    if (bind) {
      if (emitter.fn) {
        emitter.fn.each(function (property, key) {
          property.call(bind, data, event, original)
        }, emitter.isExecutable, stamp)
      }
      if (emitter.attach) {
        emitter.attach.each(function (property) {
          execattach(property, bind, event, emitter, data)
        }, emitter.isExecutable, stamp)
      }
    }
  },
  trigger (binds, event) {
    if (binds) {
      for (let uid in binds) {
        if (uid !== 'val') {
          let bind = binds[uid]
          let data
          triggerBind(this, bind, event, data)
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe("first");

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(undefined);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe("John rules!");

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!");

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(FILL_ME_IN);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(FILL_ME_IN);
  });
});
<commit_msg>Made functions-as-strings test pass.<commit_after>describe("About Functions", function() {

  it("should declare functions", function() {

    function add(a, b) {
      return a + b;
    }

    expect(add(1, 2)).toBe(3);
  });

  it("should know internal variables override outer variables", function () {
    var message = "Outer";

    function getMessage() {
      return message;
    }

    function overrideMessage() {
      var message = "Inner";
      return message;
    }

    expect(getMessage()).toBe("Outer");
    expect(overrideMessage()).toBe("Inner");
    expect(message).toBe("Outer");
  });

  it("should have lexical scoping", function () {
    var variable = "top-level";
    function parentfunction() {
        var variable = "local";
      function childfunction() {
          return variable;
      }
      return childfunction();
    }
    expect(parentfunction()).toBe("local");
  });

  it("should use lexical scoping to synthesise functions", function () {

    function makeIncreaseByFunction(increaseByAmount) {
      return function (numberToIncrease) {
        return numberToIncrease + increaseByAmount;
      };
    }

    var increaseBy3 = makeIncreaseByFunction(3);
    var increaseBy5 = makeIncreaseByFunction(5);

    expect(increaseBy3(10) + increaseBy5(10)).toBe(28);
  });

  it("should allow extra function arguments", function () {

    function returnFirstArg(firstArg) {
      return firstArg;
    }

    expect(returnFirstArg("first", "second", "third")).toBe("first");

    function returnSecondArg(firstArg, secondArg) {
      return secondArg;
    }

    expect(returnSecondArg("only give first arg")).toBe(undefined);

    function returnAllArgs() {
      var argsArray = [];
      for (var i = 0; i < arguments.length; i += 1) {
        argsArray.push(arguments[i]);
      }
      return argsArray.join(",");
    }

    expect(returnAllArgs("first", "second", "third")).toBe("first,second,third");
  });

  it("should pass functions as values", function () {

    var appendRules = function (name) {
      return name + " rules!";
    };

    var appendDoubleRules = function (name) {
      return name + " totally rules!";
    };

    var praiseSinger = { givePraise: appendRules };
    expect(praiseSinger.givePraise("John")).toBe("John rules!");

    praiseSinger.givePraise = appendDoubleRules;
    expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!");

  });

  it("should use function body as a string", function () {
    var add = new Function("a", "b", "return a + b;");
    expect(add(1, 2)).toBe(3);

    var multiply = function (a, b) {
      //An internal comment
      return a * b;
    };
    expect(multiply.toString()).toBe(
'function (a, b) {
  // An internal comment
  return a * b;
}');
  });
});
<|endoftext|>