<commit_before>/* See license.txt for terms of usage */

FBL.ns(function() { with (FBL) {

// ************************************************************************************************
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

const httpObserver = Cc["@joehewitt.com/firebug-http-observer;1"].getService(Ci.nsIObserverService);

// List of text content types. These content-types are cached.
var contentTypes =
{
    "text/plain": 1,
    "text/html": 1,
    "text/xml": 1,
    "text/xsl": 1,
    "text/xul": 1,
    "text/css": 1,
    "text/sgml": 1,
    "text/rtf": 1,
    "text/richtext": 1,
    "text/x-setext": 1,
    "text/rtf": 1,
    "text/richtext": 1,
    "text/javascript": 1,
    "text/tab-separated-values": 1,
    "text/rdf": 1,
    "text/xif": 1,
    "text/ecmascript": 1,
    "text/vnd.curl": 1,
    "view-source": 1,
    "view-fragment": 1,
    "application/xml": 1,
    "application/xhtml+xml": 1,
    "application/vnd.mozilla.xul+xml": 1,
    "application/javascript": 1,
    "application/x-javascript": 1,
    "application/x-httpd-php": 1,
    "application/rdf+xml": 1,
    "application/ecmascript": 1,
    "application/http-index-format": 1,
};

// ************************************************************************************************
// Model implementation

/**
 * Implementation of cache model. The only purpose of this object is to register an HTTP
 * observer so, HTTP communication can be interecepted and all incoming data stored within
 * a cache.
 */
Firebug.TabCacheModel = extend(Firebug.Module,
{
    initializeUI: function(owner)
    {
        if (FBTrace.DBG_CACHE)
            FBTrace.sysout("tabCache. Cache model initialized.");

        // Read additional text mime-types from preferences.
        var mimeTypes = Firebug.getPref(Firebug.prefDomain, "cache.mimeTypes");
        if (mimeTypes) {
            var list = mimeTypes.split(" ");
            for (var i=0; i<list.length; i++)
                contentTypes[list[i]] = 1;

            if (FBTrace.DBG_CACHE)
                FBTrace.sysout("tabCache.initializeUI, custom mime-types added", list);
        }

        // Register for HTTP events.
        if (Ci.nsITraceableChannel)
            httpObserver.addObserver(this, "firebug-http-event", false);
    },

    shutdown: function()
    {
        if (Ci.nsITraceableChannel)
            httpObserver.removeObserver(this, "firebug-http-event");
    },

    initContext: function(context)
    {
        if (FBTrace.DBG_CACHE)
            FBTrace.dumpProperties("tabCache.initContext for: " + context.window.location.href);
    },

    /* nsIObserver */
    observe: function(subject, topic, data)
    {
        try
        {
            if (!(subject instanceof Ci.nsIHttpChannel))
                return;

            var win = getWindowForRequest(subject);
            var tabId = Firebug.getTabIdForWindow(win);
            if (!(tabId && win))
                return;

            if (topic == "http-on-modify-request")
                this.onModifyRequest(subject, win, tabId);
            else if (topic == "http-on-examine-response")
                this.onExamineResponse(subject, win, tabId);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("tabCache.observe EXCEPTION", err);
        }
    },

    onModifyRequest: function(request, win, tabId)
    {
    },

    onExamineResponse: function(request, win, tabId)
    {
        try
        {
            // Register traceable channel listener in order to intercept all incoming data for
            // this context/tab. nsITraceableChannel interface is introduced in Firefox 3.0.4
            request.QueryInterface(Ci.nsITraceableChannel);
            var newListener = new TracingListener(win);
            newListener.listener = request.setNewListener(newListener);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache: Register Traceable Listener EXCEPTION", err);
        }
    },
});

// ************************************************************************************************

/**
 * This cache object is intended to cache all responses made by a specific tab.
 * The implementation is based on nsITraceableChannel interface introduced in
 * Firefox 3.0.4. This interface allows to intercept all incoming HTTP data.
 *
 * This object replaces the SourceCache, which still exist only for backward
 * compatibility.
 *
 * The object is derived from SourceCache so, the same interface and most of the
 * implementation is used.
 */
Firebug.TabCache = function(win)
{
    if (FBTrace.DBG_CACHE)
        FBTrace.dumpProperties("tabCache.TabCache Created for: " + win.location.href);

    Firebug.SourceCache.call(this, win, null);
};

Firebug.TabCache.prototype = extend(Firebug.SourceCache.prototype,
{
    listeners: [],
    requests: [],       // requests in progress.

    storePartialResponse: function(request, responseText)
    {
        var url = safeGetName(request);

        if (!this.requests[url])
        {
            this.invalidate(url);
            this.requests[url] = request;
        }

        // Convert
        responseText = FBL.convertToUnicode(responseText);

        // Store partial content into the cache.
        this.store(url, responseText);
    },

    stopRequest: function(request)
    {
        var url = safeGetName(request);
        delete this.requests[url];

        // Notify listeners.
        dispatch(this.listeners, "onStoreResponse", [this.window, request, this.cache[url]]);
    },

    storeSplitLines: function(url, lines)
    {
        if (FBTrace.DBG_CACHE)
            FBTrace.sysout("tabCache.storeSplitLines: " + url, lines);

        var currLines = this.cache[url];
        if (!currLines)
            currLines = this.cache[url] = [];

        // Join the last line with the new first one so, the source code
        // lines are properly formatted.
        if (currLines.length)
            currLines[currLines.length-1] += lines.shift();

        // Append new lines (if any) into the array for specified url.
        if (lines.length)
            this.cache[url] = currLines.concat(lines);

    	return this.cache[url];
    },

    loadFromCache: function(url, method, file)
    {
        // The ancestor implementation (SourceCache) uses ioService.newChannel, which
        // can result in additional request to the server (in case the response can't
        // be loaded from the Firefox cache) - known as double-load problem.
        // This new implementation (TabCache) uses nsITraceableListener so, all responses
        // should be already cached.

        if (FBTrace.DBG_CACHE)
            FBTrace.dumpProperties("tabCache.loadFromCache: FAILED " +
                this.window.location.href, this.cache);
    },

    // Listeners
    addListener: function(listener)
    {
        this.listeners.push(listener);
    },

    removeListener: function(listener)
    {
        remove(this.listeners, listener);
    }
});

// ************************************************************************************************
// TracingListener implementation

/**
 * This object implements nsIStreamListener interface and is intended to monitor all network
 * channels (nsIHttpChannel). For every channel a new instance of this object is created and
 * registered. See Firebug.TabCacheModel.onExamineResponse method.
 */
function TracingListener(win)
{
    this.window = win;
    this.listener = null;
    this.endOfLine = false;
}

TracingListener.prototype =
{
    onCollectData: function(request, inputStream, offset, count)
    {
        try
        {
            var binaryInputStream = CCIN("@mozilla.org/binaryinputstream;1", "nsIBinaryInputStream");
            var storageStream = CCIN("@mozilla.org/storagestream;1", "nsIStorageStream");
            var binaryOutputStream = CCIN("@mozilla.org/binaryoutputstream;1", "nsIBinaryOutputStream");

            binaryInputStream.setInputStream(inputStream);
            storageStream.init(8192, count, null);
            binaryOutputStream.setOutputStream(storageStream.getOutputStream(0));

            var data = binaryInputStream.readBytes(count);
            binaryOutputStream.writeBytes(data, count);

            // Avoid creating additional empty line if response comes in more pieces
            // and the split is made just between "\r" and "\n" (Win line-end).
            // So, if the response starts with "\n" while the previous part ended with "\r",
            // remove the first character.
            if (this.endOfLine && data.length && data[0] == "\n")
                data = data.substring(1);

            if (data.length)
                this.endOfLine = data[data.length-1] == "\r";

            // At this moment, initContext is alredy called so, the context is
            // ready and associated with the window.
            var context = TabWatcher.getContextByWindow(this.window);
            if (context)
            {
                // Store received data into the cache as they come.
                context.sourceCache.storePartialResponse(request, data);
            }
            else
            {
                if (FBTrace.DBG_CACHE)
                    FBTrace.dumpProperties("tabCache.onCollectData NO CONTEXT for: " + this.window.location.href);
            }

            // Let other listeners use the stream.
            return storageStream.newInputStream(0);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache.TracingListener.onCollectData EXCEPTION\n", err);
        }

        return null;
    },

    /* nsIStreamListener */
    onDataAvailable: function(request, requestContext, inputStream, offset, count)
    {
        // Cache only text responses for now.
        if (contentTypes[request.contentType])
        {
            var newStream = this.onCollectData(request, inputStream, offset, count);
            if (newStream)
                inputStream = newStream;
        }
        else
        {
            if (FBTrace.DBG_CACHE)
                FBTrace.dumpProperties("tabCache.onDataAvailable Content-Type not cached: " +
                    request.contentType + ", " + safeGetName(request));
        }

        try
        {
            if (this.listener)
                this.listener.onDataAvailable(request, requestContext, inputStream, offset, count);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache.TracingListener.onDataAvailable" +
                    "(" + request + ", " + requestContext + ", " +
                    inputStream + ", " + offset + ", " + count + ") EXCEPTION: " +
                    safeGetName(request), err);
        }
    },

    onStartRequest: function(request, requestContext)
    {
        try
        {
            if (this.listener)
                this.listener.onStartRequest(request, requestContext);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache.TracingListener.onStartRequest EXCEPTION\n", err);
        }
    },

    onStopRequest: function(request, requestContext, statusCode)
    {
        try
        {
            var context = TabWatcher.getContextByWindow(this.window);
            if (context)
            {
                context.sourceCache.stopRequest(request);
            }
            else
            {
                if (FBTrace.DBG_CACHE)
                    FBTrace.dumpProperties("tabCache.onStopRequest NO CONTEXT for: " + this.window.location.href);
            }

            if (this.listener)
                this.listener.onStopRequest(request, requestContext, statusCode);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache.TracingListener.onStopRequest EXCEPTION\n", err);
        }
    },

    /* nsISupports */
    QueryInterface: function(iid)
    {
        if (iid.equals(Ci.nsIStreamListener) ||
            iid.equals(Ci.nsISupportsWeakReference) ||
            iid.equals(Ci.nsISupports))
        {
            return this;
        }

        throw Components.results.NS_NOINTERFACE;
    }
}

// ************************************************************************************************
// Helpers

function safeGetName(request)
{
    try {
        return request.name;
    }
    catch (exc) {
    }

    return null;
}

// ************************************************************************************************
// Registration

Firebug.registerModule(Firebug.TabCacheModel);

// ************************************************************************************************

}});
<commit_msg>Additional mimetypes to cache.<commit_after>/* See license.txt for terms of usage */

FBL.ns(function() { with (FBL) {

// ************************************************************************************************
// Constants

const Cc = Components.classes;
const Ci = Components.interfaces;

const httpObserver = Cc["@joehewitt.com/firebug-http-observer;1"].getService(Ci.nsIObserverService);

// List of text content types. These content-types are cached.
var contentTypes =
{
    "text/plain": 1,
    "text/html": 1,
    "text/xml": 1,
    "text/xsl": 1,
    "text/xul": 1,
    "text/css": 1,
    "text/sgml": 1,
    "text/rtf": 1,
    "text/richtext": 1,
    "text/x-setext": 1,
    "text/rtf": 1,
    "text/richtext": 1,
    "text/javascript": 1,
    "text/tab-separated-values": 1,
    "text/rdf": 1,
    "text/xif": 1,
    "text/ecmascript": 1,
    "text/vnd.curl": 1,
    "text/x-json": 1,
    "view-source": 1,
    "view-fragment": 1,
    "application/xml": 1,
    "application/xhtml+xml": 1,
    "application/vnd.mozilla.xul+xml": 1,
    "application/javascript": 1,
    "application/x-javascript": 1,
    "application/x-httpd-php": 1,
    "application/rdf+xml": 1,
    "application/ecmascript": 1,
    "application/http-index-format": 1,
    "application/json": 1,
};

// ************************************************************************************************
// Model implementation

/**
 * Implementation of cache model. The only purpose of this object is to register an HTTP
 * observer so, HTTP communication can be interecepted and all incoming data stored within
 * a cache.
 */
Firebug.TabCacheModel = extend(Firebug.Module,
{
    initializeUI: function(owner)
    {
        if (FBTrace.DBG_CACHE)
            FBTrace.sysout("tabCache. Cache model initialized.");

        // Read additional text mime-types from preferences.
        var mimeTypes = Firebug.getPref(Firebug.prefDomain, "cache.mimeTypes");
        if (mimeTypes) {
            var list = mimeTypes.split(" ");
            for (var i=0; i<list.length; i++)
                contentTypes[list[i]] = 1;

            if (FBTrace.DBG_CACHE)
                FBTrace.sysout("tabCache.initializeUI, custom mime-types added", list);
        }

        // Register for HTTP events.
        if (Ci.nsITraceableChannel)
            httpObserver.addObserver(this, "firebug-http-event", false);
    },

    shutdown: function()
    {
        if (Ci.nsITraceableChannel)
            httpObserver.removeObserver(this, "firebug-http-event");
    },

    initContext: function(context)
    {
        if (FBTrace.DBG_CACHE)
            FBTrace.dumpProperties("tabCache.initContext for: " + context.window.location.href);
    },

    /* nsIObserver */
    observe: function(subject, topic, data)
    {
        try
        {
            if (!(subject instanceof Ci.nsIHttpChannel))
                return;

            var win = getWindowForRequest(subject);
            var tabId = Firebug.getTabIdForWindow(win);
            if (!(tabId && win))
                return;

            if (topic == "http-on-modify-request")
                this.onModifyRequest(subject, win, tabId);
            else if (topic == "http-on-examine-response")
                this.onExamineResponse(subject, win, tabId);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.sysout("tabCache.observe EXCEPTION", err);
        }
    },

    onModifyRequest: function(request, win, tabId)
    {
    },

    onExamineResponse: function(request, win, tabId)
    {
        try
        {
            // Register traceable channel listener in order to intercept all incoming data for
            // this context/tab. nsITraceableChannel interface is introduced in Firefox 3.0.4
            request.QueryInterface(Ci.nsITraceableChannel);
            var newListener = new TracingListener(win);
            newListener.listener = request.setNewListener(newListener);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache: Register Traceable Listener EXCEPTION", err);
        }
    },
});

// ************************************************************************************************

/**
 * This cache object is intended to cache all responses made by a specific tab.
 * The implementation is based on nsITraceableChannel interface introduced in
 * Firefox 3.0.4. This interface allows to intercept all incoming HTTP data.
 *
 * This object replaces the SourceCache, which still exist only for backward
 * compatibility.
 *
 * The object is derived from SourceCache so, the same interface and most of the
 * implementation is used.
 */
Firebug.TabCache = function(win)
{
    if (FBTrace.DBG_CACHE)
        FBTrace.dumpProperties("tabCache.TabCache Created for: " + win.location.href);

    Firebug.SourceCache.call(this, win, null);
};

Firebug.TabCache.prototype = extend(Firebug.SourceCache.prototype,
{
    listeners: [],
    requests: [],       // requests in progress.

    storePartialResponse: function(request, responseText)
    {
        var url = safeGetName(request);

        if (!this.requests[url])
        {
            this.invalidate(url);
            this.requests[url] = request;
        }

        // Convert
        responseText = FBL.convertToUnicode(responseText);

        // Store partial content into the cache.
        this.store(url, responseText);
    },

    stopRequest: function(request)
    {
        var url = safeGetName(request);
        delete this.requests[url];

        // Notify listeners.
        dispatch(this.listeners, "onStoreResponse", [this.window, request, this.cache[url]]);
    },

    storeSplitLines: function(url, lines)
    {
        if (FBTrace.DBG_CACHE)
            FBTrace.sysout("tabCache.storeSplitLines: " + url, lines);

        var currLines = this.cache[url];
        if (!currLines)
            currLines = this.cache[url] = [];

        // Join the last line with the new first one so, the source code
        // lines are properly formatted.
        if (currLines.length)
            currLines[currLines.length-1] += lines.shift();

        // Append new lines (if any) into the array for specified url.
        if (lines.length)
            this.cache[url] = currLines.concat(lines);

    	return this.cache[url];
    },

    loadFromCache: function(url, method, file)
    {
        // The ancestor implementation (SourceCache) uses ioService.newChannel, which
        // can result in additional request to the server (in case the response can't
        // be loaded from the Firefox cache) - known as double-load problem.
        // This new implementation (TabCache) uses nsITraceableListener so, all responses
        // should be already cached.

        if (FBTrace.DBG_CACHE)
            FBTrace.dumpProperties("tabCache.loadFromCache: FAILED " +
                this.window.location.href, this.cache);
    },

    // Listeners
    addListener: function(listener)
    {
        this.listeners.push(listener);
    },

    removeListener: function(listener)
    {
        remove(this.listeners, listener);
    }
});

// ************************************************************************************************
// TracingListener implementation

/**
 * This object implements nsIStreamListener interface and is intended to monitor all network
 * channels (nsIHttpChannel). For every channel a new instance of this object is created and
 * registered. See Firebug.TabCacheModel.onExamineResponse method.
 */
function TracingListener(win)
{
    this.window = win;
    this.listener = null;
    this.endOfLine = false;
}

TracingListener.prototype =
{
    onCollectData: function(request, inputStream, offset, count)
    {
        try
        {
            var binaryInputStream = CCIN("@mozilla.org/binaryinputstream;1", "nsIBinaryInputStream");
            var storageStream = CCIN("@mozilla.org/storagestream;1", "nsIStorageStream");
            var binaryOutputStream = CCIN("@mozilla.org/binaryoutputstream;1", "nsIBinaryOutputStream");

            binaryInputStream.setInputStream(inputStream);
            storageStream.init(8192, count, null);
            binaryOutputStream.setOutputStream(storageStream.getOutputStream(0));

            var data = binaryInputStream.readBytes(count);
            binaryOutputStream.writeBytes(data, count);

            // Avoid creating additional empty line if response comes in more pieces
            // and the split is made just between "\r" and "\n" (Win line-end).
            // So, if the response starts with "\n" while the previous part ended with "\r",
            // remove the first character.
            if (this.endOfLine && data.length && data[0] == "\n")
                data = data.substring(1);

            if (data.length)
                this.endOfLine = data[data.length-1] == "\r";

            // At this moment, initContext is alredy called so, the context is
            // ready and associated with the window.
            var context = TabWatcher.getContextByWindow(this.window);
            if (context)
            {
                // Store received data into the cache as they come.
                context.sourceCache.storePartialResponse(request, data);
            }
            else
            {
                if (FBTrace.DBG_CACHE)
                    FBTrace.dumpProperties("tabCache.onCollectData NO CONTEXT for: " + this.window.location.href);
            }

            // Let other listeners use the stream.
            return storageStream.newInputStream(0);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache.TracingListener.onCollectData EXCEPTION\n", err);
        }

        return null;
    },

    /* nsIStreamListener */
    onDataAvailable: function(request, requestContext, inputStream, offset, count)
    {
        // Cache only text responses for now.
        if (contentTypes[request.contentType])
        {
            var newStream = this.onCollectData(request, inputStream, offset, count);
            if (newStream)
                inputStream = newStream;
        }
        else
        {
            if (FBTrace.DBG_CACHE)
                FBTrace.dumpProperties("tabCache.onDataAvailable Content-Type not cached: " +
                    request.contentType + ", " + safeGetName(request));
        }

        try
        {
            if (this.listener)
                this.listener.onDataAvailable(request, requestContext, inputStream, offset, count);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache.TracingListener.onDataAvailable" +
                    "(" + request + ", " + requestContext + ", " +
                    inputStream + ", " + offset + ", " + count + ") EXCEPTION: " +
                    safeGetName(request), err);
        }
    },

    onStartRequest: function(request, requestContext)
    {
        try
        {
            if (this.listener)
                this.listener.onStartRequest(request, requestContext);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache.TracingListener.onStartRequest EXCEPTION\n", err);
        }
    },

    onStopRequest: function(request, requestContext, statusCode)
    {
        try
        {
            var context = TabWatcher.getContextByWindow(this.window);
            if (context)
            {
                context.sourceCache.stopRequest(request);
            }
            else
            {
                if (FBTrace.DBG_CACHE)
                    FBTrace.dumpProperties("tabCache.onStopRequest NO CONTEXT for: " + this.window.location.href);
            }

            if (this.listener)
                this.listener.onStopRequest(request, requestContext, statusCode);
        }
        catch (err)
        {
            if (FBTrace.DBG_ERRORS)
                FBTrace.dumpProperties("tabCache.TracingListener.onStopRequest EXCEPTION\n", err);
        }
    },

    /* nsISupports */
    QueryInterface: function(iid)
    {
        if (iid.equals(Ci.nsIStreamListener) ||
            iid.equals(Ci.nsISupportsWeakReference) ||
            iid.equals(Ci.nsISupports))
        {
            return this;
        }

        throw Components.results.NS_NOINTERFACE;
    }
}

// ************************************************************************************************
// Helpers

function safeGetName(request)
{
    try {
        return request.name;
    }
    catch (exc) {
    }

    return null;
}

// ************************************************************************************************
// Registration

Firebug.registerModule(Firebug.TabCacheModel);

// ************************************************************************************************

}});
<|endoftext|>


<commit_before>module.exports = {
    default: {
        estimationMetadata: [
            { name: 'customerName', 'label': '発行先正式社名', 'required': true },
            { name: 'issueDate', 'label': '発行希望日' },
            { name: 'title', 'label': '件名', 'required': true },
            { name: 'deliveryDate', 'label': '納品日' },
            { name: 'deliveryPlace', 'label': '納品場所' },
            { name: 'contractStartDate', 'label': '契約期間開始日' },
            { name: 'contractEndDate', 'label': '契約期間終了日' }
        ],
        summaryColumns: [
            { name: 'cost', 'label': '仕入額(コスト)', type: 'yen' },
            { name: 'receipt', 'label': '売上', type: 'yen' },
            { name: 'profitRate', 'label': '利益率', type: 'rate' }
        ],
        purchaseItemsColumns: [
            { name: 'itemId', 'label': '商品番号' },
            { name: 'name', 'label': '商品名' },
            { name: 'unit', 'label': '単位' },
            { name: 'supplierPrice', 'label': '仕入単価', type: 'yen' }
        ]
    },
    sellers: [
        {
            name: 'distributor',
            summaryColumns: [
                { name: 'receipt', 'label': '売上', type: 'yen' }
            ],
            purchaseItemsColumns: [
                { name: 'itemId', 'label': '商品番号' },
                { name: 'name', 'label': '商品名' },
                { name: 'unit', 'label': '単位' }
            ]
        }
    ]
};<commit_msg>Update sample setting<commit_after>module.exports = {
    default: {
        fileName: '概算見積',
        estimationMetadata: [
            { name: 'customerName', 'label': '発行先正式社名', 'required': true },
            { name: 'issueDate', 'label': '発行希望日' },
            { name: 'title', 'label': '件名', 'required': true },
            { name: 'deliveryDate', 'label': '納品日' },
            { name: 'deliveryPlace', 'label': '納品場所' },
            { name: 'contractStartDate', 'label': '契約期間開始日' },
            { name: 'contractEndDate', 'label': '契約期間終了日' }
        ],
        summaryColumns: [
            { name: 'cost', 'label': '仕入額', type: 'yen' },
            { name: 'receipt', 'label': '売上', type: 'yen' },
            { name: 'profitRate', 'label': '利益率', type: 'rate' }
        ],
        purchaseItemsColumns: [
            { name: 'itemId', 'label': '商品番号' },
            { name: 'name', 'label': '商品名' },
            { name: 'unit', 'label': '単位' },
            { name: 'supplierPrice', 'label': '仕入単価', type: 'yen' }
        ],
        exchangeRate: {
            main: 'JPY',
            pairs: [
                {
                    pair: 'USD/JPY',
                    rate: 105
                }
            ]
        },
        showExchangeRate: ['USD/JPY']
    },
    sellers: [
        {
            name: 'distributor',
            fileName: '概算見積-distributor',
            summaryColumns: [
                { name: 'receipt', 'label': '売上', type: 'yen' }
            ],
            purchaseItemsColumns: [
                { name: 'itemId', 'label': '商品番号' },
                { name: 'name', 'label': '商品名' },
                { name: 'unit', 'label': '単位' }
            ]
        }
    ]
};<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { View, Text } from 'react-native'
import css from '../../styles/css'
import ParkingDetail from './ParkingDetail'
import LAYOUT from '../../styles/LayoutConstants'
import { getPRM } from '../../util/general'

class ParkingOverview extends Component {
	getTotalSpots() {
		const { structureData, spotsSelected } = this.props
		let totalAvailableSpots = 0
		for (let i = 0; i < spotsSelected.length; i++) {
			const parkingSpotsPerType = structureData.Availability[spotsSelected[i]]
			if (parkingSpotsPerType) {
				for (let j = 0; j < parkingSpotsPerType.length; j++) {
					totalAvailableSpots += Number(parkingSpotsPerType[j].Open)
				}
			}
		}
		return totalAvailableSpots
	}

	// this function returns the number of parking spots open of a given type
	// returns -1 if the structure does not have the specific type
	getOpenPerType(currentType) {
		const { structureData } = this.props

		const tempType = structureData.Availability[currentType]
		let openPerType = 0
		if (tempType) {
			for (let i = 0; i < tempType.length; i++) {
				openPerType += Number(tempType[i].Open)
			}
			return openPerType
		} else {
			return -1
		}
	}

	getTotalPerType(currentType) {
		const { structureData } = this.props
		const tempType = structureData.Availability[currentType]
		let totalPerType = 0
		if (tempType) {
			for (let i = 0; i < tempType.length; i++) {
				totalPerType += Number(tempType[i].Total)
			}
		}
		return totalPerType
	}

	displaySpots() {
		const message = 'Please select parking type'
		if (this.getTotalSpots() === 0) {
			return message
		} else {
			return this.getTotalSpots()
		}
	}

	renderDetails() {
		const { spotsSelected } = this.props
		if (spotsSelected.length === 0) {
			return null
		} else if (spotsSelected.length === 1) {
			return (
				<View style={css.po_one_spot_selected}>
					<ParkingDetail
						spotType={spotsSelected[0]}
						spotsAvailable={this.getOpenPerType(spotsSelected[0])}
						totalSpots={this.getTotalPerType(spotsSelected[0])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.38}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.037}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.14) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.08}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.14}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.06}
					/>
				</View>
			)
		} else if (spotsSelected.length === 2) {
			return (
				<View style={css.po_two_spots_selected}>
					<ParkingDetail
						spotType={spotsSelected[0]}
						spotsAvailable={this.getOpenPerType(spotsSelected[0])}
						totalSpots={this.getTotalPerType(spotsSelected[0])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.32}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.032}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.137) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.075}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.12}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.05}
					/>
					<View style={{ paddingHorizontal: 20 }} />
					<ParkingDetail
						spotType={spotsSelected[1]}
						spotsAvailable={this.getOpenPerType(spotsSelected[1])}
						totalSpots={this.getTotalPerType(spotsSelected[1])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.32}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.032}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.137) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.075}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.12}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.05}
					/>
				</View>
			)
		} else {
			return (
				<View style={css.po_three_spots_selected}>
					<ParkingDetail
						spotType={spotsSelected[0]}
						spotsAvailable={this.getOpenPerType(spotsSelected[0])}
						totalSpots={this.getTotalPerType(spotsSelected[0])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.25}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.025}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.124) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.062}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.08}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.035}
					/>
					<View style={{ paddingHorizontal: 10 }} />
					<ParkingDetail
						spotType={spotsSelected[1]}
						spotsAvailable={this.getOpenPerType(spotsSelected[1])}
						totalSpots={this.getTotalPerType(spotsSelected[1])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.25}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.025}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.124) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.062}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.08}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.035}
					/>
					<View style={{ paddingHorizontal: 10 }} />
					<ParkingDetail
						spotType={spotsSelected[2]}
						spotsAvailable={this.getOpenPerType(spotsSelected[2])}
						totalSpots={this.getTotalPerType(spotsSelected[2])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.25}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.025}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.124) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.062}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.08}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.035}
					/>
				</View>
			)
		}
	}

	render() {
		const { structureData, spotsSelected } = this.props
		let message
		if (Array.isArray(spotsSelected) && spotsSelected.length > 0) {
			const totalSpots = this.getTotalSpots()
			if (totalSpots === 1) {
				message = '~ ' + totalSpots + ' Spot Available'
			} else {
				message = '~ ' + totalSpots + ' Spots Available'
			}
		} else {
			message = 'Please select a parking type'
		}

		return (
			<View style={{ flex: 1, width: LAYOUT.MAX_CARD_WIDTH }}>
				<Text style={css.po_structure_name}>{structureData.LocationName}</Text>
				<Text style={css.po_structure_spots_available}>{message}</Text>
				{this.renderDetails()}
				<Text style={css.po_structure_comingsoon}>More Lots Coming Soon!</Text>
			</View>
		)
	}
}

export default ParkingOverview
<commit_msg>Handle an issue where structureData.Availability can be undefined<commit_after>import React, { Component } from 'react'
import { View, Text } from 'react-native'
import css from '../../styles/css'
import ParkingDetail from './ParkingDetail'
import LAYOUT from '../../styles/LayoutConstants'
import logger from '../../util/logger'

class ParkingOverview extends Component {
	getTotalSpots() {
		try {
			const { structureData, spotsSelected } = this.props
			let totalAvailableSpots = 0
			if (Array.isArray(spotsSelected)) {
				for (let i = 0; i < spotsSelected.length; i++) {
					if (structureData.Availability && spotsSelected[i]) {
						const parkingSpotsPerType = structureData.Availability[spotsSelected[i]]
						if (Array.isArray(parkingSpotsPerType)) {
							for (let j = 0; j < parkingSpotsPerType.length; j++) {
								totalAvailableSpots += Number(parkingSpotsPerType[j].Open)
							}
						}
					}
				}
			}
			return totalAvailableSpots
		} catch (error) {
			logger.trackException(error, false)
		}
	}

	// this function returns the number of parking spots open of a given type
	// returns -1 if the structure does not have the specific type
	getOpenPerType(currentType) {
		const { structureData } = this.props

		const tempType = structureData.Availability[currentType]
		let openPerType = 0
		if (tempType) {
			for (let i = 0; i < tempType.length; i++) {
				openPerType += Number(tempType[i].Open)
			}
			return openPerType
		} else {
			return -1
		}
	}

	getTotalPerType(currentType) {
		const { structureData } = this.props
		const tempType = structureData.Availability[currentType]
		let totalPerType = 0
		if (tempType) {
			for (let i = 0; i < tempType.length; i++) {
				totalPerType += Number(tempType[i].Total)
			}
		}
		return totalPerType
	}

	displaySpots() {
		const message = 'Please select parking type'
		if (this.getTotalSpots() === 0) {
			return message
		} else {
			return this.getTotalSpots()
		}
	}

	renderDetails() {
		const { spotsSelected } = this.props
		if (spotsSelected.length === 0) {
			return null
		} else if (spotsSelected.length === 1) {
			return (
				<View style={css.po_one_spot_selected}>
					<ParkingDetail
						spotType={spotsSelected[0]}
						spotsAvailable={this.getOpenPerType(spotsSelected[0])}
						totalSpots={this.getTotalPerType(spotsSelected[0])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.38}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.037}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.14) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.08}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.14}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.06}
					/>
				</View>
			)
		} else if (spotsSelected.length === 2) {
			return (
				<View style={css.po_two_spots_selected}>
					<ParkingDetail
						spotType={spotsSelected[0]}
						spotsAvailable={this.getOpenPerType(spotsSelected[0])}
						totalSpots={this.getTotalPerType(spotsSelected[0])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.32}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.032}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.137) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.075}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.12}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.05}
					/>
					<View style={{ paddingHorizontal: 20 }} />
					<ParkingDetail
						spotType={spotsSelected[1]}
						spotsAvailable={this.getOpenPerType(spotsSelected[1])}
						totalSpots={this.getTotalPerType(spotsSelected[1])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.32}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.032}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.137) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.075}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.12}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.05}
					/>
				</View>
			)
		} else {
			return (
				<View style={css.po_three_spots_selected}>
					<ParkingDetail
						spotType={spotsSelected[0]}
						spotsAvailable={this.getOpenPerType(spotsSelected[0])}
						totalSpots={this.getTotalPerType(spotsSelected[0])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.25}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.025}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.124) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.062}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.08}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.035}
					/>
					<View style={{ paddingHorizontal: 10 }} />
					<ParkingDetail
						spotType={spotsSelected[1]}
						spotsAvailable={this.getOpenPerType(spotsSelected[1])}
						totalSpots={this.getTotalPerType(spotsSelected[1])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.25}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.025}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.124) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.062}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.08}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.035}
					/>
					<View style={{ paddingHorizontal: 10 }} />
					<ParkingDetail
						spotType={spotsSelected[2]}
						spotsAvailable={this.getOpenPerType(spotsSelected[2])}
						totalSpots={this.getTotalPerType(spotsSelected[2])}
						size={LAYOUT.MAX_CARD_WIDTH * 0.25}
						widthMultiplier={LAYOUT.MAX_CARD_WIDTH * 0.025}
						circleRadius={(LAYOUT.MAX_CARD_WIDTH * 0.124) / 2}
						letterSize={LAYOUT.MAX_CARD_WIDTH * 0.062}
						progressNumber={LAYOUT.MAX_CARD_WIDTH * 0.08}
						progressPercent={LAYOUT.MAX_CARD_WIDTH * 0.035}
					/>
				</View>
			)
		}
	}

	render() {
		const { structureData, spotsSelected } = this.props
		let message
		if (Array.isArray(spotsSelected) && spotsSelected.length > 0) {
			const totalSpots = this.getTotalSpots()
			if (totalSpots === 1) {
				message = '~ ' + totalSpots + ' Spot Available'
			} else {
				message = '~ ' + totalSpots + ' Spots Available'
			}
		} else {
			message = 'Please select a parking type'
		}

		return (
			<View style={{ flex: 1, width: LAYOUT.MAX_CARD_WIDTH }}>
				<Text style={css.po_structure_name}>{structureData.LocationName}</Text>
				<Text style={css.po_structure_spots_available}>{message}</Text>
				{this.renderDetails()}
				<Text style={css.po_structure_comingsoon}>More Lots Coming Soon!</Text>
			</View>
		)
	}
}

export default ParkingOverview
<|endoftext|>


<commit_before>var async = require("async");
var es = require("event-stream");
var fs = require("fs");
var gulp = require("gulp");
var templateCache = require("gulp-angular-templatecache");
var clean = require("gulp-clean");
var concat = require("gulp-concat");
var cssBase64 = require("gulp-css-base64");
var gulpIf = require("gulp-if");
var cleanCss = require("gulp-clean-css");
var newer = require("gulp-newer");
var ngAnnotate = require("gulp-ng-annotate");
var replace = require("gulp-replace");
var uglify = require("gulp-uglify");
var mainBowerFiles = require("main-bower-files");
var combine = require("stream-combiner");
var sourcemaps = require("gulp-sourcemaps");

var files = [
	"app/**/*.js",
	"app/**/*.css",
	"app/**/*.html"
];

var deps = mainBowerFiles();

gulp.task("default", [ "all" ]);

gulp.task("clean", function() {
	return combine(
		gulp.src("build"),
		clean()
	);
});

gulp.task("deps", function() {
	return combine(
		gulp.src(deps, { base: process.cwd() + "/" }),
		gulpIf([ "**/*.js", "**/*.css" ], combine(
			gulpIf("**/*.js", combine(
				newer("build/dependencies.js"),
				sourcemaps.init({ loadMaps: true }),
				concat("dependencies.js"),
				uglify(),
				sourcemaps.write("./sourcemaps")
			)),
			gulpIf("**/*.css", combine(
				newer("build/dependencies.css"),
				gulpIf("**/bower_components/bootstrap/**", combine(
					replace("src: url('../fonts/glyphicons-halflings-regular.eot');", ""),
					replace(/src: url\('\.\.\/fonts\/glyphicons-halflings-regular\..*/g, "src: url('../fonts/glyphicons-halflings-regular.ttf') format('truetype');")
				)),
				cssBase64({ maxWeightResource: 1000000 }),
				sourcemaps.init({ loadMaps: true }),
				concat("dependencies.css"),
				cleanCss(),
				sourcemaps.write("./sourcemaps")
			)),
			gulp.dest("build")
		))
	);
});

gulp.task("app", function() {
	return combine(
		gulp.src(files, { base: process.cwd() + "/" }),
		gulpIf("**/*.html", templateCache({ module: "facilpad", base: process.cwd() + "/app/" })),
		gulpIf("**/*.js", combine(
			newer("build/app.js"),
			sourcemaps.init(),
			concat("app.js"),
			ngAnnotate(),
			uglify(),
			sourcemaps.write("./sourcemaps")
		)),
		gulpIf("**/*.css", combine(
			newer("build/app.css"),
			cssBase64({ maxWeightResource: 1000000 }),
			sourcemaps.init(),
			concat("app.css"),
			cleanCss(),
			sourcemaps.write("./sourcemaps")
		)),
		gulp.dest("build")
	);
});

gulp.task("all", [ "deps", "app" ], function(callback) {
	async.series([
		function(next) {
			combine(
				es.merge(
					combine(
						gulp.src([ "build/dependencies.js", "build/app.js" ]),
						sourcemaps.init({ loadMaps: true }),
						concat("all.js"),
						sourcemaps.write("./sourcemaps")
					),
					combine(
						gulp.src([ "build/dependencies.css", "build/app.css" ]),
						sourcemaps.init({ loadMaps: true }),
						concat("all.css"),
						sourcemaps.write("./sourcemaps")
					)
				),
				gulp.dest("build"),
				es.wait(next)
			);
		}/*, function(next) {
			combine(
				gulp.src("index.html"),
				replace("<!-- inject:css -->", "<style>" + fs.readFileSync("build/all.css") + "</style>"),
				replace("<!-- inject:js -->", "<script>" + fs.readFileSync("build/all.js") + "</script>"),
				replace("<!-- endinject -->", ""),
				gulp.dest("build"),
				es.wait(next)
			);
		}*/
	], callback);
});

gulp.task("watch", [ "all" ], function() {
	gulp.watch([ "index.html" ].concat(files), [ "all" ]);
});<commit_msg>Detect changes in bower.json in gulp watch<commit_after>var async = require("async");
var es = require("event-stream");
var fs = require("fs");
var gulp = require("gulp");
var templateCache = require("gulp-angular-templatecache");
var clean = require("gulp-clean");
var concat = require("gulp-concat");
var cssBase64 = require("gulp-css-base64");
var gulpIf = require("gulp-if");
var cleanCss = require("gulp-clean-css");
var newer = require("gulp-newer");
var ngAnnotate = require("gulp-ng-annotate");
var replace = require("gulp-replace");
var uglify = require("gulp-uglify");
var mainBowerFiles = require("main-bower-files");
var combine = require("stream-combiner");
var sourcemaps = require("gulp-sourcemaps");

var files = [
	"app/**/*.js",
	"app/**/*.css",
	"app/**/*.html"
];

gulp.task("default", [ "all" ]);

gulp.task("clean", function() {
	return combine(
		gulp.src("build"),
		clean()
	);
});

gulp.task("deps", function() {
	return combine(
		gulp.src(mainBowerFiles(), { base: process.cwd() + "/" }),
		gulpIf([ "**/*.js", "**/*.css" ], combine(
			gulpIf("**/*.js", combine(
				newer("build/dependencies.js"),
				sourcemaps.init({ loadMaps: true }),
				concat("dependencies.js"),
				uglify(),
				sourcemaps.write("./sourcemaps")
			)),
			gulpIf("**/*.css", combine(
				newer("build/dependencies.css"),
				gulpIf("**/bower_components/bootstrap/**", combine(
					replace("src: url('../fonts/glyphicons-halflings-regular.eot');", ""),
					replace(/src: url\('\.\.\/fonts\/glyphicons-halflings-regular\..*/g, "src: url('../fonts/glyphicons-halflings-regular.ttf') format('truetype');")
				)),
				cssBase64({ maxWeightResource: 1000000 }),
				sourcemaps.init({ loadMaps: true }),
				concat("dependencies.css"),
				cleanCss(),
				sourcemaps.write("./sourcemaps")
			)),
			gulp.dest("build")
		))
	);
});

gulp.task("app", function() {
	return combine(
		gulp.src(files, { base: process.cwd() + "/" }),
		gulpIf("**/*.html", templateCache({ module: "facilpad", base: process.cwd() + "/app/" })),
		gulpIf("**/*.js", combine(
			newer("build/app.js"),
			sourcemaps.init(),
			concat("app.js"),
			ngAnnotate(),
			uglify(),
			sourcemaps.write("./sourcemaps")
		)),
		gulpIf("**/*.css", combine(
			newer("build/app.css"),
			cssBase64({ maxWeightResource: 1000000 }),
			sourcemaps.init(),
			concat("app.css"),
			cleanCss(),
			sourcemaps.write("./sourcemaps")
		)),
		gulp.dest("build")
	);
});

gulp.task("all", [ "deps", "app" ], function(callback) {
	async.series([
		function(next) {
			combine(
				es.merge(
					combine(
						gulp.src([ "build/dependencies.js", "build/app.js" ]),
						sourcemaps.init({ loadMaps: true }),
						concat("all.js"),
						sourcemaps.write("./sourcemaps")
					),
					combine(
						gulp.src([ "build/dependencies.css", "build/app.css" ]),
						sourcemaps.init({ loadMaps: true }),
						concat("all.css"),
						sourcemaps.write("./sourcemaps")
					)
				),
				gulp.dest("build"),
				es.wait(next)
			);
		}/*, function(next) {
			combine(
				gulp.src("index.html"),
				replace("<!-- inject:css -->", "<style>" + fs.readFileSync("build/all.css") + "</style>"),
				replace("<!-- inject:js -->", "<script>" + fs.readFileSync("build/all.js") + "</script>"),
				replace("<!-- endinject -->", ""),
				gulp.dest("build"),
				es.wait(next)
			);
		}*/
	], callback);
});

gulp.task("watch", [ "all" ], function() {
	gulp.watch([ "index.html", "bower.json" ].concat(files), [ "all" ]);
});<|endoftext|>


<commit_before>((window) => {
  // TODO: show world data when click outside countries
  let map;

  let width = 0;
  let height = 0;
  let shift = 0;

  let tooltipLeft = 0;
  let tooltipTop = 0;
  let tooltip;

  let scale = 1;
  let initX = 0;
  let mouseClicked = false;
  let selectedCountry = '';
  let zoomExtent = [1, 10];

  let onSelectLocation;

  let projection, path, zoom, g;

  function onStartPanning() {
    d3.event.preventDefault();
    initX = d3.mouse(this)[0];
    mouseClicked = true;
  };

  function onEndPanning() {
    shift = shift + ((d3.mouse(this)[0] - initX) * 360 / (scale * width));
    mouseClicked = false;
  };

  const svg = d3.select('#map svg')
    .on('mousedown', onStartPanning)
    .on('mouseup', onEndPanning);

  function onShiftMap(endX) {
    projection.rotate([shift + (endX - initX) * 360 / (scale * width), 0, 0])
    g.selectAll('path')
      .attr('d', path);
  };

  function showTooltip(name) {
    const mouse = d3.mouse(svg.node())
      .map(function(v) { return parseInt(v); } );
    tooltip.classed('__hidden', false)
      .attr('style', 'left:' + (mouse[0] + tooltipLeft) + 'px;top:' + (mouse[1] + tooltipTop) + 'px')
      .html(name);
  };

  function onClick(id, name) {
    if (selectedCountry !== id) {
      selectedCountry = id;
      d3.select('.__selected').classed('__selected', false);
      d3.select('#' + id).classed('__selected', true);
      onSelectLocation(id, name);
    }
  };

  function onZoomMap() {
    const t = d3.event.translate;
    const h = 0;
    scale = d3.event.scale;

    t[0] = Math.min(
      (width/height) * (scale - 1),
      Math.max(width * (1 - scale), t[0])
    );

    t[1] = Math.min(
      h * (scale - 1) + h * scale,
      Math.max(height * (1 - scale) - h * scale, t[1])
    );

    zoom.translate(t);
    if (mouseClicked) {
      onShiftMap(d3.mouse(this)[0]);
      return;
    }

    g.attr('transform', 'translate(' + t + ')scale(' + scale + ')');
    d3.selectAll('.vis-world')
      .style('stroke-width', 0.5 / scale);

    // TODO: call for cities
  };

  function resizeMap() {
    scale = 1;
    width = map.clientWidth;
    height = map.clientHeight;

    tooltipLeft = map.offsetLeft + 10;
    tooltipTop = map.offsetTop + 10;

    projection = d3.geo.mercator()
      .scale(Math.min(width, height) * 0.2)
      .translate([width / 2, height / 1.5])
      .rotate([shift, 0, 0]);

    zoom.on('zoom', onZoomMap);

    path = d3.geo
      .path()
      .projection(projection);

    svg
      .attr('width', width)
      .attr('height', height)
      .call(zoom);

    onShiftMap(initX);
  };

  // Public methods
  const WorldMap = {
    resize() {
      resizeMap();
    },

    showCities(avaliableCities) {
      // TODO
    },

    init(onSelect, avaliableCountries) {
      map = document.getElementById('map');
      tooltip = d3.select('#map .vis-tooltip');
      g = svg.append('g');
      onSelectLocation = onSelect;
      zoom = d3.behavior.zoom().scaleExtent(zoomExtent)

      resize();

      d3.json('data/topology.json', function(error, world) {
        if(error) return console.error(error);

        g.append('g')
          .attr('class', 'vis-world')
          .selectAll('vis-world')
          .data(topojson.feature(world, world.countries).features)
          .enter().append('path')
          .attr('class', 'vis-country')
          .attr('id', function(d) { return d.id; })
          .attr('d', path)
          .each(function(d) {
            const item = d3.select(this);
            const filter = avaliableCountries.filter((country) => country.code === d.id);
            if (filter.length > 0) {
              item
                .on('mousedown', function(d) { onClick(d.id, filter[0].name); })
                .on('mousemove', function(d) { showTooltip(filter[0].name); })
                .on('mouseout',  function(d, i) { tooltip.classed('__hidden', true); });
            } else {
              item
                .attr('class', 'vis-country __disabled');
            }
          });
      });
    },
  };

  // Expose API globally.
  window.DS = Object.assign({}, window.DS || {}, {
    WorldMap
  });
})(window);
<commit_msg>Fix wrong func name<commit_after>((window) => {
  // TODO: show world data when click outside countries
  let map;

  let width = 0;
  let height = 0;
  let shift = 0;

  let tooltipLeft = 0;
  let tooltipTop = 0;
  let tooltip;

  let scale = 1;
  let initX = 0;
  let mouseClicked = false;
  let selectedCountry = '';
  let zoomExtent = [1, 10];

  let onSelectLocation;

  let projection, path, zoom, g;

  function onStartPanning() {
    d3.event.preventDefault();
    initX = d3.mouse(this)[0];
    mouseClicked = true;
  };

  function onEndPanning() {
    shift = shift + ((d3.mouse(this)[0] - initX) * 360 / (scale * width));
    mouseClicked = false;
  };

  const svg = d3.select('#map svg')
    .on('mousedown', onStartPanning)
    .on('mouseup', onEndPanning);

  function onShiftMap(endX) {
    projection.rotate([shift + (endX - initX) * 360 / (scale * width), 0, 0])
    g.selectAll('path')
      .attr('d', path);
  };

  function showTooltip(name) {
    const mouse = d3.mouse(svg.node())
      .map(function(v) { return parseInt(v); } );
    tooltip.classed('__hidden', false)
      .attr('style', 'left:' + (mouse[0] + tooltipLeft) + 'px;top:' + (mouse[1] + tooltipTop) + 'px')
      .html(name);
  };

  function onClick(id, name) {
    if (selectedCountry !== id) {
      selectedCountry = id;
      d3.select('.__selected').classed('__selected', false);
      d3.select('#' + id).classed('__selected', true);
      onSelectLocation(id, name);
    }
  };

  function onZoomMap() {
    const t = d3.event.translate;
    const h = 0;
    scale = d3.event.scale;

    t[0] = Math.min(
      (width/height) * (scale - 1),
      Math.max(width * (1 - scale), t[0])
    );

    t[1] = Math.min(
      h * (scale - 1) + h * scale,
      Math.max(height * (1 - scale) - h * scale, t[1])
    );

    zoom.translate(t);
    if (mouseClicked) {
      onShiftMap(d3.mouse(this)[0]);
      return;
    }

    g.attr('transform', 'translate(' + t + ')scale(' + scale + ')');
    d3.selectAll('.vis-world')
      .style('stroke-width', 0.5 / scale);

    // TODO: call for cities
  };

  function resizeMap() {
    scale = 1;
    width = map.clientWidth;
    height = map.clientHeight;

    tooltipLeft = map.offsetLeft + 10;
    tooltipTop = map.offsetTop + 10;

    projection = d3.geo.mercator()
      .scale(Math.min(width, height) * 0.2)
      .translate([width / 2, height / 1.5])
      .rotate([shift, 0, 0]);

    zoom.on('zoom', onZoomMap);

    path = d3.geo
      .path()
      .projection(projection);

    svg
      .attr('width', width)
      .attr('height', height)
      .call(zoom);

    onShiftMap(initX);
  };

  // Public methods
  const WorldMap = {
    resize() {
      resizeMap();
    },

    showCities(avaliableCities) {
      // TODO
    },

    init(onSelect, avaliableCountries) {
      map = document.getElementById('map');
      tooltip = d3.select('#map .vis-tooltip');
      g = svg.append('g');
      onSelectLocation = onSelect;
      zoom = d3.behavior.zoom().scaleExtent(zoomExtent)

      resizeMap();

      d3.json('data/topology.json', function(error, world) {
        if(error) return console.error(error);

        g.append('g')
          .attr('class', 'vis-world')
          .selectAll('vis-world')
          .data(topojson.feature(world, world.countries).features)
          .enter().append('path')
          .attr('class', 'vis-country')
          .attr('id', function(d) { return d.id; })
          .attr('d', path)
          .each(function(d) {
            const item = d3.select(this);
            const filter = avaliableCountries.filter((country) => country.code === d.id);
            if (filter.length > 0) {
              item
                .on('mousedown', function(d) { onClick(d.id, filter[0].name); })
                .on('mousemove', function(d) { showTooltip(filter[0].name); })
                .on('mouseout',  function(d, i) { tooltip.classed('__hidden', true); });
            } else {
              item
                .attr('class', 'vis-country __disabled');
            }
          });
      });
    },
  };

  // Expose API globally.
  window.DS = Object.assign({}, window.DS || {}, {
    WorldMap
  });
})(window);
<|endoftext|>


<commit_before>const chalk = require('chalk');
module.exports = client => { // eslint-disable-line no-unused-vars
  console.log(chalk.bgGreen.black('I\'m Online'));
};
<commit_msg>Update ready.js<commit_after>const chalk = require('chalk');
const Discord = require("discord.js");
module.exports = client => { // eslint-disable-line no-unused-vars
  console.log(chalk.bgGreen.black('I\'m Online'));
}

exports.run = (client, message) => {
const modlog = client.channels.find('name', 'on-duty');
const embed = new RichEmbed()
.setColor(0x00ff00)
.setTimestamp()
.setTitle("Bot Status")
.setThumbnail(`${user.avatarURL}`)
.setDescription(`\n`)
.addField("Hey Pie the bot is",`Online! :ok_hand:`,true)
.setFooter(`Bot is currently online!`);
client.channels.get(modlog.id).send({embed}).catch(console.error);
};
<|endoftext|>


<commit_before>/* Copyright (c) 2013 Rod Vagg, MIT License */

function AbstractChainedBatch (db) {
  this._db         = db
  this._operations = []
  this._written    = false
}

AbstractChainedBatch.prototype._checkWritten = function () {
  if (this._written)
    throw new Error('write() already called on this batch')
}

AbstractChainedBatch.prototype.put = function (key, value) {
  this._checkWritten()

  var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
  if (err) throw err
  err = this._db._checkKeyValue(value, 'value', this._db._isBuffer)
  if (err) throw err

  if (!this._db._isBuffer(key)) key = String(key)
  if (!this._db._isBuffer(value)) value = String(value)

  if (typeof this._put == 'function' )
    return this._put(key, value)

  this._operations.push({ type: 'put', key: key, value: value })

  return this
}

AbstractChainedBatch.prototype.del = function (key) {
  this._checkWritten()

  var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
  if (err) throw err

  if (!this._db._isBuffer(key)) key = String(key)

  if (typeof this._del == 'function' )
    return this._del(key)

  this._operations.push({ type: 'del', key: key })

  return this
}

AbstractChainedBatch.prototype.clear = function () {
  this._checkWritten()

  this._operations = []

  if (typeof this._clear == 'function' )
    return this._clear()

  return this
}

AbstractChainedBatch.prototype.write = function (options, callback) {
  this._checkWritten()

  if (typeof options == 'function')
    callback = options
  if (typeof callback != 'function')
    throw new Error('write() requires a callback argument')
  if (typeof options != 'object')
    options = {}

  this._written = true

  if (typeof this._write == 'function' )
    return this._write(options, callback)

  if (typeof this._db._batch == 'function')
    return this._db._batch(this._operations, options, callback)

  process.nextTick(callback)
}

module.exports = AbstractChainedBatch<commit_msg>[fix] Always return this from .put(), .del() and .clear()<commit_after>/* Copyright (c) 2013 Rod Vagg, MIT License */

function AbstractChainedBatch (db) {
  this._db         = db
  this._operations = []
  this._written    = false
}

AbstractChainedBatch.prototype._checkWritten = function () {
  if (this._written)
    throw new Error('write() already called on this batch')
}

AbstractChainedBatch.prototype.put = function (key, value) {
  this._checkWritten()

  var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
  if (err) throw err
  err = this._db._checkKeyValue(value, 'value', this._db._isBuffer)
  if (err) throw err

  if (!this._db._isBuffer(key)) key = String(key)
  if (!this._db._isBuffer(value)) value = String(value)

  if (typeof this._put == 'function' )
    this._put(key, value)
  else
    this._operations.push({ type: 'put', key: key, value: value })

  return this
}

AbstractChainedBatch.prototype.del = function (key) {
  this._checkWritten()

  var err = this._db._checkKeyValue(key, 'key', this._db._isBuffer)
  if (err) throw err

  if (!this._db._isBuffer(key)) key = String(key)

  if (typeof this._del == 'function' )
    this._del(key)
  else
    this._operations.push({ type: 'del', key: key })

  return this
}

AbstractChainedBatch.prototype.clear = function () {
  this._checkWritten()

  this._operations = []

  if (typeof this._clear == 'function' )
    this._clear()

  return this
}

AbstractChainedBatch.prototype.write = function (options, callback) {
  this._checkWritten()

  if (typeof options == 'function')
    callback = options
  if (typeof callback != 'function')
    throw new Error('write() requires a callback argument')
  if (typeof options != 'object')
    options = {}

  this._written = true

  if (typeof this._write == 'function' )
    return this._write(options, callback)

  if (typeof this._db._batch == 'function')
    return this._db._batch(this._operations, options, callback)

  process.nextTick(callback)
}

module.exports = AbstractChainedBatch<|endoftext|>


<commit_before>const webpack = require('webpack')
const base = require('./webpack.base.config')
const vueConfig = require('./vue-loader.config')
const utils = require('./utils')
const path = require('path')
const HTMLPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const SWPrecachePlugin = require('sw-precache-webpack-plugin')

const config = Object.assign({}, base, {
  resolve: {
    alias: Object.assign({}, base.resolve.alias, {
      'create-api': './create-api-client.js',
      'create-route': './create-route-client.js'
    }),
    extensions: base.resolve.extensions
  },
  plugins: (base.plugins || []).concat([
    // strip comments in Vue code
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
      'process.env.VUE_ENV': '"client"',
      'process.BROWSER': true
    }),
    // generate output HTML
    new HTMLPlugin({
      template: 'src/index.template.html'
    })
  ])
})

if (process.env.NODE_ENV === 'production') {
  // Use ExtractTextPlugin to extract CSS into a single file
  // so it's applied on initial render.
  vueConfig.loaders = utils.cssLoaders({
    extract: true
  })

  config.plugins.push(
    new ExtractTextPlugin('styles.css'),
    // this is needed in webpack 2 for minifying CSS
    new webpack.LoaderOptionsPlugin({
      minimize: true
    }),
    // minify JS
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      output: {
        comments: false
      }
    }),
    new SWPrecachePlugin({
      cacheId: 'blog',
      filename: 'service-worker.js',
      minify: true,
      mergeStaticsConfig: true,
      staticFileGlobs: [
        path.join(__dirname, '../dist/static/*.*')
      ],
      stripPrefixMulti: {
        [path.join(__dirname, '../dist/static')]: '/static'
      },
      // add hash to path to force updated
      dontCacheBustUrlsMatching: false,
      staticFileGlobsIgnorePatterns: [
        /index\.html$/,
        /\.map$/,
        /\.css$/,
        /\.svg$/,
        /\.eot$/
      ],
      // runtime caching for offline pwa
      runtimeCaching: [
        {
          // note that this pattern will cache ajax request
          urlPattern: /(.+\/[^\.]*$)/,
          handler: 'networkFirst',
          options: {
            cache: {
              maxEntries: 30,
              name: 'blog-runtime-cache'
            }
          }
        },
        {
          urlPattern: /\.(png|jpg|webp)/,
          handler: 'cacheFirst',
          options: {
            cache: {
              maxEntries: 20,
              name: 'blog-picture-cache'
            }
          }
        }
      ]
    })
  )
}

module.exports = config
<commit_msg>[前端] sw-toolbox禁止缓存sw文件<commit_after>const webpack = require('webpack')
const base = require('./webpack.base.config')
const vueConfig = require('./vue-loader.config')
const utils = require('./utils')
const path = require('path')
const HTMLPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const SWPrecachePlugin = require('sw-precache-webpack-plugin')

const config = Object.assign({}, base, {
  resolve: {
    alias: Object.assign({}, base.resolve.alias, {
      'create-api': './create-api-client.js',
      'create-route': './create-route-client.js'
    }),
    extensions: base.resolve.extensions
  },
  plugins: (base.plugins || []).concat([
    // strip comments in Vue code
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development'),
      'process.env.VUE_ENV': '"client"',
      'process.BROWSER': true
    }),
    // generate output HTML
    new HTMLPlugin({
      template: 'src/index.template.html'
    })
  ])
})

if (process.env.NODE_ENV === 'production') {
  // Use ExtractTextPlugin to extract CSS into a single file
  // so it's applied on initial render.
  vueConfig.loaders = utils.cssLoaders({
    extract: true
  })

  config.plugins.push(
    new ExtractTextPlugin('styles.css'),
    // this is needed in webpack 2 for minifying CSS
    new webpack.LoaderOptionsPlugin({
      minimize: true
    }),
    // minify JS
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      output: {
        comments: false
      }
    }),
    new SWPrecachePlugin({
      cacheId: 'blog',
      filename: 'service-worker.js',
      minify: true,
      mergeStaticsConfig: true,
      staticFileGlobs: [
        path.join(__dirname, '../dist/static/*.*')
      ],
      stripPrefixMulti: {
        [path.join(__dirname, '../dist/static')]: '/static'
      },
      // add hash to path to force updated
      dontCacheBustUrlsMatching: false,
      staticFileGlobsIgnorePatterns: [
        /index\.html$/,
        /\.map$/,
        /\.css$/,
        /\.svg$/,
        /\.eot$/
      ],
      // runtime caching for offline pwa
      runtimeCaching: [
        {
          // never cache service worker
          urlPattern: /service-worker.js/,
          handler: 'networkOnly'
        },
        {
          // note that this pattern will cache ajax request
          urlPattern: /(.+\/[^\.]*$)/,
          handler: 'networkFirst',
          options: {
            cache: {
              maxEntries: 30,
              name: 'blog-runtime-cache'
            }
          }
        },
        {
          urlPattern: /\.(png|jpg|webp)/,
          handler: 'cacheFirst',
          options: {
            cache: {
              maxEntries: 20,
              name: 'blog-picture-cache'
            }
          }
        }
      ]
    })
  )
}

module.exports = config
<|endoftext|>


<commit_before>/* global OC, OCA */

/**
 *
 * @copyright Copyright (c) 2019, Daniel Calviño Sánchez (danxuliu@gmail.com)
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function(OC, OCA) {

	'use strict';

	OCA.Talk = OCA.Talk || {};
	OCA.Talk.Views = OCA.Talk.Views || {};

	/**
	 * Helper to warn the user if she is talking while muted.
	 *
	 * The WebRTC helper emits events when it detects that the user is speaking
	 * while muted; this helper shows a warning to the user based on those
	 * events.
	 *
	 * The warning is not immediately shown, though; the WebRTC helper flags
	 * even short sounds as "speaking" (provided they are strong enough), so to
	 * prevent unnecesary warnings the user has to speak for a few seconds for
	 * the warning to be shown. On the other hand, the warning is hidden as soon
	 * as the WebRTC helper detects that the speaking has stopped; in this case
	 * there is no delay, as the helper itself has a delay before emitting the
	 * event.
	 */
	function SpeakingWhileMutedWarner() {
		this._handleSpeakingWhileMutedBound = this._handleSpeakingWhileMuted.bind(this);
		this._handleStoppedSpeakingWhileMutedBound = this._handleStoppedSpeakingWhileMuted.bind(this);
	}
	SpeakingWhileMutedWarner.prototype = {

		setWebRtc: function(webrtc) {
			if (this._webrtc && this._webrtc.webrtc) {
				this._webrtc.webrtc.off('speakingWhileMuted', this._handleSpeakingWhileMutedBound);
				this._webrtc.webrtc.off('stoppedSpeakingWhileMuted', this._handleStoppedSpeakingWhileMutedBound);
			}

			this._webrtc = webrtc;

			this._webrtc.webrtc.on('speakingWhileMuted', this._handleSpeakingWhileMutedBound);
			this._webrtc.webrtc.on('stoppedSpeakingWhileMuted', this._handleStoppedSpeakingWhileMutedBound);
		},

		_handleSpeakingWhileMuted: function() {
			this._startedSpeakingTimeout = setTimeout(function() {
				delete this._startedSpeakingTimeout;

				this._showWarning();
			}.bind(this), 3000);
		},

		_handleStoppedSpeakingWhileMuted: function() {
			if (this._startedSpeakingTimeout) {
				clearTimeout(this._startedSpeakingTimeout);
				delete this._startedSpeakingTimeout;
			}

			this._hideWarning();
		},

		_showWarning: function() {
			if (this._notification) {
				return;
			}

			this._notification = OC.Notification.show(t('spreed', 'You seem to be talking while muted, please unmute yourself for others to hear you'));
		},

		_hideWarning: function() {
			if (!this._notification) {
				return;
			}

			OC.Notification.hide(this._notification);

			this._notification = null;
		},

	};

	OCA.Talk.Views.SpeakingWhileMutedWarner = SpeakingWhileMutedWarner;

})(OC, OCA);
<commit_msg>Show browser notification if the browser is hidden<commit_after>/* global OC, OCA */

/**
 *
 * @copyright Copyright (c) 2019, Daniel Calviño Sánchez (danxuliu@gmail.com)
 *
 * @license GNU AGPL version 3 or any later version
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

(function(OC, OCA) {

	'use strict';

	OCA.Talk = OCA.Talk || {};
	OCA.Talk.Views = OCA.Talk.Views || {};

	/**
	 * Helper to warn the user if she is talking while muted.
	 *
	 * The WebRTC helper emits events when it detects that the user is speaking
	 * while muted; this helper shows a warning to the user based on those
	 * events.
	 *
	 * The warning is not immediately shown, though; the WebRTC helper flags
	 * even short sounds as "speaking" (provided they are strong enough), so to
	 * prevent unnecesary warnings the user has to speak for a few seconds for
	 * the warning to be shown. On the other hand, the warning is hidden as soon
	 * as the WebRTC helper detects that the speaking has stopped; in this case
	 * there is no delay, as the helper itself has a delay before emitting the
	 * event.
	 *
	 * The way of warning the user changes depending on whether Talk is visible
	 * or not; if it is visible the warning is shown in the Talk UI, but if it
	 * is not it is shown using a browser notification, which will be visible
	 * to the user even if the browser window is not in the foreground (provided
	 * the user granted the permissions to receive notifications from the site).
	 */
	function SpeakingWhileMutedWarner() {
		this._handleSpeakingWhileMutedBound = this._handleSpeakingWhileMuted.bind(this);
		this._handleStoppedSpeakingWhileMutedBound = this._handleStoppedSpeakingWhileMuted.bind(this);
	}
	SpeakingWhileMutedWarner.prototype = {

		setWebRtc: function(webrtc) {
			if (this._webrtc && this._webrtc.webrtc) {
				this._webrtc.webrtc.off('speakingWhileMuted', this._handleSpeakingWhileMutedBound);
				this._webrtc.webrtc.off('stoppedSpeakingWhileMuted', this._handleStoppedSpeakingWhileMutedBound);
			}

			this._webrtc = webrtc;

			this._webrtc.webrtc.on('speakingWhileMuted', this._handleSpeakingWhileMutedBound);
			this._webrtc.webrtc.on('stoppedSpeakingWhileMuted', this._handleStoppedSpeakingWhileMutedBound);
		},

		_handleSpeakingWhileMuted: function() {
			this._startedSpeakingTimeout = setTimeout(function() {
				delete this._startedSpeakingTimeout;

				this._showWarning();
			}.bind(this), 3000);
		},

		_handleStoppedSpeakingWhileMuted: function() {
			if (this._startedSpeakingTimeout) {
				clearTimeout(this._startedSpeakingTimeout);
				delete this._startedSpeakingTimeout;
			}

			this._hideWarning();
		},

		_showWarning: function() {
			var message = t('spreed', 'You seem to be talking while muted, please unmute yourself for others to hear you');

			if (!document.hidden) {
				this._showNotification(message);
			} else {
				this._showBrowserNotification(message);
			}
		},

		_showNotification: function(message) {
			if (this._notification) {
				return;
			}

			this._notification = OC.Notification.show(message);
		},

		_showBrowserNotification: function(message) {
			if (this._browserNotification) {
				return;
			}

			if (!Notification) {
				// The browser does not support the Notification API.
				return;
			}

			if (Notification.permission === 'denied') {
				return;
			}

			if (Notification.permission === 'granted') {
				this._browserNotification = new Notification(message);

				return;
			}

			Notification.requestPermission().then(function(permission) {
				if (permission === 'granted') {
					this._browserNotification = new Notification(message);
				}
			}.bind(this));
		},

		_hideWarning: function() {
			if (this._notification) {
				OC.Notification.hide(this._notification);

				this._notification = null;
			}

			if (this._browserNotification) {
				this._browserNotification.close();

				this._browserNotification = null;
			}
		},

	};

	OCA.Talk.Views.SpeakingWhileMutedWarner = SpeakingWhileMutedWarner;

})(OC, OCA);
<|endoftext|>


<commit_before>/*jslint browser: true*/
/*global $, jQuery, alert, lunr, Search, DOCUMENTATION_OPTIONS*/
(function () {
    "use strict";

    var LunrSearch = {
        store : null,
        index : null,
        highlight : null,

        init : function () {
            var self = this,
                id = null;

            // Search.store is a global that's set before the window load
            // in searchbox.html
            this.store = Search.store;
            this.highlight = $("#ls_lunrsearch-highlight").value === "true";

            lunr.tokenizer.seperator = '.';
            this.index = lunr(function () {
                this.field('prefix');
                this.field('name', { boost: 10 });
                this.ref('id');
            });

            for (id in this.store) {
                if (this.store.hasOwnProperty(id)) {
                    this.index.add({
                        id: id,
                        name: this.store[id].name,
                        prefix: this.store[id].prefix,
                    });
                }
            }

            $("#ls_search-field")
                .keyup(function (event) {
                    self.onKeyUp(self, event);
                })
                .keypress(function (event) {
                    if (event.keyCode === 13) {
                        event.preventDefault();
                        var active = $('#ls_search-results li a.hover')[0];
                        active.click();
                    }
                })
                .focusout(function () {
                    // http://stackoverflow.com/a/13980492/1079728
                    window.setTimeout(function () {
                        $('.results').hide();
                    }, 100);
                })
                .focusin(function () {
                    if ($('#ls_search-results li').length > 0) {
                        $('#ls_search-results').show();
                    }
                });
        }, // end init

        buildHref : function (self, s) {
            var highlightstring = self.highlight ? '?highlight=' + $.urlencode(s.name) : "";

            return DOCUMENTATION_OPTIONS.URL_ROOT + s.filename +
                   DOCUMENTATION_OPTIONS.FILE_SUFFIX +
                   highlightstring +
                   '#' + s.prefix + '.' + s.name;
        }, // buildHref

        onKeyUp : function (self, event) {
            var keycode = event.keyCode || event.which,
                query = $("#ls_search-field").val(),
                ul = $('#ls_search-results'),
                i = 0,
                results = null;

            if (keycode === 13) {
                return;
            }
            if (keycode === 40 || keycode === 38) {
                return this.handleKeyboardNavigation(self, keycode);
            }
            if (query === '') {
                ul.empty().hide();
                return;
            }

            results = self.index.search(query);
            ul.show();

            if (results.length === 0) {
                ul.empty().append($('
No results found
'));
                return;
            }

            ul.empty();
            for (i = 0; i < Math.min(results.length, 5); i += 1) {
                ul.append(self.createResultListElement(self, self.store[results[i].ref]));
            }
        },  // end onKeyUp

        createResultListElement : function (self, s) {
            var prefix = (s.objtype === "py:method") ? (s.last_prefix + ".") : "",
                ul = $('#ls_search-results');

            return $('
')
                .append($('')
                    .attr('href', self.buildHref(self, s))
                    .text(prefix + s.name)
                    .mouseenter(function () {
                        ul.find('li a').removeClass('hover');
                        $(this).addClass('hover');
                    })
                    .mouseleave(function () {
                        $(this).removeClass('hover');
                    })
                    );
        }, // createResultListElement

        handleKeyboardNavigation : function (self, keycode) {
            var ul = $('#ls_search-results'),
                active = $(ul.find('li a.hover')[0]);

            if (keycode === 40) {
                // next
                if (!active.length) {
                    $(ul.find('li a')[0]).addClass('hover');
                } else {
                    active.removeClass('hover');
                    active.parent().next().find('a').addClass('hover');
                }
            } else if (keycode === 38) {
                // prev
                active.removeClass('hover');
                active.parent().prev().find('a').addClass('hover');
            }
        }, // end handle_navigation
    };

    window.onload = function () {
        LunrSearch.init();
    };
}());
<commit_msg>Change javascript style<commit_after>/*jslint browser: true*/
/*global $, jQuery, alert, lunr, Search, DOCUMENTATION_OPTIONS*/
(function () {
    "use strict";

    var store = null,
        index = null,
        highlight = null;

    function init() {
        var id = null;

        // Search.store is a global that's set before the window load
        // in searchbox.html
        store = Search.store;
        highlight = $("#ls_lunrsearch-highlight").value === "true";

        lunr.tokenizer.seperator = '.';
        index = lunr(function () {
            this.field('prefix');
            this.field('name', { boost: 10 });
            this.ref('id');
        });

        for (id in store) {
            if (store.hasOwnProperty(id)) {
                index.add({
                    id: id,
                    name: store[id].name,
                    prefix: store[id].prefix,
                });
            }
        }

        $("#ls_search-field")
            .keyup(function (event) {
                onKeyUp(event);
            })
            .keypress(function (event) {
                if (event.keyCode === 13) {
                    event.preventDefault();
                    var active = $('#ls_search-results li a.hover')[0];
                    active.click();
                }
            })
            .focusout(function () {
                // http://stackoverflow.com/a/13980492/1079728
                window.setTimeout(function () {
                    $('.results').hide();
                }, 100);
            })
            .focusin(function () {
                if ($('#ls_search-results li').length > 0) {
                    $('#ls_search-results').show();
                }
            });
    } // end init

    function onKeyUp(event) {
        var keycode = event.keyCode || event.which,
            query = $("#ls_search-field").val(),
            ul = $('#ls_search-results'),
            i = 0,
            results = null;

        if (keycode === 13) {
            return;
        }
        if (keycode === 40 || keycode === 38) {
            return handleKeyboardNavigation(keycode);
        }
        if (query === '') {
            ul.empty().hide();
            return;
        }

        results = index.search(query);
        ul.show();

        if (results.length === 0) {
            ul.empty().append($('
No results found
'));
            return;
        }

        ul.empty();
        for (i = 0; i < Math.min(results.length, 5); i += 1) {
            ul.append(createResultListElement(store[results[i].ref]));
        }
    }  // end onKeyUp

    function handleKeyboardNavigation(keycode) {
        var ul = $('#ls_search-results'),
            active = $(ul.find('li a.hover')[0]);

        if (keycode === 40) {
            // next
            if (!active.length) {
                $(ul.find('li a')[0]).addClass('hover');
            } else {
                active.removeClass('hover');
                active.parent().next().find('a').addClass('hover');
            }
        } else if (keycode === 38) {
            // prev
            active.removeClass('hover');
            active.parent().prev().find('a').addClass('hover');
        }
    }  // end handleKeyboardNavigation

    function buildHref(s) {
        var highlightstring = highlight ? '?highlight=' + $.urlencode(s.name) : "";

        return DOCUMENTATION_OPTIONS.URL_ROOT + s.filename +
               DOCUMENTATION_OPTIONS.FILE_SUFFIX +
               highlightstring +
               '#' + s.prefix + '.' + s.name;
    } // end buildHref

    function createResultListElement(s) {
        var prefix = (s.objtype === "py:method") ? (s.last_prefix + ".") : "",
            ul = $('#ls_search-results');

        return $('
')
            .append($('')
                .attr('href', buildHref(s))
                .text(prefix + s.name)
                .mouseenter(function () {
                    ul.find('li a').removeClass('hover');
                    $(this).addClass('hover');
                })
                .mouseleave(function () {
                    $(this).removeClass('hover');
                })
                );
    } // end createResultListElement

    window.onload = function () {
        init();
    };
}());
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';

var safeParse = require('./lib/util.js').safeParse;
var TChannel = require('tchannel');
var TypedError = require('error/typed');

var ChannelDestroyedError = TypedError({
    type: 'ringpop.client.channel-destroyed',
    message: 'Channel is already destroyed',
    endpoint: null,
    channelType: null
});

function RingpopClient(subChannel) {
    this.subChannel = subChannel;
    this.isChannelOwner = false;
    if (!this.subChannel) {
        this.tchannel = new TChannel();
        this.subChannel = this.tchannel.makeSubChannel({
            serviceName: 'ringpop'
        });
        this.isChannelOwner = true;
    }
}

RingpopClient.prototype.adminConfigGet = function adminConfigGet(host, body, callback) {
    this._request({
        host: host
    }, '/admin/config/get', null, body, callback);
};

RingpopClient.prototype.adminConfigSet = function adminConfigSet(host, body, callback) {
    this._request({
        host: host
    }, '/admin/config/set', null, body, callback);
};

RingpopClient.prototype.adminGossipStart = function adminGossipStart(host, callback) {
    this._request({
        host: host
    }, '/admin/gossip/start', null, null, callback);
};

RingpopClient.prototype.adminGossipStop = function adminGossipStop(host, callback) {
    this._request({
        host: host
    }, '/admin/gossip/stop', null, null, callback);
};

RingpopClient.prototype.adminGossipTick = function adminGossipTick(host, callback) {
    this._request({
        host: host
    }, '/admin/gossip/tick', null, null, callback);
};

RingpopClient.prototype.protocolJoin = function protocolJoin(opts, body, callback) {
    this._request(opts, '/protocol/join', null, body, callback);
};

RingpopClient.prototype.protocolPing = function protocolPing(opts, body, callback) {
    this._request(opts, '/protocol/ping', null, body, callback);
};

RingpopClient.prototype.protocolPingReq = function protocolPingReq(opts, body, callback) {
    this._request(opts, '/protocol/ping-req', null, body, callback);
};

RingpopClient.prototype.destroy = function destroy(callback) {
    if (this.isChannelOwner) {
        this.tchannel.close(callback);
    }
};

/* jshint maxparams: 5 */
RingpopClient.prototype._request = function _request(opts, endpoint, head, body, callback) {
    var self = this;

    if (this.subChannel.destroyed) {
        process.nextTick(function onTick() {
            callback(ChannelDestroyedError({
                endpoint: endpoint,
                channelType: 'subChannel'
            }));
        });
        return;
    }

    if (this.subChannel.topChannel.destroyed) {
        process.nextTick(function onTick() {
            callback(ChannelDestroyedError({
                endpoint: endpoint,
                channelType: 'topChannel'
            }));
        });
        return;
    }

    this.subChannel.waitForIdentified({
        host: opts.host
    }, function onIdentified(err) {
        if (err) {
            callback(err);
            return;
        }

        self.subChannel.request({
            host: opts.host,
            serviceName: 'ringpop',
            hasNoParent: true,
            retryLimit: opts.retryLimit || 0,
            trace: false,
            headers: {
                as: 'raw',
                cn: 'ringpop'
            },
            timeout: opts.timeout || 30000
        }).send(endpoint, JSON.stringify(head), JSON.stringify(body), onSend);
    });

    function onSend(err, res, arg2, arg3) {
        if (!err && !res.ok) {
            err = safeParse(arg3) || new Error('Server Error');
        }

        if (err) {
            callback(err);
            return;
        }

        callback(null, safeParse(arg3));
    }
};

module.exports = RingpopClient;
<commit_msg>Check for subChannel and topChannel<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';

var safeParse = require('./lib/util.js').safeParse;
var TChannel = require('tchannel');
var TypedError = require('error/typed');

var ChannelDestroyedError = TypedError({
    type: 'ringpop.client.channel-destroyed',
    message: 'Channel is already destroyed',
    endpoint: null,
    channelType: null
});

function RingpopClient(subChannel) {
    this.subChannel = subChannel;
    this.isChannelOwner = false;
    if (!this.subChannel) {
        this.tchannel = new TChannel();
        this.subChannel = this.tchannel.makeSubChannel({
            serviceName: 'ringpop'
        });
        this.isChannelOwner = true;
    }
}

RingpopClient.prototype.adminConfigGet = function adminConfigGet(host, body, callback) {
    this._request({
        host: host
    }, '/admin/config/get', null, body, callback);
};

RingpopClient.prototype.adminConfigSet = function adminConfigSet(host, body, callback) {
    this._request({
        host: host
    }, '/admin/config/set', null, body, callback);
};

RingpopClient.prototype.adminGossipStart = function adminGossipStart(host, callback) {
    this._request({
        host: host
    }, '/admin/gossip/start', null, null, callback);
};

RingpopClient.prototype.adminGossipStop = function adminGossipStop(host, callback) {
    this._request({
        host: host
    }, '/admin/gossip/stop', null, null, callback);
};

RingpopClient.prototype.adminGossipTick = function adminGossipTick(host, callback) {
    this._request({
        host: host
    }, '/admin/gossip/tick', null, null, callback);
};

RingpopClient.prototype.protocolJoin = function protocolJoin(opts, body, callback) {
    this._request(opts, '/protocol/join', null, body, callback);
};

RingpopClient.prototype.protocolPing = function protocolPing(opts, body, callback) {
    this._request(opts, '/protocol/ping', null, body, callback);
};

RingpopClient.prototype.protocolPingReq = function protocolPingReq(opts, body, callback) {
    this._request(opts, '/protocol/ping-req', null, body, callback);
};

RingpopClient.prototype.destroy = function destroy(callback) {
    if (this.isChannelOwner) {
        this.tchannel.close(callback);
    }
};

/* jshint maxparams: 5 */
RingpopClient.prototype._request = function _request(opts, endpoint, head, body, callback) {
    var self = this;

    if (this.subChannel && this.subChannel.destroyed) {
        process.nextTick(function onTick() {
            callback(ChannelDestroyedError({
                endpoint: endpoint,
                channelType: 'subChannel'
            }));
        });
        return;
    }

    if (this.subChannel &&
            this.subChannel.topChannel &&
            this.subChannel.topChannel.destroyed) {
        process.nextTick(function onTick() {
            callback(ChannelDestroyedError({
                endpoint: endpoint,
                channelType: 'topChannel'
            }));
        });
        return;
    }

    this.subChannel.waitForIdentified({
        host: opts.host
    }, function onIdentified(err) {
        if (err) {
            callback(err);
            return;
        }

        self.subChannel.request({
            host: opts.host,
            serviceName: 'ringpop',
            hasNoParent: true,
            retryLimit: opts.retryLimit || 0,
            trace: false,
            headers: {
                as: 'raw',
                cn: 'ringpop'
            },
            timeout: opts.timeout || 30000
        }).send(endpoint, JSON.stringify(head), JSON.stringify(body), onSend);
    });

    function onSend(err, res, arg2, arg3) {
        if (!err && !res.ok) {
            err = safeParse(arg3) || new Error('Server Error');
        }

        if (err) {
            callback(err);
            return;
        }

        callback(null, safeParse(arg3));
    }
};

module.exports = RingpopClient;
<|endoftext|>